From 87884287949f5a3a227c1b15d9bbbe09f2d0ef93 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 13:20:05 +0400 Subject: [PATCH 0001/1567] feat(sessions): persist and continue logical child sessions --- docs/rf-contract/capability-tokens.md | 8 + docs/tools.md | 12 + src/chat/action.rs | 1 + src/chat/binding.rs | 39 +- src/chat/binding/tests/operator_accounting.rs | 1 + src/chat/child_focus.rs | 428 ++ src/chat/mod.rs | 1 + src/chat/run.rs | 5159 ++--------------- src/chat/run/commands.rs | 1429 +++++ src/chat/run/event_pump.rs | 721 +++ src/chat/run/provider_turn.rs | 1829 ++++++ src/chat/sessions/focus.rs | 10 +- src/chat/sessions/runtime.rs | 30 +- src/chat/state/tests/mod.rs | 1 + src/chat/tests/p2_iss005_tests.rs | 1 + src/chat/tui/layout.rs | 4 +- src/chat/tui/render_chrome.rs | 14 + src/chat/tui/render_conversation.rs | 39 +- src/chat/tui/tests/mod.rs | 1 + src/chat/tui/tests/rearch_chrome.rs | 3 + src/chat/tui/tests/s4_a_2.rs | 1 + src/chat/tui/tests/switcher.rs | 1 + src/chat/tui/views.rs | 2 + src/chat/views.rs | 3 +- src/memory/child_sessions.rs | 37 + src/memory/sqlite/child_sessions.rs | 20 + src/memory/sqlite/child_turns.rs | 171 + src/memory/sqlite/event_append.rs | 328 ++ src/memory/sqlite/events.rs | 284 +- src/memory/sqlite/mod.rs | 2 + src/memory/sqlite/sync_lifecycle.rs | 8 +- src/runtime/operator_spawn.rs | 43 +- src/runtime/operator_spawn/process.rs | 7 +- src/runtime/operator_spawn/task.rs | 11 +- src/session_worker/protocol.rs | 5 + src/session_worker/runner/run.rs | 12 +- src/session_worker/runner/tests/hybrid.rs | 4 + src/session_worker/runner/tests/mod.rs | 1 + .../runner/tests/spawn_context.rs | 2 + src/tools/sessions_spawn/continuation.rs | 122 + src/tools/sessions_spawn/events.rs | 38 + src/tools/sessions_spawn/live_usage.rs | 34 + src/tools/sessions_spawn/mod.rs | 2 + src/tools/sessions_spawn/process_mode.rs | 21 +- src/tools/sessions_spawn/spawn.rs | 71 +- src/tools/sessions_spawn/task_mode.rs | 17 +- .../sessions_spawn/tests/process_manifest.rs | 1 + src/tools/sessions_spawn/tool.rs | 8 +- src/tools/sessions_spawn/worker_manifest.rs | 1 + tests/architecture_boundaries/memory.rs | 7 + tests/session_worker_stdin_protocol.rs | 1 + 51 files changed, 6124 insertions(+), 4872 deletions(-) create mode 100644 src/chat/child_focus.rs create mode 100644 src/chat/run/commands.rs create mode 100644 src/chat/run/event_pump.rs create mode 100644 src/chat/run/provider_turn.rs create mode 100644 src/memory/sqlite/child_turns.rs create mode 100644 src/memory/sqlite/event_append.rs create mode 100644 src/tools/sessions_spawn/continuation.rs create mode 100644 src/tools/sessions_spawn/live_usage.rs diff --git a/docs/rf-contract/capability-tokens.md b/docs/rf-contract/capability-tokens.md index ea99a29ea..cc885d6dc 100644 --- a/docs/rf-contract/capability-tokens.md +++ b/docs/rf-contract/capability-tokens.md @@ -657,6 +657,14 @@ WebSocket hello is `{"type":"hello","proto":1,"cursor":null}` or a saved A client Close frame, including normal code 1000, is echoed by flushing the protocol's queued close reply before the server drops the socket. This also applies when the client closes before hello. +Child sessions retain `spawn:` across continuation turns. Each +continuation has a fresh run ID; `turn.started`, `turn.appended`, and +`child_session.upsert` keep that turn's run and the four ancestry links. +Consumers must accept repeated running-to-succeeded cycles for one child +session key. Terminal-chat child sessions remain outside this journal. +Process-child approvals remain denied with `no_resolver`; focused task-child +approvals resolve only that child's pending call. + Welcome is `{type:"welcome",epoch,head_seq}`; events replay in sequence before live delivery. The install epoch is 32 lowercase hex characters and survives restart. Headers retain owner scope and stable identity; the four descendant diff --git a/docs/tools.md b/docs/tools.md index 66fbb8f80..349d345a9 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -1952,3 +1952,15 @@ are directly published for gateway Main and named turns, subject to explicit operator exclusions and the existing execution gates. Named targeted agents at Full have the Full tool surface, including shell and file writes; Supervised and ReadOnly retain their existing restrictions. + +### Continuing a child session + +`sessions_spawn` accepts `action="continue"`, `session_key` (or an earlier +`run_id`), and `task`. The child retains its session key and public history, +uses a fresh admitted run, and can continue after the parent chat is resumed +following a restart. A child remains depth one and cannot spawn or delegate. +In `prx chat`, Enter in a focused child starts a turn or queues behind its +current turn. `/now` puts input first; `/steer` explicitly interrupts the +current turn. Session commands operate on the focused child's context, +model, history, usage, and task-mode approvals. `/level` displays the inherited +level. Process-child approval calls remain denied with `no_resolver`. diff --git a/src/chat/action.rs b/src/chat/action.rs index 4dce20eda..fb3c28957 100644 --- a/src/chat/action.rs +++ b/src/chat/action.rs @@ -149,6 +149,7 @@ pub fn build_provider_worker_active_view_with_io( lines.push("view: read-only provider worker detail".to_string()); lines.push("keys: PageUp/PageDown scroll, Esc returns to main".to_string()); crate::chat::sessions::ActiveSessionView { + turns: Vec::new(), seq: sequence, kind: PROVIDER_WORKER_VIEW_KIND.to_string(), title, diff --git a/src/chat/binding.rs b/src/chat/binding.rs index 0634049a8..3e2856b7b 100644 --- a/src/chat/binding.rs +++ b/src/chat/binding.rs @@ -376,6 +376,7 @@ impl Drop for ChatAdmissionGuard { /// Private fields keep mailbox content and decoded tool arguments from minting /// an operator command or replacing the model after verification. pub(super) struct ChatOperatorSpawn { + child: Option, command: String, binding: ChatProviderBinding, task: String, @@ -404,6 +405,7 @@ impl ChatOperatorSpawn { ); binding.verify(generation, provider, provider_name, model_name)?; Ok(Self { + child: None, command: message.content.clone(), binding: ChatProviderBinding { choice: binding.choice.clone(), @@ -416,6 +418,30 @@ impl ChatOperatorSpawn { }) } + pub(super) fn capture_child( + message: &crate::channels::traits::ChannelMessage, + task: &str, + record: crate::memory::child_sessions::ChildSessionRecord, + binding: ChatProviderBinding, + ) -> anyhow::Result { + anyhow::ensure!( + super::is_local_operator_input(message) + && !message.sender_is_bot + && message.content.strip_prefix("/now ").unwrap_or(&message.content) == task + && !task.is_empty(), + "child input requires an actual local operator message" + ); + binding.verify(&binding.generation, &binding.provider, &record.provider, &record.model)?; + Ok(Self { + command: message.content.clone(), + provider: record.provider.clone(), + model: record.model.clone(), + child: Some(record), + binding, + task: task.to_owned(), + }) + } + pub(super) async fn admit( self, memory: Arc, @@ -464,7 +490,7 @@ impl ChatOperatorSpawn { ) }; let runtime = Arc::clone(publication.runtime_holder()); - let source = crate::runtime::operator_spawn::OperatorSpawnSource::new( + let mut source = crate::runtime::operator_spawn::OperatorSpawnSource::new( binding.as_ref(), Arc::clone(generation), fabric, @@ -474,13 +500,16 @@ impl ChatOperatorSpawn { publication, runtime, )?; + let mut args = serde_json::json!({ "task": self.task, "provider": self.provider, "model": self.model }); + if let Some(record) = self.child { + args["action"] = "continue".into(); + args["session_key"] = record.session_key.clone().into(); + source = source.for_continuation(record)?; + } if let Some(guard) = admission_guard { guard.handoff(); } - Ok(( - serde_json::json!({ "task": self.task, "provider": self.provider, "model": self.model }), - source, - )) + Ok((args, source)) } } diff --git a/src/chat/binding/tests/operator_accounting.rs b/src/chat/binding/tests/operator_accounting.rs index 097a95282..40fdf8335 100644 --- a/src/chat/binding/tests/operator_accounting.rs +++ b/src/chat/binding/tests/operator_accounting.rs @@ -347,6 +347,7 @@ async fn restore_operator_process( let launch = source.capture_process(scope, task, receipt, config_generation.clone())?; let workspace = &config.workspace_dir; let mut manifest = crate::session_worker::protocol::WorkerManifest { + seed_history: Vec::new(), parent_capability: None, ordinary_source: None, operator_source: None, diff --git a/src/chat/child_focus.rs b/src/chat/child_focus.rs new file mode 100644 index 000000000..f38ba479b --- /dev/null +++ b/src/chat/child_focus.rs @@ -0,0 +1,428 @@ +//! Child input queues and commands, independent of the main conversation. +use super::binding::{ChatOperatorSpawn, ChatProviderBinding}; +use crate::channels::traits::ChannelMessage; +use crate::memory::Memory; +use crate::memory::child_sessions::{ChildSessionRecord, ChildTurn}; +use crate::tools::sessions_spawn::{SubAgentRun, SubAgentStatus}; +use anyhow::Context; +use std::{collections::VecDeque, sync::Arc}; + +#[derive(Default)] +pub(super) struct ChildFocus { + queue: VecDeque<(String, ChannelMessage)>, +} + +pub(super) struct ChildFocusContext<'a> { + pub memory: &'a Arc, + pub generation: &'a Arc, + pub parent: &'a str, + pub security: &'a Arc, + pub service: &'a Arc, + pub tools: &'a [Box], + pub sessions: &'a super::sessions::ChatSessionsHandle, + pub approvals: &'a super::sessions::PendingApprovals, +} + +impl ChildFocusContext<'_> { + pub(super) async fn view( + &self, + target: &str, + seq: u64, + lines: Vec, + scroll_offset: usize, + ) -> anyhow::Result { + let record = self.record(target)?; + let store = self.memory.child_session_store().context("child storage unavailable")?; + let mut turns = store.history(&record)?; + if let Some(run) = self.sessions.child_run(&record.session_key).await { + let live = run.history.read().await; + if live.len() > turns.len() { + turns = live + .iter() + .filter(|turn| turn.role != "system") + .map(|turn| ChildTurn { + role: turn.role.clone(), + content: turn.content.clone(), + timestamp: turn.timestamp, + }) + .collect(); + } + } + Ok(super::sessions::ActiveSessionView { + seq, + kind: "agent".into(), + title: format!("{} / {} · {:?}", record.provider, record.model, record.level), + turns, + lines: if self.busy(&record).await { lines } else { Vec::new() }, + truncated: false, + scroll_offset, + }) + } + pub(super) async fn restore(&self) -> anyhow::Result<()> { + let workspace = self.generation.effective.workspace_dir.to_string_lossy(); + let owner = super::chat_runtime_envelope(&workspace, self.parent).resolved_owner_id(); + let Some(store) = self.memory.child_session_store() else { + return Ok(()); + }; + for record in store + .sessions(&workspace, &owner)? + .into_iter() + .filter(|record| record.parent_session == self.parent) + { + let history = store.history(&record)?; + let id = record.runs.last().cloned().context("child session has no run")?; + let output = history + .iter() + .rev() + .find(|turn| turn.role == "assistant") + .map_or_else(String::new, |turn| turn.content.clone()); + self.sessions + .restore_child(SubAgentRun { + id, + task: history + .first() + .map_or_else(|| "Child session".into(), |turn| turn.content.clone()), + owner_id: Some(owner.clone()), + topic_id: None, + source_message_event_id: None, + started_at: record.created_at, + finished_at: record.ended_at.or(Some(chrono::Utc::now())), + status: SubAgentStatus::Completed(output), + recipient: None, + channel_name: Some("terminal".into()), + abort_handle: None, + process_control: None, + task_control: None, + history: Arc::new(tokio::sync::RwLock::new( + history + .into_iter() + .map(|turn| crate::tools::sessions_spawn::HistoryEntry { + role: turn.role, + content: turn.content, + timestamp: turn.timestamp, + }) + .collect(), + )), + steer_tx: None, + parent_run_id: Some(record.parent_run), + session_scope_key: record.session_key, + spawn_depth: 0, + delegation: None, + token_usage_records: Vec::new(), + progress: crate::agent::idle::child_beat(), + batch_id: None, + agent_partition: None, + }) + .await; + } + Ok(()) + } + fn record(&self, target: &str) -> anyhow::Result { + let workspace = self.generation.effective.workspace_dir.to_string_lossy(); + let owner = super::chat_runtime_envelope(&workspace, self.parent).resolved_owner_id(); + self.memory + .child_session_store() + .context("child session storage unavailable")? + .sessions(&workspace, &owner)? + .into_iter() + .find(|record| { + record.parent_session == self.parent + && (record.session_key == target || record.runs.iter().any(|run| run == target)) + }) + .context("child_session_unknown") + } + + async fn busy(&self, record: &ChildSessionRecord) -> bool { + self.sessions.child_run(&record.session_key).await.is_some_and(|run| { + matches!( + run.status, + SubAgentStatus::Running | SubAgentStatus::AwaitingInput { .. } + ) + }) + } + + fn provider(&self, record: &ChildSessionRecord) -> anyhow::Result> { + let config = &self.generation.effective; + let (_, provider) = super::bootstrap::chat_provider_chain( + config, + &record.provider, + crate::providers::selection::default_provider(config), + &record.model, + &crate::providers::provider_runtime_options_from_config(config), + )?; + Ok(Arc::from(provider)) + } + + async fn start(&self, record: ChildSessionRecord, message: ChannelMessage) -> anyhow::Result { + let task = message.content.strip_prefix("/now ").unwrap_or(&message.content); + let provider = self.provider(&record)?; + let binding = ChatProviderBinding::capture(self.generation, &provider, &record.provider, &record.model)? + .context("child provider binding missing")?; + let command = ChatOperatorSpawn::capture_child(&message, task, record, binding)?; + let (mut args, source) = command + .admit( + Arc::clone(self.memory), + self.parent, + Arc::clone(self.security), + Arc::clone(self.service), + ) + .await?; + args[crate::security::policy::RUNTIME_APPROVAL_GRANT_ARG] = + serde_json::to_value(crate::security::policy::ApprovalGrant::for_resource_operation( + "sessions_spawn", + "sessions_spawn:spawn", + "chat-operator", + None, + ))?; + let tool = self + .tools + .iter() + .find(|tool| tool.supports_name("sessions_spawn")) + .context("child execution unavailable")?; + let result = source.scope(tool.execute_named("sessions_spawn", args)).await?; + anyhow::ensure!( + result.success, + "{}", + result.error.as_deref().unwrap_or("child continuation failed") + ); + Ok(result.output) + } +} + +impl ChildFocus { + pub(super) async fn submit( + &mut self, + target: &str, + message: ChannelMessage, + ctx: &ChildFocusContext<'_>, + ) -> anyhow::Result> { + let command = message.content.split_whitespace().next().unwrap_or_default(); + let scoped = matches!( + command, + "/clear" + | "/compact" + | "/model" + | "/tools" + | "/cost" + | "/export" + | "/copy" + | "/transcript" + | "/rewind" + | "/approve" + | "/deny" + | "/help" + | "/level" + ); + if command.starts_with('/') && !scoped && command != "/now" { + return Ok(None); + } + anyhow::ensure!( + super::is_local_operator_input(&message) && !message.sender_is_bot, + "child focus requires local operator input" + ); + let mut record = ctx.record(target)?; + if !scoped { + if ctx.busy(&record).await { + if command == "/now" { + self.queue.push_front((record.session_key, message)); + } else { + self.queue.push_back((record.session_key, message)); + } + return Ok(Some("Queued for the child session.".into())); + } + return ctx.start(record, message).await.map(Some); + } + if matches!(command, "/approve" | "/deny") { + let run = ctx + .sessions + .child_run(&record.session_key) + .await + .context("child is not running")?; + if record.mode == "process" { + return Ok(Some("Process-child approval is denied: no_resolver.".into())); + } + let decision = if command == "/approve" { + crate::agent::turn_contracts::ApprovalDecision::Grant + } else { + crate::agent::turn_contracts::ApprovalDecision::Deny + }; + return Ok(Some( + if ctx.approvals.resolve(&run.id, decision) { + "Child approval resolved." + } else { + "No pending child approval." + } + .into(), + )); + } + if command == "/level" { + return Ok(Some(format!( + "Child level: {:?} (inherited from its parent).", + record.level + ))); + } + let store = ctx.memory.child_session_store().context("child storage unavailable")?; + let mut turns = store.history(&record)?; + if matches!(command, "/clear" | "/compact" | "/rewind") || message.content.starts_with("/model ") { + anyhow::ensure!( + !ctx.busy(&record).await, + "child_session_busy: wait for the current turn before changing context" + ); + match command { + "/clear" => turns.clear(), + "/model" => { + let model = message.content.strip_prefix("/model ").unwrap_or_default().trim(); + super::bootstrap::chat_model_switch(&ctx.generation.effective, &record.provider, model)?; + record.model = model.to_owned(); + } + "/rewind" => { + let index = message + .content + .strip_prefix("/rewind") + .unwrap_or_default() + .trim() + .parse::()?; + let boundary = turns + .iter() + .enumerate() + .filter(|(_, turn)| turn.role == "user") + .nth(index.saturating_sub(1)) + .map(|(index, _)| index) + .context("unknown child turn")?; + turns.truncate(boundary); + } + "/compact" => { + let provider = ctx.provider(&record)?; + let mut history: Vec<_> = turns + .iter() + .map(|turn| crate::providers::ChatMessage { + role: turn.role.clone(), + content: turn.content.clone(), + }) + .collect(); + let source = crate::agent::turn_history::CanonicalHistory::from_acknowledged( + None, + turns.iter().map(|turn| (turn.role.as_str(), turn.content.as_str())), + ); + if let crate::agent::compaction::CompactionBuild::Patch(patch) = + crate::agent::compaction::build_configurable_compaction_patch_with_source_history( + &history, + &source, + provider.as_ref(), + &record.model, + &ctx.generation.effective.agent.compaction, + None, + "manual", + ) + .await? + { + crate::agent::compaction::apply_compaction_patch_exact(&mut history, &patch)?; + turns = history + .into_iter() + .map(|message| ChildTurn { + role: message.role, + content: message.content, + timestamp: chrono::Utc::now(), + }) + .collect(); + } + } + _ => {} + } + store.replace_context(&record, &turns)?; + return Ok(Some("Child session updated.".into())); + } + let mut session = super::session::ChatSession::new(&record.provider, &record.model); + session.id = record.session_key.clone(); + session.turns = turns + .iter() + .map(|turn| super::session::ChatTurn { + role: turn.role.clone(), + content: turn.content.clone(), + timestamp: turn.timestamp, + tool_calls: Vec::new(), + context_handoff: false, + tool_evidence: None, + }) + .collect(); + if let Some(run) = ctx.sessions.child_run(&record.session_key).await { + session.token_usage_records = run.token_usage_records; + } + if command == "/transcript" { + return Ok(Some( + turns + .iter() + .map(|turn| format!("{}: {}", turn.role, turn.content)) + .collect::>() + .join("\n"), + )); + } + if command == "/tools" { + let configured = ctx.generation.effective.agents.get(&record.agent); + let names = ctx + .tools + .iter() + .filter(|tool| !matches!(tool.name(), "sessions_spawn" | "delegate")) + .filter(|tool| { + record.level == crate::security::AutonomyLevel::Full + || configured.is_none_or(|agent| { + agent.allowed_tools.is_empty() + || agent + .allowed_tools + .iter() + .any(|name| name == "*" || tool.supports_name(name)) + }) + }) + .map(|tool| tool.name()) + .collect::>(); + return Ok(Some(format!("Child session tools: {}", names.join(", ")))); + } + if command == "/copy" { + let selected = + super::copy_select::select_copy_content(&session, &message.content).map_err(anyhow::Error::msg)?; + super::terminal_proto::copy_to_clipboard(&selected.content)?; + return Ok(Some(super::copy_select::copy_success_message(&selected))); + } + let context = super::commands::CommandContext { + model_name: &record.model, + provider_name: &record.provider, + chat_session: &session, + tools_registry: ctx.tools, + mem: ctx.memory.as_ref(), + }; + match super::commands::dispatch(&message.content, &context).await { + super::commands::CommandResult::HandledWithOutput(output) => Ok(Some(output)), + super::commands::CommandResult::Handled => Ok(Some(String::new())), + _ => anyhow::bail!("unsupported child session command"), + } + } + + pub(super) async fn pump(&mut self, ctx: &ChildFocusContext<'_>) -> Vec { + let mut outputs = Vec::new(); + let mut index = 0; + while index < self.queue.len() { + let Some((target, _)) = self.queue.get(index) else { + break; + }; + let record = match ctx.record(target) { + Ok(record) => record, + Err(error) => { + self.queue.remove(index); + outputs.push(error.to_string()); + continue; + } + }; + if ctx.busy(&record).await { + index += 1; + continue; + } + if let Some((_, message)) = self.queue.remove(index) { + outputs.push(match ctx.start(record, message).await { + Ok(output) => output, + Err(error) => error.to_string(), + }); + } + } + outputs + } +} diff --git a/src/chat/mod.rs b/src/chat/mod.rs index 290e5302b..3d7898bee 100644 --- a/src/chat/mod.rs +++ b/src/chat/mod.rs @@ -82,6 +82,7 @@ pub(crate) mod approval_context; mod bootstrap; mod branch_copy; mod chat_events; +mod child_focus; mod compaction; mod copy_select; #[cfg(feature = "terminal-tui")] diff --git a/src/chat/run.rs b/src/chat/run.rs index c8de812b0..de5a69a26 100644 --- a/src/chat/run.rs +++ b/src/chat/run.rs @@ -328,4595 +328,702 @@ async fn run_internal( crate::runtime::turn_cleanup::current_tracker().as_ref(), CancellationToken::new(), )?; - let chat_result = cleanup.run(async { - let child_cleanup = crate::runtime::turn_cleanup::current_tracker() - .context("chat cleanup owner missing")?; - child_cleanup.retain_service(Arc::clone(&turn_service)); - - // v3a: coordination handle for interactive PTY terminal handoff. Shared with - // the unified TUI render loop (which parks while a PTY is attached) and the - // main loop's `/pty` handler (which pauses/resumes it around the passthrough). - // Only the TUI path performs the handoff; the non-TUI fallback has no render - // loop to suspend. - #[cfg(feature = "terminal-tui")] - let pty_handoff = Arc::new(crate::chat::sessions::pty::HandoffControl::new()); - - // Pre-load construction: the only mutable session copy, consumed by the - // reducer seed below. Afterwards the run loop reads the acknowledged session. - let mut initial_session = startup::resume_session( - session_id.as_deref(), one_shot.is_some(), &mem, &memory_fabric, &config, provider_name, model_name, - ).await?; - bind_session_to_runtime_provider_model(&mut initial_session, provider_name, model_name); - let (mut chat_session_key, mut fabric_turn_seq, banner, mut history) = startup::initial_conversation( - &initial_session, &config, provider_name, model_name, &skills, native_tools, - ); - - #[cfg(feature = "terminal-tui")] - let (initial_saved_session_entries, chat_mirror) = startup::initial_tui_mirror( - &mem, &initial_session, &config, provider_name, model_name, - ).await; - - - // A resumed plain session shows its recent history on a terminal stdout. - let resume_recap = (plain_mode && session_id.is_some() && one_shot.is_none() && std::io::IsTerminal::is_terminal(&std::io::stdout())) - .then(|| super::resume_recap::format_resume_recap(&initial_session)) - .flatten(); - #[cfg(feature = "terminal-tui")] - let ui_startup = startup::ChatStartupUi { - banner: &banner, - session_id: &initial_session.id, - initial_saved_session_entries: &initial_saved_session_entries, - resume_recap: resume_recap.as_deref(), - }; - - // ── Input channel ──────────────────────────────────────────── - let (input_tx, mut input_rx) = crate::runtime::h2_entry::ChatInputSender::channel(INPUT_CHANNEL_CAPACITY); - scheduled_input_handle.set_input_sender(input_tx.clone()); - // Taken before the terminal listener consumes `input_tx`: daemon-assigned - // work is submitted through the very same FIFO as typed input, which is - // what makes it go through the ordinary turn machinery rather than a - // parallel path with its own bugs. - let assignment_input_tx = input_tx.clone(); - let (control_tx, mut control_rx) = mpsc::channel::(CHAT_CONTROL_CHANNEL_CAPACITY); - #[cfg(not(feature = "terminal-tui"))] - let _ = &control_tx; - - // ── Graceful shutdown signal ───────────────────────────────── - // Instead of std::process::exit(), all signal handlers use this token to - // break the main loop gracefully, allowing final session save + teardown. - // The token is now supplied by the caller (D5/D9 step 1): dispatch owns the - // root shutdown token and passes it down. The internal ctrl_c single/double - // handlers below cancel this same external token, so chat remains the sole - // owner of ctrl_c semantics while the caller can also request shutdown. - - // The reducer seed opens with the startup provider view's system prompt. - let startup_system_prompt = history.first().filter(|message| message.role == "system").map(|message| message.content.clone()); - let (chat_dispatcher, chat_action_rx, dispatcher_shadow_state) = startup::initial_dispatcher( - provider_name, model_name, &shutdown, &initial_session, startup_system_prompt, - #[cfg(feature = "terminal-tui")] &config, - #[cfg(feature = "terminal-tui")] &ui_startup, - ); - - // Shared dual-write guard (raised by the EffectExecutor in Both/Redux mode; the old path checks - // the guard to decide whether to skip persistence. It is built even in Off mode, where the old - // path's check is always false at zero cost. - // P0-1 fix: dropped allow(unused_variables) — the guard is read at the end of an old-path turn, - // so it is genuinely used under both feature configurations.) - let dual_write_guard = dispatcher::RuntimeDualWriteGuard::new(); - // The run loop's only view of the session: the reducer's acknowledged state. - let mut chat_session = chat_dispatcher.session_reader(); - - // PRX_CHAT_REDUX is read once at the entry point and reused inside the function body, so the env - // var is not parsed in several places. - // S4-B: Pure is the only supported run path; non-Pure values are warned about and forced up. - #[cfg(feature = "terminal-tui")] - let top_redux_mode: ReduxMode = { ReduxMode::from_env() }; - // The plain REPL runs one turn of the session at a time; later lines queue. - // Typed lines (terminal stdin) are acknowledged and bounded; piped input - // keeps every line. - let plain_typed_queue = plain_mode && std::io::IsTerminal::is_terminal(&std::io::stdin()); - #[cfg(feature = "terminal-tui")] - let max_concurrent_visible_turns = if plain_mode { 1 } else { config.chat.max_concurrent_visible_turns.max(1) }; - #[cfg(not(feature = "terminal-tui"))] - let max_concurrent_visible_turns = 1usize; - #[cfg(feature = "terminal-tui")] - let visible_input_admission_kind = crate::chat::turn_worker::ProviderTurnWorkerKind::Detached; - #[cfg(not(feature = "terminal-tui"))] - let visible_input_admission_kind = crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited; - - // Class B — bounded. Three events are emitted per provider turn, and with - // no cap on concurrent turns the emission rate is unbounded while the sole - // consumer is this loop, which also renders and handles input. See - // `PROVIDER_TURN_LIFECYCLE_CHANNEL_CAPACITY` for the sizing rationale. - let (provider_turn_lifecycle_tx, mut provider_turn_lifecycle_rx) = - mpsc::channel::(PROVIDER_TURN_LIFECYCLE_CHANNEL_CAPACITY); - #[cfg(not(feature = "terminal-tui"))] - let _ = &provider_turn_lifecycle_tx; - - // The last request's tool-surface reserve: `/compact`, compaction - // feedback and the context footer budget with it, as the preflight does. - let tool_surface_reserve = crate::agent::context_budget::ToolSurfaceReserve::default(); - - // Pick the EffectExecutor mode from the redux mode (TUI feature only) - #[cfg(feature = "terminal-tui")] - let effect_executor = { - let mode: ReduxMode = top_redux_mode; - let deps = dispatcher::EffectDeps { - provider: Arc::clone(&provider), - memory_event_recording: config.memory.event_recording_config(), - channel: Arc::clone(&terminal) as Arc, - hooks: Arc::clone(&hooks), - observer: Arc::clone(&observer), - persistence: dispatcher::PersistenceDeps { - memory: Arc::clone(&mem), - action_tx: chat_dispatcher.sender(), - dual_write_guard: dual_write_guard.clone(), - }, - provider_turn_lifecycle_tx: Some(provider_turn_lifecycle_tx.clone()), - redraw_tx: None, - tui_mirror: Some(Arc::clone(&chat_mirror)), - shutdown: shutdown.clone(), - model: dispatcher::ModelSlot::new(Arc::from(model_name)), - temperature, - tools_registry: Some(Arc::clone(&tools_registry)), - approval_router: Arc::new(dispatcher::ApprovalRouter::new()), - tool_security_policy: Arc::clone(&security), - tool_tiering: config.tool_tiering.clone(), - tool_surface_reserve: tool_surface_reserve.clone(), - }; - tracing::info!(mode = ?mode, "chat EffectExecutor in Pure real-deps mode"); - let executor = dispatcher::EffectExecutor::new_with_deps(deps) - .with_cleanup_owner(Arc::clone(&child_cleanup)) - .with_session_publisher(chat_dispatcher.session_publisher()); - if persist_sessions { executor } else { executor.without_session_rows() } - }; - // Non-TUI: the persistence effects run for real (save, publish, ack); the - // tool loop performs provider turns, hooks and output itself. - #[cfg(not(feature = "terminal-tui"))] - let effect_executor = { - let executor = dispatcher::EffectExecutor::new_persistence_only(dispatcher::PersistenceDeps { - memory: Arc::clone(&mem), - action_tx: chat_dispatcher.sender(), - dual_write_guard: dual_write_guard.clone(), - }) - .with_session_publisher(chat_dispatcher.session_publisher()); - if persist_sessions { executor } else { executor.without_session_rows() } - }; - - // P0-2 fix: take the redraw_slot Arc up front so redraw_tx can be injected after TUI - // initialization completes. The EffectExecutor is consumed by the dispatcher - // spawn (`spawn_dispatcher_task_full`), but the Arc is cloned before the spawn, so the real sender - // can still be filled in afterwards through this Arc and RequestRedraw really executes. - #[cfg(feature = "terminal-tui")] - let executor_redraw_slot = effect_executor.redraw_handle(); - - // BUG-07: take the model hot-swap slot handle up front (same idea as redraw_slot: cloned before - // the spawn so that after the spawn `/model ` can still replace the model through this - // handle, and drive_start_turn_stream of later turns reads the new value). Shadow mode has no - // deps → None. - #[cfg(feature = "terminal-tui")] - let model_slot = effect_executor.model_handle(); - - // Bug #3: the provider hot-swap slot handle (same idea as model_slot). Cloned before the spawn, - // so that on `/provider ` the rebuilt provider handle can be set into it and the Redux - // driver of later turns (drive_start_turn_stream) reads the new provider. Shadow mode has no - // deps → None. - #[cfg(feature = "terminal-tui")] - let provider_slot = effect_executor.provider_handle(); - - #[cfg(feature = "terminal-tui")] - let approval_router = effect_executor.approval_router(); - #[cfg(not(feature = "terminal-tui"))] - let approval_router: Option> = None; - - // Step 5a-4: TurnCompletionSignal — the switched-over Redux driver path uses this signal to await - // turn completion in the chat::run main loop. After the dispatcher task consumes a terminal action - // (StreamCompleted/Failed/Cancelled) it calls notify_waiters to wake the waiter. - // The Off / legacy paths do not read the signal, and building it is very cheap (Arc). - let turn_signal = dispatcher::TurnCompletionSignal::with_turn_cancellation(shutdown.child_token()); - let _turn_cancellation_guard = turn_signal.cancel_turns_on_exit(); - - #[cfg(feature = "terminal-tui")] - let (snapshot_tx_for_dispatcher, snapshot_rx_for_tui) = startup::initial_snapshot_channel( - provider_name, model_name, &initial_session, &config, top_redux_mode, - ); + let chat_result = cleanup + .run(async { + let child_cleanup = + crate::runtime::turn_cleanup::current_tracker().context("chat cleanup owner missing")?; + child_cleanup.retain_service(Arc::clone(&turn_service)); + + // v3a: coordination handle for interactive PTY terminal handoff. Shared with + // the unified TUI render loop (which parks while a PTY is attached) and the + // main loop's `/pty` handler (which pauses/resumes it around the passthrough). + // Only the TUI path performs the handoff; the non-TUI fallback has no render + // loop to suspend. + #[cfg(feature = "terminal-tui")] + let pty_handoff = Arc::new(crate::chat::sessions::pty::HandoffControl::new()); + + // Pre-load construction: the only mutable session copy, consumed by the + // reducer seed below. Afterwards the run loop reads the acknowledged session. + let mut initial_session = startup::resume_session( + session_id.as_deref(), + one_shot.is_some(), + &mem, + &memory_fabric, + &config, + provider_name, + model_name, + ) + .await?; + bind_session_to_runtime_provider_model(&mut initial_session, provider_name, model_name); + let (mut chat_session_key, mut fabric_turn_seq, banner, mut history) = startup::initial_conversation( + &initial_session, + &config, + provider_name, + model_name, + &skills, + native_tools, + ); - // The session authority outlives `shutdown`: shutdown cancels turns, and - // the exit sequence still settles them (and records the final usage and - // child exit summaries) through the dispatcher. It stops only in - // `finish_chat_session`, after the last of those commits; the guard stops - // it on an early error return as well, so no dispatcher task outlives this - // scope. - let dispatcher_stop = CancellationToken::new(); - let _dispatcher_stop_on_exit = dispatcher_stop.clone().drop_guard(); + #[cfg(feature = "terminal-tui")] + let (initial_saved_session_entries, chat_mirror) = + startup::initial_tui_mirror(&mem, &initial_session, &config, provider_name, model_name).await; + + // A resumed plain session shows its recent history on a terminal stdout. + let resume_recap = (plain_mode + && session_id.is_some() + && one_shot.is_none() + && std::io::IsTerminal::is_terminal(&std::io::stdout())) + .then(|| super::resume_recap::format_resume_recap(&initial_session)) + .flatten(); + #[cfg(feature = "terminal-tui")] + let ui_startup = startup::ChatStartupUi { + banner: &banner, + session_id: &initial_session.id, + initial_saved_session_entries: &initial_saved_session_entries, + resume_recap: resume_recap.as_deref(), + }; - #[cfg(feature = "terminal-tui")] - let dispatcher_handle = dispatcher::spawn_dispatcher_task_full( - dispatcher_shadow_state, - chat_action_rx, - dispatcher_stop.clone(), - effect_executor, - Some(turn_signal.clone()), - snapshot_tx_for_dispatcher, - ); - #[cfg(not(feature = "terminal-tui"))] - let dispatcher_handle = dispatcher::spawn_dispatcher_task_with_signal( - dispatcher_shadow_state, - chat_action_rx, - dispatcher_stop.clone(), - effect_executor, - Some(turn_signal.clone()), - ); + // ── Input channel ──────────────────────────────────────────── + let (input_tx, mut input_rx) = crate::runtime::h2_entry::ChatInputSender::channel(INPUT_CHANNEL_CAPACITY); + scheduled_input_handle.set_input_sender(input_tx.clone()); + // Taken before the terminal listener consumes `input_tx`: daemon-assigned + // work is submitted through the very same FIFO as typed input, which is + // what makes it go through the ordinary turn machinery rather than a + // parallel path with its own bugs. + let assignment_input_tx = input_tx.clone(); + let (control_tx, mut control_rx) = mpsc::channel::(CHAT_CONTROL_CHANNEL_CAPACITY); + #[cfg(not(feature = "terminal-tui"))] + let _ = &control_tx; + + // ── Graceful shutdown signal ───────────────────────────────── + // Instead of std::process::exit(), all signal handlers use this token to + // break the main loop gracefully, allowing final session save + teardown. + // The token is now supplied by the caller (D5/D9 step 1): dispatch owns the + // root shutdown token and passes it down. The internal ctrl_c single/double + // handlers below cancel this same external token, so chat remains the sole + // owner of ctrl_c semantics while the caller can also request shutdown. + + // The reducer seed opens with the startup provider view's system prompt. + let startup_system_prompt = history + .first() + .filter(|message| message.role == "system") + .map(|message| message.content.clone()); + let (chat_dispatcher, chat_action_rx, dispatcher_shadow_state) = startup::initial_dispatcher( + provider_name, + model_name, + &shutdown, + &initial_session, + startup_system_prompt, + #[cfg(feature = "terminal-tui")] + &config, + #[cfg(feature = "terminal-tui")] + &ui_startup, + ); - // Created before `terminal_input` shows the banner, so a press from then on is kept for the handler below. - let interrupts = startup::interrupt_listener()?; + // Shared dual-write guard (raised by the EffectExecutor in Both/Redux mode; the old path checks + // the guard to decide whether to skip persistence. It is built even in Off mode, where the old + // path's check is always false at zero cost. + // P0-1 fix: dropped allow(unused_variables) — the guard is read at the end of an old-path turn, + // so it is genuinely used under both feature configurations.) + let dual_write_guard = dispatcher::RuntimeDualWriteGuard::new(); + // The run loop's only view of the session: the reducer's acknowledged state. + let mut chat_session = chat_dispatcher.session_reader(); + + // PRX_CHAT_REDUX is read once at the entry point and reused inside the function body, so the env + // var is not parsed in several places. + // S4-B: Pure is the only supported run path; non-Pure values are warned about and forced up. + #[cfg(feature = "terminal-tui")] + let top_redux_mode: ReduxMode = { ReduxMode::from_env() }; + // The plain REPL runs one turn of the session at a time; later lines queue. + // Typed lines (terminal stdin) are acknowledged and bounded; piped input + // keeps every line. + let plain_typed_queue = plain_mode && std::io::IsTerminal::is_terminal(&std::io::stdin()); + #[cfg(feature = "terminal-tui")] + let max_concurrent_visible_turns = if plain_mode { + 1 + } else { + config.chat.max_concurrent_visible_turns.max(1) + }; + #[cfg(not(feature = "terminal-tui"))] + let max_concurrent_visible_turns = 1usize; + #[cfg(feature = "terminal-tui")] + let visible_input_admission_kind = crate::chat::turn_worker::ProviderTurnWorkerKind::Detached; + #[cfg(not(feature = "terminal-tui"))] + let visible_input_admission_kind = crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited; + + // Class B — bounded. Three events are emitted per provider turn, and with + // no cap on concurrent turns the emission rate is unbounded while the sole + // consumer is this loop, which also renders and handles input. See + // `PROVIDER_TURN_LIFECYCLE_CHANNEL_CAPACITY` for the sizing rationale. + let (provider_turn_lifecycle_tx, mut provider_turn_lifecycle_rx) = + mpsc::channel::(PROVIDER_TURN_LIFECYCLE_CHANNEL_CAPACITY); + #[cfg(not(feature = "terminal-tui"))] + let _ = &provider_turn_lifecycle_tx; - // ── Ctrl+C shared state ───────────────────────────────────── - // Tracks the timestamp (ms) of the last Ctrl+C press for double-press detection. - // Lifted above the input loop so the TUI dispatcher can fold its own - // Ctrl+C presses into the same double-press → exit semantics. - let last_ctrlc_ms = Arc::new(AtomicU64::new(0)); - // Non-TUI fallback still needs a shared cancellation slot for SIGINT. - #[cfg(not(feature = "terminal-tui"))] - let active_cancel: Arc>> = Arc::new(parking_lot::Mutex::new(None)); - // Fires when the line front end's stdin reaches EOF. - let stdin_closed = CancellationToken::new(); - // A one-shot reads no terminal input: its one message is queued below. - #[cfg(feature = "terminal-tui")] - let (terminal_guard, redraw_tx_for_main) = if one_shot.is_some() { - drop(input_tx); - (None, None) - } else { - startup::terminal_input( - plain_mode, entry::take_producer(&ctx), &ui_startup, &terminal, input_tx, &control_tx, &chat_mirror, &shutdown, - &last_ctrlc_ms, &chat_dispatcher, &executor_redraw_slot, &snapshot_rx_for_tui, - &pty_handoff, &config, &security, &stdin_closed, - ).await - }; - #[cfg(feature = "terminal-tui")] - let _operator_notices = startup::tui_operator_notices(&chat_dispatcher, redraw_tx_for_main.as_ref()); - #[cfg(not(feature = "terminal-tui"))] - let redraw_tx_for_main: Option> = None; - #[cfg(not(feature = "terminal-tui"))] - if one_shot.is_some() { - drop(input_tx); - } else { - println!("{banner}"); - eprintln!("{}", super::session_glue::current_chat_session_line(&chat_session.session().id)); - if let Some(recap) = resume_recap.as_deref() { - println!("{recap}"); - } - startup::spawn_line_input_listener(plain_mode, input_tx, stdin_closed.clone()); - } + // The last request's tool-surface reserve: `/compact`, compaction + // feedback and the context footer budget with it, as the preflight does. + let tool_surface_reserve = crate::agent::context_budget::ToolSurfaceReserve::default(); - let mut plain_mode_turn_failed = false; + // Pick the EffectExecutor mode from the redux mode (TUI feature only) + #[cfg(feature = "terminal-tui")] + let effect_executor = { + let mode: ReduxMode = top_redux_mode; + let deps = dispatcher::EffectDeps { + provider: Arc::clone(&provider), + memory_event_recording: config.memory.event_recording_config(), + channel: Arc::clone(&terminal) as Arc, + hooks: Arc::clone(&hooks), + observer: Arc::clone(&observer), + persistence: dispatcher::PersistenceDeps { + memory: Arc::clone(&mem), + action_tx: chat_dispatcher.sender(), + dual_write_guard: dual_write_guard.clone(), + }, + provider_turn_lifecycle_tx: Some(provider_turn_lifecycle_tx.clone()), + redraw_tx: None, + tui_mirror: Some(Arc::clone(&chat_mirror)), + shutdown: shutdown.clone(), + model: dispatcher::ModelSlot::new(Arc::from(model_name)), + temperature, + tools_registry: Some(Arc::clone(&tools_registry)), + approval_router: Arc::new(dispatcher::ApprovalRouter::new()), + tool_security_policy: Arc::clone(&security), + tool_tiering: config.tool_tiering.clone(), + tool_surface_reserve: tool_surface_reserve.clone(), + }; + tracing::info!(mode = ?mode, "chat EffectExecutor in Pure real-deps mode"); + let executor = dispatcher::EffectExecutor::new_with_deps(deps) + .with_cleanup_owner(Arc::clone(&child_cleanup)) + .with_session_publisher(chat_dispatcher.session_publisher()); + if persist_sessions { + executor + } else { + executor.without_session_rows() + } + }; + // Non-TUI: the persistence effects run for real (save, publish, ack); the + // tool loop performs provider turns, hooks and output itself. + #[cfg(not(feature = "terminal-tui"))] + let effect_executor = { + let executor = dispatcher::EffectExecutor::new_persistence_only(dispatcher::PersistenceDeps { + memory: Arc::clone(&mem), + action_tx: chat_dispatcher.sender(), + dual_write_guard: dual_write_guard.clone(), + }) + .with_session_publisher(chat_dispatcher.session_publisher()); + if persist_sessions { + executor + } else { + executor.without_session_rows() + } + }; - startup::ctrlc_handler( - interrupts, &last_ctrlc_ms, &shutdown, &chat_dispatcher, - #[cfg(feature = "terminal-tui")] &chat_mirror, - #[cfg(feature = "terminal-tui")] &redraw_tx_for_main, - #[cfg(not(feature = "terminal-tui"))] &active_cancel, - ); + // P0-2 fix: take the redraw_slot Arc up front so redraw_tx can be injected after TUI + // initialization completes. The EffectExecutor is consumed by the dispatcher + // spawn (`spawn_dispatcher_task_full`), but the Arc is cloned before the spawn, so the real sender + // can still be filled in afterwards through this Arc and RequestRedraw really executes. + #[cfg(feature = "terminal-tui")] + let executor_redraw_slot = effect_executor.redraw_handle(); - #[cfg(unix)] - startup::sigterm_handler(&shutdown, &chat_dispatcher); + // BUG-07: take the model hot-swap slot handle up front (same idea as redraw_slot: cloned before + // the spawn so that after the spawn `/model ` can still replace the model through this + // handle, and drive_start_turn_stream of later turns reads the new value). Shadow mode has no + // deps → None. + #[cfg(feature = "terminal-tui")] + let model_slot = effect_executor.model_handle(); - // BUG-07: the currently effective model name (owned, mutable). An online `/model ` switch - // rewrites this value; the top of each loop iteration borrows it as `model_name: &str` for the - // rest of the turn (system prompt / fabric events / snapshot). Its initial value matches the - // `model_name` resolved at startup. - let mut current_model_owned: String = model_name.to_string(); + // Bug #3: the provider hot-swap slot handle (same idea as model_slot). Cloned before the spawn, + // so that on `/provider ` the rebuilt provider handle can be set into it and the Redux + // driver of later turns (drive_start_turn_stream) reads the new provider. Shadow mode has no + // deps → None. + #[cfg(feature = "terminal-tui")] + let provider_slot = effect_executor.provider_handle(); - // Bug #3: the currently effective provider name (owned, mutable). An online `/provider ` - // switch rewrites this value; the top of each loop iteration borrows it as - // `provider_name: &str`, covering every later use of the provider in the turn (system prompt / - // fabric events / snapshot / the legacy tool-loop path's run_turn call). Its initial value matches the - // `provider_name` resolved at startup. - let mut current_provider_owned: String = provider_name.to_string(); - // Bug #3: the provider handle (the legacy tool-loop path's run_turn call uses `provider.as_ref()` - // directly). On `/provider ` this Arc is rebuilt and replaced with the new provider, which - // is also set into provider_slot (the Redux path). - let mut provider = provider; + #[cfg(feature = "terminal-tui")] + let approval_router = effect_executor.approval_router(); + #[cfg(not(feature = "terminal-tui"))] + let approval_router: Option> = None; - // ── Background-session observation state (v1b) ──────────────── - // Owned by the main loop (single-threaded), per the iron law that runtime - // state is only written here — the detached spawn tasks only mutate the - // shared registry, never this. `reported_sessions` dedups the one-shot - // summary reflow; `announced_started_sessions` dedups the started notices - // that promote sessions_spawn agents into the same visible child-session - // mode as shells; `last_sessions_summary` dedups the persistent status-line - // action so we only dispatch on change. The 1s timer is a read-only poll of - // the registry (no event bus until v1.1). - let mut reported_sessions: std::collections::HashSet = std::collections::HashSet::new(); - let mut announced_started_sessions: std::collections::HashSet = std::collections::HashSet::new(); - let mut last_sessions_summary: String = String::new(); - let mut last_sessions_entries: Vec = Vec::new(); - let mut sessions_tick = tokio::time::interval(Duration::from_secs(1)); - sessions_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); - // ── Event bridge state (v1.1a) ──────────────────────────────── - // Per-session ring buffers, written ONLY here (single consumer; iron law: - // the ring is never written by the background agent or the drainer). Live - // `/attach` follows one session at a time: when `attached_follow` matches an - // incoming event's session, its delta/tool lines are streamed inline to the - // existing scrollback (read-only — no input routing; that is v1.1b). - let mut session_rings: std::collections::HashMap< - crate::chat::sessions::id::SessionId, - crate::chat::sessions::SessionRing, - > = std::collections::HashMap::new(); - let reap_policy = crate::chat::sessions::runtime::ReapPolicy::default(); - let mut reaped_log_archive = ReapedSessionLogArchive::default(); - let mut ignored_session_events: std::collections::HashSet = - std::collections::HashSet::new(); - let mut input_backlog: std::collections::VecDeque = std::collections::VecDeque::new(); - let mut defer_visible_input_pop_once = false; - let mut turn_scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let mut history_commit_coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); - // The acknowledged compaction epoch the provider view was last brought up - // to at a turn's admission (see the admission barrier below). - let mut provider_view_compaction_epoch = chat_session.acked().compaction_epoch; - let mut provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - let mut provider_turn_lifecycle_events_open = true; - let (provider_completion_tx, mut provider_completion_rx) = mpsc::channel::(64); - #[cfg(not(feature = "terminal-tui"))] - let _ = &provider_completion_tx; - #[cfg(feature = "terminal-tui")] - let mut provider_turn_finalizer_events: std::collections::VecDeque = - std::collections::VecDeque::new(); - let mut pending_provider_completion_events: std::collections::HashMap< - crate::chat::turn_scheduler::TurnTaskId, - ProviderTurnCompletionEvent, - > = std::collections::HashMap::new(); - let mut provider_turn_completion_contexts: std::collections::HashMap< - crate::chat::turn_scheduler::TurnTaskId, - ProviderTurnCompletionContext, - > = std::collections::HashMap::new(); - #[cfg(feature = "terminal-tui")] - let mut per_turn_contexts: std::collections::HashMap = - std::collections::HashMap::new(); - #[cfg(feature = "terminal-tui")] - let mut pending_ordered_provider_turn_commits: std::collections::HashMap< - crate::chat::turn_scheduler::TurnTaskId, - PendingOrderedProviderTurnCommit, - > = std::collections::HashMap::new(); - #[cfg(feature = "terminal-tui")] - let mut deferred_resume_saved_session_ids: std::collections::VecDeque = std::collections::VecDeque::new(); - let mut attached_follow: Option = None; - // Display sequence `#N` of the currently-followed session, kept in lock-step - // with `attached_follow`. Used purely to reconstruct the *previous* focus - // target when an optimistic attach must be rolled back (v1.1b review P0): on - // attach failure the key thread has already pointed the prompt at the new - // seq, so the main loop restores `Main` (when None) or `Session { seq }`. - let mut attached_follow_seq: Option = None; - // Guards the event-drain select arm: once the event channel closes (only at - // shutdown — the sender lives as long as the tool registry) we disable the - // arm so a closed channel does not busy-spin returning `None`. - let mut session_events_open = true; - let mut control_events_open = true; - // Renderer nudge handle, available in both feature configs (the TUI-only - // `redraw_tx_for_main` is `Some` only on the TUI path; `None` otherwise so - // the helpers fall back to plain stdout). - #[cfg(feature = "terminal-tui")] - let sessions_redraw_handle: Option> = redraw_tx_for_main.clone(); - #[cfg(not(feature = "terminal-tui"))] - let sessions_redraw_handle: Option> = None; - let mut pending_chat_rewind: Option = None; - let mut pending_diff_apply: Option = None; - let mut input_events_open = one_shot.is_none(); - // The one-shot message, queued literally (D4): no priority prefix or - // command is interpreted. The input channel stays closed, so the loop - // ends once this turn resolves. - // The one-shot succeeds when its turn's ordered commit is acknowledged. - let mut one_shot_task_id: Option = None; - let mut one_shot_binding: Option> = None; - if let Some(turn) = one_shot.as_ref() { - turn.enqueue(&mut input_backlog, &mut turn_scheduler, chat_session.session().turns.len()); - } + // Step 5a-4: TurnCompletionSignal — the switched-over Redux driver path uses this signal to await + // turn completion in the chat::run main loop. After the dispatcher task consumes a terminal action + // (StreamCompleted/Failed/Cancelled) it calls notify_waiters to wake the waiter. + // The Off / legacy paths do not read the signal, and building it is very cheap (Arc). + let turn_signal = dispatcher::TurnCompletionSignal::with_turn_cancellation(shutdown.child_token()); + let _turn_cancellation_guard = turn_signal.cancel_turns_on_exit(); - // ── Reload notice: historical child sessions (v4) ──────── - // If this chat session was resumed and carried persisted background-session - // summaries, surface a one-shot recap so the user sees what their previous - // background tasks produced. These are **summaries only** — no process, - // sub-agent, or PTY is revived (those belonged to the prior process and are - // long gone); any session that was still running at last exit shows as - // `interrupted`. - // ── Inherited embedding default ────────────────────────────── - // The same notice `main` wrote to stderr, repeated on the first screen of - // the session: the stderr line is behind the alternate screen for as long - // as the TUI runs, and this is the entry point where vector recall costs - // something every turn. - if let Some(embedding_notice) = chat_embedding_upgrade_notice(&config) { - surface_session_message(&chat_dispatcher, sessions_redraw_handle.as_ref(), &embedding_notice); - } + #[cfg(feature = "terminal-tui")] + let (snapshot_tx_for_dispatcher, snapshot_rx_for_tui) = + startup::initial_snapshot_channel(provider_name, model_name, &initial_session, &config, top_redux_mode); + + // The session authority outlives `shutdown`: shutdown cancels turns, and + // the exit sequence still settles them (and records the final usage and + // child exit summaries) through the dispatcher. It stops only in + // `finish_chat_session`, after the last of those commits; the guard stops + // it on an early error return as well, so no dispatcher task outlives this + // scope. + let dispatcher_stop = CancellationToken::new(); + let _dispatcher_stop_on_exit = dispatcher_stop.clone().drop_guard(); - let loaded_background_sessions = chat_session.session(); - if !loaded_background_sessions.background_sessions.is_empty() { - let recap = format_reloaded_background_sessions(&loaded_background_sessions.background_sessions); - surface_session_message(&chat_dispatcher, sessions_redraw_handle.as_ref(), &recap); - } + #[cfg(feature = "terminal-tui")] + let dispatcher_handle = dispatcher::spawn_dispatcher_task_full( + dispatcher_shadow_state, + chat_action_rx, + dispatcher_stop.clone(), + effect_executor, + Some(turn_signal.clone()), + snapshot_tx_for_dispatcher, + ); + #[cfg(not(feature = "terminal-tui"))] + let dispatcher_handle = dispatcher::spawn_dispatcher_task_with_signal( + dispatcher_shadow_state, + chat_action_rx, + dispatcher_stop.clone(), + effect_executor, + Some(turn_signal.clone()), + ); - // ── Daemon-assigned work (c2) ──────────────────────────────── - // - // The other direction of the control link: a message on another channel can - // name this chat session and a task, and the task has to run *here*. Chat - // pulls its mailbox over the same control API it already uses, so nothing - // listens and no new transport exists. Enrolment happens off this path — a - // daemon that is down, slow or refusing credentials costs this chat the - // ability to be assigned work and nothing else. - // An unsaved one-shot session cannot be assigned work. - let assignment_enrolment = if one_shot.is_none() { - start_assignment_enrolment( - &config, - &chat_sessions, - &assignment_input_tx, - &chat_dispatcher, - sessions_redraw_handle.as_ref(), - ) - } else { - None - }; + // Created before `terminal_input` shows the banner, so a press from then on is kept for the handler below. + let interrupts = startup::interrupt_listener()?; - // ── Main message loop ──────────────────────────────────────── - // - // The inner `loop` lets a timer tick do background-session work (summary - // reflow + status-line refresh) without producing a message or ending the - // outer loop: it only `break`s with a real input message (or `None` on - // shutdown). On a tick we poll the registry and surface results via the - // dispatcher (single source, reaches both render paths), then keep waiting. - 'chat: while let Some(input) = loop { - turn_signal.ensure_history_commits_healthy()?; - #[cfg(feature = "terminal-tui")] - macro_rules! handle_resume_saved_session_control { - ($id:expr) => {{ - let provider_name = current_provider_owned.as_str(); - let model_name = current_model_owned.as_str(); - match resume_saved_session_by_id( - mem.as_ref(), - &$id, - ChatSwitchCtx { - chat_session: &mut chat_session, - commits: &turn_signal, - chat_session_key: &mut chat_session_key, - fabric_turn_seq: &mut fabric_turn_seq, - history: &mut history, - approval_router: approval_router.as_ref(), - pending_chat_rewind: &mut pending_chat_rewind, - pending_diff_apply: &mut pending_diff_apply, - chat_sessions: &mut chat_sessions, - ignored_session_events: &mut ignored_session_events, - session_rings: &mut session_rings, - reported_sessions: &mut reported_sessions, - announced_started_sessions: &mut announced_started_sessions, - last_sessions_summary: &mut last_sessions_summary, - last_sessions_entries: &mut last_sessions_entries, - attached_follow: &mut attached_follow, - attached_follow_seq: &mut attached_follow_seq, - chat_dispatcher: &chat_dispatcher, - redraw_handle: sessions_redraw_handle.as_ref(), - config: &config, - provider_name, - model_name, - skills: &skills, - native_tools, - #[cfg(feature = "terminal-tui")] - chat_mirror: &chat_mirror, - }, + // ── Ctrl+C shared state ───────────────────────────────────── + // Tracks the timestamp (ms) of the last Ctrl+C press for double-press detection. + // Lifted above the input loop so the TUI dispatcher can fold its own + // Ctrl+C presses into the same double-press → exit semantics. + let last_ctrlc_ms = Arc::new(AtomicU64::new(0)); + // Non-TUI fallback still needs a shared cancellation slot for SIGINT. + #[cfg(not(feature = "terminal-tui"))] + let active_cancel: Arc>> = + Arc::new(parking_lot::Mutex::new(None)); + // Fires when the line front end's stdin reaches EOF. + let stdin_closed = CancellationToken::new(); + // A one-shot reads no terminal input: its one message is queued below. + #[cfg(feature = "terminal-tui")] + let (terminal_guard, redraw_tx_for_main) = if one_shot.is_some() { + drop(input_tx); + (None, None) + } else { + startup::terminal_input( + plain_mode, + entry::take_producer(&ctx), + &ui_startup, + &terminal, + input_tx, + &control_tx, + &chat_mirror, + &shutdown, + &last_ctrlc_ms, + &chat_dispatcher, + &executor_redraw_slot, + &snapshot_rx_for_tui, + &pty_handoff, + &config, + &security, + &stdin_closed, ) .await - { - Ok(message) => surface_session_message(&chat_dispatcher, sessions_redraw_handle.as_ref(), &message), - Err(e) => { - surface_session_message(&chat_dispatcher, sessions_redraw_handle.as_ref(), &e.to_string()) - } - } - }}; - } - #[cfg(feature = "terminal-tui")] - if finalize_ready_per_turn_contexts( - &mut per_turn_contexts, - &mut pending_ordered_provider_turn_commits, - &mut pending_provider_completion_events, - &turn_signal, - &mut provider_turn_completion_contexts, - &mut history, - &tools_registry, - &mut provider_turn_finalizer_events, - &mut turn_scheduler, - &mut history_commit_coordinator, - &mut provider_turn_workers, - &chat_dispatcher, - &terminal, - &memory_fabric, - &chat_session_key, - &config, - sessions_redraw_handle.as_ref(), - redraw_tx_for_main.as_ref(), - plain_mode, - &mut plain_mode_turn_failed, - ) - .await - { - continue; - } - if !input_events_open && input_backlog.is_empty() { + }; #[cfg(feature = "terminal-tui")] - if should_continue_event_pump_after_input_closed(per_turn_contexts.len()) { - // Keep lifecycle/completion arms alive until the detached Redux turn - // resolves; this mirrors the old inner wait, which ignored closed - // input while the active turn was still running. + let _operator_notices = startup::tui_operator_notices(&chat_dispatcher, redraw_tx_for_main.as_ref()); + #[cfg(not(feature = "terminal-tui"))] + let redraw_tx_for_main: Option> = None; + #[cfg(not(feature = "terminal-tui"))] + if one_shot.is_some() { + drop(input_tx); } else { - break None; + println!("{banner}"); + eprintln!( + "{}", + super::session_glue::current_chat_session_line(&chat_session.session().id) + ); + if let Some(recap) = resume_recap.as_deref() { + println!("{recap}"); + } + startup::spawn_line_input_listener(plain_mode, input_tx, stdin_closed.clone()); } - #[cfg(not(feature = "terminal-tui"))] - break None; - } - #[cfg(feature = "terminal-tui")] - if !provider_turn_finalizer_events.is_empty() { - let results = drain_provider_turn_finalizer_events_and_publish( - &mut turn_scheduler, - &mut history_commit_coordinator, - &mut provider_turn_workers, - &mut provider_turn_finalizer_events, + + let mut plain_mode_turn_failed = false; + + startup::ctrlc_handler( + interrupts, + &last_ctrlc_ms, + &shutdown, &chat_dispatcher, + #[cfg(feature = "terminal-tui")] + &chat_mirror, + #[cfg(feature = "terminal-tui")] + &redraw_tx_for_main, + #[cfg(not(feature = "terminal-tui"))] + &active_cancel, ); + + #[cfg(unix)] + startup::sigterm_handler(&shutdown, &chat_dispatcher); + + // BUG-07: the currently effective model name (owned, mutable). An online `/model ` switch + // rewrites this value; the top of each loop iteration borrows it as `model_name: &str` for the + // rest of the turn (system prompt / fabric events / snapshot). Its initial value matches the + // `model_name` resolved at startup. + let mut current_model_owned: String = model_name.to_string(); + + // Bug #3: the currently effective provider name (owned, mutable). An online `/provider ` + // switch rewrites this value; the top of each loop iteration borrows it as + // `provider_name: &str`, covering every later use of the provider in the turn (system prompt / + // fabric events / snapshot / the legacy tool-loop path's run_turn call). Its initial value matches the + // `provider_name` resolved at startup. + let mut current_provider_owned: String = provider_name.to_string(); + // Bug #3: the provider handle (the legacy tool-loop path's run_turn call uses `provider.as_ref()` + // directly). On `/provider ` this Arc is rebuilt and replaced with the new provider, which + // is also set into provider_slot (the Redux path). + let mut provider = provider; + + // ── Background-session observation state (v1b) ──────────────── + // Owned by the main loop (single-threaded), per the iron law that runtime + // state is only written here — the detached spawn tasks only mutate the + // shared registry, never this. `reported_sessions` dedups the one-shot + // summary reflow; `announced_started_sessions` dedups the started notices + // that promote sessions_spawn agents into the same visible child-session + // mode as shells; `last_sessions_summary` dedups the persistent status-line + // action so we only dispatch on change. The 1s timer is a read-only poll of + // the registry (no event bus until v1.1). + let mut reported_sessions: std::collections::HashSet = std::collections::HashSet::new(); + let mut announced_started_sessions: std::collections::HashSet = std::collections::HashSet::new(); + let mut last_sessions_summary: String = String::new(); + let mut last_sessions_entries: Vec = Vec::new(); + let mut sessions_tick = tokio::time::interval(Duration::from_secs(1)); + sessions_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + // ── Event bridge state (v1.1a) ──────────────────────────────── + // Per-session ring buffers, written ONLY here (single consumer; iron law: + // the ring is never written by the background agent or the drainer). Live + // `/attach` follows one session at a time: when `attached_follow` matches an + // incoming event's session, its delta/tool lines are streamed inline to the + // existing scrollback (read-only — no input routing; that is v1.1b). + let mut session_rings: std::collections::HashMap< + crate::chat::sessions::id::SessionId, + crate::chat::sessions::SessionRing, + > = std::collections::HashMap::new(); + let reap_policy = crate::chat::sessions::runtime::ReapPolicy::default(); + let mut reaped_log_archive = ReapedSessionLogArchive::default(); + let mut ignored_session_events: std::collections::HashSet = + std::collections::HashSet::new(); + let mut input_backlog: std::collections::VecDeque = std::collections::VecDeque::new(); + let mut defer_visible_input_pop_once = false; + let mut turn_scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let mut history_commit_coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); + // The acknowledged compaction epoch the provider view was last brought up + // to at a turn's admission (see the admission barrier below). + let mut provider_view_compaction_epoch = chat_session.acked().compaction_epoch; + let mut provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + let mut provider_turn_lifecycle_events_open = true; + let (provider_completion_tx, mut provider_completion_rx) = mpsc::channel::(64); + #[cfg(not(feature = "terminal-tui"))] + let _ = &provider_completion_tx; #[cfg(feature = "terminal-tui")] - let applied_ordered_commits = apply_ready_ordered_provider_turn_commits( - results, - &mut pending_ordered_provider_turn_commits, - &mut history, - &mut turn_scheduler, - &provider_turn_workers, - &chat_dispatcher, - &terminal, - &memory_fabric, - &chat_session_key, - &config, - sessions_redraw_handle.as_ref(), - redraw_tx_for_main.as_ref(), - &turn_signal, - plain_mode, - &mut plain_mode_turn_failed, - ) - .await; + let mut provider_turn_finalizer_events: std::collections::VecDeque = + std::collections::VecDeque::new(); + let mut pending_provider_completion_events: std::collections::HashMap< + crate::chat::turn_scheduler::TurnTaskId, + ProviderTurnCompletionEvent, + > = std::collections::HashMap::new(); + let mut provider_turn_completion_contexts: std::collections::HashMap< + crate::chat::turn_scheduler::TurnTaskId, + ProviderTurnCompletionContext, + > = std::collections::HashMap::new(); + #[cfg(feature = "terminal-tui")] + let mut per_turn_contexts: std::collections::HashMap< + crate::chat::turn_scheduler::TurnTaskId, + PerTurnContext, + > = std::collections::HashMap::new(); + #[cfg(feature = "terminal-tui")] + let mut pending_ordered_provider_turn_commits: std::collections::HashMap< + crate::chat::turn_scheduler::TurnTaskId, + PendingOrderedProviderTurnCommit, + > = std::collections::HashMap::new(); + #[cfg(feature = "terminal-tui")] + let mut deferred_resume_saved_session_ids: std::collections::VecDeque = + std::collections::VecDeque::new(); + let mut attached_follow: Option = None; + // Display sequence `#N` of the currently-followed session, kept in lock-step + // with `attached_follow`. Used purely to reconstruct the *previous* focus + // target when an optimistic attach must be rolled back (v1.1b review P0): on + // attach failure the key thread has already pointed the prompt at the new + // seq, so the main loop restores `Main` (when None) or `Session { seq }`. + let mut attached_follow_seq: Option = None; + let mut child_focus = super::child_focus::ChildFocus::default(); + // Guards the event-drain select arm: once the event channel closes (only at + // shutdown — the sender lives as long as the tool registry) we disable the + // arm so a closed channel does not busy-spin returning `None`. + let mut session_events_open = true; + let mut control_events_open = true; + // Renderer nudge handle, available in both feature configs (the TUI-only + // `redraw_tx_for_main` is `Some` only on the TUI path; `None` otherwise so + // the helpers fall back to plain stdout). + #[cfg(feature = "terminal-tui")] + let sessions_redraw_handle: Option> = redraw_tx_for_main.clone(); #[cfg(not(feature = "terminal-tui"))] - let applied_ordered_commits = !results.is_empty(); - if applied_ordered_commits { - continue; - } - } - if consume_deferred_visible_input_pop(&mut defer_visible_input_pop_once) { - // A post-route admission failure just requeued the same input at the - // front. Skip one immediate visible pop so the event pump can consume - // in-flight completion/lifecycle events that may free stricter Legacy - // admission. - } else if let Some(input) = pop_next_visible_input_task_with_scheduler( - &mut input_backlog, - &mut turn_scheduler, - &provider_turn_workers, - visible_input_admission_kind, - max_concurrent_visible_turns, - ) { - publish_main_queue_status(&chat_dispatcher, &turn_scheduler); - break Some(input); - } - #[cfg(feature = "terminal-tui")] - if should_drain_deferred_resume_after_visible_inputs( - per_turn_contexts.len(), - &input_backlog, - &provider_turn_workers, - ) && let Some(id) = deferred_resume_saved_session_ids.pop_front() - { - handle_resume_saved_session_control!(id); - continue; - } - tokio::select! { - msg = input_rx.recv(), if input_events_open => { - let Some(msg) = msg else { - #[cfg(feature = "terminal-tui")] - { - if !per_turn_contexts.is_empty() { - input_events_open = false; - continue; - } - } - break None; - }; - #[cfg(feature = "terminal-tui")] - let active_task_id = per_turn_contexts.keys().next().copied(); - #[cfg(feature = "terminal-tui")] - if let Some(active_task_id) = active_task_id { - let mut emit_active_turn_output = - |text: &str| surface_active_turn_message(&chat_dispatcher, redraw_tx_for_main.as_ref(), text); - let daemon_control = DaemonControl { - config: &config, - dispatcher: &chat_dispatcher, - redraw_tx: redraw_tx_for_main.as_ref(), - }; - let queued_from = input_backlog.len(); - process_active_turn_input_batch( - msg, - &mut emit_active_turn_output, - &mut input_rx, - &mut input_backlog, - &mut turn_scheduler, - &mut provider_turn_workers, - Some(active_task_id), - &chat_dispatcher, - &chat_session.session(), - &mut chat_sessions, - &session_rings, - &mut reaped_log_archive, - &reap_policy, - &tools_registry, - daemon_control, - ) - .await; - if plain_typed_queue { - let added = lines_queued_since(&input_backlog, queued_from); - settle_queued_lines(&mut input_backlog, &mut turn_scheduler, &added); - } - publish_main_queue_status(&chat_dispatcher, &turn_scheduler); - continue; - } - let queued_from = input_backlog.len(); - enqueue_input_message_with_scheduler( + let sessions_redraw_handle: Option> = None; + let mut pending_chat_rewind: Option = None; + let mut pending_diff_apply: Option = None; + let mut input_events_open = one_shot.is_none(); + // The one-shot message, queued literally (D4): no priority prefix or + // command is interpreted. The input channel stays closed, so the loop + // ends once this turn resolves. + // The one-shot succeeds when its turn's ordered commit is acknowledged. + let mut one_shot_task_id: Option = None; + let mut one_shot_binding: Option> = None; + if let Some(turn) = one_shot.as_ref() { + turn.enqueue( &mut input_backlog, &mut turn_scheduler, - msg, - chat_session.session().turns.len(), - ); - drain_available_input_messages( - &mut input_rx, - &mut input_backlog, - Some(&mut turn_scheduler), chat_session.session().turns.len(), ); - let added = lines_queued_since(&input_backlog, queued_from); - publish_main_queue_status(&chat_dispatcher, &turn_scheduler); - let next = pop_next_visible_input_task_with_scheduler( - &mut input_backlog, - &mut turn_scheduler, - &provider_turn_workers, - visible_input_admission_kind, - max_concurrent_visible_turns, - ); - if plain_typed_queue { - settle_queued_lines(&mut input_backlog, &mut turn_scheduler, &added); - } - if let Some(next) = next { - // The enqueue snapshot above reports this item as queued. - // Publish again after dequeue so fast slash commands, which - // never enter the provider-turn path, cannot leave a stale - // `queue:1` badge behind in the TUI. - publish_main_queue_status(&chat_dispatcher, &turn_scheduler); - break Some(next); - } - continue; - }, - // EOF on the line front end's stdin. Lines read before it are - // still queued; the arm waits until the input arm has taken them, - // then closes the input like a closed channel would. The guard is - // evaluated before the select polls: the reader may send its last - // lines and fire EOF while the loop waits, making both arms ready - // at once. Re-check here so lines sent before EOF are never dropped. - () = stdin_closed.cancelled(), if input_events_open && input_rx.is_empty() => { - if !input_rx.is_empty() { - continue; - } - input_events_open = false; - continue; - }, - lifecycle = provider_turn_lifecycle_rx.recv(), if provider_turn_lifecycle_events_open => { - let Some(lifecycle) = lifecycle else { - provider_turn_lifecycle_events_open = false; - continue; - }; - record_provider_turn_lifecycle_event( - &mut provider_turn_workers, - lifecycle, - ); - publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); - continue; - }, - completion = provider_completion_rx.recv() => { - let Some(completion) = completion else { - continue; - }; - let _ = route_provider_completion_event_and_publish( - &mut provider_turn_lifecycle_rx, - &mut provider_turn_lifecycle_events_open, - &mut provider_turn_workers, - &mut pending_provider_completion_events, - None, - completion, + } + + // ── Reload notice: historical child sessions (v4) ──────── + // If this chat session was resumed and carried persisted background-session + // summaries, surface a one-shot recap so the user sees what their previous + // background tasks produced. These are **summaries only** — no process, + // sub-agent, or PTY is revived (those belonged to the prior process and are + // long gone); any session that was still running at last exit shows as + // `interrupted`. + // ── Inherited embedding default ────────────────────────────── + // The same notice `main` wrote to stderr, repeated on the first screen of + // the session: the stderr line is behind the alternate screen for as long + // as the TUI runs, and this is the entry point where vector recall costs + // something every turn. + if let Some(embedding_notice) = chat_embedding_upgrade_notice(&config) { + surface_session_message(&chat_dispatcher, sessions_redraw_handle.as_ref(), &embedding_notice); + } + + let loaded_background_sessions = chat_session.session(); + if !loaded_background_sessions.background_sessions.is_empty() { + let recap = format_reloaded_background_sessions(&loaded_background_sessions.background_sessions); + surface_session_message(&chat_dispatcher, sessions_redraw_handle.as_ref(), &recap); + } + + // ── Daemon-assigned work (c2) ──────────────────────────────── + // + // The other direction of the control link: a message on another channel can + // name this chat session and a task, and the task has to run *here*. Chat + // pulls its mailbox over the same control API it already uses, so nothing + // listens and no new transport exists. Enrolment happens off this path — a + // daemon that is down, slow or refusing credentials costs this chat the + // ability to be assigned work and nothing else. + // An unsaved one-shot session cannot be assigned work. + let assignment_enrolment = if one_shot.is_none() { + start_assignment_enrolment( + &config, + &chat_sessions, + &assignment_input_tx, &chat_dispatcher, - ); - #[cfg(feature = "terminal-tui")] + sessions_redraw_handle.as_ref(), + ) + } else { + None + }; + + super::child_focus::ChildFocusContext { + memory: &mem, + generation: &ctx.config_generation, + parent: &chat_session_key, + security: &ctx.security, + service: &turn_service, + tools: &tools_registry, + sessions: &chat_sessions, + approvals: &pending_approvals, + } + .restore() + .await?; + + // ── Main message loop ──────────────────────────────────────── + // + // The inner `loop` lets a timer tick do background-session work (summary + // reflow + status-line refresh) without producing a message or ending the + // outer loop: it only `break`s with a real input message (or `None` on + // shutdown). On a tick we poll the registry and surface results via the + // dispatcher (single source, reaches both render paths), then keep waiting. + 'chat: while let Some(input) = include!("run/event_pump.rs") { + turn_signal.ensure_history_commits_healthy()?; + let provider_queue_task_id = input.turn_task_id; + let input_priority = input.priority; + let terminal_origin = input.terminal_origin; + let msg = input.msg; + if let Err(error) = + entry::validate_input(ctx.controlled_entry.is_some(), terminal_origin.is_some(), &msg.content) { - let _ = finalize_ready_per_turn_contexts( - &mut per_turn_contexts, - &mut pending_ordered_provider_turn_commits, - &mut pending_provider_completion_events, - &turn_signal, - &mut provider_turn_completion_contexts, - &mut history, - &tools_registry, - &mut provider_turn_finalizer_events, - &mut turn_scheduler, - &mut history_commit_coordinator, - &mut provider_turn_workers, - &chat_dispatcher, - &terminal, - &memory_fabric, - &chat_session_key, - &config, - sessions_redraw_handle.as_ref(), - redraw_tx_for_main.as_ref(), - plain_mode, - &mut plain_mode_turn_failed, - ) - .await; + surface_session_message(&chat_dispatcher, sessions_redraw_handle.as_ref(), &error.to_string()); + continue; } - continue; - }, - _ = shutdown.cancelled() => { - #[cfg(feature = "terminal-tui")] - { - if !per_turn_contexts.is_empty() { - finalize_all_per_turn_contexts_as_cancelled( - &mut per_turn_contexts, - &mut pending_ordered_provider_turn_commits, - &turn_signal, - &mut provider_turn_completion_contexts, - &mut history, - tools_registry.as_ref(), - &mut provider_turn_finalizer_events, - &mut turn_scheduler, - &mut history_commit_coordinator, - &mut provider_turn_workers, - &chat_dispatcher, - &terminal, - &memory_fabric, - &chat_session_key, - &config, - sessions_redraw_handle.as_ref(), - redraw_tx_for_main.as_ref(), - plain_mode, - &mut plain_mode_turn_failed, + if let Some(target) = attached_follow.as_ref() { + match child_focus + .submit( + target.as_str(), + msg.clone(), + &super::child_focus::ChildFocusContext { + memory: &mem, + generation: &ctx.config_generation, + parent: &chat_session_key, + security: &ctx.security, + service: &turn_service, + tools: &tools_registry, + sessions: &chat_sessions, + approvals: &pending_approvals, + }, ) - .await; - } - } - break None - }, - maybe_control = control_rx.recv(), if control_events_open => { - let Some(control) = maybe_control else { - control_events_open = false; - continue; - }; - match control { - #[cfg(feature = "terminal-tui")] - ChatControlEvent::ResumeSavedSession { id } => { - #[cfg(feature = "terminal-tui")] - if defer_resume_saved_session_if_provider_turn_pending( - per_turn_contexts.len(), - &mut deferred_resume_saved_session_ids, - id.clone(), - ) { - // Old Redux N=1 behavior waited inside the turn and did not - // poll control_rx, so session switching could not mutate - // chat_session/history until the active turn was finalized. + .await + { + Ok(Some(output)) => { + surface_session_message(&chat_dispatcher, sessions_redraw_handle.as_ref(), &output); continue; } - handle_resume_saved_session_control!(id); - continue; - } - } - } - rewind_approval = async { - match pending_chat_rewind.as_mut() { - Some(pending) => (&mut pending.approval_rx).await, - None => std::future::pending::>().await, - } - }, if pending_chat_rewind.is_some() => { - let Some(pending) = pending_chat_rewind.take() else { - continue; - }; - match resolve_rewind_approval(&pending.tool_id, rewind_approval) { - RewindApprovalOutcome::Apply => { - let target_id = pending.target_session.id.clone(); - let target_turns = pending.target_session.turn_count(); - let provider_name = current_provider_owned.as_str(); - let model_name = current_model_owned.as_str(); - match apply_chat_session_switch(ChatSwitchCtx { - chat_session: &mut chat_session, - commits: &turn_signal, - chat_session_key: &mut chat_session_key, - fabric_turn_seq: &mut fabric_turn_seq, - history: &mut history, - approval_router: approval_router.as_ref(), - pending_chat_rewind: &mut pending_chat_rewind, - pending_diff_apply: &mut pending_diff_apply, - chat_sessions: &mut chat_sessions, - ignored_session_events: &mut ignored_session_events, - session_rings: &mut session_rings, - reported_sessions: &mut reported_sessions, - announced_started_sessions: &mut announced_started_sessions, - last_sessions_summary: &mut last_sessions_summary, - last_sessions_entries: &mut last_sessions_entries, - attached_follow: &mut attached_follow, - attached_follow_seq: &mut attached_follow_seq, - chat_dispatcher: &chat_dispatcher, - redraw_handle: sessions_redraw_handle.as_ref(), - config: &config, - provider_name, - model_name, - skills: &skills, - native_tools, - #[cfg(feature = "terminal-tui")] - chat_mirror: &chat_mirror, - }, pending.target_session, true).await { - Ok(()) => surface_session_message( - &chat_dispatcher, - sessions_redraw_handle.as_ref(), - &format!("Rewound chat session {target_id} to {target_turns} turns."), - ), - Err(e) => surface_session_message( - &chat_dispatcher, - sessions_redraw_handle.as_ref(), - &format!("Rewind aborted: failed to save trimmed session: {e}"), - ), - } - } - RewindApprovalOutcome::Cancelled(message) => { - surface_session_message(&chat_dispatcher, sessions_redraw_handle.as_ref(), &message); - } - } - continue; - } - apply_approval = async { - match pending_diff_apply.as_mut() { - Some(pending) => (&mut pending.approval_rx).await, - None => std::future::pending::>().await, - } - }, if pending_diff_apply.is_some() => { - let Some(pending) = pending_diff_apply.take() else { - continue; - }; - match apply_approval { - Ok(true) => { - let security = crate::runtime::bootstrap::build_security_policy(&config); - match diff_apply::execute_plan(&pending.plan, security.as_ref()).await { - Ok(message) => surface_session_message( - &chat_dispatcher, - sessions_redraw_handle.as_ref(), - &message, - ), - Err(error) => surface_session_message( + Err(error) => { + surface_session_message( &chat_dispatcher, sessions_redraw_handle.as_ref(), - &format!("Diff apply aborted: {error}. Workspace unchanged."), - ), + &error.to_string(), + ); + continue; } - } - Ok(false) => { - surface_session_message( - &chat_dispatcher, - sessions_redraw_handle.as_ref(), - "Diff apply cancelled; workspace unchanged.", - ); - } - Err(_) => { - surface_session_message( - &chat_dispatcher, - sessions_redraw_handle.as_ref(), - &format!( - "Diff apply cancelled; approval channel closed for {} and workspace is unchanged.", - pending.tool_id - ), - ); + Ok(None) => {} } } - continue; - } - _ = sessions_tick.tick() => { - // 1) Summary reflow: surface each newly-finished session once, - // carrying its `#N` + status (plan §v1b). No auto-focus. - let finished = chat_sessions.poll_finished(&mut reported_sessions).await; - // 2) Persistent status line: recompute and dispatch only on change. - let views = chat_sessions.snapshot().await; - for fin in &finished { - let line = format_finished_session_announcement(fin); - let compact_summary = compact_child_completion_summary(&fin.summary); - surface_session_message( - &chat_dispatcher, - sessions_redraw_handle.as_ref(), - &line, - ); - // v4: persist a summary of this finished child session - // into the chat session so a reload can show what it - // produced. Title / created_at come from the live view (the - // finished record itself only carries seq/status/summary); - // if the view is already gone we still record with the - // finished record's own fields so nothing is lost. - let persisted = views - .iter() - .find(|v| v.id.as_str() == fin.run_id) - .map_or_else( - || crate::chat::sessions::PersistedSessionSummary { - id: fin.run_id.clone(), - seq: fin.seq, - kind: fin.kind.as_str().to_string(), - origin: fin.origin.as_str().to_string(), - status: fin.status.as_str().to_string(), - title: String::new(), - summary: compact_summary.clone(), - token_usage_records: fin.token_usage_records.clone(), - created_at: fin.created_at, - }, - |view| { - crate::chat::sessions::PersistedSessionSummary::from_view( - view, - compact_summary.clone(), - ) - }, - ); - // The reducer records and saves the summary (both builds). + let user_input = msg.content.clone(); + let synthetic_ui_command = is_synthetic_ui_command(&msg); + // Armed here, at the top, because the turn body has many exits — a + // slash command short-circuits it, a cancellation unwinds it, `/quit` + // breaks the loop — and an assigner left waiting forever is the worst + // of them. The guard reports on whichever exit happens; the one that + // requeues the input disarms it, because that work still has to run. + let mut assignment_guard = assignment_turn_guard( + assignment_enrolment.as_ref(), + &chat_sessions, + &chat_dispatcher, + sessions_redraw_handle.as_ref(), + &msg, + ); + + // Bug #3: the provider name effective for this iteration (borrowed from the mutable owned + // value). The `/provider ` interception rewrites `current_provider_owned` and the + // `provider` Arc, so on the next iteration this shadow points at the new provider name and + // covers every later use of `provider_name` (including `/model` validation / system prompt / + // fabric / the legacy tool-loop path's run_turn call). + let provider_name: &str = current_provider_owned.as_str(); + + // Step 5b dual write: every user input enters the dispatcher (shadow observation of the + // reducer). InputSubmitted only records UI/LogTrace; RecordUserTurn really writes history + + // session.turns and must only be dispatched after mem_context injection (using `enriched` so + // it is byte-for-byte aligned with the legacy `history.push` — see the S2-B Step 4 risk + // notes). + if !synthetic_ui_command { let _ = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::BackgroundSessionRecorded { summary: persisted }, - "chat.bg_session_recorded", + crate::chat::action::Action::InputSubmitted(user_input.clone()), + "chat.input_submitted", ); } - let now = chrono::Utc::now(); - let reaped = chat_sessions.reap(&reap_policy, now).await; - if !reaped.reaped.is_empty() { - let reaped_ids = reaped - .reaped - .iter() - .map(|session| session.id.clone()) - .collect::>(); - for session in &reaped.reaped { - if chat_session - .session() - .background_sessions - .iter() - .any(|summary| summary.id == session.summary.id) - { - continue; - } - let _ = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::BackgroundSessionRecorded { - summary: session.summary.clone(), - }, - "chat.bg_session_recorded_reap", - ); - } - reaped_log_archive.archive_reaped(&reaped.reaped, &mut session_rings, &reap_policy, now); - if attached_follow.as_ref().is_some_and(|id| reaped_ids.contains(id)) { - attached_follow = None; - attached_follow_seq = None; - let focus = crate::chat::sessions::FocusTarget::Main; - let _ = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::SessionFocusChanged { focus }, - "chat.session_focus_reaped", - ); - #[cfg(feature = "terminal-tui")] - { - { - let mut mirror = chat_mirror.lock(); - mirror.focus = focus; - mirror.active_session_view = None; - } - let _ = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::ActiveSessionViewUpdated { view: None }, - "chat.active_session_view_reaped", - ); - } - } - } - let views = chat_sessions.snapshot().await; - for view in &views { - if view.kind != crate::chat::sessions::model::ManagedKind::Agent { - continue; - } - if announced_started_sessions.insert(view.id.as_str().to_string()) { - let line = format_observed_session_announcement(view); - surface_session_message(&chat_dispatcher, sessions_redraw_handle.as_ref(), &line); - } - } - // v1.1b: refresh the switcher cache the key thread reads on Ctrl+G - // (it cannot run async registry queries itself). Display staleness - // is harmless: switcher Enter re-resolves the seq via /attach. + + // Echo the user's input into the TUI conversation pane. + // + // Why: in raw-mode TUI the input box clears on submit, so without + // this push the user has no visual confirmation of what they sent + // until the assistant streams its reply. We push BEFORE the slash + // command short-circuits below so that even `/quit`, `/clear`, etc. + // produce a visible record of what was typed. + // + // Non-TUI (`--plain`, piped stdin, reedline fallback) is unaffected: + // the terminal already echoes typed characters as cooked input, and + // `redraw_tx_for_main` is `None` on those paths. #[cfg(feature = "terminal-tui")] { - let idle_warnings = chat_sessions - .idle_warning_seqs(&reap_policy, chrono::Utc::now(), &session_rings) - .await; - let mut entries = crate::chat::sessions::focus::switcher_entries(&views); - for entry in &mut entries { - entry.idle_warning = idle_warnings.contains(&entry.seq); - } - { - let mut mirror = chat_mirror.lock(); - refresh_sessions_cache(&mut mirror, entries.clone()); - } - if entries != last_sessions_entries { - last_sessions_entries = entries.clone(); + // S4-B: the legacy mirror push is deleted; the reducer is the single source through + // UserMessageEchoed. + if !synthetic_ui_command { let _ = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::SessionsEntriesUpdated { entries }, - "chat.sessions_entries", + crate::chat::action::Action::UserMessageEchoed(user_input.clone()), + "chat.user_message_echoed", ); - if let Some(tx) = sessions_redraw_handle.as_ref() { - let _ = tx.try_send(()); - } + } + if let Some(tx) = redraw_tx_for_main.as_ref() { + let _ = tx.try_send(()); } } - let new_summary = crate::chat::sessions::status_summary(&views); - if new_summary != last_sessions_summary { - last_sessions_summary = new_summary.clone(); + + // Route any user-visible slash-command output into the right sink: + // (defined before the bang handler so `!cmd` can emit its output). + // ratatui mirror on the TUI path (so it survives raw-mode `\n` + // mangling), plain stdout otherwise. Returns immediately for plain + // mode so the legacy `--plain` / piped path is unchanged. + #[cfg(feature = "terminal-tui")] + let mut emit_chat_output = |text: &str| { + // S4-B: the mirror side write is deleted; the reducer is the single source through + // SystemMessageAdded. let _ = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::SessionsStatusUpdated { summary: new_summary }, - "chat.sessions_status", + crate::chat::action::Action::SystemMessageAdded { text: text.to_string() }, + "chat.system_message_slash", ); - if let Some(tx) = sessions_redraw_handle.as_ref() { + if let Some(tx) = redraw_tx_for_main.as_ref() { let _ = tx.try_send(()); + } else { + print_fallback_chat_output(text); } - } - // Keep waiting (do not break the inner loop / produce a message). - continue; - } - maybe_event = session_event_rx.recv(), if session_events_open => { - // Drain one background-session event: append it to that session's - // ring (single-consumer write, no lock) and, if focused, refresh - // the child viewport. P2 keeps child output out of main scrollback. - let Some(event) = maybe_event else { - // Sender side closed (chat shutting down). Disable this arm so - // a closed channel does not busy-spin; other arms drive exit. - session_events_open = false; - continue; }; - let sid = event.session_id().clone(); - if should_ignore_session_event_after_chat_resume(&ignored_session_events, &event) { - continue; - } - let ring = session_rings - .entry(sid.clone()) - .or_insert_with(|| crate::chat::sessions::SessionRing::with_capacity( - crate::chat::sessions::event::DEFAULT_RING_CAPACITY, - )); - // A `Truncated` marker carries no output line; it only flags the - // ring so `/attach` shows `[output truncated]` for events the - // drainer had to drop on a full channel (P1 fix). Delta/ToolCall - // append their text as a new ring line. - let line = match &event { - crate::chat::sessions::SessionEvent::Delta { text, .. } => Some(text.clone()), - crate::chat::sessions::SessionEvent::ToolCall { summary, .. } => Some(summary.clone()), - crate::chat::sessions::SessionEvent::Truncated { .. } => { - ring.mark_truncated(); - None - } - // NeedsInput: a background sub-agent suspended awaiting an - // operator approval decision. Record a ring line for `/attach` - // visibility; the non-intrusive `/approve` hint is surfaced - // below (after the seq is resolved). Status flips to - // `❓ needs-input` via the registry (already set by the - // resolver) on the next status refresh. - crate::chat::sessions::SessionEvent::NeedsInput { prompt, .. } => { - Some(format!("[needs approval] {prompt}")) - } - crate::chat::sessions::SessionEvent::Resumed { .. } => { - Some("[approval resolved — resuming]".to_string()) - } + #[cfg(not(feature = "terminal-tui"))] + let emit_chat_output = |text: &str| { + print_fallback_chat_output(text); }; - if let Some(line) = line { - ring.push(line); - } - // NeedsInput / Resumed are control signals (not stream output): - // surface a non-intrusive operator hint with the session's `#N` - // and refresh the status line / switcher so the `❓` glyph and - // `needs-input` counter appear immediately, regardless of attach. - match &event { - crate::chat::sessions::SessionEvent::NeedsInput { prompt, .. } => { - let seq = chat_sessions.seq_for_id(&sid).await; - let label = seq - .map(|n| format!("#{n}")) - .unwrap_or_else(|| sid.as_str().to_string()); - surface_session_message( - &chat_dispatcher, - sessions_redraw_handle.as_ref(), - &format!( - "session {label} awaiting approval: {prompt} — /approve {} or /deny {} (/attach {} to inspect)", - seq.map(|n| n.to_string()).unwrap_or_else(|| label.clone()), - seq.map(|n| n.to_string()).unwrap_or_else(|| label.clone()), - seq.map(|n| n.to_string()).unwrap_or_else(|| label.clone()), - ), - ); - } - crate::chat::sessions::SessionEvent::Resumed { .. } => { - if let Some(tx) = sessions_redraw_handle.as_ref() { - let _ = tx.try_send(()); - } - } - _ => {} - } - #[cfg(feature = "terminal-tui")] - if attached_follow.as_ref() == Some(&sid) { - refresh_attached_session_view_from_ring( - &chat_mirror, - &chat_dispatcher, - sessions_redraw_handle.as_ref(), - &sid, - ring, - ); - } - continue; - } - } - } { - turn_signal.ensure_history_commits_healthy()?; - let provider_queue_task_id = input.turn_task_id; - let input_priority = input.priority; - let terminal_origin = input.terminal_origin; - let msg = input.msg; - if let Err(error) = entry::validate_input(ctx.controlled_entry.is_some(),terminal_origin.is_some(),&msg.content) { - surface_session_message(&chat_dispatcher,sessions_redraw_handle.as_ref(),&error.to_string()); continue; - } - let user_input = msg.content.clone(); - let synthetic_ui_command = is_synthetic_ui_command(&msg); - // Armed here, at the top, because the turn body has many exits — a - // slash command short-circuits it, a cancellation unwinds it, `/quit` - // breaks the loop — and an assigner left waiting forever is the worst - // of them. The guard reports on whichever exit happens; the one that - // requeues the input disarms it, because that work still has to run. - let mut assignment_guard = assignment_turn_guard( - assignment_enrolment.as_ref(), - &chat_sessions, - &chat_dispatcher, - sessions_redraw_handle.as_ref(), - &msg, - ); - - // Bug #3: the provider name effective for this iteration (borrowed from the mutable owned - // value). The `/provider ` interception rewrites `current_provider_owned` and the - // `provider` Arc, so on the next iteration this shadow points at the new provider name and - // covers every later use of `provider_name` (including `/model` validation / system prompt / - // fabric / the legacy tool-loop path's run_turn call). - let provider_name: &str = current_provider_owned.as_str(); - - // Step 5b dual write: every user input enters the dispatcher (shadow observation of the - // reducer). InputSubmitted only records UI/LogTrace; RecordUserTurn really writes history + - // session.turns and must only be dispatched after mem_context injection (using `enriched` so - // it is byte-for-byte aligned with the legacy `history.push` — see the S2-B Step 4 risk - // notes). - if !synthetic_ui_command { - let _ = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::InputSubmitted(user_input.clone()), - "chat.input_submitted", - ); - } - - // Echo the user's input into the TUI conversation pane. - // - // Why: in raw-mode TUI the input box clears on submit, so without - // this push the user has no visual confirmation of what they sent - // until the assistant streams its reply. We push BEFORE the slash - // command short-circuits below so that even `/quit`, `/clear`, etc. - // produce a visible record of what was typed. - // - // Non-TUI (`--plain`, piped stdin, reedline fallback) is unaffected: - // the terminal already echoes typed characters as cooked input, and - // `redraw_tx_for_main` is `None` on those paths. - #[cfg(feature = "terminal-tui")] - { - // S4-B: the legacy mirror push is deleted; the reducer is the single source through - // UserMessageEchoed. - if !synthetic_ui_command { - let _ = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::UserMessageEchoed(user_input.clone()), - "chat.user_message_echoed", - ); - } - if let Some(tx) = redraw_tx_for_main.as_ref() { - let _ = tx.try_send(()); - } - } - - // Route any user-visible slash-command output into the right sink: - // (defined before the bang handler so `!cmd` can emit its output). - // ratatui mirror on the TUI path (so it survives raw-mode `\n` - // mangling), plain stdout otherwise. Returns immediately for plain - // mode so the legacy `--plain` / piped path is unchanged. - #[cfg(feature = "terminal-tui")] - let mut emit_chat_output = |text: &str| { - // S4-B: the mirror side write is deleted; the reducer is the single source through - // SystemMessageAdded. - let _ = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::SystemMessageAdded { text: text.to_string() }, - "chat.system_message_slash", - ); - if let Some(tx) = redraw_tx_for_main.as_ref() { - let _ = tx.try_send(()); - } else { - print_fallback_chat_output(text); - } - }; - #[cfg(not(feature = "terminal-tui"))] - let emit_chat_output = |text: &str| { - print_fallback_chat_output(text); - }; - - // A one-shot message is literal model input (D4): it skips every - // quit, copy, queue, slash and bang command below. - if one_shot.is_none() { - // Handle /quit and /exit immediately - if is_chat_quit_command(user_input.as_str()) { - break 'chat; - } - - if is_copy_command(&user_input) { - match select_copy_content(&chat_session.session(), &user_input) { - Ok(selection) if plain_mode => { - println!("{}", selection.content); - let _ = std::io::stdout().flush(); - } - Ok(selection) => match terminal_proto::copy_to_clipboard(&selection.content) { - Ok(()) => emit_chat_output(©_success_message(&selection)), - Err(error) => emit_chat_output(&format!("Copy failed: {error}")), - }, - Err(message) => emit_chat_output(&message), - } - continue; - } - - if is_queue_command(&user_input) { - emit_chat_output(&format_input_backlog_report(&input_backlog, &turn_scheduler, 8)); - continue; - } - - if is_workers_command(&user_input) { - if let Some((output, signal_cancel)) = provider_workers_cancel_output_for_input( - &msg, - &user_input, - &mut turn_scheduler, - &mut provider_turn_workers, - None, - ) { - emit_chat_output(&output); - publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); - dispatch_provider_worker_cancel_signal(&chat_dispatcher, signal_cancel); - } else { - emit_chat_output(&format_provider_worker_report(&provider_worker_status( - &provider_turn_workers, - ))); - } - continue; - } - - // BUG-07: `/model ` switches the model online (same provider, different model). - // - // Intercepted before commands::dispatch, because taking effect requires (a) rewriting the main - // loop's `current_model_owned` (which affects the system prompt / event records of later - // turns), (b) writing the hot-swap slot of EffectDeps (which affects the model the dispatcher - // subtask actually requests on the next turn), and (c) dispatching ModelChanged so the reducer - // updates session.model → the status bar reflects it immediately. A bare `/model` (no - // argument) is still handed to dispatch, which shows the current model. - if user_input == "/model save-default" { - let saved = super::model_commands::save_default(&config, provider_name, ¤t_model_owned, &provider_runtime_options).await; - match saved { - Ok(()) => emit_chat_output("Saved the current model and level as the default."), - Err(error) => emit_chat_output(&format!("Cannot save model default: {}", providers::sanitize_api_error(&error.to_string()))), - } - continue; - } - let model_command = user_input.strip_prefix("/model "); - let level_command = user_input.strip_prefix("/level "); - if model_command.is_some() || level_command.is_some() { - let (new_model, candidate_options) = match super::model_commands::selection(&user_input, ¤t_model_owned, provider_name, &provider_runtime_options) { - Ok(selection) => selection, - Err(error) => { emit_chat_output(&crate::security::redaction::redact_provider_text(&format!("{error:#}"))); continue; } - }; - let new_model = new_model.as_str(); - let rebuilt = chat_model_switch(&config, provider_name, new_model).and_then(|()| { - chat_provider_chain( - &config, - provider_name, - configured_provider_name, - new_model, - &candidate_options, - ) - }); - match rebuilt { - Ok((_connection, built)) => { - let new_provider_arc: Arc = Arc::from(built); - let binding = match binding::ChatProviderBinding::capture( - &ctx.config_generation, - &new_provider_arc, - provider_name, - new_model, - ) { - Ok(binding) => binding, - Err(error) => { - emit_chat_output(&format!( - "Cannot bind model selection: {}", - providers::sanitize_api_error(&error.to_string()) - )); - continue; - } - }; - provider_runtime_options = candidate_options; - provider_binding = binding; - provider = Arc::clone(&new_provider_arc); - #[cfg(feature = "terminal-tui")] - if let Some(slot) = provider_slot.as_ref() { - slot.set(Arc::clone(&new_provider_arc)); - } - current_model_owned = new_model.to_string(); - #[cfg(feature = "terminal-tui")] - if let Some(slot) = model_slot.as_ref() { - slot.set(Arc::from(new_model)); - } - #[cfg(feature = "terminal-tui")] - { - chat_mirror.lock().model = new_model.to_string(); - } - if let Err(error) = await_metadata_change( - &chat_dispatcher, - &turn_signal, - &mut chat_session, - crate::chat::action::Action::ModelChanged { - model: new_model.to_string(), - }, - ) - .await - { - emit_chat_output(&format!("Model switch was not saved: {error}")); - continue; - } - // emit_chat_output already nudges the renderer (try_send on - // the TUI redraw channel) so the status bar repaints. - emit_chat_output(&format!( - "Switched model to {new_model} (provider {}). Applies from the next turn.", - providers::redact_endpoint_userinfo(&provider_name) - )); - } - Err(e) => { - emit_chat_output(&format!("Cannot switch to '{new_model}': {e}")); - } - } - continue; - } - - // Bug #3: `/provider [model]` — hot-switch the provider within a session. - // - // Like `/model`, it is intercepted before commands::dispatch, because taking effect requires - // the main loop to rebuild the provider instance and rewrite several pieces of runtime state: - // (a) rebuild the `Arc` from the new provider's auth/base/protocol, replacing - // the `provider` handle the legacy tool-loop path's `run_turn` call uses; - // (b) `set()` it into `provider_slot` (so the Redux driver subtask reads the new provider on - // its next turn); - // (c) rewrite `current_provider_owned` (which affects the system prompt / events / snapshot - // of later turns) and validate that the current model is valid for the new provider (if - // not, the command must carry a compatible model: `/provider `). - // Credential resolution: when switching to a provider that is not the startup primary we pass - // `api_key=None`/`api_url=None` and let the provider resolve its own credentials from the auth - // profile / environment (reusing the startup `config.api_key` only makes sense for the - // original primary); when switching back to the original primary we reuse - // `config.api_key`/`config.api_url`. - if let Some(raw) = user_input.strip_prefix("/provider ") { - let mut parts = raw.split_whitespace(); - // Own the parsed tokens up front so we can freely reassign the runtime - // provider/model state below without lingering borrows. - let new_provider = parts.next().unwrap_or_default().to_string(); - let requested_model = parts.next().map(str::to_string); - if new_provider.is_empty() { - emit_chat_output("Usage: /provider [model]"); - continue; - } - // Decide the model effective after the switch: prefer the one given explicitly on the - // command, otherwise keep the current model (if compatible). - let candidate_model = requested_model.unwrap_or_else(|| current_model_owned.clone()); - if let Err(e) = chat_model_switch(&config, &new_provider, &candidate_model) { - let shown = providers::redact_endpoint_userinfo(&new_provider); - emit_chat_output(&format!( - "Cannot switch to provider '{shown}': model '{candidate_model}' is incompatible ({}). \ -Retry with a compatible model: /provider {shown} ", - providers::redact_endpoint_userinfo(&e.to_string()) - )); - continue; - } - // When switching to a provider other than the configured primary, do not carry over the - // primary's explicit credentials/URL; let the new provider resolve its own (so provider - // A's key is never fed to provider B). - match chat_provider_chain( - &config, - &new_provider, - configured_provider_name, - &candidate_model, - &provider_runtime_options, - ) { - Ok((_switch_connection, built)) => { - let new_provider_arc: Arc = Arc::from(built); - let next_binding = match binding::ChatProviderBinding::capture( - &ctx.config_generation, &new_provider_arc, &new_provider, &candidate_model, - ) { - Ok(binding) => binding, - Err(error) => { - emit_chat_output(&format!("Cannot bind provider selection: {}", providers::sanitize_api_error(&error.to_string()))); - continue; - } - }; - provider_binding = next_binding; - // (a) the legacy path handle - provider = Arc::clone(&new_provider_arc); - // (b) Redux driver slot - #[cfg(feature = "terminal-tui")] - if let Some(slot) = provider_slot.as_ref() { - slot.set(Arc::clone(&new_provider_arc)); - } - // (c) the runtime provider / model names - let model_changed = candidate_model != current_model_owned; - if model_changed { - current_model_owned = candidate_model.clone(); - #[cfg(feature = "terminal-tui")] - if let Some(slot) = model_slot.as_ref() { - slot.set(Arc::from(candidate_model.as_str())); - } - } - current_provider_owned = new_provider.clone(); - #[cfg(feature = "terminal-tui")] - { - let mut mirror = chat_mirror.lock(); - mirror.provider = new_provider.clone(); - if model_changed { - mirror.model = candidate_model.clone(); - } - } - // (d) the session ledger: dispatch ProviderChanged so the reducer updates - // session.provider (and session.model when needed), making the status bar / UI - // snapshot reflect the new provider immediately. All three places (the legacy - // provider handle, the Redux provider_slot and the session ledger) stay - // consistent this way. When switching providers also changes the model, both go - // into the same action (no separate ModelChanged needed). - if let Err(error) = await_metadata_change( - &chat_dispatcher, - &turn_signal, - &mut chat_session, - crate::chat::action::Action::ProviderChanged { - provider: new_provider.clone(), - model: model_changed.then(|| candidate_model.clone()), - }, - ) - .await - { - emit_chat_output(&format!("Provider switch was not saved: {error}")); - continue; - } - let model_note = if model_changed { - format!(" (model set to {candidate_model})") - } else { - String::new() - }; - emit_chat_output(&format!( - "Switched provider to {}{model_note}. Applies from the next turn.", - providers::redact_endpoint_userinfo(&new_provider) - )); - } - Err(e) => { - emit_chat_output(&format!( - "Cannot switch to provider '{}': {}", - providers::redact_endpoint_userinfo(&new_provider), - providers::redact_endpoint_userinfo(&e.to_string()) - )); - } - } - continue; - } - - // BUG-07: the model name effective for this iteration (borrowed from the mutable owned - // value). The `/model` interception above already handled its case and called `continue`, so - // the shadowed `model_name` here is always the newest value and covers every later use of - // `model_name` (system prompt / fabric / snapshot). - let model_name: &str = current_model_owned.as_str(); - // BUG-04: `!cmd` bang mode — run the rest of the line directly as a - // shell command (matching the footer hint "! for bash") instead of - // sending it to the LLM. Output is shown inline; the LLM is not - // involved. A bare `!` is ignored. The shell tool already applies the - // direct host execution + workspace cwd, so bang commands share the same host FS view - // as file_write (see BUG-02). - if let Some(bang_cmd) = user_input.strip_prefix('!') { - let bang_cmd = bang_cmd.trim(); - if bang_cmd.is_empty() { - emit_chat_output("Usage: ! (runs directly in the workspace)"); - continue; - } - let shell_tool = tools_registry.iter().find(|t| t.supports_name("shell")); - match shell_tool { - Some(tool) => { - let args = serde_json::json!({ "command": bang_cmd }); - match tool.execute_named("shell", args).await { - Ok(result) => { - let mut out = String::new(); - if !result.output.is_empty() { - out.push_str(&result.output); - } - if let Some(err) = result.error.as_ref().filter(|e| !e.is_empty()) { - if !out.is_empty() { - out.push('\n'); - } - out.push_str(err); - } - if out.is_empty() { - out = if result.success { - "(no output)".to_string() - } else { - "(command failed with no output)".to_string() - }; - } - emit_chat_output(&out); - } - Err(e) => emit_chat_output(&format!("Shell error: {e}")), - } - } - None => emit_chat_output("Shell tool is not available in this session."), - } - continue; - } + include!("run/commands.rs"); - // Both reset commands save the current state and switch every - // session-scoped UI/model ledger to a fresh identity. Stored memories - // remain intact, including those owned by other sessions or channels. - if matches!(user_input.as_str(), "/new" | "/clear") { - match start_new_chat_session( - ChatSwitchCtx { - chat_session: &mut chat_session, - commits: &turn_signal, - chat_session_key: &mut chat_session_key, - fabric_turn_seq: &mut fabric_turn_seq, - history: &mut history, - approval_router: approval_router.as_ref(), - pending_chat_rewind: &mut pending_chat_rewind, - pending_diff_apply: &mut pending_diff_apply, - chat_sessions: &mut chat_sessions, - ignored_session_events: &mut ignored_session_events, - session_rings: &mut session_rings, - reported_sessions: &mut reported_sessions, - announced_started_sessions: &mut announced_started_sessions, - last_sessions_summary: &mut last_sessions_summary, - last_sessions_entries: &mut last_sessions_entries, - attached_follow: &mut attached_follow, - attached_follow_seq: &mut attached_follow_seq, - chat_dispatcher: &chat_dispatcher, - redraw_handle: sessions_redraw_handle.as_ref(), - config: &config, - provider_name, - model_name, - skills: &skills, - native_tools, - #[cfg(feature = "terminal-tui")] - chat_mirror: &chat_mirror, - }, - ) - .await - { - Ok(message) => emit_chat_output(&message), - Err(e) => emit_chat_output(&e.to_string()), + include!("run/provider_turn.rs"); } - continue; - } - - // `/compact` is an explicit request: it compacts whatever lies beyond - // the kept window, through the same budget the preflight uses. - if matches!(user_input.as_str(), "/compact") { - let compact_context = provider_binding - .as_ref() - .ok_or_else(|| anyhow::anyhow!("chat provider binding is missing"))? - .effective_compaction(); - let compact_config = tool_surface_reserve.reserved_config(&compact_context.config); - let compact_envelope = - super::chat_runtime_envelope(&config.workspace_dir.to_string_lossy(), &chat_session_key); - let (compact_turns_before, compact_tokens_before) = - super::compaction::chat_history_turns_and_tokens(&history); - let compact_outcome = super::compaction::run_manual_compact( - super::compaction::ManualCompact { - history: &mut history, - chat_session: &chat_session.session(), - provider: provider.as_ref(), - model: model_name, - config: &compact_config, - memory: Arc::clone(&mem), - envelope: &compact_envelope, - chat_dispatcher: &chat_dispatcher, - commits: &turn_signal, - }, - &mut |text: &str| emit_chat_output(text), - ) - .await; - emit_chat_output(&compact_outcome.feedback(compact_turns_before, compact_tokens_before, &compact_config)); - #[cfg(feature = "terminal-tui")] - refresh_context_budget_for_tui( - &history, - &compact_context.config, - &tool_surface_reserve, - redraw_tx_for_main.is_some(), - &chat_mirror, - &chat_dispatcher, - ); - continue; - } - - // Dispatch other slash commands - { - let cmd_ctx = commands::CommandContext { - model_name, - provider_name, - chat_session: &chat_session.session(), - tools_registry: &tools_registry, - mem: mem.as_ref(), - }; - match commands::dispatch(&user_input, &cmd_ctx).await { - commands::CommandResult::Handled => continue, - commands::CommandResult::HandledWithOutput(text) => { - emit_chat_output(&text); - continue; - } - commands::CommandResult::Quit => break 'chat, - commands::CommandResult::SetMode(mode) => { - // The reducer saves a changed mode; success is reported - // only after its acknowledgement. - if let Err(error) = await_metadata_change( - &chat_dispatcher, - &turn_signal, - &mut chat_session, - crate::chat::action::Action::ModeChanged(mode), - ) - .await - { - emit_chat_output(&format!("Mode unchanged: {error}")); - continue; - } - #[cfg(feature = "terminal-tui")] - { - chat_mirror.lock().chat_mode = mode; - } - let msg = match mode { - commands::ChatMode::Plan => { - "Switched to plan mode (read-only tools only — write/shell/git_commit will be simulated)" - } - commands::ChatMode::Edit => "Switched to edit mode (default — write tools enabled)", - commands::ChatMode::Auto => "Switched to auto mode (does not override [autonomy])", - }; - emit_chat_output(msg); - continue; - } - commands::CommandResult::ResumeAction(action) => { - match action { - commands::ResumeCommand::List => match saved_chat_sessions(mem.as_ref()).await { - Ok(sessions) => { - #[cfg(feature = "terminal-tui")] - if sessions_redraw_handle.is_some() { - let entries = sessions - .iter() - .map(|session| { - crate::chat::session::SavedSessionPickerEntry::from_session( - session, - &chat_session.session().id, - ) - }) - .collect::>(); - { - let mut mirror = chat_mirror.lock(); - mirror.saved_sessions_cache = entries.clone(); - mirror.saved_session_picker = - Some(crate::chat::session::SavedSessionPickerState::new(entries.clone())); - } - let _ = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::SavedSessionPickerOpened { entries }, - "chat.saved_session_picker_opened_resume", - ); - let sources = { - let mirror = chat_mirror.lock(); - crate::chat::action::Action::SlashMenuSourcesUpdated { - saved_sessions: mirror.saved_sessions_cache.clone(), - provider_model_catalog: mirror.provider_model_catalog.clone(), - } - }; - let _ = chat_dispatcher.dispatch_or_log(sources, "chat.slash_menu_sources_resume"); - if let Some(tx) = sessions_redraw_handle.as_ref() { - let _ = tx.try_send(()); - } - } else { - emit_chat_output(&format_saved_chat_sessions(&sessions)); - } - #[cfg(not(feature = "terminal-tui"))] - emit_chat_output(&format_saved_chat_sessions(&sessions)); - } - Err(e) => emit_chat_output(&format!("Failed to list saved chat sessions: {e}")), - }, - commands::ResumeCommand::Id(id) => { - match resume_saved_session_by_id( - mem.as_ref(), - &id, - ChatSwitchCtx { - chat_session: &mut chat_session, - commits: &turn_signal, - chat_session_key: &mut chat_session_key, - fabric_turn_seq: &mut fabric_turn_seq, - history: &mut history, - approval_router: approval_router.as_ref(), - pending_chat_rewind: &mut pending_chat_rewind, - pending_diff_apply: &mut pending_diff_apply, - chat_sessions: &mut chat_sessions, - ignored_session_events: &mut ignored_session_events, - session_rings: &mut session_rings, - reported_sessions: &mut reported_sessions, - announced_started_sessions: &mut announced_started_sessions, - last_sessions_summary: &mut last_sessions_summary, - last_sessions_entries: &mut last_sessions_entries, - attached_follow: &mut attached_follow, - attached_follow_seq: &mut attached_follow_seq, - chat_dispatcher: &chat_dispatcher, - redraw_handle: sessions_redraw_handle.as_ref(), - config: &config, - provider_name, - model_name, - skills: &skills, - native_tools, - #[cfg(feature = "terminal-tui")] - chat_mirror: &chat_mirror, - }, - ) - .await - { - Ok(message) => emit_chat_output(&message), - Err(e) => emit_chat_output(&e.to_string()), - } - } - commands::ResumeCommand::Last => { - if let Err(e) = - record_child_summaries_awaited(&mut chat_sessions, &chat_dispatcher, &turn_signal).await - { - emit_chat_output(&format!( - "Resume aborted: failed to save current session before switching: {e}" - )); - continue; - } - - let loaded = match load_latest_session_with_message_events( - mem.as_ref(), - memory_fabric.workspace_id(), - &config.cost, - ) - .await - { - Ok(Some(session)) => Some(session), - Ok(None) => { - emit_chat_output("No saved chat sessions to resume."); - None - } - Err(e) => { - emit_chat_output(&format!( - "Resume aborted: failed to load saved chat session: {e}" - )); - None - } - }; - let Some(loaded_session) = loaded else { - continue; - }; - if let Err(e) = apply_chat_session_switch( - ChatSwitchCtx { - chat_session: &mut chat_session, - commits: &turn_signal, - chat_session_key: &mut chat_session_key, - fabric_turn_seq: &mut fabric_turn_seq, - history: &mut history, - approval_router: approval_router.as_ref(), - pending_chat_rewind: &mut pending_chat_rewind, - pending_diff_apply: &mut pending_diff_apply, - chat_sessions: &mut chat_sessions, - ignored_session_events: &mut ignored_session_events, - session_rings: &mut session_rings, - reported_sessions: &mut reported_sessions, - announced_started_sessions: &mut announced_started_sessions, - last_sessions_summary: &mut last_sessions_summary, - last_sessions_entries: &mut last_sessions_entries, - attached_follow: &mut attached_follow, - attached_follow_seq: &mut attached_follow_seq, - chat_dispatcher: &chat_dispatcher, - redraw_handle: sessions_redraw_handle.as_ref(), - config: &config, - provider_name, - model_name, - skills: &skills, - native_tools, - #[cfg(feature = "terminal-tui")] - chat_mirror: &chat_mirror, - }, - loaded_session, - false, - ) - .await - { - emit_chat_output(&format!("Resume aborted: {e}")); - continue; - } - - let resumed = chat_session.session(); - let title = if resumed.title.is_empty() { - "(untitled)" - } else { - resumed.title.as_str() - }; - emit_chat_output(&format!( - "Resumed saved chat session {} ({title}, {} turns).", - resumed.id, - resumed.turn_count() - )); - } - } - continue; - } - commands::CommandResult::HistoryAction(action) => { - match action { - commands::HistoryCommand::BranchList => { - emit_chat_output(&format_turn_boundaries(&chat_session.session())); - } - commands::HistoryCommand::Branch(raw) => { - let keep_turns = match parse_turn_boundary(&raw, chat_session.session().turn_count(), "branch") { - Ok(value) => value, - Err(msg) => { - emit_chat_output(&msg); - continue; - } - }; - if let Err(e) = - record_child_summaries_awaited(&mut chat_sessions, &chat_dispatcher, &turn_signal).await - { - emit_chat_output(&format!( - "Branch aborted: failed to save current session before forking: {e}" - )); - continue; - } - // The branch boundary reads the acknowledged state. - let current = chat_session.session(); - let mut branch = branched_chat_session_from(¤t, keep_turns, provider_name, model_name); - let branch_id = branch.id.clone(); - let branch_turns = branch.turn_count(); - // The branch's own transcript rows (handoff chain and - // retained turns) commit in one transaction before the - // branch session exists; any failure aborts the branch. - if let Err(e) = super::branch_copy::copy_branch_transcript( - mem.as_ref(), - memory_fabric.workspace_id(), - ¤t.id, - &mut branch, - ) - .await - { - emit_chat_output(&format!("Branch aborted: failed to copy the transcript: {e}")); - continue; - } - if let Err(e) = save_session(mem.as_ref(), &branch).await { - emit_chat_output(&format!("Branch aborted: failed to save new branch session: {e}")); - continue; - } - if let Err(e) = apply_chat_session_switch( - ChatSwitchCtx { - chat_session: &mut chat_session, - commits: &turn_signal, - chat_session_key: &mut chat_session_key, - fabric_turn_seq: &mut fabric_turn_seq, - history: &mut history, - approval_router: approval_router.as_ref(), - pending_chat_rewind: &mut pending_chat_rewind, - pending_diff_apply: &mut pending_diff_apply, - chat_sessions: &mut chat_sessions, - ignored_session_events: &mut ignored_session_events, - session_rings: &mut session_rings, - reported_sessions: &mut reported_sessions, - announced_started_sessions: &mut announced_started_sessions, - last_sessions_summary: &mut last_sessions_summary, - last_sessions_entries: &mut last_sessions_entries, - attached_follow: &mut attached_follow, - attached_follow_seq: &mut attached_follow_seq, - chat_dispatcher: &chat_dispatcher, - redraw_handle: sessions_redraw_handle.as_ref(), - config: &config, - provider_name, - model_name, - skills: &skills, - native_tools, - #[cfg(feature = "terminal-tui")] - chat_mirror: &chat_mirror, - }, - branch, - true, - ) - .await - { - emit_chat_output(&format!("Branch aborted: {e}")); - continue; - } - emit_chat_output(&format!( - "Created branch {branch_id} from the first {branch_turns} turns and switched to it." - )); - } - commands::HistoryCommand::Rewind(raw) => { - let keep_turns = match parse_turn_boundary(&raw, chat_session.session().turn_count(), "rewind") { - Ok(value) => value, - Err(msg) => { - emit_chat_output(&msg); - continue; - } - }; - if keep_turns == chat_session.session().turn_count() { - emit_chat_output(&format!( - "Rewind skipped: session already has exactly {keep_turns} turns." - )); - continue; - } - if approval_in_progress(approval_router.as_ref(), &pending_chat_rewind, &pending_diff_apply) - { - emit_chat_output(approval_already_pending_message()); - continue; - } - if sessions_redraw_handle.is_none() { - emit_chat_output( - "Rewind requires interactive confirmation; unavailable in this mode. Current session unchanged.", - ); - continue; - } - #[cfg(not(feature = "terminal-tui"))] - { - emit_chat_output( - "Rewind requires interactive confirmation; unavailable in this mode. Current session unchanged.", - ); - continue; - } - #[cfg(feature = "terminal-tui")] - { - let Some(router) = approval_router.as_ref() else { - emit_chat_output( - "Rewind requires interactive confirmation; approval router unavailable. Current session unchanged.", - ); - continue; - }; - let target_session = rewound_chat_session_from(&chat_session.session(), keep_turns); - let (approval_tx, approval_rx) = tokio::sync::oneshot::channel::(); - let tool_id = format!("chat_rewind:{}", uuid::Uuid::new_v4()); - if !router.register(tool_id.clone(), approval_tx) { - emit_chat_output(approval_already_pending_message()); - continue; - } - let args = serde_json::json!({ - "session_id": chat_session.session().id, - "from_turns": chat_session.session().turn_count(), - "to_turns": keep_turns, - "drops_child_summaries": keep_turns < chat_session.session().turn_count(), - }) - .to_string(); - let dispatch_result = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::ToolApprovalRequested { - task_id: None, - tool_id: tool_id.clone(), - name: "rewind_chat_session".to_string(), - args, - }, - "chat.rewind_approval_requested", - ); - if dispatch_result != crate::chat::dispatcher::DispatchResult::Sent { - let _ = router.resolve(&tool_id, false); - emit_chat_output("Rewind approval could not be shown; current session unchanged."); - continue; - } - pending_chat_rewind = Some(PendingChatRewind { - tool_id, - target_session, - approval_rx, - }); - emit_chat_output(&format!( - "Confirm rewind to {keep_turns} turns in the approval prompt." - )); - } - } - } - continue; - } - commands::CommandResult::ApplyAction(action) => { - let latest_index = match action { - commands::ApplyCommand::Latest => 1, - commands::ApplyCommand::Index(index) => index, - }; - if approval_in_progress(approval_router.as_ref(), &pending_chat_rewind, &pending_diff_apply) { - emit_chat_output(approval_already_pending_message()); - continue; - } - let Some(diff) = diff_apply::latest_fenced_diff(&chat_session.session().turns, latest_index) else { - emit_chat_output("No applicable fenced diff block found in this conversation."); - continue; - }; - let plan = match diff_apply::parse_unified_diff(&diff, config.autonomy.level) { - Ok(plan) => plan, - Err(error) => { - emit_chat_output(&format!("Diff apply rejected: {error}. Workspace unchanged.")); - continue; - } - }; - #[cfg(not(feature = "terminal-tui"))] - let _ = &plan; - if sessions_redraw_handle.is_none() { - emit_chat_output( - "Diff apply requires interactive TUI approval; unavailable in this mode. Workspace unchanged.", - ); - continue; - } - #[cfg(not(feature = "terminal-tui"))] - { - emit_chat_output( - "Diff apply requires interactive TUI approval; unavailable in this build. Workspace unchanged.", - ); - continue; - } - #[cfg(feature = "terminal-tui")] - { - match request_diff_apply_approval(plan, true, approval_router.as_ref(), &chat_dispatcher) { - Ok(pending) => { - let summary = pending.plan.summary(); - pending_diff_apply = Some(pending); - emit_chat_output(&format!("Confirm diff apply in the approval prompt.\n{summary}")); - } - Err(message) => emit_chat_output(&message), - } - } - #[cfg(feature = "terminal-tui")] - continue; - } - commands::CommandResult::SessionAction(action) => { - use crate::chat::sessions::SessionCommand; - // Shared parsing must not turn mailbox/model input into - // local operator authority for a child or approval action. - if action.requires_local_operator() && !is_local_operator_input(&msg) { - emit_chat_output("This session command requires local terminal operator input."); - if let Some(guard) = assignment_guard.as_mut() { - guard.failed("Assigned task cannot issue local operator session commands."); - } - continue; - } - match action { - SessionCommand::Bg { task } => { - // Spawn a background agent via sessions_spawn, passing - // the *current* provider/model (read from the main-loop - // strings, which `/provider` and `/model` keep in sync) - // so a hot switch is honoured (plan §C.0 blocker 3). - match tools_registry.iter().find(|t| t.supports_name("sessions_spawn")) { - Some(tool) => { - let command = provider_binding.as_ref() - .ok_or_else(|| anyhow::anyhow!("chat provider binding is missing")) - .and_then(|binding| binding::ChatOperatorSpawn::capture( - &msg, &task, binding, &ctx.config_generation, &provider, - ¤t_provider_owned, ¤t_model_owned, - )); - let command = match command { - Ok(command) => command, - Err(error) => { - emit_chat_output(&format!("Cannot admit background command: {error}")); - continue; - } - }; - let (mut args, operator_source) = match command.admit(Arc::clone(&mem), &chat_session_key, Arc::clone(&ctx.security), Arc::clone(&turn_service)).await { - Ok(admitted) => admitted, - Err(error) => { emit_chat_output(&format!("Cannot record background command source: {error}")); continue; } - }; - // Spawning is a Medium-risk side effect; under - // supervised autonomy the gate requires a grant - // bound to `sessions_spawn:spawn`. The operator - // typed `/bg`, so issue the matching grant here - // (same op name the gate authorizes), mirroring - // `/kill` and `/steer` and how the agent loop - // grants after operator approval. - let grant = crate::security::policy::ApprovalGrant::for_resource_operation( - "sessions_spawn", - "sessions_spawn:spawn", - "chat-operator", - None, - ); - match serde_json::to_value(&grant) { - Ok(grant_value) => { - if let Some(obj) = args.as_object_mut() { - obj.insert( - crate::security::policy::RUNTIME_APPROVAL_GRANT_ARG.to_string(), - grant_value, - ); - } - } - Err(e) => { - tracing::warn!( - error = %crate::agent::diagnostics::error_class(&e), - "Failed to serialize spawn approval grant; proceeding without it" - ); - } - } - match operator_source.scope(tool.execute_named("sessions_spawn", args)).await { - Ok(result) => { - let out = if result.output.is_empty() { - result - .error - .filter(|e| !e.is_empty()) - .unwrap_or_else(|| "(no output)".to_string()) - } else { - result.output - }; - emit_chat_output(&out); - } - Err(e) => emit_chat_output(&format!("Failed to start background agent: {e}")), - } - } - None => emit_chat_output("Background sessions are not available in this session."), - } - continue; - } - SessionCommand::Sessions => { - if let Some(output) = handle_local_session_command( - &action, - &mut chat_sessions, - &session_rings, - &mut reaped_log_archive, - &reap_policy, - &tools_registry, - ) - .await - { - emit_chat_output(&super::session_glue::sessions_listing_with_current( - &chat_session.session().id, - &output, - )); - } - continue; - } - SessionCommand::Transcript => { - attached_follow = None; - attached_follow_seq = None; - #[cfg(feature = "terminal-tui")] - { - open_transcript_view( - &chat_mirror, - &chat_dispatcher, - sessions_redraw_handle.as_ref(), - snapshot_rx_for_tui.as_ref(), - ); - } - #[cfg(not(feature = "terminal-tui"))] - emit_chat_output("Transcript viewer is only available in the terminal TUI."); - continue; - } - SessionCommand::Diff { cached } => { - attached_follow = None; - attached_follow_seq = None; - let source = collect_workspace_diff(&config.workspace_dir, cached).await; - #[cfg(feature = "terminal-tui")] - { - if sessions_redraw_handle.is_some() { - open_diff_view( - &chat_mirror, - &chat_dispatcher, - sessions_redraw_handle.as_ref(), - source, - ); - } else { - emit_chat_output(&source.to_plain_text()); - } - } - #[cfg(not(feature = "terminal-tui"))] - emit_chat_output(&source.to_plain_text()); - continue; - } - SessionCommand::Kill { seq: _ } => { - if let Some(output) = handle_local_session_command( - &action, - &mut chat_sessions, - &session_rings, - &mut reaped_log_archive, - &reap_policy, - &tools_registry, - ) - .await - { - emit_chat_output(&output); - } - continue; - } - SessionCommand::Steer { seq, message } => { - // v5: steer only applies to agent sessions (it appends - // an instruction to a running sub-agent's steer - // channel). Shells and PTYs have no steer channel — - // resolving their seq would yield a non-agent id that - // the sessions_spawn tool can't address, producing a - // cryptic "run not found". Guard with a clear message - // up front, mirroring `/kill`'s kind dispatch. - match chat_sessions.kind_for_seq(seq).await { - Ok(kind) => { - if let Some(msg) = - crate::chat::sessions::command::steer_unsupported_message(kind, seq) - { - emit_chat_output(&msg); - continue; - } - // Agent: fall through to the steer delegation. - } - Err(e) => { - emit_chat_output(&format!("Steer failed: {e}")); - continue; - } - } - // Resolve `#N` -> run UUID, then delegate to the - // sessions_spawn tool's `steer` action so the shared - // semantics apply uniformly (Low-risk side-effect gate - // op `sessions_spawn:steer:`, running-status - // check, steer_tx delivery). Mirrors `/kill`. - let run_id = match chat_sessions.resolve_run_id(seq).await { - Ok(id) => id, - Err(e) => { - emit_chat_output(&format!("Steer failed: {e}")); - continue; - } - }; - match tools_registry.iter().find(|t| t.supports_name("sessions_spawn")) { - Some(tool) => { - let operation_name = format!("sessions_spawn:steer:{run_id}"); - let grant = crate::security::policy::ApprovalGrant::for_resource_operation( - "sessions_spawn", - &operation_name, - "chat-operator", - None, - ); - let mut args = serde_json::json!({ - "action": "steer", - "run_id": run_id, - "message": message, - }); - match serde_json::to_value(&grant) { - Ok(grant_value) => { - if let Some(obj) = args.as_object_mut() { - obj.insert( - crate::security::policy::RUNTIME_APPROVAL_GRANT_ARG.to_string(), - grant_value, - ); - } - } - Err(e) => { - tracing::warn!( - error = %crate::agent::diagnostics::error_class(&e), - "Failed to serialize steer approval grant; proceeding without it" - ); - } - } - match tool.execute_named("sessions_spawn", args).await { - Ok(result) => { - let out = if result.output.is_empty() { - result - .error - .filter(|e| !e.is_empty()) - .unwrap_or_else(|| "(no output)".to_string()) - } else { - result.output - }; - emit_chat_output(&out); - } - Err(e) => emit_chat_output(&format!("Steer failed: {e}")), - } - } - None => emit_chat_output("Background sessions are not available in this session."), - } - continue; - } - SessionCommand::Attach { seq } => { - // P2 `/attach` focuses the child session viewport. - // Main history receives only a breadcrumb; retained - // and live child output render inside ActiveSessionView. - // - // v5: PTY sessions are interactive terminal handoffs, - // not line-streamed output, so a read-only follow makes - // no sense for them. The Ctrl+G switcher routes Enter - // through this same `/attach ` path for every kind, - // so guard PTYs here with a clear redirect rather than - // silently starting an empty follow. (A live PTY can be - // re-entered with `/pty`; an exited one is terminal.) - #[cfg(feature = "terminal-tui")] - if matches!( - chat_sessions.kind_for_seq(seq).await, - Ok(crate::chat::sessions::model::ManagedKind::Pty) - ) { - // v3b: a live PTY can be RE-ATTACHED — the detach - // path keeps the child running, so `/attach #N` - // (and the Ctrl+G switcher's synthetic /attach) - // hands the terminal back to it. An exited PTY is - // terminal and cannot be attached. - let pty = chat_sessions.pty_for_seq_public(seq); - match pty { - Some(session) if session.is_attachable() => { - reattach_pty( - &session, - seq, - &pty_handoff, - sessions_redraw_handle.as_ref(), - &emit_chat_output, - ) - .await; - } - _ => { - emit_chat_output(&format!( - "Interactive PTY session #{seq} has exited — nothing to attach to. \ - Start a new one with /pty ." - )); - } - } - // Restore the prompt/focus the switcher may have set - // optimistically (it pointed at this seq before the - // handoff), so the chat prompt is not left targeting - // the detached PTY for steering. - let prev_focus = crate::chat::sessions::focus::rollback_focus(attached_follow_seq); - let _ = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::SessionFocusChanged { focus: prev_focus }, - "chat.session_focus_attach_pty_done", - ); - { - let mut mirror = chat_mirror.lock(); - mirror.focus = prev_focus; - mirror.active_session_view = None; - } - let _ = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::ActiveSessionViewUpdated { view: None }, - "chat.active_session_view_attach_pty_done", - ); - if let Some(tx) = sessions_redraw_handle.as_ref() { - let _ = tx.try_send(()); - } - continue; - } - const ATTACH_TAIL_LINES: usize = 20; - match chat_sessions.resolve_run_id(seq).await { - Ok(run_id) => { - let sid = crate::chat::sessions::id::SessionId::from_run_id(&run_id); - let was_following_before_attach = attached_follow.is_some(); - let is_terminal = chat_sessions.is_terminal_for_seq(seq).await.unwrap_or(false); - let views = chat_sessions.snapshot().await; - let view_meta = views.iter().find(|view| view.seq == seq); - let tail_lines = match chat_sessions.tail(seq, ATTACH_TAIL_LINES).await { - Ok(lines) => lines - .into_iter() - .map(|line| format!("[{}] {}", line.role, line.content)) - .collect::>(), - Err(e) => { - emit_chat_output(&format!("Attach tail failed: {e}")); - Vec::new() - } - }; - let (ring_lines, truncated) = session_rings.get(&sid).map_or_else( - || (Vec::new(), false), - |ring| { - let lines = if is_terminal { - Vec::new() - } else { - ring.recent_lines(crate::chat::sessions::event::DEFAULT_RING_CAPACITY) - }; - (lines, ring.is_truncated()) - }, - ); - #[cfg(not(feature = "terminal-tui"))] - let _ = ( - &was_following_before_attach, - &view_meta, - &tail_lines, - &ring_lines, - truncated, - ); - #[cfg(feature = "terminal-tui")] - let active_projection = build_active_session_attach_projection( - seq, view_meta, tail_lines, ring_lines, truncated, - ); - attached_follow = Some(sid); - attached_follow_seq = Some(seq); - // v1.1b: route plain input to this session as - // a steer and reflect the target in the prompt - // (colour+glyph). Update both the render - // snapshot (Action) and the key thread's - // mirror (read by `resolve_esc`). When the - // attach was triggered from the switcher the - // key thread already set this optimistically; - // re-affirming it here is idempotent and also - // covers the typed `/attach N` path. - let focus = crate::chat::sessions::FocusTarget::Session { seq }; - let _ = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::SessionFocusChanged { focus }, - "chat.session_focus_attach", - ); - #[cfg(feature = "terminal-tui")] - { - { - let mut mirror = chat_mirror.lock(); - mirror.focus = focus; - mirror.active_session_view = Some(active_projection.view.clone()); - } - let _ = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::ActiveSessionViewUpdated { - view: Some(active_projection.view.clone()), - }, - "chat.active_session_view_attach", - ); - if let Some(tx) = sessions_redraw_handle.as_ref() { - let _ = tx.try_send(()); - } - } - #[cfg(feature = "terminal-tui")] - if let Some(breadcrumb) = attach_breadcrumb_for_transition( - was_following_before_attach, - &active_projection, - ) { - emit_chat_output(breadcrumb); - } - #[cfg(not(feature = "terminal-tui"))] - emit_chat_output(&format!( - "Attached session #{seq} (input routes as steer). Type /detach to stop." - )); - } - Err(e) => { - // P0 race fix: the switcher key thread may have - // optimistically pointed the prompt + Esc - // judgment at `seq` before this attach ran. The - // attach failed (seq no longer resolves / the - // session is gone), so `attached_follow` is - // unchanged — restore the prompt to the *actual* - // current target so perception cannot diverge - // from routing. (A typed `/attach N` that fails - // has no optimistic set, but restoring the same - // unchanged focus is an idempotent no-op there.) - let prev_focus = crate::chat::sessions::focus::rollback_focus(attached_follow_seq); - let _ = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::SessionFocusChanged { focus: prev_focus }, - "chat.session_focus_attach_rollback", - ); - #[cfg(feature = "terminal-tui")] - { - { - let mut mirror = chat_mirror.lock(); - mirror.focus = prev_focus; - mirror.active_session_view = None; - } - let _ = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::ActiveSessionViewUpdated { view: None }, - "chat.active_session_view_attach_rollback", - ); - if let Some(tx) = sessions_redraw_handle.as_ref() { - let _ = tx.try_send(()); - } - } - emit_chat_output(&format!("Attach failed: {e}")); - } - } - continue; - } - SessionCommand::Detach => { - let was_following = attached_follow.take().is_some(); - attached_follow_seq = None; - if was_following { - // v1.1b: reset input routing back to main and clear - // the prompt target indicator (snapshot + mirror). - let focus = crate::chat::sessions::FocusTarget::Main; - let _ = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::SessionFocusChanged { focus }, - "chat.session_focus_detach", - ); - #[cfg(feature = "terminal-tui")] - { - { - let mut mirror = chat_mirror.lock(); - mirror.focus = focus; - mirror.active_session_view = None; - } - let _ = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::ActiveSessionViewUpdated { view: None }, - "chat.active_session_view_detach", - ); - if let Some(tx) = sessions_redraw_handle.as_ref() { - let _ = tx.try_send(()); - } - } - emit_chat_output("Detached. Input routes to main chat again."); - } else { - emit_chat_output("Not currently following any session."); - } - continue; - } - SessionCommand::Shell { command } => { - // v2: run a non-interactive command in the background. - // Runs directly in the configured workspace with the - // inherited host environment and the v1.1 event bridge. - match crate::chat::sessions::shell::spawn_shell( - &command, - &config.workspace_dir, - &shell_event_sink, - ) { - Ok(session) => { - let seq = chat_sessions.add_shell(session); - emit_chat_output(&format!("Started background shell #{seq}: {command}")); - } - Err(e) => { - emit_chat_output(&format!("Failed to start background shell: {e}")); - } - } - continue; - } - SessionCommand::Logs { seq: _ } => { - if let Some(output) = handle_local_session_command( - &action, - &mut chat_sessions, - &session_rings, - &mut reaped_log_archive, - &reap_policy, - &tools_registry, - ) - .await - { - emit_chat_output(&output); - } - continue; - } - SessionCommand::Pty { command } => { - // v3a: interactive PTY shell with a full terminal - // handoff. The chat ratatui render loop is suspended - // and the real terminal is wired straight to the PTY - // for the duration; Ctrl-] detaches, Ctrl-C/Ctrl-D - // pass through. Restoration is guaranteed by the RAII - // `PtyHandoffGuard` regardless of how the passthrough - // ends (detach, child exit, error, or panic). - #[cfg(feature = "terminal-tui")] - { - handle_pty_command( - &command, - &config.workspace_dir, - &mut chat_sessions, - &pty_handoff, - sessions_redraw_handle.as_ref(), - &emit_chat_output, - ) - .await; - } - #[cfg(not(feature = "terminal-tui"))] - { - let _ = &command; - emit_chat_output("Interactive PTY sessions require the terminal UI."); - } - continue; - } - SessionCommand::Approve { seq } | SessionCommand::Deny { seq } => { - // NeedsInput: deliver an approval decision to a - // background sub-agent suspended on the supervised - // approval gate. `/approve` injects a runtime grant - // (Grant) so the gated tool can pass the gate; `/deny` - // reports the tool as denied to the sub-agent. - let approve = matches!(action, SessionCommand::Approve { .. }); - let run_id = match chat_sessions.resolve_run_id(seq).await { - Ok(id) => id, - Err(e) => { - emit_chat_output(&format!( - "{} failed: {e}", - if approve { "Approve" } else { "Deny" } - )); - continue; - } - }; - let decision = if approve { - crate::agent::turn_contracts::ApprovalDecision::Grant - } else { - crate::agent::turn_contracts::ApprovalDecision::Deny - }; - if pending_approvals.resolve(&run_id, decision) { - emit_chat_output(&format!( - "{} session #{seq}.", - if approve { "Approved" } else { "Denied" } - )); - } else { - emit_chat_output(&format!( - "Session #{seq} is not awaiting approval (it may have resumed, \ - timed out, completed, or was killed)." - )); - } - continue; - } - SessionCommand::DaemonSessions - | SessionCommand::DaemonKill { .. } - | SessionCommand::DaemonSteer { .. } => { - // a5: the daemon's work registry lives in another - // process, so this is a control-API call, not a - // registry read. The listing's local fallback is - // built here, on the loop where `chat_sessions` is - // reachable, and handed to the request to show if - // the daemon turns out to be unreachable. - let local_fallback = if matches!(action, SessionCommand::DaemonSessions) { - handle_local_session_command( - &SessionCommand::Sessions, - &mut chat_sessions, - &session_rings, - &mut reaped_log_archive, - &reap_policy, - &tools_registry, - ) - .await - } else { - None - }; - if let Some(notice) = start_daemon_session_command( - &action, - local_fallback, - &chat_sessions.daemon_requests(), - DaemonControl { - config: &config, - dispatcher: &chat_dispatcher, - redraw_tx: redraw_tx_for_main.as_ref(), - }, - ) { - emit_chat_output(¬ice); - } - continue; - } - } - } - commands::CommandResult::NotACommand => { - // v1.1b input routing (head footgun: input-target ambiguity). - // When a child session is attached, plain text + Enter is - // routed as a *steer* to that session instead of starting a - // main-chat turn. The prompt's colour+glyph indicator already - // shows the target, and `/detach` (or Esc) returns to main. - // We never auto-switch focus — only an explicit /attach or the - // switcher changes the routing target. - if let Some(sid) = attached_follow.clone() { - if !is_local_operator_input(&msg) { - emit_chat_output("Steering an attached session requires local terminal operator input."); - if let Some(guard) = assignment_guard.as_mut() { - guard.failed("Assigned task cannot steer the operator's attached session."); - } - continue; - } - let run_id = sid.as_str().to_string(); - match tools_registry.iter().find(|t| t.supports_name("sessions_spawn")) { - Some(tool) => { - // Same Low-risk steer path as `/steer`: delegate to - // the sessions_spawn tool with the matching grant so - // the shared side-effect gate + running-status check - // + steer_tx delivery all apply uniformly. - let operation_name = format!("sessions_spawn:steer:{run_id}"); - let grant = crate::security::policy::ApprovalGrant::for_resource_operation( - "sessions_spawn", - &operation_name, - "chat-operator", - None, - ); - let mut args = serde_json::json!({ - "action": "steer", - "run_id": run_id, - "message": user_input, - }); - match serde_json::to_value(&grant) { - Ok(grant_value) => { - if let Some(obj) = args.as_object_mut() { - obj.insert( - crate::security::policy::RUNTIME_APPROVAL_GRANT_ARG.to_string(), - grant_value, - ); - } - } - Err(e) => { - tracing::warn!( - error = %crate::agent::diagnostics::error_class(&e), - "Failed to serialize steer approval grant; proceeding without it" - ); - } - } - match tool.execute_named("sessions_spawn", args).await { - Ok(result) => { - let out = if result.output.is_empty() { - result - .error - .filter(|e| !e.is_empty()) - .unwrap_or_else(|| "(steered)".to_string()) - } else { - result.output - }; - emit_chat_output(&out); - } - Err(e) => emit_chat_output(&format!("Steer failed: {e}")), - } - } - None => emit_chat_output("Background sessions are not available in this session."), - } - continue; - } - } - } - } - - } - - // This is the concrete TerminalChannel: send_draft always returns - // Some(id), including when its UI receiver has closed. Capacity can - // therefore be selected before creating the durable source. The local - // worker registry is inserted into only by this main loop; awaits below - // cannot consume another slot. - #[cfg(feature = "terminal-tui")] - let reducer_driver_turn_active = true; - #[cfg(feature = "terminal-tui")] - let provider_worker_kind = crate::chat::turn_worker::ProviderTurnWorkerKind::Detached; - #[cfg(not(feature = "terminal-tui"))] - let provider_worker_kind = crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited; - let provider_admission_max = match provider_worker_kind { - crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited => 1, - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached => max_concurrent_visible_turns, - }; - let provider_admission = - provider_turn_visible_admission(&provider_turn_workers, provider_worker_kind, provider_admission_max); - let catalog_changed = turn_service.check_live_parity().is_err(); - if !provider_admission.can_start_visible || (catalog_changed && provider_admission.active_workers > 0) { - tracing::warn!( - active_workers = provider_admission.active_workers, - foreground_active = provider_admission.foreground_active, - detached_active = provider_admission.detached_active, - effective_max_visible_turns = provider_admission.effective_max_visible_turns, - target_kind = ?provider_worker_kind, - "visible provider turn capacity unavailable before source admission; queueing input" - ); - // No durable input or decision exists yet. Keep the original - // assignment and queue identity for its first actual admission. - if let Some(guard) = assignment_guard.as_mut() { - guard.disarm(); - } - requeue_post_route_admission_rejected_input( - &mut input_backlog, - &mut turn_scheduler, - &mut defer_visible_input_pop_once, - DequeuedInputMessage { - priority: input_priority, - turn_task_id: provider_queue_task_id, - msg, - terminal_origin: terminal_origin.clone(), - }, - ); - publish_main_queue_status(&chat_dispatcher, &turn_scheduler); - continue; - } - if catalog_changed { - // Publish only at a new source boundary after existing model turns - // have finished. Their sealed catalog/grants are never rewritten. - // Keep publication's large builder future off the chat task's - // stack, including unoptimized binaries used by PTY regression. - let replacement = Box::pin(ctx.publish_turn_runtimes( - Arc::clone(&tools_registry), - crate::tools::capability::turn_state::TurnSurfaceKind::Interactive, - )).await?; - child_cleanup.retain_service(Arc::clone(&replacement)); - let retired = std::mem::replace(&mut turn_service, replacement); - let retirement = child_cleanup.retire(&retired)?; - let drained = retired.drain_writes(std::time::Instant::now() + Duration::from_secs(2)).await; - retirement.finish(drained); - anyhow::ensure!(drained, "previous chat catalog writes were not confirmed"); - } - fabric_turn_seq += 1; - // D8-2: one run_id per turn, generated at the turn entry and reused by - // every run_id consumer within this loop iteration (user event, route - // scope, assistant event). No parent_run_id is set (turns are not a spawn - // lineage; session relation is via chat_session_key). - let turn_run_id = uuid::Uuid::new_v4().to_string(); - let current_provider_binding = provider_binding.as_ref() - .ok_or_else(|| anyhow::anyhow!("chat provider binding is missing"))?; - current_provider_binding.verify(&ctx.config_generation, &provider, provider_name, model_name)?; - let cancellation = turn_signal.new_turn_cancellation(); - let mut input_scope = chat_message_event_scope( - memory_fabric.workspace_id(), &chat_session_key, &turn_run_id, provider_name, model_name, - ); - input_scope.config_generation_id = Some(ctx.config_generation.id.0); - input_scope.config_source_revision = Some(ctx.config_generation.source_revision.fingerprint_sha256.clone()); - // The TUI mirror is updated synchronously by /mode; its legacy session - // deliberately stops tracking mode when the reducer owns UI state. - #[cfg(feature = "terminal-tui")] - let admitted_chat_mode = chat_mirror.lock().chat_mode; - #[cfg(not(feature = "terminal-tui"))] - let admitted_chat_mode = chat_session.session().mode; - let has_conversation_history = history.iter().any(|message| message.role != "system"); - let (chat_user_event, admitted_binding, mut admission_guard) = current_provider_binding.record_guarded_with_origin( - memory_fabric.clone(), (input_scope, &chat_session_key, binding::ChatAdmissionMode::Model(admitted_chat_mode), has_conversation_history), &user_input, - format!("chat:{}:{turn_run_id}:{fabric_turn_seq}:user", chat_session.session().id), - child_cleanup.register(cancellation.clone())?, entry::prepare_origin(terminal_origin,&msg,&user_input)?, - ).await?; - let admission = admitted_binding - .issue_decision(&turn_service, &cancellation) - .await; - if let Err(error) = admission { - if let Err(record_error) = admission_guard.finish_failure( - cancellation.is_cancelled(), &format!("decision admission failed: {error}"), - ).await { - return Err(error.context(format!("Chat admission failure persistence is unconfirmed: {record_error}"))); - } - return Err(error); - } - admission_guard.handoff_terminal()?; - let chat_turn_binding = Some(Arc::clone(&admitted_binding)); - if one_shot.is_some() { - one_shot_binding = Some(Arc::clone(&admitted_binding)); - } - - let file_mention_enrichment = enrich_file_mentions_for_prompt(&user_input, tools_registry.as_ref()).await; - if let Some(note) = file_mention_enrichment.visible_note.as_deref() { - emit_chat_output(note); - } - let user_input_for_prompt = file_mention_enrichment.prompt; - - // Auto-save user message to memory - if config.memory.should_auto_promote_user_message(&user_input) { - let safe_user_input = sanitize_chat_semantic_memory_content(&user_input); - let _ = crate::agent::entry::save_current_input(&memory_fabric, - admitted_binding.envelope().run_id.as_deref().context("chat turn run id missing")?, - &admitted_binding.envelope().session_key, - &safe_user_input, chat_user_event.as_ref().map(|event| event.event_id.as_str())).await; - } - - // Inject memory context - let runtime_envelope = admitted_binding.envelope().clone(); - let memory_runtime = crate::agent::turn_request::ToolLoopMemory::new( - &mem, - &config.workspace_dir, - Some( - DocumentIngestRuntime::from_envelope(mem.clone(), &runtime_envelope) - .with_source_message_event_id(chat_user_event.as_ref().map(|event| event.event_id.clone())), - ), - ) - .with_event_fabric(memory_fabric.clone()) - .with_request_event_scope( - runtime_envelope.message_scope().with_recipient(format!("{provider_name}/{model_name}")), - ) - .with_tool_surface_reserve(tool_surface_reserve.clone()); - // The TUI handoff retains the original source input, before enrichment. - #[cfg(feature = "terminal-tui")] - let routing_input = admitted_binding.routing_input().to_owned(); - let mem_context = admitted_binding.recalled_context(mem.as_ref()).await; - let context = mem_context.preamble.clone(); - let enriched = if context.is_empty() { - user_input_for_prompt.clone() - } else { - format!("{context}{user_input_for_prompt}") - }; - - // Build system prompt with skill selection - let selected_skills = admitted_binding.prompt_skills()?; - // Publish only this turn's selected metadata. Previous turns do not - // grant continued Skill exposure; the prompt builder orders entries. - let system_prompt = build_chat_system_prompt(&config, model_name, &selected_skills, native_tools); - // An ordered, acknowledged read before this turn builds its sources - // and copies its provider view: every action sent before it (another - // turn's compaction whose finalization is still pending included) is - // applied first, so no turn starts from a view the session already - // compacted, and its start epoch is from before its own preflight. - let admitted_session = acknowledged_session_barrier(&chat_dispatcher, &turn_signal).await?; - if admitted_session.compaction_epoch != provider_view_compaction_epoch { - history = super::compaction::provider_view_from_acked(&history, &admitted_session); - provider_view_compaction_epoch = admitted_session.compaction_epoch; - } - let persisted_history_for_turn = persisted_history_for_current_turn(&chat_session.session(), &system_prompt, &user_input); - upsert_leading_system_prompt(&mut history, system_prompt.clone()); - // S2-C Step 4: dual-write SetLeadingSystemPrompt to the reducer — byte-for-byte aligned with - // the legacy `if empty { push } else { first_mut = ... }` (the reducer takes the same - // branches internally). It runs on every turn, and expressing it as an append would pile up - // system messages. - let _ = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::SetLeadingSystemPrompt { - content: system_prompt.clone(), - }, - "chat.system_prompt_per_turn", - ); - let history_len_before_user_turn = history.len(); - let history_user_message = crate::agent::turn_contracts::inbound_user_message(&enriched); - // The provider-side copy is read only by the TUI reducer driver. - // The compaction epoch the provider-side copy reflects; a worker - // compaction during the turn moves it on (see the finalizer). - #[cfg(feature = "terminal-tui")] - let compaction_epoch_at_start = admitted_session.compaction_epoch; - #[cfg(feature = "terminal-tui")] - let history_for_provider = { - let mut history_for_provider = history.clone(); - history_for_provider.push(history_user_message.clone()); - history_for_provider - }; - - // ── Set active recipient/channel on tools (for proactive messaging) ── - for tool in tools_registry.iter() { - if tool.name() == "message_send" { - continue; - } - tool.set_active_recipient("user").await; - tool.set_active_channel(Arc::clone(&terminal) as Arc).await; - } - - // ── Streaming pipeline setup ───────────────────────────── - // - // The delta channel carries ONLY visible assistant text — never the - // model's reasoning/thinking content. Reasoning is separated upstream - // at the provider parsing layer (see `parse_native_response` / - // `parse_sse_line` in providers/{anthropic,openai,ollama,compatible}.rs) - // and travels back via `ProviderChatResponse.reasoning_content`. The - // tool-call loop persists reasoning into conversation history through - // `build_native_assistant_history`; the live stream below renders text - // only, so the user never sees the model's internal monologue. - let (delta_tx, delta_rx) = mpsc::channel::(DELTA_CHANNEL_CAPACITY); - - // Start a streaming draft on the terminal - let draft_id = match terminal.send_draft(&SendMessage::new("", "user")).await { - Ok(id) => id, - Err(e) => { - tracing::debug!(error = %crate::agent::diagnostics::error_class(&e), "Failed to start draft"); - None - } - }; - - #[cfg(feature = "terminal-tui")] - anyhow::ensure!( - !reducer_driver_turn_active || draft_id.is_some(), - "admitted detached chat turn requires its terminal draft; execution was not requeued" - ); - - // Step 5b dual write: announce that a new LLM inference turn starts (only when a draft - // exists). In shadow mode the reducer sets stream.draft + control.generating=true, with no - // external side effects (business Effects are no-ops). - if let Some(ref d_id) = draft_id { - let _ = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::TurnStarted { - draft_id: d_id.clone(), - cancel: cancellation.clone(), - }, - "chat.turn_started", - ); - } - - // Spawn background task: accumulate deltas → channel.update_draft() - // Follows the exact same pattern as process_channel_message in channels/mod.rs. - // - // P1-6 — Monotonic draft version protocol (Step 3 update). The - // sender-side counter still stamps each accumulated snapshot with a - // strictly monotonic `u64` (kept for `update_draft` downstream - // consumers and the inline-redraw protocol). The receiver-side stale - // check formerly performed here by `DraftVersionTracker.accept()` has - // been DELETED — its protection is now owned end-to-end by the - // Redux-style reducer in `chat::state` via `StreamState::draft.version` - // (see `ChatState::reduce_stream_chunk_received`). - // - // Why this is safe to remove: - // 1. `delta_rx` is a single-task tokio mpsc; FIFO is guaranteed at - // the runtime layer (no parallel accumulators). - // 2. The counter is incremented atomically inside the same task, - // producing a strictly monotonic sequence by construction. The - // old tracker call was over-defence ("unreachable here" per the - // original comment). - // 3. The reducer's `StreamChunkReceived` arm now enforces - // strict-monotonic version + draft_id matching + finalize-state - // check as the single source of truth. Once Step 5 makes the - // reducer the renderer source, this task disappears entirely. - // - // Terminal TUI now relies on the reducer for the visible stream; the - // non-TUI fallback still forwards full accumulated drafts to the - // channel implementation. - let draft_updater = if let Some(ref d_id) = draft_id { - #[cfg(not(feature = "terminal-tui"))] - let channel: Arc = Arc::clone(&terminal); - #[cfg(not(feature = "terminal-tui"))] - let reply_target = "user".to_string(); - #[cfg(not(feature = "terminal-tui"))] - let draft_id_owned = d_id.clone(); - let mut rx = delta_rx; - let version_counter = Arc::new(DraftVersionCounter::new()); - // Step 5b dual write: send every delta through the coalescer as - // Action::StreamChunkReceived. When the bounded(2048) action_tx is full the coalescer - // merges deltas, so nothing grows without bound. - let coalescer_sender = chat_dispatcher.sender(); - let coalescer_draft_id = d_id.clone(); - Some(tokio::spawn(async move { - #[cfg(not(feature = "terminal-tui"))] - let mut accumulated = String::new(); - let mut coalescer = dispatcher::StreamChunkCoalescer::new(coalescer_sender); - while let Some(delta) = rx.recv().await { - // Counter still ticks for downstream consumers (UiActor's - // inline-redraw protocol uses it). No tracker.accept() — - // see comment block above. - let version = version_counter.next(); - #[cfg(not(feature = "terminal-tui"))] - { - accumulated.push_str(&delta); - if let Err(e) = channel.update_draft(&reply_target, &draft_id_owned, &accumulated).await { - tracing::debug!(error = %crate::agent::diagnostics::error_class(&e), "Draft update failed"); - } - } - // Step 5b shadow: forward the **incremental** delta into - // the reducer via the coalescer. The reducer accumulates - // its own `draft.accumulated` mirror — feeding the full - // `accumulated` string here would cause double-accumulation. - // Backpressure or close are silently tolerated (legacy - // path remains the renderer source; shadow path observes). - let _ = coalescer.try_send_chunk(coalescer_draft_id.clone(), delta, version); - } - // Stream ended — flush pending coalescer state, counter goes - // out of scope; reducer-side version state is cleared on - // StreamCompleted/Failed/Cancelled (dispatched from the chat::run main loop). - let _ = coalescer.flush(); - })) - } else { - // No draft — consume delta_rx so the sender doesn't block - let mut rx = delta_rx; - Some(tokio::spawn(async move { while rx.recv().await.is_some() {} })) - }; - - #[cfg(not(feature = "terminal-tui"))] - { - *active_cancel.lock() = Some(cancellation.clone()); - } - - // ── Tool event forwarding (visual feedback in terminal) ── - // - // P2-7: in addition to the existing notify_tool_* calls (which feed - // the legacy UiActor renderer in `channels/terminal.rs`), we also - // mirror every tool event into a `TuiState` instance behind a - // `parking_lot::Mutex`. The ratatui renderer in `chat/tui.rs` reads - // from this mirror; full renderer wiring lands in P2-12. - let (tool_event_tx, mut tool_event_rx) = mpsc::channel::(TOOL_EVENT_CHANNEL_CAPACITY); - let terminal_for_tools = Arc::clone(&terminal); - // P3-3: every producer in this turn now shares the chat-scoped - // `chat_mirror` (created once at the top of `run`). The previous - // per-turn `tui_mirror` instance is gone — keeping a per-turn alias - // here so downstream code that already says `tui_mirror.lock()` keeps - // compiling, but the underlying `Arc` is the same one the render - // task and the input task hold. - #[cfg(feature = "terminal-tui")] - let tui_mirror: Arc> = Arc::clone(&chat_mirror); - // P0-5 fix: tool start/finish events now have a single mirror path. - // The UiActor in `channels/terminal.rs::handle_event_tui` is the sole - // writer of tool cards into `TuiState` (it sanitises name/args via - // `sanitize_terminal_output` and calls `notify_redraw()` on the same - // 1-slot channel as `redraw_tx_for_main`). The previous double-mirror - // here pushed a second card and could reorder Running/Done with the - // UiActor path under load — the forwarder now just relays the event - // to the UiActor and lets that path own the mirror mutation. - let tool_event_forwarder = tokio::spawn(async move { - while let Some(notif) = tool_event_rx.recv().await { - match notif { - ToolCallNotification::Started { name, args_summary, .. } => { - terminal_for_tools.notify_tool_started(&name, &args_summary).await; - } - ToolCallNotification::Finished { - name, - success, - duration_ms, - .. - } => { - terminal_for_tools - .notify_tool_finished(&name, success, duration_ms) - .await; - } - ToolCallNotification::Progress { iteration } => { - terminal_for_tools.notify_progress(iteration).await; - } - } - } - }); - // Log a trace stat so the mirror is observably wired (also keeps the - // `tui_mirror` binding from being flagged as unused when the renderer - // wiring lands in P2-12). - #[cfg(feature = "terminal-tui")] - { - let tracked_tool_cards_count: usize = - tui_mirror.lock().last_tool_result_index().map_or(0, |index| index + 1); - tracing::trace!(tracked_tool_cards_count, "tui_mirror initialized"); - } - - // ── Unified tool authorization (permission-model Phase 1) ── - // Tool access is governed solely by `[autonomy]` via - // `SecurityPolicy::decide`; the former PolicyPipeline is removed. - let scope_owner_id = runtime_envelope.resolved_owner_id(); - let scope_ctx = ScopeContext { - policy: &security, - sender: "user", - channel: "terminal", - chat_type: "private", - chat_id: "terminal:user", - session_key: Some(&runtime_envelope.session_key), - owner_id: Some(&scope_owner_id), - owner_isolated: runtime_envelope.owner_isolated, - topic_id: runtime_envelope.topic_id.as_deref(), - task_id: runtime_envelope.resolved_task_id(), - source_message_event_id: runtime_envelope.source_message_event_id.as_deref(), - config_generation_id: runtime_envelope.config_generation_id, - config_source_revision: runtime_envelope.config_source_revision.as_deref(), - }; - - let mut effective_compaction = admitted_binding.effective_compaction()?; - effective_compaction.config = admitted_binding.main_compaction() - .ok_or_else(|| anyhow::anyhow!("chat compaction requires an admitted decision"))?.clone(); - crate::providers::context_window::trace_effective_compaction_resolution(&effective_compaction); - #[cfg(feature = "terminal-tui")] - refresh_context_budget_for_tui( - &history_for_provider, - &effective_compaction.config, - &tool_surface_reserve, - redraw_tx_for_main.is_some(), - &chat_mirror, - &chat_dispatcher, - ); - - let route_decision = RouteDecision::from_model_routes_for_context( - provider_name, - model_name, - &config.model_routes, - runtime_envelope.resolved_owner_id(), - chat_session_key.clone(), - chat_user_event.as_ref().map(|event| event.event_id.clone()), - "chat", - (user_input.chars().count() / 4 + 1).min(u32::MAX as usize) as u32, - true, - false, - ); - let route_scope = route_event_scope( - "chat", - Some(runtime_envelope.resolved_owner_id()), - Some(chat_session_key.clone()), - Some(turn_run_id.clone()), - Some("local-user".to_string()), - Some(format!( - "{}/{}", - route_decision.selected.provider, route_decision.selected.model - )), - ); - if let Err(e) = record_route_decision_event(&memory_fabric, route_scope.clone(), &route_decision).await { - tracing::warn!(error = %crate::agent::diagnostics::error_class(&e), "Failed to append router.route_decision message event"); - } - let provider_started_at = chrono::Utc::now(); - - // The shared turn engine owns context-overflow recovery. Chat projects - // its final outcome and does not start a second compaction/replay loop. - // - // There is deliberately no wall-clock budget around the turn. A chat turn - // ends when it finishes, when the user cancels it, or when the stall - // detector in `crate::agent::idle` finds it has stopped making progress. - #[cfg(feature = "terminal-tui")] - let history_len_before_tools; - - // S2-A refinement: split the coarse `Failed` variant so the Redux - // dispatch path can distinguish user-driven cancellation from real - // errors. The legacy renderer still treats every non-Success as a - // failure (continue), but the reducer now sees the correct semantic - // (`StreamCancelled` vs `StreamFailed { err, retryable }`). - enum TurnOutcome { - // FIX-P0-30/31: carry the loop's provider-attribution trace so the - // success path can record the *real* serving model/attempts instead - // of the routed `decision.selected.model`. - Success(String), - /// User-initiated cancel (Ctrl+C) or `is_tool_loop_cancelled` from - /// the inner loop. Reducer side maps to `StreamCancelled`. - Cancelled, - /// Genuine failure (timeout / context-overflow exhausted / other - /// error). Carries error string + retryable hint for the reducer's - /// `StreamFailed` payload (mirrors `dispatcher::TurnOutcomeKind::Failed`). - FailedWithError { - err: String, - retryable: bool, - }, - } - - // The terminal TUI always routes a turn to the reducer driver; without - // the TUI the shared agent loop runs it (the driver branch is cfg'd out). - #[cfg(feature = "terminal-tui")] - tracing::info!( - redux_mode = ?top_redux_mode, - // Registry roots before routing, refresh and alias expansion; - // the wire count is the compiled-request event's - // `tool_snapshot.count`. - registry_root_tools = Vec::len(&tools_registry), - route = "ReduxDriver", - "chat::run turn route decision" - ); - let provider_history_len_before_assistant; - // The identity of the request recorded at admission: an aborted turn - // settles by it, so no earlier request with the same text is touched. - let admission; - #[cfg(feature = "terminal-tui")] - { - if reducer_driver_turn_active { - admission = None; - provider_history_len_before_assistant = history_for_provider.len(); - } else { - admission = Some(record_user_turn_at_admission(&chat_dispatcher, &turn_signal, &user_input).await?); - history.push(history_user_message.clone()); - provider_history_len_before_assistant = history.len(); - } - } - #[cfg(not(feature = "terminal-tui"))] - { - admission = Some(record_user_turn_at_admission(&chat_dispatcher, &turn_signal, &user_input).await?); - history.push(history_user_message.clone()); - provider_history_len_before_assistant = history.len(); - } - - let provider_turn_task_id = start_provider_turn_task( - &mut turn_scheduler, - provider_queue_task_id, - &user_input, - history_len_before_user_turn, - ); - anyhow::ensure!( - !chat_turn_binding.as_ref().is_some_and(|binding| binding.is_decided()) || provider_turn_task_id.is_some(), - "decision-owned Chat turn could not acquire a scheduler task" - ); - if one_shot.is_some() { - one_shot_task_id = provider_turn_task_id; - } - register_provider_history_commit_task(&mut history_commit_coordinator, &turn_scheduler, provider_turn_task_id); - record_provider_turn_completion_context( - &mut provider_turn_completion_contexts, - provider_turn_task_id, - provider_history_len_before_assistant, - ); - register_provider_turn_worker( - &mut provider_turn_workers, - &turn_scheduler, - provider_turn_task_id, - provider_worker_kind, - ); - publish_main_queue_status(&chat_dispatcher, &turn_scheduler); - publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); - - // ── Redux driver switched-over path (Step 5a-4) ──────────── - // - // Entered only when routing selects ReduxDriver. dispatch Action::StartLLMTurn → - // EffectExecutor::execute_real(Effect::StartTurn) → spawn drive_start_turn_stream - // streaming driver → post StreamChunkReceived / Completed / Failed / Cancelled back through - // action_tx → the dispatcher task reduces them and calls turn_signal.record_and_notify → - // this code awaits the outcome. - // - // This branch does **not** call run_turn; the old path does not run at all: - // * no duplicate hooks (the old path's hooks.emit does not run; only the reducer's - // NotifyHook(Error) writes) - // * no duplicate history writes (the reducer writes once through RecordAssistantTurn) - // * round 2 hang defence: shutdown.cancelled() as a fallback arm of tokio::select! - // - #[cfg(feature = "terminal-tui")] - if reducer_driver_turn_active && let Some(d_id) = draft_id.clone() { - // Protocol: register the keyed turn before dispatch, then obtain the - // waiter. The legacy single-slot signal remains as fallback while - // P6J migrates toward detached provider workers. - if let Some(id) = provider_turn_task_id { - turn_signal.register_turn(id, d_id.clone()); - let _ = turn_signal.consume_turn_outcome(id); - let _ = turn_signal.consume_turn_usage(id); - } - if let Some(id) = provider_turn_task_id { - spawn_provider_turn_completion_waiter( - turn_signal.clone(), - id, - provider_completion_tx.clone(), - shutdown.clone(), - ); - } - let mut notify_fut: Option + Send + '_>>> = - provider_turn_task_id - .is_none() - .then(|| Box::pin(turn_signal.notified()) as _); - // Consume any leftover outcome before dispatching, so what we read belongs to this turn. - let _ = turn_signal.consume_outcome(); - - // S2.5 P1-A: handle dispatch_result in explicit branches (a failed StartLLMTurn must - // fall through, otherwise notify_fut hangs forever); dispatch_or_log already meters and - // warns, so no extra tracing is needed. - // D8-4 (redux path real fix): seed the turn-root spawn execution - // context for this turn and hand it to the driver via StartLLMTurn → - // Effect::StartTurn. This is the redux mirror of the legacy - // `SPAWN_EXECUTION_CONTEXT.scope(seed_turn_context(turn_run_id, ..))` - // wrapper applied below at the legacy tool-loop path's `run_turn` call - // — the redux path `continue`s before reaching it, so the seed must - // travel with the effect. Same `turn_run_id` + `chat_session_key` - // source as the legacy path (single source of truth) so a sub-agent - // spawned inside this turn inherits `parent_run_id = turn_run_id`. - let mut redux_turn_spawn_ctx = crate::tools::sessions_spawn::SpawnExecutionContext::seed_turn_context( - turn_run_id.clone(), - chat_session_key.clone(), - ); - redux_turn_spawn_ctx.owner_id = Some(runtime_envelope.resolved_owner_id()); - redux_turn_spawn_ctx.topic_id = runtime_envelope.topic_id.clone(); - redux_turn_spawn_ctx.source_message_event_id = runtime_envelope.source_message_event_id.clone(); - let redux_turn_message_send_ctx = crate::tools::message_send::MessageSendExecutionContext::new( - Some("user".to_string()), - Arc::clone(&terminal) as Arc, - ); - let provider_turn_sequence = - provider_turn_task_id.and_then(|id| turn_scheduler.task(id).map(|task| task.sequence)); - let dispatch_result = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::StartLLMTurn { - provider_turn_task_id, - provider_turn_sequence, - draft_id: d_id.clone(), - history: history_for_provider.clone(), - compaction_guard_history: Some(persisted_history_for_turn.clone()), - compaction_config: Some(effective_compaction.config.clone()), - cancel: cancellation.clone(), - turn_spawn_ctx: Some(redux_turn_spawn_ctx), - turn_message_send_ctx: Some(redux_turn_message_send_ctx), - // Route on what the user typed. `history_for_provider` - // already carries the memory preamble and the - // `[Recent shared workspace events]` block, and routing on - // that let injected text widen the published tool surface. - routing_input: Some(routing_input.clone()), - turn_binding: chat_turn_binding.clone(), - }, - "chat.start_llm_turn", - ); - // Codex P1: the dispatch may be Backpressured / ChannelClosed. Either failure means the - // dispatcher task will not produce a turn outcome, so chat::run must immediately treat it - // as Failed and fall through to cleanup, otherwise notify_fut is never fired. - if !matches!(dispatch_result, dispatcher::DispatchResult::Sent) { - tracing::warn!( - result = dispatch_result.kind(), - "Redux driver: StartLLMTurn dispatch failed; aborting turn" - ); - // S2-B Step 3: send StreamCancelled synchronously so the reducer clears - // active_cancel; the old field is only a fallback under Off/Both (symmetric with the - // guard at the register site). - if let Some(ref d_id) = draft_id { - let _ = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::StreamCancelled { draft_id: d_id.clone() }, - "chat.stream_cancelled_dispatch_failed", - ); - } - #[cfg(not(feature = "terminal-tui"))] - { - *active_cancel.lock() = None; - } - drop(delta_tx); - drop(tool_event_tx); - if let Some(handle) = draft_updater { - let _ = handle.await; - } - let _ = tool_event_forwarder.await; - if let Some(ref id) = draft_id { - let _ = terminal.cancel_draft("user", id).await; - } - enqueue_provider_turn_finalizer_event( - &mut provider_turn_finalizer_events, - provider_turn_task_id, - ProviderTurnTerminalPlan::Failed { - err: "redux driver dispatch failed".to_string(), - history_commit_len: take_provider_turn_completion_history_len( - &mut provider_turn_completion_contexts, - provider_turn_task_id, - history.len(), - ), - summary: "redux driver dispatch failed".to_string(), - }, - ); - continue; - } - - if let Some(task_id) = provider_turn_task_id { - if per_turn_contexts - .insert( - task_id, - PerTurnContext { - turn_binding: chat_turn_binding.clone(), - - task_id, - draft_id: d_id.clone(), - delta_tx: Some(delta_tx), - tool_event_tx: Some(tool_event_tx), - draft_updater, - tool_event_forwarder: Some(tool_event_forwarder), - user_input: user_input.clone(), - turn_run_id: turn_run_id.clone(), - route_scope: route_scope.clone(), - route_decision: route_decision.clone(), - provider_started_at, - provider_name: provider_name.to_string(), - model_name: model_name.to_string(), - history_len_before_user_turn, - compaction_epoch_at_start, - assignment: assignment_guard.take(), - }, - ) - .is_some() - { - tracing::warn!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), - "replaced pending Redux turn context before completion" - ); - } - continue; - } - - // Shutdown preemption guard against a round 2 hang. - let mut turn_input_open = true; - let mut provider_completion_event: Option = - provider_turn_task_id.and_then(|id| pending_provider_completion_events.remove(&id)); - if provider_completion_event.is_none() { - loop { - tokio::select! { - () = async { - if let Some(fut) = notify_fut.as_mut() { - fut.await; - } else { - std::future::pending::<()>().await; - } - } => break, - completion = provider_completion_rx.recv(), if provider_turn_task_id.is_some() => { - let Some(completion) = completion else { - break; - }; - // the completion of the current turn; `None`: retained as pending - if let Some(completion) = route_provider_completion_event_and_publish( - &mut provider_turn_lifecycle_rx, - &mut provider_turn_lifecycle_events_open, - &mut provider_turn_workers, - &mut pending_provider_completion_events, - provider_turn_task_id, - completion, - &chat_dispatcher, - ) { - provider_completion_event = Some(completion); - break; - } - } - lifecycle = provider_turn_lifecycle_rx.recv(), if provider_turn_lifecycle_events_open => { - let Some(lifecycle) = lifecycle else { - provider_turn_lifecycle_events_open = false; - continue; - }; - record_provider_turn_lifecycle_event( - &mut provider_turn_workers, - lifecycle, - ); - publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); - } - () = shutdown.cancelled() => { - tracing::debug!("Redux driver: shutdown.cancelled before turn complete"); - break; - } - msg = input_rx.recv(), if turn_input_open => { - let Some(msg) = msg else { - turn_input_open = false; - continue; - }; - let daemon_control = DaemonControl { - config: &config, - dispatcher: &chat_dispatcher, - redraw_tx: redraw_tx_for_main.as_ref(), - }; - let queued_from = input_backlog.len(); - process_active_turn_input_batch( - msg, - &mut emit_chat_output, - &mut input_rx, - &mut input_backlog, - &mut turn_scheduler, - &mut provider_turn_workers, - provider_turn_task_id, - &chat_dispatcher, - &chat_session.session(), - &mut chat_sessions, - &session_rings, - &mut reaped_log_archive, - &reap_policy, - &tools_registry, - daemon_control, - ) - .await; - if plain_typed_queue { - let added = lines_queued_since(&input_backlog, queued_from); - settle_queued_lines(&mut input_backlog, &mut turn_scheduler, &added); - } - publish_main_queue_status(&chat_dispatcher, &turn_scheduler); - } - } - } - } - - let resolved_completion = - resolve_provider_turn_completion(&turn_signal, provider_turn_task_id, provider_completion_event); - let completion_history_len = take_provider_turn_completion_history_len( - &mut provider_turn_completion_contexts, - provider_turn_task_id, - history.len(), - ); - let terminal_plan = provider_turn_terminal_plan_from_completion( - resolved_completion, - completion_history_len, - &tools_registry, - ); - enqueue_provider_turn_finalizer_event( - &mut provider_turn_finalizer_events, - provider_turn_task_id, - terminal_plan.clone(), - ); - let finalizer_result = drain_provider_turn_finalizer_events_and_publish( - &mut turn_scheduler, - &mut history_commit_coordinator, - &mut provider_turn_workers, - &mut provider_turn_finalizer_events, - &chat_dispatcher, - ) - .into_iter() - .rev() - .find(|result| result.task_id == provider_turn_task_id) - .unwrap_or(ProviderTurnFinalizerResult { - task_id: provider_turn_task_id, - terminal_status: "unknown", - finalized: false, - }); - - // Finalize streaming (aligned with the legacy teardown): drop the senders so the - // background tasks wind down. - // - // S2-B Step 3: on the driver path the reducer already cleared - // `state.control.active_cancel` when it received StreamCompleted/Failed/Cancelled; the - // legacy Arc is only a fallback under Off/Both. - #[cfg(not(feature = "terminal-tui"))] - { - *active_cancel.lock() = None; - } - drop(delta_tx); - drop(tool_event_tx); - if let Some(handle) = draft_updater { - let _ = handle.await; - } - let _ = tool_event_forwarder.await; - - match terminal_plan { - ProviderTurnTerminalPlan::Completed { - final_text, - recorded_response, - empty_response, - usage: redux_tokens_used, - history_commit_len, - .. - } => { - if empty_response { - let provider_outcome = if let Some(binding) = chat_turn_binding.as_ref() { - binding.provider_outcome(&route_decision, provider_started_at)? - } else { ProviderExecutionOutcome::success_for_decision_with_usage( - &route_decision, provider_started_at, redux_tokens_used.clone(), - ) }; - if !finalizer_result.finalized { - if let Err(e) = terminal.cancel_draft("user", &d_id).await { - tracing::debug!(error = %crate::agent::diagnostics::error_class(&e), "Redux driver: cancel empty-response draft failed"); - } - publish_main_queue_status(&chat_dispatcher, &turn_scheduler); - publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); - continue; - } - if let Err(e) = terminal.cancel_draft("user", &d_id).await { - tracing::debug!(error = %crate::agent::diagnostics::error_class(&e), "Redux driver: cancel empty-response draft failed"); - } - let terminal_usage = match finalize_chat_success_turn( - chat_turn_binding.as_deref(), - &memory_fabric, - &chat_session_key, - &turn_run_id, - provider_name, - model_name, - route_scope.clone(), - provider_outcome.clone(), - None, - history_commit_len, - "redux driver completed with empty response", - &config.cost, - &config.workspace_dir, - ) - .await - { - Ok(receipt) => receipt.into_session_usage(), - Err(error) => { - tracing::error!(error = %crate::agent::diagnostics::error_class(&error), "Chat terminal persistence is unconfirmed"); - return Err(error); - } - }; - if let Err(error) = dispatch_final_usage( - &chat_dispatcher, - &turn_signal, - &mut turn_scheduler, - provider_turn_task_id, - terminal_usage, - "chat.provider_usage_recorded_empty_response", - ) - .await - { - anyhow::bail!("Chat stopped after an unconfirmed history commit: {error}"); - } - #[cfg(feature = "terminal-tui")] - if let Some(tx) = redraw_tx_for_main.as_ref() { - let _ = tx.try_send(()); - } - surface_turn_elapsed_message( - &chat_dispatcher, - sessions_redraw_handle.as_ref(), - "completed", - provider_outcome.started_at, - provider_outcome.finished_at, - ); - publish_main_queue_status(&chat_dispatcher, &turn_scheduler); - publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); - continue; - } - let provider_outcome = if let Some(binding) = chat_turn_binding.as_ref() { - binding.provider_outcome(&route_decision, provider_started_at)? - } else { ProviderExecutionOutcome::success_for_decision_with_usage( - &route_decision, provider_started_at, redux_tokens_used.clone(), - ) }; - if !finalizer_result.finalized { - if let Err(e) = terminal.cancel_draft("user", &d_id).await { - tracing::debug!(error = %crate::agent::diagnostics::error_class(&e), "Redux driver: cancel commit-gated draft failed"); - } - publish_main_queue_status(&chat_dispatcher, &turn_scheduler); - publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); - continue; - } - // 1) Write the final text accumulated by the driver's stream back into the LLM - // history (aligned with the legacy tail - // `history.push(ChatMessage::assistant(...))`). - history.push(committed_reply_message(&chat_dispatcher.session_reader().acked(), &final_text)); - // 2) finalize_draft: deliver the text to the terminal channel so the user sees - // it (the driver path does not go through the delta_tx → draft_updater chain, - // it finalizes directly). - if let Err(e) = terminal.finalize_draft("user", &d_id, &final_text).await { - tracing::warn!(error = %crate::agent::diagnostics::error_class(&e), "Redux driver: finalize_draft failed"); - } - let terminal_usage = match finalize_chat_success_turn( - chat_turn_binding.as_deref(), - &memory_fabric, - &chat_session_key, - &turn_run_id, - provider_name, - model_name, - route_scope.clone(), - provider_outcome.clone(), - Some(recorded_response.clone()), - history_commit_len, - "redux driver completed", - &config.cost, - &config.workspace_dir, - ) - .await - { - Ok(receipt) => receipt.into_session_usage(), - Err(error) => { - tracing::error!(error = %crate::agent::diagnostics::error_class(&error), "Chat terminal persistence is unconfirmed"); - return Err(error); - } - }; - let attempts_count = u8::try_from(provider_outcome.attempts.len()).unwrap_or(u8::MAX); - crate::runtime::control_ladder::append_provider_outcome_trace( - std::path::Path::new(&config.workspace_dir), - &provider_outcome.decision_id, - &provider_outcome.final_provider, - &provider_outcome.final_model, - attempts_count, - "success", - ); - // On this driver path the worker's sink already sent - // RecordAssistantTurn + StreamCompleted (fixB B5); the - // reducer owns the turn, and the slash commands read its - // acknowledged snapshot. - if let Err(error) = dispatch_final_usage( - &chat_dispatcher, - &turn_signal, - &mut turn_scheduler, - provider_turn_task_id, - terminal_usage, - "chat.provider_usage_recorded", - ) - .await - { - anyhow::bail!("Chat stopped after an unconfirmed history commit: {error}"); - } - #[cfg(feature = "terminal-tui")] - if let Some(tx) = redraw_tx_for_main.as_ref() { - let _ = tx.try_send(()); - } - surface_turn_elapsed_message( - &chat_dispatcher, - sessions_redraw_handle.as_ref(), - "completed", - provider_outcome.started_at, - provider_outcome.finished_at, - ); - publish_main_queue_status(&chat_dispatcher, &turn_scheduler); - publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); - let _ = final_text; - } - ProviderTurnTerminalPlan::Failed { err, .. } => { - if let Err(error) = finalize_chat_non_success_turn( - chat_turn_binding.as_deref(), - &memory_fabric, - &turn_run_id, - route_scope.clone(), - crate::agent::terminal::TurnTerminalStatus::Failed, - None, - provider_started_at, - &format!("redux driver failed: {err}"), - &config.cost, - &config.workspace_dir, - ) - .await - { - if chat_turn_binding.as_ref().is_some_and(|binding| binding.is_decided()) { return Err(error); } - tracing::warn!(error = %crate::agent::diagnostics::error_class(&error), "Failed to commit shared failed Chat terminal event"); - } - // The worker's compactions and terminal precede this settlement on the - // action channel; the reducer never recorded a driver turn's request. - let settled = settle_aborted_turn(&chat_dispatcher, &turn_signal, None).await?; - provider_view_after_settled_abort(&mut history, &settled, compaction_epoch_at_start, false, None); - // The reducer's NotifyHook(Error) has already been sent; do not hooks.emit here - // again, to avoid duplicates. - #[cfg(feature = "terminal-tui")] - let interactive_tui_active = redraw_tx_for_main.is_some(); - #[cfg(not(feature = "terminal-tui"))] - let interactive_tui_active = false; - - if !interactive_tui_active && let Some(ref id) = draft_id { - let _ = terminal.cancel_draft("user", id).await; - } - if !interactive_tui_active { - super::output::print_turn_failure(plain_mode, &err); - } - if plain_mode { - plain_mode_turn_failed = true; - } - surface_turn_elapsed_message( - &chat_dispatcher, - sessions_redraw_handle.as_ref(), - "failed", - provider_started_at, - chrono::Utc::now(), - ); - publish_main_queue_status(&chat_dispatcher, &turn_scheduler); - publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); - } - ProviderTurnTerminalPlan::Cancelled { .. } => { - if let Err(error) = finalize_chat_non_success_turn( - chat_turn_binding.as_deref(), - &memory_fabric, - &turn_run_id, - route_scope.clone(), - crate::agent::terminal::TurnTerminalStatus::Cancelled, - None, - provider_started_at, - "redux driver cancelled", - &config.cost, - &config.workspace_dir, - ) - .await - { - if chat_turn_binding.as_ref().is_some_and(|binding| binding.is_decided()) { return Err(error); } - tracing::warn!(error = %crate::agent::diagnostics::error_class(&error), "Failed to commit shared cancelled Chat terminal event"); - } - if let Some(ref id) = draft_id { - let _ = terminal.cancel_draft("user", id).await; - } - let settled = settle_aborted_turn(&chat_dispatcher, &turn_signal, None).await?; - provider_view_after_settled_abort( - &mut history, - &settled, - compaction_epoch_at_start, - false, - Some(history_len_before_user_turn), - ); - publish_main_queue_status(&chat_dispatcher, &turn_scheduler); - publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); - } - } - - continue; - } - - // The compaction epoch before the preflight: a compaction adopted by - // the preflight or during the turn moves it, and every turn end then - // rebuilds the provider view from the acknowledged session. - let inline_compaction_epoch_before_preflight = admitted_session.compaction_epoch; - let legacy_budget_config = tool_surface_reserve.reserved_config(&effective_compaction.config); - let preflight_budget = crate::agent::context_budget::plan_context_budget( - &history, - &legacy_budget_config, - crate::agent::context_budget::PRE_TURN_FLUSH_THRESHOLD, - ); - if preflight_budget.over_hard_limit { - let audit_source_history = original_legacy_chat_compaction_audit_source(persisted_history_for_turn.messages()); - let summary_projection = bounded_legacy_chat_compaction_audit_source(persisted_history_for_turn.messages()); - let token_metadata = legacy_compaction_token_metadata(&history, persisted_history_for_turn.messages()); - let (turns_before, tokens_before) = super::compaction::chat_history_turns_and_tokens(&history); - // The request is already recorded (`UserTurnAdmitted` above), so the - // source is the persisted history including it and the reducer gets - // the same patch. The enriched request replaces the source's plain - // final message in the provider view. - let enriched_request = history.last().filter(|message| message.role == "user").cloned(); - let preflight_outcome = if let Some(patch) = build_chat_compaction_patch( - &history, - &persisted_history_for_turn, - provider.as_ref(), - model_name, - &legacy_budget_config, - memory_runtime.ingest(), - "chat_preflight", - ) - .await - { - apply_chat_compaction_patch_and_sync( - &mut history, - &persisted_history_for_turn, - enriched_request, - patch, - &legacy_budget_config, - crate::chat::action::CompactReason::ContextOverflow, - &chat_dispatcher, - &turn_signal, - ) + // ── Child-session shutdown on exit (Phase C) ───────────────── + // Snapshot every child session still tracked at exit, persist summaries for + // live sessions as interrupted, then terminate and clear every child + // registry through the single session owner. This covers running agents, + // NeedsInput agents, background shells, and interactive PTYs uniformly. + // A lost exit summary does not stop the cleanup below; it is returned + // once teardown has finished. + let exit_summaries = shutdown_child_sessions_for_exit(&mut chat_sessions, &chat_dispatcher, &turn_signal) .await - } else { - // No handoff or summary: the session and this view stay as they - // are; the turn's own preflight trims each request (a projection - // that is never persisted). - super::compaction::ManualCompactOutcome::NoDurableCompaction - }; - persist_legacy_chat_compaction_audit( - mem.as_ref(), - &runtime_envelope, - &audit_source_history, - &summary_projection, - token_metadata, - "chat_preflight", + .map(drop); + session_rings.clear(); + withdraw_assignment_enrolment( + assignment_enrolment.as_ref(), + &chat_dispatcher, + sessions_redraw_handle.as_ref(), ) .await; - #[cfg(feature = "terminal-tui")] - refresh_context_budget_for_tui( - &history, - &effective_compaction.config, - &tool_surface_reserve, - redraw_tx_for_main.is_some(), - &chat_mirror, - &chat_dispatcher, - ); - let compact_msg = preflight_outcome.feedback(turns_before, tokens_before, &legacy_budget_config); - surface_session_message(&chat_dispatcher, sessions_redraw_handle.as_ref(), &compact_msg); - tracing::warn!( - before_used_tokens = preflight_budget.used_tokens, - hard_limit = preflight_budget.available_input_tokens, - "legacy chat context budget preflight compacted before provider call" - ); - } - - // The inline loop hands its in-turn compactions to the reducer instead - // of keeping them as private mutations of `history`; after the turn the - // view follows the acknowledged session (`reconcile_inline_turn`). The - // reducer history it guards against holds the recorded request once: - // after an adopted preflight the acknowledged snapshot already holds - // it, identified by this turn's admission, and it keeps its `Request` - // origin, so an in-turn compaction that keeps it records it once. - let inline_compaction = { - let reducer_source = super::session_store::canonical_history_for_admitted_turn( - &chat_session.acked(), - &system_prompt, - admission, - &user_input, - ); - super::compaction::InlineCompactionSink::new(chat_dispatcher.clone(), turn_signal.clone(), &user_input, reducer_source) - }; - // The inline turn's canonical history: the acknowledged turns plus the - // plain request, never the enriched provider view (r6-2). - let inline_canonical = inline_compaction.reducer_source(); - - // D8-4: seed a turn-root spawn execution context so a sub-agent spawned - // directly from this chat turn inherits parent_run_id = the per-turn - // run_id. spawn_depth starts at 0 and is_turn_root keeps the first child's - // reported depth at 0 (a turn is not itself a spawn). A spawned child records - // under its own `spawn:` key, never under this chat session key. - let turn_spawn_ctx = crate::tools::sessions_spawn::SpawnExecutionContext::seed_turn_context( - turn_run_id.clone(), - chat_session_key.clone(), - ); - let turn_message_send_ctx = crate::tools::message_send::MessageSendExecutionContext::new( - Some("user".to_string()), - Arc::clone(&terminal) as Arc, - ); - - // The view this turn starts from; a turn that changes it other than by - // appending (a compaction, a projection trim, a middleware rewrite) - // rebuilds it from the session when it ends. - let inline_view_before_turn = super::compaction::ViewPrefix::of(&history); - // Keep the large trace inline outside the small outcome discriminator. - let (turn_outcome, successful_trace) = { - #[cfg(feature = "terminal-tui")] - { - history_len_before_tools = history.len(); - } - - let result = crate::tools::message_send::MESSAGE_SEND_EXECUTION_CONTEXT - .scope( - turn_message_send_ctx.clone(), - crate::tools::sessions_spawn::SPAWN_EXECUTION_CONTEXT.scope(turn_spawn_ctx.clone(), async { - run_turn( - &mut history, - crate::agent::turn_request::TurnRequest { - advice: admitted_binding.decision_advice(), - channel_name: "terminal", - scope: Some(&scope_ctx), - mode: admitted_binding.admitted_model_mode()?, - silent: false, - expose_stay_silent: false, - multimodal: &config.multimodal, - schedule: crate::agent::turn_request::TurnSchedule { - read_only_tool_concurrency_window: config.agent.read_only_tool_concurrency_window, - priority_scheduling_enabled: config.agent.priority_scheduling_enabled, - low_priority_tool_names: config.agent.low_priority_tools.clone(), - }, - compaction: Some(&effective_compaction.config), - decision: admitted_binding.decision_routing() - .ok_or_else(|| anyhow::anyhow!("chat runtime turn requires an admitted decision"))?, - }, - crate::agent::turn_request::TurnServices { - provider: provider.as_ref(), - provider_name, - model: model_name, - temperature, - tools_registry: Arc::clone(&tools_registry), - observer: observer.as_ref(), - hooks: &hooks, - approval: Some(Arc::clone(&approval_manager)), - approval_resolver: None, - // Supervised calls ask on the terminal (CR-2), as on the reducer path. - runtime_adapter: chat_turn_binding.as_ref().map(|binding| crate::agent::turn_contracts::ToolLoopRuntimeAdapter { - live_frames: None, - guarded_delivery: true, - provider_trace: binding.retained_provider_trace(), - events: Some(Arc::clone(&inline_compaction) as Arc), - stream_provider: false, - tool_execution_service: Some(Arc::new(super::line_approval::line_tool_execution_service( - Arc::clone(&tools_registry), &mem, &security, - Arc::clone(&approval_manager), cancellation.clone(), - Arc::new(super::terminal_approval::ControllingTerminal), - ))), - tool_execution_context: super::approval_context::line_mode(binding.envelope().clone()) - .with_approval_ledger(binding.h2_approval_ledger()), - allowed_tool_names: None, - }), - memory: memory_runtime.clone().with_canonical_history(inline_canonical.clone(), false), - }, - crate::agent::turn_request::TurnDelivery { - cancellation: Some(cancellation.clone()), - on_delta: Some(delta_tx.clone()), - on_tool_call: Some(tool_event_tx.clone()), - }, - ) - .await - .map(|(outcome, trace)| (outcome.into_text(), trace)) - }), - ) - .await; - - match result { - // ── Success ─────────────────────────────────────── - Ok((resp, trace)) => (TurnOutcome::Success(resp), Some(trace)), - // ── Cancelled (Ctrl+C) ──────────────────────────── - Err(ref e) if is_tool_loop_cancelled(e) || cancellation.is_cancelled() => { - if let Some(ref d_id) = draft_id { - let _ = terminal.cancel_draft("user", d_id).await; - } - // S2-A: user-driven cancel — distinguished from real - // failures so the reducer emits `StreamCancelled` (no - // Error hook fan-out) instead of `StreamFailed`. - (TurnOutcome::Cancelled, None) - } - // ── Other errors ────────────────────────────────── - Err(e) => { - if let Some(ref d_id) = draft_id { - let _ = terminal.cancel_draft("user", d_id).await; - } - // The one-shot reads this note: a send-admission refusal - // exits 2 with its reply, any other failure exits 1. - one_shot::note_turn_failure(chat_turn_binding.as_deref(), &e); - let err_text = e.to_string(); - super::output::print_turn_failure(plain_mode, &err_text); - if plain_mode { - plain_mode_turn_failed = true; - } - // Phase E (5a-4): same dual_write_guard reasoning as the timeout branch. - if !dual_write_guard.is_active() { - hooks - .emit(HookEvent::Error, payload_error("chat-turn", &err_text)) - .await; - } - // S2-A: generic provider/loop error — retryable hint is - // false (the caller already chose to surface and continue; - // retry policy is owned by upstream once tooling lands). - ( - TurnOutcome::FailedWithError { - err: err_text, - retryable: false, - }, - None, - ) - } - } - }; - - // ── Finalize streaming ──────────────────────────────────── - // Deregister this turn's cancellation token. - // - // S2-B Step 3: on the legacy path the reducer also clears `state.control.active_cancel` when - // Stream{Completed,Cancelled,Failed} is dispatched (lines 1886-1911 below); the legacy Arc is - // only a fallback in Off/Both mode (the external Ctrl+C handler reads it). - #[cfg(not(feature = "terminal-tui"))] - { - *active_cancel.lock() = None; - } - - // Drop our channel senders so background tasks receive channel close - drop(delta_tx); - drop(tool_event_tx); - if let Some(handle) = draft_updater { - let _ = handle.await; - } - let _ = tool_event_forwarder.await; - - // Step 5b dual write: dispatch the matching stream-termination Action for the turn outcome. - // Only when draft_id exists can the reducer match stream.draft and clean it up; otherwise this - // is a no-op. - // - // S2-A: split the previous single-pronged "Failed → StreamCancelled" - // fallback. Order is **critical**: cancellation is detected up the - // stack via `is_tool_loop_cancelled` / `cancellation.is_cancelled()` - // and surfaces as `TurnOutcome::Cancelled`. Real errors (timeout / - // context overflow / provider error) surface as `FailedWithError` and - // map to `StreamFailed { err, retryable }` so the reducer emits the - // `NotifyHook(Error) + LogTrace + RequestRedraw` effect chain. - // - // T3-3-fixA P0-1: the StreamCompleted of the Success branch was moved down to be dispatched - // after RecordAssistantTurn, so that when the reducer builds the SaveSession snapshot - // session.turns already contains this turn's assistant message. Cancelled / FailedWithError - // write no assistant turn, so their dispatch position is unchanged. - match &turn_outcome { - TurnOutcome::Success(..) => {} - TurnOutcome::Cancelled => { - if let Some(ref d_id) = draft_id { - let _ = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::StreamCancelled { draft_id: d_id.clone() }, - "chat.stream_cancelled", - ); - } - if let Err(error) = finalize_chat_non_success_turn( - chat_turn_binding.as_deref(), - &memory_fabric, - &turn_run_id, - route_scope.clone(), - crate::agent::terminal::TurnTerminalStatus::Cancelled, - None, - provider_started_at, - "legacy tool loop cancelled", - &config.cost, - &config.workspace_dir, - ) - .await - { - if chat_turn_binding.as_ref().is_some_and(|binding| binding.is_decided()) { return Err(error); } - tracing::warn!(error = %crate::agent::diagnostics::error_class(&error), "Failed to commit shared cancelled Chat terminal event"); - } - } - TurnOutcome::FailedWithError { err, retryable } => { - if let Some(ref d_id) = draft_id { - let _ = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::StreamFailed { - draft_id: d_id.clone(), - err: err.clone(), - retryable: *retryable, - }, - "chat.stream_failed", - ); - } - // The terminal records the loop failure. Decided turns retain - // only observed provider attempts in their owning trace. - if let Err(error) = finalize_chat_non_success_turn( - chat_turn_binding.as_deref(), - &memory_fabric, - &turn_run_id, - route_scope.clone(), - crate::agent::terminal::TurnTerminalStatus::Failed, - None, - provider_started_at, - &format!("legacy tool loop failed: {err}"), - &config.cost, - &config.workspace_dir, - ) - .await - { - if chat_turn_binding.as_ref().is_some_and(|binding| binding.is_decided()) { return Err(error); } - tracing::warn!(error = %crate::agent::diagnostics::error_class(&error), "Failed to commit shared failed Chat terminal event"); - } - surface_turn_elapsed_message( - &chat_dispatcher, - sessions_redraw_handle.as_ref(), - "failed", - provider_started_at, - chrono::Utc::now(), - ); - } - } - let inline_view_changed = inline_compaction.compacted() || inline_view_before_turn.changed_in(&history); - // If the turn failed or was cancelled, skip response processing - let (response, turn_trace) = match turn_outcome { - TurnOutcome::Success(resp) => (resp, successful_trace.context("successful Chat outcome has no serving trace")?), - TurnOutcome::Cancelled => { - let settled = settle_aborted_turn(&chat_dispatcher, &turn_signal, admission).await?; - provider_view_after_settled_abort( - &mut history, - &settled, - inline_compaction_epoch_before_preflight, - inline_view_changed, - Some(history_len_before_user_turn), - ); - finish_inline_provider_turn(&mut provider_turn_workers, provider_turn_task_id, None); - gate_cancelled_provider_turn_finalization( - &mut turn_scheduler, - &mut history_commit_coordinator, - &mut provider_turn_workers, - provider_turn_task_id, - "legacy tool loop cancelled", - ); - publish_main_queue_status(&chat_dispatcher, &turn_scheduler); - publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); - continue; - } - TurnOutcome::FailedWithError { err, .. } => { - let settled = settle_aborted_turn(&chat_dispatcher, &turn_signal, admission).await?; - provider_view_after_settled_abort( - &mut history, - &settled, - inline_compaction_epoch_before_preflight, - inline_view_changed, - Some(history_len_before_user_turn), - ); - finish_inline_provider_turn(&mut provider_turn_workers, provider_turn_task_id, None); - gate_failed_provider_turn_finalization( - &mut turn_scheduler, - &mut history_commit_coordinator, - &mut provider_turn_workers, - provider_turn_task_id, - history.len(), - format!("legacy tool loop failed: {err}"), - ); - publish_main_queue_status(&chat_dispatcher, &turn_scheduler); - publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); - continue; - } - }; - if let Some(binding) = chat_turn_binding.as_ref() { - binding.capture_trace(&turn_trace)?; - } - // FIX-P0-30/31: build the provider outcome from the loop's real - // attribution trace. When the trace carries the actual serving - // provider/model + attempts (the `ReliableProvider` path), use them so a - // retry/fallback is recorded as `FallbackSuccess` and `final_model` - // reflects what truly executed. Fall back to the routed - // `decision.selected.{provider,model}` only when no trace is available - // (e.g. a provider whose `chat_traced` default produced a synthetic - // attribution). - let provider_outcome = { - let has_trace = turn_trace.final_model.is_some() && !turn_trace.attempts.is_empty(); - if has_trace { - let final_provider = turn_trace - .final_provider - .unwrap_or_else(|| route_decision.selected.provider.clone()); - let final_model = turn_trace - .final_model - .unwrap_or_else(|| route_decision.selected.model.clone()); - ProviderExecutionOutcome::from_trace_with_usage( - &route_decision, - turn_trace.attempts, - final_provider, - final_model, - provider_started_at, - chrono::Utc::now(), - // FIX #2: a fallback on any earlier (tool-call) turn must - // surface as FallbackSuccess even when the final turn is clean. - turn_trace.any_turn_had_fallback, - turn_trace.tokens_used, - ) - } else { - ProviderExecutionOutcome::success_for_decision_with_usage( - &route_decision, - provider_started_at, - turn_trace.tokens_used, + // The one-shot outcome is read before teardown; its failure is reported + // as that outcome, not as the interactive "turns failed" summary. + let one_shot_reply = one_shot.as_ref().map(|_| { + one_shot::outcome( + one_shot_binding.as_deref(), + plain_mode_turn_failed, + one_shot_task_id.is_some_and(|task_id| turn_signal.history_commit_acknowledged(task_id)), + // The committed turns' stored text, never the provider view (which + // renders each reply with its tool evidence). + &session_turns_to_history(&chat_dispatcher.session_reader().acked().session), ) - } - }; - surface_turn_elapsed_message( - &chat_dispatcher, - sessions_redraw_handle.as_ref(), - "completed", - provider_outcome.started_at, - provider_outcome.finished_at, - ); - // d04 §10 G7: emit a control-ladder trace carrying the structured - // decision_id / final_provider / final_model / attempts_count so a - // `decision_id` join links the routing decision to the provider that - // actually served the request. Best-effort (failures logged, not fatal). - { - let status_label = match &provider_outcome.status { - crate::llm::route_decision::ExecutionStatus::Success => "success", - crate::llm::route_decision::ExecutionStatus::FallbackSuccess => "fallback_success", - crate::llm::route_decision::ExecutionStatus::AllFailed { .. } => "all_failed", - }; - let attempts_count = u8::try_from(provider_outcome.attempts.len()).unwrap_or(u8::MAX); - crate::runtime::control_ladder::append_provider_outcome_trace( - std::path::Path::new(&config.workspace_dir), - &provider_outcome.decision_id, - &provider_outcome.final_provider, - &provider_outcome.final_model, - attempts_count, - status_label, - ); - } - - // ── P2-12: Mirror reasoning content into the TUI as a folded card. ── - // - // Reasoning is separated upstream at the provider layer (P0-2) and - // persisted into the assistant-history JSON via - // `build_native_assistant_history`. We scan the slice of history - // produced during this turn for `reasoning_content` fields, aggregate - // them, and push a single folded `Reasoning` card to the TUI mirror. - // Empty buffers are skipped by `push_reasoning`. This does NOT touch - // the visible delta stream — the user-facing assistant text remains - // the only thing rendered in the streaming draft. - #[cfg(feature = "terminal-tui")] - { - let turn_slice = history.get(history_len_before_tools..).unwrap_or(&[]); - let aggregated = collect_reasoning_from_history_slice(turn_slice); - if !aggregated.is_empty() { - // S4-B: the mirror push_reasoning is deleted; the reducer - // (reduce_stream_completed) is the single source that pushes the Reasoning card. - if let Some(tx) = redraw_tx_for_main.as_ref() { - let _ = tx.try_send(()); - } - } - } - - increment_recalled_useful_counts(mem.as_ref(), &mem_context.ids).await; - - // ── Sanitize response: strip tool-call XML/JSON artifacts ── - let response = sanitize_channel_response(&response, &tools_registry); - - if crate::agent::response_guard::is_empty_assistant_response(&response, false) { - let terminal_usage = match finalize_chat_success_turn( - chat_turn_binding.as_deref(), - &memory_fabric, - &chat_session_key, - &turn_run_id, - provider_name, - model_name, - route_scope.clone(), - provider_outcome.clone(), - None, - history.len(), - "legacy tool loop completed with empty response", - &config.cost, - &config.workspace_dir, - ) - .await - { - Ok(receipt) => receipt.into_session_usage(), - Err(error) => { - tracing::error!(error = %crate::agent::diagnostics::error_class(&error), "Chat terminal persistence is unconfirmed"); - return Err(error); - } - }; - let inline_payload = inline_provider_turn_payload(history.len(), 0, terminal_usage.as_ref()); - // Usage first (inside the commit's acknowledged revision), then - // the awaited commit (the user turn was recorded at admission). - if let Err(error) = dispatch_final_usage( - &chat_dispatcher, - &turn_signal, - &mut turn_scheduler, - provider_turn_task_id, - terminal_usage, - "chat.provider_usage_recorded_empty_response", - ) - .await - { - anyhow::bail!("Chat stopped after an unconfirmed history commit: {error}"); - } - let Some(commit_task_id) = provider_turn_task_id else { - anyhow::bail!("chat turn has no provider task; its history cannot be committed"); - }; - if let Err(error) = dispatch_ordered_provider_turn_commit_and_wait( - &chat_dispatcher, - &turn_signal, - commit_task_id, - OrderedCommitTerminal::TurnCommitRequested { draft_id: draft_id.as_deref() }, - &user_input, - "", - true, - false, + }); + let finished = startup::finish_chat_session( + &shutdown, + &dispatcher_stop, + chat_dispatcher, + dispatcher_handle, + #[cfg(feature = "terminal-tui")] + &terminal_guard, + plain_mode_turn_failed && one_shot.is_none(), ) - .await - { - anyhow::bail!("Chat stopped after an unconfirmed history commit: {error}"); - } - super::compaction::reconcile_inline_turn(&mut history, &chat_dispatcher); - if let Some(ref d_id) = draft_id - && let Err(e) = terminal.cancel_draft("user", d_id).await - { - let (error_len, error_sha256) = crate::agent::diagnostics::error_log_digest(&e); - tracing::debug!(error_len, error_sha256, "cancel empty-response draft failed"); - } - surface_session_message( - &chat_dispatcher, - sessions_redraw_handle.as_ref(), - crate::agent::response_guard::EMPTY_ASSISTANT_RESPONSE_MESSAGE, - ); - #[cfg(feature = "terminal-tui")] - if let Some(tx) = redraw_tx_for_main.as_ref() { - let _ = tx.try_send(()); - } - observer.record_event(&ObserverEvent::TurnComplete); - if !dual_write_guard.is_active() { - hooks - .emit( - HookEvent::TurnComplete, - serde_json::json!({ - "mode": "chat", - "response_chars": 0, - }), - ) - .await; - } - finish_inline_provider_turn(&mut provider_turn_workers, provider_turn_task_id, Some(inline_payload)); - mark_provider_turn_completed( - &mut turn_scheduler, - &mut history_commit_coordinator, - &mut provider_turn_workers, - provider_turn_task_id, - history.len(), - "legacy tool loop completed with empty response", - ); - publish_main_queue_status(&chat_dispatcher, &turn_scheduler); - publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); - continue; - } - - // Persist only the user-facing assistant response. Tool results already - // live in structured history entries; adding a synthetic summary here - // can teach the model to emit that internal marker as a final answer. - // The loop already appended its final reply: that slot becomes the - // committed (sanitized) response, so the next request carries the - // reply once, as the saved session does. - match history.last_mut() { - Some(last) if last.role == "assistant" => *last = ChatMessage::assistant(&response), - _ => history.push(ChatMessage::assistant(&response)), - } - let terminal_usage = match finalize_chat_success_turn( - chat_turn_binding.as_deref(), - &memory_fabric, - &chat_session_key, - &turn_run_id, - provider_name, - model_name, - route_scope.clone(), - provider_outcome.clone(), - Some(response.clone()), - history.len(), - "legacy tool loop completed", - &config.cost, - &config.workspace_dir, - ) - .await - { - Ok(receipt) => receipt.into_session_usage(), - Err(error) => { - tracing::error!(error = %crate::agent::diagnostics::error_class(&error), "Chat terminal persistence is unconfirmed"); - return Err(error); - } - }; - - - // S2-B Step 4: RecordAssistantTurn(response) is dispatched at the same point as the legacy - // `history.push(ChatMessage::assistant(...))` — so the reducer's session.history is - // byte-for-byte aligned with the legacy history. The old dispatch at line 2055 below used - // sanitized_response, whose content differs from history.push — from S2-B Step 4 on it is - // dispatched here with response instead, and the old dispatch below is deleted. - // The final usage goes first so the commit's acknowledged revision - // carries it; the ordered commit then sends RecordAssistantTurn and - // the awaited TurnCommitRequested (the user turn was recorded at - // admission). - let inline_payload = - inline_provider_turn_payload(history.len(), response.chars().count(), terminal_usage.as_ref()); - if let Err(error) = dispatch_final_usage( - &chat_dispatcher, - &turn_signal, - &mut turn_scheduler, - provider_turn_task_id, - terminal_usage, - "chat.provider_usage_recorded", - ) - .await - { - anyhow::bail!("Chat stopped after an unconfirmed history commit: {error}"); - } - let Some(commit_task_id) = provider_turn_task_id else { - anyhow::bail!("chat turn has no provider task; its history cannot be committed"); - }; - if let Err(error) = dispatch_ordered_provider_turn_commit_and_wait( - &chat_dispatcher, - &turn_signal, - commit_task_id, - OrderedCommitTerminal::TurnCommitRequested { draft_id: draft_id.as_deref() }, - &user_input, - &response, - false, - false, - ) - .await - { - anyhow::bail!("Chat stopped after an unconfirmed history commit: {error}"); - } - super::compaction::reconcile_inline_turn(&mut history, &chat_dispatcher); - #[cfg(feature = "terminal-tui")] - if let Some(tx) = redraw_tx_for_main.as_ref() { - let _ = tx.try_send(()); - } - - // ── Extract and display media markers (images, documents, etc.) ── - let (clean_response, media_items) = extract_outgoing_media(&response)?; - for (media_type, path) in &media_items { - if media_type == "IMAGE" && std::path::Path::new(path).exists() { - if let Err(e) = terminal_proto::display_image(path) { - tracing::debug!(error = %crate::agent::diagnostics::error_class(&e), "Image display failed"); - println!(" [image: {path}]"); - } - } else { - println!(" [{media_type}: {path}]"); - } - } - // Use the cleaned response (media markers removed) for display - let display_response = if media_items.is_empty() { - &response - } else { - &clean_response - }; - - // Finalize the streaming draft with the full response. - // - // Idempotency contract (P1-4): - // When a draft exists, the streamed deltas have already painted the - // full response on screen via `update_draft`. `finalize_draft` is - // only a structural close (locking in the final text for non-TTY - // channels such as Telegram). On failure we therefore MUST NOT - // re-send the whole message — that would duplicate output that the - // user has already seen via the live stream. We log a warning and - // carry on; the assistant turn is already in `history`, so the - // conversation state remains consistent. - // - // The "no draft" branch is the genuine first-send path (drafts were - // never created, e.g. `send_draft` failed earlier and returned - // `None`), so a normal `send` is correct and not a duplicate. - if let Some(ref d_id) = draft_id { - if let Err(e) = terminal.finalize_draft("user", d_id, display_response).await { - if should_resend_on_finalize_failure(true) { - let rendered = render_response(display_response); - let _ = terminal.send(&SendMessage::new(rendered, "user")).await; - } else { - tracing::warn!( - error = %crate::agent::diagnostics::error_class(&e), - "finalize_draft failed; suppressing resend to preserve idempotency (user already saw streamed content)" - ); - } - } - } else { - // No draft was created — send as a complete message with highlighting. - let rendered = render_response(display_response); - let _ = terminal.send(&SendMessage::new(rendered, "user")).await; - } - - // P0-1 fix: in Both/Redux mode the old path is gated by dual_write_guard. - // The Redux reducer's SaveSession effect already raised the guard inside execute_real, and - // when the guard is active the old path skips save_session + hooks.emit(TurnComplete), which - // prevents double hook/webhook firing (hooks/webhooks are not idempotent and really would - // fire twice). - // In Off mode the guard is always false and the old path writes alone as usual. - // The guard is turn-level (not effect-level): once Redux has executed either - // SaveSession or NotifyHook during a turn, the guard is active and every later write of the - // old path is suppressed. - if !dual_write_guard.is_active() { - observer.record_event(&ObserverEvent::TurnComplete); - hooks - .emit( - HookEvent::TurnComplete, - serde_json::json!({ - "mode": "chat", - "response_chars": response.chars().count(), - }), - ) - .await; - } else { - // Guard active: the Redux path already handled hooks.emit. - tracing::debug!("P0-1: dual_write_guard active — legacy path skipping hooks.emit(TurnComplete)"); - // observer.record_event is still called (the observer is only a local counter, with no - // external side effects). - observer.record_event(&ObserverEvent::TurnComplete); - } - finish_inline_provider_turn(&mut provider_turn_workers, provider_turn_task_id, Some(inline_payload)); - mark_provider_turn_completed( - &mut turn_scheduler, - &mut history_commit_coordinator, - &mut provider_turn_workers, - provider_turn_task_id, - history.len(), - "legacy tool loop completed", - ); - publish_main_queue_status(&chat_dispatcher, &turn_scheduler); - publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); - // The reply this turn produced *is* the answer to the assignment, so it - // is what goes back. Reaching here at all is what distinguishes a turn - // that answered from every other way the body can end. - if let Some(guard) = assignment_guard.as_mut() { - guard.completed(&response); - } - } - - // ── Child-session shutdown on exit (Phase C) ───────────────── - // Snapshot every child session still tracked at exit, persist summaries for - // live sessions as interrupted, then terminate and clear every child - // registry through the single session owner. This covers running agents, - // NeedsInput agents, background shells, and interactive PTYs uniformly. - // A lost exit summary does not stop the cleanup below; it is returned - // once teardown has finished. - let exit_summaries = shutdown_child_sessions_for_exit(&mut chat_sessions, &chat_dispatcher, &turn_signal) - .await - .map(drop); - session_rings.clear(); - withdraw_assignment_enrolment( - assignment_enrolment.as_ref(), - &chat_dispatcher, - sessions_redraw_handle.as_ref(), - ) - .await; - - // The one-shot outcome is read before teardown; its failure is reported - // as that outcome, not as the interactive "turns failed" summary. - let one_shot_reply = one_shot.as_ref().map(|_| { - one_shot::outcome( - one_shot_binding.as_deref(), - plain_mode_turn_failed, - one_shot_task_id.is_some_and(|task_id| turn_signal.history_commit_acknowledged(task_id)), - // The committed turns' stored text, never the provider view (which - // renders each reply with its tool evidence). - &session_turns_to_history(&chat_dispatcher.session_reader().acked().session), - ) - }); - let finished = startup::finish_chat_session( - &shutdown, &dispatcher_stop, chat_dispatcher, dispatcher_handle, - #[cfg(feature = "terminal-tui")] &terminal_guard, - plain_mode_turn_failed && one_shot.is_none(), - ).await; - // The dispatcher is drained now: a save that failed during exit, - // including one only seen while draining, has latched by this point, and - // `/exit` or EOF must not report success over it. - exit_summaries?; - turn_signal.ensure_history_commits_healthy()?; - finished?; - one_shot_reply.transpose() - }).await; + .await; + // The dispatcher is drained now: a save that failed during exit, + // including one only seen while draining, has latched by this point, and + // `/exit` or EOF must not report success over it. + exit_summaries?; + turn_signal.ensure_history_commits_healthy()?; + finished?; + one_shot_reply.transpose() + }) + .await; turn_service .shutdown(std::time::Instant::now() + Duration::from_secs(2)) .await; diff --git a/src/chat/run/commands.rs b/src/chat/run/commands.rs new file mode 100644 index 000000000..6df02e61d --- /dev/null +++ b/src/chat/run/commands.rs @@ -0,0 +1,1429 @@ +{ + // A one-shot message is literal model input (D4): it skips every + // quit, copy, queue, slash and bang command below. + if one_shot.is_none() { + // Handle /quit and /exit immediately + if is_chat_quit_command(user_input.as_str()) { + break 'chat; + } + + if is_copy_command(&user_input) { + match select_copy_content(&chat_session.session(), &user_input) { + Ok(selection) if plain_mode => { + println!("{}", selection.content); + let _ = std::io::stdout().flush(); + } + Ok(selection) => match terminal_proto::copy_to_clipboard(&selection.content) { + Ok(()) => emit_chat_output(©_success_message(&selection)), + Err(error) => emit_chat_output(&format!("Copy failed: {error}")), + }, + Err(message) => emit_chat_output(&message), + } + continue; + } + + if is_queue_command(&user_input) { + emit_chat_output(&format_input_backlog_report(&input_backlog, &turn_scheduler, 8)); + continue; + } + + if is_workers_command(&user_input) { + if let Some((output, signal_cancel)) = provider_workers_cancel_output_for_input( + &msg, + &user_input, + &mut turn_scheduler, + &mut provider_turn_workers, + None, + ) { + emit_chat_output(&output); + publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); + dispatch_provider_worker_cancel_signal(&chat_dispatcher, signal_cancel); + } else { + emit_chat_output(&format_provider_worker_report(&provider_worker_status( + &provider_turn_workers, + ))); + } + continue; + } + + // BUG-07: `/model ` switches the model online (same provider, different model). + // + // Intercepted before commands::dispatch, because taking effect requires (a) rewriting the main + // loop's `current_model_owned` (which affects the system prompt / event records of later + // turns), (b) writing the hot-swap slot of EffectDeps (which affects the model the dispatcher + // subtask actually requests on the next turn), and (c) dispatching ModelChanged so the reducer + // updates session.model → the status bar reflects it immediately. A bare `/model` (no + // argument) is still handed to dispatch, which shows the current model. + if user_input == "/model save-default" { + let saved = super::model_commands::save_default(&config, provider_name, ¤t_model_owned, &provider_runtime_options).await; + match saved { + Ok(()) => emit_chat_output("Saved the current model and level as the default."), + Err(error) => emit_chat_output(&format!("Cannot save model default: {}", providers::sanitize_api_error(&error.to_string()))), + } + continue; + } + let model_command = user_input.strip_prefix("/model "); + let level_command = user_input.strip_prefix("/level "); + if model_command.is_some() || level_command.is_some() { + let (new_model, candidate_options) = match super::model_commands::selection(&user_input, ¤t_model_owned, provider_name, &provider_runtime_options) { + Ok(selection) => selection, + Err(error) => { emit_chat_output(&crate::security::redaction::redact_provider_text(&format!("{error:#}"))); continue; } + }; + let new_model = new_model.as_str(); + let rebuilt = chat_model_switch(&config, provider_name, new_model).and_then(|()| { + chat_provider_chain( + &config, + provider_name, + configured_provider_name, + new_model, + &candidate_options, + ) + }); + match rebuilt { + Ok((_connection, built)) => { + let new_provider_arc: Arc = Arc::from(built); + let binding = match binding::ChatProviderBinding::capture( + &ctx.config_generation, + &new_provider_arc, + provider_name, + new_model, + ) { + Ok(binding) => binding, + Err(error) => { + emit_chat_output(&format!( + "Cannot bind model selection: {}", + providers::sanitize_api_error(&error.to_string()) + )); + continue; + } + }; + provider_runtime_options = candidate_options; + provider_binding = binding; + provider = Arc::clone(&new_provider_arc); + #[cfg(feature = "terminal-tui")] + if let Some(slot) = provider_slot.as_ref() { + slot.set(Arc::clone(&new_provider_arc)); + } + current_model_owned = new_model.to_string(); + #[cfg(feature = "terminal-tui")] + if let Some(slot) = model_slot.as_ref() { + slot.set(Arc::from(new_model)); + } + #[cfg(feature = "terminal-tui")] + { + chat_mirror.lock().model = new_model.to_string(); + } + if let Err(error) = await_metadata_change( + &chat_dispatcher, + &turn_signal, + &mut chat_session, + crate::chat::action::Action::ModelChanged { + model: new_model.to_string(), + }, + ) + .await + { + emit_chat_output(&format!("Model switch was not saved: {error}")); + continue; + } + // emit_chat_output already nudges the renderer (try_send on + // the TUI redraw channel) so the status bar repaints. + emit_chat_output(&format!( + "Switched model to {new_model} (provider {}). Applies from the next turn.", + providers::redact_endpoint_userinfo(&provider_name) + )); + } + Err(e) => { + emit_chat_output(&format!("Cannot switch to '{new_model}': {e}")); + } + } + continue; + } + + // Bug #3: `/provider [model]` — hot-switch the provider within a session. + // + // Like `/model`, it is intercepted before commands::dispatch, because taking effect requires + // the main loop to rebuild the provider instance and rewrite several pieces of runtime state: + // (a) rebuild the `Arc` from the new provider's auth/base/protocol, replacing + // the `provider` handle the legacy tool-loop path's `run_turn` call uses; + // (b) `set()` it into `provider_slot` (so the Redux driver subtask reads the new provider on + // its next turn); + // (c) rewrite `current_provider_owned` (which affects the system prompt / events / snapshot + // of later turns) and validate that the current model is valid for the new provider (if + // not, the command must carry a compatible model: `/provider `). + // Credential resolution: when switching to a provider that is not the startup primary we pass + // `api_key=None`/`api_url=None` and let the provider resolve its own credentials from the auth + // profile / environment (reusing the startup `config.api_key` only makes sense for the + // original primary); when switching back to the original primary we reuse + // `config.api_key`/`config.api_url`. + if let Some(raw) = user_input.strip_prefix("/provider ") { + let mut parts = raw.split_whitespace(); + // Own the parsed tokens up front so we can freely reassign the runtime + // provider/model state below without lingering borrows. + let new_provider = parts.next().unwrap_or_default().to_string(); + let requested_model = parts.next().map(str::to_string); + if new_provider.is_empty() { + emit_chat_output("Usage: /provider [model]"); + continue; + } + // Decide the model effective after the switch: prefer the one given explicitly on the + // command, otherwise keep the current model (if compatible). + let candidate_model = requested_model.unwrap_or_else(|| current_model_owned.clone()); + if let Err(e) = chat_model_switch(&config, &new_provider, &candidate_model) { + let shown = providers::redact_endpoint_userinfo(&new_provider); + emit_chat_output(&format!( + "Cannot switch to provider '{shown}': model '{candidate_model}' is incompatible ({}). \ +Retry with a compatible model: /provider {shown} ", + providers::redact_endpoint_userinfo(&e.to_string()) + )); + continue; + } + // When switching to a provider other than the configured primary, do not carry over the + // primary's explicit credentials/URL; let the new provider resolve its own (so provider + // A's key is never fed to provider B). + match chat_provider_chain( + &config, + &new_provider, + configured_provider_name, + &candidate_model, + &provider_runtime_options, + ) { + Ok((_switch_connection, built)) => { + let new_provider_arc: Arc = Arc::from(built); + let next_binding = match binding::ChatProviderBinding::capture( + &ctx.config_generation, &new_provider_arc, &new_provider, &candidate_model, + ) { + Ok(binding) => binding, + Err(error) => { + emit_chat_output(&format!("Cannot bind provider selection: {}", providers::sanitize_api_error(&error.to_string()))); + continue; + } + }; + provider_binding = next_binding; + // (a) the legacy path handle + provider = Arc::clone(&new_provider_arc); + // (b) Redux driver slot + #[cfg(feature = "terminal-tui")] + if let Some(slot) = provider_slot.as_ref() { + slot.set(Arc::clone(&new_provider_arc)); + } + // (c) the runtime provider / model names + let model_changed = candidate_model != current_model_owned; + if model_changed { + current_model_owned = candidate_model.clone(); + #[cfg(feature = "terminal-tui")] + if let Some(slot) = model_slot.as_ref() { + slot.set(Arc::from(candidate_model.as_str())); + } + } + current_provider_owned = new_provider.clone(); + #[cfg(feature = "terminal-tui")] + { + let mut mirror = chat_mirror.lock(); + mirror.provider = new_provider.clone(); + if model_changed { + mirror.model = candidate_model.clone(); + } + } + // (d) the session ledger: dispatch ProviderChanged so the reducer updates + // session.provider (and session.model when needed), making the status bar / UI + // snapshot reflect the new provider immediately. All three places (the legacy + // provider handle, the Redux provider_slot and the session ledger) stay + // consistent this way. When switching providers also changes the model, both go + // into the same action (no separate ModelChanged needed). + if let Err(error) = await_metadata_change( + &chat_dispatcher, + &turn_signal, + &mut chat_session, + crate::chat::action::Action::ProviderChanged { + provider: new_provider.clone(), + model: model_changed.then(|| candidate_model.clone()), + }, + ) + .await + { + emit_chat_output(&format!("Provider switch was not saved: {error}")); + continue; + } + let model_note = if model_changed { + format!(" (model set to {candidate_model})") + } else { + String::new() + }; + emit_chat_output(&format!( + "Switched provider to {}{model_note}. Applies from the next turn.", + providers::redact_endpoint_userinfo(&new_provider) + )); + } + Err(e) => { + emit_chat_output(&format!( + "Cannot switch to provider '{}': {}", + providers::redact_endpoint_userinfo(&new_provider), + providers::redact_endpoint_userinfo(&e.to_string()) + )); + } + } + continue; + } + + // BUG-07: the model name effective for this iteration (borrowed from the mutable owned + // value). The `/model` interception above already handled its case and called `continue`, so + // the shadowed `model_name` here is always the newest value and covers every later use of + // `model_name` (system prompt / fabric / snapshot). + let model_name: &str = current_model_owned.as_str(); + + // BUG-04: `!cmd` bang mode — run the rest of the line directly as a + // shell command (matching the footer hint "! for bash") instead of + // sending it to the LLM. Output is shown inline; the LLM is not + // involved. A bare `!` is ignored. The shell tool already applies the + // direct host execution + workspace cwd, so bang commands share the same host FS view + // as file_write (see BUG-02). + if let Some(bang_cmd) = user_input.strip_prefix('!') { + let bang_cmd = bang_cmd.trim(); + if bang_cmd.is_empty() { + emit_chat_output("Usage: ! (runs directly in the workspace)"); + continue; + } + let shell_tool = tools_registry.iter().find(|t| t.supports_name("shell")); + match shell_tool { + Some(tool) => { + let args = serde_json::json!({ "command": bang_cmd }); + match tool.execute_named("shell", args).await { + Ok(result) => { + let mut out = String::new(); + if !result.output.is_empty() { + out.push_str(&result.output); + } + if let Some(err) = result.error.as_ref().filter(|e| !e.is_empty()) { + if !out.is_empty() { + out.push('\n'); + } + out.push_str(err); + } + if out.is_empty() { + out = if result.success { + "(no output)".to_string() + } else { + "(command failed with no output)".to_string() + }; + } + emit_chat_output(&out); + } + Err(e) => emit_chat_output(&format!("Shell error: {e}")), + } + } + None => emit_chat_output("Shell tool is not available in this session."), + } + continue; + } + + // Both reset commands save the current state and switch every + // session-scoped UI/model ledger to a fresh identity. Stored memories + // remain intact, including those owned by other sessions or channels. + if matches!(user_input.as_str(), "/new" | "/clear") { + match start_new_chat_session( + ChatSwitchCtx { + chat_session: &mut chat_session, + commits: &turn_signal, + chat_session_key: &mut chat_session_key, + fabric_turn_seq: &mut fabric_turn_seq, + history: &mut history, + approval_router: approval_router.as_ref(), + pending_chat_rewind: &mut pending_chat_rewind, + pending_diff_apply: &mut pending_diff_apply, + chat_sessions: &mut chat_sessions, + ignored_session_events: &mut ignored_session_events, + session_rings: &mut session_rings, + reported_sessions: &mut reported_sessions, + announced_started_sessions: &mut announced_started_sessions, + last_sessions_summary: &mut last_sessions_summary, + last_sessions_entries: &mut last_sessions_entries, + attached_follow: &mut attached_follow, + attached_follow_seq: &mut attached_follow_seq, + chat_dispatcher: &chat_dispatcher, + redraw_handle: sessions_redraw_handle.as_ref(), + config: &config, + provider_name, + model_name, + skills: &skills, + native_tools, + #[cfg(feature = "terminal-tui")] + chat_mirror: &chat_mirror, + }, + ) + .await + { + Ok(message) => emit_chat_output(&message), + Err(e) => emit_chat_output(&e.to_string()), + } + continue; + } + + // `/compact` is an explicit request: it compacts whatever lies beyond + // the kept window, through the same budget the preflight uses. + if matches!(user_input.as_str(), "/compact") { + let compact_context = provider_binding + .as_ref() + .ok_or_else(|| anyhow::anyhow!("chat provider binding is missing"))? + .effective_compaction(); + let compact_config = tool_surface_reserve.reserved_config(&compact_context.config); + let compact_envelope = + super::chat_runtime_envelope(&config.workspace_dir.to_string_lossy(), &chat_session_key); + let (compact_turns_before, compact_tokens_before) = + super::compaction::chat_history_turns_and_tokens(&history); + let compact_outcome = super::compaction::run_manual_compact( + super::compaction::ManualCompact { + history: &mut history, + chat_session: &chat_session.session(), + provider: provider.as_ref(), + model: model_name, + config: &compact_config, + memory: Arc::clone(&mem), + envelope: &compact_envelope, + chat_dispatcher: &chat_dispatcher, + commits: &turn_signal, + }, + &mut |text: &str| emit_chat_output(text), + ) + .await; + emit_chat_output(&compact_outcome.feedback(compact_turns_before, compact_tokens_before, &compact_config)); + #[cfg(feature = "terminal-tui")] + refresh_context_budget_for_tui( + &history, + &compact_context.config, + &tool_surface_reserve, + redraw_tx_for_main.is_some(), + &chat_mirror, + &chat_dispatcher, + ); + continue; + } + + // Dispatch other slash commands + { + let cmd_ctx = commands::CommandContext { + model_name, + provider_name, + chat_session: &chat_session.session(), + tools_registry: &tools_registry, + mem: mem.as_ref(), + }; + match commands::dispatch(&user_input, &cmd_ctx).await { + commands::CommandResult::Handled => continue, + commands::CommandResult::HandledWithOutput(text) => { + emit_chat_output(&text); + continue; + } + commands::CommandResult::Quit => break 'chat, + commands::CommandResult::SetMode(mode) => { + // The reducer saves a changed mode; success is reported + // only after its acknowledgement. + if let Err(error) = await_metadata_change( + &chat_dispatcher, + &turn_signal, + &mut chat_session, + crate::chat::action::Action::ModeChanged(mode), + ) + .await + { + emit_chat_output(&format!("Mode unchanged: {error}")); + continue; + } + #[cfg(feature = "terminal-tui")] + { + chat_mirror.lock().chat_mode = mode; + } + let msg = match mode { + commands::ChatMode::Plan => { + "Switched to plan mode (read-only tools only — write/shell/git_commit will be simulated)" + } + commands::ChatMode::Edit => "Switched to edit mode (default — write tools enabled)", + commands::ChatMode::Auto => "Switched to auto mode (does not override [autonomy])", + }; + emit_chat_output(msg); + continue; + } + commands::CommandResult::ResumeAction(action) => { + match action { + commands::ResumeCommand::List => match saved_chat_sessions(mem.as_ref()).await { + Ok(sessions) => { + #[cfg(feature = "terminal-tui")] + if sessions_redraw_handle.is_some() { + let entries = sessions + .iter() + .map(|session| { + crate::chat::session::SavedSessionPickerEntry::from_session( + session, + &chat_session.session().id, + ) + }) + .collect::>(); + { + let mut mirror = chat_mirror.lock(); + mirror.saved_sessions_cache = entries.clone(); + mirror.saved_session_picker = + Some(crate::chat::session::SavedSessionPickerState::new(entries.clone())); + } + let _ = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::SavedSessionPickerOpened { entries }, + "chat.saved_session_picker_opened_resume", + ); + let sources = { + let mirror = chat_mirror.lock(); + crate::chat::action::Action::SlashMenuSourcesUpdated { + saved_sessions: mirror.saved_sessions_cache.clone(), + provider_model_catalog: mirror.provider_model_catalog.clone(), + } + }; + let _ = chat_dispatcher.dispatch_or_log(sources, "chat.slash_menu_sources_resume"); + if let Some(tx) = sessions_redraw_handle.as_ref() { + let _ = tx.try_send(()); + } + } else { + emit_chat_output(&format_saved_chat_sessions(&sessions)); + } + #[cfg(not(feature = "terminal-tui"))] + emit_chat_output(&format_saved_chat_sessions(&sessions)); + } + Err(e) => emit_chat_output(&format!("Failed to list saved chat sessions: {e}")), + }, + commands::ResumeCommand::Id(id) => { + match resume_saved_session_by_id( + mem.as_ref(), + &id, + ChatSwitchCtx { + chat_session: &mut chat_session, + commits: &turn_signal, + chat_session_key: &mut chat_session_key, + fabric_turn_seq: &mut fabric_turn_seq, + history: &mut history, + approval_router: approval_router.as_ref(), + pending_chat_rewind: &mut pending_chat_rewind, + pending_diff_apply: &mut pending_diff_apply, + chat_sessions: &mut chat_sessions, + ignored_session_events: &mut ignored_session_events, + session_rings: &mut session_rings, + reported_sessions: &mut reported_sessions, + announced_started_sessions: &mut announced_started_sessions, + last_sessions_summary: &mut last_sessions_summary, + last_sessions_entries: &mut last_sessions_entries, + attached_follow: &mut attached_follow, + attached_follow_seq: &mut attached_follow_seq, + chat_dispatcher: &chat_dispatcher, + redraw_handle: sessions_redraw_handle.as_ref(), + config: &config, + provider_name, + model_name, + skills: &skills, + native_tools, + #[cfg(feature = "terminal-tui")] + chat_mirror: &chat_mirror, + }, + ) + .await + { + Ok(message) => emit_chat_output(&message), + Err(e) => emit_chat_output(&e.to_string()), + } + } + commands::ResumeCommand::Last => { + if let Err(e) = + record_child_summaries_awaited(&mut chat_sessions, &chat_dispatcher, &turn_signal).await + { + emit_chat_output(&format!( + "Resume aborted: failed to save current session before switching: {e}" + )); + continue; + } + + let loaded = match load_latest_session_with_message_events( + mem.as_ref(), + memory_fabric.workspace_id(), + &config.cost, + ) + .await + { + Ok(Some(session)) => Some(session), + Ok(None) => { + emit_chat_output("No saved chat sessions to resume."); + None + } + Err(e) => { + emit_chat_output(&format!( + "Resume aborted: failed to load saved chat session: {e}" + )); + None + } + }; + let Some(loaded_session) = loaded else { + continue; + }; + + if let Err(e) = apply_chat_session_switch( + ChatSwitchCtx { + chat_session: &mut chat_session, + commits: &turn_signal, + chat_session_key: &mut chat_session_key, + fabric_turn_seq: &mut fabric_turn_seq, + history: &mut history, + approval_router: approval_router.as_ref(), + pending_chat_rewind: &mut pending_chat_rewind, + pending_diff_apply: &mut pending_diff_apply, + chat_sessions: &mut chat_sessions, + ignored_session_events: &mut ignored_session_events, + session_rings: &mut session_rings, + reported_sessions: &mut reported_sessions, + announced_started_sessions: &mut announced_started_sessions, + last_sessions_summary: &mut last_sessions_summary, + last_sessions_entries: &mut last_sessions_entries, + attached_follow: &mut attached_follow, + attached_follow_seq: &mut attached_follow_seq, + chat_dispatcher: &chat_dispatcher, + redraw_handle: sessions_redraw_handle.as_ref(), + config: &config, + provider_name, + model_name, + skills: &skills, + native_tools, + #[cfg(feature = "terminal-tui")] + chat_mirror: &chat_mirror, + }, + loaded_session, + false, + ) + .await + { + emit_chat_output(&format!("Resume aborted: {e}")); + continue; + } + + let resumed = chat_session.session(); + let title = if resumed.title.is_empty() { + "(untitled)" + } else { + resumed.title.as_str() + }; + emit_chat_output(&format!( + "Resumed saved chat session {} ({title}, {} turns).", + resumed.id, + resumed.turn_count() + )); + } + } + continue; + } + commands::CommandResult::HistoryAction(action) => { + match action { + commands::HistoryCommand::BranchList => { + emit_chat_output(&format_turn_boundaries(&chat_session.session())); + } + commands::HistoryCommand::Branch(raw) => { + let keep_turns = match parse_turn_boundary(&raw, chat_session.session().turn_count(), "branch") { + Ok(value) => value, + Err(msg) => { + emit_chat_output(&msg); + continue; + } + }; + if let Err(e) = + record_child_summaries_awaited(&mut chat_sessions, &chat_dispatcher, &turn_signal).await + { + emit_chat_output(&format!( + "Branch aborted: failed to save current session before forking: {e}" + )); + continue; + } + // The branch boundary reads the acknowledged state. + let current = chat_session.session(); + let mut branch = branched_chat_session_from(¤t, keep_turns, provider_name, model_name); + let branch_id = branch.id.clone(); + let branch_turns = branch.turn_count(); + // The branch's own transcript rows (handoff chain and + // retained turns) commit in one transaction before the + // branch session exists; any failure aborts the branch. + if let Err(e) = super::branch_copy::copy_branch_transcript( + mem.as_ref(), + memory_fabric.workspace_id(), + ¤t.id, + &mut branch, + ) + .await + { + emit_chat_output(&format!("Branch aborted: failed to copy the transcript: {e}")); + continue; + } + if let Err(e) = save_session(mem.as_ref(), &branch).await { + emit_chat_output(&format!("Branch aborted: failed to save new branch session: {e}")); + continue; + } + if let Err(e) = apply_chat_session_switch( + ChatSwitchCtx { + chat_session: &mut chat_session, + commits: &turn_signal, + chat_session_key: &mut chat_session_key, + fabric_turn_seq: &mut fabric_turn_seq, + history: &mut history, + approval_router: approval_router.as_ref(), + pending_chat_rewind: &mut pending_chat_rewind, + pending_diff_apply: &mut pending_diff_apply, + chat_sessions: &mut chat_sessions, + ignored_session_events: &mut ignored_session_events, + session_rings: &mut session_rings, + reported_sessions: &mut reported_sessions, + announced_started_sessions: &mut announced_started_sessions, + last_sessions_summary: &mut last_sessions_summary, + last_sessions_entries: &mut last_sessions_entries, + attached_follow: &mut attached_follow, + attached_follow_seq: &mut attached_follow_seq, + chat_dispatcher: &chat_dispatcher, + redraw_handle: sessions_redraw_handle.as_ref(), + config: &config, + provider_name, + model_name, + skills: &skills, + native_tools, + #[cfg(feature = "terminal-tui")] + chat_mirror: &chat_mirror, + }, + branch, + true, + ) + .await + { + emit_chat_output(&format!("Branch aborted: {e}")); + continue; + } + emit_chat_output(&format!( + "Created branch {branch_id} from the first {branch_turns} turns and switched to it." + )); + } + commands::HistoryCommand::Rewind(raw) => { + let keep_turns = match parse_turn_boundary(&raw, chat_session.session().turn_count(), "rewind") { + Ok(value) => value, + Err(msg) => { + emit_chat_output(&msg); + continue; + } + }; + if keep_turns == chat_session.session().turn_count() { + emit_chat_output(&format!( + "Rewind skipped: session already has exactly {keep_turns} turns." + )); + continue; + } + if approval_in_progress(approval_router.as_ref(), &pending_chat_rewind, &pending_diff_apply) + { + emit_chat_output(approval_already_pending_message()); + continue; + } + if sessions_redraw_handle.is_none() { + emit_chat_output( + "Rewind requires interactive confirmation; unavailable in this mode. Current session unchanged.", + ); + continue; + } + #[cfg(not(feature = "terminal-tui"))] + { + emit_chat_output( + "Rewind requires interactive confirmation; unavailable in this mode. Current session unchanged.", + ); + continue; + } + #[cfg(feature = "terminal-tui")] + { + let Some(router) = approval_router.as_ref() else { + emit_chat_output( + "Rewind requires interactive confirmation; approval router unavailable. Current session unchanged.", + ); + continue; + }; + let target_session = rewound_chat_session_from(&chat_session.session(), keep_turns); + let (approval_tx, approval_rx) = tokio::sync::oneshot::channel::(); + let tool_id = format!("chat_rewind:{}", uuid::Uuid::new_v4()); + if !router.register(tool_id.clone(), approval_tx) { + emit_chat_output(approval_already_pending_message()); + continue; + } + let args = serde_json::json!({ + "session_id": chat_session.session().id, + "from_turns": chat_session.session().turn_count(), + "to_turns": keep_turns, + "drops_child_summaries": keep_turns < chat_session.session().turn_count(), + }) + .to_string(); + let dispatch_result = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::ToolApprovalRequested { + task_id: None, + tool_id: tool_id.clone(), + name: "rewind_chat_session".to_string(), + args, + }, + "chat.rewind_approval_requested", + ); + if dispatch_result != crate::chat::dispatcher::DispatchResult::Sent { + let _ = router.resolve(&tool_id, false); + emit_chat_output("Rewind approval could not be shown; current session unchanged."); + continue; + } + pending_chat_rewind = Some(PendingChatRewind { + tool_id, + target_session, + approval_rx, + }); + emit_chat_output(&format!( + "Confirm rewind to {keep_turns} turns in the approval prompt." + )); + } + } + } + continue; + } + commands::CommandResult::ApplyAction(action) => { + let latest_index = match action { + commands::ApplyCommand::Latest => 1, + commands::ApplyCommand::Index(index) => index, + }; + if approval_in_progress(approval_router.as_ref(), &pending_chat_rewind, &pending_diff_apply) { + emit_chat_output(approval_already_pending_message()); + continue; + } + let Some(diff) = diff_apply::latest_fenced_diff(&chat_session.session().turns, latest_index) else { + emit_chat_output("No applicable fenced diff block found in this conversation."); + continue; + }; + let plan = match diff_apply::parse_unified_diff(&diff, config.autonomy.level) { + Ok(plan) => plan, + Err(error) => { + emit_chat_output(&format!("Diff apply rejected: {error}. Workspace unchanged.")); + continue; + } + }; + #[cfg(not(feature = "terminal-tui"))] + let _ = &plan; + if sessions_redraw_handle.is_none() { + emit_chat_output( + "Diff apply requires interactive TUI approval; unavailable in this mode. Workspace unchanged.", + ); + continue; + } + #[cfg(not(feature = "terminal-tui"))] + { + emit_chat_output( + "Diff apply requires interactive TUI approval; unavailable in this build. Workspace unchanged.", + ); + continue; + } + #[cfg(feature = "terminal-tui")] + { + match request_diff_apply_approval(plan, true, approval_router.as_ref(), &chat_dispatcher) { + Ok(pending) => { + let summary = pending.plan.summary(); + pending_diff_apply = Some(pending); + emit_chat_output(&format!("Confirm diff apply in the approval prompt.\n{summary}")); + } + Err(message) => emit_chat_output(&message), + } + } + #[cfg(feature = "terminal-tui")] + continue; + } + commands::CommandResult::SessionAction(action) => { + use crate::chat::sessions::SessionCommand; + // Shared parsing must not turn mailbox/model input into + // local operator authority for a child or approval action. + if action.requires_local_operator() && !is_local_operator_input(&msg) { + emit_chat_output("This session command requires local terminal operator input."); + if let Some(guard) = assignment_guard.as_mut() { + guard.failed("Assigned task cannot issue local operator session commands."); + } + continue; + } + match action { + SessionCommand::Bg { task } => { + // Spawn a background agent via sessions_spawn, passing + // the *current* provider/model (read from the main-loop + // strings, which `/provider` and `/model` keep in sync) + // so a hot switch is honoured (plan §C.0 blocker 3). + match tools_registry.iter().find(|t| t.supports_name("sessions_spawn")) { + Some(tool) => { + let command = provider_binding.as_ref() + .ok_or_else(|| anyhow::anyhow!("chat provider binding is missing")) + .and_then(|binding| binding::ChatOperatorSpawn::capture( + &msg, &task, binding, &ctx.config_generation, &provider, + ¤t_provider_owned, ¤t_model_owned, + )); + let command = match command { + Ok(command) => command, + Err(error) => { + emit_chat_output(&format!("Cannot admit background command: {error}")); + continue; + } + }; + let (mut args, operator_source) = match command.admit(Arc::clone(&mem), &chat_session_key, Arc::clone(&ctx.security), Arc::clone(&turn_service)).await { + Ok(admitted) => admitted, + Err(error) => { emit_chat_output(&format!("Cannot record background command source: {error}")); continue; } + }; + // Spawning is a Medium-risk side effect; under + // supervised autonomy the gate requires a grant + // bound to `sessions_spawn:spawn`. The operator + // typed `/bg`, so issue the matching grant here + // (same op name the gate authorizes), mirroring + // `/kill` and `/steer` and how the agent loop + // grants after operator approval. + let grant = crate::security::policy::ApprovalGrant::for_resource_operation( + "sessions_spawn", + "sessions_spawn:spawn", + "chat-operator", + None, + ); + match serde_json::to_value(&grant) { + Ok(grant_value) => { + if let Some(obj) = args.as_object_mut() { + obj.insert( + crate::security::policy::RUNTIME_APPROVAL_GRANT_ARG.to_string(), + grant_value, + ); + } + } + Err(e) => { + tracing::warn!( + error = %crate::agent::diagnostics::error_class(&e), + "Failed to serialize spawn approval grant; proceeding without it" + ); + } + } + match operator_source.scope(tool.execute_named("sessions_spawn", args)).await { + Ok(result) => { + let out = if result.output.is_empty() { + result + .error + .filter(|e| !e.is_empty()) + .unwrap_or_else(|| "(no output)".to_string()) + } else { + result.output + }; + emit_chat_output(&out); + } + Err(e) => emit_chat_output(&format!("Failed to start background agent: {e}")), + } + } + None => emit_chat_output("Background sessions are not available in this session."), + } + continue; + } + SessionCommand::Sessions => { + if let Some(output) = handle_local_session_command( + &action, + &mut chat_sessions, + &session_rings, + &mut reaped_log_archive, + &reap_policy, + &tools_registry, + ) + .await + { + emit_chat_output(&super::session_glue::sessions_listing_with_current( + &chat_session.session().id, + &output, + )); + } + continue; + } + SessionCommand::Transcript => { + attached_follow = None; + attached_follow_seq = None; + #[cfg(feature = "terminal-tui")] + { + open_transcript_view( + &chat_mirror, + &chat_dispatcher, + sessions_redraw_handle.as_ref(), + snapshot_rx_for_tui.as_ref(), + ); + } + #[cfg(not(feature = "terminal-tui"))] + emit_chat_output("Transcript viewer is only available in the terminal TUI."); + continue; + } + SessionCommand::Diff { cached } => { + attached_follow = None; + attached_follow_seq = None; + let source = collect_workspace_diff(&config.workspace_dir, cached).await; + #[cfg(feature = "terminal-tui")] + { + if sessions_redraw_handle.is_some() { + open_diff_view( + &chat_mirror, + &chat_dispatcher, + sessions_redraw_handle.as_ref(), + source, + ); + } else { + emit_chat_output(&source.to_plain_text()); + } + } + #[cfg(not(feature = "terminal-tui"))] + emit_chat_output(&source.to_plain_text()); + continue; + } + SessionCommand::Kill { seq: _ } => { + if let Some(output) = handle_local_session_command( + &action, + &mut chat_sessions, + &session_rings, + &mut reaped_log_archive, + &reap_policy, + &tools_registry, + ) + .await + { + emit_chat_output(&output); + } + continue; + } + SessionCommand::Steer { seq, message } => { + // v5: steer only applies to agent sessions (it appends + // an instruction to a running sub-agent's steer + // channel). Shells and PTYs have no steer channel — + // resolving their seq would yield a non-agent id that + // the sessions_spawn tool can't address, producing a + // cryptic "run not found". Guard with a clear message + // up front, mirroring `/kill`'s kind dispatch. + match chat_sessions.kind_for_seq(seq).await { + Ok(kind) => { + if let Some(msg) = + crate::chat::sessions::command::steer_unsupported_message(kind, seq) + { + emit_chat_output(&msg); + continue; + } + // Agent: fall through to the steer delegation. + } + Err(e) => { + emit_chat_output(&format!("Steer failed: {e}")); + continue; + } + } + // Resolve `#N` -> run UUID, then delegate to the + // sessions_spawn tool's `steer` action so the shared + // semantics apply uniformly (Low-risk side-effect gate + // op `sessions_spawn:steer:`, running-status + // check, steer_tx delivery). Mirrors `/kill`. + let run_id = match chat_sessions.resolve_run_id(seq).await { + Ok(id) => id, + Err(e) => { + emit_chat_output(&format!("Steer failed: {e}")); + continue; + } + }; + match tools_registry.iter().find(|t| t.supports_name("sessions_spawn")) { + Some(tool) => { + let operation_name = format!("sessions_spawn:steer:{run_id}"); + let grant = crate::security::policy::ApprovalGrant::for_resource_operation( + "sessions_spawn", + &operation_name, + "chat-operator", + None, + ); + let mut args = serde_json::json!({ + "action": "steer", + "run_id": run_id, + "message": message, + }); + match serde_json::to_value(&grant) { + Ok(grant_value) => { + if let Some(obj) = args.as_object_mut() { + obj.insert( + crate::security::policy::RUNTIME_APPROVAL_GRANT_ARG.to_string(), + grant_value, + ); + } + } + Err(e) => { + tracing::warn!( + error = %crate::agent::diagnostics::error_class(&e), + "Failed to serialize steer approval grant; proceeding without it" + ); + } + } + match tool.execute_named("sessions_spawn", args).await { + Ok(result) => { + let out = if result.output.is_empty() { + result + .error + .filter(|e| !e.is_empty()) + .unwrap_or_else(|| "(no output)".to_string()) + } else { + result.output + }; + emit_chat_output(&out); + } + Err(e) => emit_chat_output(&format!("Steer failed: {e}")), + } + } + None => emit_chat_output("Background sessions are not available in this session."), + } + continue; + } + SessionCommand::Attach { seq } => { + // P2 `/attach` focuses the child session viewport. + // Main history receives only a breadcrumb; retained + // and live child output render inside ActiveSessionView. + // + // v5: PTY sessions are interactive terminal handoffs, + // not line-streamed output, so a read-only follow makes + // no sense for them. The Ctrl+G switcher routes Enter + // through this same `/attach ` path for every kind, + // so guard PTYs here with a clear redirect rather than + // silently starting an empty follow. (A live PTY can be + // re-entered with `/pty`; an exited one is terminal.) + #[cfg(feature = "terminal-tui")] + if matches!( + chat_sessions.kind_for_seq(seq).await, + Ok(crate::chat::sessions::model::ManagedKind::Pty) + ) { + // v3b: a live PTY can be RE-ATTACHED — the detach + // path keeps the child running, so `/attach #N` + // (and the Ctrl+G switcher's synthetic /attach) + // hands the terminal back to it. An exited PTY is + // terminal and cannot be attached. + let pty = chat_sessions.pty_for_seq_public(seq); + match pty { + Some(session) if session.is_attachable() => { + reattach_pty( + &session, + seq, + &pty_handoff, + sessions_redraw_handle.as_ref(), + &emit_chat_output, + ) + .await; + } + _ => { + emit_chat_output(&format!( + "Interactive PTY session #{seq} has exited — nothing to attach to. \ + Start a new one with /pty ." + )); + } + } + // Restore the prompt/focus the switcher may have set + // optimistically (it pointed at this seq before the + // handoff), so the chat prompt is not left targeting + // the detached PTY for steering. + let prev_focus = crate::chat::sessions::focus::rollback_focus(attached_follow_seq); + let _ = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::SessionFocusChanged { focus: prev_focus }, + "chat.session_focus_attach_pty_done", + ); + { + let mut mirror = chat_mirror.lock(); + mirror.focus = prev_focus; + mirror.active_session_view = None; + } + let _ = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::ActiveSessionViewUpdated { view: None }, + "chat.active_session_view_attach_pty_done", + ); + if let Some(tx) = sessions_redraw_handle.as_ref() { + let _ = tx.try_send(()); + } + continue; + } + const ATTACH_TAIL_LINES: usize = 20; + match chat_sessions.resolve_run_id(seq).await { + Ok(run_id) => { + let sid = crate::chat::sessions::id::SessionId::from_run_id(&run_id); + let was_following_before_attach = attached_follow.is_some(); + let is_terminal = chat_sessions.is_terminal_for_seq(seq).await.unwrap_or(false); + let views = chat_sessions.snapshot().await; + let view_meta = views.iter().find(|view| view.seq == seq); + let tail_lines = match chat_sessions.tail(seq, ATTACH_TAIL_LINES).await { + Ok(lines) => lines + .into_iter() + .map(|line| format!("[{}] {}", line.role, line.content)) + .collect::>(), + Err(e) => { + emit_chat_output(&format!("Attach tail failed: {e}")); + Vec::new() + } + }; + let (ring_lines, truncated) = session_rings.get(&sid).map_or_else( + || (Vec::new(), false), + |ring| { + let lines = if is_terminal { + Vec::new() + } else { + ring.recent_lines(crate::chat::sessions::event::DEFAULT_RING_CAPACITY) + }; + (lines, ring.is_truncated()) + }, + ); + #[cfg(not(feature = "terminal-tui"))] + let _ = ( + &was_following_before_attach, + &view_meta, + &tail_lines, + &ring_lines, + truncated, + ); + #[cfg(feature = "terminal-tui")] + let active_projection = build_active_session_attach_projection( + seq, view_meta, tail_lines, ring_lines, truncated, + ); + attached_follow = Some(sid); + attached_follow_seq = Some(seq); + // v1.1b: route plain input to this session as + // a steer and reflect the target in the prompt + // (colour+glyph). Update both the render + // snapshot (Action) and the key thread's + // mirror (read by `resolve_esc`). When the + // attach was triggered from the switcher the + // key thread already set this optimistically; + // re-affirming it here is idempotent and also + // covers the typed `/attach N` path. + let focus = crate::chat::sessions::FocusTarget::Session { seq }; + let _ = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::SessionFocusChanged { focus }, + "chat.session_focus_attach", + ); + #[cfg(feature = "terminal-tui")] + { + { + let mut mirror = chat_mirror.lock(); + mirror.focus = focus; + mirror.active_session_view = Some(active_projection.view.clone()); + } + let _ = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::ActiveSessionViewUpdated { + view: Some(active_projection.view.clone()), + }, + "chat.active_session_view_attach", + ); + if let Some(tx) = sessions_redraw_handle.as_ref() { + let _ = tx.try_send(()); + } + } + #[cfg(feature = "terminal-tui")] + if let Some(breadcrumb) = attach_breadcrumb_for_transition( + was_following_before_attach, + &active_projection, + ) { + emit_chat_output(breadcrumb); + } + #[cfg(not(feature = "terminal-tui"))] + emit_chat_output(&format!( + "Attached session #{seq} (input starts or queues a child turn). Type /detach to stop." + )); + } + Err(e) => { + // P0 race fix: the switcher key thread may have + // optimistically pointed the prompt + Esc + // judgment at `seq` before this attach ran. The + // attach failed (seq no longer resolves / the + // session is gone), so `attached_follow` is + // unchanged — restore the prompt to the *actual* + // current target so perception cannot diverge + // from routing. (A typed `/attach N` that fails + // has no optimistic set, but restoring the same + // unchanged focus is an idempotent no-op there.) + let prev_focus = crate::chat::sessions::focus::rollback_focus(attached_follow_seq); + let _ = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::SessionFocusChanged { focus: prev_focus }, + "chat.session_focus_attach_rollback", + ); + #[cfg(feature = "terminal-tui")] + { + { + let mut mirror = chat_mirror.lock(); + mirror.focus = prev_focus; + mirror.active_session_view = None; + } + let _ = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::ActiveSessionViewUpdated { view: None }, + "chat.active_session_view_attach_rollback", + ); + if let Some(tx) = sessions_redraw_handle.as_ref() { + let _ = tx.try_send(()); + } + } + emit_chat_output(&format!("Attach failed: {e}")); + } + } + continue; + } + SessionCommand::Detach => { + let was_following = attached_follow.take().is_some(); + attached_follow_seq = None; + if was_following { + // v1.1b: reset input routing back to main and clear + // the prompt target indicator (snapshot + mirror). + let focus = crate::chat::sessions::FocusTarget::Main; + let _ = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::SessionFocusChanged { focus }, + "chat.session_focus_detach", + ); + #[cfg(feature = "terminal-tui")] + { + { + let mut mirror = chat_mirror.lock(); + mirror.focus = focus; + mirror.active_session_view = None; + } + let _ = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::ActiveSessionViewUpdated { view: None }, + "chat.active_session_view_detach", + ); + if let Some(tx) = sessions_redraw_handle.as_ref() { + let _ = tx.try_send(()); + } + } + emit_chat_output("Detached. Input routes to main chat again."); + } else { + emit_chat_output("Not currently following any session."); + } + continue; + } + SessionCommand::Shell { command } => { + // v2: run a non-interactive command in the background. + // Runs directly in the configured workspace with the + // inherited host environment and the v1.1 event bridge. + match crate::chat::sessions::shell::spawn_shell( + &command, + &config.workspace_dir, + &shell_event_sink, + ) { + Ok(session) => { + let seq = chat_sessions.add_shell(session); + emit_chat_output(&format!("Started background shell #{seq}: {command}")); + } + Err(e) => { + emit_chat_output(&format!("Failed to start background shell: {e}")); + } + } + continue; + } + SessionCommand::Logs { seq: _ } => { + if let Some(output) = handle_local_session_command( + &action, + &mut chat_sessions, + &session_rings, + &mut reaped_log_archive, + &reap_policy, + &tools_registry, + ) + .await + { + emit_chat_output(&output); + } + continue; + } + SessionCommand::Pty { command } => { + // v3a: interactive PTY shell with a full terminal + // handoff. The chat ratatui render loop is suspended + // and the real terminal is wired straight to the PTY + // for the duration; Ctrl-] detaches, Ctrl-C/Ctrl-D + // pass through. Restoration is guaranteed by the RAII + // `PtyHandoffGuard` regardless of how the passthrough + // ends (detach, child exit, error, or panic). + #[cfg(feature = "terminal-tui")] + { + handle_pty_command( + &command, + &config.workspace_dir, + &mut chat_sessions, + &pty_handoff, + sessions_redraw_handle.as_ref(), + &emit_chat_output, + ) + .await; + } + #[cfg(not(feature = "terminal-tui"))] + { + let _ = &command; + emit_chat_output("Interactive PTY sessions require the terminal UI."); + } + continue; + } + SessionCommand::Approve { seq } | SessionCommand::Deny { seq } => { + // NeedsInput: deliver an approval decision to a + // background sub-agent suspended on the supervised + // approval gate. `/approve` injects a runtime grant + // (Grant) so the gated tool can pass the gate; `/deny` + // reports the tool as denied to the sub-agent. + let approve = matches!(action, SessionCommand::Approve { .. }); + let run_id = match chat_sessions.resolve_run_id(seq).await { + Ok(id) => id, + Err(e) => { + emit_chat_output(&format!( + "{} failed: {e}", + if approve { "Approve" } else { "Deny" } + )); + continue; + } + }; + let decision = if approve { + crate::agent::turn_contracts::ApprovalDecision::Grant + } else { + crate::agent::turn_contracts::ApprovalDecision::Deny + }; + if pending_approvals.resolve(&run_id, decision) { + emit_chat_output(&format!( + "{} session #{seq}.", + if approve { "Approved" } else { "Denied" } + )); + } else { + emit_chat_output(&format!( + "Session #{seq} is not awaiting approval (it may have resumed, \ + timed out, completed, or was killed)." + )); + } + continue; + } + SessionCommand::DaemonSessions + | SessionCommand::DaemonKill { .. } + | SessionCommand::DaemonSteer { .. } => { + // a5: the daemon's work registry lives in another + // process, so this is a control-API call, not a + // registry read. The listing's local fallback is + // built here, on the loop where `chat_sessions` is + // reachable, and handed to the request to show if + // the daemon turns out to be unreachable. + let local_fallback = if matches!(action, SessionCommand::DaemonSessions) { + handle_local_session_command( + &SessionCommand::Sessions, + &mut chat_sessions, + &session_rings, + &mut reaped_log_archive, + &reap_policy, + &tools_registry, + ) + .await + } else { + None + }; + if let Some(notice) = start_daemon_session_command( + &action, + local_fallback, + &chat_sessions.daemon_requests(), + DaemonControl { + config: &config, + dispatcher: &chat_dispatcher, + redraw_tx: redraw_tx_for_main.as_ref(), + }, + ) { + emit_chat_output(¬ice); + } + continue; + } + } + } + commands::CommandResult::NotACommand => { + // Focused child input was admitted by child_focus above. + + } + } + } + + } + +} diff --git a/src/chat/run/event_pump.rs b/src/chat/run/event_pump.rs new file mode 100644 index 000000000..809921420 --- /dev/null +++ b/src/chat/run/event_pump.rs @@ -0,0 +1,721 @@ +loop { + #[cfg(feature="terminal-tui")] + if let (Some(target),Some(seq))=(attached_follow.as_ref(),attached_follow_seq) { + let lines=session_rings.get(target).map_or_else(Vec::new,|ring|ring.recent_lines(crate::chat::sessions::event::DEFAULT_RING_CAPACITY)); + let offset=chat_mirror.lock().active_session_view.as_ref().map_or(0,|view|view.scroll_offset); + if let Ok(view)=(super::child_focus::ChildFocusContext { memory:&mem,generation:&ctx.config_generation,parent:&chat_session_key, + security:&ctx.security,service:&turn_service,tools:&tools_registry,sessions:&chat_sessions,approvals:&pending_approvals }).view(target.as_str(),seq,lines,offset).await { + chat_mirror.lock().active_session_view=Some(view.clone()); + let _=chat_dispatcher.dispatch_or_log(crate::chat::action::Action::ActiveSessionViewUpdated{view:Some(view)},"chat.child_session_view"); + } + } + if let Some(seq)=attached_follow_seq { + if let Ok(run)=chat_sessions.resolve_run_id(seq).await { attached_follow=Some(crate::chat::sessions::id::SessionId::from_run_id(&run)); } + } + for notice in child_focus.pump(&super::child_focus::ChildFocusContext { memory:&mem,generation:&ctx.config_generation,parent:&chat_session_key, + security:&ctx.security,service:&turn_service,tools:&tools_registry,sessions:&chat_sessions,approvals:&pending_approvals }).await { + surface_session_message(&chat_dispatcher,sessions_redraw_handle.as_ref(),¬ice); + } + turn_signal.ensure_history_commits_healthy()?; + #[cfg(feature = "terminal-tui")] + macro_rules! handle_resume_saved_session_control { + ($id:expr) => {{ + let provider_name = current_provider_owned.as_str(); + let model_name = current_model_owned.as_str(); + match resume_saved_session_by_id( + mem.as_ref(), + &$id, + ChatSwitchCtx { + chat_session: &mut chat_session, + commits: &turn_signal, + chat_session_key: &mut chat_session_key, + fabric_turn_seq: &mut fabric_turn_seq, + history: &mut history, + approval_router: approval_router.as_ref(), + pending_chat_rewind: &mut pending_chat_rewind, + pending_diff_apply: &mut pending_diff_apply, + chat_sessions: &mut chat_sessions, + ignored_session_events: &mut ignored_session_events, + session_rings: &mut session_rings, + reported_sessions: &mut reported_sessions, + announced_started_sessions: &mut announced_started_sessions, + last_sessions_summary: &mut last_sessions_summary, + last_sessions_entries: &mut last_sessions_entries, + attached_follow: &mut attached_follow, + attached_follow_seq: &mut attached_follow_seq, + chat_dispatcher: &chat_dispatcher, + redraw_handle: sessions_redraw_handle.as_ref(), + config: &config, + provider_name, + model_name, + skills: &skills, + native_tools, + #[cfg(feature = "terminal-tui")] + chat_mirror: &chat_mirror, + }, + ) + .await + { + Ok(message) => surface_session_message(&chat_dispatcher, sessions_redraw_handle.as_ref(), &message), + Err(e) => { + surface_session_message(&chat_dispatcher, sessions_redraw_handle.as_ref(), &e.to_string()) + } + } + }}; + } + #[cfg(feature = "terminal-tui")] + if finalize_ready_per_turn_contexts( + &mut per_turn_contexts, + &mut pending_ordered_provider_turn_commits, + &mut pending_provider_completion_events, + &turn_signal, + &mut provider_turn_completion_contexts, + &mut history, + &tools_registry, + &mut provider_turn_finalizer_events, + &mut turn_scheduler, + &mut history_commit_coordinator, + &mut provider_turn_workers, + &chat_dispatcher, + &terminal, + &memory_fabric, + &chat_session_key, + &config, + sessions_redraw_handle.as_ref(), + redraw_tx_for_main.as_ref(), + plain_mode, + &mut plain_mode_turn_failed, + ) + .await + { + continue; + } + if !input_events_open && input_backlog.is_empty() { + #[cfg(feature = "terminal-tui")] + if should_continue_event_pump_after_input_closed(per_turn_contexts.len()) { + // Keep lifecycle/completion arms alive until the detached Redux turn + // resolves; this mirrors the old inner wait, which ignored closed + // input while the active turn was still running. + } else { + break None; + } + #[cfg(not(feature = "terminal-tui"))] + break None; + } + #[cfg(feature = "terminal-tui")] + if !provider_turn_finalizer_events.is_empty() { + let results = drain_provider_turn_finalizer_events_and_publish( + &mut turn_scheduler, + &mut history_commit_coordinator, + &mut provider_turn_workers, + &mut provider_turn_finalizer_events, + &chat_dispatcher, + ); + #[cfg(feature = "terminal-tui")] + let applied_ordered_commits = apply_ready_ordered_provider_turn_commits( + results, + &mut pending_ordered_provider_turn_commits, + &mut history, + &mut turn_scheduler, + &provider_turn_workers, + &chat_dispatcher, + &terminal, + &memory_fabric, + &chat_session_key, + &config, + sessions_redraw_handle.as_ref(), + redraw_tx_for_main.as_ref(), + &turn_signal, + plain_mode, + &mut plain_mode_turn_failed, + ) + .await; + #[cfg(not(feature = "terminal-tui"))] + let applied_ordered_commits = !results.is_empty(); + if applied_ordered_commits { + continue; + } + } + if consume_deferred_visible_input_pop(&mut defer_visible_input_pop_once) { + // A post-route admission failure just requeued the same input at the + // front. Skip one immediate visible pop so the event pump can consume + // in-flight completion/lifecycle events that may free stricter Legacy + // admission. + } else if let Some(input) = pop_next_visible_input_task_with_scheduler( + &mut input_backlog, + &mut turn_scheduler, + &provider_turn_workers, + visible_input_admission_kind, + max_concurrent_visible_turns, + ) { + publish_main_queue_status(&chat_dispatcher, &turn_scheduler); + break Some(input); + } + #[cfg(feature = "terminal-tui")] + if should_drain_deferred_resume_after_visible_inputs( + per_turn_contexts.len(), + &input_backlog, + &provider_turn_workers, + ) && let Some(id) = deferred_resume_saved_session_ids.pop_front() + { + handle_resume_saved_session_control!(id); + continue; + } + tokio::select! { + msg = input_rx.recv(), if input_events_open => { + let Some(msg) = msg else { + #[cfg(feature = "terminal-tui")] + { + if !per_turn_contexts.is_empty() { + input_events_open = false; + continue; + } + } + break None; + }; + if let Some(target)=attached_follow.as_ref() { + match child_focus.submit(target.as_str(),msg.message.clone(),&super::child_focus::ChildFocusContext { memory:&mem,generation:&ctx.config_generation,parent:&chat_session_key, + security:&ctx.security,service:&turn_service,tools:&tools_registry,sessions:&chat_sessions,approvals:&pending_approvals }).await { + Ok(Some(output))=>{surface_session_message(&chat_dispatcher,sessions_redraw_handle.as_ref(),&output);continue;}, + Err(error)=>{surface_session_message(&chat_dispatcher,sessions_redraw_handle.as_ref(),&error.to_string());continue;}, + Ok(None)=>{} + } + } + #[cfg(feature = "terminal-tui")] + let active_task_id = per_turn_contexts.keys().next().copied(); + #[cfg(feature = "terminal-tui")] + if let Some(active_task_id) = active_task_id { + let mut emit_active_turn_output = + |text: &str| surface_active_turn_message(&chat_dispatcher, redraw_tx_for_main.as_ref(), text); + let daemon_control = DaemonControl { + config: &config, + dispatcher: &chat_dispatcher, + redraw_tx: redraw_tx_for_main.as_ref(), + }; + let queued_from = input_backlog.len(); + process_active_turn_input_batch( + msg, + &mut emit_active_turn_output, + &mut input_rx, + &mut input_backlog, + &mut turn_scheduler, + &mut provider_turn_workers, + Some(active_task_id), + &chat_dispatcher, + &chat_session.session(), + &mut chat_sessions, + &session_rings, + &mut reaped_log_archive, + &reap_policy, + &tools_registry, + daemon_control, + ) + .await; + if plain_typed_queue { + let added = lines_queued_since(&input_backlog, queued_from); + settle_queued_lines(&mut input_backlog, &mut turn_scheduler, &added); + } + publish_main_queue_status(&chat_dispatcher, &turn_scheduler); + continue; + } + let queued_from = input_backlog.len(); + enqueue_input_message_with_scheduler( + &mut input_backlog, + &mut turn_scheduler, + msg, + chat_session.session().turns.len(), + ); + drain_available_input_messages( + &mut input_rx, + &mut input_backlog, + Some(&mut turn_scheduler), + chat_session.session().turns.len(), + ); + let added = lines_queued_since(&input_backlog, queued_from); + publish_main_queue_status(&chat_dispatcher, &turn_scheduler); + let next = pop_next_visible_input_task_with_scheduler( + &mut input_backlog, + &mut turn_scheduler, + &provider_turn_workers, + visible_input_admission_kind, + max_concurrent_visible_turns, + ); + if plain_typed_queue { + settle_queued_lines(&mut input_backlog, &mut turn_scheduler, &added); + } + if let Some(next) = next { + // The enqueue snapshot above reports this item as queued. + // Publish again after dequeue so fast slash commands, which + // never enter the provider-turn path, cannot leave a stale + // `queue:1` badge behind in the TUI. + publish_main_queue_status(&chat_dispatcher, &turn_scheduler); + break Some(next); + } + continue; + }, + // EOF on the line front end's stdin. Lines read before it are + // still queued; the arm waits until the input arm has taken them, + // then closes the input like a closed channel would. The guard is + // evaluated before the select polls: the reader may send its last + // lines and fire EOF while the loop waits, making both arms ready + // at once. Re-check here so lines sent before EOF are never dropped. + () = stdin_closed.cancelled(), if input_events_open && input_rx.is_empty() => { + if !input_rx.is_empty() { + continue; + } + input_events_open = false; + continue; + }, + lifecycle = provider_turn_lifecycle_rx.recv(), if provider_turn_lifecycle_events_open => { + let Some(lifecycle) = lifecycle else { + provider_turn_lifecycle_events_open = false; + continue; + }; + record_provider_turn_lifecycle_event( + &mut provider_turn_workers, + lifecycle, + ); + publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); + continue; + }, + completion = provider_completion_rx.recv() => { + let Some(completion) = completion else { + continue; + }; + let _ = route_provider_completion_event_and_publish( + &mut provider_turn_lifecycle_rx, + &mut provider_turn_lifecycle_events_open, + &mut provider_turn_workers, + &mut pending_provider_completion_events, + None, + completion, + &chat_dispatcher, + ); + #[cfg(feature = "terminal-tui")] + { + let _ = finalize_ready_per_turn_contexts( + &mut per_turn_contexts, + &mut pending_ordered_provider_turn_commits, + &mut pending_provider_completion_events, + &turn_signal, + &mut provider_turn_completion_contexts, + &mut history, + &tools_registry, + &mut provider_turn_finalizer_events, + &mut turn_scheduler, + &mut history_commit_coordinator, + &mut provider_turn_workers, + &chat_dispatcher, + &terminal, + &memory_fabric, + &chat_session_key, + &config, + sessions_redraw_handle.as_ref(), + redraw_tx_for_main.as_ref(), + plain_mode, + &mut plain_mode_turn_failed, + ) + .await; + } + continue; + }, + _ = shutdown.cancelled() => { + #[cfg(feature = "terminal-tui")] + { + if !per_turn_contexts.is_empty() { + finalize_all_per_turn_contexts_as_cancelled( + &mut per_turn_contexts, + &mut pending_ordered_provider_turn_commits, + &turn_signal, + &mut provider_turn_completion_contexts, + &mut history, + tools_registry.as_ref(), + &mut provider_turn_finalizer_events, + &mut turn_scheduler, + &mut history_commit_coordinator, + &mut provider_turn_workers, + &chat_dispatcher, + &terminal, + &memory_fabric, + &chat_session_key, + &config, + sessions_redraw_handle.as_ref(), + redraw_tx_for_main.as_ref(), + plain_mode, + &mut plain_mode_turn_failed, + ) + .await; + } + } + break None + }, + maybe_control = control_rx.recv(), if control_events_open => { + let Some(control) = maybe_control else { + control_events_open = false; + continue; + }; + match control { + #[cfg(feature = "terminal-tui")] + ChatControlEvent::ResumeSavedSession { id } => { + #[cfg(feature = "terminal-tui")] + if defer_resume_saved_session_if_provider_turn_pending( + per_turn_contexts.len(), + &mut deferred_resume_saved_session_ids, + id.clone(), + ) { + // Old Redux N=1 behavior waited inside the turn and did not + // poll control_rx, so session switching could not mutate + // chat_session/history until the active turn was finalized. + continue; + } + handle_resume_saved_session_control!(id); + continue; + } + } + } + rewind_approval = async { + match pending_chat_rewind.as_mut() { + Some(pending) => (&mut pending.approval_rx).await, + None => std::future::pending::>().await, + } + }, if pending_chat_rewind.is_some() => { + let Some(pending) = pending_chat_rewind.take() else { + continue; + }; + match resolve_rewind_approval(&pending.tool_id, rewind_approval) { + RewindApprovalOutcome::Apply => { + let target_id = pending.target_session.id.clone(); + let target_turns = pending.target_session.turn_count(); + let provider_name = current_provider_owned.as_str(); + let model_name = current_model_owned.as_str(); + match apply_chat_session_switch(ChatSwitchCtx { + chat_session: &mut chat_session, + commits: &turn_signal, + chat_session_key: &mut chat_session_key, + fabric_turn_seq: &mut fabric_turn_seq, + history: &mut history, + approval_router: approval_router.as_ref(), + pending_chat_rewind: &mut pending_chat_rewind, + pending_diff_apply: &mut pending_diff_apply, + chat_sessions: &mut chat_sessions, + ignored_session_events: &mut ignored_session_events, + session_rings: &mut session_rings, + reported_sessions: &mut reported_sessions, + announced_started_sessions: &mut announced_started_sessions, + last_sessions_summary: &mut last_sessions_summary, + last_sessions_entries: &mut last_sessions_entries, + attached_follow: &mut attached_follow, + attached_follow_seq: &mut attached_follow_seq, + chat_dispatcher: &chat_dispatcher, + redraw_handle: sessions_redraw_handle.as_ref(), + config: &config, + provider_name, + model_name, + skills: &skills, + native_tools, + #[cfg(feature = "terminal-tui")] + chat_mirror: &chat_mirror, + }, pending.target_session, true).await { + Ok(()) => surface_session_message( + &chat_dispatcher, + sessions_redraw_handle.as_ref(), + &format!("Rewound chat session {target_id} to {target_turns} turns."), + ), + Err(e) => surface_session_message( + &chat_dispatcher, + sessions_redraw_handle.as_ref(), + &format!("Rewind aborted: failed to save trimmed session: {e}"), + ), + } + } + RewindApprovalOutcome::Cancelled(message) => { + surface_session_message(&chat_dispatcher, sessions_redraw_handle.as_ref(), &message); + } + } + continue; + } + apply_approval = async { + match pending_diff_apply.as_mut() { + Some(pending) => (&mut pending.approval_rx).await, + None => std::future::pending::>().await, + } + }, if pending_diff_apply.is_some() => { + let Some(pending) = pending_diff_apply.take() else { + continue; + }; + match apply_approval { + Ok(true) => { + let security = crate::runtime::bootstrap::build_security_policy(&config); + match diff_apply::execute_plan(&pending.plan, security.as_ref()).await { + Ok(message) => surface_session_message( + &chat_dispatcher, + sessions_redraw_handle.as_ref(), + &message, + ), + Err(error) => surface_session_message( + &chat_dispatcher, + sessions_redraw_handle.as_ref(), + &format!("Diff apply aborted: {error}. Workspace unchanged."), + ), + } + } + Ok(false) => { + surface_session_message( + &chat_dispatcher, + sessions_redraw_handle.as_ref(), + "Diff apply cancelled; workspace unchanged.", + ); + } + Err(_) => { + surface_session_message( + &chat_dispatcher, + sessions_redraw_handle.as_ref(), + &format!( + "Diff apply cancelled; approval channel closed for {} and workspace is unchanged.", + pending.tool_id + ), + ); + } + } + continue; + } + _ = sessions_tick.tick() => { + // 1) Summary reflow: surface each newly-finished session once, + // carrying its `#N` + status (plan §v1b). No auto-focus. + let finished = chat_sessions.poll_finished(&mut reported_sessions).await; + // 2) Persistent status line: recompute and dispatch only on change. + let views = chat_sessions.snapshot().await; + for fin in &finished { + let line = format_finished_session_announcement(fin); + let compact_summary = compact_child_completion_summary(&fin.summary); + surface_session_message( + &chat_dispatcher, + sessions_redraw_handle.as_ref(), + &line, + ); + // v4: persist a summary of this finished child session + // into the chat session so a reload can show what it + // produced. Title / created_at come from the live view (the + // finished record itself only carries seq/status/summary); + // if the view is already gone we still record with the + // finished record's own fields so nothing is lost. + let persisted = views + .iter() + .find(|v| v.id.as_str() == fin.run_id) + .map_or_else( + || crate::chat::sessions::PersistedSessionSummary { + id: fin.run_id.clone(), + seq: fin.seq, + kind: fin.kind.as_str().to_string(), + origin: fin.origin.as_str().to_string(), + status: fin.status.as_str().to_string(), + title: String::new(), + summary: compact_summary.clone(), + token_usage_records: fin.token_usage_records.clone(), + created_at: fin.created_at, + }, + |view| { + crate::chat::sessions::PersistedSessionSummary::from_view( + view, + compact_summary.clone(), + ) + }, + ); + // The reducer records and saves the summary (both builds). + let _ = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::BackgroundSessionRecorded { summary: persisted }, + "chat.bg_session_recorded", + ); + } + let now = chrono::Utc::now(); + let reaped = chat_sessions.reap(&reap_policy, now).await; + if !reaped.reaped.is_empty() { + let reaped_ids = reaped + .reaped + .iter() + .map(|session| session.id.clone()) + .collect::>(); + for session in &reaped.reaped { + if chat_session + .session() + .background_sessions + .iter() + .any(|summary| summary.id == session.summary.id) + { + continue; + } + let _ = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::BackgroundSessionRecorded { + summary: session.summary.clone(), + }, + "chat.bg_session_recorded_reap", + ); + } + reaped_log_archive.archive_reaped(&reaped.reaped, &mut session_rings, &reap_policy, now); + if attached_follow.as_ref().is_some_and(|id| reaped_ids.contains(id)) { + attached_follow = None; + attached_follow_seq = None; + let focus = crate::chat::sessions::FocusTarget::Main; + let _ = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::SessionFocusChanged { focus }, + "chat.session_focus_reaped", + ); + #[cfg(feature = "terminal-tui")] + { + { + let mut mirror = chat_mirror.lock(); + mirror.focus = focus; + mirror.active_session_view = None; + } + let _ = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::ActiveSessionViewUpdated { view: None }, + "chat.active_session_view_reaped", + ); + } + } + } + let views = chat_sessions.snapshot().await; + for view in &views { + if view.kind != crate::chat::sessions::model::ManagedKind::Agent { + continue; + } + if announced_started_sessions.insert(view.id.as_str().to_string()) { + let line = format_observed_session_announcement(view); + surface_session_message(&chat_dispatcher, sessions_redraw_handle.as_ref(), &line); + } + } + // v1.1b: refresh the switcher cache the key thread reads on Ctrl+G + // (it cannot run async registry queries itself). Display staleness + // is harmless: switcher Enter re-resolves the seq via /attach. + #[cfg(feature = "terminal-tui")] + { + let idle_warnings = chat_sessions + .idle_warning_seqs(&reap_policy, chrono::Utc::now(), &session_rings) + .await; + let mut entries = crate::chat::sessions::focus::switcher_entries(&views); + for entry in &mut entries { + entry.idle_warning = idle_warnings.contains(&entry.seq); + } + { + let mut mirror = chat_mirror.lock(); + refresh_sessions_cache(&mut mirror, entries.clone()); + } + if entries != last_sessions_entries { + last_sessions_entries = entries.clone(); + let _ = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::SessionsEntriesUpdated { entries }, + "chat.sessions_entries", + ); + if let Some(tx) = sessions_redraw_handle.as_ref() { + let _ = tx.try_send(()); + } + } + } + let new_summary = crate::chat::sessions::status_summary(&views); + if new_summary != last_sessions_summary { + last_sessions_summary = new_summary.clone(); + let _ = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::SessionsStatusUpdated { summary: new_summary }, + "chat.sessions_status", + ); + if let Some(tx) = sessions_redraw_handle.as_ref() { + let _ = tx.try_send(()); + } + } + // Keep waiting (do not break the inner loop / produce a message). + continue; + } + maybe_event = session_event_rx.recv(), if session_events_open => { + // Drain one background-session event: append it to that session's + // ring (single-consumer write, no lock) and, if focused, refresh + // the child viewport. P2 keeps child output out of main scrollback. + let Some(event) = maybe_event else { + // Sender side closed (chat shutting down). Disable this arm so + // a closed channel does not busy-spin; other arms drive exit. + session_events_open = false; + continue; + }; + let sid = event.session_id().clone(); + if should_ignore_session_event_after_chat_resume(&ignored_session_events, &event) { + continue; + } + let ring = session_rings + .entry(sid.clone()) + .or_insert_with(|| crate::chat::sessions::SessionRing::with_capacity( + crate::chat::sessions::event::DEFAULT_RING_CAPACITY, + )); + // A `Truncated` marker carries no output line; it only flags the + // ring so `/attach` shows `[output truncated]` for events the + // drainer had to drop on a full channel (P1 fix). Delta/ToolCall + // append their text as a new ring line. + let line = match &event { + crate::chat::sessions::SessionEvent::Delta { text, .. } => Some(text.clone()), + crate::chat::sessions::SessionEvent::ToolCall { summary, .. } => Some(summary.clone()), + crate::chat::sessions::SessionEvent::Truncated { .. } => { + ring.mark_truncated(); + None + } + // NeedsInput: a background sub-agent suspended awaiting an + // operator approval decision. Record a ring line for `/attach` + // visibility; the non-intrusive `/approve` hint is surfaced + // below (after the seq is resolved). Status flips to + // `❓ needs-input` via the registry (already set by the + // resolver) on the next status refresh. + crate::chat::sessions::SessionEvent::NeedsInput { prompt, .. } => { + Some(format!("[needs approval] {prompt}")) + } + crate::chat::sessions::SessionEvent::Resumed { .. } => { + Some("[approval resolved — resuming]".to_string()) + } + }; + if let Some(line) = line { + ring.push(line); + } + // NeedsInput / Resumed are control signals (not stream output): + // surface a non-intrusive operator hint with the session's `#N` + // and refresh the status line / switcher so the `❓` glyph and + // `needs-input` counter appear immediately, regardless of attach. + match &event { + crate::chat::sessions::SessionEvent::NeedsInput { prompt, .. } => { + let seq = chat_sessions.seq_for_id(&sid).await; + let label = seq + .map(|n| format!("#{n}")) + .unwrap_or_else(|| sid.as_str().to_string()); + surface_session_message( + &chat_dispatcher, + sessions_redraw_handle.as_ref(), + &format!( + "session {label} awaiting approval: {prompt} — /approve {} or /deny {} (/attach {} to inspect)", + seq.map(|n| n.to_string()).unwrap_or_else(|| label.clone()), + seq.map(|n| n.to_string()).unwrap_or_else(|| label.clone()), + seq.map(|n| n.to_string()).unwrap_or_else(|| label.clone()), + ), + ); + } + crate::chat::sessions::SessionEvent::Resumed { .. } => { + if let Some(tx) = sessions_redraw_handle.as_ref() { + let _ = tx.try_send(()); + } + } + _ => {} + } + #[cfg(feature = "terminal-tui")] + if attached_follow.as_ref() == Some(&sid) { + refresh_attached_session_view_from_ring( + &chat_mirror, + &chat_dispatcher, + sessions_redraw_handle.as_ref(), + &sid, + ring, + ); + } + continue; + } + } + } diff --git a/src/chat/run/provider_turn.rs b/src/chat/run/provider_turn.rs new file mode 100644 index 000000000..7a0975847 --- /dev/null +++ b/src/chat/run/provider_turn.rs @@ -0,0 +1,1829 @@ +{ + // This is the concrete TerminalChannel: send_draft always returns + // Some(id), including when its UI receiver has closed. Capacity can + // therefore be selected before creating the durable source. The local + // worker registry is inserted into only by this main loop; awaits below + // cannot consume another slot. + #[cfg(feature = "terminal-tui")] + let reducer_driver_turn_active = true; + #[cfg(feature = "terminal-tui")] + let provider_worker_kind = crate::chat::turn_worker::ProviderTurnWorkerKind::Detached; + #[cfg(not(feature = "terminal-tui"))] + let provider_worker_kind = crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited; + let provider_admission_max = match provider_worker_kind { + crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited => 1, + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached => max_concurrent_visible_turns, + }; + let provider_admission = + provider_turn_visible_admission(&provider_turn_workers, provider_worker_kind, provider_admission_max); + let catalog_changed = turn_service.check_live_parity().is_err(); + if !provider_admission.can_start_visible || (catalog_changed && provider_admission.active_workers > 0) { + tracing::warn!( + active_workers = provider_admission.active_workers, + foreground_active = provider_admission.foreground_active, + detached_active = provider_admission.detached_active, + effective_max_visible_turns = provider_admission.effective_max_visible_turns, + target_kind = ?provider_worker_kind, + "visible provider turn capacity unavailable before source admission; queueing input" + ); + // No durable input or decision exists yet. Keep the original + // assignment and queue identity for its first actual admission. + if let Some(guard) = assignment_guard.as_mut() { + guard.disarm(); + } + requeue_post_route_admission_rejected_input( + &mut input_backlog, + &mut turn_scheduler, + &mut defer_visible_input_pop_once, + DequeuedInputMessage { + priority: input_priority, + turn_task_id: provider_queue_task_id, + msg, + terminal_origin: terminal_origin.clone(), + }, + ); + publish_main_queue_status(&chat_dispatcher, &turn_scheduler); + continue; + } + if catalog_changed { + // Publish only at a new source boundary after existing model turns + // have finished. Their sealed catalog/grants are never rewritten. + // Keep publication's large builder future off the chat task's + // stack, including unoptimized binaries used by PTY regression. + let replacement = Box::pin(ctx.publish_turn_runtimes( + Arc::clone(&tools_registry), + crate::tools::capability::turn_state::TurnSurfaceKind::Interactive, + )).await?; + child_cleanup.retain_service(Arc::clone(&replacement)); + let retired = std::mem::replace(&mut turn_service, replacement); + let retirement = child_cleanup.retire(&retired)?; + let drained = retired.drain_writes(std::time::Instant::now() + Duration::from_secs(2)).await; + retirement.finish(drained); + anyhow::ensure!(drained, "previous chat catalog writes were not confirmed"); + } + fabric_turn_seq += 1; + // D8-2: one run_id per turn, generated at the turn entry and reused by + // every run_id consumer within this loop iteration (user event, route + // scope, assistant event). No parent_run_id is set (turns are not a spawn + // lineage; session relation is via chat_session_key). + let turn_run_id = uuid::Uuid::new_v4().to_string(); + let current_provider_binding = provider_binding.as_ref() + .ok_or_else(|| anyhow::anyhow!("chat provider binding is missing"))?; + current_provider_binding.verify(&ctx.config_generation, &provider, provider_name, model_name)?; + let cancellation = turn_signal.new_turn_cancellation(); + let mut input_scope = chat_message_event_scope( + memory_fabric.workspace_id(), &chat_session_key, &turn_run_id, provider_name, model_name, + ); + input_scope.config_generation_id = Some(ctx.config_generation.id.0); + input_scope.config_source_revision = Some(ctx.config_generation.source_revision.fingerprint_sha256.clone()); + // The TUI mirror is updated synchronously by /mode; its legacy session + // deliberately stops tracking mode when the reducer owns UI state. + #[cfg(feature = "terminal-tui")] + let admitted_chat_mode = chat_mirror.lock().chat_mode; + #[cfg(not(feature = "terminal-tui"))] + let admitted_chat_mode = chat_session.session().mode; + let has_conversation_history = history.iter().any(|message| message.role != "system"); + let (chat_user_event, admitted_binding, mut admission_guard) = current_provider_binding.record_guarded_with_origin( + memory_fabric.clone(), (input_scope, &chat_session_key, binding::ChatAdmissionMode::Model(admitted_chat_mode), has_conversation_history), &user_input, + format!("chat:{}:{turn_run_id}:{fabric_turn_seq}:user", chat_session.session().id), + child_cleanup.register(cancellation.clone())?, entry::prepare_origin(terminal_origin,&msg,&user_input)?, + ).await?; + let admission = admitted_binding + .issue_decision(&turn_service, &cancellation) + .await; + if let Err(error) = admission { + if let Err(record_error) = admission_guard.finish_failure( + cancellation.is_cancelled(), &format!("decision admission failed: {error}"), + ).await { + return Err(error.context(format!("Chat admission failure persistence is unconfirmed: {record_error}"))); + } + return Err(error); + } + admission_guard.handoff_terminal()?; + let chat_turn_binding = Some(Arc::clone(&admitted_binding)); + if one_shot.is_some() { + one_shot_binding = Some(Arc::clone(&admitted_binding)); + } + + let file_mention_enrichment = enrich_file_mentions_for_prompt(&user_input, tools_registry.as_ref()).await; + if let Some(note) = file_mention_enrichment.visible_note.as_deref() { + emit_chat_output(note); + } + let user_input_for_prompt = file_mention_enrichment.prompt; + + // Auto-save user message to memory + if config.memory.should_auto_promote_user_message(&user_input) { + let safe_user_input = sanitize_chat_semantic_memory_content(&user_input); + let _ = crate::agent::entry::save_current_input(&memory_fabric, + admitted_binding.envelope().run_id.as_deref().context("chat turn run id missing")?, + &admitted_binding.envelope().session_key, + &safe_user_input, chat_user_event.as_ref().map(|event| event.event_id.as_str())).await; + } + + // Inject memory context + let runtime_envelope = admitted_binding.envelope().clone(); + let memory_runtime = crate::agent::turn_request::ToolLoopMemory::new( + &mem, + &config.workspace_dir, + Some( + DocumentIngestRuntime::from_envelope(mem.clone(), &runtime_envelope) + .with_source_message_event_id(chat_user_event.as_ref().map(|event| event.event_id.clone())), + ), + ) + .with_event_fabric(memory_fabric.clone()) + .with_request_event_scope( + runtime_envelope.message_scope().with_recipient(format!("{provider_name}/{model_name}")), + ) + .with_tool_surface_reserve(tool_surface_reserve.clone()); + // The TUI handoff retains the original source input, before enrichment. + #[cfg(feature = "terminal-tui")] + let routing_input = admitted_binding.routing_input().to_owned(); + let mem_context = admitted_binding.recalled_context(mem.as_ref()).await; + let context = mem_context.preamble.clone(); + let enriched = if context.is_empty() { + user_input_for_prompt.clone() + } else { + format!("{context}{user_input_for_prompt}") + }; + + // Build system prompt with skill selection + let selected_skills = admitted_binding.prompt_skills()?; + // Publish only this turn's selected metadata. Previous turns do not + // grant continued Skill exposure; the prompt builder orders entries. + let system_prompt = build_chat_system_prompt(&config, model_name, &selected_skills, native_tools); + // An ordered, acknowledged read before this turn builds its sources + // and copies its provider view: every action sent before it (another + // turn's compaction whose finalization is still pending included) is + // applied first, so no turn starts from a view the session already + // compacted, and its start epoch is from before its own preflight. + let admitted_session = acknowledged_session_barrier(&chat_dispatcher, &turn_signal).await?; + if admitted_session.compaction_epoch != provider_view_compaction_epoch { + history = super::compaction::provider_view_from_acked(&history, &admitted_session); + provider_view_compaction_epoch = admitted_session.compaction_epoch; + } + let persisted_history_for_turn = persisted_history_for_current_turn(&chat_session.session(), &system_prompt, &user_input); + upsert_leading_system_prompt(&mut history, system_prompt.clone()); + // S2-C Step 4: dual-write SetLeadingSystemPrompt to the reducer — byte-for-byte aligned with + // the legacy `if empty { push } else { first_mut = ... }` (the reducer takes the same + // branches internally). It runs on every turn, and expressing it as an append would pile up + // system messages. + let _ = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::SetLeadingSystemPrompt { + content: system_prompt.clone(), + }, + "chat.system_prompt_per_turn", + ); + let history_len_before_user_turn = history.len(); + let history_user_message = crate::agent::turn_contracts::inbound_user_message(&enriched); + // The provider-side copy is read only by the TUI reducer driver. + // The compaction epoch the provider-side copy reflects; a worker + // compaction during the turn moves it on (see the finalizer). + #[cfg(feature = "terminal-tui")] + let compaction_epoch_at_start = admitted_session.compaction_epoch; + #[cfg(feature = "terminal-tui")] + let history_for_provider = { + let mut history_for_provider = history.clone(); + history_for_provider.push(history_user_message.clone()); + history_for_provider + }; + + // ── Set active recipient/channel on tools (for proactive messaging) ── + for tool in tools_registry.iter() { + if tool.name() == "message_send" { + continue; + } + tool.set_active_recipient("user").await; + tool.set_active_channel(Arc::clone(&terminal) as Arc).await; + } + + // ── Streaming pipeline setup ───────────────────────────── + // + // The delta channel carries ONLY visible assistant text — never the + // model's reasoning/thinking content. Reasoning is separated upstream + // at the provider parsing layer (see `parse_native_response` / + // `parse_sse_line` in providers/{anthropic,openai,ollama,compatible}.rs) + // and travels back via `ProviderChatResponse.reasoning_content`. The + // tool-call loop persists reasoning into conversation history through + // `build_native_assistant_history`; the live stream below renders text + // only, so the user never sees the model's internal monologue. + let (delta_tx, delta_rx) = mpsc::channel::(DELTA_CHANNEL_CAPACITY); + + // Start a streaming draft on the terminal + let draft_id = match terminal.send_draft(&SendMessage::new("", "user")).await { + Ok(id) => id, + Err(e) => { + tracing::debug!(error = %crate::agent::diagnostics::error_class(&e), "Failed to start draft"); + None + } + }; + + #[cfg(feature = "terminal-tui")] + anyhow::ensure!( + !reducer_driver_turn_active || draft_id.is_some(), + "admitted detached chat turn requires its terminal draft; execution was not requeued" + ); + + // Step 5b dual write: announce that a new LLM inference turn starts (only when a draft + // exists). In shadow mode the reducer sets stream.draft + control.generating=true, with no + // external side effects (business Effects are no-ops). + if let Some(ref d_id) = draft_id { + let _ = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::TurnStarted { + draft_id: d_id.clone(), + cancel: cancellation.clone(), + }, + "chat.turn_started", + ); + } + + // Spawn background task: accumulate deltas → channel.update_draft() + // Follows the exact same pattern as process_channel_message in channels/mod.rs. + // + // P1-6 — Monotonic draft version protocol (Step 3 update). The + // sender-side counter still stamps each accumulated snapshot with a + // strictly monotonic `u64` (kept for `update_draft` downstream + // consumers and the inline-redraw protocol). The receiver-side stale + // check formerly performed here by `DraftVersionTracker.accept()` has + // been DELETED — its protection is now owned end-to-end by the + // Redux-style reducer in `chat::state` via `StreamState::draft.version` + // (see `ChatState::reduce_stream_chunk_received`). + // + // Why this is safe to remove: + // 1. `delta_rx` is a single-task tokio mpsc; FIFO is guaranteed at + // the runtime layer (no parallel accumulators). + // 2. The counter is incremented atomically inside the same task, + // producing a strictly monotonic sequence by construction. The + // old tracker call was over-defence ("unreachable here" per the + // original comment). + // 3. The reducer's `StreamChunkReceived` arm now enforces + // strict-monotonic version + draft_id matching + finalize-state + // check as the single source of truth. Once Step 5 makes the + // reducer the renderer source, this task disappears entirely. + // + // Terminal TUI now relies on the reducer for the visible stream; the + // non-TUI fallback still forwards full accumulated drafts to the + // channel implementation. + let draft_updater = if let Some(ref d_id) = draft_id { + #[cfg(not(feature = "terminal-tui"))] + let channel: Arc = Arc::clone(&terminal); + #[cfg(not(feature = "terminal-tui"))] + let reply_target = "user".to_string(); + #[cfg(not(feature = "terminal-tui"))] + let draft_id_owned = d_id.clone(); + let mut rx = delta_rx; + let version_counter = Arc::new(DraftVersionCounter::new()); + // Step 5b dual write: send every delta through the coalescer as + // Action::StreamChunkReceived. When the bounded(2048) action_tx is full the coalescer + // merges deltas, so nothing grows without bound. + let coalescer_sender = chat_dispatcher.sender(); + let coalescer_draft_id = d_id.clone(); + Some(tokio::spawn(async move { + #[cfg(not(feature = "terminal-tui"))] + let mut accumulated = String::new(); + let mut coalescer = dispatcher::StreamChunkCoalescer::new(coalescer_sender); + while let Some(delta) = rx.recv().await { + // Counter still ticks for downstream consumers (UiActor's + // inline-redraw protocol uses it). No tracker.accept() — + // see comment block above. + let version = version_counter.next(); + #[cfg(not(feature = "terminal-tui"))] + { + accumulated.push_str(&delta); + if let Err(e) = channel.update_draft(&reply_target, &draft_id_owned, &accumulated).await { + tracing::debug!(error = %crate::agent::diagnostics::error_class(&e), "Draft update failed"); + } + } + // Step 5b shadow: forward the **incremental** delta into + // the reducer via the coalescer. The reducer accumulates + // its own `draft.accumulated` mirror — feeding the full + // `accumulated` string here would cause double-accumulation. + // Backpressure or close are silently tolerated (legacy + // path remains the renderer source; shadow path observes). + let _ = coalescer.try_send_chunk(coalescer_draft_id.clone(), delta, version); + } + // Stream ended — flush pending coalescer state, counter goes + // out of scope; reducer-side version state is cleared on + // StreamCompleted/Failed/Cancelled (dispatched from the chat::run main loop). + let _ = coalescer.flush(); + })) + } else { + // No draft — consume delta_rx so the sender doesn't block + let mut rx = delta_rx; + Some(tokio::spawn(async move { while rx.recv().await.is_some() {} })) + }; + + #[cfg(not(feature = "terminal-tui"))] + { + *active_cancel.lock() = Some(cancellation.clone()); + } + + // ── Tool event forwarding (visual feedback in terminal) ── + // + // P2-7: in addition to the existing notify_tool_* calls (which feed + // the legacy UiActor renderer in `channels/terminal.rs`), we also + // mirror every tool event into a `TuiState` instance behind a + // `parking_lot::Mutex`. The ratatui renderer in `chat/tui.rs` reads + // from this mirror; full renderer wiring lands in P2-12. + let (tool_event_tx, mut tool_event_rx) = mpsc::channel::(TOOL_EVENT_CHANNEL_CAPACITY); + let terminal_for_tools = Arc::clone(&terminal); + // P3-3: every producer in this turn now shares the chat-scoped + // `chat_mirror` (created once at the top of `run`). The previous + // per-turn `tui_mirror` instance is gone — keeping a per-turn alias + // here so downstream code that already says `tui_mirror.lock()` keeps + // compiling, but the underlying `Arc` is the same one the render + // task and the input task hold. + #[cfg(feature = "terminal-tui")] + let tui_mirror: Arc> = Arc::clone(&chat_mirror); + // P0-5 fix: tool start/finish events now have a single mirror path. + // The UiActor in `channels/terminal.rs::handle_event_tui` is the sole + // writer of tool cards into `TuiState` (it sanitises name/args via + // `sanitize_terminal_output` and calls `notify_redraw()` on the same + // 1-slot channel as `redraw_tx_for_main`). The previous double-mirror + // here pushed a second card and could reorder Running/Done with the + // UiActor path under load — the forwarder now just relays the event + // to the UiActor and lets that path own the mirror mutation. + let tool_event_forwarder = tokio::spawn(async move { + while let Some(notif) = tool_event_rx.recv().await { + match notif { + ToolCallNotification::Started { name, args_summary, .. } => { + terminal_for_tools.notify_tool_started(&name, &args_summary).await; + } + ToolCallNotification::Finished { + name, + success, + duration_ms, + .. + } => { + terminal_for_tools + .notify_tool_finished(&name, success, duration_ms) + .await; + } + ToolCallNotification::Progress { iteration } => { + terminal_for_tools.notify_progress(iteration).await; + } + } + } + }); + // Log a trace stat so the mirror is observably wired (also keeps the + // `tui_mirror` binding from being flagged as unused when the renderer + // wiring lands in P2-12). + #[cfg(feature = "terminal-tui")] + { + let tracked_tool_cards_count: usize = + tui_mirror.lock().last_tool_result_index().map_or(0, |index| index + 1); + tracing::trace!(tracked_tool_cards_count, "tui_mirror initialized"); + } + + // ── Unified tool authorization (permission-model Phase 1) ── + // Tool access is governed solely by `[autonomy]` via + // `SecurityPolicy::decide`; the former PolicyPipeline is removed. + let scope_owner_id = runtime_envelope.resolved_owner_id(); + let scope_ctx = ScopeContext { + policy: &security, + sender: "user", + channel: "terminal", + chat_type: "private", + chat_id: "terminal:user", + session_key: Some(&runtime_envelope.session_key), + owner_id: Some(&scope_owner_id), + owner_isolated: runtime_envelope.owner_isolated, + topic_id: runtime_envelope.topic_id.as_deref(), + task_id: runtime_envelope.resolved_task_id(), + source_message_event_id: runtime_envelope.source_message_event_id.as_deref(), + config_generation_id: runtime_envelope.config_generation_id, + config_source_revision: runtime_envelope.config_source_revision.as_deref(), + }; + + let mut effective_compaction = admitted_binding.effective_compaction()?; + effective_compaction.config = admitted_binding.main_compaction() + .ok_or_else(|| anyhow::anyhow!("chat compaction requires an admitted decision"))?.clone(); + crate::providers::context_window::trace_effective_compaction_resolution(&effective_compaction); + #[cfg(feature = "terminal-tui")] + refresh_context_budget_for_tui( + &history_for_provider, + &effective_compaction.config, + &tool_surface_reserve, + redraw_tx_for_main.is_some(), + &chat_mirror, + &chat_dispatcher, + ); + + let route_decision = RouteDecision::from_model_routes_for_context( + provider_name, + model_name, + &config.model_routes, + runtime_envelope.resolved_owner_id(), + chat_session_key.clone(), + chat_user_event.as_ref().map(|event| event.event_id.clone()), + "chat", + (user_input.chars().count() / 4 + 1).min(u32::MAX as usize) as u32, + true, + false, + ); + let route_scope = route_event_scope( + "chat", + Some(runtime_envelope.resolved_owner_id()), + Some(chat_session_key.clone()), + Some(turn_run_id.clone()), + Some("local-user".to_string()), + Some(format!( + "{}/{}", + route_decision.selected.provider, route_decision.selected.model + )), + ); + if let Err(e) = record_route_decision_event(&memory_fabric, route_scope.clone(), &route_decision).await { + tracing::warn!(error = %crate::agent::diagnostics::error_class(&e), "Failed to append router.route_decision message event"); + } + let provider_started_at = chrono::Utc::now(); + + // The shared turn engine owns context-overflow recovery. Chat projects + // its final outcome and does not start a second compaction/replay loop. + // + // There is deliberately no wall-clock budget around the turn. A chat turn + // ends when it finishes, when the user cancels it, or when the stall + // detector in `crate::agent::idle` finds it has stopped making progress. + #[cfg(feature = "terminal-tui")] + let history_len_before_tools; + + // S2-A refinement: split the coarse `Failed` variant so the Redux + // dispatch path can distinguish user-driven cancellation from real + // errors. The legacy renderer still treats every non-Success as a + // failure (continue), but the reducer now sees the correct semantic + // (`StreamCancelled` vs `StreamFailed { err, retryable }`). + enum TurnOutcome { + // FIX-P0-30/31: carry the loop's provider-attribution trace so the + // success path can record the *real* serving model/attempts instead + // of the routed `decision.selected.model`. + Success(String), + /// User-initiated cancel (Ctrl+C) or `is_tool_loop_cancelled` from + /// the inner loop. Reducer side maps to `StreamCancelled`. + Cancelled, + /// Genuine failure (timeout / context-overflow exhausted / other + /// error). Carries error string + retryable hint for the reducer's + /// `StreamFailed` payload (mirrors `dispatcher::TurnOutcomeKind::Failed`). + FailedWithError { + err: String, + retryable: bool, + }, + } + + // The terminal TUI always routes a turn to the reducer driver; without + // the TUI the shared agent loop runs it (the driver branch is cfg'd out). + #[cfg(feature = "terminal-tui")] + tracing::info!( + redux_mode = ?top_redux_mode, + // Registry roots before routing, refresh and alias expansion; + // the wire count is the compiled-request event's + // `tool_snapshot.count`. + registry_root_tools = Vec::len(&tools_registry), + route = "ReduxDriver", + "chat::run turn route decision" + ); + let provider_history_len_before_assistant; + // The identity of the request recorded at admission: an aborted turn + // settles by it, so no earlier request with the same text is touched. + let admission; + #[cfg(feature = "terminal-tui")] + { + if reducer_driver_turn_active { + admission = None; + provider_history_len_before_assistant = history_for_provider.len(); + } else { + admission = Some(record_user_turn_at_admission(&chat_dispatcher, &turn_signal, &user_input).await?); + history.push(history_user_message.clone()); + provider_history_len_before_assistant = history.len(); + } + } + #[cfg(not(feature = "terminal-tui"))] + { + admission = Some(record_user_turn_at_admission(&chat_dispatcher, &turn_signal, &user_input).await?); + history.push(history_user_message.clone()); + provider_history_len_before_assistant = history.len(); + } + + let provider_turn_task_id = start_provider_turn_task( + &mut turn_scheduler, + provider_queue_task_id, + &user_input, + history_len_before_user_turn, + ); + anyhow::ensure!( + !chat_turn_binding.as_ref().is_some_and(|binding| binding.is_decided()) || provider_turn_task_id.is_some(), + "decision-owned Chat turn could not acquire a scheduler task" + ); + if one_shot.is_some() { + one_shot_task_id = provider_turn_task_id; + } + register_provider_history_commit_task(&mut history_commit_coordinator, &turn_scheduler, provider_turn_task_id); + record_provider_turn_completion_context( + &mut provider_turn_completion_contexts, + provider_turn_task_id, + provider_history_len_before_assistant, + ); + register_provider_turn_worker( + &mut provider_turn_workers, + &turn_scheduler, + provider_turn_task_id, + provider_worker_kind, + ); + publish_main_queue_status(&chat_dispatcher, &turn_scheduler); + publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); + + // ── Redux driver switched-over path (Step 5a-4) ──────────── + // + // Entered only when routing selects ReduxDriver. dispatch Action::StartLLMTurn → + // EffectExecutor::execute_real(Effect::StartTurn) → spawn drive_start_turn_stream + // streaming driver → post StreamChunkReceived / Completed / Failed / Cancelled back through + // action_tx → the dispatcher task reduces them and calls turn_signal.record_and_notify → + // this code awaits the outcome. + // + // This branch does **not** call run_turn; the old path does not run at all: + // * no duplicate hooks (the old path's hooks.emit does not run; only the reducer's + // NotifyHook(Error) writes) + // * no duplicate history writes (the reducer writes once through RecordAssistantTurn) + // * round 2 hang defence: shutdown.cancelled() as a fallback arm of tokio::select! + // + #[cfg(feature = "terminal-tui")] + if reducer_driver_turn_active && let Some(d_id) = draft_id.clone() { + // Protocol: register the keyed turn before dispatch, then obtain the + // waiter. The legacy single-slot signal remains as fallback while + // P6J migrates toward detached provider workers. + if let Some(id) = provider_turn_task_id { + turn_signal.register_turn(id, d_id.clone()); + let _ = turn_signal.consume_turn_outcome(id); + let _ = turn_signal.consume_turn_usage(id); + } + if let Some(id) = provider_turn_task_id { + spawn_provider_turn_completion_waiter( + turn_signal.clone(), + id, + provider_completion_tx.clone(), + shutdown.clone(), + ); + } + let mut notify_fut: Option + Send + '_>>> = + provider_turn_task_id + .is_none() + .then(|| Box::pin(turn_signal.notified()) as _); + // Consume any leftover outcome before dispatching, so what we read belongs to this turn. + let _ = turn_signal.consume_outcome(); + + // S2.5 P1-A: handle dispatch_result in explicit branches (a failed StartLLMTurn must + // fall through, otherwise notify_fut hangs forever); dispatch_or_log already meters and + // warns, so no extra tracing is needed. + // D8-4 (redux path real fix): seed the turn-root spawn execution + // context for this turn and hand it to the driver via StartLLMTurn → + // Effect::StartTurn. This is the redux mirror of the legacy + // `SPAWN_EXECUTION_CONTEXT.scope(seed_turn_context(turn_run_id, ..))` + // wrapper applied below at the legacy tool-loop path's `run_turn` call + // — the redux path `continue`s before reaching it, so the seed must + // travel with the effect. Same `turn_run_id` + `chat_session_key` + // source as the legacy path (single source of truth) so a sub-agent + // spawned inside this turn inherits `parent_run_id = turn_run_id`. + let mut redux_turn_spawn_ctx = crate::tools::sessions_spawn::SpawnExecutionContext::seed_turn_context( + turn_run_id.clone(), + chat_session_key.clone(), + ); + redux_turn_spawn_ctx.owner_id = Some(runtime_envelope.resolved_owner_id()); + redux_turn_spawn_ctx.topic_id = runtime_envelope.topic_id.clone(); + redux_turn_spawn_ctx.source_message_event_id = runtime_envelope.source_message_event_id.clone(); + let redux_turn_message_send_ctx = crate::tools::message_send::MessageSendExecutionContext::new( + Some("user".to_string()), + Arc::clone(&terminal) as Arc, + ); + let provider_turn_sequence = + provider_turn_task_id.and_then(|id| turn_scheduler.task(id).map(|task| task.sequence)); + let dispatch_result = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::StartLLMTurn { + provider_turn_task_id, + provider_turn_sequence, + draft_id: d_id.clone(), + history: history_for_provider.clone(), + compaction_guard_history: Some(persisted_history_for_turn.clone()), + compaction_config: Some(effective_compaction.config.clone()), + cancel: cancellation.clone(), + turn_spawn_ctx: Some(redux_turn_spawn_ctx), + turn_message_send_ctx: Some(redux_turn_message_send_ctx), + // Route on what the user typed. `history_for_provider` + // already carries the memory preamble and the + // `[Recent shared workspace events]` block, and routing on + // that let injected text widen the published tool surface. + routing_input: Some(routing_input.clone()), + turn_binding: chat_turn_binding.clone(), + }, + "chat.start_llm_turn", + ); + // Codex P1: the dispatch may be Backpressured / ChannelClosed. Either failure means the + // dispatcher task will not produce a turn outcome, so chat::run must immediately treat it + // as Failed and fall through to cleanup, otherwise notify_fut is never fired. + if !matches!(dispatch_result, dispatcher::DispatchResult::Sent) { + tracing::warn!( + result = dispatch_result.kind(), + "Redux driver: StartLLMTurn dispatch failed; aborting turn" + ); + // S2-B Step 3: send StreamCancelled synchronously so the reducer clears + // active_cancel; the old field is only a fallback under Off/Both (symmetric with the + // guard at the register site). + if let Some(ref d_id) = draft_id { + let _ = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::StreamCancelled { draft_id: d_id.clone() }, + "chat.stream_cancelled_dispatch_failed", + ); + } + #[cfg(not(feature = "terminal-tui"))] + { + *active_cancel.lock() = None; + } + drop(delta_tx); + drop(tool_event_tx); + if let Some(handle) = draft_updater { + let _ = handle.await; + } + let _ = tool_event_forwarder.await; + if let Some(ref id) = draft_id { + let _ = terminal.cancel_draft("user", id).await; + } + enqueue_provider_turn_finalizer_event( + &mut provider_turn_finalizer_events, + provider_turn_task_id, + ProviderTurnTerminalPlan::Failed { + err: "redux driver dispatch failed".to_string(), + history_commit_len: take_provider_turn_completion_history_len( + &mut provider_turn_completion_contexts, + provider_turn_task_id, + history.len(), + ), + summary: "redux driver dispatch failed".to_string(), + }, + ); + continue; + } + + if let Some(task_id) = provider_turn_task_id { + if per_turn_contexts + .insert( + task_id, + PerTurnContext { + turn_binding: chat_turn_binding.clone(), + + task_id, + draft_id: d_id.clone(), + delta_tx: Some(delta_tx), + tool_event_tx: Some(tool_event_tx), + draft_updater, + tool_event_forwarder: Some(tool_event_forwarder), + user_input: user_input.clone(), + turn_run_id: turn_run_id.clone(), + route_scope: route_scope.clone(), + route_decision: route_decision.clone(), + provider_started_at, + provider_name: provider_name.to_string(), + model_name: model_name.to_string(), + history_len_before_user_turn, + compaction_epoch_at_start, + assignment: assignment_guard.take(), + }, + ) + .is_some() + { + tracing::warn!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), + "replaced pending Redux turn context before completion" + ); + } + continue; + } + + // Shutdown preemption guard against a round 2 hang. + let mut turn_input_open = true; + let mut provider_completion_event: Option = + provider_turn_task_id.and_then(|id| pending_provider_completion_events.remove(&id)); + if provider_completion_event.is_none() { + loop { + tokio::select! { + () = async { + if let Some(fut) = notify_fut.as_mut() { + fut.await; + } else { + std::future::pending::<()>().await; + } + } => break, + completion = provider_completion_rx.recv(), if provider_turn_task_id.is_some() => { + let Some(completion) = completion else { + break; + }; + // the completion of the current turn; `None`: retained as pending + if let Some(completion) = route_provider_completion_event_and_publish( + &mut provider_turn_lifecycle_rx, + &mut provider_turn_lifecycle_events_open, + &mut provider_turn_workers, + &mut pending_provider_completion_events, + provider_turn_task_id, + completion, + &chat_dispatcher, + ) { + provider_completion_event = Some(completion); + break; + } + } + lifecycle = provider_turn_lifecycle_rx.recv(), if provider_turn_lifecycle_events_open => { + let Some(lifecycle) = lifecycle else { + provider_turn_lifecycle_events_open = false; + continue; + }; + record_provider_turn_lifecycle_event( + &mut provider_turn_workers, + lifecycle, + ); + publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); + } + () = shutdown.cancelled() => { + tracing::debug!("Redux driver: shutdown.cancelled before turn complete"); + break; + } + msg = input_rx.recv(), if turn_input_open => { + let Some(msg) = msg else { + turn_input_open = false; + continue; + }; + let daemon_control = DaemonControl { + config: &config, + dispatcher: &chat_dispatcher, + redraw_tx: redraw_tx_for_main.as_ref(), + }; + let queued_from = input_backlog.len(); + process_active_turn_input_batch( + msg, + &mut emit_chat_output, + &mut input_rx, + &mut input_backlog, + &mut turn_scheduler, + &mut provider_turn_workers, + provider_turn_task_id, + &chat_dispatcher, + &chat_session.session(), + &mut chat_sessions, + &session_rings, + &mut reaped_log_archive, + &reap_policy, + &tools_registry, + daemon_control, + ) + .await; + if plain_typed_queue { + let added = lines_queued_since(&input_backlog, queued_from); + settle_queued_lines(&mut input_backlog, &mut turn_scheduler, &added); + } + publish_main_queue_status(&chat_dispatcher, &turn_scheduler); + } + } + } + } + + let resolved_completion = + resolve_provider_turn_completion(&turn_signal, provider_turn_task_id, provider_completion_event); + let completion_history_len = take_provider_turn_completion_history_len( + &mut provider_turn_completion_contexts, + provider_turn_task_id, + history.len(), + ); + let terminal_plan = provider_turn_terminal_plan_from_completion( + resolved_completion, + completion_history_len, + &tools_registry, + ); + enqueue_provider_turn_finalizer_event( + &mut provider_turn_finalizer_events, + provider_turn_task_id, + terminal_plan.clone(), + ); + let finalizer_result = drain_provider_turn_finalizer_events_and_publish( + &mut turn_scheduler, + &mut history_commit_coordinator, + &mut provider_turn_workers, + &mut provider_turn_finalizer_events, + &chat_dispatcher, + ) + .into_iter() + .rev() + .find(|result| result.task_id == provider_turn_task_id) + .unwrap_or(ProviderTurnFinalizerResult { + task_id: provider_turn_task_id, + terminal_status: "unknown", + finalized: false, + }); + + // Finalize streaming (aligned with the legacy teardown): drop the senders so the + // background tasks wind down. + // + // S2-B Step 3: on the driver path the reducer already cleared + // `state.control.active_cancel` when it received StreamCompleted/Failed/Cancelled; the + // legacy Arc is only a fallback under Off/Both. + #[cfg(not(feature = "terminal-tui"))] + { + *active_cancel.lock() = None; + } + drop(delta_tx); + drop(tool_event_tx); + if let Some(handle) = draft_updater { + let _ = handle.await; + } + let _ = tool_event_forwarder.await; + + match terminal_plan { + ProviderTurnTerminalPlan::Completed { + final_text, + recorded_response, + empty_response, + usage: redux_tokens_used, + history_commit_len, + .. + } => { + if empty_response { + let provider_outcome = if let Some(binding) = chat_turn_binding.as_ref() { + binding.provider_outcome(&route_decision, provider_started_at)? + } else { ProviderExecutionOutcome::success_for_decision_with_usage( + &route_decision, provider_started_at, redux_tokens_used.clone(), + ) }; + if !finalizer_result.finalized { + if let Err(e) = terminal.cancel_draft("user", &d_id).await { + tracing::debug!(error = %crate::agent::diagnostics::error_class(&e), "Redux driver: cancel empty-response draft failed"); + } + publish_main_queue_status(&chat_dispatcher, &turn_scheduler); + publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); + continue; + } + if let Err(e) = terminal.cancel_draft("user", &d_id).await { + tracing::debug!(error = %crate::agent::diagnostics::error_class(&e), "Redux driver: cancel empty-response draft failed"); + } + let terminal_usage = match finalize_chat_success_turn( + chat_turn_binding.as_deref(), + &memory_fabric, + &chat_session_key, + &turn_run_id, + provider_name, + model_name, + route_scope.clone(), + provider_outcome.clone(), + None, + history_commit_len, + "redux driver completed with empty response", + &config.cost, + &config.workspace_dir, + ) + .await + { + Ok(receipt) => receipt.into_session_usage(), + Err(error) => { + tracing::error!(error = %crate::agent::diagnostics::error_class(&error), "Chat terminal persistence is unconfirmed"); + return Err(error); + } + }; + if let Err(error) = dispatch_final_usage( + &chat_dispatcher, + &turn_signal, + &mut turn_scheduler, + provider_turn_task_id, + terminal_usage, + "chat.provider_usage_recorded_empty_response", + ) + .await + { + anyhow::bail!("Chat stopped after an unconfirmed history commit: {error}"); + } + #[cfg(feature = "terminal-tui")] + if let Some(tx) = redraw_tx_for_main.as_ref() { + let _ = tx.try_send(()); + } + surface_turn_elapsed_message( + &chat_dispatcher, + sessions_redraw_handle.as_ref(), + "completed", + provider_outcome.started_at, + provider_outcome.finished_at, + ); + publish_main_queue_status(&chat_dispatcher, &turn_scheduler); + publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); + continue; + } + let provider_outcome = if let Some(binding) = chat_turn_binding.as_ref() { + binding.provider_outcome(&route_decision, provider_started_at)? + } else { ProviderExecutionOutcome::success_for_decision_with_usage( + &route_decision, provider_started_at, redux_tokens_used.clone(), + ) }; + if !finalizer_result.finalized { + if let Err(e) = terminal.cancel_draft("user", &d_id).await { + tracing::debug!(error = %crate::agent::diagnostics::error_class(&e), "Redux driver: cancel commit-gated draft failed"); + } + publish_main_queue_status(&chat_dispatcher, &turn_scheduler); + publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); + continue; + } + // 1) Write the final text accumulated by the driver's stream back into the LLM + // history (aligned with the legacy tail + // `history.push(ChatMessage::assistant(...))`). + history.push(committed_reply_message(&chat_dispatcher.session_reader().acked(), &final_text)); + // 2) finalize_draft: deliver the text to the terminal channel so the user sees + // it (the driver path does not go through the delta_tx → draft_updater chain, + // it finalizes directly). + if let Err(e) = terminal.finalize_draft("user", &d_id, &final_text).await { + tracing::warn!(error = %crate::agent::diagnostics::error_class(&e), "Redux driver: finalize_draft failed"); + } + let terminal_usage = match finalize_chat_success_turn( + chat_turn_binding.as_deref(), + &memory_fabric, + &chat_session_key, + &turn_run_id, + provider_name, + model_name, + route_scope.clone(), + provider_outcome.clone(), + Some(recorded_response.clone()), + history_commit_len, + "redux driver completed", + &config.cost, + &config.workspace_dir, + ) + .await + { + Ok(receipt) => receipt.into_session_usage(), + Err(error) => { + tracing::error!(error = %crate::agent::diagnostics::error_class(&error), "Chat terminal persistence is unconfirmed"); + return Err(error); + } + }; + let attempts_count = u8::try_from(provider_outcome.attempts.len()).unwrap_or(u8::MAX); + crate::runtime::control_ladder::append_provider_outcome_trace( + std::path::Path::new(&config.workspace_dir), + &provider_outcome.decision_id, + &provider_outcome.final_provider, + &provider_outcome.final_model, + attempts_count, + "success", + ); + // On this driver path the worker's sink already sent + // RecordAssistantTurn + StreamCompleted (fixB B5); the + // reducer owns the turn, and the slash commands read its + // acknowledged snapshot. + if let Err(error) = dispatch_final_usage( + &chat_dispatcher, + &turn_signal, + &mut turn_scheduler, + provider_turn_task_id, + terminal_usage, + "chat.provider_usage_recorded", + ) + .await + { + anyhow::bail!("Chat stopped after an unconfirmed history commit: {error}"); + } + #[cfg(feature = "terminal-tui")] + if let Some(tx) = redraw_tx_for_main.as_ref() { + let _ = tx.try_send(()); + } + surface_turn_elapsed_message( + &chat_dispatcher, + sessions_redraw_handle.as_ref(), + "completed", + provider_outcome.started_at, + provider_outcome.finished_at, + ); + publish_main_queue_status(&chat_dispatcher, &turn_scheduler); + publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); + let _ = final_text; + } + ProviderTurnTerminalPlan::Failed { err, .. } => { + if let Err(error) = finalize_chat_non_success_turn( + chat_turn_binding.as_deref(), + &memory_fabric, + &turn_run_id, + route_scope.clone(), + crate::agent::terminal::TurnTerminalStatus::Failed, + None, + provider_started_at, + &format!("redux driver failed: {err}"), + &config.cost, + &config.workspace_dir, + ) + .await + { + if chat_turn_binding.as_ref().is_some_and(|binding| binding.is_decided()) { return Err(error); } + tracing::warn!(error = %crate::agent::diagnostics::error_class(&error), "Failed to commit shared failed Chat terminal event"); + } + // The worker's compactions and terminal precede this settlement on the + // action channel; the reducer never recorded a driver turn's request. + let settled = settle_aborted_turn(&chat_dispatcher, &turn_signal, None).await?; + provider_view_after_settled_abort(&mut history, &settled, compaction_epoch_at_start, false, None); + // The reducer's NotifyHook(Error) has already been sent; do not hooks.emit here + // again, to avoid duplicates. + #[cfg(feature = "terminal-tui")] + let interactive_tui_active = redraw_tx_for_main.is_some(); + #[cfg(not(feature = "terminal-tui"))] + let interactive_tui_active = false; + + if !interactive_tui_active && let Some(ref id) = draft_id { + let _ = terminal.cancel_draft("user", id).await; + } + if !interactive_tui_active { + super::output::print_turn_failure(plain_mode, &err); + } + if plain_mode { + plain_mode_turn_failed = true; + } + surface_turn_elapsed_message( + &chat_dispatcher, + sessions_redraw_handle.as_ref(), + "failed", + provider_started_at, + chrono::Utc::now(), + ); + publish_main_queue_status(&chat_dispatcher, &turn_scheduler); + publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); + } + ProviderTurnTerminalPlan::Cancelled { .. } => { + if let Err(error) = finalize_chat_non_success_turn( + chat_turn_binding.as_deref(), + &memory_fabric, + &turn_run_id, + route_scope.clone(), + crate::agent::terminal::TurnTerminalStatus::Cancelled, + None, + provider_started_at, + "redux driver cancelled", + &config.cost, + &config.workspace_dir, + ) + .await + { + if chat_turn_binding.as_ref().is_some_and(|binding| binding.is_decided()) { return Err(error); } + tracing::warn!(error = %crate::agent::diagnostics::error_class(&error), "Failed to commit shared cancelled Chat terminal event"); + } + if let Some(ref id) = draft_id { + let _ = terminal.cancel_draft("user", id).await; + } + let settled = settle_aborted_turn(&chat_dispatcher, &turn_signal, None).await?; + provider_view_after_settled_abort( + &mut history, + &settled, + compaction_epoch_at_start, + false, + Some(history_len_before_user_turn), + ); + publish_main_queue_status(&chat_dispatcher, &turn_scheduler); + publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); + } + } + + continue; + } + + // The compaction epoch before the preflight: a compaction adopted by + // the preflight or during the turn moves it, and every turn end then + // rebuilds the provider view from the acknowledged session. + let inline_compaction_epoch_before_preflight = admitted_session.compaction_epoch; + let legacy_budget_config = tool_surface_reserve.reserved_config(&effective_compaction.config); + let preflight_budget = crate::agent::context_budget::plan_context_budget( + &history, + &legacy_budget_config, + crate::agent::context_budget::PRE_TURN_FLUSH_THRESHOLD, + ); + if preflight_budget.over_hard_limit { + let audit_source_history = original_legacy_chat_compaction_audit_source(persisted_history_for_turn.messages()); + let summary_projection = bounded_legacy_chat_compaction_audit_source(persisted_history_for_turn.messages()); + let token_metadata = legacy_compaction_token_metadata(&history, persisted_history_for_turn.messages()); + let (turns_before, tokens_before) = super::compaction::chat_history_turns_and_tokens(&history); + // The request is already recorded (`UserTurnAdmitted` above), so the + // source is the persisted history including it and the reducer gets + // the same patch. The enriched request replaces the source's plain + // final message in the provider view. + let enriched_request = history.last().filter(|message| message.role == "user").cloned(); + let preflight_outcome = if let Some(patch) = build_chat_compaction_patch( + &history, + &persisted_history_for_turn, + provider.as_ref(), + model_name, + &legacy_budget_config, + memory_runtime.ingest(), + "chat_preflight", + ) + .await + { + apply_chat_compaction_patch_and_sync( + &mut history, + &persisted_history_for_turn, + enriched_request, + patch, + &legacy_budget_config, + crate::chat::action::CompactReason::ContextOverflow, + &chat_dispatcher, + &turn_signal, + ) + .await + } else { + // No handoff or summary: the session and this view stay as they + // are; the turn's own preflight trims each request (a projection + // that is never persisted). + super::compaction::ManualCompactOutcome::NoDurableCompaction + }; + persist_legacy_chat_compaction_audit( + mem.as_ref(), + &runtime_envelope, + &audit_source_history, + &summary_projection, + token_metadata, + "chat_preflight", + ) + .await; + #[cfg(feature = "terminal-tui")] + refresh_context_budget_for_tui( + &history, + &effective_compaction.config, + &tool_surface_reserve, + redraw_tx_for_main.is_some(), + &chat_mirror, + &chat_dispatcher, + ); + let compact_msg = preflight_outcome.feedback(turns_before, tokens_before, &legacy_budget_config); + surface_session_message(&chat_dispatcher, sessions_redraw_handle.as_ref(), &compact_msg); + tracing::warn!( + before_used_tokens = preflight_budget.used_tokens, + hard_limit = preflight_budget.available_input_tokens, + "legacy chat context budget preflight compacted before provider call" + ); + } + + // The inline loop hands its in-turn compactions to the reducer instead + // of keeping them as private mutations of `history`; after the turn the + // view follows the acknowledged session (`reconcile_inline_turn`). The + // reducer history it guards against holds the recorded request once: + // after an adopted preflight the acknowledged snapshot already holds + // it, identified by this turn's admission, and it keeps its `Request` + // origin, so an in-turn compaction that keeps it records it once. + let inline_compaction = { + let reducer_source = super::session_store::canonical_history_for_admitted_turn( + &chat_session.acked(), + &system_prompt, + admission, + &user_input, + ); + super::compaction::InlineCompactionSink::new(chat_dispatcher.clone(), turn_signal.clone(), &user_input, reducer_source) + }; + // The inline turn's canonical history: the acknowledged turns plus the + // plain request, never the enriched provider view (r6-2). + let inline_canonical = inline_compaction.reducer_source(); + + // D8-4: seed a turn-root spawn execution context so a sub-agent spawned + // directly from this chat turn inherits parent_run_id = the per-turn + // run_id. spawn_depth starts at 0 and is_turn_root keeps the first child's + // reported depth at 0 (a turn is not itself a spawn). A spawned child records + // under its own `spawn:` key, never under this chat session key. + let turn_spawn_ctx = crate::tools::sessions_spawn::SpawnExecutionContext::seed_turn_context( + turn_run_id.clone(), + chat_session_key.clone(), + ); + let turn_message_send_ctx = crate::tools::message_send::MessageSendExecutionContext::new( + Some("user".to_string()), + Arc::clone(&terminal) as Arc, + ); + + // The view this turn starts from; a turn that changes it other than by + // appending (a compaction, a projection trim, a middleware rewrite) + // rebuilds it from the session when it ends. + let inline_view_before_turn = super::compaction::ViewPrefix::of(&history); + // Keep the large trace inline outside the small outcome discriminator. + let (turn_outcome, successful_trace) = { + #[cfg(feature = "terminal-tui")] + { + history_len_before_tools = history.len(); + } + + let result = crate::tools::message_send::MESSAGE_SEND_EXECUTION_CONTEXT + .scope( + turn_message_send_ctx.clone(), + crate::tools::sessions_spawn::SPAWN_EXECUTION_CONTEXT.scope(turn_spawn_ctx.clone(), async { + run_turn( + &mut history, + crate::agent::turn_request::TurnRequest { + advice: admitted_binding.decision_advice(), + channel_name: "terminal", + scope: Some(&scope_ctx), + mode: admitted_binding.admitted_model_mode()?, + silent: false, + expose_stay_silent: false, + multimodal: &config.multimodal, + schedule: crate::agent::turn_request::TurnSchedule { + read_only_tool_concurrency_window: config.agent.read_only_tool_concurrency_window, + priority_scheduling_enabled: config.agent.priority_scheduling_enabled, + low_priority_tool_names: config.agent.low_priority_tools.clone(), + }, + compaction: Some(&effective_compaction.config), + decision: admitted_binding.decision_routing() + .ok_or_else(|| anyhow::anyhow!("chat runtime turn requires an admitted decision"))?, + }, + crate::agent::turn_request::TurnServices { + provider: provider.as_ref(), + provider_name, + model: model_name, + temperature, + tools_registry: Arc::clone(&tools_registry), + observer: observer.as_ref(), + hooks: &hooks, + approval: Some(Arc::clone(&approval_manager)), + approval_resolver: None, + // Supervised calls ask on the terminal (CR-2), as on the reducer path. + runtime_adapter: chat_turn_binding.as_ref().map(|binding| crate::agent::turn_contracts::ToolLoopRuntimeAdapter { + live_frames: None, + guarded_delivery: true, + provider_trace: binding.retained_provider_trace(), + events: Some(Arc::clone(&inline_compaction) as Arc), + stream_provider: false, + tool_execution_service: Some(Arc::new(super::line_approval::line_tool_execution_service( + Arc::clone(&tools_registry), &mem, &security, + Arc::clone(&approval_manager), cancellation.clone(), + Arc::new(super::terminal_approval::ControllingTerminal), + ))), + tool_execution_context: super::approval_context::line_mode(binding.envelope().clone()) + .with_approval_ledger(binding.h2_approval_ledger()), + allowed_tool_names: None, + }), + memory: memory_runtime.clone().with_canonical_history(inline_canonical.clone(), false), + }, + crate::agent::turn_request::TurnDelivery { + cancellation: Some(cancellation.clone()), + on_delta: Some(delta_tx.clone()), + on_tool_call: Some(tool_event_tx.clone()), + }, + ) + .await + .map(|(outcome, trace)| (outcome.into_text(), trace)) + }), + ) + .await; + + match result { + // ── Success ─────────────────────────────────────── + Ok((resp, trace)) => (TurnOutcome::Success(resp), Some(trace)), + // ── Cancelled (Ctrl+C) ──────────────────────────── + Err(ref e) if is_tool_loop_cancelled(e) || cancellation.is_cancelled() => { + if let Some(ref d_id) = draft_id { + let _ = terminal.cancel_draft("user", d_id).await; + } + // S2-A: user-driven cancel — distinguished from real + // failures so the reducer emits `StreamCancelled` (no + // Error hook fan-out) instead of `StreamFailed`. + (TurnOutcome::Cancelled, None) + } + // ── Other errors ────────────────────────────────── + Err(e) => { + if let Some(ref d_id) = draft_id { + let _ = terminal.cancel_draft("user", d_id).await; + } + // The one-shot reads this note: a send-admission refusal + // exits 2 with its reply, any other failure exits 1. + one_shot::note_turn_failure(chat_turn_binding.as_deref(), &e); + let err_text = e.to_string(); + super::output::print_turn_failure(plain_mode, &err_text); + if plain_mode { + plain_mode_turn_failed = true; + } + // Phase E (5a-4): same dual_write_guard reasoning as the timeout branch. + if !dual_write_guard.is_active() { + hooks + .emit(HookEvent::Error, payload_error("chat-turn", &err_text)) + .await; + } + // S2-A: generic provider/loop error — retryable hint is + // false (the caller already chose to surface and continue; + // retry policy is owned by upstream once tooling lands). + ( + TurnOutcome::FailedWithError { + err: err_text, + retryable: false, + }, + None, + ) + } + } + }; + + // ── Finalize streaming ──────────────────────────────────── + // Deregister this turn's cancellation token. + // + // S2-B Step 3: on the legacy path the reducer also clears `state.control.active_cancel` when + // Stream{Completed,Cancelled,Failed} is dispatched (lines 1886-1911 below); the legacy Arc is + // only a fallback in Off/Both mode (the external Ctrl+C handler reads it). + #[cfg(not(feature = "terminal-tui"))] + { + *active_cancel.lock() = None; + } + + // Drop our channel senders so background tasks receive channel close + drop(delta_tx); + drop(tool_event_tx); + if let Some(handle) = draft_updater { + let _ = handle.await; + } + let _ = tool_event_forwarder.await; + + // Step 5b dual write: dispatch the matching stream-termination Action for the turn outcome. + // Only when draft_id exists can the reducer match stream.draft and clean it up; otherwise this + // is a no-op. + // + // S2-A: split the previous single-pronged "Failed → StreamCancelled" + // fallback. Order is **critical**: cancellation is detected up the + // stack via `is_tool_loop_cancelled` / `cancellation.is_cancelled()` + // and surfaces as `TurnOutcome::Cancelled`. Real errors (timeout / + // context overflow / provider error) surface as `FailedWithError` and + // map to `StreamFailed { err, retryable }` so the reducer emits the + // `NotifyHook(Error) + LogTrace + RequestRedraw` effect chain. + // + // T3-3-fixA P0-1: the StreamCompleted of the Success branch was moved down to be dispatched + // after RecordAssistantTurn, so that when the reducer builds the SaveSession snapshot + // session.turns already contains this turn's assistant message. Cancelled / FailedWithError + // write no assistant turn, so their dispatch position is unchanged. + match &turn_outcome { + TurnOutcome::Success(..) => {} + TurnOutcome::Cancelled => { + if let Some(ref d_id) = draft_id { + let _ = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::StreamCancelled { draft_id: d_id.clone() }, + "chat.stream_cancelled", + ); + } + if let Err(error) = finalize_chat_non_success_turn( + chat_turn_binding.as_deref(), + &memory_fabric, + &turn_run_id, + route_scope.clone(), + crate::agent::terminal::TurnTerminalStatus::Cancelled, + None, + provider_started_at, + "legacy tool loop cancelled", + &config.cost, + &config.workspace_dir, + ) + .await + { + if chat_turn_binding.as_ref().is_some_and(|binding| binding.is_decided()) { return Err(error); } + tracing::warn!(error = %crate::agent::diagnostics::error_class(&error), "Failed to commit shared cancelled Chat terminal event"); + } + } + TurnOutcome::FailedWithError { err, retryable } => { + if let Some(ref d_id) = draft_id { + let _ = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::StreamFailed { + draft_id: d_id.clone(), + err: err.clone(), + retryable: *retryable, + }, + "chat.stream_failed", + ); + } + // The terminal records the loop failure. Decided turns retain + // only observed provider attempts in their owning trace. + if let Err(error) = finalize_chat_non_success_turn( + chat_turn_binding.as_deref(), + &memory_fabric, + &turn_run_id, + route_scope.clone(), + crate::agent::terminal::TurnTerminalStatus::Failed, + None, + provider_started_at, + &format!("legacy tool loop failed: {err}"), + &config.cost, + &config.workspace_dir, + ) + .await + { + if chat_turn_binding.as_ref().is_some_and(|binding| binding.is_decided()) { return Err(error); } + tracing::warn!(error = %crate::agent::diagnostics::error_class(&error), "Failed to commit shared failed Chat terminal event"); + } + surface_turn_elapsed_message( + &chat_dispatcher, + sessions_redraw_handle.as_ref(), + "failed", + provider_started_at, + chrono::Utc::now(), + ); + } + } + + let inline_view_changed = inline_compaction.compacted() || inline_view_before_turn.changed_in(&history); + // If the turn failed or was cancelled, skip response processing + let (response, turn_trace) = match turn_outcome { + TurnOutcome::Success(resp) => (resp, successful_trace.context("successful Chat outcome has no serving trace")?), + TurnOutcome::Cancelled => { + let settled = settle_aborted_turn(&chat_dispatcher, &turn_signal, admission).await?; + provider_view_after_settled_abort( + &mut history, + &settled, + inline_compaction_epoch_before_preflight, + inline_view_changed, + Some(history_len_before_user_turn), + ); + finish_inline_provider_turn(&mut provider_turn_workers, provider_turn_task_id, None); + gate_cancelled_provider_turn_finalization( + &mut turn_scheduler, + &mut history_commit_coordinator, + &mut provider_turn_workers, + provider_turn_task_id, + "legacy tool loop cancelled", + ); + publish_main_queue_status(&chat_dispatcher, &turn_scheduler); + publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); + continue; + } + TurnOutcome::FailedWithError { err, .. } => { + let settled = settle_aborted_turn(&chat_dispatcher, &turn_signal, admission).await?; + provider_view_after_settled_abort( + &mut history, + &settled, + inline_compaction_epoch_before_preflight, + inline_view_changed, + Some(history_len_before_user_turn), + ); + finish_inline_provider_turn(&mut provider_turn_workers, provider_turn_task_id, None); + gate_failed_provider_turn_finalization( + &mut turn_scheduler, + &mut history_commit_coordinator, + &mut provider_turn_workers, + provider_turn_task_id, + history.len(), + format!("legacy tool loop failed: {err}"), + ); + publish_main_queue_status(&chat_dispatcher, &turn_scheduler); + publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); + continue; + } + }; + if let Some(binding) = chat_turn_binding.as_ref() { + binding.capture_trace(&turn_trace)?; + } + // FIX-P0-30/31: build the provider outcome from the loop's real + // attribution trace. When the trace carries the actual serving + // provider/model + attempts (the `ReliableProvider` path), use them so a + // retry/fallback is recorded as `FallbackSuccess` and `final_model` + // reflects what truly executed. Fall back to the routed + // `decision.selected.{provider,model}` only when no trace is available + // (e.g. a provider whose `chat_traced` default produced a synthetic + // attribution). + let provider_outcome = { + let has_trace = turn_trace.final_model.is_some() && !turn_trace.attempts.is_empty(); + if has_trace { + let final_provider = turn_trace + .final_provider + .unwrap_or_else(|| route_decision.selected.provider.clone()); + let final_model = turn_trace + .final_model + .unwrap_or_else(|| route_decision.selected.model.clone()); + ProviderExecutionOutcome::from_trace_with_usage( + &route_decision, + turn_trace.attempts, + final_provider, + final_model, + provider_started_at, + chrono::Utc::now(), + // FIX #2: a fallback on any earlier (tool-call) turn must + // surface as FallbackSuccess even when the final turn is clean. + turn_trace.any_turn_had_fallback, + turn_trace.tokens_used, + ) + } else { + ProviderExecutionOutcome::success_for_decision_with_usage( + &route_decision, + provider_started_at, + turn_trace.tokens_used, + ) + } + }; + surface_turn_elapsed_message( + &chat_dispatcher, + sessions_redraw_handle.as_ref(), + "completed", + provider_outcome.started_at, + provider_outcome.finished_at, + ); + // d04 §10 G7: emit a control-ladder trace carrying the structured + // decision_id / final_provider / final_model / attempts_count so a + // `decision_id` join links the routing decision to the provider that + // actually served the request. Best-effort (failures logged, not fatal). + { + let status_label = match &provider_outcome.status { + crate::llm::route_decision::ExecutionStatus::Success => "success", + crate::llm::route_decision::ExecutionStatus::FallbackSuccess => "fallback_success", + crate::llm::route_decision::ExecutionStatus::AllFailed { .. } => "all_failed", + }; + let attempts_count = u8::try_from(provider_outcome.attempts.len()).unwrap_or(u8::MAX); + crate::runtime::control_ladder::append_provider_outcome_trace( + std::path::Path::new(&config.workspace_dir), + &provider_outcome.decision_id, + &provider_outcome.final_provider, + &provider_outcome.final_model, + attempts_count, + status_label, + ); + } + + // ── P2-12: Mirror reasoning content into the TUI as a folded card. ── + // + // Reasoning is separated upstream at the provider layer (P0-2) and + // persisted into the assistant-history JSON via + // `build_native_assistant_history`. We scan the slice of history + // produced during this turn for `reasoning_content` fields, aggregate + // them, and push a single folded `Reasoning` card to the TUI mirror. + // Empty buffers are skipped by `push_reasoning`. This does NOT touch + // the visible delta stream — the user-facing assistant text remains + // the only thing rendered in the streaming draft. + #[cfg(feature = "terminal-tui")] + { + let turn_slice = history.get(history_len_before_tools..).unwrap_or(&[]); + let aggregated = collect_reasoning_from_history_slice(turn_slice); + if !aggregated.is_empty() { + // S4-B: the mirror push_reasoning is deleted; the reducer + // (reduce_stream_completed) is the single source that pushes the Reasoning card. + if let Some(tx) = redraw_tx_for_main.as_ref() { + let _ = tx.try_send(()); + } + } + } + + increment_recalled_useful_counts(mem.as_ref(), &mem_context.ids).await; + + // ── Sanitize response: strip tool-call XML/JSON artifacts ── + let response = sanitize_channel_response(&response, &tools_registry); + + if crate::agent::response_guard::is_empty_assistant_response(&response, false) { + let terminal_usage = match finalize_chat_success_turn( + chat_turn_binding.as_deref(), + &memory_fabric, + &chat_session_key, + &turn_run_id, + provider_name, + model_name, + route_scope.clone(), + provider_outcome.clone(), + None, + history.len(), + "legacy tool loop completed with empty response", + &config.cost, + &config.workspace_dir, + ) + .await + { + Ok(receipt) => receipt.into_session_usage(), + Err(error) => { + tracing::error!(error = %crate::agent::diagnostics::error_class(&error), "Chat terminal persistence is unconfirmed"); + return Err(error); + } + }; + let inline_payload = inline_provider_turn_payload(history.len(), 0, terminal_usage.as_ref()); + // Usage first (inside the commit's acknowledged revision), then + // the awaited commit (the user turn was recorded at admission). + if let Err(error) = dispatch_final_usage( + &chat_dispatcher, + &turn_signal, + &mut turn_scheduler, + provider_turn_task_id, + terminal_usage, + "chat.provider_usage_recorded_empty_response", + ) + .await + { + anyhow::bail!("Chat stopped after an unconfirmed history commit: {error}"); + } + let Some(commit_task_id) = provider_turn_task_id else { + anyhow::bail!("chat turn has no provider task; its history cannot be committed"); + }; + if let Err(error) = dispatch_ordered_provider_turn_commit_and_wait( + &chat_dispatcher, + &turn_signal, + commit_task_id, + OrderedCommitTerminal::TurnCommitRequested { draft_id: draft_id.as_deref() }, + &user_input, + "", + true, + false, + ) + .await + { + anyhow::bail!("Chat stopped after an unconfirmed history commit: {error}"); + } + super::compaction::reconcile_inline_turn(&mut history, &chat_dispatcher); + if let Some(ref d_id) = draft_id + && let Err(e) = terminal.cancel_draft("user", d_id).await + { + let (error_len, error_sha256) = crate::agent::diagnostics::error_log_digest(&e); + tracing::debug!(error_len, error_sha256, "cancel empty-response draft failed"); + } + surface_session_message( + &chat_dispatcher, + sessions_redraw_handle.as_ref(), + crate::agent::response_guard::EMPTY_ASSISTANT_RESPONSE_MESSAGE, + ); + #[cfg(feature = "terminal-tui")] + if let Some(tx) = redraw_tx_for_main.as_ref() { + let _ = tx.try_send(()); + } + observer.record_event(&ObserverEvent::TurnComplete); + if !dual_write_guard.is_active() { + hooks + .emit( + HookEvent::TurnComplete, + serde_json::json!({ + "mode": "chat", + "response_chars": 0, + }), + ) + .await; + } + finish_inline_provider_turn(&mut provider_turn_workers, provider_turn_task_id, Some(inline_payload)); + mark_provider_turn_completed( + &mut turn_scheduler, + &mut history_commit_coordinator, + &mut provider_turn_workers, + provider_turn_task_id, + history.len(), + "legacy tool loop completed with empty response", + ); + publish_main_queue_status(&chat_dispatcher, &turn_scheduler); + publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); + continue; + } + + // Persist only the user-facing assistant response. Tool results already + // live in structured history entries; adding a synthetic summary here + // can teach the model to emit that internal marker as a final answer. + // The loop already appended its final reply: that slot becomes the + // committed (sanitized) response, so the next request carries the + // reply once, as the saved session does. + match history.last_mut() { + Some(last) if last.role == "assistant" => *last = ChatMessage::assistant(&response), + _ => history.push(ChatMessage::assistant(&response)), + } + let terminal_usage = match finalize_chat_success_turn( + chat_turn_binding.as_deref(), + &memory_fabric, + &chat_session_key, + &turn_run_id, + provider_name, + model_name, + route_scope.clone(), + provider_outcome.clone(), + Some(response.clone()), + history.len(), + "legacy tool loop completed", + &config.cost, + &config.workspace_dir, + ) + .await + { + Ok(receipt) => receipt.into_session_usage(), + Err(error) => { + tracing::error!(error = %crate::agent::diagnostics::error_class(&error), "Chat terminal persistence is unconfirmed"); + return Err(error); + } + }; + + + // S2-B Step 4: RecordAssistantTurn(response) is dispatched at the same point as the legacy + // `history.push(ChatMessage::assistant(...))` — so the reducer's session.history is + // byte-for-byte aligned with the legacy history. The old dispatch at line 2055 below used + // sanitized_response, whose content differs from history.push — from S2-B Step 4 on it is + // dispatched here with response instead, and the old dispatch below is deleted. + // The final usage goes first so the commit's acknowledged revision + // carries it; the ordered commit then sends RecordAssistantTurn and + // the awaited TurnCommitRequested (the user turn was recorded at + // admission). + let inline_payload = + inline_provider_turn_payload(history.len(), response.chars().count(), terminal_usage.as_ref()); + if let Err(error) = dispatch_final_usage( + &chat_dispatcher, + &turn_signal, + &mut turn_scheduler, + provider_turn_task_id, + terminal_usage, + "chat.provider_usage_recorded", + ) + .await + { + anyhow::bail!("Chat stopped after an unconfirmed history commit: {error}"); + } + let Some(commit_task_id) = provider_turn_task_id else { + anyhow::bail!("chat turn has no provider task; its history cannot be committed"); + }; + if let Err(error) = dispatch_ordered_provider_turn_commit_and_wait( + &chat_dispatcher, + &turn_signal, + commit_task_id, + OrderedCommitTerminal::TurnCommitRequested { draft_id: draft_id.as_deref() }, + &user_input, + &response, + false, + false, + ) + .await + { + anyhow::bail!("Chat stopped after an unconfirmed history commit: {error}"); + } + super::compaction::reconcile_inline_turn(&mut history, &chat_dispatcher); + #[cfg(feature = "terminal-tui")] + if let Some(tx) = redraw_tx_for_main.as_ref() { + let _ = tx.try_send(()); + } + + // ── Extract and display media markers (images, documents, etc.) ── + let (clean_response, media_items) = extract_outgoing_media(&response)?; + for (media_type, path) in &media_items { + if media_type == "IMAGE" && std::path::Path::new(path).exists() { + if let Err(e) = terminal_proto::display_image(path) { + tracing::debug!(error = %crate::agent::diagnostics::error_class(&e), "Image display failed"); + println!(" [image: {path}]"); + } + } else { + println!(" [{media_type}: {path}]"); + } + } + // Use the cleaned response (media markers removed) for display + let display_response = if media_items.is_empty() { + &response + } else { + &clean_response + }; + + // Finalize the streaming draft with the full response. + // + // Idempotency contract (P1-4): + // When a draft exists, the streamed deltas have already painted the + // full response on screen via `update_draft`. `finalize_draft` is + // only a structural close (locking in the final text for non-TTY + // channels such as Telegram). On failure we therefore MUST NOT + // re-send the whole message — that would duplicate output that the + // user has already seen via the live stream. We log a warning and + // carry on; the assistant turn is already in `history`, so the + // conversation state remains consistent. + // + // The "no draft" branch is the genuine first-send path (drafts were + // never created, e.g. `send_draft` failed earlier and returned + // `None`), so a normal `send` is correct and not a duplicate. + if let Some(ref d_id) = draft_id { + if let Err(e) = terminal.finalize_draft("user", d_id, display_response).await { + if should_resend_on_finalize_failure(true) { + let rendered = render_response(display_response); + let _ = terminal.send(&SendMessage::new(rendered, "user")).await; + } else { + tracing::warn!( + error = %crate::agent::diagnostics::error_class(&e), + "finalize_draft failed; suppressing resend to preserve idempotency (user already saw streamed content)" + ); + } + } + } else { + // No draft was created — send as a complete message with highlighting. + let rendered = render_response(display_response); + let _ = terminal.send(&SendMessage::new(rendered, "user")).await; + } + + // P0-1 fix: in Both/Redux mode the old path is gated by dual_write_guard. + // The Redux reducer's SaveSession effect already raised the guard inside execute_real, and + // when the guard is active the old path skips save_session + hooks.emit(TurnComplete), which + // prevents double hook/webhook firing (hooks/webhooks are not idempotent and really would + // fire twice). + // In Off mode the guard is always false and the old path writes alone as usual. + // The guard is turn-level (not effect-level): once Redux has executed either + // SaveSession or NotifyHook during a turn, the guard is active and every later write of the + // old path is suppressed. + if !dual_write_guard.is_active() { + observer.record_event(&ObserverEvent::TurnComplete); + hooks + .emit( + HookEvent::TurnComplete, + serde_json::json!({ + "mode": "chat", + "response_chars": response.chars().count(), + }), + ) + .await; + } else { + // Guard active: the Redux path already handled hooks.emit. + tracing::debug!("P0-1: dual_write_guard active — legacy path skipping hooks.emit(TurnComplete)"); + // observer.record_event is still called (the observer is only a local counter, with no + // external side effects). + observer.record_event(&ObserverEvent::TurnComplete); + } + finish_inline_provider_turn(&mut provider_turn_workers, provider_turn_task_id, Some(inline_payload)); + mark_provider_turn_completed( + &mut turn_scheduler, + &mut history_commit_coordinator, + &mut provider_turn_workers, + provider_turn_task_id, + history.len(), + "legacy tool loop completed", + ); + publish_main_queue_status(&chat_dispatcher, &turn_scheduler); + publish_provider_worker_status(&chat_dispatcher, &provider_turn_workers); + // The reply this turn produced *is* the answer to the assignment, so it + // is what goes back. Reaching here at all is what distinguishes a turn + // that answered from every other way the body can end. + if let Some(guard) = assignment_guard.as_mut() { + guard.completed(&response); + }} diff --git a/src/chat/sessions/focus.rs b/src/chat/sessions/focus.rs index 14c9fa1b4..53b698fd2 100644 --- a/src/chat/sessions/focus.rs +++ b/src/chat/sessions/focus.rs @@ -8,8 +8,8 @@ //! Two concerns: //! //! - [`FocusTarget`] — where plain text + Enter is routed. `Main` (the default) -//! sends to the main chat agent; `Session { seq }` routes the text as a -//! *steer* to the attached child session (head footgun: input target +//! sends to the main chat agent; `Session { seq }` starts or queues a +//! turn in the attached child session (head footgun: input target //! ambiguity — see plan §0.2.1 A). The target is shown in the prompt with a //! colour **and** a glyph so it is never colour-only (colour-blind / no-color //! safe). @@ -32,7 +32,7 @@ pub enum FocusTarget { /// Default: input goes to the main chat agent loop. #[default] Main, - /// Input is routed as a *steer* to the attached child TUI session `#seq`. + /// Input starts or queues a turn in the attached child TUI session `#seq`. Session { seq: u64 }, /// Read-only conversation transcript viewer. It reuses the child viewport but /// never routes submitted text as a steer to a managed session. @@ -130,6 +130,8 @@ pub struct SwitcherEntry { /// the TUI receives only this bounded, cloneable view. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ActiveSessionView { + /// Full public child transcript; never includes reasoning or source proofs. + pub turns: Vec, /// Display sequence `#N`. pub seq: u64, /// Stable lowercase kind label (`agent` / `shell`). @@ -644,6 +646,7 @@ mod tests { #[test] fn active_session_view_scroll_offset_saturates_and_resumes_follow() { let view = ActiveSessionView { + turns: Vec::new(), seq: 1, kind: "agent".to_string(), title: "task".to_string(), @@ -666,6 +669,7 @@ mod tests { #[test] fn active_session_view_clamps_when_visible_rows_exceed_lines() { let view = ActiveSessionView { + turns: Vec::new(), seq: 2, kind: "shell".to_string(), title: "cmd".to_string(), diff --git a/src/chat/sessions/runtime.rs b/src/chat/sessions/runtime.rs index babd82e63..c54fb7d33 100644 --- a/src/chat/sessions/runtime.rs +++ b/src/chat/sessions/runtime.rs @@ -177,6 +177,7 @@ pub struct ChatSessionsHandle { seq_map: Vec<(u64, SessionId)>, /// Next sequence number to hand out. next_seq: u64, + session_runs: HashMap, /// First time this handle observed a PTY as exited. PTY sessions do not /// carry `finished_at`, so cleanup ages them from this observation point. pty_terminal_seen_at: HashMap>, @@ -192,11 +193,28 @@ pub struct ChatSessionsHandle { } impl ChatSessionsHandle { + pub(crate) async fn child_run(&self, target: &str) -> Option { + self.runs + .read() + .await + .iter() + .find(|run| run.id == target || run.session_scope_key == target) + .cloned() + } + + pub(crate) async fn restore_child(&self, run: SubAgentRun) { + let mut runs = self.runs.write().await; + if !runs.iter().any(|old| old.session_scope_key == run.session_scope_key) { + runs.push(run); + } + } + /// Build a handle over the supplied single-source agent registry Arc, with a /// fresh empty shell registry. #[must_use] pub fn new(runs: Arc>>) -> Self { Self { + session_runs: HashMap::new(), runs, shells: Arc::new(Mutex::new(Vec::new())), #[cfg(feature = "terminal-tui")] @@ -349,7 +367,17 @@ impl ChatSessionsHandle { async fn refresh_seqs(&mut self) -> Vec { let runs: Vec = self.runs.read().await.clone(); for run in &runs { - let _ = self.seq_for(&SessionId::from_run_id(&run.id)); + let id = SessionId::from_run_id(&run.id); + if !run.session_scope_key.is_empty() { + if let Some(previous) = self.session_runs.insert(run.session_scope_key.clone(), id.clone()) { + if previous != id { + if let Some((_, mapped)) = self.seq_map.iter_mut().find(|(_, mapped)| *mapped == previous) { + *mapped = id.clone(); + } + } + } + } + let _ = self.seq_for(&id); } // Shells come after agents in seq order. Clone the ids out under the lock, // then assign (no await while the lock is held). diff --git a/src/chat/state/tests/mod.rs b/src/chat/state/tests/mod.rs index 8783b2b28..59ae455ed 100644 --- a/src/chat/state/tests/mod.rs +++ b/src/chat/state/tests/mod.rs @@ -347,6 +347,7 @@ fn active_session_view_updated_writes_snapshot_and_dedups() { assert!(state.ui.active_session_view.is_none()); let view = crate::chat::sessions::ActiveSessionView { + turns: Vec::new(), seq: 4, kind: "shell".to_string(), title: "tail -f app.log".to_string(), diff --git a/src/chat/tests/p2_iss005_tests.rs b/src/chat/tests/p2_iss005_tests.rs index a4c5ecef6..9d2741ed2 100644 --- a/src/chat/tests/p2_iss005_tests.rs +++ b/src/chat/tests/p2_iss005_tests.rs @@ -54,6 +54,7 @@ fn active_session_live_refresh_preserves_nonzero_scroll_offset() { ring.push(format!("line {i}")); } let current = crate::chat::sessions::ActiveSessionView { + turns: Vec::new(), seq: 3, kind: "shell".to_string(), title: "watch logs".to_string(), diff --git a/src/chat/tui/layout.rs b/src/chat/tui/layout.rs index 342e3f955..be20aa300 100644 --- a/src/chat/tui/layout.rs +++ b/src/chat/tui/layout.rs @@ -444,8 +444,8 @@ pub fn fullscreen_transcript_scroll_available(stat && state.switcher().is_none() && state.saved_session_picker().is_none() && state.pending_tool_approval().is_none() - && state.active_session_view().is_none() - && !state.focus().is_child_view() + && state.active_session_view().is_none_or(|view| view.kind == "agent") + && (!state.focus().is_child_view() || state.focus().is_session()) } /// Legacy compatibility hook for reasoning-card clicks. diff --git a/src/chat/tui/render_chrome.rs b/src/chat/tui/render_chrome.rs index 4d028a2bb..7247bfc3c 100644 --- a/src/chat/tui/render_chrome.rs +++ b/src/chat/tui/render_chrome.rs @@ -847,6 +847,20 @@ pub(super) fn render_status_bar_line(state: &V, wi #[allow(clippy::option_if_let_else)] pub(super) fn render_status_bar_text(state: &V, width: u16) -> String { + if let Some(view) = state.active_session_view().filter(|view| view.kind == "agent") { + let usage = state + .sessions_entries() + .iter() + .find(|entry| entry.seq == view.seq) + .and_then(|entry| entry.token_usage_summary()) + .and_then(crate::chat::session::format_session_token_usage_inline) + .unwrap_or_else(|| "0 tok | $0.0000".into()); + return truncate_chars_with_ellipsis( + &format!(" PRX Chat | child #{} | {} | {usage} ", view.seq, view.title), + width, + state.ascii_fallback(), + ); + } let title_str = state.session_title(); let title = if title_str.is_empty() { "(new session)" diff --git a/src/chat/tui/render_conversation.rs b/src/chat/tui/render_conversation.rs index 91144831c..9dd76c0af 100644 --- a/src/chat/tui/render_conversation.rs +++ b/src/chat/tui/render_conversation.rs @@ -126,6 +126,12 @@ pub(super) fn push_conversation_transcript_lines<'a, V: BottomChromeView + ?Size lines: &mut Vec>, state: &'a V, ) { + if let Some(view) = state.active_session_view().filter(|view| view.kind == "agent") { + for turn in &view.turns { + render_public_message(lines, &turn.role, &turn.content, state.ascii_fallback()); + } + return; + } for line in state.conversation_lines() { // Reasoning is diagnostic data, not a second completion summary. Keep // it in the backing conversation for Ctrl+O's verbose transcript, but @@ -141,6 +147,16 @@ pub(super) fn push_live_turn_transcript_lines<'a, V: BottomChromeView + ?Sized>( lines: &mut Vec>, state: &'a V, ) { + if let Some(view) = state.active_session_view().filter(|view| view.kind == "agent") { + if !view.lines.is_empty() { + push_assistant_rendered_lines( + lines, + render_streaming_assistant_markdown_lines(&view.lines.join("\n"), state.ascii_fallback()), + state.ascii_fallback(), + ); + } + return; + } let Some(streaming) = state.streaming() else { return; }; @@ -321,6 +337,9 @@ pub fn render_fullscreen_chat_with_selection( } pub(super) fn fullscreen_content_areas(area: Rect, state: &V) -> (Rect, Option) { + if state.active_session_view().is_some_and(|view| view.kind == "agent") { + return (area, None); + } if area.height == 0 || (state.pending_tool_approval().is_none() && state.active_session_view().is_none()) { return (area, None); } @@ -504,9 +523,9 @@ pub(super) fn measure_wrapped_rows(lines: &[Line<'_>], width: u16) -> u16 { /// Pure function (apart from the &mut push target) — kept outside /// [`render_fullscreen_transcript`] so unit tests can drive it with a /// `Vec>` sink. -pub(super) fn render_conversation_line<'a>(lines: &mut Vec>, conv_line: &'a ConversationLine, ascii: bool) { - match conv_line { - ConversationLine::User { content } => { +fn render_public_message<'a>(lines: &mut Vec>, role: &str, content: &'a str, ascii: bool) { + match role { + "user" => { // Claude Code style: `> ` prompt in dim gray (no bold), content in // default foreground on the same row when single-line; multi-line // continuation rows are dedented two spaces to align under the @@ -522,7 +541,7 @@ pub(super) fn render_conversation_line<'a>(lines: &mut Vec>, conv_line: } lines.push(Line::from("")); } - ConversationLine::Assistant { content } => { + "assistant" => { // PRX chat uses an explicit actor marker for assistant-authored // prose so it is visually distinct from tool IO and child-session // output when scanning a dense orchestration transcript. @@ -531,6 +550,18 @@ pub(super) fn render_conversation_line<'a>(lines: &mut Vec>, conv_line: push_assistant_rendered_lines(lines, rendered.iter().cloned(), ascii); lines.push(Line::from("")); } + _ => { + for text in content.lines() { + lines.push(Line::from(Span::styled(text, Style::default().fg(Color::DarkGray)))); + } + } + } +} + +pub(super) fn render_conversation_line<'a>(lines: &mut Vec>, conv_line: &'a ConversationLine, ascii: bool) { + match conv_line { + ConversationLine::User { content } => render_public_message(lines, "user", content, ascii), + ConversationLine::Assistant { content } => render_public_message(lines, "assistant", content, ascii), ConversationLine::StreamingAssistant { content } => { // Same actor marker as finalized assistant text. A trailing cursor // glyph (`▌`, or `_` in ASCII mode) signals that more bytes are diff --git a/src/chat/tui/tests/mod.rs b/src/chat/tui/tests/mod.rs index 0d4526db4..cfbfcb576 100644 --- a/src/chat/tui/tests/mod.rs +++ b/src/chat/tui/tests/mod.rs @@ -174,6 +174,7 @@ fn long_strip_entries(count: u64) -> Vec { fn active_view(seq: u64, lines: Vec, scroll_offset: usize) -> crate::chat::sessions::ActiveSessionView { crate::chat::sessions::ActiveSessionView { + turns: Vec::new(), seq, kind: "agent".to_string(), title: "\u{ac00}".repeat(13) + "-with-a-long-title", diff --git a/src/chat/tui/tests/rearch_chrome.rs b/src/chat/tui/tests/rearch_chrome.rs index 6c37934cb..cfb8056b3 100644 --- a/src/chat/tui/tests/rearch_chrome.rs +++ b/src/chat/tui/tests/rearch_chrome.rs @@ -224,6 +224,7 @@ fn fullscreen_child_and_diff_views_use_large_panel_above_input() { }); state.focus = crate::chat::sessions::FocusTarget::Session { seq: 7 }; state.active_session_view = Some(crate::chat::sessions::ActiveSessionView { + turns: Vec::new(), seq: 7, kind: "agent".to_string(), title: "phase2 child".to_string(), @@ -244,6 +245,7 @@ fn fullscreen_child_and_diff_views_use_large_panel_above_input() { state.focus = crate::chat::sessions::FocusTarget::Diff; state.active_session_view = Some(crate::chat::sessions::ActiveSessionView { + turns: Vec::new(), seq: DIFF_SESSION_SEQ, kind: crate::chat::sessions::model::ManagedKind::Diff.as_str().to_string(), title: "workspace diff".to_string(), @@ -294,6 +296,7 @@ fn fullscreen_scroll_focus_rules_do_not_steal_input_or_child_keys() { let mut child_state = TuiState::new("provider", "model"); child_state.focus = crate::chat::sessions::FocusTarget::Session { seq: 3 }; child_state.active_session_view = Some(crate::chat::sessions::ActiveSessionView { + turns: Vec::new(), seq: 3, kind: "agent".to_string(), title: "child".to_string(), diff --git a/src/chat/tui/tests/s4_a_2.rs b/src/chat/tui/tests/s4_a_2.rs index 4dc7e74f0..2d623eb9b 100644 --- a/src/chat/tui/tests/s4_a_2.rs +++ b/src/chat/tui/tests/s4_a_2.rs @@ -101,6 +101,7 @@ fn s4_a_2_view_getters_parity() { state.ui.chat_mode = ChatMode::Auto; state.ui.autonomy_level = AutonomyLevel::ReadOnly; let active_view = crate::chat::sessions::ActiveSessionView { + turns: Vec::new(), seq: DIFF_SESSION_SEQ, kind: crate::chat::sessions::model::ManagedKind::Diff.as_str().to_string(), title: "workspace diff".to_string(), diff --git a/src/chat/tui/tests/switcher.rs b/src/chat/tui/tests/switcher.rs index 9ecc6f9eb..1ffbd7067 100644 --- a/src/chat/tui/tests/switcher.rs +++ b/src/chat/tui/tests/switcher.rs @@ -100,6 +100,7 @@ fn bare_arrows_scroll_transcript_and_child_views_not_history() { state.input.clear(); state.focus = crate::chat::sessions::FocusTarget::Session { seq: 1 }; state.active_session_view = Some(crate::chat::sessions::ActiveSessionView { + turns: Vec::new(), seq: 1, kind: "agent".to_string(), title: "task 1".to_string(), diff --git a/src/chat/tui/views.rs b/src/chat/tui/views.rs index a5b531425..ad9616410 100644 --- a/src/chat/tui/views.rs +++ b/src/chat/tui/views.rs @@ -363,6 +363,7 @@ pub fn build_transcript_view( lines.push("(transcript is empty - PageUp/Home view history; /help for copy/export)".to_string()); } crate::chat::sessions::ActiveSessionView { + turns: Vec::new(), seq: TRANSCRIPT_SESSION_SEQ, kind: crate::chat::sessions::model::ManagedKind::Transcript .as_str() @@ -391,6 +392,7 @@ pub fn build_diff_view( lines.push("(no workspace diff)".to_string()); } crate::chat::sessions::ActiveSessionView { + turns: Vec::new(), seq: DIFF_SESSION_SEQ, kind: crate::chat::sessions::model::ManagedKind::Diff.as_str().to_string(), title: if title.trim().is_empty() { diff --git a/src/chat/views.rs b/src/chat/views.rs index cef4279bf..3bc989e78 100644 --- a/src/chat/views.rs +++ b/src/chat/views.rs @@ -83,7 +83,7 @@ pub(super) fn build_active_session_attach_projection( ActiveSessionAttachProjection { view: build_active_session_view(seq, meta, tail_lines, ring_lines, truncated, 0), breadcrumb: format!( - "Attached session #{seq} (child viewport; input routes as steer). Type /detach or press Esc to stop." + "Attached session #{seq} (child session; input starts or queues a turn). Type /detach or press Esc to stop." ), } } @@ -105,6 +105,7 @@ fn build_active_session_view( lines.extend(tail_lines); lines.extend(ring_lines); crate::chat::sessions::ActiveSessionView { + turns: Vec::new(), seq, kind, title, diff --git a/src/memory/child_sessions.rs b/src/memory/child_sessions.rs index 404287d2a..e2019bd85 100644 --- a/src/memory/child_sessions.rs +++ b/src/memory/child_sessions.rs @@ -41,6 +41,13 @@ pub struct ScopedChildRecord { /// Opaque record schema belongs to chat; ownership and scope belong to storage. pub trait ChildSessionStore: Send + Sync { + /// Durable spawn sessions belonging to this authenticated owner/workspace. + fn sessions(&self, workspace: &str, owner: &str) -> anyhow::Result>; + /// Full model-visible history, excluding internal lifecycle and reasoning rows. + fn history(&self, record: &ChildSessionRecord) -> anyhow::Result>; + /// Replace only a child's model-visible context and selection. Transcript + /// erasure remains the owner's separate history-erase operation. + fn replace_context(&self, record: &ChildSessionRecord, turns: &[ChildTurn]) -> anyhow::Result<()>; fn load(&self, key: &str, context: &ChildSessionContext) -> anyhow::Result>; /// Invoke the callback once inside the writer transaction. Failure leaves /// the record unchanged. New writes always require a complete live scope. @@ -51,3 +58,33 @@ pub trait ChildSessionStore: Send + Sync { update: &mut dyn FnMut(Option<&str>) -> anyhow::Result, ) -> anyhow::Result; } + +/// A logical child session. Stored data is never execution authority: every +/// continuation must be admitted from a fresh parent/operator source. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ChildSessionRecord { + pub workspace: String, + pub owner: String, + pub session_key: String, + pub parent_session: String, + pub parent_run: String, + pub agent: String, + pub mode: String, + pub provider: String, + pub model: String, + pub level: crate::security::AutonomyLevel, + pub created_at: DateTime, + pub ended_at: Option>, + pub status: String, + pub runs: Vec, + pub context_after: i64, + pub context: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct ChildTurn { + pub role: String, + pub content: String, + pub timestamp: DateTime, +} diff --git a/src/memory/sqlite/child_sessions.rs b/src/memory/sqlite/child_sessions.rs index 80dfba278..fb05d04d8 100644 --- a/src/memory/sqlite/child_sessions.rs +++ b/src/memory/sqlite/child_sessions.rs @@ -132,6 +132,26 @@ fn resolve_new_scope(tx: &Transaction<'_>, context: &ChildSessionContext, key: & } impl ChildSessionStore for SqliteMemory { + fn replace_context( + &self, + record: &crate::memory::child_sessions::ChildSessionRecord, + turns: &[crate::memory::child_sessions::ChildTurn], + ) -> anyhow::Result<()> { + super::child_turns::replace_context(self, record, turns) + } + fn sessions( + &self, + workspace: &str, + owner: &str, + ) -> anyhow::Result> { + super::child_turns::sessions(self, workspace, owner) + } + fn history( + &self, + record: &crate::memory::child_sessions::ChildSessionRecord, + ) -> anyhow::Result> { + super::child_turns::history(self, record) + } fn load(&self, key: &str, context: &ChildSessionContext) -> anyhow::Result> { validate_key(key, context)?; let writer = self.pool.write(); diff --git a/src/memory/sqlite/child_turns.rs b/src/memory/sqlite/child_turns.rs new file mode 100644 index 000000000..dc4b19a58 --- /dev/null +++ b/src/memory/sqlite/child_turns.rs @@ -0,0 +1,171 @@ +//! Spawn-session persistence shares the source event transaction and scope. +use super::SqliteMemory; +use crate::memory::child_sessions::{ChildSessionError, ChildSessionRecord, ChildTurn}; +use crate::memory::{AgentPartition, MessageEvent, PartitionKey}; +use rusqlite::{OptionalExtension, params}; + +pub(super) fn source_written(conn: &rusqlite::Transaction<'_>, event: &MessageEvent) -> anyhow::Result<()> { + if !matches!( + event.source, + crate::memory::MessageEventSource::SessionsSpawn | crate::memory::MessageEventSource::SessionWorker + ) { + return Ok(()); + } + let Some(raw) = event.raw_payload_json.as_deref() else { + return Ok(()); + }; + let value: serde_json::Value = serde_json::from_str(raw)?; + if let Some(value) = value.get("child_session_record") { + let mut record: ChildSessionRecord = serde_json::from_value(value.clone())?; + let run = event.run_id.as_deref().ok_or(ChildSessionError::InvalidRecord)?; + anyhow::ensure!( + event.role == "user" + && event.source == crate::memory::MessageEventSource::SessionsSpawn + && record.workspace == event.workspace_id + && Some(record.owner.as_str()) == event.owner_id.as_deref() + && Some(record.session_key.as_str()) == event.session_key.as_deref() + && Some(record.parent_run.as_str()) == event.parent_run_id.as_deref() + && Some(record.parent_session.as_str()) == event.parent_session_key.as_deref() + && record.runs.last().is_some_and(|last| last == run) + && record.session_key.starts_with("spawn:"), + ChildSessionError::IdentityMismatch + ); + let existing: Option = conn + .query_row( + "SELECT record FROM child_sessions WHERE key=?1 AND workspace_id=?2 AND owner_id=?3", + params![record.session_key, record.workspace, record.owner], + |r| r.get(0), + ) + .optional()?; + if let Some(existing) = existing { + let previous: ChildSessionRecord = serde_json::from_str(&existing)?; + anyhow::ensure!( + previous.parent_session == record.parent_session && previous.agent == record.agent, + ChildSessionError::IdentityMismatch + ); + anyhow::ensure!( + record.runs.len() == previous.runs.len() + 1 && record.runs.starts_with(&previous.runs), + ChildSessionError::InvalidRecord + ); + record.created_at = previous.created_at; + record.context_after = previous.context_after; + record.context = previous.context; + } + let scope: Option = conn.query_row( + "SELECT ma_scope_id FROM message_events WHERE event_id=?1", + [&event.event_id], + |r| r.get(0), + )?; + let scope = match scope { + Some(scope) => scope, + None => super::agent_migration::resolve_write_scope( + conn, + &AgentPartition { + workspace_id: record.workspace.clone(), + owner_id: record.owner.clone(), + key: PartitionKey::Main, + }, + Some(&record.session_key), + )?, + }; + conn.execute( + "UPDATE message_events SET ma_scope_id=?2 WHERE event_id=?1 AND ma_scope_id IS NULL", + params![event.event_id, scope], + )?; + conn.execute("UPDATE memory_events SET ma_scope_id=?2 WHERE subject_table='message_events' AND subject_id=?1 AND ma_scope_id IS NULL",params![event.event_id,scope])?; + conn.execute("INSERT INTO child_sessions(key,record,workspace_id,owner_id,instance_id,session_id,agent_key,ma_scope_id,incarnation,generation) + SELECT ?1,?2,?3,?4,'local',?1,agent_key,scope_id,incarnation,generation FROM agent_scopes WHERE scope_id=?5 + ON CONFLICT(key) DO UPDATE SET record=excluded.record WHERE child_sessions.workspace_id=excluded.workspace_id AND child_sessions.owner_id=excluded.owner_id AND child_sessions.ma_scope_id=excluded.ma_scope_id", + params![record.session_key,serde_json::to_string(&record)?,record.workspace,record.owner,scope])?; + } + if matches!(event.event_type.as_str(), "turn.finalized" | "turn.admission.failed") { + let status = value + .get("status") + .and_then(serde_json::Value::as_str) + .unwrap_or("failed"); + conn.execute( + "UPDATE child_sessions SET record=json_set(record,'$.status',?4,'$.ended_at',?5) + WHERE workspace_id=?1 AND owner_id=?2 AND session_id=?3 AND json_extract(record,'$.runs[#-1]')=?6", + params![ + event.workspace_id, + event.owner_id, + event.session_key, + status, + event.created_at, + event.run_id + ], + )?; + } + Ok(()) +} + +pub(super) fn sessions(memory: &SqliteMemory, workspace: &str, owner: &str) -> anyhow::Result> { + let reader = memory.pool.read()?; + let conn = reader.connection()?; + let mut query = conn.prepare("SELECT record FROM child_sessions c JOIN agent_scopes s ON s.scope_id=c.ma_scope_id + WHERE c.workspace_id=?1 AND c.owner_id=?2 AND c.key LIKE 'spawn:%' + AND EXISTS(SELECT 1 FROM agent_incarnations i WHERE i.workspace_id=s.workspace_id AND i.owner_id=s.owner_id AND i.agent_key=s.agent_key AND i.incarnation=s.incarnation AND i.state='active') + AND NOT EXISTS(SELECT 1 FROM agent_erase_fences f WHERE f.scope_id=s.scope_id) ORDER BY c.rowid")?; + let mut records = Vec::new(); + for row in query.query_map(params![workspace, owner], |r| r.get::<_, String>(0))? { + records.push(serde_json::from_str(&row?)?); + } + Ok(records) +} + +pub(super) fn history(memory: &SqliteMemory, record: &ChildSessionRecord) -> anyhow::Result> { + let reader = memory.pool.read()?; + let conn = reader.connection()?; + let live:bool=conn.query_row("SELECT EXISTS(SELECT 1 FROM child_sessions c JOIN agent_scopes s ON c.ma_scope_id=s.scope_id WHERE c.key=?1 AND c.workspace_id=?2 AND c.owner_id=?3 AND NOT EXISTS(SELECT 1 FROM agent_erase_fences f WHERE f.scope_id=s.scope_id))", + params![record.session_key,record.workspace,record.owner],|r|r.get(0))?; + anyhow::ensure!(live, ChildSessionError::ScopeRefused); + let mut query = conn.prepare("SELECT e.role,e.content,e.created_at FROM message_events e + JOIN child_sessions c ON c.key=e.session_key AND c.ma_scope_id=e.ma_scope_id + JOIN agent_scopes s ON s.scope_id=c.ma_scope_id + WHERE c.key=?1 AND c.workspace_id=?2 AND c.owner_id=?3 AND e.workspace_id=?2 AND e.owner_id=?3 + AND EXISTS(SELECT 1 FROM agent_incarnations i WHERE i.workspace_id=s.workspace_id AND i.owner_id=s.owner_id AND i.agent_key=s.agent_key AND i.incarnation=s.incarnation AND i.state='active') + AND NOT EXISTS(SELECT 1 FROM agent_erase_fences f WHERE f.scope_id=s.scope_id) + AND e.id>?4 AND e.role IN('user','assistant','tool') AND e.event_type='message.created' + AND NOT EXISTS(SELECT 1 FROM message_events p WHERE p.workspace_id=e.workspace_id AND p.owner_id=e.owner_id + AND p.id> = query + .query_map( + params![record.session_key, record.workspace, record.owner, record.context_after], + |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?)), + )? + .map(|row| { + let (role, content, timestamp) = row?; + Ok(ChildTurn { + role, + content, + timestamp: chrono::DateTime::parse_from_rfc3339(×tamp)?.with_timezone(&chrono::Utc), + }) + }) + .collect(); + result.extend(turns?); + Ok(result) +} + +pub(super) fn replace_context( + memory: &SqliteMemory, + record: &ChildSessionRecord, + turns: &[ChildTurn], +) -> anyhow::Result<()> { + let writer = memory.pool.write(); + let tx = rusqlite::Transaction::new_unchecked(&writer, rusqlite::TransactionBehavior::Immediate)?; + let mut value = record.clone(); + value.context_after = tx.query_row( + "SELECT COALESCE(MAX(id),0) FROM message_events WHERE workspace_id=?1 AND owner_id=?2 AND session_key=?3", + params![record.workspace, record.owner, record.session_key], + |r| r.get(0), + )?; + value.context = turns.to_owned(); + let written=tx.execute("UPDATE child_sessions SET record=?4 WHERE key=?1 AND workspace_id=?2 AND owner_id=?3 AND NOT EXISTS(SELECT 1 FROM agent_erase_fences f WHERE f.scope_id=child_sessions.ma_scope_id)", + params![record.session_key,record.workspace,record.owner,serde_json::to_string(&value)?])?; + anyhow::ensure!(written == 1, ChildSessionError::ScopeRefused); + tx.commit()?; + Ok(()) +} diff --git a/src/memory/sqlite/event_append.rs b/src/memory/sqlite/event_append.rs new file mode 100644 index 000000000..b5abb0dc7 --- /dev/null +++ b/src/memory/sqlite/event_append.rs @@ -0,0 +1,328 @@ +//! Atomic event append, recovery fencing and child-session persistence. +#[cfg(test)] +use super::events::hold_append_snapshot_for_test; +use super::recovery_authority::{self, FullSync}; +use super::recovery_keys::KeyDirectory; +use super::{SqliteMemory, ingress_recovery}; +use crate::memory::ingress_recovery::AtomicIngressMutation; +use crate::memory::{AgentScopeRefused, MessageEvent, MessageEventInput, PartitionKey}; +use anyhow::Context; +use chrono::Utc; +use rusqlite::{OptionalExtension, TransactionBehavior, params}; +use std::sync::Arc; +use uuid::Uuid; +impl SqliteMemory { + pub(super) async fn append_event_with_recovery( + &self, + input: MessageEventInput, + mutation: Option, + repair_deadline: Option, + ) -> anyhow::Result<(MessageEvent, bool)> { + // The attested append future carries the whole input, the mutation and the + // blocking closure; keep it on the heap so callers' futures stay small. + Box::pin(self.append_attested_event(input, mutation, repair_deadline, None)) + .await? + .context("only an ingress input can hit a tombstone without an error") + } + + /// The single append transaction; `None` means the stable key of an ingress + /// input is tombstoned (any other tombstoned input is `StableKeyTombstoned`). + /// Every stable-key user input runs the tombstone fence inside it. An attested + /// ingress input also writes its pending attestation and transport index row, + /// under FULL synchronization, so a crash leaves all of them or none. An rf + /// admission writes its attempt row in the same transaction (AC-1b2a). + pub(super) async fn append_attested_event( + &self, + input: MessageEventInput, + mutation: Option, + repair_deadline: Option, + admission: Option, + ) -> anyhow::Result> { + input.validate()?; + let pool = self.pool.clone(); + let deadline = mutation.as_ref().map(ingress_recovery::deadline).or(repair_deadline); + let repair_owner = repair_deadline + .map(|_| self.repair_owner(&input.workspace_id)) + .transpose()?; + let key_root = self.db_path.parent().map(std::path::Path::to_path_buf); + #[cfg(test)] + let db_path = self.db_path.clone(); + + Box::pin(crate::runtime::blocking::spawn_blocking( + move || -> anyhow::Result> { + // The mutation owns the genuine lease inside this blocking closure, + // including when its async waiter is cancelled. + let mut write = match deadline { + Some(deadline) => pool.write_until(deadline)?, + None => pool.write(), + }; + let conn = ingress_recovery::DeadlineConn::wrap(&mut write, deadline)?; + let attested = match &mutation { + Some(AtomicIngressMutation::Input { + capsule, + attestation: Some(attestation), + .. + }) => Some((capsule, attestation)), + _ => None, + }; + // Synchronization cannot change inside a transaction: set it first. + let _sync = attested.map(|_| FullSync::new(&conn)).transpose()?; + let keys = attested + .map(|_| KeyDirectory::open(key_root.as_deref().context("missing memory directory")?, false)) + .transpose()?; + // BEGIN IMMEDIATE takes the WAL write lock before any read. + // BEGIN DEFERRED pins a snapshot on the first SELECT (the + // tombstone fence when it runs); a second opener that commits + // then makes this INSERT return SQLITE_BUSY_SNAPSHOT / + // "database is locked" without the busy handler — the + // spawn_batch child-start failure against another pool on + // brain.db. + let tx = rusqlite::Transaction::new_unchecked(&conn, TransactionBehavior::Immediate)?; + if let (Some(owner), Some(deadline)) = (&repair_owner, repair_deadline) { + ingress_recovery::validate_owner(&tx, owner, &input.workspace_id, deadline)?; + } + if let Some(operation) = &mutation { + ingress_recovery::before_append(&tx, operation, &input)?; + } + // Every stable-key user input is fenced, with or without a recorder. + if matches!( + recovery_authority::stable_key_fence(&tx, key_root.as_deref(), &input)?, + recovery_authority::Fence::Tombstoned + ) { + // Dropping the transaction rolls back; nothing was inserted. + return match mutation { + Some(AtomicIngressMutation::Input { .. }) => Ok(None), + _ => Err(crate::memory::ingress_recovery::StableKeyTombstoned.into()), + }; + } + #[cfg(test)] + hold_append_snapshot_for_test(&input, &db_path)?; + let (event, inserted) = Self::append_event_row(&tx, input, deadline.is_some())?; + if let Some(operation) = &mutation { + ingress_recovery::after_append(&tx, operation, &event, inserted)?; + } + if let (true, Some((capsule, attestation)), Some(keys)) = (inserted, attested, &keys) { + recovery_authority::attest_ingress(&tx, keys, capsule, attestation, &event)?; + } + if let Some(admission) = &admission { + let lifetime = mutation.as_ref().map(|operation| operation.lease().token()); + super::rf_messages::admit(&tx, admission, &event, inserted, lifetime)?; + } + if let (Some(owner), Some(deadline)) = (&repair_owner, repair_deadline) { + ingress_recovery::validate_owner(&tx, owner, &event.workspace_id, deadline)?; + } + if let Some(deadline) = deadline { + crate::memory::ingress_recovery::remaining(deadline)?; + } + tx.commit()?; + if let Some(deadline) = deadline { + crate::memory::ingress_recovery::remaining(deadline)?; + } + Ok(Some((event, inserted))) + }, + )) + .await? + } + + pub(in crate::memory::sqlite) fn append_event_row( + tx: &rusqlite::Transaction<'_>, + input: MessageEventInput, + bounded_receipt: bool, + ) -> anyhow::Result<(MessageEvent, bool)> { + let now = Utc::now().to_rfc3339(); + let event_id = input.event_id.unwrap_or_else(|| Uuid::new_v4().to_string()); + let content_hash = Self::content_hash(&input.content); + let visibility = input.visibility.as_str().to_string(); + let source = input.source.as_str().to_string(); + let source_ref_json = serde_json::to_string(&input.source)?; + let subject_ref_json = input.subject.as_ref().map(serde_json::to_string).transpose()?; + let config_generation_id = input.config_generation_id.map(i64::try_from).transpose()?; + + let mut bound_scope = super::agent_migration::resolve_input_scope( + tx, + input.agent_partition.as_ref(), + input.session_key.as_deref(), + &input.workspace_id, + input.owner_id.as_deref(), + )?; + if bound_scope.is_none() + && matches!( + input.source, + crate::memory::MessageEventSource::SessionsSpawn | crate::memory::MessageEventSource::SessionWorker + ) + { + bound_scope = tx + .query_row( + "SELECT ma_scope_id FROM child_sessions WHERE workspace_id=?1 AND owner_id=?2 AND session_id=?3", + params![input.workspace_id, input.owner_id, input.session_key], + |r| r.get(0), + ) + .optional()? + .flatten(); + if let Some(scope) = &bound_scope { + let fenced: bool = tx.query_row( + "SELECT EXISTS(SELECT 1 FROM agent_erase_fences WHERE scope_id=?1)", + [scope], + |r| r.get(0), + )?; + anyhow::ensure!(!fenced, AgentScopeRefused); + } else if input + .raw_payload_json + .as_deref() + .and_then(|raw| serde_json::from_str::(raw).ok()) + .is_some_and(|value| value.get("child_session_record").is_some()) + { + let owner = input.owner_id.clone().ok_or(AgentScopeRefused)?; + bound_scope = Some(super::agent_migration::resolve_write_scope( + tx, + &crate::memory::AgentPartition { + workspace_id: input.workspace_id.clone(), + owner_id: owner, + key: crate::memory::PartitionKey::Main, + }, + input.session_key.as_deref(), + )?); + } + } + let inserted = tx.execute( + "INSERT OR IGNORE INTO message_events ( + event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, + parent_session_key, run_id, parent_run_id, agent_id, persona_id, + sender, recipient, role, event_type, source_ref_json, subject_ref_json, + goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, + content, content_hash, raw_payload_json, visibility, created_at, updated_at, ma_scope_id + ) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, + ?16, ?17, ?18, ?19, ?20, ?21, ?22, ?23, ?24, ?25, ?26, ?27, ?28, ?29, + ?30, ?31, ?32)", + params![ + event_id, + input.idempotency_key, + input.workspace_id, + input.owner_id, + source, + input.channel, + input.session_key, + input.parent_session_key, + input.run_id, + input.parent_run_id, + input.agent_id, + input.persona_id, + input.sender, + input.recipient, + input.role, + input.event_type, + source_ref_json, + subject_ref_json, + input.goal_id, + input.causation_event_id, + input.correlation_id, + input.attempt_id, + input.lease_epoch, + config_generation_id, + input.config_source_revision, + input.content, + content_hash, + input.raw_payload_json, + visibility, + now, + now, + bound_scope + ], + )?; + + if bounded_receipt { + ingress_recovery::check_receipt_size(tx, &event_id, input.idempotency_key.as_deref(), &input.workspace_id)?; + } + + let event = if let Some(ref idempotency_key) = input.idempotency_key { + tx.query_row( + "SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, + parent_session_key, run_id, parent_run_id, agent_id, persona_id, + sender, recipient, role, event_type, source_ref_json, subject_ref_json, + goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, + content, content_hash, raw_payload_json, visibility, created_at, updated_at + FROM message_events + WHERE event_id = ?1 + OR (workspace_id = ?3 AND idempotency_key = ?2) + ORDER BY CASE WHEN event_id = ?1 THEN 0 ELSE 1 END + LIMIT 1", + params![event_id, idempotency_key, input.workspace_id], + Self::message_event_from_row, + )? + } else { + tx.query_row( + "SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, + parent_session_key, run_id, parent_run_id, agent_id, persona_id, + sender, recipient, role, event_type, source_ref_json, subject_ref_json, + goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, + content, content_hash, raw_payload_json, visibility, created_at, updated_at + FROM message_events + WHERE event_id = ?1 + LIMIT 1", + params![event_id], + Self::message_event_from_row, + )? + }; + + let stored_scope: Option = tx.query_row( + "SELECT ma_scope_id FROM message_events WHERE event_id = ?1", + params![event.event_id], + |row| row.get(0), + )?; + if stored_scope != bound_scope { + return Err(AgentScopeRefused.into()); + } + if inserted > 0 { + let mirror_scope = match (input.agent_partition.as_ref(), stored_scope) { + (_, Some(scope)) => Some(scope), + (Some(partition), None) => match &partition.key { + PartitionKey::Named { .. } => return Err(AgentScopeRefused.into()), + PartitionKey::Main => Some(super::agent_migration::resolve_write_scope( + tx, + partition, + input.session_key.as_deref(), + )?), + }, + (None, None) => None, + }; + tx.execute( + "INSERT INTO memory_events ( + event_id, workspace_id, owner_id, event_type, subject_table, subject_id, session_key, + agent_id, persona_id, visibility, payload_json, created_at, ma_scope_id + ) + VALUES (?1, ?2, ?3, ?4, 'message_events', ?5, ?6, ?7, ?8, ?9, NULL, ?10, ?11)", + params![ + Uuid::new_v4().to_string(), + event.workspace_id, + event.owner_id, + event.event_type, + event.event_id, + event.session_key, + event.agent_id, + event.persona_id, + event.visibility.as_str(), + Utc::now().to_rfc3339(), + mirror_scope + ], + )?; + } + if inserted > 0 { + super::child_turns::source_written(tx, &event)?; + super::sync_journal::event_written(tx, &event)?; + } + Ok((event, inserted > 0)) + } + + pub(super) fn repair_owner( + &self, + workspace: &str, + ) -> anyhow::Result> { + self.ingress_owners + .cell(workspace)? + .cell + .get() + .cloned() + .ok_or_else(|| anyhow::anyhow!("SQLite ingress repair requires an initialized owner")) + } +} diff --git a/src/memory/sqlite/events.rs b/src/memory/sqlite/events.rs index 02d1d44b8..d1c5be158 100644 --- a/src/memory/sqlite/events.rs +++ b/src/memory/sqlite/events.rs @@ -1,7 +1,7 @@ //! Conversations, ingress recovery, message events and memory events. use crate::memory::traits::{ - AgentScopeRefused, ChatProfile, ConversationSessionSummary, ConversationTurn, MemoryEvent, MemoryEventInput, + ChatProfile, ConversationSessionSummary, ConversationTurn, MemoryEvent, MemoryEventInput, MemoryPrincipal, MessageEvent, MessageEventInput, PartitionKey, SessionContextQuery, SharedContextQuery, }; use crate::runtime::sqlite_pool::begin_immediate; @@ -201,11 +201,8 @@ fn conversation_turns_statement_with( } use super::ingress_recovery; -use super::recovery_authority::{self, FullSync}; -use super::recovery_keys::KeyDirectory; use super::{SQLITE_DIALECT, SqliteMemory}; use crate::memory::ingress_recovery::AtomicIngressMutation; -use anyhow::Context; impl SqliteMemory { pub(super) async fn list_conversation_turns_ordered( @@ -299,280 +296,6 @@ impl SqliteMemory { .await? } - pub(super) async fn append_event_with_recovery( - &self, - input: MessageEventInput, - mutation: Option, - repair_deadline: Option, - ) -> anyhow::Result<(MessageEvent, bool)> { - // The attested append future carries the whole input, the mutation and the - // blocking closure; keep it on the heap so callers' futures stay small. - Box::pin(self.append_attested_event(input, mutation, repair_deadline, None)) - .await? - .context("only an ingress input can hit a tombstone without an error") - } - - /// The single append transaction; `None` means the stable key of an ingress - /// input is tombstoned (any other tombstoned input is `StableKeyTombstoned`). - /// Every stable-key user input runs the tombstone fence inside it. An attested - /// ingress input also writes its pending attestation and transport index row, - /// under FULL synchronization, so a crash leaves all of them or none. An rf - /// admission writes its attempt row in the same transaction (AC-1b2a). - pub(super) async fn append_attested_event( - &self, - input: MessageEventInput, - mutation: Option, - repair_deadline: Option, - admission: Option, - ) -> anyhow::Result> { - input.validate()?; - let pool = self.pool.clone(); - let deadline = mutation.as_ref().map(ingress_recovery::deadline).or(repair_deadline); - let repair_owner = repair_deadline - .map(|_| self.repair_owner(&input.workspace_id)) - .transpose()?; - let key_root = self.db_path.parent().map(std::path::Path::to_path_buf); - #[cfg(test)] - let db_path = self.db_path.clone(); - - Box::pin(crate::runtime::blocking::spawn_blocking( - move || -> anyhow::Result> { - // The mutation owns the genuine lease inside this blocking closure, - // including when its async waiter is cancelled. - let mut write = match deadline { - Some(deadline) => pool.write_until(deadline)?, - None => pool.write(), - }; - let conn = ingress_recovery::DeadlineConn::wrap(&mut write, deadline)?; - let attested = match &mutation { - Some(AtomicIngressMutation::Input { - capsule, - attestation: Some(attestation), - .. - }) => Some((capsule, attestation)), - _ => None, - }; - // Synchronization cannot change inside a transaction: set it first. - let _sync = attested.map(|_| FullSync::new(&conn)).transpose()?; - let keys = attested - .map(|_| KeyDirectory::open(key_root.as_deref().context("missing memory directory")?, false)) - .transpose()?; - // BEGIN IMMEDIATE takes the WAL write lock before any read. - // BEGIN DEFERRED pins a snapshot on the first SELECT (the - // tombstone fence when it runs); a second opener that commits - // then makes this INSERT return SQLITE_BUSY_SNAPSHOT / - // "database is locked" without the busy handler — the - // spawn_batch child-start failure against another pool on - // brain.db. - let tx = rusqlite::Transaction::new_unchecked(&conn, TransactionBehavior::Immediate)?; - if let (Some(owner), Some(deadline)) = (&repair_owner, repair_deadline) { - ingress_recovery::validate_owner(&tx, owner, &input.workspace_id, deadline)?; - } - if let Some(operation) = &mutation { - ingress_recovery::before_append(&tx, operation, &input)?; - } - // Every stable-key user input is fenced, with or without a recorder. - if matches!( - recovery_authority::stable_key_fence(&tx, key_root.as_deref(), &input)?, - recovery_authority::Fence::Tombstoned - ) { - // Dropping the transaction rolls back; nothing was inserted. - return match mutation { - Some(AtomicIngressMutation::Input { .. }) => Ok(None), - _ => Err(crate::memory::ingress_recovery::StableKeyTombstoned.into()), - }; - } - #[cfg(test)] - hold_append_snapshot_for_test(&input, &db_path)?; - let (event, inserted) = Self::append_event_row(&tx, input, deadline.is_some())?; - if let Some(operation) = &mutation { - ingress_recovery::after_append(&tx, operation, &event, inserted)?; - } - if let (true, Some((capsule, attestation)), Some(keys)) = (inserted, attested, &keys) { - recovery_authority::attest_ingress(&tx, keys, capsule, attestation, &event)?; - } - if let Some(admission) = &admission { - let lifetime = mutation.as_ref().map(|operation| operation.lease().token()); - super::rf_messages::admit(&tx, admission, &event, inserted, lifetime)?; - } - if let (Some(owner), Some(deadline)) = (&repair_owner, repair_deadline) { - ingress_recovery::validate_owner(&tx, owner, &event.workspace_id, deadline)?; - } - if let Some(deadline) = deadline { - crate::memory::ingress_recovery::remaining(deadline)?; - } - tx.commit()?; - if let Some(deadline) = deadline { - crate::memory::ingress_recovery::remaining(deadline)?; - } - Ok(Some((event, inserted))) - }, - )) - .await? - } - - pub(in crate::memory::sqlite) fn append_event_row( - tx: &rusqlite::Transaction<'_>, - input: MessageEventInput, - bounded_receipt: bool, - ) -> anyhow::Result<(MessageEvent, bool)> { - let now = Utc::now().to_rfc3339(); - let event_id = input.event_id.unwrap_or_else(|| Uuid::new_v4().to_string()); - let content_hash = Self::content_hash(&input.content); - let visibility = input.visibility.as_str().to_string(); - let source = input.source.as_str().to_string(); - let source_ref_json = serde_json::to_string(&input.source)?; - let subject_ref_json = input.subject.as_ref().map(serde_json::to_string).transpose()?; - let config_generation_id = input.config_generation_id.map(i64::try_from).transpose()?; - - let bound_scope = super::agent_migration::resolve_input_scope( - tx, - input.agent_partition.as_ref(), - input.session_key.as_deref(), - &input.workspace_id, - input.owner_id.as_deref(), - )?; - let inserted = tx.execute( - "INSERT OR IGNORE INTO message_events ( - event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, - parent_session_key, run_id, parent_run_id, agent_id, persona_id, - sender, recipient, role, event_type, source_ref_json, subject_ref_json, - goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, - content, content_hash, raw_payload_json, visibility, created_at, updated_at, ma_scope_id - ) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, - ?16, ?17, ?18, ?19, ?20, ?21, ?22, ?23, ?24, ?25, ?26, ?27, ?28, ?29, - ?30, ?31, ?32)", - params![ - event_id, - input.idempotency_key, - input.workspace_id, - input.owner_id, - source, - input.channel, - input.session_key, - input.parent_session_key, - input.run_id, - input.parent_run_id, - input.agent_id, - input.persona_id, - input.sender, - input.recipient, - input.role, - input.event_type, - source_ref_json, - subject_ref_json, - input.goal_id, - input.causation_event_id, - input.correlation_id, - input.attempt_id, - input.lease_epoch, - config_generation_id, - input.config_source_revision, - input.content, - content_hash, - input.raw_payload_json, - visibility, - now, - now, - bound_scope - ], - )?; - - if bounded_receipt { - ingress_recovery::check_receipt_size(tx, &event_id, input.idempotency_key.as_deref(), &input.workspace_id)?; - } - - let event = if let Some(ref idempotency_key) = input.idempotency_key { - tx.query_row( - "SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, - parent_session_key, run_id, parent_run_id, agent_id, persona_id, - sender, recipient, role, event_type, source_ref_json, subject_ref_json, - goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, - content, content_hash, raw_payload_json, visibility, created_at, updated_at - FROM message_events - WHERE event_id = ?1 - OR (workspace_id = ?3 AND idempotency_key = ?2) - ORDER BY CASE WHEN event_id = ?1 THEN 0 ELSE 1 END - LIMIT 1", - params![event_id, idempotency_key, input.workspace_id], - Self::message_event_from_row, - )? - } else { - tx.query_row( - "SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, - parent_session_key, run_id, parent_run_id, agent_id, persona_id, - sender, recipient, role, event_type, source_ref_json, subject_ref_json, - goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, - content, content_hash, raw_payload_json, visibility, created_at, updated_at - FROM message_events - WHERE event_id = ?1 - LIMIT 1", - params![event_id], - Self::message_event_from_row, - )? - }; - - let stored_scope: Option = tx.query_row( - "SELECT ma_scope_id FROM message_events WHERE event_id = ?1", - params![event.event_id], - |row| row.get(0), - )?; - if stored_scope != bound_scope { - return Err(AgentScopeRefused.into()); - } - if inserted > 0 { - let mirror_scope = match (input.agent_partition.as_ref(), stored_scope) { - (_, Some(scope)) => Some(scope), - (Some(partition), None) => match &partition.key { - PartitionKey::Named { .. } => return Err(AgentScopeRefused.into()), - PartitionKey::Main => Some(super::agent_migration::resolve_write_scope( - tx, - partition, - input.session_key.as_deref(), - )?), - }, - (None, None) => None, - }; - tx.execute( - "INSERT INTO memory_events ( - event_id, workspace_id, owner_id, event_type, subject_table, subject_id, session_key, - agent_id, persona_id, visibility, payload_json, created_at, ma_scope_id - ) - VALUES (?1, ?2, ?3, ?4, 'message_events', ?5, ?6, ?7, ?8, ?9, NULL, ?10, ?11)", - params![ - Uuid::new_v4().to_string(), - event.workspace_id, - event.owner_id, - event.event_type, - event.event_id, - event.session_key, - event.agent_id, - event.persona_id, - event.visibility.as_str(), - Utc::now().to_rfc3339(), - mirror_scope - ], - )?; - } - if inserted > 0 { - super::sync_journal::event_written(tx, &event)?; - } - Ok((event, inserted > 0)) - } - - fn repair_owner( - &self, - workspace: &str, - ) -> anyhow::Result> { - self.ingress_owners - .cell(workspace)? - .cell - .get() - .cloned() - .ok_or_else(|| anyhow::anyhow!("SQLite ingress repair requires an initialized owner")) - } - pub(super) async fn project_console_message_with_deadline( &self, event: &MessageEvent, @@ -2238,7 +1961,10 @@ fn hold_paths_match(left: &std::path::Path, right: &std::path::Path) -> bool { } #[cfg(test)] -fn hold_append_snapshot_for_test(input: &MessageEventInput, db_path: &std::path::Path) -> anyhow::Result<()> { +pub(super) fn hold_append_snapshot_for_test( + input: &MessageEventInput, + db_path: &std::path::Path, +) -> anyhow::Result<()> { let mut slot = APPEND_SNAPSHOT_HOLD.lock(); let matched = slot.as_ref().is_some_and(|hold| { input.run_id.as_deref() == Some(hold.run_id.as_str()) diff --git a/src/memory/sqlite/mod.rs b/src/memory/sqlite/mod.rs index b07bbf15c..0801f7a7e 100644 --- a/src/memory/sqlite/mod.rs +++ b/src/memory/sqlite/mod.rs @@ -5,8 +5,10 @@ mod agent_registry; mod approval_grants; mod branch_copy; mod child_sessions; +mod child_turns; mod documents; mod drafts; +mod event_append; mod event_batch; mod events; mod evolution; diff --git a/src/memory/sqlite/sync_lifecycle.rs b/src/memory/sqlite/sync_lifecycle.rs index 8ed57f25a..69c00cb22 100644 --- a/src/memory/sqlite/sync_lifecycle.rs +++ b/src/memory/sqlite/sync_lifecycle.rs @@ -34,7 +34,13 @@ pub(super) fn memory_written(conn: &Connection, event: &MemoryEvent) -> anyhow:: h.source_ref = format!("memory:{}", event.event_id); h.event_id = format!("child:{}", event.event_id); h.timestamp = event.created_at.clone(); - append(conn, &h) + append(conn, &h)?; + if event.event_type == "task.spawned" { + h.kind = "turn.started".into(); + h.event_id = format!("child-turn:{}", event.event_id); + append(conn, &h)?; + } + Ok(()) } pub(super) fn child_payload(conn: &Connection, h: &Header) -> anyhow::Result { diff --git a/src/runtime/operator_spawn.rs b/src/runtime/operator_spawn.rs index a87f1a528..92a132b8a 100644 --- a/src/runtime/operator_spawn.rs +++ b/src/runtime/operator_spawn.rs @@ -10,6 +10,7 @@ use std::sync::{ use tokio_util::sync::CancellationToken; pub(crate) struct OperatorSpawnSource { + continuation: Option, proof: OwnedTurnSourceProof, generation: Arc, fabric: crate::memory::MemoryFabric, @@ -34,6 +35,10 @@ impl Drop for OperatorLifetime { tokio::task_local! { static OPERATOR_SPAWN: Arc; } +pub(crate) fn current() -> Option> { + OPERATOR_SPAWN.try_with(Arc::clone).ok() +} + impl OperatorSpawnSource { pub(crate) fn new( proof: &dyn TurnSourceProof, @@ -82,6 +87,7 @@ impl OperatorSpawnSource { "operator model source differs from pinned PMM selection" ); Ok(Self { + continuation: None, catalog, resolved, route, @@ -98,6 +104,22 @@ impl OperatorSpawnSource { }) } + pub(crate) fn for_continuation( + mut self, + record: crate::memory::child_sessions::ChildSessionRecord, + ) -> anyhow::Result { + anyhow::ensure!( + record.owner == self.proof.owner_id() + && record.workspace == self.proof.workspace_id() + && record.parent_session == self.proof.session_key() + && record.provider == self.proof.provider_name() + && record.model == self.proof.model_name(), + "operator continuation identity differs" + ); + self.continuation = Some(record); + Ok(self) + } + pub(crate) async fn scope(self, work: F) -> F::Output { let _lifetime = OperatorLifetime(self.cancellation.clone()); OPERATOR_SPAWN.scope(Arc::new(self), work).await @@ -135,8 +157,7 @@ impl OperatorSpawnSource { ); scope.subject = scope.run_id.clone().map(crate::memory::MessageEventSubject::Task); scope.owner_id = Some(self.proof.owner_id().to_owned()); - scope.session_key = Some(self.proof.session_key().to_owned()); - scope.parent_session_key = scope.session_key.clone(); + scope.parent_session_key = Some(self.proof.session_key().to_owned()); scope.parent_run_id = Some(self.proof.run_id().to_owned()); scope.channel = Some(self.proof.policy_channel().to_owned()); scope.sender = Some(self.proof.policy_sender().to_owned()); @@ -169,7 +190,7 @@ pub(crate) fn claim(args: &serde_json::Value) -> anyhow::Result anyhow::Result + args.get("session_key").and_then(serde_json::Value::as_str) == Some(record.session_key.as_str()) + && args.get("mode").and_then(serde_json::Value::as_str) == Some(record.mode.as_str()) + && args.get("agent").and_then(serde_json::Value::as_str).unwrap_or("main") == record.agent, + None => !["session_key", "mode", "agent"] + .iter() + .any(|key| args.get(key).is_some()), + }, "operator spawn differs from captured command" ); anyhow::ensure!( diff --git a/src/runtime/operator_spawn/process.rs b/src/runtime/operator_spawn/process.rs index 77ab0d62a..95f48f018 100644 --- a/src/runtime/operator_spawn/process.rs +++ b/src/runtime/operator_spawn/process.rs @@ -140,9 +140,12 @@ impl super::OperatorSpawnSource { .as_deref() .is_some_and(|run| !run.is_empty() && run != self.proof.run_id()) && scope.owner_id.as_deref() == Some(self.proof.owner_id()) - && scope.session_key.as_deref() == Some(self.proof.session_key()) + && scope + .session_key + .as_deref() + .is_some_and(|key| key.starts_with("spawn:")) && scope.parent_run_id.as_deref() == Some(self.proof.run_id()) - && scope.parent_session_key == scope.session_key + && scope.parent_session_key.as_deref() == Some(self.proof.session_key()) && scope.channel.as_deref() == Some(self.proof.policy_channel()) && scope.sender.as_deref() == Some(self.proof.policy_sender()) && scope.recipient == self.proof.memory_scope().chat_id diff --git a/src/runtime/operator_spawn/task.rs b/src/runtime/operator_spawn/task.rs index 61441f14e..0bdb4acef 100644 --- a/src/runtime/operator_spawn/task.rs +++ b/src/runtime/operator_spawn/task.rs @@ -57,8 +57,11 @@ impl OperatorSpawnSource { && run_id != self.proof.run_id() && scope.source == crate::memory::MessageEventSource::SessionsSpawn && scope.owner_id.as_deref() == Some(self.proof.owner_id()) - && scope.session_key.as_deref() == Some(self.proof.session_key()) - && scope.parent_session_key == scope.session_key + && scope + .session_key + .as_deref() + .is_some_and(|key| key.starts_with("spawn:")) + && scope.parent_session_key.as_deref() == Some(self.proof.session_key()) && scope.parent_run_id.as_deref() == Some(self.proof.run_id()) && scope.channel.as_deref() == Some(self.proof.policy_channel()) && scope.sender.as_deref() == Some(self.proof.policy_sender()) @@ -191,7 +194,7 @@ impl OperatorTaskAuthority { && proof.surface() == crate::tools::capability::turn_state::TurnSurfaceKind::Worker && proof.workspace_id() == self.source.proof.workspace_id() && proof.owner_id() == self.source.proof.owner_id() - && proof.session_key() == self.source.proof.session_key() + && Some(proof.session_key()) == self.scope.session_key.as_deref() && proof.task_id() == Some(self.run_id.as_str()) && proof.provider_name() == self.source.proof.provider_name() && proof.model_name() == self.source.proof.model_name() @@ -249,7 +252,7 @@ impl TurnSourceProof for OperatorTaskAuthority { self.source.proof.owner_id() } fn session_key(&self) -> &str { - self.source.proof.session_key() + self.scope.session_key.as_deref().unwrap_or_default() } fn run_id(&self) -> &str { &self.run_id diff --git a/src/session_worker/protocol.rs b/src/session_worker/protocol.rs index 1ae20ff8e..f6a562820 100644 --- a/src/session_worker/protocol.rs +++ b/src/session_worker/protocol.rs @@ -127,6 +127,9 @@ pub struct WorkerManifest { #[serde(default, skip_serializing_if = "Option::is_none")] pub session_addr: Option, pub task: String, + /// Prior public turns of a continued child, covered by the manifest MAC. + #[serde(default)] + pub seed_history: Vec, pub provider_name: String, pub model: String, /// Selected model route, when the parent resolved a `hint:` model. @@ -407,6 +410,7 @@ mod tests { #[test] fn worker_manifest_roundtrip_json_preserves_owner_isolation() { let manifest = WorkerManifest { + seed_history: Vec::new(), parent_capability: Some("capability".into()), ordinary_source: None, operator_source: None, @@ -594,6 +598,7 @@ mod tests { #[test] fn inherited_provenance_is_sealed_into_worker_manifest() { let mut manifest = WorkerManifest { + seed_history: Vec::new(), parent_capability: None, ordinary_source: None, operator_source: None, diff --git a/src/session_worker/runner/run.rs b/src/session_worker/runner/run.rs index 2c6c2876b..76072add8 100644 --- a/src/session_worker/runner/run.rs +++ b/src/session_worker/runner/run.rs @@ -892,7 +892,17 @@ async fn run_owned_manifest( let process_denials = Arc::new(crate::session_worker::denials::DenialSink::default()); let run_future = boxed_worker_segments(|| async { - let initial_history = Vec::new(); + let mut initial_history: Vec = manifest + .seed_history + .iter() + .map(|turn| crate::providers::ChatMessage { + role: turn.role.clone(), + content: turn.content.clone(), + }) + .collect(); + if !initial_history.is_empty() { + initial_history.push(crate::providers::ChatMessage::user(&manifest.task)); + } let observer = NoopObserver; let scope_ctx = match ( diff --git a/src/session_worker/runner/tests/hybrid.rs b/src/session_worker/runner/tests/hybrid.rs index 944aaa6d7..798cb5300 100644 --- a/src/session_worker/runner/tests/hybrid.rs +++ b/src/session_worker/runner/tests/hybrid.rs @@ -50,6 +50,7 @@ async fn hybrid_worker_shared_context_reads_parent_fabric() { .await .unwrap(); let manifest = WorkerManifest { + seed_history: Vec::new(), parent_capability: Some("capability".to_string()), ordinary_source: None, operator_source: None, @@ -170,6 +171,7 @@ async fn process_mode_worker_prompt_carries_no_other_owners_spawn_text() { .expect("test: seed a workspace event"); } let manifest = WorkerManifest { + seed_history: Vec::new(), parent_capability: Some("capability".to_string()), ordinary_source: None, operator_source: None, @@ -264,6 +266,7 @@ async fn hybrid_worker_result_creates_private_draft_and_parent_merge_request() { .await .unwrap(); let manifest = WorkerManifest { + seed_history: Vec::new(), parent_capability: Some("capability".to_string()), ordinary_source: None, operator_source: None, @@ -414,6 +417,7 @@ async fn hybrid_worker_draft_obeys_readonly_resource_gate() { tokens_used: None, }; let manifest = WorkerManifest { + seed_history: Vec::new(), parent_capability: Some("capability".to_string()), ordinary_source: None, operator_source: None, diff --git a/src/session_worker/runner/tests/mod.rs b/src/session_worker/runner/tests/mod.rs index 8f1d66c7e..d952e9212 100644 --- a/src/session_worker/runner/tests/mod.rs +++ b/src/session_worker/runner/tests/mod.rs @@ -15,6 +15,7 @@ use std::path::Path; pub(crate) fn base_manifest(workspace: &Path, capability: &str) -> WorkerManifest { WorkerManifest { + seed_history: Vec::new(), parent_capability: Some(capability.to_string()), ordinary_source: None, operator_source: None, diff --git a/src/session_worker/runner/tests/spawn_context.rs b/src/session_worker/runner/tests/spawn_context.rs index 257062ab2..116b776da 100644 --- a/src/session_worker/runner/tests/spawn_context.rs +++ b/src/session_worker/runner/tests/spawn_context.rs @@ -8,6 +8,7 @@ use crate::session_worker::runner::context::{ #[tokio::test] async fn process_mode_restores_spawn_context_for_nested_runs() { let manifest = WorkerManifest { + seed_history: Vec::new(), parent_capability: Some("capability".to_string()), ordinary_source: None, operator_source: None, @@ -90,6 +91,7 @@ async fn process_mode_restores_spawn_context_for_nested_runs() { #[test] fn worker_event_scope_preserves_spawn_lineage_and_owner_isolation() { let manifest = WorkerManifest { + seed_history: Vec::new(), parent_capability: Some("capability".to_string()), ordinary_source: None, operator_source: None, diff --git a/src/tools/sessions_spawn/continuation.rs b/src/tools/sessions_spawn/continuation.rs new file mode 100644 index 000000000..8594372f5 --- /dev/null +++ b/src/tools/sessions_spawn/continuation.rs @@ -0,0 +1,122 @@ +//! Freshly admitted turns over a durable logical child session. +use super::{HistoryEntry, SessionsSpawnTool, SubAgentRun, SubAgentStatus}; +use crate::memory::child_sessions::{ChildSessionRecord, ChildTurn}; +use crate::runtime::turn_source::TurnSourceProof; +use crate::tools::traits::ToolResult; +use anyhow::Context; + +#[derive(Clone)] +pub(super) struct Continuation { + pub record: ChildSessionRecord, + pub history: Vec, +} +tokio::task_local! { static CONTINUATION: Continuation; } + +pub(super) fn current() -> Option { + CONTINUATION.try_with(Clone::clone).ok() +} + +pub(super) fn seed_history() -> Vec { + current().map_or_else(Vec::new, |seed| { + seed.history + .into_iter() + .map(|turn| HistoryEntry { + role: turn.role, + content: turn.content, + timestamp: turn.timestamp, + }) + .collect() + }) +} + +pub(super) fn register(runs: &mut Vec, run: SubAgentRun) -> anyhow::Result<()> { + if let Some(previous) = runs + .iter_mut() + .find(|old| old.session_scope_key == run.session_scope_key) + { + anyhow::ensure!( + !matches!( + previous.status, + SubAgentStatus::Running | SubAgentStatus::AwaitingInput { .. } + ), + "child_session_busy" + ); + let mut run = run; + run.token_usage_records.clone_from(&previous.token_usage_records); + *previous = run; + } else { + runs.push(run); + } + Ok(()) +} + +impl SessionsSpawnTool { + pub(super) async fn execute_continue(&self, args: &serde_json::Value) -> anyhow::Result { + let fabric = self.memory_fabric().context("child sessions require durable storage")?; + let operator = crate::runtime::operator_spawn::current(); + let caller = crate::tools::execution::current_child_call_context(); + let (owner, parent) = if let Some(operator) = &operator { + operator.verify_live()?; + ( + operator.proof().owner_id().to_owned(), + operator.proof().session_key().to_owned(), + ) + } else if let Some(caller) = &caller { + caller.verify_tool("sessions_spawn")?; + ( + caller.context().envelope.resolved_owner_id(), + caller.context().envelope.session_key.clone(), + ) + } else { + anyhow::bail!("child continuation requires an admitted parent or operator source"); + }; + let target = args + .get("session_key") + .or_else(|| args.get("run_id")) + .and_then(serde_json::Value::as_str) + .context("child continuation requires session_key or run_id")?; + let memory = fabric.memory(); + let store = memory + .child_session_store() + .context("child session storage unsupported")?; + let record = store + .sessions(fabric.workspace_id(), &owner)? + .into_iter() + .find(|record| { + record.parent_session == parent + && (record.session_key == target || record.runs.iter().any(|run| run == target)) + }) + .context("child_session_unknown")?; + anyhow::ensure!( + !self + .active_runs + .read() + .await + .iter() + .any(|run| run.session_scope_key == record.session_key + && matches!( + run.status, + SubAgentStatus::Running | SubAgentStatus::AwaitingInput { .. } + )), + "child_session_busy" + ); + let history = store.history(&record)?; + let mut launch = args.clone(); + let object = launch + .as_object_mut() + .context("continuation arguments must be an object")?; + object.insert("provider".into(), record.provider.clone().into()); + object.insert("model".into(), record.model.clone().into()); + object.insert("mode".into(), record.mode.clone().into()); + if record.agent != "main" { + object.insert("agent".into(), record.agent.clone().into()); + } + CONTINUATION + .scope( + Continuation { record, history }, + super::boxed_spawn_field(|| self.execute_spawn(&launch, None)), + ) + .await + .map(|outcome| outcome.result) + } +} diff --git a/src/tools/sessions_spawn/events.rs b/src/tools/sessions_spawn/events.rs index 0ffb27f45..9a2c5363f 100644 --- a/src/tools/sessions_spawn/events.rs +++ b/src/tools/sessions_spawn/events.rs @@ -70,6 +70,44 @@ pub(super) async fn record_spawn_request_event( "parent_task_id": lineage.parent_task_id, "source_message_event_id": lineage.source_message_event_id }); + let run = scope + .run_id + .as_deref() + .ok_or_else(|| anyhow::anyhow!("child run missing"))?; + let session = scope + .session_key + .as_deref() + .ok_or_else(|| anyhow::anyhow!("child session missing"))?; + let parent = scope + .parent_session_key + .as_deref() + .ok_or_else(|| anyhow::anyhow!("child parent session missing"))?; + let mut runs = super::continuation::current().map_or_else(Vec::new, |seed| seed.record.runs); + runs.push(run.to_owned()); + metadata["child_session_record"] = serde_json::to_value(crate::memory::child_sessions::ChildSessionRecord { + workspace: fabric.workspace_id().to_owned(), + owner: scope + .owner_id + .clone() + .ok_or_else(|| anyhow::anyhow!("child owner missing"))?, + session_key: session.to_owned(), + parent_session: parent.to_owned(), + parent_run: scope + .parent_run_id + .clone() + .ok_or_else(|| anyhow::anyhow!("child parent run missing"))?, + agent: scope.agent_id.clone().unwrap_or_else(|| "main".into()), + mode: mode.to_owned(), + provider: provider_name.into_owned(), + model: selection.1.to_owned(), + level: codes.child_level, + created_at: chrono::Utc::now(), + ended_at: None, + status: "running".into(), + runs, + context_after: 0, + context: Vec::new(), + })?; let receipt = crate::runtime::child_source::record_child_input(fabric, scope, task, None, Some(metadata.to_string())).await?; delegation::append_task(&mut metadata, task)?; diff --git a/src/tools/sessions_spawn/live_usage.rs b/src/tools/sessions_spawn/live_usage.rs new file mode 100644 index 000000000..0c73685fe --- /dev/null +++ b/src/tools/sessions_spawn/live_usage.rs @@ -0,0 +1,34 @@ +//! Display confirmed segment usage while a logical child task remains live. +use super::SubAgentRun; +use std::sync::Arc; +use tokio::sync::RwLock; +use tokio_util::sync::CancellationToken; + +pub(super) fn observe( + collector: Arc, + runs: Arc>>, + run: String, +) -> tokio_util::sync::DropGuard { + let cancellation = CancellationToken::new(); + let guard = cancellation.clone().drop_guard(); + tokio::spawn(async move { + let mut interval = tokio::time::interval(std::time::Duration::from_millis(250)); + loop { + tokio::select! { + ()=cancellation.cancelled()=>break, + _=interval.tick()=>{ + let usage=collector.session_snapshot(); + let mut runs=runs.write().await; + let Some(run)=runs.iter_mut().find(|row|row.id==run) else {break;}; + for usage in usage.into_iter().filter(|usage|usage.settlement_class.is_some()) { + let Some(id)=usage.settlement_id.as_ref() else {continue;}; + if !run.token_usage_records.iter().any(|known|known.settlement_id.as_ref()==Some(id)) { + run.token_usage_records.push(usage); + } + } + } + } + } + }); + guard +} diff --git a/src/tools/sessions_spawn/mod.rs b/src/tools/sessions_spawn/mod.rs index 5a2f701dd..5542493e9 100644 --- a/src/tools/sessions_spawn/mod.rs +++ b/src/tools/sessions_spawn/mod.rs @@ -23,8 +23,10 @@ mod batch; mod builders; mod chat_assign; mod child_lifecycle; +mod continuation; mod events; mod failure; +mod live_usage; mod memory_scope; mod monitor; mod owned_process; diff --git a/src/tools/sessions_spawn/process_mode.rs b/src/tools/sessions_spawn/process_mode.rs index ae08cc972..14801970b 100644 --- a/src/tools/sessions_spawn/process_mode.rs +++ b/src/tools/sessions_spawn/process_mode.rs @@ -247,7 +247,7 @@ pub(super) async fn run_sub_agent_process( // it with an HMAC bound to the run id, an absolute expiry, and a digest of // the manifest contents. A leaked capability token therefore cannot be // replayed for a different run, after expiry, or with a tampered manifest. - let (manifest, sealed_capability, capability_expiry, mut mailbox_binding) = build_session_worker_manifest( + let (mut manifest, _, capability_expiry, mut mailbox_binding) = build_session_worker_manifest( run_id, task, provider_name, @@ -286,6 +286,25 @@ pub(super) async fn run_sub_agent_process( ) .map_err(refused_here)?; + manifest.seed_history = history + .read() + .await + .iter() + .filter(|entry| entry.role != "system") + .map(|entry| crate::memory::child_sessions::ChildTurn { + role: entry.role.clone(), + content: entry.content.clone(), + timestamp: entry.timestamp, + }) + .collect(); + let sealed_capability = super::compute_worker_capability_with_key( + &launch_transport_key, + &manifest.run_id, + capability_expiry, + &super::manifest_signing_payload(&manifest)?, + ); + manifest.parent_capability = Some(sealed_capability.clone()); + if let Some(reason) = process_control.termination_reason() { cleanup_process_worker_workspace(run_id, &worker_workspace, keep_workspace); return Ok(ProcessWorkerOutcome::Terminated(reason)); diff --git a/src/tools/sessions_spawn/spawn.rs b/src/tools/sessions_spawn/spawn.rs index eb39343fc..75bf8133a 100644 --- a/src/tools/sessions_spawn/spawn.rs +++ b/src/tools/sessions_spawn/spawn.rs @@ -351,13 +351,8 @@ impl SessionsSpawnTool { // Every ordinary spawned run records under its own key; the caller // link is `parent_session_key` and `parent_run_id`. An operator // source keeps its authenticated session. - let session_scope_key = operator_source.as_ref().map_or_else( - || spawn_session_key(&run_id), - |source| { - use crate::runtime::turn_source::TurnSourceProof; - source.proof().session_key().to_owned() - }, - ); + let session_scope_key = + super::continuation::current().map_or_else(|| spawn_session_key(&run_id), |seed| seed.record.session_key); // The registry imposes no global fan-out or nesting limit. A child's // sealed delegation grant independently bounds its depth. An operator sees every @@ -851,7 +846,8 @@ impl SessionsSpawnTool { None => process_source_launch, }; let temperature = resolved_temperature; - let history_arc: Arc>> = Arc::new(RwLock::new(Vec::new())); + let history_arc: Arc>> = + Arc::new(RwLock::new(super::continuation::seed_history())); let process_control = ProcessRunControl::new(); // Process-mode steering: the sender lives in the registry exactly as // it does for task mode, so `sessions_send` / `sessions_spawn:steer` @@ -886,7 +882,7 @@ impl SessionsSpawnTool { batch_id: batch_id.map(str::to_string), }); run.agent_partition = spawn_scope_for_event.agent_partition.clone(); - runs.push(run); + super::continuation::register(&mut runs, run)?; } let model = resolved_model; @@ -1377,7 +1373,7 @@ impl SessionsSpawnTool { } // Create shared history and steer channel for this run - let history_arc: Arc>> = Arc::new(RwLock::new(Vec::new())); + let history_arc: Arc>> = Arc::new(RwLock::new(super::continuation::seed_history())); // Class B — bounded. Steering messages are produced by operators and by // model tool calls, neither of which is rate-limited now that sub-agent // concurrency is uncapped, while the consumer only polls between tool @@ -1633,32 +1629,35 @@ impl SessionsSpawnTool { // `abort_handle` is filled in right after `tokio::spawn` returns. { let mut runs = self.active_runs.write().await; - runs.push(SubAgentRun { - agent_partition: spawn_scope_for_event.agent_partition.clone(), - id: run_id.clone(), - task: task.to_string(), - owner_id: run_lineage.owner_id.clone(), - topic_id: run_lineage.topic_id.clone(), - source_message_event_id: run_lineage.source_message_event_id.clone(), - started_at: Utc::now(), - finished_at: None, - status: SubAgentStatus::Running, - recipient: recipient.clone(), - channel_name: run_channel_name.clone(), - abort_handle: None, - process_control: None, - task_control: Some(Arc::clone(&task_control)), - history: history_arc.clone(), - steer_tx: Some(steer_tx.clone()), - parent_run_id: parent_run_id.clone(), - session_scope_key: session_scope_key.clone(), - spawn_depth, - // Recursive delegation status is issued by no parent (P2-G4). - delegation: None, - token_usage_records: Vec::new(), - progress: Arc::clone(&task_progress), - batch_id: batch_id.map(str::to_string), - }); + super::continuation::register( + &mut runs, + SubAgentRun { + agent_partition: spawn_scope_for_event.agent_partition.clone(), + id: run_id.clone(), + task: task.to_string(), + owner_id: run_lineage.owner_id.clone(), + topic_id: run_lineage.topic_id.clone(), + source_message_event_id: run_lineage.source_message_event_id.clone(), + started_at: Utc::now(), + finished_at: None, + status: SubAgentStatus::Running, + recipient: recipient.clone(), + channel_name: run_channel_name.clone(), + abort_handle: None, + process_control: None, + task_control: Some(Arc::clone(&task_control)), + history: history_arc.clone(), + steer_tx: Some(steer_tx.clone()), + parent_run_id: parent_run_id.clone(), + session_scope_key: session_scope_key.clone(), + spawn_depth, + // Recursive delegation status is issued by no parent (P2-G4). + delegation: None, + token_usage_records: Vec::new(), + progress: Arc::clone(&task_progress), + batch_id: batch_id.map(str::to_string), + }, + )?; } // Registry row for this run. Parent captured on the spawning task, which diff --git a/src/tools/sessions_spawn/task_mode.rs b/src/tools/sessions_spawn/task_mode.rs index 1ec3cd893..ec543ccb0 100644 --- a/src/tools/sessions_spawn/task_mode.rs +++ b/src/tools/sessions_spawn/task_mode.rs @@ -162,6 +162,10 @@ pub(super) async fn run_sub_agent_task( .try_with(|context| context.terminal_usage.clone()) .ok() .flatten(); + let _live_usage = match (child_usage.clone(), active_runs.clone(), run_id.clone()) { + (Some(usage), Some(runs), Some(run)) => Some(super::live_usage::observe(usage, runs, run)), + _ => None, + }; anyhow::ensure!( (ordinary_segments.is_none() && operator_segments.is_none()) || child_usage.is_some(), "child segment usage owner missing" @@ -224,7 +228,18 @@ pub(super) async fn run_sub_agent_task( .transpose()?; // --- Agentic loop with steering support --- - let mut history: Vec = Vec::new(); + let mut history: Vec = history_out + .read() + .await + .iter() + .map(|entry| ChatMessage { + role: entry.role.clone(), + content: entry.content.clone(), + }) + .collect(); + if !history.is_empty() { + history.push(ChatMessage::user(task)); + } // NeedsInput: deterministically restore a suspended run to `Running` before // re-entering the loop. Called on every path that *continues* running after a diff --git a/src/tools/sessions_spawn/tests/process_manifest.rs b/src/tools/sessions_spawn/tests/process_manifest.rs index fb1ba286f..f3db8cd31 100644 --- a/src/tools/sessions_spawn/tests/process_manifest.rs +++ b/src/tools/sessions_spawn/tests/process_manifest.rs @@ -149,6 +149,7 @@ async fn spawn_agent_uses_identity_prompt() { #[test] fn process_mode_task_arg_is_not_json_encoded() { let manifest = WorkerManifest { + seed_history: Vec::new(), parent_capability: Some("capability".to_string()), ordinary_source: None, operator_source: None, diff --git a/src/tools/sessions_spawn/tool.rs b/src/tools/sessions_spawn/tool.rs index bbb5d736e..a3018c184 100644 --- a/src/tools/sessions_spawn/tool.rs +++ b/src/tools/sessions_spawn/tool.rs @@ -51,7 +51,7 @@ impl SessionsSpawnTool { "properties": { "action": { "type": "string", - "enum": ["spawn", "spawn_batch", "join", "list", "kill", "history", "steer", "chat_sessions", "chat_assign"], + "enum": ["spawn", "continue", "spawn_batch", "join", "list", "kill", "history", "steer", "chat_sessions", "chat_assign"], "default": "spawn", "description": "Action to perform, with the parameter it reads: 'spawn' task; \ 'spawn_batch' tasks; 'join' batch_id; 'list' none; 'kill' run_id; 'history' run_id; \ @@ -135,6 +135,7 @@ impl SessionsSpawnTool { "description": "For 'spawn', default true: whether the sub-agent posts its own result to the channel. \ A 'spawn_batch' member never announces; collect a batch with 'join' and report it once." }, + "session_key": {"type":"string","description":"Stable spawn session key for continue."}, "last_n": { "type": "integer", "minimum": 1, @@ -161,6 +162,10 @@ impl SessionsSpawnTool { action: "spawn_batch", required: &["tasks"], }, + crate::tools::schema::ActionRequirement { + action: "continue", + required: &["task"], + }, crate::tools::schema::ActionRequirement { action: "kill", required: &["run_id"], @@ -240,6 +245,7 @@ impl Tool for SessionsSpawnTool { } match action { + "continue" => return self.execute_continue(&args).await, "list" => return self.execute_list(&owner_scope).await, "kill" => { let run_id = args diff --git a/src/tools/sessions_spawn/worker_manifest.rs b/src/tools/sessions_spawn/worker_manifest.rs index 8822b98f6..5ff8807b8 100644 --- a/src/tools/sessions_spawn/worker_manifest.rs +++ b/src/tools/sessions_spawn/worker_manifest.rs @@ -135,6 +135,7 @@ pub(super) fn build_session_worker_manifest( operator_source: None, run_id: run_id.to_string(), task: task.to_string(), + seed_history: Vec::new(), provider_name: provider_name.to_string(), model: model.to_string(), route_hint: route_hint.map(str::to_string), diff --git a/tests/architecture_boundaries/memory.rs b/tests/architecture_boundaries/memory.rs index c99189d5c..3c008d840 100644 --- a/tests/architecture_boundaries/memory.rs +++ b/tests/architecture_boundaries/memory.rs @@ -152,6 +152,7 @@ const SQLITE_BACKEND_FILES: &[&str] = &[ "drafts.rs", "erasure_pool.rs", "events.rs", + "event_append.rs", "evolution.rs", "fixture_readback.rs", "mailbox.rs", @@ -162,6 +163,7 @@ const SQLITE_BACKEND_FILES: &[&str] = &[ "recall.rs", "remote_tree.rs", "child_sessions.rs", + "child_turns.rs", "rows.rs", "schema.rs", ]; @@ -375,6 +377,7 @@ fn runtime_and_message_events_preserve_typed_config_generation_columns() { "child_sessions.rs", include_str!("../../src/memory/sqlite/child_sessions.rs"), ), + ("child_turns.rs", include_str!("../../src/memory/sqlite/child_turns.rs")), ("documents.rs", include_str!("../../src/memory/sqlite/documents.rs")), ("drafts.rs", include_str!("../../src/memory/sqlite/drafts.rs")), ( @@ -382,6 +385,10 @@ fn runtime_and_message_events_preserve_typed_config_generation_columns() { include_str!("../../src/memory/sqlite/erasure_pool.rs"), ), ("events.rs", include_str!("../../src/memory/sqlite/events.rs")), + ( + "event_append.rs", + include_str!("../../src/memory/sqlite/event_append.rs"), + ), ("evolution.rs", include_str!("../../src/memory/sqlite/evolution.rs")), ("mailbox.rs", include_str!("../../src/memory/sqlite/mailbox.rs")), ( diff --git a/tests/session_worker_stdin_protocol.rs b/tests/session_worker_stdin_protocol.rs index 528aaa78f..bb98fb0d0 100644 --- a/tests/session_worker_stdin_protocol.rs +++ b/tests/session_worker_stdin_protocol.rs @@ -60,6 +60,7 @@ struct WorkerRun { /// decision source, the run stops immediately after transport verification. fn manifest_for(config_dir: &Path, workspace_dir: &Path) -> WorkerManifest { WorkerManifest { + seed_history: Vec::new(), parent_capability: None, ordinary_source: None, operator_source: None, From 2667a77c0caca2c51dbcbad0c3040ce3a6c6bd0e Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 15:00:40 +0400 Subject: [PATCH 0002/1567] feat(messaging): activate durable local and pinned mTLS delivery --- Cargo.lock | 2 + Cargo.toml | 4 +- docs/configuration.md | 45 +- docs/tools.md | 22 + src/agent/agent/cleanup_diagnostic_tests.rs | 1 + src/agent/tests.rs | 1 + src/channels/startup.rs | 1 + src/chat/action.rs | 2 +- src/chat/binding.rs | 41 +- src/chat/chat_events.rs | 2 +- src/chat/child_focus.rs | 124 +- src/chat/commands.rs | 7 + src/chat/commands/msg.rs | 12 +- src/chat/message_inbox.rs | 139 + src/chat/mod.rs | 4 +- src/chat/provider_turns.rs | 2339 +-------- src/chat/provider_turns/section_1.rs | 1701 ++++++ src/chat/provider_turns/section_2.rs | 636 +++ src/chat/run.rs | 55 +- src/chat/run/event_pump.rs | 42 +- src/chat/run/provider_turn.rs | 4 +- src/chat/run/startup.rs | 1 + src/chat/session_glue.rs | 6 + src/chat/sessions/assignment.rs | 2102 +------- src/chat/sessions/assignment/section_1.rs | 1222 +++++ src/chat/sessions/assignment/section_2.rs | 909 ++++ src/chat/sessions/child.rs | 72 +- src/chat/state/mod.rs | 2 +- src/chat/tests/p3_directional_switch_tests.rs | 3668 +------------ .../p3_directional_switch_tests/section_1.rs | 1721 ++++++ .../p3_directional_switch_tests/section_2.rs | 1737 ++++++ .../p3_directional_switch_tests/section_3.rs | 206 + src/config/generation.rs | 2284 +------- src/config/generation/section_1.rs | 1201 +++++ src/config/generation/section_2.rs | 1080 ++++ src/config/mod.rs | 39 +- src/config/schema/agent.rs | 3 + src/config/schema/integrations.rs | 244 +- src/config/schema/providers.rs | 15 + src/config/schema/tests/mod.rs | 1 + src/config/schema/tests/persistence.rs | 2 + src/config/secret_paths.rs | 2132 +------- src/config/secret_paths/tests.rs | 4 + src/config/secret_paths/tests/section_1.rs | 1732 ++++++ src/config/secret_paths/tests/section_2.rs | 365 ++ src/doctor/implementation/section_1.rs | 1445 +++++ src/doctor/implementation/section_2.rs | 1152 ++++ src/doctor/mod.rs | 4559 +--------------- src/doctor/tests.rs | 14 + src/doctor/tests/section_1.rs | 1734 ++++++ src/doctor/tests/section_2.rs | 217 + src/gateway/api/chat_sessions.rs | 29 + src/gateway/api/sessions.rs | 4488 +--------------- src/gateway/api/sessions/mailbox.rs | 98 + src/gateway/api/sessions/section_1.rs | 1718 ++++++ src/gateway/api/sessions/section_2.rs | 1060 ++++ src/gateway/api/sessions/section_3.rs | 1731 ++++++ src/gateway/api/sessions/tests/targeting.rs | 2865 +--------- .../api/sessions/tests/targeting/section_1.rs | 1538 ++++++ .../api/sessions/tests/targeting/section_2.rs | 1325 +++++ src/gateway/implementation/section_1.rs | 1740 ++++++ src/gateway/implementation/section_2.rs | 1570 ++++++ src/gateway/implementation/section_3.rs | 972 ++++ src/gateway/mod.rs | 4283 +-------------- src/gateway/tests/agent_registry.rs | 1 + src/main.rs | 4647 +---------------- src/main/section_1.rs | 1647 ++++++ src/main/section_2.rs | 1683 ++++++ src/main/section_3.rs | 1319 +++++ src/memory/sqlite/child_turns.rs | 1 + src/memory/sqlite/events.rs | 1985 +------ src/memory/sqlite/events/section_1.rs | 203 + src/memory/sqlite/events/section_2.rs | 1744 +++++++ src/memory/sqlite/events/section_3.rs | 33 + src/memory/sqlite/mailbox.rs | 9 +- src/memory/sqlite/mailbox/adopt.rs | 76 +- src/memory/sqlite/mailbox/harness.rs | 8 +- src/memory/sqlite/mailbox/local_runtime.rs | 137 + src/memory/sqlite/mailbox/model.rs | 6 +- src/memory/sqlite/mailbox/outbox.rs | 9 +- src/memory/sqlite/mailbox/pin.rs | 6 +- src/memory/sqlite/mailbox/publish.rs | 29 +- src/memory/sqlite/mailbox/receipt.rs | 3 +- src/memory/sqlite/mailbox/retry.rs | 166 + src/memory/sqlite/mailbox/runtime.rs | 16 + src/memory/sqlite/mailbox/sender.rs | 23 +- src/memory/sqlite/sync_journal.rs | 12 +- src/memory/sqlite/sync_projection.rs | 12 + src/memory/sqlite/tests/mailbox.rs | 3535 +------------ src/memory/sqlite/tests/mailbox/section_1.rs | 1733 ++++++ src/memory/sqlite/tests/mailbox/section_2.rs | 1698 ++++++ src/memory/sqlite/tests/mailbox/section_3.rs | 76 + src/messaging/a2a/cli.rs | 174 + src/messaging/a2a/clients.rs | 98 + src/messaging/a2a/connections.rs | 96 + src/messaging/a2a/identity.rs | 228 + src/messaging/a2a/listener.rs | 285 + src/messaging/a2a/mod.rs | 12 + src/messaging/a2a/outbound.rs | 193 + src/messaging/a2a/peers.rs | 78 + src/messaging/a2a/resources.rs | 101 + src/messaging/a2a/tls.rs | 240 + src/messaging/mailbox.rs | 11 +- src/messaging/mod.rs | 7 + src/messaging/receiver.rs | 48 + src/messaging/runtime.rs | 389 ++ src/messaging/types.rs | 20 +- src/messaging/worker.rs | 233 + src/providers/catalog/resolver_tests.rs | 1 + src/providers/credential_containment_tests.rs | 1 + .../child_source/golden_effective_config.json | 2 +- src/runtime/child_source/tests.rs | 2 +- src/runtime/mode.rs | 4 + src/runtime/operator_spawn.rs | 78 +- src/runtime/tasks_cli.rs | 15 +- src/session_worker/frame_auth.rs | 98 + src/session_worker/frames.rs | 15 + src/session_worker/mailbox.rs | 6 +- src/session_worker/mailbox_harness.rs | 12 +- src/session_worker/mod.rs | 2 + src/session_worker/runner/mod.rs | 9 +- src/session_worker/runner/run.rs | 23 +- src/session_worker/runner/steering.rs | 27 +- src/session_worker/stdout.rs | 12 +- src/tools/agents_list.rs | 2 + src/tools/capability/catalog.rs | 2369 +-------- src/tools/capability/catalog/section_1.rs | 1081 ++++ src/tools/capability/catalog/section_2.rs | 1287 +++++ src/tools/delegate.rs | 2136 +------- .../delegate/credential_containment_tests.rs | 1 + src/tools/delegate/tests.rs | 4 + src/tools/delegate/tests/section_1.rs | 1717 ++++++ src/tools/delegate/tests/section_2.rs | 421 ++ src/tools/mod.rs | 4 +- src/tools/prx_message.rs | 59 - src/tools/session_status.rs | 18 + src/tools/sessions_send.rs | 85 +- src/tools/sessions_spawn/child_lifecycle.rs | 22 +- src/tools/sessions_spawn/continuation.rs | 11 +- src/tools/sessions_spawn/events.rs | 6 +- src/tools/sessions_spawn/spawn.rs | 38 +- src/tools/sessions_spawn/task_mode.rs | 7 +- .../tests/credential_containment.rs | 1 + src/tools/sessions_spawn/tests/mod.rs | 1 + tests/architecture_boundaries/config.rs | 5 +- tests/architecture_boundaries/helpers.rs | 147 +- .../architecture_boundaries/loop_contracts.rs | 3 +- tests/architecture_boundaries/loop_prompt.rs | 6 +- tests/architecture_boundaries/memory.rs | 6 +- tests/architecture_boundaries/panic_policy.rs | 2 +- tests/architecture_boundaries/process.rs | 2 +- .../architecture_boundaries/scanner_probes.rs | 6 +- tests/architecture_boundaries/tool_tables.rs | 7 +- tests/int_memory_delegate.rs | 3 + 154 files changed, 47404 insertions(+), 43860 deletions(-) create mode 100644 src/chat/message_inbox.rs create mode 100644 src/chat/provider_turns/section_1.rs create mode 100644 src/chat/provider_turns/section_2.rs create mode 100644 src/chat/sessions/assignment/section_1.rs create mode 100644 src/chat/sessions/assignment/section_2.rs create mode 100644 src/chat/tests/p3_directional_switch_tests/section_1.rs create mode 100644 src/chat/tests/p3_directional_switch_tests/section_2.rs create mode 100644 src/chat/tests/p3_directional_switch_tests/section_3.rs create mode 100644 src/config/generation/section_1.rs create mode 100644 src/config/generation/section_2.rs create mode 100644 src/config/secret_paths/tests.rs create mode 100644 src/config/secret_paths/tests/section_1.rs create mode 100644 src/config/secret_paths/tests/section_2.rs create mode 100644 src/doctor/implementation/section_1.rs create mode 100644 src/doctor/implementation/section_2.rs create mode 100644 src/doctor/tests.rs create mode 100644 src/doctor/tests/section_1.rs create mode 100644 src/doctor/tests/section_2.rs create mode 100644 src/gateway/api/sessions/mailbox.rs create mode 100644 src/gateway/api/sessions/section_1.rs create mode 100644 src/gateway/api/sessions/section_2.rs create mode 100644 src/gateway/api/sessions/section_3.rs create mode 100644 src/gateway/api/sessions/tests/targeting/section_1.rs create mode 100644 src/gateway/api/sessions/tests/targeting/section_2.rs create mode 100644 src/gateway/implementation/section_1.rs create mode 100644 src/gateway/implementation/section_2.rs create mode 100644 src/gateway/implementation/section_3.rs create mode 100644 src/main/section_1.rs create mode 100644 src/main/section_2.rs create mode 100644 src/main/section_3.rs create mode 100644 src/memory/sqlite/events/section_1.rs create mode 100644 src/memory/sqlite/events/section_2.rs create mode 100644 src/memory/sqlite/events/section_3.rs create mode 100644 src/memory/sqlite/mailbox/local_runtime.rs create mode 100644 src/memory/sqlite/mailbox/retry.rs create mode 100644 src/memory/sqlite/tests/mailbox/section_1.rs create mode 100644 src/memory/sqlite/tests/mailbox/section_2.rs create mode 100644 src/memory/sqlite/tests/mailbox/section_3.rs create mode 100644 src/messaging/a2a/cli.rs create mode 100644 src/messaging/a2a/clients.rs create mode 100644 src/messaging/a2a/connections.rs create mode 100644 src/messaging/a2a/identity.rs create mode 100644 src/messaging/a2a/listener.rs create mode 100644 src/messaging/a2a/mod.rs create mode 100644 src/messaging/a2a/outbound.rs create mode 100644 src/messaging/a2a/peers.rs create mode 100644 src/messaging/a2a/resources.rs create mode 100644 src/messaging/a2a/tls.rs create mode 100644 src/messaging/receiver.rs create mode 100644 src/messaging/runtime.rs create mode 100644 src/messaging/worker.rs create mode 100644 src/session_worker/frame_auth.rs create mode 100644 src/tools/capability/catalog/section_1.rs create mode 100644 src/tools/capability/catalog/section_2.rs create mode 100644 src/tools/delegate/tests.rs create mode 100644 src/tools/delegate/tests/section_1.rs create mode 100644 src/tools/delegate/tests/section_2.rs delete mode 100644 src/tools/prx_message.rs diff --git a/Cargo.lock b/Cargo.lock index 97d2903ce..4f05e47d9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3205,6 +3205,8 @@ dependencies = [ "hmac 0.12.1", "hostname", "http-body-util", + "hyper", + "hyper-util", "jsonwebtoken", "lettre", "libc", diff --git a/Cargo.toml b/Cargo.toml index abfabee6e..10a7c881e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -176,6 +176,9 @@ futures = "0.3" regex = "1.10" unicode-normalization = "0.1" hostname = "0.4.2" +rcgen = { version = "0.14.8", default-features = false, features = ["ring", "pem"] } +hyper = { version = "1", features = ["server", "http1"] } +hyper-util = { version = "0.1.20", features = ["tokio"] } rustls = "0.23.46" rustls-pki-types = "1.14.0" # X.509 SVID parsing for SPIFFE peer verification (PEM/DER decode, SAN URI, @@ -282,7 +285,6 @@ criterion = { version = "0.7", features = ["html_reports"] } # PTY-driven end-to-end tests for `prx chat` (see tests/chat_pty_e2e.rs). expectrl = "0.7" proptest = "1.6" -rcgen = "0.14" # Serialize PTY tests that share controlling-tty resources, without forcing # `--test-threads=1` on the whole test binary. serial_test = "3" diff --git a/docs/configuration.md b/docs/configuration.md index 36f167998..e792fa1e2 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -136,7 +136,7 @@ and the module-gate family are absorbed on load; they are not live switches. | `[composio]` | `api_key` unset; `entity_id = "default"` | | `[mcp]` | `servers = {}`; `workspace_servers = "off"` (`http_only` or `stdio` to widen). A server: `transport = "stdio"`; `command`/`url` unset; `args = []`; `env = {}`; `startup_timeout_ms = 10000`; `request_timeout_ms = 30000`; `tool_name_prefix = "mcp"`; `allow_tools`/`deny_tools = []`; `working_dir` unset | | `[mcp_server]` | `bind = "127.0.0.1:16831"`; `require_auth = true`; `exposed_tools` the read-only set (`memory_search`, `memory_recall`, `memory_get`, `document_search`, `document_get_chunk`, `sessions_list`, `sessions_history`); `allowed_origins = ["claude.ai", "openai.com", "localhost"]`; `rate_limit_rps = 10`; JWT fields unset; `jwt_jwks_cache_ttl_secs = 300`; `jwt_algorithms = ["RS256"]` | -| `[a2a]` | `bind = "127.0.0.1:16832"`; `agent_id = "prx-default"`; `spiffe_id = "spiffe://prx-local/agent/prx-default"`; `discovery_advertised = false`; `allowed_peer_issuers = []`; `handoff_nonce_ttl_seconds = 3600`; `card_signing_key_path` unset; `card_ttl_seconds = 3600`; `card_jwks_uri` unset; `trusted_trust_domains = []`; `spiffe_trust_bundle_pem` unset; `spiffe_strict_validation = false`; `tls_cert_path`/`tls_key_path`/`client_ca_path` unset; `messaging_enabled = false`; `[a2a.remote_tree]` `max_spawned = 16`, `max_scheduled = 4`, `max_connections = 4`, `max_sends = 4`; `peers = {}`; `credentials = {}`. When `messaging_enabled` is true, a non-loopback bind is refused at load unless `tls_cert_path` and `tls_key_path` are set. With messaging disabled, the existing advertised bind remains accepted. TLS files are read at use. Messaging routes stay unregistered while `messaging_enabled` is false | +| `[a2a]` | Messaging is disabled by default (`messaging_enabled = false`). `bind = "127.0.0.1:16832"`, `trust_domain = "prx.local"`. Run `prx a2a init` before enabling messaging. The dedicated listener always requires pinned mutual TLS, including on loopback. `[a2a.peers.]` has `spiffe_id`, `fingerprints` (one or two full SHA-256 certificate fingerprints), `address` (`host:port`), `owner`, `sessions` and `agents` (default `["*"]`). Legacy discovery/card fields retain their existing behavior. | | `[auth]` | `codex_auth_json_auto_import = false`; `codex_auth_json_path` the platform Codex `auth.json` | | `[secrets]` | `encrypt = true` | | `[browser]` | `allowed_domains = []` (`web_fetch`); `computer_use.api_key` unset (retained for secret handling; browser automation tools are gone) | @@ -3468,3 +3468,46 @@ The rf gateway's approve-and-continue wait is `approval_wait_secs`: set it in seconds and accepts 1–86400. Waiting pauses that turn's idle detector; other turns retain their own idle windows. Console approval expiry remains four minutes. See [the rf live-frame and approval contract](rf-contract/capability-tokens.md#live-frames-and-run-approvals-b2). + +## Session messaging + +`[agent.messaging] inbound = true` controls Main. Each +`[agents..messaging] inbound = true` controls that agent. Both default to +true. Messages are user data; an approval-looking body grants no permission. +An idle receiver starts a turn at its own level and budget; a busy receiver +queues it. After eight automatic hops, delivery continues without starting a +turn. The chain bound stops loops between honest instances; peers can be revoked. + +For cross-machine messaging, initialize each instance, exchange its printed +SPIFFE ID and full certificate fingerprint, and add each side explicitly: + +```sh +prx a2a init +prx a2a peer add peer_a --spiffe spiffe://prx.local/prx/00000000-0000-4000-8000-000000000001 --fingerprint <64-lowercase-hex> --address example.com:16832 --owner +prx a2a peer list +prx a2a peer remove peer_a +``` + +Set `a2a.messaging_enabled = true` and the listener bind, then run the daemon or +gateway. Identity files live under the workspace's `a2a/`: directory mode 0700, +private files 0600. Wider permissions are refused. Unix mode enforcement does +not apply on Windows. Keys are separate from memory exports and backups. + +Use `prx a2a init --prepare-rotate` to stage a new certificate/key and print +its fingerprint while the current identity remains active. Add that fingerprint +on the other instance using the existing peer name, then run `prx a2a init +--rotate` to activate the staged identity atomically. It keeps the persisted +UUID and SPIFFE ID. Remove the old pin with `a2a peer remove +--fingerprint `. A peer accepts at most two fingerprints during +overlap. Removal and rotation close connections and cancel outstanding client +requests; TLS sessions are never resumed. Certificates expire after five years. +`a2a init` displays the local expiry; `a2a peer list` obtains each remote expiry +through authenticated TLS and reports when a peer is unreachable or refused. + +The outbox persists retries for up to 24 hours, below the seven-day replay +window. Authentication, authorization, malformed-chain and oversized-message +refusals are permanent. Network failures, 429 and server failures retry with +jitter and `Retry-After`. A receiver pin is refreshed before each attempt; +recipient incarnation changes fail rather than redirect old data. To roll back, +disable messaging and restart the gateway; retain the outbox and identity files. +There are no remote-tree permission caps. Queue/body storage bounds remain. diff --git a/docs/tools.md b/docs/tools.md index 349d345a9..1d10e2e6f 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -1964,3 +1964,25 @@ current turn. `/now` puts input first; `/steer` explicitly interrupts the current turn. Session commands operate on the focused child's context, model, history, usage, and task-mode approvals. `/level` displays the inherited level. Process-child approval calls remain denied with `no_resolver`. + +## Messages between sessions + +`sessions_send {"to":"parent","message":"public update"}` delivers ordinary +user input, while `{"run_id":"","message":"new direction"}` keeps +the existing explicit steering behavior. Targets include `main`, `parent`, +`#N`, a child run ID, a stable `spawn:` session key, or another session key of +the same owner. Structured `to` accepts `instance`, `owner`, `session`, `agent`; +absent instance/owner default to the admitted caller. For a paired remote +instance, specify its persisted UUID and receiving owner explicitly. + +In interactive chat, `/msg ` uses the focused child's identity +when attached. Incoming data appears as `[message from /]`. +Messages never approve tools, execute slash commands, or publish into an rf +chat. Local adoption is journaled with session provenance; peer adoption carries +its TLS SPIFFE identity. Erasing the local copy cannot erase a remote copy. +Process children continue in a new worker with public history seeded. Their +tool approvals remain denied with `no_resolver`; task/delegate approvals use +the owner's pending-approval surface. + +`session_status` includes the caller session's last 64 outbox states, including +`expired` and permanent refusals, without message bodies or recipient tokens. diff --git a/src/agent/agent/cleanup_diagnostic_tests.rs b/src/agent/agent/cleanup_diagnostic_tests.rs index 8b05df992..4412edc7d 100644 --- a/src/agent/agent/cleanup_diagnostic_tests.rs +++ b/src/agent/agent/cleanup_diagnostic_tests.rs @@ -122,6 +122,7 @@ async fn genuine_depth_denial_retains_parent_cleanup_ack_evidence() -> anyhow::R }, ); let depth_config = crate::config::DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), approval_wait_secs: 600, limits: crate::config::AgentLimits::default(), provider: "test".to_owned(), diff --git a/src/agent/tests.rs b/src/agent/tests.rs index 182ebe8de..2916037a0 100644 --- a/src/agent/tests.rs +++ b/src/agent/tests.rs @@ -571,6 +571,7 @@ async fn default_causal_embedded_turn_runs_delegate_child_and_confirms_cleanup() let agents = HashMap::from([( "worker".to_owned(), crate::config::DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), approval_wait_secs: 600, limits: crate::config::AgentLimits::default(), provider: child_provider, diff --git a/src/channels/startup.rs b/src/channels/startup.rs index ea67d039d..f15ddc573 100644 --- a/src/channels/startup.rs +++ b/src/channels/startup.rs @@ -532,6 +532,7 @@ pub async fn start_channels_with_config( // sessions_send: cross-session message injection (OpenClaw alignment) tools_list.push(Box::new( tools::SessionsSendTool::with_security(active_runs.clone(), security.clone()) + .with_messaging(&config) .with_shared_memory(Arc::clone(&mem)) .with_event_recording(config.memory.event_recording_config()), )); diff --git a/src/chat/action.rs b/src/chat/action.rs index fb3c28957..0039093c7 100644 --- a/src/chat/action.rs +++ b/src/chat/action.rs @@ -360,7 +360,7 @@ pub enum Action { /// `None` means "no turn-root context" (e.g. tests, or callers that do /// not originate a chat turn) — sub-agents then fall back to user origin, /// which is correct for non-turn paths such as the `/bg` slash command. - turn_spawn_ctx: Option, + turn_spawn_ctx: Option>, /// Per-turn default route for `message_send` tool calls. This mirrors /// `turn_spawn_ctx`: the real Redux driver runs in a spawned task, so /// the routing default must be carried through the reducer/effect diff --git a/src/chat/binding.rs b/src/chat/binding.rs index 3e2856b7b..51885a04d 100644 --- a/src/chat/binding.rs +++ b/src/chat/binding.rs @@ -376,6 +376,7 @@ impl Drop for ChatAdmissionGuard { /// Private fields keep mailbox content and decoded tool arguments from minting /// an operator command or replacing the model after verification. pub(super) struct ChatOperatorSpawn { + mailbox: Option, child: Option, command: String, binding: ChatProviderBinding, @@ -405,6 +406,7 @@ impl ChatOperatorSpawn { ); binding.verify(generation, provider, provider_name, model_name)?; Ok(Self { + mailbox: None, child: None, command: message.content.clone(), binding: ChatProviderBinding { @@ -433,7 +435,8 @@ impl ChatOperatorSpawn { ); binding.verify(&binding.generation, &binding.provider, &record.provider, &record.model)?; Ok(Self { - command: message.content.clone(), + mailbox: None, + command: format!("Continue child session {}", record.session_key), provider: record.provider.clone(), model: record.model.clone(), child: Some(record), @@ -442,6 +445,27 @@ impl ChatOperatorSpawn { }) } + pub(super) fn capture_message( + input: crate::messaging::runtime::MessageInput, + record: crate::memory::child_sessions::ChildSessionRecord, + binding: ChatProviderBinding, + ) -> anyhow::Result { + anyhow::ensure!( + input.auto_start() && input.message.to.session == record.session_key, + "mailbox wake target differs" + ); + binding.verify(&binding.generation, &binding.provider, &record.provider, &record.model)?; + Ok(Self { + command: format!("Continue child session {}", record.session_key), + task: input.text.clone(), + provider: record.provider.clone(), + model: record.model.clone(), + child: Some(record), + mailbox: Some(input), + binding, + }) + } + pub(super) async fn admit( self, memory: Arc, @@ -502,9 +526,18 @@ impl ChatOperatorSpawn { )?; let mut args = serde_json::json!({ "task": self.task, "provider": self.provider, "model": self.model }); if let Some(record) = self.child { - args["action"] = "continue".into(); - args["session_key"] = record.session_key.clone().into(); - source = source.for_continuation(record)?; + let object = args.as_object_mut().context("child arguments must be an object")?; + object.insert("action".into(), "continue".into()); + object.insert("session_key".into(), record.session_key.clone().into()); + object.insert("mode".into(), record.mode.clone().into()); + if record.agent != "main" { + object.insert("agent".into(), record.agent.clone().into()); + } + source = if let Some(input) = self.mailbox { + source.for_message(record, &input).await? + } else { + source.for_continuation(record)? + }; } if let Some(guard) = admission_guard { guard.handoff(); diff --git a/src/chat/chat_events.rs b/src/chat/chat_events.rs index a7e30da4c..a642cbe16 100644 --- a/src/chat/chat_events.rs +++ b/src/chat/chat_events.rs @@ -79,7 +79,7 @@ pub(super) fn chat_message_event_scope( /// Build the chat read envelope on the same stable durable-canonical /// `session_key` as the write scope (D4 C6), carrying the legacy `chat:{id}` key /// for read-merge so the read principal unions canonical + legacy history. -pub(super) fn chat_runtime_envelope(workspace_id: &str, chat_session_key: &str) -> RuntimeEnvelope { +pub(crate) fn chat_runtime_envelope(workspace_id: &str, chat_session_key: &str) -> RuntimeEnvelope { let chat_session_id = chat_session_id_from_key(chat_session_key); RuntimeEnvelope::chat_canonical(workspace_id.to_string(), chat_session_id, MemoryVisibility::Workspace) .with_recipient("terminal:user") diff --git a/src/chat/child_focus.rs b/src/chat/child_focus.rs index f38ba479b..e6855682d 100644 --- a/src/chat/child_focus.rs +++ b/src/chat/child_focus.rs @@ -9,7 +9,10 @@ use std::{collections::VecDeque, sync::Arc}; #[derive(Default)] pub(super) struct ChildFocus { + parent: Option, + message_queue: VecDeque<(String, crate::messaging::runtime::MessageInput)>, queue: VecDeque<(String, ChannelMessage)>, + mailboxes: std::collections::HashMap, } pub(super) struct ChildFocusContext<'a> { @@ -24,6 +27,25 @@ pub(super) struct ChildFocusContext<'a> { } impl ChildFocusContext<'_> { + async fn start_message( + &self, + record: ChildSessionRecord, + input: crate::messaging::runtime::MessageInput, + ) -> anyhow::Result { + let provider = self.provider(&record)?; + let binding = ChatProviderBinding::capture(self.generation, &provider, &record.provider, &record.model)? + .context("child provider missing")?; + let command = ChatOperatorSpawn::capture_message(input, record, binding)?; + let (args, source) = command + .admit( + Arc::clone(self.memory), + self.parent, + Arc::clone(self.security), + Arc::clone(self.service), + ) + .await?; + self.execute_source(source, args).await + } pub(super) async fn view( &self, target: &str, @@ -86,7 +108,7 @@ impl ChildFocusContext<'_> { topic_id: None, source_message_event_id: None, started_at: record.created_at, - finished_at: record.ended_at.or(Some(chrono::Utc::now())), + finished_at: record.ended_at.or_else(|| Some(chrono::Utc::now())), status: SubAgentStatus::Completed(output), recipient: None, channel_name: Some("terminal".into()), @@ -167,13 +189,22 @@ impl ChildFocusContext<'_> { Arc::clone(self.service), ) .await?; - args[crate::security::policy::RUNTIME_APPROVAL_GRANT_ARG] = - serde_json::to_value(crate::security::policy::ApprovalGrant::for_resource_operation( - "sessions_spawn", - "sessions_spawn:spawn", - "chat-operator", - None, - ))?; + let grant = serde_json::to_value(crate::security::policy::ApprovalGrant::for_resource_operation( + "sessions_spawn", + "sessions_spawn:spawn", + "chat-operator", + None, + ))?; + args.as_object_mut() + .context("child arguments must be an object")? + .insert(crate::security::policy::RUNTIME_APPROVAL_GRANT_ARG.into(), grant); + self.execute_source(source, args).await + } + async fn execute_source( + &self, + source: crate::runtime::operator_spawn::OperatorSpawnSource, + args: serde_json::Value, + ) -> anyhow::Result { let tool = self .tools .iter() @@ -295,9 +326,8 @@ impl ChildFocus { let provider = ctx.provider(&record)?; let mut history: Vec<_> = turns .iter() - .map(|turn| crate::providers::ChatMessage { - role: turn.role.clone(), - content: turn.content.clone(), + .map(|turn| { + crate::agent::turn_contracts::stored_turn_message(turn.role.clone(), turn.content.clone()) }) .collect(); let source = crate::agent::turn_history::CanonicalHistory::from_acknowledged( @@ -399,6 +429,78 @@ impl ChildFocus { pub(super) async fn pump(&mut self, ctx: &ChildFocusContext<'_>) -> Vec { let mut outputs = Vec::new(); + if self.parent.as_deref() != Some(ctx.parent) { + self.queue.clear(); + self.message_queue.clear(); + self.mailboxes.clear(); + self.parent = Some(ctx.parent.into()); + } + if ctx.generation.effective.memory.backend == "sqlite" { + let messages = async { + let runtime = crate::messaging::runtime::MessagingRuntime::for_config(&ctx.generation.effective)?; + self.message_queue.retain(|(_, input)| input.verify(&runtime).is_ok()); + let workspace = ctx.generation.effective.workspace_dir.to_string_lossy(); + let owner = super::chat_runtime_envelope(&workspace, ctx.parent).resolved_owner_id(); + let store = ctx.memory.child_session_store().context("child storage unavailable")?; + for record in store + .sessions(&workspace, &owner)? + .into_iter() + .filter(|record| record.parent_session == ctx.parent) + { + if ctx.busy(&record).await { + continue; + } + if !self.mailboxes.contains_key(&record.session_key) { + let inbox = runtime.register(runtime.address(&owner, &record.session_key, &record.agent))?; + self.mailboxes.insert(record.session_key.clone(), inbox); + } + let inputs = self + .mailboxes + .get_mut(&record.session_key) + .context("child inbox disappeared")? + .poll()?; + for input in inputs { + if input.auto_start() { + self.message_queue.push_back((record.session_key.clone(), input)); + } else { + outputs.push(format!( + "Message recorded for {} (automatic reply chain stopped).", + record.session_key + )); + } + } + } + Ok::<(), anyhow::Error>(()) + } + .await; + if let Err(error) = messages { + outputs.push(error.to_string()); + } + } + let mut message_index = 0; + while message_index < self.message_queue.len() { + let Some((target, _)) = self.message_queue.get(message_index) else { + break; + }; + let record = match ctx.record(target) { + Ok(record) => record, + Err(error) => { + self.message_queue.remove(message_index); + outputs.push(error.to_string()); + continue; + } + }; + if ctx.busy(&record).await { + message_index += 1; + continue; + } + if let Some((_, input)) = self.message_queue.remove(message_index) { + outputs.push(match ctx.start_message(record, input).await { + Ok(output) => output, + Err(error) => error.to_string(), + }); + } + } let mut index = 0; while index < self.queue.len() { let Some((target, _)) = self.queue.get(index) else { diff --git a/src/chat/commands.rs b/src/chat/commands.rs index e3e4bf7ba..198b3a3d6 100644 --- a/src/chat/commands.rs +++ b/src/chat/commands.rs @@ -196,6 +196,13 @@ const DAEMON_SCOPE_CANDIDATES: &[CommandArgCandidate] = &[CommandArgCandidate { /// Single source of truth for user-visible chat slash commands. pub const COMMAND_SPECS: &[CommandSpec] = &[ + CommandSpec { + name: "/msg", + aliases: &[], + args_hint: " ", + description: "Message a session; /msg uses the same durable mailbox as sessions_send. Remote copies cannot be erased here.", + arg: NO_ARG, + }, CommandSpec { name: "/help", aliases: &[], diff --git a/src/chat/commands/msg.rs b/src/chat/commands/msg.rs index 13a12589d..91c49c7f3 100644 --- a/src/chat/commands/msg.rs +++ b/src/chat/commands/msg.rs @@ -1,4 +1,4 @@ -//! Dormant /msg parser. Deliberately absent from command dispatch/help. +//! Explicit local-operator messaging command: /msg . use crate::messaging::{ SessionAddr, mailbox::{MailboxError, MailboxResult}, @@ -12,21 +12,13 @@ pub fn parse(input: &str, caller: &SessionAddr) -> MailboxResult<(SessionAddr, S .strip_prefix("/msg ") .ok_or(MailboxError::InvalidMetadata)? .trim_start(); - let (peer, rest) = rest - .split_once(char::is_whitespace) - .ok_or(MailboxError::InvalidMetadata)?; let (session, text) = rest - .trim_start() .split_once(char::is_whitespace) .ok_or(MailboxError::InvalidMetadata)?; if text.trim().is_empty() { return Err(MailboxError::InvalidMetadata); } - let (session, agent) = session.split_once('/').unwrap_or((session, "main")); - let target = parse_target( - &json!({"instance":if peer=="local" {&caller.instance} else {peer},"session":session,"agent":agent}), - caller, - )?; + let target = parse_target(&json!({"session":session}), caller)?; Ok((target, text.trim_start().to_owned())) } pub async fn send( diff --git a/src/chat/message_inbox.rs b/src/chat/message_inbox.rs new file mode 100644 index 000000000..6a905c884 --- /dev/null +++ b/src/chat/message_inbox.rs @@ -0,0 +1,139 @@ +//! The main chat consumes mailbox data as model input, never as an operator command. +use crate::channels::traits::ChannelMessage; +use crate::messaging::runtime::{MessageInput, MessagingRuntime, SessionInbox}; +use std::sync::Arc; + +pub(super) struct ChatInbox { + pub(super) runtime: Arc, + inbox: SessionInbox, + session: String, + wake: bool, + pending: std::collections::HashMap, +} +impl ChatInbox { + pub(super) fn open(config: &crate::config::Config, session: &str) -> anyhow::Result> { + if config.memory.backend != "sqlite" { + return Ok(None); + } + let runtime = MessagingRuntime::for_config(config)?; + let owner = super::chat_runtime_envelope(&config.workspace_dir.to_string_lossy(), session).resolved_owner_id(); + let inbox = runtime.register(runtime.address(&owner, session, "main"))?; + Ok(Some(Self { + runtime, + inbox, + session: session.into(), + wake: true, + pending: Default::default(), + })) + } + pub(super) const fn wake(&mut self) { + self.wake = true; + } + pub(super) fn poll(&mut self) -> anyhow::Result> { + if !std::mem::take(&mut self.wake) && !self.inbox.take_notification() { + return Ok(Vec::new()); + } + let inputs = self.inbox.poll()?; + for input in &inputs { + if input.auto_start() + && let Some(event) = input.receipt.adopted_message_event_id + { + self.pending.insert(event.to_string(), input.clone()); + } + } + Ok(inputs) + } + pub(super) fn fenced(&self) -> bool { + !self.inbox.live() + } + pub(super) fn drain(&mut self) { + self.pending.clear(); + } + pub(super) fn take_input(&mut self, message: &ChannelMessage) -> anyhow::Result> { + let Some(event) = cause(message) else { + return Ok(None); + }; + let input = self + .pending + .remove(event) + .ok_or_else(|| anyhow::anyhow!("mailbox input is no longer queued"))?; + input.verify(&self.runtime)?; + anyhow::ensure!(input.text == message.content, "mailbox input content differs"); + Ok(Some(input)) + } + pub(super) fn session(&self) -> &str { + &self.session + } +} + +pub(super) fn channel_input(input: &MessageInput) -> anyhow::Result { + let event = input + .receipt + .adopted_message_event_id + .ok_or_else(|| anyhow::anyhow!("adopted message event missing"))?; + Ok(ChannelMessage { + id: format!("mailbox:{event}"), + sender: "session-message".into(), + sender_is_bot: true, + content: input.text.clone(), + channel: "terminal".into(), + reply_target: input.message.to.session.clone(), + timestamp: u64::try_from(chrono::Utc::now().timestamp())?, + ..ChannelMessage::default() + }) +} + +pub(super) fn cause(message: &ChannelMessage) -> Option<&str> { + (message.sender == "session-message" && message.sender_is_bot) + .then(|| message.id.strip_prefix("mailbox:")) + .flatten() +} + +pub(super) async fn send_command( + config: &crate::config::Config, + parent: &str, + focused: Option<&str>, + message: &ChannelMessage, + sessions: &mut super::sessions::ChatSessionsHandle, +) -> anyhow::Result { + use crate::messaging::send::MailboxSender; + anyhow::ensure!( + super::is_local_operator_input(message) && !message.sender_is_bot, + "/msg requires local operator input" + ); + let runtime = MessagingRuntime::for_config(config)?; + let owner = super::chat_runtime_envelope(&config.workspace_dir.to_string_lossy(), parent).resolved_owner_id(); + let source_session = if let Some(focused) = focused { + sessions + .child_run(focused) + .await + .map(|run| run.session_scope_key) + .unwrap_or_else(|| parent.into()) + } else { + parent.into() + }; + let mut source = runtime.address(&owner, &source_session, "main"); + if let Some(agent) = runtime + .store + .logical_agent(&runtime.workspace, &owner, &source_session)? + { + source.agent = agent; + } + let (target, text) = super::commands::msg::parse(&message.content, &source)?; + let mut target = serde_json::Value::String(target.session); + if let Some(seq) = target + .as_str() + .and_then(|target| target.strip_prefix('#')) + .and_then(|seq| seq.parse::().ok()) + { + let run = sessions.resolve_run_id(seq).await?; + let run = sessions + .child_run(&run) + .await + .ok_or_else(|| anyhow::anyhow!("message target is not a child session"))?; + target = run.session_scope_key.into(); + } + let target = runtime.alias(&source, &target)?; + let sender = runtime.bind(source, None)?; + Ok(crate::messaging::send::send_result(sender.send(target, text, "text/plain".into()).await).to_string()) +} diff --git a/src/chat/mod.rs b/src/chat/mod.rs index 3d7898bee..06fd6a3c9 100644 --- a/src/chat/mod.rs +++ b/src/chat/mod.rs @@ -90,6 +90,7 @@ mod external_editor; mod file_mention; mod input_queue; mod line_approval; +mod message_inbox; mod model_commands; mod output; mod plain_queue; @@ -110,7 +111,8 @@ mod tests; #[cfg(test)] pub(crate) use self::bootstrap::chat_provider_chain; -use self::chat_events::{chat_runtime_envelope, chat_session_id_from_key}; +pub(crate) use self::chat_events::chat_runtime_envelope; +use self::chat_events::chat_session_id_from_key; #[cfg(test)] use self::chat_events::{ finalize_chat_non_success_turn, finalize_chat_success_turn, record_chat_user_message_event_in_generation, diff --git a/src/chat/provider_turns.rs b/src/chat/provider_turns.rs index d22e8d2c0..fa6ba9970 100644 --- a/src/chat/provider_turns.rs +++ b/src/chat/provider_turns.rs @@ -1,2339 +1,4 @@ //! Provider-turn lifecycle: completion events, ordered commit and finalization of per-turn contexts. -use super::active_turn::rollback_cancelled_turn_history; -#[cfg(feature = "terminal-tui")] -use super::binding; -#[cfg(feature = "terminal-tui")] -use super::chat_events::{finalize_chat_non_success_turn, finalize_chat_success_turn}; -use super::dispatcher; -#[cfg(feature = "terminal-tui")] -use super::input_queue::publish_main_queue_status; -#[cfg(feature = "terminal-tui")] -use super::session_glue::{surface_session_message, surface_turn_elapsed_message}; -#[cfg(feature = "terminal-tui")] -use crate::agent::turn_contracts::ToolCallNotification; -#[cfg(feature = "terminal-tui")] -use crate::channels::Channel; -#[cfg(feature = "terminal-tui")] -use crate::channels::TerminalChannel; -#[cfg(feature = "terminal-tui")] -use crate::channels::sanitize_channel_response; -#[cfg(feature = "terminal-tui")] -use crate::config::Config; -#[cfg(feature = "terminal-tui")] -use crate::llm::route_decision::ProviderExecutionOutcome; -#[cfg(feature = "terminal-tui")] -use crate::llm::route_decision::RouteDecision; -#[cfg(feature = "terminal-tui")] -use crate::memory::MemoryFabric; -#[cfg(feature = "terminal-tui")] -use crate::memory::MessageEventScope; -#[cfg(feature = "terminal-tui")] -use crate::providers::ChatMessage; -#[cfg(feature = "terminal-tui")] -use crate::tools::Tool; -#[cfg(feature = "terminal-tui")] -use std::sync::Arc; -#[cfg(feature = "terminal-tui")] -use std::time::Duration; -use tokio::sync::mpsc; -#[cfg(feature = "terminal-tui")] -use tokio_util::sync::CancellationToken; - -/// Queue depth for provider-turn lifecycle events (`HandleAttached`, `Started`, -/// `Exited`) travelling from the effect executor back to the chat loop. -/// -/// Sized as a backpressure valve, not a concurrency limit. Each turn emits -/// exactly three of these small, `Copy`-sized records, so this depth absorbs -/// roughly 1300 turns' worth of lifecycle traffic — far more than the chat loop -/// can fall behind by in practice, since it drains the queue at several points -/// in every iteration. If it ever does fill, the emitting turn parks on -/// `send().await` instead of the queue growing without bound; slowing turn -/// startup is the correct outcome, because the worker registry driving aborts -/// and completion routing must not fall arbitrarily far behind reality. -pub(crate) const PROVIDER_TURN_LIFECYCLE_CHANNEL_CAPACITY: usize = 4096; - -#[derive(Debug, Clone)] -pub(super) struct ProviderTurnCompletionEvent { - pub(super) task_id: crate::chat::turn_scheduler::TurnTaskId, - // Only the TUI completion waiter fills these and only the TUI finalizer - // reads them. - #[cfg(feature = "terminal-tui")] - pub(super) outcome: Option, - #[cfg(feature = "terminal-tui")] - pub(super) usage: crate::llm::route_decision::TokenUsage, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(super) struct ProviderTurnCompletionContext { - history_len_before_assistant: usize, -} - -#[cfg(feature = "terminal-tui")] -pub(super) struct PerTurnContext { - pub(super) turn_binding: Option>, - pub(super) task_id: crate::chat::turn_scheduler::TurnTaskId, - pub(super) draft_id: String, - pub(super) delta_tx: Option>, - pub(super) tool_event_tx: Option>, - pub(super) draft_updater: Option>, - pub(super) tool_event_forwarder: Option>, - pub(super) user_input: String, - pub(super) turn_run_id: String, - pub(super) route_scope: MessageEventScope, - pub(super) route_decision: RouteDecision, - pub(super) provider_started_at: chrono::DateTime, - pub(super) provider_name: String, - pub(super) model_name: String, - pub(super) history_len_before_user_turn: usize, - /// The reducer's compaction epoch when the turn's provider view was - /// copied. A newer acknowledged epoch at commit means a worker compaction - /// ran during the turn, and the run loop's view is rebuilt from the - /// committed snapshot instead of being appended to. - pub(super) compaction_epoch_at_start: u64, - /// Set when this turn was started by daemon-assigned work, and carried all - /// the way to the commit because that is where the reply exists. - /// - /// A visible turn is *launched* by the main loop and finalized somewhere - /// else entirely, so a guard left behind in the loop body would report the - /// moment the turn started — an answer of "no reply" to work that was about - /// to produce one. Moving it into the context ties the report to the turn - /// rather than to the iteration that started it. - pub(super) assignment: Option, -} - -#[cfg(feature = "terminal-tui")] -pub(super) struct PendingOrderedProviderTurnCommit { - pub(super) context: PerTurnContext, - pub(super) terminal_plan: ProviderTurnTerminalPlan, -} - -#[derive(Debug)] -#[cfg(feature = "terminal-tui")] -pub(super) struct ResolvedProviderTurnCompletion { - pub(super) outcome: Option, - pub(super) usage: crate::llm::route_decision::TokenUsage, -} - -#[derive(Debug, Clone)] -#[cfg(feature = "terminal-tui")] -pub(super) enum ProviderTurnTerminalPlan { - Completed { - final_text: String, - reasoning: String, - recorded_response: String, - empty_response: bool, - usage: crate::llm::route_decision::TokenUsage, - history_commit_len: usize, - final_text_chars: usize, - recorded_response_chars: usize, - summary: &'static str, - }, - Failed { - err: String, - history_commit_len: usize, - summary: String, - }, - Cancelled { - summary: &'static str, - }, -} - -#[cfg(feature = "terminal-tui")] -#[derive(Debug, Clone)] -pub(super) struct ProviderTurnFinalizerEvent { - pub(super) task_id: Option, - pub(super) plan: ProviderTurnTerminalPlan, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[cfg(feature = "terminal-tui")] -pub(super) struct ProviderTurnFinalizerResult { - pub(super) task_id: Option, - pub(super) terminal_status: &'static str, - pub(super) finalized: bool, -} - -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub(super) struct ProviderTurnVisibleAdmission { - pub(super) active_workers: usize, - pub(super) foreground_active: usize, - pub(super) detached_active: usize, - pub(super) effective_max_visible_turns: usize, - pub(super) can_start_visible: bool, -} - -#[cfg(feature = "terminal-tui")] -pub(super) enum ProviderTurnTerminalGate<'a> { - Completed { - history_commit_len: usize, - final_text_chars: usize, - recorded_response_chars: usize, - usage: &'a crate::llm::route_decision::TokenUsage, - summary: &'static str, - }, - Failed { - history_commit_len: usize, - summary: String, - }, - Cancelled { - summary: &'static str, - }, -} - -pub(super) fn provider_worker_status( - workers: &crate::chat::turn_worker::ProviderTurnWorkerRegistry, -) -> crate::chat::action::ProviderWorkerStatus { - use crate::chat::action::{ProviderWorkerRowKind, ProviderWorkerRowState, ProviderWorkerStatusRow}; - - let mut status = crate::chat::action::ProviderWorkerStatus::default(); - for worker in workers.snapshot() { - if worker.finalized_payload_ready { - status.finalized_payloads = status.finalized_payloads.saturating_add(1); - status.finalized_total_tokens = status - .finalized_total_tokens - .saturating_add(worker.finalized_total_tokens.unwrap_or_default()); - } - let row_state = match worker.state { - crate::chat::turn_worker::ProviderTurnWorkerState::Running => ProviderWorkerRowState::Running, - crate::chat::turn_worker::ProviderTurnWorkerState::Cancelling => ProviderWorkerRowState::Cancelling, - crate::chat::turn_worker::ProviderTurnWorkerState::AwaitingCommit(_) => { - ProviderWorkerRowState::AwaitingCommit - } - crate::chat::turn_worker::ProviderTurnWorkerState::Committed => ProviderWorkerRowState::Committed, - crate::chat::turn_worker::ProviderTurnWorkerState::Cancelled => ProviderWorkerRowState::Cancelled, - crate::chat::turn_worker::ProviderTurnWorkerState::Failed => ProviderWorkerRowState::Failed, - }; - if !worker.state.is_terminal() || worker.finalized_payload_ready { - let row_kind = match worker.kind { - crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited => { - ProviderWorkerRowKind::ForegroundAwaited - } - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached => ProviderWorkerRowKind::Detached, - }; - status.rows.push(ProviderWorkerStatusRow { - task_id: worker.task_id.get(), - sequence: worker.sequence, - kind: row_kind, - state: row_state, - started_at_ms: worker.started_at_ms, - finalized_total_tokens: worker.finalized_total_tokens, - completion_ready: worker.completion_ready, - recent_tool_call: None, - }); - } - match worker.state { - crate::chat::turn_worker::ProviderTurnWorkerState::Running => { - status.running = status.running.saturating_add(1); - status.oldest_started_at_ms = Some( - status - .oldest_started_at_ms - .map_or(worker.started_at_ms, |current| current.min(worker.started_at_ms)), - ); - } - crate::chat::turn_worker::ProviderTurnWorkerState::Cancelling => { - status.cancelling = status.cancelling.saturating_add(1); - status.oldest_started_at_ms = Some( - status - .oldest_started_at_ms - .map_or(worker.started_at_ms, |current| current.min(worker.started_at_ms)), - ); - } - crate::chat::turn_worker::ProviderTurnWorkerState::AwaitingCommit(_) => { - status.awaiting_commit = status.awaiting_commit.saturating_add(1); - } - crate::chat::turn_worker::ProviderTurnWorkerState::Committed - | crate::chat::turn_worker::ProviderTurnWorkerState::Cancelled - | crate::chat::turn_worker::ProviderTurnWorkerState::Failed => {} - } - } - status -} - -pub(super) fn publish_provider_worker_status( - chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, - workers: &crate::chat::turn_worker::ProviderTurnWorkerRegistry, -) { - let _ = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::ProviderWorkerStatusUpdated { - status: provider_worker_status(workers), - }, - "chat.provider_worker_status_updated", - ); -} - -pub(super) fn provider_turn_visible_admission( - workers: &crate::chat::turn_worker::ProviderTurnWorkerRegistry, - target_kind: crate::chat::turn_worker::ProviderTurnWorkerKind, - max_concurrent_visible_turns: usize, -) -> ProviderTurnVisibleAdmission { - let effective_max_visible_turns = max_concurrent_visible_turns.max(1); - let active_rows: Vec<_> = workers - .snapshot() - .into_iter() - .filter(|worker| { - matches!( - worker.state, - crate::chat::turn_worker::ProviderTurnWorkerState::Running - | crate::chat::turn_worker::ProviderTurnWorkerState::Cancelling - | crate::chat::turn_worker::ProviderTurnWorkerState::AwaitingCommit(_) - ) - }) - .collect(); - let active_workers = active_rows.len(); - let foreground_active = active_rows - .iter() - .filter(|worker| worker.kind == crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited) - .count(); - let detached_active = active_rows - .iter() - .filter(|worker| worker.kind == crate::chat::turn_worker::ProviderTurnWorkerKind::Detached) - .count(); - let can_start_visible = match target_kind { - crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited => active_workers == 0, - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached => { - foreground_active == 0 && detached_active < effective_max_visible_turns - } - }; - ProviderTurnVisibleAdmission { - active_workers, - foreground_active, - detached_active, - effective_max_visible_turns, - can_start_visible, - } -} - -fn drain_provider_turn_lifecycle_events( - rx: &mut mpsc::Receiver, - events_open: &mut bool, - workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, -) -> bool { - if !*events_open { - return false; - } - - let mut drained = false; - loop { - match rx.try_recv() { - Ok(event) => { - drained = true; - record_provider_turn_lifecycle_event(workers, event); - } - Err(mpsc::error::TryRecvError::Empty) => return drained, - Err(mpsc::error::TryRecvError::Disconnected) => { - *events_open = false; - return drained; - } - } - } -} - -pub(super) fn record_provider_turn_lifecycle_event( - workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, - event: dispatcher::ProviderTurnLifecycleEvent, -) { - use crate::chat::turn_worker::ProviderTurnWorkerError; - let (task_id, lease_id, kind, result): ( - crate::chat::turn_scheduler::TurnTaskId, - u64, - &'static str, - Result<(), ProviderTurnWorkerError>, - ) = match event { - dispatcher::ProviderTurnLifecycleEvent::HandleAttached { - task_id, - lease_id, - abort_handle, - } => { - let result = workers.attach_execution_handle(task_id, lease_id, abort_handle); - (task_id, lease_id, "handle_attached", result) - } - dispatcher::ProviderTurnLifecycleEvent::Started { task_id, lease_id } => { - let result = workers.record_execution_started(task_id, lease_id); - (task_id, lease_id, "started", result) - } - dispatcher::ProviderTurnLifecycleEvent::FailureRequested { - task_id, - lease_id, - accepted, - } => { - let result = workers.record_execution_failed(task_id, lease_id); - if accepted.send(result.is_ok()).is_err() { - tracing::debug!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), - lease_id, - "provider worker supervisor left before the failure answer" - ); - } - if let Err(error) = result { - // Expected when the turn already produced its terminal: the - // failure gate refuses and the turn keeps its outcome. - tracing::debug!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), - lease_id, - error = %crate::agent::diagnostics::error_class(&error), - "provider worker failure refused" - ); - } - return; - } - dispatcher::ProviderTurnLifecycleEvent::Exited { task_id, lease_id } => { - let result = workers.record_execution_exited(task_id, lease_id); - if let Err(ProviderTurnWorkerError::UnknownWorker(_)) = result { - tracing::debug!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), - lease_id, - "provider worker exit for a retired task" - ); - return; - } - (task_id, lease_id, "exited", result) - } - }; - if let Err(error) = result { - tracing::warn!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), - lease_id, - kind, - error = %crate::agent::diagnostics::error_class(&error), - "ProviderTurnWorkerRegistry provider execution lifecycle record failed" - ); - } -} - -fn record_provider_turn_completion_ready( - workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, - task_id: crate::chat::turn_scheduler::TurnTaskId, -) { - if let Err(error) = workers.record_completion_ready(task_id) { - tracing::warn!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), - error = %crate::agent::diagnostics::error_class(&error), - "ProviderTurnWorkerRegistry provider completion-ready gate failed" - ); - } -} - -pub(super) fn route_provider_completion_event( - lifecycle_rx: &mut mpsc::Receiver, - lifecycle_events_open: &mut bool, - workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, - pending: &mut std::collections::HashMap, - current_task_id: Option, - completion: ProviderTurnCompletionEvent, -) -> Option { - if drain_provider_turn_lifecycle_events(lifecycle_rx, lifecycle_events_open, workers) { - tracing::trace!( - task_id = completion.task_id.get(), - "drained provider lifecycle events before routing completion" - ); - } - let task_id = completion.task_id; - record_provider_turn_completion_ready(workers, task_id); - if Some(task_id) == current_task_id { - return Some(completion); - } - if pending.insert(task_id, completion).is_some() { - tracing::warn!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), - "replaced duplicate pending provider completion event" - ); - } - None -} - -pub(super) fn route_provider_completion_event_and_publish( - lifecycle_rx: &mut mpsc::Receiver, - lifecycle_events_open: &mut bool, - workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, - pending: &mut std::collections::HashMap, - current_task_id: Option, - completion: ProviderTurnCompletionEvent, - chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, -) -> Option { - let route = route_provider_completion_event( - lifecycle_rx, - lifecycle_events_open, - workers, - pending, - current_task_id, - completion, - ); - publish_provider_worker_status(chat_dispatcher, workers); - route -} - -pub(super) fn record_provider_turn_completion_context( - contexts: &mut std::collections::HashMap, - task_id: Option, - history_len_before_assistant: usize, -) { - if let Some(task_id) = task_id - && contexts - .insert( - task_id, - ProviderTurnCompletionContext { - history_len_before_assistant, - }, - ) - .is_some() - { - tracing::warn!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), - "replaced duplicate provider turn completion context" - ); - } -} - -#[cfg(feature = "terminal-tui")] -pub(super) fn take_provider_turn_completion_history_len( - contexts: &mut std::collections::HashMap, - task_id: Option, - fallback_history_len: usize, -) -> usize { - task_id - .and_then(|task_id| contexts.remove(&task_id)) - .map_or(fallback_history_len, |context| context.history_len_before_assistant) -} - -#[cfg(feature = "terminal-tui")] -fn provider_turn_finalized_payload_from_usage( - history_commit_len: usize, - final_text_chars: usize, - recorded_response_chars: usize, - usage: &crate::llm::route_decision::TokenUsage, -) -> crate::chat::turn_worker::ProviderTurnFinalizedPayload { - let prompt_tokens = usage.prompt_tokens.map_or(0, u64::from); - let completion_tokens = usage.completion_tokens.map_or(0, u64::from); - let total_tokens = usage - .total_tokens - .map_or_else(|| prompt_tokens.saturating_add(completion_tokens), u64::from); - crate::chat::turn_worker::ProviderTurnFinalizedPayload { - history_commit_len, - final_text_chars, - recorded_response_chars, - total_tokens, - prompt_tokens, - completion_tokens, - } -} - -#[cfg(feature = "terminal-tui")] -fn record_provider_turn_finalized_payload( - workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, - id: Option, - payload: crate::chat::turn_worker::ProviderTurnFinalizedPayload, -) -> bool { - let Some(id) = id else { - tracing::warn!("ProviderTurnWorkerRegistry missing provider task for finalized payload"); - return false; - }; - if let Err(error) = workers.record_finalized_payload(id, payload) { - tracing::warn!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), - error = %crate::agent::diagnostics::error_class(&error), - "ProviderTurnWorkerRegistry provider finalized payload record failed" - ); - return false; - } - true -} - -#[cfg(feature = "terminal-tui")] -pub(super) fn gate_completed_provider_turn_finalization( - scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, - coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, - workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, - id: Option, - history_commit_len: usize, - final_text_chars: usize, - recorded_response_chars: usize, - usage: &crate::llm::route_decision::TokenUsage, - summary: &'static str, -) -> Vec { - let finalized_payload = provider_turn_finalized_payload_from_usage( - history_commit_len, - final_text_chars, - recorded_response_chars, - usage, - ); - if !record_provider_turn_finalized_payload(workers, id, finalized_payload) { - return Vec::new(); - } - mark_provider_turn_completed(scheduler, coordinator, workers, id, history_commit_len, summary) -} - -/// Finalized payload of a turn the non-TUI tool loop completed inline. -pub(super) fn inline_provider_turn_payload( - history_commit_len: usize, - response_chars: usize, - usage: Option<&crate::chat::session::MainSessionTokenUsageRecord>, -) -> crate::chat::turn_worker::ProviderTurnFinalizedPayload { - crate::chat::turn_worker::ProviderTurnFinalizedPayload { - history_commit_len, - final_text_chars: response_chars, - recorded_response_chars: response_chars, - total_tokens: usage.map_or(0, |usage| usage.total_tokens), - prompt_tokens: usage.map_or(0, |usage| usage.prompt_tokens), - completion_tokens: usage.map_or(0, |usage| usage.completion_tokens), - } -} - -/// The non-TUI tool loop awaited provider turn `id` inline and reached its -/// terminal. Records the inline execution as complete and, for a completed -/// turn, its finalized payload, so the terminal mark that follows commits the -/// worker and frees the visible-turn slot (without it the worker stays -/// `Running` and every later input, `/exit` included, waits for a slot). -pub(super) fn finish_inline_provider_turn( - workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, - id: Option, - payload: Option, -) { - let Some(id) = id else { - return; - }; - if let Err(error) = workers.record_inline_completion_ready(id) { - tracing::warn!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), - error = %crate::agent::diagnostics::error_class(&error), - "ProviderTurnWorkerRegistry inline provider completion failed" - ); - return; - } - if let Some(payload) = payload - && let Err(error) = workers.record_finalized_payload(id, payload) - { - tracing::warn!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), - error = %crate::agent::diagnostics::error_class(&error), - "ProviderTurnWorkerRegistry inline provider finalized payload record failed" - ); - } -} - -pub(super) fn gate_failed_provider_turn_finalization( - scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, - coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, - workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, - id: Option, - history_commit_len: usize, - summary: impl Into, -) -> Vec { - mark_provider_turn_failed(scheduler, coordinator, workers, id, history_commit_len, summary) -} - -pub(super) fn gate_cancelled_provider_turn_finalization( - scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, - coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, - workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, - id: Option, - summary: &'static str, -) -> Vec { - mark_provider_turn_cancelled(scheduler, coordinator, workers, id, summary) -} - -#[allow(clippy::option_if_let_else)] -#[cfg(feature = "terminal-tui")] -pub(super) fn resolve_provider_turn_completion( - turn_signal: &dispatcher::TurnCompletionSignal, - task_id: Option, - completion_event: Option, -) -> ResolvedProviderTurnCompletion { - let outcome = if let Some(completion) = completion_event.as_ref() { - completion.outcome.clone().or_else(|| turn_signal.consume_outcome()) - } else if let Some(id) = task_id { - turn_signal - .consume_turn_outcome(id) - .or_else(|| turn_signal.consume_outcome()) - } else { - turn_signal.consume_outcome() - }; - let usage = if let Some(completion) = completion_event { - if completion.usage.has_any_tokens() { - completion.usage - } else { - turn_signal.consume_usage() - } - } else if let Some(id) = task_id { - let keyed_usage = turn_signal.consume_turn_usage(id); - if keyed_usage.has_any_tokens() { - keyed_usage - } else { - turn_signal.consume_usage() - } - } else { - turn_signal.consume_usage() - }; - if let Some(id) = task_id { - turn_signal.unregister_turn(id); - } - ResolvedProviderTurnCompletion { outcome, usage } -} - -#[cfg(feature = "terminal-tui")] -pub(super) fn provider_turn_terminal_plan_from_completion( - resolved: ResolvedProviderTurnCompletion, - history_len: usize, - tools_registry: &[Box], -) -> ProviderTurnTerminalPlan { - match resolved.outcome { - Some(dispatcher::TurnOutcomeKind::Completed { final_text, reasoning }) => { - let mut usage = resolved.usage; - if !usage.has_any_tokens() { - let accumulator = crate::llm::route_decision::ProviderUsageAccumulator::new(); - usage = accumulator.finish_or_estimate_completion_chars(final_text.chars().count()); - } - if crate::agent::response_guard::is_empty_assistant_response(&final_text, false) { - ProviderTurnTerminalPlan::Completed { - final_text, - reasoning: String::new(), - recorded_response: String::new(), - empty_response: true, - usage, - history_commit_len: history_len, - final_text_chars: 0, - recorded_response_chars: 0, - summary: "redux driver completed with empty response", - } - } else { - let recorded_response = sanitize_channel_response(&final_text, tools_registry); - let final_text_chars = final_text.chars().count(); - let recorded_response_chars = recorded_response.chars().count(); - ProviderTurnTerminalPlan::Completed { - final_text, - reasoning, - final_text_chars, - recorded_response_chars, - recorded_response, - empty_response: false, - usage, - history_commit_len: history_len.saturating_add(1), - summary: "redux driver completed", - } - } - } - Some(dispatcher::TurnOutcomeKind::Failed { err, retryable: _ }) => ProviderTurnTerminalPlan::Failed { - summary: format!("redux driver failed: {err}"), - err, - history_commit_len: history_len, - }, - Some(dispatcher::TurnOutcomeKind::Cancelled) | None => ProviderTurnTerminalPlan::Cancelled { - summary: "redux driver cancelled", - }, - } -} - -#[cfg(feature = "terminal-tui")] -pub(super) fn gate_provider_turn_terminal_finalization( - scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, - coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, - workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, - id: Option, - gate: ProviderTurnTerminalGate<'_>, -) -> Vec { - match gate { - ProviderTurnTerminalGate::Completed { - history_commit_len, - final_text_chars, - recorded_response_chars, - usage, - summary, - } => gate_completed_provider_turn_finalization( - scheduler, - coordinator, - workers, - id, - history_commit_len, - final_text_chars, - recorded_response_chars, - usage, - summary, - ), - ProviderTurnTerminalGate::Failed { - history_commit_len, - summary, - } => gate_failed_provider_turn_finalization(scheduler, coordinator, workers, id, history_commit_len, summary), - ProviderTurnTerminalGate::Cancelled { summary } => { - gate_cancelled_provider_turn_finalization(scheduler, coordinator, workers, id, summary) - } - } -} - -#[cfg(feature = "terminal-tui")] -pub(super) fn finalize_provider_turn_from_event( - scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, - coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, - workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, - event: ProviderTurnFinalizerEvent, -) -> Vec { - let task_id = event.task_id; - let decisions = match event.plan { - ProviderTurnTerminalPlan::Completed { - usage, - history_commit_len, - final_text_chars, - recorded_response_chars, - summary, - .. - } => gate_provider_turn_terminal_finalization( - scheduler, - coordinator, - workers, - task_id, - ProviderTurnTerminalGate::Completed { - history_commit_len, - final_text_chars, - recorded_response_chars, - usage: &usage, - summary, - }, - ), - ProviderTurnTerminalPlan::Failed { - history_commit_len, - summary, - .. - } => gate_provider_turn_terminal_finalization( - scheduler, - coordinator, - workers, - task_id, - ProviderTurnTerminalGate::Failed { - history_commit_len, - summary, - }, - ), - ProviderTurnTerminalPlan::Cancelled { summary } => gate_provider_turn_terminal_finalization( - scheduler, - coordinator, - workers, - task_id, - ProviderTurnTerminalGate::Cancelled { summary }, - ), - }; - if decisions.is_empty() { - return vec![ProviderTurnFinalizerResult { - task_id, - terminal_status: "unknown", - finalized: false, - }]; - } - decisions - .iter() - .map(provider_turn_finalizer_result_from_commit_decision) - .collect() -} - -#[cfg(feature = "terminal-tui")] -const fn provider_turn_finalizer_result_from_commit_decision( - decision: &crate::chat::history_commit::HistoryCommitDecision, -) -> ProviderTurnFinalizerResult { - match decision { - crate::chat::history_commit::HistoryCommitDecision::Commit { task_id, .. } => ProviderTurnFinalizerResult { - task_id: Some(*task_id), - terminal_status: "completed", - finalized: true, - }, - crate::chat::history_commit::HistoryCommitDecision::Skip { task_id, status, .. } => { - ProviderTurnFinalizerResult { - task_id: Some(*task_id), - terminal_status: match status { - crate::chat::history_commit::HistoryCommitStatus::Completed => "completed", - crate::chat::history_commit::HistoryCommitStatus::Cancelled => "cancelled", - crate::chat::history_commit::HistoryCommitStatus::Failed => "failed", - }, - finalized: true, - } - } - } -} - -#[cfg(feature = "terminal-tui")] -pub(super) fn enqueue_provider_turn_finalizer_event( - queue: &mut std::collections::VecDeque, - task_id: Option, - plan: ProviderTurnTerminalPlan, -) { - queue.push_back(ProviderTurnFinalizerEvent { task_id, plan }); -} - -/// The terminal action of an ordered provider-turn commit. -#[derive(Debug, Clone, Copy)] -pub(super) enum OrderedCommitTerminal<'a> { - /// TUI: `StreamCompleted` for the visible draft, acknowledged through the - /// task-scoped turn signal. - #[cfg(feature = "terminal-tui")] - StreamCompleted { draft_id: &'a str, reasoning: &'a str }, - /// Non-TUI: `TurnCommitRequested`, acknowledged through - /// `dispatch_awaited` (keyed by the task). - TurnCommitRequested { draft_id: Option<&'a str> }, -} - -/// Queue the turn's history records (user turn when `record_user`, then the -/// assistant turn unless the reply is empty) ahead of its terminal action. -fn dispatch_ordered_turn_records( - chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, - task_id: crate::chat::turn_scheduler::TurnTaskId, - user_input: &str, - final_text: &str, - empty_response: bool, - record_user: bool, -) -> std::result::Result<(), String> { - if record_user { - let result = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::RecordUserTurn(user_input.to_string()), - "chat.ordered_record_user_turn", - ); - if !matches!(result, dispatcher::DispatchResult::Sent) { - return Err(format!("ordered history dispatch failed: {result:?}")); - } - } - if !empty_response { - let result = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::RecordAssistantTurn { - task_id: Some(task_id), - content: final_text.to_string(), - }, - "chat.ordered_record_assistant_turn", - ); - if !matches!(result, dispatcher::DispatchResult::Sent) { - return Err(format!("ordered history dispatch failed: {result:?}")); - } - } - Ok(()) -} - -#[cfg(feature = "terminal-tui")] -pub(super) fn dispatch_ordered_provider_turn_commit( - chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, - task_id: crate::chat::turn_scheduler::TurnTaskId, - draft_id: &str, - user_input: &str, - final_text: &str, - reasoning: &str, - empty_response: bool, - record_user: bool, -) -> std::result::Result<(), String> { - dispatch_ordered_turn_records( - chat_dispatcher, - task_id, - user_input, - final_text, - empty_response, - record_user, - )?; - let result = chat_dispatcher.dispatch_or_log( - crate::chat::action::Action::StreamCompleted { - draft_id: draft_id.to_string(), - final_text: final_text.to_string(), - reasoning: reasoning.to_string(), - }, - "chat.ordered_stream_completed", - ); - if !matches!(result, dispatcher::DispatchResult::Sent) { - return Err(format!("ordered history dispatch failed: {result:?}")); - } - Ok(()) -} - -pub(super) async fn dispatch_ordered_provider_turn_commit_and_wait( - chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, - turn_signal: &dispatcher::TurnCompletionSignal, - task_id: crate::chat::turn_scheduler::TurnTaskId, - terminal: OrderedCommitTerminal<'_>, - user_input: &str, - final_text: &str, - empty_response: bool, - record_user: bool, -) -> std::result::Result<(), String> { - let result = match terminal { - #[cfg(feature = "terminal-tui")] - OrderedCommitTerminal::StreamCompleted { draft_id, reasoning } => { - dispatch_stream_completed_commit_and_wait( - chat_dispatcher, - turn_signal, - task_id, - draft_id, - user_input, - final_text, - reasoning, - empty_response, - record_user, - ) - .await - } - OrderedCommitTerminal::TurnCommitRequested { draft_id } => { - dispatch_turn_commit_requested_and_wait( - chat_dispatcher, - turn_signal, - task_id, - draft_id, - user_input, - final_text, - empty_response, - record_user, - ) - .await - } - }; - if result.is_ok() { - turn_signal.record_history_commit(task_id); - } - result -} - -/// TUI ordered commit: the records, then `StreamCompleted`, acknowledged by -/// the dispatcher's second task-scoped turn-signal notification. -#[cfg(feature = "terminal-tui")] -#[allow(clippy::too_many_arguments)] -async fn dispatch_stream_completed_commit_and_wait( - chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, - turn_signal: &dispatcher::TurnCompletionSignal, - task_id: crate::chat::turn_scheduler::TurnTaskId, - draft_id: &str, - user_input: &str, - final_text: &str, - reasoning: &str, - empty_response: bool, - record_user: bool, -) -> std::result::Result<(), String> { - // The first task-scoped notification means the provider produced its - // terminal payload. The ordered StreamCompleted below is a distinct phase: - // the dispatcher only emits its second notification after every reducer - // effect, including SaveSession, has completed. Arm the waiter before - // dispatch so the latch-less Notify cannot be missed. - // Provider completion consumption unregisters the first-phase slot. Open - // a fresh slot for the same task/draft so the ordered reducer commit has - // its own acknowledgement lifecycle. - turn_signal.register_turn(task_id, draft_id.to_string()); - let Some(persistence_committed) = turn_signal.notified_for(task_id) else { - tracing::error!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), - "missing task-scoped persistence waiter" - ); - turn_signal.fail_history_commit("missing task-scoped persistence waiter"); - return Err("missing task-scoped persistence waiter".to_string()); - }; - if let Err(error) = dispatch_ordered_provider_turn_commit( - chat_dispatcher, - task_id, - draft_id, - user_input, - final_text, - reasoning, - empty_response, - record_user, - ) { - turn_signal.unregister_turn(task_id); - turn_signal.fail_history_commit(error.clone()); - return Err(error); - } - let result = match tokio::time::timeout(Duration::from_secs(30), persistence_committed).await { - Ok(()) => { - // Consume the second terminal outcome so a later waiter cannot - // mistake this persistence acknowledgement for a provider result. - let outcome = turn_signal.consume_turn_outcome(task_id); - turn_signal.unregister_turn(task_id); - match outcome { - Some(dispatcher::TurnOutcomeKind::Completed { .. }) => Ok(()), - Some(dispatcher::TurnOutcomeKind::Failed { err, .. }) => Err(err), - Some(dispatcher::TurnOutcomeKind::Cancelled) => { - Err("ordered session persistence was cancelled".to_string()) - } - None => Err("ordered session persistence acknowledged without an outcome".to_string()), - } - } - Err(_) => { - tracing::error!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), - "timed out waiting for ordered session persistence" - ); - turn_signal.unregister_turn(task_id); - Err("timed out waiting for ordered session persistence".to_string()) - } - }; - if let Err(error) = &result { - turn_signal.fail_history_commit(error.clone()); - } - result -} - -/// Non-TUI ordered commit: the records, then `TurnCommitRequested` awaited -/// through the acknowledged-session barrier. Any failure latches the -/// unconfirmed-commit stop. -#[allow(clippy::too_many_arguments)] -async fn dispatch_turn_commit_requested_and_wait( - chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, - turn_signal: &dispatcher::TurnCompletionSignal, - task_id: crate::chat::turn_scheduler::TurnTaskId, - draft_id: Option<&str>, - user_input: &str, - final_text: &str, - empty_response: bool, - record_user: bool, -) -> std::result::Result<(), String> { - if let Err(error) = dispatch_ordered_turn_records( - chat_dispatcher, - task_id, - user_input, - final_text, - empty_response, - record_user, - ) { - turn_signal.fail_history_commit(error.clone()); - return Err(error); - } - let ack = chat_dispatcher - .dispatch_awaited( - crate::chat::action::Action::TurnCommitRequested { - task_id, - draft_id: draft_id.map(str::to_owned), - }, - turn_signal, - ) - .await - .map_err(|error| error.to_string())?; - match ack { - crate::chat::acked_session::Ack::Published(_) => Ok(()), - crate::chat::acked_session::Ack::Unchanged(_) => { - let error = "turn commit was acknowledged without a saved revision".to_owned(); - turn_signal.fail_history_commit(error.clone()); - Err(error) - } - crate::chat::acked_session::Ack::Rejected(reason) => { - turn_signal.fail_history_commit(reason.clone()); - Err(reason) - } - } -} - -#[cfg(feature = "terminal-tui")] -#[allow(clippy::too_many_arguments)] -async fn commit_completed_provider_turn( - pending_commit: PendingOrderedProviderTurnCommit, - history: &mut Vec, - turn_scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, - provider_turn_workers: &crate::chat::turn_worker::ProviderTurnWorkerRegistry, - chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, - terminal: &Arc, - memory_fabric: &MemoryFabric, - chat_session_key: &str, - config: &Config, - sessions_redraw_handle: Option<&mpsc::Sender<()>>, - redraw_tx_for_main: Option<&mpsc::Sender<()>>, - turn_signal: &dispatcher::TurnCompletionSignal, -) -> bool { - let mut pending = pending_commit.context; - let ProviderTurnTerminalPlan::Completed { - final_text, - reasoning, - recorded_response, - empty_response, - usage: redux_tokens_used, - history_commit_len, - .. - } = pending_commit.terminal_plan - else { - tracing::warn!( - task_id = pending.task_id.get(), - "ordered provider turn commit received non-completed terminal plan" - ); - return false; - }; - - let provider_turn_task_id = Some(pending.task_id); - // Provider trace capture seals execution authority before this ordered - // finalizer runs. Re-reading the live disposition here would therefore - // reject every successful provider-backed turn. Use the immutable - // pre-execution classification carried with the turn instead. - let (provider_outcome, terminal_usage) = { - let provider_outcome = if let Some(binding) = pending.turn_binding.as_ref() { - match binding.provider_outcome(&pending.route_decision, pending.provider_started_at) { - Ok(outcome) => outcome, - Err(error) => { - tracing::error!(error = %crate::agent::diagnostics::error_class(&error), "Chat completion has no authenticated provider trace"); - return false; - } - } - } else { - ProviderExecutionOutcome::success_for_decision_with_usage( - &pending.route_decision, - pending.provider_started_at, - redux_tokens_used.clone(), - ) - }; - let terminal_usage = match finalize_chat_success_turn( - pending.turn_binding.as_deref(), - memory_fabric, - chat_session_key, - &pending.turn_run_id, - &pending.provider_name, - &pending.model_name, - pending.route_scope.clone(), - provider_outcome.clone(), - (!empty_response).then(|| recorded_response.clone()), - history_commit_len, - if empty_response { - "redux driver completed with empty response" - } else { - "redux driver completed" - }, - &config.cost, - &config.workspace_dir, - ) - .await - { - Ok(receipt) => receipt.into_session_usage(), - Err(error) => { - tracing::error!(error = %crate::agent::diagnostics::error_class(&error), "Chat terminal persistence is unconfirmed"); - return false; - } - }; - (Some(provider_outcome), terminal_usage) - }; - let finished_at = provider_outcome - .as_ref() - .map_or_else(chrono::Utc::now, |outcome| outcome.finished_at); - if empty_response { - if let Err(e) = terminal.cancel_draft("user", &pending.draft_id).await { - tracing::debug!(error = %crate::agent::diagnostics::error_class(&e), "Redux driver: cancel empty-response draft failed"); - } - // Metered usage goes in before the commit: same-channel FIFO puts it - // in the commit's acknowledged revision, and it is recorded even if - // the commit then fails, because the provider charged it. - if let Err(error) = dispatch_final_usage( - chat_dispatcher, - turn_signal, - turn_scheduler, - provider_turn_task_id, - terminal_usage, - "chat.provider_usage_recorded_empty_response", - ) - .await - { - surface_session_message( - chat_dispatcher, - sessions_redraw_handle, - &format!("Session persistence failed; dependent commands remain blocked: {error}"), - ); - return false; - } - if let Some(tx) = redraw_tx_for_main { - let _ = tx.try_send(()); - } - let persistence_result = dispatch_ordered_provider_turn_commit_and_wait( - chat_dispatcher, - turn_signal, - pending.task_id, - OrderedCommitTerminal::StreamCompleted { - draft_id: &pending.draft_id, - reasoning: &reasoning, - }, - &pending.user_input, - &final_text, - empty_response, - true, - ) - .await; - if let Err(error) = persistence_result { - surface_session_message( - chat_dispatcher, - sessions_redraw_handle, - &format!("Session persistence failed; dependent commands remain blocked: {error}"), - ); - return false; - } - if let Some(guard) = pending.assignment.as_mut() { - guard.failed("The turn finished without reply text."); - } - adopt_committed_turn(history, chat_dispatcher, &pending, None); - surface_turn_elapsed_message( - chat_dispatcher, - sessions_redraw_handle, - "completed", - pending.provider_started_at, - finished_at, - ); - publish_main_queue_status(chat_dispatcher, turn_scheduler); - publish_provider_worker_status(chat_dispatcher, provider_turn_workers); - return true; - } - - if let Err(error) = dispatch_final_usage( - chat_dispatcher, - turn_signal, - turn_scheduler, - provider_turn_task_id, - terminal_usage, - "chat.provider_usage_recorded", - ) - .await - { - surface_session_message( - chat_dispatcher, - sessions_redraw_handle, - &format!("Session persistence failed; dependent commands remain blocked: {error}"), - ); - return false; - } - if let Some(tx) = redraw_tx_for_main { - let _ = tx.try_send(()); - } - let persistence_result = dispatch_ordered_provider_turn_commit_and_wait( - chat_dispatcher, - turn_signal, - pending.task_id, - OrderedCommitTerminal::StreamCompleted { - draft_id: &pending.draft_id, - reasoning: &reasoning, - }, - &pending.user_input, - &final_text, - empty_response, - true, - ) - .await; - if let Err(error) = persistence_result { - surface_session_message( - chat_dispatcher, - sessions_redraw_handle, - &format!("Session persistence failed; dependent commands remain blocked: {error}"), - ); - return false; - } - adopt_committed_turn(history, chat_dispatcher, &pending, Some(&final_text)); - if let Err(e) = terminal.finalize_draft("user", &pending.draft_id, &final_text).await { - tracing::warn!(error = %crate::agent::diagnostics::error_class(&e), "Redux driver: finalize_draft failed"); - } - if let Some(provider_outcome) = provider_outcome.as_ref() { - let attempts_count = u8::try_from(provider_outcome.attempts.len()).unwrap_or(u8::MAX); - crate::runtime::control_ladder::append_provider_outcome_trace( - std::path::Path::new(&config.workspace_dir), - &provider_outcome.decision_id, - &provider_outcome.final_provider, - &provider_outcome.final_model, - attempts_count, - "success", - ); - } - if let Some(guard) = pending.assignment.as_mut() { - guard.completed(&recorded_response); - } - surface_turn_elapsed_message( - chat_dispatcher, - sessions_redraw_handle, - "completed", - pending.provider_started_at, - finished_at, - ); - publish_main_queue_status(chat_dispatcher, turn_scheduler); - publish_provider_worker_status(chat_dispatcher, provider_turn_workers); - true -} - -/// Bring the run loop's provider view up to an acknowledged turn commit, so -/// it equals the view rebuilt from the committed snapshot -/// ([`super::compaction::provider_view_from_acked`]). Without a compaction -/// since the turn copied its view, the committed request and reply are -/// appended; the request is the plain stored text, never the enriched form -/// the turn sent (only a request still being sent carries its recalled -/// context and attached files). After a worker compaction the view is rebuilt -/// from the committed snapshot instead: appending to the pre-compaction view -/// would resend the replaced cold prefix and force another rollover or a lossy -/// fallback on the next turn. -#[cfg(feature = "terminal-tui")] -fn adopt_committed_turn( - history: &mut Vec, - chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, - pending: &PerTurnContext, - reply: Option<&str>, -) { - let acked = chat_dispatcher.session_reader().acked(); - if acked.compaction_epoch != pending.compaction_epoch_at_start { - let view = super::compaction::provider_view_from_acked(history, &acked); - tracing::info!( - task_id = pending.task_id.get(), - messages_before = history.len(), - messages_after = view.len(), - "provider view rebuilt from the committed snapshot after a worker compaction" - ); - *history = view; - return; - } - history.push(crate::agent::turn_contracts::inbound_user_message(&pending.user_input)); - if let Some(reply) = reply { - history.push(committed_reply_message(&acked, reply)); - } -} - -/// The provider-view message of a committed reply: `reply` rendered with the -/// tool evidence of the snapshot's newest turn when that turn is this reply -/// (an `assistant` turn holding exactly `reply`); otherwise the bare reply, -/// since evidence that cannot be tied to the reply is never attached to it. -/// A reply that is a context handoff passes through the handoff renderer -/// first, as on every other provider-view path. -#[cfg(feature = "terminal-tui")] -pub(super) fn committed_reply_message(acked: &crate::chat::acked_session::AckedSession, reply: &str) -> ChatMessage { - let evidence = acked - .session - .turns - .last() - .filter(|turn| turn.role == "assistant" && turn.content == reply) - .map(|turn| turn.tool_evidence.as_ref()); - if evidence.is_none() { - tracing::debug!("committed reply is not the snapshot's newest assistant turn; replayed without tool evidence"); - } - let reply = crate::agent::compaction::render_context_handoff_for_provider("assistant", reply); - ChatMessage::assistant( - crate::agent::tool_evidence::render_assistant_content(&reply, evidence.flatten()).into_owned(), - ) -} - -/// A worker turn that failed or was cancelled: settled in order after the -/// worker's compactions and terminal action (the reducer never recorded a -/// worker turn's request, so none is removed), then the provider view follows -/// the settled revision. The epoch the turn's view was copied at is from -/// before the worker's detached switch and every in-turn compaction. A failed -/// settlement is already latched; the run loop's health check stops the chat. -#[cfg(feature = "terminal-tui")] -async fn settle_aborted_worker_turn( - history: &mut Vec, - chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, - commits: &dispatcher::TurnCompletionSignal, - pending: &PerTurnContext, - len_before_user_turn: Option, -) { - match settle_aborted_turn(chat_dispatcher, commits, None).await { - Ok(settled) => { - provider_view_after_settled_abort( - history, - &settled, - pending.compaction_epoch_at_start, - false, - len_before_user_turn, - ); - } - Err(_) => tracing::error!( - task_id = pending.task_id.get(), - "failed or cancelled worker turn was not settled; the history commit is latched as failed" - ), - } -} - -#[cfg(feature = "terminal-tui")] -#[allow(clippy::too_many_arguments)] -pub(super) async fn apply_ready_ordered_provider_turn_commits( - results: Vec, - pending_ordered_provider_turn_commits: &mut std::collections::HashMap< - crate::chat::turn_scheduler::TurnTaskId, - PendingOrderedProviderTurnCommit, - >, - history: &mut Vec, - turn_scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, - provider_turn_workers: &crate::chat::turn_worker::ProviderTurnWorkerRegistry, - chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, - terminal: &Arc, - memory_fabric: &MemoryFabric, - chat_session_key: &str, - config: &Config, - sessions_redraw_handle: Option<&mpsc::Sender<()>>, - redraw_tx_for_main: Option<&mpsc::Sender<()>>, - turn_signal: &dispatcher::TurnCompletionSignal, - plain_mode: bool, - plain_mode_turn_failed: &mut bool, -) -> bool { - let mut applied = false; - for result in results { - if turn_signal.ensure_history_commits_healthy().is_err() { - break; - } - if !result.finalized || result.terminal_status != "completed" { - continue; - } - let Some(task_id) = result.task_id else { - continue; - }; - let Some(pending_commit) = pending_ordered_provider_turn_commits.remove(&task_id) else { - tracing::debug!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), - "ordered provider turn commit ready before local payload was registered" - ); - continue; - }; - let committed = commit_completed_provider_turn( - pending_commit, - history, - turn_scheduler, - provider_turn_workers, - chat_dispatcher, - terminal, - memory_fabric, - chat_session_key, - config, - sessions_redraw_handle, - redraw_tx_for_main, - turn_signal, - ) - .await; - if !committed { - turn_signal.fail_history_commit(format!("ordered turn {} was not committed", task_id.get())); - if plain_mode { - *plain_mode_turn_failed = true; - } - break; - } - applied = true; - } - applied -} - -/// The failed provider attempt a decided turn's terminal records, as every -/// other entry records it; a policy refusal sent nothing, so it records none. -#[cfg(feature = "terminal-tui")] -fn failed_provider_outcome(pending: &PerTurnContext, err: &str) -> Option { - let binding = pending.turn_binding.as_ref()?; - let refused = matches!( - binding.failure_note(), - Some(crate::chat::binding::TurnFailureNote::Refused { .. }) - ); - (binding.is_decided() && !refused).then(|| { - ProviderExecutionOutcome::failed_for_decision( - &pending.route_decision, - pending.provider_started_at, - &anyhow::anyhow!("{err}"), - ) - }) -} - -#[cfg(feature = "terminal-tui")] -#[allow(clippy::too_many_arguments)] -async fn finalize_per_turn_context( - mut pending: PerTurnContext, - completion_event: Option, - pending_ordered_provider_turn_commits: &mut std::collections::HashMap< - crate::chat::turn_scheduler::TurnTaskId, - PendingOrderedProviderTurnCommit, - >, - turn_signal: &dispatcher::TurnCompletionSignal, - provider_turn_completion_contexts: &mut std::collections::HashMap< - crate::chat::turn_scheduler::TurnTaskId, - ProviderTurnCompletionContext, - >, - history: &mut Vec, - tools_registry: &[Box], - provider_turn_finalizer_events: &mut std::collections::VecDeque, - turn_scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, - history_commit_coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, - provider_turn_workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, - chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, - terminal: &Arc, - memory_fabric: &MemoryFabric, - chat_session_key: &str, - config: &Config, - sessions_redraw_handle: Option<&mpsc::Sender<()>>, - redraw_tx_for_main: Option<&mpsc::Sender<()>>, - plain_mode: bool, - plain_mode_turn_failed: &mut bool, -) { - let provider_turn_task_id = Some(pending.task_id); - let resolved_completion = resolve_provider_turn_completion(turn_signal, provider_turn_task_id, completion_event); - let completion_history_len = take_provider_turn_completion_history_len( - provider_turn_completion_contexts, - provider_turn_task_id, - history.len(), - ); - let terminal_plan = - provider_turn_terminal_plan_from_completion(resolved_completion, completion_history_len, tools_registry); - let history_len_before_user_turn: usize = pending.history_len_before_user_turn; - tracing::debug!( - task_id = pending.task_id.get(), - draft_id = %crate::agent::diagnostics::text_class(&pending.draft_id), - turn_run_id = %crate::agent::diagnostics::text_class(&pending.turn_run_id), - provider_name = %crate::security::redaction::redact_provider_text(&pending.provider_name), - model_name = %crate::security::redaction::redact_provider_text(&pending.model_name), - history_len_before_user_turn, - "finalizing provider turn context" - ); - enqueue_provider_turn_finalizer_event( - provider_turn_finalizer_events, - provider_turn_task_id, - terminal_plan.clone(), - ); - let finalizer_results = drain_provider_turn_finalizer_events_and_publish( - turn_scheduler, - history_commit_coordinator, - provider_turn_workers, - provider_turn_finalizer_events, - chat_dispatcher, - ); - - drop(pending.delta_tx.take()); - drop(pending.tool_event_tx.take()); - if let Some(handle) = pending.draft_updater.take() { - let _ = handle.await; - } - if let Some(handle) = pending.tool_event_forwarder.take() { - let _ = handle.await; - } - - match terminal_plan { - plan @ ProviderTurnTerminalPlan::Completed { .. } => { - let task_id = pending.task_id; - if pending_ordered_provider_turn_commits - .insert( - task_id, - PendingOrderedProviderTurnCommit { - context: pending, - terminal_plan: plan, - }, - ) - .is_some() - { - tracing::warn!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), - "replaced pending ordered provider turn commit payload" - ); - } - } - ProviderTurnTerminalPlan::Failed { err, .. } => { - if let Some(guard) = pending.assignment.as_mut() { - guard.failed(&format!("The turn this chat ran for the assignment failed: {err}")); - } - let provider_outcome = failed_provider_outcome(&pending, &err); - if let Err(error) = finalize_chat_non_success_turn( - pending.turn_binding.as_deref(), - memory_fabric, - &pending.turn_run_id, - pending.route_scope.clone(), - crate::agent::terminal::TurnTerminalStatus::Failed, - provider_outcome, - pending.provider_started_at, - &format!("redux driver failed: {err}"), - &config.cost, - &config.workspace_dir, - ) - .await - { - if pending - .turn_binding - .as_ref() - .is_some_and(|binding| binding.is_decided()) - { - *plain_mode_turn_failed = true; - } - tracing::warn!(error = %crate::agent::diagnostics::error_class(&error), "Failed to commit ordered failed Chat terminal event"); - } - settle_aborted_worker_turn(history, chat_dispatcher, turn_signal, &pending, None).await; - let interactive_tui_active = redraw_tx_for_main.is_some(); - if !interactive_tui_active { - let _ = terminal.cancel_draft("user", &pending.draft_id).await; - super::output::print_turn_failure(plain_mode, &err); - } - if plain_mode { - *plain_mode_turn_failed = true; - } - surface_turn_elapsed_message( - chat_dispatcher, - sessions_redraw_handle, - "failed", - pending.provider_started_at, - chrono::Utc::now(), - ); - publish_main_queue_status(chat_dispatcher, turn_scheduler); - publish_provider_worker_status(chat_dispatcher, provider_turn_workers); - } - ProviderTurnTerminalPlan::Cancelled { .. } => { - // Deliberately not marked: the guard's own default already says the - // turn ended before it answered, which is exactly what happened — - // and `cancelled` is the daemon's verdict, not a client's to claim. - if let Err(error) = finalize_chat_non_success_turn( - pending.turn_binding.as_deref(), - memory_fabric, - &pending.turn_run_id, - pending.route_scope.clone(), - crate::agent::terminal::TurnTerminalStatus::Cancelled, - None, - pending.provider_started_at, - "redux driver cancelled", - &config.cost, - &config.workspace_dir, - ) - .await - { - if pending - .turn_binding - .as_ref() - .is_some_and(|binding| binding.is_decided()) - { - *plain_mode_turn_failed = true; - } - tracing::warn!(error = %crate::agent::diagnostics::error_class(&error), "Failed to commit ordered cancelled Chat terminal event"); - } - let _ = terminal.cancel_draft("user", &pending.draft_id).await; - settle_aborted_worker_turn( - history, - chat_dispatcher, - turn_signal, - &pending, - Some(pending.history_len_before_user_turn), - ) - .await; - publish_main_queue_status(chat_dispatcher, turn_scheduler); - publish_provider_worker_status(chat_dispatcher, provider_turn_workers); - } - } - let _ = apply_ready_ordered_provider_turn_commits( - finalizer_results, - pending_ordered_provider_turn_commits, - history, - turn_scheduler, - provider_turn_workers, - chat_dispatcher, - terminal, - memory_fabric, - chat_session_key, - config, - sessions_redraw_handle, - redraw_tx_for_main, - turn_signal, - plain_mode, - plain_mode_turn_failed, - ) - .await; -} - -#[cfg(feature = "terminal-tui")] -#[allow(clippy::too_many_arguments)] -pub(super) async fn finalize_ready_per_turn_contexts( - per_turn_contexts: &mut std::collections::HashMap, - pending_ordered_provider_turn_commits: &mut std::collections::HashMap< - crate::chat::turn_scheduler::TurnTaskId, - PendingOrderedProviderTurnCommit, - >, - pending_provider_completion_events: &mut std::collections::HashMap< - crate::chat::turn_scheduler::TurnTaskId, - ProviderTurnCompletionEvent, - >, - turn_signal: &dispatcher::TurnCompletionSignal, - provider_turn_completion_contexts: &mut std::collections::HashMap< - crate::chat::turn_scheduler::TurnTaskId, - ProviderTurnCompletionContext, - >, - history: &mut Vec, - tools_registry: &[Box], - provider_turn_finalizer_events: &mut std::collections::VecDeque, - turn_scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, - history_commit_coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, - provider_turn_workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, - chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, - terminal: &Arc, - memory_fabric: &MemoryFabric, - chat_session_key: &str, - config: &Config, - sessions_redraw_handle: Option<&mpsc::Sender<()>>, - redraw_tx_for_main: Option<&mpsc::Sender<()>>, - plain_mode: bool, - plain_mode_turn_failed: &mut bool, -) -> bool { - let ready_task_ids: Vec<_> = per_turn_contexts - .keys() - .copied() - .filter(|task_id| pending_provider_completion_events.contains_key(task_id)) - .collect(); - if ready_task_ids.is_empty() { - return false; - } - for task_id in ready_task_ids { - if turn_signal.ensure_history_commits_healthy().is_err() { - break; - } - let Some(pending) = per_turn_contexts.remove(&task_id) else { - continue; - }; - let completion = pending_provider_completion_events.remove(&task_id); - finalize_per_turn_context( - pending, - completion, - pending_ordered_provider_turn_commits, - turn_signal, - provider_turn_completion_contexts, - history, - tools_registry, - provider_turn_finalizer_events, - turn_scheduler, - history_commit_coordinator, - provider_turn_workers, - chat_dispatcher, - terminal, - memory_fabric, - chat_session_key, - config, - sessions_redraw_handle, - redraw_tx_for_main, - plain_mode, - plain_mode_turn_failed, - ) - .await; - } - true -} - -#[cfg(feature = "terminal-tui")] -#[allow(clippy::too_many_arguments)] -pub(super) async fn finalize_all_per_turn_contexts_as_cancelled( - per_turn_contexts: &mut std::collections::HashMap, - pending_ordered_provider_turn_commits: &mut std::collections::HashMap< - crate::chat::turn_scheduler::TurnTaskId, - PendingOrderedProviderTurnCommit, - >, - turn_signal: &dispatcher::TurnCompletionSignal, - provider_turn_completion_contexts: &mut std::collections::HashMap< - crate::chat::turn_scheduler::TurnTaskId, - ProviderTurnCompletionContext, - >, - history: &mut Vec, - tools_registry: &[Box], - provider_turn_finalizer_events: &mut std::collections::VecDeque, - turn_scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, - history_commit_coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, - provider_turn_workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, - chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, - terminal: &Arc, - memory_fabric: &MemoryFabric, - chat_session_key: &str, - config: &Config, - sessions_redraw_handle: Option<&mpsc::Sender<()>>, - redraw_tx_for_main: Option<&mpsc::Sender<()>>, - plain_mode: bool, - plain_mode_turn_failed: &mut bool, -) { - let pending_turns: Vec<_> = per_turn_contexts.drain().map(|(_, pending)| pending).collect(); - for pending in pending_turns { - finalize_per_turn_context( - pending, - None, - pending_ordered_provider_turn_commits, - turn_signal, - provider_turn_completion_contexts, - history, - tools_registry, - provider_turn_finalizer_events, - turn_scheduler, - history_commit_coordinator, - provider_turn_workers, - chat_dispatcher, - terminal, - memory_fabric, - chat_session_key, - config, - sessions_redraw_handle, - redraw_tx_for_main, - plain_mode, - plain_mode_turn_failed, - ) - .await; - } -} - -#[cfg(feature = "terminal-tui")] -pub(super) fn drain_provider_turn_finalizer_events( - scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, - coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, - workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, - queue: &mut std::collections::VecDeque, -) -> Vec { - let mut results = Vec::new(); - while let Some(event) = queue.pop_front() { - results.extend(finalize_provider_turn_from_event( - scheduler, - coordinator, - workers, - event, - )); - } - results -} - -#[cfg(feature = "terminal-tui")] -pub(super) fn drain_provider_turn_finalizer_events_and_publish( - scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, - coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, - workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, - queue: &mut std::collections::VecDeque, - chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, -) -> Vec { - let results = drain_provider_turn_finalizer_events(scheduler, coordinator, workers, queue); - if !results.is_empty() { - publish_main_queue_status(chat_dispatcher, scheduler); - publish_provider_worker_status(chat_dispatcher, workers); - } - results -} - -pub(super) fn start_provider_turn_task( - scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, - existing_task_id: Option, - input: &str, - history_base_len: usize, -) -> Option { - let id = existing_task_id.unwrap_or_else(|| { - scheduler.enqueue( - input.to_string(), - crate::chat::turn_scheduler::TurnPriority::Normal, - history_base_len, - ) - }); - if let Err(error) = scheduler.start_task(id) { - tracing::warn!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), - reused_queued_task = existing_task_id.is_some(), - error = %crate::agent::diagnostics::error_class(&error), - "TurnScheduler provider task start failed" - ); - return None; - } - Some(id) -} - -pub(super) fn register_provider_history_commit_task( - coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, - scheduler: &crate::chat::turn_scheduler::TurnScheduler, - id: Option, -) { - if let Some(id) = id - && let Some(task) = scheduler.task(id) - && let Err(error) = coordinator.register_task(task) - { - let task_seq: u64 = task.sequence; - tracing::warn!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), - task_seq, - error = %crate::agent::diagnostics::error_class(&error), - "HistoryCommitCoordinator provider task registration failed" - ); - } -} - -pub(super) fn register_provider_turn_worker( - workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, - scheduler: &crate::chat::turn_scheduler::TurnScheduler, - id: Option, - kind: crate::chat::turn_worker::ProviderTurnWorkerKind, -) { - if let Some(id) = id - && let Some(task) = scheduler.task(id) - && let Err(error) = workers.start_from_task(task, kind) - { - let task_seq: u64 = task.sequence; - tracing::warn!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), - task_seq, - kind = ?kind, - error = %crate::agent::diagnostics::error_class(&error), - "ProviderTurnWorkerRegistry provider worker registration failed" - ); - } -} - -#[cfg(feature = "terminal-tui")] -pub(super) fn spawn_provider_turn_completion_waiter( - turn_signal: dispatcher::TurnCompletionSignal, - task_id: crate::chat::turn_scheduler::TurnTaskId, - tx: mpsc::Sender, - shutdown: CancellationToken, -) { - tokio::spawn(async move { - let notified = turn_signal.notified_for(task_id); - match notified { - Some(notified) => { - tokio::select! { - () = notified => {} - () = shutdown.cancelled() => {} - } - } - None => { - tokio::select! { - () = turn_signal.notified() => {} - () = shutdown.cancelled() => {} - } - } - } - let event = ProviderTurnCompletionEvent { - task_id, - outcome: turn_signal.consume_turn_outcome(task_id), - usage: turn_signal.consume_turn_usage(task_id), - }; - if tx.send(event).await.is_err() { - tracing::debug!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), - "provider turn completion waiter could not deliver event" - ); - } - }); -} - -pub(super) fn request_provider_turn_cancel( - scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, - workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, - id: Option, - reason: &'static str, -) { - if let Some(id) = id { - if let Err(error) = scheduler.request_cancel(id) { - tracing::warn!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), - reason, - error = %crate::agent::diagnostics::error_class(&error), - "TurnScheduler provider task cancel request failed" - ); - } - if let Err(error) = workers.request_cancel(id) { - tracing::warn!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), - reason, - error = %crate::agent::diagnostics::error_class(&error), - "ProviderTurnWorkerRegistry provider worker cancel request failed" - ); - } - } -} - -/// Record the user's request when the turn is admitted (the non-TUI path; -/// its completion commits with `record_user: false`). The send is bounded and -/// awaited on the ordered action channel -/// ([`crate::chat::dispatcher::ChatDispatcher::dispatch_bounded`]): a full -/// channel delays the turn instead of dropping the request, so the later -/// commit always includes it. A send that is not accepted latches the -/// unconfirmed-commit stop once and fails the turn before it runs. -/// -/// Returns the admission's identity: a failed or cancelled turn settles by -/// it ([`settle_aborted_turn`]), so only this request is ever removed. -pub(super) async fn record_user_turn_at_admission( - chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, - commits: &crate::chat::dispatcher::TurnCompletionSignal, - user_input: &str, -) -> anyhow::Result { - let admission = crate::chat::action::AdmissionId::next(); - chat_dispatcher - .dispatch_bounded( - crate::chat::action::Action::UserTurnAdmitted { - admission, - content: user_input.to_owned(), - }, - commits, - ) - .await - .map_err(|error| anyhow::anyhow!("Chat stopped after an unconfirmed history commit: {error}"))?; - Ok(admission) -} - -/// The acknowledged session as of every action sent before this call: an -/// awaited no-op (`RedrawRequested`) on the same ordered channel. A turn's -/// admission reads its start state through it, so a compaction another turn -/// already sent is never missed by a racing snapshot read. A failed -/// acknowledgement latches `commits` and is the unconfirmed-commit stop. -pub(super) async fn acknowledged_session_barrier( - chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, - commits: &crate::chat::dispatcher::TurnCompletionSignal, -) -> anyhow::Result { - match chat_dispatcher - .dispatch_awaited(crate::chat::action::Action::RedrawRequested, commits) - .await - .map_err(|error| anyhow::anyhow!("Chat stopped after an unconfirmed history commit: {error}"))? - { - crate::chat::acked_session::Ack::Published(acked) | crate::chat::acked_session::Ack::Unchanged(acked) => { - Ok(acked) - } - crate::chat::acked_session::Ack::Rejected(_) => Ok(chat_dispatcher.session_reader().acked()), - } -} - -/// Settle a failed or cancelled turn with the session authority, in order -/// after its terminal action and every in-turn compaction the turn sent: -/// `TurnAbortSettled` removes the request admitted as `admission` (when the -/// turn recorded one and that admission is still open) and saves, and the -/// acknowledged revision is returned. Then the run loop's provider view -/// follows that revision ([`provider_view_after_settled_abort`]). -/// -/// A failed acknowledgement latches `commits` and is returned as the -/// unconfirmed-commit stop; a refusal (which this action never produces for -/// a live session) is latched the same way. -pub(super) async fn settle_aborted_turn( - chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, - commits: &crate::chat::dispatcher::TurnCompletionSignal, - admission: Option, -) -> anyhow::Result { - let ack = chat_dispatcher - .dispatch_awaited(crate::chat::action::Action::TurnAbortSettled { admission }, commits) - .await - .map_err(|error| anyhow::anyhow!("Chat stopped after an unconfirmed history commit: {error}"))?; - match ack { - crate::chat::acked_session::Ack::Published(acked) | crate::chat::acked_session::Ack::Unchanged(acked) => { - Ok(acked) - } - crate::chat::acked_session::Ack::Rejected(_) => { - let reason = "the failed or cancelled turn could not be settled"; - commits.fail_history_commit(reason.to_owned()); - anyhow::bail!("Chat stopped after an unconfirmed history commit: {reason}") - } - } -} - -/// The run loop's provider view after a settled failed or cancelled turn. -/// The aborted request is never kept: the settled snapshot already excludes it -/// (admission identity, `TurnAbortSettled`), so no text is matched to remove -/// anything. When the session was compacted or the view was changed at any -/// point since before the turn's preflight (`settled` carries a compaction -/// epoch other than `compaction_epoch_before_preflight`, or the turn itself -/// reported one), the view is rebuilt from the settled snapshot; otherwise it -/// is cut back to `len_before_user_turn`, its length before the request -/// (`None` for a view the request was never pushed to). Returns whether it -/// rebuilt the view. -pub(super) fn provider_view_after_settled_abort( - history: &mut Vec, - settled: &crate::chat::acked_session::AckedSession, - compaction_epoch_before_preflight: u64, - compacted_in_turn: bool, - len_before_user_turn: Option, -) -> bool { - if settled.compaction_epoch == compaction_epoch_before_preflight && !compacted_in_turn { - if let Some(len) = len_before_user_turn { - rollback_cancelled_turn_history(history, len); - } - return false; - } - let view = super::compaction::provider_view_from_acked(history, settled); - tracing::info!( - messages_before = history.len(), - messages_after = view.len(), - "provider view rebuilt from the settled snapshot after a compaction in a failed or cancelled turn" - ); - *history = view; - true -} - -/// Dispatch a turn's final metered usage (`FinalAggregate`) unconditionally, -/// before the turn's awaited commit; the reducer deduplicates per task. The -/// scheduler bookkeeping uses the same terminal usage. -/// -/// The send waits for channel capacity within the acknowledgement bound -/// ([`crate::chat::dispatcher::ChatDispatcher::dispatch_bounded`]); when the -/// usage is not accepted the history commit is latched as failed and the -/// error is returned, and the caller must not commit the turn. -pub(super) async fn dispatch_final_usage( - chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, - commits: &crate::chat::dispatcher::TurnCompletionSignal, - turn_scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, - task_id: Option, - terminal_usage: Option, - site: &'static str, -) -> Result<(), crate::chat::acked_session::AckError> { - let Some(record) = terminal_usage else { - return Ok(()); - }; - record_provider_turn_usage(turn_scheduler, task_id, &record); - chat_dispatcher - .dispatch_bounded( - crate::chat::action::Action::ProviderUsageRecorded { - task_id, - usage_kind: crate::chat::action::ProviderUsageRecordKind::FinalAggregate, - record, - }, - commits, - ) - .await - .inspect_err(|error| tracing::error!(site, error_kind = error.kind(), "final provider usage was not accepted")) -} - -pub(super) fn record_provider_turn_usage( - scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, - id: Option, - record: &crate::chat::session::MainSessionTokenUsageRecord, -) { - if let Some(id) = id - && let Err(error) = scheduler.record_usage(id, record) - { - tracing::warn!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), - error = %crate::agent::diagnostics::error_class(&error), - "TurnScheduler provider usage ledger record failed" - ); - } -} - -pub(super) fn mark_provider_turn_completed( - scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, - coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, - workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, - id: Option, - history_commit_len: usize, - summary: &'static str, -) -> Vec { - if let Some(id) = id { - match scheduler.mark_completed(id, history_commit_len, summary) { - Ok(()) => { - if record_provider_worker_completed(workers, id) { - return record_provider_history_commit_outcome(coordinator, workers, scheduler, id); - } - } - Err(error) => { - tracing::warn!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), - error = %crate::agent::diagnostics::error_class(&error), - "TurnScheduler provider task completion failed" - ); - } - } - } - Vec::new() -} - -fn mark_provider_turn_failed( - scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, - coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, - workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, - id: Option, - history_commit_len: usize, - summary: impl Into, -) -> Vec { - if let Some(id) = id { - match scheduler.mark_failed(id, history_commit_len, summary) { - Ok(()) => { - if record_provider_worker_failed(workers, id) { - return record_provider_history_commit_outcome(coordinator, workers, scheduler, id); - } - } - Err(error) => { - tracing::warn!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), - error = %crate::agent::diagnostics::error_class(&error), - "TurnScheduler provider task failure failed" - ); - } - } - } - Vec::new() -} - -fn mark_provider_turn_cancelled( - scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, - coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, - workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, - id: Option, - summary: &'static str, -) -> Vec { - if let Some(id) = id { - match scheduler.mark_cancelled(id, summary) { - Ok(()) => { - if record_provider_worker_cancelled(workers, id) { - return record_provider_history_commit_outcome(coordinator, workers, scheduler, id); - } - } - Err(error) => { - tracing::warn!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), - error = %crate::agent::diagnostics::error_class(&error), - "TurnScheduler provider task cancellation failed" - ); - } - } - } - Vec::new() -} - -fn record_provider_worker_completed( - workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, - id: crate::chat::turn_scheduler::TurnTaskId, -) -> bool { - if let Err(error) = workers.record_completed(id) { - tracing::warn!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), - error = %crate::agent::diagnostics::error_class(&error), - "ProviderTurnWorkerRegistry provider worker completion failed" - ); - return false; - } - true -} - -fn record_provider_worker_failed( - workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, - id: crate::chat::turn_scheduler::TurnTaskId, -) -> bool { - if let Err(error) = workers.record_failed(id) { - tracing::warn!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), - error = %crate::agent::diagnostics::error_class(&error), - "ProviderTurnWorkerRegistry provider worker failure failed" - ); - return false; - } - true -} - -fn record_provider_worker_cancelled( - workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, - id: crate::chat::turn_scheduler::TurnTaskId, -) -> bool { - if let Err(error) = workers.record_cancelled(id) { - tracing::warn!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), - error = %crate::agent::diagnostics::error_class(&error), - "ProviderTurnWorkerRegistry provider worker cancellation failed" - ); - return false; - } - true -} - -fn record_provider_history_commit_outcome( - coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, - workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, - scheduler: &crate::chat::turn_scheduler::TurnScheduler, - id: crate::chat::turn_scheduler::TurnTaskId, -) -> Vec { - let Some(task) = scheduler.task(id) else { - tracing::warn!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), - "HistoryCommitCoordinator missing scheduler task for provider outcome" - ); - return Vec::new(); - }; - let Some(outcome) = crate::chat::history_commit::HistoryCommitOutcome::from_terminal_task(task) else { - tracing::warn!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), - state = task.state.kind(), - "HistoryCommitCoordinator ignored non-terminal provider outcome" - ); - return Vec::new(); - }; - if let Err(error) = coordinator.record_outcome(outcome) { - let task_seq: u64 = task.sequence; - tracing::warn!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), - task_seq, - error = %crate::agent::diagnostics::error_class(&error), - "HistoryCommitCoordinator provider outcome record failed" - ); - return Vec::new(); - } - let mut decisions = Vec::new(); - for decision in coordinator.drain_ready() { - if let Err(error) = workers.apply_commit_decision(&decision) { - tracing::warn!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), - decision_kind = decision.kind(), - error = %crate::agent::diagnostics::error_class(&error), - "ProviderTurnWorkerRegistry provider worker commit decision failed" - ); - } - tracing::trace!( - task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), - decision_kind = decision.kind(), - pending_tasks = coordinator.pending_tasks(), - pending_outcomes = coordinator.pending_outcomes(), - "HistoryCommitCoordinator provider outcome became ready" - ); - decisions.push(decision); - } - decisions -} +include!("provider_turns/section_1.rs"); +include!("provider_turns/section_2.rs"); diff --git a/src/chat/provider_turns/section_1.rs b/src/chat/provider_turns/section_1.rs new file mode 100644 index 000000000..b1d513a64 --- /dev/null +++ b/src/chat/provider_turns/section_1.rs @@ -0,0 +1,1701 @@ +use super::active_turn::rollback_cancelled_turn_history; +#[cfg(feature = "terminal-tui")] +use super::binding; +#[cfg(feature = "terminal-tui")] +use super::chat_events::{finalize_chat_non_success_turn, finalize_chat_success_turn}; +use super::dispatcher; +#[cfg(feature = "terminal-tui")] +use super::input_queue::publish_main_queue_status; +#[cfg(feature = "terminal-tui")] +use super::session_glue::{surface_session_message, surface_turn_elapsed_message}; +#[cfg(feature = "terminal-tui")] +use crate::agent::turn_contracts::ToolCallNotification; +#[cfg(feature = "terminal-tui")] +use crate::channels::Channel; +#[cfg(feature = "terminal-tui")] +use crate::channels::TerminalChannel; +#[cfg(feature = "terminal-tui")] +use crate::channels::sanitize_channel_response; +#[cfg(feature = "terminal-tui")] +use crate::config::Config; +#[cfg(feature = "terminal-tui")] +use crate::llm::route_decision::ProviderExecutionOutcome; +#[cfg(feature = "terminal-tui")] +use crate::llm::route_decision::RouteDecision; +#[cfg(feature = "terminal-tui")] +use crate::memory::MemoryFabric; +#[cfg(feature = "terminal-tui")] +use crate::memory::MessageEventScope; +#[cfg(feature = "terminal-tui")] +use crate::providers::ChatMessage; +#[cfg(feature = "terminal-tui")] +use crate::tools::Tool; +#[cfg(feature = "terminal-tui")] +use std::sync::Arc; +#[cfg(feature = "terminal-tui")] +use std::time::Duration; +use tokio::sync::mpsc; +#[cfg(feature = "terminal-tui")] +use tokio_util::sync::CancellationToken; + +/// Queue depth for provider-turn lifecycle events (`HandleAttached`, `Started`, +/// `Exited`) travelling from the effect executor back to the chat loop. +/// +/// Sized as a backpressure valve, not a concurrency limit. Each turn emits +/// exactly three of these small, `Copy`-sized records, so this depth absorbs +/// roughly 1300 turns' worth of lifecycle traffic — far more than the chat loop +/// can fall behind by in practice, since it drains the queue at several points +/// in every iteration. If it ever does fill, the emitting turn parks on +/// `send().await` instead of the queue growing without bound; slowing turn +/// startup is the correct outcome, because the worker registry driving aborts +/// and completion routing must not fall arbitrarily far behind reality. +pub(crate) const PROVIDER_TURN_LIFECYCLE_CHANNEL_CAPACITY: usize = 4096; + +#[derive(Debug, Clone)] +pub(super) struct ProviderTurnCompletionEvent { + pub(super) task_id: crate::chat::turn_scheduler::TurnTaskId, + // Only the TUI completion waiter fills these and only the TUI finalizer + // reads them. + #[cfg(feature = "terminal-tui")] + pub(super) outcome: Option, + #[cfg(feature = "terminal-tui")] + pub(super) usage: crate::llm::route_decision::TokenUsage, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) struct ProviderTurnCompletionContext { + history_len_before_assistant: usize, +} + +#[cfg(feature = "terminal-tui")] +pub(super) struct PerTurnContext { + pub(super) _mailbox_input: Option, + pub(super) turn_binding: Option>, + pub(super) task_id: crate::chat::turn_scheduler::TurnTaskId, + pub(super) draft_id: String, + pub(super) delta_tx: Option>, + pub(super) tool_event_tx: Option>, + pub(super) draft_updater: Option>, + pub(super) tool_event_forwarder: Option>, + pub(super) user_input: String, + pub(super) turn_run_id: String, + pub(super) route_scope: MessageEventScope, + pub(super) route_decision: RouteDecision, + pub(super) provider_started_at: chrono::DateTime, + pub(super) provider_name: String, + pub(super) model_name: String, + pub(super) history_len_before_user_turn: usize, + /// The reducer's compaction epoch when the turn's provider view was + /// copied. A newer acknowledged epoch at commit means a worker compaction + /// ran during the turn, and the run loop's view is rebuilt from the + /// committed snapshot instead of being appended to. + pub(super) compaction_epoch_at_start: u64, + /// Set when this turn was started by daemon-assigned work, and carried all + /// the way to the commit because that is where the reply exists. + /// + /// A visible turn is *launched* by the main loop and finalized somewhere + /// else entirely, so a guard left behind in the loop body would report the + /// moment the turn started — an answer of "no reply" to work that was about + /// to produce one. Moving it into the context ties the report to the turn + /// rather than to the iteration that started it. + pub(super) assignment: Option, +} + +#[cfg(feature = "terminal-tui")] +pub(super) struct PendingOrderedProviderTurnCommit { + pub(super) context: PerTurnContext, + pub(super) terminal_plan: ProviderTurnTerminalPlan, +} + +#[derive(Debug)] +#[cfg(feature = "terminal-tui")] +pub(super) struct ResolvedProviderTurnCompletion { + pub(super) outcome: Option, + pub(super) usage: crate::llm::route_decision::TokenUsage, +} + +#[derive(Debug, Clone)] +#[cfg(feature = "terminal-tui")] +pub(super) enum ProviderTurnTerminalPlan { + Completed { + final_text: String, + reasoning: String, + recorded_response: String, + empty_response: bool, + usage: crate::llm::route_decision::TokenUsage, + history_commit_len: usize, + final_text_chars: usize, + recorded_response_chars: usize, + summary: &'static str, + }, + Failed { + err: String, + history_commit_len: usize, + summary: String, + }, + Cancelled { + summary: &'static str, + }, +} + +#[cfg(feature = "terminal-tui")] +#[derive(Debug, Clone)] +pub(super) struct ProviderTurnFinalizerEvent { + pub(super) task_id: Option, + pub(super) plan: ProviderTurnTerminalPlan, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg(feature = "terminal-tui")] +pub(super) struct ProviderTurnFinalizerResult { + pub(super) task_id: Option, + pub(super) terminal_status: &'static str, + pub(super) finalized: bool, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub(super) struct ProviderTurnVisibleAdmission { + pub(super) active_workers: usize, + pub(super) foreground_active: usize, + pub(super) detached_active: usize, + pub(super) effective_max_visible_turns: usize, + pub(super) can_start_visible: bool, +} + +#[cfg(feature = "terminal-tui")] +pub(super) enum ProviderTurnTerminalGate<'a> { + Completed { + history_commit_len: usize, + final_text_chars: usize, + recorded_response_chars: usize, + usage: &'a crate::llm::route_decision::TokenUsage, + summary: &'static str, + }, + Failed { + history_commit_len: usize, + summary: String, + }, + Cancelled { + summary: &'static str, + }, +} + +pub(super) fn provider_worker_status( + workers: &crate::chat::turn_worker::ProviderTurnWorkerRegistry, +) -> crate::chat::action::ProviderWorkerStatus { + use crate::chat::action::{ProviderWorkerRowKind, ProviderWorkerRowState, ProviderWorkerStatusRow}; + + let mut status = crate::chat::action::ProviderWorkerStatus::default(); + for worker in workers.snapshot() { + if worker.finalized_payload_ready { + status.finalized_payloads = status.finalized_payloads.saturating_add(1); + status.finalized_total_tokens = status + .finalized_total_tokens + .saturating_add(worker.finalized_total_tokens.unwrap_or_default()); + } + let row_state = match worker.state { + crate::chat::turn_worker::ProviderTurnWorkerState::Running => ProviderWorkerRowState::Running, + crate::chat::turn_worker::ProviderTurnWorkerState::Cancelling => ProviderWorkerRowState::Cancelling, + crate::chat::turn_worker::ProviderTurnWorkerState::AwaitingCommit(_) => { + ProviderWorkerRowState::AwaitingCommit + } + crate::chat::turn_worker::ProviderTurnWorkerState::Committed => ProviderWorkerRowState::Committed, + crate::chat::turn_worker::ProviderTurnWorkerState::Cancelled => ProviderWorkerRowState::Cancelled, + crate::chat::turn_worker::ProviderTurnWorkerState::Failed => ProviderWorkerRowState::Failed, + }; + if !worker.state.is_terminal() || worker.finalized_payload_ready { + let row_kind = match worker.kind { + crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited => { + ProviderWorkerRowKind::ForegroundAwaited + } + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached => ProviderWorkerRowKind::Detached, + }; + status.rows.push(ProviderWorkerStatusRow { + task_id: worker.task_id.get(), + sequence: worker.sequence, + kind: row_kind, + state: row_state, + started_at_ms: worker.started_at_ms, + finalized_total_tokens: worker.finalized_total_tokens, + completion_ready: worker.completion_ready, + recent_tool_call: None, + }); + } + match worker.state { + crate::chat::turn_worker::ProviderTurnWorkerState::Running => { + status.running = status.running.saturating_add(1); + status.oldest_started_at_ms = Some( + status + .oldest_started_at_ms + .map_or(worker.started_at_ms, |current| current.min(worker.started_at_ms)), + ); + } + crate::chat::turn_worker::ProviderTurnWorkerState::Cancelling => { + status.cancelling = status.cancelling.saturating_add(1); + status.oldest_started_at_ms = Some( + status + .oldest_started_at_ms + .map_or(worker.started_at_ms, |current| current.min(worker.started_at_ms)), + ); + } + crate::chat::turn_worker::ProviderTurnWorkerState::AwaitingCommit(_) => { + status.awaiting_commit = status.awaiting_commit.saturating_add(1); + } + crate::chat::turn_worker::ProviderTurnWorkerState::Committed + | crate::chat::turn_worker::ProviderTurnWorkerState::Cancelled + | crate::chat::turn_worker::ProviderTurnWorkerState::Failed => {} + } + } + status +} + +pub(super) fn publish_provider_worker_status( + chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, + workers: &crate::chat::turn_worker::ProviderTurnWorkerRegistry, +) { + let _ = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::ProviderWorkerStatusUpdated { + status: provider_worker_status(workers), + }, + "chat.provider_worker_status_updated", + ); +} + +pub(super) fn provider_turn_visible_admission( + workers: &crate::chat::turn_worker::ProviderTurnWorkerRegistry, + target_kind: crate::chat::turn_worker::ProviderTurnWorkerKind, + max_concurrent_visible_turns: usize, +) -> ProviderTurnVisibleAdmission { + let effective_max_visible_turns = max_concurrent_visible_turns.max(1); + let active_rows: Vec<_> = workers + .snapshot() + .into_iter() + .filter(|worker| { + matches!( + worker.state, + crate::chat::turn_worker::ProviderTurnWorkerState::Running + | crate::chat::turn_worker::ProviderTurnWorkerState::Cancelling + | crate::chat::turn_worker::ProviderTurnWorkerState::AwaitingCommit(_) + ) + }) + .collect(); + let active_workers = active_rows.len(); + let foreground_active = active_rows + .iter() + .filter(|worker| worker.kind == crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited) + .count(); + let detached_active = active_rows + .iter() + .filter(|worker| worker.kind == crate::chat::turn_worker::ProviderTurnWorkerKind::Detached) + .count(); + let can_start_visible = match target_kind { + crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited => active_workers == 0, + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached => { + foreground_active == 0 && detached_active < effective_max_visible_turns + } + }; + ProviderTurnVisibleAdmission { + active_workers, + foreground_active, + detached_active, + effective_max_visible_turns, + can_start_visible, + } +} + +fn drain_provider_turn_lifecycle_events( + rx: &mut mpsc::Receiver, + events_open: &mut bool, + workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, +) -> bool { + if !*events_open { + return false; + } + + let mut drained = false; + loop { + match rx.try_recv() { + Ok(event) => { + drained = true; + record_provider_turn_lifecycle_event(workers, event); + } + Err(mpsc::error::TryRecvError::Empty) => return drained, + Err(mpsc::error::TryRecvError::Disconnected) => { + *events_open = false; + return drained; + } + } + } +} + +pub(super) fn record_provider_turn_lifecycle_event( + workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, + event: dispatcher::ProviderTurnLifecycleEvent, +) { + use crate::chat::turn_worker::ProviderTurnWorkerError; + let (task_id, lease_id, kind, result): ( + crate::chat::turn_scheduler::TurnTaskId, + u64, + &'static str, + Result<(), ProviderTurnWorkerError>, + ) = match event { + dispatcher::ProviderTurnLifecycleEvent::HandleAttached { + task_id, + lease_id, + abort_handle, + } => { + let result = workers.attach_execution_handle(task_id, lease_id, abort_handle); + (task_id, lease_id, "handle_attached", result) + } + dispatcher::ProviderTurnLifecycleEvent::Started { task_id, lease_id } => { + let result = workers.record_execution_started(task_id, lease_id); + (task_id, lease_id, "started", result) + } + dispatcher::ProviderTurnLifecycleEvent::FailureRequested { + task_id, + lease_id, + accepted, + } => { + let result = workers.record_execution_failed(task_id, lease_id); + if accepted.send(result.is_ok()).is_err() { + tracing::debug!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), + lease_id, + "provider worker supervisor left before the failure answer" + ); + } + if let Err(error) = result { + // Expected when the turn already produced its terminal: the + // failure gate refuses and the turn keeps its outcome. + tracing::debug!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), + lease_id, + error = %crate::agent::diagnostics::error_class(&error), + "provider worker failure refused" + ); + } + return; + } + dispatcher::ProviderTurnLifecycleEvent::Exited { task_id, lease_id } => { + let result = workers.record_execution_exited(task_id, lease_id); + if let Err(ProviderTurnWorkerError::UnknownWorker(_)) = result { + tracing::debug!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), + lease_id, + "provider worker exit for a retired task" + ); + return; + } + (task_id, lease_id, "exited", result) + } + }; + if let Err(error) = result { + tracing::warn!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), + lease_id, + kind, + error = %crate::agent::diagnostics::error_class(&error), + "ProviderTurnWorkerRegistry provider execution lifecycle record failed" + ); + } +} + +fn record_provider_turn_completion_ready( + workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, + task_id: crate::chat::turn_scheduler::TurnTaskId, +) { + if let Err(error) = workers.record_completion_ready(task_id) { + tracing::warn!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), + error = %crate::agent::diagnostics::error_class(&error), + "ProviderTurnWorkerRegistry provider completion-ready gate failed" + ); + } +} + +pub(super) fn route_provider_completion_event( + lifecycle_rx: &mut mpsc::Receiver, + lifecycle_events_open: &mut bool, + workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, + pending: &mut std::collections::HashMap, + current_task_id: Option, + completion: ProviderTurnCompletionEvent, +) -> Option { + if drain_provider_turn_lifecycle_events(lifecycle_rx, lifecycle_events_open, workers) { + tracing::trace!( + task_id = completion.task_id.get(), + "drained provider lifecycle events before routing completion" + ); + } + let task_id = completion.task_id; + record_provider_turn_completion_ready(workers, task_id); + if Some(task_id) == current_task_id { + return Some(completion); + } + if pending.insert(task_id, completion).is_some() { + tracing::warn!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), + "replaced duplicate pending provider completion event" + ); + } + None +} + +pub(super) fn route_provider_completion_event_and_publish( + lifecycle_rx: &mut mpsc::Receiver, + lifecycle_events_open: &mut bool, + workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, + pending: &mut std::collections::HashMap, + current_task_id: Option, + completion: ProviderTurnCompletionEvent, + chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, +) -> Option { + let route = route_provider_completion_event( + lifecycle_rx, + lifecycle_events_open, + workers, + pending, + current_task_id, + completion, + ); + publish_provider_worker_status(chat_dispatcher, workers); + route +} + +pub(super) fn record_provider_turn_completion_context( + contexts: &mut std::collections::HashMap, + task_id: Option, + history_len_before_assistant: usize, +) { + if let Some(task_id) = task_id + && contexts + .insert( + task_id, + ProviderTurnCompletionContext { + history_len_before_assistant, + }, + ) + .is_some() + { + tracing::warn!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), + "replaced duplicate provider turn completion context" + ); + } +} + +#[cfg(feature = "terminal-tui")] +pub(super) fn take_provider_turn_completion_history_len( + contexts: &mut std::collections::HashMap, + task_id: Option, + fallback_history_len: usize, +) -> usize { + task_id + .and_then(|task_id| contexts.remove(&task_id)) + .map_or(fallback_history_len, |context| context.history_len_before_assistant) +} + +#[cfg(feature = "terminal-tui")] +fn provider_turn_finalized_payload_from_usage( + history_commit_len: usize, + final_text_chars: usize, + recorded_response_chars: usize, + usage: &crate::llm::route_decision::TokenUsage, +) -> crate::chat::turn_worker::ProviderTurnFinalizedPayload { + let prompt_tokens = usage.prompt_tokens.map_or(0, u64::from); + let completion_tokens = usage.completion_tokens.map_or(0, u64::from); + let total_tokens = usage + .total_tokens + .map_or_else(|| prompt_tokens.saturating_add(completion_tokens), u64::from); + crate::chat::turn_worker::ProviderTurnFinalizedPayload { + history_commit_len, + final_text_chars, + recorded_response_chars, + total_tokens, + prompt_tokens, + completion_tokens, + } +} + +#[cfg(feature = "terminal-tui")] +fn record_provider_turn_finalized_payload( + workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, + id: Option, + payload: crate::chat::turn_worker::ProviderTurnFinalizedPayload, +) -> bool { + let Some(id) = id else { + tracing::warn!("ProviderTurnWorkerRegistry missing provider task for finalized payload"); + return false; + }; + if let Err(error) = workers.record_finalized_payload(id, payload) { + tracing::warn!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), + error = %crate::agent::diagnostics::error_class(&error), + "ProviderTurnWorkerRegistry provider finalized payload record failed" + ); + return false; + } + true +} + +#[cfg(feature = "terminal-tui")] +pub(super) fn gate_completed_provider_turn_finalization( + scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, + coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, + workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, + id: Option, + history_commit_len: usize, + final_text_chars: usize, + recorded_response_chars: usize, + usage: &crate::llm::route_decision::TokenUsage, + summary: &'static str, +) -> Vec { + let finalized_payload = provider_turn_finalized_payload_from_usage( + history_commit_len, + final_text_chars, + recorded_response_chars, + usage, + ); + if !record_provider_turn_finalized_payload(workers, id, finalized_payload) { + return Vec::new(); + } + mark_provider_turn_completed(scheduler, coordinator, workers, id, history_commit_len, summary) +} + +/// Finalized payload of a turn the non-TUI tool loop completed inline. +pub(super) fn inline_provider_turn_payload( + history_commit_len: usize, + response_chars: usize, + usage: Option<&crate::chat::session::MainSessionTokenUsageRecord>, +) -> crate::chat::turn_worker::ProviderTurnFinalizedPayload { + crate::chat::turn_worker::ProviderTurnFinalizedPayload { + history_commit_len, + final_text_chars: response_chars, + recorded_response_chars: response_chars, + total_tokens: usage.map_or(0, |usage| usage.total_tokens), + prompt_tokens: usage.map_or(0, |usage| usage.prompt_tokens), + completion_tokens: usage.map_or(0, |usage| usage.completion_tokens), + } +} + +/// The non-TUI tool loop awaited provider turn `id` inline and reached its +/// terminal. Records the inline execution as complete and, for a completed +/// turn, its finalized payload, so the terminal mark that follows commits the +/// worker and frees the visible-turn slot (without it the worker stays +/// `Running` and every later input, `/exit` included, waits for a slot). +pub(super) fn finish_inline_provider_turn( + workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, + id: Option, + payload: Option, +) { + let Some(id) = id else { + return; + }; + if let Err(error) = workers.record_inline_completion_ready(id) { + tracing::warn!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), + error = %crate::agent::diagnostics::error_class(&error), + "ProviderTurnWorkerRegistry inline provider completion failed" + ); + return; + } + if let Some(payload) = payload + && let Err(error) = workers.record_finalized_payload(id, payload) + { + tracing::warn!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), + error = %crate::agent::diagnostics::error_class(&error), + "ProviderTurnWorkerRegistry inline provider finalized payload record failed" + ); + } +} + +pub(super) fn gate_failed_provider_turn_finalization( + scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, + coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, + workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, + id: Option, + history_commit_len: usize, + summary: impl Into, +) -> Vec { + mark_provider_turn_failed(scheduler, coordinator, workers, id, history_commit_len, summary) +} + +pub(super) fn gate_cancelled_provider_turn_finalization( + scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, + coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, + workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, + id: Option, + summary: &'static str, +) -> Vec { + mark_provider_turn_cancelled(scheduler, coordinator, workers, id, summary) +} + +#[allow(clippy::option_if_let_else)] +#[cfg(feature = "terminal-tui")] +pub(super) fn resolve_provider_turn_completion( + turn_signal: &dispatcher::TurnCompletionSignal, + task_id: Option, + completion_event: Option, +) -> ResolvedProviderTurnCompletion { + let outcome = if let Some(completion) = completion_event.as_ref() { + completion.outcome.clone().or_else(|| turn_signal.consume_outcome()) + } else if let Some(id) = task_id { + turn_signal + .consume_turn_outcome(id) + .or_else(|| turn_signal.consume_outcome()) + } else { + turn_signal.consume_outcome() + }; + let usage = if let Some(completion) = completion_event { + if completion.usage.has_any_tokens() { + completion.usage + } else { + turn_signal.consume_usage() + } + } else if let Some(id) = task_id { + let keyed_usage = turn_signal.consume_turn_usage(id); + if keyed_usage.has_any_tokens() { + keyed_usage + } else { + turn_signal.consume_usage() + } + } else { + turn_signal.consume_usage() + }; + if let Some(id) = task_id { + turn_signal.unregister_turn(id); + } + ResolvedProviderTurnCompletion { outcome, usage } +} + +#[cfg(feature = "terminal-tui")] +pub(super) fn provider_turn_terminal_plan_from_completion( + resolved: ResolvedProviderTurnCompletion, + history_len: usize, + tools_registry: &[Box], +) -> ProviderTurnTerminalPlan { + match resolved.outcome { + Some(dispatcher::TurnOutcomeKind::Completed { final_text, reasoning }) => { + let mut usage = resolved.usage; + if !usage.has_any_tokens() { + let accumulator = crate::llm::route_decision::ProviderUsageAccumulator::new(); + usage = accumulator.finish_or_estimate_completion_chars(final_text.chars().count()); + } + if crate::agent::response_guard::is_empty_assistant_response(&final_text, false) { + ProviderTurnTerminalPlan::Completed { + final_text, + reasoning: String::new(), + recorded_response: String::new(), + empty_response: true, + usage, + history_commit_len: history_len, + final_text_chars: 0, + recorded_response_chars: 0, + summary: "redux driver completed with empty response", + } + } else { + let recorded_response = sanitize_channel_response(&final_text, tools_registry); + let final_text_chars = final_text.chars().count(); + let recorded_response_chars = recorded_response.chars().count(); + ProviderTurnTerminalPlan::Completed { + final_text, + reasoning, + final_text_chars, + recorded_response_chars, + recorded_response, + empty_response: false, + usage, + history_commit_len: history_len.saturating_add(1), + summary: "redux driver completed", + } + } + } + Some(dispatcher::TurnOutcomeKind::Failed { err, retryable: _ }) => ProviderTurnTerminalPlan::Failed { + summary: format!("redux driver failed: {err}"), + err, + history_commit_len: history_len, + }, + Some(dispatcher::TurnOutcomeKind::Cancelled) | None => ProviderTurnTerminalPlan::Cancelled { + summary: "redux driver cancelled", + }, + } +} + +#[cfg(feature = "terminal-tui")] +pub(super) fn gate_provider_turn_terminal_finalization( + scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, + coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, + workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, + id: Option, + gate: ProviderTurnTerminalGate<'_>, +) -> Vec { + match gate { + ProviderTurnTerminalGate::Completed { + history_commit_len, + final_text_chars, + recorded_response_chars, + usage, + summary, + } => gate_completed_provider_turn_finalization( + scheduler, + coordinator, + workers, + id, + history_commit_len, + final_text_chars, + recorded_response_chars, + usage, + summary, + ), + ProviderTurnTerminalGate::Failed { + history_commit_len, + summary, + } => gate_failed_provider_turn_finalization(scheduler, coordinator, workers, id, history_commit_len, summary), + ProviderTurnTerminalGate::Cancelled { summary } => { + gate_cancelled_provider_turn_finalization(scheduler, coordinator, workers, id, summary) + } + } +} + +#[cfg(feature = "terminal-tui")] +pub(super) fn finalize_provider_turn_from_event( + scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, + coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, + workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, + event: ProviderTurnFinalizerEvent, +) -> Vec { + let task_id = event.task_id; + let decisions = match event.plan { + ProviderTurnTerminalPlan::Completed { + usage, + history_commit_len, + final_text_chars, + recorded_response_chars, + summary, + .. + } => gate_provider_turn_terminal_finalization( + scheduler, + coordinator, + workers, + task_id, + ProviderTurnTerminalGate::Completed { + history_commit_len, + final_text_chars, + recorded_response_chars, + usage: &usage, + summary, + }, + ), + ProviderTurnTerminalPlan::Failed { + history_commit_len, + summary, + .. + } => gate_provider_turn_terminal_finalization( + scheduler, + coordinator, + workers, + task_id, + ProviderTurnTerminalGate::Failed { + history_commit_len, + summary, + }, + ), + ProviderTurnTerminalPlan::Cancelled { summary } => gate_provider_turn_terminal_finalization( + scheduler, + coordinator, + workers, + task_id, + ProviderTurnTerminalGate::Cancelled { summary }, + ), + }; + if decisions.is_empty() { + return vec![ProviderTurnFinalizerResult { + task_id, + terminal_status: "unknown", + finalized: false, + }]; + } + decisions + .iter() + .map(provider_turn_finalizer_result_from_commit_decision) + .collect() +} + +#[cfg(feature = "terminal-tui")] +const fn provider_turn_finalizer_result_from_commit_decision( + decision: &crate::chat::history_commit::HistoryCommitDecision, +) -> ProviderTurnFinalizerResult { + match decision { + crate::chat::history_commit::HistoryCommitDecision::Commit { task_id, .. } => ProviderTurnFinalizerResult { + task_id: Some(*task_id), + terminal_status: "completed", + finalized: true, + }, + crate::chat::history_commit::HistoryCommitDecision::Skip { task_id, status, .. } => { + ProviderTurnFinalizerResult { + task_id: Some(*task_id), + terminal_status: match status { + crate::chat::history_commit::HistoryCommitStatus::Completed => "completed", + crate::chat::history_commit::HistoryCommitStatus::Cancelled => "cancelled", + crate::chat::history_commit::HistoryCommitStatus::Failed => "failed", + }, + finalized: true, + } + } + } +} + +#[cfg(feature = "terminal-tui")] +pub(super) fn enqueue_provider_turn_finalizer_event( + queue: &mut std::collections::VecDeque, + task_id: Option, + plan: ProviderTurnTerminalPlan, +) { + queue.push_back(ProviderTurnFinalizerEvent { task_id, plan }); +} + +/// The terminal action of an ordered provider-turn commit. +#[derive(Debug, Clone, Copy)] +pub(super) enum OrderedCommitTerminal<'a> { + /// TUI: `StreamCompleted` for the visible draft, acknowledged through the + /// task-scoped turn signal. + #[cfg(feature = "terminal-tui")] + StreamCompleted { draft_id: &'a str, reasoning: &'a str }, + /// Non-TUI: `TurnCommitRequested`, acknowledged through + /// `dispatch_awaited` (keyed by the task). + TurnCommitRequested { draft_id: Option<&'a str> }, +} + +/// Queue the turn's history records (user turn when `record_user`, then the +/// assistant turn unless the reply is empty) ahead of its terminal action. +fn dispatch_ordered_turn_records( + chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, + task_id: crate::chat::turn_scheduler::TurnTaskId, + user_input: &str, + final_text: &str, + empty_response: bool, + record_user: bool, +) -> std::result::Result<(), String> { + if record_user { + let result = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::RecordUserTurn(user_input.to_string()), + "chat.ordered_record_user_turn", + ); + if !matches!(result, dispatcher::DispatchResult::Sent) { + return Err(format!("ordered history dispatch failed: {result:?}")); + } + } + if !empty_response { + let result = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::RecordAssistantTurn { + task_id: Some(task_id), + content: final_text.to_string(), + }, + "chat.ordered_record_assistant_turn", + ); + if !matches!(result, dispatcher::DispatchResult::Sent) { + return Err(format!("ordered history dispatch failed: {result:?}")); + } + } + Ok(()) +} + +#[cfg(feature = "terminal-tui")] +pub(super) fn dispatch_ordered_provider_turn_commit( + chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, + task_id: crate::chat::turn_scheduler::TurnTaskId, + draft_id: &str, + user_input: &str, + final_text: &str, + reasoning: &str, + empty_response: bool, + record_user: bool, +) -> std::result::Result<(), String> { + dispatch_ordered_turn_records( + chat_dispatcher, + task_id, + user_input, + final_text, + empty_response, + record_user, + )?; + let result = chat_dispatcher.dispatch_or_log( + crate::chat::action::Action::StreamCompleted { + draft_id: draft_id.to_string(), + final_text: final_text.to_string(), + reasoning: reasoning.to_string(), + }, + "chat.ordered_stream_completed", + ); + if !matches!(result, dispatcher::DispatchResult::Sent) { + return Err(format!("ordered history dispatch failed: {result:?}")); + } + Ok(()) +} + +pub(super) async fn dispatch_ordered_provider_turn_commit_and_wait( + chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, + turn_signal: &dispatcher::TurnCompletionSignal, + task_id: crate::chat::turn_scheduler::TurnTaskId, + terminal: OrderedCommitTerminal<'_>, + user_input: &str, + final_text: &str, + empty_response: bool, + record_user: bool, +) -> std::result::Result<(), String> { + let result = match terminal { + #[cfg(feature = "terminal-tui")] + OrderedCommitTerminal::StreamCompleted { draft_id, reasoning } => { + dispatch_stream_completed_commit_and_wait( + chat_dispatcher, + turn_signal, + task_id, + draft_id, + user_input, + final_text, + reasoning, + empty_response, + record_user, + ) + .await + } + OrderedCommitTerminal::TurnCommitRequested { draft_id } => { + dispatch_turn_commit_requested_and_wait( + chat_dispatcher, + turn_signal, + task_id, + draft_id, + user_input, + final_text, + empty_response, + record_user, + ) + .await + } + }; + if result.is_ok() { + turn_signal.record_history_commit(task_id); + } + result +} + +/// TUI ordered commit: the records, then `StreamCompleted`, acknowledged by +/// the dispatcher's second task-scoped turn-signal notification. +#[cfg(feature = "terminal-tui")] +#[allow(clippy::too_many_arguments)] +async fn dispatch_stream_completed_commit_and_wait( + chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, + turn_signal: &dispatcher::TurnCompletionSignal, + task_id: crate::chat::turn_scheduler::TurnTaskId, + draft_id: &str, + user_input: &str, + final_text: &str, + reasoning: &str, + empty_response: bool, + record_user: bool, +) -> std::result::Result<(), String> { + // The first task-scoped notification means the provider produced its + // terminal payload. The ordered StreamCompleted below is a distinct phase: + // the dispatcher only emits its second notification after every reducer + // effect, including SaveSession, has completed. Arm the waiter before + // dispatch so the latch-less Notify cannot be missed. + // Provider completion consumption unregisters the first-phase slot. Open + // a fresh slot for the same task/draft so the ordered reducer commit has + // its own acknowledgement lifecycle. + turn_signal.register_turn(task_id, draft_id.to_string()); + let Some(persistence_committed) = turn_signal.notified_for(task_id) else { + tracing::error!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), + "missing task-scoped persistence waiter" + ); + turn_signal.fail_history_commit("missing task-scoped persistence waiter"); + return Err("missing task-scoped persistence waiter".to_string()); + }; + if let Err(error) = dispatch_ordered_provider_turn_commit( + chat_dispatcher, + task_id, + draft_id, + user_input, + final_text, + reasoning, + empty_response, + record_user, + ) { + turn_signal.unregister_turn(task_id); + turn_signal.fail_history_commit(error.clone()); + return Err(error); + } + let result = match tokio::time::timeout(Duration::from_secs(30), persistence_committed).await { + Ok(()) => { + // Consume the second terminal outcome so a later waiter cannot + // mistake this persistence acknowledgement for a provider result. + let outcome = turn_signal.consume_turn_outcome(task_id); + turn_signal.unregister_turn(task_id); + match outcome { + Some(dispatcher::TurnOutcomeKind::Completed { .. }) => Ok(()), + Some(dispatcher::TurnOutcomeKind::Failed { err, .. }) => Err(err), + Some(dispatcher::TurnOutcomeKind::Cancelled) => { + Err("ordered session persistence was cancelled".to_string()) + } + None => Err("ordered session persistence acknowledged without an outcome".to_string()), + } + } + Err(_) => { + tracing::error!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), + "timed out waiting for ordered session persistence" + ); + turn_signal.unregister_turn(task_id); + Err("timed out waiting for ordered session persistence".to_string()) + } + }; + if let Err(error) = &result { + turn_signal.fail_history_commit(error.clone()); + } + result +} + +/// Non-TUI ordered commit: the records, then `TurnCommitRequested` awaited +/// through the acknowledged-session barrier. Any failure latches the +/// unconfirmed-commit stop. +#[allow(clippy::too_many_arguments)] +async fn dispatch_turn_commit_requested_and_wait( + chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, + turn_signal: &dispatcher::TurnCompletionSignal, + task_id: crate::chat::turn_scheduler::TurnTaskId, + draft_id: Option<&str>, + user_input: &str, + final_text: &str, + empty_response: bool, + record_user: bool, +) -> std::result::Result<(), String> { + if let Err(error) = dispatch_ordered_turn_records( + chat_dispatcher, + task_id, + user_input, + final_text, + empty_response, + record_user, + ) { + turn_signal.fail_history_commit(error.clone()); + return Err(error); + } + let ack = chat_dispatcher + .dispatch_awaited( + crate::chat::action::Action::TurnCommitRequested { + task_id, + draft_id: draft_id.map(str::to_owned), + }, + turn_signal, + ) + .await + .map_err(|error| error.to_string())?; + match ack { + crate::chat::acked_session::Ack::Published(_) => Ok(()), + crate::chat::acked_session::Ack::Unchanged(_) => { + let error = "turn commit was acknowledged without a saved revision".to_owned(); + turn_signal.fail_history_commit(error.clone()); + Err(error) + } + crate::chat::acked_session::Ack::Rejected(reason) => { + turn_signal.fail_history_commit(reason.clone()); + Err(reason) + } + } +} + +#[cfg(feature = "terminal-tui")] +#[allow(clippy::too_many_arguments)] +async fn commit_completed_provider_turn( + pending_commit: PendingOrderedProviderTurnCommit, + history: &mut Vec, + turn_scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, + provider_turn_workers: &crate::chat::turn_worker::ProviderTurnWorkerRegistry, + chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, + terminal: &Arc, + memory_fabric: &MemoryFabric, + chat_session_key: &str, + config: &Config, + sessions_redraw_handle: Option<&mpsc::Sender<()>>, + redraw_tx_for_main: Option<&mpsc::Sender<()>>, + turn_signal: &dispatcher::TurnCompletionSignal, +) -> bool { + let mut pending = pending_commit.context; + let ProviderTurnTerminalPlan::Completed { + final_text, + reasoning, + recorded_response, + empty_response, + usage: redux_tokens_used, + history_commit_len, + .. + } = pending_commit.terminal_plan + else { + tracing::warn!( + task_id = pending.task_id.get(), + "ordered provider turn commit received non-completed terminal plan" + ); + return false; + }; + + let provider_turn_task_id = Some(pending.task_id); + // Provider trace capture seals execution authority before this ordered + // finalizer runs. Re-reading the live disposition here would therefore + // reject every successful provider-backed turn. Use the immutable + // pre-execution classification carried with the turn instead. + let (provider_outcome, terminal_usage) = { + let provider_outcome = if let Some(binding) = pending.turn_binding.as_ref() { + match binding.provider_outcome(&pending.route_decision, pending.provider_started_at) { + Ok(outcome) => outcome, + Err(error) => { + tracing::error!(error = %crate::agent::diagnostics::error_class(&error), "Chat completion has no authenticated provider trace"); + return false; + } + } + } else { + ProviderExecutionOutcome::success_for_decision_with_usage( + &pending.route_decision, + pending.provider_started_at, + redux_tokens_used.clone(), + ) + }; + let terminal_usage = match finalize_chat_success_turn( + pending.turn_binding.as_deref(), + memory_fabric, + chat_session_key, + &pending.turn_run_id, + &pending.provider_name, + &pending.model_name, + pending.route_scope.clone(), + provider_outcome.clone(), + (!empty_response).then(|| recorded_response.clone()), + history_commit_len, + if empty_response { + "redux driver completed with empty response" + } else { + "redux driver completed" + }, + &config.cost, + &config.workspace_dir, + ) + .await + { + Ok(receipt) => receipt.into_session_usage(), + Err(error) => { + tracing::error!(error = %crate::agent::diagnostics::error_class(&error), "Chat terminal persistence is unconfirmed"); + return false; + } + }; + (Some(provider_outcome), terminal_usage) + }; + let finished_at = provider_outcome + .as_ref() + .map_or_else(chrono::Utc::now, |outcome| outcome.finished_at); + if empty_response { + if let Err(e) = terminal.cancel_draft("user", &pending.draft_id).await { + tracing::debug!(error = %crate::agent::diagnostics::error_class(&e), "Redux driver: cancel empty-response draft failed"); + } + // Metered usage goes in before the commit: same-channel FIFO puts it + // in the commit's acknowledged revision, and it is recorded even if + // the commit then fails, because the provider charged it. + if let Err(error) = dispatch_final_usage( + chat_dispatcher, + turn_signal, + turn_scheduler, + provider_turn_task_id, + terminal_usage, + "chat.provider_usage_recorded_empty_response", + ) + .await + { + surface_session_message( + chat_dispatcher, + sessions_redraw_handle, + &format!("Session persistence failed; dependent commands remain blocked: {error}"), + ); + return false; + } + if let Some(tx) = redraw_tx_for_main { + let _ = tx.try_send(()); + } + let persistence_result = dispatch_ordered_provider_turn_commit_and_wait( + chat_dispatcher, + turn_signal, + pending.task_id, + OrderedCommitTerminal::StreamCompleted { + draft_id: &pending.draft_id, + reasoning: &reasoning, + }, + &pending.user_input, + &final_text, + empty_response, + true, + ) + .await; + if let Err(error) = persistence_result { + surface_session_message( + chat_dispatcher, + sessions_redraw_handle, + &format!("Session persistence failed; dependent commands remain blocked: {error}"), + ); + return false; + } + if let Some(guard) = pending.assignment.as_mut() { + guard.failed("The turn finished without reply text."); + } + adopt_committed_turn(history, chat_dispatcher, &pending, None); + surface_turn_elapsed_message( + chat_dispatcher, + sessions_redraw_handle, + "completed", + pending.provider_started_at, + finished_at, + ); + publish_main_queue_status(chat_dispatcher, turn_scheduler); + publish_provider_worker_status(chat_dispatcher, provider_turn_workers); + return true; + } + + if let Err(error) = dispatch_final_usage( + chat_dispatcher, + turn_signal, + turn_scheduler, + provider_turn_task_id, + terminal_usage, + "chat.provider_usage_recorded", + ) + .await + { + surface_session_message( + chat_dispatcher, + sessions_redraw_handle, + &format!("Session persistence failed; dependent commands remain blocked: {error}"), + ); + return false; + } + if let Some(tx) = redraw_tx_for_main { + let _ = tx.try_send(()); + } + let persistence_result = dispatch_ordered_provider_turn_commit_and_wait( + chat_dispatcher, + turn_signal, + pending.task_id, + OrderedCommitTerminal::StreamCompleted { + draft_id: &pending.draft_id, + reasoning: &reasoning, + }, + &pending.user_input, + &final_text, + empty_response, + true, + ) + .await; + if let Err(error) = persistence_result { + surface_session_message( + chat_dispatcher, + sessions_redraw_handle, + &format!("Session persistence failed; dependent commands remain blocked: {error}"), + ); + return false; + } + adopt_committed_turn(history, chat_dispatcher, &pending, Some(&final_text)); + if let Err(e) = terminal.finalize_draft("user", &pending.draft_id, &final_text).await { + tracing::warn!(error = %crate::agent::diagnostics::error_class(&e), "Redux driver: finalize_draft failed"); + } + if let Some(provider_outcome) = provider_outcome.as_ref() { + let attempts_count = u8::try_from(provider_outcome.attempts.len()).unwrap_or(u8::MAX); + crate::runtime::control_ladder::append_provider_outcome_trace( + std::path::Path::new(&config.workspace_dir), + &provider_outcome.decision_id, + &provider_outcome.final_provider, + &provider_outcome.final_model, + attempts_count, + "success", + ); + } + if let Some(guard) = pending.assignment.as_mut() { + guard.completed(&recorded_response); + } + surface_turn_elapsed_message( + chat_dispatcher, + sessions_redraw_handle, + "completed", + pending.provider_started_at, + finished_at, + ); + publish_main_queue_status(chat_dispatcher, turn_scheduler); + publish_provider_worker_status(chat_dispatcher, provider_turn_workers); + true +} + +/// Bring the run loop's provider view up to an acknowledged turn commit, so +/// it equals the view rebuilt from the committed snapshot +/// ([`super::compaction::provider_view_from_acked`]). Without a compaction +/// since the turn copied its view, the committed request and reply are +/// appended; the request is the plain stored text, never the enriched form +/// the turn sent (only a request still being sent carries its recalled +/// context and attached files). After a worker compaction the view is rebuilt +/// from the committed snapshot instead: appending to the pre-compaction view +/// would resend the replaced cold prefix and force another rollover or a lossy +/// fallback on the next turn. +#[cfg(feature = "terminal-tui")] +fn adopt_committed_turn( + history: &mut Vec, + chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, + pending: &PerTurnContext, + reply: Option<&str>, +) { + let acked = chat_dispatcher.session_reader().acked(); + if acked.compaction_epoch != pending.compaction_epoch_at_start { + let view = super::compaction::provider_view_from_acked(history, &acked); + tracing::info!( + task_id = pending.task_id.get(), + messages_before = history.len(), + messages_after = view.len(), + "provider view rebuilt from the committed snapshot after a worker compaction" + ); + *history = view; + return; + } + history.push(crate::agent::turn_contracts::inbound_user_message(&pending.user_input)); + if let Some(reply) = reply { + history.push(committed_reply_message(&acked, reply)); + } +} + +/// The provider-view message of a committed reply: `reply` rendered with the +/// tool evidence of the snapshot's newest turn when that turn is this reply +/// (an `assistant` turn holding exactly `reply`); otherwise the bare reply, +/// since evidence that cannot be tied to the reply is never attached to it. +/// A reply that is a context handoff passes through the handoff renderer +/// first, as on every other provider-view path. +#[cfg(feature = "terminal-tui")] +pub(super) fn committed_reply_message(acked: &crate::chat::acked_session::AckedSession, reply: &str) -> ChatMessage { + let evidence = acked + .session + .turns + .last() + .filter(|turn| turn.role == "assistant" && turn.content == reply) + .map(|turn| turn.tool_evidence.as_ref()); + if evidence.is_none() { + tracing::debug!("committed reply is not the snapshot's newest assistant turn; replayed without tool evidence"); + } + let reply = crate::agent::compaction::render_context_handoff_for_provider("assistant", reply); + ChatMessage::assistant( + crate::agent::tool_evidence::render_assistant_content(&reply, evidence.flatten()).into_owned(), + ) +} + +/// A worker turn that failed or was cancelled: settled in order after the +/// worker's compactions and terminal action (the reducer never recorded a +/// worker turn's request, so none is removed), then the provider view follows +/// the settled revision. The epoch the turn's view was copied at is from +/// before the worker's detached switch and every in-turn compaction. A failed +/// settlement is already latched; the run loop's health check stops the chat. +#[cfg(feature = "terminal-tui")] +async fn settle_aborted_worker_turn( + history: &mut Vec, + chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, + commits: &dispatcher::TurnCompletionSignal, + pending: &PerTurnContext, + len_before_user_turn: Option, +) { + match settle_aborted_turn(chat_dispatcher, commits, None).await { + Ok(settled) => { + provider_view_after_settled_abort( + history, + &settled, + pending.compaction_epoch_at_start, + false, + len_before_user_turn, + ); + } + Err(_) => tracing::error!( + task_id = pending.task_id.get(), + "failed or cancelled worker turn was not settled; the history commit is latched as failed" + ), + } +} + +#[cfg(feature = "terminal-tui")] +#[allow(clippy::too_many_arguments)] +pub(super) async fn apply_ready_ordered_provider_turn_commits( + results: Vec, + pending_ordered_provider_turn_commits: &mut std::collections::HashMap< + crate::chat::turn_scheduler::TurnTaskId, + PendingOrderedProviderTurnCommit, + >, + history: &mut Vec, + turn_scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, + provider_turn_workers: &crate::chat::turn_worker::ProviderTurnWorkerRegistry, + chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, + terminal: &Arc, + memory_fabric: &MemoryFabric, + chat_session_key: &str, + config: &Config, + sessions_redraw_handle: Option<&mpsc::Sender<()>>, + redraw_tx_for_main: Option<&mpsc::Sender<()>>, + turn_signal: &dispatcher::TurnCompletionSignal, + plain_mode: bool, + plain_mode_turn_failed: &mut bool, +) -> bool { + let mut applied = false; + for result in results { + if turn_signal.ensure_history_commits_healthy().is_err() { + break; + } + if !result.finalized || result.terminal_status != "completed" { + continue; + } + let Some(task_id) = result.task_id else { + continue; + }; + let Some(pending_commit) = pending_ordered_provider_turn_commits.remove(&task_id) else { + tracing::debug!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), + "ordered provider turn commit ready before local payload was registered" + ); + continue; + }; + let committed = commit_completed_provider_turn( + pending_commit, + history, + turn_scheduler, + provider_turn_workers, + chat_dispatcher, + terminal, + memory_fabric, + chat_session_key, + config, + sessions_redraw_handle, + redraw_tx_for_main, + turn_signal, + ) + .await; + if !committed { + turn_signal.fail_history_commit(format!("ordered turn {} was not committed", task_id.get())); + if plain_mode { + *plain_mode_turn_failed = true; + } + break; + } + applied = true; + } + applied +} + +/// The failed provider attempt a decided turn's terminal records, as every +/// other entry records it; a policy refusal sent nothing, so it records none. +#[cfg(feature = "terminal-tui")] +fn failed_provider_outcome(pending: &PerTurnContext, err: &str) -> Option { + let binding = pending.turn_binding.as_ref()?; + let refused = matches!( + binding.failure_note(), + Some(crate::chat::binding::TurnFailureNote::Refused { .. }) + ); + (binding.is_decided() && !refused).then(|| { + ProviderExecutionOutcome::failed_for_decision( + &pending.route_decision, + pending.provider_started_at, + &anyhow::anyhow!("{err}"), + ) + }) +} + +#[cfg(feature = "terminal-tui")] +#[allow(clippy::too_many_arguments)] +async fn finalize_per_turn_context( + mut pending: PerTurnContext, + completion_event: Option, + pending_ordered_provider_turn_commits: &mut std::collections::HashMap< + crate::chat::turn_scheduler::TurnTaskId, + PendingOrderedProviderTurnCommit, + >, + turn_signal: &dispatcher::TurnCompletionSignal, + provider_turn_completion_contexts: &mut std::collections::HashMap< + crate::chat::turn_scheduler::TurnTaskId, + ProviderTurnCompletionContext, + >, + history: &mut Vec, + tools_registry: &[Box], + provider_turn_finalizer_events: &mut std::collections::VecDeque, + turn_scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, + history_commit_coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, + provider_turn_workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, + chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, + terminal: &Arc, + memory_fabric: &MemoryFabric, + chat_session_key: &str, + config: &Config, + sessions_redraw_handle: Option<&mpsc::Sender<()>>, + redraw_tx_for_main: Option<&mpsc::Sender<()>>, + plain_mode: bool, + plain_mode_turn_failed: &mut bool, +) { + let provider_turn_task_id = Some(pending.task_id); + let resolved_completion = resolve_provider_turn_completion(turn_signal, provider_turn_task_id, completion_event); + let completion_history_len = take_provider_turn_completion_history_len( + provider_turn_completion_contexts, + provider_turn_task_id, + history.len(), + ); + let terminal_plan = + provider_turn_terminal_plan_from_completion(resolved_completion, completion_history_len, tools_registry); + let history_len_before_user_turn: usize = pending.history_len_before_user_turn; + tracing::debug!( + task_id = pending.task_id.get(), + draft_id = %crate::agent::diagnostics::text_class(&pending.draft_id), + turn_run_id = %crate::agent::diagnostics::text_class(&pending.turn_run_id), + provider_name = %crate::security::redaction::redact_provider_text(&pending.provider_name), + model_name = %crate::security::redaction::redact_provider_text(&pending.model_name), + history_len_before_user_turn, + "finalizing provider turn context" + ); + enqueue_provider_turn_finalizer_event( + provider_turn_finalizer_events, + provider_turn_task_id, + terminal_plan.clone(), + ); + let finalizer_results = drain_provider_turn_finalizer_events_and_publish( + turn_scheduler, + history_commit_coordinator, + provider_turn_workers, + provider_turn_finalizer_events, + chat_dispatcher, + ); + + drop(pending.delta_tx.take()); + drop(pending.tool_event_tx.take()); + if let Some(handle) = pending.draft_updater.take() { + let _ = handle.await; + } + if let Some(handle) = pending.tool_event_forwarder.take() { + let _ = handle.await; + } + + match terminal_plan { + plan @ ProviderTurnTerminalPlan::Completed { .. } => { + let task_id = pending.task_id; + if pending_ordered_provider_turn_commits + .insert( + task_id, + PendingOrderedProviderTurnCommit { + context: pending, + terminal_plan: plan, + }, + ) + .is_some() + { + tracing::warn!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), + "replaced pending ordered provider turn commit payload" + ); + } + } + ProviderTurnTerminalPlan::Failed { err, .. } => { + if let Some(guard) = pending.assignment.as_mut() { + guard.failed(&format!("The turn this chat ran for the assignment failed: {err}")); + } + let provider_outcome = failed_provider_outcome(&pending, &err); + if let Err(error) = finalize_chat_non_success_turn( + pending.turn_binding.as_deref(), + memory_fabric, + &pending.turn_run_id, + pending.route_scope.clone(), + crate::agent::terminal::TurnTerminalStatus::Failed, + provider_outcome, + pending.provider_started_at, + &format!("redux driver failed: {err}"), + &config.cost, + &config.workspace_dir, + ) + .await + { + if pending + .turn_binding + .as_ref() + .is_some_and(|binding| binding.is_decided()) + { + *plain_mode_turn_failed = true; + } + tracing::warn!(error = %crate::agent::diagnostics::error_class(&error), "Failed to commit ordered failed Chat terminal event"); + } + settle_aborted_worker_turn(history, chat_dispatcher, turn_signal, &pending, None).await; + let interactive_tui_active = redraw_tx_for_main.is_some(); + if !interactive_tui_active { + let _ = terminal.cancel_draft("user", &pending.draft_id).await; + super::output::print_turn_failure(plain_mode, &err); + } + if plain_mode { + *plain_mode_turn_failed = true; + } + surface_turn_elapsed_message( + chat_dispatcher, + sessions_redraw_handle, + "failed", + pending.provider_started_at, + chrono::Utc::now(), + ); + publish_main_queue_status(chat_dispatcher, turn_scheduler); + publish_provider_worker_status(chat_dispatcher, provider_turn_workers); + } + ProviderTurnTerminalPlan::Cancelled { .. } => { + // Deliberately not marked: the guard's own default already says the + // turn ended before it answered, which is exactly what happened — + // and `cancelled` is the daemon's verdict, not a client's to claim. + if let Err(error) = finalize_chat_non_success_turn( + pending.turn_binding.as_deref(), + memory_fabric, + &pending.turn_run_id, + pending.route_scope.clone(), + crate::agent::terminal::TurnTerminalStatus::Cancelled, + None, + pending.provider_started_at, + "redux driver cancelled", + &config.cost, + &config.workspace_dir, + ) + .await + { + if pending + .turn_binding + .as_ref() + .is_some_and(|binding| binding.is_decided()) + { + *plain_mode_turn_failed = true; + } + tracing::warn!(error = %crate::agent::diagnostics::error_class(&error), "Failed to commit ordered cancelled Chat terminal event"); + } + let _ = terminal.cancel_draft("user", &pending.draft_id).await; + settle_aborted_worker_turn( + history, + chat_dispatcher, + turn_signal, + &pending, + Some(pending.history_len_before_user_turn), + ) + .await; + publish_main_queue_status(chat_dispatcher, turn_scheduler); + publish_provider_worker_status(chat_dispatcher, provider_turn_workers); + } + } + let _ = apply_ready_ordered_provider_turn_commits( + finalizer_results, + pending_ordered_provider_turn_commits, + history, + turn_scheduler, + provider_turn_workers, + chat_dispatcher, + terminal, + memory_fabric, + chat_session_key, + config, + sessions_redraw_handle, + redraw_tx_for_main, + turn_signal, + plain_mode, + plain_mode_turn_failed, + ) + .await; +} diff --git a/src/chat/provider_turns/section_2.rs b/src/chat/provider_turns/section_2.rs new file mode 100644 index 000000000..48ca88359 --- /dev/null +++ b/src/chat/provider_turns/section_2.rs @@ -0,0 +1,636 @@ +#[cfg(feature = "terminal-tui")] +#[allow(clippy::too_many_arguments)] +pub(super) async fn finalize_ready_per_turn_contexts( + per_turn_contexts: &mut std::collections::HashMap, + pending_ordered_provider_turn_commits: &mut std::collections::HashMap< + crate::chat::turn_scheduler::TurnTaskId, + PendingOrderedProviderTurnCommit, + >, + pending_provider_completion_events: &mut std::collections::HashMap< + crate::chat::turn_scheduler::TurnTaskId, + ProviderTurnCompletionEvent, + >, + turn_signal: &dispatcher::TurnCompletionSignal, + provider_turn_completion_contexts: &mut std::collections::HashMap< + crate::chat::turn_scheduler::TurnTaskId, + ProviderTurnCompletionContext, + >, + history: &mut Vec, + tools_registry: &[Box], + provider_turn_finalizer_events: &mut std::collections::VecDeque, + turn_scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, + history_commit_coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, + provider_turn_workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, + chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, + terminal: &Arc, + memory_fabric: &MemoryFabric, + chat_session_key: &str, + config: &Config, + sessions_redraw_handle: Option<&mpsc::Sender<()>>, + redraw_tx_for_main: Option<&mpsc::Sender<()>>, + plain_mode: bool, + plain_mode_turn_failed: &mut bool, +) -> bool { + let ready_task_ids: Vec<_> = per_turn_contexts + .keys() + .copied() + .filter(|task_id| pending_provider_completion_events.contains_key(task_id)) + .collect(); + if ready_task_ids.is_empty() { + return false; + } + for task_id in ready_task_ids { + if turn_signal.ensure_history_commits_healthy().is_err() { + break; + } + let Some(pending) = per_turn_contexts.remove(&task_id) else { + continue; + }; + let completion = pending_provider_completion_events.remove(&task_id); + finalize_per_turn_context( + pending, + completion, + pending_ordered_provider_turn_commits, + turn_signal, + provider_turn_completion_contexts, + history, + tools_registry, + provider_turn_finalizer_events, + turn_scheduler, + history_commit_coordinator, + provider_turn_workers, + chat_dispatcher, + terminal, + memory_fabric, + chat_session_key, + config, + sessions_redraw_handle, + redraw_tx_for_main, + plain_mode, + plain_mode_turn_failed, + ) + .await; + } + true +} + +#[cfg(feature = "terminal-tui")] +#[allow(clippy::too_many_arguments)] +pub(super) async fn finalize_all_per_turn_contexts_as_cancelled( + per_turn_contexts: &mut std::collections::HashMap, + pending_ordered_provider_turn_commits: &mut std::collections::HashMap< + crate::chat::turn_scheduler::TurnTaskId, + PendingOrderedProviderTurnCommit, + >, + turn_signal: &dispatcher::TurnCompletionSignal, + provider_turn_completion_contexts: &mut std::collections::HashMap< + crate::chat::turn_scheduler::TurnTaskId, + ProviderTurnCompletionContext, + >, + history: &mut Vec, + tools_registry: &[Box], + provider_turn_finalizer_events: &mut std::collections::VecDeque, + turn_scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, + history_commit_coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, + provider_turn_workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, + chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, + terminal: &Arc, + memory_fabric: &MemoryFabric, + chat_session_key: &str, + config: &Config, + sessions_redraw_handle: Option<&mpsc::Sender<()>>, + redraw_tx_for_main: Option<&mpsc::Sender<()>>, + plain_mode: bool, + plain_mode_turn_failed: &mut bool, +) { + let pending_turns: Vec<_> = per_turn_contexts.drain().map(|(_, pending)| pending).collect(); + for pending in pending_turns { + finalize_per_turn_context( + pending, + None, + pending_ordered_provider_turn_commits, + turn_signal, + provider_turn_completion_contexts, + history, + tools_registry, + provider_turn_finalizer_events, + turn_scheduler, + history_commit_coordinator, + provider_turn_workers, + chat_dispatcher, + terminal, + memory_fabric, + chat_session_key, + config, + sessions_redraw_handle, + redraw_tx_for_main, + plain_mode, + plain_mode_turn_failed, + ) + .await; + } +} + +#[cfg(feature = "terminal-tui")] +pub(super) fn drain_provider_turn_finalizer_events( + scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, + coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, + workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, + queue: &mut std::collections::VecDeque, +) -> Vec { + let mut results = Vec::new(); + while let Some(event) = queue.pop_front() { + results.extend(finalize_provider_turn_from_event( + scheduler, + coordinator, + workers, + event, + )); + } + results +} + +#[cfg(feature = "terminal-tui")] +pub(super) fn drain_provider_turn_finalizer_events_and_publish( + scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, + coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, + workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, + queue: &mut std::collections::VecDeque, + chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, +) -> Vec { + let results = drain_provider_turn_finalizer_events(scheduler, coordinator, workers, queue); + if !results.is_empty() { + publish_main_queue_status(chat_dispatcher, scheduler); + publish_provider_worker_status(chat_dispatcher, workers); + } + results +} + +pub(super) fn start_provider_turn_task( + scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, + existing_task_id: Option, + input: &str, + history_base_len: usize, +) -> Option { + let id = existing_task_id.unwrap_or_else(|| { + scheduler.enqueue( + input.to_string(), + crate::chat::turn_scheduler::TurnPriority::Normal, + history_base_len, + ) + }); + if let Err(error) = scheduler.start_task(id) { + tracing::warn!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), + reused_queued_task = existing_task_id.is_some(), + error = %crate::agent::diagnostics::error_class(&error), + "TurnScheduler provider task start failed" + ); + return None; + } + Some(id) +} + +pub(super) fn register_provider_history_commit_task( + coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, + scheduler: &crate::chat::turn_scheduler::TurnScheduler, + id: Option, +) { + if let Some(id) = id + && let Some(task) = scheduler.task(id) + && let Err(error) = coordinator.register_task(task) + { + let task_seq: u64 = task.sequence; + tracing::warn!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), + task_seq, + error = %crate::agent::diagnostics::error_class(&error), + "HistoryCommitCoordinator provider task registration failed" + ); + } +} + +pub(super) fn register_provider_turn_worker( + workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, + scheduler: &crate::chat::turn_scheduler::TurnScheduler, + id: Option, + kind: crate::chat::turn_worker::ProviderTurnWorkerKind, +) { + if let Some(id) = id + && let Some(task) = scheduler.task(id) + && let Err(error) = workers.start_from_task(task, kind) + { + let task_seq: u64 = task.sequence; + tracing::warn!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), + task_seq, + kind = ?kind, + error = %crate::agent::diagnostics::error_class(&error), + "ProviderTurnWorkerRegistry provider worker registration failed" + ); + } +} + +#[cfg(feature = "terminal-tui")] +pub(super) fn spawn_provider_turn_completion_waiter( + turn_signal: dispatcher::TurnCompletionSignal, + task_id: crate::chat::turn_scheduler::TurnTaskId, + tx: mpsc::Sender, + shutdown: CancellationToken, +) { + tokio::spawn(async move { + let notified = turn_signal.notified_for(task_id); + match notified { + Some(notified) => { + tokio::select! { + () = notified => {} + () = shutdown.cancelled() => {} + } + } + None => { + tokio::select! { + () = turn_signal.notified() => {} + () = shutdown.cancelled() => {} + } + } + } + let event = ProviderTurnCompletionEvent { + task_id, + outcome: turn_signal.consume_turn_outcome(task_id), + usage: turn_signal.consume_turn_usage(task_id), + }; + if tx.send(event).await.is_err() { + tracing::debug!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(task_id), + "provider turn completion waiter could not deliver event" + ); + } + }); +} + +pub(super) fn request_provider_turn_cancel( + scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, + workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, + id: Option, + reason: &'static str, +) { + if let Some(id) = id { + if let Err(error) = scheduler.request_cancel(id) { + tracing::warn!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), + reason, + error = %crate::agent::diagnostics::error_class(&error), + "TurnScheduler provider task cancel request failed" + ); + } + if let Err(error) = workers.request_cancel(id) { + tracing::warn!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), + reason, + error = %crate::agent::diagnostics::error_class(&error), + "ProviderTurnWorkerRegistry provider worker cancel request failed" + ); + } + } +} + +/// Record the user's request when the turn is admitted (the non-TUI path; +/// its completion commits with `record_user: false`). The send is bounded and +/// awaited on the ordered action channel +/// ([`crate::chat::dispatcher::ChatDispatcher::dispatch_bounded`]): a full +/// channel delays the turn instead of dropping the request, so the later +/// commit always includes it. A send that is not accepted latches the +/// unconfirmed-commit stop once and fails the turn before it runs. +/// +/// Returns the admission's identity: a failed or cancelled turn settles by +/// it ([`settle_aborted_turn`]), so only this request is ever removed. +pub(super) async fn record_user_turn_at_admission( + chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, + commits: &crate::chat::dispatcher::TurnCompletionSignal, + user_input: &str, +) -> anyhow::Result { + let admission = crate::chat::action::AdmissionId::next(); + chat_dispatcher + .dispatch_bounded( + crate::chat::action::Action::UserTurnAdmitted { + admission, + content: user_input.to_owned(), + }, + commits, + ) + .await + .map_err(|error| anyhow::anyhow!("Chat stopped after an unconfirmed history commit: {error}"))?; + Ok(admission) +} + +/// The acknowledged session as of every action sent before this call: an +/// awaited no-op (`RedrawRequested`) on the same ordered channel. A turn's +/// admission reads its start state through it, so a compaction another turn +/// already sent is never missed by a racing snapshot read. A failed +/// acknowledgement latches `commits` and is the unconfirmed-commit stop. +pub(super) async fn acknowledged_session_barrier( + chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, + commits: &crate::chat::dispatcher::TurnCompletionSignal, +) -> anyhow::Result { + match chat_dispatcher + .dispatch_awaited(crate::chat::action::Action::RedrawRequested, commits) + .await + .map_err(|error| anyhow::anyhow!("Chat stopped after an unconfirmed history commit: {error}"))? + { + crate::chat::acked_session::Ack::Published(acked) | crate::chat::acked_session::Ack::Unchanged(acked) => { + Ok(acked) + } + crate::chat::acked_session::Ack::Rejected(_) => Ok(chat_dispatcher.session_reader().acked()), + } +} + +/// Settle a failed or cancelled turn with the session authority, in order +/// after its terminal action and every in-turn compaction the turn sent: +/// `TurnAbortSettled` removes the request admitted as `admission` (when the +/// turn recorded one and that admission is still open) and saves, and the +/// acknowledged revision is returned. Then the run loop's provider view +/// follows that revision ([`provider_view_after_settled_abort`]). +/// +/// A failed acknowledgement latches `commits` and is returned as the +/// unconfirmed-commit stop; a refusal (which this action never produces for +/// a live session) is latched the same way. +pub(super) async fn settle_aborted_turn( + chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, + commits: &crate::chat::dispatcher::TurnCompletionSignal, + admission: Option, +) -> anyhow::Result { + let ack = chat_dispatcher + .dispatch_awaited(crate::chat::action::Action::TurnAbortSettled { admission }, commits) + .await + .map_err(|error| anyhow::anyhow!("Chat stopped after an unconfirmed history commit: {error}"))?; + match ack { + crate::chat::acked_session::Ack::Published(acked) | crate::chat::acked_session::Ack::Unchanged(acked) => { + Ok(acked) + } + crate::chat::acked_session::Ack::Rejected(_) => { + let reason = "the failed or cancelled turn could not be settled"; + commits.fail_history_commit(reason.to_owned()); + anyhow::bail!("Chat stopped after an unconfirmed history commit: {reason}") + } + } +} + +/// The run loop's provider view after a settled failed or cancelled turn. +/// The aborted request is never kept: the settled snapshot already excludes it +/// (admission identity, `TurnAbortSettled`), so no text is matched to remove +/// anything. When the session was compacted or the view was changed at any +/// point since before the turn's preflight (`settled` carries a compaction +/// epoch other than `compaction_epoch_before_preflight`, or the turn itself +/// reported one), the view is rebuilt from the settled snapshot; otherwise it +/// is cut back to `len_before_user_turn`, its length before the request +/// (`None` for a view the request was never pushed to). Returns whether it +/// rebuilt the view. +pub(super) fn provider_view_after_settled_abort( + history: &mut Vec, + settled: &crate::chat::acked_session::AckedSession, + compaction_epoch_before_preflight: u64, + compacted_in_turn: bool, + len_before_user_turn: Option, +) -> bool { + if settled.compaction_epoch == compaction_epoch_before_preflight && !compacted_in_turn { + if let Some(len) = len_before_user_turn { + rollback_cancelled_turn_history(history, len); + } + return false; + } + let view = super::compaction::provider_view_from_acked(history, settled); + tracing::info!( + messages_before = history.len(), + messages_after = view.len(), + "provider view rebuilt from the settled snapshot after a compaction in a failed or cancelled turn" + ); + *history = view; + true +} + +/// Dispatch a turn's final metered usage (`FinalAggregate`) unconditionally, +/// before the turn's awaited commit; the reducer deduplicates per task. The +/// scheduler bookkeeping uses the same terminal usage. +/// +/// The send waits for channel capacity within the acknowledgement bound +/// ([`crate::chat::dispatcher::ChatDispatcher::dispatch_bounded`]); when the +/// usage is not accepted the history commit is latched as failed and the +/// error is returned, and the caller must not commit the turn. +pub(super) async fn dispatch_final_usage( + chat_dispatcher: &crate::chat::dispatcher::ChatDispatcher, + commits: &crate::chat::dispatcher::TurnCompletionSignal, + turn_scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, + task_id: Option, + terminal_usage: Option, + site: &'static str, +) -> Result<(), crate::chat::acked_session::AckError> { + let Some(record) = terminal_usage else { + return Ok(()); + }; + record_provider_turn_usage(turn_scheduler, task_id, &record); + chat_dispatcher + .dispatch_bounded( + crate::chat::action::Action::ProviderUsageRecorded { + task_id, + usage_kind: crate::chat::action::ProviderUsageRecordKind::FinalAggregate, + record, + }, + commits, + ) + .await + .inspect_err(|error| tracing::error!(site, error_kind = error.kind(), "final provider usage was not accepted")) +} + +pub(super) fn record_provider_turn_usage( + scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, + id: Option, + record: &crate::chat::session::MainSessionTokenUsageRecord, +) { + if let Some(id) = id + && let Err(error) = scheduler.record_usage(id, record) + { + tracing::warn!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), + error = %crate::agent::diagnostics::error_class(&error), + "TurnScheduler provider usage ledger record failed" + ); + } +} + +pub(super) fn mark_provider_turn_completed( + scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, + coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, + workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, + id: Option, + history_commit_len: usize, + summary: &'static str, +) -> Vec { + if let Some(id) = id { + match scheduler.mark_completed(id, history_commit_len, summary) { + Ok(()) => { + if record_provider_worker_completed(workers, id) { + return record_provider_history_commit_outcome(coordinator, workers, scheduler, id); + } + } + Err(error) => { + tracing::warn!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), + error = %crate::agent::diagnostics::error_class(&error), + "TurnScheduler provider task completion failed" + ); + } + } + } + Vec::new() +} + +fn mark_provider_turn_failed( + scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, + coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, + workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, + id: Option, + history_commit_len: usize, + summary: impl Into, +) -> Vec { + if let Some(id) = id { + match scheduler.mark_failed(id, history_commit_len, summary) { + Ok(()) => { + if record_provider_worker_failed(workers, id) { + return record_provider_history_commit_outcome(coordinator, workers, scheduler, id); + } + } + Err(error) => { + tracing::warn!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), + error = %crate::agent::diagnostics::error_class(&error), + "TurnScheduler provider task failure failed" + ); + } + } + } + Vec::new() +} + +fn mark_provider_turn_cancelled( + scheduler: &mut crate::chat::turn_scheduler::TurnScheduler, + coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, + workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, + id: Option, + summary: &'static str, +) -> Vec { + if let Some(id) = id { + match scheduler.mark_cancelled(id, summary) { + Ok(()) => { + if record_provider_worker_cancelled(workers, id) { + return record_provider_history_commit_outcome(coordinator, workers, scheduler, id); + } + } + Err(error) => { + tracing::warn!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), + error = %crate::agent::diagnostics::error_class(&error), + "TurnScheduler provider task cancellation failed" + ); + } + } + } + Vec::new() +} + +fn record_provider_worker_completed( + workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, + id: crate::chat::turn_scheduler::TurnTaskId, +) -> bool { + if let Err(error) = workers.record_completed(id) { + tracing::warn!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), + error = %crate::agent::diagnostics::error_class(&error), + "ProviderTurnWorkerRegistry provider worker completion failed" + ); + return false; + } + true +} + +fn record_provider_worker_failed( + workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, + id: crate::chat::turn_scheduler::TurnTaskId, +) -> bool { + if let Err(error) = workers.record_failed(id) { + tracing::warn!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), + error = %crate::agent::diagnostics::error_class(&error), + "ProviderTurnWorkerRegistry provider worker failure failed" + ); + return false; + } + true +} + +fn record_provider_worker_cancelled( + workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, + id: crate::chat::turn_scheduler::TurnTaskId, +) -> bool { + if let Err(error) = workers.record_cancelled(id) { + tracing::warn!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), + error = %crate::agent::diagnostics::error_class(&error), + "ProviderTurnWorkerRegistry provider worker cancellation failed" + ); + return false; + } + true +} + +fn record_provider_history_commit_outcome( + coordinator: &mut crate::chat::history_commit::HistoryCommitCoordinator, + workers: &mut crate::chat::turn_worker::ProviderTurnWorkerRegistry, + scheduler: &crate::chat::turn_scheduler::TurnScheduler, + id: crate::chat::turn_scheduler::TurnTaskId, +) -> Vec { + let Some(task) = scheduler.task(id) else { + tracing::warn!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), + "HistoryCommitCoordinator missing scheduler task for provider outcome" + ); + return Vec::new(); + }; + let Some(outcome) = crate::chat::history_commit::HistoryCommitOutcome::from_terminal_task(task) else { + tracing::warn!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), + state = task.state.kind(), + "HistoryCommitCoordinator ignored non-terminal provider outcome" + ); + return Vec::new(); + }; + if let Err(error) = coordinator.record_outcome(outcome) { + let task_seq: u64 = task.sequence; + tracing::warn!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), + task_seq, + error = %crate::agent::diagnostics::error_class(&error), + "HistoryCommitCoordinator provider outcome record failed" + ); + return Vec::new(); + } + let mut decisions = Vec::new(); + for decision in coordinator.drain_ready() { + if let Err(error) = workers.apply_commit_decision(&decision) { + tracing::warn!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), + decision_kind = decision.kind(), + error = %crate::agent::diagnostics::error_class(&error), + "ProviderTurnWorkerRegistry provider worker commit decision failed" + ); + } + tracing::trace!( + task_id = crate::chat::turn_scheduler::TurnTaskId::get(id), + decision_kind = decision.kind(), + pending_tasks = coordinator.pending_tasks(), + pending_outcomes = coordinator.pending_outcomes(), + "HistoryCommitCoordinator provider outcome became ready" + ); + decisions.push(decision); + } + decisions +} diff --git a/src/chat/run.rs b/src/chat/run.rs index de5a69a26..9b7f66ee9 100644 --- a/src/chat/run.rs +++ b/src/chat/run.rs @@ -749,6 +749,7 @@ async fn run_internal( // seq, so the main loop restores `Main` (when None) or `Session { seq }`. let mut attached_follow_seq: Option = None; let mut child_focus = super::child_focus::ChildFocus::default(); + let mut message_inbox = super::message_inbox::ChatInbox::open(&config, &chat_session_key)?; // Guards the event-drain select arm: once the event channel closes (only at // shutdown — the sender lives as long as the tool registry) we disable the // arm so a closed channel does not busy-spin returning `None`. @@ -812,6 +813,7 @@ async fn run_internal( let assignment_enrolment = if one_shot.is_none() { start_assignment_enrolment( &config, + &chat_session_key, &chat_sessions, &assignment_input_tx, &chat_dispatcher, @@ -853,7 +855,10 @@ async fn run_internal( surface_session_message(&chat_dispatcher, sessions_redraw_handle.as_ref(), &error.to_string()); continue; } - if let Some(target) = attached_follow.as_ref() { + if let Some(target) = attached_follow + .as_ref() + .filter(|_| super::is_local_operator_input(&msg) && !msg.sender_is_bot) + { match child_focus .submit( target.as_str(), @@ -886,6 +891,52 @@ async fn run_internal( Ok(None) => {} } } + if msg.id == "mailbox-wake" && msg.sender == "session-message" && msg.sender_is_bot { + if let Some(inbox) = message_inbox.as_mut() { + inbox.wake(); + } + continue; + } + if one_shot.is_none() + && super::is_local_operator_input(&msg) + && !msg.sender_is_bot + && msg.content.starts_with("/msg ") + { + let result = super::message_inbox::send_command( + &config, + &chat_session_key, + attached_follow.as_ref().map(|id| id.as_str()), + &msg, + &mut chat_sessions, + ) + .await; + match result { + Ok(output) => { + surface_session_message(&chat_dispatcher, sessions_redraw_handle.as_ref(), &output) + } + Err(error) => surface_session_message( + &chat_dispatcher, + sessions_redraw_handle.as_ref(), + &error.to_string(), + ), + } + continue; + } + let mut mailbox_input = if let Some(inbox) = message_inbox.as_mut() { + match inbox.take_input(&msg) { + Ok(input) => input, + Err(error) => { + surface_session_message( + &chat_dispatcher, + sessions_redraw_handle.as_ref(), + &error.to_string(), + ); + continue; + } + } + } else { + None + }; let user_input = msg.content.clone(); let synthetic_ui_command = is_synthetic_ui_command(&msg); // Armed here, at the top, because the turn body has many exits — a @@ -970,7 +1021,7 @@ async fn run_internal( print_fallback_chat_output(text); }; - include!("run/commands.rs"); + let () = include!("run/commands.rs"); include!("run/provider_turn.rs"); } diff --git a/src/chat/run/event_pump.rs b/src/chat/run/event_pump.rs index 809921420..8122e0e24 100644 --- a/src/chat/run/event_pump.rs +++ b/src/chat/run/event_pump.rs @@ -1,4 +1,37 @@ loop { + if let Some(inbox) = message_inbox.as_mut().filter(|inbox|inbox.fenced()) { + input_backlog.retain(|queued| { + if super::message_inbox::cause(&queued.msg).is_some() { + if let Some(task) = queued.turn_task_id {let _ = turn_scheduler.request_cancel(task);} + false + } else {true} + }); + inbox.drain(); + } + + if message_inbox.as_ref().is_some_and(|inbox|inbox.session()!=chat_session_key) { + drop(message_inbox.take()); + message_inbox=super::message_inbox::ChatInbox::open(&config,&chat_session_key)?; + } + #[cfg(feature="terminal-tui")] + let message_idle = per_turn_contexts.is_empty(); + #[cfg(not(feature="terminal-tui"))] + let message_idle = true; + if let Some(inbox)=message_inbox.as_mut().filter(|_| message_idle) { + match inbox.poll() { + Ok(inputs)=>for input in inputs { + if input.auto_start() { + let message=super::message_inbox::channel_input(&input)?; + enqueue_input_message_with_scheduler(&mut input_backlog,&mut turn_scheduler,message,chat_session.session().turns.len()); + } else { + history.push(crate::agent::turn_contracts::inbound_user_message(&input.text)); + surface_session_message(&chat_dispatcher,sessions_redraw_handle.as_ref(),&input.text); + } + }, + Err(error)=>surface_session_message(&chat_dispatcher,sessions_redraw_handle.as_ref(),&error.to_string()), + } + } + #[cfg(feature="terminal-tui")] if let (Some(target),Some(seq))=(attached_follow.as_ref(),attached_follow_seq) { let lines=session_rings.get(target).map_or_else(Vec::new,|ring|ring.recent_lines(crate::chat::sessions::event::DEFAULT_RING_CAPACITY)); @@ -173,7 +206,14 @@ loop { } break None; }; - if let Some(target)=attached_follow.as_ref() { + if msg.message.id == "mailbox-wake" && msg.message.sender == "session-message" && msg.message.sender_is_bot { + if let Some(inbox) = message_inbox.as_mut() { inbox.wake(); } + continue; + } + if super::is_local_operator_input(&msg.message) && !msg.message.sender_is_bot { + if let Some(inbox) = message_inbox.as_mut() { inbox.wake(); } + } + if let Some(target)=attached_follow.as_ref().filter(|_|super::is_local_operator_input(&msg.message) && !msg.message.sender_is_bot) { match child_focus.submit(target.as_str(),msg.message.clone(),&super::child_focus::ChildFocusContext { memory:&mem,generation:&ctx.config_generation,parent:&chat_session_key, security:&ctx.security,service:&turn_service,tools:&tools_registry,sessions:&chat_sessions,approvals:&pending_approvals }).await { Ok(Some(output))=>{surface_session_message(&chat_dispatcher,sessions_redraw_handle.as_ref(),&output);continue;}, diff --git a/src/chat/run/provider_turn.rs b/src/chat/run/provider_turn.rs index 7a0975847..3edd86da4 100644 --- a/src/chat/run/provider_turn.rs +++ b/src/chat/run/provider_turn.rs @@ -74,6 +74,7 @@ let mut input_scope = chat_message_event_scope( memory_fabric.workspace_id(), &chat_session_key, &turn_run_id, provider_name, model_name, ); + input_scope.causation_event_id=super::message_inbox::cause(&msg).map(str::to_owned); input_scope.config_generation_id = Some(ctx.config_generation.id.0); input_scope.config_source_revision = Some(ctx.config_generation.source_revision.fingerprint_sha256.clone()); // The TUI mirror is updated synchronously by /mode; its legacy session @@ -602,7 +603,7 @@ compaction_guard_history: Some(persisted_history_for_turn.clone()), compaction_config: Some(effective_compaction.config.clone()), cancel: cancellation.clone(), - turn_spawn_ctx: Some(redux_turn_spawn_ctx), + turn_spawn_ctx: Some(Box::new(redux_turn_spawn_ctx)), turn_message_send_ctx: Some(redux_turn_message_send_ctx), // Route on what the user typed. `history_for_provider` // already carries the memory preamble and the @@ -664,6 +665,7 @@ .insert( task_id, PerTurnContext { + _mailbox_input: mailbox_input.take(), turn_binding: chat_turn_binding.clone(), task_id, diff --git a/src/chat/run/startup.rs b/src/chat/run/startup.rs index 86575a3df..62c08b9b9 100644 --- a/src/chat/run/startup.rs +++ b/src/chat/run/startup.rs @@ -167,6 +167,7 @@ pub(super) fn session_tools( )); base_tools_vec.push(Box::new( crate::tools::SessionsSendTool::with_security(Arc::clone(&active_runs), security.clone()) + .with_messaging(config) .with_shared_memory(Arc::clone(mem)) .with_event_recording(config.memory.event_recording_config()), )); diff --git a/src/chat/session_glue.rs b/src/chat/session_glue.rs index 35383d1cd..4e1acc1f8 100644 --- a/src/chat/session_glue.rs +++ b/src/chat/session_glue.rs @@ -726,6 +726,7 @@ fn assignment_notifier( /// down, or refusing credentials never delays the prompt. pub(super) fn start_assignment_enrolment( config: &Config, + message_session: &str, chat_sessions: &crate::chat::sessions::ChatSessionsHandle, input_tx: &crate::runtime::h2_entry::ChatInputSender, dispatcher: &dispatcher::ChatDispatcher, @@ -742,6 +743,11 @@ pub(super) fn start_assignment_enrolment( Enrolable::Yes => {} } let client = assignment::AssignmentClient::new(config); + if let Ok(runtime) = crate::messaging::runtime::MessagingRuntime::for_config(config) { + let owner = + super::chat_runtime_envelope(&config.workspace_dir.to_string_lossy(), message_session).resolved_owner_id(); + client.set_message_target(runtime.address(&owner, message_session, "main")); + } let cancel = CancellationToken::new(); tokio::spawn(assignment::enrol_and_poll( std::sync::Arc::clone(&client), diff --git a/src/chat/sessions/assignment.rs b/src/chat/sessions/assignment.rs index 89b738755..18c17d8df 100644 --- a/src/chat/sessions/assignment.rs +++ b/src/chat/sessions/assignment.rs @@ -40,2103 +40,5 @@ //! the daemon only records a disposition and puts the item at the head of the //! queue, and chat maps each one onto a path it already had. -use std::collections::HashSet; -use std::future::Future; -use std::pin::Pin; -use std::sync::Arc; - -use anyhow::Result; -use parking_lot::Mutex; -use tokio_util::sync::CancellationToken; - -use crate::config::Config; -use crate::runtime::tasks_cli::{self, AssignmentPull, AssignmentReceipt, PulledAssignment, TasksEndpoint}; - -use super::daemon::{InFlightGuard, InFlightRegistry, register_in_flight_labeled}; - -/// How often chat asks the daemon whether it has been given work. -/// -/// A sampling interval, in the same sense as `sessions_spawn`'s -/// `JOIN_POLL_INTERVAL`: it decides how often a question is asked, never how -/// long an answer may take. No call in this module carries a timeout, and -/// nothing here compares an elapsed duration against a limit. -pub const POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(1_500); - -/// Shortest gap between two attempts by this poller to register again. -/// -/// Re-enrolment is idempotent, so a repeat costs the daemon little — but every -/// successful one puts a line on the operator's screen, and a daemon that keeps -/// forgetting this session would otherwise write one every [`POLL_INTERVAL`]. -/// A floor of a minute keeps the recovery automatic while bounding what a -/// pathological daemon can print, at the price of up to a minute of extra -/// downtime on the pathological path only: a single restart still recovers on -/// the first unregistered answer. -pub const RE_ENROLMENT_MIN_INTERVAL: std::time::Duration = std::time::Duration::from_mins(1); - -/// How many assignments to take in one pull. -/// -/// A response-size bound, not a concurrency limit: whatever is left stays at -/// the head of the daemon's queue and comes on the next pull. Chat runs turns -/// one queue at a time regardless, so asking for more would only make a single -/// HTTP body larger. -const PULL_BATCH: usize = 8; - -/// Upper bound the daemon enforces on a reported summary, in bytes. -const MAX_SUMMARY_BYTES: usize = 16_384; - -/// Upper bound the daemon enforces on a registered label, in bytes. -const MAX_LABEL_BYTES: usize = 64; - -/// How much of an assigned task is echoed into the transcript on arrival. -const TASK_PREVIEW_CHARS: usize = 120; - -/// Marker prefix on the synthetic input message carrying an assignment. -/// -/// The sender field is the same place `prx-ui` marks synthetic slash commands, -/// and for the same reason: the input queue is typed as channel messages, so a -/// message that is not a person typing has to say so somewhere the queue -/// already carries. Nothing outside this module parses it. -const SENDER_PREFIX: &str = "prx-assignment:"; - -/// Channel an assignment is delivered on. -/// -/// `terminal`, exactly like a typed line: the whole point is that assigned work -/// runs through the ordinary turn machinery rather than a parallel path with -/// its own bugs. -const ASSIGNMENT_CHANNEL: &str = "terminal"; - -/// Reply target on the synthetic message, matching a typed line. -const ASSIGNMENT_REPLY_TARGET: &str = "user"; - -// ── Dispositions ──────────────────────────────────────────────────────────── - -/// What the assigning side asked chat to do about work already in flight. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Disposition { - /// Run it when the current work is done. The default, and the least - /// disruptive: an assignment is somebody else's priority, not necessarily - /// this terminal's. - Queue, - /// Put it in front of whatever else is queued, without stopping the turn in - /// flight. - Steer, - /// Stop the turn in flight first, then run it. - Interrupt, -} - -impl Disposition { - /// Read the daemon's word for a disposition. - /// - /// An unrecognised word becomes [`Disposition::Queue`], never - /// [`Disposition::Interrupt`]: a newer daemon inventing a stronger - /// disposition must not be able to make an older chat destroy a turn it - /// does not understand the reason for. The caller is told, so silence is - /// not how it degrades. - #[must_use] - pub fn from_wire(raw: &str) -> Self { - match raw.trim() { - "steer" => Self::Steer, - "interrupt" => Self::Interrupt, - _ => Self::Queue, - } - } - - /// Whether the daemon's word was one this chat actually knows. - #[must_use] - pub fn is_known_wire(raw: &str) -> bool { - matches!(raw.trim(), "queue" | "steer" | "interrupt") - } - - /// The wire word for this disposition. - #[must_use] - pub const fn as_str(self) -> &'static str { - match self { - Self::Queue => "queue", - Self::Steer => "steer", - Self::Interrupt => "interrupt", - } - } - - /// Whether this disposition jumps the input queue. - /// - /// `steer` and `interrupt` both do; they differ only in whether the turn in - /// flight is stopped first. - #[must_use] - pub const fn jumps_the_queue(self) -> bool { - matches!(self, Self::Steer | Self::Interrupt) - } - - /// Whether this disposition ends the turn in flight before delivering. - #[must_use] - pub const fn ends_the_turn_in_flight(self) -> bool { - matches!(self, Self::Interrupt) - } -} - -/// What chat may report back about an assignment. -/// -/// `cancelled` is deliberately absent. It is the daemon's own verdict about -/// work *it* ended, and a client able to claim it would make "an operator -/// killed this" indistinguishable from "the client gave up". The daemon refuses -/// it at the boundary; this enum makes it unrepresentable on the way there. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ResultStatus { - /// The turn ran and produced a reply. - Completed, - /// The turn ran and did not produce a reply, or was ended before it could. - Failed, - /// Chat declined to run it at all. - Rejected, -} - -impl ResultStatus { - /// The wire word for this status. - #[must_use] - pub const fn as_str(self) -> &'static str { - match self { - Self::Completed => "completed", - Self::Failed => "failed", - Self::Rejected => "rejected", - } - } - - /// Every status a chat session can report, for tests and documentation. - #[must_use] - pub const fn all() -> [Self; 3] { - [Self::Completed, Self::Failed, Self::Rejected] - } -} - -// ── The mailbox, behind a trait ───────────────────────────────────────────── - -/// Boxed future returned by [`AssignmentMailbox`] calls. -pub type MailboxFuture<'a, T> = Pin> + Send + 'a>>; - -/// The two calls the poll loop and the result guard make. -/// -/// A trait rather than a concrete client so the loop's ordering guarantees — -/// acknowledge on the *next* pull, run a redelivery once — can be asserted -/// against a recording double instead of against a live daemon. The HTTP -/// implementation is [`AssignmentClient`]. -pub trait AssignmentMailbox: Send + Sync { - /// Redacted handle for this session, for anything an operator will read. - fn session_ref(&self) -> String; - - /// Where this mailbox lives, for the in-flight listing. - fn base_url(&self) -> String; - - /// Take queued work, acknowledging `ack` — the ids from the previous pull — - /// on the way in. - fn pull(&self, ack: Vec) -> MailboxFuture<'_, AssignmentPull>; - - /// Say what this session made of one assignment. - fn report( - &self, - assignment_id: String, - status: ResultStatus, - summary: String, - ) -> MailboxFuture<'_, AssignmentReceipt>; - - /// Claim one assignment id, returning `false` when it was already taken. - /// - /// The mailbox is at-least-once, so this is what makes a redelivery cost - /// nothing: `false` means "work I already hold", which must still be - /// acknowledged and must not be run a second time. - fn accept(&self, assignment_id: &str) -> bool; - - /// Which enrolment the caller is looking at. `0` means "not enrolled". - /// - /// Read before a call that may fail, and handed back to [`Self::re_enrol`] - /// afterwards: that is what makes re-enrolment idempotent without a lock - /// held across the network. Two callers that saw the same dead enrolment - /// pass the same number, and only the first of them registers. - fn enrolment_generation(&self) -> u64; - - /// Register again, because the enrolment `stale` names is gone. - /// - /// Registering is the entire recovery: the daemon keeps its session - /// registry in memory and rebuilds nothing on start, so a restart leaves - /// this chat holding a session id nothing answers to. A new registration - /// yields a new id and a new token, and the old row does not need - /// withdrawing because a refusal that says "no such session" is the daemon - /// saying the row is already gone. - fn re_enrol(&self, stale: u64) -> MailboxFuture<'_, ReEnrolment>; -} - -/// What one re-enrolment attempt did. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum ReEnrolment { - /// This call registered again. The session id and token are new, and every - /// id from the old enrolment is meaningless to the daemon now. - Registered { session_ref: String }, - /// The enrolment the caller saw had already been replaced — or withdrawn on - /// the way out — so this call registered nothing. Idempotency, stated - /// rather than assumed. - Superseded { session_ref: String }, -} - -/// Chat's enrolment with one daemon, and the state that keeps it honest. -pub struct AssignmentClient { - endpoint: TasksEndpoint, - label: String, - pid: Option, - enrolment: Mutex>, - /// Serialises re-enrolment, so two callers that raced the same dead - /// enrolment produce one registration rather than two sessions the daemon - /// then has to be told apart. `tokio::sync::Mutex` because the section it - /// guards contains an HTTP round trip; the `parking_lot` mutexes here are - /// never held across an await. - re_enrolling: tokio::sync::Mutex<()>, - /// Assignment ids this chat has already taken into its own queue. - /// - /// The mailbox is at-least-once, so the same id can arrive again whenever a - /// response was lost on the way back. Running it twice would be the client - /// duplicating somebody's work; this set is what makes redelivery - /// harmless. - taken: Mutex>, -} - -/// The identity and credential one registration yielded. -#[derive(Debug, Clone)] -struct Enrolment { - session_id: String, - session_ref: String, - /// Returned once by the daemon, which keeps only its hash. Held in memory - /// for the life of the process and never written anywhere. - token: String, - /// Which registration this is: 1 for the first, one more for each - /// replacement. The version stamp re-enrolment checks so a caller acting on - /// an enrolment that has already been replaced replaces nothing. - generation: u64, -} - -impl AssignmentClient { - /// Build a client for the daemon this chat is configured to talk to. - #[must_use] - pub fn new(config: &Config) -> Arc { - Arc::new(Self { - endpoint: super::daemon::endpoint(config), - label: label_for(config), - pid: Some(std::process::id()), - enrolment: Mutex::new(None), - re_enrolling: tokio::sync::Mutex::new(()), - taken: Mutex::new(HashSet::new()), - }) - } - - /// The label this chat registers under. - #[must_use] - pub fn label(&self) -> &str { - &self.label - } - - /// Register with the daemon, storing the session id and one-time token. - /// - /// Returns the redacted session handle on success. The caller decides what - /// to do with a failure; nothing here retries, because a chat that cannot - /// enrol at all has a perfectly usable degraded mode and hammering a daemon - /// that refused it would only bury the reason. Losing an enrolment that - /// once worked is the different case, and [`AssignmentClient::re_enrol_now`] - /// is what answers it. - pub async fn enrol(&self) -> Result { - let registration = tasks_cli::register_chat_session(&self.endpoint, &self.label, self.pid).await?; - let session_ref = registration.session_ref.clone(); - self.install(registration, 1); - Ok(session_ref) - } - - /// Replace the held enrolment with a fresh registration. - /// - /// Everything the old one meant goes with it: the id, the token, and the - /// set of assignment ids already taken, which belonged to a mailbox that no - /// longer exists. Keeping the last of those would let an id the *new* - /// daemon hands out collide with a dead one and be silently discarded as a - /// redelivery. - fn install(&self, registration: tasks_cli::ChatSessionRegistration, generation: u64) { - *self.enrolment.lock() = Some(Enrolment { - session_id: registration.session_id, - session_ref: registration.session_ref, - token: registration.token, - generation, - }); - self.taken.lock().clear(); - } - - /// The enrolment version this client currently holds; `0` when unenrolled. - fn generation(&self) -> u64 { - self.enrolment.lock().as_ref().map_or(0, |held| held.generation) - } - - /// Whether this chat is currently enrolled. - #[must_use] - pub fn is_enrolled(&self) -> bool { - self.enrolment.lock().is_some() - } - - /// The daemon-assigned session id, once enrolled. - #[must_use] - pub fn session_id(&self) -> Option { - self.enrolment.lock().as_ref().map(|e| e.session_id.clone()) - } - - fn credentials(&self) -> Result<(String, String)> { - let held = self.enrolment.lock().clone(); - let enrolment = held.ok_or_else(|| anyhow::anyhow!("this chat session is not enrolled with a daemon"))?; - Ok((enrolment.session_id, enrolment.token)) - } - - /// Withdraw from the daemon's registry. - /// - /// Nothing on the daemon side removes a session on a clock — a session that - /// stopped pulling is reported as silent, never evicted — so an exit that - /// skips this leaves a row that assignments can still be addressed to, with - /// nobody left to run them. - pub async fn deregister(&self) -> Result { - let (session_id, _) = self.credentials()?; - let report = tasks_cli::deregister_chat_session(&self.endpoint, &session_id).await?; - *self.enrolment.lock() = None; - Ok(report.discarded) - } - - /// Register again after the daemon stopped recognising this session. - /// - /// Idempotent by version stamp rather than by trust: the generation the - /// caller saw is compared with the one held now, under a lock that is also - /// held across the registration call, so concurrent callers that saw the - /// same dead enrolment yield exactly one new session. A caller holding an - /// older stamp is told it was superseded and registers nothing — which is - /// also what stops a poll that raced the exit path from re-registering a - /// chat that has just withdrawn. - async fn re_enrol_now(&self, stale: u64) -> Result { - let _serialised = self.re_enrolling.lock().await; - let held = self.enrolment.lock().clone(); - let current = held.as_ref().map_or(0, |enrolment| enrolment.generation); - if current != stale { - return Ok(ReEnrolment::Superseded { - session_ref: held.map_or_else(|| "unenrolled".to_string(), |enrolment| enrolment.session_ref), - }); - } - let registration = tasks_cli::register_chat_session(&self.endpoint, &self.label, self.pid).await?; - let session_ref = registration.session_ref.clone(); - self.install(registration, stale.saturating_add(1)); - Ok(ReEnrolment::Registered { session_ref }) - } -} - -impl AssignmentMailbox for AssignmentClient { - fn session_ref(&self) -> String { - self.enrolment - .lock() - .as_ref() - .map_or_else(|| "unenrolled".to_string(), |e| e.session_ref.clone()) - } - - fn base_url(&self) -> String { - self.endpoint.base_url().to_string() - } - - fn pull(&self, ack: Vec) -> MailboxFuture<'_, AssignmentPull> { - Box::pin(async move { - let (session_id, token) = self.credentials()?; - tasks_cli::pull_chat_assignments(&self.endpoint, &session_id, &token, &ack, Some(PULL_BATCH)).await - }) - } - - fn report( - &self, - assignment_id: String, - status: ResultStatus, - summary: String, - ) -> MailboxFuture<'_, AssignmentReceipt> { - Box::pin(async move { - let (session_id, token) = self.credentials()?; - tasks_cli::report_chat_assignment( - &self.endpoint, - &session_id, - &token, - &assignment_id, - status.as_str(), - &summary, - ) - .await - }) - } - - fn accept(&self, assignment_id: &str) -> bool { - self.taken.lock().insert(assignment_id.to_string()) - } - - fn enrolment_generation(&self) -> u64 { - self.generation() - } - - fn re_enrol(&self, stale: u64) -> MailboxFuture<'_, ReEnrolment> { - Box::pin(self.re_enrol_now(stale)) - } -} - -// ── Whether to enrol at all ───────────────────────────────────────────────── - -/// Whether this configuration means chat to enrol with a daemon. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Enrolable { - /// A daemon was named, or a credential for one exists: enrol. - Yes, - /// Nothing points this chat at a daemon. The reason is carried so it can be - /// shown to anyone who asks why they cannot be assigned work. - No(&'static str), -} - -/// Decide whether to enrol, from configuration alone. -/// -/// Enrolment is opt-in by evidence rather than by a flag, because there is no -/// safe default guess: the fallback daemon address is `[gateway]`'s own bind, -/// which every chat has whether or not a daemon is listening on it, and -/// `gateway.require_pairing` is on by default, so an unconfigured chat would -/// announce a 401 on every single start. Two things count as evidence that an -/// operator meant chat to talk to a daemon: -/// -/// 1. `chat.daemon.url` is set — chat has been pointed at one explicitly; -/// 2. a credential resolves — `chat.daemon.token`, or a plaintext entry in -/// `gateway.paired_tokens` when chat and the daemon share a config dir. -/// -/// Neither of those is a promise that enrolment will succeed. It is only the -/// difference between a failure worth reporting and a question nobody asked. -#[must_use] -pub fn enrolable(config: &Config) -> Enrolable { - if !config.chat.daemon.url.trim().is_empty() { - return Enrolable::Yes; - } - if super::daemon::operator_token(config).is_some() { - return Enrolable::Yes; - } - Enrolable::No( - "no daemon is configured for this chat: set `chat.daemon.url` to the daemon's gateway, or \ - `chat.daemon.token` to a token it accepts", - ) -} - -/// The label this chat registers under. -/// -/// The workspace directory name: stable across restarts, which is what an -/// `assign_allow` rule needs, and already how an operator thinks about which -/// chat is which. The daemon treats it as self-declared and does not verify it. -fn label_for(config: &Config) -> String { - let raw = config - .workspace_dir - .file_name() - .map(|name| name.to_string_lossy().trim().to_string()) - .filter(|name| !name.is_empty()) - .unwrap_or_else(|| "chat".to_string()); - truncate_bytes(&raw, MAX_LABEL_BYTES) -} - -/// Cut a string to at most `limit` bytes, on a character boundary. -fn truncate_bytes(text: &str, limit: usize) -> String { - if text.len() <= limit { - return text.to_string(); - } - let mut end = limit; - while end > 0 && !text.is_char_boundary(end) { - end -= 1; - } - text.get(..end).unwrap_or_default().to_string() -} - -// ── Carrying an assignment through the ordinary input queue ───────────────── - -/// One assignment recognised on an input message. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Delivered { - pub assignment_id: String, - pub disposition: Disposition, -} - -/// Build the input message that carries one assignment into the chat queue. -/// -/// The content is the task verbatim for [`Disposition::Queue`], and prefixed -/// with `/now ` for the two that jump the queue — the same prefix a person -/// types to put their own input in front of the backlog, so priority ordering -/// stays one mechanism with one set of tests rather than two that can drift. -/// The prefix is consumed by `classify_input_priority`, so the model sees the -/// task and nothing else. -#[must_use] -pub fn assignment_message( - assignment: &PulledAssignment, - disposition: Disposition, -) -> crate::channels::traits::ChannelMessage { - let content = if disposition.jumps_the_queue() { - format!("/now {}", assignment.task) - } else { - assignment.task.clone() - }; - crate::channels::traits::ChannelMessage { - id: uuid::Uuid::new_v4().to_string(), - sender: format!("{SENDER_PREFIX}{}:{}", disposition.as_str(), assignment.assignment_id), - reply_target: ASSIGNMENT_REPLY_TARGET.to_string(), - content, - channel: ASSIGNMENT_CHANNEL.to_string(), - timestamp: std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap_or_default() - .as_secs(), - thread_ts: None, - chat_kind: crate::channels::traits::ChatKind::Dm, - chat_title: None, - sender_display: None, - mentioned_uuids: vec![], - mentioned: false, - is_group_hint: false, - sender_is_bot: false, - } -} - -/// Recognise an assignment on an input message, or `None` for ordinary input. -#[must_use] -pub fn delivered(msg: &crate::channels::traits::ChannelMessage) -> Option { - let rest = msg.sender.strip_prefix(SENDER_PREFIX)?; - let (disposition, assignment_id) = rest.split_once(':')?; - if assignment_id.is_empty() { - return None; - } - Some(Delivered { - assignment_id: assignment_id.to_string(), - disposition: Disposition::from_wire(disposition), - }) -} - -// ── What the operator sees ────────────────────────────────────────────────── - -/// The line shown when an assignment arrives. -/// -/// Someone other than the person at the keyboard just put work into this -/// terminal. Where it came from, how it was dispatched, and enough of the task -/// to recognise it all have to be on screen; the origin is already a -/// fingerprint by the time it reaches here, and is passed through unchanged. -#[must_use] -pub fn arrival_notice(assignment: &PulledAssignment, disposition: Disposition) -> String { - let origin = origin_label(assignment); - let preview = preview_of(&assignment.task); - let redelivery = if assignment.deliveries > 1 { - format!(" (redelivery #{})", assignment.deliveries) - } else { - String::new() - }; - let dispatched = match disposition { - Disposition::Queue => "queued behind whatever this chat is already doing", - Disposition::Steer => "put in front of the queue; the turn in flight keeps running", - Disposition::Interrupt => "the turn in flight is being ended first", - }; - format!( - "Assigned by {origin}{redelivery}: {preview}\n Disposition {} — {dispatched}.", - disposition.as_str() - ) -} - -/// The line shown when a disposition this chat does not know arrives. -#[must_use] -pub fn unknown_disposition_notice(raw: &str) -> String { - format!( - "Daemon assignment carried disposition {raw:?}, which this chat does not know; running it as \ - `queue`. A word this chat cannot read is never treated as permission to end a turn." - ) -} - -/// The line shown when a result was handed back to the daemon. -#[must_use] -pub fn reported_notice(assignment_id: &str, status: ResultStatus, seq: u64) -> String { - format!( - "Reported {} for daemon assignment {} (result #{seq}).", - status.as_str(), - short_id(assignment_id) - ) -} - -/// The line shown when a result could not be handed back. -#[must_use] -pub fn report_failure_notice(assignment_id: &str, status: ResultStatus, error: &anyhow::Error) -> String { - let error = crate::security::redaction::redact_provider_text(&format!("{error:#}")); - format!( - "Could not report {} for daemon assignment {}: {error}. The daemon still has it outstanding; \ - whoever assigned it is waiting.", - status.as_str(), - short_id(assignment_id) - ) -} - -/// The line shown when this chat could not enrol. -#[must_use] -pub fn enrolment_failure_notice(base_url: &str, error: &anyhow::Error) -> String { - let base_url = crate::security::redaction::redact_provider_text(base_url); - let error = crate::security::redaction::redact_provider_text(&format!("{error:#}")); - format!( - "This chat could not enrol with the daemon at {base_url}, so it cannot be assigned work: {error}\n\ - Everything else in this chat is unaffected. Restart chat once the daemon accepts it to become \ - assignable again." - ) -} - -/// The line shown when this chat had to register with the daemon again. -/// -/// Not silent, and not a warning either: the session id and the mailbox behind -/// it are new, so anything an operator wrote down about the old one — a -/// `--session` argument, an `assign_allow` rule keyed on the id — is stale, and -/// the only place they can learn that is here. Printed once per re-enrolment, -/// which is once per daemon restart rather than once per poll. -#[must_use] -pub fn re_enrolled_notice(base_url: &str, session_ref: &str) -> String { - format!( - "The daemon at {base_url} no longer had this chat's registration — it keeps them in memory, so a \ - restart forgets every one — and this chat registered again as {session_ref}. It is assignable \ - again; anything queued for the old registration is gone with it." - ) -} - -/// The line shown once this chat is assignable. -#[must_use] -pub fn enrolled_notice(label: &str, session_ref: &str, base_url: &str) -> String { - format!("This chat is assignable at {base_url} as {label} ({session_ref}).") -} - -fn origin_label(assignment: &PulledAssignment) -> String { - let channel = if assignment.origin_channel.trim().is_empty() { - "unknown" - } else { - assignment.origin_channel.trim() - }; - assignment - .origin_ref - .as_deref() - .map(str::trim) - .filter(|origin_ref| !origin_ref.is_empty()) - .map_or_else(|| channel.to_string(), |origin_ref| format!("{channel} {origin_ref}")) -} - -fn preview_of(task: &str) -> String { - let first_line = task.lines().next().unwrap_or("").trim(); - if first_line.chars().count() <= TASK_PREVIEW_CHARS { - return first_line.to_string(); - } - let head: String = first_line.chars().take(TASK_PREVIEW_CHARS).collect(); - format!("{head}…") -} - -fn short_id(assignment_id: &str) -> String { - let head: String = assignment_id.chars().take(8).collect(); - if head.is_empty() { "?".to_string() } else { head } -} - -/// Fit a summary into what the daemon accepts: never empty, never oversized. -/// -/// The daemon refuses both, and a refusal here would lose the only account of -/// what happened. Truncation says so in the text rather than silently handing -/// back a sentence that stops mid-word. -#[must_use] -pub fn bound_summary(text: &str) -> String { - let trimmed = text.trim(); - if trimmed.is_empty() { - return "(this chat produced no text for the assignment)".to_string(); - } - if trimmed.len() <= MAX_SUMMARY_BYTES { - return trimmed.to_string(); - } - const MARKER: &str = "\n… (truncated by chat to fit the result field)"; - truncate_bytes(trimmed, MAX_SUMMARY_BYTES.saturating_sub(MARKER.len())) + MARKER -} - -// ── Reporting one assignment's turn ───────────────────────────────────────── - -/// Default account when a turn ends without a reply to report. -const NO_REPLY_SUMMARY: &str = "This chat ended the turn for the assignment without producing a reply. \ - The input may have been handled as a local chat command, or the turn was \ - ended before it answered."; - -/// Reports one assignment's outcome when the turn that ran it ends, whichever -/// way it ends. -/// -/// A guard rather than a call at the end of the turn because the turn body has -/// many exits: a slash command short-circuits it, a cancellation unwinds it, a -/// quit breaks out of the loop entirely. Anything that only reported on the -/// straight-line path would leave the assigner waiting forever on exactly the -/// cases they most need to hear about. Dropping is the one thing every exit has -/// in common. -/// -/// The one exit that must *not* report is a requeue: the message goes back into -/// the backlog and will run later, so [`AssignmentTurnGuard::disarm`] is called -/// there and the next attempt takes over. -pub struct AssignmentTurnGuard { - mailbox: Arc, - in_flight: InFlightRegistry, - notify: Arc, - assignment_id: String, - outcome: Option<(ResultStatus, String)>, - armed: bool, -} - -impl AssignmentTurnGuard { - /// Arm a report for one assignment. - #[must_use] - pub fn new( - mailbox: Arc, - in_flight: InFlightRegistry, - notify: Arc, - assignment_id: String, - ) -> Self { - Self { - mailbox, - in_flight, - notify, - assignment_id, - outcome: None, - armed: true, - } - } - - /// Record the reply this turn produced. - /// - /// The daemon stores the report as the assignment's result, so the reply - /// is redacted like the terminal commit first (D-053). - pub fn completed(&mut self, reply: &str) { - self.outcome = Some(( - ResultStatus::Completed, - bound_summary(&crate::agent::terminal::redact_persisted_text(reply)), - )); - } - - /// Record that the turn ran and failed, with the reason (redacted like - /// the reply). - pub fn failed(&mut self, reason: &str) { - self.outcome = Some(( - ResultStatus::Failed, - bound_summary(&crate::agent::terminal::redact_persisted_text(reason)), - )); - } - - /// Give up the report because this assignment has not actually run yet. - /// - /// Used where the input is put back on the backlog: reporting there would - /// answer for a turn that is still going to happen, and the daemon would - /// then refuse the real report as unknown. - pub const fn disarm(&mut self) { - self.armed = false; - } - - /// Whether this guard will still report when dropped. - #[must_use] - pub const fn is_armed(&self) -> bool { - self.armed - } - - /// The status and summary this guard would report right now. - #[must_use] - pub fn pending_outcome(&self) -> (ResultStatus, String) { - self.outcome - .clone() - .unwrap_or_else(|| (ResultStatus::Failed, NO_REPLY_SUMMARY.to_string())) - } -} - -impl Drop for AssignmentTurnGuard { - fn drop(&mut self) { - if !self.armed { - return; - } - let (status, summary) = self.pending_outcome(); - let Ok(handle) = tokio::runtime::Handle::try_current() else { - // Outside a runtime there is nothing to spawn onto. Say so where it - // can be found rather than pretending the report went out. - let status_label: &'static str = status.as_str(); - tracing::warn!( - assignment = %crate::agent::diagnostics::text_class(&self.assignment_id), - status = status_label, - "no tokio runtime to report a daemon assignment result on" - ); - return; - }; - let mailbox = Arc::clone(&self.mailbox); - let notify = Arc::clone(&self.notify); - let assignment_id = self.assignment_id.clone(); - // The report is a request to the daemon like any other, so it is listed - // and endable while it runs: a daemon that accepts the connection and - // never answers must not leave an invisible task behind. - let cancel = CancellationToken::new(); - let guard = register_in_flight_labeled( - &self.in_flight, - &format!("assignment result {}", short_id(&assignment_id)), - &mailbox.base_url(), - cancel.clone(), - ); - handle.spawn(async move { - let _row = guard; - let outcome = tokio::select! { - () = cancel.cancelled() => None, - outcome = mailbox.report(assignment_id.clone(), status, summary) => Some(outcome), - }; - match outcome { - Some(Ok(receipt)) => notify(&reported_notice(&assignment_id, status, receipt.seq)), - Some(Err(error)) => notify(&report_failure_notice(&assignment_id, status, &error)), - None => notify(&format!( - "Stopped waiting on the daemon's acknowledgement for assignment {}. The result may or \ - may not have landed.", - short_id(&assignment_id) - )), - } - }); - } -} - -// ── How often a failing pull is allowed to say so ─────────────────────────── - -/// How many distinct failure reasons this policy will ever announce. -/// -/// The reason text comes from the daemon, so a peer whose message varies (an -/// id, a counter, a clock) could otherwise grow this set without bound. Past -/// the cap nothing new is announced and nothing new is remembered; the log -/// still has every occurrence. -const MAX_TRACKED_REASONS: usize = 16; - -/// One unbroken run of failing pulls, all with the same reason. -#[derive(Debug, Clone)] -struct FailingEpisode { - reason: String, - /// Failing pulls in this episode, announced or not — the number the - /// recovery line quotes. - pulls: u64, - /// Whether this episode's reason reached the screen. A recovery is only - /// announced for an episode that was, or the operator is told something - /// healed that they were never told had broken. - announced: bool, -} - -/// Decides what a failing — and a recovering — pull is allowed to say. -/// -/// # Why the obvious version was not enough -/// -/// The first version kept the *last* failure text, skipped a repeat of it, and -/// cleared it on any successful pull. That holds only while failure is -/// sustained. The failure it was written against was not: the daemon rate -/// limited the mailbox, so pulls alternated success, refusal, success, refusal -/// — and every success cleared the key, so every refusal was "new" and printed -/// again. The dedup was real and the flood was real at the same time. -/// -/// So the key here is the reason itself and it is kept **across** recoveries: -/// one distinct reason is stated once for the life of one poller, and its -/// recovery once. Alternating failures collapse onto that one statement instead -/// of resetting it, which is the property the flood needed and the previous -/// version did not have. The ceiling is total, not per-interval: no failure -/// mode, however it recurs, can cost more than two lines per distinct reason. -/// -/// What that trades away is being told a second time that a reason that has -/// already been announced and recovered is back. That is the deliberate side to -/// err on: a stale silence costs an operator one `/sessions --daemon`, and a -/// screen full of the same sentence costs them the chat they were using. -#[derive(Debug, Default)] -pub struct FailureNotices { - /// Reasons already put on screen. Kept across recoveries on purpose. - announced: std::collections::HashSet, - /// Reasons whose recovery has already been put on screen. - recovered: std::collections::HashSet, - episode: Option, -} - -impl FailureNotices { - /// Record a failing pull, returning the line to show — or `None` when this - /// reason has already said everything it is allowed to say. - pub fn failed(&mut self, reason: &str) -> Option { - let reason = crate::security::redaction::redact_provider_text(reason); - let reason = reason.as_str(); - if self.episode.as_ref().is_none_or(|episode| episode.reason != reason) { - self.episode = Some(FailingEpisode { - reason: reason.to_string(), - pulls: 0, - announced: false, - }); - } - let episode = self.episode.as_mut()?; - episode.pulls = episode.pulls.saturating_add(1); - if self.announced.contains(reason) || self.announced.len() >= MAX_TRACKED_REASONS { - let failed_pulls: u64 = episode.pulls; - tracing::debug!(reason = %crate::agent::diagnostics::text_class(reason), failed_pulls, "chat assignment pull is still failing"); - return None; - } - self.announced.insert(reason.to_string()); - episode.announced = true; - Some(pull_failure_notice(reason)) - } - - /// Record a successful pull, returning the line to show when it ends an - /// episode the operator was told about. - pub fn recovered(&mut self) -> Option { - let episode = self.episode.take()?; - if !episode.announced || !self.recovered.insert(episode.reason.clone()) { - return None; - } - Some(pull_recovery_notice(&episode.reason, episode.pulls)) - } - - /// End the failing episode without a recovery line, for a caller that has - /// already said something more specific about the same recovery. - /// - /// The re-enrolment notice is exactly that: it names what was wrong and - /// says this chat is assignable again, so adding the generic line after it - /// would say the same thing twice. - pub fn settled(&mut self) { - self.episode = None; - } - - /// Whether a failing episode is currently open. - #[must_use] - pub const fn is_failing(&self) -> bool { - self.episode.is_some() - } -} - -/// The line shown when this chat's mailbox cannot be reached. -#[must_use] -pub fn pull_failure_notice(reason: &str) -> String { - format!( - "Daemon assignments are not being received: {reason}\nThis chat keeps asking, and nothing else \ - is affected. This reason will not be repeated here; further occurrences of it go to the log." - ) -} - -/// The line shown when the mailbox answers again after a run of failures. -#[must_use] -pub fn pull_recovery_notice(reason: &str, failed_pulls: u64) -> String { - let cause = reason.lines().next().unwrap_or(reason).trim(); - let pulls = if failed_pulls == 1 { "pull" } else { "pulls" }; - format!( - "Daemon assignments are being received again after {failed_pulls} failed {pulls} ({cause}). \ - This chat can be assigned work again." - ) -} - -// ── The poll loop ─────────────────────────────────────────────────────────── - -/// Where one pulled batch went, so the loop's ordering can be asserted. -#[derive(Debug, Default, PartialEq, Eq)] -pub struct BatchOutcome { - /// Ids handed to the local input queue by this batch, in order. - pub delivered: Vec, - /// Ids already held from an earlier delivery, taken again and not re-run. - pub duplicates: Vec, - /// Ids to acknowledge on the *next* pull. - pub acks: Vec, - /// True when the input queue is gone and the loop should stop. - pub input_closed: bool, -} - -/// Hand one pulled batch to the chat input queue. -/// -/// The ordering here is the whole point, and it is the reverse of the obvious -/// one: an id joins `acks` only **after** the message it carries has been -/// accepted by the local queue. Acknowledging first would tell the daemon the -/// work is safe at the moment it is least safe — still in flight, owned by -/// nobody — and a process that died there would take it with it. Paying for -/// that with an occasional redelivery is the trade the mailbox is designed -/// around, and `taken` is what makes a redelivery cost nothing. -/// -/// MUTATION GUARD: move the `acks.push` above the `send` and -/// `a_batch_is_acknowledged_only_after_it_reaches_the_local_queue` fails. -pub async fn take_batch( - mailbox: &dyn AssignmentMailbox, - batch: Vec, - input: &crate::runtime::h2_entry::ChatInputSender, - notify: &(dyn Fn(&str) + Send + Sync), -) -> BatchOutcome { - let mut outcome = BatchOutcome::default(); - for assignment in batch { - let id = assignment.assignment_id.clone(); - if !mailbox.accept(&id) { - // A redelivery of work already queued here. Acknowledge it so the - // daemon stops resending, and do not run it a second time. - outcome.duplicates.push(id.clone()); - outcome.acks.push(id); - continue; - } - if !Disposition::is_known_wire(&assignment.disposition) { - notify(&unknown_disposition_notice(&assignment.disposition)); - } - let disposition = Disposition::from_wire(&assignment.disposition); - let message = assignment_message(&assignment, disposition); - // Announced before it is handed over, not after: the turn can start, - // finish and print its answer before this task is scheduled again, and - // an announcement that lands after the answer explains nothing. - notify(&arrival_notice(&assignment, disposition)); - if input.send(message).await.is_err() { - // The chat loop is gone. The id is deliberately *not* acknowledged: - // nothing here will ever run it, so the daemon should keep it. - outcome.input_closed = true; - return outcome; - } - outcome.delivered.push(id.clone()); - outcome.acks.push(id); - } - outcome -} - -/// Enrol with the daemon, then pull this chat's mailbox until it is ended. -/// -/// Enrolment runs **here**, inside the spawned task, rather than on the startup -/// path: reaching a daemon can take as long as a TCP connect takes, and a chat -/// that will not show a prompt until some other process answers has made a -/// convenience into a dependency. A refusal costs exactly one capability, is -/// stated once, and everything else about this chat is unchanged. -/// -/// The enrolment call is itself listed and endable while it runs, for the same -/// reason every other daemon call in this process is. -pub async fn enrol_and_poll( - client: Arc, - in_flight: InFlightRegistry, - input: crate::runtime::h2_entry::ChatInputSender, - notify: Arc, - cancel: CancellationToken, -) { - let base_url = client.base_url(); - let enrolling = register_in_flight_labeled(&in_flight, "assignment enrolment", &base_url, cancel.clone()); - let enrolled = tokio::select! { - () = cancel.cancelled() => return, - result = client.enrol() => result, - }; - drop(enrolling); - match enrolled { - Ok(session_ref) => notify(&enrolled_notice(client.label(), &session_ref, &base_url)), - Err(error) => { - notify(&enrolment_failure_notice(&base_url, &error)); - return; - } - } - run_poller(client, in_flight, input, notify, cancel).await; -} - -/// Pull this chat's mailbox until it is cancelled or the chat loop ends. -/// -/// Registers itself in the chat's own in-flight list first, so `/sessions` -/// shows it and `/kill --daemon d` ends it — the same answer to a stuck -/// daemon that every other request in this process gets, and the reason none of -/// this needs a clock. -/// -/// MUTATION GUARD: drop the re-enrolment arm — treat a refusal that says this -/// session is unregistered like any other failure — and -/// `a_daemon_that_forgot_this_session_is_answered_by_registering_again` fails: -/// the poller keeps asking with credentials nothing recognises until a human -/// restarts the chat. -pub async fn run_poller( - mailbox: Arc, - in_flight: InFlightRegistry, - input: crate::runtime::h2_entry::ChatInputSender, - notify: Arc, - cancel: CancellationToken, -) { - let session_ref = mailbox.session_ref(); - let row: InFlightGuard = register_in_flight_labeled( - &in_flight, - &format!("assignment poll {session_ref}"), - &mailbox.base_url(), - cancel.clone(), - ); - let _row = row; - let mut pending_acks: Vec = Vec::new(); - let mut notices = FailureNotices::default(); - // When this poller last tried to register again, so a daemon that forgets - // this session on every pull cannot buy one notice per poll interval. A - // clock reading, not a timer: nothing here waits on it. - let mut last_re_enrolment: Option = None; - loop { - let pull = tokio::select! { - () = cancel.cancelled() => break, - pull = mailbox.pull(pending_acks.clone()) => pull, - }; - match pull { - Ok(batch) => { - // The acknowledgements rode along with this request and the - // daemon answered, so they are spent. Anything new takes their - // place only once it is in the local queue. - pending_acks.clear(); - if let Some(line) = notices.recovered() { - notify(&line); - } - let outcome = take_batch(mailbox.as_ref(), batch.assignments, &input, notify.as_ref()).await; - pending_acks = outcome.acks; - if outcome.input_closed { - break; - } - } - Err(error) if tasks_cli::session_is_unregistered(&error) => { - // The daemon holds no row for this session: it restarted — the - // registry is process memory and rebuilds nothing — or an - // operator removed the row. Either way this chat is - // unassignable until it registers again, and requiring a human - // to restart every chat after every daemon restart is not a - // recovery. Registering again is, and the next pull is the - // natural retry for a registration that also fails: this loop - // is already periodic, so nothing here needs a timer. - // - // Whatever happens next, the acknowledgements were for a mailbox - // that no longer exists. Sending them to a new session would - // acknowledge ids it never handed out. - pending_acks.clear(); - // At most one attempt per [`RE_ENROLMENT_MIN_INTERVAL`]: a daemon - // stuck in "who are you?" answers every pull, and re-registering - // on each one would put a notice on screen every poll interval. - if last_re_enrolment.is_some_and(|at| at.elapsed() < RE_ENROLMENT_MIN_INTERVAL) { - tracing::debug!( - session = %crate::agent::diagnostics::text_class(&session_ref), - "daemon still does not know this chat session; re-enrolment is rate limited" - ); - tokio::select! { - () = cancel.cancelled() => break, - () = tokio::time::sleep(POLL_INTERVAL) => {} - } - continue; - } - last_re_enrolment = Some(tokio::time::Instant::now()); - let stale = mailbox.enrolment_generation(); - let re_enrolled = tokio::select! { - () = cancel.cancelled() => break, - outcome = mailbox.re_enrol(stale) => outcome, - }; - match re_enrolled { - Ok(ReEnrolment::Registered { session_ref }) => { - notices.settled(); - notify(&re_enrolled_notice(&mailbox.base_url(), &session_ref)); - } - // Someone else had already replaced this enrolment. Saying - // so again would be one line per poller for one event. - Ok(ReEnrolment::Superseded { .. }) => notices.settled(), - Err(error) => { - if let Some(line) = notices.failed(&format!("{error:#}")) { - notify(&line); - } - } - } - } - Err(error) => { - // What is allowed to reach the screen is [`FailureNotices`]'s - // decision, not this loop's: a reason that recurs — including - // one that alternates with success — must cost a bounded number - // of lines, or the failure buries the chat somebody is using. - if let Some(line) = notices.failed(&format!("{error:#}")) { - notify(&line); - } - } - } - tokio::select! { - () = cancel.cancelled() => break, - () = tokio::time::sleep(POLL_INTERVAL) => {} - } - } - // Nothing is announced on the way out. A poller ends for exactly two - // reasons: an operator killed it, and `cancel_in_flight` already told them - // so by name; or the chat loop is gone, and there is no longer anywhere for - // a notice to be read. -} - -#[cfg(test)] -#[allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)] -mod tests { - use super::*; - use std::sync::atomic::{AtomicUsize, Ordering}; - - fn assignment(id: &str, task: &str, disposition: &str) -> PulledAssignment { - PulledAssignment { - assignment_id: id.to_string(), - session_id: "session".to_string(), - task: task.to_string(), - disposition: disposition.to_string(), - deliveries: 1, - created_at_unix_ms: 0, - work_id: "w1".to_string(), - origin_channel: "wacli".to_string(), - origin_ref: Some("3d1a4f5b".to_string()), - } - } - - fn silent() -> Arc { - Arc::new(|_: &str| {}) - } - - fn client_for_tests() -> Arc { - let config = Config::default(); - AssignmentClient::new(&config) - } - - /// One scripted answer to a pull. - enum Answer { - /// Hand these assignments over. - Batch(Vec), - /// Refuse with this reason. - Refuse(&'static str), - /// Refuse the way a daemon that has forgotten this session does: a - /// `404` carrying the registry's own machine tag. - ForgotTheSession, - /// Refuse the way a daemon answers when the *assignment* is unknown — - /// the same status, a different tag, and never a reason to register - /// again. - ForgotTheAssignment, - } - - /// A refusal in the shape the daemon really sends one, so the poller's - /// decision is made on the wire form rather than on a sentence. - fn refusal(status: u16, code: &str, detail: &str) -> anyhow::Error { - let body = serde_json::json!({ "error": detail, "code": code }).to_string(); - tasks_cli::refusal_for_tests(status, &body, "chat assignment pull") - } - - /// Records every pull's `ack` array and every report, and answers from a - /// script. Enough to assert the loop's ordering without a live daemon. - struct RecordingMailbox { - base_url: String, - pulls: Mutex>>, - reports: Mutex>, - script: Mutex>, - taken: Mutex>, - seq: AtomicUsize, - /// Which enrolment this double is on; bumped by every registration. - generation: Mutex, - /// How many times the poller registered again. - registrations: AtomicUsize, - /// How many times it *tried*, successful or not: what the re-enrolment - /// rate limit is about. - re_enrol_attempts: AtomicUsize, - /// Makes registration fail, for the case where the daemon is not just - /// forgetful but down. - refuse_registration: std::sync::atomic::AtomicBool, - } - - impl RecordingMailbox { - fn new(script: Vec>) -> Arc { - Self::scripted(script.into_iter().map(Answer::Batch).collect()) - } - - fn scripted(script: Vec) -> Arc { - Arc::new(Self { - base_url: "http://127.0.0.1:9".to_string(), - pulls: Mutex::new(Vec::new()), - reports: Mutex::new(Vec::new()), - script: Mutex::new(script), - taken: Mutex::new(HashSet::new()), - seq: AtomicUsize::new(0), - generation: Mutex::new(1), - registrations: AtomicUsize::new(0), - re_enrol_attempts: AtomicUsize::new(0), - refuse_registration: std::sync::atomic::AtomicBool::new(false), - }) - } - } - - impl AssignmentMailbox for RecordingMailbox { - fn session_ref(&self) -> String { - "9b2e0f7c".to_string() - } - - fn base_url(&self) -> String { - self.base_url.clone() - } - - fn pull(&self, ack: Vec) -> MailboxFuture<'_, AssignmentPull> { - self.pulls.lock().push(ack); - let answer = { - let mut script = self.script.lock(); - if script.is_empty() { - Answer::Batch(Vec::new()) - } else { - script.remove(0) - } - }; - Box::pin(async move { - match answer { - Answer::Batch(assignments) => Ok(AssignmentPull { - assignments, - acked: 0, - requeued: 0, - queued_remaining: 0, - }), - Answer::Refuse(reason) => Err(anyhow::anyhow!("{reason}")), - Answer::ForgotTheSession => Err(refusal( - 404, - "unknown_session", - "no chat session with that id is registered; `GET /api/chat-sessions` lists the live ones", - )), - Answer::ForgotTheAssignment => Err(refusal( - 404, - "unknown_assignment", - "that assignment is not outstanding for this session", - )), - } - }) - } - - fn report( - &self, - assignment_id: String, - status: ResultStatus, - summary: String, - ) -> MailboxFuture<'_, AssignmentReceipt> { - self.reports.lock().push((assignment_id.clone(), status, summary)); - let seq = self.seq.fetch_add(1, Ordering::SeqCst) as u64 + 1; - Box::pin(async move { - Ok(AssignmentReceipt { - assignment_id, - status: status.as_str().to_string(), - seq, - }) - }) - } - - fn accept(&self, assignment_id: &str) -> bool { - self.taken.lock().insert(assignment_id.to_string()) - } - - fn enrolment_generation(&self) -> u64 { - *self.generation.lock() - } - - fn re_enrol(&self, stale: u64) -> MailboxFuture<'_, ReEnrolment> { - self.re_enrol_attempts.fetch_add(1, Ordering::SeqCst); - Box::pin(async move { - if self.refuse_registration.load(Ordering::SeqCst) { - anyhow::bail!("cannot reach a running PRX process at {}", self.base_url); - } - let mut generation = self.generation.lock(); - if *generation != stale { - return Ok(ReEnrolment::Superseded { - session_ref: "9b2e0f7c".to_string(), - }); - } - *generation = stale + 1; - self.registrations.fetch_add(1, Ordering::SeqCst); - Ok(ReEnrolment::Registered { - session_ref: format!("re-enrolled-{}", *generation), - }) - }) - } - } - - #[tokio::test] - async fn a_batch_is_acknowledged_only_after_it_reaches_the_local_queue() { - let client = client_for_tests(); - let (tx, mut rx) = tokio::sync::mpsc::channel::(4); - let tx: crate::runtime::h2_entry::ChatInputSender = tx.into(); - let outcome = take_batch( - client.as_ref(), - vec![assignment("a-1", "summarise the repo", "queue")], - &tx, - silent().as_ref(), - ) - .await; - assert_eq!(outcome.delivered, vec!["a-1".to_string()]); - assert_eq!( - outcome.acks, - vec!["a-1".to_string()], - "an assignment safely in the local queue is acknowledged on the next pull" - ); - assert!(rx.try_recv().is_ok(), "the assignment must reach the chat input queue"); - - // The same call with nowhere to deliver must acknowledge nothing: work - // this chat cannot run has to stay the daemon's. - let client2 = client_for_tests(); - let (closed_tx, closed_rx) = tokio::sync::mpsc::channel::(1); - let closed_tx: crate::runtime::h2_entry::ChatInputSender = closed_tx.into(); - drop(closed_rx); - let refused = take_batch( - client2.as_ref(), - vec![assignment("a-2", "do a thing", "queue")], - &closed_tx, - silent().as_ref(), - ) - .await; - assert!(refused.input_closed); - assert!( - refused.acks.is_empty(), - "work that never reached the local queue must not be acknowledged: {:?}", - refused.acks - ); - } - - #[tokio::test] - async fn a_redelivered_assignment_is_acknowledged_but_never_run_twice() { - let client = client_for_tests(); - let (tx, mut rx) = tokio::sync::mpsc::channel::(8); - let tx: crate::runtime::h2_entry::ChatInputSender = tx.into(); - let first = take_batch( - client.as_ref(), - vec![assignment("dup", "work", "queue")], - &tx, - silent().as_ref(), - ) - .await; - assert_eq!(first.delivered, vec!["dup".to_string()]); - - let mut again = assignment("dup", "work", "queue"); - again.deliveries = 2; - let second = take_batch(client.as_ref(), vec![again], &tx, silent().as_ref()).await; - assert!( - second.delivered.is_empty(), - "a redelivery of held work must not be queued again: {:?}", - second.delivered - ); - assert_eq!(second.duplicates, vec!["dup".to_string()]); - assert_eq!( - second.acks, - vec!["dup".to_string()], - "a redelivery must still be acknowledged, or the daemon keeps resending it" - ); - assert!(rx.try_recv().is_ok()); - assert!( - rx.try_recv().is_err(), - "exactly one input message may exist for one assignment id" - ); - } - - #[tokio::test] - async fn the_first_pull_acknowledges_nothing_and_the_second_acknowledges_the_first_batch() { - let mailbox = RecordingMailbox::new(vec![vec![assignment("a-1", "one", "queue")], vec![]]); - let client = client_for_tests(); - let (tx, _rx) = tokio::sync::mpsc::channel::(8); - let tx: crate::runtime::h2_entry::ChatInputSender = tx.into(); - - // Drive the same two steps the loop drives, without its sleep. - let mut pending: Vec = Vec::new(); - for _ in 0..2u8 { - let batch = mailbox.pull(pending.clone()).await.unwrap(); - pending.clear(); - let outcome = take_batch(client.as_ref(), batch.assignments, &tx, silent().as_ref()).await; - pending = outcome.acks; - } - let pulls = mailbox.pulls.lock().clone(); - assert_eq!(pulls.len(), 2); - assert!( - pulls[0].is_empty(), - "the first pull cannot acknowledge anything it has not received yet: {:?}", - pulls[0] - ); - assert_eq!( - pulls[1], - vec!["a-1".to_string()], - "the batch taken by the first pull is acknowledged by the second" - ); - } - - #[tokio::test] - async fn a_dropped_turn_guard_reports_a_failure_rather_than_going_quiet() { - let mailbox = RecordingMailbox::new(vec![]); - let registry = super::super::daemon::new_in_flight_registry(); - { - let _guard = AssignmentTurnGuard::new( - Arc::clone(&mailbox) as Arc, - Arc::clone(®istry), - silent(), - "a-1".to_string(), - ); - } - tokio::task::yield_now().await; - let reports = mailbox.reports.lock().clone(); - assert_eq!( - reports.len(), - 1, - "a turn that ended without a reply still owes an answer" - ); - assert_eq!(reports[0].0, "a-1"); - assert_eq!(reports[0].1, ResultStatus::Failed); - assert!(!reports[0].2.trim().is_empty(), "expected a non-empty value"); - } - - #[tokio::test] - async fn a_completed_turn_reports_its_reply() { - let mailbox = RecordingMailbox::new(vec![]); - let registry = super::super::daemon::new_in_flight_registry(); - { - let mut guard = AssignmentTurnGuard::new( - Arc::clone(&mailbox) as Arc, - Arc::clone(®istry), - silent(), - "a-2".to_string(), - ); - guard.completed("37 TODOs"); - } - tokio::task::yield_now().await; - let reports = mailbox.reports.lock().clone(); - assert_eq!(reports.len(), 1); - assert_eq!(reports[0].1, ResultStatus::Completed); - assert_eq!(reports[0].2, "37 TODOs"); - } - - /// D-053 / REDACT-TURN: the daemon stores an assignment report as the - /// assignment's result, so the reply and the failure reason are redacted - /// before they leave the chat. Fails before REDACT-TURN. - #[tokio::test] - async fn an_assignment_report_carries_no_secret_from_the_reply_or_the_failure() { - use crate::agent::terminal::persistence_probe::PROBE_SECRET; - let mailbox = RecordingMailbox::new(vec![]); - let registry = super::super::daemon::new_in_flight_registry(); - { - let mut completed = AssignmentTurnGuard::new( - Arc::clone(&mailbox) as Arc, - Arc::clone(®istry), - silent(), - "a-secret-1".to_string(), - ); - completed.completed(&format!("Here is the key {PROBE_SECRET} you asked for")); - let mut failed = AssignmentTurnGuard::new( - Arc::clone(&mailbox) as Arc, - Arc::clone(®istry), - silent(), - "a-secret-2".to_string(), - ); - failed.failed(&format!("redux driver failed: upstream rejected key {PROBE_SECRET}")); - } - tokio::task::yield_now().await; - let reports = mailbox.reports.lock().clone(); - assert_eq!(reports.len(), 2, "both turns report"); - for report in &reports { - assert!(!report.2.contains(PROBE_SECRET), "{report:?}"); - assert!(report.2.contains("[REDACTED]"), "{report:?}"); - } - } - - #[tokio::test] - async fn a_disarmed_guard_reports_nothing_because_the_work_still_has_to_run() { - let mailbox = RecordingMailbox::new(vec![]); - let registry = super::super::daemon::new_in_flight_registry(); - { - let mut guard = AssignmentTurnGuard::new( - Arc::clone(&mailbox) as Arc, - Arc::clone(®istry), - silent(), - "a-3".to_string(), - ); - guard.disarm(); - assert!(!guard.is_armed()); - } - tokio::task::yield_now().await; - assert!( - mailbox.reports.lock().is_empty(), - "a requeued assignment must not be answered for before it runs" - ); - } - - /// Collects every line the poller put on screen. - fn recording_notifier() -> (Arc, Arc>>) { - let lines = Arc::new(Mutex::new(Vec::new())); - let sink = Arc::clone(&lines); - let notify: Arc = Arc::new(move |text: &str| sink.lock().push(text.to_string())); - (notify, lines) - } - - /// Lines the poller printed to say the mailbox is failing, for a reason - /// containing `marker`. The recovery line quotes the reason it is about, so - /// counting occurrences of the reason alone would count that too. - fn complaints_about(said: &[String], marker: &str) -> usize { - said.iter() - .filter(|line| line.starts_with("Daemon assignments are not being received") && line.contains(marker)) - .count() - } - - /// Drive the poller over a script and hand back everything it said. - /// - /// `start_paused` because the loop sleeps a poll interval between pulls: the - /// interval is a sampling rate, and simulating it is what keeps a test about - /// twenty pulls from taking thirty seconds. - async fn lines_from_script(script: Vec) -> Vec { - drive_script(RecordingMailbox::scripted(script)).await.1 - } - - /// Drive a prepared mailbox to the end of its script, handing back the - /// mailbox and everything the poller said. - async fn drive_script(mailbox: Arc) -> (Arc, Vec) { - let pulls_scripted = mailbox.script.lock().len(); - let (notify, lines) = recording_notifier(); - let registry = super::super::daemon::new_in_flight_registry(); - let (tx, _rx) = tokio::sync::mpsc::channel::(8); - let tx: crate::runtime::h2_entry::ChatInputSender = tx.into(); - let cancel = CancellationToken::new(); - let handle = tokio::spawn(run_poller( - Arc::clone(&mailbox) as Arc, - registry, - tx, - notify, - cancel.clone(), - )); - for _ in 0..(pulls_scripted * 4 + 8) { - if mailbox.pulls.lock().len() > pulls_scripted { - break; - } - tokio::time::sleep(POLL_INTERVAL).await; - } - cancel.cancel(); - handle.await.expect("the poller must end when it is cancelled"); - assert!( - mailbox.pulls.lock().len() > pulls_scripted, - "the script must have been driven to the end" - ); - let said = lines.lock().clone(); - (mailbox, said) - } - - const RATE_LIMITED: &str = "chat assignment pull failed with HTTP 429 Too Many Requests: \ - Too many API requests. Please retry later."; - const UNREACHABLE: &str = "cannot reach a running PRX process at http://127.0.0.1:9"; - - /// A daemon restart forgets every registration, and this chat holds a - /// session id nothing answers to. Registering again is the recovery, and it - /// happens here rather than in whoever notices the chat stopped working. - #[tokio::test(start_paused = true)] - async fn a_daemon_that_forgot_this_session_is_answered_by_registering_again() { - let (mailbox, said) = drive_script(RecordingMailbox::scripted(vec![ - Answer::Batch(vec![]), - Answer::ForgotTheSession, - Answer::Batch(vec![assignment("after-restart", "count the crates", "queue")]), - ])) - .await; - assert_eq!( - mailbox.registrations.load(Ordering::SeqCst), - 1, - "the poller must register again by itself; said:\n{said:#?}" - ); - assert_eq!(*mailbox.generation.lock(), 2, "the new enrolment replaces the old one"); - assert!( - mailbox.taken.lock().contains("after-restart"), - "the point of re-enrolling is taking work again, and this chat took none" - ); - assert!( - said.iter().any(|line| line.contains("registered again")), - "a new session id is a fact the operator has to be told; said:\n{said:#?}" - ); - assert!( - !said.iter().any(|line| line.contains("are not being received")), - "a restart that healed itself must not be reported as a failure; said:\n{said:#?}" - ); - } - - /// The acknowledgements from before the restart belong to a mailbox that no - /// longer exists; sending them on would acknowledge ids the new session - /// never handed out. - #[tokio::test(start_paused = true)] - async fn work_acknowledged_to_the_old_session_is_not_acknowledged_to_the_new_one() { - let (mailbox, _said) = drive_script(RecordingMailbox::scripted(vec![ - Answer::Batch(vec![assignment("before-restart", "work", "queue")]), - Answer::ForgotTheSession, - Answer::Batch(vec![]), - ])) - .await; - let acks = mailbox.pulls.lock().clone(); - assert_eq!( - acks.first().map(Vec::len), - Some(0), - "the first pull acknowledges nothing: {acks:?}" - ); - assert_eq!( - acks.get(1).map(Vec::as_slice), - Some(["before-restart".to_string()].as_slice()), - "the pull that met the restart still carried the acknowledgement it owed: {acks:?}" - ); - assert!( - acks.iter().skip(2).all(Vec::is_empty), - "a new session must not be handed the dead session's acknowledgements: {acks:?}" - ); - } - - /// A daemon stuck in "who are you?" answers every single pull that way. The - /// recovery is idempotent, but every successful one puts a line on the - /// operator's screen, so re-registering on each answer would write one - /// every poll interval — a notification flood from a loop that is supposed - /// to be quiet. - /// - /// MUTATION GUARD: remove the [`RE_ENROLMENT_MIN_INTERVAL`] gate and this - /// fails with one attempt (and one notice) per unregistered answer. - #[tokio::test(start_paused = true)] - async fn a_daemon_that_keeps_forgetting_this_session_is_answered_at_most_once_a_minute() { - let (mailbox, said) = drive_script(RecordingMailbox::scripted(vec![ - Answer::ForgotTheSession, - Answer::ForgotTheSession, - Answer::ForgotTheSession, - Answer::ForgotTheSession, - Answer::ForgotTheSession, - Answer::ForgotTheSession, - ])) - .await; - assert_eq!( - mailbox.re_enrol_attempts.load(Ordering::SeqCst), - 1, - "six unregistered answers inside one minute are one recovery attempt; said:\n{said:#?}" - ); - assert_eq!( - said.iter().filter(|line| line.contains("registered again")).count(), - 1, - "and therefore exactly one notice; said:\n{said:#?}" - ); - assert!( - mailbox.pulls.lock().len() > 6, - "the poller must keep polling while the recovery is rate limited: {:?}", - mailbox.pulls.lock().len() - ); - } - - /// The same status, a different fact. An unknown *assignment* says nothing - /// about whether this session is registered, and re-registering on it would - /// abandon a perfectly good enrolment. - #[tokio::test(start_paused = true)] - async fn a_refusal_about_an_assignment_never_makes_this_chat_register_again() { - let (mailbox, said) = drive_script(RecordingMailbox::scripted(vec![ - Answer::ForgotTheAssignment, - Answer::ForgotTheAssignment, - Answer::Batch(vec![]), - ])) - .await; - assert_eq!( - mailbox.registrations.load(Ordering::SeqCst), - 0, - "only `unknown_session` means this session is gone; said:\n{said:#?}" - ); - assert!( - said.iter().any(|line| line.contains("are not being received")), - "a refusal this chat cannot heal must still be stated; said:\n{said:#?}" - ); - } - - /// A daemon that is gone rather than merely forgetful: registering again - /// fails too, a later pull is the retry, and it costs one line however long - /// the daemon stays down. The retry is rate limited (see - /// [`RE_ENROLMENT_MIN_INTERVAL`]), so the poller keeps polling while the - /// recovery attempt itself happens at most once a minute. - #[tokio::test(start_paused = true)] - async fn a_registration_that_also_fails_is_retried_later_and_said_once() { - let mailbox = RecordingMailbox::scripted(vec![ - Answer::ForgotTheSession, - Answer::ForgotTheSession, - Answer::ForgotTheSession, - ]); - mailbox.refuse_registration.store(true, Ordering::SeqCst); - let (mailbox, said) = drive_script(mailbox).await; - assert_eq!(mailbox.registrations.load(Ordering::SeqCst), 0); - assert!( - mailbox.pulls.lock().len() >= 3, - "the poll loop is the retry; it must keep asking: {:?}", - mailbox.pulls.lock().len() - ); - assert_eq!( - mailbox.re_enrol_attempts.load(Ordering::SeqCst), - 1, - "three refusals inside one minute buy one recovery attempt, not three" - ); - assert_eq!( - complaints_about(&said, "cannot reach"), - 1, - "one blocked recovery, one line; said:\n{said:#?}" - ); - } - - /// Idempotency, at the level it actually matters: two callers that saw the - /// same dead enrolment must produce one registration, not two sessions the - /// daemon then has to be told apart. - #[tokio::test] - async fn concurrent_recoveries_from_the_same_dead_enrolment_register_once() { - let mailbox = RecordingMailbox::scripted(vec![]); - let stale = mailbox.enrolment_generation(); - let first = mailbox.re_enrol(stale); - let second = mailbox.re_enrol(stale); - let third = mailbox.re_enrol(stale); - let (first, second, third) = tokio::join!(first, second, third); - let outcomes = [ - first.expect("re-enrolment"), - second.expect("re-enrolment"), - third.expect("re-enrolment"), - ]; - let registered = outcomes - .iter() - .filter(|outcome| matches!(outcome, ReEnrolment::Registered { .. })) - .count(); - assert_eq!(registered, 1, "three triggers, one registration: {outcomes:?}"); - assert_eq!(mailbox.registrations.load(Ordering::SeqCst), 1); - } - - /// The flood this was written against: a mailbox that refuses every other - /// pull. The reason is identical every time, so it is worth exactly one - /// line however many times it comes back. - /// - /// MUTATION GUARD: clear `FailureNotices::announced` on a successful pull — - /// the shape of the dedup this replaced — and this fails with one line per - /// refusal. - #[tokio::test(start_paused = true)] - async fn one_failure_reason_is_stated_once_however_often_it_recurs() { - let said = lines_from_script(vec![ - Answer::Refuse(RATE_LIMITED), - Answer::Batch(vec![]), - Answer::Refuse(RATE_LIMITED), - Answer::Batch(vec![]), - Answer::Refuse(RATE_LIMITED), - Answer::Refuse(RATE_LIMITED), - Answer::Batch(vec![]), - Answer::Refuse(RATE_LIMITED), - ]) - .await; - assert_eq!( - complaints_about(&said, "429"), - 1, - "one reason is worth one line, not one per failing pull; said:\n{said:#?}" - ); - let recoveries = said.iter().filter(|line| line.contains("being received again")).count(); - assert_eq!( - recoveries, 1, - "recovery is announced, and it is announced once; said:\n{said:#?}" - ); - } - - /// Going quiet about a failure is the other half of the bug: the operator - /// has to be told, once, and told again when it clears. - #[tokio::test(start_paused = true)] - async fn a_failure_and_its_recovery_are_both_stated() { - let said = lines_from_script(vec![ - Answer::Refuse(UNREACHABLE), - Answer::Refuse(UNREACHABLE), - Answer::Batch(vec![]), - ]) - .await; - assert!( - said.iter().any(|line| line.contains("are not being received")), - "a mailbox that cannot be reached must say so; said:\n{said:#?}" - ); - let recovery = said - .iter() - .find(|line| line.contains("being received again")) - .expect("recovery must be announced, or nobody knows when it healed"); - assert!( - recovery.contains("2 failed pulls"), - "the recovery line says how long it was broken: {recovery}" - ); - } - - /// A different reason is a different fact, and is stated on its own. - #[tokio::test(start_paused = true)] - async fn a_changed_reason_is_stated_even_while_the_mailbox_is_still_failing() { - let said = lines_from_script(vec![ - Answer::Refuse(RATE_LIMITED), - Answer::Refuse(RATE_LIMITED), - Answer::Refuse(UNREACHABLE), - Answer::Refuse(UNREACHABLE), - ]) - .await; - assert_eq!(complaints_about(&said, "429"), 1, "said:\n{said:#?}"); - assert_eq!( - complaints_about(&said, "cannot reach"), - 1, - "a reason the operator has not seen must not be swallowed by the previous one; said:\n{said:#?}" - ); - } - - #[test] - fn a_recovery_is_never_announced_for_a_failure_that_was_never_announced() { - let mut notices = FailureNotices::default(); - assert!(notices.recovered().is_none(), "nothing has failed yet"); - assert!(notices.failed("reason a").is_some()); - assert!(notices.failed("reason a").is_none()); - assert!(notices.recovered().is_some()); - // Second episode of the same reason: silent, so its recovery is silent - // too. Announcing "it works again" for something never reported broken - // is noise about a fact nobody was missing. - assert!(notices.failed("reason a").is_none()); - assert!(notices.recovered().is_none()); - assert!(!notices.is_failing()); - } - - #[test] - fn a_peer_whose_wording_keeps_changing_cannot_grow_the_policy_without_bound() { - let mut notices = FailureNotices::default(); - let mut announced = 0; - for attempt in 0..(MAX_TRACKED_REASONS * 4) { - if notices.failed(&format!("refused, attempt {attempt}")).is_some() { - announced += 1; - } - } - assert_eq!( - announced, MAX_TRACKED_REASONS, - "a varying message must not buy unlimited screen space" - ); - } - - #[tokio::test] - async fn the_poller_is_listed_while_it_runs_and_a_kill_ends_it() { - let registry = super::super::daemon::new_in_flight_registry(); - let client = client_for_tests(); - let (tx, _rx) = tokio::sync::mpsc::channel::(8); - let tx: crate::runtime::h2_entry::ChatInputSender = tx.into(); - let cancel = CancellationToken::new(); - let handle = tokio::spawn(run_poller( - Arc::clone(&client) as Arc, - Arc::clone(®istry), - tx, - silent(), - cancel.clone(), - )); - // The row is published before the first request, so it is visible even - // while the very first pull is outstanding. - let mut listed = None; - for _ in 0..100u16 { - if let Some(report) = super::super::daemon::in_flight_report(®istry) { - listed = Some(report); - break; - } - tokio::task::yield_now().await; - } - let listed = listed.expect("the poller must be listed in /sessions while it runs"); - assert!(listed.contains("assignment poll"), "listing was: {listed}"); - let killed = super::super::daemon::cancel_in_flight(®istry, "d1").expect("d1 is this chat's address space"); - assert!(killed.contains("d1"), "kill notice was: {killed}"); - handle.await.expect("the poller must end when it is killed"); - assert!( - super::super::daemon::in_flight_report(®istry).is_none(), - "an ended poller must stop being listed" - ); - } - - #[test] - fn an_assignment_survives_a_round_trip_through_the_input_queue() { - for (wire, disposition) in [ - ("queue", Disposition::Queue), - ("steer", Disposition::Steer), - ("interrupt", Disposition::Interrupt), - ] { - let msg = assignment_message(&assignment("a-1", "do the thing", wire), disposition); - let seen = delivered(&msg).expect("an assignment message must be recognisable"); - assert_eq!(seen.assignment_id, "a-1"); - assert_eq!(seen.disposition, disposition); - if disposition.jumps_the_queue() { - assert!( - msg.content.starts_with("/now "), - "a queue-jumping disposition must use the existing priority prefix: {}", - msg.content - ); - } else { - assert_eq!(msg.content, "do the thing"); - } - } - } - - #[test] - fn ordinary_input_is_never_mistaken_for_an_assignment() { - let mut msg = assignment_message(&assignment("a-1", "task", "queue"), Disposition::Queue); - msg.sender = "user".to_string(); - assert!(delivered(&msg).is_none()); - msg.sender = "prx-ui".to_string(); - assert!(delivered(&msg).is_none()); - msg.sender = format!("{SENDER_PREFIX}queue:"); - assert!(delivered(&msg).is_none(), "an empty assignment id is not an assignment"); - } - - #[test] - fn an_unknown_disposition_degrades_to_queue_and_never_to_interrupt() { - assert_eq!(Disposition::from_wire("obliterate"), Disposition::Queue); - assert_eq!(Disposition::from_wire(""), Disposition::Queue); - assert!(!Disposition::is_known_wire("obliterate")); - assert!(Disposition::is_known_wire("interrupt")); - assert!(!Disposition::from_wire("obliterate").ends_the_turn_in_flight()); - } - - #[test] - fn only_interrupt_ends_the_turn_in_flight() { - assert!(!Disposition::Queue.jumps_the_queue()); - assert!(Disposition::Steer.jumps_the_queue()); - assert!(Disposition::Interrupt.jumps_the_queue()); - assert!(!Disposition::Queue.ends_the_turn_in_flight()); - assert!( - !Disposition::Steer.ends_the_turn_in_flight(), - "steer inserts into the turn in flight; it does not destroy it" - ); - assert!(Disposition::Interrupt.ends_the_turn_in_flight()); - } - - #[test] - fn a_chat_session_can_never_report_the_daemons_own_cancelled_verdict() { - let reportable: Vec<&str> = ResultStatus::all().iter().map(|status| status.as_str()).collect(); - assert_eq!(reportable, vec!["completed", "failed", "rejected"]); - assert!( - !reportable.contains(&"cancelled"), - "`cancelled` is the daemon's verdict about work it ended, not something a client may claim" - ); - } - - #[test] - fn a_summary_is_fitted_to_what_the_daemon_accepts() { - assert_eq!(bound_summary(" answer "), "answer"); - assert!( - !bound_summary(" ").is_empty(), - "an empty summary is refused by the daemon" - ); - let huge = "x".repeat(MAX_SUMMARY_BYTES * 2); - let bounded = bound_summary(&huge); - assert!(bounded.len() <= MAX_SUMMARY_BYTES, "bounded to {}", bounded.len()); - assert!(bounded.ends_with("to fit the result field)")); - let wide = "\u{20ac}".repeat(MAX_SUMMARY_BYTES); - assert!(bound_summary(&wide).len() <= MAX_SUMMARY_BYTES); - } - - #[test] - fn enrolment_is_declined_when_nothing_points_this_chat_at_a_daemon() { - let mut config = Config::default(); - config.chat.daemon.url = String::new(); - config.chat.daemon.token = String::new(); - config.gateway.paired_tokens = vec![]; - match enrolable(&config) { - Enrolable::No(reason) => { - assert!(reason.contains("chat.daemon.url"), "reason was: {reason}"); - } - Enrolable::Yes => panic!("an unconfigured chat must not announce a daemon failure on every start"), - } - config.chat.daemon.url = "http://127.0.0.1:8765".to_string(); - assert_eq!(enrolable(&config), Enrolable::Yes); - - let mut with_token = Config::default(); - with_token.chat.daemon.url = String::new(); - with_token.chat.daemon.token = "plaintext-token".to_string(); - assert_eq!(enrolable(&with_token), Enrolable::Yes); - } - - #[test] - fn an_arrival_names_the_origin_and_the_disposition_without_going_quiet() { - let notice = arrival_notice( - &assignment("a-1", "summarise the repo", "interrupt"), - Disposition::Interrupt, - ); - assert!(notice.contains("wacli"), "{notice}"); - assert!(notice.contains("3d1a4f5b"), "{notice}"); - assert!(notice.contains("summarise the repo"), "{notice}"); - assert!(notice.contains("interrupt"), "{notice}"); - - let mut redelivered = assignment("a-1", "task", "queue"); - redelivered.deliveries = 3; - assert!(arrival_notice(&redelivered, Disposition::Queue).contains("redelivery #3")); - - let mut operator = assignment("a-2", "task", "queue"); - operator.origin_channel = "api".to_string(); - operator.origin_ref = None; - let plane = arrival_notice(&operator, Disposition::Queue); - assert!(plane.contains("api"), "{plane}"); - } - - #[test] - fn a_label_is_stable_and_fits_what_the_daemon_accepts() { - let mut config = Config::default(); - config.workspace_dir = std::path::PathBuf::from("/tmp/some/workstation"); - assert_eq!(label_for(&config), "workstation"); - config.workspace_dir = std::path::PathBuf::from(format!("/tmp/{}", "n".repeat(200))); - assert!(label_for(&config).len() <= MAX_LABEL_BYTES); - config.workspace_dir = std::path::PathBuf::from("/"); - assert_eq!(label_for(&config), "chat"); - } - /// Mutation: retain a raw chain in an assignment notice or repeated-pull episode. - #[test] - fn assignment_failure_notices_hide_nested_credentials() { - let error = anyhow::anyhow!("token=opaque7credential").context("failed"); - let mut notices = FailureNotices::default(); - let pull = notices.failed(&format!("{error:#}")).expect("test: first notice"); - for notice in [ - report_failure_notice("assignment", ResultStatus::Failed, &error), - enrolment_failure_notice("https://example.com?key=opaque7credential", &error), - pull, - ] { - assert!(notice.contains("[REDACTED]"), "{notice}"); - assert!(!notice.contains("opaque7credential"), "{notice}"); - } - } -} +include!("assignment/section_1.rs"); +include!("assignment/section_2.rs"); diff --git a/src/chat/sessions/assignment/section_1.rs b/src/chat/sessions/assignment/section_1.rs new file mode 100644 index 000000000..7fccfde03 --- /dev/null +++ b/src/chat/sessions/assignment/section_1.rs @@ -0,0 +1,1222 @@ +use std::collections::HashSet; +use std::future::Future; +use std::pin::Pin; +use std::sync::Arc; + +use anyhow::Result; +use parking_lot::Mutex; +use tokio_util::sync::CancellationToken; + +use crate::config::Config; +use crate::runtime::tasks_cli::{self, AssignmentPull, AssignmentReceipt, PulledAssignment, TasksEndpoint}; + +use super::daemon::{InFlightGuard, InFlightRegistry, register_in_flight_labeled}; + +/// How often chat asks the daemon whether it has been given work. +/// +/// A sampling interval, in the same sense as `sessions_spawn`'s +/// `JOIN_POLL_INTERVAL`: it decides how often a question is asked, never how +/// long an answer may take. No call in this module carries a timeout, and +/// nothing here compares an elapsed duration against a limit. +pub const POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(1_500); + +/// Shortest gap between two attempts by this poller to register again. +/// +/// Re-enrolment is idempotent, so a repeat costs the daemon little — but every +/// successful one puts a line on the operator's screen, and a daemon that keeps +/// forgetting this session would otherwise write one every [`POLL_INTERVAL`]. +/// A floor of a minute keeps the recovery automatic while bounding what a +/// pathological daemon can print, at the price of up to a minute of extra +/// downtime on the pathological path only: a single restart still recovers on +/// the first unregistered answer. +pub const RE_ENROLMENT_MIN_INTERVAL: std::time::Duration = std::time::Duration::from_mins(1); + +/// How many assignments to take in one pull. +/// +/// A response-size bound, not a concurrency limit: whatever is left stays at +/// the head of the daemon's queue and comes on the next pull. Chat runs turns +/// one queue at a time regardless, so asking for more would only make a single +/// HTTP body larger. +const PULL_BATCH: usize = 8; + +/// Upper bound the daemon enforces on a reported summary, in bytes. +const MAX_SUMMARY_BYTES: usize = 16_384; + +/// Upper bound the daemon enforces on a registered label, in bytes. +const MAX_LABEL_BYTES: usize = 64; + +/// How much of an assigned task is echoed into the transcript on arrival. +const TASK_PREVIEW_CHARS: usize = 120; + +/// Marker prefix on the synthetic input message carrying an assignment. +/// +/// The sender field is the same place `prx-ui` marks synthetic slash commands, +/// and for the same reason: the input queue is typed as channel messages, so a +/// message that is not a person typing has to say so somewhere the queue +/// already carries. Nothing outside this module parses it. +const SENDER_PREFIX: &str = "prx-assignment:"; + +/// Channel an assignment is delivered on. +/// +/// `terminal`, exactly like a typed line: the whole point is that assigned work +/// runs through the ordinary turn machinery rather than a parallel path with +/// its own bugs. +const ASSIGNMENT_CHANNEL: &str = "terminal"; + +/// Reply target on the synthetic message, matching a typed line. +const ASSIGNMENT_REPLY_TARGET: &str = "user"; + +// ── Dispositions ──────────────────────────────────────────────────────────── + +/// What the assigning side asked chat to do about work already in flight. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Disposition { + /// Run it when the current work is done. The default, and the least + /// disruptive: an assignment is somebody else's priority, not necessarily + /// this terminal's. + Queue, + /// Put it in front of whatever else is queued, without stopping the turn in + /// flight. + Steer, + /// Stop the turn in flight first, then run it. + Interrupt, +} + +impl Disposition { + /// Read the daemon's word for a disposition. + /// + /// An unrecognised word becomes [`Disposition::Queue`], never + /// [`Disposition::Interrupt`]: a newer daemon inventing a stronger + /// disposition must not be able to make an older chat destroy a turn it + /// does not understand the reason for. The caller is told, so silence is + /// not how it degrades. + #[must_use] + pub fn from_wire(raw: &str) -> Self { + match raw.trim() { + "steer" => Self::Steer, + "interrupt" => Self::Interrupt, + _ => Self::Queue, + } + } + + /// Whether the daemon's word was one this chat actually knows. + #[must_use] + pub fn is_known_wire(raw: &str) -> bool { + matches!(raw.trim(), "queue" | "steer" | "interrupt") + } + + /// The wire word for this disposition. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Queue => "queue", + Self::Steer => "steer", + Self::Interrupt => "interrupt", + } + } + + /// Whether this disposition jumps the input queue. + /// + /// `steer` and `interrupt` both do; they differ only in whether the turn in + /// flight is stopped first. + #[must_use] + pub const fn jumps_the_queue(self) -> bool { + matches!(self, Self::Steer | Self::Interrupt) + } + + /// Whether this disposition ends the turn in flight before delivering. + #[must_use] + pub const fn ends_the_turn_in_flight(self) -> bool { + matches!(self, Self::Interrupt) + } +} + +/// What chat may report back about an assignment. +/// +/// `cancelled` is deliberately absent. It is the daemon's own verdict about +/// work *it* ended, and a client able to claim it would make "an operator +/// killed this" indistinguishable from "the client gave up". The daemon refuses +/// it at the boundary; this enum makes it unrepresentable on the way there. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ResultStatus { + /// The turn ran and produced a reply. + Completed, + /// The turn ran and did not produce a reply, or was ended before it could. + Failed, + /// Chat declined to run it at all. + Rejected, +} + +impl ResultStatus { + /// The wire word for this status. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Completed => "completed", + Self::Failed => "failed", + Self::Rejected => "rejected", + } + } + + /// Every status a chat session can report, for tests and documentation. + #[must_use] + pub const fn all() -> [Self; 3] { + [Self::Completed, Self::Failed, Self::Rejected] + } +} + +// ── The mailbox, behind a trait ───────────────────────────────────────────── + +/// Boxed future returned by [`AssignmentMailbox`] calls. +pub type MailboxFuture<'a, T> = Pin> + Send + 'a>>; + +/// The two calls the poll loop and the result guard make. +/// +/// A trait rather than a concrete client so the loop's ordering guarantees — +/// acknowledge on the *next* pull, run a redelivery once — can be asserted +/// against a recording double instead of against a live daemon. The HTTP +/// implementation is [`AssignmentClient`]. +pub trait AssignmentMailbox: Send + Sync { + /// Redacted handle for this session, for anything an operator will read. + fn session_ref(&self) -> String; + + /// Where this mailbox lives, for the in-flight listing. + fn base_url(&self) -> String; + + /// Take queued work, acknowledging `ack` — the ids from the previous pull — + /// on the way in. + fn pull(&self, ack: Vec) -> MailboxFuture<'_, AssignmentPull>; + + /// Say what this session made of one assignment. + fn report( + &self, + assignment_id: String, + status: ResultStatus, + summary: String, + ) -> MailboxFuture<'_, AssignmentReceipt>; + + /// Claim one assignment id, returning `false` when it was already taken. + /// + /// The mailbox is at-least-once, so this is what makes a redelivery cost + /// nothing: `false` means "work I already hold", which must still be + /// acknowledged and must not be run a second time. + fn accept(&self, assignment_id: &str) -> bool; + + /// Which enrolment the caller is looking at. `0` means "not enrolled". + /// + /// Read before a call that may fail, and handed back to [`Self::re_enrol`] + /// afterwards: that is what makes re-enrolment idempotent without a lock + /// held across the network. Two callers that saw the same dead enrolment + /// pass the same number, and only the first of them registers. + fn enrolment_generation(&self) -> u64; + + /// Register again, because the enrolment `stale` names is gone. + /// + /// Registering is the entire recovery: the daemon keeps its session + /// registry in memory and rebuilds nothing on start, so a restart leaves + /// this chat holding a session id nothing answers to. A new registration + /// yields a new id and a new token, and the old row does not need + /// withdrawing because a refusal that says "no such session" is the daemon + /// saying the row is already gone. + fn re_enrol(&self, stale: u64) -> MailboxFuture<'_, ReEnrolment>; +} + +/// What one re-enrolment attempt did. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ReEnrolment { + /// This call registered again. The session id and token are new, and every + /// id from the old enrolment is meaningless to the daemon now. + Registered { session_ref: String }, + /// The enrolment the caller saw had already been replaced — or withdrawn on + /// the way out — so this call registered nothing. Idempotency, stated + /// rather than assumed. + Superseded { session_ref: String }, +} + +/// Chat's enrolment with one daemon, and the state that keeps it honest. +pub struct AssignmentClient { + message_target: Mutex>, + endpoint: TasksEndpoint, + label: String, + pid: Option, + enrolment: Mutex>, + /// Serialises re-enrolment, so two callers that raced the same dead + /// enrolment produce one registration rather than two sessions the daemon + /// then has to be told apart. `tokio::sync::Mutex` because the section it + /// guards contains an HTTP round trip; the `parking_lot` mutexes here are + /// never held across an await. + re_enrolling: tokio::sync::Mutex<()>, + /// Assignment ids this chat has already taken into its own queue. + /// + /// The mailbox is at-least-once, so the same id can arrive again whenever a + /// response was lost on the way back. Running it twice would be the client + /// duplicating somebody's work; this set is what makes redelivery + /// harmless. + taken: Mutex>, +} + +/// The identity and credential one registration yielded. +#[derive(Debug, Clone)] +struct Enrolment { + session_id: String, + session_ref: String, + /// Returned once by the daemon, which keeps only its hash. Held in memory + /// for the life of the process and never written anywhere. + token: String, + /// Which registration this is: 1 for the first, one more for each + /// replacement. The version stamp re-enrolment checks so a caller acting on + /// an enrolment that has already been replaced replaces nothing. + generation: u64, +} + +impl AssignmentClient { + /// Build a client for the daemon this chat is configured to talk to. + #[must_use] + pub fn new(config: &Config) -> Arc { + Arc::new(Self { + message_target: Mutex::new(None), + endpoint: super::daemon::endpoint(config), + label: label_for(config), + pid: Some(std::process::id()), + enrolment: Mutex::new(None), + re_enrolling: tokio::sync::Mutex::new(()), + taken: Mutex::new(HashSet::new()), + }) + } + + pub(crate) fn set_message_target(&self, target: crate::messaging::SessionAddr) { + *self.message_target.lock() = Some(target); + } + + /// The label this chat registers under. + #[must_use] + pub fn label(&self) -> &str { + &self.label + } + + /// Register with the daemon, storing the session id and one-time token. + /// + /// Returns the redacted session handle on success. The caller decides what + /// to do with a failure; nothing here retries, because a chat that cannot + /// enrol at all has a perfectly usable degraded mode and hammering a daemon + /// that refused it would only bury the reason. Losing an enrolment that + /// once worked is the different case, and [`AssignmentClient::re_enrol_now`] + /// is what answers it. + pub async fn enrol(&self) -> Result { + let registration = tasks_cli::register_chat_session(&self.endpoint, &self.label, self.pid).await?; + let session_ref = registration.session_ref.clone(); + self.install(registration, 1); + Ok(session_ref) + } + + /// Replace the held enrolment with a fresh registration. + /// + /// Everything the old one meant goes with it: the id, the token, and the + /// set of assignment ids already taken, which belonged to a mailbox that no + /// longer exists. Keeping the last of those would let an id the *new* + /// daemon hands out collide with a dead one and be silently discarded as a + /// redelivery. + fn install(&self, registration: tasks_cli::ChatSessionRegistration, generation: u64) { + *self.enrolment.lock() = Some(Enrolment { + session_id: registration.session_id, + session_ref: registration.session_ref, + token: registration.token, + generation, + }); + self.taken.lock().clear(); + } + + /// The enrolment version this client currently holds; `0` when unenrolled. + fn generation(&self) -> u64 { + self.enrolment.lock().as_ref().map_or(0, |held| held.generation) + } + + /// Whether this chat is currently enrolled. + #[must_use] + pub fn is_enrolled(&self) -> bool { + self.enrolment.lock().is_some() + } + + /// The daemon-assigned session id, once enrolled. + #[must_use] + pub fn session_id(&self) -> Option { + self.enrolment.lock().as_ref().map(|e| e.session_id.clone()) + } + + fn credentials(&self) -> Result<(String, String)> { + let held = self.enrolment.lock().clone(); + let enrolment = held.ok_or_else(|| anyhow::anyhow!("this chat session is not enrolled with a daemon"))?; + Ok((enrolment.session_id, enrolment.token)) + } + + /// Withdraw from the daemon's registry. + /// + /// Nothing on the daemon side removes a session on a clock — a session that + /// stopped pulling is reported as silent, never evicted — so an exit that + /// skips this leaves a row that assignments can still be addressed to, with + /// nobody left to run them. + pub async fn deregister(&self) -> Result { + let (session_id, _) = self.credentials()?; + let report = tasks_cli::deregister_chat_session(&self.endpoint, &session_id).await?; + *self.enrolment.lock() = None; + Ok(report.discarded) + } + + /// Register again after the daemon stopped recognising this session. + /// + /// Idempotent by version stamp rather than by trust: the generation the + /// caller saw is compared with the one held now, under a lock that is also + /// held across the registration call, so concurrent callers that saw the + /// same dead enrolment yield exactly one new session. A caller holding an + /// older stamp is told it was superseded and registers nothing — which is + /// also what stops a poll that raced the exit path from re-registering a + /// chat that has just withdrawn. + async fn re_enrol_now(&self, stale: u64) -> Result { + let _serialised = self.re_enrolling.lock().await; + let held = self.enrolment.lock().clone(); + let current = held.as_ref().map_or(0, |enrolment| enrolment.generation); + if current != stale { + return Ok(ReEnrolment::Superseded { + session_ref: held.map_or_else(|| "unenrolled".to_string(), |enrolment| enrolment.session_ref), + }); + } + let registration = tasks_cli::register_chat_session(&self.endpoint, &self.label, self.pid).await?; + let session_ref = registration.session_ref.clone(); + self.install(registration, stale.saturating_add(1)); + Ok(ReEnrolment::Registered { session_ref }) + } +} + +impl AssignmentMailbox for AssignmentClient { + fn session_ref(&self) -> String { + self.enrolment + .lock() + .as_ref() + .map_or_else(|| "unenrolled".to_string(), |e| e.session_ref.clone()) + } + + fn base_url(&self) -> String { + self.endpoint.base_url().to_string() + } + + fn pull(&self, ack: Vec) -> MailboxFuture<'_, AssignmentPull> { + Box::pin(async move { + let (session_id, token) = self.credentials()?; + let target = self.message_target.lock().clone(); + tasks_cli::pull_chat_inbox( + &self.endpoint, + &session_id, + &token, + &ack, + Some(PULL_BATCH), + target.as_ref(), + ) + .await + }) + } + + fn report( + &self, + assignment_id: String, + status: ResultStatus, + summary: String, + ) -> MailboxFuture<'_, AssignmentReceipt> { + Box::pin(async move { + let (session_id, token) = self.credentials()?; + tasks_cli::report_chat_assignment( + &self.endpoint, + &session_id, + &token, + &assignment_id, + status.as_str(), + &summary, + ) + .await + }) + } + + fn accept(&self, assignment_id: &str) -> bool { + self.taken.lock().insert(assignment_id.to_string()) + } + + fn enrolment_generation(&self) -> u64 { + self.generation() + } + + fn re_enrol(&self, stale: u64) -> MailboxFuture<'_, ReEnrolment> { + Box::pin(self.re_enrol_now(stale)) + } +} + +// ── Whether to enrol at all ───────────────────────────────────────────────── + +/// Whether this configuration means chat to enrol with a daemon. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Enrolable { + /// A daemon was named, or a credential for one exists: enrol. + Yes, + /// Nothing points this chat at a daemon. The reason is carried so it can be + /// shown to anyone who asks why they cannot be assigned work. + No(&'static str), +} + +/// Decide whether to enrol, from configuration alone. +/// +/// Enrolment is opt-in by evidence rather than by a flag, because there is no +/// safe default guess: the fallback daemon address is `[gateway]`'s own bind, +/// which every chat has whether or not a daemon is listening on it, and +/// `gateway.require_pairing` is on by default, so an unconfigured chat would +/// announce a 401 on every single start. Two things count as evidence that an +/// operator meant chat to talk to a daemon: +/// +/// 1. `chat.daemon.url` is set — chat has been pointed at one explicitly; +/// 2. a credential resolves — `chat.daemon.token`, or a plaintext entry in +/// `gateway.paired_tokens` when chat and the daemon share a config dir. +/// +/// Neither of those is a promise that enrolment will succeed. It is only the +/// difference between a failure worth reporting and a question nobody asked. +#[must_use] +pub fn enrolable(config: &Config) -> Enrolable { + if !config.chat.daemon.url.trim().is_empty() { + return Enrolable::Yes; + } + if super::daemon::operator_token(config).is_some() { + return Enrolable::Yes; + } + Enrolable::No( + "no daemon is configured for this chat: set `chat.daemon.url` to the daemon's gateway, or \ + `chat.daemon.token` to a token it accepts", + ) +} + +/// The label this chat registers under. +/// +/// The workspace directory name: stable across restarts, which is what an +/// `assign_allow` rule needs, and already how an operator thinks about which +/// chat is which. The daemon treats it as self-declared and does not verify it. +fn label_for(config: &Config) -> String { + let raw = config + .workspace_dir + .file_name() + .map(|name| name.to_string_lossy().trim().to_string()) + .filter(|name| !name.is_empty()) + .unwrap_or_else(|| "chat".to_string()); + truncate_bytes(&raw, MAX_LABEL_BYTES) +} + +/// Cut a string to at most `limit` bytes, on a character boundary. +fn truncate_bytes(text: &str, limit: usize) -> String { + if text.len() <= limit { + return text.to_string(); + } + let mut end = limit; + while end > 0 && !text.is_char_boundary(end) { + end -= 1; + } + text.get(..end).unwrap_or_default().to_string() +} + +// ── Carrying an assignment through the ordinary input queue ───────────────── + +/// One assignment recognised on an input message. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Delivered { + pub assignment_id: String, + pub disposition: Disposition, +} + +/// Build the input message that carries one assignment into the chat queue. +/// +/// The content is the task verbatim for [`Disposition::Queue`], and prefixed +/// with `/now ` for the two that jump the queue — the same prefix a person +/// types to put their own input in front of the backlog, so priority ordering +/// stays one mechanism with one set of tests rather than two that can drift. +/// The prefix is consumed by `classify_input_priority`, so the model sees the +/// task and nothing else. +#[must_use] +pub fn assignment_message( + assignment: &PulledAssignment, + disposition: Disposition, +) -> crate::channels::traits::ChannelMessage { + let content = if disposition.jumps_the_queue() { + format!("/now {}", assignment.task) + } else { + assignment.task.clone() + }; + crate::channels::traits::ChannelMessage { + id: uuid::Uuid::new_v4().to_string(), + sender: format!("{SENDER_PREFIX}{}:{}", disposition.as_str(), assignment.assignment_id), + reply_target: ASSIGNMENT_REPLY_TARGET.to_string(), + content, + channel: ASSIGNMENT_CHANNEL.to_string(), + timestamp: std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs(), + thread_ts: None, + chat_kind: crate::channels::traits::ChatKind::Dm, + chat_title: None, + sender_display: None, + mentioned_uuids: vec![], + mentioned: false, + is_group_hint: false, + sender_is_bot: false, + } +} + +/// Recognise an assignment on an input message, or `None` for ordinary input. +#[must_use] +pub fn delivered(msg: &crate::channels::traits::ChannelMessage) -> Option { + let rest = msg.sender.strip_prefix(SENDER_PREFIX)?; + let (disposition, assignment_id) = rest.split_once(':')?; + if assignment_id.is_empty() { + return None; + } + Some(Delivered { + assignment_id: assignment_id.to_string(), + disposition: Disposition::from_wire(disposition), + }) +} + +// ── What the operator sees ────────────────────────────────────────────────── + +/// The line shown when an assignment arrives. +/// +/// Someone other than the person at the keyboard just put work into this +/// terminal. Where it came from, how it was dispatched, and enough of the task +/// to recognise it all have to be on screen; the origin is already a +/// fingerprint by the time it reaches here, and is passed through unchanged. +#[must_use] +pub fn arrival_notice(assignment: &PulledAssignment, disposition: Disposition) -> String { + let origin = origin_label(assignment); + let preview = preview_of(&assignment.task); + let redelivery = if assignment.deliveries > 1 { + format!(" (redelivery #{})", assignment.deliveries) + } else { + String::new() + }; + let dispatched = match disposition { + Disposition::Queue => "queued behind whatever this chat is already doing", + Disposition::Steer => "put in front of the queue; the turn in flight keeps running", + Disposition::Interrupt => "the turn in flight is being ended first", + }; + format!( + "Assigned by {origin}{redelivery}: {preview}\n Disposition {} — {dispatched}.", + disposition.as_str() + ) +} + +/// The line shown when a disposition this chat does not know arrives. +#[must_use] +pub fn unknown_disposition_notice(raw: &str) -> String { + format!( + "Daemon assignment carried disposition {raw:?}, which this chat does not know; running it as \ + `queue`. A word this chat cannot read is never treated as permission to end a turn." + ) +} + +/// The line shown when a result was handed back to the daemon. +#[must_use] +pub fn reported_notice(assignment_id: &str, status: ResultStatus, seq: u64) -> String { + format!( + "Reported {} for daemon assignment {} (result #{seq}).", + status.as_str(), + short_id(assignment_id) + ) +} + +/// The line shown when a result could not be handed back. +#[must_use] +pub fn report_failure_notice(assignment_id: &str, status: ResultStatus, error: &anyhow::Error) -> String { + let error = crate::security::redaction::redact_provider_text(&format!("{error:#}")); + format!( + "Could not report {} for daemon assignment {}: {error}. The daemon still has it outstanding; \ + whoever assigned it is waiting.", + status.as_str(), + short_id(assignment_id) + ) +} + +/// The line shown when this chat could not enrol. +#[must_use] +pub fn enrolment_failure_notice(base_url: &str, error: &anyhow::Error) -> String { + let base_url = crate::security::redaction::redact_provider_text(base_url); + let error = crate::security::redaction::redact_provider_text(&format!("{error:#}")); + format!( + "This chat could not enrol with the daemon at {base_url}, so it cannot be assigned work: {error}\n\ + Everything else in this chat is unaffected. Restart chat once the daemon accepts it to become \ + assignable again." + ) +} + +/// The line shown when this chat had to register with the daemon again. +/// +/// Not silent, and not a warning either: the session id and the mailbox behind +/// it are new, so anything an operator wrote down about the old one — a +/// `--session` argument, an `assign_allow` rule keyed on the id — is stale, and +/// the only place they can learn that is here. Printed once per re-enrolment, +/// which is once per daemon restart rather than once per poll. +#[must_use] +pub fn re_enrolled_notice(base_url: &str, session_ref: &str) -> String { + format!( + "The daemon at {base_url} no longer had this chat's registration — it keeps them in memory, so a \ + restart forgets every one — and this chat registered again as {session_ref}. It is assignable \ + again; anything queued for the old registration is gone with it." + ) +} + +/// The line shown once this chat is assignable. +#[must_use] +pub fn enrolled_notice(label: &str, session_ref: &str, base_url: &str) -> String { + format!("This chat is assignable at {base_url} as {label} ({session_ref}).") +} + +fn origin_label(assignment: &PulledAssignment) -> String { + let channel = if assignment.origin_channel.trim().is_empty() { + "unknown" + } else { + assignment.origin_channel.trim() + }; + assignment + .origin_ref + .as_deref() + .map(str::trim) + .filter(|origin_ref| !origin_ref.is_empty()) + .map_or_else(|| channel.to_string(), |origin_ref| format!("{channel} {origin_ref}")) +} + +fn preview_of(task: &str) -> String { + let first_line = task.lines().next().unwrap_or("").trim(); + if first_line.chars().count() <= TASK_PREVIEW_CHARS { + return first_line.to_string(); + } + let head: String = first_line.chars().take(TASK_PREVIEW_CHARS).collect(); + format!("{head}…") +} + +fn short_id(assignment_id: &str) -> String { + let head: String = assignment_id.chars().take(8).collect(); + if head.is_empty() { "?".to_string() } else { head } +} + +/// Fit a summary into what the daemon accepts: never empty, never oversized. +/// +/// The daemon refuses both, and a refusal here would lose the only account of +/// what happened. Truncation says so in the text rather than silently handing +/// back a sentence that stops mid-word. +#[must_use] +pub fn bound_summary(text: &str) -> String { + let trimmed = text.trim(); + if trimmed.is_empty() { + return "(this chat produced no text for the assignment)".to_string(); + } + if trimmed.len() <= MAX_SUMMARY_BYTES { + return trimmed.to_string(); + } + const MARKER: &str = "\n… (truncated by chat to fit the result field)"; + truncate_bytes(trimmed, MAX_SUMMARY_BYTES.saturating_sub(MARKER.len())) + MARKER +} + +// ── Reporting one assignment's turn ───────────────────────────────────────── + +/// Default account when a turn ends without a reply to report. +const NO_REPLY_SUMMARY: &str = "This chat ended the turn for the assignment without producing a reply. \ + The input may have been handled as a local chat command, or the turn was \ + ended before it answered."; + +/// Reports one assignment's outcome when the turn that ran it ends, whichever +/// way it ends. +/// +/// A guard rather than a call at the end of the turn because the turn body has +/// many exits: a slash command short-circuits it, a cancellation unwinds it, a +/// quit breaks out of the loop entirely. Anything that only reported on the +/// straight-line path would leave the assigner waiting forever on exactly the +/// cases they most need to hear about. Dropping is the one thing every exit has +/// in common. +/// +/// The one exit that must *not* report is a requeue: the message goes back into +/// the backlog and will run later, so [`AssignmentTurnGuard::disarm`] is called +/// there and the next attempt takes over. +pub struct AssignmentTurnGuard { + mailbox: Arc, + in_flight: InFlightRegistry, + notify: Arc, + assignment_id: String, + outcome: Option<(ResultStatus, String)>, + armed: bool, +} + +impl AssignmentTurnGuard { + /// Arm a report for one assignment. + #[must_use] + pub fn new( + mailbox: Arc, + in_flight: InFlightRegistry, + notify: Arc, + assignment_id: String, + ) -> Self { + Self { + mailbox, + in_flight, + notify, + assignment_id, + outcome: None, + armed: true, + } + } + + /// Record the reply this turn produced. + /// + /// The daemon stores the report as the assignment's result, so the reply + /// is redacted like the terminal commit first (D-053). + pub fn completed(&mut self, reply: &str) { + self.outcome = Some(( + ResultStatus::Completed, + bound_summary(&crate::agent::terminal::redact_persisted_text(reply)), + )); + } + + /// Record that the turn ran and failed, with the reason (redacted like + /// the reply). + pub fn failed(&mut self, reason: &str) { + self.outcome = Some(( + ResultStatus::Failed, + bound_summary(&crate::agent::terminal::redact_persisted_text(reason)), + )); + } + + /// Give up the report because this assignment has not actually run yet. + /// + /// Used where the input is put back on the backlog: reporting there would + /// answer for a turn that is still going to happen, and the daemon would + /// then refuse the real report as unknown. + pub const fn disarm(&mut self) { + self.armed = false; + } + + /// Whether this guard will still report when dropped. + #[must_use] + pub const fn is_armed(&self) -> bool { + self.armed + } + + /// The status and summary this guard would report right now. + #[must_use] + pub fn pending_outcome(&self) -> (ResultStatus, String) { + self.outcome + .clone() + .unwrap_or_else(|| (ResultStatus::Failed, NO_REPLY_SUMMARY.to_string())) + } +} + +impl Drop for AssignmentTurnGuard { + fn drop(&mut self) { + if !self.armed { + return; + } + let (status, summary) = self.pending_outcome(); + let Ok(handle) = tokio::runtime::Handle::try_current() else { + // Outside a runtime there is nothing to spawn onto. Say so where it + // can be found rather than pretending the report went out. + let status_label: &'static str = status.as_str(); + tracing::warn!( + assignment = %crate::agent::diagnostics::text_class(&self.assignment_id), + status = status_label, + "no tokio runtime to report a daemon assignment result on" + ); + return; + }; + let mailbox = Arc::clone(&self.mailbox); + let notify = Arc::clone(&self.notify); + let assignment_id = self.assignment_id.clone(); + // The report is a request to the daemon like any other, so it is listed + // and endable while it runs: a daemon that accepts the connection and + // never answers must not leave an invisible task behind. + let cancel = CancellationToken::new(); + let guard = register_in_flight_labeled( + &self.in_flight, + &format!("assignment result {}", short_id(&assignment_id)), + &mailbox.base_url(), + cancel.clone(), + ); + handle.spawn(async move { + let _row = guard; + let outcome = tokio::select! { + () = cancel.cancelled() => None, + outcome = mailbox.report(assignment_id.clone(), status, summary) => Some(outcome), + }; + match outcome { + Some(Ok(receipt)) => notify(&reported_notice(&assignment_id, status, receipt.seq)), + Some(Err(error)) => notify(&report_failure_notice(&assignment_id, status, &error)), + None => notify(&format!( + "Stopped waiting on the daemon's acknowledgement for assignment {}. The result may or \ + may not have landed.", + short_id(&assignment_id) + )), + } + }); + } +} + +// ── How often a failing pull is allowed to say so ─────────────────────────── + +/// How many distinct failure reasons this policy will ever announce. +/// +/// The reason text comes from the daemon, so a peer whose message varies (an +/// id, a counter, a clock) could otherwise grow this set without bound. Past +/// the cap nothing new is announced and nothing new is remembered; the log +/// still has every occurrence. +const MAX_TRACKED_REASONS: usize = 16; + +/// One unbroken run of failing pulls, all with the same reason. +#[derive(Debug, Clone)] +struct FailingEpisode { + reason: String, + /// Failing pulls in this episode, announced or not — the number the + /// recovery line quotes. + pulls: u64, + /// Whether this episode's reason reached the screen. A recovery is only + /// announced for an episode that was, or the operator is told something + /// healed that they were never told had broken. + announced: bool, +} + +/// Decides what a failing — and a recovering — pull is allowed to say. +/// +/// # Why the obvious version was not enough +/// +/// The first version kept the *last* failure text, skipped a repeat of it, and +/// cleared it on any successful pull. That holds only while failure is +/// sustained. The failure it was written against was not: the daemon rate +/// limited the mailbox, so pulls alternated success, refusal, success, refusal +/// — and every success cleared the key, so every refusal was "new" and printed +/// again. The dedup was real and the flood was real at the same time. +/// +/// So the key here is the reason itself and it is kept **across** recoveries: +/// one distinct reason is stated once for the life of one poller, and its +/// recovery once. Alternating failures collapse onto that one statement instead +/// of resetting it, which is the property the flood needed and the previous +/// version did not have. The ceiling is total, not per-interval: no failure +/// mode, however it recurs, can cost more than two lines per distinct reason. +/// +/// What that trades away is being told a second time that a reason that has +/// already been announced and recovered is back. That is the deliberate side to +/// err on: a stale silence costs an operator one `/sessions --daemon`, and a +/// screen full of the same sentence costs them the chat they were using. +#[derive(Debug, Default)] +pub struct FailureNotices { + /// Reasons already put on screen. Kept across recoveries on purpose. + announced: std::collections::HashSet, + /// Reasons whose recovery has already been put on screen. + recovered: std::collections::HashSet, + episode: Option, +} + +impl FailureNotices { + /// Record a failing pull, returning the line to show — or `None` when this + /// reason has already said everything it is allowed to say. + pub fn failed(&mut self, reason: &str) -> Option { + let reason = crate::security::redaction::redact_provider_text(reason); + let reason = reason.as_str(); + if self.episode.as_ref().is_none_or(|episode| episode.reason != reason) { + self.episode = Some(FailingEpisode { + reason: reason.to_string(), + pulls: 0, + announced: false, + }); + } + let episode = self.episode.as_mut()?; + episode.pulls = episode.pulls.saturating_add(1); + if self.announced.contains(reason) || self.announced.len() >= MAX_TRACKED_REASONS { + let failed_pulls: u64 = episode.pulls; + tracing::debug!(reason = %crate::agent::diagnostics::text_class(reason), failed_pulls, "chat assignment pull is still failing"); + return None; + } + self.announced.insert(reason.to_string()); + episode.announced = true; + Some(pull_failure_notice(reason)) + } + + /// Record a successful pull, returning the line to show when it ends an + /// episode the operator was told about. + pub fn recovered(&mut self) -> Option { + let episode = self.episode.take()?; + if !episode.announced || !self.recovered.insert(episode.reason.clone()) { + return None; + } + Some(pull_recovery_notice(&episode.reason, episode.pulls)) + } + + /// End the failing episode without a recovery line, for a caller that has + /// already said something more specific about the same recovery. + /// + /// The re-enrolment notice is exactly that: it names what was wrong and + /// says this chat is assignable again, so adding the generic line after it + /// would say the same thing twice. + pub fn settled(&mut self) { + self.episode = None; + } + + /// Whether a failing episode is currently open. + #[must_use] + pub const fn is_failing(&self) -> bool { + self.episode.is_some() + } +} + +/// The line shown when this chat's mailbox cannot be reached. +#[must_use] +pub fn pull_failure_notice(reason: &str) -> String { + format!( + "Daemon assignments are not being received: {reason}\nThis chat keeps asking, and nothing else \ + is affected. This reason will not be repeated here; further occurrences of it go to the log." + ) +} + +/// The line shown when the mailbox answers again after a run of failures. +#[must_use] +pub fn pull_recovery_notice(reason: &str, failed_pulls: u64) -> String { + let cause = reason.lines().next().unwrap_or(reason).trim(); + let pulls = if failed_pulls == 1 { "pull" } else { "pulls" }; + format!( + "Daemon assignments are being received again after {failed_pulls} failed {pulls} ({cause}). \ + This chat can be assigned work again." + ) +} + +// ── The poll loop ─────────────────────────────────────────────────────────── + +/// Where one pulled batch went, so the loop's ordering can be asserted. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct BatchOutcome { + /// Ids handed to the local input queue by this batch, in order. + pub delivered: Vec, + /// Ids already held from an earlier delivery, taken again and not re-run. + pub duplicates: Vec, + /// Ids to acknowledge on the *next* pull. + pub acks: Vec, + /// True when the input queue is gone and the loop should stop. + pub input_closed: bool, +} + +/// Hand one pulled batch to the chat input queue. +/// +/// The ordering here is the whole point, and it is the reverse of the obvious +/// one: an id joins `acks` only **after** the message it carries has been +/// accepted by the local queue. Acknowledging first would tell the daemon the +/// work is safe at the moment it is least safe — still in flight, owned by +/// nobody — and a process that died there would take it with it. Paying for +/// that with an occasional redelivery is the trade the mailbox is designed +/// around, and `taken` is what makes a redelivery cost nothing. +/// +/// MUTATION GUARD: move the `acks.push` above the `send` and +/// `a_batch_is_acknowledged_only_after_it_reaches_the_local_queue` fails. +pub async fn take_batch( + mailbox: &dyn AssignmentMailbox, + batch: Vec, + input: &crate::runtime::h2_entry::ChatInputSender, + notify: &(dyn Fn(&str) + Send + Sync), +) -> BatchOutcome { + let mut outcome = BatchOutcome::default(); + for assignment in batch { + let id = assignment.assignment_id.clone(); + if !mailbox.accept(&id) { + // A redelivery of work already queued here. Acknowledge it so the + // daemon stops resending, and do not run it a second time. + outcome.duplicates.push(id.clone()); + outcome.acks.push(id); + continue; + } + if !Disposition::is_known_wire(&assignment.disposition) { + notify(&unknown_disposition_notice(&assignment.disposition)); + } + let disposition = Disposition::from_wire(&assignment.disposition); + let message = assignment_message(&assignment, disposition); + // Announced before it is handed over, not after: the turn can start, + // finish and print its answer before this task is scheduled again, and + // an announcement that lands after the answer explains nothing. + notify(&arrival_notice(&assignment, disposition)); + if input.send(message).await.is_err() { + // The chat loop is gone. The id is deliberately *not* acknowledged: + // nothing here will ever run it, so the daemon should keep it. + outcome.input_closed = true; + return outcome; + } + outcome.delivered.push(id.clone()); + outcome.acks.push(id); + } + outcome +} + +/// Enrol with the daemon, then pull this chat's mailbox until it is ended. +/// +/// Enrolment runs **here**, inside the spawned task, rather than on the startup +/// path: reaching a daemon can take as long as a TCP connect takes, and a chat +/// that will not show a prompt until some other process answers has made a +/// convenience into a dependency. A refusal costs exactly one capability, is +/// stated once, and everything else about this chat is unchanged. +/// +/// The enrolment call is itself listed and endable while it runs, for the same +/// reason every other daemon call in this process is. +pub async fn enrol_and_poll( + client: Arc, + in_flight: InFlightRegistry, + input: crate::runtime::h2_entry::ChatInputSender, + notify: Arc, + cancel: CancellationToken, +) { + let base_url = client.base_url(); + let enrolling = register_in_flight_labeled(&in_flight, "assignment enrolment", &base_url, cancel.clone()); + let enrolled = tokio::select! { + () = cancel.cancelled() => return, + result = client.enrol() => result, + }; + drop(enrolling); + match enrolled { + Ok(session_ref) => notify(&enrolled_notice(client.label(), &session_ref, &base_url)), + Err(error) => { + notify(&enrolment_failure_notice(&base_url, &error)); + return; + } + } + run_poller(client, in_flight, input, notify, cancel).await; +} + +/// Pull this chat's mailbox until it is cancelled or the chat loop ends. +/// +/// Registers itself in the chat's own in-flight list first, so `/sessions` +/// shows it and `/kill --daemon d` ends it — the same answer to a stuck +/// daemon that every other request in this process gets, and the reason none of +/// this needs a clock. +/// +/// MUTATION GUARD: drop the re-enrolment arm — treat a refusal that says this +/// session is unregistered like any other failure — and +/// `a_daemon_that_forgot_this_session_is_answered_by_registering_again` fails: +/// the poller keeps asking with credentials nothing recognises until a human +/// restarts the chat. +pub async fn run_poller( + mailbox: Arc, + in_flight: InFlightRegistry, + input: crate::runtime::h2_entry::ChatInputSender, + notify: Arc, + cancel: CancellationToken, +) { + let session_ref = mailbox.session_ref(); + let row: InFlightGuard = register_in_flight_labeled( + &in_flight, + &format!("assignment poll {session_ref}"), + &mailbox.base_url(), + cancel.clone(), + ); + let _row = row; + let mut pending_acks: Vec = Vec::new(); + let mut notices = FailureNotices::default(); + // When this poller last tried to register again, so a daemon that forgets + // this session on every pull cannot buy one notice per poll interval. A + // clock reading, not a timer: nothing here waits on it. + let mut last_re_enrolment: Option = None; + loop { + let pull = tokio::select! { + () = cancel.cancelled() => break, + pull = mailbox.pull(pending_acks.clone()) => pull, + }; + match pull { + Ok(batch) => { + // The acknowledgements rode along with this request and the + // daemon answered, so they are spent. Anything new takes their + // place only once it is in the local queue. + pending_acks.clear(); + if batch + .messages + .iter() + .any(|value| value.get("kind").and_then(|v| v.as_str()) == Some("message")) + { + let wake = crate::channels::traits::ChannelMessage { + id: "mailbox-wake".into(), + sender: "session-message".into(), + sender_is_bot: true, + channel: "terminal".into(), + ..crate::channels::traits::ChannelMessage::default() + }; + if input.send(wake).await.is_err() { + break; + } + } + if let Some(line) = notices.recovered() { + notify(&line); + } + let outcome = take_batch(mailbox.as_ref(), batch.assignments, &input, notify.as_ref()).await; + pending_acks = outcome.acks; + if outcome.input_closed { + break; + } + } + Err(error) if tasks_cli::session_is_unregistered(&error) => { + // The daemon holds no row for this session: it restarted — the + // registry is process memory and rebuilds nothing — or an + // operator removed the row. Either way this chat is + // unassignable until it registers again, and requiring a human + // to restart every chat after every daemon restart is not a + // recovery. Registering again is, and the next pull is the + // natural retry for a registration that also fails: this loop + // is already periodic, so nothing here needs a timer. + // + // Whatever happens next, the acknowledgements were for a mailbox + // that no longer exists. Sending them to a new session would + // acknowledge ids it never handed out. + pending_acks.clear(); + // At most one attempt per [`RE_ENROLMENT_MIN_INTERVAL`]: a daemon + // stuck in "who are you?" answers every pull, and re-registering + // on each one would put a notice on screen every poll interval. + if last_re_enrolment.is_some_and(|at| at.elapsed() < RE_ENROLMENT_MIN_INTERVAL) { + tracing::debug!( + session = %crate::agent::diagnostics::text_class(&session_ref), + "daemon still does not know this chat session; re-enrolment is rate limited" + ); + tokio::select! { + () = cancel.cancelled() => break, + () = tokio::time::sleep(POLL_INTERVAL) => {} + } + continue; + } + last_re_enrolment = Some(tokio::time::Instant::now()); + let stale = mailbox.enrolment_generation(); + let re_enrolled = tokio::select! { + () = cancel.cancelled() => break, + outcome = mailbox.re_enrol(stale) => outcome, + }; + match re_enrolled { + Ok(ReEnrolment::Registered { session_ref }) => { + notices.settled(); + notify(&re_enrolled_notice(&mailbox.base_url(), &session_ref)); + } + // Someone else had already replaced this enrolment. Saying + // so again would be one line per poller for one event. + Ok(ReEnrolment::Superseded { .. }) => notices.settled(), + Err(error) => { + if let Some(line) = notices.failed(&format!("{error:#}")) { + notify(&line); + } + } + } + } + Err(error) => { + // What is allowed to reach the screen is [`FailureNotices`]'s + // decision, not this loop's: a reason that recurs — including + // one that alternates with success — must cost a bounded number + // of lines, or the failure buries the chat somebody is using. + if let Some(line) = notices.failed(&format!("{error:#}")) { + notify(&line); + } + } + } + tokio::select! { + () = cancel.cancelled() => break, + () = tokio::time::sleep(POLL_INTERVAL) => {} + } + } + // Nothing is announced on the way out. A poller ends for exactly two + // reasons: an operator killed it, and `cancel_in_flight` already told them + // so by name; or the chat loop is gone, and there is no longer anywhere for + // a notice to be read. +} diff --git a/src/chat/sessions/assignment/section_2.rs b/src/chat/sessions/assignment/section_2.rs new file mode 100644 index 000000000..d204cdd72 --- /dev/null +++ b/src/chat/sessions/assignment/section_2.rs @@ -0,0 +1,909 @@ +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + fn assignment(id: &str, task: &str, disposition: &str) -> PulledAssignment { + PulledAssignment { + assignment_id: id.to_string(), + session_id: "session".to_string(), + task: task.to_string(), + disposition: disposition.to_string(), + deliveries: 1, + created_at_unix_ms: 0, + work_id: "w1".to_string(), + origin_channel: "wacli".to_string(), + origin_ref: Some("3d1a4f5b".to_string()), + } + } + + fn silent() -> Arc { + Arc::new(|_: &str| {}) + } + + fn client_for_tests() -> Arc { + let config = Config::default(); + AssignmentClient::new(&config) + } + + /// One scripted answer to a pull. + enum Answer { + /// Hand these assignments over. + Batch(Vec), + /// Refuse with this reason. + Refuse(&'static str), + /// Refuse the way a daemon that has forgotten this session does: a + /// `404` carrying the registry's own machine tag. + ForgotTheSession, + /// Refuse the way a daemon answers when the *assignment* is unknown — + /// the same status, a different tag, and never a reason to register + /// again. + ForgotTheAssignment, + } + + /// A refusal in the shape the daemon really sends one, so the poller's + /// decision is made on the wire form rather than on a sentence. + fn refusal(status: u16, code: &str, detail: &str) -> anyhow::Error { + let body = serde_json::json!({ "error": detail, "code": code }).to_string(); + tasks_cli::refusal_for_tests(status, &body, "chat assignment pull") + } + + /// Records every pull's `ack` array and every report, and answers from a + /// script. Enough to assert the loop's ordering without a live daemon. + struct RecordingMailbox { + base_url: String, + pulls: Mutex>>, + reports: Mutex>, + script: Mutex>, + taken: Mutex>, + seq: AtomicUsize, + /// Which enrolment this double is on; bumped by every registration. + generation: Mutex, + /// How many times the poller registered again. + registrations: AtomicUsize, + /// How many times it *tried*, successful or not: what the re-enrolment + /// rate limit is about. + re_enrol_attempts: AtomicUsize, + /// Makes registration fail, for the case where the daemon is not just + /// forgetful but down. + refuse_registration: std::sync::atomic::AtomicBool, + } + + impl RecordingMailbox { + fn new(script: Vec>) -> Arc { + Self::scripted(script.into_iter().map(Answer::Batch).collect()) + } + + fn scripted(script: Vec) -> Arc { + Arc::new(Self { + base_url: "http://127.0.0.1:9".to_string(), + pulls: Mutex::new(Vec::new()), + reports: Mutex::new(Vec::new()), + script: Mutex::new(script), + taken: Mutex::new(HashSet::new()), + seq: AtomicUsize::new(0), + generation: Mutex::new(1), + registrations: AtomicUsize::new(0), + re_enrol_attempts: AtomicUsize::new(0), + refuse_registration: std::sync::atomic::AtomicBool::new(false), + }) + } + } + + impl AssignmentMailbox for RecordingMailbox { + fn session_ref(&self) -> String { + "9b2e0f7c".to_string() + } + + fn base_url(&self) -> String { + self.base_url.clone() + } + + fn pull(&self, ack: Vec) -> MailboxFuture<'_, AssignmentPull> { + self.pulls.lock().push(ack); + let answer = { + let mut script = self.script.lock(); + if script.is_empty() { + Answer::Batch(Vec::new()) + } else { + script.remove(0) + } + }; + Box::pin(async move { + match answer { + Answer::Batch(assignments) => Ok(AssignmentPull { + messages: Vec::new(), + assignments, + acked: 0, + requeued: 0, + queued_remaining: 0, + }), + Answer::Refuse(reason) => Err(anyhow::anyhow!("{reason}")), + Answer::ForgotTheSession => Err(refusal( + 404, + "unknown_session", + "no chat session with that id is registered; `GET /api/chat-sessions` lists the live ones", + )), + Answer::ForgotTheAssignment => Err(refusal( + 404, + "unknown_assignment", + "that assignment is not outstanding for this session", + )), + } + }) + } + + fn report( + &self, + assignment_id: String, + status: ResultStatus, + summary: String, + ) -> MailboxFuture<'_, AssignmentReceipt> { + self.reports.lock().push((assignment_id.clone(), status, summary)); + let seq = self.seq.fetch_add(1, Ordering::SeqCst) as u64 + 1; + Box::pin(async move { + Ok(AssignmentReceipt { + assignment_id, + status: status.as_str().to_string(), + seq, + }) + }) + } + + fn accept(&self, assignment_id: &str) -> bool { + self.taken.lock().insert(assignment_id.to_string()) + } + + fn enrolment_generation(&self) -> u64 { + *self.generation.lock() + } + + fn re_enrol(&self, stale: u64) -> MailboxFuture<'_, ReEnrolment> { + self.re_enrol_attempts.fetch_add(1, Ordering::SeqCst); + Box::pin(async move { + if self.refuse_registration.load(Ordering::SeqCst) { + anyhow::bail!("cannot reach a running PRX process at {}", self.base_url); + } + let mut generation = self.generation.lock(); + if *generation != stale { + return Ok(ReEnrolment::Superseded { + session_ref: "9b2e0f7c".to_string(), + }); + } + *generation = stale + 1; + self.registrations.fetch_add(1, Ordering::SeqCst); + Ok(ReEnrolment::Registered { + session_ref: format!("re-enrolled-{}", *generation), + }) + }) + } + } + + #[tokio::test] + async fn a_batch_is_acknowledged_only_after_it_reaches_the_local_queue() { + let client = client_for_tests(); + let (tx, mut rx) = tokio::sync::mpsc::channel::(4); + let tx: crate::runtime::h2_entry::ChatInputSender = tx.into(); + let outcome = take_batch( + client.as_ref(), + vec![assignment("a-1", "summarise the repo", "queue")], + &tx, + silent().as_ref(), + ) + .await; + assert_eq!(outcome.delivered, vec!["a-1".to_string()]); + assert_eq!( + outcome.acks, + vec!["a-1".to_string()], + "an assignment safely in the local queue is acknowledged on the next pull" + ); + assert!(rx.try_recv().is_ok(), "the assignment must reach the chat input queue"); + + // The same call with nowhere to deliver must acknowledge nothing: work + // this chat cannot run has to stay the daemon's. + let client2 = client_for_tests(); + let (closed_tx, closed_rx) = tokio::sync::mpsc::channel::(1); + let closed_tx: crate::runtime::h2_entry::ChatInputSender = closed_tx.into(); + drop(closed_rx); + let refused = take_batch( + client2.as_ref(), + vec![assignment("a-2", "do a thing", "queue")], + &closed_tx, + silent().as_ref(), + ) + .await; + assert!(refused.input_closed); + assert!( + refused.acks.is_empty(), + "work that never reached the local queue must not be acknowledged: {:?}", + refused.acks + ); + } + + #[tokio::test] + async fn a_redelivered_assignment_is_acknowledged_but_never_run_twice() { + let client = client_for_tests(); + let (tx, mut rx) = tokio::sync::mpsc::channel::(8); + let tx: crate::runtime::h2_entry::ChatInputSender = tx.into(); + let first = take_batch( + client.as_ref(), + vec![assignment("dup", "work", "queue")], + &tx, + silent().as_ref(), + ) + .await; + assert_eq!(first.delivered, vec!["dup".to_string()]); + + let mut again = assignment("dup", "work", "queue"); + again.deliveries = 2; + let second = take_batch(client.as_ref(), vec![again], &tx, silent().as_ref()).await; + assert!( + second.delivered.is_empty(), + "a redelivery of held work must not be queued again: {:?}", + second.delivered + ); + assert_eq!(second.duplicates, vec!["dup".to_string()]); + assert_eq!( + second.acks, + vec!["dup".to_string()], + "a redelivery must still be acknowledged, or the daemon keeps resending it" + ); + assert!(rx.try_recv().is_ok()); + assert!( + rx.try_recv().is_err(), + "exactly one input message may exist for one assignment id" + ); + } + + #[tokio::test] + async fn the_first_pull_acknowledges_nothing_and_the_second_acknowledges_the_first_batch() { + let mailbox = RecordingMailbox::new(vec![vec![assignment("a-1", "one", "queue")], vec![]]); + let client = client_for_tests(); + let (tx, _rx) = tokio::sync::mpsc::channel::(8); + let tx: crate::runtime::h2_entry::ChatInputSender = tx.into(); + + // Drive the same two steps the loop drives, without its sleep. + let mut pending: Vec = Vec::new(); + for _ in 0..2u8 { + let batch = mailbox.pull(pending.clone()).await.unwrap(); + pending.clear(); + let outcome = take_batch(client.as_ref(), batch.assignments, &tx, silent().as_ref()).await; + pending = outcome.acks; + } + let pulls = mailbox.pulls.lock().clone(); + assert_eq!(pulls.len(), 2); + assert!( + pulls[0].is_empty(), + "the first pull cannot acknowledge anything it has not received yet: {:?}", + pulls[0] + ); + assert_eq!( + pulls[1], + vec!["a-1".to_string()], + "the batch taken by the first pull is acknowledged by the second" + ); + } + + #[tokio::test] + async fn a_dropped_turn_guard_reports_a_failure_rather_than_going_quiet() { + let mailbox = RecordingMailbox::new(vec![]); + let registry = super::super::daemon::new_in_flight_registry(); + { + let _guard = AssignmentTurnGuard::new( + Arc::clone(&mailbox) as Arc, + Arc::clone(®istry), + silent(), + "a-1".to_string(), + ); + } + tokio::task::yield_now().await; + let reports = mailbox.reports.lock().clone(); + assert_eq!( + reports.len(), + 1, + "a turn that ended without a reply still owes an answer" + ); + assert_eq!(reports[0].0, "a-1"); + assert_eq!(reports[0].1, ResultStatus::Failed); + assert!(!reports[0].2.trim().is_empty(), "expected a non-empty value"); + } + + #[tokio::test] + async fn a_completed_turn_reports_its_reply() { + let mailbox = RecordingMailbox::new(vec![]); + let registry = super::super::daemon::new_in_flight_registry(); + { + let mut guard = AssignmentTurnGuard::new( + Arc::clone(&mailbox) as Arc, + Arc::clone(®istry), + silent(), + "a-2".to_string(), + ); + guard.completed("37 TODOs"); + } + tokio::task::yield_now().await; + let reports = mailbox.reports.lock().clone(); + assert_eq!(reports.len(), 1); + assert_eq!(reports[0].1, ResultStatus::Completed); + assert_eq!(reports[0].2, "37 TODOs"); + } + + /// D-053 / REDACT-TURN: the daemon stores an assignment report as the + /// assignment's result, so the reply and the failure reason are redacted + /// before they leave the chat. Fails before REDACT-TURN. + #[tokio::test] + async fn an_assignment_report_carries_no_secret_from_the_reply_or_the_failure() { + use crate::agent::terminal::persistence_probe::PROBE_SECRET; + let mailbox = RecordingMailbox::new(vec![]); + let registry = super::super::daemon::new_in_flight_registry(); + { + let mut completed = AssignmentTurnGuard::new( + Arc::clone(&mailbox) as Arc, + Arc::clone(®istry), + silent(), + "a-secret-1".to_string(), + ); + completed.completed(&format!("Here is the key {PROBE_SECRET} you asked for")); + let mut failed = AssignmentTurnGuard::new( + Arc::clone(&mailbox) as Arc, + Arc::clone(®istry), + silent(), + "a-secret-2".to_string(), + ); + failed.failed(&format!("redux driver failed: upstream rejected key {PROBE_SECRET}")); + } + tokio::task::yield_now().await; + let reports = mailbox.reports.lock().clone(); + assert_eq!(reports.len(), 2, "both turns report"); + for report in &reports { + assert!(!report.2.contains(PROBE_SECRET), "{report:?}"); + assert!(report.2.contains("[REDACTED]"), "{report:?}"); + } + } + + #[tokio::test] + async fn a_disarmed_guard_reports_nothing_because_the_work_still_has_to_run() { + let mailbox = RecordingMailbox::new(vec![]); + let registry = super::super::daemon::new_in_flight_registry(); + { + let mut guard = AssignmentTurnGuard::new( + Arc::clone(&mailbox) as Arc, + Arc::clone(®istry), + silent(), + "a-3".to_string(), + ); + guard.disarm(); + assert!(!guard.is_armed()); + } + tokio::task::yield_now().await; + assert!( + mailbox.reports.lock().is_empty(), + "a requeued assignment must not be answered for before it runs" + ); + } + + /// Collects every line the poller put on screen. + fn recording_notifier() -> (Arc, Arc>>) { + let lines = Arc::new(Mutex::new(Vec::new())); + let sink = Arc::clone(&lines); + let notify: Arc = Arc::new(move |text: &str| sink.lock().push(text.to_string())); + (notify, lines) + } + + /// Lines the poller printed to say the mailbox is failing, for a reason + /// containing `marker`. The recovery line quotes the reason it is about, so + /// counting occurrences of the reason alone would count that too. + fn complaints_about(said: &[String], marker: &str) -> usize { + said.iter() + .filter(|line| line.starts_with("Daemon assignments are not being received") && line.contains(marker)) + .count() + } + + /// Drive the poller over a script and hand back everything it said. + /// + /// `start_paused` because the loop sleeps a poll interval between pulls: the + /// interval is a sampling rate, and simulating it is what keeps a test about + /// twenty pulls from taking thirty seconds. + async fn lines_from_script(script: Vec) -> Vec { + drive_script(RecordingMailbox::scripted(script)).await.1 + } + + /// Drive a prepared mailbox to the end of its script, handing back the + /// mailbox and everything the poller said. + async fn drive_script(mailbox: Arc) -> (Arc, Vec) { + let pulls_scripted = mailbox.script.lock().len(); + let (notify, lines) = recording_notifier(); + let registry = super::super::daemon::new_in_flight_registry(); + let (tx, _rx) = tokio::sync::mpsc::channel::(8); + let tx: crate::runtime::h2_entry::ChatInputSender = tx.into(); + let cancel = CancellationToken::new(); + let handle = tokio::spawn(run_poller( + Arc::clone(&mailbox) as Arc, + registry, + tx, + notify, + cancel.clone(), + )); + for _ in 0..(pulls_scripted * 4 + 8) { + if mailbox.pulls.lock().len() > pulls_scripted { + break; + } + tokio::time::sleep(POLL_INTERVAL).await; + } + cancel.cancel(); + handle.await.expect("the poller must end when it is cancelled"); + assert!( + mailbox.pulls.lock().len() > pulls_scripted, + "the script must have been driven to the end" + ); + let said = lines.lock().clone(); + (mailbox, said) + } + + const RATE_LIMITED: &str = "chat assignment pull failed with HTTP 429 Too Many Requests: \ + Too many API requests. Please retry later."; + const UNREACHABLE: &str = "cannot reach a running PRX process at http://127.0.0.1:9"; + + /// A daemon restart forgets every registration, and this chat holds a + /// session id nothing answers to. Registering again is the recovery, and it + /// happens here rather than in whoever notices the chat stopped working. + #[tokio::test(start_paused = true)] + async fn a_daemon_that_forgot_this_session_is_answered_by_registering_again() { + let (mailbox, said) = drive_script(RecordingMailbox::scripted(vec![ + Answer::Batch(vec![]), + Answer::ForgotTheSession, + Answer::Batch(vec![assignment("after-restart", "count the crates", "queue")]), + ])) + .await; + assert_eq!( + mailbox.registrations.load(Ordering::SeqCst), + 1, + "the poller must register again by itself; said:\n{said:#?}" + ); + assert_eq!(*mailbox.generation.lock(), 2, "the new enrolment replaces the old one"); + assert!( + mailbox.taken.lock().contains("after-restart"), + "the point of re-enrolling is taking work again, and this chat took none" + ); + assert!( + said.iter().any(|line| line.contains("registered again")), + "a new session id is a fact the operator has to be told; said:\n{said:#?}" + ); + assert!( + !said.iter().any(|line| line.contains("are not being received")), + "a restart that healed itself must not be reported as a failure; said:\n{said:#?}" + ); + } + + /// The acknowledgements from before the restart belong to a mailbox that no + /// longer exists; sending them on would acknowledge ids the new session + /// never handed out. + #[tokio::test(start_paused = true)] + async fn work_acknowledged_to_the_old_session_is_not_acknowledged_to_the_new_one() { + let (mailbox, _said) = drive_script(RecordingMailbox::scripted(vec![ + Answer::Batch(vec![assignment("before-restart", "work", "queue")]), + Answer::ForgotTheSession, + Answer::Batch(vec![]), + ])) + .await; + let acks = mailbox.pulls.lock().clone(); + assert_eq!( + acks.first().map(Vec::len), + Some(0), + "the first pull acknowledges nothing: {acks:?}" + ); + assert_eq!( + acks.get(1).map(Vec::as_slice), + Some(["before-restart".to_string()].as_slice()), + "the pull that met the restart still carried the acknowledgement it owed: {acks:?}" + ); + assert!( + acks.iter().skip(2).all(Vec::is_empty), + "a new session must not be handed the dead session's acknowledgements: {acks:?}" + ); + } + + /// A daemon stuck in "who are you?" answers every single pull that way. The + /// recovery is idempotent, but every successful one puts a line on the + /// operator's screen, so re-registering on each answer would write one + /// every poll interval — a notification flood from a loop that is supposed + /// to be quiet. + /// + /// MUTATION GUARD: remove the [`RE_ENROLMENT_MIN_INTERVAL`] gate and this + /// fails with one attempt (and one notice) per unregistered answer. + #[tokio::test(start_paused = true)] + async fn a_daemon_that_keeps_forgetting_this_session_is_answered_at_most_once_a_minute() { + let (mailbox, said) = drive_script(RecordingMailbox::scripted(vec![ + Answer::ForgotTheSession, + Answer::ForgotTheSession, + Answer::ForgotTheSession, + Answer::ForgotTheSession, + Answer::ForgotTheSession, + Answer::ForgotTheSession, + ])) + .await; + assert_eq!( + mailbox.re_enrol_attempts.load(Ordering::SeqCst), + 1, + "six unregistered answers inside one minute are one recovery attempt; said:\n{said:#?}" + ); + assert_eq!( + said.iter().filter(|line| line.contains("registered again")).count(), + 1, + "and therefore exactly one notice; said:\n{said:#?}" + ); + assert!( + mailbox.pulls.lock().len() > 6, + "the poller must keep polling while the recovery is rate limited: {:?}", + mailbox.pulls.lock().len() + ); + } + + /// The same status, a different fact. An unknown *assignment* says nothing + /// about whether this session is registered, and re-registering on it would + /// abandon a perfectly good enrolment. + #[tokio::test(start_paused = true)] + async fn a_refusal_about_an_assignment_never_makes_this_chat_register_again() { + let (mailbox, said) = drive_script(RecordingMailbox::scripted(vec![ + Answer::ForgotTheAssignment, + Answer::ForgotTheAssignment, + Answer::Batch(vec![]), + ])) + .await; + assert_eq!( + mailbox.registrations.load(Ordering::SeqCst), + 0, + "only `unknown_session` means this session is gone; said:\n{said:#?}" + ); + assert!( + said.iter().any(|line| line.contains("are not being received")), + "a refusal this chat cannot heal must still be stated; said:\n{said:#?}" + ); + } + + /// A daemon that is gone rather than merely forgetful: registering again + /// fails too, a later pull is the retry, and it costs one line however long + /// the daemon stays down. The retry is rate limited (see + /// [`RE_ENROLMENT_MIN_INTERVAL`]), so the poller keeps polling while the + /// recovery attempt itself happens at most once a minute. + #[tokio::test(start_paused = true)] + async fn a_registration_that_also_fails_is_retried_later_and_said_once() { + let mailbox = RecordingMailbox::scripted(vec![ + Answer::ForgotTheSession, + Answer::ForgotTheSession, + Answer::ForgotTheSession, + ]); + mailbox.refuse_registration.store(true, Ordering::SeqCst); + let (mailbox, said) = drive_script(mailbox).await; + assert_eq!(mailbox.registrations.load(Ordering::SeqCst), 0); + assert!( + mailbox.pulls.lock().len() >= 3, + "the poll loop is the retry; it must keep asking: {:?}", + mailbox.pulls.lock().len() + ); + assert_eq!( + mailbox.re_enrol_attempts.load(Ordering::SeqCst), + 1, + "three refusals inside one minute buy one recovery attempt, not three" + ); + assert_eq!( + complaints_about(&said, "cannot reach"), + 1, + "one blocked recovery, one line; said:\n{said:#?}" + ); + } + + /// Idempotency, at the level it actually matters: two callers that saw the + /// same dead enrolment must produce one registration, not two sessions the + /// daemon then has to be told apart. + #[tokio::test] + async fn concurrent_recoveries_from_the_same_dead_enrolment_register_once() { + let mailbox = RecordingMailbox::scripted(vec![]); + let stale = mailbox.enrolment_generation(); + let first = mailbox.re_enrol(stale); + let second = mailbox.re_enrol(stale); + let third = mailbox.re_enrol(stale); + let (first, second, third) = tokio::join!(first, second, third); + let outcomes = [ + first.expect("re-enrolment"), + second.expect("re-enrolment"), + third.expect("re-enrolment"), + ]; + let registered = outcomes + .iter() + .filter(|outcome| matches!(outcome, ReEnrolment::Registered { .. })) + .count(); + assert_eq!(registered, 1, "three triggers, one registration: {outcomes:?}"); + assert_eq!(mailbox.registrations.load(Ordering::SeqCst), 1); + } + + /// The flood this was written against: a mailbox that refuses every other + /// pull. The reason is identical every time, so it is worth exactly one + /// line however many times it comes back. + /// + /// MUTATION GUARD: clear `FailureNotices::announced` on a successful pull — + /// the shape of the dedup this replaced — and this fails with one line per + /// refusal. + #[tokio::test(start_paused = true)] + async fn one_failure_reason_is_stated_once_however_often_it_recurs() { + let said = lines_from_script(vec![ + Answer::Refuse(RATE_LIMITED), + Answer::Batch(vec![]), + Answer::Refuse(RATE_LIMITED), + Answer::Batch(vec![]), + Answer::Refuse(RATE_LIMITED), + Answer::Refuse(RATE_LIMITED), + Answer::Batch(vec![]), + Answer::Refuse(RATE_LIMITED), + ]) + .await; + assert_eq!( + complaints_about(&said, "429"), + 1, + "one reason is worth one line, not one per failing pull; said:\n{said:#?}" + ); + let recoveries = said.iter().filter(|line| line.contains("being received again")).count(); + assert_eq!( + recoveries, 1, + "recovery is announced, and it is announced once; said:\n{said:#?}" + ); + } + + /// Going quiet about a failure is the other half of the bug: the operator + /// has to be told, once, and told again when it clears. + #[tokio::test(start_paused = true)] + async fn a_failure_and_its_recovery_are_both_stated() { + let said = lines_from_script(vec![ + Answer::Refuse(UNREACHABLE), + Answer::Refuse(UNREACHABLE), + Answer::Batch(vec![]), + ]) + .await; + assert!( + said.iter().any(|line| line.contains("are not being received")), + "a mailbox that cannot be reached must say so; said:\n{said:#?}" + ); + let recovery = said + .iter() + .find(|line| line.contains("being received again")) + .expect("recovery must be announced, or nobody knows when it healed"); + assert!( + recovery.contains("2 failed pulls"), + "the recovery line says how long it was broken: {recovery}" + ); + } + + /// A different reason is a different fact, and is stated on its own. + #[tokio::test(start_paused = true)] + async fn a_changed_reason_is_stated_even_while_the_mailbox_is_still_failing() { + let said = lines_from_script(vec![ + Answer::Refuse(RATE_LIMITED), + Answer::Refuse(RATE_LIMITED), + Answer::Refuse(UNREACHABLE), + Answer::Refuse(UNREACHABLE), + ]) + .await; + assert_eq!(complaints_about(&said, "429"), 1, "said:\n{said:#?}"); + assert_eq!( + complaints_about(&said, "cannot reach"), + 1, + "a reason the operator has not seen must not be swallowed by the previous one; said:\n{said:#?}" + ); + } + + #[test] + fn a_recovery_is_never_announced_for_a_failure_that_was_never_announced() { + let mut notices = FailureNotices::default(); + assert!(notices.recovered().is_none(), "nothing has failed yet"); + assert!(notices.failed("reason a").is_some()); + assert!(notices.failed("reason a").is_none()); + assert!(notices.recovered().is_some()); + // Second episode of the same reason: silent, so its recovery is silent + // too. Announcing "it works again" for something never reported broken + // is noise about a fact nobody was missing. + assert!(notices.failed("reason a").is_none()); + assert!(notices.recovered().is_none()); + assert!(!notices.is_failing()); + } + + #[test] + fn a_peer_whose_wording_keeps_changing_cannot_grow_the_policy_without_bound() { + let mut notices = FailureNotices::default(); + let mut announced = 0; + for attempt in 0..(MAX_TRACKED_REASONS * 4) { + if notices.failed(&format!("refused, attempt {attempt}")).is_some() { + announced += 1; + } + } + assert_eq!( + announced, MAX_TRACKED_REASONS, + "a varying message must not buy unlimited screen space" + ); + } + + #[tokio::test] + async fn the_poller_is_listed_while_it_runs_and_a_kill_ends_it() { + let registry = super::super::daemon::new_in_flight_registry(); + let client = client_for_tests(); + let (tx, _rx) = tokio::sync::mpsc::channel::(8); + let tx: crate::runtime::h2_entry::ChatInputSender = tx.into(); + let cancel = CancellationToken::new(); + let handle = tokio::spawn(run_poller( + Arc::clone(&client) as Arc, + Arc::clone(®istry), + tx, + silent(), + cancel.clone(), + )); + // The row is published before the first request, so it is visible even + // while the very first pull is outstanding. + let mut listed = None; + for _ in 0..100u16 { + if let Some(report) = super::super::daemon::in_flight_report(®istry) { + listed = Some(report); + break; + } + tokio::task::yield_now().await; + } + let listed = listed.expect("the poller must be listed in /sessions while it runs"); + assert!(listed.contains("assignment poll"), "listing was: {listed}"); + let killed = super::super::daemon::cancel_in_flight(®istry, "d1").expect("d1 is this chat's address space"); + assert!(killed.contains("d1"), "kill notice was: {killed}"); + handle.await.expect("the poller must end when it is killed"); + assert!( + super::super::daemon::in_flight_report(®istry).is_none(), + "an ended poller must stop being listed" + ); + } + + #[test] + fn an_assignment_survives_a_round_trip_through_the_input_queue() { + for (wire, disposition) in [ + ("queue", Disposition::Queue), + ("steer", Disposition::Steer), + ("interrupt", Disposition::Interrupt), + ] { + let msg = assignment_message(&assignment("a-1", "do the thing", wire), disposition); + let seen = delivered(&msg).expect("an assignment message must be recognisable"); + assert_eq!(seen.assignment_id, "a-1"); + assert_eq!(seen.disposition, disposition); + if disposition.jumps_the_queue() { + assert!( + msg.content.starts_with("/now "), + "a queue-jumping disposition must use the existing priority prefix: {}", + msg.content + ); + } else { + assert_eq!(msg.content, "do the thing"); + } + } + } + + #[test] + fn ordinary_input_is_never_mistaken_for_an_assignment() { + let mut msg = assignment_message(&assignment("a-1", "task", "queue"), Disposition::Queue); + msg.sender = "user".to_string(); + assert!(delivered(&msg).is_none()); + msg.sender = "prx-ui".to_string(); + assert!(delivered(&msg).is_none()); + msg.sender = format!("{SENDER_PREFIX}queue:"); + assert!(delivered(&msg).is_none(), "an empty assignment id is not an assignment"); + } + + #[test] + fn an_unknown_disposition_degrades_to_queue_and_never_to_interrupt() { + assert_eq!(Disposition::from_wire("obliterate"), Disposition::Queue); + assert_eq!(Disposition::from_wire(""), Disposition::Queue); + assert!(!Disposition::is_known_wire("obliterate")); + assert!(Disposition::is_known_wire("interrupt")); + assert!(!Disposition::from_wire("obliterate").ends_the_turn_in_flight()); + } + + #[test] + fn only_interrupt_ends_the_turn_in_flight() { + assert!(!Disposition::Queue.jumps_the_queue()); + assert!(Disposition::Steer.jumps_the_queue()); + assert!(Disposition::Interrupt.jumps_the_queue()); + assert!(!Disposition::Queue.ends_the_turn_in_flight()); + assert!( + !Disposition::Steer.ends_the_turn_in_flight(), + "steer inserts into the turn in flight; it does not destroy it" + ); + assert!(Disposition::Interrupt.ends_the_turn_in_flight()); + } + + #[test] + fn a_chat_session_can_never_report_the_daemons_own_cancelled_verdict() { + let reportable: Vec<&str> = ResultStatus::all().iter().map(|status| status.as_str()).collect(); + assert_eq!(reportable, vec!["completed", "failed", "rejected"]); + assert!( + !reportable.contains(&"cancelled"), + "`cancelled` is the daemon's verdict about work it ended, not something a client may claim" + ); + } + + #[test] + fn a_summary_is_fitted_to_what_the_daemon_accepts() { + assert_eq!(bound_summary(" answer "), "answer"); + assert!( + !bound_summary(" ").is_empty(), + "an empty summary is refused by the daemon" + ); + let huge = "x".repeat(MAX_SUMMARY_BYTES * 2); + let bounded = bound_summary(&huge); + assert!(bounded.len() <= MAX_SUMMARY_BYTES, "bounded to {}", bounded.len()); + assert!(bounded.ends_with("to fit the result field)")); + let wide = "\u{20ac}".repeat(MAX_SUMMARY_BYTES); + assert!(bound_summary(&wide).len() <= MAX_SUMMARY_BYTES); + } + + #[test] + fn enrolment_is_declined_when_nothing_points_this_chat_at_a_daemon() { + let mut config = Config::default(); + config.chat.daemon.url = String::new(); + config.chat.daemon.token = String::new(); + config.gateway.paired_tokens = vec![]; + match enrolable(&config) { + Enrolable::No(reason) => { + assert!(reason.contains("chat.daemon.url"), "reason was: {reason}"); + } + Enrolable::Yes => panic!("an unconfigured chat must not announce a daemon failure on every start"), + } + config.chat.daemon.url = "http://127.0.0.1:8765".to_string(); + assert_eq!(enrolable(&config), Enrolable::Yes); + + let mut with_token = Config::default(); + with_token.chat.daemon.url = String::new(); + with_token.chat.daemon.token = "plaintext-token".to_string(); + assert_eq!(enrolable(&with_token), Enrolable::Yes); + } + + #[test] + fn an_arrival_names_the_origin_and_the_disposition_without_going_quiet() { + let notice = arrival_notice( + &assignment("a-1", "summarise the repo", "interrupt"), + Disposition::Interrupt, + ); + assert!(notice.contains("wacli"), "{notice}"); + assert!(notice.contains("3d1a4f5b"), "{notice}"); + assert!(notice.contains("summarise the repo"), "{notice}"); + assert!(notice.contains("interrupt"), "{notice}"); + + let mut redelivered = assignment("a-1", "task", "queue"); + redelivered.deliveries = 3; + assert!(arrival_notice(&redelivered, Disposition::Queue).contains("redelivery #3")); + + let mut operator = assignment("a-2", "task", "queue"); + operator.origin_channel = "api".to_string(); + operator.origin_ref = None; + let plane = arrival_notice(&operator, Disposition::Queue); + assert!(plane.contains("api"), "{plane}"); + } + + #[test] + fn a_label_is_stable_and_fits_what_the_daemon_accepts() { + let mut config = Config::default(); + config.workspace_dir = std::path::PathBuf::from("/tmp/some/workstation"); + assert_eq!(label_for(&config), "workstation"); + config.workspace_dir = std::path::PathBuf::from(format!("/tmp/{}", "n".repeat(200))); + assert!(label_for(&config).len() <= MAX_LABEL_BYTES); + config.workspace_dir = std::path::PathBuf::from("/"); + assert_eq!(label_for(&config), "chat"); + } + /// Mutation: retain a raw chain in an assignment notice or repeated-pull episode. + #[test] + fn assignment_failure_notices_hide_nested_credentials() { + let error = anyhow::anyhow!("token=opaque7credential").context("failed"); + let mut notices = FailureNotices::default(); + let pull = notices.failed(&format!("{error:#}")).expect("test: first notice"); + for notice in [ + report_failure_notice("assignment", ResultStatus::Failed, &error), + enrolment_failure_notice("https://example.com?key=opaque7credential", &error), + pull, + ] { + assert!(notice.contains("[REDACTED]"), "{notice}"); + assert!(!notice.contains("opaque7credential"), "{notice}"); + } + } +} diff --git a/src/chat/sessions/child.rs b/src/chat/sessions/child.rs index dd9c6ec82..4d6bac14f 100644 --- a/src/chat/sessions/child.rs +++ b/src/chat/sessions/child.rs @@ -10,15 +10,9 @@ use sha2::{Digest, Sha256}; use uuid::Uuid; use super::approval::PendingApprovals; -use crate::messaging::{InheritedProvenance, SessionAddr}; +use crate::messaging::SessionAddr; use crate::tools::sessions_spawn::HistoryEntry; -/// Inbound mailbox consume cursor. MSG-CORE fills reconstruction. -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct MailboxCursor { - pub streams: std::collections::BTreeMap, -} - /// Provider binding without credentials (no key wiring). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ProviderBinding { @@ -28,26 +22,13 @@ pub struct ProviderBinding { pub model: String, } -/// Process-mode relaunch recipe: same [`SessionAddr`], new run. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct RelaunchRecipe { - /// Stable address across relaunch. - pub addr: SessionAddr, - /// Last completed run, if any. - pub last_run: Option, - /// Sealed provenance restored on relaunch. - pub inherited_provenance: Option, -} - /// One child session owned by the parent chat for its lifetime. pub struct ChildSession { addr: SessionAddr, history: Vec, provider: Option, - mailbox_cursor: MailboxCursor, approvals: PendingApprovals, turn: Mutex<()>, - recipe: Option, mailbox_projection: std::collections::BTreeMap, tool_calls: std::collections::BTreeMap>, mailbox_scope: Option, @@ -57,23 +38,17 @@ pub struct ChildSession { impl ChildSession { /// Construct a live child session. #[must_use] - pub fn new(addr: SessionAddr, provider: Option, recipe: Option) -> Self { + pub fn new(addr: SessionAddr, provider: Option) -> Self { Self { - addr: addr.clone(), + addr, history: Vec::new(), provider, - mailbox_cursor: MailboxCursor::default(), mailbox_projection: Default::default(), tool_calls: Default::default(), mailbox_scope: None, _history_lease: None, approvals: PendingApprovals::new(), turn: Mutex::new(()), - recipe: recipe.or(Some(RelaunchRecipe { - addr, - last_run: None, - inherited_provenance: None, - })), } } @@ -107,28 +82,15 @@ impl ChildSession { self.provider.as_ref() } - /// Mailbox cursor (empty until MSG-CORE). - #[must_use] - pub const fn mailbox_cursor(&self) -> &MailboxCursor { - &self.mailbox_cursor - } - /// Acquire the turn mutex. pub fn lock_turn(&self) -> parking_lot::MutexGuard<'_, ()> { self.turn.lock() } - /// Process relaunch recipe, if this is a process child. - #[must_use] - pub const fn recipe(&self) -> Option<&RelaunchRecipe> { - self.recipe.as_ref() - } - fn metadata(&self) -> ChildSessionMetadata { ChildSessionMetadata { addr: self.addr.clone(), provider: self.provider.clone(), - recipe: self.recipe.clone(), mailbox_projection: self.mailbox_projection.clone(), } } @@ -140,7 +102,6 @@ impl ChildSession { pub struct ChildSessionMetadata { pub addr: SessionAddr, pub provider: Option, - pub recipe: Option, /// Event identities of mailbox-projected turns; never a progress cursor. #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] pub mailbox_projection: std::collections::BTreeMap, @@ -153,8 +114,6 @@ struct ScopedChatRecord { #[serde(skip)] scope: crate::messaging::mailbox::MailboxScope, #[serde(skip)] - cursors: std::collections::BTreeMap, - #[serde(skip)] mailbox_turns: Vec, #[serde(skip)] lease: Box, @@ -178,7 +137,6 @@ impl ScopedChatRecord { Ok(Self { record, scope: loaded.scope, - cursors: loaded.cursors, mailbox_turns: loaded.mailbox_turns, lease: loaded.lease, }) @@ -278,7 +236,7 @@ impl ChildSessionRegistry { let preserved_calls = child.tool_calls.clone(); let key = Self::record_id(child.addr())?; self.update_record(child.addr(), move |old| { - let mut metadata = metadata.clone(); + let metadata = metadata.clone(); let mut record = old.unwrap_or_else(|| { let mut record = crate::chat::session::ChatSession::new( metadata @@ -293,11 +251,6 @@ impl ChildSessionRegistry { record.id = key.clone(); record }); - if let Some(recipe) = metadata.recipe.as_mut() - && let Some(previous) = record.child_session.as_ref().and_then(|value| value.recipe.as_ref()) - { - recipe.last_run.clone_from(&previous.last_run); - } record.child_session = Some(metadata); record.turns = history .iter() @@ -352,7 +305,6 @@ impl ChildSessionRegistry { let ScopedChatRecord { record, scope, - cursors, mailbox_turns, lease, } = self.load_record(addr).await?; @@ -408,8 +360,6 @@ impl ChildSessionRegistry { addr: metadata.addr, history, provider: metadata.provider, - recipe: metadata.recipe, - mailbox_cursor: MailboxCursor { streams: cursors }, approvals: PendingApprovals::new(), turn: Mutex::new(()), mailbox_projection: projection, @@ -430,8 +380,8 @@ mod tests { #[test] fn two_child_sessions_hold_independent_approvals() { - let a = ChildSession::new(addr("child-a"), None, None); - let b = ChildSession::new(addr("child-b"), None, None); + let a = ChildSession::new(addr("child-a"), None); + let b = ChildSession::new(addr("child-b"), None); a.approvals().test_register("run-a"); assert!( a.approvals().is_pending("run-a"), @@ -469,7 +419,6 @@ mod tests { provider: "openrouter".into(), model: "m".into(), }), - None, ); live.history.push(HistoryEntry { role: "user".into(), @@ -501,11 +450,6 @@ mod tests { "child session reconstructs from registry: expected messaging contract changed" ); assert!(!restored.approvals().is_pending("ask-1"), "in-memory Ask dies"); - assert_eq!( - restored.mailbox_cursor(), - &MailboxCursor::default(), - "child session reconstructs from registry: expected messaging contract changed" - ); } #[tokio::test] @@ -514,7 +458,7 @@ mod tests { let memory: Arc = Arc::new(crate::memory::SqliteMemory::new(dir.path()).expect("test: sqlite")); let registry = ChildSessionRegistry::new(Arc::clone(&memory)).with_workspace("prx_workspace".to_owned()); - let child = ChildSession::new(addr("child-a"), None, None); + let child = ChildSession::new(addr("child-a"), None); registry.insert(&child).await.expect("test: insert child"); assert!( memory @@ -597,7 +541,7 @@ mod tests { } async fn rich_child(registry: &ChildSessionRegistry) -> ChildSession { - let mut child = ChildSession::new(addr("child-a"), None, None); + let mut child = ChildSession::new(addr("child-a"), None); child.history.push(HistoryEntry { role: "assistant".into(), content: "prx result".into(), diff --git a/src/chat/state/mod.rs b/src/chat/state/mod.rs index 5a8f6797b..ed44261d2 100644 --- a/src/chat/state/mod.rs +++ b/src/chat/state/mod.rs @@ -1342,7 +1342,7 @@ impl ChatState { compaction_guard_history, compaction_config, cancel, - turn_spawn_ctx, + turn_spawn_ctx.map(|context| *context), turn_message_send_ctx, routing_input, turn_binding, diff --git a/src/chat/tests/p3_directional_switch_tests.rs b/src/chat/tests/p3_directional_switch_tests.rs index 80ee7e083..7a3b1365e 100644 --- a/src/chat/tests/p3_directional_switch_tests.rs +++ b/src/chat/tests/p3_directional_switch_tests.rs @@ -1,3667 +1,5 @@ #![cfg(test)] -use super::*; -use crate::chat::sessions::id::SessionId; -use crate::chat::sessions::model::{ManagedKind, ManagedSessionView, ManagedStatus, SessionOrigin}; - -fn session_view(seq: u64) -> ManagedSessionView { - ManagedSessionView { - id: SessionId::from_run_id(&format!("p3-run-{seq}")), - seq, - kind: ManagedKind::Agent, - origin: SessionOrigin::User, - title: format!("session {seq}"), - status: ManagedStatus::Running, - created_at: chrono::Utc::now(), - updated_at: chrono::Utc::now(), - token_usage_records: Vec::new(), - } -} - -#[test] -fn directional_switch_focus_and_synthetic_attach_seq_match() { - let seq = 42; - let focus = - crate::chat::sessions::focus::optimistic_focus(crate::chat::sessions::focus::RoutingIntent::Attach { seq }); - - assert_eq!(focus, crate::chat::sessions::FocusTarget::Session { seq }); - assert_eq!(attach_command_for_seq(seq), "/attach 42"); -} - -#[test] -fn synthetic_ui_command_is_identified_for_hidden_echo_path() { - let mut msg = crate::channels::traits::ChannelMessage { - id: "synthetic".to_string(), - sender: SYNTHETIC_UI_COMMAND_SENDER.to_string(), - reply_target: "user".to_string(), - content: "/attach 42".to_string(), - channel: "terminal".to_string(), - timestamp: 0, - thread_ts: None, - chat_kind: crate::channels::traits::ChatKind::Dm, - chat_title: None, - sender_display: None, - mentioned_uuids: vec![], - mentioned: false, - is_group_hint: false, - sender_is_bot: false, - }; - - assert!(is_synthetic_ui_command(&msg)); - - msg.sender = "user".to_string(); - assert!(!is_synthetic_ui_command(&msg)); -} - -fn input_msg(content: &str) -> crate::channels::traits::ChannelMessage { - crate::channels::traits::ChannelMessage { - id: uuid::Uuid::new_v4().to_string(), - sender: "user".to_string(), - reply_target: "user".to_string(), - content: content.to_string(), - channel: "terminal".to_string(), - timestamp: 0, - thread_ts: None, - chat_kind: crate::channels::traits::ChatKind::Dm, - chat_title: None, - sender_display: None, - mentioned_uuids: vec![], - mentioned: false, - is_group_hint: false, - sender_is_bot: false, - } -} - -#[test] -fn priority_input_prefix_is_stripped_for_execution() { - let (priority, content) = input_priority_from_text(" /now inspect queue "); - assert_eq!(priority, InputQueuePriority::Priority); - assert_eq!(content, "inspect queue"); - - let (priority, content) = input_priority_from_text("!! urgent"); - assert_eq!(priority, InputQueuePriority::Priority); - assert_eq!(content, "urgent"); -} - -#[test] -fn active_turn_enqueue_reports_priority_and_strips_prefix() { - let mut backlog = std::collections::VecDeque::new(); - - let priority = enqueue_input_message_and_return_priority(&mut backlog, input_msg("/now inspect status")); - - assert_eq!(priority, InputQueuePriority::Priority); - let msg = pop_next_queued_input_message(&mut backlog) - .map(|queued| queued.msg) - .expect("queued priority message"); - assert_eq!(msg.content, "inspect status"); -} - -#[test] -fn input_backlog_status_counts_priority_messages() { - let mut backlog = std::collections::VecDeque::new(); - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("normal one"), 3); - enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("/priority urgent two"), 3); - enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("normal three"), 3); - - // the production status source: the scheduler the queue mirrors into - let status = scheduler.status().main_queue_status(); - - assert_eq!(status.queued, 3); - assert_eq!(status.priority, 1); -} - -#[test] -fn scheduler_mirror_projects_same_queue_status_as_backlog() { - let mut backlog = std::collections::VecDeque::new(); - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - - enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("normal one"), 5); - enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("/priority urgent two"), 5); - - assert_eq!(backlog.len(), scheduler.status().main_queue_status().queued); - assert_eq!(scheduler.status().main_queue_status().queued, 2); - assert_eq!(scheduler.status().main_queue_status().priority, 1); -} - -#[test] -fn scheduler_mirror_does_not_change_priority_pop_order() { - let mut backlog = std::collections::VecDeque::new(); - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - - enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("normal one"), 7); - enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("/priority urgent two"), 7); - enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("normal three"), 7); - - let first = pop_next_input_task_with_scheduler(&mut backlog, &mut scheduler) - .map(|task| task.msg) - .expect("priority first"); - let second = pop_next_input_task_with_scheduler(&mut backlog, &mut scheduler) - .map(|task| task.msg) - .expect("normal one second"); - let third = pop_next_input_task_with_scheduler(&mut backlog, &mut scheduler) - .map(|task| task.msg) - .expect("normal three third"); - - assert_eq!(first.content, "urgent two"); - assert_eq!(second.content, "normal one"); - assert_eq!(third.content, "normal three"); - assert_eq!( - scheduler.status().main_queue_status(), - crate::chat::action::MainQueueStatus::default() - ); -} - -#[test] -fn dequeued_input_task_id_is_reused_for_provider_start() { - let mut backlog = std::collections::VecDeque::new(); - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - - enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("normal provider turn"), 7); - let expected_id = backlog - .front() - .and_then(|queued| queued.turn_task_id) - .expect("queued task id"); - - let dequeued = pop_next_input_task_with_scheduler(&mut backlog, &mut scheduler).expect("dequeued input"); - - assert_eq!(dequeued.turn_task_id, Some(expected_id)); - assert_eq!( - scheduler.task(expected_id).unwrap().state, - crate::chat::turn_scheduler::TurnTaskState::Dispatched - ); - assert_eq!( - scheduler.status().main_queue_status(), - crate::chat::action::MainQueueStatus::default() - ); - - let provider_id = start_provider_turn_task(&mut scheduler, dequeued.turn_task_id, &dequeued.msg.content, 7) - .expect("provider task id"); - - assert_eq!(provider_id, expected_id); - assert_eq!( - scheduler.task(provider_id).unwrap().state, - crate::chat::turn_scheduler::TurnTaskState::Running - ); -} - -#[test] -fn queue_report_summarizes_backlog_with_preview() { - let mut backlog = std::collections::VecDeque::new(); - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("normal one"), 3); - enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("/priority urgent two"), 3); - let running = scheduler.enqueue("running turn", crate::chat::turn_scheduler::TurnPriority::Normal, 3); - scheduler.start_task(running).expect("running turn starts"); - - let report = format_input_backlog_report(&backlog, &scheduler, 8); - - assert!( - report.contains("Main queue: 2 queued (1 priority), 1 running."), - "{report}" - ); - assert!(report.contains("1. [normal] normal one"), "{report}"); - assert!(report.contains("2. [priority] urgent two"), "{report}"); -} - -#[tokio::test] -async fn active_turn_queue_command_is_handled_without_enqueue() { - let mut backlog = std::collections::VecDeque::new(); - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("normal one"), 3); - let running = scheduler.enqueue("active turn", crate::chat::turn_scheduler::TurnPriority::Normal, 3); - scheduler.start_task(running).expect("active turn starts"); - let msg = input_msg("/now /queue"); - let chat_session = session::ChatSession::new("p", "m"); - let provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - let mut chat_sessions = - crate::chat::sessions::ChatSessionsHandle::new(std::sync::Arc::new(tokio::sync::RwLock::new(Vec::new()))); - let session_rings = std::collections::HashMap::new(); - let mut reaped_log_archive = ReapedSessionLogArchive::default(); - let reap_policy = crate::chat::sessions::runtime::ReapPolicy::default(); - let tools_registry: Vec> = Vec::new(); - let daemon_config = Config::default(); - let (daemon_dispatcher, _daemon_action_rx) = dispatcher::ChatDispatcher::new(); - let daemon_control = DaemonControl { - config: &daemon_config, - dispatcher: &daemon_dispatcher, - redraw_tx: None, - }; - - let output = active_turn_local_command_output( - &msg, - &backlog, - &scheduler, - &chat_session, - &provider_turn_workers, - &mut chat_sessions, - &session_rings, - &mut reaped_log_archive, - &reap_policy, - &tools_registry, - daemon_control, - ) - .await - .expect("queue command output"); - - assert!( - output.contains("Main queue: 1 queued (0 priority), 1 running."), - "{output}" - ); - assert_eq!(backlog.len(), 1, "read-only queue command must not mutate backlog"); -} - -#[tokio::test] -async fn active_turn_cost_command_is_handled_without_enqueue() { - let mut backlog = std::collections::VecDeque::new(); - enqueue_input_message(&mut backlog, input_msg("normal one")); - let scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let msg = input_msg("/now /cost"); - let chat_session = session::ChatSession::new("p", "m"); - let provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - let mut chat_sessions = - crate::chat::sessions::ChatSessionsHandle::new(std::sync::Arc::new(tokio::sync::RwLock::new(Vec::new()))); - let session_rings = std::collections::HashMap::new(); - let mut reaped_log_archive = ReapedSessionLogArchive::default(); - let reap_policy = crate::chat::sessions::runtime::ReapPolicy::default(); - let tools_registry: Vec> = Vec::new(); - let daemon_config = Config::default(); - let (daemon_dispatcher, _daemon_action_rx) = dispatcher::ChatDispatcher::new(); - let daemon_control = DaemonControl { - config: &daemon_config, - dispatcher: &daemon_dispatcher, - redraw_tx: None, - }; - - let output = active_turn_local_command_output( - &msg, - &backlog, - &scheduler, - &chat_session, - &provider_turn_workers, - &mut chat_sessions, - &session_rings, - &mut reaped_log_archive, - &reap_policy, - &tools_registry, - daemon_control, - ) - .await - .expect("cost command output"); - - assert!(output.contains("Session cost:"), "{output}"); - assert!(output.contains("Turns:"), "{output}"); - assert_eq!(backlog.len(), 1, "read-only cost command must not mutate backlog"); -} - -#[tokio::test] -async fn active_turn_workers_command_is_handled_without_enqueue() { - let mut backlog = std::collections::VecDeque::new(); - enqueue_input_message(&mut backlog, input_msg("normal one")); - let msg = input_msg("/now /workers"); - let chat_session = session::ChatSession::new("p", "m"); - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let task_id = scheduler.enqueue("long worker", crate::chat::turn_scheduler::TurnPriority::Normal, 3); - scheduler.start_task(task_id).expect("task starts"); - let mut provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - provider_turn_workers - .start_from_task( - scheduler.task(task_id).expect("task snapshot"), - crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited, - ) - .expect("worker starts"); - let mut chat_sessions = - crate::chat::sessions::ChatSessionsHandle::new(std::sync::Arc::new(tokio::sync::RwLock::new(Vec::new()))); - let session_rings = std::collections::HashMap::new(); - let mut reaped_log_archive = ReapedSessionLogArchive::default(); - let reap_policy = crate::chat::sessions::runtime::ReapPolicy::default(); - let tools_registry: Vec> = Vec::new(); - let daemon_config = Config::default(); - let (daemon_dispatcher, _daemon_action_rx) = dispatcher::ChatDispatcher::new(); - let daemon_control = DaemonControl { - config: &daemon_config, - dispatcher: &daemon_dispatcher, - redraw_tx: None, - }; - - let output = active_turn_local_command_output( - &msg, - &backlog, - &scheduler, - &chat_session, - &provider_turn_workers, - &mut chat_sessions, - &session_rings, - &mut reaped_log_archive, - &reap_policy, - &tools_registry, - daemon_control, - ) - .await - .expect("workers command output"); - - assert!(output.contains("Main provider workers: 1 running"), "{output}"); - assert!(output.contains("w#1 task="), "{output}"); - assert!(output.contains("kind=foreground_awaited"), "{output}"); - assert!(output.contains("state=running"), "{output}"); - assert_eq!(backlog.len(), 1, "read-only workers command must not mutate backlog"); -} - -#[test] -fn workers_cancel_command_parser_accepts_worker_sequence_forms() { - assert_eq!( - parse_workers_cancel_command("/workers cancel w#7"), - ProviderWorkerCancelCommand::Cancel { sequence: 7 } - ); - assert_eq!( - parse_workers_cancel_command("/workers stop #8"), - ProviderWorkerCancelCommand::Cancel { sequence: 8 } - ); - assert_eq!( - parse_workers_cancel_command("/workers cancel 9"), - ProviderWorkerCancelCommand::Cancel { sequence: 9 } - ); - assert!(matches!( - parse_workers_cancel_command("/workers cancel nope"), - ProviderWorkerCancelCommand::Invalid(_) - )); - assert!(matches!( - parse_workers_cancel_command("/workers status"), - ProviderWorkerCancelCommand::NotCancel - )); -} - -#[tokio::test] -async fn active_turn_workers_cancel_command_marks_current_worker_cancelling_without_enqueue() { - let msg = input_msg("/now /workers cancel w#1"); - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let task_id = scheduler.enqueue("long worker", crate::chat::turn_scheduler::TurnPriority::Normal, 3); - scheduler.start_task(task_id).expect("task starts"); - let mut provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - provider_turn_workers - .start_from_task( - scheduler.task(task_id).expect("task snapshot"), - crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited, - ) - .expect("worker starts"); - - let (output, signal_cancel) = - active_turn_workers_cancel_output(&msg, &mut scheduler, &mut provider_turn_workers, Some(task_id)) - .expect("workers cancel output"); - - assert_eq!( - signal_cancel, - Some(ProviderWorkerCancelSignal::CancelRequested), - "current foreground worker should signal the active turn" - ); - assert!( - output.contains("Requested cancellation for provider worker w#1"), - "{output}" - ); - assert!(output.contains("state=cancelling"), "{output}"); - assert_eq!( - scheduler.task(task_id).unwrap().state, - crate::chat::turn_scheduler::TurnTaskState::Cancelling - ); - assert_eq!( - provider_turn_workers.worker(task_id).unwrap().state, - crate::chat::turn_worker::ProviderTurnWorkerState::Cancelling - ); -} - -#[tokio::test] -async fn workers_cancel_command_targets_detached_worker_without_cancelling_peer() { - let msg = input_msg("/workers cancel w#2"); - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let first = scheduler.enqueue("first detached", crate::chat::turn_scheduler::TurnPriority::Normal, 3); - let second = scheduler.enqueue("second detached", crate::chat::turn_scheduler::TurnPriority::Normal, 3); - scheduler.start_task(first).expect("first task starts"); - scheduler.start_task(second).expect("second task starts"); - let mut provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - provider_turn_workers - .start_from_task( - scheduler.task(first).expect("first task snapshot"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("first worker starts"); - provider_turn_workers - .start_from_task( - scheduler.task(second).expect("second task snapshot"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("second worker starts"); - - let (output, signal_cancel) = - active_turn_workers_cancel_output(&msg, &mut scheduler, &mut provider_turn_workers, Some(first)) - .expect("workers cancel output"); - - assert!( - output.contains("Requested cancellation for provider worker w#2"), - "{output}" - ); - assert!(output.contains("kind=detached"), "{output}"); - assert_eq!( - signal_cancel, - Some(ProviderWorkerCancelSignal::CancelProviderTurn { task_id: second }), - "detached worker cancellation must target the requested task id" - ); - assert_eq!( - scheduler.task(first).expect("first task").state, - crate::chat::turn_scheduler::TurnTaskState::Running, - "peer detached task must stay running" - ); - assert_eq!( - scheduler.task(second).expect("second task").state, - crate::chat::turn_scheduler::TurnTaskState::Cancelling, - "requested detached task should enter cancelling" - ); - assert_eq!( - provider_turn_workers.worker(first).expect("first worker").state, - crate::chat::turn_worker::ProviderTurnWorkerState::Running, - "peer detached worker must stay running" - ); - assert_eq!( - provider_turn_workers.worker(second).expect("second worker").state, - crate::chat::turn_worker::ProviderTurnWorkerState::Cancelling, - "requested detached worker should enter cancelling" - ); -} - -#[test] -fn workers_cancel_command_targets_detached_worker_from_outer_loop() { - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let first = scheduler.enqueue("first detached", crate::chat::turn_scheduler::TurnPriority::Normal, 3); - let second = scheduler.enqueue("second detached", crate::chat::turn_scheduler::TurnPriority::Normal, 3); - scheduler.start_task(first).expect("first task starts"); - scheduler.start_task(second).expect("second task starts"); - let mut provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - provider_turn_workers - .start_from_task( - scheduler.task(first).expect("first task snapshot"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("first worker starts"); - provider_turn_workers - .start_from_task( - scheduler.task(second).expect("second task snapshot"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("second worker starts"); - - let (output, signal_cancel) = provider_workers_cancel_output_for_input( - &input_msg("/workers cancel w#2"), - "/workers cancel w#2", - &mut scheduler, - &mut provider_turn_workers, - None, - ) - .expect("workers cancel output"); - - assert!( - output.contains("Requested cancellation for provider worker w#2"), - "{output}" - ); - assert_eq!( - signal_cancel, - Some(ProviderWorkerCancelSignal::CancelProviderTurn { task_id: second }), - "outer-loop worker cancel must target the requested detached task" - ); - assert_eq!( - scheduler.task(first).expect("first task").state, - crate::chat::turn_scheduler::TurnTaskState::Running, - "peer detached task must stay running" - ); - assert_eq!( - scheduler.task(second).expect("second task").state, - crate::chat::turn_scheduler::TurnTaskState::Cancelling, - "requested detached task should enter cancelling" - ); -} - -#[tokio::test] -async fn p4a_active_turn_event_pump_preserves_cancel_local_and_enqueue_order() { - let first_msg = input_msg("/workers cancel w#1"); - let (tx, mut input_rx) = mpsc::channel(4); - tx.send(input_msg("/queue")).await.expect("send queue command"); - tx.send(input_msg("follow up turn")).await.expect("send follow-up turn"); - drop(tx); - let mut outputs = Vec::::new(); - let mut emit = |text: &str| outputs.push(text.to_string()); - let mut backlog = std::collections::VecDeque::new(); - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let task_id = scheduler.enqueue( - "active provider turn", - crate::chat::turn_scheduler::TurnPriority::Normal, - 3, - ); - scheduler.start_task(task_id).expect("task starts"); - let mut provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - provider_turn_workers - .start_from_task( - scheduler.task(task_id).expect("task snapshot"), - crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited, - ) - .expect("worker starts"); - let (chat_dispatcher, _action_rx) = dispatcher::ChatDispatcher::new(); - let chat_session = session::ChatSession::new("p", "m"); - let mut chat_sessions = - crate::chat::sessions::ChatSessionsHandle::new(std::sync::Arc::new(tokio::sync::RwLock::new(Vec::new()))); - let session_rings = std::collections::HashMap::new(); - let mut reaped_log_archive = ReapedSessionLogArchive::default(); - let reap_policy = crate::chat::sessions::runtime::ReapPolicy::default(); - let tools_registry: Vec> = Vec::new(); - let daemon_config = Config::default(); - let (daemon_dispatcher, _daemon_action_rx) = dispatcher::ChatDispatcher::new(); - let daemon_control = DaemonControl { - config: &daemon_config, - dispatcher: &daemon_dispatcher, - redraw_tx: None, - }; - - process_active_turn_input_batch( - first_msg, - &mut emit, - &mut input_rx, - &mut backlog, - &mut scheduler, - &mut provider_turn_workers, - Some(task_id), - &chat_dispatcher, - &chat_session, - &mut chat_sessions, - &session_rings, - &mut reaped_log_archive, - &reap_policy, - &tools_registry, - daemon_control, - ) - .await; - - assert_eq!(outputs.len(), 2, "cancel and /queue should emit local output"); - assert!( - outputs[0].contains("Requested cancellation for provider worker w#1"), - "{}", - outputs[0] - ); - assert!( - outputs[1].contains("Main queue: 0 queued (0 priority), 0 running."), - "{}", - outputs[1] - ); - assert_eq!(backlog.len(), 1, "ordinary input after local commands remains queued"); - assert_eq!(backlog.front().expect("queued follow-up").msg.content, "follow up turn"); - assert_eq!( - scheduler.task(task_id).unwrap().state, - crate::chat::turn_scheduler::TurnTaskState::Cancelling - ); - assert_eq!(scheduler.status().main_queue_status().queued, 1); -} - -/// Build the input message a daemon assignment arrives as. -fn assigned_msg(id: &str, task: &str, disposition: &str) -> crate::channels::traits::ChannelMessage { - let pulled = crate::runtime::tasks_cli::PulledAssignment { - assignment_id: id.to_string(), - session_id: "sess".to_string(), - task: task.to_string(), - disposition: disposition.to_string(), - deliveries: 1, - created_at_unix_ms: 0, - work_id: "w1".to_string(), - origin_channel: "wacli".to_string(), - origin_ref: Some("3d1a4f5b".to_string()), - }; - crate::chat::sessions::assignment::assignment_message( - &pulled, - crate::chat::sessions::assignment::Disposition::from_wire(disposition), - ) -} - -/// Feed one assignment into a chat with a turn in flight, and report what -/// the backlog and the running task look like afterwards. -async fn dispatch_assignment_during_a_turn( - disposition: &str, -) -> ( - Vec<(InputQueuePriority, String)>, - crate::chat::turn_scheduler::TurnTaskState, -) { - let msg = assigned_msg("assign-1", "count the crates", disposition); - let (tx, mut input_rx) = mpsc::channel::(4); - drop(tx); - // The output sink is read back: an assignment must never emit a local - // command answer, which is what it would mean for it to be handled as - // one instead of run as a turn. - let mut outputs = Vec::::new(); - let mut emit = |text: &str| outputs.push(text.to_string()); - let mut backlog = std::collections::VecDeque::new(); - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let task_id = scheduler.enqueue( - "active provider turn", - crate::chat::turn_scheduler::TurnPriority::Normal, - 3, - ); - scheduler.start_task(task_id).expect("task starts"); - let mut provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - provider_turn_workers - .start_from_task( - scheduler.task(task_id).expect("task snapshot"), - crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited, - ) - .expect("worker starts"); - let (chat_dispatcher, _action_rx) = dispatcher::ChatDispatcher::new(); - let chat_session = session::ChatSession::new("p", "m"); - let mut chat_sessions = - crate::chat::sessions::ChatSessionsHandle::new(std::sync::Arc::new(tokio::sync::RwLock::new(Vec::new()))); - let session_rings = std::collections::HashMap::new(); - let mut reaped_log_archive = ReapedSessionLogArchive::default(); - let reap_policy = crate::chat::sessions::runtime::ReapPolicy::default(); - let tools_registry: Vec> = Vec::new(); - let daemon_config = Config::default(); - let (daemon_dispatcher, _daemon_action_rx) = dispatcher::ChatDispatcher::new(); - let daemon_control = DaemonControl { - config: &daemon_config, - dispatcher: &daemon_dispatcher, - redraw_tx: None, - }; - - process_active_turn_input_batch( - msg, - &mut emit, - &mut input_rx, - &mut backlog, - &mut scheduler, - &mut provider_turn_workers, - Some(task_id), - &chat_dispatcher, - &chat_session, - &mut chat_sessions, - &session_rings, - &mut reaped_log_archive, - &reap_policy, - &tools_registry, - daemon_control, - ) - .await; - - assert!( - outputs.is_empty(), - "an assignment must be run as a turn, not answered as a local command: {outputs:?}" - ); - let queued = backlog - .iter() - .map(|entry| (entry.priority, entry.msg.content.clone())) - .collect::>(); - let state = scheduler.task(task_id).expect("task snapshot").state; - (queued, state) -} - -/// The three dispositions differ in exactly two observable ways: where the -/// work lands in the queue, and whether the turn in flight survives. -#[tokio::test] -async fn each_assignment_disposition_reaches_the_path_it_names() { - let (queued, state) = dispatch_assignment_during_a_turn("queue").await; - assert_eq!(queued.len(), 1); - assert_eq!(queued[0].0, InputQueuePriority::Normal, "queue must not jump the queue"); - assert_eq!( - queued[0].1, "count the crates", - "the model must see the task, not a prefix" - ); - assert_eq!( - state, - crate::chat::turn_scheduler::TurnTaskState::Running, - "queue must leave the turn in flight alone" - ); - - let (queued, state) = dispatch_assignment_during_a_turn("steer").await; - assert_eq!(queued.len(), 1); - assert_eq!( - queued[0].0, - InputQueuePriority::Priority, - "steer must go in front of the backlog" - ); - assert_eq!(queued[0].1, "count the crates"); - assert_eq!( - state, - crate::chat::turn_scheduler::TurnTaskState::Running, - "steer inserts into the turn in flight; it must not destroy it" - ); - - let (queued, state) = dispatch_assignment_during_a_turn("interrupt").await; - assert_eq!(queued.len(), 1); - assert_eq!(queued[0].0, InputQueuePriority::Priority); - assert_eq!(queued[0].1, "count the crates"); - assert_eq!( - state, - crate::chat::turn_scheduler::TurnTaskState::Cancelling, - "interrupt must end the turn in flight before the assignment runs" - ); -} - -/// A word this chat cannot read is never permission to destroy a turn. -#[tokio::test] -async fn an_unknown_disposition_never_ends_the_turn_in_flight() { - let (queued, state) = dispatch_assignment_during_a_turn("obliterate").await; - assert_eq!(queued.len(), 1); - assert_eq!(queued[0].0, InputQueuePriority::Normal); - assert_eq!( - state, - crate::chat::turn_scheduler::TurnTaskState::Running, - "an unrecognised disposition degrades to queue, never to interrupt" - ); -} - -/// Ordinary typed input must not acquire assignment behaviour. -#[tokio::test] -async fn ordinary_input_during_a_turn_still_only_queues() { - let msg = input_msg("just a message"); - assert!(crate::chat::sessions::assignment::delivered(&msg).is_none()); -} - -#[tokio::test] -async fn p4a_active_turn_quit_is_queued_for_delayed_exit() { - let mut outputs = Vec::::new(); - let mut emit = |text: &str| outputs.push(text.to_string()); - let mut backlog = std::collections::VecDeque::new(); - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let task_id = scheduler.enqueue( - "active provider turn", - crate::chat::turn_scheduler::TurnPriority::Normal, - 3, - ); - scheduler.start_task(task_id).expect("task starts"); - let mut provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - provider_turn_workers - .start_from_task( - scheduler.task(task_id).expect("task snapshot"), - crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited, - ) - .expect("worker starts"); - let (chat_dispatcher, _action_rx) = dispatcher::ChatDispatcher::new(); - let chat_session = session::ChatSession::new("p", "m"); - let mut chat_sessions = - crate::chat::sessions::ChatSessionsHandle::new(std::sync::Arc::new(tokio::sync::RwLock::new(Vec::new()))); - let session_rings = std::collections::HashMap::new(); - let mut reaped_log_archive = ReapedSessionLogArchive::default(); - let reap_policy = crate::chat::sessions::runtime::ReapPolicy::default(); - let tools_registry: Vec> = Vec::new(); - let daemon_config = Config::default(); - let (daemon_dispatcher, _daemon_action_rx) = dispatcher::ChatDispatcher::new(); - let daemon_control = DaemonControl { - config: &daemon_config, - dispatcher: &daemon_dispatcher, - redraw_tx: None, - }; - - process_active_turn_input_message( - input_msg("/exit"), - &mut emit, - &mut backlog, - &mut scheduler, - &mut provider_turn_workers, - Some(task_id), - &chat_dispatcher, - &chat_session, - &mut chat_sessions, - &session_rings, - &mut reaped_log_archive, - &reap_policy, - &tools_registry, - daemon_control, - ) - .await; - - assert!(outputs.is_empty(), "/exit during an active turn is not a local command"); - assert_eq!(backlog.len(), 1, "/exit should wait behind the active turn"); - assert_eq!(backlog.front().expect("queued exit").msg.content, "/exit"); - assert_eq!(scheduler.status().main_queue_status().queued, 1); - assert_eq!( - scheduler.task(task_id).unwrap().state, - crate::chat::turn_scheduler::TurnTaskState::Running, - "delayed exit must not cancel or complete the active provider turn" - ); -} - -#[test] -fn persistence_dependent_commands_cover_terminal_session_contract() { - for command in [ - "/exit", - "/quit", - "/apply", - "/cost", - "/export", - "/new", - "/clear", - "/resume", - "/resume last", - "/branch 1", - "/rewind 0", - "/priority /cost", - ] { - assert!(is_persistence_dependent_command(command), "{command}"); - } - for command in ["hello", "/help", "/workers", "/queue status"] { - assert!(!is_persistence_dependent_command(command), "{command}"); - } -} - -#[test] -fn new_session_has_fresh_identity_and_empty_session_scoped_ledgers() { - let first = fresh_chat_session("provider-a", "model-a", commands::ChatMode::Plan); - let second = fresh_chat_session("provider-a", "model-a", commands::ChatMode::Plan); - - assert_ne!(first.id, second.id); - assert!(first.title.is_empty(), "expected an empty value"); - assert!(first.turns.is_empty()); - assert!(first.token_usage_records.is_empty(), "expected an empty value"); - assert!(first.background_sessions.is_empty(), "expected an empty value"); - assert_eq!(first.provider, "provider-a"); - assert_eq!(first.model, "model-a"); - assert_eq!(first.mode, commands::ChatMode::Plan); -} - -#[cfg(feature = "terminal-tui")] -#[test] -fn p4a_input_close_keeps_event_pump_alive_until_pending_turn_finishes() { - assert!( - should_continue_event_pump_after_input_closed(1), - "closed input should not terminate the event pump while a detached Redux turn is pending" - ); - assert!( - !should_continue_event_pump_after_input_closed(0), - "with no pending Redux turn, closed input can end the outer loop" - ); -} - -#[cfg(feature = "terminal-tui")] -#[test] -fn p4a_deferred_resume_waits_for_queued_visible_input_from_current_session() { - let mut backlog = std::collections::VecDeque::new(); - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - let mut deferred_resume = std::collections::VecDeque::from(["session-b".to_string()]); - let session_a_history_len = 4; - - enqueue_input_message_with_scheduler( - &mut backlog, - &mut scheduler, - input_msg("queued for session A"), - session_a_history_len, - ); - - assert!( - !should_drain_deferred_resume_after_visible_inputs(0, &backlog, &workers), - "deferred resume must not run before queued visible input is dequeued" - ); - assert_eq!( - deferred_resume.front().map(String::as_str), - Some("session-b"), - "resume request remains deferred while session-A input is pending" - ); - - let next = pop_next_visible_input_task_with_scheduler( - &mut backlog, - &mut scheduler, - &workers, - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - 1, - ) - .expect("queued input"); - assert_eq!(next.msg.content, "queued for session A"); - let task_id = next.turn_task_id.expect("scheduler task id"); - let task = scheduler.task(task_id).expect("queued task snapshot"); - assert_eq!( - task.history_base_len, session_a_history_len, - "queued input keeps the pre-resume session-A history boundary" - ); - assert_eq!( - task.state, - crate::chat::turn_scheduler::TurnTaskState::Dispatched, - "queued input is dispatched before deferred resume can drain" - ); - - assert!(should_drain_deferred_resume_after_visible_inputs(0, &backlog, &workers)); - assert_eq!(deferred_resume.pop_front().as_deref(), Some("session-b")); -} - -#[test] -fn workers_report_lists_only_active_worker_rows() { - let status = crate::chat::action::ProviderWorkerStatus { - running: 1, - cancelling: 0, - awaiting_commit: 0, - finalized_payloads: 1, - finalized_total_tokens: 1_250, - oldest_started_at_ms: Some(chrono::Utc::now().timestamp_millis().saturating_sub(1_000)), - rows: vec![ - crate::chat::action::ProviderWorkerStatusRow { - task_id: 1, - sequence: 1, - kind: crate::chat::action::ProviderWorkerRowKind::ForegroundAwaited, - state: crate::chat::action::ProviderWorkerRowState::Running, - started_at_ms: chrono::Utc::now().timestamp_millis().saturating_sub(1_000), - finalized_total_tokens: None, - completion_ready: false, - recent_tool_call: None, - }, - crate::chat::action::ProviderWorkerStatusRow { - task_id: 2, - sequence: 2, - kind: crate::chat::action::ProviderWorkerRowKind::Detached, - state: crate::chat::action::ProviderWorkerRowState::Committed, - started_at_ms: chrono::Utc::now().timestamp_millis().saturating_sub(9_000), - finalized_total_tokens: Some(1_250), - completion_ready: true, - recent_tool_call: None, - }, - ], - }; - - let report = format_provider_worker_report(&status); - - assert!( - report.contains("1 finalized payloads, 1.2k finalized tokens"), - "report should retain finalized aggregate: {report}" - ); - assert!(report.contains("- w#1 task=1"), "active row should be listed: {report}"); - assert!( - report.contains("completion=pending"), - "active row should expose completion readiness: {report}" - ); - assert!( - !report.contains("- w#2 task=2"), - "completed row should not stay in the active worker list: {report}" - ); -} - -/// Backpressure contract for the provider-turn lifecycle channel. -/// -/// The channel is bounded, so the guarantee under load is: a producer that -/// finds it full is *slowed down* (its `send` parks until the chat loop -/// drains) rather than dropping events or panicking, and every event -/// eventually arrives in order. -#[cfg(feature = "terminal-tui")] -#[tokio::test] -async fn provider_turn_lifecycle_channel_backpressures_instead_of_dropping() { - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let task_id = scheduler.enqueue("turn", crate::chat::turn_scheduler::TurnPriority::Normal, 1); - - let (tx, mut rx) = - mpsc::channel::(PROVIDER_TURN_LIFECYCLE_CHANNEL_CAPACITY); - - // Fill the queue exactly to capacity. - for lease_id in 0..PROVIDER_TURN_LIFECYCLE_CHANNEL_CAPACITY as u64 { - tx.try_send(dispatcher::ProviderTurnLifecycleEvent::Started { task_id, lease_id }) - .expect("channel accepts events up to its capacity"); - } - assert!( - tx.try_send(dispatcher::ProviderTurnLifecycleEvent::Started { - task_id, - lease_id: u64::MAX, - }) - .is_err(), - "channel must be bounded at PROVIDER_TURN_LIFECYCLE_CHANNEL_CAPACITY" - ); - - // The overflow send parks; it neither resolves nor discards the event. - let overflow = tx.send(dispatcher::ProviderTurnLifecycleEvent::Exited { - task_id, - lease_id: u64::MAX, - }); - tokio::pin!(overflow); - assert!( - tokio::time::timeout(std::time::Duration::from_millis(100), &mut overflow) - .await - .is_err(), - "a full queue must park the producer rather than complete the send" - ); - - // Draining frees a permit, which wakes the parked producer. - let first = rx.recv().await.expect("queued event is delivered"); - assert!(matches!( - first, - dispatcher::ProviderTurnLifecycleEvent::Started { lease_id: 0, .. } - )); - tokio::time::timeout(std::time::Duration::from_secs(5), overflow) - .await - .expect("parked producer resumes once the consumer drains") - .expect("receiver is still alive"); - - // Nothing was lost or reordered: the remaining fillers arrive in order, - // followed by the event that had been waiting on backpressure. - for expected_lease in 1..PROVIDER_TURN_LIFECYCLE_CHANNEL_CAPACITY as u64 { - match rx.recv().await.expect("queued event is delivered") { - dispatcher::ProviderTurnLifecycleEvent::Started { lease_id, .. } => { - assert_eq!(lease_id, expected_lease); - } - other => panic!("unexpected event while draining: {other:?}"), - } - } - match rx.recv().await.expect("backpressured event is delivered") { - dispatcher::ProviderTurnLifecycleEvent::Exited { lease_id, .. } => { - assert_eq!(lease_id, u64::MAX); - } - other => panic!("unexpected trailing event: {other:?}"), - } -} - -#[cfg(feature = "terminal-tui")] -#[test] -fn non_current_provider_completion_is_retained_and_marks_ready() { - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let first = scheduler.enqueue("first", crate::chat::turn_scheduler::TurnPriority::Normal, 1); - let second = scheduler.enqueue("second", crate::chat::turn_scheduler::TurnPriority::Normal, 1); - scheduler.start_task(first).expect("first starts"); - scheduler.start_task(second).expect("second starts"); - - let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - workers - .start_from_task( - scheduler.task(first).expect("first task"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("first worker starts"); - workers - .start_from_task( - scheduler.task(second).expect("second task"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("second worker starts"); - workers - .record_execution_started(second, 42) - .expect("second worker execution starts"); - - let (_tx, mut lifecycle_rx) = tokio::sync::mpsc::channel(PROVIDER_TURN_LIFECYCLE_CHANNEL_CAPACITY); - let mut lifecycle_open = true; - let mut pending = std::collections::HashMap::new(); - let completion = ProviderTurnCompletionEvent { - task_id: second, - outcome: Some(dispatcher::TurnOutcomeKind::Completed { - final_text: "second done".to_string(), - reasoning: String::new(), - }), - usage: crate::llm::route_decision::TokenUsage { - total_tokens: Some(42), - ..Default::default() - }, - }; - - let route = route_provider_completion_event( - &mut lifecycle_rx, - &mut lifecycle_open, - &mut workers, - &mut pending, - Some(first), - completion, - ); - - assert!(route.is_none(), "a non-current completion is retained as pending"); - assert!( - pending.contains_key(&second), - "non-current completion should be retained" - ); - let rows = workers.snapshot(); - let second_row = rows - .iter() - .find(|row| row.task_id == second) - .expect("second worker snapshot"); - assert!( - second_row.completion_ready, - "retained completion should still mark the worker completion-ready" - ); - assert!( - !rows - .iter() - .find(|row| row.task_id == first) - .expect("first worker snapshot") - .completion_ready, - "uncompleted worker should remain pending" - ); -} - -#[cfg(feature = "terminal-tui")] -#[test] -fn current_provider_completion_is_routed_without_retaining_pending() { - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let task_id = scheduler.enqueue("current", crate::chat::turn_scheduler::TurnPriority::Normal, 1); - scheduler.start_task(task_id).expect("task starts"); - - let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - workers - .start_from_task( - scheduler.task(task_id).expect("task snapshot"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("worker starts"); - workers - .record_execution_started(task_id, 43) - .expect("worker execution starts"); - - let (_tx, mut lifecycle_rx) = tokio::sync::mpsc::channel(PROVIDER_TURN_LIFECYCLE_CHANNEL_CAPACITY); - let mut lifecycle_open = true; - let mut pending = std::collections::HashMap::new(); - let completion = ProviderTurnCompletionEvent { - task_id, - outcome: Some(dispatcher::TurnOutcomeKind::Completed { - final_text: "current done".to_string(), - reasoning: String::new(), - }), - usage: crate::llm::route_decision::TokenUsage { - total_tokens: Some(43), - ..Default::default() - }, - }; - - let route = route_provider_completion_event( - &mut lifecycle_rx, - &mut lifecycle_open, - &mut workers, - &mut pending, - Some(task_id), - completion, - ); - - let completion = route.expect("current completion must not be retained as pending"); - assert_eq!(completion.task_id, task_id); - assert_eq!(completion.usage.total_tokens, Some(43)); - assert!(pending.is_empty(), "current completion should bypass pending map"); - assert!( - workers - .snapshot() - .into_iter() - .find(|row| row.task_id == task_id) - .expect("worker snapshot") - .completion_ready, - "current completion should still mark the worker completion-ready" - ); -} - -#[cfg(feature = "terminal-tui")] -#[test] -fn p4a_outer_completion_route_retains_event_for_pending_redux_finalizer() { - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let task_id = scheduler.enqueue("redux pending", crate::chat::turn_scheduler::TurnPriority::Normal, 1); - scheduler.start_task(task_id).expect("task starts"); - let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - workers - .start_from_task( - scheduler.task(task_id).expect("task snapshot"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("worker starts"); - workers - .record_execution_started(task_id, 60) - .expect("worker execution starts"); - let (_tx, mut lifecycle_rx) = tokio::sync::mpsc::channel(PROVIDER_TURN_LIFECYCLE_CHANNEL_CAPACITY); - let mut lifecycle_open = true; - let mut pending = std::collections::HashMap::new(); - let (chat_dispatcher, _action_rx) = dispatcher::ChatDispatcher::new(); - let completion = ProviderTurnCompletionEvent { - task_id, - outcome: Some(dispatcher::TurnOutcomeKind::Completed { - final_text: "done".to_string(), - reasoning: String::new(), - }), - usage: crate::llm::route_decision::TokenUsage { - total_tokens: Some(9), - ..Default::default() - }, - }; - - let route = route_provider_completion_event_and_publish( - &mut lifecycle_rx, - &mut lifecycle_open, - &mut workers, - &mut pending, - None, - completion, - &chat_dispatcher, - ); - - assert!(route.is_none(), "a non-current completion is retained as pending"); - let retained = pending.get(&task_id).expect("outer completion retained by task id"); - assert_eq!(retained.usage.total_tokens, Some(9)); - assert!( - workers - .snapshot() - .into_iter() - .find(|row| row.task_id == task_id) - .expect("worker snapshot") - .completion_ready, - "outer route still marks worker completion-ready before finalizer" - ); -} - -#[cfg(feature = "terminal-tui")] -#[test] -fn p4a_completion_event_and_finalizer_chain_commits_ready_turn() { - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let task_id = scheduler.enqueue( - "redux pending finalizer", - crate::chat::turn_scheduler::TurnPriority::Normal, - 1, - ); - scheduler.start_task(task_id).expect("task starts"); - let mut coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); - coordinator - .register_task(scheduler.task(task_id).expect("task snapshot")) - .expect("history task registers"); - let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - workers - .start_from_task( - scheduler.task(task_id).expect("task snapshot"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("worker starts"); - workers - .record_execution_started(task_id, 64) - .expect("worker execution starts"); - let (_tx, mut lifecycle_rx) = tokio::sync::mpsc::channel(PROVIDER_TURN_LIFECYCLE_CHANNEL_CAPACITY); - let mut lifecycle_open = true; - let mut pending = std::collections::HashMap::new(); - let (chat_dispatcher, _action_rx) = dispatcher::ChatDispatcher::new(); - - let route = route_provider_completion_event_and_publish( - &mut lifecycle_rx, - &mut lifecycle_open, - &mut workers, - &mut pending, - None, - ProviderTurnCompletionEvent { - task_id, - outcome: Some(dispatcher::TurnOutcomeKind::Completed { - final_text: "ready finalizer".to_string(), - reasoning: String::new(), - }), - usage: crate::llm::route_decision::TokenUsage { - total_tokens: Some(64), - ..Default::default() - }, - }, - &chat_dispatcher, - ); - assert!(route.is_none(), "a non-current completion is retained as pending"); - - let completion = pending - .remove(&task_id) - .expect("ready completion retained for finalizer"); - let tools: Vec> = Vec::new(); - let plan = provider_turn_terminal_plan_from_completion( - ResolvedProviderTurnCompletion { - outcome: completion.outcome, - usage: completion.usage, - }, - 1, - &tools, - ); - let mut queue = std::collections::VecDeque::new(); - enqueue_provider_turn_finalizer_event(&mut queue, Some(task_id), plan); - - let results = drain_provider_turn_finalizer_events_and_publish( - &mut scheduler, - &mut coordinator, - &mut workers, - &mut queue, - &chat_dispatcher, - ); - - assert_eq!(results.len(), 1); - assert_eq!(results[0].terminal_status, "completed"); - assert!(results[0].finalized); - assert_eq!( - scheduler.task(task_id).unwrap().state, - crate::chat::turn_scheduler::TurnTaskState::Completed - ); - let row = workers - .snapshot() - .into_iter() - .find(|row| row.task_id == task_id) - .expect("worker snapshot retained"); - assert_eq!(row.finalized_total_tokens, Some(64)); - assert!(matches!( - row.state, - crate::chat::turn_worker::ProviderTurnWorkerState::Committed - )); -} - -#[cfg(feature = "terminal-tui")] -#[test] -fn p4b1_ready_signal_is_noop_until_ordered_commit_dispatches_save() { - use crate::chat::action::Action; - use crate::chat::state::{ChatState, Effect}; - use std::sync::Arc; - - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let task_id = scheduler.enqueue("ordered commit", crate::chat::turn_scheduler::TurnPriority::Normal, 0); - scheduler.start_task(task_id).expect("task starts"); - let sequence = scheduler.task(task_id).expect("task snapshot").sequence; - let mut state = ChatState::new(Arc::from("provider"), Arc::from("model"), CancellationToken::new()); - let _ = state.reduce(Action::StartLLMTurn { - provider_turn_task_id: Some(task_id), - provider_turn_sequence: Some(sequence), - draft_id: "draft-p4b1".to_string(), - history: Vec::new(), - compaction_guard_history: None, - compaction_config: None, - cancel: CancellationToken::new(), - turn_spawn_ctx: None, - turn_message_send_ctx: None, - routing_input: None, - turn_binding: None, - }); - - let ready_effects = state.reduce(Action::ProviderTurnReadyForCommit { - draft_id: "draft-p4b1".to_string(), - final_text: "answer".to_string(), - reasoning: "reason".to_string(), - }); - assert!(ready_effects.is_empty(), "ready signal must not emit SaveSession"); - assert!( - state.stream.primary_streaming_draft().is_some(), - "ready signal must leave reducer draft open until ordered commit" - ); - - let (dispatcher, mut rx) = dispatcher::ChatDispatcher::new(); - dispatch_ordered_provider_turn_commit( - &dispatcher, - task_id, - "draft-p4b1", - "question", - "answer", - "reason", - false, - true, - ) - .expect("ordered history dispatch"); - - let user = rx.try_recv().expect("ordered RecordUserTurn action"); - match user { - Action::RecordUserTurn(content) => { - assert_eq!(content, "question"); - let effects = state.reduce(Action::RecordUserTurn(content)); - assert!( - !effects.iter().any(|effect| matches!(effect, Effect::SaveSession(_))), - "RecordUserTurn alone must not save before terminal commit" - ); - } - other => panic!("expected ordered RecordUserTurn, got {other:?}"), - } - - let record = rx.try_recv().expect("ordered RecordAssistantTurn action"); - match record { - Action::RecordAssistantTurn { task_id: seen, content } => { - assert_eq!(seen, Some(task_id)); - assert_eq!(content, "answer"); - let effects = state.reduce(Action::RecordAssistantTurn { task_id: seen, content }); - assert!( - !effects.iter().any(|effect| matches!(effect, Effect::SaveSession(_))), - "RecordAssistantTurn alone must not save before terminal commit" - ); - } - other => panic!("expected ordered RecordAssistantTurn, got {other:?}"), - } - - let terminal = rx.try_recv().expect("ordered StreamCompleted action"); - match terminal { - Action::StreamCompleted { - draft_id, - final_text, - reasoning, - } => { - assert_eq!(draft_id, "draft-p4b1"); - assert_eq!(final_text, "answer"); - assert_eq!(reasoning, "reason"); - let effects = state.reduce(Action::StreamCompleted { - draft_id, - final_text, - reasoning, - }); - assert!( - effects.iter().any(|effect| matches!(effect, Effect::SaveSession(_))), - "SaveSession must be emitted only by ordered StreamCompleted" - ); - } - other => panic!("expected ordered StreamCompleted, got {other:?}"), - } - assert!( - rx.try_recv().is_err(), - "ordered commit helper should emit exactly record + terminal actions" - ); -} - -#[cfg(feature = "terminal-tui")] -#[test] -fn p4b1_failed_and_cancelled_skip_do_not_emit_persistence_actions() { - use crate::chat::action::Action; - - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let failed = scheduler.enqueue("failed", crate::chat::turn_scheduler::TurnPriority::Normal, 0); - let cancelled = scheduler.enqueue("cancelled", crate::chat::turn_scheduler::TurnPriority::Normal, 0); - scheduler.start_task(failed).expect("failed task starts"); - scheduler.start_task(cancelled).expect("cancelled task starts"); - scheduler.request_cancel(cancelled).expect("cancel request accepted"); - let mut coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); - coordinator - .register_task(scheduler.task(failed).expect("failed task snapshot")) - .expect("failed task registers"); - coordinator - .register_task(scheduler.task(cancelled).expect("cancelled task snapshot")) - .expect("cancelled task registers"); - let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - for task_id in [failed, cancelled] { - workers - .start_from_task( - scheduler.task(task_id).expect("task snapshot"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("worker starts"); - workers - .record_execution_started(task_id, 70) - .expect("worker execution starts"); - workers - .record_completion_ready(task_id) - .expect("worker completion ready"); - } - workers - .request_cancel(cancelled) - .expect("worker cancellation requested"); - let mut queue = std::collections::VecDeque::new(); - enqueue_provider_turn_finalizer_event( - &mut queue, - Some(failed), - ProviderTurnTerminalPlan::Failed { - err: "failed".to_string(), - history_commit_len: 0, - summary: "test failed skip".to_string(), - }, - ); - enqueue_provider_turn_finalizer_event( - &mut queue, - Some(cancelled), - ProviderTurnTerminalPlan::Cancelled { - summary: "test cancelled skip", - }, - ); - let (dispatcher, mut rx) = dispatcher::ChatDispatcher::new(); - - let results = drain_provider_turn_finalizer_events_and_publish( - &mut scheduler, - &mut coordinator, - &mut workers, - &mut queue, - &dispatcher, - ); - - assert_eq!(results.len(), 2); - assert_eq!(results[0].terminal_status, "failed"); - assert_eq!(results[1].terminal_status, "cancelled"); - assert!(results.iter().all(|result| result.finalized)); - while let Ok(action) = rx.try_recv() { - assert!( - !matches!( - action, - Action::RecordAssistantTurn { .. } | Action::StreamCompleted { .. } - ), - "skip decisions must not emit assistant/session persistence actions: {action:?}" - ); - } -} - -#[test] -fn provider_turn_visible_admission_blocks_while_provider_worker_active() { - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let running = scheduler.enqueue("running", crate::chat::turn_scheduler::TurnPriority::Normal, 0); - let committed = scheduler.enqueue("committed", crate::chat::turn_scheduler::TurnPriority::Normal, 0); - scheduler.start_task(running).expect("running starts"); - scheduler.start_task(committed).expect("committed starts"); - - let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - assert!( - provider_turn_visible_admission(&workers, crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, 1,) - .can_start_visible - ); - - workers - .start_from_task( - scheduler.task(running).expect("running task"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("running worker starts"); - let admission = - provider_turn_visible_admission(&workers, crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, 1); - assert_eq!(admission.active_workers, 1); - assert!(!admission.can_start_visible); - - workers - .record_execution_started(running, 44) - .expect("running execution starts"); - workers - .record_completion_ready(running) - .expect("running completion ready"); - workers - .record_finalized_payload( - running, - crate::chat::turn_worker::ProviderTurnFinalizedPayload { - history_commit_len: 1, - final_text_chars: 1, - recorded_response_chars: 1, - total_tokens: 1, - prompt_tokens: 0, - completion_tokens: 1, - }, - ) - .expect("running payload finalized"); - workers.record_completed(running).expect("running worker completed"); - let admission = - provider_turn_visible_admission(&workers, crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, 1); - assert_eq!(admission.active_workers, 1); - assert!( - !admission.can_start_visible, - "awaiting commit still owns the visible draft boundary" - ); - - workers - .start_from_task( - scheduler.task(committed).expect("committed task"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("committed worker starts"); - workers - .record_execution_started(committed, 45) - .expect("committed execution starts"); - workers - .record_completion_ready(committed) - .expect("committed completion ready"); - workers - .record_finalized_payload( - committed, - crate::chat::turn_worker::ProviderTurnFinalizedPayload { - history_commit_len: 1, - final_text_chars: 1, - recorded_response_chars: 1, - total_tokens: 1, - prompt_tokens: 0, - completion_tokens: 1, - }, - ) - .expect("committed payload finalized"); - workers.record_completed(committed).expect("committed worker completed"); - let decision = crate::chat::history_commit::HistoryCommitDecision::Commit { - task_id: running, - sequence: scheduler.task(running).expect("running task").sequence, - history_commit_len: 1, - summary: "running committed".to_string(), - }; - workers - .apply_commit_decision(&decision) - .expect("running commit applies"); - let admission = - provider_turn_visible_admission(&workers, crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, 1); - assert_eq!(admission.active_workers, 1); - assert!( - !admission.can_start_visible, - "second awaiting commit worker still blocks" - ); - - let decision = crate::chat::history_commit::HistoryCommitDecision::Commit { - task_id: committed, - sequence: scheduler.task(committed).expect("committed task").sequence, - history_commit_len: 1, - summary: "committed committed".to_string(), - }; - workers - .apply_commit_decision(&decision) - .expect("committed commit applies"); - let admission = - provider_turn_visible_admission(&workers, crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, 1); - assert_eq!(admission.active_workers, 0); - assert!(admission.can_start_visible); -} - -#[test] -fn provider_turn_visible_admission_allows_detached_until_configured_limit() { - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let first = scheduler.enqueue("first", crate::chat::turn_scheduler::TurnPriority::Normal, 0); - let second = scheduler.enqueue("second", crate::chat::turn_scheduler::TurnPriority::Normal, 0); - scheduler.start_task(first).expect("first starts"); - scheduler.start_task(second).expect("second starts"); - - let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - workers - .start_from_task( - scheduler.task(first).expect("first task"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("first worker starts"); - let admission = - provider_turn_visible_admission(&workers, crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, 2); - assert_eq!(admission.detached_active, 1); - assert!(admission.can_start_visible, "one detached turn leaves one N=2 slot"); - - workers - .start_from_task( - scheduler.task(second).expect("second task"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("second worker starts"); - let admission = - provider_turn_visible_admission(&workers, crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, 2); - assert_eq!(admission.detached_active, 2); - assert!( - !admission.can_start_visible, - "two detached turns exhaust configured N=2 admission" - ); -} - -#[test] -fn provider_turn_visible_admission_legacy_foreground_is_exclusive() { - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let legacy = scheduler.enqueue("legacy", crate::chat::turn_scheduler::TurnPriority::Normal, 0); - scheduler.start_task(legacy).expect("legacy starts"); - - let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - workers - .start_from_task( - scheduler.task(legacy).expect("legacy task"), - crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited, - ) - .expect("legacy worker starts"); - - let detached = - provider_turn_visible_admission(&workers, crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, 2); - assert_eq!(detached.foreground_active, 1); - assert!(!detached.can_start_visible, "legacy active blocks detached turns"); - - let foreground = provider_turn_visible_admission( - &workers, - crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited, - 2, - ); - assert!( - !foreground.can_start_visible, - "legacy active blocks another legacy turn" - ); -} - -#[test] -fn visible_input_pop_preserves_queue_while_provider_worker_active() { - let mut backlog = std::collections::VecDeque::new(); - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let active = scheduler.enqueue("active", crate::chat::turn_scheduler::TurnPriority::Normal, 0); - scheduler.start_task(active).expect("active task starts"); - - let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - workers - .start_from_task( - scheduler.task(active).expect("active task"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("active worker starts"); - enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("queued while active"), 7); - let queued_task = backlog - .front() - .and_then(|queued| queued.turn_task_id) - .expect("queued task id"); - - let popped = pop_next_visible_input_task_with_scheduler( - &mut backlog, - &mut scheduler, - &workers, - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - 1, - ); - - assert!( - popped.is_none(), - "active provider worker must hold visible input admission" - ); - assert_eq!(backlog.len(), 1, "queued input must remain queued"); - assert_eq!( - scheduler.task(queued_task).expect("queued task").state, - crate::chat::turn_scheduler::TurnTaskState::Queued, - "blocked visible input must not be marked dispatched" - ); - assert_eq!(scheduler.status().main_queue_status().queued, 1); -} - -#[test] -fn session_reset_commands_wait_for_active_turn_even_when_concurrency_has_capacity() { - for command in ["/new", "/clear"] { - let mut backlog = std::collections::VecDeque::new(); - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let active = scheduler.enqueue("active", crate::chat::turn_scheduler::TurnPriority::Normal, 0); - scheduler.start_task(active).expect("active task starts"); - - let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - workers - .start_from_task( - scheduler.task(active).expect("active task"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("active worker starts"); - enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg(command), 7); - let queued_task = backlog - .front() - .and_then(|queued| queued.turn_task_id) - .expect("queued command task id"); - - let popped = pop_next_visible_input_task_with_scheduler( - &mut backlog, - &mut scheduler, - &workers, - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - 2, - ); - - assert!(popped.is_none(), "{command} must wait for the active turn to persist"); - assert_eq!(backlog.len(), 1, "{command} must remain queued"); - assert_eq!( - scheduler.task(queued_task).expect("queued command task").state, - crate::chat::turn_scheduler::TurnTaskState::Queued, - "{command} must not be dispatched across the session boundary" - ); - } -} - -#[test] -fn visible_input_pop_prefers_priority_when_detached_slot_is_available() { - let mut backlog = std::collections::VecDeque::new(); - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let active = scheduler.enqueue("active", crate::chat::turn_scheduler::TurnPriority::Normal, 0); - scheduler.start_task(active).expect("active task starts"); - - let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - workers - .start_from_task( - scheduler.task(active).expect("active task"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("active worker starts"); - enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("normal queued first"), 7); - enqueue_input_message_with_scheduler( - &mut backlog, - &mut scheduler, - input_msg("/priority urgent queued second"), - 7, - ); - - let popped = pop_next_visible_input_task_with_scheduler( - &mut backlog, - &mut scheduler, - &workers, - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - 2, - ) - .expect("second detached slot should be available"); - - assert_eq!( - popped.msg.content, "urgent queued second", - "priority input must dispatch before older normal input when a visible slot opens" - ); - let popped_task = popped.turn_task_id.expect("popped task id"); - assert_eq!( - scheduler.task(popped_task).expect("priority task").priority, - crate::chat::turn_scheduler::TurnPriority::Priority - ); - assert_eq!( - backlog.front().map(|queued| queued.msg.content.as_str()), - Some("normal queued first"), - "normal input remains queued after priority dispatch" - ); -} - -#[test] -fn post_route_requeue_defers_next_visible_pop_once_under_detached_capacity() { - let mut backlog = std::collections::VecDeque::new(); - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let active = scheduler.enqueue("active detached", crate::chat::turn_scheduler::TurnPriority::Normal, 0); - scheduler.start_task(active).expect("active task starts"); - - let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - workers - .start_from_task( - scheduler.task(active).expect("active task"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("active worker starts"); - enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("legacy fallback"), 7); - let queued_task = backlog - .front() - .and_then(|queued| queued.turn_task_id) - .expect("queued task id"); - - assert!( - provider_turn_visible_admission(&workers, crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, 2,) - .can_start_visible, - "ordinary detached pop admission would otherwise immediately re-pop" - ); - let mut defer_visible_input_pop_once = true; - - assert!( - consume_deferred_visible_input_pop(&mut defer_visible_input_pop_once), - "post-route requeue should force one event-pump wait" - ); - assert_eq!(backlog.len(), 1, "deferred pop leaves requeued input in place"); - assert_eq!( - scheduler.task(queued_task).expect("queued task").state, - crate::chat::turn_scheduler::TurnTaskState::Queued, - "deferred pop must not repeatedly mark the requeued task dispatched" - ); - assert!( - !consume_deferred_visible_input_pop(&mut defer_visible_input_pop_once), - "defer gate is one-shot" - ); - - let popped = pop_next_visible_input_task_with_scheduler( - &mut backlog, - &mut scheduler, - &workers, - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - 2, - ) - .expect("input can pop after one event-pump wait"); - assert_eq!(popped.turn_task_id, Some(queued_task)); - assert_eq!( - scheduler.task(queued_task).expect("queued task").state, - crate::chat::turn_scheduler::TurnTaskState::Dispatched - ); -} - -#[test] -fn post_route_admission_rejection_requeues_input_and_defers_next_pop() { - let mut backlog = std::collections::VecDeque::new(); - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let active = scheduler.enqueue("active detached", crate::chat::turn_scheduler::TurnPriority::Normal, 0); - scheduler.start_task(active).expect("active task starts"); - - let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - workers - .start_from_task( - scheduler.task(active).expect("active task"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("active worker starts"); - enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("legacy after draft failure"), 7); - - let popped = pop_next_visible_input_task_with_scheduler( - &mut backlog, - &mut scheduler, - &workers, - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - 2, - ) - .expect("detached admission allows second visible turn before route is known"); - let task_id = popped.turn_task_id.expect("popped task id"); - assert_eq!( - scheduler.task(task_id).expect("popped task").state, - crate::chat::turn_scheduler::TurnTaskState::Dispatched, - "chat-loop pop marks the task dispatched before post-route admission runs" - ); - assert!( - !provider_turn_visible_admission( - &workers, - crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited, - 1 - ) - .can_start_visible, - "legacy-routed turn is rejected while another detached worker is active" - ); - - let mut defer_visible_input_pop_once = false; - requeue_post_route_admission_rejected_input( - &mut backlog, - &mut scheduler, - &mut defer_visible_input_pop_once, - popped, - ); - - assert_eq!(backlog.len(), 1, "post-route rejection must requeue the popped input"); - assert_eq!( - backlog.front().and_then(|queued| queued.turn_task_id), - Some(task_id), - "requeued input keeps the original scheduler task id" - ); - assert_eq!( - scheduler.task(task_id).expect("requeued task").state, - crate::chat::turn_scheduler::TurnTaskState::Queued, - "requeued input is queued again in the scheduler" - ); - assert_eq!( - scheduler.status().queued, - 1, - "queue status counts the requeued input it lists" - ); - assert!( - provider_turn_visible_admission(&workers, crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, 2) - .can_start_visible, - "without the defer gate, the next pump pass would immediately re-pop under detached capacity" - ); - assert!( - consume_deferred_visible_input_pop(&mut defer_visible_input_pop_once), - "post-route rejection must force one event-pump wait before the same input can pop again" - ); - assert_eq!( - backlog.len(), - 1, - "deferred pump pass leaves the requeued input in place" - ); - assert!( - !consume_deferred_visible_input_pop(&mut defer_visible_input_pop_once), - "defer gate is one-shot after the event-pump wait" - ); - let repopped = pop_next_visible_input_task_with_scheduler( - &mut backlog, - &mut scheduler, - &workers, - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - 2, - ) - .expect("the requeued input pops again"); - assert_eq!(repopped.turn_task_id, Some(task_id)); - assert_eq!( - scheduler.task(task_id).expect("re-dispatched task").state, - crate::chat::turn_scheduler::TurnTaskState::Dispatched, - "the second dequeue is a valid queued -> dispatched transition" - ); -} - -#[test] -fn provider_turn_completion_context_supplies_stable_history_boundary_once() { - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let task_id = scheduler.enqueue("context", crate::chat::turn_scheduler::TurnPriority::Normal, 9); - let mut contexts = std::collections::HashMap::new(); - - record_provider_turn_completion_context(&mut contexts, Some(task_id), 12); - - assert_eq!( - take_provider_turn_completion_history_len(&mut contexts, Some(task_id), 99), - 12 - ); - assert_eq!( - take_provider_turn_completion_history_len(&mut contexts, Some(task_id), 99), - 99, - "completion context is single-use" - ); - assert_eq!( - take_provider_turn_completion_history_len(&mut contexts, None, 7), - 7, - "legacy turns without task id use the local fallback" - ); -} - -#[test] -fn provider_terminal_plan_uses_completion_context_history_boundary() { - let tools: Vec> = Vec::new(); - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let task_id = scheduler.enqueue("context plan", crate::chat::turn_scheduler::TurnPriority::Normal, 1); - let mut contexts = std::collections::HashMap::new(); - record_provider_turn_completion_context(&mut contexts, Some(task_id), 4); - let history_len = take_provider_turn_completion_history_len(&mut contexts, Some(task_id), 99); - - let plan = provider_turn_terminal_plan_from_completion( - ResolvedProviderTurnCompletion { - outcome: Some(dispatcher::TurnOutcomeKind::Completed { - final_text: "context done".to_string(), - reasoning: String::new(), - }), - usage: crate::llm::route_decision::TokenUsage::default(), - }, - history_len, - &tools, - ); - - match plan { - ProviderTurnTerminalPlan::Completed { history_commit_len, .. } => assert_eq!(history_commit_len, 5), - other => panic!("unexpected terminal plan: {other:?}"), - } -} - -#[test] -fn completed_provider_turn_finalization_gate_records_payload_and_commit() { - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let task_id = scheduler.enqueue("complete me", crate::chat::turn_scheduler::TurnPriority::Normal, 2); - scheduler.start_task(task_id).expect("task starts"); - let mut coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); - coordinator - .register_task(scheduler.task(task_id).expect("task snapshot")) - .expect("history task registers"); - let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - workers - .start_from_task( - scheduler.task(task_id).expect("task snapshot"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("worker starts"); - workers.record_execution_started(task_id, 7).expect("execution starts"); - workers.record_completion_ready(task_id).expect("completion ready"); - let usage = crate::llm::route_decision::TokenUsage { - prompt_tokens: Some(10), - completion_tokens: Some(5), - total_tokens: Some(15), - ..Default::default() - }; - - let decisions = gate_completed_provider_turn_finalization( - &mut scheduler, - &mut coordinator, - &mut workers, - Some(task_id), - 3, - 12, - 10, - &usage, - "test completed", - ); - - assert_eq!(decisions.len(), 1, "completion gate should release one ready decision"); - assert_eq!( - scheduler.task(task_id).unwrap().state, - crate::chat::turn_scheduler::TurnTaskState::Completed - ); - let row = workers - .snapshot() - .into_iter() - .find(|row| row.task_id == task_id) - .expect("worker snapshot retained"); - assert_eq!(row.finalized_total_tokens, Some(15)); - assert!(matches!( - row.state, - crate::chat::turn_worker::ProviderTurnWorkerState::Committed - )); -} - -#[test] -fn failed_provider_turn_finalization_gate_records_skip_decision() { - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let task_id = scheduler.enqueue("fail me", crate::chat::turn_scheduler::TurnPriority::Normal, 2); - scheduler.start_task(task_id).expect("task starts"); - let mut coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); - coordinator - .register_task(scheduler.task(task_id).expect("task snapshot")) - .expect("history task registers"); - let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - workers - .start_from_task( - scheduler.task(task_id).expect("task snapshot"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("worker starts"); - workers.record_execution_started(task_id, 8).expect("execution starts"); - workers.record_completion_ready(task_id).expect("completion ready"); - - let decisions = gate_failed_provider_turn_finalization( - &mut scheduler, - &mut coordinator, - &mut workers, - Some(task_id), - 2, - "test failed", - ); - - assert_eq!(decisions.len(), 1, "failure gate should release one skip decision"); - assert_eq!( - scheduler.task(task_id).unwrap().state, - crate::chat::turn_scheduler::TurnTaskState::Failed - ); - let row = workers - .snapshot() - .into_iter() - .find(|row| row.task_id == task_id) - .expect("worker snapshot retained"); - assert!(matches!( - row.state, - crate::chat::turn_worker::ProviderTurnWorkerState::Failed - )); -} - -#[test] -fn cancelled_provider_turn_finalization_gate_records_skip_decision() { - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let task_id = scheduler.enqueue("cancel me", crate::chat::turn_scheduler::TurnPriority::Normal, 2); - scheduler.start_task(task_id).expect("task starts"); - scheduler.request_cancel(task_id).expect("task cancellation requested"); - let mut coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); - coordinator - .register_task(scheduler.task(task_id).expect("task snapshot")) - .expect("history task registers"); - let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - workers - .start_from_task( - scheduler.task(task_id).expect("task snapshot"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("worker starts"); - workers.record_execution_started(task_id, 9).expect("execution starts"); - workers.request_cancel(task_id).expect("worker cancellation requested"); - workers.record_completion_ready(task_id).expect("completion ready"); - - let decisions = gate_cancelled_provider_turn_finalization( - &mut scheduler, - &mut coordinator, - &mut workers, - Some(task_id), - "test cancelled", - ); - - assert_eq!(decisions.len(), 1, "cancellation gate should release one skip decision"); - assert_eq!( - scheduler.task(task_id).unwrap().state, - crate::chat::turn_scheduler::TurnTaskState::Cancelled - ); - let row = workers - .snapshot() - .into_iter() - .find(|row| row.task_id == task_id) - .expect("worker snapshot retained"); - assert!(matches!( - row.state, - crate::chat::turn_worker::ProviderTurnWorkerState::Cancelled - )); -} - -#[test] -fn provider_completion_resolution_prefers_completion_event() { - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let task_id = scheduler.enqueue("event", crate::chat::turn_scheduler::TurnPriority::Normal, 0); - let signal = dispatcher::TurnCompletionSignal::new(); - signal.register_turn(task_id, "draft-event"); - signal.record_and_notify(dispatcher::TurnOutcomeKind::Cancelled); - signal.record_usage(crate::llm::route_decision::TokenUsage { - total_tokens: Some(99), - ..Default::default() - }); - let event = ProviderTurnCompletionEvent { - task_id, - outcome: Some(dispatcher::TurnOutcomeKind::Completed { - final_text: "event wins".to_string(), - reasoning: String::new(), - }), - usage: crate::llm::route_decision::TokenUsage { - total_tokens: Some(12), - ..Default::default() - }, - }; - - let resolved = resolve_provider_turn_completion(&signal, Some(task_id), Some(event)); - - match resolved.outcome { - Some(dispatcher::TurnOutcomeKind::Completed { final_text, .. }) => { - assert_eq!(final_text, "event wins"); - } - other => panic!("unexpected outcome: {other:?}"), - } - assert_eq!(resolved.usage.total_tokens, Some(12)); - assert!(signal.notified_for(task_id).is_none(), "task should unregister"); -} - -#[test] -fn provider_completion_resolution_uses_legacy_usage_when_event_usage_empty() { - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let task_id = scheduler.enqueue( - "event empty usage", - crate::chat::turn_scheduler::TurnPriority::Normal, - 0, - ); - let signal = dispatcher::TurnCompletionSignal::new(); - signal.record_usage(crate::llm::route_decision::TokenUsage { - total_tokens: Some(21), - ..Default::default() - }); - let event = ProviderTurnCompletionEvent { - task_id, - outcome: Some(dispatcher::TurnOutcomeKind::Cancelled), - usage: crate::llm::route_decision::TokenUsage::default(), - }; - - let resolved = resolve_provider_turn_completion(&signal, Some(task_id), Some(event)); - - assert!(matches!(resolved.outcome, Some(dispatcher::TurnOutcomeKind::Cancelled))); - assert_eq!(resolved.usage.total_tokens, Some(21)); -} - -#[test] -fn provider_completion_resolution_uses_keyed_signal_without_event() { - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let task_id = scheduler.enqueue("keyed", crate::chat::turn_scheduler::TurnPriority::Normal, 0); - let signal = dispatcher::TurnCompletionSignal::new(); - signal.register_turn(task_id, "draft-keyed"); - assert!(signal.record_usage_for_draft( - "draft-keyed", - crate::llm::route_decision::TokenUsage { - total_tokens: Some(34), - ..Default::default() - } - )); - assert!(signal.record_and_notify_for_draft( - "draft-keyed", - dispatcher::TurnOutcomeKind::Failed { - err: "keyed failed".to_string(), - retryable: false, - }, - )); - - let resolved = resolve_provider_turn_completion(&signal, Some(task_id), None); - - match resolved.outcome { - Some(dispatcher::TurnOutcomeKind::Failed { err, retryable }) => { - assert_eq!(err, "keyed failed"); - assert!(!retryable); - } - other => panic!("unexpected outcome: {other:?}"), - } - assert_eq!(resolved.usage.total_tokens, Some(34)); - assert!(signal.notified_for(task_id).is_none(), "task should unregister"); -} - -#[test] -fn provider_turn_terminal_gate_dispatches_completed_finalization() { - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let task_id = scheduler.enqueue("unified gate", crate::chat::turn_scheduler::TurnPriority::Normal, 1); - scheduler.start_task(task_id).expect("task starts"); - let mut coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); - coordinator - .register_task(scheduler.task(task_id).expect("task snapshot")) - .expect("history task registers"); - let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - workers - .start_from_task( - scheduler.task(task_id).expect("task snapshot"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("worker starts"); - workers.record_execution_started(task_id, 55).expect("execution starts"); - workers.record_completion_ready(task_id).expect("completion ready"); - let usage = crate::llm::route_decision::TokenUsage { - total_tokens: Some(55), - ..Default::default() - }; - - let decisions = gate_provider_turn_terminal_finalization( - &mut scheduler, - &mut coordinator, - &mut workers, - Some(task_id), - ProviderTurnTerminalGate::Completed { - history_commit_len: 2, - final_text_chars: 11, - recorded_response_chars: 10, - usage: &usage, - summary: "test unified completed", - }, - ); - - assert_eq!( - decisions.len(), - 1, - "unified terminal gate should finalize completed turn" - ); - let row = workers - .snapshot() - .into_iter() - .find(|row| row.task_id == task_id) - .expect("worker snapshot retained"); - assert_eq!(row.finalized_total_tokens, Some(55)); - assert!(matches!( - row.state, - crate::chat::turn_worker::ProviderTurnWorkerState::Committed - )); -} - -#[test] -fn provider_turn_finalizer_event_commits_completed_plan() { - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let task_id = scheduler.enqueue( - "finalizer completed", - crate::chat::turn_scheduler::TurnPriority::Normal, - 1, - ); - scheduler.start_task(task_id).expect("task starts"); - let mut coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); - coordinator - .register_task(scheduler.task(task_id).expect("task snapshot")) - .expect("history task registers"); - let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - workers - .start_from_task( - scheduler.task(task_id).expect("task snapshot"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("worker starts"); - workers.record_execution_started(task_id, 56).expect("execution starts"); - workers.record_completion_ready(task_id).expect("completion ready"); - - let result = finalize_provider_turn_from_event( - &mut scheduler, - &mut coordinator, - &mut workers, - ProviderTurnFinalizerEvent { - task_id: Some(task_id), - plan: ProviderTurnTerminalPlan::Completed { - final_text: "done".to_string(), - reasoning: String::new(), - recorded_response: "done".to_string(), - empty_response: false, - usage: crate::llm::route_decision::TokenUsage { - total_tokens: Some(56), - ..Default::default() - }, - history_commit_len: 2, - final_text_chars: 4, - recorded_response_chars: 4, - summary: "test finalizer completed", - }, - }, - ); - - assert_eq!( - result, - vec![ProviderTurnFinalizerResult { - task_id: Some(task_id), - terminal_status: "completed", - finalized: true, - }] - ); - let row = workers - .snapshot() - .into_iter() - .find(|row| row.task_id == task_id) - .expect("worker snapshot retained"); - assert_eq!(row.finalized_total_tokens, Some(56)); - assert!(matches!( - row.state, - crate::chat::turn_worker::ProviderTurnWorkerState::Committed - )); -} - -#[test] -fn provider_turn_finalizer_event_closes_failed_and_cancelled_plans() { - let mut failed_scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let failed_id = failed_scheduler.enqueue("finalizer failed", crate::chat::turn_scheduler::TurnPriority::Normal, 1); - failed_scheduler.start_task(failed_id).expect("failed task starts"); - let mut failed_coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); - failed_coordinator - .register_task(failed_scheduler.task(failed_id).expect("failed task snapshot")) - .expect("failed history task registers"); - let mut failed_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - failed_workers - .start_from_task( - failed_scheduler.task(failed_id).expect("failed task snapshot"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("failed worker starts"); - failed_workers - .record_execution_started(failed_id, 57) - .expect("failed execution starts"); - failed_workers - .record_completion_ready(failed_id) - .expect("failed completion ready"); - - let failed_result = finalize_provider_turn_from_event( - &mut failed_scheduler, - &mut failed_coordinator, - &mut failed_workers, - ProviderTurnFinalizerEvent { - task_id: Some(failed_id), - plan: ProviderTurnTerminalPlan::Failed { - err: "failed".to_string(), - history_commit_len: 1, - summary: "test finalizer failed".to_string(), - }, - }, - ); - - assert_eq!(failed_result.len(), 1); - assert_eq!(failed_result[0].terminal_status, "failed"); - assert!(failed_result[0].finalized); - assert!(matches!( - failed_workers - .snapshot() - .into_iter() - .find(|row| row.task_id == failed_id) - .expect("failed worker snapshot") - .state, - crate::chat::turn_worker::ProviderTurnWorkerState::Failed - )); - - let mut cancelled_scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let cancelled_id = cancelled_scheduler.enqueue( - "finalizer cancelled", - crate::chat::turn_scheduler::TurnPriority::Normal, - 1, - ); - cancelled_scheduler - .start_task(cancelled_id) - .expect("cancelled task starts"); - cancelled_scheduler - .request_cancel(cancelled_id) - .expect("cancelled task requested"); - let mut cancelled_coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); - cancelled_coordinator - .register_task(cancelled_scheduler.task(cancelled_id).expect("cancelled task snapshot")) - .expect("cancelled history task registers"); - let mut cancelled_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - cancelled_workers - .start_from_task( - cancelled_scheduler.task(cancelled_id).expect("cancelled task snapshot"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("cancelled worker starts"); - cancelled_workers - .record_execution_started(cancelled_id, 58) - .expect("cancelled execution starts"); - cancelled_workers - .request_cancel(cancelled_id) - .expect("cancelled worker requested"); - cancelled_workers - .record_completion_ready(cancelled_id) - .expect("cancelled completion ready"); - - let cancelled_result = finalize_provider_turn_from_event( - &mut cancelled_scheduler, - &mut cancelled_coordinator, - &mut cancelled_workers, - ProviderTurnFinalizerEvent { - task_id: Some(cancelled_id), - plan: ProviderTurnTerminalPlan::Cancelled { - summary: "test finalizer cancelled", - }, - }, - ); - - assert_eq!(cancelled_result.len(), 1); - assert_eq!(cancelled_result[0].terminal_status, "cancelled"); - assert!(cancelled_result[0].finalized); - assert!(matches!( - cancelled_workers - .snapshot() - .into_iter() - .find(|row| row.task_id == cancelled_id) - .expect("cancelled worker snapshot") - .state, - crate::chat::turn_worker::ProviderTurnWorkerState::Cancelled - )); -} - -#[test] -fn provider_turn_finalizer_queue_drains_fifo_and_unlocks_commit_order() { - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let first = scheduler.enqueue("first failed", crate::chat::turn_scheduler::TurnPriority::Normal, 1); - let second = scheduler.enqueue("second completed", crate::chat::turn_scheduler::TurnPriority::Normal, 1); - scheduler.start_task(first).expect("first starts"); - scheduler.start_task(second).expect("second starts"); - - let mut coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); - coordinator - .register_task(scheduler.task(first).expect("first task")) - .expect("first history task registers"); - coordinator - .register_task(scheduler.task(second).expect("second task")) - .expect("second history task registers"); - - let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - for (id, lease) in [(first, 61), (second, 62)] { - workers - .start_from_task( - scheduler.task(id).expect("task snapshot"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("worker starts"); - workers.record_execution_started(id, lease).expect("execution starts"); - workers.record_completion_ready(id).expect("completion ready"); - } - - let mut queue = std::collections::VecDeque::new(); - enqueue_provider_turn_finalizer_event( - &mut queue, - Some(first), - ProviderTurnTerminalPlan::Failed { - err: "first failed".to_string(), - history_commit_len: 1, - summary: "test first failed".to_string(), - }, - ); - enqueue_provider_turn_finalizer_event( - &mut queue, - Some(second), - ProviderTurnTerminalPlan::Completed { - final_text: "second done".to_string(), - reasoning: String::new(), - recorded_response: "second done".to_string(), - empty_response: false, - usage: crate::llm::route_decision::TokenUsage { - total_tokens: Some(62), - ..Default::default() - }, - history_commit_len: 2, - final_text_chars: 11, - recorded_response_chars: 11, - summary: "test second completed", - }, - ); - - let results = drain_provider_turn_finalizer_events(&mut scheduler, &mut coordinator, &mut workers, &mut queue); - - assert!(queue.is_empty()); - assert_eq!(results.len(), 2); - assert_eq!(results[0].task_id, Some(first)); - assert_eq!(results[0].terminal_status, "failed"); - assert!(results[0].finalized); - assert_eq!(results[1].task_id, Some(second)); - assert_eq!(results[1].terminal_status, "completed"); - assert!(results[1].finalized); - let rows = workers.snapshot(); - assert!(matches!( - rows.iter().find(|row| row.task_id == first).expect("first row").state, - crate::chat::turn_worker::ProviderTurnWorkerState::Failed - )); - let second_row = rows.iter().find(|row| row.task_id == second).expect("second row"); - assert_eq!(second_row.finalized_total_tokens, Some(62)); - assert!(matches!( - second_row.state, - crate::chat::turn_worker::ProviderTurnWorkerState::Committed - )); -} - -#[test] -fn provider_turn_finalizer_delays_later_completed_turn_until_earlier_ready() { - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let first = scheduler.enqueue("first slow", crate::chat::turn_scheduler::TurnPriority::Normal, 1); - let second = scheduler.enqueue("second fast", crate::chat::turn_scheduler::TurnPriority::Normal, 1); - scheduler.start_task(first).expect("first starts"); - scheduler.start_task(second).expect("second starts"); - let mut coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); - coordinator - .register_task(scheduler.task(first).expect("first task")) - .expect("first history task registers"); - coordinator - .register_task(scheduler.task(second).expect("second task")) - .expect("second history task registers"); - let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - for (id, lease) in [(first, 81), (second, 82)] { - workers - .start_from_task( - scheduler.task(id).expect("task snapshot"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("worker starts"); - workers.record_execution_started(id, lease).expect("execution starts"); - workers.record_completion_ready(id).expect("completion ready"); - } - - let second_results = finalize_provider_turn_from_event( - &mut scheduler, - &mut coordinator, - &mut workers, - ProviderTurnFinalizerEvent { - task_id: Some(second), - plan: ProviderTurnTerminalPlan::Completed { - final_text: "second answer".to_string(), - reasoning: String::new(), - recorded_response: "second answer".to_string(), - empty_response: false, - usage: crate::llm::route_decision::TokenUsage { - total_tokens: Some(82), - ..Default::default() - }, - history_commit_len: 3, - final_text_chars: 13, - recorded_response_chars: 13, - summary: "test second completed", - }, - }, - ); - assert_eq!( - second_results, - vec![ProviderTurnFinalizerResult { - task_id: Some(second), - terminal_status: "unknown", - finalized: false, - }], - "later completion must wait for the earlier sequence" - ); - assert!(matches!( - workers.worker(second).expect("second worker").state, - crate::chat::turn_worker::ProviderTurnWorkerState::AwaitingCommit(_) - )); - - let first_results = finalize_provider_turn_from_event( - &mut scheduler, - &mut coordinator, - &mut workers, - ProviderTurnFinalizerEvent { - task_id: Some(first), - plan: ProviderTurnTerminalPlan::Completed { - final_text: "first answer".to_string(), - reasoning: String::new(), - recorded_response: "first answer".to_string(), - empty_response: false, - usage: crate::llm::route_decision::TokenUsage { - total_tokens: Some(81), - ..Default::default() - }, - history_commit_len: 3, - final_text_chars: 12, - recorded_response_chars: 12, - summary: "test first completed", - }, - }, - ); - - assert_eq!( - first_results.iter().map(|result| result.task_id).collect::>(), - vec![Some(first), Some(second)], - "earlier completion should release both ready decisions in sequence" - ); - assert!(first_results.iter().all(|result| result.finalized)); - assert!(matches!( - workers.worker(first).expect("first worker").state, - crate::chat::turn_worker::ProviderTurnWorkerState::Committed - )); - assert!(matches!( - workers.worker(second).expect("second worker").state, - crate::chat::turn_worker::ProviderTurnWorkerState::Committed - )); -} - -#[test] -fn provider_turn_finalizer_releases_later_completed_turn_when_earlier_cancelled() { - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let first = scheduler.enqueue("first cancelled", crate::chat::turn_scheduler::TurnPriority::Normal, 1); - let second = scheduler.enqueue("second held", crate::chat::turn_scheduler::TurnPriority::Normal, 1); - scheduler.start_task(first).expect("first starts"); - scheduler.request_cancel(first).expect("first cancellation requested"); - scheduler.start_task(second).expect("second starts"); - let mut coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); - coordinator - .register_task(scheduler.task(first).expect("first task")) - .expect("first history task registers"); - coordinator - .register_task(scheduler.task(second).expect("second task")) - .expect("second history task registers"); - let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - workers - .start_from_task( - scheduler.task(first).expect("first task"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("first worker starts"); - workers - .record_execution_started(first, 91) - .expect("first execution starts"); - workers - .request_cancel(first) - .expect("first worker cancellation requested"); - workers.record_completion_ready(first).expect("first completion ready"); - workers - .start_from_task( - scheduler.task(second).expect("second task"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("second worker starts"); - workers - .record_execution_started(second, 92) - .expect("second execution starts"); - workers - .record_completion_ready(second) - .expect("second completion ready"); - - let second_results = finalize_provider_turn_from_event( - &mut scheduler, - &mut coordinator, - &mut workers, - ProviderTurnFinalizerEvent { - task_id: Some(second), - plan: ProviderTurnTerminalPlan::Completed { - final_text: "second after cancel".to_string(), - reasoning: String::new(), - recorded_response: "second after cancel".to_string(), - empty_response: false, - usage: crate::llm::route_decision::TokenUsage { - total_tokens: Some(92), - ..Default::default() - }, - history_commit_len: 3, - final_text_chars: 19, - recorded_response_chars: 19, - summary: "test second completed after cancel", - }, - }, - ); - assert_eq!( - second_results, - vec![ProviderTurnFinalizerResult { - task_id: Some(second), - terminal_status: "unknown", - finalized: false, - }], - "later completion must remain held until earlier cancellation is ordered" - ); - - let first_results = finalize_provider_turn_from_event( - &mut scheduler, - &mut coordinator, - &mut workers, - ProviderTurnFinalizerEvent { - task_id: Some(first), - plan: ProviderTurnTerminalPlan::Cancelled { - summary: "test first cancelled", - }, - }, - ); - - assert_eq!( - first_results - .iter() - .map(|result| (result.task_id, result.terminal_status)) - .collect::>(), - vec![(Some(first), "cancelled"), (Some(second), "completed")], - "earlier cancellation should skip first and then release held later commit" - ); - assert!(first_results.iter().all(|result| result.finalized)); - assert!(matches!( - workers.worker(first).expect("first worker").state, - crate::chat::turn_worker::ProviderTurnWorkerState::Cancelled - )); - assert!(matches!( - workers.worker(second).expect("second worker").state, - crate::chat::turn_worker::ProviderTurnWorkerState::Committed - )); -} - -#[cfg(feature = "terminal-tui")] -#[test] -fn provider_turn_finalizer_n3_out_of_order_releases_ordered_persistence_actions() { - use crate::chat::action::Action; - - fn completed_plan(final_text: &str, total_tokens: u32, history_commit_len: usize) -> ProviderTurnTerminalPlan { - ProviderTurnTerminalPlan::Completed { - final_text: final_text.to_string(), - reasoning: String::new(), - recorded_response: final_text.to_string(), - empty_response: false, - usage: crate::llm::route_decision::TokenUsage { - total_tokens: Some(total_tokens), - ..Default::default() - }, - history_commit_len, - final_text_chars: final_text.chars().count(), - recorded_response_chars: final_text.chars().count(), - summary: "test n3 completed", - } - } - - fn pending_commit_for( - task_id: crate::chat::turn_scheduler::TurnTaskId, - draft_id: &str, - user_input: &str, - plan: ProviderTurnTerminalPlan, - ) -> PendingOrderedProviderTurnCommit { - PendingOrderedProviderTurnCommit { - context: PerTurnContext { - turn_binding: None, - task_id, - draft_id: draft_id.to_string(), - delta_tx: None, - tool_event_tx: None, - draft_updater: None, - tool_event_forwarder: None, - user_input: user_input.to_string(), - turn_run_id: format!("test-run-{}", task_id.get()), - route_scope: crate::memory::MessageEventScope::new("chat", crate::memory::MemoryVisibility::Workspace), - route_decision: RouteDecision::single_candidate("mock", "mock"), - provider_started_at: chrono::Utc::now(), - provider_name: "mock".to_string(), - model_name: "mock".to_string(), - history_len_before_user_turn: 0, - compaction_epoch_at_start: 0, - assignment: None, - }, - terminal_plan: plan, - } - } - - fn dispatch_ready_for_test( - results: Vec, - pending: &mut std::collections::HashMap< - crate::chat::turn_scheduler::TurnTaskId, - PendingOrderedProviderTurnCommit, - >, - dispatcher: &dispatcher::ChatDispatcher, - ) { - for result in results { - if !result.finalized || result.terminal_status != "completed" { - continue; - } - let task_id = result.task_id.expect("finalized result has task id"); - let pending_commit = pending.remove(&task_id).expect("pending commit payload"); - let ProviderTurnTerminalPlan::Completed { - final_text, - reasoning, - empty_response, - .. - } = pending_commit.terminal_plan - else { - panic!("expected completed terminal plan"); - }; - dispatch_ordered_provider_turn_commit( - dispatcher, - task_id, - &pending_commit.context.draft_id, - &pending_commit.context.user_input, - &final_text, - &reasoning, - empty_response, - true, - ) - .expect("ordered history dispatch"); - } - } - - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let first = scheduler.enqueue("alpha prompt", crate::chat::turn_scheduler::TurnPriority::Normal, 0); - let second = scheduler.enqueue("bravo prompt", crate::chat::turn_scheduler::TurnPriority::Normal, 0); - let third = scheduler.enqueue("charlie prompt", crate::chat::turn_scheduler::TurnPriority::Normal, 0); - for task_id in [first, second, third] { - scheduler.start_task(task_id).expect("task starts"); - } - - let mut coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); - for task_id in [first, second, third] { - coordinator - .register_task(scheduler.task(task_id).expect("task snapshot")) - .expect("history task registers"); - } - - let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - for (task_id, lease) in [(first, 101), (second, 102), (third, 103)] { - workers - .start_from_task( - scheduler.task(task_id).expect("task snapshot"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("worker starts"); - workers - .record_execution_started(task_id, lease) - .expect("execution starts"); - workers.record_completion_ready(task_id).expect("completion ready"); - } - - let first_plan = completed_plan("alpha answer", 11, 2); - let second_plan = completed_plan("bravo answer", 12, 4); - let third_plan = completed_plan("charlie answer", 13, 6); - let mut pending_ordered_provider_turn_commits = std::collections::HashMap::from([ - ( - first, - pending_commit_for(first, "draft-alpha", "alpha prompt", first_plan.clone()), - ), - ( - second, - pending_commit_for(second, "draft-bravo", "bravo prompt", second_plan.clone()), - ), - ( - third, - pending_commit_for(third, "draft-charlie", "charlie prompt", third_plan.clone()), - ), - ]); - let (dispatcher, mut rx) = dispatcher::ChatDispatcher::new(); - - let third_results = finalize_provider_turn_from_event( - &mut scheduler, - &mut coordinator, - &mut workers, - ProviderTurnFinalizerEvent { - task_id: Some(third), - plan: third_plan, - }, - ); - assert_eq!( - third_results, - vec![ProviderTurnFinalizerResult { - task_id: Some(third), - terminal_status: "unknown", - finalized: false, - }], - "third completion must stay held until first and second are terminal" - ); - dispatch_ready_for_test(third_results, &mut pending_ordered_provider_turn_commits, &dispatcher); - assert!( - rx.try_recv().is_err(), - "held third turn must emit no persistence actions" - ); - assert!(matches!( - workers.worker(third).expect("third worker").state, - crate::chat::turn_worker::ProviderTurnWorkerState::AwaitingCommit(_) - )); - - let second_results = finalize_provider_turn_from_event( - &mut scheduler, - &mut coordinator, - &mut workers, - ProviderTurnFinalizerEvent { - task_id: Some(second), - plan: second_plan, - }, - ); - assert_eq!( - second_results, - vec![ProviderTurnFinalizerResult { - task_id: Some(second), - terminal_status: "unknown", - finalized: false, - }], - "second completion must stay held until first is terminal" - ); - dispatch_ready_for_test(second_results, &mut pending_ordered_provider_turn_commits, &dispatcher); - assert!( - rx.try_recv().is_err(), - "held second turn must emit no persistence actions" - ); - - let first_results = finalize_provider_turn_from_event( - &mut scheduler, - &mut coordinator, - &mut workers, - ProviderTurnFinalizerEvent { - task_id: Some(first), - plan: first_plan, - }, - ); - assert_eq!( - first_results - .iter() - .map(|result| (result.task_id, result.terminal_status, result.finalized)) - .collect::>(), - vec![ - (Some(first), "completed", true), - (Some(second), "completed", true), - (Some(third), "completed", true), - ], - "first completion must release all held completed turns in dispatch order" - ); - dispatch_ready_for_test(first_results, &mut pending_ordered_provider_turn_commits, &dispatcher); - - for (expected_user, expected_assistant, expected_draft, expected_task) in [ - ("alpha prompt", "alpha answer", "draft-alpha", first), - ("bravo prompt", "bravo answer", "draft-bravo", second), - ("charlie prompt", "charlie answer", "draft-charlie", third), - ] { - match rx.try_recv().expect("ordered user action") { - Action::RecordUserTurn(content) => assert_eq!(content, expected_user), - other => panic!("expected RecordUserTurn, got {other:?}"), - } - match rx.try_recv().expect("ordered assistant action") { - Action::RecordAssistantTurn { task_id, content } => { - assert_eq!(task_id, Some(expected_task)); - assert_eq!(content, expected_assistant); - } - other => panic!("expected RecordAssistantTurn, got {other:?}"), - } - match rx.try_recv().expect("ordered stream completed action") { - Action::StreamCompleted { - draft_id, - final_text, - reasoning, - } => { - assert_eq!(draft_id, expected_draft); - assert_eq!(final_text, expected_assistant); - assert!(reasoning.is_empty(), "expected an empty value"); - } - other => panic!("expected StreamCompleted, got {other:?}"), - } - } - assert!( - rx.try_recv().is_err(), - "ordered dispatch should emit exactly three action triplets" - ); - assert!(pending_ordered_provider_turn_commits.is_empty()); - assert_eq!(coordinator.pending_tasks(), 0); - assert_eq!(coordinator.pending_outcomes(), 0); - for task_id in [first, second, third] { - assert!(matches!( - workers.worker(task_id).expect("worker").state, - crate::chat::turn_worker::ProviderTurnWorkerState::Committed - )); - } -} - -#[tokio::test] -async fn provider_turn_finalizer_drain_helper_publishes_queue_and_worker_status() { - let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let task_id = scheduler.enqueue( - "publish finalizer", - crate::chat::turn_scheduler::TurnPriority::Normal, - 1, - ); - scheduler.start_task(task_id).expect("task starts"); - let mut coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); - coordinator - .register_task(scheduler.task(task_id).expect("task snapshot")) - .expect("history task registers"); - let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - workers - .start_from_task( - scheduler.task(task_id).expect("task snapshot"), - crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, - ) - .expect("worker starts"); - workers.record_execution_started(task_id, 63).expect("execution starts"); - workers.record_completion_ready(task_id).expect("completion ready"); - let mut queue = std::collections::VecDeque::new(); - enqueue_provider_turn_finalizer_event( - &mut queue, - Some(task_id), - ProviderTurnTerminalPlan::Completed { - final_text: "published".to_string(), - reasoning: String::new(), - recorded_response: "published".to_string(), - empty_response: false, - usage: crate::llm::route_decision::TokenUsage { - total_tokens: Some(63), - ..Default::default() - }, - history_commit_len: 2, - final_text_chars: 9, - recorded_response_chars: 9, - summary: "test finalizer published", - }, - ); - let (dispatcher, mut rx) = dispatcher::ChatDispatcher::new(); - - let results = drain_provider_turn_finalizer_events_and_publish( - &mut scheduler, - &mut coordinator, - &mut workers, - &mut queue, - &dispatcher, - ); - - assert_eq!(results.len(), 1); - assert!(results[0].finalized); - assert!(queue.is_empty()); - let first = rx.recv().await.expect("main queue status action"); - let second = rx.recv().await.expect("provider worker status action"); - assert!(matches!( - first, - crate::chat::action::Action::MainQueueStatusUpdated { .. } - )); - match second { - crate::chat::action::Action::ProviderWorkerStatusUpdated { status } => { - assert_eq!(status.finalized_payloads, 1); - assert_eq!(status.finalized_total_tokens, 63); - } - other => panic!("unexpected action: {other:?}"), - } -} - -#[test] -fn provider_terminal_plan_completed_non_empty_builds_gate_fields() { - let tools: Vec> = Vec::new(); - let resolved = ResolvedProviderTurnCompletion { - outcome: Some(dispatcher::TurnOutcomeKind::Completed { - final_text: "P7J terminal plan".to_string(), - reasoning: "kept reasoning".to_string(), - }), - usage: crate::llm::route_decision::TokenUsage { - total_tokens: Some(77), - ..Default::default() - }, - }; - - let plan = provider_turn_terminal_plan_from_completion(resolved, 4, &tools); - - match plan { - ProviderTurnTerminalPlan::Completed { - final_text, - recorded_response, - reasoning, - empty_response, - usage, - history_commit_len, - final_text_chars, - recorded_response_chars, - summary, - } => { - assert_eq!(final_text, "P7J terminal plan"); - assert_eq!(recorded_response, "P7J terminal plan"); - assert_eq!(reasoning, "kept reasoning"); - assert!(!empty_response); - assert_eq!(usage.total_tokens, Some(77)); - assert_eq!(history_commit_len, 5); - assert_eq!(final_text_chars, "P7J terminal plan".chars().count()); - assert_eq!(recorded_response_chars, "P7J terminal plan".chars().count()); - assert_eq!(summary, "redux driver completed"); - } - other => panic!("unexpected terminal plan: {other:?}"), - } -} - -#[test] -fn provider_terminal_plan_empty_failed_and_cancelled_keep_boundaries() { - let tools: Vec> = Vec::new(); - let empty = provider_turn_terminal_plan_from_completion( - ResolvedProviderTurnCompletion { - outcome: Some(dispatcher::TurnOutcomeKind::Completed { - final_text: " ".to_string(), - reasoning: "hidden reasoning".to_string(), - }), - usage: crate::llm::route_decision::TokenUsage::default(), - }, - 6, - &tools, - ); - match empty { - ProviderTurnTerminalPlan::Completed { - empty_response, - history_commit_len, - final_text_chars, - recorded_response_chars, - summary, - .. - } => { - assert!(empty_response); - assert_eq!(history_commit_len, 6); - assert_eq!(final_text_chars, 0); - assert_eq!(recorded_response_chars, 0); - assert_eq!(summary, "redux driver completed with empty response"); - } - other => panic!("unexpected empty terminal plan: {other:?}"), - } - - let failed = provider_turn_terminal_plan_from_completion( - ResolvedProviderTurnCompletion { - outcome: Some(dispatcher::TurnOutcomeKind::Failed { - err: "provider failed".to_string(), - retryable: false, - }), - usage: crate::llm::route_decision::TokenUsage::default(), - }, - 7, - &tools, - ); - match failed { - ProviderTurnTerminalPlan::Failed { - err, - history_commit_len, - summary, - } => { - assert_eq!(err, "provider failed"); - assert_eq!(history_commit_len, 7); - assert_eq!(summary, "redux driver failed: provider failed"); - } - other => panic!("unexpected failed terminal plan: {other:?}"), - } - - let cancelled = provider_turn_terminal_plan_from_completion( - ResolvedProviderTurnCompletion { - outcome: None, - usage: crate::llm::route_decision::TokenUsage::default(), - }, - 8, - &tools, - ); - match cancelled { - ProviderTurnTerminalPlan::Cancelled { summary } => { - assert_eq!(summary, "redux driver cancelled"); - } - other => panic!("unexpected cancelled terminal plan: {other:?}"), - } -} - -#[tokio::test] -async fn active_turn_sessions_command_is_handled_without_enqueue() { - let mut backlog = std::collections::VecDeque::new(); - enqueue_input_message(&mut backlog, input_msg("normal one")); - let scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let msg = input_msg("/sessions"); - let chat_session = session::ChatSession::new("p", "m"); - let provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - let mut chat_sessions = - crate::chat::sessions::ChatSessionsHandle::new(std::sync::Arc::new(tokio::sync::RwLock::new(Vec::new()))); - let session_rings = std::collections::HashMap::new(); - let mut reaped_log_archive = ReapedSessionLogArchive::default(); - let reap_policy = crate::chat::sessions::runtime::ReapPolicy::default(); - let tools_registry: Vec> = Vec::new(); - let daemon_config = Config::default(); - let (daemon_dispatcher, _daemon_action_rx) = dispatcher::ChatDispatcher::new(); - let daemon_control = DaemonControl { - config: &daemon_config, - dispatcher: &daemon_dispatcher, - redraw_tx: None, - }; - - let output = active_turn_local_command_output( - &msg, - &backlog, - &scheduler, - &chat_session, - &provider_turn_workers, - &mut chat_sessions, - &session_rings, - &mut reaped_log_archive, - &reap_policy, - &tools_registry, - daemon_control, - ) - .await - .expect("sessions command output"); - - assert_eq!( - output, - format!("current chat session: {}\nNo child TUI sessions.", chat_session.id) - ); - assert_eq!(backlog.len(), 1, "read-only sessions command must not mutate backlog"); -} - -/// A `--daemon` command exists to look at, or end, work in another -/// process — and the moment an operator reaches for one is precisely while -/// a long turn is running here. Queueing them behind that turn made the -/// feature unavailable exactly when it was wanted, so both entry points -/// have to answer: the whitelist that decides what stays answerable, and -/// the dispatch that actually runs it. -#[tokio::test] -async fn active_turn_daemon_commands_run_instead_of_queueing() { - let mut daemon_config = Config::default(); - // A closed port: the request fails on its own, promptly, in its task. - daemon_config.chat.daemon.url = "http://127.0.0.1:1".to_string(); - let (daemon_dispatcher, _daemon_action_rx) = dispatcher::ChatDispatcher::new(); - let daemon_control = DaemonControl { - config: &daemon_config, - dispatcher: &daemon_dispatcher, - redraw_tx: None, - }; - - for (command, expected) in [ - ("/sessions --daemon", "Listing daemon work at http://127.0.0.1:1"), - ( - "/kill --daemon w42", - "Asking the daemon at http://127.0.0.1:1 to kill w42", - ), - ( - "/steer --daemon w42 change course", - "Sending a message to daemon task w42 at http://127.0.0.1:1", - ), - ] { - assert!( - is_active_turn_local_command(command), - "{command} must stay answerable while a turn is in flight" - ); - - let mut backlog = std::collections::VecDeque::new(); - enqueue_input_message(&mut backlog, input_msg("normal one")); - let scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let chat_session = session::ChatSession::new("p", "m"); - let provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - let mut chat_sessions = - crate::chat::sessions::ChatSessionsHandle::new(std::sync::Arc::new(tokio::sync::RwLock::new(Vec::new()))); - let session_rings = std::collections::HashMap::new(); - let mut reaped_log_archive = ReapedSessionLogArchive::default(); - let reap_policy = crate::chat::sessions::runtime::ReapPolicy::default(); - let tools_registry: Vec> = Vec::new(); - - let output = active_turn_local_command_output( - &input_msg(command), - &backlog, - &scheduler, - &chat_session, - &provider_turn_workers, - &mut chat_sessions, - &session_rings, - &mut reaped_log_archive, - &reap_policy, - &tools_registry, - daemon_control, - ) - .await - .unwrap_or_else(|| panic!("{command} must be answered during a turn, not queued")); - - assert!(output.contains(expected), "{command}: {output}"); - assert_eq!(backlog.len(), 1, "{command} must not be enqueued behind the turn"); - } -} - -/// The idle loop runs the same three commands through -/// `start_daemon_session_command`, so the two entry points cannot drift -/// apart again: this is the whole of what the loop's `Daemon*` arm does. -#[tokio::test] -async fn the_idle_loop_entry_point_starts_the_same_three_commands() { - let mut daemon_config = Config::default(); - daemon_config.chat.daemon.url = "http://127.0.0.1:1".to_string(); - let (daemon_dispatcher, _daemon_action_rx) = dispatcher::ChatDispatcher::new(); - let control = DaemonControl { - config: &daemon_config, - dispatcher: &daemon_dispatcher, - redraw_tx: None, - }; - let in_flight = crate::chat::sessions::daemon::new_in_flight_registry(); - - for (action, expected) in [ - ( - crate::chat::sessions::SessionCommand::DaemonSessions, - "Listing daemon work at http://127.0.0.1:1", - ), - ( - crate::chat::sessions::SessionCommand::DaemonKill { - address: "w42".to_string(), - }, - "Asking the daemon at http://127.0.0.1:1 to kill w42", - ), - ( - crate::chat::sessions::SessionCommand::DaemonSteer { - address: "w42".to_string(), - message: "change course".to_string(), - }, - "Sending a message to daemon task w42 at http://127.0.0.1:1", - ), - ] { - let notice = start_daemon_session_command(&action, None, &in_flight, control) - .unwrap_or_else(|| panic!("{action:?} must start a daemon request")); - assert!(notice.contains(expected), "{action:?}: {notice}"); - } - - // A local `/sessions` is not daemon-scoped and must fall through to the - // local handler rather than being swallowed here. - assert!( - start_daemon_session_command( - &crate::chat::sessions::SessionCommand::Sessions, - None, - &in_flight, - control - ) - .is_none() - ); -} - -/// §7-2's own argument, applied to chat's own cross-process call: in a -/// runtime with no wall clock, the fallback for something stuck is being -/// seen and being killed. A daemon that accepts the connection and then -/// answers nothing used to leave a spawned task that was neither. -#[cfg(feature = "terminal-tui")] -#[tokio::test] -async fn a_stuck_daemon_request_is_listed_and_can_be_ended() { - // A daemon that accepts the connection and then never answers. Nothing - // here expires: the request stays outstanding until it is ended. - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("test: bind ephemeral port"); - let addr = listener.local_addr().expect("test: local addr"); - let silent_daemon = tokio::spawn(async move { - let held = listener.accept().await; - std::future::pending::<()>().await; - drop(held); - }); - - let mut daemon_config = Config::default(); - daemon_config.chat.daemon.url = format!("http://{addr}"); - let (daemon_dispatcher, mut daemon_action_rx) = dispatcher::ChatDispatcher::new(); - let control = DaemonControl { - config: &daemon_config, - dispatcher: &daemon_dispatcher, - redraw_tx: None, - }; - let mut chat_sessions = - crate::chat::sessions::ChatSessionsHandle::new(std::sync::Arc::new(tokio::sync::RwLock::new(Vec::new()))); - let in_flight = chat_sessions.daemon_requests(); - let session_rings = std::collections::HashMap::new(); - let mut reaped_log_archive = ReapedSessionLogArchive::default(); - let reap_policy = crate::chat::sessions::runtime::ReapPolicy::default(); - let tools_registry: Vec> = Vec::new(); - - let notice = start_daemon_session_command( - &crate::chat::sessions::SessionCommand::DaemonSessions, - None, - &in_flight, - control, - ) - .expect("test: the listing request starts"); - assert!(notice.contains("Listing daemon work at"), "{notice}"); - - // Visible: the hung request shows up in this chat's own `/sessions`. - let listing = handle_local_session_command( - &crate::chat::sessions::SessionCommand::Sessions, - &mut chat_sessions, - &session_rings, - &mut reaped_log_archive, - &reap_policy, - &tools_registry, - ) - .await - .expect("test: /sessions renders"); - assert!(listing.contains("Daemon requests in flight (1)"), "{listing}"); - assert!(listing.contains("d1 list"), "{listing}"); - - // Killable: ending it by address stops the task, which then reports - // back instead of hanging on a daemon that will never answer. - let killed = start_daemon_session_command( - &crate::chat::sessions::SessionCommand::DaemonKill { - address: "d1".to_string(), - }, - None, - &in_flight, - control, - ) - .expect("test: d1 is this chat's own address space"); - assert!(killed.contains("Stopped waiting on daemon request d1"), "{killed}"); - - let reported = tokio::time::timeout(Duration::from_secs(10), async { - loop { - match daemon_action_rx.recv().await { - Some(crate::chat::action::Action::SystemMessageAdded { text }) => return text, - Some(_) => (), - None => return String::new(), - } - } - }) - .await - .expect("test: an ended request must report back rather than leak"); - assert!( - reported.contains("was ended from this chat before the daemon answered"), - "{reported}" - ); - - silent_daemon.abort(); -} - -#[tokio::test] -async fn active_turn_logs_command_is_handled_without_enqueue() { - let mut backlog = std::collections::VecDeque::new(); - enqueue_input_message(&mut backlog, input_msg("normal one")); - let scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let msg = input_msg("/logs #99"); - let chat_session = session::ChatSession::new("p", "m"); - let provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - let mut chat_sessions = - crate::chat::sessions::ChatSessionsHandle::new(std::sync::Arc::new(tokio::sync::RwLock::new(Vec::new()))); - let session_rings = std::collections::HashMap::new(); - let mut reaped_log_archive = ReapedSessionLogArchive::default(); - let reap_policy = crate::chat::sessions::runtime::ReapPolicy::default(); - let tools_registry: Vec> = Vec::new(); - let daemon_config = Config::default(); - let (daemon_dispatcher, _daemon_action_rx) = dispatcher::ChatDispatcher::new(); - let daemon_control = DaemonControl { - config: &daemon_config, - dispatcher: &daemon_dispatcher, - redraw_tx: None, - }; - - let output = active_turn_local_command_output( - &msg, - &backlog, - &scheduler, - &chat_session, - &provider_turn_workers, - &mut chat_sessions, - &session_rings, - &mut reaped_log_archive, - &reap_policy, - &tools_registry, - daemon_control, - ) - .await - .expect("logs command output"); - - assert!(output.contains("Logs failed: no session #99"), "{output}"); - assert_eq!(backlog.len(), 1, "read-only logs command must not mutate backlog"); -} - -#[tokio::test] -async fn active_turn_kill_command_is_handled_without_enqueue() { - let mut backlog = std::collections::VecDeque::new(); - enqueue_input_message(&mut backlog, input_msg("normal one")); - let scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); - let msg = input_msg("/kill #99"); - let chat_session = session::ChatSession::new("p", "m"); - let provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); - let mut chat_sessions = - crate::chat::sessions::ChatSessionsHandle::new(std::sync::Arc::new(tokio::sync::RwLock::new(Vec::new()))); - let session_rings = std::collections::HashMap::new(); - let mut reaped_log_archive = ReapedSessionLogArchive::default(); - let reap_policy = crate::chat::sessions::runtime::ReapPolicy::default(); - let tools_registry: Vec> = Vec::new(); - let daemon_config = Config::default(); - let (daemon_dispatcher, _daemon_action_rx) = dispatcher::ChatDispatcher::new(); - let daemon_control = DaemonControl { - config: &daemon_config, - dispatcher: &daemon_dispatcher, - redraw_tx: None, - }; - - let output = active_turn_local_command_output( - &msg, - &backlog, - &scheduler, - &chat_session, - &provider_turn_workers, - &mut chat_sessions, - &session_rings, - &mut reaped_log_archive, - &reap_policy, - &tools_registry, - daemon_control, - ) - .await - .expect("kill command output"); - - assert!(output.contains("Kill failed: no session #99"), "{output}"); - assert_eq!(backlog.len(), 1, "explicit kill command must not mutate backlog"); -} - -#[test] -fn queued_input_scheduler_prefers_priority_over_older_normal() { - let mut backlog = std::collections::VecDeque::new(); - enqueue_input_message(&mut backlog, input_msg("normal one")); - enqueue_input_message(&mut backlog, input_msg("/priority urgent two")); - enqueue_input_message(&mut backlog, input_msg("normal three")); - - let first = pop_next_queued_input_message(&mut backlog) - .map(|queued| queued.msg) - .expect("priority first"); - let second = pop_next_queued_input_message(&mut backlog) - .map(|queued| queued.msg) - .expect("normal one second"); - let third = pop_next_queued_input_message(&mut backlog) - .map(|queued| queued.msg) - .expect("normal three third"); - - assert_eq!(first.content, "urgent two"); - assert_eq!(second.content, "normal one"); - assert_eq!(third.content, "normal three"); -} - -#[test] -fn cancelled_turn_rolls_back_legacy_history_user_message() { - let mut history = vec![ - ChatMessage::system("system"), - ChatMessage::user("previous question"), - ChatMessage::assistant("previous answer"), - ]; - let len_before = history.len(); - history.push(ChatMessage::user("cancelled long task")); - - rollback_cancelled_turn_history(&mut history, len_before); - - assert_eq!(history.len(), len_before); - assert!( - history.iter().all(|message| message.content != "cancelled long task"), - "cancelled turn must not leak into the next queued prompt" - ); -} - -#[test] -fn p4a_shutdown_cancelled_pending_turn_rolls_back_to_user_boundary() { - let mut history = vec![ - ChatMessage::system("system"), - ChatMessage::user("previous question"), - ChatMessage::assistant("previous answer"), - ]; - let len_before_user_turn = history.len(); - history.push(ChatMessage::user("pending provider turn")); - history.push(ChatMessage::assistant("partial assistant text")); - - rollback_cancelled_turn_history(&mut history, len_before_user_turn); - - assert_eq!(history.len(), len_before_user_turn); - assert!( - history - .iter() - .all(|message| message.content != "pending provider turn" && message.content != "partial assistant text"), - "shutdown cancellation must remove both the queued user turn and partial assistant output" - ); -} - -#[test] -fn queued_input_notice_is_single_line_and_bounded() { - let notice = format_queued_input_notice(" first line\nsecond\tline ", InputQueuePriority::Normal); - assert_eq!(notice, "queued > first line second line"); - - let long = format_queued_input_notice(&"x".repeat(220), InputQueuePriority::Normal); - assert!(long.starts_with("queued > ")); - assert!(long.ends_with('…')); - assert!(long.chars().count() <= "queued > ".chars().count() + 160); - - let priority = format_queued_input_notice("/now urgent", InputQueuePriority::Priority); - assert_eq!(priority, "priority queued > urgent"); -} - -#[test] -fn active_turn_local_notice_strips_priority_prefix() { - assert!(is_active_turn_local_command("/now /cost")); - assert!(is_active_turn_local_command("/workers")); - assert!(is_active_turn_local_command("/workers cancel w#1")); - assert!(is_active_turn_local_command("/sessions")); - assert!(is_active_turn_local_command("/now /logs #1")); - assert!(is_active_turn_local_command("/priority /kill 2")); - assert!(!is_active_turn_local_command("/bg create child")); - assert_eq!(format_active_turn_local_notice("/now /cost"), "local > /cost"); - assert_eq!( - format_active_turn_local_notice("/priority /queue status"), - "local > /queue status" - ); - assert_eq!( - format_active_turn_local_notice("/priority /workers cancel #2"), - "local > /workers cancel #2" - ); -} - -#[test] -fn session_to_session_switch_suppresses_attach_breadcrumb_spam() { - let meta = session_view(1); - let projection = - build_active_session_attach_projection(1, Some(&meta), vec!["tail".into()], vec!["ring".into()], false); - - assert!( - attach_breadcrumb_for_transition(false, &projection).is_some(), - "Main->Session entry keeps one breadcrumb" - ); - - let switches = [ - build_active_session_attach_projection(2, Some(&session_view(2)), Vec::new(), Vec::new(), false), - build_active_session_attach_projection(3, Some(&session_view(3)), Vec::new(), Vec::new(), false), - build_active_session_attach_projection(1, Some(&session_view(1)), Vec::new(), Vec::new(), false), - ]; - let emitted = switches - .iter() - .filter_map(|projection| attach_breadcrumb_for_transition(true, projection)) - .count(); - assert_eq!( - emitted, 0, - "Session->Session directional cycling must not append extra main-history breadcrumbs" - ); -} +include!("p3_directional_switch_tests/section_1.rs"); +include!("p3_directional_switch_tests/section_2.rs"); +include!("p3_directional_switch_tests/section_3.rs"); diff --git a/src/chat/tests/p3_directional_switch_tests/section_1.rs b/src/chat/tests/p3_directional_switch_tests/section_1.rs new file mode 100644 index 000000000..c65c07872 --- /dev/null +++ b/src/chat/tests/p3_directional_switch_tests/section_1.rs @@ -0,0 +1,1721 @@ +use super::*; +use crate::chat::sessions::id::SessionId; +use crate::chat::sessions::model::{ManagedKind, ManagedSessionView, ManagedStatus, SessionOrigin}; + +fn session_view(seq: u64) -> ManagedSessionView { + ManagedSessionView { + id: SessionId::from_run_id(&format!("p3-run-{seq}")), + seq, + kind: ManagedKind::Agent, + origin: SessionOrigin::User, + title: format!("session {seq}"), + status: ManagedStatus::Running, + created_at: chrono::Utc::now(), + updated_at: chrono::Utc::now(), + token_usage_records: Vec::new(), + } +} + +#[test] +fn directional_switch_focus_and_synthetic_attach_seq_match() { + let seq = 42; + let focus = + crate::chat::sessions::focus::optimistic_focus(crate::chat::sessions::focus::RoutingIntent::Attach { seq }); + + assert_eq!(focus, crate::chat::sessions::FocusTarget::Session { seq }); + assert_eq!(attach_command_for_seq(seq), "/attach 42"); +} + +#[test] +fn synthetic_ui_command_is_identified_for_hidden_echo_path() { + let mut msg = crate::channels::traits::ChannelMessage { + id: "synthetic".to_string(), + sender: SYNTHETIC_UI_COMMAND_SENDER.to_string(), + reply_target: "user".to_string(), + content: "/attach 42".to_string(), + channel: "terminal".to_string(), + timestamp: 0, + thread_ts: None, + chat_kind: crate::channels::traits::ChatKind::Dm, + chat_title: None, + sender_display: None, + mentioned_uuids: vec![], + mentioned: false, + is_group_hint: false, + sender_is_bot: false, + }; + + assert!(is_synthetic_ui_command(&msg)); + + msg.sender = "user".to_string(); + assert!(!is_synthetic_ui_command(&msg)); +} + +fn input_msg(content: &str) -> crate::channels::traits::ChannelMessage { + crate::channels::traits::ChannelMessage { + id: uuid::Uuid::new_v4().to_string(), + sender: "user".to_string(), + reply_target: "user".to_string(), + content: content.to_string(), + channel: "terminal".to_string(), + timestamp: 0, + thread_ts: None, + chat_kind: crate::channels::traits::ChatKind::Dm, + chat_title: None, + sender_display: None, + mentioned_uuids: vec![], + mentioned: false, + is_group_hint: false, + sender_is_bot: false, + } +} + +#[test] +fn priority_input_prefix_is_stripped_for_execution() { + let (priority, content) = input_priority_from_text(" /now inspect queue "); + assert_eq!(priority, InputQueuePriority::Priority); + assert_eq!(content, "inspect queue"); + + let (priority, content) = input_priority_from_text("!! urgent"); + assert_eq!(priority, InputQueuePriority::Priority); + assert_eq!(content, "urgent"); +} + +#[test] +fn active_turn_enqueue_reports_priority_and_strips_prefix() { + let mut backlog = std::collections::VecDeque::new(); + + let priority = enqueue_input_message_and_return_priority(&mut backlog, input_msg("/now inspect status")); + + assert_eq!(priority, InputQueuePriority::Priority); + let msg = pop_next_queued_input_message(&mut backlog) + .map(|queued| queued.msg) + .expect("queued priority message"); + assert_eq!(msg.content, "inspect status"); +} + +#[test] +fn input_backlog_status_counts_priority_messages() { + let mut backlog = std::collections::VecDeque::new(); + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("normal one"), 3); + enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("/priority urgent two"), 3); + enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("normal three"), 3); + + // the production status source: the scheduler the queue mirrors into + let status = scheduler.status().main_queue_status(); + + assert_eq!(status.queued, 3); + assert_eq!(status.priority, 1); +} + +#[test] +fn scheduler_mirror_projects_same_queue_status_as_backlog() { + let mut backlog = std::collections::VecDeque::new(); + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + + enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("normal one"), 5); + enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("/priority urgent two"), 5); + + assert_eq!(backlog.len(), scheduler.status().main_queue_status().queued); + assert_eq!(scheduler.status().main_queue_status().queued, 2); + assert_eq!(scheduler.status().main_queue_status().priority, 1); +} + +#[test] +fn scheduler_mirror_does_not_change_priority_pop_order() { + let mut backlog = std::collections::VecDeque::new(); + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + + enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("normal one"), 7); + enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("/priority urgent two"), 7); + enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("normal three"), 7); + + let first = pop_next_input_task_with_scheduler(&mut backlog, &mut scheduler) + .map(|task| task.msg) + .expect("priority first"); + let second = pop_next_input_task_with_scheduler(&mut backlog, &mut scheduler) + .map(|task| task.msg) + .expect("normal one second"); + let third = pop_next_input_task_with_scheduler(&mut backlog, &mut scheduler) + .map(|task| task.msg) + .expect("normal three third"); + + assert_eq!(first.content, "urgent two"); + assert_eq!(second.content, "normal one"); + assert_eq!(third.content, "normal three"); + assert_eq!( + scheduler.status().main_queue_status(), + crate::chat::action::MainQueueStatus::default() + ); +} + +#[test] +fn dequeued_input_task_id_is_reused_for_provider_start() { + let mut backlog = std::collections::VecDeque::new(); + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + + enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("normal provider turn"), 7); + let expected_id = backlog + .front() + .and_then(|queued| queued.turn_task_id) + .expect("queued task id"); + + let dequeued = pop_next_input_task_with_scheduler(&mut backlog, &mut scheduler).expect("dequeued input"); + + assert_eq!(dequeued.turn_task_id, Some(expected_id)); + assert_eq!( + scheduler.task(expected_id).unwrap().state, + crate::chat::turn_scheduler::TurnTaskState::Dispatched + ); + assert_eq!( + scheduler.status().main_queue_status(), + crate::chat::action::MainQueueStatus::default() + ); + + let provider_id = start_provider_turn_task(&mut scheduler, dequeued.turn_task_id, &dequeued.msg.content, 7) + .expect("provider task id"); + + assert_eq!(provider_id, expected_id); + assert_eq!( + scheduler.task(provider_id).unwrap().state, + crate::chat::turn_scheduler::TurnTaskState::Running + ); +} + +#[test] +fn queue_report_summarizes_backlog_with_preview() { + let mut backlog = std::collections::VecDeque::new(); + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("normal one"), 3); + enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("/priority urgent two"), 3); + let running = scheduler.enqueue("running turn", crate::chat::turn_scheduler::TurnPriority::Normal, 3); + scheduler.start_task(running).expect("running turn starts"); + + let report = format_input_backlog_report(&backlog, &scheduler, 8); + + assert!( + report.contains("Main queue: 2 queued (1 priority), 1 running."), + "{report}" + ); + assert!(report.contains("1. [normal] normal one"), "{report}"); + assert!(report.contains("2. [priority] urgent two"), "{report}"); +} + +#[tokio::test] +async fn active_turn_queue_command_is_handled_without_enqueue() { + let mut backlog = std::collections::VecDeque::new(); + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("normal one"), 3); + let running = scheduler.enqueue("active turn", crate::chat::turn_scheduler::TurnPriority::Normal, 3); + scheduler.start_task(running).expect("active turn starts"); + let msg = input_msg("/now /queue"); + let chat_session = session::ChatSession::new("p", "m"); + let provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + let mut chat_sessions = + crate::chat::sessions::ChatSessionsHandle::new(std::sync::Arc::new(tokio::sync::RwLock::new(Vec::new()))); + let session_rings = std::collections::HashMap::new(); + let mut reaped_log_archive = ReapedSessionLogArchive::default(); + let reap_policy = crate::chat::sessions::runtime::ReapPolicy::default(); + let tools_registry: Vec> = Vec::new(); + let daemon_config = Config::default(); + let (daemon_dispatcher, _daemon_action_rx) = dispatcher::ChatDispatcher::new(); + let daemon_control = DaemonControl { + config: &daemon_config, + dispatcher: &daemon_dispatcher, + redraw_tx: None, + }; + + let output = active_turn_local_command_output( + &msg, + &backlog, + &scheduler, + &chat_session, + &provider_turn_workers, + &mut chat_sessions, + &session_rings, + &mut reaped_log_archive, + &reap_policy, + &tools_registry, + daemon_control, + ) + .await + .expect("queue command output"); + + assert!( + output.contains("Main queue: 1 queued (0 priority), 1 running."), + "{output}" + ); + assert_eq!(backlog.len(), 1, "read-only queue command must not mutate backlog"); +} + +#[tokio::test] +async fn active_turn_cost_command_is_handled_without_enqueue() { + let mut backlog = std::collections::VecDeque::new(); + enqueue_input_message(&mut backlog, input_msg("normal one")); + let scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let msg = input_msg("/now /cost"); + let chat_session = session::ChatSession::new("p", "m"); + let provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + let mut chat_sessions = + crate::chat::sessions::ChatSessionsHandle::new(std::sync::Arc::new(tokio::sync::RwLock::new(Vec::new()))); + let session_rings = std::collections::HashMap::new(); + let mut reaped_log_archive = ReapedSessionLogArchive::default(); + let reap_policy = crate::chat::sessions::runtime::ReapPolicy::default(); + let tools_registry: Vec> = Vec::new(); + let daemon_config = Config::default(); + let (daemon_dispatcher, _daemon_action_rx) = dispatcher::ChatDispatcher::new(); + let daemon_control = DaemonControl { + config: &daemon_config, + dispatcher: &daemon_dispatcher, + redraw_tx: None, + }; + + let output = active_turn_local_command_output( + &msg, + &backlog, + &scheduler, + &chat_session, + &provider_turn_workers, + &mut chat_sessions, + &session_rings, + &mut reaped_log_archive, + &reap_policy, + &tools_registry, + daemon_control, + ) + .await + .expect("cost command output"); + + assert!(output.contains("Session cost:"), "{output}"); + assert!(output.contains("Turns:"), "{output}"); + assert_eq!(backlog.len(), 1, "read-only cost command must not mutate backlog"); +} + +#[tokio::test] +async fn active_turn_workers_command_is_handled_without_enqueue() { + let mut backlog = std::collections::VecDeque::new(); + enqueue_input_message(&mut backlog, input_msg("normal one")); + let msg = input_msg("/now /workers"); + let chat_session = session::ChatSession::new("p", "m"); + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let task_id = scheduler.enqueue("long worker", crate::chat::turn_scheduler::TurnPriority::Normal, 3); + scheduler.start_task(task_id).expect("task starts"); + let mut provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + provider_turn_workers + .start_from_task( + scheduler.task(task_id).expect("task snapshot"), + crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited, + ) + .expect("worker starts"); + let mut chat_sessions = + crate::chat::sessions::ChatSessionsHandle::new(std::sync::Arc::new(tokio::sync::RwLock::new(Vec::new()))); + let session_rings = std::collections::HashMap::new(); + let mut reaped_log_archive = ReapedSessionLogArchive::default(); + let reap_policy = crate::chat::sessions::runtime::ReapPolicy::default(); + let tools_registry: Vec> = Vec::new(); + let daemon_config = Config::default(); + let (daemon_dispatcher, _daemon_action_rx) = dispatcher::ChatDispatcher::new(); + let daemon_control = DaemonControl { + config: &daemon_config, + dispatcher: &daemon_dispatcher, + redraw_tx: None, + }; + + let output = active_turn_local_command_output( + &msg, + &backlog, + &scheduler, + &chat_session, + &provider_turn_workers, + &mut chat_sessions, + &session_rings, + &mut reaped_log_archive, + &reap_policy, + &tools_registry, + daemon_control, + ) + .await + .expect("workers command output"); + + assert!(output.contains("Main provider workers: 1 running"), "{output}"); + assert!(output.contains("w#1 task="), "{output}"); + assert!(output.contains("kind=foreground_awaited"), "{output}"); + assert!(output.contains("state=running"), "{output}"); + assert_eq!(backlog.len(), 1, "read-only workers command must not mutate backlog"); +} + +#[test] +fn workers_cancel_command_parser_accepts_worker_sequence_forms() { + assert_eq!( + parse_workers_cancel_command("/workers cancel w#7"), + ProviderWorkerCancelCommand::Cancel { sequence: 7 } + ); + assert_eq!( + parse_workers_cancel_command("/workers stop #8"), + ProviderWorkerCancelCommand::Cancel { sequence: 8 } + ); + assert_eq!( + parse_workers_cancel_command("/workers cancel 9"), + ProviderWorkerCancelCommand::Cancel { sequence: 9 } + ); + assert!(matches!( + parse_workers_cancel_command("/workers cancel nope"), + ProviderWorkerCancelCommand::Invalid(_) + )); + assert!(matches!( + parse_workers_cancel_command("/workers status"), + ProviderWorkerCancelCommand::NotCancel + )); +} + +#[tokio::test] +async fn active_turn_workers_cancel_command_marks_current_worker_cancelling_without_enqueue() { + let msg = input_msg("/now /workers cancel w#1"); + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let task_id = scheduler.enqueue("long worker", crate::chat::turn_scheduler::TurnPriority::Normal, 3); + scheduler.start_task(task_id).expect("task starts"); + let mut provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + provider_turn_workers + .start_from_task( + scheduler.task(task_id).expect("task snapshot"), + crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited, + ) + .expect("worker starts"); + + let (output, signal_cancel) = + active_turn_workers_cancel_output(&msg, &mut scheduler, &mut provider_turn_workers, Some(task_id)) + .expect("workers cancel output"); + + assert_eq!( + signal_cancel, + Some(ProviderWorkerCancelSignal::CancelRequested), + "current foreground worker should signal the active turn" + ); + assert!( + output.contains("Requested cancellation for provider worker w#1"), + "{output}" + ); + assert!(output.contains("state=cancelling"), "{output}"); + assert_eq!( + scheduler.task(task_id).unwrap().state, + crate::chat::turn_scheduler::TurnTaskState::Cancelling + ); + assert_eq!( + provider_turn_workers.worker(task_id).unwrap().state, + crate::chat::turn_worker::ProviderTurnWorkerState::Cancelling + ); +} + +#[tokio::test] +async fn workers_cancel_command_targets_detached_worker_without_cancelling_peer() { + let msg = input_msg("/workers cancel w#2"); + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let first = scheduler.enqueue("first detached", crate::chat::turn_scheduler::TurnPriority::Normal, 3); + let second = scheduler.enqueue("second detached", crate::chat::turn_scheduler::TurnPriority::Normal, 3); + scheduler.start_task(first).expect("first task starts"); + scheduler.start_task(second).expect("second task starts"); + let mut provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + provider_turn_workers + .start_from_task( + scheduler.task(first).expect("first task snapshot"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("first worker starts"); + provider_turn_workers + .start_from_task( + scheduler.task(second).expect("second task snapshot"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("second worker starts"); + + let (output, signal_cancel) = + active_turn_workers_cancel_output(&msg, &mut scheduler, &mut provider_turn_workers, Some(first)) + .expect("workers cancel output"); + + assert!( + output.contains("Requested cancellation for provider worker w#2"), + "{output}" + ); + assert!(output.contains("kind=detached"), "{output}"); + assert_eq!( + signal_cancel, + Some(ProviderWorkerCancelSignal::CancelProviderTurn { task_id: second }), + "detached worker cancellation must target the requested task id" + ); + assert_eq!( + scheduler.task(first).expect("first task").state, + crate::chat::turn_scheduler::TurnTaskState::Running, + "peer detached task must stay running" + ); + assert_eq!( + scheduler.task(second).expect("second task").state, + crate::chat::turn_scheduler::TurnTaskState::Cancelling, + "requested detached task should enter cancelling" + ); + assert_eq!( + provider_turn_workers.worker(first).expect("first worker").state, + crate::chat::turn_worker::ProviderTurnWorkerState::Running, + "peer detached worker must stay running" + ); + assert_eq!( + provider_turn_workers.worker(second).expect("second worker").state, + crate::chat::turn_worker::ProviderTurnWorkerState::Cancelling, + "requested detached worker should enter cancelling" + ); +} + +#[test] +fn workers_cancel_command_targets_detached_worker_from_outer_loop() { + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let first = scheduler.enqueue("first detached", crate::chat::turn_scheduler::TurnPriority::Normal, 3); + let second = scheduler.enqueue("second detached", crate::chat::turn_scheduler::TurnPriority::Normal, 3); + scheduler.start_task(first).expect("first task starts"); + scheduler.start_task(second).expect("second task starts"); + let mut provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + provider_turn_workers + .start_from_task( + scheduler.task(first).expect("first task snapshot"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("first worker starts"); + provider_turn_workers + .start_from_task( + scheduler.task(second).expect("second task snapshot"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("second worker starts"); + + let (output, signal_cancel) = provider_workers_cancel_output_for_input( + &input_msg("/workers cancel w#2"), + "/workers cancel w#2", + &mut scheduler, + &mut provider_turn_workers, + None, + ) + .expect("workers cancel output"); + + assert!( + output.contains("Requested cancellation for provider worker w#2"), + "{output}" + ); + assert_eq!( + signal_cancel, + Some(ProviderWorkerCancelSignal::CancelProviderTurn { task_id: second }), + "outer-loop worker cancel must target the requested detached task" + ); + assert_eq!( + scheduler.task(first).expect("first task").state, + crate::chat::turn_scheduler::TurnTaskState::Running, + "peer detached task must stay running" + ); + assert_eq!( + scheduler.task(second).expect("second task").state, + crate::chat::turn_scheduler::TurnTaskState::Cancelling, + "requested detached task should enter cancelling" + ); +} + +#[tokio::test] +async fn p4a_active_turn_event_pump_preserves_cancel_local_and_enqueue_order() { + let first_msg = input_msg("/workers cancel w#1"); + let (tx, mut input_rx) = mpsc::channel(4); + tx.send(input_msg("/queue")).await.expect("send queue command"); + tx.send(input_msg("follow up turn")).await.expect("send follow-up turn"); + drop(tx); + let mut outputs = Vec::::new(); + let mut emit = |text: &str| outputs.push(text.to_string()); + let mut backlog = std::collections::VecDeque::new(); + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let task_id = scheduler.enqueue( + "active provider turn", + crate::chat::turn_scheduler::TurnPriority::Normal, + 3, + ); + scheduler.start_task(task_id).expect("task starts"); + let mut provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + provider_turn_workers + .start_from_task( + scheduler.task(task_id).expect("task snapshot"), + crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited, + ) + .expect("worker starts"); + let (chat_dispatcher, _action_rx) = dispatcher::ChatDispatcher::new(); + let chat_session = session::ChatSession::new("p", "m"); + let mut chat_sessions = + crate::chat::sessions::ChatSessionsHandle::new(std::sync::Arc::new(tokio::sync::RwLock::new(Vec::new()))); + let session_rings = std::collections::HashMap::new(); + let mut reaped_log_archive = ReapedSessionLogArchive::default(); + let reap_policy = crate::chat::sessions::runtime::ReapPolicy::default(); + let tools_registry: Vec> = Vec::new(); + let daemon_config = Config::default(); + let (daemon_dispatcher, _daemon_action_rx) = dispatcher::ChatDispatcher::new(); + let daemon_control = DaemonControl { + config: &daemon_config, + dispatcher: &daemon_dispatcher, + redraw_tx: None, + }; + + process_active_turn_input_batch( + first_msg, + &mut emit, + &mut input_rx, + &mut backlog, + &mut scheduler, + &mut provider_turn_workers, + Some(task_id), + &chat_dispatcher, + &chat_session, + &mut chat_sessions, + &session_rings, + &mut reaped_log_archive, + &reap_policy, + &tools_registry, + daemon_control, + ) + .await; + + assert_eq!(outputs.len(), 2, "cancel and /queue should emit local output"); + assert!( + outputs[0].contains("Requested cancellation for provider worker w#1"), + "{}", + outputs[0] + ); + assert!( + outputs[1].contains("Main queue: 0 queued (0 priority), 0 running."), + "{}", + outputs[1] + ); + assert_eq!(backlog.len(), 1, "ordinary input after local commands remains queued"); + assert_eq!(backlog.front().expect("queued follow-up").msg.content, "follow up turn"); + assert_eq!( + scheduler.task(task_id).unwrap().state, + crate::chat::turn_scheduler::TurnTaskState::Cancelling + ); + assert_eq!(scheduler.status().main_queue_status().queued, 1); +} + +/// Build the input message a daemon assignment arrives as. +fn assigned_msg(id: &str, task: &str, disposition: &str) -> crate::channels::traits::ChannelMessage { + let pulled = crate::runtime::tasks_cli::PulledAssignment { + assignment_id: id.to_string(), + session_id: "sess".to_string(), + task: task.to_string(), + disposition: disposition.to_string(), + deliveries: 1, + created_at_unix_ms: 0, + work_id: "w1".to_string(), + origin_channel: "wacli".to_string(), + origin_ref: Some("3d1a4f5b".to_string()), + }; + crate::chat::sessions::assignment::assignment_message( + &pulled, + crate::chat::sessions::assignment::Disposition::from_wire(disposition), + ) +} + +/// Feed one assignment into a chat with a turn in flight, and report what +/// the backlog and the running task look like afterwards. +async fn dispatch_assignment_during_a_turn( + disposition: &str, +) -> ( + Vec<(InputQueuePriority, String)>, + crate::chat::turn_scheduler::TurnTaskState, +) { + let msg = assigned_msg("assign-1", "count the crates", disposition); + let (tx, mut input_rx) = mpsc::channel::(4); + drop(tx); + // The output sink is read back: an assignment must never emit a local + // command answer, which is what it would mean for it to be handled as + // one instead of run as a turn. + let mut outputs = Vec::::new(); + let mut emit = |text: &str| outputs.push(text.to_string()); + let mut backlog = std::collections::VecDeque::new(); + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let task_id = scheduler.enqueue( + "active provider turn", + crate::chat::turn_scheduler::TurnPriority::Normal, + 3, + ); + scheduler.start_task(task_id).expect("task starts"); + let mut provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + provider_turn_workers + .start_from_task( + scheduler.task(task_id).expect("task snapshot"), + crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited, + ) + .expect("worker starts"); + let (chat_dispatcher, _action_rx) = dispatcher::ChatDispatcher::new(); + let chat_session = session::ChatSession::new("p", "m"); + let mut chat_sessions = + crate::chat::sessions::ChatSessionsHandle::new(std::sync::Arc::new(tokio::sync::RwLock::new(Vec::new()))); + let session_rings = std::collections::HashMap::new(); + let mut reaped_log_archive = ReapedSessionLogArchive::default(); + let reap_policy = crate::chat::sessions::runtime::ReapPolicy::default(); + let tools_registry: Vec> = Vec::new(); + let daemon_config = Config::default(); + let (daemon_dispatcher, _daemon_action_rx) = dispatcher::ChatDispatcher::new(); + let daemon_control = DaemonControl { + config: &daemon_config, + dispatcher: &daemon_dispatcher, + redraw_tx: None, + }; + + process_active_turn_input_batch( + msg, + &mut emit, + &mut input_rx, + &mut backlog, + &mut scheduler, + &mut provider_turn_workers, + Some(task_id), + &chat_dispatcher, + &chat_session, + &mut chat_sessions, + &session_rings, + &mut reaped_log_archive, + &reap_policy, + &tools_registry, + daemon_control, + ) + .await; + + assert!( + outputs.is_empty(), + "an assignment must be run as a turn, not answered as a local command: {outputs:?}" + ); + let queued = backlog + .iter() + .map(|entry| (entry.priority, entry.msg.content.clone())) + .collect::>(); + let state = scheduler.task(task_id).expect("task snapshot").state; + (queued, state) +} + +/// The three dispositions differ in exactly two observable ways: where the +/// work lands in the queue, and whether the turn in flight survives. +#[tokio::test] +async fn each_assignment_disposition_reaches_the_path_it_names() { + let (queued, state) = dispatch_assignment_during_a_turn("queue").await; + assert_eq!(queued.len(), 1); + assert_eq!(queued[0].0, InputQueuePriority::Normal, "queue must not jump the queue"); + assert_eq!( + queued[0].1, "count the crates", + "the model must see the task, not a prefix" + ); + assert_eq!( + state, + crate::chat::turn_scheduler::TurnTaskState::Running, + "queue must leave the turn in flight alone" + ); + + let (queued, state) = dispatch_assignment_during_a_turn("steer").await; + assert_eq!(queued.len(), 1); + assert_eq!( + queued[0].0, + InputQueuePriority::Priority, + "steer must go in front of the backlog" + ); + assert_eq!(queued[0].1, "count the crates"); + assert_eq!( + state, + crate::chat::turn_scheduler::TurnTaskState::Running, + "steer inserts into the turn in flight; it must not destroy it" + ); + + let (queued, state) = dispatch_assignment_during_a_turn("interrupt").await; + assert_eq!(queued.len(), 1); + assert_eq!(queued[0].0, InputQueuePriority::Priority); + assert_eq!(queued[0].1, "count the crates"); + assert_eq!( + state, + crate::chat::turn_scheduler::TurnTaskState::Cancelling, + "interrupt must end the turn in flight before the assignment runs" + ); +} + +/// A word this chat cannot read is never permission to destroy a turn. +#[tokio::test] +async fn an_unknown_disposition_never_ends_the_turn_in_flight() { + let (queued, state) = dispatch_assignment_during_a_turn("obliterate").await; + assert_eq!(queued.len(), 1); + assert_eq!(queued[0].0, InputQueuePriority::Normal); + assert_eq!( + state, + crate::chat::turn_scheduler::TurnTaskState::Running, + "an unrecognised disposition degrades to queue, never to interrupt" + ); +} + +/// Ordinary typed input must not acquire assignment behaviour. +#[tokio::test] +async fn ordinary_input_during_a_turn_still_only_queues() { + let msg = input_msg("just a message"); + assert!(crate::chat::sessions::assignment::delivered(&msg).is_none()); +} + +#[tokio::test] +async fn p4a_active_turn_quit_is_queued_for_delayed_exit() { + let mut outputs = Vec::::new(); + let mut emit = |text: &str| outputs.push(text.to_string()); + let mut backlog = std::collections::VecDeque::new(); + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let task_id = scheduler.enqueue( + "active provider turn", + crate::chat::turn_scheduler::TurnPriority::Normal, + 3, + ); + scheduler.start_task(task_id).expect("task starts"); + let mut provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + provider_turn_workers + .start_from_task( + scheduler.task(task_id).expect("task snapshot"), + crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited, + ) + .expect("worker starts"); + let (chat_dispatcher, _action_rx) = dispatcher::ChatDispatcher::new(); + let chat_session = session::ChatSession::new("p", "m"); + let mut chat_sessions = + crate::chat::sessions::ChatSessionsHandle::new(std::sync::Arc::new(tokio::sync::RwLock::new(Vec::new()))); + let session_rings = std::collections::HashMap::new(); + let mut reaped_log_archive = ReapedSessionLogArchive::default(); + let reap_policy = crate::chat::sessions::runtime::ReapPolicy::default(); + let tools_registry: Vec> = Vec::new(); + let daemon_config = Config::default(); + let (daemon_dispatcher, _daemon_action_rx) = dispatcher::ChatDispatcher::new(); + let daemon_control = DaemonControl { + config: &daemon_config, + dispatcher: &daemon_dispatcher, + redraw_tx: None, + }; + + process_active_turn_input_message( + input_msg("/exit"), + &mut emit, + &mut backlog, + &mut scheduler, + &mut provider_turn_workers, + Some(task_id), + &chat_dispatcher, + &chat_session, + &mut chat_sessions, + &session_rings, + &mut reaped_log_archive, + &reap_policy, + &tools_registry, + daemon_control, + ) + .await; + + assert!(outputs.is_empty(), "/exit during an active turn is not a local command"); + assert_eq!(backlog.len(), 1, "/exit should wait behind the active turn"); + assert_eq!(backlog.front().expect("queued exit").msg.content, "/exit"); + assert_eq!(scheduler.status().main_queue_status().queued, 1); + assert_eq!( + scheduler.task(task_id).unwrap().state, + crate::chat::turn_scheduler::TurnTaskState::Running, + "delayed exit must not cancel or complete the active provider turn" + ); +} + +#[test] +fn persistence_dependent_commands_cover_terminal_session_contract() { + for command in [ + "/exit", + "/quit", + "/apply", + "/cost", + "/export", + "/new", + "/clear", + "/resume", + "/resume last", + "/branch 1", + "/rewind 0", + "/priority /cost", + ] { + assert!(is_persistence_dependent_command(command), "{command}"); + } + for command in ["hello", "/help", "/workers", "/queue status"] { + assert!(!is_persistence_dependent_command(command), "{command}"); + } +} + +#[test] +fn new_session_has_fresh_identity_and_empty_session_scoped_ledgers() { + let first = fresh_chat_session("provider-a", "model-a", commands::ChatMode::Plan); + let second = fresh_chat_session("provider-a", "model-a", commands::ChatMode::Plan); + + assert_ne!(first.id, second.id); + assert!(first.title.is_empty(), "expected an empty value"); + assert!(first.turns.is_empty()); + assert!(first.token_usage_records.is_empty(), "expected an empty value"); + assert!(first.background_sessions.is_empty(), "expected an empty value"); + assert_eq!(first.provider, "provider-a"); + assert_eq!(first.model, "model-a"); + assert_eq!(first.mode, commands::ChatMode::Plan); +} + +#[cfg(feature = "terminal-tui")] +#[test] +fn p4a_input_close_keeps_event_pump_alive_until_pending_turn_finishes() { + assert!( + should_continue_event_pump_after_input_closed(1), + "closed input should not terminate the event pump while a detached Redux turn is pending" + ); + assert!( + !should_continue_event_pump_after_input_closed(0), + "with no pending Redux turn, closed input can end the outer loop" + ); +} + +#[cfg(feature = "terminal-tui")] +#[test] +fn p4a_deferred_resume_waits_for_queued_visible_input_from_current_session() { + let mut backlog = std::collections::VecDeque::new(); + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + let mut deferred_resume = std::collections::VecDeque::from(["session-b".to_string()]); + let session_a_history_len = 4; + + enqueue_input_message_with_scheduler( + &mut backlog, + &mut scheduler, + input_msg("queued for session A"), + session_a_history_len, + ); + + assert!( + !should_drain_deferred_resume_after_visible_inputs(0, &backlog, &workers), + "deferred resume must not run before queued visible input is dequeued" + ); + assert_eq!( + deferred_resume.front().map(String::as_str), + Some("session-b"), + "resume request remains deferred while session-A input is pending" + ); + + let next = pop_next_visible_input_task_with_scheduler( + &mut backlog, + &mut scheduler, + &workers, + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + 1, + ) + .expect("queued input"); + assert_eq!(next.msg.content, "queued for session A"); + let task_id = next.turn_task_id.expect("scheduler task id"); + let task = scheduler.task(task_id).expect("queued task snapshot"); + assert_eq!( + task.history_base_len, session_a_history_len, + "queued input keeps the pre-resume session-A history boundary" + ); + assert_eq!( + task.state, + crate::chat::turn_scheduler::TurnTaskState::Dispatched, + "queued input is dispatched before deferred resume can drain" + ); + + assert!(should_drain_deferred_resume_after_visible_inputs(0, &backlog, &workers)); + assert_eq!(deferred_resume.pop_front().as_deref(), Some("session-b")); +} + +#[test] +fn workers_report_lists_only_active_worker_rows() { + let status = crate::chat::action::ProviderWorkerStatus { + running: 1, + cancelling: 0, + awaiting_commit: 0, + finalized_payloads: 1, + finalized_total_tokens: 1_250, + oldest_started_at_ms: Some(chrono::Utc::now().timestamp_millis().saturating_sub(1_000)), + rows: vec![ + crate::chat::action::ProviderWorkerStatusRow { + task_id: 1, + sequence: 1, + kind: crate::chat::action::ProviderWorkerRowKind::ForegroundAwaited, + state: crate::chat::action::ProviderWorkerRowState::Running, + started_at_ms: chrono::Utc::now().timestamp_millis().saturating_sub(1_000), + finalized_total_tokens: None, + completion_ready: false, + recent_tool_call: None, + }, + crate::chat::action::ProviderWorkerStatusRow { + task_id: 2, + sequence: 2, + kind: crate::chat::action::ProviderWorkerRowKind::Detached, + state: crate::chat::action::ProviderWorkerRowState::Committed, + started_at_ms: chrono::Utc::now().timestamp_millis().saturating_sub(9_000), + finalized_total_tokens: Some(1_250), + completion_ready: true, + recent_tool_call: None, + }, + ], + }; + + let report = format_provider_worker_report(&status); + + assert!( + report.contains("1 finalized payloads, 1.2k finalized tokens"), + "report should retain finalized aggregate: {report}" + ); + assert!(report.contains("- w#1 task=1"), "active row should be listed: {report}"); + assert!( + report.contains("completion=pending"), + "active row should expose completion readiness: {report}" + ); + assert!( + !report.contains("- w#2 task=2"), + "completed row should not stay in the active worker list: {report}" + ); +} + +/// Backpressure contract for the provider-turn lifecycle channel. +/// +/// The channel is bounded, so the guarantee under load is: a producer that +/// finds it full is *slowed down* (its `send` parks until the chat loop +/// drains) rather than dropping events or panicking, and every event +/// eventually arrives in order. +#[cfg(feature = "terminal-tui")] +#[tokio::test] +async fn provider_turn_lifecycle_channel_backpressures_instead_of_dropping() { + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let task_id = scheduler.enqueue("turn", crate::chat::turn_scheduler::TurnPriority::Normal, 1); + + let (tx, mut rx) = + mpsc::channel::(PROVIDER_TURN_LIFECYCLE_CHANNEL_CAPACITY); + + // Fill the queue exactly to capacity. + for lease_id in 0..PROVIDER_TURN_LIFECYCLE_CHANNEL_CAPACITY as u64 { + tx.try_send(dispatcher::ProviderTurnLifecycleEvent::Started { task_id, lease_id }) + .expect("channel accepts events up to its capacity"); + } + assert!( + tx.try_send(dispatcher::ProviderTurnLifecycleEvent::Started { + task_id, + lease_id: u64::MAX, + }) + .is_err(), + "channel must be bounded at PROVIDER_TURN_LIFECYCLE_CHANNEL_CAPACITY" + ); + + // The overflow send parks; it neither resolves nor discards the event. + let overflow = tx.send(dispatcher::ProviderTurnLifecycleEvent::Exited { + task_id, + lease_id: u64::MAX, + }); + tokio::pin!(overflow); + assert!( + tokio::time::timeout(std::time::Duration::from_millis(100), &mut overflow) + .await + .is_err(), + "a full queue must park the producer rather than complete the send" + ); + + // Draining frees a permit, which wakes the parked producer. + let first = rx.recv().await.expect("queued event is delivered"); + assert!(matches!( + first, + dispatcher::ProviderTurnLifecycleEvent::Started { lease_id: 0, .. } + )); + tokio::time::timeout(std::time::Duration::from_secs(5), overflow) + .await + .expect("parked producer resumes once the consumer drains") + .expect("receiver is still alive"); + + // Nothing was lost or reordered: the remaining fillers arrive in order, + // followed by the event that had been waiting on backpressure. + for expected_lease in 1..PROVIDER_TURN_LIFECYCLE_CHANNEL_CAPACITY as u64 { + match rx.recv().await.expect("queued event is delivered") { + dispatcher::ProviderTurnLifecycleEvent::Started { lease_id, .. } => { + assert_eq!(lease_id, expected_lease); + } + other => panic!("unexpected event while draining: {other:?}"), + } + } + match rx.recv().await.expect("backpressured event is delivered") { + dispatcher::ProviderTurnLifecycleEvent::Exited { lease_id, .. } => { + assert_eq!(lease_id, u64::MAX); + } + other => panic!("unexpected trailing event: {other:?}"), + } +} + +#[cfg(feature = "terminal-tui")] +#[test] +fn non_current_provider_completion_is_retained_and_marks_ready() { + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let first = scheduler.enqueue("first", crate::chat::turn_scheduler::TurnPriority::Normal, 1); + let second = scheduler.enqueue("second", crate::chat::turn_scheduler::TurnPriority::Normal, 1); + scheduler.start_task(first).expect("first starts"); + scheduler.start_task(second).expect("second starts"); + + let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + workers + .start_from_task( + scheduler.task(first).expect("first task"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("first worker starts"); + workers + .start_from_task( + scheduler.task(second).expect("second task"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("second worker starts"); + workers + .record_execution_started(second, 42) + .expect("second worker execution starts"); + + let (_tx, mut lifecycle_rx) = tokio::sync::mpsc::channel(PROVIDER_TURN_LIFECYCLE_CHANNEL_CAPACITY); + let mut lifecycle_open = true; + let mut pending = std::collections::HashMap::new(); + let completion = ProviderTurnCompletionEvent { + task_id: second, + outcome: Some(dispatcher::TurnOutcomeKind::Completed { + final_text: "second done".to_string(), + reasoning: String::new(), + }), + usage: crate::llm::route_decision::TokenUsage { + total_tokens: Some(42), + ..Default::default() + }, + }; + + let route = route_provider_completion_event( + &mut lifecycle_rx, + &mut lifecycle_open, + &mut workers, + &mut pending, + Some(first), + completion, + ); + + assert!(route.is_none(), "a non-current completion is retained as pending"); + assert!( + pending.contains_key(&second), + "non-current completion should be retained" + ); + let rows = workers.snapshot(); + let second_row = rows + .iter() + .find(|row| row.task_id == second) + .expect("second worker snapshot"); + assert!( + second_row.completion_ready, + "retained completion should still mark the worker completion-ready" + ); + assert!( + !rows + .iter() + .find(|row| row.task_id == first) + .expect("first worker snapshot") + .completion_ready, + "uncompleted worker should remain pending" + ); +} + +#[cfg(feature = "terminal-tui")] +#[test] +fn current_provider_completion_is_routed_without_retaining_pending() { + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let task_id = scheduler.enqueue("current", crate::chat::turn_scheduler::TurnPriority::Normal, 1); + scheduler.start_task(task_id).expect("task starts"); + + let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + workers + .start_from_task( + scheduler.task(task_id).expect("task snapshot"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("worker starts"); + workers + .record_execution_started(task_id, 43) + .expect("worker execution starts"); + + let (_tx, mut lifecycle_rx) = tokio::sync::mpsc::channel(PROVIDER_TURN_LIFECYCLE_CHANNEL_CAPACITY); + let mut lifecycle_open = true; + let mut pending = std::collections::HashMap::new(); + let completion = ProviderTurnCompletionEvent { + task_id, + outcome: Some(dispatcher::TurnOutcomeKind::Completed { + final_text: "current done".to_string(), + reasoning: String::new(), + }), + usage: crate::llm::route_decision::TokenUsage { + total_tokens: Some(43), + ..Default::default() + }, + }; + + let route = route_provider_completion_event( + &mut lifecycle_rx, + &mut lifecycle_open, + &mut workers, + &mut pending, + Some(task_id), + completion, + ); + + let completion = route.expect("current completion must not be retained as pending"); + assert_eq!(completion.task_id, task_id); + assert_eq!(completion.usage.total_tokens, Some(43)); + assert!(pending.is_empty(), "current completion should bypass pending map"); + assert!( + workers + .snapshot() + .into_iter() + .find(|row| row.task_id == task_id) + .expect("worker snapshot") + .completion_ready, + "current completion should still mark the worker completion-ready" + ); +} + +#[cfg(feature = "terminal-tui")] +#[test] +fn p4a_outer_completion_route_retains_event_for_pending_redux_finalizer() { + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let task_id = scheduler.enqueue("redux pending", crate::chat::turn_scheduler::TurnPriority::Normal, 1); + scheduler.start_task(task_id).expect("task starts"); + let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + workers + .start_from_task( + scheduler.task(task_id).expect("task snapshot"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("worker starts"); + workers + .record_execution_started(task_id, 60) + .expect("worker execution starts"); + let (_tx, mut lifecycle_rx) = tokio::sync::mpsc::channel(PROVIDER_TURN_LIFECYCLE_CHANNEL_CAPACITY); + let mut lifecycle_open = true; + let mut pending = std::collections::HashMap::new(); + let (chat_dispatcher, _action_rx) = dispatcher::ChatDispatcher::new(); + let completion = ProviderTurnCompletionEvent { + task_id, + outcome: Some(dispatcher::TurnOutcomeKind::Completed { + final_text: "done".to_string(), + reasoning: String::new(), + }), + usage: crate::llm::route_decision::TokenUsage { + total_tokens: Some(9), + ..Default::default() + }, + }; + + let route = route_provider_completion_event_and_publish( + &mut lifecycle_rx, + &mut lifecycle_open, + &mut workers, + &mut pending, + None, + completion, + &chat_dispatcher, + ); + + assert!(route.is_none(), "a non-current completion is retained as pending"); + let retained = pending.get(&task_id).expect("outer completion retained by task id"); + assert_eq!(retained.usage.total_tokens, Some(9)); + assert!( + workers + .snapshot() + .into_iter() + .find(|row| row.task_id == task_id) + .expect("worker snapshot") + .completion_ready, + "outer route still marks worker completion-ready before finalizer" + ); +} + +#[cfg(feature = "terminal-tui")] +#[test] +fn p4a_completion_event_and_finalizer_chain_commits_ready_turn() { + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let task_id = scheduler.enqueue( + "redux pending finalizer", + crate::chat::turn_scheduler::TurnPriority::Normal, + 1, + ); + scheduler.start_task(task_id).expect("task starts"); + let mut coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); + coordinator + .register_task(scheduler.task(task_id).expect("task snapshot")) + .expect("history task registers"); + let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + workers + .start_from_task( + scheduler.task(task_id).expect("task snapshot"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("worker starts"); + workers + .record_execution_started(task_id, 64) + .expect("worker execution starts"); + let (_tx, mut lifecycle_rx) = tokio::sync::mpsc::channel(PROVIDER_TURN_LIFECYCLE_CHANNEL_CAPACITY); + let mut lifecycle_open = true; + let mut pending = std::collections::HashMap::new(); + let (chat_dispatcher, _action_rx) = dispatcher::ChatDispatcher::new(); + + let route = route_provider_completion_event_and_publish( + &mut lifecycle_rx, + &mut lifecycle_open, + &mut workers, + &mut pending, + None, + ProviderTurnCompletionEvent { + task_id, + outcome: Some(dispatcher::TurnOutcomeKind::Completed { + final_text: "ready finalizer".to_string(), + reasoning: String::new(), + }), + usage: crate::llm::route_decision::TokenUsage { + total_tokens: Some(64), + ..Default::default() + }, + }, + &chat_dispatcher, + ); + assert!(route.is_none(), "a non-current completion is retained as pending"); + + let completion = pending + .remove(&task_id) + .expect("ready completion retained for finalizer"); + let tools: Vec> = Vec::new(); + let plan = provider_turn_terminal_plan_from_completion( + ResolvedProviderTurnCompletion { + outcome: completion.outcome, + usage: completion.usage, + }, + 1, + &tools, + ); + let mut queue = std::collections::VecDeque::new(); + enqueue_provider_turn_finalizer_event(&mut queue, Some(task_id), plan); + + let results = drain_provider_turn_finalizer_events_and_publish( + &mut scheduler, + &mut coordinator, + &mut workers, + &mut queue, + &chat_dispatcher, + ); + + assert_eq!(results.len(), 1); + assert_eq!(results[0].terminal_status, "completed"); + assert!(results[0].finalized); + assert_eq!( + scheduler.task(task_id).unwrap().state, + crate::chat::turn_scheduler::TurnTaskState::Completed + ); + let row = workers + .snapshot() + .into_iter() + .find(|row| row.task_id == task_id) + .expect("worker snapshot retained"); + assert_eq!(row.finalized_total_tokens, Some(64)); + assert!(matches!( + row.state, + crate::chat::turn_worker::ProviderTurnWorkerState::Committed + )); +} + +#[cfg(feature = "terminal-tui")] +#[test] +fn p4b1_ready_signal_is_noop_until_ordered_commit_dispatches_save() { + use crate::chat::action::Action; + use crate::chat::state::{ChatState, Effect}; + use std::sync::Arc; + + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let task_id = scheduler.enqueue("ordered commit", crate::chat::turn_scheduler::TurnPriority::Normal, 0); + scheduler.start_task(task_id).expect("task starts"); + let sequence = scheduler.task(task_id).expect("task snapshot").sequence; + let mut state = ChatState::new(Arc::from("provider"), Arc::from("model"), CancellationToken::new()); + let _ = state.reduce(Action::StartLLMTurn { + provider_turn_task_id: Some(task_id), + provider_turn_sequence: Some(sequence), + draft_id: "draft-p4b1".to_string(), + history: Vec::new(), + compaction_guard_history: None, + compaction_config: None, + cancel: CancellationToken::new(), + turn_spawn_ctx: None, + turn_message_send_ctx: None, + routing_input: None, + turn_binding: None, + }); + + let ready_effects = state.reduce(Action::ProviderTurnReadyForCommit { + draft_id: "draft-p4b1".to_string(), + final_text: "answer".to_string(), + reasoning: "reason".to_string(), + }); + assert!(ready_effects.is_empty(), "ready signal must not emit SaveSession"); + assert!( + state.stream.primary_streaming_draft().is_some(), + "ready signal must leave reducer draft open until ordered commit" + ); + + let (dispatcher, mut rx) = dispatcher::ChatDispatcher::new(); + dispatch_ordered_provider_turn_commit( + &dispatcher, + task_id, + "draft-p4b1", + "question", + "answer", + "reason", + false, + true, + ) + .expect("ordered history dispatch"); + + let user = rx.try_recv().expect("ordered RecordUserTurn action"); + match user { + Action::RecordUserTurn(content) => { + assert_eq!(content, "question"); + let effects = state.reduce(Action::RecordUserTurn(content)); + assert!( + !effects.iter().any(|effect| matches!(effect, Effect::SaveSession(_))), + "RecordUserTurn alone must not save before terminal commit" + ); + } + other => panic!("expected ordered RecordUserTurn, got {other:?}"), + } + + let record = rx.try_recv().expect("ordered RecordAssistantTurn action"); + match record { + Action::RecordAssistantTurn { task_id: seen, content } => { + assert_eq!(seen, Some(task_id)); + assert_eq!(content, "answer"); + let effects = state.reduce(Action::RecordAssistantTurn { task_id: seen, content }); + assert!( + !effects.iter().any(|effect| matches!(effect, Effect::SaveSession(_))), + "RecordAssistantTurn alone must not save before terminal commit" + ); + } + other => panic!("expected ordered RecordAssistantTurn, got {other:?}"), + } + + let terminal = rx.try_recv().expect("ordered StreamCompleted action"); + match terminal { + Action::StreamCompleted { + draft_id, + final_text, + reasoning, + } => { + assert_eq!(draft_id, "draft-p4b1"); + assert_eq!(final_text, "answer"); + assert_eq!(reasoning, "reason"); + let effects = state.reduce(Action::StreamCompleted { + draft_id, + final_text, + reasoning, + }); + assert!( + effects.iter().any(|effect| matches!(effect, Effect::SaveSession(_))), + "SaveSession must be emitted only by ordered StreamCompleted" + ); + } + other => panic!("expected ordered StreamCompleted, got {other:?}"), + } + assert!( + rx.try_recv().is_err(), + "ordered commit helper should emit exactly record + terminal actions" + ); +} + +#[cfg(feature = "terminal-tui")] +#[test] +fn p4b1_failed_and_cancelled_skip_do_not_emit_persistence_actions() { + use crate::chat::action::Action; + + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let failed = scheduler.enqueue("failed", crate::chat::turn_scheduler::TurnPriority::Normal, 0); + let cancelled = scheduler.enqueue("cancelled", crate::chat::turn_scheduler::TurnPriority::Normal, 0); + scheduler.start_task(failed).expect("failed task starts"); + scheduler.start_task(cancelled).expect("cancelled task starts"); + scheduler.request_cancel(cancelled).expect("cancel request accepted"); + let mut coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); + coordinator + .register_task(scheduler.task(failed).expect("failed task snapshot")) + .expect("failed task registers"); + coordinator + .register_task(scheduler.task(cancelled).expect("cancelled task snapshot")) + .expect("cancelled task registers"); + let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + for task_id in [failed, cancelled] { + workers + .start_from_task( + scheduler.task(task_id).expect("task snapshot"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("worker starts"); + workers + .record_execution_started(task_id, 70) + .expect("worker execution starts"); + workers + .record_completion_ready(task_id) + .expect("worker completion ready"); + } + workers + .request_cancel(cancelled) + .expect("worker cancellation requested"); + let mut queue = std::collections::VecDeque::new(); + enqueue_provider_turn_finalizer_event( + &mut queue, + Some(failed), + ProviderTurnTerminalPlan::Failed { + err: "failed".to_string(), + history_commit_len: 0, + summary: "test failed skip".to_string(), + }, + ); + enqueue_provider_turn_finalizer_event( + &mut queue, + Some(cancelled), + ProviderTurnTerminalPlan::Cancelled { + summary: "test cancelled skip", + }, + ); + let (dispatcher, mut rx) = dispatcher::ChatDispatcher::new(); + + let results = drain_provider_turn_finalizer_events_and_publish( + &mut scheduler, + &mut coordinator, + &mut workers, + &mut queue, + &dispatcher, + ); + + assert_eq!(results.len(), 2); + assert_eq!(results[0].terminal_status, "failed"); + assert_eq!(results[1].terminal_status, "cancelled"); + assert!(results.iter().all(|result| result.finalized)); + while let Ok(action) = rx.try_recv() { + assert!( + !matches!( + action, + Action::RecordAssistantTurn { .. } | Action::StreamCompleted { .. } + ), + "skip decisions must not emit assistant/session persistence actions: {action:?}" + ); + } +} + +#[test] +fn provider_turn_visible_admission_blocks_while_provider_worker_active() { + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let running = scheduler.enqueue("running", crate::chat::turn_scheduler::TurnPriority::Normal, 0); + let committed = scheduler.enqueue("committed", crate::chat::turn_scheduler::TurnPriority::Normal, 0); + scheduler.start_task(running).expect("running starts"); + scheduler.start_task(committed).expect("committed starts"); + + let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + assert!( + provider_turn_visible_admission(&workers, crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, 1,) + .can_start_visible + ); + + workers + .start_from_task( + scheduler.task(running).expect("running task"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("running worker starts"); + let admission = + provider_turn_visible_admission(&workers, crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, 1); + assert_eq!(admission.active_workers, 1); + assert!(!admission.can_start_visible); + + workers + .record_execution_started(running, 44) + .expect("running execution starts"); + workers + .record_completion_ready(running) + .expect("running completion ready"); + workers + .record_finalized_payload( + running, + crate::chat::turn_worker::ProviderTurnFinalizedPayload { + history_commit_len: 1, + final_text_chars: 1, + recorded_response_chars: 1, + total_tokens: 1, + prompt_tokens: 0, + completion_tokens: 1, + }, + ) + .expect("running payload finalized"); + workers.record_completed(running).expect("running worker completed"); + let admission = + provider_turn_visible_admission(&workers, crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, 1); + assert_eq!(admission.active_workers, 1); + assert!( + !admission.can_start_visible, + "awaiting commit still owns the visible draft boundary" + ); + + workers + .start_from_task( + scheduler.task(committed).expect("committed task"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("committed worker starts"); + workers + .record_execution_started(committed, 45) + .expect("committed execution starts"); + workers + .record_completion_ready(committed) + .expect("committed completion ready"); + workers + .record_finalized_payload( + committed, + crate::chat::turn_worker::ProviderTurnFinalizedPayload { + history_commit_len: 1, + final_text_chars: 1, + recorded_response_chars: 1, + total_tokens: 1, + prompt_tokens: 0, + completion_tokens: 1, + }, + ) + .expect("committed payload finalized"); + workers.record_completed(committed).expect("committed worker completed"); + let decision = crate::chat::history_commit::HistoryCommitDecision::Commit { + task_id: running, + sequence: scheduler.task(running).expect("running task").sequence, + history_commit_len: 1, + summary: "running committed".to_string(), + }; + workers + .apply_commit_decision(&decision) + .expect("running commit applies"); + let admission = + provider_turn_visible_admission(&workers, crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, 1); + assert_eq!(admission.active_workers, 1); + assert!( + !admission.can_start_visible, + "second awaiting commit worker still blocks" + ); + + let decision = crate::chat::history_commit::HistoryCommitDecision::Commit { + task_id: committed, + sequence: scheduler.task(committed).expect("committed task").sequence, + history_commit_len: 1, + summary: "committed committed".to_string(), + }; + workers + .apply_commit_decision(&decision) + .expect("committed commit applies"); + let admission = + provider_turn_visible_admission(&workers, crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, 1); + assert_eq!(admission.active_workers, 0); + assert!(admission.can_start_visible); +} + +#[test] +fn provider_turn_visible_admission_allows_detached_until_configured_limit() { + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let first = scheduler.enqueue("first", crate::chat::turn_scheduler::TurnPriority::Normal, 0); + let second = scheduler.enqueue("second", crate::chat::turn_scheduler::TurnPriority::Normal, 0); + scheduler.start_task(first).expect("first starts"); + scheduler.start_task(second).expect("second starts"); + + let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + workers + .start_from_task( + scheduler.task(first).expect("first task"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("first worker starts"); + let admission = + provider_turn_visible_admission(&workers, crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, 2); + assert_eq!(admission.detached_active, 1); + assert!(admission.can_start_visible, "one detached turn leaves one N=2 slot"); + + workers + .start_from_task( + scheduler.task(second).expect("second task"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("second worker starts"); + let admission = + provider_turn_visible_admission(&workers, crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, 2); + assert_eq!(admission.detached_active, 2); + assert!( + !admission.can_start_visible, + "two detached turns exhaust configured N=2 admission" + ); +} + +#[test] +fn provider_turn_visible_admission_legacy_foreground_is_exclusive() { + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let legacy = scheduler.enqueue("legacy", crate::chat::turn_scheduler::TurnPriority::Normal, 0); + scheduler.start_task(legacy).expect("legacy starts"); + + let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + workers + .start_from_task( + scheduler.task(legacy).expect("legacy task"), + crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited, + ) + .expect("legacy worker starts"); + + let detached = + provider_turn_visible_admission(&workers, crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, 2); + assert_eq!(detached.foreground_active, 1); + assert!(!detached.can_start_visible, "legacy active blocks detached turns"); + + let foreground = provider_turn_visible_admission( + &workers, + crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited, + 2, + ); + assert!( + !foreground.can_start_visible, + "legacy active blocks another legacy turn" + ); +} + +#[test] +fn visible_input_pop_preserves_queue_while_provider_worker_active() { + let mut backlog = std::collections::VecDeque::new(); + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let active = scheduler.enqueue("active", crate::chat::turn_scheduler::TurnPriority::Normal, 0); + scheduler.start_task(active).expect("active task starts"); + + let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + workers + .start_from_task( + scheduler.task(active).expect("active task"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("active worker starts"); + enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("queued while active"), 7); + let queued_task = backlog + .front() + .and_then(|queued| queued.turn_task_id) + .expect("queued task id"); + + let popped = pop_next_visible_input_task_with_scheduler( + &mut backlog, + &mut scheduler, + &workers, + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + 1, + ); + + assert!( + popped.is_none(), + "active provider worker must hold visible input admission" + ); + assert_eq!(backlog.len(), 1, "queued input must remain queued"); + assert_eq!( + scheduler.task(queued_task).expect("queued task").state, + crate::chat::turn_scheduler::TurnTaskState::Queued, + "blocked visible input must not be marked dispatched" + ); + assert_eq!(scheduler.status().main_queue_status().queued, 1); +} diff --git a/src/chat/tests/p3_directional_switch_tests/section_2.rs b/src/chat/tests/p3_directional_switch_tests/section_2.rs new file mode 100644 index 000000000..e2bcdeb44 --- /dev/null +++ b/src/chat/tests/p3_directional_switch_tests/section_2.rs @@ -0,0 +1,1737 @@ +#[test] +fn session_reset_commands_wait_for_active_turn_even_when_concurrency_has_capacity() { + for command in ["/new", "/clear"] { + let mut backlog = std::collections::VecDeque::new(); + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let active = scheduler.enqueue("active", crate::chat::turn_scheduler::TurnPriority::Normal, 0); + scheduler.start_task(active).expect("active task starts"); + + let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + workers + .start_from_task( + scheduler.task(active).expect("active task"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("active worker starts"); + enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg(command), 7); + let queued_task = backlog + .front() + .and_then(|queued| queued.turn_task_id) + .expect("queued command task id"); + + let popped = pop_next_visible_input_task_with_scheduler( + &mut backlog, + &mut scheduler, + &workers, + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + 2, + ); + + assert!(popped.is_none(), "{command} must wait for the active turn to persist"); + assert_eq!(backlog.len(), 1, "{command} must remain queued"); + assert_eq!( + scheduler.task(queued_task).expect("queued command task").state, + crate::chat::turn_scheduler::TurnTaskState::Queued, + "{command} must not be dispatched across the session boundary" + ); + } +} + +#[test] +fn visible_input_pop_prefers_priority_when_detached_slot_is_available() { + let mut backlog = std::collections::VecDeque::new(); + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let active = scheduler.enqueue("active", crate::chat::turn_scheduler::TurnPriority::Normal, 0); + scheduler.start_task(active).expect("active task starts"); + + let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + workers + .start_from_task( + scheduler.task(active).expect("active task"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("active worker starts"); + enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("normal queued first"), 7); + enqueue_input_message_with_scheduler( + &mut backlog, + &mut scheduler, + input_msg("/priority urgent queued second"), + 7, + ); + + let popped = pop_next_visible_input_task_with_scheduler( + &mut backlog, + &mut scheduler, + &workers, + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + 2, + ) + .expect("second detached slot should be available"); + + assert_eq!( + popped.msg.content, "urgent queued second", + "priority input must dispatch before older normal input when a visible slot opens" + ); + let popped_task = popped.turn_task_id.expect("popped task id"); + assert_eq!( + scheduler.task(popped_task).expect("priority task").priority, + crate::chat::turn_scheduler::TurnPriority::Priority + ); + assert_eq!( + backlog.front().map(|queued| queued.msg.content.as_str()), + Some("normal queued first"), + "normal input remains queued after priority dispatch" + ); +} + +#[test] +fn post_route_requeue_defers_next_visible_pop_once_under_detached_capacity() { + let mut backlog = std::collections::VecDeque::new(); + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let active = scheduler.enqueue("active detached", crate::chat::turn_scheduler::TurnPriority::Normal, 0); + scheduler.start_task(active).expect("active task starts"); + + let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + workers + .start_from_task( + scheduler.task(active).expect("active task"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("active worker starts"); + enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("legacy fallback"), 7); + let queued_task = backlog + .front() + .and_then(|queued| queued.turn_task_id) + .expect("queued task id"); + + assert!( + provider_turn_visible_admission(&workers, crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, 2,) + .can_start_visible, + "ordinary detached pop admission would otherwise immediately re-pop" + ); + let mut defer_visible_input_pop_once = true; + + assert!( + consume_deferred_visible_input_pop(&mut defer_visible_input_pop_once), + "post-route requeue should force one event-pump wait" + ); + assert_eq!(backlog.len(), 1, "deferred pop leaves requeued input in place"); + assert_eq!( + scheduler.task(queued_task).expect("queued task").state, + crate::chat::turn_scheduler::TurnTaskState::Queued, + "deferred pop must not repeatedly mark the requeued task dispatched" + ); + assert!( + !consume_deferred_visible_input_pop(&mut defer_visible_input_pop_once), + "defer gate is one-shot" + ); + + let popped = pop_next_visible_input_task_with_scheduler( + &mut backlog, + &mut scheduler, + &workers, + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + 2, + ) + .expect("input can pop after one event-pump wait"); + assert_eq!(popped.turn_task_id, Some(queued_task)); + assert_eq!( + scheduler.task(queued_task).expect("queued task").state, + crate::chat::turn_scheduler::TurnTaskState::Dispatched + ); +} + +#[test] +fn post_route_admission_rejection_requeues_input_and_defers_next_pop() { + let mut backlog = std::collections::VecDeque::new(); + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let active = scheduler.enqueue("active detached", crate::chat::turn_scheduler::TurnPriority::Normal, 0); + scheduler.start_task(active).expect("active task starts"); + + let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + workers + .start_from_task( + scheduler.task(active).expect("active task"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("active worker starts"); + enqueue_input_message_with_scheduler(&mut backlog, &mut scheduler, input_msg("legacy after draft failure"), 7); + + let popped = pop_next_visible_input_task_with_scheduler( + &mut backlog, + &mut scheduler, + &workers, + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + 2, + ) + .expect("detached admission allows second visible turn before route is known"); + let task_id = popped.turn_task_id.expect("popped task id"); + assert_eq!( + scheduler.task(task_id).expect("popped task").state, + crate::chat::turn_scheduler::TurnTaskState::Dispatched, + "chat-loop pop marks the task dispatched before post-route admission runs" + ); + assert!( + !provider_turn_visible_admission( + &workers, + crate::chat::turn_worker::ProviderTurnWorkerKind::ForegroundAwaited, + 1 + ) + .can_start_visible, + "legacy-routed turn is rejected while another detached worker is active" + ); + + let mut defer_visible_input_pop_once = false; + requeue_post_route_admission_rejected_input( + &mut backlog, + &mut scheduler, + &mut defer_visible_input_pop_once, + popped, + ); + + assert_eq!(backlog.len(), 1, "post-route rejection must requeue the popped input"); + assert_eq!( + backlog.front().and_then(|queued| queued.turn_task_id), + Some(task_id), + "requeued input keeps the original scheduler task id" + ); + assert_eq!( + scheduler.task(task_id).expect("requeued task").state, + crate::chat::turn_scheduler::TurnTaskState::Queued, + "requeued input is queued again in the scheduler" + ); + assert_eq!( + scheduler.status().queued, + 1, + "queue status counts the requeued input it lists" + ); + assert!( + provider_turn_visible_admission(&workers, crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, 2) + .can_start_visible, + "without the defer gate, the next pump pass would immediately re-pop under detached capacity" + ); + assert!( + consume_deferred_visible_input_pop(&mut defer_visible_input_pop_once), + "post-route rejection must force one event-pump wait before the same input can pop again" + ); + assert_eq!( + backlog.len(), + 1, + "deferred pump pass leaves the requeued input in place" + ); + assert!( + !consume_deferred_visible_input_pop(&mut defer_visible_input_pop_once), + "defer gate is one-shot after the event-pump wait" + ); + let repopped = pop_next_visible_input_task_with_scheduler( + &mut backlog, + &mut scheduler, + &workers, + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + 2, + ) + .expect("the requeued input pops again"); + assert_eq!(repopped.turn_task_id, Some(task_id)); + assert_eq!( + scheduler.task(task_id).expect("re-dispatched task").state, + crate::chat::turn_scheduler::TurnTaskState::Dispatched, + "the second dequeue is a valid queued -> dispatched transition" + ); +} + +#[test] +fn provider_turn_completion_context_supplies_stable_history_boundary_once() { + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let task_id = scheduler.enqueue("context", crate::chat::turn_scheduler::TurnPriority::Normal, 9); + let mut contexts = std::collections::HashMap::new(); + + record_provider_turn_completion_context(&mut contexts, Some(task_id), 12); + + assert_eq!( + take_provider_turn_completion_history_len(&mut contexts, Some(task_id), 99), + 12 + ); + assert_eq!( + take_provider_turn_completion_history_len(&mut contexts, Some(task_id), 99), + 99, + "completion context is single-use" + ); + assert_eq!( + take_provider_turn_completion_history_len(&mut contexts, None, 7), + 7, + "legacy turns without task id use the local fallback" + ); +} + +#[test] +fn provider_terminal_plan_uses_completion_context_history_boundary() { + let tools: Vec> = Vec::new(); + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let task_id = scheduler.enqueue("context plan", crate::chat::turn_scheduler::TurnPriority::Normal, 1); + let mut contexts = std::collections::HashMap::new(); + record_provider_turn_completion_context(&mut contexts, Some(task_id), 4); + let history_len = take_provider_turn_completion_history_len(&mut contexts, Some(task_id), 99); + + let plan = provider_turn_terminal_plan_from_completion( + ResolvedProviderTurnCompletion { + outcome: Some(dispatcher::TurnOutcomeKind::Completed { + final_text: "context done".to_string(), + reasoning: String::new(), + }), + usage: crate::llm::route_decision::TokenUsage::default(), + }, + history_len, + &tools, + ); + + match plan { + ProviderTurnTerminalPlan::Completed { history_commit_len, .. } => assert_eq!(history_commit_len, 5), + other => panic!("unexpected terminal plan: {other:?}"), + } +} + +#[test] +fn completed_provider_turn_finalization_gate_records_payload_and_commit() { + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let task_id = scheduler.enqueue("complete me", crate::chat::turn_scheduler::TurnPriority::Normal, 2); + scheduler.start_task(task_id).expect("task starts"); + let mut coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); + coordinator + .register_task(scheduler.task(task_id).expect("task snapshot")) + .expect("history task registers"); + let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + workers + .start_from_task( + scheduler.task(task_id).expect("task snapshot"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("worker starts"); + workers.record_execution_started(task_id, 7).expect("execution starts"); + workers.record_completion_ready(task_id).expect("completion ready"); + let usage = crate::llm::route_decision::TokenUsage { + prompt_tokens: Some(10), + completion_tokens: Some(5), + total_tokens: Some(15), + ..Default::default() + }; + + let decisions = gate_completed_provider_turn_finalization( + &mut scheduler, + &mut coordinator, + &mut workers, + Some(task_id), + 3, + 12, + 10, + &usage, + "test completed", + ); + + assert_eq!(decisions.len(), 1, "completion gate should release one ready decision"); + assert_eq!( + scheduler.task(task_id).unwrap().state, + crate::chat::turn_scheduler::TurnTaskState::Completed + ); + let row = workers + .snapshot() + .into_iter() + .find(|row| row.task_id == task_id) + .expect("worker snapshot retained"); + assert_eq!(row.finalized_total_tokens, Some(15)); + assert!(matches!( + row.state, + crate::chat::turn_worker::ProviderTurnWorkerState::Committed + )); +} + +#[test] +fn failed_provider_turn_finalization_gate_records_skip_decision() { + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let task_id = scheduler.enqueue("fail me", crate::chat::turn_scheduler::TurnPriority::Normal, 2); + scheduler.start_task(task_id).expect("task starts"); + let mut coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); + coordinator + .register_task(scheduler.task(task_id).expect("task snapshot")) + .expect("history task registers"); + let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + workers + .start_from_task( + scheduler.task(task_id).expect("task snapshot"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("worker starts"); + workers.record_execution_started(task_id, 8).expect("execution starts"); + workers.record_completion_ready(task_id).expect("completion ready"); + + let decisions = gate_failed_provider_turn_finalization( + &mut scheduler, + &mut coordinator, + &mut workers, + Some(task_id), + 2, + "test failed", + ); + + assert_eq!(decisions.len(), 1, "failure gate should release one skip decision"); + assert_eq!( + scheduler.task(task_id).unwrap().state, + crate::chat::turn_scheduler::TurnTaskState::Failed + ); + let row = workers + .snapshot() + .into_iter() + .find(|row| row.task_id == task_id) + .expect("worker snapshot retained"); + assert!(matches!( + row.state, + crate::chat::turn_worker::ProviderTurnWorkerState::Failed + )); +} + +#[test] +fn cancelled_provider_turn_finalization_gate_records_skip_decision() { + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let task_id = scheduler.enqueue("cancel me", crate::chat::turn_scheduler::TurnPriority::Normal, 2); + scheduler.start_task(task_id).expect("task starts"); + scheduler.request_cancel(task_id).expect("task cancellation requested"); + let mut coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); + coordinator + .register_task(scheduler.task(task_id).expect("task snapshot")) + .expect("history task registers"); + let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + workers + .start_from_task( + scheduler.task(task_id).expect("task snapshot"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("worker starts"); + workers.record_execution_started(task_id, 9).expect("execution starts"); + workers.request_cancel(task_id).expect("worker cancellation requested"); + workers.record_completion_ready(task_id).expect("completion ready"); + + let decisions = gate_cancelled_provider_turn_finalization( + &mut scheduler, + &mut coordinator, + &mut workers, + Some(task_id), + "test cancelled", + ); + + assert_eq!(decisions.len(), 1, "cancellation gate should release one skip decision"); + assert_eq!( + scheduler.task(task_id).unwrap().state, + crate::chat::turn_scheduler::TurnTaskState::Cancelled + ); + let row = workers + .snapshot() + .into_iter() + .find(|row| row.task_id == task_id) + .expect("worker snapshot retained"); + assert!(matches!( + row.state, + crate::chat::turn_worker::ProviderTurnWorkerState::Cancelled + )); +} + +#[test] +fn provider_completion_resolution_prefers_completion_event() { + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let task_id = scheduler.enqueue("event", crate::chat::turn_scheduler::TurnPriority::Normal, 0); + let signal = dispatcher::TurnCompletionSignal::new(); + signal.register_turn(task_id, "draft-event"); + signal.record_and_notify(dispatcher::TurnOutcomeKind::Cancelled); + signal.record_usage(crate::llm::route_decision::TokenUsage { + total_tokens: Some(99), + ..Default::default() + }); + let event = ProviderTurnCompletionEvent { + task_id, + outcome: Some(dispatcher::TurnOutcomeKind::Completed { + final_text: "event wins".to_string(), + reasoning: String::new(), + }), + usage: crate::llm::route_decision::TokenUsage { + total_tokens: Some(12), + ..Default::default() + }, + }; + + let resolved = resolve_provider_turn_completion(&signal, Some(task_id), Some(event)); + + match resolved.outcome { + Some(dispatcher::TurnOutcomeKind::Completed { final_text, .. }) => { + assert_eq!(final_text, "event wins"); + } + other => panic!("unexpected outcome: {other:?}"), + } + assert_eq!(resolved.usage.total_tokens, Some(12)); + assert!(signal.notified_for(task_id).is_none(), "task should unregister"); +} + +#[test] +fn provider_completion_resolution_uses_legacy_usage_when_event_usage_empty() { + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let task_id = scheduler.enqueue( + "event empty usage", + crate::chat::turn_scheduler::TurnPriority::Normal, + 0, + ); + let signal = dispatcher::TurnCompletionSignal::new(); + signal.record_usage(crate::llm::route_decision::TokenUsage { + total_tokens: Some(21), + ..Default::default() + }); + let event = ProviderTurnCompletionEvent { + task_id, + outcome: Some(dispatcher::TurnOutcomeKind::Cancelled), + usage: crate::llm::route_decision::TokenUsage::default(), + }; + + let resolved = resolve_provider_turn_completion(&signal, Some(task_id), Some(event)); + + assert!(matches!(resolved.outcome, Some(dispatcher::TurnOutcomeKind::Cancelled))); + assert_eq!(resolved.usage.total_tokens, Some(21)); +} + +#[test] +fn provider_completion_resolution_uses_keyed_signal_without_event() { + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let task_id = scheduler.enqueue("keyed", crate::chat::turn_scheduler::TurnPriority::Normal, 0); + let signal = dispatcher::TurnCompletionSignal::new(); + signal.register_turn(task_id, "draft-keyed"); + assert!(signal.record_usage_for_draft( + "draft-keyed", + crate::llm::route_decision::TokenUsage { + total_tokens: Some(34), + ..Default::default() + } + )); + assert!(signal.record_and_notify_for_draft( + "draft-keyed", + dispatcher::TurnOutcomeKind::Failed { + err: "keyed failed".to_string(), + retryable: false, + }, + )); + + let resolved = resolve_provider_turn_completion(&signal, Some(task_id), None); + + match resolved.outcome { + Some(dispatcher::TurnOutcomeKind::Failed { err, retryable }) => { + assert_eq!(err, "keyed failed"); + assert!(!retryable); + } + other => panic!("unexpected outcome: {other:?}"), + } + assert_eq!(resolved.usage.total_tokens, Some(34)); + assert!(signal.notified_for(task_id).is_none(), "task should unregister"); +} + +#[test] +fn provider_turn_terminal_gate_dispatches_completed_finalization() { + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let task_id = scheduler.enqueue("unified gate", crate::chat::turn_scheduler::TurnPriority::Normal, 1); + scheduler.start_task(task_id).expect("task starts"); + let mut coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); + coordinator + .register_task(scheduler.task(task_id).expect("task snapshot")) + .expect("history task registers"); + let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + workers + .start_from_task( + scheduler.task(task_id).expect("task snapshot"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("worker starts"); + workers.record_execution_started(task_id, 55).expect("execution starts"); + workers.record_completion_ready(task_id).expect("completion ready"); + let usage = crate::llm::route_decision::TokenUsage { + total_tokens: Some(55), + ..Default::default() + }; + + let decisions = gate_provider_turn_terminal_finalization( + &mut scheduler, + &mut coordinator, + &mut workers, + Some(task_id), + ProviderTurnTerminalGate::Completed { + history_commit_len: 2, + final_text_chars: 11, + recorded_response_chars: 10, + usage: &usage, + summary: "test unified completed", + }, + ); + + assert_eq!( + decisions.len(), + 1, + "unified terminal gate should finalize completed turn" + ); + let row = workers + .snapshot() + .into_iter() + .find(|row| row.task_id == task_id) + .expect("worker snapshot retained"); + assert_eq!(row.finalized_total_tokens, Some(55)); + assert!(matches!( + row.state, + crate::chat::turn_worker::ProviderTurnWorkerState::Committed + )); +} + +#[test] +fn provider_turn_finalizer_event_commits_completed_plan() { + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let task_id = scheduler.enqueue( + "finalizer completed", + crate::chat::turn_scheduler::TurnPriority::Normal, + 1, + ); + scheduler.start_task(task_id).expect("task starts"); + let mut coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); + coordinator + .register_task(scheduler.task(task_id).expect("task snapshot")) + .expect("history task registers"); + let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + workers + .start_from_task( + scheduler.task(task_id).expect("task snapshot"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("worker starts"); + workers.record_execution_started(task_id, 56).expect("execution starts"); + workers.record_completion_ready(task_id).expect("completion ready"); + + let result = finalize_provider_turn_from_event( + &mut scheduler, + &mut coordinator, + &mut workers, + ProviderTurnFinalizerEvent { + task_id: Some(task_id), + plan: ProviderTurnTerminalPlan::Completed { + final_text: "done".to_string(), + reasoning: String::new(), + recorded_response: "done".to_string(), + empty_response: false, + usage: crate::llm::route_decision::TokenUsage { + total_tokens: Some(56), + ..Default::default() + }, + history_commit_len: 2, + final_text_chars: 4, + recorded_response_chars: 4, + summary: "test finalizer completed", + }, + }, + ); + + assert_eq!( + result, + vec![ProviderTurnFinalizerResult { + task_id: Some(task_id), + terminal_status: "completed", + finalized: true, + }] + ); + let row = workers + .snapshot() + .into_iter() + .find(|row| row.task_id == task_id) + .expect("worker snapshot retained"); + assert_eq!(row.finalized_total_tokens, Some(56)); + assert!(matches!( + row.state, + crate::chat::turn_worker::ProviderTurnWorkerState::Committed + )); +} + +#[test] +fn provider_turn_finalizer_event_closes_failed_and_cancelled_plans() { + let mut failed_scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let failed_id = failed_scheduler.enqueue("finalizer failed", crate::chat::turn_scheduler::TurnPriority::Normal, 1); + failed_scheduler.start_task(failed_id).expect("failed task starts"); + let mut failed_coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); + failed_coordinator + .register_task(failed_scheduler.task(failed_id).expect("failed task snapshot")) + .expect("failed history task registers"); + let mut failed_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + failed_workers + .start_from_task( + failed_scheduler.task(failed_id).expect("failed task snapshot"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("failed worker starts"); + failed_workers + .record_execution_started(failed_id, 57) + .expect("failed execution starts"); + failed_workers + .record_completion_ready(failed_id) + .expect("failed completion ready"); + + let failed_result = finalize_provider_turn_from_event( + &mut failed_scheduler, + &mut failed_coordinator, + &mut failed_workers, + ProviderTurnFinalizerEvent { + task_id: Some(failed_id), + plan: ProviderTurnTerminalPlan::Failed { + err: "failed".to_string(), + history_commit_len: 1, + summary: "test finalizer failed".to_string(), + }, + }, + ); + + assert_eq!(failed_result.len(), 1); + assert_eq!(failed_result[0].terminal_status, "failed"); + assert!(failed_result[0].finalized); + assert!(matches!( + failed_workers + .snapshot() + .into_iter() + .find(|row| row.task_id == failed_id) + .expect("failed worker snapshot") + .state, + crate::chat::turn_worker::ProviderTurnWorkerState::Failed + )); + + let mut cancelled_scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let cancelled_id = cancelled_scheduler.enqueue( + "finalizer cancelled", + crate::chat::turn_scheduler::TurnPriority::Normal, + 1, + ); + cancelled_scheduler + .start_task(cancelled_id) + .expect("cancelled task starts"); + cancelled_scheduler + .request_cancel(cancelled_id) + .expect("cancelled task requested"); + let mut cancelled_coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); + cancelled_coordinator + .register_task(cancelled_scheduler.task(cancelled_id).expect("cancelled task snapshot")) + .expect("cancelled history task registers"); + let mut cancelled_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + cancelled_workers + .start_from_task( + cancelled_scheduler.task(cancelled_id).expect("cancelled task snapshot"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("cancelled worker starts"); + cancelled_workers + .record_execution_started(cancelled_id, 58) + .expect("cancelled execution starts"); + cancelled_workers + .request_cancel(cancelled_id) + .expect("cancelled worker requested"); + cancelled_workers + .record_completion_ready(cancelled_id) + .expect("cancelled completion ready"); + + let cancelled_result = finalize_provider_turn_from_event( + &mut cancelled_scheduler, + &mut cancelled_coordinator, + &mut cancelled_workers, + ProviderTurnFinalizerEvent { + task_id: Some(cancelled_id), + plan: ProviderTurnTerminalPlan::Cancelled { + summary: "test finalizer cancelled", + }, + }, + ); + + assert_eq!(cancelled_result.len(), 1); + assert_eq!(cancelled_result[0].terminal_status, "cancelled"); + assert!(cancelled_result[0].finalized); + assert!(matches!( + cancelled_workers + .snapshot() + .into_iter() + .find(|row| row.task_id == cancelled_id) + .expect("cancelled worker snapshot") + .state, + crate::chat::turn_worker::ProviderTurnWorkerState::Cancelled + )); +} + +#[test] +fn provider_turn_finalizer_queue_drains_fifo_and_unlocks_commit_order() { + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let first = scheduler.enqueue("first failed", crate::chat::turn_scheduler::TurnPriority::Normal, 1); + let second = scheduler.enqueue("second completed", crate::chat::turn_scheduler::TurnPriority::Normal, 1); + scheduler.start_task(first).expect("first starts"); + scheduler.start_task(second).expect("second starts"); + + let mut coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); + coordinator + .register_task(scheduler.task(first).expect("first task")) + .expect("first history task registers"); + coordinator + .register_task(scheduler.task(second).expect("second task")) + .expect("second history task registers"); + + let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + for (id, lease) in [(first, 61), (second, 62)] { + workers + .start_from_task( + scheduler.task(id).expect("task snapshot"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("worker starts"); + workers.record_execution_started(id, lease).expect("execution starts"); + workers.record_completion_ready(id).expect("completion ready"); + } + + let mut queue = std::collections::VecDeque::new(); + enqueue_provider_turn_finalizer_event( + &mut queue, + Some(first), + ProviderTurnTerminalPlan::Failed { + err: "first failed".to_string(), + history_commit_len: 1, + summary: "test first failed".to_string(), + }, + ); + enqueue_provider_turn_finalizer_event( + &mut queue, + Some(second), + ProviderTurnTerminalPlan::Completed { + final_text: "second done".to_string(), + reasoning: String::new(), + recorded_response: "second done".to_string(), + empty_response: false, + usage: crate::llm::route_decision::TokenUsage { + total_tokens: Some(62), + ..Default::default() + }, + history_commit_len: 2, + final_text_chars: 11, + recorded_response_chars: 11, + summary: "test second completed", + }, + ); + + let results = drain_provider_turn_finalizer_events(&mut scheduler, &mut coordinator, &mut workers, &mut queue); + + assert!(queue.is_empty()); + assert_eq!(results.len(), 2); + assert_eq!(results[0].task_id, Some(first)); + assert_eq!(results[0].terminal_status, "failed"); + assert!(results[0].finalized); + assert_eq!(results[1].task_id, Some(second)); + assert_eq!(results[1].terminal_status, "completed"); + assert!(results[1].finalized); + let rows = workers.snapshot(); + assert!(matches!( + rows.iter().find(|row| row.task_id == first).expect("first row").state, + crate::chat::turn_worker::ProviderTurnWorkerState::Failed + )); + let second_row = rows.iter().find(|row| row.task_id == second).expect("second row"); + assert_eq!(second_row.finalized_total_tokens, Some(62)); + assert!(matches!( + second_row.state, + crate::chat::turn_worker::ProviderTurnWorkerState::Committed + )); +} + +#[test] +fn provider_turn_finalizer_delays_later_completed_turn_until_earlier_ready() { + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let first = scheduler.enqueue("first slow", crate::chat::turn_scheduler::TurnPriority::Normal, 1); + let second = scheduler.enqueue("second fast", crate::chat::turn_scheduler::TurnPriority::Normal, 1); + scheduler.start_task(first).expect("first starts"); + scheduler.start_task(second).expect("second starts"); + let mut coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); + coordinator + .register_task(scheduler.task(first).expect("first task")) + .expect("first history task registers"); + coordinator + .register_task(scheduler.task(second).expect("second task")) + .expect("second history task registers"); + let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + for (id, lease) in [(first, 81), (second, 82)] { + workers + .start_from_task( + scheduler.task(id).expect("task snapshot"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("worker starts"); + workers.record_execution_started(id, lease).expect("execution starts"); + workers.record_completion_ready(id).expect("completion ready"); + } + + let second_results = finalize_provider_turn_from_event( + &mut scheduler, + &mut coordinator, + &mut workers, + ProviderTurnFinalizerEvent { + task_id: Some(second), + plan: ProviderTurnTerminalPlan::Completed { + final_text: "second answer".to_string(), + reasoning: String::new(), + recorded_response: "second answer".to_string(), + empty_response: false, + usage: crate::llm::route_decision::TokenUsage { + total_tokens: Some(82), + ..Default::default() + }, + history_commit_len: 3, + final_text_chars: 13, + recorded_response_chars: 13, + summary: "test second completed", + }, + }, + ); + assert_eq!( + second_results, + vec![ProviderTurnFinalizerResult { + task_id: Some(second), + terminal_status: "unknown", + finalized: false, + }], + "later completion must wait for the earlier sequence" + ); + assert!(matches!( + workers.worker(second).expect("second worker").state, + crate::chat::turn_worker::ProviderTurnWorkerState::AwaitingCommit(_) + )); + + let first_results = finalize_provider_turn_from_event( + &mut scheduler, + &mut coordinator, + &mut workers, + ProviderTurnFinalizerEvent { + task_id: Some(first), + plan: ProviderTurnTerminalPlan::Completed { + final_text: "first answer".to_string(), + reasoning: String::new(), + recorded_response: "first answer".to_string(), + empty_response: false, + usage: crate::llm::route_decision::TokenUsage { + total_tokens: Some(81), + ..Default::default() + }, + history_commit_len: 3, + final_text_chars: 12, + recorded_response_chars: 12, + summary: "test first completed", + }, + }, + ); + + assert_eq!( + first_results.iter().map(|result| result.task_id).collect::>(), + vec![Some(first), Some(second)], + "earlier completion should release both ready decisions in sequence" + ); + assert!(first_results.iter().all(|result| result.finalized)); + assert!(matches!( + workers.worker(first).expect("first worker").state, + crate::chat::turn_worker::ProviderTurnWorkerState::Committed + )); + assert!(matches!( + workers.worker(second).expect("second worker").state, + crate::chat::turn_worker::ProviderTurnWorkerState::Committed + )); +} + +#[test] +fn provider_turn_finalizer_releases_later_completed_turn_when_earlier_cancelled() { + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let first = scheduler.enqueue("first cancelled", crate::chat::turn_scheduler::TurnPriority::Normal, 1); + let second = scheduler.enqueue("second held", crate::chat::turn_scheduler::TurnPriority::Normal, 1); + scheduler.start_task(first).expect("first starts"); + scheduler.request_cancel(first).expect("first cancellation requested"); + scheduler.start_task(second).expect("second starts"); + let mut coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); + coordinator + .register_task(scheduler.task(first).expect("first task")) + .expect("first history task registers"); + coordinator + .register_task(scheduler.task(second).expect("second task")) + .expect("second history task registers"); + let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + workers + .start_from_task( + scheduler.task(first).expect("first task"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("first worker starts"); + workers + .record_execution_started(first, 91) + .expect("first execution starts"); + workers + .request_cancel(first) + .expect("first worker cancellation requested"); + workers.record_completion_ready(first).expect("first completion ready"); + workers + .start_from_task( + scheduler.task(second).expect("second task"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("second worker starts"); + workers + .record_execution_started(second, 92) + .expect("second execution starts"); + workers + .record_completion_ready(second) + .expect("second completion ready"); + + let second_results = finalize_provider_turn_from_event( + &mut scheduler, + &mut coordinator, + &mut workers, + ProviderTurnFinalizerEvent { + task_id: Some(second), + plan: ProviderTurnTerminalPlan::Completed { + final_text: "second after cancel".to_string(), + reasoning: String::new(), + recorded_response: "second after cancel".to_string(), + empty_response: false, + usage: crate::llm::route_decision::TokenUsage { + total_tokens: Some(92), + ..Default::default() + }, + history_commit_len: 3, + final_text_chars: 19, + recorded_response_chars: 19, + summary: "test second completed after cancel", + }, + }, + ); + assert_eq!( + second_results, + vec![ProviderTurnFinalizerResult { + task_id: Some(second), + terminal_status: "unknown", + finalized: false, + }], + "later completion must remain held until earlier cancellation is ordered" + ); + + let first_results = finalize_provider_turn_from_event( + &mut scheduler, + &mut coordinator, + &mut workers, + ProviderTurnFinalizerEvent { + task_id: Some(first), + plan: ProviderTurnTerminalPlan::Cancelled { + summary: "test first cancelled", + }, + }, + ); + + assert_eq!( + first_results + .iter() + .map(|result| (result.task_id, result.terminal_status)) + .collect::>(), + vec![(Some(first), "cancelled"), (Some(second), "completed")], + "earlier cancellation should skip first and then release held later commit" + ); + assert!(first_results.iter().all(|result| result.finalized)); + assert!(matches!( + workers.worker(first).expect("first worker").state, + crate::chat::turn_worker::ProviderTurnWorkerState::Cancelled + )); + assert!(matches!( + workers.worker(second).expect("second worker").state, + crate::chat::turn_worker::ProviderTurnWorkerState::Committed + )); +} + +#[cfg(feature = "terminal-tui")] +#[test] +fn provider_turn_finalizer_n3_out_of_order_releases_ordered_persistence_actions() { + use crate::chat::action::Action; + + fn completed_plan(final_text: &str, total_tokens: u32, history_commit_len: usize) -> ProviderTurnTerminalPlan { + ProviderTurnTerminalPlan::Completed { + final_text: final_text.to_string(), + reasoning: String::new(), + recorded_response: final_text.to_string(), + empty_response: false, + usage: crate::llm::route_decision::TokenUsage { + total_tokens: Some(total_tokens), + ..Default::default() + }, + history_commit_len, + final_text_chars: final_text.chars().count(), + recorded_response_chars: final_text.chars().count(), + summary: "test n3 completed", + } + } + + fn pending_commit_for( + task_id: crate::chat::turn_scheduler::TurnTaskId, + draft_id: &str, + user_input: &str, + plan: ProviderTurnTerminalPlan, + ) -> PendingOrderedProviderTurnCommit { + PendingOrderedProviderTurnCommit { + context: PerTurnContext { + _mailbox_input: None, + turn_binding: None, + task_id, + draft_id: draft_id.to_string(), + delta_tx: None, + tool_event_tx: None, + draft_updater: None, + tool_event_forwarder: None, + user_input: user_input.to_string(), + turn_run_id: format!("test-run-{}", task_id.get()), + route_scope: crate::memory::MessageEventScope::new("chat", crate::memory::MemoryVisibility::Workspace), + route_decision: RouteDecision::single_candidate("mock", "mock"), + provider_started_at: chrono::Utc::now(), + provider_name: "mock".to_string(), + model_name: "mock".to_string(), + history_len_before_user_turn: 0, + compaction_epoch_at_start: 0, + assignment: None, + }, + terminal_plan: plan, + } + } + + fn dispatch_ready_for_test( + results: Vec, + pending: &mut std::collections::HashMap< + crate::chat::turn_scheduler::TurnTaskId, + PendingOrderedProviderTurnCommit, + >, + dispatcher: &dispatcher::ChatDispatcher, + ) { + for result in results { + if !result.finalized || result.terminal_status != "completed" { + continue; + } + let task_id = result.task_id.expect("finalized result has task id"); + let pending_commit = pending.remove(&task_id).expect("pending commit payload"); + let ProviderTurnTerminalPlan::Completed { + final_text, + reasoning, + empty_response, + .. + } = pending_commit.terminal_plan + else { + panic!("expected completed terminal plan"); + }; + dispatch_ordered_provider_turn_commit( + dispatcher, + task_id, + &pending_commit.context.draft_id, + &pending_commit.context.user_input, + &final_text, + &reasoning, + empty_response, + true, + ) + .expect("ordered history dispatch"); + } + } + + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let first = scheduler.enqueue("alpha prompt", crate::chat::turn_scheduler::TurnPriority::Normal, 0); + let second = scheduler.enqueue("bravo prompt", crate::chat::turn_scheduler::TurnPriority::Normal, 0); + let third = scheduler.enqueue("charlie prompt", crate::chat::turn_scheduler::TurnPriority::Normal, 0); + for task_id in [first, second, third] { + scheduler.start_task(task_id).expect("task starts"); + } + + let mut coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); + for task_id in [first, second, third] { + coordinator + .register_task(scheduler.task(task_id).expect("task snapshot")) + .expect("history task registers"); + } + + let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + for (task_id, lease) in [(first, 101), (second, 102), (third, 103)] { + workers + .start_from_task( + scheduler.task(task_id).expect("task snapshot"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("worker starts"); + workers + .record_execution_started(task_id, lease) + .expect("execution starts"); + workers.record_completion_ready(task_id).expect("completion ready"); + } + + let first_plan = completed_plan("alpha answer", 11, 2); + let second_plan = completed_plan("bravo answer", 12, 4); + let third_plan = completed_plan("charlie answer", 13, 6); + let mut pending_ordered_provider_turn_commits = std::collections::HashMap::from([ + ( + first, + pending_commit_for(first, "draft-alpha", "alpha prompt", first_plan.clone()), + ), + ( + second, + pending_commit_for(second, "draft-bravo", "bravo prompt", second_plan.clone()), + ), + ( + third, + pending_commit_for(third, "draft-charlie", "charlie prompt", third_plan.clone()), + ), + ]); + let (dispatcher, mut rx) = dispatcher::ChatDispatcher::new(); + + let third_results = finalize_provider_turn_from_event( + &mut scheduler, + &mut coordinator, + &mut workers, + ProviderTurnFinalizerEvent { + task_id: Some(third), + plan: third_plan, + }, + ); + assert_eq!( + third_results, + vec![ProviderTurnFinalizerResult { + task_id: Some(third), + terminal_status: "unknown", + finalized: false, + }], + "third completion must stay held until first and second are terminal" + ); + dispatch_ready_for_test(third_results, &mut pending_ordered_provider_turn_commits, &dispatcher); + assert!( + rx.try_recv().is_err(), + "held third turn must emit no persistence actions" + ); + assert!(matches!( + workers.worker(third).expect("third worker").state, + crate::chat::turn_worker::ProviderTurnWorkerState::AwaitingCommit(_) + )); + + let second_results = finalize_provider_turn_from_event( + &mut scheduler, + &mut coordinator, + &mut workers, + ProviderTurnFinalizerEvent { + task_id: Some(second), + plan: second_plan, + }, + ); + assert_eq!( + second_results, + vec![ProviderTurnFinalizerResult { + task_id: Some(second), + terminal_status: "unknown", + finalized: false, + }], + "second completion must stay held until first is terminal" + ); + dispatch_ready_for_test(second_results, &mut pending_ordered_provider_turn_commits, &dispatcher); + assert!( + rx.try_recv().is_err(), + "held second turn must emit no persistence actions" + ); + + let first_results = finalize_provider_turn_from_event( + &mut scheduler, + &mut coordinator, + &mut workers, + ProviderTurnFinalizerEvent { + task_id: Some(first), + plan: first_plan, + }, + ); + assert_eq!( + first_results + .iter() + .map(|result| (result.task_id, result.terminal_status, result.finalized)) + .collect::>(), + vec![ + (Some(first), "completed", true), + (Some(second), "completed", true), + (Some(third), "completed", true), + ], + "first completion must release all held completed turns in dispatch order" + ); + dispatch_ready_for_test(first_results, &mut pending_ordered_provider_turn_commits, &dispatcher); + + for (expected_user, expected_assistant, expected_draft, expected_task) in [ + ("alpha prompt", "alpha answer", "draft-alpha", first), + ("bravo prompt", "bravo answer", "draft-bravo", second), + ("charlie prompt", "charlie answer", "draft-charlie", third), + ] { + match rx.try_recv().expect("ordered user action") { + Action::RecordUserTurn(content) => assert_eq!(content, expected_user), + other => panic!("expected RecordUserTurn, got {other:?}"), + } + match rx.try_recv().expect("ordered assistant action") { + Action::RecordAssistantTurn { task_id, content } => { + assert_eq!(task_id, Some(expected_task)); + assert_eq!(content, expected_assistant); + } + other => panic!("expected RecordAssistantTurn, got {other:?}"), + } + match rx.try_recv().expect("ordered stream completed action") { + Action::StreamCompleted { + draft_id, + final_text, + reasoning, + } => { + assert_eq!(draft_id, expected_draft); + assert_eq!(final_text, expected_assistant); + assert!(reasoning.is_empty(), "expected an empty value"); + } + other => panic!("expected StreamCompleted, got {other:?}"), + } + } + assert!( + rx.try_recv().is_err(), + "ordered dispatch should emit exactly three action triplets" + ); + assert!(pending_ordered_provider_turn_commits.is_empty()); + assert_eq!(coordinator.pending_tasks(), 0); + assert_eq!(coordinator.pending_outcomes(), 0); + for task_id in [first, second, third] { + assert!(matches!( + workers.worker(task_id).expect("worker").state, + crate::chat::turn_worker::ProviderTurnWorkerState::Committed + )); + } +} + +#[tokio::test] +async fn provider_turn_finalizer_drain_helper_publishes_queue_and_worker_status() { + let mut scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let task_id = scheduler.enqueue( + "publish finalizer", + crate::chat::turn_scheduler::TurnPriority::Normal, + 1, + ); + scheduler.start_task(task_id).expect("task starts"); + let mut coordinator = crate::chat::history_commit::HistoryCommitCoordinator::new(); + coordinator + .register_task(scheduler.task(task_id).expect("task snapshot")) + .expect("history task registers"); + let mut workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + workers + .start_from_task( + scheduler.task(task_id).expect("task snapshot"), + crate::chat::turn_worker::ProviderTurnWorkerKind::Detached, + ) + .expect("worker starts"); + workers.record_execution_started(task_id, 63).expect("execution starts"); + workers.record_completion_ready(task_id).expect("completion ready"); + let mut queue = std::collections::VecDeque::new(); + enqueue_provider_turn_finalizer_event( + &mut queue, + Some(task_id), + ProviderTurnTerminalPlan::Completed { + final_text: "published".to_string(), + reasoning: String::new(), + recorded_response: "published".to_string(), + empty_response: false, + usage: crate::llm::route_decision::TokenUsage { + total_tokens: Some(63), + ..Default::default() + }, + history_commit_len: 2, + final_text_chars: 9, + recorded_response_chars: 9, + summary: "test finalizer published", + }, + ); + let (dispatcher, mut rx) = dispatcher::ChatDispatcher::new(); + + let results = drain_provider_turn_finalizer_events_and_publish( + &mut scheduler, + &mut coordinator, + &mut workers, + &mut queue, + &dispatcher, + ); + + assert_eq!(results.len(), 1); + assert!(results[0].finalized); + assert!(queue.is_empty()); + let first = rx.recv().await.expect("main queue status action"); + let second = rx.recv().await.expect("provider worker status action"); + assert!(matches!( + first, + crate::chat::action::Action::MainQueueStatusUpdated { .. } + )); + match second { + crate::chat::action::Action::ProviderWorkerStatusUpdated { status } => { + assert_eq!(status.finalized_payloads, 1); + assert_eq!(status.finalized_total_tokens, 63); + } + other => panic!("unexpected action: {other:?}"), + } +} + +#[test] +fn provider_terminal_plan_completed_non_empty_builds_gate_fields() { + let tools: Vec> = Vec::new(); + let resolved = ResolvedProviderTurnCompletion { + outcome: Some(dispatcher::TurnOutcomeKind::Completed { + final_text: "P7J terminal plan".to_string(), + reasoning: "kept reasoning".to_string(), + }), + usage: crate::llm::route_decision::TokenUsage { + total_tokens: Some(77), + ..Default::default() + }, + }; + + let plan = provider_turn_terminal_plan_from_completion(resolved, 4, &tools); + + match plan { + ProviderTurnTerminalPlan::Completed { + final_text, + recorded_response, + reasoning, + empty_response, + usage, + history_commit_len, + final_text_chars, + recorded_response_chars, + summary, + } => { + assert_eq!(final_text, "P7J terminal plan"); + assert_eq!(recorded_response, "P7J terminal plan"); + assert_eq!(reasoning, "kept reasoning"); + assert!(!empty_response); + assert_eq!(usage.total_tokens, Some(77)); + assert_eq!(history_commit_len, 5); + assert_eq!(final_text_chars, "P7J terminal plan".chars().count()); + assert_eq!(recorded_response_chars, "P7J terminal plan".chars().count()); + assert_eq!(summary, "redux driver completed"); + } + other => panic!("unexpected terminal plan: {other:?}"), + } +} + +#[test] +fn provider_terminal_plan_empty_failed_and_cancelled_keep_boundaries() { + let tools: Vec> = Vec::new(); + let empty = provider_turn_terminal_plan_from_completion( + ResolvedProviderTurnCompletion { + outcome: Some(dispatcher::TurnOutcomeKind::Completed { + final_text: " ".to_string(), + reasoning: "hidden reasoning".to_string(), + }), + usage: crate::llm::route_decision::TokenUsage::default(), + }, + 6, + &tools, + ); + match empty { + ProviderTurnTerminalPlan::Completed { + empty_response, + history_commit_len, + final_text_chars, + recorded_response_chars, + summary, + .. + } => { + assert!(empty_response); + assert_eq!(history_commit_len, 6); + assert_eq!(final_text_chars, 0); + assert_eq!(recorded_response_chars, 0); + assert_eq!(summary, "redux driver completed with empty response"); + } + other => panic!("unexpected empty terminal plan: {other:?}"), + } + + let failed = provider_turn_terminal_plan_from_completion( + ResolvedProviderTurnCompletion { + outcome: Some(dispatcher::TurnOutcomeKind::Failed { + err: "provider failed".to_string(), + retryable: false, + }), + usage: crate::llm::route_decision::TokenUsage::default(), + }, + 7, + &tools, + ); + match failed { + ProviderTurnTerminalPlan::Failed { + err, + history_commit_len, + summary, + } => { + assert_eq!(err, "provider failed"); + assert_eq!(history_commit_len, 7); + assert_eq!(summary, "redux driver failed: provider failed"); + } + other => panic!("unexpected failed terminal plan: {other:?}"), + } + + let cancelled = provider_turn_terminal_plan_from_completion( + ResolvedProviderTurnCompletion { + outcome: None, + usage: crate::llm::route_decision::TokenUsage::default(), + }, + 8, + &tools, + ); + match cancelled { + ProviderTurnTerminalPlan::Cancelled { summary } => { + assert_eq!(summary, "redux driver cancelled"); + } + other => panic!("unexpected cancelled terminal plan: {other:?}"), + } +} + +#[tokio::test] +async fn active_turn_sessions_command_is_handled_without_enqueue() { + let mut backlog = std::collections::VecDeque::new(); + enqueue_input_message(&mut backlog, input_msg("normal one")); + let scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let msg = input_msg("/sessions"); + let chat_session = session::ChatSession::new("p", "m"); + let provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + let mut chat_sessions = + crate::chat::sessions::ChatSessionsHandle::new(std::sync::Arc::new(tokio::sync::RwLock::new(Vec::new()))); + let session_rings = std::collections::HashMap::new(); + let mut reaped_log_archive = ReapedSessionLogArchive::default(); + let reap_policy = crate::chat::sessions::runtime::ReapPolicy::default(); + let tools_registry: Vec> = Vec::new(); + let daemon_config = Config::default(); + let (daemon_dispatcher, _daemon_action_rx) = dispatcher::ChatDispatcher::new(); + let daemon_control = DaemonControl { + config: &daemon_config, + dispatcher: &daemon_dispatcher, + redraw_tx: None, + }; + + let output = active_turn_local_command_output( + &msg, + &backlog, + &scheduler, + &chat_session, + &provider_turn_workers, + &mut chat_sessions, + &session_rings, + &mut reaped_log_archive, + &reap_policy, + &tools_registry, + daemon_control, + ) + .await + .expect("sessions command output"); + + assert_eq!( + output, + format!("current chat session: {}\nNo child TUI sessions.", chat_session.id) + ); + assert_eq!(backlog.len(), 1, "read-only sessions command must not mutate backlog"); +} + +/// A `--daemon` command exists to look at, or end, work in another +/// process — and the moment an operator reaches for one is precisely while +/// a long turn is running here. Queueing them behind that turn made the +/// feature unavailable exactly when it was wanted, so both entry points +/// have to answer: the whitelist that decides what stays answerable, and +/// the dispatch that actually runs it. +#[tokio::test] +async fn active_turn_daemon_commands_run_instead_of_queueing() { + let mut daemon_config = Config::default(); + // A closed port: the request fails on its own, promptly, in its task. + daemon_config.chat.daemon.url = "http://127.0.0.1:1".to_string(); + let (daemon_dispatcher, _daemon_action_rx) = dispatcher::ChatDispatcher::new(); + let daemon_control = DaemonControl { + config: &daemon_config, + dispatcher: &daemon_dispatcher, + redraw_tx: None, + }; + + for (command, expected) in [ + ("/sessions --daemon", "Listing daemon work at http://127.0.0.1:1"), + ( + "/kill --daemon w42", + "Asking the daemon at http://127.0.0.1:1 to kill w42", + ), + ( + "/steer --daemon w42 change course", + "Sending a message to daemon task w42 at http://127.0.0.1:1", + ), + ] { + assert!( + is_active_turn_local_command(command), + "{command} must stay answerable while a turn is in flight" + ); + + let mut backlog = std::collections::VecDeque::new(); + enqueue_input_message(&mut backlog, input_msg("normal one")); + let scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let chat_session = session::ChatSession::new("p", "m"); + let provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + let mut chat_sessions = + crate::chat::sessions::ChatSessionsHandle::new(std::sync::Arc::new(tokio::sync::RwLock::new(Vec::new()))); + let session_rings = std::collections::HashMap::new(); + let mut reaped_log_archive = ReapedSessionLogArchive::default(); + let reap_policy = crate::chat::sessions::runtime::ReapPolicy::default(); + let tools_registry: Vec> = Vec::new(); + + let output = active_turn_local_command_output( + &input_msg(command), + &backlog, + &scheduler, + &chat_session, + &provider_turn_workers, + &mut chat_sessions, + &session_rings, + &mut reaped_log_archive, + &reap_policy, + &tools_registry, + daemon_control, + ) + .await + .unwrap_or_else(|| panic!("{command} must be answered during a turn, not queued")); + + assert!(output.contains(expected), "{command}: {output}"); + assert_eq!(backlog.len(), 1, "{command} must not be enqueued behind the turn"); + } +} + +/// The idle loop runs the same three commands through +/// `start_daemon_session_command`, so the two entry points cannot drift +/// apart again: this is the whole of what the loop's `Daemon*` arm does. +#[tokio::test] +async fn the_idle_loop_entry_point_starts_the_same_three_commands() { + let mut daemon_config = Config::default(); + daemon_config.chat.daemon.url = "http://127.0.0.1:1".to_string(); + let (daemon_dispatcher, _daemon_action_rx) = dispatcher::ChatDispatcher::new(); + let control = DaemonControl { + config: &daemon_config, + dispatcher: &daemon_dispatcher, + redraw_tx: None, + }; + let in_flight = crate::chat::sessions::daemon::new_in_flight_registry(); + + for (action, expected) in [ + ( + crate::chat::sessions::SessionCommand::DaemonSessions, + "Listing daemon work at http://127.0.0.1:1", + ), + ( + crate::chat::sessions::SessionCommand::DaemonKill { + address: "w42".to_string(), + }, + "Asking the daemon at http://127.0.0.1:1 to kill w42", + ), + ( + crate::chat::sessions::SessionCommand::DaemonSteer { + address: "w42".to_string(), + message: "change course".to_string(), + }, + "Sending a message to daemon task w42 at http://127.0.0.1:1", + ), + ] { + let notice = start_daemon_session_command(&action, None, &in_flight, control) + .unwrap_or_else(|| panic!("{action:?} must start a daemon request")); + assert!(notice.contains(expected), "{action:?}: {notice}"); + } + + // A local `/sessions` is not daemon-scoped and must fall through to the + // local handler rather than being swallowed here. + assert!( + start_daemon_session_command( + &crate::chat::sessions::SessionCommand::Sessions, + None, + &in_flight, + control + ) + .is_none() + ); +} + +/// §7-2's own argument, applied to chat's own cross-process call: in a +/// runtime with no wall clock, the fallback for something stuck is being +/// seen and being killed. A daemon that accepts the connection and then +/// answers nothing used to leave a spawned task that was neither. +#[cfg(feature = "terminal-tui")] +#[tokio::test] +async fn a_stuck_daemon_request_is_listed_and_can_be_ended() { + // A daemon that accepts the connection and then never answers. Nothing + // here expires: the request stays outstanding until it is ended. + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("test: bind ephemeral port"); + let addr = listener.local_addr().expect("test: local addr"); + let silent_daemon = tokio::spawn(async move { + let held = listener.accept().await; + std::future::pending::<()>().await; + drop(held); + }); + + let mut daemon_config = Config::default(); + daemon_config.chat.daemon.url = format!("http://{addr}"); + let (daemon_dispatcher, mut daemon_action_rx) = dispatcher::ChatDispatcher::new(); + let control = DaemonControl { + config: &daemon_config, + dispatcher: &daemon_dispatcher, + redraw_tx: None, + }; + let mut chat_sessions = + crate::chat::sessions::ChatSessionsHandle::new(std::sync::Arc::new(tokio::sync::RwLock::new(Vec::new()))); + let in_flight = chat_sessions.daemon_requests(); + let session_rings = std::collections::HashMap::new(); + let mut reaped_log_archive = ReapedSessionLogArchive::default(); + let reap_policy = crate::chat::sessions::runtime::ReapPolicy::default(); + let tools_registry: Vec> = Vec::new(); + + let notice = start_daemon_session_command( + &crate::chat::sessions::SessionCommand::DaemonSessions, + None, + &in_flight, + control, + ) + .expect("test: the listing request starts"); + assert!(notice.contains("Listing daemon work at"), "{notice}"); + + // Visible: the hung request shows up in this chat's own `/sessions`. + let listing = handle_local_session_command( + &crate::chat::sessions::SessionCommand::Sessions, + &mut chat_sessions, + &session_rings, + &mut reaped_log_archive, + &reap_policy, + &tools_registry, + ) + .await + .expect("test: /sessions renders"); + assert!(listing.contains("Daemon requests in flight (1)"), "{listing}"); + assert!(listing.contains("d1 list"), "{listing}"); + + // Killable: ending it by address stops the task, which then reports + // back instead of hanging on a daemon that will never answer. + let killed = start_daemon_session_command( + &crate::chat::sessions::SessionCommand::DaemonKill { + address: "d1".to_string(), + }, + None, + &in_flight, + control, + ) + .expect("test: d1 is this chat's own address space"); + assert!(killed.contains("Stopped waiting on daemon request d1"), "{killed}"); + + let reported = tokio::time::timeout(Duration::from_secs(10), async { + loop { + match daemon_action_rx.recv().await { + Some(crate::chat::action::Action::SystemMessageAdded { text }) => return text, + Some(_) => (), + None => return String::new(), + } + } + }) + .await + .expect("test: an ended request must report back rather than leak"); + assert!( + reported.contains("was ended from this chat before the daemon answered"), + "{reported}" + ); + + silent_daemon.abort(); +} diff --git a/src/chat/tests/p3_directional_switch_tests/section_3.rs b/src/chat/tests/p3_directional_switch_tests/section_3.rs new file mode 100644 index 000000000..d3297cc88 --- /dev/null +++ b/src/chat/tests/p3_directional_switch_tests/section_3.rs @@ -0,0 +1,206 @@ +#[tokio::test] +async fn active_turn_logs_command_is_handled_without_enqueue() { + let mut backlog = std::collections::VecDeque::new(); + enqueue_input_message(&mut backlog, input_msg("normal one")); + let scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let msg = input_msg("/logs #99"); + let chat_session = session::ChatSession::new("p", "m"); + let provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + let mut chat_sessions = + crate::chat::sessions::ChatSessionsHandle::new(std::sync::Arc::new(tokio::sync::RwLock::new(Vec::new()))); + let session_rings = std::collections::HashMap::new(); + let mut reaped_log_archive = ReapedSessionLogArchive::default(); + let reap_policy = crate::chat::sessions::runtime::ReapPolicy::default(); + let tools_registry: Vec> = Vec::new(); + let daemon_config = Config::default(); + let (daemon_dispatcher, _daemon_action_rx) = dispatcher::ChatDispatcher::new(); + let daemon_control = DaemonControl { + config: &daemon_config, + dispatcher: &daemon_dispatcher, + redraw_tx: None, + }; + + let output = active_turn_local_command_output( + &msg, + &backlog, + &scheduler, + &chat_session, + &provider_turn_workers, + &mut chat_sessions, + &session_rings, + &mut reaped_log_archive, + &reap_policy, + &tools_registry, + daemon_control, + ) + .await + .expect("logs command output"); + + assert!(output.contains("Logs failed: no session #99"), "{output}"); + assert_eq!(backlog.len(), 1, "read-only logs command must not mutate backlog"); +} + +#[tokio::test] +async fn active_turn_kill_command_is_handled_without_enqueue() { + let mut backlog = std::collections::VecDeque::new(); + enqueue_input_message(&mut backlog, input_msg("normal one")); + let scheduler = crate::chat::turn_scheduler::TurnScheduler::new(); + let msg = input_msg("/kill #99"); + let chat_session = session::ChatSession::new("p", "m"); + let provider_turn_workers = crate::chat::turn_worker::ProviderTurnWorkerRegistry::new(); + let mut chat_sessions = + crate::chat::sessions::ChatSessionsHandle::new(std::sync::Arc::new(tokio::sync::RwLock::new(Vec::new()))); + let session_rings = std::collections::HashMap::new(); + let mut reaped_log_archive = ReapedSessionLogArchive::default(); + let reap_policy = crate::chat::sessions::runtime::ReapPolicy::default(); + let tools_registry: Vec> = Vec::new(); + let daemon_config = Config::default(); + let (daemon_dispatcher, _daemon_action_rx) = dispatcher::ChatDispatcher::new(); + let daemon_control = DaemonControl { + config: &daemon_config, + dispatcher: &daemon_dispatcher, + redraw_tx: None, + }; + + let output = active_turn_local_command_output( + &msg, + &backlog, + &scheduler, + &chat_session, + &provider_turn_workers, + &mut chat_sessions, + &session_rings, + &mut reaped_log_archive, + &reap_policy, + &tools_registry, + daemon_control, + ) + .await + .expect("kill command output"); + + assert!(output.contains("Kill failed: no session #99"), "{output}"); + assert_eq!(backlog.len(), 1, "explicit kill command must not mutate backlog"); +} + +#[test] +fn queued_input_scheduler_prefers_priority_over_older_normal() { + let mut backlog = std::collections::VecDeque::new(); + enqueue_input_message(&mut backlog, input_msg("normal one")); + enqueue_input_message(&mut backlog, input_msg("/priority urgent two")); + enqueue_input_message(&mut backlog, input_msg("normal three")); + + let first = pop_next_queued_input_message(&mut backlog) + .map(|queued| queued.msg) + .expect("priority first"); + let second = pop_next_queued_input_message(&mut backlog) + .map(|queued| queued.msg) + .expect("normal one second"); + let third = pop_next_queued_input_message(&mut backlog) + .map(|queued| queued.msg) + .expect("normal three third"); + + assert_eq!(first.content, "urgent two"); + assert_eq!(second.content, "normal one"); + assert_eq!(third.content, "normal three"); +} + +#[test] +fn cancelled_turn_rolls_back_legacy_history_user_message() { + let mut history = vec![ + ChatMessage::system("system"), + ChatMessage::user("previous question"), + ChatMessage::assistant("previous answer"), + ]; + let len_before = history.len(); + history.push(ChatMessage::user("cancelled long task")); + + rollback_cancelled_turn_history(&mut history, len_before); + + assert_eq!(history.len(), len_before); + assert!( + history.iter().all(|message| message.content != "cancelled long task"), + "cancelled turn must not leak into the next queued prompt" + ); +} + +#[test] +fn p4a_shutdown_cancelled_pending_turn_rolls_back_to_user_boundary() { + let mut history = vec![ + ChatMessage::system("system"), + ChatMessage::user("previous question"), + ChatMessage::assistant("previous answer"), + ]; + let len_before_user_turn = history.len(); + history.push(ChatMessage::user("pending provider turn")); + history.push(ChatMessage::assistant("partial assistant text")); + + rollback_cancelled_turn_history(&mut history, len_before_user_turn); + + assert_eq!(history.len(), len_before_user_turn); + assert!( + history + .iter() + .all(|message| message.content != "pending provider turn" && message.content != "partial assistant text"), + "shutdown cancellation must remove both the queued user turn and partial assistant output" + ); +} + +#[test] +fn queued_input_notice_is_single_line_and_bounded() { + let notice = format_queued_input_notice(" first line\nsecond\tline ", InputQueuePriority::Normal); + assert_eq!(notice, "queued > first line second line"); + + let long = format_queued_input_notice(&"x".repeat(220), InputQueuePriority::Normal); + assert!(long.starts_with("queued > ")); + assert!(long.ends_with('…')); + assert!(long.chars().count() <= "queued > ".chars().count() + 160); + + let priority = format_queued_input_notice("/now urgent", InputQueuePriority::Priority); + assert_eq!(priority, "priority queued > urgent"); +} + +#[test] +fn active_turn_local_notice_strips_priority_prefix() { + assert!(is_active_turn_local_command("/now /cost")); + assert!(is_active_turn_local_command("/workers")); + assert!(is_active_turn_local_command("/workers cancel w#1")); + assert!(is_active_turn_local_command("/sessions")); + assert!(is_active_turn_local_command("/now /logs #1")); + assert!(is_active_turn_local_command("/priority /kill 2")); + assert!(!is_active_turn_local_command("/bg create child")); + assert_eq!(format_active_turn_local_notice("/now /cost"), "local > /cost"); + assert_eq!( + format_active_turn_local_notice("/priority /queue status"), + "local > /queue status" + ); + assert_eq!( + format_active_turn_local_notice("/priority /workers cancel #2"), + "local > /workers cancel #2" + ); +} + +#[test] +fn session_to_session_switch_suppresses_attach_breadcrumb_spam() { + let meta = session_view(1); + let projection = + build_active_session_attach_projection(1, Some(&meta), vec!["tail".into()], vec!["ring".into()], false); + + assert!( + attach_breadcrumb_for_transition(false, &projection).is_some(), + "Main->Session entry keeps one breadcrumb" + ); + + let switches = [ + build_active_session_attach_projection(2, Some(&session_view(2)), Vec::new(), Vec::new(), false), + build_active_session_attach_projection(3, Some(&session_view(3)), Vec::new(), Vec::new(), false), + build_active_session_attach_projection(1, Some(&session_view(1)), Vec::new(), Vec::new(), false), + ]; + let emitted = switches + .iter() + .filter_map(|projection| attach_breadcrumb_for_transition(true, projection)) + .count(); + assert_eq!( + emitted, 0, + "Session->Session directional cycling must not append extra main-history breadcrumbs" + ); +} diff --git a/src/config/generation.rs b/src/config/generation.rs index 63a2964c9..ebd27da1f 100644 --- a/src/config/generation.rs +++ b/src/config/generation.rs @@ -4,2285 +4,5 @@ //! configuration. Readers pin an immutable [`ConfigGeneration`] (or its //! `Arc` payload) for the lifetime of one operation. -use super::{files::compute_config_revision_gated, schema::Config}; -use anyhow::Context; -use arc_swap::ArcSwap; -use chrono::{DateTime, Utc}; -use parking_lot::{Mutex, RwLock}; -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; -use std::{ - collections::{BTreeMap, BTreeSet}, - path::{Path, PathBuf}, - sync::{ - Arc, Weak, - atomic::{AtomicBool, AtomicU64, Ordering}, - }, -}; - -/// Resolve the existing part of a process-bound path and retain any missing -/// tail. This gives aliases one filesystem identity while keeping a pinned -/// binding verifiable if its config file is removed after launch. -fn process_path_identity(path: &Path) -> anyhow::Result { - if path.as_os_str().is_empty() { - return Ok(PathBuf::new()); - } - let mut cursor = path.to_path_buf(); - let mut missing = Vec::new(); - loop { - match cursor.canonicalize() { - Ok(mut resolved) => { - for segment in missing.iter().rev() { - resolved.push(segment); - } - return Ok(resolved); - } - Err(error) => { - let Some(segment) = cursor.file_name().map(ToOwned::to_owned) else { - return Err(error) - .with_context(|| format!("failed to resolve process-bound path {}", path.display())); - }; - missing.push(segment); - if !cursor.pop() { - return Err(error) - .with_context(|| format!("failed to resolve process-bound path {}", path.display())); - } - } - } - } -} - -pub(crate) fn process_paths_match(left: &Path, right: &Path) -> anyhow::Result { - Ok(process_path_identity(left)? == process_path_identity(right)?) -} - -/// Stable revision of the desired configuration source. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct ConfigSourceRevision { - pub fingerprint_sha256: String, - pub disk_generation: Option, -} - -impl ConfigSourceRevision { - fn from_config(config: &Config) -> anyhow::Result { - if !config.config_path.as_os_str().is_empty() && config.config_path.exists() { - let (fingerprint, disk_generation) = compute_config_revision_gated(&config.config_path)?; - return Ok(Self { - fingerprint_sha256: fingerprint.iter().map(|byte| format!("{byte:02x}")).collect(), - disk_generation: Some(disk_generation), - }); - } - - let encoded = serde_json::to_vec(&normalized_process_config(config)?)?; - Ok(Self { - fingerprint_sha256: format!("{:x}", Sha256::digest(encoded)), - disk_generation: None, - }) - } -} - -/// Monotonic, process-local identifier of an actually published generation. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -pub struct ConfigGenerationId(pub u64); - -/// Origin of a reload attempt. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum ConfigReloadTrigger { - Startup, - FileWatcher, - Api, - Tool, - ConfigFileApi, - PairingPersistence, - /// A configuration management transaction: an operator rollback, or the - /// restore of a change the runtime refused. - Management, - Test, -} - -/// A desired field that is valid on disk but cannot be activated in-process. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct DeferredConfigChange { - pub field: String, - pub reason: String, -} - -/// Immutable runtime configuration generation. -#[derive(Debug, Clone)] -pub struct ConfigGeneration { - pub id: ConfigGenerationId, - pub source_revision: ConfigSourceRevision, - pub effective: Arc, - pub applied_at: DateTime, - pub trigger: ConfigReloadTrigger, - pub deferred_changes: Arc<[DeferredConfigChange]>, -} - -/// A worker cannot replace the working root selected by its parent. -#[derive(Debug, thiserror::Error)] -#[error("worker working root differs from signed parent configuration")] -pub(crate) struct ProcessWorkingRootMismatch; - -/// Metadata, a working root override and a keyed effective snapshot digest. -/// Credential values and other configuration overrides are not transported. -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct ProcessGenerationBinding { - /// Parent in-memory working root, authenticated by the effective-config seal. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub working_root: Option, - pub id: ConfigGenerationId, - pub source_revision: ConfigSourceRevision, - pub applied_at: DateTime, - pub trigger: ConfigReloadTrigger, - pub deferred_changes: Vec, - pub seal: [u8; 32], -} - -// Disk migration materializes the inherited backend. Fingerprints and seals -// must bind the same representation while retaining explicit overrides. -fn normalized_process_config(config: &Config) -> anyhow::Result { - let mut normalized = serde_json::to_value(config)?; - let backend = crate::config::schema::decision_engine::effective_engine_backend(config); - let mut engine = config.decision_engine.clone(); - engine.backend = Some(backend.clone()); - if let Some(root) = normalized.as_object_mut() { - root.insert("decision_engine".into(), serde_json::to_value(engine)?); - } - normalized.sort_all_objects(); - Ok(normalized) -} - -impl ProcessGenerationBinding { - pub(crate) fn signing_payload(&self, config: &Config) -> anyhow::Result> { - // Config excludes both paths from serde; bind them explicitly. Sort - // nested maps so process-specific HashMap iteration cannot change a tag. - let workspace = process_path_identity(&config.workspace_dir)?; - let config_path = process_path_identity(&config.config_path)?; - let normalized = normalized_process_config(config)?; - let mut value = serde_json::to_value(( - self.id, - &self.source_revision, - self.applied_at, - self.trigger, - &self.deferred_changes, - workspace, - config_path, - ))?; - value.sort_all_objects(); - value - .as_array_mut() - .context("process signing metadata must serialize as an array")? - .push(normalized); - Ok(serde_json::to_vec(&value)?) - } -} - -impl ConfigGeneration { - /// Pin an ordinary child without startup globals or disk reloads. - pub(crate) fn for_child(config: &Config) -> anyhow::Result> { - let mut value = serde_json::to_value((&config.workspace_dir, &config.config_path, config))?; - value.sort_all_objects(); - let encoded = serde_json::to_vec(&value)?; - Ok(Arc::new(Self { - id: ConfigGenerationId(0), - source_revision: ConfigSourceRevision { - fingerprint_sha256: format!("{:x}", Sha256::digest(encoded)), - disk_generation: None, - }, - effective: Arc::new(config.clone()), - applied_at: Utc::now(), - trigger: ConfigReloadTrigger::Startup, - deferred_changes: Arc::from([]), - })) - } - - pub(crate) fn bind_process( - &self, - key: &crate::security::runtime_key::DecisionKey, - ) -> anyhow::Result { - anyhow::ensure!( - self.source_revision.fingerprint_sha256.len() == 64 - && self - .source_revision - .fingerprint_sha256 - .bytes() - .all(|byte| byte.is_ascii_hexdigit()), - "process configuration source revision is unavailable" - ); - let mut binding = ProcessGenerationBinding { - working_root: self.effective.runtime.workdir.clone(), - id: self.id, - source_revision: self.source_revision.clone(), - applied_at: self.applied_at, - trigger: self.trigger, - deferred_changes: self.deferred_changes.to_vec(), - seal: [0; 32], - }; - binding.seal = key.hmac( - crate::security::runtime_key::KeyDomain::StateFingerprint, - &[ - b"process-effective-config-v1", - &binding.signing_payload(&self.effective)?, - ], - ); - Ok(binding) - } - - /// Authenticate a parent-owned pinned generation without reopening mutable disk state. - pub(crate) fn verify_pinned_process_binding( - &self, - binding: &ProcessGenerationBinding, - key: &crate::security::runtime_key::DecisionKey, - ) -> anyhow::Result<()> { - let deferred_changes_match = self.deferred_changes.as_ref() == binding.deferred_changes.as_slice(); - anyhow::ensure!( - self.effective.runtime.workdir == binding.working_root - && self.id == binding.id - && self.source_revision == binding.source_revision - && self.applied_at == binding.applied_at - && self.trigger == binding.trigger - && deferred_changes_match, - "pinned process generation differs from launch" - ); - anyhow::ensure!( - key.verify_hmac( - crate::security::runtime_key::KeyDomain::StateFingerprint, - &[ - b"process-effective-config-v1", - &binding.signing_payload(&self.effective)? - ], - &binding.seal, - ), - "pinned process effective configuration differs from launch" - ); - Ok(()) - } - - /// Restore only an exact snapshot. A newer disk revision or a configuration - /// with different effective values cannot borrow the parent's generation id. - pub(crate) fn restore_process( - config: Config, - binding: &ProcessGenerationBinding, - key: &crate::security::runtime_key::DecisionKey, - ) -> anyhow::Result> { - if config.runtime.workdir != binding.working_root { - return Err(ProcessWorkingRootMismatch.into()); - } - anyhow::ensure!( - ConfigSourceRevision::from_config(&config)? == binding.source_revision, - "process configuration source differs from parent generation" - ); - anyhow::ensure!( - key.verify_hmac( - crate::security::runtime_key::KeyDomain::StateFingerprint, - &[b"process-effective-config-v1", &binding.signing_payload(&config)?], - &binding.seal - ), - "process effective configuration differs from parent generation" - ); - Ok(Arc::new(Self { - id: binding.id, - source_revision: binding.source_revision.clone(), - effective: Arc::new(config), - applied_at: binding.applied_at, - trigger: binding.trigger, - deferred_changes: binding.deferred_changes.clone().into(), - })) - } -} - -/// Latest valid configuration found on disk, including fields awaiting restart. -#[derive(Debug, Clone)] -pub struct DesiredConfigState { - pub source_revision: ConfigSourceRevision, - pub config: Arc, - pub observed_at: DateTime, -} - -/// Structured result shared by watcher, API and tool reload entry points. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ConfigApplyReport { - pub active_generation: ConfigGenerationId, - pub active_source_revision: ConfigSourceRevision, - pub desired_source_revision: ConfigSourceRevision, - pub changed: Vec, - pub applied: Vec, - pub rebuilt: Vec, - pub restarted: Vec, - pub restart_required: Vec, - pub participant_acks: Vec, -} - -impl ConfigApplyReport { - #[must_use] - pub const fn has_runtime_change(&self) -> bool { - !(self.applied.is_empty() && self.rebuilt.is_empty() && self.restarted.is_empty()) - } - - #[must_use] - pub const fn status(&self) -> &'static str { - if self.changed.is_empty() { - "unchanged" - } else if self.restart_required.is_empty() { - "applied" - } else if self.has_runtime_change() { - "applied_with_restart_required" - } else { - "restart_required" - } - } -} - -/// Most recent reload failure retained for doctor/health/config status. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ConfigReloadFailure { - pub occurred_at: DateTime, - pub trigger: ConfigReloadTrigger, - pub desired_source_revision: Option, - pub error: String, -} - -/// Read-only process status for the generation coordinator. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ConfigGenerationStatus { - pub active_generation: ConfigGenerationId, - pub active_source_revision: ConfigSourceRevision, - pub desired_source_revision: ConfigSourceRevision, - pub reload_in_progress: bool, - pub last_report: Option, - pub last_failure: Option, - pub registered_participants: Vec, -} - -/// Reload/supervisor event emitted into the existing MessageEvent ledger. -#[derive(Debug, Clone, Serialize)] -pub struct ConfigGenerationAuditEvent { - pub event_type: String, - pub generation_id: Option, - pub source_revision: Option, - pub trigger: ConfigReloadTrigger, - pub payload: serde_json::Value, -} - -/// Adapter used to route config lifecycle events to the process event fabric. -pub trait ConfigGenerationAuditSink: Send + Sync { - fn record(&self, event: ConfigGenerationAuditEvent); -} - -/// Sole process-level owner of active and desired configuration generations. -pub struct ConfigGenerationManager { - runtime_writes_frozen: AtomicBool, - active: ArcSwap, - /// Published generations remain addressable while an admitted operation - /// still owns its exact snapshot. Weak entries retain no configuration or - /// credentials after the last operation releases that generation. - published: Mutex>>, - desired: ArcSwap, - reload_lock: Mutex<()>, - next_generation: AtomicU64, - participants: RwLock>>, - reload_in_progress: AtomicBool, - last_report: RwLock>, - last_failure: RwLock>, - audit_sinks: RwLock>>, - /// The configured-model allowlist refreshed with every generation. - model_allowlist: Arc, -} - -/// Runtime subsystem that must prepare a complete candidate before publication. -pub trait ConfigGenerationParticipant: Send + Sync { - fn name(&self) -> &'static str; - - /// Whether this participant can atomically rebuild a rebuild-and-swap field. - fn supports_rebuild_field(&self, _field: &str) -> bool { - false - } - - /// Whether this participant can perform a controlled restart for a field. - fn supports_controlled_restart_field(&self, _field: &str) -> bool { - false - } - - /// Whether the participant must prepare when this effective field changes. - fn prepares_for_field(&self, field: &str) -> bool { - self.supports_rebuild_field(field) || self.supports_controlled_restart_field(field) - } - - fn prepare( - &self, - generation: Arc, - changed_fields: &[String], - ) -> anyhow::Result>; -} - -/// Reversible commit produced by a successful participant preparation. -pub trait PreparedConfigGeneration: Send { - fn commit(&mut self) -> anyhow::Result<()>; - fn rollback(&mut self); - - /// Release rollback state after the manager has published active. - fn finalize(&mut self) {} -} - -impl std::fmt::Debug for ConfigGenerationManager { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let active = self.active.load(); - formatter - .debug_struct("ConfigGenerationManager") - .field("active_generation", &active.id) - .field("active_source_revision", &active.source_revision) - .finish_non_exhaustive() - } -} - -impl ConfigGenerationManager { - /// Build the process owner around the startup-effective configuration. - #[must_use] - pub fn new(initial: Config) -> Self { - Self::with_model_allowlist(initial, crate::observability::labels::ModelAllowlist::global()) - } - - /// Establish an owner for a standalone caller that already holds an - /// effective generation. Unlike startup loading, this never relabels the - /// snapshot using a later on-disk revision. A generation with deferred - /// fields needs its existing manager, which owns the distinct desired - /// configuration; an effective snapshot cannot reconstruct that state. - pub(crate) fn from_pinned_generation(generation: Arc) -> anyhow::Result { - anyhow::ensure!( - generation.deferred_changes.is_empty(), - "a generation with deferred configuration requires its existing manager" - ); - anyhow::ensure!( - !generation.source_revision.fingerprint_sha256.is_empty() - && generation.source_revision.fingerprint_sha256 != "startup-unavailable", - "pinned configuration source revision is unavailable" - ); - let next_generation = generation - .id - .0 - .checked_add(1) - .ok_or_else(|| anyhow::anyhow!("configuration generation counter is exhausted"))?; - let model_allowlist = crate::observability::labels::ModelAllowlist::global(); - // Preserve standalone startup setup, but take every value from the - // supplied effective snapshot rather than loading a new revision. - crate::config::set_runtime_proxy_config(generation.effective.proxy.clone()); - if let Some(warning) = crate::config::manage::validate::decision_startup_check(&generation.effective) { - tracing::warn!("{warning}"); - } - if generation.effective.decision_engine.enabled - && let Some(warning) = crate::config::manage::validate::decision_orphans_warning(&generation.effective) - { - tracing::warn!("{warning}"); - } - model_allowlist.refresh(&generation.effective); - let desired = Arc::new(DesiredConfigState { - source_revision: generation.source_revision.clone(), - config: Arc::clone(&generation.effective), - observed_at: generation.applied_at, - }); - let published = BTreeMap::from([(generation.id, Arc::downgrade(&generation))]); - Ok(Self { - active: ArcSwap::from(generation), - published: Mutex::new(published), - desired: ArcSwap::from(desired), - reload_lock: Mutex::new(()), - next_generation: AtomicU64::new(next_generation), - participants: RwLock::new(Vec::new()), - runtime_writes_frozen: AtomicBool::new(false), - reload_in_progress: AtomicBool::new(false), - last_report: RwLock::new(None), - last_failure: RwLock::new(None), - audit_sinks: RwLock::new(Vec::new()), - model_allowlist, - }) - } - - /// [`Self::new`] refreshing `model_allowlist` instead of the process - /// allowlist the metrics read. - fn with_model_allowlist( - initial: Config, - model_allowlist: Arc, - ) -> Self { - crate::config::set_runtime_proxy_config(initial.proxy.clone()); - // Startup never fails for the decision plane: a refused backend - // runs builtin-only, and says so (D-094 C-1). - if let Some(warning) = crate::config::manage::validate::decision_startup_check(&initial) { - tracing::warn!("{warning}"); - } - // Decision credentials left unreferenced are reported (D-094 C-5); - // a disabled engine does not read the credential store. - if initial.decision_engine.enabled - && let Some(warning) = crate::config::manage::validate::decision_orphans_warning(&initial) - { - tracing::warn!("{warning}"); - } - // Metric model labels follow the configured models (D-059). - model_allowlist.refresh(&initial); - let source_revision = ConfigSourceRevision::from_config(&initial).unwrap_or_else(|_| ConfigSourceRevision { - fingerprint_sha256: "startup-unavailable".to_string(), - disk_generation: None, - }); - let config = Arc::new(initial); - let generation = Arc::new(ConfigGeneration { - id: ConfigGenerationId(0), - source_revision: source_revision.clone(), - effective: Arc::clone(&config), - applied_at: Utc::now(), - trigger: ConfigReloadTrigger::Startup, - deferred_changes: Arc::from([]), - }); - let desired = Arc::new(DesiredConfigState { - source_revision, - config, - observed_at: Utc::now(), - }); - let published = BTreeMap::from([(generation.id, Arc::downgrade(&generation))]); - Self { - active: ArcSwap::from(generation), - published: Mutex::new(published), - desired: ArcSwap::from(desired), - reload_lock: Mutex::new(()), - next_generation: AtomicU64::new(1), - participants: RwLock::new(Vec::new()), - runtime_writes_frozen: AtomicBool::new(false), - reload_in_progress: AtomicBool::new(false), - last_report: RwLock::new(None), - last_failure: RwLock::new(None), - audit_sinks: RwLock::new(Vec::new()), - model_allowlist, - } - } - - /// A runtime may only narrow this policy; no Config field clears it. - pub(crate) fn freeze_runtime_writes(&self) { - self.runtime_writes_frozen.store(true, Ordering::Release); - } - pub(crate) fn ensure_runtime_writable(&self) -> anyhow::Result<()> { - anyhow::ensure!( - !self.runtime_writes_frozen.load(Ordering::Acquire), - "configuration is frozen for controlled experiments" - ); - Ok(()) - } - - /// Register a weakly-held runtime participant. - /// - /// The caller retains the strong `Arc`; stale registrations disappear when - /// their owning component is dropped or restarted. - pub fn register_participant(&self, participant: &Arc) { - let _reload_guard = self.reload_lock.lock(); - self.participants.write().push(Arc::downgrade(participant)); - } - - /// Register an event-fabric adapter for reload and supervisor lifecycle audit. - pub fn register_audit_sink(&self, sink: Arc) { - self.audit_sinks.write().push(sink); - } - - /// Pin the complete immutable active generation for one operation. - #[must_use] - pub fn pin(&self) -> Arc { - self.active.load_full() - } - - /// Recover one published generation only while an admitted operation still - /// pins it. This lets long-lived tool registries resolve the provider owned - /// by an in-flight turn without retaining superseded credentials forever. - #[must_use] - pub(crate) fn pin_generation(&self, id: ConfigGenerationId) -> Option> { - let active = self.active.load_full(); - if active.id == id { - return Some(active); - } - let mut published = self.published.lock(); - published.retain(|_, generation| generation.strong_count() > 0); - published.get(&id).and_then(Weak::upgrade) - } - - /// Compatibility accessor for readers that only need the effective config. - #[must_use] - pub fn load_full(&self) -> Arc { - Arc::clone(&self.active.load_full().effective) - } - - /// Compatibility accessor matching the former ArcSwap reader surface. - #[must_use] - pub fn load(&self) -> Arc { - self.load_full() - } - - /// Return the latest desired configuration, including deferred fields. - #[must_use] - pub fn desired(&self) -> Arc { - self.desired.load_full() - } - - #[must_use] - pub fn active_generation_id(&self) -> ConfigGenerationId { - self.active.load().id - } - - /// Snapshot coordinator status without exposing mutation primitives. - #[must_use] - pub fn status(&self) -> ConfigGenerationStatus { - let active = self.active.load_full(); - let desired = self.desired.load_full(); - let mut registered_participants = self - .participants - .read() - .iter() - .filter_map(Weak::upgrade) - .map(|participant| participant.name().to_string()) - .collect::>(); - registered_participants.sort(); - registered_participants.dedup(); - ConfigGenerationStatus { - active_generation: active.id, - active_source_revision: active.source_revision.clone(), - desired_source_revision: desired.source_revision.clone(), - reload_in_progress: self.reload_in_progress.load(Ordering::Acquire), - last_report: self.last_report.read().clone(), - last_failure: self.last_failure.read().clone(), - registered_participants, - } - } - - /// Load a stable merged snapshot from the configured source and apply it. - pub fn reload_from_disk(&self, trigger: ConfigReloadTrigger) -> anyhow::Result { - self.ensure_runtime_writable()?; - let current = self.load_full(); - let config_path = current.config_path.clone(); - if config_path.as_os_str().is_empty() { - let error = anyhow::anyhow!("Config path is not set; cannot reload"); - self.record_failure(trigger, None, &error); - return Err(error); - } - // The revision is the one the loaded files had, not one read again - // afterwards: a write landing in between must not be published as the - // revision of content that does not contain it. - let (fresh, revision) = match load_stable_config_snapshot(&config_path, current.workspace_dir.clone()) { - Ok(snapshot) => snapshot, - Err(error) => { - self.record_failure(trigger, None, &error); - return Err(error); - } - }; - #[cfg(test)] - run_after_snapshot_hook(&config_path); - // An operator's file edit is trusted and applied without - // confirmation; one that sends decisions off the machine is said so, - // once the reload is applied (D-079 L-4, D-082 N-4). It is compared - // with the desired configuration, so an edit already published and - // waiting for a restart is not reported again. - let remote_paths = if matches!(trigger, ConfigReloadTrigger::FileWatcher | ConfigReloadTrigger::Tool) { - hand_edited_remote_decisions(&self.desired().config, &fresh) - } else { - Vec::new() - }; - let report = self.apply_config(fresh, revision, trigger)?; - for path in remote_paths { - tracing::warn!( - path = %path, - "a configuration file edit sends decision state off this machine; it was applied without \ - confirmation because the operator edited the file" - ); - } - Ok(report) - } - - /// Publish a validated desired configuration through the sole owner. - /// - /// Process-restart-only fields are retained from the previous active - /// generation while the complete desired value remains queryable via - /// [`desired`](Self::desired). - pub fn apply_config( - &self, - desired: Config, - source_revision: ConfigSourceRevision, - trigger: ConfigReloadTrigger, - ) -> anyhow::Result { - self.ensure_runtime_writable()?; - let _reload_guard = self.reload_lock.lock(); - self.reload_in_progress.store(true, Ordering::Release); - let result = self.apply_config_locked(desired, source_revision.clone(), trigger); - self.reload_in_progress.store(false, Ordering::Release); - match &result { - Ok(report) => { - *self.last_report.write() = Some(report.clone()); - *self.last_failure.write() = None; - if report.has_runtime_change() { - self.emit_audit(ConfigGenerationAuditEvent { - event_type: "config.reload.applied".to_string(), - generation_id: Some(report.active_generation), - source_revision: Some(report.active_source_revision.clone()), - trigger, - payload: serde_json::to_value(report).unwrap_or_else(|_| serde_json::json!({})), - }); - } - if !report.restart_required.is_empty() { - self.emit_audit(ConfigGenerationAuditEvent { - event_type: "config.reload.deferred".to_string(), - generation_id: Some(report.active_generation), - source_revision: Some(report.desired_source_revision.clone()), - trigger, - payload: serde_json::json!({ - "restart_required": report.restart_required, - }), - }); - } - } - Err(error) => self.record_failure(trigger, Some(source_revision), error), - } - result - } - - fn apply_config_locked( - &self, - desired: Config, - source_revision: ConfigSourceRevision, - trigger: ConfigReloadTrigger, - ) -> anyhow::Result { - desired.validate()?; - - let old_generation = self.active.load_full(); - // The decision backend check every configuration plan runs: a hand - // edit to an invalid backend leaves this generation active - // (CDP-12, R-CXR P0-B t2). - // A reload that does not own a refusal is not held back by it - // (D-094 C-1). - if let Some(warning) = - crate::config::manage::validate::check_decision_plane(Some(old_generation.effective.as_ref()), &desired) - .map_err(|refusal| anyhow::anyhow!(refusal))? - { - tracing::warn!("{warning}"); - } - let active = old_generation.effective.as_ref(); - let adopted = adopt_live_pairing_tokens(active, &desired, trigger); - let old = adopted.as_ref().unwrap_or(active); - let changed = changed_top_level_fields(old, &desired)?; - let participants = { - let mut registrations = self.participants.write(); - let active = registrations.iter().filter_map(Weak::upgrade).collect::>(); - registrations.retain(|participant| participant.strong_count() > 0); - active - }; - let restart_required = changed - .iter() - .filter(|field| { - is_process_restart_only(field) - || (is_rebuild_and_swap(field) - && !participants - .iter() - .any(|participant| participant.supports_rebuild_field(field))) - || (is_controlled_restart(field) - && !participants - .iter() - .any(|participant| participant.supports_controlled_restart_field(field))) - }) - .cloned() - .collect::>(); - let rebuilt = changed - .iter() - .filter(|field| is_rebuild_and_swap(field) && !restart_required.contains(field)) - .cloned() - .collect::>(); - let restarted = changed - .iter() - .filter(|field| is_controlled_restart(field) && !restart_required.contains(field)) - .cloned() - .collect::>(); - let mut applied = changed - .iter() - .filter(|field| { - !is_process_restart_only(field) && !is_rebuild_and_swap(field) && !is_controlled_restart(field) - }) - .cloned() - .collect::>(); - // Adopted pairing tokens are applied in-process (the pairing guard - // holds them); report them so, unless another `gateway` change is - // what is being deferred. - let mut changed = changed; - if adopted.is_some() && !changed.iter().any(|field| field == "gateway") { - changed.push("gateway".to_string()); - applied.push("gateway".to_string()); - } - - self.desired.store(Arc::new(DesiredConfigState { - source_revision: source_revision.clone(), - config: Arc::new(desired.clone()), - observed_at: Utc::now(), - })); - - let effective = preserve_deferred_fields(old, desired, &restart_required)?; - // Against the generation that is really active: adopted pairing - // tokens are a change to publish even when nothing else changed. - let effective_changed = changed_top_level_fields(active, &effective)?; - let deferred_changes: Arc<[DeferredConfigChange]> = restart_required - .iter() - .map(|field| DeferredConfigChange { - field: field.clone(), - reason: "process restart required".to_string(), - }) - .collect::>() - .into(); - - let mut participant_acks = Vec::new(); - let (active_generation, active_source_revision) = if effective_changed.is_empty() { - (old_generation.id, old_generation.source_revision.clone()) - } else { - let supervisor_switch = !restarted.is_empty() - || participants.iter().any(|participant| { - participant.name() == "daemon_component_supervisors" - && effective_changed - .iter() - .any(|field| participant.prepares_for_field(field)) - }); - let id = ConfigGenerationId( - self.next_generation - .try_update(Ordering::SeqCst, Ordering::SeqCst, |next| next.checked_add(1)) - .map_err(|_| anyhow::anyhow!("configuration generation counter is exhausted"))?, - ); - let generation = Arc::new(ConfigGeneration { - id, - source_revision: source_revision.clone(), - effective: Arc::new(effective), - applied_at: Utc::now(), - trigger, - deferred_changes, - }); - self.emit_audit(ConfigGenerationAuditEvent { - event_type: "config.reload.prepared".to_string(), - generation_id: Some(generation.id), - source_revision: Some(generation.source_revision.clone()), - trigger, - payload: serde_json::json!({ - "changed": effective_changed, - "rebuilt": rebuilt, - "restarted": restarted, - }), - }); - let previous_runtime_proxy = effective_changed - .iter() - .any(|field| field == "proxy") - .then(crate::config::runtime_proxy_config); - if previous_runtime_proxy.is_some() { - crate::config::set_runtime_proxy_config(generation.effective.proxy.clone()); - } - if supervisor_switch { - self.emit_audit(ConfigGenerationAuditEvent { - event_type: "config.supervisor.restart_started".to_string(), - generation_id: Some(generation.id), - source_revision: Some(generation.source_revision.clone()), - trigger, - payload: serde_json::json!({ "fields": restarted }), - }); - } - let mut prepared = Vec::with_capacity(participants.len()); - for participant in participants.into_iter().filter(|participant| { - effective_changed - .iter() - .any(|field| participant.prepares_for_field(field)) - }) { - match participant.prepare(Arc::clone(&generation), &effective_changed) { - Ok(update) => { - participant_acks.push(participant.name().to_string()); - prepared.push(update); - } - Err(error) => { - for update in prepared.iter_mut().rev() { - update.rollback(); - } - if let Some(previous_proxy) = previous_runtime_proxy.as_ref() { - crate::config::set_runtime_proxy_config(previous_proxy.clone()); - } - if supervisor_switch { - self.emit_audit(ConfigGenerationAuditEvent { - event_type: "config.supervisor.rollback".to_string(), - generation_id: Some(generation.id), - source_revision: Some(generation.source_revision.clone()), - trigger, - payload: serde_json::json!({ - "participant": participant.name(), - "reason": error.to_string(), - }), - }); - } - return Err(anyhow::anyhow!( - "config generation participant '{}' rejected generation {}: {error}", - participant.name(), - generation.id.0 - )); - } - } - } - if let Err(error) = prepared.iter_mut().try_for_each(|update| update.commit()) { - for update in prepared.iter_mut().rev() { - update.rollback(); - } - if let Some(previous_proxy) = previous_runtime_proxy.as_ref() { - crate::config::set_runtime_proxy_config(previous_proxy.clone()); - } - if supervisor_switch { - self.emit_audit(ConfigGenerationAuditEvent { - event_type: "config.supervisor.rollback".to_string(), - generation_id: Some(generation.id), - source_revision: Some(generation.source_revision.clone()), - trigger, - payload: serde_json::json!({ "reason": error.to_string() }), - }); - } - anyhow::bail!( - "config generation participant commit failed for generation {}: {error}", - generation.id.0 - ); - } - self.active.store(Arc::clone(&generation)); - { - let mut published = self.published.lock(); - published.retain(|_, pinned| pinned.strong_count() > 0); - published.insert(generation.id, Arc::downgrade(&generation)); - } - self.model_allowlist.refresh(&generation.effective); - for update in &mut prepared { - update.finalize(); - } - if supervisor_switch { - self.emit_audit(ConfigGenerationAuditEvent { - event_type: "config.supervisor.restart_completed".to_string(), - generation_id: Some(generation.id), - source_revision: Some(generation.source_revision.clone()), - trigger, - payload: serde_json::json!({ "fields": restarted }), - }); - } - (generation.id, generation.source_revision.clone()) - }; - - Ok(ConfigApplyReport { - active_generation, - active_source_revision, - desired_source_revision: source_revision, - changed, - applied, - rebuilt, - restarted, - restart_required, - participant_acks, - }) - } - - /// Convenience for in-memory callers and tests that do not have a disk revision. - pub fn apply_runtime_config( - &self, - desired: Config, - trigger: ConfigReloadTrigger, - ) -> anyhow::Result { - let revision = ConfigSourceRevision::from_config(&desired)?; - self.apply_config(desired, revision, trigger) - } - - fn record_failure( - &self, - trigger: ConfigReloadTrigger, - desired_source_revision: Option, - error: &anyhow::Error, - ) { - *self.last_failure.write() = Some(ConfigReloadFailure { - occurred_at: Utc::now(), - trigger, - desired_source_revision: desired_source_revision.clone(), - error: error.to_string(), - }); - self.emit_audit(ConfigGenerationAuditEvent { - event_type: "config.reload.failed".to_string(), - generation_id: Some(self.active_generation_id()), - source_revision: desired_source_revision, - trigger, - payload: serde_json::json!({ "error": error.to_string() }), - }); - } - - fn emit_audit(&self, event: ConfigGenerationAuditEvent) { - for sink in self.audit_sinks.read().iter() { - sink.record(event.clone()); - } - } -} - -/// Test seam: run once, for one config path, right after the stable -/// snapshot is loaded (a write landing in the reload's window). -#[cfg(test)] -#[allow(clippy::type_complexity)] -pub(crate) static AFTER_SNAPSHOT_HOOK: parking_lot::Mutex)>> = - parking_lot::Mutex::new(None); - -#[cfg(test)] -fn run_after_snapshot_hook(config_path: &Path) { - let hook = { - let mut slot = AFTER_SNAPSHOT_HOOK.lock(); - if slot.as_ref().is_some_and(|(path, _)| path == config_path) { - slot.take() - } else { - None - } - }; - if let Some((_, hook)) = hook { - hook(); - } -} - -fn load_stable_config_snapshot( - config_path: &Path, - workspace_dir: std::path::PathBuf, -) -> anyhow::Result<(Config, ConfigSourceRevision)> { - const MAX_ATTEMPTS: usize = 3; - - for attempt in 1..=MAX_ATTEMPTS { - let before = compute_config_revision_gated(config_path)?; - let fresh = Config::load_from_path(config_path, workspace_dir.clone())?; - let after = compute_config_revision_gated(config_path)?; - if before == after { - let (fingerprint, disk_generation) = before; - let revision = ConfigSourceRevision { - fingerprint_sha256: fingerprint.iter().map(|byte| format!("{byte:02x}")).collect(), - disk_generation: Some(disk_generation), - }; - return Ok((fresh, revision)); - } - - tracing::debug!( - path = %config_path.display(), - attempt, - "Config changed during generation snapshot; retrying" - ); - std::thread::sleep(std::time::Duration::from_millis(50)); - } - - anyhow::bail!("Config changed repeatedly while reloading: {}", config_path.display()) -} - -fn changed_top_level_fields(old: &Config, desired: &Config) -> anyhow::Result> { - let old = serde_json::to_value(old)?; - let desired = serde_json::to_value(desired)?; - let old = old - .as_object() - .ok_or_else(|| anyhow::anyhow!("serialized config root is not an object"))?; - let desired = desired - .as_object() - .ok_or_else(|| anyhow::anyhow!("serialized config root is not an object"))?; - let keys = old.keys().chain(desired.keys()).cloned().collect::>(); - Ok(keys - .into_iter() - .filter(|key| old.get(key) != desired.get(key)) - .collect()) -} - -/// The active configuration with the persisted `gateway.paired_tokens` -/// adopted, when `trigger` is the pairing persistence and the list differs. -/// -/// `gateway` is a process-restart-only field, and its token list is too for -/// every other writer: a token added by hand is not accepted until restart. -/// The one exception is `/pair`: the running pairing guard already holds the -/// token it issued, and the reload that persists it is triggered with -/// [`ConfigReloadTrigger::PairingPersistence`]. Keeping the old list active -/// after that reload made every later reload find `gateway` changed again, so -/// even a save of `agent.compact_context` reported -/// `restart_required: ["gateway"]` (CONSOLE-OBS-3), and a supervised gateway -/// restart would have been built from the list without the token. Only the -/// token list is adopted; any other `gateway` change stays deferred. -fn adopt_live_pairing_tokens(active: &Config, desired: &Config, trigger: ConfigReloadTrigger) -> Option { - if trigger != ConfigReloadTrigger::PairingPersistence - || active.gateway.paired_tokens == desired.gateway.paired_tokens - { - return None; - } - let mut adopted = active.clone(); - adopted.gateway.paired_tokens.clone_from(&desired.gateway.paired_tokens); - Some(adopted) -} - -pub(crate) fn is_process_restart_only(field: &str) -> bool { - matches!( - field, - "runtime" - | "memory" - | "storage" - | "tunnel" - | "gateway" - | "modules" - | "observability" - | "mcp_server" - | "a2a" - | "skills_lifecycle" - | "plugins" - ) -} - -pub(crate) fn is_controlled_restart(field: &str) -> bool { - matches!( - field, - "channels_config" | "cron" | "scheduler" | "heartbeat" | "xin" | "webhook" | "self_system" - ) -} - -pub(crate) fn is_rebuild_and_swap(field: &str) -> bool { - matches!( - field, - "api_key" - | "api_url" - | "auth" - | "default_provider" - | "default_model" - | "providers" - | "reliability" - | "security" - | "autonomy" - | "browser" - | "http_request" - | "multimodal" - | "mcp" - | "composio" - | "agents" - | "tool_tiering" - | "nodes" - | "skills" - | "skill_rag" - | "model_routes" - | "embedding_routes" - | "query_classification" - | "task_routing" - | "router" - | "smart_group" - | "identity" - | "identity_bindings" - | "user_policies" - | "secrets" - | "media" - | "proxy" - ) -} - -/// The paths of `remote_decision_enabled` reasons between `old` and `new`: -/// what a hand edit applied by a reload turned towards remote decisions. -fn hand_edited_remote_decisions(old: &Config, new: &Config) -> Vec { - crate::config::manage::ConfigChangeSummary::between(Some(old), new) - .map(|summary| { - summary - .risk_reasons - .into_iter() - .filter_map(|reason| match reason { - crate::config::manage::RiskReason::RemoteDecisionEnabled { path } => Some(path), - _ => None, - }) - .collect() - }) - .unwrap_or_else(|error| { - tracing::warn!(error = %crate::security::redaction::redact_provider_text(&format!("{error:#}")), "could not compare the reloaded configuration"); - Vec::new() - }) -} - -fn preserve_deferred_fields(old: &Config, desired: Config, fields: &[String]) -> anyhow::Result { - let old_value = serde_json::to_value(old)?; - let mut effective_value = serde_json::to_value(desired)?; - let old_object = old_value - .as_object() - .ok_or_else(|| anyhow::anyhow!("serialized active config root is not an object"))?; - let effective_object = effective_value - .as_object_mut() - .ok_or_else(|| anyhow::anyhow!("serialized desired config root is not an object"))?; - for field in fields { - if let Some(value) = old_object.get(field) { - effective_object.insert(field.clone(), value.clone()); - } else { - effective_object.remove(field); - } - } - let mut effective: Config = serde_json::from_value(effective_value)?; - effective.workspace_dir = old.workspace_dir.clone(); - effective.config_path = old.config_path.clone(); - Ok(effective) -} - -#[cfg(test)] -mod tests { - /// S7: the child snapshot fingerprint keeps its encoding: - /// SHA-256 over the sorted JSON of `(workspace_dir, config_path, config)`. - #[test] - fn for_child_fingerprint_encoding_is_unchanged() { - use sha2::Digest as _; - // The vector input of `runtime::child_source::tests::golden_effective_config` - // with the two paths set; its serialized object is the same literal. - let mut config = crate::config::Config::default(); - config.decision_engine.backend = - Some(crate::config::schema::decision_engine::effective_engine_backend(&config).clone()); - for model in ["zeta/model", "alpha/model"] { - config.cost.prices.insert( - model.to_owned(), - crate::config::schema::ModelPricing { - input: 1.0, - output: 2.0, - cache_write: 0.0, - cache_read: 0.0, - }, - ); - } - config.workspace_dir = std::path::PathBuf::from("/prx/ws-1"); - config.config_path = std::path::PathBuf::from("/prx/config.toml"); - let generation = super::ConfigGeneration::for_child(&config).unwrap(); - // §2: SHA-256 of the sorted array `[workspace, config_path, config]`, - // spelled out from literals, and the pinned digest of those bytes. - let preimage = [ - br#"["/prx/ws-1","/prx/config.toml","#.as_slice(), - include_bytes!("../runtime/child_source/golden_effective_config.json").as_slice(), - b"]", - ] - .concat(); - const FOR_CHILD_FINGERPRINT: &str = "36fb5c51bfd612997498393f589b371efdd01ff0fda1acf04682f28872b03341"; - assert_eq!(format!("{:x}", sha2::Sha256::digest(&preimage)), FOR_CHILD_FINGERPRINT); - assert_eq!(generation.source_revision.fingerprint_sha256, FOR_CHILD_FINGERPRINT); - assert_eq!(generation.id.0, 0); - assert!(generation.source_revision.disk_generation.is_none()); - } - use super::*; - use serial_test::serial; - - struct RecordingParticipant { - name: &'static str, - events: Arc>>, - fail_prepare: bool, - fail_commit: bool, - } - - struct RecordingPrepared { - name: &'static str, - events: Arc>>, - fail_commit: bool, - } - - struct RecordingAuditSink { - event_types: Arc>>, - } - - impl ConfigGenerationAuditSink for RecordingAuditSink { - fn record(&self, event: ConfigGenerationAuditEvent) { - self.event_types.lock().push(event.event_type); - } - } - - impl ConfigGenerationParticipant for RecordingParticipant { - fn name(&self) -> &'static str { - self.name - } - - fn supports_rebuild_field(&self, _field: &str) -> bool { - true - } - - fn supports_controlled_restart_field(&self, _field: &str) -> bool { - true - } - - fn prepares_for_field(&self, _field: &str) -> bool { - true - } - - fn prepare( - &self, - _generation: Arc, - _changed_fields: &[String], - ) -> anyhow::Result> { - self.events.lock().push(format!("{}.prepare", self.name)); - if self.fail_prepare { - anyhow::bail!("injected prepare failure"); - } - Ok(Box::new(RecordingPrepared { - name: self.name, - events: Arc::clone(&self.events), - fail_commit: self.fail_commit, - })) - } - } - - impl PreparedConfigGeneration for RecordingPrepared { - fn commit(&mut self) -> anyhow::Result<()> { - self.events.lock().push(format!("{}.commit", self.name)); - if self.fail_commit { - anyhow::bail!("injected commit failure"); - } - Ok(()) - } - - fn rollback(&mut self) { - self.events.lock().push(format!("{}.rollback", self.name)); - } - - fn finalize(&mut self) { - self.events.lock().push(format!("{}.finalize", self.name)); - } - } - - /// The proxy the publication tests publish: a real `all_proxy`, so the - /// publication stays observable, but with loopback exempt, so a test - /// running at the same time against its own `127.0.0.1` server is never - /// sent to a proxy that is not there (R-INT2A F3). A services scope with a - /// dummy key would be refused by validation, which only knows real keys. - fn test_publication_proxy(url: &str) -> crate::config::ProxyConfig { - crate::config::ProxyConfig { - all_proxy: Some(url.to_string()), - no_proxy: vec!["127.0.0.1".to_string(), "localhost".to_string(), "::1".to_string()], - ..Config::default().proxy - } - } - - /// Restores the process-wide runtime proxy when dropped, so a failing - /// assertion cannot leave a test proxy published. - struct RuntimeProxyRestore(crate::config::ProxyConfig); - - impl RuntimeProxyRestore { - fn capture() -> Self { - Self(crate::config::runtime_proxy_config()) - } - - fn publish(proxy: crate::config::ProxyConfig) -> Self { - let restore = Self::capture(); - crate::config::set_runtime_proxy_config(proxy); - restore - } - } - - impl Drop for RuntimeProxyRestore { - fn drop(&mut self) { - crate::config::set_runtime_proxy_config(self.0.clone()); - } - } - - fn participant( - name: &'static str, - events: Arc>>, - fail_prepare: bool, - fail_commit: bool, - ) -> Arc { - Arc::new(RecordingParticipant { - name, - events, - fail_prepare, - fail_commit, - }) - } - - #[test] - #[serial] - fn one_operation_keeps_pinned_generation_after_reload() { - let manager = ConfigGenerationManager::new(Config::default()); - let pinned = manager.pin(); - let mut desired = (*pinned.effective).clone(); - desired.default_temperature = 0.31; - - let report = manager - .apply_runtime_config(desired, ConfigReloadTrigger::Test) - .expect("apply config"); - - assert_eq!(pinned.id, ConfigGenerationId(0)); - assert_eq!(manager.pin().id, report.active_generation); - assert_ne!(pinned.id, manager.pin().id); - assert_ne!( - pinned.effective.default_temperature, - manager.pin().effective.default_temperature - ); - } - - #[test] - #[serial] - fn restart_only_fields_update_desired_but_not_active() { - let manager = ConfigGenerationManager::new(Config::default()); - let old_active = manager.load_full(); - let mut desired = (*old_active).clone(); - desired.runtime.kind = "docker".to_string(); - - let report = manager - .apply_runtime_config(desired.clone(), ConfigReloadTrigger::Test) - .expect("apply config"); - - assert_eq!(manager.load_full().runtime.kind, old_active.runtime.kind); - assert_eq!(manager.desired().config.runtime.kind, desired.runtime.kind); - assert_eq!(report.restart_required, vec!["runtime"]); - assert_eq!(report.status(), "restart_required"); - } - - /// `[skills_lifecycle]` is read once at process start (the service, its - /// store and the registered tools are built from it), so a reload that - /// changes it reports `restart_required` and the effective configuration - /// keeps the old value, while the desired one records the edit. - #[test] - #[serial] - fn a_changed_skills_lifecycle_needs_a_restart_and_keeps_the_old_value() { - let manager = ConfigGenerationManager::new(Config::default()); - let old_active = manager.load_full(); - assert!(!old_active.skills_lifecycle.enabled); - let mut desired = (*old_active).clone(); - desired.skills_lifecycle.enabled = true; - desired.skills_lifecycle.owner_scope = Some("owner:ws:cli:alice".to_string()); - desired.skills_lifecycle.mode = crate::config::skills_lifecycle::SkillsLifecycleModeConfig::Auto; - - let report = manager - .apply_runtime_config(desired.clone(), ConfigReloadTrigger::Test) - .expect("apply config"); - - assert_eq!(report.restart_required, vec!["skills_lifecycle"]); - assert_eq!(report.status(), "restart_required"); - assert_eq!(manager.load_full().skills_lifecycle, old_active.skills_lifecycle); - assert!(!manager.load_full().skills_lifecycle.enabled); - assert_eq!(manager.desired().config.skills_lifecycle, desired.skills_lifecycle); - assert!(is_process_restart_only("skills_lifecycle")); - } - - #[test] - #[serial] - fn reload_report_classifies_runtime_changes() { - let manager = ConfigGenerationManager::new(Config::default()); - let events = Arc::new(Mutex::new(Vec::new())); - let runtime = participant("runtime", events, false, false); - manager.register_participant(&runtime); - let mut desired = (*manager.load_full()).clone(); - desired.default_temperature = 0.22; - desired.default_model = Some("example/model".to_string()); - desired.cron.max_run_history += 1; - - let report = manager - .apply_runtime_config(desired, ConfigReloadTrigger::Test) - .expect("apply config"); - - assert_eq!(report.applied, vec!["default_temperature"]); - assert_eq!(report.rebuilt, vec!["default_model"]); - assert_eq!(report.restarted, vec!["cron"]); - assert!(report.restart_required.is_empty(), "expected an empty value"); - } - - /// CONSOLE-OBS-3 (CONSOLE-VERIFY): once the gateway paired, every later - /// save reported `restart_required: ["gateway"]`, even one that changed - /// only `agent.compact_context`. `/pair` persists the new token hash and - /// reloads; `gateway` is restart-only, so the active generation kept the - /// old (empty) token list while disk held the new one, and every reload - /// after it found `gateway` different again. The pairing guard already - /// holds that token, so the pairing reload adopts the persisted list into - /// the active generation; nothing else about `gateway` is adopted. - #[test] - #[serial] - fn a_save_after_pairing_does_not_report_a_gateway_restart() { - let manager = ConfigGenerationManager::new(Config::default()); - let mut paired = (*manager.load_full()).clone(); - paired.gateway.paired_tokens = vec![crate::security::pairing::hash_token("zc_paired_in_test")]; - - let pairing = manager - .apply_runtime_config(paired.clone(), ConfigReloadTrigger::PairingPersistence) - .expect("test: pairing reload"); - assert!( - pairing.restart_required.is_empty(), - "the token pairing just issued is live already: {:?}", - pairing.restart_required - ); - assert_eq!( - manager.load_full().gateway.paired_tokens, - paired.gateway.paired_tokens, - "the active generation carries the persisted token list" - ); - assert_eq!(pairing.applied, vec!["gateway"], "the adoption is reported as applied"); - - let mut save = paired; - save.agent.compact_context = !save.agent.compact_context; - let report = manager - .apply_runtime_config(save, ConfigReloadTrigger::Api) - .expect("test: low-risk save"); - assert!( - report.restart_required.is_empty(), - "a save of agent.compact_context must not report a restart: {:?}", - report.restart_required - ); - assert_eq!(report.applied, vec!["agent"]); - } - - /// The pairing adoption is exactly the token list: another `gateway` - /// change in the same reload stays deferred, and a token list changed by - /// any other writer (a hand edit picked up by the watcher) still needs a - /// restart, because the running pairing guard never loaded it. - #[test] - #[serial] - fn only_pairing_adopts_only_the_token_list() { - let manager = ConfigGenerationManager::new(Config::default()); - let original_port = manager.load_full().gateway.port; - let mut desired = (*manager.load_full()).clone(); - desired.gateway.paired_tokens = vec![crate::security::pairing::hash_token("zc_first")]; - desired.gateway.port = original_port.wrapping_add(1); - - let report = manager - .apply_runtime_config(desired.clone(), ConfigReloadTrigger::PairingPersistence) - .expect("test: pairing reload with a port change"); - assert_eq!(report.restart_required, vec!["gateway"]); - let active = manager.load_full(); - assert_eq!( - active.gateway.port, original_port, - "the port change waits for a restart" - ); - assert_eq!(active.gateway.paired_tokens, desired.gateway.paired_tokens); - - let mut hand_edit = desired; - hand_edit.gateway.port = original_port; - hand_edit.gateway.paired_tokens.push("operator-added-token".to_string()); - let report = manager - .apply_runtime_config(hand_edit, ConfigReloadTrigger::FileWatcher) - .expect("test: watcher reload"); - assert_eq!( - report.restart_required, - vec!["gateway"], - "a token the pairing guard never loaded is not live until restart" - ); - assert_eq!(manager.load_full().gateway.paired_tokens.len(), 1); - } - - #[test] - fn auth_and_proxy_are_rebuild_and_swap_fields() { - assert!(is_rebuild_and_swap("auth")); - assert!(is_rebuild_and_swap("proxy")); - assert!(!is_process_restart_only("auth")); - assert!(!is_process_restart_only("proxy")); - } - - /// Serve one HTTP response on a loopback port and return its URL. - fn one_shot_loopback_server() -> String { - use std::io::{Read, Write}; - let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("test: bind"); - let addr = listener.local_addr().expect("test: addr"); - std::thread::spawn(move || { - if let Ok((mut socket, _)) = listener.accept() { - let mut buffer = [0_u8; 1024]; - let _ = socket.read(&mut buffer); - let _ = socket.write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 2\r\nconnection: close\r\n\r\nok"); - } - }); - format!("http://{addr}/") - } - - /// R-INT2A F3: while a publication test's proxy is live, a concurrently - /// running test's runtime-proxy-built client can still reach its own - /// loopback server. Before, the published `all_proxy` applied to every - /// service with no loopback exemption, so such a client was sent to the - /// absent proxy and refused (this is how the A12 test hung). - #[tokio::test] - #[serial] - async fn a_published_test_proxy_leaves_loopback_clients_alone() { - let url = one_shot_loopback_server(); - let _restore = RuntimeProxyRestore::publish(test_publication_proxy("http://127.0.0.1:8080")); - let client = crate::config::build_runtime_proxy_client("provider.compatible").expect("test: client"); - let response = tokio::time::timeout(std::time::Duration::from_secs(20), client.get(&url).send()) - .await - .expect("test: bounded") - .expect("test: the loopback request bypasses the test proxy"); - assert!(response.status().is_success()); - } - - #[test] - #[serial] - fn proxy_runtime_state_tracks_successful_generation_publication() { - let _restore = RuntimeProxyRestore::capture(); - let initial = Config::default(); - let manager = ConfigGenerationManager::new(initial.clone()); - let events = Arc::new(Mutex::new(Vec::new())); - let runtime = participant("runtime", events, false, false); - manager.register_participant(&runtime); - let mut desired = initial; - desired.proxy = test_publication_proxy("http://127.0.0.1:8080"); - - let report = manager - .apply_runtime_config(desired.clone(), ConfigReloadTrigger::Test) - .expect("proxy generation must publish"); - let runtime_proxy = crate::config::runtime_proxy_config(); - - assert_eq!(report.rebuilt, vec!["proxy"]); - assert!(runtime_proxy.has_any_proxy_url()); - assert_eq!(runtime_proxy.all_proxy, desired.proxy.all_proxy); - } - - #[test] - #[serial] - fn proxy_runtime_state_rolls_back_when_participant_rejects_candidate() { - let _restore = RuntimeProxyRestore::capture(); - let initial = Config::default(); - let manager = ConfigGenerationManager::new(initial.clone()); - let events = Arc::new(Mutex::new(Vec::new())); - let rejecting = participant("rejecting", events, true, false); - manager.register_participant(&rejecting); - let mut desired = initial.clone(); - desired.proxy = test_publication_proxy("http://127.0.0.1:8081"); - - manager - .apply_runtime_config(desired, ConfigReloadTrigger::Test) - .expect_err("rejected proxy candidate must roll back"); - let runtime_proxy = crate::config::runtime_proxy_config(); - - assert_eq!(manager.active_generation_id(), ConfigGenerationId(0)); - assert_eq!(runtime_proxy.has_any_proxy_url(), initial.proxy.has_any_proxy_url()); - assert_eq!(runtime_proxy.all_proxy, initial.proxy.all_proxy); - } - - #[test] - #[serial] - fn participant_prepare_failure_rolls_back_and_keeps_active_generation() { - let manager = ConfigGenerationManager::new(Config::default()); - let events = Arc::new(Mutex::new(Vec::new())); - let first = participant("first", Arc::clone(&events), false, false); - let second = participant("second", Arc::clone(&events), true, false); - manager.register_participant(&first); - manager.register_participant(&second); - let mut desired = (*manager.load_full()).clone(); - desired.default_temperature = 0.19; - - let error = manager - .apply_runtime_config(desired.clone(), ConfigReloadTrigger::Test) - .expect_err("second participant must reject candidate"); - - assert!(error.to_string().contains("second")); - assert_eq!(manager.active_generation_id(), ConfigGenerationId(0)); - assert_eq!( - manager.desired().config.default_temperature, - desired.default_temperature - ); - assert_eq!( - *events.lock(), - vec!["first.prepare", "second.prepare", "first.rollback"] - ); - assert!(manager.status().last_failure.is_some()); - } - - #[test] - #[serial] - fn participant_commit_failure_rolls_every_candidate_back_before_publish() { - let manager = ConfigGenerationManager::new(Config::default()); - let events = Arc::new(Mutex::new(Vec::new())); - let first = participant("first", Arc::clone(&events), false, false); - let second = participant("second", Arc::clone(&events), false, true); - manager.register_participant(&first); - manager.register_participant(&second); - let mut desired = (*manager.load_full()).clone(); - desired.default_temperature = 0.18; - - manager - .apply_runtime_config(desired, ConfigReloadTrigger::Test) - .expect_err("second participant commit must fail"); - - assert_eq!(manager.active_generation_id(), ConfigGenerationId(0)); - assert_eq!( - *events.lock(), - vec![ - "first.prepare", - "second.prepare", - "first.commit", - "second.commit", - "second.rollback", - "first.rollback", - ] - ); - } - - #[test] - #[serial] - fn successful_participants_finalize_only_after_publication() { - let manager = ConfigGenerationManager::new(Config::default()); - let events = Arc::new(Mutex::new(Vec::new())); - let participant = participant("runtime", Arc::clone(&events), false, false); - manager.register_participant(&participant); - let mut desired = (*manager.load_full()).clone(); - desired.default_temperature = 0.17; - - let report = manager - .apply_runtime_config(desired, ConfigReloadTrigger::Test) - .expect("candidate must publish"); - - assert_eq!(manager.active_generation_id(), report.active_generation); - assert_eq!(report.participant_acks, vec!["runtime"]); - assert_eq!( - *events.lock(), - vec!["runtime.prepare", "runtime.commit", "runtime.finalize"] - ); - } - - #[test] - #[serial] - fn concurrent_reload_attempts_are_serialized_into_distinct_generations() { - let manager = Arc::new(ConfigGenerationManager::new(Config::default())); - let mut handles = Vec::new(); - for temperature in [0.12, 0.13] { - let manager = Arc::clone(&manager); - handles.push(std::thread::spawn(move || { - let mut desired = (*manager.load_full()).clone(); - desired.default_temperature = temperature; - manager - .apply_runtime_config(desired, ConfigReloadTrigger::Test) - .expect("serialized reload") - .active_generation - })); - } - let mut generations = handles - .into_iter() - .map(|handle| handle.join().expect("reload thread")) - .collect::>(); - generations.sort(); - - assert_eq!(generations, vec![ConfigGenerationId(1), ConfigGenerationId(2)]); - assert_eq!(manager.active_generation_id(), ConfigGenerationId(2)); - } - - #[test] - #[serial] - fn reload_and_supervisor_lifecycle_use_the_shared_audit_sink() { - let manager = ConfigGenerationManager::new(Config::default()); - let participant_events = Arc::new(Mutex::new(Vec::new())); - let runtime = participant("runtime", participant_events, false, false); - manager.register_participant(&runtime); - let audit_events = Arc::new(Mutex::new(Vec::new())); - manager.register_audit_sink(Arc::new(RecordingAuditSink { - event_types: Arc::clone(&audit_events), - })); - let mut desired = (*manager.load_full()).clone(); - desired.default_temperature = 0.11; - desired.cron.max_run_history += 1; - - manager - .apply_runtime_config(desired, ConfigReloadTrigger::Test) - .expect("reload with controlled restart"); - - assert_eq!( - *audit_events.lock(), - vec![ - "config.reload.prepared", - "config.supervisor.restart_started", - "config.supervisor.restart_completed", - "config.reload.applied", - ] - ); - } - - /// PMMD-g (N-8): the revision `reload_from_disk` publishes with the - /// desired configuration is the one of the files it loaded, not of a - /// write that landed after the load. - /// D-074 P1-1: the reload rebuilds the active generation through a JSON - /// round trip (`preserve_deferred_fields`); configured values and the - /// schema version survive the reload. - #[test] - fn a_reload_keeps_the_decision_engine_settings() { - let dir = tempfile::TempDir::new().expect("test: temp dir"); - let config_path = dir.path().join("config.toml"); - std::fs::write(&config_path, CAUSAL_FIXTURE).expect("test: causal config"); - let initial = Config::load_from_path(&config_path, dir.path().join("workspace")).expect("test: load"); - let manager = ConfigGenerationManager::new(initial); - std::fs::write( - &config_path, - CAUSAL_FIXTURE.replace("default_temperature = 0.7", "default_temperature = 0.4"), - ) - .expect("test: edited config"); - - manager - .reload_from_disk(ConfigReloadTrigger::Test) - .expect("test: reload"); - assert!((manager.load_full().default_temperature - 0.4).abs() < f64::EPSILON); - - for config in [manager.load_full(), Arc::clone(&manager.desired().config)] { - let engine = &config.decision_engine; - assert_eq!(engine.latency_budget_ms, 3_000); - assert!((engine.token_ratio_limit - 0.5).abs() < f32::EPSILON); - assert_eq!(engine.max_candidates, 5); - } - } - - /// D-079 L-4: a hand edit that turns remote decisions on is found, so - /// the reload can warn; a local edit is not. - #[test] - fn a_hand_edited_remote_enablement_is_reported() { - use crate::config::schema::decision_engine::BackendSelection; - let old = Config::default(); - let mut new = old.clone(); - new.decision_engine.backend.get_or_insert_with(Default::default).kind = - BackendSelection::Fixed(crate::config::schema::decision_engine::BackendKind::CompatibleHttp); - new.decision_engine - .backend - .get_or_insert_with(Default::default) - .endpoint = "https://decisions.example.com/v1".to_string(); - new.decision_engine - .backend - .get_or_insert_with(Default::default) - .remote_enabled = true; - assert_eq!( - hand_edited_remote_decisions(&old, &new), - vec!["decision_engine.backend.remote_enabled".to_string()] - ); - let mut local = old.clone(); - local.decision_engine.enabled = true; - assert!( - hand_edited_remote_decisions(&old, &local).is_empty(), - "expected an empty value" - ); - } - - /// D-082 N-4: the hand-edit warning is logged only when the reload is - /// applied; a refused reload logs nothing of it. - /// D-059: the configured-model allowlist follows the applied - /// generation: a model named only by the new configuration becomes a - /// label after the reload, and one no longer named becomes `unlisted`. - /// The manager refreshes its own allowlist here, so no other test can - /// race it. - #[test] - fn the_model_allowlist_follows_the_applied_generation() { - use crate::observability::labels::{ModelAllowlist, UNLISTED_MODEL}; - let dir = tempfile::TempDir::new().expect("test: temp dir"); - let config_path = dir.path().join("config.toml"); - std::fs::write( - &config_path, - "default_temperature = 0.7\n\n[decision_engine.backend]\nmodel = \"vendor/before-reload\"\n", - ) - .expect("test: config"); - let initial = Config::load_from_path(&config_path, dir.path().join("workspace")).expect("test: load"); - let allowlist = Arc::new(ModelAllowlist::default()); - let manager = ConfigGenerationManager::with_model_allowlist(initial, Arc::clone(&allowlist)); - // A participant that rebuilds, so every edit is applied rather than - // deferred to a restart. - let events = Arc::new(Mutex::new(Vec::new())); - let rebuilding = participant("decision", events, false, false); - manager.register_participant(&rebuilding); - assert_eq!(allowlist.label("vendor/before-reload"), "vendor/before-reload"); - assert_eq!(allowlist.label("vendor/after-reload"), UNLISTED_MODEL); - std::fs::write( - &config_path, - "default_temperature = 0.7\n\n[decision_engine.backend]\nmodel = \"vendor/after-reload\"\n", - ) - .expect("test: edit"); - manager - .reload_from_disk(ConfigReloadTrigger::FileWatcher) - .expect("test: reload"); - assert_eq!(allowlist.label("vendor/after-reload"), "vendor/after-reload"); - assert_eq!(allowlist.label("vendor/before-reload"), UNLISTED_MODEL); - } - - #[test] - #[serial] - fn a_hand_edited_remote_enablement_is_logged_only_when_applied() { - #[derive(Clone, Default)] - struct Sink(Arc>>); - impl std::io::Write for Sink { - fn write(&mut self, buf: &[u8]) -> std::io::Result { - self.0.lock().extend_from_slice(buf); - Ok(buf.len()) - } - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) - } - } - impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Sink { - type Writer = Self; - fn make_writer(&'a self) -> Self::Writer { - self.clone() - } - } - const REMOTE: &str = "default_temperature = 0.4\n\n[decision_engine.backend]\n\ - kind = \"compatible_http\"\nendpoint = \"https://decisions.example.com/v1\"\n\ - model = \"decider-1\"\nremote_enabled = true\n\n[[providers.models]]\n\ - provider = \"custom:https://decisions.example.com/v1\"\nmodel = \"decider-1\"\n\ - operations = [\"decision_endpoint\"]\n"; - let run = |fail_prepare: bool| { - let dir = tempfile::TempDir::new().expect("test: temp dir"); - let config_path = dir.path().join("config.toml"); - std::fs::write(&config_path, "default_temperature = 0.7\n").expect("test: config"); - let initial = Config::load_from_path(&config_path, dir.path().join("workspace")).expect("test: load"); - let manager = ConfigGenerationManager::new(initial); - let events = Arc::new(Mutex::new(Vec::new())); - let refusing = participant("refusing", Arc::clone(&events), fail_prepare, false); - manager.register_participant(&refusing); - std::fs::write(&config_path, REMOTE).expect("test: edit"); - let sink = Sink::default(); - let subscriber = tracing_subscriber::fmt() - .with_writer(sink.clone()) - .with_ansi(false) - .finish(); - let result = tracing::subscriber::with_default(subscriber, || { - // Another test may have cached this callsite as disabled. - tracing::callsite::rebuild_interest_cache(); - let result = manager.reload_from_disk(ConfigReloadTrigger::FileWatcher); - // A control line: the capture worked for this run, so a - // missing warning is a real absence (D-086 C-3). - tracing::warn!("capture control line"); - result - }); - let logs = String::from_utf8_lossy(&sink.0.lock()).to_string(); - (result.is_ok(), logs) - }; - let (applied, logs) = run(false); - assert!(applied); - assert!( - logs.contains("sends decision state off this machine") - && logs.contains("decision_engine.backend.remote_enabled"), - "{logs}" - ); - assert!( - !logs.contains("decisions.example.com"), - "the warning names the path, never the endpoint: {logs}" - ); - let (applied, logs) = run(true); - assert!(!applied, "the participant refused the reload"); - assert!(logs.contains("capture control line"), "the capture must work: {logs}"); - assert!(!logs.contains("sends decision state off this machine"), "{logs}"); - } - - /// CDP-04 (V6.07 hot-reload half): a hand edit that points the decision - /// backend at a remote host without `remote_enabled` does not activate; - /// the running generation is kept. - #[test] - fn a_remote_decision_endpoint_without_the_remote_switch_keeps_the_generation() { - let dir = tempfile::TempDir::new().expect("test: temp dir"); - let config_path = dir.path().join("config.toml"); - std::fs::write(&config_path, "default_temperature = 0.7\n").expect("test: config"); - let initial = Config::load_from_path(&config_path, dir.path().join("workspace")).expect("test: load"); - let manager = ConfigGenerationManager::new(initial); - let active = manager.active_generation_id(); - std::fs::write( - &config_path, - "default_temperature = 0.4\n\n[decision_engine.backend]\nkind = \"compatible_http\"\n\ - endpoint = \"https://decisions.example.com/v1\"\n", - ) - .expect("test: edit"); - let error = manager - .reload_from_disk(ConfigReloadTrigger::Test) - .expect_err("test: refused"); - let message = format!("{error:#}"); - assert!(message.contains("remote_enabled"), "{message}"); - assert!(!message.contains("decisions.example.com"), "{message}"); - assert_eq!(manager.active_generation_id(), active); - assert!((manager.load_full().default_temperature - 0.7).abs() < f64::EPSILON); - assert!(manager.load_full().decision_engine.backend.is_none()); - } - - /// CDP-12 (R-CXR P0-B t2): a hand edit to a decision backend the strict - /// selection refuses (here a model nobody declared for - /// `decision_endpoint`) leaves the running generation active. - #[test] - fn an_invalid_causal_backend_leaves_the_prior_generation_active() { - let dir = tempfile::TempDir::new().expect("test: temp dir"); - let config_path = dir.path().join("config.toml"); - std::fs::write(&config_path, "default_temperature = 0.7\n").expect("test: config"); - let initial = Config::load_from_path(&config_path, dir.path().join("workspace")).expect("test: load"); - let manager = ConfigGenerationManager::new(initial); - let events = Arc::new(Mutex::new(Vec::new())); - let rebuilding = participant("decision", events, false, false); - manager.register_participant(&rebuilding); - let active = manager.active_generation_id(); - std::fs::write( - &config_path, - "default_temperature = 0.4\n\n[decision_engine.backend]\nkind = \"compatible_http\"\n\ - endpoint = \"http://127.0.0.1:8900/v1\"\nmodel = \"undeclared-model\"\n", - ) - .expect("test: edit"); - let error = manager - .reload_from_disk(ConfigReloadTrigger::Test) - .expect_err("test: refused"); - assert!(format!("{error:#}").contains("decision_engine.backend"), "{error:#}"); - assert_eq!(manager.active_generation_id(), active); - assert!((manager.load_full().default_temperature - 0.7).abs() < f64::EPSILON); - - // Declared for decision_endpoint, the same backend activates. - std::fs::write( - &config_path, - "default_temperature = 0.4\n\n[decision_engine.backend]\nkind = \"compatible_http\"\n\ - endpoint = \"http://127.0.0.1:8900/v1\"\nmodel = \"undeclared-model\"\n\n\ - [[providers.models]]\nprovider = \"custom:http://127.0.0.1:8900/v1\"\nmodel = \"undeclared-model\"\n\ - operations = [\"decision_endpoint\"]\n", - ) - .expect("test: edit"); - manager - .reload_from_disk(ConfigReloadTrigger::Test) - .expect("test: applied"); - assert_ne!(manager.active_generation_id(), active); - } - - /// D-094 C-1: a daemon started with a decision section the check - /// refuses starts, and a later reload that does not touch - /// `[decision_engine]` is applied; one that does is still refused. - #[test] - fn an_invalid_decision_section_never_blocks_startup_or_unrelated_reloads() { - const INVALID: &str = "\n[decision_engine.backend]\nkind = \"compatible_http\"\n\ - endpoint = \"http://127.0.0.1:8900/v1\"\nmodel = \"undeclared-model\"\n"; - let dir = tempfile::TempDir::new().expect("test: temp dir"); - let config_path = dir.path().join("config.toml"); - std::fs::write(&config_path, format!("default_temperature = 0.7\n{INVALID}")).expect("test: config"); - let initial = Config::load_from_path(&config_path, dir.path().join("workspace")).expect("test: load"); - let manager = ConfigGenerationManager::new(initial); - let active = manager.active_generation_id(); - // A declaration for another provider: the check runs, finds the - // section already refused, and does not hold the change back. - const UNRELATED: &str = "\n[[providers.models]]\nprovider = \"openrouter\"\nmodel = \"vendor/chat-model\"\n\ - operations = [\"chat\"]\n"; - std::fs::write(&config_path, format!("default_temperature = 0.4\n{INVALID}{UNRELATED}")).expect("test: edit"); - manager - .reload_from_disk(ConfigReloadTrigger::Test) - .expect("test: an unrelated change is applied"); - assert_ne!(manager.active_generation_id(), active); - assert!((manager.load_full().default_temperature - 0.4).abs() < f64::EPSILON); - let active = manager.active_generation_id(); - std::fs::write( - &config_path, - format!( - "default_temperature = 0.4\n{}{UNRELATED}", - INVALID.replace("undeclared-model", "other-model") - ), - ) - .expect("test: edit"); - let error = manager - .reload_from_disk(ConfigReloadTrigger::Test) - .expect_err("test: a change to the section is refused"); - assert!(format!("{error:#}").contains("decision_engine.backend"), "{error:#}"); - assert_eq!(manager.active_generation_id(), active); - } - - const CAUSAL_FIXTURE: &str = r#"default_temperature = 0.7 - -[decision_engine] -latency_budget_ms = 3000 -token_ratio_limit = 0.5 -max_candidates = 5 -"#; - - #[test] - fn a_reload_publishes_the_revision_of_the_files_it_loaded() { - let dir = tempfile::TempDir::new().expect("test: temp dir"); - let config_path = dir.path().join("config.toml"); - std::fs::write(&config_path, "default_temperature = 0.7\n").expect("test: config"); - let mut initial = Config::default(); - initial.config_path = config_path.clone(); - initial.workspace_dir = dir.path().join("workspace"); - let manager = ConfigGenerationManager::new(initial); - let loaded_revision = crate::config::files::current_config_revision(&config_path).expect("test: revision"); - let writer_path = config_path.clone(); - *AFTER_SNAPSHOT_HOOK.lock() = Some(( - config_path, - Box::new(move || { - std::fs::write(&writer_path, "default_temperature = 0.4\n").expect("test: late write"); - }), - )); - - manager - .reload_from_disk(ConfigReloadTrigger::Test) - .expect("test: reload"); - - let desired = manager.desired(); - assert!((desired.config.default_temperature - 0.7).abs() < f64::EPSILON); - assert_eq!( - desired.source_revision.fingerprint_sha256, loaded_revision, - "the desired configuration must carry the revision it was loaded from" - ); - } -} - -#[cfg(test)] -mod pinned_parent_process_binding_tests { - use super::*; - - fn fixture() -> anyhow::Result<( - tempfile::TempDir, - ConfigGeneration, - Arc, - )> { - let home = tempfile::tempdir()?; - let config = Config { - config_path: home.path().join("config.toml"), - workspace_dir: home.path().join("workspace"), - ..Config::default() - }; - std::fs::write(&config.config_path, toml::to_string(&config)?)?; - let generation = ConfigGeneration { - id: ConfigGenerationId(7), - source_revision: ConfigSourceRevision::from_config(&config)?, - effective: Arc::new(config), - applied_at: Utc::now(), - trigger: ConfigReloadTrigger::Test, - deferred_changes: Arc::from([]), - }; - let transport = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, b"prx-parent-binding-fixture"); - let key = crate::security::runtime_key::DecisionKey::from_worker_channel( - &transport, - "prx-workspace", - "prx-run", - "prx-config", - )?; - Ok((home, generation, key)) - } - - #[cfg(unix)] - #[test] - fn canonical_config_working_root_survives_signed_worker_restore() -> anyhow::Result<()> { - let (home, mut generation, key) = fixture()?; - let root = home.path().join("root"); - std::fs::create_dir(&root)?; - let alias = home.path().join("alias"); - std::os::unix::fs::symlink(&root, &alias)?; - let mut stored = generation.effective.as_ref().clone(); - stored.runtime.workdir = Some(alias); - std::fs::write(&stored.config_path, toml::to_string(&stored)?)?; - let parent = Config::load_from_path(&stored.config_path, stored.workspace_dir.clone())?; - generation.source_revision = ConfigSourceRevision::from_config(&parent)?; - generation.effective = Arc::new(parent); - let binding = generation.bind_process(&key)?; - let canonical = root.canonicalize()?; - assert_eq!( - binding.working_root.as_ref(), - Some(&canonical), - "test: signed carrier uses the canonical parent value" - ); - generation.verify_pinned_process_binding(&binding, &key)?; - let mut worker = Config::load_from_path(&stored.config_path, stored.workspace_dir)?; - worker.runtime.workdir = binding.working_root.clone(); - let restored = ConfigGeneration::restore_process(worker, &binding, &key)?; - assert_eq!( - restored.effective.runtime.workdir.as_ref(), - Some(&canonical), - "test: worker and parent authenticate the same canonical root" - ); - Ok(()) - } - - #[test] - fn working_root_binding_rejects_worker_widening_and_tampering() -> anyhow::Result<()> { - let (home, mut generation, key) = fixture()?; - let root = home.path().join("root"); - std::fs::create_dir(&root)?; - Arc::make_mut(&mut generation.effective).runtime.workdir = Some(root.clone()); - let binding = generation.bind_process(&key)?; - assert_eq!( - binding.working_root.as_ref(), - Some(&root), - "test: parent root is carried" - ); - ConfigGeneration::restore_process(generation.effective.as_ref().clone(), &binding, &key)?; - for candidate in [None, Some(home.path().to_path_buf())] { - let mut child = generation.effective.as_ref().clone(); - child.runtime.workdir = candidate; - let error = ConfigGeneration::restore_process(child, &binding, &key) - .expect_err("test: worker cannot widen or discard signed parent root"); - assert!( - error.downcast_ref::().is_some(), - "test: root mismatch is a typed refusal" - ); - } - let mut tampered = binding; - tampered.working_root = Some(home.path().to_path_buf()); - assert!( - generation.verify_pinned_process_binding(&tampered, &key).is_err(), - "test: carrier cannot differ from pinned parent root" - ); - Ok(()) - } - - #[test] - fn pinned_parent_binding_survives_removed_source_but_child_restore_rejects() -> anyhow::Result<()> { - let (_home, generation, key) = fixture()?; - let binding = generation.bind_process(&key)?; - generation.verify_pinned_process_binding(&binding, &key)?; - ConfigGeneration::restore_process(generation.effective.as_ref().clone(), &binding, &key)?; - std::fs::remove_file(&generation.effective.config_path)?; - generation.verify_pinned_process_binding(&binding, &key)?; - assert!(ConfigGeneration::restore_process(generation.effective.as_ref().clone(), &binding, &key).is_err()); - Ok(()) - } - - #[test] - fn pinned_parent_binding_survives_changed_source_but_child_restore_rejects() -> anyhow::Result<()> { - let (_home, generation, key) = fixture()?; - let binding = generation.bind_process(&key)?; - std::fs::write(&generation.effective.config_path, "default_temperature = 0.25\n")?; - generation.verify_pinned_process_binding(&binding, &key)?; - assert!(ConfigGeneration::restore_process(generation.effective.as_ref().clone(), &binding, &key).is_err()); - Ok(()) - } - - #[cfg(unix)] - #[test] - fn process_binding_accepts_a_filesystem_alias_for_the_same_source() -> anyhow::Result<()> { - use std::os::unix::fs::symlink; - - let (home, generation, key) = fixture()?; - std::fs::create_dir_all(&generation.effective.workspace_dir)?; - let binding = generation.bind_process(&key)?; - let alias = home.path().join("source-alias"); - symlink(home.path(), &alias)?; - let mut child = generation.effective.as_ref().clone(); - child.config_path = alias.join("config.toml"); - child.workspace_dir = alias.join("workspace"); - - let restored = ConfigGeneration::restore_process(child, &binding, &key)?; - assert_eq!(restored.id, generation.id); - assert_eq!(restored.source_revision, generation.source_revision); - Ok(()) - } - - #[test] - fn pinned_parent_binding_rejects_metadata_snapshot_paths_and_key_mutation() -> anyhow::Result<()> { - let (_home, generation, key) = fixture()?; - let binding = generation.bind_process(&key)?; - let mut changed = generation.clone(); - changed.id = ConfigGenerationId(8); - assert!(changed.verify_pinned_process_binding(&binding, &key).is_err()); - let mut changed = generation.clone(); - changed.source_revision.disk_generation = None; - assert!(changed.verify_pinned_process_binding(&binding, &key).is_err()); - let mut changed = generation.clone(); - changed.source_revision.fingerprint_sha256 = "0".repeat(64); - assert!(changed.verify_pinned_process_binding(&binding, &key).is_err()); - let mut changed = generation.clone(); - changed.applied_at += chrono::Duration::seconds(1); - assert!(changed.verify_pinned_process_binding(&binding, &key).is_err()); - let mut changed = generation.clone(); - changed.trigger = ConfigReloadTrigger::Startup; - assert!(changed.verify_pinned_process_binding(&binding, &key).is_err()); - let mut changed = generation.clone(); - changed.deferred_changes = vec![DeferredConfigChange { - field: "prx-field".to_owned(), - reason: "prx-reason".to_owned(), - }] - .into(); - assert!(changed.verify_pinned_process_binding(&binding, &key).is_err()); - for field in ["workspace", "config", "effective"] { - let mut changed = generation.clone(); - let config = Arc::make_mut(&mut changed.effective); - match field { - "workspace" => config.workspace_dir = std::path::PathBuf::from("/prx-other-workspace"), - "config" => config.config_path = std::path::PathBuf::from("/prx-other-config"), - _ => config.default_temperature += 0.1, - } - assert!(changed.verify_pinned_process_binding(&binding, &key).is_err()); - } - let transport = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, b"prx-wrong-binding-key"); - let wrong = crate::security::runtime_key::DecisionKey::from_worker_channel( - &transport, - "prx-workspace", - "prx-run", - "prx-config", - )?; - assert!(generation.verify_pinned_process_binding(&binding, &wrong).is_err()); - let transport = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, b"prx-parent-binding-fixture"); - for (workspace, run, config) in [ - ("prx-other-workspace", "prx-run", "prx-config"), - ("prx-workspace", "prx-other-run", "prx-config"), - ("prx-workspace", "prx-run", "prx-other-config"), - ] { - let different_scope = - crate::security::runtime_key::DecisionKey::from_worker_channel(&transport, workspace, run, config)?; - assert!( - generation - .verify_pinned_process_binding(&binding, &different_scope) - .is_err() - ); - } - let mut forged = binding; - forged.seal = [0; 32]; - assert!(generation.verify_pinned_process_binding(&forged, &key).is_err()); - Ok(()) - } -} +include!("generation/section_1.rs"); +include!("generation/section_2.rs"); diff --git a/src/config/generation/section_1.rs b/src/config/generation/section_1.rs new file mode 100644 index 000000000..bcedd623e --- /dev/null +++ b/src/config/generation/section_1.rs @@ -0,0 +1,1201 @@ +use super::{files::compute_config_revision_gated, schema::Config}; +use anyhow::Context; +use arc_swap::ArcSwap; +use chrono::{DateTime, Utc}; +use parking_lot::{Mutex, RwLock}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{ + collections::{BTreeMap, BTreeSet}, + path::{Path, PathBuf}, + sync::{ + Arc, Weak, + atomic::{AtomicBool, AtomicU64, Ordering}, + }, +}; + +/// Resolve the existing part of a process-bound path and retain any missing +/// tail. This gives aliases one filesystem identity while keeping a pinned +/// binding verifiable if its config file is removed after launch. +fn process_path_identity(path: &Path) -> anyhow::Result { + if path.as_os_str().is_empty() { + return Ok(PathBuf::new()); + } + let mut cursor = path.to_path_buf(); + let mut missing = Vec::new(); + loop { + match cursor.canonicalize() { + Ok(mut resolved) => { + for segment in missing.iter().rev() { + resolved.push(segment); + } + return Ok(resolved); + } + Err(error) => { + let Some(segment) = cursor.file_name().map(ToOwned::to_owned) else { + return Err(error) + .with_context(|| format!("failed to resolve process-bound path {}", path.display())); + }; + missing.push(segment); + if !cursor.pop() { + return Err(error) + .with_context(|| format!("failed to resolve process-bound path {}", path.display())); + } + } + } + } +} + +pub(crate) fn process_paths_match(left: &Path, right: &Path) -> anyhow::Result { + Ok(process_path_identity(left)? == process_path_identity(right)?) +} + +/// Stable revision of the desired configuration source. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ConfigSourceRevision { + pub fingerprint_sha256: String, + pub disk_generation: Option, +} + +impl ConfigSourceRevision { + fn from_config(config: &Config) -> anyhow::Result { + if !config.config_path.as_os_str().is_empty() && config.config_path.exists() { + let (fingerprint, disk_generation) = compute_config_revision_gated(&config.config_path)?; + return Ok(Self { + fingerprint_sha256: fingerprint.iter().map(|byte| format!("{byte:02x}")).collect(), + disk_generation: Some(disk_generation), + }); + } + + let encoded = serde_json::to_vec(&normalized_process_config(config)?)?; + Ok(Self { + fingerprint_sha256: format!("{:x}", Sha256::digest(encoded)), + disk_generation: None, + }) + } +} + +/// Monotonic, process-local identifier of an actually published generation. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub struct ConfigGenerationId(pub u64); + +/// Origin of a reload attempt. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ConfigReloadTrigger { + Startup, + FileWatcher, + Api, + Tool, + ConfigFileApi, + PairingPersistence, + /// A configuration management transaction: an operator rollback, or the + /// restore of a change the runtime refused. + Management, + Test, +} + +/// A desired field that is valid on disk but cannot be activated in-process. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct DeferredConfigChange { + pub field: String, + pub reason: String, +} + +/// Immutable runtime configuration generation. +#[derive(Debug, Clone)] +pub struct ConfigGeneration { + pub id: ConfigGenerationId, + pub source_revision: ConfigSourceRevision, + pub effective: Arc, + pub applied_at: DateTime, + pub trigger: ConfigReloadTrigger, + pub deferred_changes: Arc<[DeferredConfigChange]>, +} + +/// A worker cannot replace the working root selected by its parent. +#[derive(Debug, thiserror::Error)] +#[error("worker working root differs from signed parent configuration")] +pub(crate) struct ProcessWorkingRootMismatch; + +/// Metadata, a working root override and a keyed effective snapshot digest. +/// Credential values and other configuration overrides are not transported. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ProcessGenerationBinding { + /// Parent in-memory working root, authenticated by the effective-config seal. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub working_root: Option, + pub id: ConfigGenerationId, + pub source_revision: ConfigSourceRevision, + pub applied_at: DateTime, + pub trigger: ConfigReloadTrigger, + pub deferred_changes: Vec, + pub seal: [u8; 32], +} + +// Disk migration materializes the inherited backend. Fingerprints and seals +// must bind the same representation while retaining explicit overrides. +fn normalized_process_config(config: &Config) -> anyhow::Result { + let mut normalized = serde_json::to_value(config)?; + let backend = crate::config::schema::decision_engine::effective_engine_backend(config); + let mut engine = config.decision_engine.clone(); + engine.backend = Some(backend.clone()); + if let Some(root) = normalized.as_object_mut() { + root.insert("decision_engine".into(), serde_json::to_value(engine)?); + } + normalized.sort_all_objects(); + Ok(normalized) +} + +impl ProcessGenerationBinding { + pub(crate) fn signing_payload(&self, config: &Config) -> anyhow::Result> { + // Config excludes both paths from serde; bind them explicitly. Sort + // nested maps so process-specific HashMap iteration cannot change a tag. + let workspace = process_path_identity(&config.workspace_dir)?; + let config_path = process_path_identity(&config.config_path)?; + let normalized = normalized_process_config(config)?; + let mut value = serde_json::to_value(( + self.id, + &self.source_revision, + self.applied_at, + self.trigger, + &self.deferred_changes, + workspace, + config_path, + ))?; + value.sort_all_objects(); + value + .as_array_mut() + .context("process signing metadata must serialize as an array")? + .push(normalized); + Ok(serde_json::to_vec(&value)?) + } +} + +impl ConfigGeneration { + /// Pin an ordinary child without startup globals or disk reloads. + pub(crate) fn for_child(config: &Config) -> anyhow::Result> { + let mut value = serde_json::to_value((&config.workspace_dir, &config.config_path, config))?; + value.sort_all_objects(); + let encoded = serde_json::to_vec(&value)?; + Ok(Arc::new(Self { + id: ConfigGenerationId(0), + source_revision: ConfigSourceRevision { + fingerprint_sha256: format!("{:x}", Sha256::digest(encoded)), + disk_generation: None, + }, + effective: Arc::new(config.clone()), + applied_at: Utc::now(), + trigger: ConfigReloadTrigger::Startup, + deferred_changes: Arc::from([]), + })) + } + + pub(crate) fn bind_process( + &self, + key: &crate::security::runtime_key::DecisionKey, + ) -> anyhow::Result { + anyhow::ensure!( + self.source_revision.fingerprint_sha256.len() == 64 + && self + .source_revision + .fingerprint_sha256 + .bytes() + .all(|byte| byte.is_ascii_hexdigit()), + "process configuration source revision is unavailable" + ); + let mut binding = ProcessGenerationBinding { + working_root: self.effective.runtime.workdir.clone(), + id: self.id, + source_revision: self.source_revision.clone(), + applied_at: self.applied_at, + trigger: self.trigger, + deferred_changes: self.deferred_changes.to_vec(), + seal: [0; 32], + }; + binding.seal = key.hmac( + crate::security::runtime_key::KeyDomain::StateFingerprint, + &[ + b"process-effective-config-v1", + &binding.signing_payload(&self.effective)?, + ], + ); + Ok(binding) + } + + /// Authenticate a parent-owned pinned generation without reopening mutable disk state. + pub(crate) fn verify_pinned_process_binding( + &self, + binding: &ProcessGenerationBinding, + key: &crate::security::runtime_key::DecisionKey, + ) -> anyhow::Result<()> { + let deferred_changes_match = self.deferred_changes.as_ref() == binding.deferred_changes.as_slice(); + anyhow::ensure!( + self.effective.runtime.workdir == binding.working_root + && self.id == binding.id + && self.source_revision == binding.source_revision + && self.applied_at == binding.applied_at + && self.trigger == binding.trigger + && deferred_changes_match, + "pinned process generation differs from launch" + ); + anyhow::ensure!( + key.verify_hmac( + crate::security::runtime_key::KeyDomain::StateFingerprint, + &[ + b"process-effective-config-v1", + &binding.signing_payload(&self.effective)? + ], + &binding.seal, + ), + "pinned process effective configuration differs from launch" + ); + Ok(()) + } + + /// Restore only an exact snapshot. A newer disk revision or a configuration + /// with different effective values cannot borrow the parent's generation id. + pub(crate) fn restore_process( + config: Config, + binding: &ProcessGenerationBinding, + key: &crate::security::runtime_key::DecisionKey, + ) -> anyhow::Result> { + if config.runtime.workdir != binding.working_root { + return Err(ProcessWorkingRootMismatch.into()); + } + anyhow::ensure!( + ConfigSourceRevision::from_config(&config)? == binding.source_revision, + "process configuration source differs from parent generation" + ); + anyhow::ensure!( + key.verify_hmac( + crate::security::runtime_key::KeyDomain::StateFingerprint, + &[b"process-effective-config-v1", &binding.signing_payload(&config)?], + &binding.seal + ), + "process effective configuration differs from parent generation" + ); + Ok(Arc::new(Self { + id: binding.id, + source_revision: binding.source_revision.clone(), + effective: Arc::new(config), + applied_at: binding.applied_at, + trigger: binding.trigger, + deferred_changes: binding.deferred_changes.clone().into(), + })) + } +} + +/// Latest valid configuration found on disk, including fields awaiting restart. +#[derive(Debug, Clone)] +pub struct DesiredConfigState { + pub source_revision: ConfigSourceRevision, + pub config: Arc, + pub observed_at: DateTime, +} + +/// Structured result shared by watcher, API and tool reload entry points. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ConfigApplyReport { + pub active_generation: ConfigGenerationId, + pub active_source_revision: ConfigSourceRevision, + pub desired_source_revision: ConfigSourceRevision, + pub changed: Vec, + pub applied: Vec, + pub rebuilt: Vec, + pub restarted: Vec, + pub restart_required: Vec, + pub participant_acks: Vec, +} + +impl ConfigApplyReport { + #[must_use] + pub const fn has_runtime_change(&self) -> bool { + !(self.applied.is_empty() && self.rebuilt.is_empty() && self.restarted.is_empty()) + } + + #[must_use] + pub const fn status(&self) -> &'static str { + if self.changed.is_empty() { + "unchanged" + } else if self.restart_required.is_empty() { + "applied" + } else if self.has_runtime_change() { + "applied_with_restart_required" + } else { + "restart_required" + } + } +} + +/// Most recent reload failure retained for doctor/health/config status. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ConfigReloadFailure { + pub occurred_at: DateTime, + pub trigger: ConfigReloadTrigger, + pub desired_source_revision: Option, + pub error: String, +} + +/// Read-only process status for the generation coordinator. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ConfigGenerationStatus { + pub active_generation: ConfigGenerationId, + pub active_source_revision: ConfigSourceRevision, + pub desired_source_revision: ConfigSourceRevision, + pub reload_in_progress: bool, + pub last_report: Option, + pub last_failure: Option, + pub registered_participants: Vec, +} + +/// Reload/supervisor event emitted into the existing MessageEvent ledger. +#[derive(Debug, Clone, Serialize)] +pub struct ConfigGenerationAuditEvent { + pub event_type: String, + pub generation_id: Option, + pub source_revision: Option, + pub trigger: ConfigReloadTrigger, + pub payload: serde_json::Value, +} + +/// Adapter used to route config lifecycle events to the process event fabric. +pub trait ConfigGenerationAuditSink: Send + Sync { + fn record(&self, event: ConfigGenerationAuditEvent); +} + +/// Sole process-level owner of active and desired configuration generations. +pub struct ConfigGenerationManager { + runtime_writes_frozen: AtomicBool, + active: ArcSwap, + /// Published generations remain addressable while an admitted operation + /// still owns its exact snapshot. Weak entries retain no configuration or + /// credentials after the last operation releases that generation. + published: Mutex>>, + desired: ArcSwap, + reload_lock: Mutex<()>, + next_generation: AtomicU64, + participants: RwLock>>, + reload_in_progress: AtomicBool, + last_report: RwLock>, + last_failure: RwLock>, + audit_sinks: RwLock>>, + /// The configured-model allowlist refreshed with every generation. + model_allowlist: Arc, +} + +/// Runtime subsystem that must prepare a complete candidate before publication. +pub trait ConfigGenerationParticipant: Send + Sync { + fn name(&self) -> &'static str; + + /// Whether this participant can atomically rebuild a rebuild-and-swap field. + fn supports_rebuild_field(&self, _field: &str) -> bool { + false + } + + /// Whether this participant can perform a controlled restart for a field. + fn supports_controlled_restart_field(&self, _field: &str) -> bool { + false + } + + /// Whether the participant must prepare when this effective field changes. + fn prepares_for_field(&self, field: &str) -> bool { + self.supports_rebuild_field(field) || self.supports_controlled_restart_field(field) + } + + fn prepare( + &self, + generation: Arc, + changed_fields: &[String], + ) -> anyhow::Result>; +} + +/// Reversible commit produced by a successful participant preparation. +pub trait PreparedConfigGeneration: Send { + fn commit(&mut self) -> anyhow::Result<()>; + fn rollback(&mut self); + + /// Release rollback state after the manager has published active. + fn finalize(&mut self) {} +} + +impl std::fmt::Debug for ConfigGenerationManager { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let active = self.active.load(); + formatter + .debug_struct("ConfigGenerationManager") + .field("active_generation", &active.id) + .field("active_source_revision", &active.source_revision) + .finish_non_exhaustive() + } +} + +impl ConfigGenerationManager { + /// Build the process owner around the startup-effective configuration. + #[must_use] + pub fn new(initial: Config) -> Self { + Self::with_model_allowlist(initial, crate::observability::labels::ModelAllowlist::global()) + } + + /// Establish an owner for a standalone caller that already holds an + /// effective generation. Unlike startup loading, this never relabels the + /// snapshot using a later on-disk revision. A generation with deferred + /// fields needs its existing manager, which owns the distinct desired + /// configuration; an effective snapshot cannot reconstruct that state. + pub(crate) fn from_pinned_generation(generation: Arc) -> anyhow::Result { + anyhow::ensure!( + generation.deferred_changes.is_empty(), + "a generation with deferred configuration requires its existing manager" + ); + anyhow::ensure!( + !generation.source_revision.fingerprint_sha256.is_empty() + && generation.source_revision.fingerprint_sha256 != "startup-unavailable", + "pinned configuration source revision is unavailable" + ); + let next_generation = generation + .id + .0 + .checked_add(1) + .ok_or_else(|| anyhow::anyhow!("configuration generation counter is exhausted"))?; + let model_allowlist = crate::observability::labels::ModelAllowlist::global(); + // Preserve standalone startup setup, but take every value from the + // supplied effective snapshot rather than loading a new revision. + crate::config::set_runtime_proxy_config(generation.effective.proxy.clone()); + if let Some(warning) = crate::config::manage::validate::decision_startup_check(&generation.effective) { + tracing::warn!("{warning}"); + } + if generation.effective.decision_engine.enabled + && let Some(warning) = crate::config::manage::validate::decision_orphans_warning(&generation.effective) + { + tracing::warn!("{warning}"); + } + model_allowlist.refresh(&generation.effective); + let desired = Arc::new(DesiredConfigState { + source_revision: generation.source_revision.clone(), + config: Arc::clone(&generation.effective), + observed_at: generation.applied_at, + }); + let published = BTreeMap::from([(generation.id, Arc::downgrade(&generation))]); + Ok(Self { + active: ArcSwap::from(generation), + published: Mutex::new(published), + desired: ArcSwap::from(desired), + reload_lock: Mutex::new(()), + next_generation: AtomicU64::new(next_generation), + participants: RwLock::new(Vec::new()), + runtime_writes_frozen: AtomicBool::new(false), + reload_in_progress: AtomicBool::new(false), + last_report: RwLock::new(None), + last_failure: RwLock::new(None), + audit_sinks: RwLock::new(Vec::new()), + model_allowlist, + }) + } + + /// [`Self::new`] refreshing `model_allowlist` instead of the process + /// allowlist the metrics read. + fn with_model_allowlist( + initial: Config, + model_allowlist: Arc, + ) -> Self { + crate::config::set_runtime_proxy_config(initial.proxy.clone()); + // Startup never fails for the decision plane: a refused backend + // runs builtin-only, and says so (D-094 C-1). + if let Some(warning) = crate::config::manage::validate::decision_startup_check(&initial) { + tracing::warn!("{warning}"); + } + // Decision credentials left unreferenced are reported (D-094 C-5); + // a disabled engine does not read the credential store. + if initial.decision_engine.enabled + && let Some(warning) = crate::config::manage::validate::decision_orphans_warning(&initial) + { + tracing::warn!("{warning}"); + } + // Metric model labels follow the configured models (D-059). + model_allowlist.refresh(&initial); + let source_revision = ConfigSourceRevision::from_config(&initial).unwrap_or_else(|_| ConfigSourceRevision { + fingerprint_sha256: "startup-unavailable".to_string(), + disk_generation: None, + }); + let config = Arc::new(initial); + let generation = Arc::new(ConfigGeneration { + id: ConfigGenerationId(0), + source_revision: source_revision.clone(), + effective: Arc::clone(&config), + applied_at: Utc::now(), + trigger: ConfigReloadTrigger::Startup, + deferred_changes: Arc::from([]), + }); + let desired = Arc::new(DesiredConfigState { + source_revision, + config, + observed_at: Utc::now(), + }); + let published = BTreeMap::from([(generation.id, Arc::downgrade(&generation))]); + Self { + active: ArcSwap::from(generation), + published: Mutex::new(published), + desired: ArcSwap::from(desired), + reload_lock: Mutex::new(()), + next_generation: AtomicU64::new(1), + participants: RwLock::new(Vec::new()), + runtime_writes_frozen: AtomicBool::new(false), + reload_in_progress: AtomicBool::new(false), + last_report: RwLock::new(None), + last_failure: RwLock::new(None), + audit_sinks: RwLock::new(Vec::new()), + model_allowlist, + } + } + + /// A runtime may only narrow this policy; no Config field clears it. + pub(crate) fn freeze_runtime_writes(&self) { + self.runtime_writes_frozen.store(true, Ordering::Release); + } + pub(crate) fn ensure_runtime_writable(&self) -> anyhow::Result<()> { + anyhow::ensure!( + !self.runtime_writes_frozen.load(Ordering::Acquire), + "configuration is frozen for controlled experiments" + ); + Ok(()) + } + + /// Register a weakly-held runtime participant. + /// + /// The caller retains the strong `Arc`; stale registrations disappear when + /// their owning component is dropped or restarted. + pub fn register_participant(&self, participant: &Arc) { + let _reload_guard = self.reload_lock.lock(); + self.participants.write().push(Arc::downgrade(participant)); + } + + /// Register an event-fabric adapter for reload and supervisor lifecycle audit. + pub fn register_audit_sink(&self, sink: Arc) { + self.audit_sinks.write().push(sink); + } + + /// Pin the complete immutable active generation for one operation. + #[must_use] + pub fn pin(&self) -> Arc { + self.active.load_full() + } + + /// Recover one published generation only while an admitted operation still + /// pins it. This lets long-lived tool registries resolve the provider owned + /// by an in-flight turn without retaining superseded credentials forever. + #[must_use] + pub(crate) fn pin_generation(&self, id: ConfigGenerationId) -> Option> { + let active = self.active.load_full(); + if active.id == id { + return Some(active); + } + let mut published = self.published.lock(); + published.retain(|_, generation| generation.strong_count() > 0); + published.get(&id).and_then(Weak::upgrade) + } + + /// Compatibility accessor for readers that only need the effective config. + #[must_use] + pub fn load_full(&self) -> Arc { + Arc::clone(&self.active.load_full().effective) + } + + /// Compatibility accessor matching the former ArcSwap reader surface. + #[must_use] + pub fn load(&self) -> Arc { + self.load_full() + } + + /// Return the latest desired configuration, including deferred fields. + #[must_use] + pub fn desired(&self) -> Arc { + self.desired.load_full() + } + + #[must_use] + pub fn active_generation_id(&self) -> ConfigGenerationId { + self.active.load().id + } + + /// Snapshot coordinator status without exposing mutation primitives. + #[must_use] + pub fn status(&self) -> ConfigGenerationStatus { + let active = self.active.load_full(); + let desired = self.desired.load_full(); + let mut registered_participants = self + .participants + .read() + .iter() + .filter_map(Weak::upgrade) + .map(|participant| participant.name().to_string()) + .collect::>(); + registered_participants.sort(); + registered_participants.dedup(); + ConfigGenerationStatus { + active_generation: active.id, + active_source_revision: active.source_revision.clone(), + desired_source_revision: desired.source_revision.clone(), + reload_in_progress: self.reload_in_progress.load(Ordering::Acquire), + last_report: self.last_report.read().clone(), + last_failure: self.last_failure.read().clone(), + registered_participants, + } + } + + /// Load a stable merged snapshot from the configured source and apply it. + pub fn reload_from_disk(&self, trigger: ConfigReloadTrigger) -> anyhow::Result { + self.ensure_runtime_writable()?; + let current = self.load_full(); + let config_path = current.config_path.clone(); + if config_path.as_os_str().is_empty() { + let error = anyhow::anyhow!("Config path is not set; cannot reload"); + self.record_failure(trigger, None, &error); + return Err(error); + } + // The revision is the one the loaded files had, not one read again + // afterwards: a write landing in between must not be published as the + // revision of content that does not contain it. + let (fresh, revision) = match load_stable_config_snapshot(&config_path, current.workspace_dir.clone()) { + Ok(snapshot) => snapshot, + Err(error) => { + self.record_failure(trigger, None, &error); + return Err(error); + } + }; + #[cfg(test)] + run_after_snapshot_hook(&config_path); + // An operator's file edit is trusted and applied without + // confirmation; one that sends decisions off the machine is said so, + // once the reload is applied (D-079 L-4, D-082 N-4). It is compared + // with the desired configuration, so an edit already published and + // waiting for a restart is not reported again. + let remote_paths = if matches!(trigger, ConfigReloadTrigger::FileWatcher | ConfigReloadTrigger::Tool) { + hand_edited_remote_decisions(&self.desired().config, &fresh) + } else { + Vec::new() + }; + let report = self.apply_config(fresh, revision, trigger)?; + for path in remote_paths { + tracing::warn!( + path = %path, + "a configuration file edit sends decision state off this machine; it was applied without \ + confirmation because the operator edited the file" + ); + } + Ok(report) + } + + /// Publish a validated desired configuration through the sole owner. + /// + /// Process-restart-only fields are retained from the previous active + /// generation while the complete desired value remains queryable via + /// [`desired`](Self::desired). + pub fn apply_config( + &self, + desired: Config, + source_revision: ConfigSourceRevision, + trigger: ConfigReloadTrigger, + ) -> anyhow::Result { + self.ensure_runtime_writable()?; + let _reload_guard = self.reload_lock.lock(); + self.reload_in_progress.store(true, Ordering::Release); + let result = self.apply_config_locked(desired, source_revision.clone(), trigger); + self.reload_in_progress.store(false, Ordering::Release); + match &result { + Ok(report) => { + *self.last_report.write() = Some(report.clone()); + *self.last_failure.write() = None; + if report.has_runtime_change() { + self.emit_audit(ConfigGenerationAuditEvent { + event_type: "config.reload.applied".to_string(), + generation_id: Some(report.active_generation), + source_revision: Some(report.active_source_revision.clone()), + trigger, + payload: serde_json::to_value(report).unwrap_or_else(|_| serde_json::json!({})), + }); + } + if !report.restart_required.is_empty() { + self.emit_audit(ConfigGenerationAuditEvent { + event_type: "config.reload.deferred".to_string(), + generation_id: Some(report.active_generation), + source_revision: Some(report.desired_source_revision.clone()), + trigger, + payload: serde_json::json!({ + "restart_required": report.restart_required, + }), + }); + } + } + Err(error) => self.record_failure(trigger, Some(source_revision), error), + } + result + } + + fn apply_config_locked( + &self, + desired: Config, + source_revision: ConfigSourceRevision, + trigger: ConfigReloadTrigger, + ) -> anyhow::Result { + desired.validate()?; + + let old_generation = self.active.load_full(); + // The decision backend check every configuration plan runs: a hand + // edit to an invalid backend leaves this generation active + // (CDP-12, R-CXR P0-B t2). + // A reload that does not own a refusal is not held back by it + // (D-094 C-1). + if let Some(warning) = + crate::config::manage::validate::check_decision_plane(Some(old_generation.effective.as_ref()), &desired) + .map_err(|refusal| anyhow::anyhow!(refusal))? + { + tracing::warn!("{warning}"); + } + let active = old_generation.effective.as_ref(); + let adopted = adopt_live_pairing_tokens(active, &desired, trigger); + let old = adopted.as_ref().unwrap_or(active); + let changed = changed_top_level_fields(old, &desired)?; + let participants = { + let mut registrations = self.participants.write(); + let active = registrations.iter().filter_map(Weak::upgrade).collect::>(); + registrations.retain(|participant| participant.strong_count() > 0); + active + }; + let restart_required = changed + .iter() + .filter(|field| { + is_process_restart_only(field) + || (is_rebuild_and_swap(field) + && !participants + .iter() + .any(|participant| participant.supports_rebuild_field(field))) + || (is_controlled_restart(field) + && !participants + .iter() + .any(|participant| participant.supports_controlled_restart_field(field))) + }) + .cloned() + .collect::>(); + let rebuilt = changed + .iter() + .filter(|field| is_rebuild_and_swap(field) && !restart_required.contains(field)) + .cloned() + .collect::>(); + let restarted = changed + .iter() + .filter(|field| is_controlled_restart(field) && !restart_required.contains(field)) + .cloned() + .collect::>(); + let mut applied = changed + .iter() + .filter(|field| { + !is_process_restart_only(field) && !is_rebuild_and_swap(field) && !is_controlled_restart(field) + }) + .cloned() + .collect::>(); + // Adopted pairing tokens are applied in-process (the pairing guard + // holds them); report them so, unless another `gateway` change is + // what is being deferred. + let mut changed = changed; + if adopted.is_some() && !changed.iter().any(|field| field == "gateway") { + changed.push("gateway".to_string()); + applied.push("gateway".to_string()); + } + + self.desired.store(Arc::new(DesiredConfigState { + source_revision: source_revision.clone(), + config: Arc::new(desired.clone()), + observed_at: Utc::now(), + })); + + let effective = preserve_deferred_fields(old, desired, &restart_required)?; + // Against the generation that is really active: adopted pairing + // tokens are a change to publish even when nothing else changed. + let effective_changed = changed_top_level_fields(active, &effective)?; + let deferred_changes: Arc<[DeferredConfigChange]> = restart_required + .iter() + .map(|field| DeferredConfigChange { + field: field.clone(), + reason: "process restart required".to_string(), + }) + .collect::>() + .into(); + + let mut participant_acks = Vec::new(); + let (active_generation, active_source_revision) = if effective_changed.is_empty() { + (old_generation.id, old_generation.source_revision.clone()) + } else { + let supervisor_switch = !restarted.is_empty() + || participants.iter().any(|participant| { + participant.name() == "daemon_component_supervisors" + && effective_changed + .iter() + .any(|field| participant.prepares_for_field(field)) + }); + let id = ConfigGenerationId( + self.next_generation + .try_update(Ordering::SeqCst, Ordering::SeqCst, |next| next.checked_add(1)) + .map_err(|_| anyhow::anyhow!("configuration generation counter is exhausted"))?, + ); + let generation = Arc::new(ConfigGeneration { + id, + source_revision: source_revision.clone(), + effective: Arc::new(effective), + applied_at: Utc::now(), + trigger, + deferred_changes, + }); + self.emit_audit(ConfigGenerationAuditEvent { + event_type: "config.reload.prepared".to_string(), + generation_id: Some(generation.id), + source_revision: Some(generation.source_revision.clone()), + trigger, + payload: serde_json::json!({ + "changed": effective_changed, + "rebuilt": rebuilt, + "restarted": restarted, + }), + }); + let previous_runtime_proxy = effective_changed + .iter() + .any(|field| field == "proxy") + .then(crate::config::runtime_proxy_config); + if previous_runtime_proxy.is_some() { + crate::config::set_runtime_proxy_config(generation.effective.proxy.clone()); + } + if supervisor_switch { + self.emit_audit(ConfigGenerationAuditEvent { + event_type: "config.supervisor.restart_started".to_string(), + generation_id: Some(generation.id), + source_revision: Some(generation.source_revision.clone()), + trigger, + payload: serde_json::json!({ "fields": restarted }), + }); + } + let mut prepared = Vec::with_capacity(participants.len()); + for participant in participants.into_iter().filter(|participant| { + effective_changed + .iter() + .any(|field| participant.prepares_for_field(field)) + }) { + match participant.prepare(Arc::clone(&generation), &effective_changed) { + Ok(update) => { + participant_acks.push(participant.name().to_string()); + prepared.push(update); + } + Err(error) => { + for update in prepared.iter_mut().rev() { + update.rollback(); + } + if let Some(previous_proxy) = previous_runtime_proxy.as_ref() { + crate::config::set_runtime_proxy_config(previous_proxy.clone()); + } + if supervisor_switch { + self.emit_audit(ConfigGenerationAuditEvent { + event_type: "config.supervisor.rollback".to_string(), + generation_id: Some(generation.id), + source_revision: Some(generation.source_revision.clone()), + trigger, + payload: serde_json::json!({ + "participant": participant.name(), + "reason": error.to_string(), + }), + }); + } + return Err(anyhow::anyhow!( + "config generation participant '{}' rejected generation {}: {error}", + participant.name(), + generation.id.0 + )); + } + } + } + if let Err(error) = prepared.iter_mut().try_for_each(|update| update.commit()) { + for update in prepared.iter_mut().rev() { + update.rollback(); + } + if let Some(previous_proxy) = previous_runtime_proxy.as_ref() { + crate::config::set_runtime_proxy_config(previous_proxy.clone()); + } + if supervisor_switch { + self.emit_audit(ConfigGenerationAuditEvent { + event_type: "config.supervisor.rollback".to_string(), + generation_id: Some(generation.id), + source_revision: Some(generation.source_revision.clone()), + trigger, + payload: serde_json::json!({ "reason": error.to_string() }), + }); + } + anyhow::bail!( + "config generation participant commit failed for generation {}: {error}", + generation.id.0 + ); + } + self.active.store(Arc::clone(&generation)); + { + let mut published = self.published.lock(); + published.retain(|_, pinned| pinned.strong_count() > 0); + published.insert(generation.id, Arc::downgrade(&generation)); + } + self.model_allowlist.refresh(&generation.effective); + for update in &mut prepared { + update.finalize(); + } + if supervisor_switch { + self.emit_audit(ConfigGenerationAuditEvent { + event_type: "config.supervisor.restart_completed".to_string(), + generation_id: Some(generation.id), + source_revision: Some(generation.source_revision.clone()), + trigger, + payload: serde_json::json!({ "fields": restarted }), + }); + } + (generation.id, generation.source_revision.clone()) + }; + + Ok(ConfigApplyReport { + active_generation, + active_source_revision, + desired_source_revision: source_revision, + changed, + applied, + rebuilt, + restarted, + restart_required, + participant_acks, + }) + } + + /// Convenience for in-memory callers and tests that do not have a disk revision. + pub fn apply_runtime_config( + &self, + desired: Config, + trigger: ConfigReloadTrigger, + ) -> anyhow::Result { + let revision = ConfigSourceRevision::from_config(&desired)?; + self.apply_config(desired, revision, trigger) + } + + fn record_failure( + &self, + trigger: ConfigReloadTrigger, + desired_source_revision: Option, + error: &anyhow::Error, + ) { + *self.last_failure.write() = Some(ConfigReloadFailure { + occurred_at: Utc::now(), + trigger, + desired_source_revision: desired_source_revision.clone(), + error: error.to_string(), + }); + self.emit_audit(ConfigGenerationAuditEvent { + event_type: "config.reload.failed".to_string(), + generation_id: Some(self.active_generation_id()), + source_revision: desired_source_revision, + trigger, + payload: serde_json::json!({ "error": error.to_string() }), + }); + } + + fn emit_audit(&self, event: ConfigGenerationAuditEvent) { + for sink in self.audit_sinks.read().iter() { + sink.record(event.clone()); + } + } +} + +/// Test seam: run once, for one config path, right after the stable +/// snapshot is loaded (a write landing in the reload's window). +#[cfg(test)] +#[allow(clippy::type_complexity)] +pub(crate) static AFTER_SNAPSHOT_HOOK: parking_lot::Mutex)>> = + parking_lot::Mutex::new(None); + +#[cfg(test)] +fn run_after_snapshot_hook(config_path: &Path) { + let hook = { + let mut slot = AFTER_SNAPSHOT_HOOK.lock(); + if slot.as_ref().is_some_and(|(path, _)| path == config_path) { + slot.take() + } else { + None + } + }; + if let Some((_, hook)) = hook { + hook(); + } +} + +fn load_stable_config_snapshot( + config_path: &Path, + workspace_dir: std::path::PathBuf, +) -> anyhow::Result<(Config, ConfigSourceRevision)> { + const MAX_ATTEMPTS: usize = 3; + + for attempt in 1..=MAX_ATTEMPTS { + let before = compute_config_revision_gated(config_path)?; + let fresh = Config::load_from_path(config_path, workspace_dir.clone())?; + let after = compute_config_revision_gated(config_path)?; + if before == after { + let (fingerprint, disk_generation) = before; + let revision = ConfigSourceRevision { + fingerprint_sha256: fingerprint.iter().map(|byte| format!("{byte:02x}")).collect(), + disk_generation: Some(disk_generation), + }; + return Ok((fresh, revision)); + } + + tracing::debug!( + path = %config_path.display(), + attempt, + "Config changed during generation snapshot; retrying" + ); + std::thread::sleep(std::time::Duration::from_millis(50)); + } + + anyhow::bail!("Config changed repeatedly while reloading: {}", config_path.display()) +} + +fn changed_top_level_fields(old: &Config, desired: &Config) -> anyhow::Result> { + let old = serde_json::to_value(old)?; + let desired = serde_json::to_value(desired)?; + let old = old + .as_object() + .ok_or_else(|| anyhow::anyhow!("serialized config root is not an object"))?; + let desired = desired + .as_object() + .ok_or_else(|| anyhow::anyhow!("serialized config root is not an object"))?; + let keys = old.keys().chain(desired.keys()).cloned().collect::>(); + Ok(keys + .into_iter() + .filter(|key| old.get(key) != desired.get(key)) + .collect()) +} + +/// The active configuration with the persisted `gateway.paired_tokens` +/// adopted, when `trigger` is the pairing persistence and the list differs. +/// +/// `gateway` is a process-restart-only field, and its token list is too for +/// every other writer: a token added by hand is not accepted until restart. +/// The one exception is `/pair`: the running pairing guard already holds the +/// token it issued, and the reload that persists it is triggered with +/// [`ConfigReloadTrigger::PairingPersistence`]. Keeping the old list active +/// after that reload made every later reload find `gateway` changed again, so +/// even a save of `agent.compact_context` reported +/// `restart_required: ["gateway"]` (CONSOLE-OBS-3), and a supervised gateway +/// restart would have been built from the list without the token. Only the +/// token list is adopted; any other `gateway` change stays deferred. +fn adopt_live_pairing_tokens(active: &Config, desired: &Config, trigger: ConfigReloadTrigger) -> Option { + if trigger != ConfigReloadTrigger::PairingPersistence + || active.gateway.paired_tokens == desired.gateway.paired_tokens + { + return None; + } + let mut adopted = active.clone(); + adopted.gateway.paired_tokens.clone_from(&desired.gateway.paired_tokens); + Some(adopted) +} + +pub(crate) fn is_process_restart_only(field: &str) -> bool { + matches!( + field, + "runtime" + | "memory" + | "storage" + | "tunnel" + | "gateway" + | "modules" + | "observability" + | "mcp_server" + | "a2a" + | "skills_lifecycle" + | "plugins" + ) +} + +pub(crate) fn is_controlled_restart(field: &str) -> bool { + matches!( + field, + "channels_config" | "cron" | "scheduler" | "heartbeat" | "xin" | "webhook" | "self_system" + ) +} + +pub(crate) fn is_rebuild_and_swap(field: &str) -> bool { + matches!( + field, + "api_key" + | "api_url" + | "auth" + | "default_provider" + | "default_model" + | "providers" + | "reliability" + | "security" + | "autonomy" + | "browser" + | "http_request" + | "multimodal" + | "mcp" + | "composio" + | "agents" + | "tool_tiering" + | "nodes" + | "skills" + | "skill_rag" + | "model_routes" + | "embedding_routes" + | "query_classification" + | "task_routing" + | "router" + | "smart_group" + | "identity" + | "identity_bindings" + | "user_policies" + | "secrets" + | "media" + | "proxy" + ) +} + +/// The paths of `remote_decision_enabled` reasons between `old` and `new`: +/// what a hand edit applied by a reload turned towards remote decisions. +fn hand_edited_remote_decisions(old: &Config, new: &Config) -> Vec { + crate::config::manage::ConfigChangeSummary::between(Some(old), new) + .map(|summary| { + summary + .risk_reasons + .into_iter() + .filter_map(|reason| match reason { + crate::config::manage::RiskReason::RemoteDecisionEnabled { path } => Some(path), + _ => None, + }) + .collect() + }) + .unwrap_or_else(|error| { + tracing::warn!(error = %crate::security::redaction::redact_provider_text(&format!("{error:#}")), "could not compare the reloaded configuration"); + Vec::new() + }) +} + +fn preserve_deferred_fields(old: &Config, desired: Config, fields: &[String]) -> anyhow::Result { + let old_value = serde_json::to_value(old)?; + let mut effective_value = serde_json::to_value(desired)?; + let old_object = old_value + .as_object() + .ok_or_else(|| anyhow::anyhow!("serialized active config root is not an object"))?; + let effective_object = effective_value + .as_object_mut() + .ok_or_else(|| anyhow::anyhow!("serialized desired config root is not an object"))?; + for field in fields { + if let Some(value) = old_object.get(field) { + effective_object.insert(field.clone(), value.clone()); + } else { + effective_object.remove(field); + } + } + let mut effective: Config = serde_json::from_value(effective_value)?; + effective.workspace_dir = old.workspace_dir.clone(); + effective.config_path = old.config_path.clone(); + Ok(effective) +} diff --git a/src/config/generation/section_2.rs b/src/config/generation/section_2.rs new file mode 100644 index 000000000..c2e10e1a0 --- /dev/null +++ b/src/config/generation/section_2.rs @@ -0,0 +1,1080 @@ +#[cfg(test)] +mod tests { + /// S7: the child snapshot fingerprint keeps its encoding: + /// SHA-256 over the sorted JSON of `(workspace_dir, config_path, config)`. + #[test] + fn for_child_fingerprint_encoding_is_unchanged() { + use sha2::Digest as _; + // The vector input of `runtime::child_source::tests::golden_effective_config` + // with the two paths set; its serialized object is the same literal. + let mut config = crate::config::Config::default(); + config.decision_engine.backend = + Some(crate::config::schema::decision_engine::effective_engine_backend(&config).clone()); + for model in ["zeta/model", "alpha/model"] { + config.cost.prices.insert( + model.to_owned(), + crate::config::schema::ModelPricing { + input: 1.0, + output: 2.0, + cache_write: 0.0, + cache_read: 0.0, + }, + ); + } + config.workspace_dir = std::path::PathBuf::from("/prx/ws-1"); + config.config_path = std::path::PathBuf::from("/prx/config.toml"); + let generation = super::ConfigGeneration::for_child(&config).unwrap(); + // §2: SHA-256 of the sorted array `[workspace, config_path, config]`, + // spelled out from literals, and the pinned digest of those bytes. + let preimage = [ + br#"["/prx/ws-1","/prx/config.toml","#.as_slice(), + include_bytes!("../../runtime/child_source/golden_effective_config.json").as_slice(), + b"]", + ] + .concat(); + const FOR_CHILD_FINGERPRINT: &str = "82d04107528a017756b4311354691ae8cdae998870eb4902307c16e0b9e23df4"; + assert_eq!(format!("{:x}", sha2::Sha256::digest(&preimage)), FOR_CHILD_FINGERPRINT); + assert_eq!(generation.source_revision.fingerprint_sha256, FOR_CHILD_FINGERPRINT); + assert_eq!(generation.id.0, 0); + assert!(generation.source_revision.disk_generation.is_none()); + } + use super::*; + use serial_test::serial; + + struct RecordingParticipant { + name: &'static str, + events: Arc>>, + fail_prepare: bool, + fail_commit: bool, + } + + struct RecordingPrepared { + name: &'static str, + events: Arc>>, + fail_commit: bool, + } + + struct RecordingAuditSink { + event_types: Arc>>, + } + + impl ConfigGenerationAuditSink for RecordingAuditSink { + fn record(&self, event: ConfigGenerationAuditEvent) { + self.event_types.lock().push(event.event_type); + } + } + + impl ConfigGenerationParticipant for RecordingParticipant { + fn name(&self) -> &'static str { + self.name + } + + fn supports_rebuild_field(&self, _field: &str) -> bool { + true + } + + fn supports_controlled_restart_field(&self, _field: &str) -> bool { + true + } + + fn prepares_for_field(&self, _field: &str) -> bool { + true + } + + fn prepare( + &self, + _generation: Arc, + _changed_fields: &[String], + ) -> anyhow::Result> { + self.events.lock().push(format!("{}.prepare", self.name)); + if self.fail_prepare { + anyhow::bail!("injected prepare failure"); + } + Ok(Box::new(RecordingPrepared { + name: self.name, + events: Arc::clone(&self.events), + fail_commit: self.fail_commit, + })) + } + } + + impl PreparedConfigGeneration for RecordingPrepared { + fn commit(&mut self) -> anyhow::Result<()> { + self.events.lock().push(format!("{}.commit", self.name)); + if self.fail_commit { + anyhow::bail!("injected commit failure"); + } + Ok(()) + } + + fn rollback(&mut self) { + self.events.lock().push(format!("{}.rollback", self.name)); + } + + fn finalize(&mut self) { + self.events.lock().push(format!("{}.finalize", self.name)); + } + } + + /// The proxy the publication tests publish: a real `all_proxy`, so the + /// publication stays observable, but with loopback exempt, so a test + /// running at the same time against its own `127.0.0.1` server is never + /// sent to a proxy that is not there (R-INT2A F3). A services scope with a + /// dummy key would be refused by validation, which only knows real keys. + fn test_publication_proxy(url: &str) -> crate::config::ProxyConfig { + crate::config::ProxyConfig { + all_proxy: Some(url.to_string()), + no_proxy: vec!["127.0.0.1".to_string(), "localhost".to_string(), "::1".to_string()], + ..Config::default().proxy + } + } + + /// Restores the process-wide runtime proxy when dropped, so a failing + /// assertion cannot leave a test proxy published. + struct RuntimeProxyRestore(crate::config::ProxyConfig); + + impl RuntimeProxyRestore { + fn capture() -> Self { + Self(crate::config::runtime_proxy_config()) + } + + fn publish(proxy: crate::config::ProxyConfig) -> Self { + let restore = Self::capture(); + crate::config::set_runtime_proxy_config(proxy); + restore + } + } + + impl Drop for RuntimeProxyRestore { + fn drop(&mut self) { + crate::config::set_runtime_proxy_config(self.0.clone()); + } + } + + fn participant( + name: &'static str, + events: Arc>>, + fail_prepare: bool, + fail_commit: bool, + ) -> Arc { + Arc::new(RecordingParticipant { + name, + events, + fail_prepare, + fail_commit, + }) + } + + #[test] + #[serial] + fn one_operation_keeps_pinned_generation_after_reload() { + let manager = ConfigGenerationManager::new(Config::default()); + let pinned = manager.pin(); + let mut desired = (*pinned.effective).clone(); + desired.default_temperature = 0.31; + + let report = manager + .apply_runtime_config(desired, ConfigReloadTrigger::Test) + .expect("apply config"); + + assert_eq!(pinned.id, ConfigGenerationId(0)); + assert_eq!(manager.pin().id, report.active_generation); + assert_ne!(pinned.id, manager.pin().id); + assert_ne!( + pinned.effective.default_temperature, + manager.pin().effective.default_temperature + ); + } + + #[test] + #[serial] + fn restart_only_fields_update_desired_but_not_active() { + let manager = ConfigGenerationManager::new(Config::default()); + let old_active = manager.load_full(); + let mut desired = (*old_active).clone(); + desired.runtime.kind = "docker".to_string(); + + let report = manager + .apply_runtime_config(desired.clone(), ConfigReloadTrigger::Test) + .expect("apply config"); + + assert_eq!(manager.load_full().runtime.kind, old_active.runtime.kind); + assert_eq!(manager.desired().config.runtime.kind, desired.runtime.kind); + assert_eq!(report.restart_required, vec!["runtime"]); + assert_eq!(report.status(), "restart_required"); + } + + /// `[skills_lifecycle]` is read once at process start (the service, its + /// store and the registered tools are built from it), so a reload that + /// changes it reports `restart_required` and the effective configuration + /// keeps the old value, while the desired one records the edit. + #[test] + #[serial] + fn a_changed_skills_lifecycle_needs_a_restart_and_keeps_the_old_value() { + let manager = ConfigGenerationManager::new(Config::default()); + let old_active = manager.load_full(); + assert!(!old_active.skills_lifecycle.enabled); + let mut desired = (*old_active).clone(); + desired.skills_lifecycle.enabled = true; + desired.skills_lifecycle.owner_scope = Some("owner:ws:cli:alice".to_string()); + desired.skills_lifecycle.mode = crate::config::skills_lifecycle::SkillsLifecycleModeConfig::Auto; + + let report = manager + .apply_runtime_config(desired.clone(), ConfigReloadTrigger::Test) + .expect("apply config"); + + assert_eq!(report.restart_required, vec!["skills_lifecycle"]); + assert_eq!(report.status(), "restart_required"); + assert_eq!(manager.load_full().skills_lifecycle, old_active.skills_lifecycle); + assert!(!manager.load_full().skills_lifecycle.enabled); + assert_eq!(manager.desired().config.skills_lifecycle, desired.skills_lifecycle); + assert!(is_process_restart_only("skills_lifecycle")); + } + + #[test] + #[serial] + fn reload_report_classifies_runtime_changes() { + let manager = ConfigGenerationManager::new(Config::default()); + let events = Arc::new(Mutex::new(Vec::new())); + let runtime = participant("runtime", events, false, false); + manager.register_participant(&runtime); + let mut desired = (*manager.load_full()).clone(); + desired.default_temperature = 0.22; + desired.default_model = Some("example/model".to_string()); + desired.cron.max_run_history += 1; + + let report = manager + .apply_runtime_config(desired, ConfigReloadTrigger::Test) + .expect("apply config"); + + assert_eq!(report.applied, vec!["default_temperature"]); + assert_eq!(report.rebuilt, vec!["default_model"]); + assert_eq!(report.restarted, vec!["cron"]); + assert!(report.restart_required.is_empty(), "expected an empty value"); + } + + /// CONSOLE-OBS-3 (CONSOLE-VERIFY): once the gateway paired, every later + /// save reported `restart_required: ["gateway"]`, even one that changed + /// only `agent.compact_context`. `/pair` persists the new token hash and + /// reloads; `gateway` is restart-only, so the active generation kept the + /// old (empty) token list while disk held the new one, and every reload + /// after it found `gateway` different again. The pairing guard already + /// holds that token, so the pairing reload adopts the persisted list into + /// the active generation; nothing else about `gateway` is adopted. + #[test] + #[serial] + fn a_save_after_pairing_does_not_report_a_gateway_restart() { + let manager = ConfigGenerationManager::new(Config::default()); + let mut paired = (*manager.load_full()).clone(); + paired.gateway.paired_tokens = vec![crate::security::pairing::hash_token("zc_paired_in_test")]; + + let pairing = manager + .apply_runtime_config(paired.clone(), ConfigReloadTrigger::PairingPersistence) + .expect("test: pairing reload"); + assert!( + pairing.restart_required.is_empty(), + "the token pairing just issued is live already: {:?}", + pairing.restart_required + ); + assert_eq!( + manager.load_full().gateway.paired_tokens, + paired.gateway.paired_tokens, + "the active generation carries the persisted token list" + ); + assert_eq!(pairing.applied, vec!["gateway"], "the adoption is reported as applied"); + + let mut save = paired; + save.agent.compact_context = !save.agent.compact_context; + let report = manager + .apply_runtime_config(save, ConfigReloadTrigger::Api) + .expect("test: low-risk save"); + assert!( + report.restart_required.is_empty(), + "a save of agent.compact_context must not report a restart: {:?}", + report.restart_required + ); + assert_eq!(report.applied, vec!["agent"]); + } + + /// The pairing adoption is exactly the token list: another `gateway` + /// change in the same reload stays deferred, and a token list changed by + /// any other writer (a hand edit picked up by the watcher) still needs a + /// restart, because the running pairing guard never loaded it. + #[test] + #[serial] + fn only_pairing_adopts_only_the_token_list() { + let manager = ConfigGenerationManager::new(Config::default()); + let original_port = manager.load_full().gateway.port; + let mut desired = (*manager.load_full()).clone(); + desired.gateway.paired_tokens = vec![crate::security::pairing::hash_token("zc_first")]; + desired.gateway.port = original_port.wrapping_add(1); + + let report = manager + .apply_runtime_config(desired.clone(), ConfigReloadTrigger::PairingPersistence) + .expect("test: pairing reload with a port change"); + assert_eq!(report.restart_required, vec!["gateway"]); + let active = manager.load_full(); + assert_eq!( + active.gateway.port, original_port, + "the port change waits for a restart" + ); + assert_eq!(active.gateway.paired_tokens, desired.gateway.paired_tokens); + + let mut hand_edit = desired; + hand_edit.gateway.port = original_port; + hand_edit.gateway.paired_tokens.push("operator-added-token".to_string()); + let report = manager + .apply_runtime_config(hand_edit, ConfigReloadTrigger::FileWatcher) + .expect("test: watcher reload"); + assert_eq!( + report.restart_required, + vec!["gateway"], + "a token the pairing guard never loaded is not live until restart" + ); + assert_eq!(manager.load_full().gateway.paired_tokens.len(), 1); + } + + #[test] + fn auth_and_proxy_are_rebuild_and_swap_fields() { + assert!(is_rebuild_and_swap("auth")); + assert!(is_rebuild_and_swap("proxy")); + assert!(!is_process_restart_only("auth")); + assert!(!is_process_restart_only("proxy")); + } + + /// Serve one HTTP response on a loopback port and return its URL. + fn one_shot_loopback_server() -> String { + use std::io::{Read, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("test: bind"); + let addr = listener.local_addr().expect("test: addr"); + std::thread::spawn(move || { + if let Ok((mut socket, _)) = listener.accept() { + let mut buffer = [0_u8; 1024]; + let _ = socket.read(&mut buffer); + let _ = socket.write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 2\r\nconnection: close\r\n\r\nok"); + } + }); + format!("http://{addr}/") + } + + /// R-INT2A F3: while a publication test's proxy is live, a concurrently + /// running test's runtime-proxy-built client can still reach its own + /// loopback server. Before, the published `all_proxy` applied to every + /// service with no loopback exemption, so such a client was sent to the + /// absent proxy and refused (this is how the A12 test hung). + #[tokio::test] + #[serial] + async fn a_published_test_proxy_leaves_loopback_clients_alone() { + let url = one_shot_loopback_server(); + let _restore = RuntimeProxyRestore::publish(test_publication_proxy("http://127.0.0.1:8080")); + let client = crate::config::build_runtime_proxy_client("provider.compatible").expect("test: client"); + let response = tokio::time::timeout(std::time::Duration::from_secs(20), client.get(&url).send()) + .await + .expect("test: bounded") + .expect("test: the loopback request bypasses the test proxy"); + assert!(response.status().is_success()); + } + + #[test] + #[serial] + fn proxy_runtime_state_tracks_successful_generation_publication() { + let _restore = RuntimeProxyRestore::capture(); + let initial = Config::default(); + let manager = ConfigGenerationManager::new(initial.clone()); + let events = Arc::new(Mutex::new(Vec::new())); + let runtime = participant("runtime", events, false, false); + manager.register_participant(&runtime); + let mut desired = initial; + desired.proxy = test_publication_proxy("http://127.0.0.1:8080"); + + let report = manager + .apply_runtime_config(desired.clone(), ConfigReloadTrigger::Test) + .expect("proxy generation must publish"); + let runtime_proxy = crate::config::runtime_proxy_config(); + + assert_eq!(report.rebuilt, vec!["proxy"]); + assert!(runtime_proxy.has_any_proxy_url()); + assert_eq!(runtime_proxy.all_proxy, desired.proxy.all_proxy); + } + + #[test] + #[serial] + fn proxy_runtime_state_rolls_back_when_participant_rejects_candidate() { + let _restore = RuntimeProxyRestore::capture(); + let initial = Config::default(); + let manager = ConfigGenerationManager::new(initial.clone()); + let events = Arc::new(Mutex::new(Vec::new())); + let rejecting = participant("rejecting", events, true, false); + manager.register_participant(&rejecting); + let mut desired = initial.clone(); + desired.proxy = test_publication_proxy("http://127.0.0.1:8081"); + + manager + .apply_runtime_config(desired, ConfigReloadTrigger::Test) + .expect_err("rejected proxy candidate must roll back"); + let runtime_proxy = crate::config::runtime_proxy_config(); + + assert_eq!(manager.active_generation_id(), ConfigGenerationId(0)); + assert_eq!(runtime_proxy.has_any_proxy_url(), initial.proxy.has_any_proxy_url()); + assert_eq!(runtime_proxy.all_proxy, initial.proxy.all_proxy); + } + + #[test] + #[serial] + fn participant_prepare_failure_rolls_back_and_keeps_active_generation() { + let manager = ConfigGenerationManager::new(Config::default()); + let events = Arc::new(Mutex::new(Vec::new())); + let first = participant("first", Arc::clone(&events), false, false); + let second = participant("second", Arc::clone(&events), true, false); + manager.register_participant(&first); + manager.register_participant(&second); + let mut desired = (*manager.load_full()).clone(); + desired.default_temperature = 0.19; + + let error = manager + .apply_runtime_config(desired.clone(), ConfigReloadTrigger::Test) + .expect_err("second participant must reject candidate"); + + assert!(error.to_string().contains("second")); + assert_eq!(manager.active_generation_id(), ConfigGenerationId(0)); + assert_eq!( + manager.desired().config.default_temperature, + desired.default_temperature + ); + assert_eq!( + *events.lock(), + vec!["first.prepare", "second.prepare", "first.rollback"] + ); + assert!(manager.status().last_failure.is_some()); + } + + #[test] + #[serial] + fn participant_commit_failure_rolls_every_candidate_back_before_publish() { + let manager = ConfigGenerationManager::new(Config::default()); + let events = Arc::new(Mutex::new(Vec::new())); + let first = participant("first", Arc::clone(&events), false, false); + let second = participant("second", Arc::clone(&events), false, true); + manager.register_participant(&first); + manager.register_participant(&second); + let mut desired = (*manager.load_full()).clone(); + desired.default_temperature = 0.18; + + manager + .apply_runtime_config(desired, ConfigReloadTrigger::Test) + .expect_err("second participant commit must fail"); + + assert_eq!(manager.active_generation_id(), ConfigGenerationId(0)); + assert_eq!( + *events.lock(), + vec![ + "first.prepare", + "second.prepare", + "first.commit", + "second.commit", + "second.rollback", + "first.rollback", + ] + ); + } + + #[test] + #[serial] + fn successful_participants_finalize_only_after_publication() { + let manager = ConfigGenerationManager::new(Config::default()); + let events = Arc::new(Mutex::new(Vec::new())); + let participant = participant("runtime", Arc::clone(&events), false, false); + manager.register_participant(&participant); + let mut desired = (*manager.load_full()).clone(); + desired.default_temperature = 0.17; + + let report = manager + .apply_runtime_config(desired, ConfigReloadTrigger::Test) + .expect("candidate must publish"); + + assert_eq!(manager.active_generation_id(), report.active_generation); + assert_eq!(report.participant_acks, vec!["runtime"]); + assert_eq!( + *events.lock(), + vec!["runtime.prepare", "runtime.commit", "runtime.finalize"] + ); + } + + #[test] + #[serial] + fn concurrent_reload_attempts_are_serialized_into_distinct_generations() { + let manager = Arc::new(ConfigGenerationManager::new(Config::default())); + let mut handles = Vec::new(); + for temperature in [0.12, 0.13] { + let manager = Arc::clone(&manager); + handles.push(std::thread::spawn(move || { + let mut desired = (*manager.load_full()).clone(); + desired.default_temperature = temperature; + manager + .apply_runtime_config(desired, ConfigReloadTrigger::Test) + .expect("serialized reload") + .active_generation + })); + } + let mut generations = handles + .into_iter() + .map(|handle| handle.join().expect("reload thread")) + .collect::>(); + generations.sort(); + + assert_eq!(generations, vec![ConfigGenerationId(1), ConfigGenerationId(2)]); + assert_eq!(manager.active_generation_id(), ConfigGenerationId(2)); + } + + #[test] + #[serial] + fn reload_and_supervisor_lifecycle_use_the_shared_audit_sink() { + let manager = ConfigGenerationManager::new(Config::default()); + let participant_events = Arc::new(Mutex::new(Vec::new())); + let runtime = participant("runtime", participant_events, false, false); + manager.register_participant(&runtime); + let audit_events = Arc::new(Mutex::new(Vec::new())); + manager.register_audit_sink(Arc::new(RecordingAuditSink { + event_types: Arc::clone(&audit_events), + })); + let mut desired = (*manager.load_full()).clone(); + desired.default_temperature = 0.11; + desired.cron.max_run_history += 1; + + manager + .apply_runtime_config(desired, ConfigReloadTrigger::Test) + .expect("reload with controlled restart"); + + assert_eq!( + *audit_events.lock(), + vec![ + "config.reload.prepared", + "config.supervisor.restart_started", + "config.supervisor.restart_completed", + "config.reload.applied", + ] + ); + } + + /// PMMD-g (N-8): the revision `reload_from_disk` publishes with the + /// desired configuration is the one of the files it loaded, not of a + /// write that landed after the load. + /// D-074 P1-1: the reload rebuilds the active generation through a JSON + /// round trip (`preserve_deferred_fields`); configured values and the + /// schema version survive the reload. + #[test] + fn a_reload_keeps_the_decision_engine_settings() { + let dir = tempfile::TempDir::new().expect("test: temp dir"); + let config_path = dir.path().join("config.toml"); + std::fs::write(&config_path, CAUSAL_FIXTURE).expect("test: causal config"); + let initial = Config::load_from_path(&config_path, dir.path().join("workspace")).expect("test: load"); + let manager = ConfigGenerationManager::new(initial); + std::fs::write( + &config_path, + CAUSAL_FIXTURE.replace("default_temperature = 0.7", "default_temperature = 0.4"), + ) + .expect("test: edited config"); + + manager + .reload_from_disk(ConfigReloadTrigger::Test) + .expect("test: reload"); + assert!((manager.load_full().default_temperature - 0.4).abs() < f64::EPSILON); + + for config in [manager.load_full(), Arc::clone(&manager.desired().config)] { + let engine = &config.decision_engine; + assert_eq!(engine.latency_budget_ms, 3_000); + assert!((engine.token_ratio_limit - 0.5).abs() < f32::EPSILON); + assert_eq!(engine.max_candidates, 5); + } + } + + /// D-079 L-4: a hand edit that turns remote decisions on is found, so + /// the reload can warn; a local edit is not. + #[test] + fn a_hand_edited_remote_enablement_is_reported() { + use crate::config::schema::decision_engine::BackendSelection; + let old = Config::default(); + let mut new = old.clone(); + new.decision_engine.backend.get_or_insert_with(Default::default).kind = + BackendSelection::Fixed(crate::config::schema::decision_engine::BackendKind::CompatibleHttp); + new.decision_engine + .backend + .get_or_insert_with(Default::default) + .endpoint = "https://decisions.example.com/v1".to_string(); + new.decision_engine + .backend + .get_or_insert_with(Default::default) + .remote_enabled = true; + assert_eq!( + hand_edited_remote_decisions(&old, &new), + vec!["decision_engine.backend.remote_enabled".to_string()] + ); + let mut local = old.clone(); + local.decision_engine.enabled = true; + assert!( + hand_edited_remote_decisions(&old, &local).is_empty(), + "expected an empty value" + ); + } + + /// D-082 N-4: the hand-edit warning is logged only when the reload is + /// applied; a refused reload logs nothing of it. + /// D-059: the configured-model allowlist follows the applied + /// generation: a model named only by the new configuration becomes a + /// label after the reload, and one no longer named becomes `unlisted`. + /// The manager refreshes its own allowlist here, so no other test can + /// race it. + #[test] + fn the_model_allowlist_follows_the_applied_generation() { + use crate::observability::labels::{ModelAllowlist, UNLISTED_MODEL}; + let dir = tempfile::TempDir::new().expect("test: temp dir"); + let config_path = dir.path().join("config.toml"); + std::fs::write( + &config_path, + "default_temperature = 0.7\n\n[decision_engine.backend]\nmodel = \"vendor/before-reload\"\n", + ) + .expect("test: config"); + let initial = Config::load_from_path(&config_path, dir.path().join("workspace")).expect("test: load"); + let allowlist = Arc::new(ModelAllowlist::default()); + let manager = ConfigGenerationManager::with_model_allowlist(initial, Arc::clone(&allowlist)); + // A participant that rebuilds, so every edit is applied rather than + // deferred to a restart. + let events = Arc::new(Mutex::new(Vec::new())); + let rebuilding = participant("decision", events, false, false); + manager.register_participant(&rebuilding); + assert_eq!(allowlist.label("vendor/before-reload"), "vendor/before-reload"); + assert_eq!(allowlist.label("vendor/after-reload"), UNLISTED_MODEL); + std::fs::write( + &config_path, + "default_temperature = 0.7\n\n[decision_engine.backend]\nmodel = \"vendor/after-reload\"\n", + ) + .expect("test: edit"); + manager + .reload_from_disk(ConfigReloadTrigger::FileWatcher) + .expect("test: reload"); + assert_eq!(allowlist.label("vendor/after-reload"), "vendor/after-reload"); + assert_eq!(allowlist.label("vendor/before-reload"), UNLISTED_MODEL); + } + + #[test] + #[serial] + fn a_hand_edited_remote_enablement_is_logged_only_when_applied() { + #[derive(Clone, Default)] + struct Sink(Arc>>); + impl std::io::Write for Sink { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.lock().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Sink { + type Writer = Self; + fn make_writer(&'a self) -> Self::Writer { + self.clone() + } + } + const REMOTE: &str = "default_temperature = 0.4\n\n[decision_engine.backend]\n\ + kind = \"compatible_http\"\nendpoint = \"https://decisions.example.com/v1\"\n\ + model = \"decider-1\"\nremote_enabled = true\n\n[[providers.models]]\n\ + provider = \"custom:https://decisions.example.com/v1\"\nmodel = \"decider-1\"\n\ + operations = [\"decision_endpoint\"]\n"; + let run = |fail_prepare: bool| { + let dir = tempfile::TempDir::new().expect("test: temp dir"); + let config_path = dir.path().join("config.toml"); + std::fs::write(&config_path, "default_temperature = 0.7\n").expect("test: config"); + let initial = Config::load_from_path(&config_path, dir.path().join("workspace")).expect("test: load"); + let manager = ConfigGenerationManager::new(initial); + let events = Arc::new(Mutex::new(Vec::new())); + let refusing = participant("refusing", Arc::clone(&events), fail_prepare, false); + manager.register_participant(&refusing); + std::fs::write(&config_path, REMOTE).expect("test: edit"); + let sink = Sink::default(); + let subscriber = tracing_subscriber::fmt() + .with_writer(sink.clone()) + .with_ansi(false) + .finish(); + let result = tracing::subscriber::with_default(subscriber, || { + // Another test may have cached this callsite as disabled. + tracing::callsite::rebuild_interest_cache(); + let result = manager.reload_from_disk(ConfigReloadTrigger::FileWatcher); + // A control line: the capture worked for this run, so a + // missing warning is a real absence (D-086 C-3). + tracing::warn!("capture control line"); + result + }); + let logs = String::from_utf8_lossy(&sink.0.lock()).to_string(); + (result.is_ok(), logs) + }; + let (applied, logs) = run(false); + assert!(applied); + assert!( + logs.contains("sends decision state off this machine") + && logs.contains("decision_engine.backend.remote_enabled"), + "{logs}" + ); + assert!( + !logs.contains("decisions.example.com"), + "the warning names the path, never the endpoint: {logs}" + ); + let (applied, logs) = run(true); + assert!(!applied, "the participant refused the reload"); + assert!(logs.contains("capture control line"), "the capture must work: {logs}"); + assert!(!logs.contains("sends decision state off this machine"), "{logs}"); + } + + /// CDP-04 (V6.07 hot-reload half): a hand edit that points the decision + /// backend at a remote host without `remote_enabled` does not activate; + /// the running generation is kept. + #[test] + fn a_remote_decision_endpoint_without_the_remote_switch_keeps_the_generation() { + let dir = tempfile::TempDir::new().expect("test: temp dir"); + let config_path = dir.path().join("config.toml"); + std::fs::write(&config_path, "default_temperature = 0.7\n").expect("test: config"); + let initial = Config::load_from_path(&config_path, dir.path().join("workspace")).expect("test: load"); + let manager = ConfigGenerationManager::new(initial); + let active = manager.active_generation_id(); + std::fs::write( + &config_path, + "default_temperature = 0.4\n\n[decision_engine.backend]\nkind = \"compatible_http\"\n\ + endpoint = \"https://decisions.example.com/v1\"\n", + ) + .expect("test: edit"); + let error = manager + .reload_from_disk(ConfigReloadTrigger::Test) + .expect_err("test: refused"); + let message = format!("{error:#}"); + assert!(message.contains("remote_enabled"), "{message}"); + assert!(!message.contains("decisions.example.com"), "{message}"); + assert_eq!(manager.active_generation_id(), active); + assert!((manager.load_full().default_temperature - 0.7).abs() < f64::EPSILON); + assert!(manager.load_full().decision_engine.backend.is_none()); + } + + /// CDP-12 (R-CXR P0-B t2): a hand edit to a decision backend the strict + /// selection refuses (here a model nobody declared for + /// `decision_endpoint`) leaves the running generation active. + #[test] + fn an_invalid_causal_backend_leaves_the_prior_generation_active() { + let dir = tempfile::TempDir::new().expect("test: temp dir"); + let config_path = dir.path().join("config.toml"); + std::fs::write(&config_path, "default_temperature = 0.7\n").expect("test: config"); + let initial = Config::load_from_path(&config_path, dir.path().join("workspace")).expect("test: load"); + let manager = ConfigGenerationManager::new(initial); + let events = Arc::new(Mutex::new(Vec::new())); + let rebuilding = participant("decision", events, false, false); + manager.register_participant(&rebuilding); + let active = manager.active_generation_id(); + std::fs::write( + &config_path, + "default_temperature = 0.4\n\n[decision_engine.backend]\nkind = \"compatible_http\"\n\ + endpoint = \"http://127.0.0.1:8900/v1\"\nmodel = \"undeclared-model\"\n", + ) + .expect("test: edit"); + let error = manager + .reload_from_disk(ConfigReloadTrigger::Test) + .expect_err("test: refused"); + assert!(format!("{error:#}").contains("decision_engine.backend"), "{error:#}"); + assert_eq!(manager.active_generation_id(), active); + assert!((manager.load_full().default_temperature - 0.7).abs() < f64::EPSILON); + + // Declared for decision_endpoint, the same backend activates. + std::fs::write( + &config_path, + "default_temperature = 0.4\n\n[decision_engine.backend]\nkind = \"compatible_http\"\n\ + endpoint = \"http://127.0.0.1:8900/v1\"\nmodel = \"undeclared-model\"\n\n\ + [[providers.models]]\nprovider = \"custom:http://127.0.0.1:8900/v1\"\nmodel = \"undeclared-model\"\n\ + operations = [\"decision_endpoint\"]\n", + ) + .expect("test: edit"); + manager + .reload_from_disk(ConfigReloadTrigger::Test) + .expect("test: applied"); + assert_ne!(manager.active_generation_id(), active); + } + + /// D-094 C-1: a daemon started with a decision section the check + /// refuses starts, and a later reload that does not touch + /// `[decision_engine]` is applied; one that does is still refused. + #[test] + fn an_invalid_decision_section_never_blocks_startup_or_unrelated_reloads() { + const INVALID: &str = "\n[decision_engine.backend]\nkind = \"compatible_http\"\n\ + endpoint = \"http://127.0.0.1:8900/v1\"\nmodel = \"undeclared-model\"\n"; + let dir = tempfile::TempDir::new().expect("test: temp dir"); + let config_path = dir.path().join("config.toml"); + std::fs::write(&config_path, format!("default_temperature = 0.7\n{INVALID}")).expect("test: config"); + let initial = Config::load_from_path(&config_path, dir.path().join("workspace")).expect("test: load"); + let manager = ConfigGenerationManager::new(initial); + let active = manager.active_generation_id(); + // A declaration for another provider: the check runs, finds the + // section already refused, and does not hold the change back. + const UNRELATED: &str = "\n[[providers.models]]\nprovider = \"openrouter\"\nmodel = \"vendor/chat-model\"\n\ + operations = [\"chat\"]\n"; + std::fs::write(&config_path, format!("default_temperature = 0.4\n{INVALID}{UNRELATED}")).expect("test: edit"); + manager + .reload_from_disk(ConfigReloadTrigger::Test) + .expect("test: an unrelated change is applied"); + assert_ne!(manager.active_generation_id(), active); + assert!((manager.load_full().default_temperature - 0.4).abs() < f64::EPSILON); + let active = manager.active_generation_id(); + std::fs::write( + &config_path, + format!( + "default_temperature = 0.4\n{}{UNRELATED}", + INVALID.replace("undeclared-model", "other-model") + ), + ) + .expect("test: edit"); + let error = manager + .reload_from_disk(ConfigReloadTrigger::Test) + .expect_err("test: a change to the section is refused"); + assert!(format!("{error:#}").contains("decision_engine.backend"), "{error:#}"); + assert_eq!(manager.active_generation_id(), active); + } + + const CAUSAL_FIXTURE: &str = r#"default_temperature = 0.7 + +[decision_engine] +latency_budget_ms = 3000 +token_ratio_limit = 0.5 +max_candidates = 5 +"#; + + #[test] + fn a_reload_publishes_the_revision_of_the_files_it_loaded() { + let dir = tempfile::TempDir::new().expect("test: temp dir"); + let config_path = dir.path().join("config.toml"); + std::fs::write(&config_path, "default_temperature = 0.7\n").expect("test: config"); + let mut initial = Config::default(); + initial.config_path = config_path.clone(); + initial.workspace_dir = dir.path().join("workspace"); + let manager = ConfigGenerationManager::new(initial); + let loaded_revision = crate::config::files::current_config_revision(&config_path).expect("test: revision"); + let writer_path = config_path.clone(); + *AFTER_SNAPSHOT_HOOK.lock() = Some(( + config_path, + Box::new(move || { + std::fs::write(&writer_path, "default_temperature = 0.4\n").expect("test: late write"); + }), + )); + + manager + .reload_from_disk(ConfigReloadTrigger::Test) + .expect("test: reload"); + + let desired = manager.desired(); + assert!((desired.config.default_temperature - 0.7).abs() < f64::EPSILON); + assert_eq!( + desired.source_revision.fingerprint_sha256, loaded_revision, + "the desired configuration must carry the revision it was loaded from" + ); + } +} + +#[cfg(test)] +mod pinned_parent_process_binding_tests { + use super::*; + + fn fixture() -> anyhow::Result<( + tempfile::TempDir, + ConfigGeneration, + Arc, + )> { + let home = tempfile::tempdir()?; + let config = Config { + config_path: home.path().join("config.toml"), + workspace_dir: home.path().join("workspace"), + ..Config::default() + }; + std::fs::write(&config.config_path, toml::to_string(&config)?)?; + let generation = ConfigGeneration { + id: ConfigGenerationId(7), + source_revision: ConfigSourceRevision::from_config(&config)?, + effective: Arc::new(config), + applied_at: Utc::now(), + trigger: ConfigReloadTrigger::Test, + deferred_changes: Arc::from([]), + }; + let transport = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, b"prx-parent-binding-fixture"); + let key = crate::security::runtime_key::DecisionKey::from_worker_channel( + &transport, + "prx-workspace", + "prx-run", + "prx-config", + )?; + Ok((home, generation, key)) + } + + #[cfg(unix)] + #[test] + fn canonical_config_working_root_survives_signed_worker_restore() -> anyhow::Result<()> { + let (home, mut generation, key) = fixture()?; + let root = home.path().join("root"); + std::fs::create_dir(&root)?; + let alias = home.path().join("alias"); + std::os::unix::fs::symlink(&root, &alias)?; + let mut stored = generation.effective.as_ref().clone(); + stored.runtime.workdir = Some(alias); + std::fs::write(&stored.config_path, toml::to_string(&stored)?)?; + let parent = Config::load_from_path(&stored.config_path, stored.workspace_dir.clone())?; + generation.source_revision = ConfigSourceRevision::from_config(&parent)?; + generation.effective = Arc::new(parent); + let binding = generation.bind_process(&key)?; + let canonical = root.canonicalize()?; + assert_eq!( + binding.working_root.as_ref(), + Some(&canonical), + "test: signed carrier uses the canonical parent value" + ); + generation.verify_pinned_process_binding(&binding, &key)?; + let mut worker = Config::load_from_path(&stored.config_path, stored.workspace_dir)?; + worker.runtime.workdir = binding.working_root.clone(); + let restored = ConfigGeneration::restore_process(worker, &binding, &key)?; + assert_eq!( + restored.effective.runtime.workdir.as_ref(), + Some(&canonical), + "test: worker and parent authenticate the same canonical root" + ); + Ok(()) + } + + #[test] + fn working_root_binding_rejects_worker_widening_and_tampering() -> anyhow::Result<()> { + let (home, mut generation, key) = fixture()?; + let root = home.path().join("root"); + std::fs::create_dir(&root)?; + Arc::make_mut(&mut generation.effective).runtime.workdir = Some(root.clone()); + let binding = generation.bind_process(&key)?; + assert_eq!( + binding.working_root.as_ref(), + Some(&root), + "test: parent root is carried" + ); + ConfigGeneration::restore_process(generation.effective.as_ref().clone(), &binding, &key)?; + for candidate in [None, Some(home.path().to_path_buf())] { + let mut child = generation.effective.as_ref().clone(); + child.runtime.workdir = candidate; + let error = ConfigGeneration::restore_process(child, &binding, &key) + .expect_err("test: worker cannot widen or discard signed parent root"); + assert!( + error.downcast_ref::().is_some(), + "test: root mismatch is a typed refusal" + ); + } + let mut tampered = binding; + tampered.working_root = Some(home.path().to_path_buf()); + assert!( + generation.verify_pinned_process_binding(&tampered, &key).is_err(), + "test: carrier cannot differ from pinned parent root" + ); + Ok(()) + } + + #[test] + fn pinned_parent_binding_survives_removed_source_but_child_restore_rejects() -> anyhow::Result<()> { + let (_home, generation, key) = fixture()?; + let binding = generation.bind_process(&key)?; + generation.verify_pinned_process_binding(&binding, &key)?; + ConfigGeneration::restore_process(generation.effective.as_ref().clone(), &binding, &key)?; + std::fs::remove_file(&generation.effective.config_path)?; + generation.verify_pinned_process_binding(&binding, &key)?; + assert!(ConfigGeneration::restore_process(generation.effective.as_ref().clone(), &binding, &key).is_err()); + Ok(()) + } + + #[test] + fn pinned_parent_binding_survives_changed_source_but_child_restore_rejects() -> anyhow::Result<()> { + let (_home, generation, key) = fixture()?; + let binding = generation.bind_process(&key)?; + std::fs::write(&generation.effective.config_path, "default_temperature = 0.25\n")?; + generation.verify_pinned_process_binding(&binding, &key)?; + assert!(ConfigGeneration::restore_process(generation.effective.as_ref().clone(), &binding, &key).is_err()); + Ok(()) + } + + #[cfg(unix)] + #[test] + fn process_binding_accepts_a_filesystem_alias_for_the_same_source() -> anyhow::Result<()> { + use std::os::unix::fs::symlink; + + let (home, generation, key) = fixture()?; + std::fs::create_dir_all(&generation.effective.workspace_dir)?; + let binding = generation.bind_process(&key)?; + let alias = home.path().join("source-alias"); + symlink(home.path(), &alias)?; + let mut child = generation.effective.as_ref().clone(); + child.config_path = alias.join("config.toml"); + child.workspace_dir = alias.join("workspace"); + + let restored = ConfigGeneration::restore_process(child, &binding, &key)?; + assert_eq!(restored.id, generation.id); + assert_eq!(restored.source_revision, generation.source_revision); + Ok(()) + } + + #[test] + fn pinned_parent_binding_rejects_metadata_snapshot_paths_and_key_mutation() -> anyhow::Result<()> { + let (_home, generation, key) = fixture()?; + let binding = generation.bind_process(&key)?; + let mut changed = generation.clone(); + changed.id = ConfigGenerationId(8); + assert!(changed.verify_pinned_process_binding(&binding, &key).is_err()); + let mut changed = generation.clone(); + changed.source_revision.disk_generation = None; + assert!(changed.verify_pinned_process_binding(&binding, &key).is_err()); + let mut changed = generation.clone(); + changed.source_revision.fingerprint_sha256 = "0".repeat(64); + assert!(changed.verify_pinned_process_binding(&binding, &key).is_err()); + let mut changed = generation.clone(); + changed.applied_at += chrono::Duration::seconds(1); + assert!(changed.verify_pinned_process_binding(&binding, &key).is_err()); + let mut changed = generation.clone(); + changed.trigger = ConfigReloadTrigger::Startup; + assert!(changed.verify_pinned_process_binding(&binding, &key).is_err()); + let mut changed = generation.clone(); + changed.deferred_changes = vec![DeferredConfigChange { + field: "prx-field".to_owned(), + reason: "prx-reason".to_owned(), + }] + .into(); + assert!(changed.verify_pinned_process_binding(&binding, &key).is_err()); + for field in ["workspace", "config", "effective"] { + let mut changed = generation.clone(); + let config = Arc::make_mut(&mut changed.effective); + match field { + "workspace" => config.workspace_dir = std::path::PathBuf::from("/prx-other-workspace"), + "config" => config.config_path = std::path::PathBuf::from("/prx-other-config"), + _ => config.default_temperature += 0.1, + } + assert!(changed.verify_pinned_process_binding(&binding, &key).is_err()); + } + let transport = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, b"prx-wrong-binding-key"); + let wrong = crate::security::runtime_key::DecisionKey::from_worker_channel( + &transport, + "prx-workspace", + "prx-run", + "prx-config", + )?; + assert!(generation.verify_pinned_process_binding(&binding, &wrong).is_err()); + let transport = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, b"prx-parent-binding-fixture"); + for (workspace, run, config) in [ + ("prx-other-workspace", "prx-run", "prx-config"), + ("prx-workspace", "prx-other-run", "prx-config"), + ("prx-workspace", "prx-run", "prx-other-config"), + ] { + let different_scope = + crate::security::runtime_key::DecisionKey::from_worker_channel(&transport, workspace, run, config)?; + assert!( + generation + .verify_pinned_process_binding(&binding, &different_scope) + .is_err() + ); + } + let mut forged = binding; + forged.seal = [0; 32]; + assert!(generation.verify_pinned_process_binding(&forged, &key).is_err()); + Ok(()) + } +} diff --git a/src/config/mod.rs b/src/config/mod.rs index c189d5525..b76dccb9d 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -23,26 +23,25 @@ pub use hotreload::{HotReloadManager, SharedConfig, new_shared}; pub(crate) use schema::set_runtime_proxy_config; pub use schema::{ - A2aConfig, A2aCredential, A2aPeer, A2aPeerAuth, AgentCompactionConfig, AgentCompactionMode, AgentConfig, - AgentLimits, AuditConfig, AuthConfig, AutonomyConfig, BrowserComputerUseConfig, BrowserConfig, ChannelsConfig, - ChatConfig, ClassificationRule, ComposioConfig, Config, CostConfig, CronConfig, DEFAULT_CHANNEL_EXCLUDED_TOOLS, - DelegateAgentConfig, DiscordConfig, DmPolicy, DockerRuntimeConfig, EMBEDDING_DEFAULT_UPGRADE_NOTICE, - EmbeddingRouteConfig, FitnessConfig, GatewayConfig, GroupPolicy, GroupReplyMode, HYBRID_PROCESS_MEMORY_UNAVAILABLE, - HeartbeatConfig, HttpRequestConfig, IMessageConfig, IdentityBindingConfig, IdentityConfig, LarkConfig, McpConfig, - McpServerConfig, McpServerRuntimeConfig, McpTransport, MediaConfig, MemoryConfig, MemoryEventsConfig, - MemorySemanticConfig, MemoryWebhookConfig, ModelRouteConfig, MultimodalConfig, NextcloudTalkConfig, - NodeServerConfig, NodesConfig, ObservabilityConfig, OllamaProviderConfig, OsPagingConfig, ProvidersConfig, - ProxyConfig, ProxyScope, QueryClassificationConfig, RamfluxAccountConfig, RamfluxAttachmentFetch, - RamfluxAuthorizationMode, RamfluxConfig, RamfluxOnNewMessage, RamfluxSurfaceLimits, - ReliabilityCircuitBreakerConfig, ReliabilityConfig, RemoteNodeConfig, RemoteTreeLimits, RetrievalInjectionRole, - RouterConfig, RouterModelConfig, RuntimeConfig, SchedulerConfig, ScopeConfig, ScopeDefault, ScopeRule, - SecretsConfig, SecurityConfig, SelfSystemConfig, SessionsSpawnConfig, SkillsConfig, SlackConfig, SmartGroupConfig, - StorageConfig, StorageProviderConfig, StorageProviderSection, StreamMode, TaskRoutingConfig, - TaskRoutingIntentConfig, TaskRoutingRule, TelegramConfig, ToolTieringConfig, TunnelConfig, UserPolicyConfig, - WacliConfig, WebSearchConfig, WebhookConfig, WhatsAppConfig, WorkdirError, WorkspaceHooks, WorkspaceMcpServers, - apply_runtime_proxy_to_builder, bootstrap_max_blocking_threads, build_runtime_proxy_client, - build_runtime_proxy_client_with_timeouts, default_openprx_dir, expand_home, platform_config_dir, - process_config_dir, resolve_init_target_dir, runtime_proxy_config, runtime_proxy_generation, + A2aConfig, A2aPeer, AgentCompactionConfig, AgentCompactionMode, AgentConfig, AgentLimits, AuditConfig, AuthConfig, + AutonomyConfig, BrowserComputerUseConfig, BrowserConfig, ChannelsConfig, ChatConfig, ClassificationRule, + ComposioConfig, Config, CostConfig, CronConfig, DEFAULT_CHANNEL_EXCLUDED_TOOLS, DelegateAgentConfig, DiscordConfig, + DmPolicy, DockerRuntimeConfig, EMBEDDING_DEFAULT_UPGRADE_NOTICE, EmbeddingRouteConfig, FitnessConfig, + GatewayConfig, GroupPolicy, GroupReplyMode, HYBRID_PROCESS_MEMORY_UNAVAILABLE, HeartbeatConfig, HttpRequestConfig, + IMessageConfig, IdentityBindingConfig, IdentityConfig, LarkConfig, McpConfig, McpServerConfig, + McpServerRuntimeConfig, McpTransport, MediaConfig, MemoryConfig, MemoryEventsConfig, MemorySemanticConfig, + MemoryWebhookConfig, ModelRouteConfig, MultimodalConfig, NextcloudTalkConfig, NodeServerConfig, NodesConfig, + ObservabilityConfig, OllamaProviderConfig, OsPagingConfig, ProvidersConfig, ProxyConfig, ProxyScope, + QueryClassificationConfig, RamfluxAccountConfig, RamfluxAttachmentFetch, RamfluxAuthorizationMode, RamfluxConfig, + RamfluxOnNewMessage, RamfluxSurfaceLimits, ReliabilityCircuitBreakerConfig, ReliabilityConfig, RemoteNodeConfig, + RemoteTreeLimits, RetrievalInjectionRole, RouterConfig, RouterModelConfig, RuntimeConfig, SchedulerConfig, + ScopeConfig, ScopeDefault, ScopeRule, SecretsConfig, SecurityConfig, SelfSystemConfig, SessionsSpawnConfig, + SkillsConfig, SlackConfig, SmartGroupConfig, StorageConfig, StorageProviderConfig, StorageProviderSection, + StreamMode, TaskRoutingConfig, TaskRoutingIntentConfig, TaskRoutingRule, TelegramConfig, ToolTieringConfig, + TunnelConfig, UserPolicyConfig, WacliConfig, WebSearchConfig, WebhookConfig, WhatsAppConfig, WorkdirError, + WorkspaceHooks, WorkspaceMcpServers, apply_runtime_proxy_to_builder, bootstrap_max_blocking_threads, + build_runtime_proxy_client, build_runtime_proxy_client_with_timeouts, default_openprx_dir, expand_home, + platform_config_dir, process_config_dir, resolve_init_target_dir, runtime_proxy_config, runtime_proxy_generation, set_process_config_dir, user_home_dir, }; diff --git a/src/config/schema/agent.rs b/src/config/schema/agent.rs index 046cbd8c1..d040c38d2 100644 --- a/src/config/schema/agent.rs +++ b/src/config/schema/agent.rs @@ -3,6 +3,8 @@ use super::{Deserialize, JsonSchema, Serialize, default_true}; /// Agent orchestration configuration (`[agent]` section). #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] pub struct AgentConfig { + #[serde(default)] + pub messaging: super::AgentMessaging, /// rf approve-and-continue wait; Console approvals retain their own expiry. #[serde( default = "super::default_approval_wait_secs", @@ -392,6 +394,7 @@ pub(super) const fn default_agent_compaction_max_context_tokens() -> usize { impl Default for AgentConfig { fn default() -> Self { Self { + messaging: super::AgentMessaging::default(), approval_wait_secs: super::default_approval_wait_secs(), compact_context: false, read_only_tool_concurrency_window: default_read_only_tool_concurrency_window(), diff --git a/src/config/schema/integrations.rs b/src/config/schema/integrations.rs index cae17fb87..4e8f90abf 100644 --- a/src/config/schema/integrations.rs +++ b/src/config/schema/integrations.rs @@ -303,30 +303,14 @@ pub struct A2aConfig { /// ignored and the caller must authenticate with a bearer JWT. #[serde(default)] pub spiffe_strict_validation: bool, - /// PEM server certificate for the dedicated A2A listener. Required for a - /// non-loopback bind. Relative to the config dir. Read at use. - #[serde(default)] - pub tls_cert_path: Option, - /// PEM server key for the dedicated A2A listener. Required for a - /// non-loopback bind. File mode must be 0600 at use. - #[serde(default)] - pub tls_key_path: Option, - /// Optional PEM CA(s) for inbound client-certificate verification. - #[serde(default)] - pub client_ca_path: Option, - /// When true, A2A messaging routes are registered. FOUNDATION keeps this - /// false; ACT-1 flips it. + /// Enable the dedicated pinned mTLS messaging listener. #[serde(default)] pub messaging_enabled: bool, - /// Remote causal-tree occupancy caps. - #[serde(default)] - pub remote_tree: RemoteTreeLimits, - /// Named peer grants. Empty until operators add `[a2a.peers.*]`. + /// SPIFFE trust domain for new instance identities. + #[serde(default = "default_a2a_trust_domain")] + pub trust_domain: String, #[serde(default)] pub peers: HashMap, - /// Outbound identities used by `[a2a.peers.*.credential]`. - #[serde(default)] - pub credentials: HashMap, } /// Caps for one remote causal tree (`[a2a.remote_tree]`). @@ -374,67 +358,24 @@ impl Default for RemoteTreeLimits { } /// Inbound key-possession method a peer must use. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] -#[serde(rename_all = "snake_case")] -pub enum A2aPeerAuth { - Jwt, - Mtls, -} - -/// One `[a2a.peers.]` grant row. -#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +/// Explicit pinned identity and local recipient grant. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] pub struct A2aPeer { - /// JWT `sub` or SPIFFE SAN. - pub subject: String, - /// JWT `iss` or SPIFFE trust-domain prefix. - pub issuer: String, - /// Stamped onto `from.instance`. - pub peer_instance: String, - /// Stamped onto `from.owner` at use. `None` means the subject. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub remote_owner: Option, - /// Outbound POST URL. - pub endpoint: String, - /// Outbound identity name in `[a2a.credentials.*]`. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub credential: Option, - /// Outbound TLS server name. Optional when the SAN equals `subject`. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub tls_server_name: Option, - /// Local owner this peer may message (`to.owner`). - pub local_owner: String, - /// Allowed session ids, or `["*"]`. + pub spiffe_id: String, + pub fingerprints: Vec, + pub address: String, + pub owner: String, #[serde(default = "default_star_list")] pub sessions: Vec, - /// Allowed agent names, or `["*"]`. #[serde(default = "default_star_list")] pub agents: Vec, - /// Inbound key-possession method. - pub auth: A2aPeerAuth, - /// Ed25519 public key PEM. Required when `auth = "jwt"`. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub jwt_public_key_path: Option, - /// Outbound CA for this peer's server cert. Unset uses system roots. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub tls_ca_path: Option, } - fn default_star_list() -> Vec { vec!["*".into()] } - -/// One `[a2a.credentials.]` outbound identity. -#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)] -pub struct A2aCredential { - /// Ed25519 signing key we use to self-issue peer JWTs. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub jwt_signing_key_path: Option, - /// Optional client certificate for mTLS. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub client_cert_path: Option, - /// Optional client key for mTLS. Mode 0600 at use. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub client_key_path: Option, +fn default_a2a_trust_domain() -> String { + "prx.local".into() } pub(super) fn default_a2a_bind() -> String { @@ -472,94 +413,20 @@ impl Default for A2aConfig { trusted_trust_domains: Vec::new(), spiffe_trust_bundle_pem: None, spiffe_strict_validation: false, - tls_cert_path: None, - tls_key_path: None, - client_ca_path: None, messaging_enabled: false, - remote_tree: RemoteTreeLimits::default(), peers: HashMap::new(), - credentials: HashMap::new(), + trust_domain: default_a2a_trust_domain(), } } } impl A2aConfig { - /// Parse-time checks. TLS files are read at use, not here. pub fn validate(&self) -> anyhow::Result<()> { anyhow::ensure!(!self.bind.trim().is_empty(), "a2a.bind must not be empty"); - if self.messaging_enabled && !a2a_bind_is_loopback(&self.bind) { - let cert = self - .tls_cert_path - .as_deref() - .map(str::trim) - .filter(|path| !path.is_empty()); - let key = self - .tls_key_path - .as_deref() - .map(str::trim) - .filter(|path| !path.is_empty()); - anyhow::ensure!( - cert.is_some() && key.is_some(), - "a2a.bind '{}' is not loopback; a2a.tls_cert_path and a2a.tls_key_path are required", - self.bind - ); - } - for (name, peer) in &self.peers { - anyhow::ensure!( - !peer.subject.trim().is_empty(), - "a2a.peers.{name}.subject must not be empty" - ); - anyhow::ensure!( - !peer.issuer.trim().is_empty(), - "a2a.peers.{name}.issuer must not be empty" - ); - anyhow::ensure!( - !peer.peer_instance.trim().is_empty(), - "a2a.peers.{name}.peer_instance must not be empty" - ); - anyhow::ensure!( - !peer.endpoint.trim().is_empty(), - "a2a.peers.{name}.endpoint must not be empty" - ); - anyhow::ensure!( - !peer.local_owner.trim().is_empty(), - "a2a.peers.{name}.local_owner must not be empty" - ); - if peer.auth == A2aPeerAuth::Jwt { - anyhow::ensure!( - peer.jwt_public_key_path - .as_deref() - .map(str::trim) - .is_some_and(|path| !path.is_empty()), - "a2a.peers.{name}.jwt_public_key_path is required when auth = jwt" - ); - } - if let Some(credential) = peer - .credential - .as_deref() - .map(str::trim) - .filter(|value| !value.is_empty()) - { - anyhow::ensure!( - self.credentials.contains_key(credential), - "a2a.peers.{name}.credential '{credential}' is not in [a2a.credentials.*]" - ); - } - } - Ok(()) + crate::messaging::a2a::peers::validate(self) } } -fn a2a_bind_is_loopback(bind: &str) -> bool { - if let Ok(addr) = bind.parse::() { - return addr.ip().is_loopback(); - } - let host = bind - .rsplit_once(':') - .map_or(bind, |(host, _)| host.trim_matches(['[', ']'])); - host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "::1" -} - #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema)] #[serde(rename_all = "snake_case")] pub enum McpTransport { @@ -659,92 +526,11 @@ mod a2a_foundation_tests { let config = Config::default(); config.a2a.validate().expect("test: default a2a"); assert!(!config.a2a.messaging_enabled); - assert_eq!(config.a2a.remote_tree.max_spawned, 16); - assert_eq!(config.a2a.remote_tree.max_scheduled, 4); - assert_eq!(config.a2a.remote_tree.max_connections, 4); - assert_eq!(config.a2a.remote_tree.max_sends, 4); assert!(config.a2a.peers.is_empty()); } - #[test] - fn a2a_non_loopback_bind_without_tls_is_refused() { - let error = parse_a2a("[a2a]\nmessaging_enabled = true\nbind = \"0.0.0.0:16832\"\n").expect_err("test: refuse"); - assert!(error.to_string().contains("tls_cert_path"), "{error}"); - } - #[test] fn a2a_disabled_messaging_keeps_advertised_non_loopback_bind() { parse_a2a("[a2a]\nbind = \"0.0.0.0:16832\"\n").expect("advertised address needs no listener TLS"); } - - #[test] - fn a2a_jwt_peer_requires_public_key_path() { - let error = parse_a2a( - r#" -[a2a.peers.rf] -subject = "spiffe://prx/rf" -issuer = "spiffe://prx" -peer_instance = "rf" -endpoint = "https://192.0.2.10:16832" -local_owner = "owner-a" -auth = "jwt" -"#, - ) - .expect_err("test: jwt key"); - assert!(error.to_string().contains("jwt_public_key_path"), "{error}"); - } - - #[test] - fn a2a_peer_credential_must_exist() { - let error = parse_a2a( - r#" -[a2a.peers.rf] -subject = "spiffe://prx/rf" -issuer = "spiffe://prx" -peer_instance = "rf" -endpoint = "https://192.0.2.10:16832" -local_owner = "owner-a" -auth = "mtls" -credential = "missing" -"#, - ) - .expect_err("test: missing cred"); - assert!(error.to_string().contains("credentials"), "{error}"); - } - - #[test] - fn a2a_peer_and_limits_round_trip() { - let a2a = parse_a2a( - r#" -[a2a] -messaging_enabled = false -tls_cert_path = "a2a/server.crt" -tls_key_path = "a2a/server.key" - -[a2a.remote_tree] -max_spawned = 8 - -[a2a.credentials.self] -jwt_signing_key_path = "a2a/self.ed25519.pem" - -[a2a.peers.rf] -subject = "spiffe://prx/rf" -issuer = "spiffe://prx" -peer_instance = "rf" -endpoint = "https://192.0.2.10:16832" -local_owner = "owner-a" -auth = "jwt" -jwt_public_key_path = "a2a/peers/rf.pub.pem" -credential = "self" -"#, - ) - .expect("test: parse"); - assert_eq!(a2a.remote_tree.max_spawned, 8); - assert_eq!(a2a.remote_tree.max_sends, 4); - let peer = a2a.peers.get("rf").expect("test: peer"); - assert_eq!(peer.auth, A2aPeerAuth::Jwt); - assert_eq!(peer.credential.as_deref(), Some("self")); - assert_eq!(peer.sessions, vec!["*".to_string()]); - assert!(peer.remote_owner.is_none()); - } } diff --git a/src/config/schema/providers.rs b/src/config/schema/providers.rs index d5510c69c..869167218 100644 --- a/src/config/schema/providers.rs +++ b/src/config/schema/providers.rs @@ -1,5 +1,17 @@ use super::{Deserialize, JsonSchema, Serialize}; +/// Owner-controlled inbound session messaging (enabled unless explicitly off). +#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema)] +pub struct AgentMessaging { + #[serde(default = "super::default_true")] + pub inbound: bool, +} +impl Default for AgentMessaging { + fn default() -> Self { + Self { inbound: true } + } +} + // ── Delegate Agents ────────────────────────────────────────────── /// Optional admission limits for rf-started turns of a named agent. @@ -30,6 +42,8 @@ impl AgentLimits { /// Configuration for a delegate sub-agent used by the `delegate` tool. #[derive(Clone, Serialize, Deserialize, JsonSchema)] pub struct DelegateAgentConfig { + #[serde(default)] + pub messaging: AgentMessaging, /// rf approve-and-continue wait; Console approvals retain their own expiry. #[serde( default = "super::default_approval_wait_secs", @@ -92,6 +106,7 @@ impl DelegateAgentConfig { #[must_use] pub const fn on(provider: String, model: String) -> Self { Self { + messaging: AgentMessaging { inbound: true }, approval_wait_secs: super::default_approval_wait_secs(), provider, model, diff --git a/src/config/schema/tests/mod.rs b/src/config/schema/tests/mod.rs index ec006a804..8db313d23 100644 --- a/src/config/schema/tests/mod.rs +++ b/src/config/schema/tests/mod.rs @@ -41,6 +41,7 @@ fn test_remove_env(key: impl AsRef) { fn agentic_delegate_config(allowed_tools: Vec) -> DelegateAgentConfig { DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), approval_wait_secs: 600, limits: crate::config::AgentLimits::default(), provider: "openrouter".into(), diff --git a/src/config/schema/tests/persistence.rs b/src/config/schema/tests/persistence.rs index d61b31fa9..656d6f73d 100644 --- a/src/config/schema/tests/persistence.rs +++ b/src/config/schema/tests/persistence.rs @@ -362,6 +362,7 @@ async fn config_split_and_reload_roundtrip_matches_original() { config.agents.insert( "worker".into(), DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), approval_wait_secs: 600, limits: crate::config::AgentLimits::default(), provider: "openrouter".into(), @@ -452,6 +453,7 @@ async fn config_save_encrypts_nested_credentials() { config.agents.insert( "worker".into(), DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), approval_wait_secs: 600, limits: crate::config::AgentLimits::default(), provider: "openrouter".into(), diff --git a/src/config/secret_paths.rs b/src/config/secret_paths.rs index 35a3eec75..3a53426fe 100644 --- a/src/config/secret_paths.rs +++ b/src/config/secret_paths.rs @@ -615,8 +615,8 @@ pub static ENDPOINT_PATHS: &[EndpointPath] = &[ userinfo("mcp_server.jwt_jwks_uri", &[Key("mcp_server"), Key("jwt_jwks_uri")]), userinfo("a2a.card_jwks_uri", &[Key("a2a"), Key("card_jwks_uri")]), recipient_url( - "a2a.peers.<*>.endpoint", - &[Key("a2a"), Key("peers"), AnyKey, Key("endpoint")], + "a2a.peers.<*>.address", + &[Key("a2a"), Key("peers"), AnyKey, Key("address")], ), // The decision endpoint (CDP-03, CDP-04): validation refuses userinfo // there, and this keeps every read surface safe for a hand-edited file. @@ -714,6 +714,26 @@ pub static ACCESS_CONTROL_PATHS: &[AccessControlPath] = &[ &[Key("mcp_server"), Key("allowed_origins")], "declared browser-origin allow-list of the MCP endpoint (not read yet)", ), + access( + "a2a.peers", + &[Key("a2a"), Key("peers")], + "messaging/a2a pinned peer recipient grants", + ), + access( + "a2a.messaging_enabled", + &[Key("a2a"), Key("messaging_enabled")], + "messaging/a2a listener activation", + ), + access( + "agent.messaging.inbound", + &[Key("agent"), Key("messaging"), Key("inbound")], + "messaging receiver admission", + ), + access( + "agents.<*>.messaging.inbound", + &[Key("agents"), AnyKey, Key("messaging"), Key("inbound")], + "named receiver admission", + ), // ── A2A peers ─────────────────────────────────────────────────── access( "a2a.allowed_peer_issuers", @@ -1853,2109 +1873,5 @@ endpoint = "https://decider:userinfo-sentinel-engine@127.0.0.1:28/v1" #[cfg(test)] #[allow(clippy::indexing_slicing)] -mod tests { - use super::*; - use std::collections::BTreeSet; - - #[test] - fn one_scrubber_masks_by_value_and_by_shape_with_or_without_a_scan() { - let message = "bad key sk-proj-abcdefghijklmnop12345 near sentinel-route"; - let tree: toml::Value = toml::from_str( - "[[model_routes]]\nhint = \"fast\"\nprovider = \"p\"\nmodel = \"m\"\napi_key = \"sentinel-route\"\n", - ) - .expect("test: parse"); - let found = scan(&tree); - let with_scan = scrub_message(Some(&found), message); - assert!(!with_scan.contains("sk-proj-abcdefghijklmnop12345"), "{with_scan}"); - assert!(!with_scan.contains("sentinel-route"), "{with_scan}"); - let without_scan = scrub_message(None, message); - assert!( - !without_scan.contains("sk-proj-abcdefghijklmnop12345"), - "{without_scan}" - ); - assert_eq!(found.scrub(message), with_scan); - } - - fn fixture_tree() -> toml::Value { - toml::from_str(fixture::TOML).expect("test: fixture parses") - } - - fn sentinel_paths() -> BTreeSet> { - fixture::string_leaves(&fixture_tree(), &|value| value.contains(fixture::SENTINEL_PREFIX)) - } - - /// Resolve `$ref` and `anyOf`/`oneOf`/`allOf` alternatives of a schema node. - fn alternatives<'a>(root: &'a serde_json::Value, node: &'a serde_json::Value) -> Vec<&'a serde_json::Value> { - if let Some(reference) = node.get("$ref").and_then(serde_json::Value::as_str) { - let name = reference.rsplit('/').next().unwrap_or_default(); - return root - .get("$defs") - .and_then(|defs| defs.get(name)) - .map(|target| alternatives(root, target)) - .unwrap_or_default(); - } - let mut found = vec![node]; - for combinator in ["anyOf", "oneOf", "allOf"] { - if let Some(options) = node.get(combinator).and_then(serde_json::Value::as_array) { - for option in options { - found.extend(alternatives(root, option)); - } - } - } - found - } - - fn step<'a>( - root: &'a serde_json::Value, - node: &'a serde_json::Value, - segment: Segment, - ) -> Option<&'a serde_json::Value> { - alternatives(root, node) - .into_iter() - .find_map(|candidate| match segment { - Segment::Key(key) => candidate.get("properties").and_then(|properties| properties.get(key)), - Segment::AnyKey => candidate - .get("additionalProperties") - .filter(|schema| schema.is_object()), - Segment::AnyIndex => candidate.get("items"), - }) - } - - fn admits_string(root: &serde_json::Value, node: &serde_json::Value) -> bool { - alternatives(root, node) - .into_iter() - .any(|candidate| match candidate.get("type") { - Some(serde_json::Value::String(kind)) => kind == "string", - Some(serde_json::Value::Array(kinds)) => kinds.iter().any(|kind| kind == "string"), - _ => false, - }) - } - - /// Every registered pattern names a real string slot of `Config`. A typo - /// in the registry would otherwise silently protect nothing. - #[test] - fn every_registered_path_names_a_string_slot_of_the_config_schema() { - let root = serde_json::to_value(schemars::schema_for!(crate::config::Config)).expect("test: schema serializes"); - // The JSON schema lists canonical names only; aliases have their - // own guard below. - for secret in SECRET_PATHS.iter().filter(|secret| secret.alias_of.is_none()) { - let leaf = secret - .segments - .iter() - .try_fold(&root, |node, segment| step(&root, node, *segment)); - let leaf = leaf.unwrap_or_else(|| panic!("registered path {} is not in the Config schema", secret.pattern)); - assert!( - admits_string(&root, leaf), - "registered path {} does not hold a string", - secret.pattern - ); - } - } - - /// The fixture really covers the registry: each registered pattern has at - /// least one sentinel instance, and every sentinel sits at a secret path. - #[test] - fn fixture_holds_a_sentinel_at_every_registered_path() { - let sentinels = sentinel_paths(); - // One fixture cannot hold a field and its alias at once. - for secret in SECRET_PATHS.iter().filter(|secret| secret.alias_of.is_none()) { - assert!( - sentinels.iter().any(|path| pattern_matches(secret.segments, path)), - "the fixture has no sentinel at {}", - secret.pattern - ); - } - for path in &sentinels { - assert!( - registered(path).is_some(), - "sentinel at {} is not registered", - display_path(path) - ); - } - } - - /// Guard: the registry's encrypted set is exactly what `Config::save` - /// encrypts, through the real save path on a temp config dir. - #[tokio::test] - async fn registry_encrypted_set_is_exactly_what_save_encrypts() { - let dir = tempfile::TempDir::new().expect("test: temp config dir"); - let config = fixture::config_in(dir.path()); - config.save().await.expect("test: save fixture"); - - let stored: toml::Value = - toml::from_str(&std::fs::read_to_string(&config.config_path).expect("test: read stored config")) - .expect("test: stored config parses"); - let store = crate::security::SecretStore::new(dir.path(), true); - - let encrypted_on_disk = fixture::string_leaves(&stored, &crate::security::SecretStore::is_encrypted); - let expected_encrypted: BTreeSet> = sentinel_paths() - .into_iter() - .filter(|path| registered(path).is_some_and(|secret| secret.handling == SecretHandling::EncryptedAtRest)) - .collect(); - assert_eq!( - encrypted_on_disk - .iter() - .map(|path| display_path(path)) - .collect::>(), - expected_encrypted - .iter() - .map(|path| display_path(path)) - .collect::>(), - "save must encrypt exactly the registered encrypted-at-rest paths" - ); - - let fixture = fixture_tree(); - for path in &expected_encrypted { - let stored_value = lookup(&stored, path).expect("test: encrypted path stored"); - let plaintext = lookup(&fixture, path).expect("test: fixture value"); - assert_eq!( - store.decrypt(stored_value).expect("test: decrypt stored value"), - plaintext, - "{} must decrypt to what was saved", - display_path(path) - ); - } - } - - fn lookup<'a>(root: &'a toml::Value, path: &[PathElem]) -> Option<&'a str> { - path.iter() - .try_fold(root, |node, elem| match elem { - PathElem::Key(key) => node.get(key.as_str()), - PathElem::Index(index) => node.get(*index), - }) - .and_then(toml::Value::as_str) - } - - /// `prx config show` renders the stored form with every registered path - /// masked and no sentinel left. - #[test] - fn config_show_rendering_masks_every_registered_path() { - let dir = tempfile::TempDir::new().expect("test: temp config dir"); - let config = fixture::config_in(dir.path()); - let rendered = redacted_stored_toml(&config).expect("test: render"); - let text = toml::to_string_pretty(&rendered).expect("test: serialize rendering"); - assert!( - !text.contains(fixture::SENTINEL_PREFIX), - "config show leaked a sentinel:\n{text}" - ); - - let masked = fixture::masked_paths(&rendered); - for path in sentinel_paths() { - assert!( - masked.contains(&display_path(&path)), - "{} is not masked by config show", - display_path(&path) - ); - } - } - - // ── SECRETS-OTHER: every registered secret is encrypted at rest ────── - - /// RED before SECRETS-OTHER: with `secrets.encrypt = true`, channel and - /// bot tokens, paired tokens, MCP environment values, webhook, tunnel, - /// daemon and node credentials were stored as plaintext. After: every - /// sentinel of the fixture is `enc2:` on disk, and the load restores it. - #[tokio::test] - async fn save_encrypts_every_registered_secret_and_load_restores_it() { - let dir = tempfile::TempDir::new().expect("test: temp config dir"); - let config = fixture::config_in(dir.path()); - config.save().await.expect("test: save fixture"); - let (raw, stored) = stored_tree(&config); - assert!( - !raw.contains(fixture::SENTINEL_PREFIX), - "a secret is stored as plaintext:\n{raw}" - ); - for path in sentinel_paths() { - let value = lookup(&stored, &path).unwrap_or_else(|| panic!("{} is not stored", display_path(&path))); - assert!( - crate::security::SecretStore::is_secure_encrypted(value), - "{} is not enc2: on disk", - display_path(&path) - ); - } - - let loaded = crate::config::Config::load_from_path(&config.config_path, config.workspace_dir.clone()) - .expect("test: load saved fixture"); - let loaded = toml::Value::try_from(&loaded).expect("test: render loaded"); - let fixture = fixture_tree(); - for path in sentinel_paths() { - assert_eq!( - lookup(&loaded, &path), - lookup(&fixture, &path), - "{} must load back as written", - display_path(&path) - ); - } - } - - /// Migration (D-018 Q4, no forced migration): a file an older release - /// wrote holds channel tokens, paired tokens and MCP environment values - /// as plaintext. They load as they are and are encrypted on the next - /// save; the values survive every step. - #[tokio::test] - async fn plaintext_channel_and_gateway_secrets_from_an_older_release_are_encrypted_on_next_save() { - let dir = tempfile::TempDir::new().expect("test: temp config dir"); - let config_path = dir.path().join("config.toml"); - std::fs::write( - &config_path, - "default_temperature = 0.7\n\n[gateway]\npaired_tokens = [\"sentinel-old-paired\"]\n\n\ - [channels_config]\ncli = true\n\n[channels_config.telegram]\nbot_token = \"sentinel-old-telegram\"\nallowed_users = []\n\n\ - [mcp.servers.local]\ncommand = \"mcp-local\"\nenv = { GITHUB_PAT = \"sentinel-old-mcp\" }\n", - ) - .expect("test: write legacy config"); - - let check = |config: &crate::config::Config| { - assert_eq!(config.gateway.paired_tokens, vec!["sentinel-old-paired".to_string()]); - assert_eq!( - config - .channels_config - .telegram - .as_ref() - .map(|telegram| telegram.bot_token.as_str()), - Some("sentinel-old-telegram") - ); - assert_eq!( - config - .mcp - .servers - .get("local") - .and_then(|server| server.env.get("GITHUB_PAT")) - .map(String::as_str), - Some("sentinel-old-mcp") - ); - }; - let loaded = crate::config::Config::load_from_path(&config_path, dir.path().join("workspace")) - .unwrap_or_else(|error| panic!("test: a plaintext legacy file must still load: {error:#}")); - check(&loaded); - loaded.save().await.expect("test: next save"); - let (raw, _) = stored_tree(&loaded); - assert!( - !raw.contains(fixture::SENTINEL_PREFIX), - "a secret survived the next save as plaintext:\n{raw}" - ); - let reloaded = crate::config::Config::load_from_path(&config_path, dir.path().join("workspace")) - .expect("test: reload re-encrypted config"); - check(&reloaded); - } - - /// Guard (downgrade path, D-018 Q4): `secrets.encrypt = false` stores - /// every registered secret as plaintext, so an older release can read - /// the file again. - #[tokio::test] - async fn disabled_encryption_keeps_every_registered_secret_plaintext() { - let dir = tempfile::TempDir::new().expect("test: temp config dir"); - let mut config = fixture::config_in(dir.path()); - config.secrets.encrypt = false; - config.save().await.expect("test: save fixture"); - let (_, stored) = stored_tree(&config); - assert!(fixture::string_leaves(&stored, &crate::security::SecretStore::is_encrypted).is_empty()); - let fixture = fixture_tree(); - for path in sentinel_paths() { - assert_eq!( - lookup(&stored, &path), - lookup(&fixture, &path), - "{}", - display_path(&path) - ); - } - } - - // ── A-2: every provider credential slot is encrypted at rest ────────── - - const ROUTE_SECRET: &str = "sentinel-route-secret"; - const EMBEDDING_SECRET: &str = "sentinel-embedding-secret"; - const ROTATION_SECRETS: [&str; 2] = ["sentinel-rotation-a", "sentinel-rotation-b"]; - - fn provider_slots_config(dir: &std::path::Path, route_provider: &str) -> crate::config::Config { - let mut config = crate::config::Config::default(); - config.config_path = dir.join("config.toml"); - config.workspace_dir = dir.join("workspace"); - config.model_routes = vec![crate::config::ModelRouteConfig { - settings: Default::default(), - hint: "fast".into(), - provider: route_provider.into(), - model: "route-model".into(), - api_key: Some(ROUTE_SECRET.into()), - credential_ref: None, - }]; - config.embedding_routes = vec![crate::config::EmbeddingRouteConfig { - hint: "semantic".into(), - provider: "openai".into(), - model: "text-embedding-3-small".into(), - dimensions: None, - api_key: Some(EMBEDDING_SECRET.into()), - credential_ref: None, - }]; - config.reliability.api_keys = ROTATION_SECRETS.iter().map(|key| (*key).to_string()).collect(); - config - } - - fn stored_tree(config: &crate::config::Config) -> (String, toml::Value) { - let raw = std::fs::read_to_string(&config.config_path).expect("test: read stored config"); - let tree = toml::from_str(&raw).expect("test: stored config parses"); - (raw, tree) - } - - fn stored_provider_slots(tree: &toml::Value) -> Vec { - let mut slots = Vec::new(); - for (section, key) in [("model_routes", "api_key"), ("embedding_routes", "api_key")] { - if let Some(routes) = tree.get(section).and_then(toml::Value::as_array) { - slots.extend( - routes - .iter() - .filter_map(|route| route.get(key).and_then(toml::Value::as_str).map(str::to_string)), - ); - } - } - if let Some(keys) = tree - .get("reliability") - .and_then(|reliability| reliability.get("api_keys")) - .and_then(toml::Value::as_array) - { - slots.extend(keys.iter().filter_map(toml::Value::as_str).map(str::to_string)); - } - slots - } - - /// RED before A-2: `Config::save` wrote route, embedding-route and - /// rotation keys to disk as plaintext on every write path. - #[tokio::test] - async fn save_encrypts_route_embedding_and_rotation_keys() { - let dir = tempfile::TempDir::new().expect("test: temp config dir"); - let config = provider_slots_config(dir.path(), "openrouter"); - config.save().await.expect("test: save"); - - let (raw, tree) = stored_tree(&config); - for secret in [ROUTE_SECRET, EMBEDDING_SECRET, ROTATION_SECRETS[0], ROTATION_SECRETS[1]] { - assert!(!raw.contains(secret), "{secret} is stored as plaintext:\n{raw}"); - } - let stored = stored_provider_slots(&tree); - assert_eq!(stored.len(), 4, "every slot must still be stored: {stored:?}"); - assert!( - stored - .iter() - .all(|value| crate::security::SecretStore::is_secure_encrypted(value)), - "every provider slot must be enc2: {stored:?}" - ); - - let loaded = crate::config::Config::load_from_path(&config.config_path, config.workspace_dir.clone()) - .expect("test: load saved config"); - assert_eq!(loaded.model_routes[0].api_key.as_deref(), Some(ROUTE_SECRET)); - assert_eq!(loaded.embedding_routes[0].api_key.as_deref(), Some(EMBEDDING_SECRET)); - assert_eq!(loaded.reliability.api_keys, ROTATION_SECRETS.to_vec()); - } - - /// Migration (D-018 Q4): a file an older release wrote holds these keys - /// as plaintext. The new binary reads them as they are and encrypts them - /// on the next save; the values survive every step. - #[tokio::test] - async fn plaintext_provider_slots_from_an_older_release_load_and_are_encrypted_on_next_save() { - let dir = tempfile::TempDir::new().expect("test: temp config dir"); - let config_path = dir.path().join("config.toml"); - let legacy = format!( - "default_temperature = 0.7\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"openrouter\"\nmodel = \"route-model\"\napi_key = \"{ROUTE_SECRET}\"\n\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\napi_key = \"{EMBEDDING_SECRET}\"\n\n[reliability]\napi_keys = [\"{}\", \"{}\"]\n", - ROTATION_SECRETS[0], ROTATION_SECRETS[1] - ); - std::fs::write(&config_path, legacy).expect("test: write legacy config"); - - let loaded = crate::config::Config::load_from_path(&config_path, dir.path().join("workspace")) - .expect("test: a plaintext legacy file must still load"); - assert_eq!(loaded.model_routes[0].api_key.as_deref(), Some(ROUTE_SECRET)); - assert_eq!(loaded.embedding_routes[0].api_key.as_deref(), Some(EMBEDDING_SECRET)); - assert_eq!(loaded.reliability.api_keys, ROTATION_SECRETS.to_vec()); - - loaded.save().await.expect("test: next save"); - let (raw, tree) = stored_tree(&loaded); - for secret in [ROUTE_SECRET, EMBEDDING_SECRET, ROTATION_SECRETS[0], ROTATION_SECRETS[1]] { - assert!(!raw.contains(secret), "{secret} survived the next save as plaintext"); - } - assert!( - stored_provider_slots(&tree) - .iter() - .all(|value| crate::security::SecretStore::is_secure_encrypted(value)) - ); - - let reloaded = crate::config::Config::load_from_path(&config_path, dir.path().join("workspace")) - .expect("test: reload re-encrypted config"); - assert_eq!(reloaded.model_routes[0].api_key.as_deref(), Some(ROUTE_SECRET)); - assert_eq!(reloaded.embedding_routes[0].api_key.as_deref(), Some(EMBEDDING_SECRET)); - assert_eq!(reloaded.reliability.api_keys, ROTATION_SECRETS.to_vec()); - } - - /// `secrets.encrypt = false` keeps every slot as plaintext, as before. - #[tokio::test] - async fn disabled_encryption_keeps_provider_slots_plaintext() { - let dir = tempfile::TempDir::new().expect("test: temp config dir"); - let mut config = provider_slots_config(dir.path(), "openrouter"); - config.secrets.encrypt = false; - config.save().await.expect("test: save"); - let (_, tree) = stored_tree(&config); - assert_eq!( - stored_provider_slots(&tree), - vec![ - ROUTE_SECRET.to_string(), - EMBEDDING_SECRET.to_string(), - ROTATION_SECRETS[0].to_string(), - ROTATION_SECRETS[1].to_string() - ] - ); - } - - /// A legacy XOR `enc:` route key is decrypted on load and upgraded to - /// `enc2:` by the startup migration, like the other encrypted slots. - /// RED before A-2: the route key was neither decrypted nor migrated, so - /// the literal `enc:` string was the route's bearer credential. - #[tokio::test] - async fn legacy_xor_route_key_is_decrypted_and_migrated() { - let dir = tempfile::TempDir::new().expect("test: temp config dir"); - let store = crate::security::SecretStore::new(dir.path(), true); - let legacy_value = legacy_xor(dir.path(), ROUTE_SECRET); - let config_path = dir.path().join("config.toml"); - std::fs::write( - &config_path, - format!( - "default_temperature = 0.7\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"openrouter\"\nmodel = \"route-model\"\napi_key = \"{legacy_value}\"\n" - ), - ) - .expect("test: write legacy config"); - - let loaded = crate::config::Config::load_from_path(&config_path, dir.path().join("workspace")) - .expect("test: load legacy route key"); - assert_eq!(loaded.model_routes[0].api_key.as_deref(), Some(ROUTE_SECRET)); - - crate::config::schema::migrate_config_legacy_secrets(&loaded) - .await - .expect("test: legacy migration"); - let (_, tree) = stored_tree(&loaded); - let stored = stored_provider_slots(&tree); - assert_eq!(stored.len(), 1); - assert!( - crate::security::SecretStore::is_secure_encrypted(&stored[0]), - "{stored:?}" - ); - assert_eq!(store.decrypt(&stored[0]).expect("test: decrypt migrated"), ROUTE_SECRET); - } - - /// RED before PMMH-f (D-101 F-5): with `secrets.encrypt = false` the - /// startup upgrade rewrote a legacy `enc:` value as plaintext. It is - /// left as it is now (it keeps loading). - #[tokio::test] - async fn a_legacy_value_is_never_rewritten_as_plaintext() { - let dir = tempfile::TempDir::new().expect("test: temp config dir"); - let legacy_value = legacy_xor(dir.path(), ROUTE_SECRET); - let config_path = dir.path().join("config.toml"); - std::fs::write( - &config_path, - format!( - "default_temperature = 0.7\n\n[secrets]\nencrypt = false\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"openrouter\"\nmodel = \"route-model\"\napi_key = \"{legacy_value}\"\n" - ), - ) - .expect("test: write legacy config"); - let before = std::fs::read(&config_path).expect("test: read"); - - let loaded = crate::config::Config::load_from_path(&config_path, dir.path().join("workspace")) - .expect("test: load legacy route key"); - crate::config::schema::migrate_config_legacy_secrets(&loaded) - .await - .expect("test: legacy migration"); - - let after = std::fs::read(&config_path).expect("test: read"); - assert!( - !String::from_utf8_lossy(&after).contains(ROUTE_SECRET), - "the legacy value was rewritten as plaintext" - ); - assert_eq!(after, before); - assert_eq!( - loaded.model_routes.first().and_then(|route| route.api_key.as_deref()), - Some(ROUTE_SECRET) - ); - } - - /// A loopback OpenAI-compatible endpoint that answers every chat request - /// with "ok" and reports each request's `Authorization` header. - async fn spawn_authorization_recorder() -> ( - std::net::SocketAddr, - tokio::sync::mpsc::UnboundedReceiver>, - tokio::task::JoinHandle<()>, - ) { - use tokio::io::{AsyncReadExt, AsyncWriteExt}; - - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("test: bind loopback"); - let addr = listener.local_addr().expect("test: loopback addr"); - let (seen_tx, seen_rx) = tokio::sync::mpsc::unbounded_channel::>(); - let server = tokio::spawn(async move { - while let Ok((mut socket, _)) = listener.accept().await { - let mut buffer = Vec::new(); - let mut chunk = [0_u8; 4096]; - let head_end = loop { - match socket.read(&mut chunk).await { - Ok(0) | Err(_) => break None, - Ok(read) => buffer.extend_from_slice(&chunk[..read]), - } - if let Some(position) = buffer.windows(4).position(|window| window == b"\r\n\r\n") { - break Some(position + 4); - } - }; - let Some(head_end) = head_end else { continue }; - let head = String::from_utf8_lossy(&buffer[..head_end]).to_string(); - let authorization = head.split("\r\n").find_map(|line| { - line.split_once(':') - .filter(|(name, _)| name.trim().eq_ignore_ascii_case("authorization")) - .map(|(_, value)| value.trim().to_string()) - }); - let content_length = head - .split("\r\n") - .find_map(|line| { - line.split_once(':') - .filter(|(name, _)| name.trim().eq_ignore_ascii_case("content-length")) - .and_then(|(_, value)| value.trim().parse::().ok()) - }) - .unwrap_or(0); - let mut body_read = buffer.len() - head_end; - while body_read < content_length { - match socket.read(&mut chunk).await { - Ok(0) | Err(_) => break, - Ok(read) => body_read += read, - } - } - let _ = seen_tx.send(authorization); - let body = r#"{"id":"c","object":"chat.completion","created":1,"model":"route-model","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}]}"#; - let response = format!( - "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", - body.len() - ); - let _ = socket.write_all(response.as_bytes()).await; - } - }); - - (addr, seen_rx, server) - } - - fn isolated_provider_options(dir: &std::path::Path) -> crate::providers::ProviderRuntimeOptions { - crate::providers::ProviderRuntimeOptions { - openprx_dir: Some(dir.to_path_buf()), - codex_auth_json_path: Some(dir.join("absent-codex-auth.json")), - codex_auth_json_auto_import: false, - ..crate::providers::ProviderRuntimeOptions::default() - } - } - - /// The legacy XOR `enc:` form of `plaintext` under the key in `dir`. - fn legacy_xor(dir: &std::path::Path, plaintext: &str) -> String { - let store = crate::security::SecretStore::new(dir, true); - store.encrypt("prime-the-key").expect("test: create key file"); - let key_hex = std::fs::read_to_string(dir.join(".secret_key")).expect("test: key file"); - let key_hex = key_hex.trim(); - let key = (0..key_hex.len()) - .step_by(2) - .map(|index| u8::from_str_radix(&key_hex[index..index + 2], 16).expect("test: key hex")) - .collect::>(); - format!( - "enc:{}", - plaintext - .bytes() - .enumerate() - .map(|(index, byte)| format!("{:02x}", byte ^ key[index % key.len()])) - .collect::() - ) - } - - /// F10: on the default split layout the route keys live in - /// `config.d/routing.toml`. A legacy `enc:` route key there is decrypted - /// on load (the merged tree is decrypted, fragments included), the routed - /// provider receives the real key, and the next structured save rewrites - /// the fragment as `enc2:`. The startup migration still rewrites - /// `config.toml` only. - #[tokio::test] - async fn legacy_route_key_in_a_fragment_reaches_the_provider_and_is_upgraded_on_next_save() { - let (addr, mut seen_rx, server) = spawn_authorization_recorder().await; - let dir = tempfile::TempDir::new().expect("test: temp config dir"); - let route_provider = format!("custom:http://{addr}/v1"); - let mut config = provider_slots_config(dir.path(), &route_provider); - config.reliability.api_keys = Vec::new(); - config.embedding_routes = Vec::new(); - crate::config::files::write_split_config(&config, false) - .await - .expect("test: write split layout"); - let fragment = crate::config::files::config_dir_path(&config.config_path).join("routing.toml"); - let stored = std::fs::read_to_string(&fragment).expect("test: routing fragment"); - assert!( - !std::fs::read_to_string(&config.config_path) - .expect("test: main") - .contains("model_routes") - ); - - // Replace the encrypted route key with its legacy XOR form. - let mut tree: toml::Value = toml::from_str(&stored).expect("test: fragment parses"); - let slot = tree - .get_mut("model_routes") - .and_then(|routes| routes.get_mut(0)) - .and_then(|route| route.get_mut("api_key")) - .expect("test: route key in the fragment"); - *slot = toml::Value::String(legacy_xor(dir.path(), ROUTE_SECRET)); - std::fs::write(&fragment, toml::to_string_pretty(&tree).expect("test: render")).expect("test: write fragment"); - - let loaded = crate::config::Config::load_from_path(&config.config_path, config.workspace_dir.clone()) - .expect("test: load split layout"); - assert_eq!( - loaded.model_routes.first().and_then(|r| r.api_key.as_deref()), - Some(ROUTE_SECRET) - ); - - let mut runtime_config = loaded.clone(); - runtime_config.default_provider = Some(route_provider.clone()); - runtime_config.default_model = Some("route-model".to_string()); - runtime_config.reliability.provider_retries = 0; - runtime_config.reliability.fallback_providers = Vec::new(); - let provider = - crate::providers::create_provider_from_test_config(&runtime_config, &isolated_provider_options(dir.path())) - .expect("test: routed provider"); - let reply = provider.chat_with_system(None, "ping", "hint:fast", 0.0).await; - assert_eq!(reply.as_deref().ok(), Some("ok"), "unexpected reply: {reply:?}"); - assert_eq!( - seen_rx.recv().await.flatten().as_deref(), - Some(format!("Bearer {ROUTE_SECRET}").as_str()) - ); - - loaded.save().await.expect("test: next save"); - let upgraded = std::fs::read_to_string(&fragment).expect("test: fragment after save"); - let upgraded: toml::Value = toml::from_str(&upgraded).expect("test: parses"); - let key = upgraded - .get("model_routes") - .and_then(|routes| routes.get(0)) - .and_then(|route| route.get("api_key")) - .and_then(toml::Value::as_str) - .expect("test: route key after save"); - assert!( - crate::security::SecretStore::is_secure_encrypted(key), - "the next save must upgrade to enc2:" - ); - server.abort(); - } - - /// RED before PMM-H (PMMA F-10): the startup migration upgraded legacy - /// `enc:` values in `config.toml` only; one in a `config.d` fragment - /// stayed XOR-encrypted on disk until a later save. It is now upgraded - /// at startup, and every other file is left byte for byte. - #[tokio::test] - async fn legacy_route_key_in_a_fragment_is_upgraded_at_startup() { - let dir = tempfile::TempDir::new().expect("test: temp config dir"); - let mut config = provider_slots_config(dir.path(), "openrouter"); - config.reliability.api_keys = Vec::new(); - config.embedding_routes = Vec::new(); - crate::config::files::write_split_config(&config, false) - .await - .expect("test: write split layout"); - let fragment = crate::config::files::config_dir_path(&config.config_path).join("routing.toml"); - let stored = std::fs::read_to_string(&fragment).expect("test: routing fragment"); - let mut tree: toml::Value = toml::from_str(&stored).expect("test: fragment parses"); - let slot = tree - .get_mut("model_routes") - .and_then(|routes| routes.get_mut(0)) - .and_then(|route| route.get_mut("api_key")) - .expect("test: route key in the fragment"); - *slot = toml::Value::String(legacy_xor(dir.path(), ROUTE_SECRET)); - std::fs::write(&fragment, toml::to_string_pretty(&tree).expect("test: render")).expect("test: write fragment"); - let main_before = std::fs::read(&config.config_path).expect("test: main"); - - let loaded = crate::config::Config::load_from_path(&config.config_path, config.workspace_dir.clone()) - .expect("test: load split layout"); - crate::config::schema::migrate_config_legacy_secrets(&loaded) - .await - .expect("test: startup migration"); - - let upgraded: toml::Value = - toml::from_str(&std::fs::read_to_string(&fragment).expect("test: fragment")).expect("test: parses"); - let key = upgraded - .get("model_routes") - .and_then(|routes| routes.get(0)) - .and_then(|route| route.get("api_key")) - .and_then(toml::Value::as_str) - .expect("test: route key"); - assert!( - crate::security::SecretStore::is_secure_encrypted(key), - "the fragment still holds a legacy value: {key}" - ); - let store = crate::security::SecretStore::new(dir.path(), true); - assert_eq!(store.decrypt(key).expect("test: decrypt"), ROUTE_SECRET); - assert_eq!(std::fs::read(&config.config_path).expect("test: main"), main_before); - // Nothing left to migrate: a second run writes nothing. - let fragment_after = std::fs::read(&fragment).expect("test: fragment"); - crate::config::schema::migrate_config_legacy_secrets(&loaded) - .await - .expect("test: second run"); - assert_eq!(std::fs::read(&fragment).expect("test: fragment"), fragment_after); - } - - /// PMM-H: a route that names a credential reference instead of an - /// inline key sends the referenced key to its own provider, and a - /// reference issued for another provider is never sent. - #[tokio::test] - async fn a_route_credential_ref_reaches_its_owner_provider_only() { - let (addr, mut seen_rx, server) = spawn_authorization_recorder().await; - let dir = tempfile::TempDir::new().expect("test: temp config dir"); - let route_provider = format!("custom:http://{addr}/v1"); - let mut config = provider_slots_config(dir.path(), &route_provider); - config.reliability.api_keys = Vec::new(); - config.embedding_routes = Vec::new(); - let references = - crate::config::manage::credentials::CredentialReferences::for_config(&config).expect("test: references"); - references - .set(&route_provider, "route", ROUTE_SECRET) - .expect("test: reference for the route's provider"); - references - .set("anthropic", "other", "sentinel-other-provider-secret") - .expect("test: reference for another provider"); - config.model_routes = vec![ - crate::config::ModelRouteConfig { - settings: Default::default(), - hint: "fast".into(), - provider: route_provider.clone(), - model: "route-model".into(), - api_key: None, - credential_ref: Some("cred-route".into()), - }, - crate::config::ModelRouteConfig { - settings: Default::default(), - hint: "wrong".into(), - provider: route_provider.clone(), - model: "route-model".into(), - api_key: None, - credential_ref: Some("cred-other".into()), - }, - ]; - config.save().await.expect("test: save"); - let stored = std::fs::read_to_string(&config.config_path).expect("test: stored"); - assert!(stored.contains("credential_ref = \"cred-route\""), "{stored}"); - assert!(!stored.contains(ROUTE_SECRET), "{stored}"); - - let loaded = crate::config::Config::load_from_path(&config.config_path, config.workspace_dir.clone()) - .expect("test: load"); - let routes = loaded.model_routes_with_references(); - assert_eq!(routes[0].api_key.as_deref(), Some(ROUTE_SECRET)); - assert_eq!(routes[1].api_key, None, "another provider's reference was released"); - - let mut runtime_config = loaded.clone(); - runtime_config.default_provider = Some(route_provider.clone()); - runtime_config.default_model = Some("route-model".to_string()); - runtime_config.model_routes = routes.to_vec(); - runtime_config.reliability.provider_retries = 0; - runtime_config.reliability.fallback_providers = Vec::new(); - let provider = - crate::providers::create_provider_from_test_config(&runtime_config, &isolated_provider_options(dir.path())) - .expect("test: routed provider"); - let reply = provider.chat_with_system(None, "ping", "hint:fast", 0.0).await; - assert_eq!(reply.as_deref().ok(), Some("ok"), "unexpected reply: {reply:?}"); - assert_eq!( - seen_rx.recv().await.flatten().as_deref(), - Some(format!("Bearer {ROUTE_SECRET}").as_str()) - ); - server.abort(); - } - - /// The route credential reaches its provider as plaintext after the - /// encrypted round trip: loopback `Authorization` equals the sentinel. - #[tokio::test] - async fn routed_provider_built_from_the_loaded_config_presents_the_plaintext_route_key() { - let (addr, mut seen_rx, server) = spawn_authorization_recorder().await; - - let dir = tempfile::TempDir::new().expect("test: temp config dir"); - let route_provider = format!("custom:http://{addr}/v1"); - let mut config = provider_slots_config(dir.path(), &route_provider); - config.reliability.api_keys = Vec::new(); - config.save().await.expect("test: save"); - let (raw, _) = stored_tree(&config); - assert!(!raw.contains(ROUTE_SECRET), "the route key must be stored encrypted"); - - let loaded = crate::config::Config::load_from_path(&config.config_path, config.workspace_dir.clone()) - .expect("test: load"); - let mut runtime_config = loaded.clone(); - runtime_config.default_provider = Some(route_provider.clone()); - runtime_config.default_model = Some("route-model".to_string()); - runtime_config.reliability.provider_retries = 0; - runtime_config.reliability.fallback_providers = Vec::new(); - let options = isolated_provider_options(dir.path()); - let provider = crate::providers::create_provider_from_test_config(&runtime_config, &options) - .expect("test: routed provider"); - let reply = provider.chat_with_system(None, "ping", "hint:fast", 0.0).await; - assert_eq!(reply.as_deref().ok(), Some("ok"), "unexpected reply: {reply:?}"); - assert_eq!( - seen_rx.recv().await.flatten().as_deref(), - Some(format!("Bearer {ROUTE_SECRET}").as_str()) - ); - server.abort(); - } - - /// The scan names plaintext at every registered encrypted slot, the - /// elements of `reliability.api_keys` and `gateway.paired_tokens` - /// included, and never flags ciphertext. - #[test] - fn scan_finds_plaintext_at_encrypted_slots_and_masks_anywhere() { - let tree: toml::Value = toml::from_str( - r#" -api_key = "enc2:00" -[reliability] -api_keys = ["enc2:00", "sentinel-rotation"] -[[model_routes]] -hint = "fast" -provider = "p" -model = "m" -api_key = "sentinel-route" -[gateway] -paired_tokens = ["sentinel-paired"] -[channels_config.telegram] -bot_token = "***" -"#, - ) - .expect("test: parse"); - let mut found = scan(&tree); - found.plaintext_at_rest.sort(); - assert_eq!( - found.plaintext_at_rest, - vec![ - "gateway.paired_tokens[0]".to_string(), - "model_routes[0].api_key".to_string(), - "reliability.api_keys[1]".to_string() - ] - ); - assert_eq!(found.masked, vec!["channels_config.telegram.bot_token".to_string()]); - assert!(found.has_secret_values()); - assert_eq!(found.scrub("x sentinel-route y sentinel-paired"), "x *** y ***"); - } - - /// F1b, RED before PMMA-f: decryption ran on the stored tree before - /// serde mapped the alias, and the alias was not registered, so an - /// encrypted `db_url` written under an alias reached the storage backend - /// as the literal ciphertext. - #[test] - fn encrypted_db_url_under_every_alias_decrypts_on_load() { - for alias in ["db_url", "dbURL", "database_url", "databaseUrl"] { - let dir = tempfile::TempDir::new().expect("test: temp config dir"); - let store = crate::security::SecretStore::new(dir.path(), true); - let secret = "postgres://u:sentinel-db-alias@h/db"; - let encrypted = store.encrypt(secret).expect("test: encrypt"); - let config_path = dir.path().join("config.toml"); - std::fs::write( - &config_path, - format!("default_temperature = 0.7\n\n[storage.provider.config]\n{alias} = \"{encrypted}\"\n"), - ) - .expect("test: write config"); - let loaded = - crate::config::Config::load_from_path(&config_path, dir.path().join("workspace")).expect("test: load"); - assert_eq!( - loaded.storage.provider.config.db_url.as_deref(), - Some(secret), - "{alias}" - ); - } - } - - /// D-049 A: every inbound-trust setting names a real slot of the - /// `Config` schema (of any type), is documented with where it is - /// enforced, and is listed once. A typo would silently classify nothing. - #[test] - fn every_access_control_path_names_a_slot_of_the_config_schema() { - let root = serde_json::to_value(schemars::schema_for!(crate::config::Config)).expect("test: schema serializes"); - let mut seen = BTreeSet::new(); - for entry in ACCESS_CONTROL_PATHS { - assert!(seen.insert(entry.pattern), "{} is listed twice", entry.pattern); - assert!( - !entry.enforced_at.is_empty(), - "{} names no enforcement site", - entry.pattern - ); - assert!( - entry - .segments - .iter() - .try_fold(&root, |node, segment| step(&root, node, *segment)) - .is_some(), - "access-control path {} is not in the Config schema", - entry.pattern - ); - // None of them is a secret: they are public trust material or - // switches, so they are not encrypted, only classified. - assert!( - !SECRET_PATHS.iter().any(|secret| secret.segments == entry.segments), - "{} is registered as a secret too", - entry.pattern - ); - } - for listed in [ - "gateway.require_pairing", - "gateway.trust_forwarded_headers", - "mcp_server.require_auth", - "mcp_server.jwt_public_key_pem", - "mcp_server.jwt_jwks", - "mcp_server.jwt_jwks_uri", - "mcp_server.jwt_issuer", - "mcp_server.jwt_audience", - "mcp_server.jwt_algorithms", - "a2a.allowed_peer_issuers", - "a2a.trusted_trust_domains", - "a2a.spiffe_trust_bundle_pem", - "a2a.spiffe_strict_validation", - ] { - assert!(seen.contains(listed), "D-049 names {listed}"); - } - // Paths under a setting count as the setting. - fn path(elems: &[&str]) -> Vec { - elems.iter().map(|key| PathElem::Key((*key).to_string())).collect() - } - let mut element = path(&["channels_config", "telegram", "allowed_users"]); - element.push(PathElem::Index(3)); - assert!(is_access_control_path(&element)); - assert!(is_access_control_path(&path(&["gateway", "require_pairing"]))); - assert!(!is_access_control_path(&path(&["gateway", "port"]))); - assert!(!is_access_control_path(&path(&[ - "channels_config", - "telegram", - "bot_token" - ]))); - } - - /// Every registered secret whose value admits a client (D-048), with what - /// it admits. Reclassifying a path, or registering a new admission - /// secret, has to change this table: the guard below compares it with - /// the registry both ways. - const ADMISSION_SECRETS: &[(&str, &str)] = &[ - ("gateway.paired_tokens[]", "Gateway API clients (bearer tokens)"), - ("webhook.token", "senders of the standalone webhook"), - ("webhook.signing_secret", "signed requests to the standalone webhook"), - ( - "channels_config.webhook.secret", - "signed requests to the webhook channel", - ), - ( - "channels_config.whatsapp.verify_token", - "the WhatsApp Cloud API webhook handshake", - ), - ( - "channels_config.whatsapp.app_secret", - "signed WhatsApp Cloud API webhook calls", - ), - ("channels_config.lark.verification_token", "Lark/Feishu event callbacks"), - ( - "channels_config.lark.encrypt_key", - "encrypted Lark/Feishu event callbacks", - ), - ("channels_config.linq.signing_secret", "signed Linq webhook calls"), - ( - "channels_config.nextcloud_talk.webhook_secret", - "signed Nextcloud Talk bot calls", - ), - ("channels_config.wacli.webhook_secret", "signed wacli webhook calls"), - ("nodes.server.bearer_token", "`prx-node` RPC clients"), - ("nodes.server.hmac_secret", "signed `prx-node` RPC requests"), - ]; - - /// D-048: the registry marks exactly the admission secrets as access - /// grants; every other canonical path is an outbound credential or the - /// MCP launch environment. An alias carries its canonical path's kind. - #[test] - fn exactly_the_admission_secrets_are_access_grants() { - let expected: BTreeSet<&str> = ADMISSION_SECRETS.iter().map(|(pattern, _)| *pattern).collect(); - let registered: BTreeSet<&str> = SECRET_PATHS - .iter() - .filter(|secret| secret.alias_of.is_none() && secret.used_as == SecretUse::AccessGrant) - .map(|secret| secret.pattern) - .collect(); - assert_eq!(registered, expected); - let environment: Vec<&str> = SECRET_PATHS - .iter() - .filter(|secret| secret.used_as == SecretUse::ProcessEnvironment) - .map(|secret| secret.pattern) - .collect(); - assert_eq!(environment, vec!["mcp.servers..env."]); - // Outbound credentials PRX presents to others stay credentials. - for outbound in [ - "channels_config.telegram.bot_token", - "channels_config.whatsapp.access_token", - "channels_config.linq.api_token", - "nodes.nodes[].bearer_token", - "nodes.nodes[].hmac_secret", - "chat.daemon.token", - ] { - assert!( - SECRET_PATHS - .iter() - .any(|secret| secret.pattern == outbound && secret.used_as == SecretUse::Credential), - "{outbound} must stay an outbound credential" - ); - } - } - - /// Every registered alias is a real serde alias of its canonical path, so - /// registering it protects a spelling the loader actually accepts. The - /// fixture's sentinel at the canonical path is moved to the alias key and - /// must land back in the canonical field. - #[test] - fn every_registered_alias_deserializes_into_its_canonical_field() { - let sentinels = sentinel_paths(); - for secret in SECRET_PATHS.iter().filter(|secret| secret.alias_of.is_some()) { - let Some(canonical) = secret.alias_of else { continue }; - let canonical_path = SECRET_PATHS - .iter() - .find(|other| { - other.pattern == canonical - && other.alias_of.is_none() - && other.handling == secret.handling - && other.used_as == secret.used_as - }) - .unwrap_or_else(|| panic!("{} names an unregistered canonical path {canonical}", secret.pattern)); - let Some(Segment::Key(alias_key)) = secret.segments.last() else { - panic!("alias {} must end in a key", secret.pattern); - }; - let concrete = sentinels - .iter() - .find(|path| pattern_matches(canonical_path.segments, path)) - .unwrap_or_else(|| panic!("the fixture has no sentinel at {canonical}")); - let Some((PathElem::Key(canonical_key), parent)) = concrete.split_last() else { - panic!("{canonical} must end in a key"); - }; - // The default tree holds the canonical key too (a default value), - // so the rename happens on the merged tree the loader would see. - let mut tree = toml::Value::try_from(crate::config::Config::default()).expect("test: default tree"); - fixture::overlay(&mut tree, fixture_tree()); - let table = parent - .iter() - .try_fold(&mut tree, |node, elem| match elem { - PathElem::Key(key) => node.get_mut(key.as_str()), - PathElem::Index(index) => node.get_mut(*index), - }) - .and_then(toml::Value::as_table_mut) - .expect("test: parent table of the sentinel"); - let value = table.remove(canonical_key).expect("test: sentinel value"); - let expected = value.clone(); - table.insert((*alias_key).to_string(), value); - - let config: crate::config::Config = tree - .try_into() - .unwrap_or_else(|error| panic!("{} is not accepted by the loader: {error}", secret.pattern)); - let rendered = toml::Value::try_from(&config).expect("test: render config"); - assert_eq!( - lookup(&rendered, concrete), - expected.as_str(), - "{} does not land in {canonical}", - secret.pattern - ); - } - } - - /// The source files of the structs the `Config` schema is made of. A serde - /// alias of a credential field in any of them must be registered. - const SCHEMA_SOURCES: &[(&str, &str)] = &[ - ("config/schema.rs", include_str!("schema.rs")), - ("config/schema/agent.rs", include_str!("schema/agent.rs")), - ("config/schema/atomic.rs", include_str!("schema/atomic.rs")), - ("config/schema/autonomy.rs", include_str!("schema/autonomy.rs")), - ("config/schema/channels.rs", include_str!("schema/channels.rs")), - ("config/schema/chat.rs", include_str!("schema/chat.rs")), - ("config/schema/codex_effort.rs", include_str!("schema/codex_effort.rs")), - ("config/schema/cost.rs", include_str!("schema/cost.rs")), - ("config/schema/credentials.rs", include_str!("schema/credentials.rs")), - ( - "config/schema/decision_engine.rs", - include_str!("schema/decision_engine.rs"), - ), - ( - "config/schema/decision_engine/backend.rs", - include_str!("schema/decision_engine/backend.rs"), - ), - ( - "config/schema/decision_engine/backend_kind.rs", - include_str!("schema/decision_engine/backend_kind.rs"), - ), - ("config/schema/gateway.rs", include_str!("schema/gateway.rs")), - ("config/schema/integrations.rs", include_str!("schema/integrations.rs")), - ("config/schema/legacy.rs", include_str!("schema/legacy.rs")), - ("config/schema/lifecycle.rs", include_str!("schema/lifecycle.rs")), - ("config/schema/media.rs", include_str!("schema/media.rs")), - ("config/schema/memory.rs", include_str!("schema/memory.rs")), - ("config/schema/messaging.rs", include_str!("schema/messaging.rs")), - ("config/schema/nodes.rs", include_str!("schema/nodes.rs")), - ( - "config/schema/observability.rs", - include_str!("schema/observability.rs"), - ), - ("config/schema/paths.rs", include_str!("schema/paths.rs")), - ("config/schema/providers.rs", include_str!("schema/providers.rs")), - ("config/schema/proxy.rs", include_str!("schema/proxy.rs")), - ( - "config/schema/ramflux_channel.rs", - include_str!("schema/ramflux_channel.rs"), - ), - ("config/schema/routing.rs", include_str!("schema/routing.rs")), - ("config/schema/runtime.rs", include_str!("schema/runtime.rs")), - ("config/schema/secrets.rs", include_str!("schema/secrets.rs")), - ("config/schema/security.rs", include_str!("schema/security.rs")), - ("config/schema/tools.rs", include_str!("schema/tools.rs")), - ("config/schema/tunnel.rs", include_str!("schema/tunnel.rs")), - ( - "channels/email_channel.rs", - include_str!("../channels/email_channel.rs"), - ), - ]; - /// Every `(alias, field)` pair of a `#[serde(alias = "...")]` attribute in - /// the schema sources, with the field it decorates. - fn serde_aliases() -> Vec<(String, String, &'static str)> { - let mut found = Vec::new(); - for &(file, source) in SCHEMA_SOURCES { - let lines: Vec<&str> = source.lines().collect(); - for (index, line) in lines.iter().enumerate() { - let trimmed = line.trim_start(); - if !trimmed.starts_with("#[serde(") || !trimmed.contains("alias = \"") { - continue; - } - let Some(field) = lines.iter().skip(index + 1).take(6).find_map(|next| { - next.trim_start() - .strip_prefix("pub ") - .and_then(|rest| rest.split_once(':')) - .map(|(name, _)| name.trim().to_string()) - }) else { - continue; - }; - for piece in trimmed.split("alias = \"").skip(1) { - if let Some((alias, _)) = piece.split_once('"') { - found.push((alias.to_string(), field.clone(), file)); - } - } - } - } - found - } - - /// a39 (R-PMMAf R1): a serde alias of a secret field is a second spelling - /// the loader accepts. Unless it is registered with `alias_of`, a value - /// written under it is not encrypted, not decrypted when encrypted, and - /// not refused as plaintext. RED before SECRETS-OTHER: the node - /// `bearer_token` aliases `token` were not registered. - #[test] - fn every_serde_alias_of_a_secret_field_is_registered() { - assert!( - SCHEMA_SOURCES - .iter() - .any(|(path, source)| path.starts_with("config/schema/") && !source.is_empty()), - "the schema scan must include nonempty split sources" - ); - let split_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/config/schema"); - for entry in std::fs::read_dir(split_dir).expect("read schema split sources") { - let path = entry.expect("schema source entry").path(); - if path.extension().is_some_and(|ext| ext == "rs") - && path - .file_name() - .is_none_or(|name| name != "decision_engine_config_tests.rs") - { - let relative = format!("config/schema/{}", path.file_name().unwrap().to_string_lossy()); - assert!( - SCHEMA_SOURCES.iter().any(|(name, _)| *name == relative), - "schema guard misses {relative}" - ); - } - } - let aliases = serde_aliases(); - assert!( - aliases - .iter() - .any(|(alias, field, _)| alias == "dbURL" && field == "db_url"), - "the alias scan must see the db_url aliases: {aliases:?}" - ); - let canonical_names: BTreeSet<&str> = SECRET_PATHS - .iter() - .filter(|secret| secret.alias_of.is_none()) - .filter_map(|secret| match secret.segments.last() { - Some(Segment::Key(key)) => Some(*key), - _ => None, - }) - .collect(); - let mut missing = Vec::new(); - for (alias, field, file) in &aliases { - if !(is_secret_key_name(field) || canonical_names.contains(field.as_str())) { - continue; - } - let occurrences = aliases - .iter() - .filter(|(other_alias, other_field, _)| other_alias == alias && other_field == field) - .count(); - let registered = SECRET_PATHS - .iter() - .filter(|secret| { - matches!(secret.segments.last(), Some(Segment::Key(key)) if key == alias) - && secret - .alias_of - .is_some_and(|canonical| canonical.rsplit('.').next() == Some(field.as_str())) - }) - .count(); - if registered < occurrences { - missing.push(format!("{file}: alias `{alias}` of `{field}`")); - } - } - missing.sort(); - missing.dedup(); - assert!( - missing.is_empty(), - "serde aliases of secret fields without an alias_of row: {missing:#?}" - ); - } - - /// One step of a schema slot, owned (the schema's keys are not static). - #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] - enum Step { - Key(String), - AnyKey, - AnyIndex, - } - - fn display_steps(steps: &[Step]) -> String { - let mut rendered = String::new(); - for step in steps { - match step { - Step::Key(key) => { - if !rendered.is_empty() { - rendered.push('.'); - } - rendered.push_str(key); - } - Step::AnyKey => rendered.push_str(".<*>"), - Step::AnyIndex => rendered.push_str("[]"), - } - } - rendered - } - - fn steps_match(segments: &[Segment], steps: &[Step]) -> bool { - segments.len() == steps.len() - && segments.iter().zip(steps).all(|(segment, step)| match (segment, step) { - (Segment::Key(expected), Step::Key(actual)) => expected == actual, - (Segment::AnyKey, Step::AnyKey) | (Segment::AnyIndex, Step::AnyIndex) => true, - _ => false, - }) - } - - /// Every slot of the `Config` schema that admits a string, as a pattern. - fn schema_string_slots() -> BTreeSet> { - fn walk( - root: &serde_json::Value, - node: &serde_json::Value, - path: &mut Vec, - out: &mut BTreeSet>, - ) { - // Recursive schema types cannot nest this deep in a real config. - if path.len() > 16 { - return; - } - if !path.is_empty() && admits_string(root, node) { - out.insert(path.clone()); - } - for candidate in alternatives(root, node) { - if let Some(properties) = candidate.get("properties").and_then(serde_json::Value::as_object) { - for (key, child) in properties { - path.push(Step::Key(key.clone())); - walk(root, child, path, out); - path.pop(); - } - } - if let Some(child) = candidate - .get("additionalProperties") - .filter(|schema| schema.is_object()) - { - path.push(Step::AnyKey); - walk(root, child, path, out); - path.pop(); - } - if let Some(child) = candidate.get("items").filter(|schema| schema.is_object()) { - path.push(Step::AnyIndex); - walk(root, child, path, out); - path.pop(); - } - } - } - let root = serde_json::to_value(schemars::schema_for!(crate::config::Config)).expect("test: schema serializes"); - let mut out = BTreeSet::new(); - walk(&root, &root, &mut Vec::new(), &mut out); - out - } - - /// The field name of a slot: its last key, looking through list indices - /// (`reliability.api_keys[]` is named `api_keys`). A map value has no - /// field name of its own. - fn slot_name(steps: &[Step]) -> Option<&str> { - steps - .iter() - .rev() - .find(|step| !matches!(step, Step::AnyIndex)) - .and_then(|step| match step { - Step::Key(key) => Some(key.as_str()), - Step::AnyKey | Step::AnyIndex => None, - }) - } - - /// Schema slots whose name looks like a credential but that hold none. - /// Each carries the reason; the guard below fails when one disappears - /// from the schema, so the list cannot go stale. - const NOT_SECRET: &[(&str, &str)] = &[ - ( - "nodes.server.tls_key", - "a filesystem path to the PEM file (like nodes.server.tls_cert), not the key material", - ), - ( - "a2a.peers.<*>.credential", - "outbound identity name referring to [a2a.credentials.*], not a secret", - ), - ]; - - /// Registry completeness (R-PMMA F5, D-018 Q6): every string slot of the - /// `Config` schema whose name looks like a credential is registered or - /// explicitly exempt. A credential field added later fails here until it - /// is registered, so it cannot be stored in plaintext unnoticed. RED - /// before SECRETS-OTHER: about 30 channel, node, tunnel and webhook - /// credentials were masked by the name rule only. - #[test] - fn every_secret_named_string_slot_of_the_schema_is_registered_or_exempt() { - let slots = schema_string_slots(); - assert!( - slots - .iter() - .any(|slot| display_steps(slot) == "channels_config.telegram.bot_token"), - "the schema walk must reach the channel sections" - ); - let unregistered: Vec = slots - .iter() - .filter(|slot| slot_name(slot).is_some_and(is_secret_key_name)) - .filter(|slot| { - !SECRET_PATHS - .iter() - .any(|secret| secret.alias_of.is_none() && steps_match(secret.segments, slot)) - }) - .map(|slot| display_steps(slot)) - .filter(|pattern| !NOT_SECRET.iter().any(|(exempt, _)| exempt == pattern)) - .collect(); - assert!( - unregistered.is_empty(), - "credential-named config fields missing from SECRET_PATHS (register them, or add them to NOT_SECRET \ - with a reason): {unregistered:#?}" - ); - for (exempt, reason) in NOT_SECRET { - assert!(!reason.is_empty(), "expected a non-empty value"); - assert!( - slots.iter().any(|slot| display_steps(slot) == *exempt), - "NOT_SECRET entry {exempt} is not a string slot of the schema any more" - ); - } - } - - /// Whether a field name says it holds a URL (or a proxy URL). - fn url_named(name: &str) -> bool { - name == "homeserver" - || name - .split('_') - .any(|token| matches!(token, "url" | "uri" | "endpoint" | "proxy")) - } - - /// URL-named slots that are not endpoint URLs. - const NOT_URL: &[(&str, &str)] = &[ - ( - "proxy.no_proxy[]", - "host and domain names that bypass the proxy, never a URL with userinfo", - ), - ( - "tunnel.custom.url_pattern", - "a pattern matched against the tunnel command's output, not a URL PRX connects to", - ), - ]; - - /// Every URL-named string slot of the schema either is a registered - /// secret (a connection string such as `storage.provider.config.db_url`) - /// or has its userinfo redacted as a `URL_USERINFO_PATHS` entry. RED - /// before SECRETS-OTHER: proxy, MCP, node, OTEL, daemon and channel - /// endpoint URLs were shown with their `user:password@` in clear. - #[test] - fn every_url_named_string_slot_of_the_schema_redacts_its_userinfo() { - let slots = schema_string_slots(); - let uncovered: Vec = slots - .iter() - .filter(|slot| slot_name(slot).is_some_and(url_named)) - .filter(|slot| { - !SECRET_PATHS - .iter() - .any(|secret| secret.alias_of.is_none() && steps_match(secret.segments, slot)) - && !ENDPOINT_PATHS - .iter() - .any(|entry| entry.userinfo && steps_match(entry.segments, slot)) - }) - .map(|slot| display_steps(slot)) - .filter(|pattern| !NOT_URL.iter().any(|(exempt, _)| exempt == pattern)) - .collect(); - assert!( - uncovered.is_empty(), - "URL-named config fields missing from ENDPOINT_PATHS (with userinfo): {uncovered:#?}" - ); - for (exempt, _) in NOT_URL { - assert!( - slots.iter().any(|slot| display_steps(slot) == *exempt), - "NOT_URL entry {exempt} is not a string slot of the schema any more" - ); - } - for entry in ENDPOINT_PATHS { - assert!( - slots.iter().any(|slot| steps_match(entry.segments, slot)), - "ENDPOINT_PATHS entry {} is not a string slot of the schema", - entry.pattern - ); - } - } - - /// R-SECRETS F3, RED before SECRETS-f: userinfo in `a2a.card_jwks_uri` - /// loaded and was published in the public Agent Card. After: the load - /// refuses it, naming the field and never the password. - #[test] - fn a_published_jwks_uri_with_userinfo_is_refused() { - let dir = tempfile::TempDir::new().expect("test: temp dir"); - let path = dir.path().join("config.toml"); - std::fs::write( - &path, - "default_temperature = 0.7\n\n[a2a]\ncard_jwks_uri = \"https://u:userinfo-sentinel-jwks@h.invalid/jwks.json\"\n", - ) - .expect("test: write config"); - let error = crate::config::Config::load_from_path(&path, dir.path().join("workspace")) - .expect_err("test: userinfo in a published URI must not load"); - let rendered = format!("{error:#}"); - assert!(rendered.contains("a2a.card_jwks_uri"), "{rendered}"); - assert!(!rendered.contains("userinfo-sentinel"), "{rendered}"); - - std::fs::write( - &path, - "default_temperature = 0.7\n\n[a2a]\ncard_jwks_uri = \"https://h.invalid/jwks.json\"\n", - ) - .expect("test: write config"); - crate::config::Config::load_from_path(&path, dir.path().join("workspace")).expect("test: plain URI loads"); - } - - /// `prx config show` and the Gateway redaction keep every endpoint URL - /// readable and replace only its userinfo. - #[test] - fn config_show_redacts_url_userinfo_in_every_endpoint_url() { - let dir = tempfile::TempDir::new().expect("test: temp config dir"); - let config = fixture::config_from_overlay(dir.path(), fixture::ENDPOINT_USERINFO_TOML); - let rendered = redacted_stored_toml(&config) - .expect("test: config show rendering") - .to_string(); - assert!( - !rendered.contains("userinfo-sentinel"), - "config show leaked URL userinfo: {rendered}" - ); - for endpoint in [ - "http://[redacted]@127.0.0.1:11", - "socks5://[redacted]@127.0.0.1:13", - "https://[redacted]@127.0.0.1:14/mcp", - "http://[redacted]@127.0.0.1:16", - "http://[redacted]@127.0.0.1:19/health", - "ws://[redacted]@127.0.0.1:26", - // The decision backend endpoint (`[causal_tree.backend]`, :27, was - // deleted with its table in P2-R24). - "https://[redacted]@127.0.0.1:28/v1", - ] { - assert!(rendered.contains(endpoint), "{endpoint} is missing from: {rendered}"); - } - - let mut json = serde_json::to_value(&config).expect("test: json"); - redact(&mut json); - let json = json.to_string(); - assert!(!json.contains("userinfo-sentinel"), "GET /api/config leaked: {json}"); - - let raw: toml::Value = toml::from_str(fixture::ENDPOINT_USERINFO_TOML).expect("test: parses"); - let found = scan(&raw); - assert!(found.has_secret_values(), "the userinfo must be scrubbed from messages"); - assert!( - !found - .scrub(fixture::ENDPOINT_USERINFO_TOML) - .contains("userinfo-sentinel") - ); - } - - /// CDP-04 (V6.09 endpoint half): the decision endpoint written by hand - /// with user information never shows it on a read surface: `prx config - /// show`, `GET /api/config`, a scrubbed message or the section's `Debug`. - #[test] - fn the_decision_endpoint_is_redacted_on_every_read_surface() { - const SENTINEL: &str = "userinfo-sentinel-cdp04"; - let dir = tempfile::TempDir::new().expect("test: temp config dir"); - let overlay = format!("[decision_engine.backend]\nendpoint = \"https://decider:{SENTINEL}@127.0.0.1:27/v1\"\n"); - let config = fixture::config_from_overlay(dir.path(), &overlay); - let rendered = redacted_stored_toml(&config) - .expect("test: config show rendering") - .to_string(); - assert!(!rendered.contains(SENTINEL), "config show leaked: {rendered}"); - assert!(rendered.contains("https://[redacted]@127.0.0.1:27/v1"), "{rendered}"); - let mut json = serde_json::to_value(&config).expect("test: json"); - redact(&mut json); - assert!(!json.to_string().contains(SENTINEL), "GET /api/config leaked: {json}"); - let found = scan(&toml::from_str::(&overlay).expect("test: overlay")); - assert!(!found.scrub(&overlay).contains(SENTINEL)); - let debug = format!("{:?}", config.decision_engine); - assert!(!debug.contains(SENTINEL), "{debug}"); - assert!(is_credential_recipient_endpoint(&[ - PathElem::Key("decision_engine".to_string()), - PathElem::Key("backend".to_string()), - PathElem::Key("endpoint".to_string()), - ])); - } - - /// F2, RED before PMMA-f: a credential stored as the literal mask (left - /// by the pre-A-4 round trip, possibly encrypted) loaded silently and was - /// sent to the provider as the key. After: the load warns, naming the - /// path and never a value. - #[test] - fn load_warns_about_a_stored_mask_by_path_only() { - #[derive(Clone, Default)] - struct Sink(std::sync::Arc>>); - impl std::io::Write for Sink { - fn write(&mut self, buf: &[u8]) -> std::io::Result { - self.0.lock().extend_from_slice(buf); - Ok(buf.len()) - } - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) - } - } - impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Sink { - type Writer = Self; - fn make_writer(&'a self) -> Self::Writer { - self.clone() - } - } - - let dir = tempfile::TempDir::new().expect("test: temp config dir"); - let store = crate::security::SecretStore::new(dir.path(), true); - let encrypted_mask = store.encrypt(REDACTION_MASK).expect("test: encrypt mask"); - let config_path = dir.path().join("config.toml"); - std::fs::write( - &config_path, - format!( - "default_temperature = 0.7\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"openrouter\"\nmodel = \"m\"\napi_key = \"{encrypted_mask}\"\n\n[gateway]\npaired_tokens = [\"***\", \"sentinel-paired-ok\"]\n" - ), - ) - .expect("test: write config"); - - let _serial = fixture::LOG_CALLSITE_LOCK.blocking_lock(); - let sink = Sink::default(); - let subscriber = tracing_subscriber::fmt() - .with_writer(sink.clone()) - .with_max_level(tracing::Level::TRACE) - .with_ansi(false) - .finish(); - let loaded = tracing::subscriber::with_default(subscriber, || { - tracing::callsite::rebuild_interest_cache(); - crate::config::Config::load_from_path(&config_path, dir.path().join("workspace")) - }) - .expect("test: a stored mask must not stop the load"); - assert_eq!( - loaded.model_routes.first().and_then(|r| r.api_key.as_deref()), - Some(REDACTION_MASK) - ); - - let logs = String::from_utf8_lossy(&sink.0.lock()).to_string(); - assert!( - logs.contains("model_routes[0].api_key"), - "the stored mask must be reported: {logs}" - ); - assert!( - logs.contains("gateway.paired_tokens[0]"), - "the stored mask must be reported: {logs}" - ); - assert!( - !logs.contains("sentinel-paired-ok"), - "the warning must not carry a value: {logs}" - ); - assert!(!logs.contains("enc2:"), "the warning must not carry a value: {logs}"); - } - - /// F7, RED before PMMA-f: `Config`'s `Debug` redacted only the root key; - /// route, agent, rotation, tool, storage and channel secrets printed in - /// clear. After: every registry path is masked and ordinary values stay. - #[test] - fn config_debug_masks_every_registered_path() { - let dir = tempfile::TempDir::new().expect("test: temp config dir"); - let config = fixture::config_in(dir.path()); - let rendered = format!("{config:?}"); - assert!( - !rendered.contains(fixture::SENTINEL_PREFIX), - "Debug leaked a secret: {rendered}" - ); - assert!( - rendered.contains("model-test"), - "Debug must keep ordinary values: {rendered}" - ); - assert!( - rendered.contains("config_path"), - "Debug must keep the path fields: {rendered}" - ); - } - - #[test] - fn name_rule_masks_an_unregistered_credential_and_keeps_ordinary_values() { - let mut value = serde_json::json!({ - "future_section": { "client_secret": "sentinel-future", "enabled": true, "count": 3 }, - "default_model": "kimi-k2", - "nested": { "credential": { "username": "user", "password": "pass" } }, - }); - redact(&mut value); - assert_eq!( - value.pointer("/future_section/client_secret"), - Some(&serde_json::json!(REDACTION_MASK)) - ); - assert_eq!(value.pointer("/future_section/enabled"), Some(&serde_json::json!(true))); - assert_eq!(value.pointer("/default_model"), Some(&serde_json::json!("kimi-k2"))); - assert_eq!( - value.pointer("/nested/credential/username"), - Some(&serde_json::json!(REDACTION_MASK)) - ); - assert_eq!( - value.pointer("/nested/credential/password"), - Some(&serde_json::json!(REDACTION_MASK)) - ); - } - - /// Every configuration path that names a provider or an endpoint by URL. - /// Each value carries a distinct fixture password, so one search finds a - /// leak from any of them. - const USERINFO_TOML: &str = r#" -default_provider = "custom:http://alice:userinfo-sentinel-default@127.0.0.1:1/v1" -api_url = "http://alice:userinfo-sentinel-api-url@127.0.0.1:2/v1" - -[reliability] -fallback_providers = ["custom:https://bob:userinfo-sentinel-fallback@127.0.0.1:3/v1", "openrouter"] - -[[model_routes]] -hint = "fast" -provider = "custom:http://carol:userinfo-sentinel-route@127.0.0.1:4/v1" -model = "route-model" - -[[embedding_routes]] -hint = "semantic" -provider = "custom:http://dave:userinfo-sentinel-embedding@127.0.0.1:5/v1" -model = "embed-model" - -[agents.worker] -provider = "custom:http://erin:userinfo-sentinel-agent@127.0.0.1:6/v1" -model = "agent-model" - -[[providers.tool_dialects]] -provider = "custom:http://frank:userinfo-sentinel-dialect@127.0.0.1:7/v1" -tool_schema = "no_root_combinators" - -[smart_group] -classifier_provider = "custom:http://grace:userinfo-sentinel-classifier@127.0.0.1:8/v1" -"#; - - fn userinfo_config(dir: &std::path::Path) -> crate::config::Config { - let mut tree = toml::Value::try_from(crate::config::Config::default()).expect("test: default config tree"); - fixture::overlay( - &mut tree, - toml::from_str(USERINFO_TOML).expect("test: userinfo fixture parses"), - ); - let mut config: crate::config::Config = tree.try_into().expect("test: the userinfo fixture must deserialize"); - config.config_path = dir.join("config.toml"); - config.workspace_dir = dir.join("workspace"); - config - } - - /// R-C2Kf S-2: `prx config show` printed every provider label verbatim, - /// so a `custom:` URL's `user:password@` reached the terminal. The - /// endpoints stay readable; only their userinfo is replaced. - #[test] - fn config_show_redacts_url_userinfo_in_every_provider_and_endpoint_field() { - let dir = tempfile::TempDir::new().expect("test: temp config dir"); - let rendered = redacted_stored_toml(&userinfo_config(dir.path())) - .expect("test: config show rendering") - .to_string(); - assert!( - !rendered.contains("userinfo-sentinel"), - "config show leaked URL userinfo: {rendered}" - ); - for endpoint in [ - "custom:http://[redacted]@127.0.0.1:1/v1", - "http://[redacted]@127.0.0.1:2/v1", - "custom:https://[redacted]@127.0.0.1:3/v1", - "custom:http://[redacted]@127.0.0.1:4/v1", - "custom:http://[redacted]@127.0.0.1:5/v1", - "custom:http://[redacted]@127.0.0.1:6/v1", - "custom:http://[redacted]@127.0.0.1:7/v1", - "custom:http://[redacted]@127.0.0.1:8/v1", - ] { - assert!(rendered.contains(endpoint), "{endpoint} is missing from: {rendered}"); - } - assert!( - rendered.contains("\"openrouter\""), - "an ordinary label must stay: {rendered}" - ); - } - - /// A redacted label posted or written back is a mask: it must be found by - /// the scan that refuses masks, never stored as a provider. - #[test] - fn a_redacted_endpoint_label_counts_as_a_mask() { - let tree: toml::Value = toml::from_str( - "default_provider = \"custom:http://[redacted]@127.0.0.1:1/v1\"\n\ - [reliability]\nfallback_providers = [\"openrouter\", \"custom:http://[redacted]@h.invalid/v1\"]\n", - ) - .expect("test: masked tree parses"); - let masked: BTreeSet = scan(&tree).masked.into_iter().collect(); - assert_eq!( - masked, - BTreeSet::from([ - "default_provider".to_string(), - "reliability.fallback_providers[1]".to_string() - ]) - ); - // Userinfo is a secret value for scrubbing messages, and a file that - // holds one is served masked. - let raw: toml::Value = toml::from_str(USERINFO_TOML).expect("test: userinfo fixture parses"); - let found = scan(&raw); - assert!(found.has_secret_values()); - assert!( - !found - .scrub("rejected custom:http://alice:userinfo-sentinel-default@127.0.0.1:1/v1") - .contains("userinfo-sentinel") - ); - } - - /// R-C2BU F-3: the memory embedding provider also takes a `custom:` URL. - #[test] - fn config_show_redacts_url_userinfo_in_the_memory_embedding_provider() { - let mut tree: toml::Value = toml::from_str( - "[memory]\nembedding_provider = \"custom:https://u:userinfo-sentinel-embed@embed.invalid/v1\"\n", - ) - .expect("test: fixture parses"); - let found = scan(&tree); - assert!( - found.has_secret_values(), - "the userinfo must be a secret value for scrubbing" - ); - redact(&mut tree); - let rendered = tree.to_string(); - assert!(!rendered.contains("userinfo-sentinel"), "{rendered}"); - assert!( - rendered.contains("custom:https://[redacted]@embed.invalid/v1"), - "{rendered}" - ); - } - - /// D-027: two credential-bearing `[cost].prices` keys that redact to the - /// same spelling are a configuration error. The error names the keys in - /// their redacted form only. - #[test] - fn colliding_credentialed_price_keys_fail_validation_without_printing_credentials() { - let dir = tempfile::TempDir::new().expect("test: temp dir"); - let path = dir.path().join("config.toml"); - std::fs::write( - &path, - "default_temperature = 0.7\n\n[cost.prices.\"custom:http://alice:pwA-d027@h.invalid/v1/m\"]\ninput = 1.0\noutput = 1.0\n\n\ - [cost.prices.\"custom:http://bob:pwB-d027@h.invalid/v1/m\"]\ninput = 9.0\noutput = 9.0\n", - ) - .expect("test: write config"); - let error = crate::config::Config::load_from_path(&path, dir.path().join("workspace")) - .expect_err("test: colliding price keys must not load"); - let rendered = format!("{error:#}"); - assert!( - rendered.contains("custom:http://[redacted]@h.invalid/v1/m"), - "{rendered}" - ); - assert!(rendered.contains("cost.prices"), "{rendered}"); - assert!( - !rendered.contains("pwA-d027") && !rendered.contains("pwB-d027"), - "{rendered}" - ); - assert!(!rendered.contains("alice") && !rendered.contains("bob"), "{rendered}"); - - // Distinct endpoints, or one credentialed key, still load. - std::fs::write( - &path, - "default_temperature = 0.7\n\n[cost.prices.\"custom:http://alice:pwA-d027@h.invalid/v1/m\"]\ninput = 1.0\noutput = 1.0\n\n\ - [cost.prices.\"custom:http://bob:pwB-d027@other.invalid/v1/m\"]\ninput = 9.0\noutput = 9.0\n", - ) - .expect("test: write config"); - crate::config::Config::load_from_path(&path, dir.path().join("workspace")) - .expect("test: distinct endpoints load"); - } - - /// The `{:?}` of every table-valued section of `config`, by its key. - fn section_debug(config: &crate::config::Config) -> Vec<(&'static str, String)> { - macro_rules! sections { - ($($field:ident),* $(,)?) => { - vec![$((stringify!($field), format!("{:?}", config.$field))),*] - }; - } - sections!( - providers, - model_settings, - observability, - autonomy, - runtime, - reliability, - scheduler, - agent, - sessions_spawn, - chat, - self_system, - skills, - skill_rag, - plugins, - skills_lifecycle, - model_routes, - embedding_routes, - query_classification, - task_routing, - router, - smart_group, - heartbeat, - xin, - cron, - channels_config, - memory, - identity_bindings, - user_policies, - storage, - tunnel, - gateway, - webhook, - composio, - mcp, - mcp_server, - a2a, - auth, - secrets, - browser, - http_request, - multimodal, - web_search, - proxy, - identity, - cost, - nodes, - agents, - media, - decision_engine, - security, - compliance, - tool_tiering, - ) - } - - /// Provider labels with URL userinfo at the label paths the endpoint - /// fixture leaves out. - const LABEL_USERINFO_TOML: &str = r#" -[[router.models]] -provider = "custom:http://router:sentinel-label-router@127.0.0.1:31/v1" -model_id = "m" - -[[providers.models]] -provider = "custom:http://models:sentinel-label-models@127.0.0.1:32/v1" -model = "m" - -[[providers.tool_dialects]] -provider = "custom:http://dialect:sentinel-label-dialect@127.0.0.1:33/v1" -tool_schema = "raw" - -[memory] -embedding_provider = "custom:http://embed:sentinel-label-memory@127.0.0.1:34/v1" - -[smart_group] -classifier_provider = "custom:http://group:sentinel-label-group@127.0.0.1:35/v1" - -[[model_routes]] -hint = "fast" -provider = "custom:http://route:sentinel-label-route@127.0.0.1:36/v1" -model = "m" - -[reliability] -fallback_providers = ["custom:http://fallback:sentinel-label-fallback@127.0.0.1:37/v1"] - -[cost.prices."custom:http://price:sentinel-label-price@127.0.0.1:38/v1/m"] -input = 1.0 -output = 1.0 -"#; - - /// The display path of every table in `tree` that has a key carrying a - /// fixture sentinel (the value leaves alone miss a secret in a key). - fn sentinel_key_owners(tree: &toml::Value) -> BTreeSet { - fn walk(node: &toml::Value, path: &mut Vec, out: &mut BTreeSet) { - match node { - toml::Value::Table(table) => { - if table.keys().any(|key| key.contains(fixture::SENTINEL_PREFIX)) { - out.insert(display_path(path)); - } - for (key, child) in table { - path.push(PathElem::Key(key.clone())); - walk(child, path, out); - path.pop(); - } - } - toml::Value::Array(items) => { - for (index, child) in items.iter().enumerate() { - path.push(PathElem::Index(index)); - walk(child, path, out); - path.pop(); - } - } - _ => {} - } - } - let mut out = BTreeSet::new(); - walk(tree, &mut Vec::new(), &mut out); - out - } - - /// `{:?}` of the sub-struct that owns the value at `owner` (the display - /// path of a sentinel's parent), or `None` when no probe is written for it. - fn owner_debug(config: &crate::config::Config, owner: &str) -> Option { - fn d(value: &dyn std::fmt::Debug) -> String { - format!("{value:?}") - } - let c = config; - let channels = &c.channels_config; - Some(match owner { - "" => d(c), - "agents.worker" => d(c.agents.get("worker")?), - "model_routes[0]" => d(c.model_routes.first()?), - "embedding_routes[0]" => d(c.embedding_routes.first()?), - "reliability" | "reliability.api_keys" | "reliability.fallback_providers" => d(&c.reliability), - "composio" => d(&c.composio), - "browser.computer_use" => d(&c.browser.computer_use), - "web_search" => d(&c.web_search), - "storage.provider.config" => d(&c.storage.provider.config), - "gateway" | "gateway.paired_tokens" => d(&c.gateway), - "mcp.servers.local" | "mcp.servers.local.env" => d(c.mcp.servers.get("local")?), - "mcp.servers.remote" => d(c.mcp.servers.get("remote")?), - "channels_config.telegram" => d(channels.telegram.as_ref()?), - "channels_config.discord" => d(channels.discord.as_ref()?), - "channels_config.slack" => d(channels.slack.as_ref()?), - "channels_config.mattermost" => d(channels.mattermost.as_ref()?), - "channels_config.dingtalk" => d(channels.dingtalk.as_ref()?), - "channels_config.email" => d(channels.email.as_ref()?), - "channels_config.irc" => d(channels.irc.as_ref()?), - "channels_config.lark" => d(channels.lark.as_ref()?), - "channels_config.linq" => d(channels.linq.as_ref()?), - "channels_config.nextcloud_talk" => d(channels.nextcloud_talk.as_ref()?), - "channels_config.qq" => d(channels.qq.as_ref()?), - "channels_config.wacli" => d(channels.wacli.as_ref()?), - "channels_config.webhook" => d(channels.webhook.as_ref()?), - "channels_config.whatsapp" => d(channels.whatsapp.as_ref()?), - "channels_config.signal" => d(channels.signal.as_ref()?), - "webhook" => d(&c.webhook), - "tunnel.cloudflare" => d(c.tunnel.cloudflare.as_ref()?), - "tunnel.ngrok" => d(c.tunnel.ngrok.as_ref()?), - "tunnel.custom" => d(c.tunnel.custom.as_ref()?), - "chat.daemon" => d(&c.chat.daemon), - "decision_engine.backend" => d(c.decision_engine.backend.as_ref()?), - "nodes.nodes[0]" => d(c.nodes.nodes.first()?), - "nodes.server" => d(&c.nodes.server), - "proxy" => d(&c.proxy), - "observability" => d(&c.observability), - "media" => d(&c.media), - "mcp_server" => d(&c.mcp_server), - "a2a" => d(&c.a2a), - "router.models[0]" => d(c.router.models.first()?), - "providers.models[0]" => d(c.providers.models.first()?), - "providers.tool_dialects[0]" => d(c.providers.tool_dialects.first()?), - "memory" => d(&c.memory), - "smart_group" => d(&c.smart_group), - "cost.prices" => d(&c.cost), - _ => return None, - }) - } - - /// INT-2B a40 (R-PMMAf sub-struct Debug), RED before: the configuration - /// sub-structs derived `Debug`, so `{:?}` of a model route, a channel - /// config or a delegate agent printed its key, and of an endpoint its URL - /// password. After: for every sentinel of the registry fixture, the - /// endpoint fixture and a provider-label fixture, `{:?}` of the sub-struct - /// that owns it prints no sentinel (a sentinel whose owner has no probe - /// fails the test), and neither does `{:?}` of any table-valued section. - #[test] - fn no_configuration_struct_debug_prints_a_secret() { - let dir = tempfile::TempDir::new().expect("test: temp dir"); - let mut unprobed = BTreeSet::new(); - let mut leaks = BTreeSet::new(); - for overlay in [fixture::TOML, fixture::ENDPOINT_USERINFO_TOML, LABEL_USERINFO_TOML] { - let config = fixture::config_from_overlay(dir.path(), overlay); - let tree: toml::Value = toml::from_str(overlay).expect("test: overlay parses"); - let sentinels = fixture::string_leaves(&tree, &|value| value.contains(fixture::SENTINEL_PREFIX)); - assert!(!sentinels.is_empty()); - // A secret in a map key (a credentialed `cost.prices` key) is - // owned by the struct that holds the map. - let key_owners = sentinel_key_owners(&tree); - let owners = sentinels - .into_iter() - .map(|path| { - let mut owner = path; - if matches!(owner.pop(), Some(PathElem::Index(_))) { - owner.pop(); - } - display_path(&owner) - }) - .chain(key_owners); - for owner in owners { - match owner_debug(&config, &owner) { - Some(rendered) if rendered.contains(fixture::SENTINEL_PREFIX) => { - leaks.insert(owner); - } - Some(_) => {} - None => { - unprobed.insert(owner); - } - } - } - - let sections = section_debug(&config); - let serialized = serde_json::to_value(&config).expect("test: serialize"); - let probed: BTreeSet<&str> = sections.iter().map(|(name, _)| *name).collect(); - for (key, value) in serialized.as_object().expect("test: config is an object") { - if value.is_object() || value.is_array() { - assert!(probed.contains(key.as_str()), "section `{key}` has no Debug probe"); - } - } - for (name, rendered) in §ions { - if rendered.contains(fixture::SENTINEL_PREFIX) { - leaks.insert((*name).to_string()); - } - } - } - assert!(unprobed.is_empty(), "add a Debug probe for: {unprobed:?}"); - assert!(leaks.is_empty(), "these print a secret with {{:?}}: {leaks:?}"); - } - - /// INT-2B a41 (R-PMMAf R5, D-056 DC-4), RED before: a commented-out - /// credential was found only as `name = value` with the exact credential - /// name, so `# api-key = …`, `# apikey = …` and `# token: …` were served - /// verbatim. After: `-` reads as `_`, `apikey` counts, and `:` separates - /// like `=`. Ordinary comments still do not count. - #[test] - fn a_commented_credential_is_found_in_its_common_spellings() { - for text in [ - "# api-key = \"sk-old\"", - "# apikey = \"sk-old\"", - "# OpenAI-ApiKey = \"sk-old\"", - "# api_key: sk-old", - "#token: abc", - "model = \"m\" # bot-token: abc", - "# Password = hunter2", - "# api_key = \"sk-old\"", - "# note: api_key = \"sk-old\"", - ] { - assert!(has_commented_secret(text), "{text:?} must count as a commented secret"); - } - for text in [ - "# see the API documentation", - "# key points: none", - "# timeout = 5", - "# model: gpt-4o", - "# http://example.invalid/a=b", - "default_model = \"m\"", - ] { - assert!(!has_commented_secret(text), "{text:?} is an ordinary comment"); - } - } -} +#[path = "secret_paths/tests.rs"] +mod tests; diff --git a/src/config/secret_paths/tests.rs b/src/config/secret_paths/tests.rs new file mode 100644 index 000000000..449a2ba29 --- /dev/null +++ b/src/config/secret_paths/tests.rs @@ -0,0 +1,4 @@ +#![cfg(test)] + +include!("tests/section_1.rs"); +include!("tests/section_2.rs"); diff --git a/src/config/secret_paths/tests/section_1.rs b/src/config/secret_paths/tests/section_1.rs new file mode 100644 index 000000000..e49a4ecc0 --- /dev/null +++ b/src/config/secret_paths/tests/section_1.rs @@ -0,0 +1,1732 @@ + use super::*; + use std::collections::BTreeSet; + + #[test] + fn one_scrubber_masks_by_value_and_by_shape_with_or_without_a_scan() { + let message = "bad key sk-proj-abcdefghijklmnop12345 near sentinel-route"; + let tree: toml::Value = toml::from_str( + "[[model_routes]]\nhint = \"fast\"\nprovider = \"p\"\nmodel = \"m\"\napi_key = \"sentinel-route\"\n", + ) + .expect("test: parse"); + let found = scan(&tree); + let with_scan = scrub_message(Some(&found), message); + assert!(!with_scan.contains("sk-proj-abcdefghijklmnop12345"), "{with_scan}"); + assert!(!with_scan.contains("sentinel-route"), "{with_scan}"); + let without_scan = scrub_message(None, message); + assert!( + !without_scan.contains("sk-proj-abcdefghijklmnop12345"), + "{without_scan}" + ); + assert_eq!(found.scrub(message), with_scan); + } + + fn fixture_tree() -> toml::Value { + toml::from_str(fixture::TOML).expect("test: fixture parses") + } + + fn sentinel_paths() -> BTreeSet> { + fixture::string_leaves(&fixture_tree(), &|value| value.contains(fixture::SENTINEL_PREFIX)) + } + + /// Resolve `$ref` and `anyOf`/`oneOf`/`allOf` alternatives of a schema node. + fn alternatives<'a>(root: &'a serde_json::Value, node: &'a serde_json::Value) -> Vec<&'a serde_json::Value> { + if let Some(reference) = node.get("$ref").and_then(serde_json::Value::as_str) { + let name = reference.rsplit('/').next().unwrap_or_default(); + return root + .get("$defs") + .and_then(|defs| defs.get(name)) + .map(|target| alternatives(root, target)) + .unwrap_or_default(); + } + let mut found = vec![node]; + for combinator in ["anyOf", "oneOf", "allOf"] { + if let Some(options) = node.get(combinator).and_then(serde_json::Value::as_array) { + for option in options { + found.extend(alternatives(root, option)); + } + } + } + found + } + + fn step<'a>( + root: &'a serde_json::Value, + node: &'a serde_json::Value, + segment: Segment, + ) -> Option<&'a serde_json::Value> { + alternatives(root, node) + .into_iter() + .find_map(|candidate| match segment { + Segment::Key(key) => candidate.get("properties").and_then(|properties| properties.get(key)), + Segment::AnyKey => candidate + .get("additionalProperties") + .filter(|schema| schema.is_object()), + Segment::AnyIndex => candidate.get("items"), + }) + } + + fn admits_string(root: &serde_json::Value, node: &serde_json::Value) -> bool { + alternatives(root, node) + .into_iter() + .any(|candidate| match candidate.get("type") { + Some(serde_json::Value::String(kind)) => kind == "string", + Some(serde_json::Value::Array(kinds)) => kinds.iter().any(|kind| kind == "string"), + _ => false, + }) + } + + /// Every registered pattern names a real string slot of `Config`. A typo + /// in the registry would otherwise silently protect nothing. + #[test] + fn every_registered_path_names_a_string_slot_of_the_config_schema() { + let root = serde_json::to_value(schemars::schema_for!(crate::config::Config)).expect("test: schema serializes"); + // The JSON schema lists canonical names only; aliases have their + // own guard below. + for secret in SECRET_PATHS.iter().filter(|secret| secret.alias_of.is_none()) { + let leaf = secret + .segments + .iter() + .try_fold(&root, |node, segment| step(&root, node, *segment)); + let leaf = leaf.unwrap_or_else(|| panic!("registered path {} is not in the Config schema", secret.pattern)); + assert!( + admits_string(&root, leaf), + "registered path {} does not hold a string", + secret.pattern + ); + } + } + + /// The fixture really covers the registry: each registered pattern has at + /// least one sentinel instance, and every sentinel sits at a secret path. + #[test] + fn fixture_holds_a_sentinel_at_every_registered_path() { + let sentinels = sentinel_paths(); + // One fixture cannot hold a field and its alias at once. + for secret in SECRET_PATHS.iter().filter(|secret| secret.alias_of.is_none()) { + assert!( + sentinels.iter().any(|path| pattern_matches(secret.segments, path)), + "the fixture has no sentinel at {}", + secret.pattern + ); + } + for path in &sentinels { + assert!( + registered(path).is_some(), + "sentinel at {} is not registered", + display_path(path) + ); + } + } + + /// Guard: the registry's encrypted set is exactly what `Config::save` + /// encrypts, through the real save path on a temp config dir. + #[tokio::test] + async fn registry_encrypted_set_is_exactly_what_save_encrypts() { + let dir = tempfile::TempDir::new().expect("test: temp config dir"); + let config = fixture::config_in(dir.path()); + config.save().await.expect("test: save fixture"); + + let stored: toml::Value = + toml::from_str(&std::fs::read_to_string(&config.config_path).expect("test: read stored config")) + .expect("test: stored config parses"); + let store = crate::security::SecretStore::new(dir.path(), true); + + let encrypted_on_disk = fixture::string_leaves(&stored, &crate::security::SecretStore::is_encrypted); + let expected_encrypted: BTreeSet> = sentinel_paths() + .into_iter() + .filter(|path| registered(path).is_some_and(|secret| secret.handling == SecretHandling::EncryptedAtRest)) + .collect(); + assert_eq!( + encrypted_on_disk + .iter() + .map(|path| display_path(path)) + .collect::>(), + expected_encrypted + .iter() + .map(|path| display_path(path)) + .collect::>(), + "save must encrypt exactly the registered encrypted-at-rest paths" + ); + + let fixture = fixture_tree(); + for path in &expected_encrypted { + let stored_value = lookup(&stored, path).expect("test: encrypted path stored"); + let plaintext = lookup(&fixture, path).expect("test: fixture value"); + assert_eq!( + store.decrypt(stored_value).expect("test: decrypt stored value"), + plaintext, + "{} must decrypt to what was saved", + display_path(path) + ); + } + } + + fn lookup<'a>(root: &'a toml::Value, path: &[PathElem]) -> Option<&'a str> { + path.iter() + .try_fold(root, |node, elem| match elem { + PathElem::Key(key) => node.get(key.as_str()), + PathElem::Index(index) => node.get(*index), + }) + .and_then(toml::Value::as_str) + } + + /// `prx config show` renders the stored form with every registered path + /// masked and no sentinel left. + #[test] + fn config_show_rendering_masks_every_registered_path() { + let dir = tempfile::TempDir::new().expect("test: temp config dir"); + let config = fixture::config_in(dir.path()); + let rendered = redacted_stored_toml(&config).expect("test: render"); + let text = toml::to_string_pretty(&rendered).expect("test: serialize rendering"); + assert!( + !text.contains(fixture::SENTINEL_PREFIX), + "config show leaked a sentinel:\n{text}" + ); + + let masked = fixture::masked_paths(&rendered); + for path in sentinel_paths() { + assert!( + masked.contains(&display_path(&path)), + "{} is not masked by config show", + display_path(&path) + ); + } + } + + // ── SECRETS-OTHER: every registered secret is encrypted at rest ────── + + /// RED before SECRETS-OTHER: with `secrets.encrypt = true`, channel and + /// bot tokens, paired tokens, MCP environment values, webhook, tunnel, + /// daemon and node credentials were stored as plaintext. After: every + /// sentinel of the fixture is `enc2:` on disk, and the load restores it. + #[tokio::test] + async fn save_encrypts_every_registered_secret_and_load_restores_it() { + let dir = tempfile::TempDir::new().expect("test: temp config dir"); + let config = fixture::config_in(dir.path()); + config.save().await.expect("test: save fixture"); + let (raw, stored) = stored_tree(&config); + assert!( + !raw.contains(fixture::SENTINEL_PREFIX), + "a secret is stored as plaintext:\n{raw}" + ); + for path in sentinel_paths() { + let value = lookup(&stored, &path).unwrap_or_else(|| panic!("{} is not stored", display_path(&path))); + assert!( + crate::security::SecretStore::is_secure_encrypted(value), + "{} is not enc2: on disk", + display_path(&path) + ); + } + + let loaded = crate::config::Config::load_from_path(&config.config_path, config.workspace_dir.clone()) + .expect("test: load saved fixture"); + let loaded = toml::Value::try_from(&loaded).expect("test: render loaded"); + let fixture = fixture_tree(); + for path in sentinel_paths() { + assert_eq!( + lookup(&loaded, &path), + lookup(&fixture, &path), + "{} must load back as written", + display_path(&path) + ); + } + } + + /// Migration (D-018 Q4, no forced migration): a file an older release + /// wrote holds channel tokens, paired tokens and MCP environment values + /// as plaintext. They load as they are and are encrypted on the next + /// save; the values survive every step. + #[tokio::test] + async fn plaintext_channel_and_gateway_secrets_from_an_older_release_are_encrypted_on_next_save() { + let dir = tempfile::TempDir::new().expect("test: temp config dir"); + let config_path = dir.path().join("config.toml"); + std::fs::write( + &config_path, + "default_temperature = 0.7\n\n[gateway]\npaired_tokens = [\"sentinel-old-paired\"]\n\n\ + [channels_config]\ncli = true\n\n[channels_config.telegram]\nbot_token = \"sentinel-old-telegram\"\nallowed_users = []\n\n\ + [mcp.servers.local]\ncommand = \"mcp-local\"\nenv = { GITHUB_PAT = \"sentinel-old-mcp\" }\n", + ) + .expect("test: write legacy config"); + + let check = |config: &crate::config::Config| { + assert_eq!(config.gateway.paired_tokens, vec!["sentinel-old-paired".to_string()]); + assert_eq!( + config + .channels_config + .telegram + .as_ref() + .map(|telegram| telegram.bot_token.as_str()), + Some("sentinel-old-telegram") + ); + assert_eq!( + config + .mcp + .servers + .get("local") + .and_then(|server| server.env.get("GITHUB_PAT")) + .map(String::as_str), + Some("sentinel-old-mcp") + ); + }; + let loaded = crate::config::Config::load_from_path(&config_path, dir.path().join("workspace")) + .unwrap_or_else(|error| panic!("test: a plaintext legacy file must still load: {error:#}")); + check(&loaded); + loaded.save().await.expect("test: next save"); + let (raw, _) = stored_tree(&loaded); + assert!( + !raw.contains(fixture::SENTINEL_PREFIX), + "a secret survived the next save as plaintext:\n{raw}" + ); + let reloaded = crate::config::Config::load_from_path(&config_path, dir.path().join("workspace")) + .expect("test: reload re-encrypted config"); + check(&reloaded); + } + + /// Guard (downgrade path, D-018 Q4): `secrets.encrypt = false` stores + /// every registered secret as plaintext, so an older release can read + /// the file again. + #[tokio::test] + async fn disabled_encryption_keeps_every_registered_secret_plaintext() { + let dir = tempfile::TempDir::new().expect("test: temp config dir"); + let mut config = fixture::config_in(dir.path()); + config.secrets.encrypt = false; + config.save().await.expect("test: save fixture"); + let (_, stored) = stored_tree(&config); + assert!(fixture::string_leaves(&stored, &crate::security::SecretStore::is_encrypted).is_empty()); + let fixture = fixture_tree(); + for path in sentinel_paths() { + assert_eq!( + lookup(&stored, &path), + lookup(&fixture, &path), + "{}", + display_path(&path) + ); + } + } + + // ── A-2: every provider credential slot is encrypted at rest ────────── + + const ROUTE_SECRET: &str = "sentinel-route-secret"; + const EMBEDDING_SECRET: &str = "sentinel-embedding-secret"; + const ROTATION_SECRETS: [&str; 2] = ["sentinel-rotation-a", "sentinel-rotation-b"]; + + fn provider_slots_config(dir: &std::path::Path, route_provider: &str) -> crate::config::Config { + let mut config = crate::config::Config::default(); + config.config_path = dir.join("config.toml"); + config.workspace_dir = dir.join("workspace"); + config.model_routes = vec![crate::config::ModelRouteConfig { + settings: Default::default(), + hint: "fast".into(), + provider: route_provider.into(), + model: "route-model".into(), + api_key: Some(ROUTE_SECRET.into()), + credential_ref: None, + }]; + config.embedding_routes = vec![crate::config::EmbeddingRouteConfig { + hint: "semantic".into(), + provider: "openai".into(), + model: "text-embedding-3-small".into(), + dimensions: None, + api_key: Some(EMBEDDING_SECRET.into()), + credential_ref: None, + }]; + config.reliability.api_keys = ROTATION_SECRETS.iter().map(|key| (*key).to_string()).collect(); + config + } + + fn stored_tree(config: &crate::config::Config) -> (String, toml::Value) { + let raw = std::fs::read_to_string(&config.config_path).expect("test: read stored config"); + let tree = toml::from_str(&raw).expect("test: stored config parses"); + (raw, tree) + } + + fn stored_provider_slots(tree: &toml::Value) -> Vec { + let mut slots = Vec::new(); + for (section, key) in [("model_routes", "api_key"), ("embedding_routes", "api_key")] { + if let Some(routes) = tree.get(section).and_then(toml::Value::as_array) { + slots.extend( + routes + .iter() + .filter_map(|route| route.get(key).and_then(toml::Value::as_str).map(str::to_string)), + ); + } + } + if let Some(keys) = tree + .get("reliability") + .and_then(|reliability| reliability.get("api_keys")) + .and_then(toml::Value::as_array) + { + slots.extend(keys.iter().filter_map(toml::Value::as_str).map(str::to_string)); + } + slots + } + + /// RED before A-2: `Config::save` wrote route, embedding-route and + /// rotation keys to disk as plaintext on every write path. + #[tokio::test] + async fn save_encrypts_route_embedding_and_rotation_keys() { + let dir = tempfile::TempDir::new().expect("test: temp config dir"); + let config = provider_slots_config(dir.path(), "openrouter"); + config.save().await.expect("test: save"); + + let (raw, tree) = stored_tree(&config); + for secret in [ROUTE_SECRET, EMBEDDING_SECRET, ROTATION_SECRETS[0], ROTATION_SECRETS[1]] { + assert!(!raw.contains(secret), "{secret} is stored as plaintext:\n{raw}"); + } + let stored = stored_provider_slots(&tree); + assert_eq!(stored.len(), 4, "every slot must still be stored: {stored:?}"); + assert!( + stored + .iter() + .all(|value| crate::security::SecretStore::is_secure_encrypted(value)), + "every provider slot must be enc2: {stored:?}" + ); + + let loaded = crate::config::Config::load_from_path(&config.config_path, config.workspace_dir.clone()) + .expect("test: load saved config"); + assert_eq!(loaded.model_routes[0].api_key.as_deref(), Some(ROUTE_SECRET)); + assert_eq!(loaded.embedding_routes[0].api_key.as_deref(), Some(EMBEDDING_SECRET)); + assert_eq!(loaded.reliability.api_keys, ROTATION_SECRETS.to_vec()); + } + + /// Migration (D-018 Q4): a file an older release wrote holds these keys + /// as plaintext. The new binary reads them as they are and encrypts them + /// on the next save; the values survive every step. + #[tokio::test] + async fn plaintext_provider_slots_from_an_older_release_load_and_are_encrypted_on_next_save() { + let dir = tempfile::TempDir::new().expect("test: temp config dir"); + let config_path = dir.path().join("config.toml"); + let legacy = format!( + "default_temperature = 0.7\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"openrouter\"\nmodel = \"route-model\"\napi_key = \"{ROUTE_SECRET}\"\n\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\napi_key = \"{EMBEDDING_SECRET}\"\n\n[reliability]\napi_keys = [\"{}\", \"{}\"]\n", + ROTATION_SECRETS[0], ROTATION_SECRETS[1] + ); + std::fs::write(&config_path, legacy).expect("test: write legacy config"); + + let loaded = crate::config::Config::load_from_path(&config_path, dir.path().join("workspace")) + .expect("test: a plaintext legacy file must still load"); + assert_eq!(loaded.model_routes[0].api_key.as_deref(), Some(ROUTE_SECRET)); + assert_eq!(loaded.embedding_routes[0].api_key.as_deref(), Some(EMBEDDING_SECRET)); + assert_eq!(loaded.reliability.api_keys, ROTATION_SECRETS.to_vec()); + + loaded.save().await.expect("test: next save"); + let (raw, tree) = stored_tree(&loaded); + for secret in [ROUTE_SECRET, EMBEDDING_SECRET, ROTATION_SECRETS[0], ROTATION_SECRETS[1]] { + assert!(!raw.contains(secret), "{secret} survived the next save as plaintext"); + } + assert!( + stored_provider_slots(&tree) + .iter() + .all(|value| crate::security::SecretStore::is_secure_encrypted(value)) + ); + + let reloaded = crate::config::Config::load_from_path(&config_path, dir.path().join("workspace")) + .expect("test: reload re-encrypted config"); + assert_eq!(reloaded.model_routes[0].api_key.as_deref(), Some(ROUTE_SECRET)); + assert_eq!(reloaded.embedding_routes[0].api_key.as_deref(), Some(EMBEDDING_SECRET)); + assert_eq!(reloaded.reliability.api_keys, ROTATION_SECRETS.to_vec()); + } + + /// `secrets.encrypt = false` keeps every slot as plaintext, as before. + #[tokio::test] + async fn disabled_encryption_keeps_provider_slots_plaintext() { + let dir = tempfile::TempDir::new().expect("test: temp config dir"); + let mut config = provider_slots_config(dir.path(), "openrouter"); + config.secrets.encrypt = false; + config.save().await.expect("test: save"); + let (_, tree) = stored_tree(&config); + assert_eq!( + stored_provider_slots(&tree), + vec![ + ROUTE_SECRET.to_string(), + EMBEDDING_SECRET.to_string(), + ROTATION_SECRETS[0].to_string(), + ROTATION_SECRETS[1].to_string() + ] + ); + } + + /// A legacy XOR `enc:` route key is decrypted on load and upgraded to + /// `enc2:` by the startup migration, like the other encrypted slots. + /// RED before A-2: the route key was neither decrypted nor migrated, so + /// the literal `enc:` string was the route's bearer credential. + #[tokio::test] + async fn legacy_xor_route_key_is_decrypted_and_migrated() { + let dir = tempfile::TempDir::new().expect("test: temp config dir"); + let store = crate::security::SecretStore::new(dir.path(), true); + let legacy_value = legacy_xor(dir.path(), ROUTE_SECRET); + let config_path = dir.path().join("config.toml"); + std::fs::write( + &config_path, + format!( + "default_temperature = 0.7\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"openrouter\"\nmodel = \"route-model\"\napi_key = \"{legacy_value}\"\n" + ), + ) + .expect("test: write legacy config"); + + let loaded = crate::config::Config::load_from_path(&config_path, dir.path().join("workspace")) + .expect("test: load legacy route key"); + assert_eq!(loaded.model_routes[0].api_key.as_deref(), Some(ROUTE_SECRET)); + + crate::config::schema::migrate_config_legacy_secrets(&loaded) + .await + .expect("test: legacy migration"); + let (_, tree) = stored_tree(&loaded); + let stored = stored_provider_slots(&tree); + assert_eq!(stored.len(), 1); + assert!( + crate::security::SecretStore::is_secure_encrypted(&stored[0]), + "{stored:?}" + ); + assert_eq!(store.decrypt(&stored[0]).expect("test: decrypt migrated"), ROUTE_SECRET); + } + + /// RED before PMMH-f (D-101 F-5): with `secrets.encrypt = false` the + /// startup upgrade rewrote a legacy `enc:` value as plaintext. It is + /// left as it is now (it keeps loading). + #[tokio::test] + async fn a_legacy_value_is_never_rewritten_as_plaintext() { + let dir = tempfile::TempDir::new().expect("test: temp config dir"); + let legacy_value = legacy_xor(dir.path(), ROUTE_SECRET); + let config_path = dir.path().join("config.toml"); + std::fs::write( + &config_path, + format!( + "default_temperature = 0.7\n\n[secrets]\nencrypt = false\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"openrouter\"\nmodel = \"route-model\"\napi_key = \"{legacy_value}\"\n" + ), + ) + .expect("test: write legacy config"); + let before = std::fs::read(&config_path).expect("test: read"); + + let loaded = crate::config::Config::load_from_path(&config_path, dir.path().join("workspace")) + .expect("test: load legacy route key"); + crate::config::schema::migrate_config_legacy_secrets(&loaded) + .await + .expect("test: legacy migration"); + + let after = std::fs::read(&config_path).expect("test: read"); + assert!( + !String::from_utf8_lossy(&after).contains(ROUTE_SECRET), + "the legacy value was rewritten as plaintext" + ); + assert_eq!(after, before); + assert_eq!( + loaded.model_routes.first().and_then(|route| route.api_key.as_deref()), + Some(ROUTE_SECRET) + ); + } + + /// A loopback OpenAI-compatible endpoint that answers every chat request + /// with "ok" and reports each request's `Authorization` header. + async fn spawn_authorization_recorder() -> ( + std::net::SocketAddr, + tokio::sync::mpsc::UnboundedReceiver>, + tokio::task::JoinHandle<()>, + ) { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("test: bind loopback"); + let addr = listener.local_addr().expect("test: loopback addr"); + let (seen_tx, seen_rx) = tokio::sync::mpsc::unbounded_channel::>(); + let server = tokio::spawn(async move { + while let Ok((mut socket, _)) = listener.accept().await { + let mut buffer = Vec::new(); + let mut chunk = [0_u8; 4096]; + let head_end = loop { + match socket.read(&mut chunk).await { + Ok(0) | Err(_) => break None, + Ok(read) => buffer.extend_from_slice(&chunk[..read]), + } + if let Some(position) = buffer.windows(4).position(|window| window == b"\r\n\r\n") { + break Some(position + 4); + } + }; + let Some(head_end) = head_end else { continue }; + let head = String::from_utf8_lossy(&buffer[..head_end]).to_string(); + let authorization = head.split("\r\n").find_map(|line| { + line.split_once(':') + .filter(|(name, _)| name.trim().eq_ignore_ascii_case("authorization")) + .map(|(_, value)| value.trim().to_string()) + }); + let content_length = head + .split("\r\n") + .find_map(|line| { + line.split_once(':') + .filter(|(name, _)| name.trim().eq_ignore_ascii_case("content-length")) + .and_then(|(_, value)| value.trim().parse::().ok()) + }) + .unwrap_or(0); + let mut body_read = buffer.len() - head_end; + while body_read < content_length { + match socket.read(&mut chunk).await { + Ok(0) | Err(_) => break, + Ok(read) => body_read += read, + } + } + let _ = seen_tx.send(authorization); + let body = r#"{"id":"c","object":"chat.completion","created":1,"model":"route-model","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}]}"#; + let response = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let _ = socket.write_all(response.as_bytes()).await; + } + }); + + (addr, seen_rx, server) + } + + fn isolated_provider_options(dir: &std::path::Path) -> crate::providers::ProviderRuntimeOptions { + crate::providers::ProviderRuntimeOptions { + openprx_dir: Some(dir.to_path_buf()), + codex_auth_json_path: Some(dir.join("absent-codex-auth.json")), + codex_auth_json_auto_import: false, + ..crate::providers::ProviderRuntimeOptions::default() + } + } + + /// The legacy XOR `enc:` form of `plaintext` under the key in `dir`. + fn legacy_xor(dir: &std::path::Path, plaintext: &str) -> String { + let store = crate::security::SecretStore::new(dir, true); + store.encrypt("prime-the-key").expect("test: create key file"); + let key_hex = std::fs::read_to_string(dir.join(".secret_key")).expect("test: key file"); + let key_hex = key_hex.trim(); + let key = (0..key_hex.len()) + .step_by(2) + .map(|index| u8::from_str_radix(&key_hex[index..index + 2], 16).expect("test: key hex")) + .collect::>(); + format!( + "enc:{}", + plaintext + .bytes() + .enumerate() + .map(|(index, byte)| format!("{:02x}", byte ^ key[index % key.len()])) + .collect::() + ) + } + + /// F10: on the default split layout the route keys live in + /// `config.d/routing.toml`. A legacy `enc:` route key there is decrypted + /// on load (the merged tree is decrypted, fragments included), the routed + /// provider receives the real key, and the next structured save rewrites + /// the fragment as `enc2:`. The startup migration still rewrites + /// `config.toml` only. + #[tokio::test] + async fn legacy_route_key_in_a_fragment_reaches_the_provider_and_is_upgraded_on_next_save() { + let (addr, mut seen_rx, server) = spawn_authorization_recorder().await; + let dir = tempfile::TempDir::new().expect("test: temp config dir"); + let route_provider = format!("custom:http://{addr}/v1"); + let mut config = provider_slots_config(dir.path(), &route_provider); + config.reliability.api_keys = Vec::new(); + config.embedding_routes = Vec::new(); + crate::config::files::write_split_config(&config, false) + .await + .expect("test: write split layout"); + let fragment = crate::config::files::config_dir_path(&config.config_path).join("routing.toml"); + let stored = std::fs::read_to_string(&fragment).expect("test: routing fragment"); + assert!( + !std::fs::read_to_string(&config.config_path) + .expect("test: main") + .contains("model_routes") + ); + + // Replace the encrypted route key with its legacy XOR form. + let mut tree: toml::Value = toml::from_str(&stored).expect("test: fragment parses"); + let slot = tree + .get_mut("model_routes") + .and_then(|routes| routes.get_mut(0)) + .and_then(|route| route.get_mut("api_key")) + .expect("test: route key in the fragment"); + *slot = toml::Value::String(legacy_xor(dir.path(), ROUTE_SECRET)); + std::fs::write(&fragment, toml::to_string_pretty(&tree).expect("test: render")).expect("test: write fragment"); + + let loaded = crate::config::Config::load_from_path(&config.config_path, config.workspace_dir.clone()) + .expect("test: load split layout"); + assert_eq!( + loaded.model_routes.first().and_then(|r| r.api_key.as_deref()), + Some(ROUTE_SECRET) + ); + + let mut runtime_config = loaded.clone(); + runtime_config.default_provider = Some(route_provider.clone()); + runtime_config.default_model = Some("route-model".to_string()); + runtime_config.reliability.provider_retries = 0; + runtime_config.reliability.fallback_providers = Vec::new(); + let provider = + crate::providers::create_provider_from_test_config(&runtime_config, &isolated_provider_options(dir.path())) + .expect("test: routed provider"); + let reply = provider.chat_with_system(None, "ping", "hint:fast", 0.0).await; + assert_eq!(reply.as_deref().ok(), Some("ok"), "unexpected reply: {reply:?}"); + assert_eq!( + seen_rx.recv().await.flatten().as_deref(), + Some(format!("Bearer {ROUTE_SECRET}").as_str()) + ); + + loaded.save().await.expect("test: next save"); + let upgraded = std::fs::read_to_string(&fragment).expect("test: fragment after save"); + let upgraded: toml::Value = toml::from_str(&upgraded).expect("test: parses"); + let key = upgraded + .get("model_routes") + .and_then(|routes| routes.get(0)) + .and_then(|route| route.get("api_key")) + .and_then(toml::Value::as_str) + .expect("test: route key after save"); + assert!( + crate::security::SecretStore::is_secure_encrypted(key), + "the next save must upgrade to enc2:" + ); + server.abort(); + } + + /// RED before PMM-H (PMMA F-10): the startup migration upgraded legacy + /// `enc:` values in `config.toml` only; one in a `config.d` fragment + /// stayed XOR-encrypted on disk until a later save. It is now upgraded + /// at startup, and every other file is left byte for byte. + #[tokio::test] + async fn legacy_route_key_in_a_fragment_is_upgraded_at_startup() { + let dir = tempfile::TempDir::new().expect("test: temp config dir"); + let mut config = provider_slots_config(dir.path(), "openrouter"); + config.reliability.api_keys = Vec::new(); + config.embedding_routes = Vec::new(); + crate::config::files::write_split_config(&config, false) + .await + .expect("test: write split layout"); + let fragment = crate::config::files::config_dir_path(&config.config_path).join("routing.toml"); + let stored = std::fs::read_to_string(&fragment).expect("test: routing fragment"); + let mut tree: toml::Value = toml::from_str(&stored).expect("test: fragment parses"); + let slot = tree + .get_mut("model_routes") + .and_then(|routes| routes.get_mut(0)) + .and_then(|route| route.get_mut("api_key")) + .expect("test: route key in the fragment"); + *slot = toml::Value::String(legacy_xor(dir.path(), ROUTE_SECRET)); + std::fs::write(&fragment, toml::to_string_pretty(&tree).expect("test: render")).expect("test: write fragment"); + let main_before = std::fs::read(&config.config_path).expect("test: main"); + + let loaded = crate::config::Config::load_from_path(&config.config_path, config.workspace_dir.clone()) + .expect("test: load split layout"); + crate::config::schema::migrate_config_legacy_secrets(&loaded) + .await + .expect("test: startup migration"); + + let upgraded: toml::Value = + toml::from_str(&std::fs::read_to_string(&fragment).expect("test: fragment")).expect("test: parses"); + let key = upgraded + .get("model_routes") + .and_then(|routes| routes.get(0)) + .and_then(|route| route.get("api_key")) + .and_then(toml::Value::as_str) + .expect("test: route key"); + assert!( + crate::security::SecretStore::is_secure_encrypted(key), + "the fragment still holds a legacy value: {key}" + ); + let store = crate::security::SecretStore::new(dir.path(), true); + assert_eq!(store.decrypt(key).expect("test: decrypt"), ROUTE_SECRET); + assert_eq!(std::fs::read(&config.config_path).expect("test: main"), main_before); + // Nothing left to migrate: a second run writes nothing. + let fragment_after = std::fs::read(&fragment).expect("test: fragment"); + crate::config::schema::migrate_config_legacy_secrets(&loaded) + .await + .expect("test: second run"); + assert_eq!(std::fs::read(&fragment).expect("test: fragment"), fragment_after); + } + + /// PMM-H: a route that names a credential reference instead of an + /// inline key sends the referenced key to its own provider, and a + /// reference issued for another provider is never sent. + #[tokio::test] + async fn a_route_credential_ref_reaches_its_owner_provider_only() { + let (addr, mut seen_rx, server) = spawn_authorization_recorder().await; + let dir = tempfile::TempDir::new().expect("test: temp config dir"); + let route_provider = format!("custom:http://{addr}/v1"); + let mut config = provider_slots_config(dir.path(), &route_provider); + config.reliability.api_keys = Vec::new(); + config.embedding_routes = Vec::new(); + let references = + crate::config::manage::credentials::CredentialReferences::for_config(&config).expect("test: references"); + references + .set(&route_provider, "route", ROUTE_SECRET) + .expect("test: reference for the route's provider"); + references + .set("anthropic", "other", "sentinel-other-provider-secret") + .expect("test: reference for another provider"); + config.model_routes = vec![ + crate::config::ModelRouteConfig { + settings: Default::default(), + hint: "fast".into(), + provider: route_provider.clone(), + model: "route-model".into(), + api_key: None, + credential_ref: Some("cred-route".into()), + }, + crate::config::ModelRouteConfig { + settings: Default::default(), + hint: "wrong".into(), + provider: route_provider.clone(), + model: "route-model".into(), + api_key: None, + credential_ref: Some("cred-other".into()), + }, + ]; + config.save().await.expect("test: save"); + let stored = std::fs::read_to_string(&config.config_path).expect("test: stored"); + assert!(stored.contains("credential_ref = \"cred-route\""), "{stored}"); + assert!(!stored.contains(ROUTE_SECRET), "{stored}"); + + let loaded = crate::config::Config::load_from_path(&config.config_path, config.workspace_dir.clone()) + .expect("test: load"); + let routes = loaded.model_routes_with_references(); + assert_eq!(routes[0].api_key.as_deref(), Some(ROUTE_SECRET)); + assert_eq!(routes[1].api_key, None, "another provider's reference was released"); + + let mut runtime_config = loaded.clone(); + runtime_config.default_provider = Some(route_provider.clone()); + runtime_config.default_model = Some("route-model".to_string()); + runtime_config.model_routes = routes.to_vec(); + runtime_config.reliability.provider_retries = 0; + runtime_config.reliability.fallback_providers = Vec::new(); + let provider = + crate::providers::create_provider_from_test_config(&runtime_config, &isolated_provider_options(dir.path())) + .expect("test: routed provider"); + let reply = provider.chat_with_system(None, "ping", "hint:fast", 0.0).await; + assert_eq!(reply.as_deref().ok(), Some("ok"), "unexpected reply: {reply:?}"); + assert_eq!( + seen_rx.recv().await.flatten().as_deref(), + Some(format!("Bearer {ROUTE_SECRET}").as_str()) + ); + server.abort(); + } + + /// The route credential reaches its provider as plaintext after the + /// encrypted round trip: loopback `Authorization` equals the sentinel. + #[tokio::test] + async fn routed_provider_built_from_the_loaded_config_presents_the_plaintext_route_key() { + let (addr, mut seen_rx, server) = spawn_authorization_recorder().await; + + let dir = tempfile::TempDir::new().expect("test: temp config dir"); + let route_provider = format!("custom:http://{addr}/v1"); + let mut config = provider_slots_config(dir.path(), &route_provider); + config.reliability.api_keys = Vec::new(); + config.save().await.expect("test: save"); + let (raw, _) = stored_tree(&config); + assert!(!raw.contains(ROUTE_SECRET), "the route key must be stored encrypted"); + + let loaded = crate::config::Config::load_from_path(&config.config_path, config.workspace_dir.clone()) + .expect("test: load"); + let mut runtime_config = loaded.clone(); + runtime_config.default_provider = Some(route_provider.clone()); + runtime_config.default_model = Some("route-model".to_string()); + runtime_config.reliability.provider_retries = 0; + runtime_config.reliability.fallback_providers = Vec::new(); + let options = isolated_provider_options(dir.path()); + let provider = crate::providers::create_provider_from_test_config(&runtime_config, &options) + .expect("test: routed provider"); + let reply = provider.chat_with_system(None, "ping", "hint:fast", 0.0).await; + assert_eq!(reply.as_deref().ok(), Some("ok"), "unexpected reply: {reply:?}"); + assert_eq!( + seen_rx.recv().await.flatten().as_deref(), + Some(format!("Bearer {ROUTE_SECRET}").as_str()) + ); + server.abort(); + } + + /// The scan names plaintext at every registered encrypted slot, the + /// elements of `reliability.api_keys` and `gateway.paired_tokens` + /// included, and never flags ciphertext. + #[test] + fn scan_finds_plaintext_at_encrypted_slots_and_masks_anywhere() { + let tree: toml::Value = toml::from_str( + r#" +api_key = "enc2:00" +[reliability] +api_keys = ["enc2:00", "sentinel-rotation"] +[[model_routes]] +hint = "fast" +provider = "p" +model = "m" +api_key = "sentinel-route" +[gateway] +paired_tokens = ["sentinel-paired"] +[channels_config.telegram] +bot_token = "***" +"#, + ) + .expect("test: parse"); + let mut found = scan(&tree); + found.plaintext_at_rest.sort(); + assert_eq!( + found.plaintext_at_rest, + vec![ + "gateway.paired_tokens[0]".to_string(), + "model_routes[0].api_key".to_string(), + "reliability.api_keys[1]".to_string() + ] + ); + assert_eq!(found.masked, vec!["channels_config.telegram.bot_token".to_string()]); + assert!(found.has_secret_values()); + assert_eq!(found.scrub("x sentinel-route y sentinel-paired"), "x *** y ***"); + } + + /// F1b, RED before PMMA-f: decryption ran on the stored tree before + /// serde mapped the alias, and the alias was not registered, so an + /// encrypted `db_url` written under an alias reached the storage backend + /// as the literal ciphertext. + #[test] + fn encrypted_db_url_under_every_alias_decrypts_on_load() { + for alias in ["db_url", "dbURL", "database_url", "databaseUrl"] { + let dir = tempfile::TempDir::new().expect("test: temp config dir"); + let store = crate::security::SecretStore::new(dir.path(), true); + let secret = "postgres://u:sentinel-db-alias@h/db"; + let encrypted = store.encrypt(secret).expect("test: encrypt"); + let config_path = dir.path().join("config.toml"); + std::fs::write( + &config_path, + format!("default_temperature = 0.7\n\n[storage.provider.config]\n{alias} = \"{encrypted}\"\n"), + ) + .expect("test: write config"); + let loaded = + crate::config::Config::load_from_path(&config_path, dir.path().join("workspace")).expect("test: load"); + assert_eq!( + loaded.storage.provider.config.db_url.as_deref(), + Some(secret), + "{alias}" + ); + } + } + + /// D-049 A: every inbound-trust setting names a real slot of the + /// `Config` schema (of any type), is documented with where it is + /// enforced, and is listed once. A typo would silently classify nothing. + #[test] + fn every_access_control_path_names_a_slot_of_the_config_schema() { + let root = serde_json::to_value(schemars::schema_for!(crate::config::Config)).expect("test: schema serializes"); + let mut seen = BTreeSet::new(); + for entry in ACCESS_CONTROL_PATHS { + assert!(seen.insert(entry.pattern), "{} is listed twice", entry.pattern); + assert!( + !entry.enforced_at.is_empty(), + "{} names no enforcement site", + entry.pattern + ); + assert!( + entry + .segments + .iter() + .try_fold(&root, |node, segment| step(&root, node, *segment)) + .is_some(), + "access-control path {} is not in the Config schema", + entry.pattern + ); + // None of them is a secret: they are public trust material or + // switches, so they are not encrypted, only classified. + assert!( + !SECRET_PATHS.iter().any(|secret| secret.segments == entry.segments), + "{} is registered as a secret too", + entry.pattern + ); + } + for listed in [ + "gateway.require_pairing", + "gateway.trust_forwarded_headers", + "mcp_server.require_auth", + "mcp_server.jwt_public_key_pem", + "mcp_server.jwt_jwks", + "mcp_server.jwt_jwks_uri", + "mcp_server.jwt_issuer", + "mcp_server.jwt_audience", + "mcp_server.jwt_algorithms", + "a2a.allowed_peer_issuers", + "a2a.trusted_trust_domains", + "a2a.spiffe_trust_bundle_pem", + "a2a.spiffe_strict_validation", + ] { + assert!(seen.contains(listed), "D-049 names {listed}"); + } + // Paths under a setting count as the setting. + fn path(elems: &[&str]) -> Vec { + elems.iter().map(|key| PathElem::Key((*key).to_string())).collect() + } + let mut element = path(&["channels_config", "telegram", "allowed_users"]); + element.push(PathElem::Index(3)); + assert!(is_access_control_path(&element)); + assert!(is_access_control_path(&path(&["gateway", "require_pairing"]))); + assert!(!is_access_control_path(&path(&["gateway", "port"]))); + assert!(!is_access_control_path(&path(&[ + "channels_config", + "telegram", + "bot_token" + ]))); + } + + /// Every registered secret whose value admits a client (D-048), with what + /// it admits. Reclassifying a path, or registering a new admission + /// secret, has to change this table: the guard below compares it with + /// the registry both ways. + const ADMISSION_SECRETS: &[(&str, &str)] = &[ + ("gateway.paired_tokens[]", "Gateway API clients (bearer tokens)"), + ("webhook.token", "senders of the standalone webhook"), + ("webhook.signing_secret", "signed requests to the standalone webhook"), + ( + "channels_config.webhook.secret", + "signed requests to the webhook channel", + ), + ( + "channels_config.whatsapp.verify_token", + "the WhatsApp Cloud API webhook handshake", + ), + ( + "channels_config.whatsapp.app_secret", + "signed WhatsApp Cloud API webhook calls", + ), + ("channels_config.lark.verification_token", "Lark/Feishu event callbacks"), + ( + "channels_config.lark.encrypt_key", + "encrypted Lark/Feishu event callbacks", + ), + ("channels_config.linq.signing_secret", "signed Linq webhook calls"), + ( + "channels_config.nextcloud_talk.webhook_secret", + "signed Nextcloud Talk bot calls", + ), + ("channels_config.wacli.webhook_secret", "signed wacli webhook calls"), + ("nodes.server.bearer_token", "`prx-node` RPC clients"), + ("nodes.server.hmac_secret", "signed `prx-node` RPC requests"), + ]; + + /// D-048: the registry marks exactly the admission secrets as access + /// grants; every other canonical path is an outbound credential or the + /// MCP launch environment. An alias carries its canonical path's kind. + #[test] + fn exactly_the_admission_secrets_are_access_grants() { + let expected: BTreeSet<&str> = ADMISSION_SECRETS.iter().map(|(pattern, _)| *pattern).collect(); + let registered: BTreeSet<&str> = SECRET_PATHS + .iter() + .filter(|secret| secret.alias_of.is_none() && secret.used_as == SecretUse::AccessGrant) + .map(|secret| secret.pattern) + .collect(); + assert_eq!(registered, expected); + let environment: Vec<&str> = SECRET_PATHS + .iter() + .filter(|secret| secret.used_as == SecretUse::ProcessEnvironment) + .map(|secret| secret.pattern) + .collect(); + assert_eq!(environment, vec!["mcp.servers..env."]); + // Outbound credentials PRX presents to others stay credentials. + for outbound in [ + "channels_config.telegram.bot_token", + "channels_config.whatsapp.access_token", + "channels_config.linq.api_token", + "nodes.nodes[].bearer_token", + "nodes.nodes[].hmac_secret", + "chat.daemon.token", + ] { + assert!( + SECRET_PATHS + .iter() + .any(|secret| secret.pattern == outbound && secret.used_as == SecretUse::Credential), + "{outbound} must stay an outbound credential" + ); + } + } + + /// Every registered alias is a real serde alias of its canonical path, so + /// registering it protects a spelling the loader actually accepts. The + /// fixture's sentinel at the canonical path is moved to the alias key and + /// must land back in the canonical field. + #[test] + fn every_registered_alias_deserializes_into_its_canonical_field() { + let sentinels = sentinel_paths(); + for secret in SECRET_PATHS.iter().filter(|secret| secret.alias_of.is_some()) { + let Some(canonical) = secret.alias_of else { continue }; + let canonical_path = SECRET_PATHS + .iter() + .find(|other| { + other.pattern == canonical + && other.alias_of.is_none() + && other.handling == secret.handling + && other.used_as == secret.used_as + }) + .unwrap_or_else(|| panic!("{} names an unregistered canonical path {canonical}", secret.pattern)); + let Some(Segment::Key(alias_key)) = secret.segments.last() else { + panic!("alias {} must end in a key", secret.pattern); + }; + let concrete = sentinels + .iter() + .find(|path| pattern_matches(canonical_path.segments, path)) + .unwrap_or_else(|| panic!("the fixture has no sentinel at {canonical}")); + let Some((PathElem::Key(canonical_key), parent)) = concrete.split_last() else { + panic!("{canonical} must end in a key"); + }; + // The default tree holds the canonical key too (a default value), + // so the rename happens on the merged tree the loader would see. + let mut tree = toml::Value::try_from(crate::config::Config::default()).expect("test: default tree"); + fixture::overlay(&mut tree, fixture_tree()); + let table = parent + .iter() + .try_fold(&mut tree, |node, elem| match elem { + PathElem::Key(key) => node.get_mut(key.as_str()), + PathElem::Index(index) => node.get_mut(*index), + }) + .and_then(toml::Value::as_table_mut) + .expect("test: parent table of the sentinel"); + let value = table.remove(canonical_key).expect("test: sentinel value"); + let expected = value.clone(); + table.insert((*alias_key).to_string(), value); + + let config: crate::config::Config = tree + .try_into() + .unwrap_or_else(|error| panic!("{} is not accepted by the loader: {error}", secret.pattern)); + let rendered = toml::Value::try_from(&config).expect("test: render config"); + assert_eq!( + lookup(&rendered, concrete), + expected.as_str(), + "{} does not land in {canonical}", + secret.pattern + ); + } + } + + /// The source files of the structs the `Config` schema is made of. A serde + /// alias of a credential field in any of them must be registered. + const SCHEMA_SOURCES: &[(&str, &str)] = &[ + ("config/schema.rs", include_str!("../../schema.rs")), + ("config/schema/agent.rs", include_str!("../../schema/agent.rs")), + ("config/schema/atomic.rs", include_str!("../../schema/atomic.rs")), + ("config/schema/autonomy.rs", include_str!("../../schema/autonomy.rs")), + ("config/schema/channels.rs", include_str!("../../schema/channels.rs")), + ("config/schema/chat.rs", include_str!("../../schema/chat.rs")), + ("config/schema/codex_effort.rs", include_str!("../../schema/codex_effort.rs")), + ("config/schema/cost.rs", include_str!("../../schema/cost.rs")), + ("config/schema/credentials.rs", include_str!("../../schema/credentials.rs")), + ( + "config/schema/decision_engine.rs", + include_str!("../../schema/decision_engine.rs"), + ), + ( + "config/schema/decision_engine/backend.rs", + include_str!("../../schema/decision_engine/backend.rs"), + ), + ( + "config/schema/decision_engine/backend_kind.rs", + include_str!("../../schema/decision_engine/backend_kind.rs"), + ), + ("config/schema/gateway.rs", include_str!("../../schema/gateway.rs")), + ("config/schema/integrations.rs", include_str!("../../schema/integrations.rs")), + ("config/schema/legacy.rs", include_str!("../../schema/legacy.rs")), + ("config/schema/lifecycle.rs", include_str!("../../schema/lifecycle.rs")), + ("config/schema/media.rs", include_str!("../../schema/media.rs")), + ("config/schema/memory.rs", include_str!("../../schema/memory.rs")), + ("config/schema/messaging.rs", include_str!("../../schema/messaging.rs")), + ("config/schema/nodes.rs", include_str!("../../schema/nodes.rs")), + ( + "config/schema/observability.rs", + include_str!("../../schema/observability.rs"), + ), + ("config/schema/paths.rs", include_str!("../../schema/paths.rs")), + ("config/schema/providers.rs", include_str!("../../schema/providers.rs")), + ("config/schema/proxy.rs", include_str!("../../schema/proxy.rs")), + ( + "config/schema/ramflux_channel.rs", + include_str!("../../schema/ramflux_channel.rs"), + ), + ("config/schema/routing.rs", include_str!("../../schema/routing.rs")), + ("config/schema/runtime.rs", include_str!("../../schema/runtime.rs")), + ("config/schema/secrets.rs", include_str!("../../schema/secrets.rs")), + ("config/schema/security.rs", include_str!("../../schema/security.rs")), + ("config/schema/tools.rs", include_str!("../../schema/tools.rs")), + ("config/schema/tunnel.rs", include_str!("../../schema/tunnel.rs")), + ( + "channels/email_channel.rs", + include_str!("../../../channels/email_channel.rs"), + ), + ]; + /// Every `(alias, field)` pair of a `#[serde(alias = "...")]` attribute in + /// the schema sources, with the field it decorates. + fn serde_aliases() -> Vec<(String, String, &'static str)> { + let mut found = Vec::new(); + for &(file, source) in SCHEMA_SOURCES { + let lines: Vec<&str> = source.lines().collect(); + for (index, line) in lines.iter().enumerate() { + let trimmed = line.trim_start(); + if !trimmed.starts_with("#[serde(") || !trimmed.contains("alias = \"") { + continue; + } + let Some(field) = lines.iter().skip(index + 1).take(6).find_map(|next| { + next.trim_start() + .strip_prefix("pub ") + .and_then(|rest| rest.split_once(':')) + .map(|(name, _)| name.trim().to_string()) + }) else { + continue; + }; + for piece in trimmed.split("alias = \"").skip(1) { + if let Some((alias, _)) = piece.split_once('"') { + found.push((alias.to_string(), field.clone(), file)); + } + } + } + } + found + } + + /// a39 (R-PMMAf R1): a serde alias of a secret field is a second spelling + /// the loader accepts. Unless it is registered with `alias_of`, a value + /// written under it is not encrypted, not decrypted when encrypted, and + /// not refused as plaintext. RED before SECRETS-OTHER: the node + /// `bearer_token` aliases `token` were not registered. + #[test] + fn every_serde_alias_of_a_secret_field_is_registered() { + assert!( + SCHEMA_SOURCES + .iter() + .any(|(path, source)| path.starts_with("config/schema/") && !source.is_empty()), + "the schema scan must include nonempty split sources" + ); + let split_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/config/schema"); + for entry in std::fs::read_dir(split_dir).expect("read schema split sources") { + let path = entry.expect("schema source entry").path(); + if path.extension().is_some_and(|ext| ext == "rs") + && path + .file_name() + .is_none_or(|name| name != "decision_engine_config_tests.rs") + { + let relative = format!("config/schema/{}", path.file_name().unwrap().to_string_lossy()); + assert!( + SCHEMA_SOURCES.iter().any(|(name, _)| *name == relative), + "schema guard misses {relative}" + ); + } + } + let aliases = serde_aliases(); + assert!( + aliases + .iter() + .any(|(alias, field, _)| alias == "dbURL" && field == "db_url"), + "the alias scan must see the db_url aliases: {aliases:?}" + ); + let canonical_names: BTreeSet<&str> = SECRET_PATHS + .iter() + .filter(|secret| secret.alias_of.is_none()) + .filter_map(|secret| match secret.segments.last() { + Some(Segment::Key(key)) => Some(*key), + _ => None, + }) + .collect(); + let mut missing = Vec::new(); + for (alias, field, file) in &aliases { + if !(is_secret_key_name(field) || canonical_names.contains(field.as_str())) { + continue; + } + let occurrences = aliases + .iter() + .filter(|(other_alias, other_field, _)| other_alias == alias && other_field == field) + .count(); + let registered = SECRET_PATHS + .iter() + .filter(|secret| { + matches!(secret.segments.last(), Some(Segment::Key(key)) if key == alias) + && secret + .alias_of + .is_some_and(|canonical| canonical.rsplit('.').next() == Some(field.as_str())) + }) + .count(); + if registered < occurrences { + missing.push(format!("{file}: alias `{alias}` of `{field}`")); + } + } + missing.sort(); + missing.dedup(); + assert!( + missing.is_empty(), + "serde aliases of secret fields without an alias_of row: {missing:#?}" + ); + } + + /// One step of a schema slot, owned (the schema's keys are not static). + #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] + enum Step { + Key(String), + AnyKey, + AnyIndex, + } + + fn display_steps(steps: &[Step]) -> String { + let mut rendered = String::new(); + for step in steps { + match step { + Step::Key(key) => { + if !rendered.is_empty() { + rendered.push('.'); + } + rendered.push_str(key); + } + Step::AnyKey => rendered.push_str(".<*>"), + Step::AnyIndex => rendered.push_str("[]"), + } + } + rendered + } + + fn steps_match(segments: &[Segment], steps: &[Step]) -> bool { + segments.len() == steps.len() + && segments.iter().zip(steps).all(|(segment, step)| match (segment, step) { + (Segment::Key(expected), Step::Key(actual)) => expected == actual, + (Segment::AnyKey, Step::AnyKey) | (Segment::AnyIndex, Step::AnyIndex) => true, + _ => false, + }) + } + + /// Every slot of the `Config` schema that admits a string, as a pattern. + fn schema_string_slots() -> BTreeSet> { + fn walk( + root: &serde_json::Value, + node: &serde_json::Value, + path: &mut Vec, + out: &mut BTreeSet>, + ) { + // Recursive schema types cannot nest this deep in a real config. + if path.len() > 16 { + return; + } + if !path.is_empty() && admits_string(root, node) { + out.insert(path.clone()); + } + for candidate in alternatives(root, node) { + if let Some(properties) = candidate.get("properties").and_then(serde_json::Value::as_object) { + for (key, child) in properties { + path.push(Step::Key(key.clone())); + walk(root, child, path, out); + path.pop(); + } + } + if let Some(child) = candidate + .get("additionalProperties") + .filter(|schema| schema.is_object()) + { + path.push(Step::AnyKey); + walk(root, child, path, out); + path.pop(); + } + if let Some(child) = candidate.get("items").filter(|schema| schema.is_object()) { + path.push(Step::AnyIndex); + walk(root, child, path, out); + path.pop(); + } + } + } + let root = serde_json::to_value(schemars::schema_for!(crate::config::Config)).expect("test: schema serializes"); + let mut out = BTreeSet::new(); + walk(&root, &root, &mut Vec::new(), &mut out); + out + } + + /// The field name of a slot: its last key, looking through list indices + /// (`reliability.api_keys[]` is named `api_keys`). A map value has no + /// field name of its own. + fn slot_name(steps: &[Step]) -> Option<&str> { + steps + .iter() + .rev() + .find(|step| !matches!(step, Step::AnyIndex)) + .and_then(|step| match step { + Step::Key(key) => Some(key.as_str()), + Step::AnyKey | Step::AnyIndex => None, + }) + } + + /// Schema slots whose name looks like a credential but that hold none. + /// Each carries the reason; the guard below fails when one disappears + /// from the schema, so the list cannot go stale. + const NOT_SECRET: &[(&str, &str)] = &[( + "nodes.server.tls_key", + "a filesystem path to the PEM file (like nodes.server.tls_cert), not the key material", + )]; + + /// Registry completeness (R-PMMA F5, D-018 Q6): every string slot of the + /// `Config` schema whose name looks like a credential is registered or + /// explicitly exempt. A credential field added later fails here until it + /// is registered, so it cannot be stored in plaintext unnoticed. RED + /// before SECRETS-OTHER: about 30 channel, node, tunnel and webhook + /// credentials were masked by the name rule only. + #[test] + fn every_secret_named_string_slot_of_the_schema_is_registered_or_exempt() { + let slots = schema_string_slots(); + assert!( + slots + .iter() + .any(|slot| display_steps(slot) == "channels_config.telegram.bot_token"), + "the schema walk must reach the channel sections" + ); + let unregistered: Vec = slots + .iter() + .filter(|slot| slot_name(slot).is_some_and(is_secret_key_name)) + .filter(|slot| { + !SECRET_PATHS + .iter() + .any(|secret| secret.alias_of.is_none() && steps_match(secret.segments, slot)) + }) + .map(|slot| display_steps(slot)) + .filter(|pattern| !NOT_SECRET.iter().any(|(exempt, _)| exempt == pattern)) + .collect(); + assert!( + unregistered.is_empty(), + "credential-named config fields missing from SECRET_PATHS (register them, or add them to NOT_SECRET \ + with a reason): {unregistered:#?}" + ); + for (exempt, reason) in NOT_SECRET { + assert!(!reason.is_empty(), "expected a non-empty value"); + assert!( + slots.iter().any(|slot| display_steps(slot) == *exempt), + "NOT_SECRET entry {exempt} is not a string slot of the schema any more" + ); + } + } + + /// Whether a field name says it holds a URL (or a proxy URL). + fn url_named(name: &str) -> bool { + name == "homeserver" + || name + .split('_') + .any(|token| matches!(token, "url" | "uri" | "endpoint" | "proxy")) + } + + /// URL-named slots that are not endpoint URLs. + const NOT_URL: &[(&str, &str)] = &[ + ( + "proxy.no_proxy[]", + "host and domain names that bypass the proxy, never a URL with userinfo", + ), + ( + "tunnel.custom.url_pattern", + "a pattern matched against the tunnel command's output, not a URL PRX connects to", + ), + ]; + + /// Every URL-named string slot of the schema either is a registered + /// secret (a connection string such as `storage.provider.config.db_url`) + /// or has its userinfo redacted as a `URL_USERINFO_PATHS` entry. RED + /// before SECRETS-OTHER: proxy, MCP, node, OTEL, daemon and channel + /// endpoint URLs were shown with their `user:password@` in clear. + #[test] + fn every_url_named_string_slot_of_the_schema_redacts_its_userinfo() { + let slots = schema_string_slots(); + let uncovered: Vec = slots + .iter() + .filter(|slot| slot_name(slot).is_some_and(url_named)) + .filter(|slot| { + !SECRET_PATHS + .iter() + .any(|secret| secret.alias_of.is_none() && steps_match(secret.segments, slot)) + && !ENDPOINT_PATHS + .iter() + .any(|entry| entry.userinfo && steps_match(entry.segments, slot)) + }) + .map(|slot| display_steps(slot)) + .filter(|pattern| !NOT_URL.iter().any(|(exempt, _)| exempt == pattern)) + .collect(); + assert!( + uncovered.is_empty(), + "URL-named config fields missing from ENDPOINT_PATHS (with userinfo): {uncovered:#?}" + ); + for (exempt, _) in NOT_URL { + assert!( + slots.iter().any(|slot| display_steps(slot) == *exempt), + "NOT_URL entry {exempt} is not a string slot of the schema any more" + ); + } + for entry in ENDPOINT_PATHS { + assert!( + slots.iter().any(|slot| steps_match(entry.segments, slot)), + "ENDPOINT_PATHS entry {} is not a string slot of the schema", + entry.pattern + ); + } + } + + /// R-SECRETS F3, RED before SECRETS-f: userinfo in `a2a.card_jwks_uri` + /// loaded and was published in the public Agent Card. After: the load + /// refuses it, naming the field and never the password. + #[test] + fn a_published_jwks_uri_with_userinfo_is_refused() { + let dir = tempfile::TempDir::new().expect("test: temp dir"); + let path = dir.path().join("config.toml"); + std::fs::write( + &path, + "default_temperature = 0.7\n\n[a2a]\ncard_jwks_uri = \"https://u:userinfo-sentinel-jwks@h.invalid/jwks.json\"\n", + ) + .expect("test: write config"); + let error = crate::config::Config::load_from_path(&path, dir.path().join("workspace")) + .expect_err("test: userinfo in a published URI must not load"); + let rendered = format!("{error:#}"); + assert!(rendered.contains("a2a.card_jwks_uri"), "{rendered}"); + assert!(!rendered.contains("userinfo-sentinel"), "{rendered}"); + + std::fs::write( + &path, + "default_temperature = 0.7\n\n[a2a]\ncard_jwks_uri = \"https://h.invalid/jwks.json\"\n", + ) + .expect("test: write config"); + crate::config::Config::load_from_path(&path, dir.path().join("workspace")).expect("test: plain URI loads"); + } + + /// `prx config show` and the Gateway redaction keep every endpoint URL + /// readable and replace only its userinfo. + #[test] + fn config_show_redacts_url_userinfo_in_every_endpoint_url() { + let dir = tempfile::TempDir::new().expect("test: temp config dir"); + let config = fixture::config_from_overlay(dir.path(), fixture::ENDPOINT_USERINFO_TOML); + let rendered = redacted_stored_toml(&config) + .expect("test: config show rendering") + .to_string(); + assert!( + !rendered.contains("userinfo-sentinel"), + "config show leaked URL userinfo: {rendered}" + ); + for endpoint in [ + "http://[redacted]@127.0.0.1:11", + "socks5://[redacted]@127.0.0.1:13", + "https://[redacted]@127.0.0.1:14/mcp", + "http://[redacted]@127.0.0.1:16", + "http://[redacted]@127.0.0.1:19/health", + "ws://[redacted]@127.0.0.1:26", + // The decision backend endpoint (`[causal_tree.backend]`, :27, was + // deleted with its table in P2-R24). + "https://[redacted]@127.0.0.1:28/v1", + ] { + assert!(rendered.contains(endpoint), "{endpoint} is missing from: {rendered}"); + } + + let mut json = serde_json::to_value(&config).expect("test: json"); + redact(&mut json); + let json = json.to_string(); + assert!(!json.contains("userinfo-sentinel"), "GET /api/config leaked: {json}"); + + let raw: toml::Value = toml::from_str(fixture::ENDPOINT_USERINFO_TOML).expect("test: parses"); + let found = scan(&raw); + assert!(found.has_secret_values(), "the userinfo must be scrubbed from messages"); + assert!( + !found + .scrub(fixture::ENDPOINT_USERINFO_TOML) + .contains("userinfo-sentinel") + ); + } + + /// CDP-04 (V6.09 endpoint half): the decision endpoint written by hand + /// with user information never shows it on a read surface: `prx config + /// show`, `GET /api/config`, a scrubbed message or the section's `Debug`. + #[test] + fn the_decision_endpoint_is_redacted_on_every_read_surface() { + const SENTINEL: &str = "userinfo-sentinel-cdp04"; + let dir = tempfile::TempDir::new().expect("test: temp config dir"); + let overlay = format!("[decision_engine.backend]\nendpoint = \"https://decider:{SENTINEL}@127.0.0.1:27/v1\"\n"); + let config = fixture::config_from_overlay(dir.path(), &overlay); + let rendered = redacted_stored_toml(&config) + .expect("test: config show rendering") + .to_string(); + assert!(!rendered.contains(SENTINEL), "config show leaked: {rendered}"); + assert!(rendered.contains("https://[redacted]@127.0.0.1:27/v1"), "{rendered}"); + let mut json = serde_json::to_value(&config).expect("test: json"); + redact(&mut json); + assert!(!json.to_string().contains(SENTINEL), "GET /api/config leaked: {json}"); + let found = scan(&toml::from_str::(&overlay).expect("test: overlay")); + assert!(!found.scrub(&overlay).contains(SENTINEL)); + let debug = format!("{:?}", config.decision_engine); + assert!(!debug.contains(SENTINEL), "{debug}"); + assert!(is_credential_recipient_endpoint(&[ + PathElem::Key("decision_engine".to_string()), + PathElem::Key("backend".to_string()), + PathElem::Key("endpoint".to_string()), + ])); + } + + /// F2, RED before PMMA-f: a credential stored as the literal mask (left + /// by the pre-A-4 round trip, possibly encrypted) loaded silently and was + /// sent to the provider as the key. After: the load warns, naming the + /// path and never a value. + #[test] + fn load_warns_about_a_stored_mask_by_path_only() { + #[derive(Clone, Default)] + struct Sink(std::sync::Arc>>); + impl std::io::Write for Sink { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.lock().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Sink { + type Writer = Self; + fn make_writer(&'a self) -> Self::Writer { + self.clone() + } + } + + let dir = tempfile::TempDir::new().expect("test: temp config dir"); + let store = crate::security::SecretStore::new(dir.path(), true); + let encrypted_mask = store.encrypt(REDACTION_MASK).expect("test: encrypt mask"); + let config_path = dir.path().join("config.toml"); + std::fs::write( + &config_path, + format!( + "default_temperature = 0.7\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"openrouter\"\nmodel = \"m\"\napi_key = \"{encrypted_mask}\"\n\n[gateway]\npaired_tokens = [\"***\", \"sentinel-paired-ok\"]\n" + ), + ) + .expect("test: write config"); + + let _serial = fixture::LOG_CALLSITE_LOCK.blocking_lock(); + let sink = Sink::default(); + let subscriber = tracing_subscriber::fmt() + .with_writer(sink.clone()) + .with_max_level(tracing::Level::TRACE) + .with_ansi(false) + .finish(); + let loaded = tracing::subscriber::with_default(subscriber, || { + tracing::callsite::rebuild_interest_cache(); + crate::config::Config::load_from_path(&config_path, dir.path().join("workspace")) + }) + .expect("test: a stored mask must not stop the load"); + assert_eq!( + loaded.model_routes.first().and_then(|r| r.api_key.as_deref()), + Some(REDACTION_MASK) + ); + + let logs = String::from_utf8_lossy(&sink.0.lock()).to_string(); + assert!( + logs.contains("model_routes[0].api_key"), + "the stored mask must be reported: {logs}" + ); + assert!( + logs.contains("gateway.paired_tokens[0]"), + "the stored mask must be reported: {logs}" + ); + assert!( + !logs.contains("sentinel-paired-ok"), + "the warning must not carry a value: {logs}" + ); + assert!(!logs.contains("enc2:"), "the warning must not carry a value: {logs}"); + } + + /// F7, RED before PMMA-f: `Config`'s `Debug` redacted only the root key; + /// route, agent, rotation, tool, storage and channel secrets printed in + /// clear. After: every registry path is masked and ordinary values stay. + #[test] + fn config_debug_masks_every_registered_path() { + let dir = tempfile::TempDir::new().expect("test: temp config dir"); + let config = fixture::config_in(dir.path()); + let rendered = format!("{config:?}"); + assert!( + !rendered.contains(fixture::SENTINEL_PREFIX), + "Debug leaked a secret: {rendered}" + ); + assert!( + rendered.contains("model-test"), + "Debug must keep ordinary values: {rendered}" + ); + assert!( + rendered.contains("config_path"), + "Debug must keep the path fields: {rendered}" + ); + } + + #[test] + fn name_rule_masks_an_unregistered_credential_and_keeps_ordinary_values() { + let mut value = serde_json::json!({ + "future_section": { "client_secret": "sentinel-future", "enabled": true, "count": 3 }, + "default_model": "kimi-k2", + "nested": { "credential": { "username": "user", "password": "pass" } }, + }); + redact(&mut value); + assert_eq!( + value.pointer("/future_section/client_secret"), + Some(&serde_json::json!(REDACTION_MASK)) + ); + assert_eq!(value.pointer("/future_section/enabled"), Some(&serde_json::json!(true))); + assert_eq!(value.pointer("/default_model"), Some(&serde_json::json!("kimi-k2"))); + assert_eq!( + value.pointer("/nested/credential/username"), + Some(&serde_json::json!(REDACTION_MASK)) + ); + assert_eq!( + value.pointer("/nested/credential/password"), + Some(&serde_json::json!(REDACTION_MASK)) + ); + } + + /// Every configuration path that names a provider or an endpoint by URL. + /// Each value carries a distinct fixture password, so one search finds a + /// leak from any of them. + const USERINFO_TOML: &str = r#" +default_provider = "custom:http://alice:userinfo-sentinel-default@127.0.0.1:1/v1" +api_url = "http://alice:userinfo-sentinel-api-url@127.0.0.1:2/v1" + +[reliability] +fallback_providers = ["custom:https://bob:userinfo-sentinel-fallback@127.0.0.1:3/v1", "openrouter"] + +[[model_routes]] +hint = "fast" +provider = "custom:http://carol:userinfo-sentinel-route@127.0.0.1:4/v1" +model = "route-model" + +[[embedding_routes]] +hint = "semantic" +provider = "custom:http://dave:userinfo-sentinel-embedding@127.0.0.1:5/v1" +model = "embed-model" + +[agents.worker] +provider = "custom:http://erin:userinfo-sentinel-agent@127.0.0.1:6/v1" +model = "agent-model" + +[[providers.tool_dialects]] +provider = "custom:http://frank:userinfo-sentinel-dialect@127.0.0.1:7/v1" +tool_schema = "no_root_combinators" + +[smart_group] +classifier_provider = "custom:http://grace:userinfo-sentinel-classifier@127.0.0.1:8/v1" +"#; + + fn userinfo_config(dir: &std::path::Path) -> crate::config::Config { + let mut tree = toml::Value::try_from(crate::config::Config::default()).expect("test: default config tree"); + fixture::overlay( + &mut tree, + toml::from_str(USERINFO_TOML).expect("test: userinfo fixture parses"), + ); + let mut config: crate::config::Config = tree.try_into().expect("test: the userinfo fixture must deserialize"); + config.config_path = dir.join("config.toml"); + config.workspace_dir = dir.join("workspace"); + config + } + + /// R-C2Kf S-2: `prx config show` printed every provider label verbatim, + /// so a `custom:` URL's `user:password@` reached the terminal. The + /// endpoints stay readable; only their userinfo is replaced. + #[test] + fn config_show_redacts_url_userinfo_in_every_provider_and_endpoint_field() { + let dir = tempfile::TempDir::new().expect("test: temp config dir"); + let rendered = redacted_stored_toml(&userinfo_config(dir.path())) + .expect("test: config show rendering") + .to_string(); + assert!( + !rendered.contains("userinfo-sentinel"), + "config show leaked URL userinfo: {rendered}" + ); + for endpoint in [ + "custom:http://[redacted]@127.0.0.1:1/v1", + "http://[redacted]@127.0.0.1:2/v1", + "custom:https://[redacted]@127.0.0.1:3/v1", + "custom:http://[redacted]@127.0.0.1:4/v1", + "custom:http://[redacted]@127.0.0.1:5/v1", + "custom:http://[redacted]@127.0.0.1:6/v1", + "custom:http://[redacted]@127.0.0.1:7/v1", + "custom:http://[redacted]@127.0.0.1:8/v1", + ] { + assert!(rendered.contains(endpoint), "{endpoint} is missing from: {rendered}"); + } + assert!( + rendered.contains("\"openrouter\""), + "an ordinary label must stay: {rendered}" + ); + } diff --git a/src/config/secret_paths/tests/section_2.rs b/src/config/secret_paths/tests/section_2.rs new file mode 100644 index 000000000..102358211 --- /dev/null +++ b/src/config/secret_paths/tests/section_2.rs @@ -0,0 +1,365 @@ + /// A redacted label posted or written back is a mask: it must be found by + /// the scan that refuses masks, never stored as a provider. + #[test] + fn a_redacted_endpoint_label_counts_as_a_mask() { + let tree: toml::Value = toml::from_str( + "default_provider = \"custom:http://[redacted]@127.0.0.1:1/v1\"\n\ + [reliability]\nfallback_providers = [\"openrouter\", \"custom:http://[redacted]@h.invalid/v1\"]\n", + ) + .expect("test: masked tree parses"); + let masked: BTreeSet = scan(&tree).masked.into_iter().collect(); + assert_eq!( + masked, + BTreeSet::from([ + "default_provider".to_string(), + "reliability.fallback_providers[1]".to_string() + ]) + ); + // Userinfo is a secret value for scrubbing messages, and a file that + // holds one is served masked. + let raw: toml::Value = toml::from_str(USERINFO_TOML).expect("test: userinfo fixture parses"); + let found = scan(&raw); + assert!(found.has_secret_values()); + assert!( + !found + .scrub("rejected custom:http://alice:userinfo-sentinel-default@127.0.0.1:1/v1") + .contains("userinfo-sentinel") + ); + } + + /// R-C2BU F-3: the memory embedding provider also takes a `custom:` URL. + #[test] + fn config_show_redacts_url_userinfo_in_the_memory_embedding_provider() { + let mut tree: toml::Value = toml::from_str( + "[memory]\nembedding_provider = \"custom:https://u:userinfo-sentinel-embed@embed.invalid/v1\"\n", + ) + .expect("test: fixture parses"); + let found = scan(&tree); + assert!( + found.has_secret_values(), + "the userinfo must be a secret value for scrubbing" + ); + redact(&mut tree); + let rendered = tree.to_string(); + assert!(!rendered.contains("userinfo-sentinel"), "{rendered}"); + assert!( + rendered.contains("custom:https://[redacted]@embed.invalid/v1"), + "{rendered}" + ); + } + + /// D-027: two credential-bearing `[cost].prices` keys that redact to the + /// same spelling are a configuration error. The error names the keys in + /// their redacted form only. + #[test] + fn colliding_credentialed_price_keys_fail_validation_without_printing_credentials() { + let dir = tempfile::TempDir::new().expect("test: temp dir"); + let path = dir.path().join("config.toml"); + std::fs::write( + &path, + "default_temperature = 0.7\n\n[cost.prices.\"custom:http://alice:pwA-d027@h.invalid/v1/m\"]\ninput = 1.0\noutput = 1.0\n\n\ + [cost.prices.\"custom:http://bob:pwB-d027@h.invalid/v1/m\"]\ninput = 9.0\noutput = 9.0\n", + ) + .expect("test: write config"); + let error = crate::config::Config::load_from_path(&path, dir.path().join("workspace")) + .expect_err("test: colliding price keys must not load"); + let rendered = format!("{error:#}"); + assert!( + rendered.contains("custom:http://[redacted]@h.invalid/v1/m"), + "{rendered}" + ); + assert!(rendered.contains("cost.prices"), "{rendered}"); + assert!( + !rendered.contains("pwA-d027") && !rendered.contains("pwB-d027"), + "{rendered}" + ); + assert!(!rendered.contains("alice") && !rendered.contains("bob"), "{rendered}"); + + // Distinct endpoints, or one credentialed key, still load. + std::fs::write( + &path, + "default_temperature = 0.7\n\n[cost.prices.\"custom:http://alice:pwA-d027@h.invalid/v1/m\"]\ninput = 1.0\noutput = 1.0\n\n\ + [cost.prices.\"custom:http://bob:pwB-d027@other.invalid/v1/m\"]\ninput = 9.0\noutput = 9.0\n", + ) + .expect("test: write config"); + crate::config::Config::load_from_path(&path, dir.path().join("workspace")) + .expect("test: distinct endpoints load"); + } + + /// The `{:?}` of every table-valued section of `config`, by its key. + fn section_debug(config: &crate::config::Config) -> Vec<(&'static str, String)> { + macro_rules! sections { + ($($field:ident),* $(,)?) => { + vec![$((stringify!($field), format!("{:?}", config.$field))),*] + }; + } + sections!( + providers, + model_settings, + observability, + autonomy, + runtime, + reliability, + scheduler, + agent, + sessions_spawn, + chat, + self_system, + skills, + skill_rag, + plugins, + skills_lifecycle, + model_routes, + embedding_routes, + query_classification, + task_routing, + router, + smart_group, + heartbeat, + xin, + cron, + channels_config, + memory, + identity_bindings, + user_policies, + storage, + tunnel, + gateway, + webhook, + composio, + mcp, + mcp_server, + a2a, + auth, + secrets, + browser, + http_request, + multimodal, + web_search, + proxy, + identity, + cost, + nodes, + agents, + media, + decision_engine, + security, + compliance, + tool_tiering, + ) + } + + /// Provider labels with URL userinfo at the label paths the endpoint + /// fixture leaves out. + const LABEL_USERINFO_TOML: &str = r#" +[[router.models]] +provider = "custom:http://router:sentinel-label-router@127.0.0.1:31/v1" +model_id = "m" + +[[providers.models]] +provider = "custom:http://models:sentinel-label-models@127.0.0.1:32/v1" +model = "m" + +[[providers.tool_dialects]] +provider = "custom:http://dialect:sentinel-label-dialect@127.0.0.1:33/v1" +tool_schema = "raw" + +[memory] +embedding_provider = "custom:http://embed:sentinel-label-memory@127.0.0.1:34/v1" + +[smart_group] +classifier_provider = "custom:http://group:sentinel-label-group@127.0.0.1:35/v1" + +[[model_routes]] +hint = "fast" +provider = "custom:http://route:sentinel-label-route@127.0.0.1:36/v1" +model = "m" + +[reliability] +fallback_providers = ["custom:http://fallback:sentinel-label-fallback@127.0.0.1:37/v1"] + +[cost.prices."custom:http://price:sentinel-label-price@127.0.0.1:38/v1/m"] +input = 1.0 +output = 1.0 +"#; + + /// The display path of every table in `tree` that has a key carrying a + /// fixture sentinel (the value leaves alone miss a secret in a key). + fn sentinel_key_owners(tree: &toml::Value) -> BTreeSet { + fn walk(node: &toml::Value, path: &mut Vec, out: &mut BTreeSet) { + match node { + toml::Value::Table(table) => { + if table.keys().any(|key| key.contains(fixture::SENTINEL_PREFIX)) { + out.insert(display_path(path)); + } + for (key, child) in table { + path.push(PathElem::Key(key.clone())); + walk(child, path, out); + path.pop(); + } + } + toml::Value::Array(items) => { + for (index, child) in items.iter().enumerate() { + path.push(PathElem::Index(index)); + walk(child, path, out); + path.pop(); + } + } + _ => {} + } + } + let mut out = BTreeSet::new(); + walk(tree, &mut Vec::new(), &mut out); + out + } + + /// `{:?}` of the sub-struct that owns the value at `owner` (the display + /// path of a sentinel's parent), or `None` when no probe is written for it. + fn owner_debug(config: &crate::config::Config, owner: &str) -> Option { + fn d(value: &dyn std::fmt::Debug) -> String { + format!("{value:?}") + } + let c = config; + let channels = &c.channels_config; + Some(match owner { + "" => d(c), + "agents.worker" => d(c.agents.get("worker")?), + "model_routes[0]" => d(c.model_routes.first()?), + "embedding_routes[0]" => d(c.embedding_routes.first()?), + "reliability" | "reliability.api_keys" | "reliability.fallback_providers" => d(&c.reliability), + "composio" => d(&c.composio), + "browser.computer_use" => d(&c.browser.computer_use), + "web_search" => d(&c.web_search), + "storage.provider.config" => d(&c.storage.provider.config), + "gateway" | "gateway.paired_tokens" => d(&c.gateway), + "mcp.servers.local" | "mcp.servers.local.env" => d(c.mcp.servers.get("local")?), + "mcp.servers.remote" => d(c.mcp.servers.get("remote")?), + "channels_config.telegram" => d(channels.telegram.as_ref()?), + "channels_config.discord" => d(channels.discord.as_ref()?), + "channels_config.slack" => d(channels.slack.as_ref()?), + "channels_config.mattermost" => d(channels.mattermost.as_ref()?), + "channels_config.dingtalk" => d(channels.dingtalk.as_ref()?), + "channels_config.email" => d(channels.email.as_ref()?), + "channels_config.irc" => d(channels.irc.as_ref()?), + "channels_config.lark" => d(channels.lark.as_ref()?), + "channels_config.linq" => d(channels.linq.as_ref()?), + "channels_config.nextcloud_talk" => d(channels.nextcloud_talk.as_ref()?), + "channels_config.qq" => d(channels.qq.as_ref()?), + "channels_config.wacli" => d(channels.wacli.as_ref()?), + "channels_config.webhook" => d(channels.webhook.as_ref()?), + "channels_config.whatsapp" => d(channels.whatsapp.as_ref()?), + "channels_config.signal" => d(channels.signal.as_ref()?), + "webhook" => d(&c.webhook), + "tunnel.cloudflare" => d(c.tunnel.cloudflare.as_ref()?), + "tunnel.ngrok" => d(c.tunnel.ngrok.as_ref()?), + "tunnel.custom" => d(c.tunnel.custom.as_ref()?), + "chat.daemon" => d(&c.chat.daemon), + "decision_engine.backend" => d(c.decision_engine.backend.as_ref()?), + "nodes.nodes[0]" => d(c.nodes.nodes.first()?), + "nodes.server" => d(&c.nodes.server), + "proxy" => d(&c.proxy), + "observability" => d(&c.observability), + "media" => d(&c.media), + "mcp_server" => d(&c.mcp_server), + "a2a" => d(&c.a2a), + "router.models[0]" => d(c.router.models.first()?), + "providers.models[0]" => d(c.providers.models.first()?), + "providers.tool_dialects[0]" => d(c.providers.tool_dialects.first()?), + "memory" => d(&c.memory), + "smart_group" => d(&c.smart_group), + "cost.prices" => d(&c.cost), + _ => return None, + }) + } + + /// INT-2B a40 (R-PMMAf sub-struct Debug), RED before: the configuration + /// sub-structs derived `Debug`, so `{:?}` of a model route, a channel + /// config or a delegate agent printed its key, and of an endpoint its URL + /// password. After: for every sentinel of the registry fixture, the + /// endpoint fixture and a provider-label fixture, `{:?}` of the sub-struct + /// that owns it prints no sentinel (a sentinel whose owner has no probe + /// fails the test), and neither does `{:?}` of any table-valued section. + #[test] + fn no_configuration_struct_debug_prints_a_secret() { + let dir = tempfile::TempDir::new().expect("test: temp dir"); + let mut unprobed = BTreeSet::new(); + let mut leaks = BTreeSet::new(); + for overlay in [fixture::TOML, fixture::ENDPOINT_USERINFO_TOML, LABEL_USERINFO_TOML] { + let config = fixture::config_from_overlay(dir.path(), overlay); + let tree: toml::Value = toml::from_str(overlay).expect("test: overlay parses"); + let sentinels = fixture::string_leaves(&tree, &|value| value.contains(fixture::SENTINEL_PREFIX)); + assert!(!sentinels.is_empty()); + // A secret in a map key (a credentialed `cost.prices` key) is + // owned by the struct that holds the map. + let key_owners = sentinel_key_owners(&tree); + let owners = sentinels + .into_iter() + .map(|path| { + let mut owner = path; + if matches!(owner.pop(), Some(PathElem::Index(_))) { + owner.pop(); + } + display_path(&owner) + }) + .chain(key_owners); + for owner in owners { + match owner_debug(&config, &owner) { + Some(rendered) if rendered.contains(fixture::SENTINEL_PREFIX) => { + leaks.insert(owner); + } + Some(_) => {} + None => { + unprobed.insert(owner); + } + } + } + + let sections = section_debug(&config); + let serialized = serde_json::to_value(&config).expect("test: serialize"); + let probed: BTreeSet<&str> = sections.iter().map(|(name, _)| *name).collect(); + for (key, value) in serialized.as_object().expect("test: config is an object") { + if value.is_object() || value.is_array() { + assert!(probed.contains(key.as_str()), "section `{key}` has no Debug probe"); + } + } + for (name, rendered) in §ions { + if rendered.contains(fixture::SENTINEL_PREFIX) { + leaks.insert((*name).to_string()); + } + } + } + assert!(unprobed.is_empty(), "add a Debug probe for: {unprobed:?}"); + assert!(leaks.is_empty(), "these print a secret with {{:?}}: {leaks:?}"); + } + + /// INT-2B a41 (R-PMMAf R5, D-056 DC-4), RED before: a commented-out + /// credential was found only as `name = value` with the exact credential + /// name, so `# api-key = …`, `# apikey = …` and `# token: …` were served + /// verbatim. After: `-` reads as `_`, `apikey` counts, and `:` separates + /// like `=`. Ordinary comments still do not count. + #[test] + fn a_commented_credential_is_found_in_its_common_spellings() { + for text in [ + "# api-key = \"sk-old\"", + "# apikey = \"sk-old\"", + "# OpenAI-ApiKey = \"sk-old\"", + "# api_key: sk-old", + "#token: abc", + "model = \"m\" # bot-token: abc", + "# Password = hunter2", + "# api_key = \"sk-old\"", + "# note: api_key = \"sk-old\"", + ] { + assert!(has_commented_secret(text), "{text:?} must count as a commented secret"); + } + for text in [ + "# see the API documentation", + "# key points: none", + "# timeout = 5", + "# model: gpt-4o", + "# http://example.invalid/a=b", + "default_model = \"m\"", + ] { + assert!(!has_commented_secret(text), "{text:?} is an ordinary comment"); + } + } diff --git a/src/doctor/implementation/section_1.rs b/src/doctor/implementation/section_1.rs new file mode 100644 index 000000000..123b7e67d --- /dev/null +++ b/src/doctor/implementation/section_1.rs @@ -0,0 +1,1445 @@ + + + + +use crate::config::Config; +use anyhow::{Context, Result}; +use chrono::{DateTime, Utc}; +use std::collections::HashSet; +use std::net::TcpStream; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +pub use ingress::{diagnose_ingress, run_ingress}; +const DAEMON_STALE_SECONDS: i64 = 30; +const SCHEDULER_STALE_SECONDS: i64 = 120; +const CHANNEL_STALE_SECONDS: i64 = 300; +const COMMAND_VERSION_PREVIEW_CHARS: usize = 60; + +// ── Diagnostic item ────────────────────────────────────────────── + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Severity { + Ok, + Warn, + Error, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum DiagnosticState { + Declared, + Configured, + Ready, + Healthy, + Disabled, + Unknown, +} + +#[derive(Debug, Clone)] +pub struct DiagItem { + pub severity: Severity, + pub state: DiagnosticState, + pub category: &'static str, + pub message: String, +} + +impl DiagItem { + fn ok(category: &'static str, msg: impl Into) -> Self { + Self::with_state(Severity::Ok, DiagnosticState::Healthy, category, msg) + } + fn healthy(category: &'static str, msg: impl Into) -> Self { + Self::ok(category, msg) + } + fn declared(category: &'static str, msg: impl Into) -> Self { + Self::with_state(Severity::Ok, DiagnosticState::Declared, category, msg) + } + fn configured(category: &'static str, msg: impl Into) -> Self { + Self::with_state(Severity::Ok, DiagnosticState::Configured, category, msg) + } + fn ready(category: &'static str, msg: impl Into) -> Self { + Self::with_state(Severity::Ok, DiagnosticState::Ready, category, msg) + } + fn disabled(category: &'static str, msg: impl Into) -> Self { + Self::with_state(Severity::Ok, DiagnosticState::Disabled, category, msg) + } + fn unknown(category: &'static str, msg: impl Into) -> Self { + Self::with_state(Severity::Warn, DiagnosticState::Unknown, category, msg) + } + /// Every item is built here, so this is the one place a message is made + /// safe to print: doctor quotes configured provider labels and endpoint + /// URLs, and a `custom:` URL may carry `user:password@`. + fn with_state(severity: Severity, state: DiagnosticState, category: &'static str, msg: impl Into) -> Self { + let message = crate::security::redaction::redact_secrets(&msg.into()); + let message = match crate::security::redaction::redact_url_components(&message) { + std::borrow::Cow::Borrowed(_) => message, + std::borrow::Cow::Owned(redacted) => redacted, + }; + Self { + severity, + state, + category, + message, + } + } + fn warn(category: &'static str, msg: impl Into) -> Self { + Self::with_state(Severity::Warn, DiagnosticState::Unknown, category, msg) + } + fn error(category: &'static str, msg: impl Into) -> Self { + Self::with_state(Severity::Error, DiagnosticState::Unknown, category, msg) + } + + const fn icon(&self) -> &'static str { + match self.severity { + Severity::Ok => "✅", + Severity::Warn => "⚠️ ", + Severity::Error => "❌", + } + } + + const fn state_label(&self) -> &'static str { + match self.state { + DiagnosticState::Declared => "DECLARED", + DiagnosticState::Configured => "CONFIGURED", + DiagnosticState::Ready => "READY", + DiagnosticState::Healthy => "HEALTHY", + DiagnosticState::Disabled => "DISABLED", + DiagnosticState::Unknown => "UNKNOWN", + } + } +} + +#[derive(Debug, Clone)] +pub struct DoctorReport { + pub title: &'static str, + pub items: Vec, + pub ok_count: usize, + pub warning_count: usize, + pub error_count: usize, +} + +impl DoctorReport { + fn new(title: &'static str, items: Vec) -> Self { + let ok_count = items.iter().filter(|item| item.severity == Severity::Ok).count(); + let warning_count = items.iter().filter(|item| item.severity == Severity::Warn).count(); + let error_count = items.iter().filter(|item| item.severity == Severity::Error).count(); + Self { + title, + items, + ok_count, + warning_count, + error_count, + } + } + + pub const fn has_errors(&self) -> bool { + self.error_count > 0 + } + + fn print(&self) { + println!("🩺 {}", self.title); + println!(); + + let mut current_cat = ""; + for item in &self.items { + if item.category != current_cat { + current_cat = item.category; + println!(" [{current_cat}]"); + } + println!(" {} [{}] {}", item.icon(), item.state_label(), item.message); + } + + println!(); + println!( + " Summary: {} ok, {} warnings, {} errors", + self.ok_count, self.warning_count, self.error_count + ); + if self.has_errors() { + println!(" 💡 Fix the errors above, then run `prx doctor` again."); + } + } + + fn ensure_success(&self) -> Result<()> { + if self.has_errors() { + anyhow::bail!("doctor found {} error(s)", self.error_count); + } + Ok(()) + } +} + +// ── Public entry point ─────────────────────────────────────────── + +pub fn run(config: &Config) -> Result<()> { + let report = diagnose(config); + report.print(); + report.ensure_success() +} + +pub fn diagnose(config: &Config) -> DoctorReport { + let mut items: Vec = Vec::new(); + + check_config_semantics(config, &mut items); + check_model_selection(config, &mut items); + check_persisted_selections(config, &mut items); + #[cfg(feature = "llm-router")] + check_router_candidates(config, &mut items); + check_decision_plane(config, &mut items); + check_workspace(config, &mut items); + ingress::check_recovery_authority(config, &mut items); + workers::check_retained_worker_folders(config, &mut items); + check_legacy_fitness_telemetry(config, &mut items); + check_workspace_mcp_servers(config, &mut items); + check_workspace_hooks(config, &mut items); + check_unowned_shell_jobs(config, &mut items); + check_unfinished_config_changes(config, &mut items); + check_daemon_state(config, &mut items); + prompt_cache::check_prompt_cache(config, &mut items); + decision_engine::check(config, &mut items); + provider_circuits::check_provider_circuits(config, &mut items); + check_daemon_process_path(config, &mut items); + check_environment(&mut items); + + DoctorReport::new("OpenPRX Doctor", items) +} + +pub fn run_memory(config: &Config) -> Result<()> { + let report = diagnose_memory(config); + report.print(); + report.ensure_success() +} + +pub fn diagnose_memory(config: &Config) -> DoctorReport { + let mut items: Vec = Vec::new(); + check_memory_diagnostics(config, &mut items); + check_legacy_fitness_telemetry(config, &mut items); + DoctorReport::new("OpenPRX Doctor - Memory", items) +} + +/// Workspace command hooks (HOOKS-ENV): a `hooks.json` whose commands do +/// not run because `security.workspace_hooks` is off is named, with the one +/// line that allows them. Reads the file only. +fn check_workspace_hooks(config: &Config, items: &mut Vec) { + let category = "hooks"; + match crate::hooks::workspace_hook_actions(&config.workspace_dir) { + Ok(None | Some(0)) => items.push(DiagItem::healthy(category, "no workspace command hooks")), + Ok(Some(actions)) if config.security.workspace_hooks == crate::config::WorkspaceHooks::On => { + items.push(DiagItem::ok( + category, + format!( + "{actions} workspace command hook(s) run (security.workspace_hooks = \"on\"), in a cleared \ + environment and a dedicated directory beside config.toml" + ), + )) + } + Ok(Some(actions)) => { + if let Some(note) = crate::hooks::blocked_hooks_note(actions) { + items.push(DiagItem::warn(category, note)); + } + } + Err(error) => items.push(DiagItem::warn( + category, + format!("the workspace hooks.json is not valid: {error:#}"), + )), + } +} + +/// Shell jobs stored before PRX recorded who creates them (D-107 +/// amendment): they count as agent-created, so a command that runs git is +/// refused. Each is named with the one command that vouches for it. Opens +/// the stores read-only and runs no migration: a store whose table predates +/// the `created_via` column has only such rows. +fn check_unowned_shell_jobs(config: &Config, items: &mut Vec) { + let category = "git"; + let cron_in_postgres = config + .storage + .provider + .config + .provider + .trim() + .eq_ignore_ascii_case("postgres"); + let mut sources = vec![( + "xin shell task", + "prx xin mark-operator", + config.workspace_dir.join("xin").join("tasks.db"), + "xin_tasks", + "SELECT id, payload FROM xin_tasks + WHERE execution_mode = 'shell' AND kind <> 'system' AND created_via IS NULL ORDER BY id", + "SELECT id, payload FROM xin_tasks WHERE execution_mode = 'shell' AND kind <> 'system' ORDER BY id", + )]; + if cron_in_postgres { + items.push(DiagItem::ok( + category, + "cron jobs are stored in Postgres and not inspected here; a shell job created before PRX recorded its \ + creator runs no git until `prx cron mark-operator `", + )); + } else { + sources.push(( + "cron shell job", + "prx cron mark-operator", + config.workspace_dir.join("cron").join("jobs.db"), + "cron_jobs", + "SELECT id, command FROM cron_jobs WHERE job_type = 'shell' AND created_via IS NULL ORDER BY id", + "SELECT id, command FROM cron_jobs WHERE job_type = 'shell' ORDER BY id", + )); + } + let mut found = 0_usize; + for (what, mark, db_path, table, unowned_sql, legacy_sql) in sources { + match read_only_unowned_rows(&db_path, table, unowned_sql, legacy_sql) { + Ok(rows) => { + for (id, _) in rows { + found += 1; + items.push(DiagItem::warn( + category, + format!( + "{what} {id} predates creator tracking and counts as agent-created, so git in it is \ + refused; if you created it: `{mark} {id}`" + ), + )); + } + } + Err(error) => items.push(DiagItem::warn( + category, + format!("the {what}s could not be read: {error:#}"), + )), + } + } + if found == 0 { + items.push(DiagItem::healthy(category, "every shell job records who created it")); + } +} + +/// `(id, command)` of the shell rows of `table` whose `created_via` is NULL +/// (`unowned_sql`), or all of them (`legacy_sql`) when the column does not +/// exist yet; read-only, and empty when the database or the table is +/// missing. +fn read_only_unowned_rows( + db_path: &Path, + table: &str, + unowned_sql: &str, + legacy_sql: &str, +) -> Result> { + if !db_path.is_file() { + return Ok(Vec::new()); + } + let connection = rusqlite::Connection::open_with_flags(db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?; + let table_exists: bool = connection.query_row( + "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?1)", + [table], + |row| row.get(0), + )?; + if !table_exists { + return Ok(Vec::new()); + } + let has_creator: bool = connection.query_row( + "SELECT EXISTS(SELECT 1 FROM pragma_table_info(?1) WHERE name = 'created_via')", + [table], + |row| row.get(0), + )?; + let mut statement = connection.prepare(if has_creator { unowned_sql } else { legacy_sql })?; + let rows = statement.query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)))?; + Ok(rows.collect::, _>>()?) +} + +/// Unfinished configuration changes (SP-PMM §2.6, D-095 L-3): a `pending` +/// history record (the process stopped between commit and activation) or a +/// `not_restored` one (a refused change whose restore failed). Nothing is +/// applied automatically; the operator decides. Reads the history only. +fn check_unfinished_config_changes(config: &Config, items: &mut Vec) { + use crate::config::manage::{ConfigHistory, RecordStatus}; + let category = "config"; + let records = match ConfigHistory::for_config(&config.config_path).and_then(|history| history.list()) { + Ok(records) => records, + Err(error) => { + items.push(DiagItem::warn( + category, + format!("configuration history could not be read: {error:#}"), + )); + return; + } + }; + // A change `prx` wrote that a later write replaced before a running PRX + // settled it (D-101 F-7): superseded, never activated. + let current = crate::config::files::current_config_revision(&config.config_path).ok(); + for record in records.iter().filter(|record| { + record.status == RecordStatus::Superseded + || (record.status == RecordStatus::ActivationDeferred + && current.is_some() + && record.committed_revision != current) + }) { + items.push(DiagItem::warn( + category, + format!( + "configuration change {} written by `prx` was replaced by a later write before a running PRX \ + settled it (superseded); inspect it with `prx config history show {}`", + record.id, record.id + ), + )); + } + let unfinished = records + .iter() + .filter(|record| matches!(record.status, RecordStatus::Pending | RecordStatus::NotRestored)) + .collect::>(); + if unfinished.is_empty() { + items.push(DiagItem::healthy(category, "no unfinished configuration change")); + return; + } + for record in unfinished { + items.push(DiagItem::warn( + category, + format!( + "configuration change {} is {} (the process stopped, or a restore failed); it is never applied \ + automatically: inspect it with `prx config history show {}` and restore the configuration from \ + before it with `prx config rollback {} --yes`", + record.id, + record.status.as_str(), + record.id, + record.id + ), + )); + } +} + +/// Every workspace `mcp.json` entry that did not start as written (blocked +/// by `mcp.workspace_servers`, disabled, or trimmed), with its one-line +/// remedy (D-088 C-7). Reads the file only; starts nothing. +fn check_workspace_mcp_servers(config: &Config, items: &mut Vec) { + let category = "mcp"; + let notes = crate::tools::mcp::workspace_server_notes(&config.mcp, &config.workspace_dir, config.autonomy.level); + if notes.is_empty() { + items.push(DiagItem::healthy( + category, + "no workspace mcp.json server is blocked or disabled", + )); + } + for note in notes { + items.push(DiagItem::warn(category, note)); + } + // An operator's `working_dir` inside the agent's workspace lets the + // workspace file tools plant files the server loads at start (a + // `.npmrc`, a shadowing module): allowed, but worth saying (D-095 N-4). + let mut servers = config.mcp.servers.iter().collect::>(); + servers.sort_by(|left, right| left.0.cmp(right.0)); + for (name, server) in servers { + if let Some(dir) = server.working_dir.as_deref() { + if std::path::Path::new(dir.trim()).starts_with(&config.workspace_dir) { + items.push(DiagItem::warn( + category, + format!( + "server '{}' starts in {}, inside the agent's workspace: the workspace file tools can \ + change what it loads there; prefer a directory outside the workspace, or leave \ + `working_dir` unset for its dedicated one", + name.escape_default(), + dir.trim() + ), + )); + } + } + } +} + +fn check_legacy_fitness_telemetry(config: &Config, items: &mut Vec) { + const PREFIX: &str = "self/fitness/daily/"; + let category = "fitness"; + match legacy_fitness_counts(config, PREFIX) { + Ok((database, memory_projection, snapshot_projection)) => { + let total = database + memory_projection + snapshot_projection; + if total == 0 { + items.push(DiagItem::healthy( + category, + "legacy fitness telemetry absent from memory storage and projections", + )); + } else { + items.push(DiagItem::warn( + category, + format!( + "legacy fitness telemetry detected: database={database}, MEMORY.md={memory_projection}, \ + MEMORY_SNAPSHOT.md={snapshot_projection}; run `prx fitness migrate-legacy --apply`" + ), + )); + } + } + Err(error) => items.push(DiagItem::warn( + category, + format!("legacy fitness telemetry inspection failed: {error}"), + )), + } +} + +fn legacy_fitness_counts(config: &Config, prefix: &str) -> Result<(usize, usize, usize)> { + let backend = + crate::memory::effective_memory_backend_name(&config.memory.backend, Some(&config.storage.provider.config)); + let database = match crate::memory::classify_memory_backend(&backend) { + crate::memory::MemoryBackendKind::Sqlite | crate::memory::MemoryBackendKind::Lucid => { + read_only_sqlite_key_prefix_count(&crate::schema_migration::memory_db_path(config), prefix)? + } + crate::memory::MemoryBackendKind::Postgres => { + let storage = &config.storage.provider.config; + let db_url = storage + .db_url + .as_deref() + .map(str::trim) + .filter(|value| !value.is_empty()) + .context("postgres fitness inspection requires storage.provider.config.db_url")?; + crate::memory::PostgresMemory::read_key_prefix_read_only( + db_url, + &storage.schema, + &storage.table, + storage.connect_timeout_secs, + prefix, + )? + .len() + } + crate::memory::MemoryBackendKind::Markdown | crate::memory::MemoryBackendKind::None => 0, + crate::memory::MemoryBackendKind::Unknown => { + anyhow::bail!("unsupported configured memory backend '{backend}'") + } + }; + let memory_projection = count_projection_lines(&config.workspace_dir.join("MEMORY.md"), |line| { + line.strip_prefix("- [") + .and_then(|rest| rest.split_once("] **")) + .and_then(|(_, rest)| rest.split_once("**:")) + .is_some_and(|(key, _)| key.starts_with(prefix)) + })?; + let snapshot_projection = count_projection_lines( + &config.workspace_dir.join(crate::memory::snapshot::SNAPSHOT_FILENAME), + |line| { + line.strip_prefix("### 🔑 `") + .and_then(|rest| rest.strip_suffix('`')) + .is_some_and(|key| key.starts_with(prefix)) + }, + )?; + Ok((database, memory_projection, snapshot_projection)) +} + +fn read_only_sqlite_key_prefix_count(db_path: &Path, prefix: &str) -> Result { + if !db_path.is_file() { + return Ok(0); + } + let connection = rusqlite::Connection::open_with_flags(db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?; + let table_exists: bool = connection.query_row( + "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'memories')", + [], + |row| row.get(0), + )?; + if !table_exists { + return Ok(0); + } + let escaped = prefix.replace('\\', "\\\\").replace('%', "\\%").replace('_', "\\_"); + let pattern = format!("{escaped}%"); + let count: i64 = connection.query_row( + "SELECT COUNT(*) FROM memories WHERE key LIKE ?1 ESCAPE '\\'", + [pattern], + |row| row.get(0), + )?; + usize::try_from(count).context("SQLite returned a negative legacy fitness count") +} + +fn count_projection_lines(path: &Path, matches: impl Fn(&str) -> bool) -> Result { + match std::fs::read_to_string(path) { + Ok(content) => Ok(content.lines().filter(|line| matches(line)).count()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(0), + Err(error) => Err(error.into()), + } +} + +pub async fn run_runtime(config: &Config) -> Result<()> { + let report = diagnose_runtime(config).await; + report.print(); + report.ensure_success() +} + +pub async fn diagnose_runtime(config: &Config) -> DoctorReport { + let mut items: Vec = Vec::new(); + check_deployed_binary(&mut items); + check_runtime_config(config, &mut items); + check_daemon_state(config, &mut items); + prompt_cache::check_prompt_cache(config, &mut items); + decision_engine::check(config, &mut items); + provider_circuits::check_provider_circuits(config, &mut items); + check_daemon_process_path(config, &mut items); + check_gateway_runtime(config, &mut items); + check_channel_runtime(config, &mut items); + check_console_runtime(config, &mut items); + check_runtime_memory_health(config, &mut items); + check_runtime_readiness(config, &mut items); + check_postgres_health(config, &mut items).await; + check_embedding_endpoint(config, &mut items).await; + DoctorReport::new("OpenPRX Doctor - Runtime Matrix", items) +} + +fn check_deployed_binary(items: &mut Vec) { + check_deployed_binary_paths(items, deployed_binary_from_path(), std::env::current_exe()); +} + +fn deployed_binary_from_path() -> Option { + let path = std::env::var_os("PATH")?; + let binary_name = format!("prx{}", std::env::consts::EXE_SUFFIX); + std::env::split_paths(&path) + .map(|directory| directory.join(&binary_name)) + .find(|candidate| candidate.is_file()) +} + +fn same_executable_path(left: &Path, right: &Path) -> bool { + match (left.canonicalize(), right.canonicalize()) { + (Ok(left), Ok(right)) => left == right, + _ => left == right, + } +} + +fn check_deployed_binary_paths( + items: &mut Vec, + deployed: Option, + current: std::io::Result, +) { + let cat = "deployed"; + let Some(deployed) = deployed else { + items.push(DiagItem::error(cat, "deployed prx binary not found on PATH")); + if let Ok(current) = current { + items.push(DiagItem::warn( + cat, + format!( + "doctor is running from {}, but no deployed prx binary was found on PATH", + current.display() + ), + )); + } + return; + }; + + if deployed.is_file() { + items.push(DiagItem::ok( + cat, + format!("deployed binary exists: {}", deployed.display()), + )); + } else { + items.push(DiagItem::error( + cat, + format!("deployed binary missing: {}", deployed.display()), + )); + } + + match current { + Ok(current) if same_executable_path(¤t, &deployed) => { + items.push(DiagItem::ok(cat, "doctor is running from deployed binary")); + } + Ok(current) => items.push(DiagItem::warn( + cat, + format!("doctor is running from {}, not deployed binary", current.display()), + )), + Err(error) => items.push(DiagItem::warn( + cat, + format!("cannot resolve current executable: {error}"), + )), + } +} + +fn check_runtime_config(config: &Config, items: &mut Vec) { + let cat = "config"; + if config.config_path.exists() { + items.push(DiagItem::configured( + cat, + format!("config path exists: {}", config.config_path.display()), + )); + } else { + items.push(DiagItem::error( + cat, + format!("config path missing: {}", config.config_path.display()), + )); + } + if config.workspace_dir.exists() { + items.push(DiagItem::configured( + cat, + format!("workspace exists: {}", config.workspace_dir.display()), + )); + } else { + items.push(DiagItem::error( + cat, + format!("workspace missing: {}", config.workspace_dir.display()), + )); + } +} + +fn check_gateway_runtime(config: &Config, items: &mut Vec) { + let cat = "gateway"; + items.push(DiagItem::configured( + cat, + format!( + "configured bind {}:{} (pairing required: {})", + config.gateway.host, config.gateway.port, config.gateway.require_pairing + ), + )); + + let address = format!("{}:{}", config.gateway.host, config.gateway.port); + match crate::tools::http_request::lookup_host_blocking(&config.gateway.host, config.gateway.port) + .ok() + .and_then(|addrs| addrs.into_iter().next()) + { + Some(socket) => match TcpStream::connect_timeout(&socket, Duration::from_millis(300)) { + Ok(_) => items.push(DiagItem::ok(cat, format!("gateway port reachable at {socket}"))), + Err(error) => items.push(DiagItem::warn( + cat, + format!("gateway port not reachable at {socket}: {error}"), + )), + }, + None => items.push(DiagItem::warn( + cat, + format!("cannot resolve gateway bind address {address}"), + )), + } +} + +fn check_channel_runtime(config: &Config, items: &mut Vec) { + let cat = "channels"; + let configured = configured_channel_names(config); + if configured.is_empty() { + items.push(DiagItem::warn(cat, "no IM channels are configured")); + } else { + items.push(DiagItem::configured( + cat, + format!("configured channels: {}", configured.join(", ")), + )); + } +} + +fn configured_channel_names(config: &Config) -> Vec<&'static str> { + let mut names = Vec::new(); + if config.channels_config.cli { + names.push("cli"); + } + if config.channels_config.telegram.is_some() { + names.push("telegram"); + } + if config.channels_config.discord.is_some() { + names.push("discord"); + } + if config.channels_config.slack.is_some() { + names.push("slack"); + } + if config.channels_config.webhook.is_some() { + names.push("webhook"); + } + if config.channels_config.signal.is_some() { + names.push("signal"); + } + if config.channels_config.whatsapp.is_some() { + names.push("whatsapp"); + } + if config.channels_config.wacli.is_some() { + names.push("wacli"); + } + if config.channels_config.nextcloud_talk.is_some() { + names.push("nextcloud-talk"); + } + if config.channels_config.email.is_some() { + names.push("email"); + } + if config.channels_config.irc.is_some() { + names.push("irc"); + } + if config.channels_config.lark.is_some() { + names.push("lark"); + } + names +} + +fn check_console_runtime(config: &Config, items: &mut Vec) { + let cat = "console"; + let backend = + crate::memory::effective_memory_backend_name(&config.memory.backend, Some(&config.storage.provider.config)); + match crate::memory::classify_memory_backend(&backend) { + crate::memory::MemoryBackendKind::Sqlite | crate::memory::MemoryBackendKind::Lucid => { + let db_path = crate::schema_migration::memory_db_path(config); + match read_only_sqlite_session_count(&db_path) { + Ok(Some(0)) => items.push(DiagItem::ready(cat, "no persisted console/channel sessions found")), + Ok(Some(count)) => items.push(DiagItem::healthy( + cat, + format!("persisted conversation sessions visible: {count}"), + )), + Ok(None) => items.push(DiagItem::unknown( + cat, + "sessions table is not present; session visibility is unknown", + )), + Err(error) => items.push(DiagItem::error( + cat, + format!("read-only console session probe failed: {error}"), + )), + } + } + crate::memory::MemoryBackendKind::Postgres => items.push(DiagItem::unknown( + cat, + "PostgreSQL console session count is not inferred; backend health is probed separately", + )), + crate::memory::MemoryBackendKind::Markdown | crate::memory::MemoryBackendKind::None => { + items.push(DiagItem::disabled( + cat, + format!("backend '{backend}' does not provide durable conversation sessions"), + )); + } + crate::memory::MemoryBackendKind::Unknown if backend.starts_with("wasm:") => items.push(DiagItem::unknown( + cat, + format!("WASM backend '{backend}' conversation persistence is defined by the plugin"), + )), + crate::memory::MemoryBackendKind::Unknown => items.push(DiagItem::error( + cat, + format!("unknown configured memory backend '{backend}'"), + )), + } +} + +fn check_runtime_memory_health(config: &Config, items: &mut Vec) { + let cat = "memory"; + let backend = + crate::memory::effective_memory_backend_name(&config.memory.backend, Some(&config.storage.provider.config)); + match crate::memory::classify_memory_backend(&backend) { + crate::memory::MemoryBackendKind::None => { + items.push(DiagItem::disabled(cat, "memory backend explicitly disabled")); + } + crate::memory::MemoryBackendKind::Markdown => { + if config.workspace_dir.is_dir() { + items.push(DiagItem::ready( + cat, + "markdown memory workspace is readable; no write probe performed", + )); + } else { + items.push(DiagItem::error(cat, "markdown memory workspace is missing")); + } + } + crate::memory::MemoryBackendKind::Sqlite + | crate::memory::MemoryBackendKind::Lucid + | crate::memory::MemoryBackendKind::Postgres => { + match crate::schema_migration::inspect_configured_backend(config) { + Ok(report) if report.status.pending.is_empty() => items.push(DiagItem::healthy( + cat, + format!( + "{} backend authoritative ledger verified ({} migrations)", + report.backend, + report.status.applied.len() + ), + )), + Ok(report) => items.push(DiagItem::with_state( + Severity::Warn, + DiagnosticState::Ready, + cat, + format!( + "{} backend ledger is readable with {} pending migration(s)", + report.backend, + report.status.pending.len() + ), + )), + Err(error) => items.push(DiagItem::error( + cat, + format!("read-only {backend} backend probe failed: {error}"), + )), + } + } + crate::memory::MemoryBackendKind::Unknown if backend.starts_with("wasm:") => { + items.push(DiagItem::ready( + cat, + format!("WASM memory backend '{backend}' will be health-checked by the live plugin runtime"), + )); + } + crate::memory::MemoryBackendKind::Unknown => { + items.push(DiagItem::error( + cat, + format!("unknown configured memory backend '{backend}'"), + )); + } + } +} + +fn read_only_sqlite_session_count(db_path: &Path) -> Result> { + if !db_path.is_file() { + anyhow::bail!("memory database is missing at {}", db_path.display()); + } + let conn = rusqlite::Connection::open_with_flags(db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?; + let exists: bool = conn.query_row( + "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sessions')", + [], + |row| row.get(0), + )?; + if !exists { + return Ok(None); + } + conn.query_row("SELECT COUNT(*) FROM sessions", [], |row| row.get(0)) + .map(Some) + .map_err(Into::into) +} + +/// FIX-P2-06: Read-only runtime readiness sub-checks. +/// +/// Each verifies that the configuration is internally consistent enough for the +/// corresponding subsystem to operate: owner ACL, topic scoping, task lineage, +/// document ingest, vector index, and the runtime-control ladder. These are +/// config-derived probes only -- they do not open the database or touch the +/// network. +fn check_runtime_readiness(config: &Config, items: &mut Vec) { + let cat = "readiness"; + let mem = &config.memory; + let backend = mem.backend.trim().to_ascii_lowercase(); + let persistent = !matches!(backend.as_str(), "none" | "markdown"); + let embeddings_enabled = !mem.embedding_provider.trim().eq_ignore_ascii_case("none"); + + // 1. owner readiness: ACL enforcement requires a persistent backend. + if !mem.acl_enabled { + items.push(DiagItem::warn( + cat, + "owner: memory.acl_enabled is false; owner/topic scoping is not enforced", + )); + } else if persistent { + items.push(DiagItem::ready(cat, "owner: ACL enforced on a persistent backend")); + } else { + items.push(DiagItem::warn( + cat, + format!("owner: ACL enabled but backend '{backend}' does not persist owner scopes"), + )); + } + + // 2. topic readiness: similarity/semantic scoping needs a persistent + // backend and embeddings. + if persistent && embeddings_enabled && mem.embedding_dimensions > 0 { + let mode = if mem.embedding_provider.trim().eq_ignore_ascii_case("local") { + "local similarity" + } else { + "semantic" + }; + items.push(DiagItem::ready( + cat, + format!("topic: {mode} topic scoping ready (dim {})", mem.embedding_dimensions), + )); + } else if !persistent { + items.push(DiagItem::warn( + cat, + format!("topic: backend '{backend}' does not persist topic scopes"), + )); + } else { + items.push(DiagItem::warn( + cat, + "topic: embeddings disabled; topic/semantic scoping falls back to keyword search", + )); + } + + items.push(DiagItem::ready(cat, "task: lifecycle/task event recording always on")); + + // 4. document readiness: document ingest needs a persistent backend. + if persistent { + items.push(DiagItem::ready(cat, "document: ingest backed by a persistent store")); + } else { + items.push(DiagItem::warn( + cat, + format!("document: backend '{backend}' does not persist ingested documents"), + )); + } + + // 5. vector readiness: vector recall needs embeddings + a sane dimension. + if !persistent { + items.push(DiagItem::warn( + cat, + format!("vector: backend '{backend}' does not persist a vector index"), + )); + } else if !embeddings_enabled { + items.push(DiagItem::warn( + cat, + "vector: embeddings disabled; vector recall unavailable (keyword/FTS only)", + )); + } else if mem.embedding_dimensions == 0 { + items.push(DiagItem::error( + cat, + "vector: embedding_dimensions is zero while embeddings are enabled", + )); + } else { + items.push(DiagItem::ready( + cat, + format!("vector: index ready (dim {})", mem.embedding_dimensions), + )); + } + + // 6. runtime-control readiness: autonomy posture is resolvable. + items.push(DiagItem::ready( + cat, + format!( + "runtime-control: control ladder ready (autonomy {:?})", + config.autonomy.level + ), + )); +} + +/// FIX-P2-07: Checks Postgres backend health when a Postgres backend is +/// selected: validates the DSN, runs `SELECT 1` under a 5s timeout, verifies the +/// `vector` (pgvector) extension is installed, and performs a lightweight column +/// parity probe against `information_schema`. Skips cleanly (no error) when +/// Postgres is not configured. +async fn check_postgres_health(config: &Config, items: &mut Vec) { + let cat = "postgres"; + let storage = &config.storage.provider.config; + let selects_postgres = storage.provider.trim().eq_ignore_ascii_case("postgres") + || config.memory.backend.trim().eq_ignore_ascii_case("postgres"); + if !selects_postgres { + // Not configured for Postgres -- nothing to check. + return; + } + + let Some(db_url) = storage.db_url.clone() else { + items.push(DiagItem::error( + cat, + "postgres backend selected but [storage.provider.config] db_url is unset", + )); + return; + }; + + // Validate the DSN scheme before attempting a connection. + let trimmed = db_url.trim(); + if !(trimmed.starts_with("postgres://") || trimmed.starts_with("postgresql://")) { + items.push(DiagItem::error( + cat, + "db_url must start with postgres:// or postgresql://", + )); + return; + } + + // The `postgres` crate is synchronous and blocking; run the probe on a + // blocking thread and bound the whole thing with a 5s timeout. + let probe_url = db_url.clone(); + let probe = crate::runtime::blocking::spawn_blocking(move || postgres_probe(&probe_url)); + let outcome = match tokio::time::timeout(Duration::from_secs(5), probe).await { + Ok(Ok(outcome)) => outcome, + Ok(Err(join_err)) => { + items.push(DiagItem::error(cat, format!("postgres probe task failed: {join_err}"))); + return; + } + Err(_) => { + items.push(DiagItem::error(cat, "postgres health probe timed out after 5s")); + return; + } + }; + + for item in outcome { + items.push(item); + } +} + +/// Result of the blocking Postgres probe, mapped to diagnostic items by the +/// caller. Runs `SELECT 1`, checks pgvector, and a column-parity probe. +fn postgres_probe(db_url: &str) -> Vec { + let cat = "postgres"; + let mut out = Vec::new(); + + let mut cfg = match db_url.parse::() { + Ok(cfg) => cfg, + Err(e) => { + out.push(DiagItem::error(cat, format!("invalid db_url: {e}"))); + return out; + } + }; + cfg.connect_timeout(Duration::from_secs(4)); + + let mut client = match cfg.connect(postgres::NoTls) { + Ok(client) => client, + Err(e) => { + out.push(DiagItem::error(cat, format!("could not connect to postgres: {e}"))); + return out; + } + }; + + // SELECT 1 connectivity probe. + match client.query_one("SELECT 1", &[]) { + Ok(_) => out.push(DiagItem::ok(cat, "SELECT 1 succeeded")), + Err(e) => { + out.push(DiagItem::error(cat, format!("SELECT 1 failed: {e}"))); + return out; + } + } + + // pgvector extension presence + version. + match client.query_opt("SELECT extversion FROM pg_extension WHERE extname = 'vector'", &[]) { + Ok(Some(row)) => { + let version: String = row.try_get(0).unwrap_or_else(|_| "unknown".to_string()); + out.push(DiagItem::ok( + cat, + format!("pgvector extension installed (version {version})"), + )); + } + Ok(None) => out.push(DiagItem::error( + cat, + "pgvector extension not installed (run: CREATE EXTENSION vector;)", + )), + Err(e) => out.push(DiagItem::warn(cat, format!("could not query pg_extension: {e}"))), + } + + // Column-parity probe: the ACL layer relies on memories.owner_id. A missing + // column indicates schema drift between the expected and deployed schema. + match client.query_opt( + "SELECT column_name FROM information_schema.columns \ + WHERE table_name = 'memories' AND column_name = 'owner_id'", + &[], + ) { + Ok(Some(_)) => out.push(DiagItem::ok(cat, "schema parity: memories.owner_id present")), + Ok(None) => out.push(DiagItem::warn( + cat, + "schema parity: memories.owner_id missing or table not yet migrated", + )), + Err(e) => out.push(DiagItem::warn( + cat, + format!("could not inspect information_schema: {e}"), + )), + } + + out +} + +/// FIX-P2-08: Probes the configured custom embedding endpoint with a +/// short-timeout HEAD request (falling back to OPTIONS), so `prx doctor` +/// surfaces an unreachable embedding service before recall silently degrades. +/// Only `custom:` providers expose a probe-able HTTP endpoint; other +/// providers (none/openai/built-in) are skipped. +async fn check_embedding_endpoint(config: &Config, items: &mut Vec) { + let cat = "embedding"; + let provider = config.memory.embedding_provider.trim(); + let Some(url) = provider.strip_prefix("custom:").map(str::trim) else { + // No custom endpoint configured -- nothing to probe here. The provider + // validity itself is reported by check_memory_diagnostics. + return; + }; + if url.is_empty() { + items.push(DiagItem::error(cat, "custom embedding endpoint URL is empty")); + return; + } + + let client = match reqwest::Client::builder().timeout(Duration::from_secs(2)).build() { + Ok(client) => client, + Err(e) => { + items.push(DiagItem::warn(cat, format!("could not build HTTP probe client: {e}"))); + return; + } + }; + + // Try HEAD first; fall back to OPTIONS for gateways that omit HEAD. Any HTTP + // response (including 4xx/405) proves reachability -- we check connectivity, + // not authorization. + let mut reachable = client.head(url).send().await.ok().map(|r| r.status()); + if reachable.is_none() { + reachable = client + .request(reqwest::Method::OPTIONS, url) + .send() + .await + .ok() + .map(|r| r.status()); + } + + match reachable { + Some(status) => items.push(DiagItem::ok( + cat, + format!("embedding endpoint reachable (HTTP {status})"), + )), + None => items.push(DiagItem::warn( + cat, + format!("embedding endpoint unreachable within 2s: {url}"), + )), + } +} + +fn check_memory_diagnostics(config: &Config, items: &mut Vec) { + let cat = "memory"; + items.push(DiagItem::declared(cat, "memory capability available")); + + let backend = + crate::memory::effective_memory_backend_name(&config.memory.backend, Some(&config.storage.provider.config)); + items.push(DiagItem::configured(cat, format!("backend configured as {backend}"))); + items.push(DiagItem::configured( + cat, + format!("workspace path {}", config.workspace_dir.display()), + )); + + let embedder = crate::memory::create_embedder_from_config(config); + if embedder.name() == "none" || embedder.dimensions() == 0 { + items.push(DiagItem::warn( + "embedding", + "embedding provider disabled or unresolved; keyword/FTS search remains the fallback", + )); + } else { + items.push(DiagItem::configured( + "embedding", + format!( + "embedding provider={} model={} dimensions={}", + embedder.name(), + embedder.model(), + embedder.dimensions() + ), + )); + } + + if let Some(notice) = config.embedding_default_upgrade_notice() { + items.push(DiagItem::warn("embedding", notice)); + } + + let provider = config.memory.embedding_provider.trim(); + if provider.starts_with("custom:") { + let url = provider.strip_prefix("custom:").unwrap_or("").trim(); + match reqwest::Url::parse(url) { + Ok(parsed) if matches!(parsed.scheme(), "http" | "https") => { + items.push(DiagItem::configured( + "embedding", + format!("custom embedding endpoint {url}"), + )); + } + _ => items.push(DiagItem::error( + "embedding", + format!("custom embedding endpoint is invalid: {url}"), + )), + } + } + + if config.memory.embedding_dimensions == 0 { + items.push(DiagItem::error( + "embedding", + "memory.embedding_dimensions must be greater than zero when embeddings are enabled", + )); + } + + items.push(DiagItem::declared( + "maintenance", + "run `prx memory reindex` to rebuild SQLite/Lucid memory and document chunk vectors", + )); +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ModelProbeVerdict { + Skipped, + AuthOrAccess, + Error, +} + +fn classify_model_probe_error(err_message: &str) -> ModelProbeVerdict { + let lower = err_message.to_lowercase(); + + if lower.contains("does not support live model discovery") { + return ModelProbeVerdict::Skipped; + } + + if [ + "401", + "403", + "429", + "unauthorized", + "forbidden", + "api key", + "token", + "insufficient balance", + "insufficient quota", + "plan does not include", + "rate limit", + ] + .iter() + .any(|hint| lower.contains(hint)) + { + return ModelProbeVerdict::AuthOrAccess; + } + + ModelProbeVerdict::Error +} + +fn doctor_model_targets(provider_override: Option<&str>) -> Vec { + if let Some(provider) = provider_override.map(str::trim).filter(|p| !p.is_empty()) { + return vec![provider.to_string()]; + } + + crate::providers::list_providers() + .into_iter() + .map(|provider| provider.name.to_string()) + .collect() +} + +pub fn run_models(config: &Config, provider_override: Option<&str>, use_cache: bool) -> Result<()> { + let targets = doctor_model_targets(provider_override); + + if targets.is_empty() { + anyhow::bail!("No providers available for model probing"); + } + + println!("🩺 OpenPRX Doctor — Model Catalog Probe"); + println!(" Providers to probe: {}", targets.len()); + println!( + " Mode: {}", + if use_cache { "cache-first" } else { "force live refresh" } + ); + println!(); + + let mut ok_count = 0usize; + let mut skipped_count = 0usize; + let mut auth_count = 0usize; + let mut error_count = 0usize; + + for provider_name in &targets { + println!( + " [{}]", + crate::security::redaction::redact_provider_text(provider_name) + ); + + match crate::providers::model_discovery::run_models_probe_read_only(config, Some(provider_name), use_cache) { + Ok(()) => { + ok_count += 1; + println!(" ✅ model catalog check passed"); + } + Err(error) => { + let error_text = crate::security::redaction::redact_provider_text(&format_error_chain(&error)); + match classify_model_probe_error(&error_text) { + ModelProbeVerdict::Skipped => { + skipped_count += 1; + println!(" ⚪ skipped: {}", truncate_for_display(&error_text, 160)); + } + ModelProbeVerdict::AuthOrAccess => { + auth_count += 1; + println!(" ⚠️ auth/access: {}", truncate_for_display(&error_text, 160)); + } + ModelProbeVerdict::Error => { + error_count += 1; + println!(" ❌ error: {}", truncate_for_display(&error_text, 160)); + } + } + } + } + + println!(); + } + + println!( + " Summary: {} ok, {} skipped, {} auth/access, {} errors", + ok_count, skipped_count, auth_count, error_count + ); + + if auth_count > 0 { + println!(" 💡 Some providers need valid API keys/plan access before `/models` can be fetched."); + } + + if provider_override.is_some() && ok_count == 0 { + anyhow::bail!("Model probe failed for target provider") + } + + if error_count > 0 { + anyhow::bail!("Model probe found {error_count} provider error(s)") + } + + Ok(()) +} + +// ── Config semantic validation ─────────────────────────────────── + +/// Resolve the configured default for chat the way every surface does: +/// refused is an error (it will not start), id-only is a warning (it runs, +/// unverified), verified is fine. +fn check_model_selection(config: &Config, items: &mut Vec) { + let cat = "models"; + if let Ok(resolved) = crate::providers::selection::check( + config, + crate::providers::selection::default_provider(config), + crate::providers::selection::default_model(config), + &crate::providers::catalog::Requirement::chat(), + crate::providers::catalog::UnknownPolicy::Invocation, + ) { + if let Some(warning) = crate::providers::selection::pricing_warning(&resolved, &config.cost) { + items.push(DiagItem::warn(cat, warning)); + } else if let Some(notice) = crate::providers::selection::subscription_billing_notice( + resolved.provider_label(), + resolved.model(), + &config.cost, + ) { + items.push(DiagItem::ok(cat, notice)); + } + } + for warning in crate::config::schema::unmatched_cost_price_key_warnings(config) { + items.push(DiagItem::warn("cost", warning)); + } + + match crate::config::model_settings::warnings(config) { + Ok(warnings) => items.extend(warnings.into_iter().map(|warning| DiagItem::warn(cat, warning))), + Err(error) => items.push(DiagItem::error(cat, error.to_string())), + } + match crate::config::manage::lifecycle::diagnostics(config) { + Ok(notes) => items.extend(notes.into_iter().map(|note| { + if note.warning { + DiagItem::warn(cat, note.message) + } else { + DiagItem::with_state(Severity::Ok, DiagnosticState::Unknown, cat, note.message) + } + })), + Err(error) => items.push(DiagItem::error(cat, error.to_string())), + } + match crate::providers::selection::default_status(config) { + Ok((true, line)) => items.push(DiagItem::ok(cat, line)), + Ok((false, line)) => items.push(DiagItem::warn(cat, line)), + Err(line) => items.push(DiagItem::error(cat, line)), + } +} + +/// Every persisted selection besides the default (routes, agents, +/// fallbacks, embeddings, ...) resolved as an existing invocation (SP-PMM +/// H-4): one warning per selection the evidence does not verify, and an +/// error when one no longer resolves. The default is reported by +/// [`check_model_selection`]. Local only; no credential is read. +fn check_persisted_selections(config: &Config, items: &mut Vec) { + let cat = "models"; + // Two embedding routes sharing a hint load, but only the first is used + // (D-104 C-1 ruling): name each with the fix. + for note in crate::config::schema::duplicate_embedding_route_hints(config) { + items.push(DiagItem::warn(cat, note)); + } + match crate::config::manage::validate::check_existing_selections(config) { + Ok(warnings) => { + let unverified = warnings + .into_iter() + .filter(|warning| !warning.starts_with("default model ")) + .collect::>(); + if unverified.is_empty() { + items.push(DiagItem::healthy(cat, "every persisted selection is verified")); + } + for warning in unverified { + items.push(DiagItem::warn(cat, warning)); + } + } + Err(refused) => items.push(DiagItem::error( + cat, + format!("a persisted selection no longer resolves: {refused}"), + )), + } +} + +/// The decision plane reports refused backends and orphaned references. +fn check_decision_plane(config: &Config, items: &mut Vec) { + let cat = "decision"; + if let Some(warning) = crate::config::manage::validate::decision_startup_check(config) { + items.push(DiagItem::warn(cat, warning)); + } + if config.decision_engine.enabled + && let Some(warning) = crate::config::manage::validate::decision_orphans_warning(config) + { + items.push(DiagItem::warn(cat, warning)); + } +} + +/// Use the same registry expansion and provider filter as `RouterEngine::new`. +#[cfg(feature = "llm-router")] +fn check_router_candidates(config: &Config, items: &mut Vec) { + let reachable = crate::router::capability::reachable_provider_names( + crate::providers::selection::default_provider(config), + &config.model_routes, + ); + let candidates = if config.router.models.is_empty() { + crate::router::models::builtin_model_capabilities(&config.cost) + } else { + config.router.models.clone() + }; + let has_reachable_model = crate::router::capability::filter_models_by_providers(candidates, &reachable) + .into_iter() + .any(|model| { + crate::router::capability::is_model_reachable( + crate::providers::selection::default_provider(config), + &config.model_routes, + &model.provider, + &model.model_id, + ) + }); + if !has_reachable_model { + items.push(DiagItem::warn( + "router", + "Router has no reachable candidates after provider/model filtering; configure reachable [[router.models]] entries; the selected default is unchanged", + )); + } +} diff --git a/src/doctor/implementation/section_2.rs b/src/doctor/implementation/section_2.rs new file mode 100644 index 000000000..d6f8ce201 --- /dev/null +++ b/src/doctor/implementation/section_2.rs @@ -0,0 +1,1152 @@ +fn check_config_semantics(config: &Config, items: &mut Vec) { + let cat = "config"; + + if !config.autonomy.acknowledge_unrestricted_profile + && !config.autonomy.workspace_only + && config.autonomy.forbidden_paths.is_empty() + && config.autonomy.max_cost_per_day_cents == u32::MAX + { + items.push(DiagItem::warn( + cat, + "explicit unrestricted autonomy profile: host-wide paths and an unbounded cost ceiling", + )); + } + + // Config file exists + if config.config_path.exists() { + items.push(DiagItem::configured( + cat, + format!("config file: {}", config.config_path.display()), + )); + } else { + items.push(DiagItem::error( + cat, + format!("config file not found: {}", config.config_path.display()), + )); + } + + // Provider validity + if let Some(ref provider) = config.default_provider { + if let Some(reason) = provider_validation_error( + config, + provider, + crate::providers::selection::default_model(config), + crate::providers::selection::credential_for(config, provider), + ) { + items.push(DiagItem::error( + cat, + format!("default provider \"{provider}\" is invalid: {reason}"), + )); + } else { + items.push(DiagItem::configured(cat, format!("provider \"{provider}\" is valid"))); + } + } else { + items.push(DiagItem::error(cat, "no default_provider configured")); + } + + // API key / auth profile presence + if config.default_provider.as_deref() != Some("ollama") { + if config.api_key.is_some() { + items.push(DiagItem::configured(cat, "API key configured")); + } else if let Some(provider) = config.default_provider.as_deref() { + match active_auth_profile_credential_status(config, provider) { + AuthProfileCredentialStatus::Present { profile_id } => { + items.push(DiagItem::configured( + cat, + format!("auth profile credential configured for \"{provider}\" ({profile_id})"), + )); + } + AuthProfileCredentialStatus::Unreadable(error) => { + items.push(DiagItem::warn( + cat, + format!("auth profile check failed for \"{provider}\": {error}"), + )); + } + AuthProfileCredentialStatus::Missing => { + items.push(DiagItem::warn(cat, "no api_key or active auth profile credential set")); + } + } + } else { + items.push(DiagItem::warn(cat, "no api_key or default provider set")); + } + } + + // Model configured + if config.default_model.is_some() { + items.push(DiagItem::configured( + cat, + format!("default model: {}", config.default_model.as_deref().unwrap_or("?")), + )); + } else { + items.push(DiagItem::warn(cat, "no default_model configured")); + } + + // Temperature range + if config.default_temperature >= 0.0 && config.default_temperature <= 2.0 { + items.push(DiagItem::configured( + cat, + format!("temperature {:.1} (valid range 0.0–2.0)", config.default_temperature), + )); + } else { + items.push(DiagItem::error( + cat, + format!( + "temperature {:.1} is out of range (expected 0.0–2.0)", + config.default_temperature + ), + )); + } + + // Gateway port range + let port = config.gateway.port; + if port > 0 { + items.push(DiagItem::configured(cat, format!("gateway port: {port}"))); + } else { + items.push(DiagItem::error(cat, "gateway port is 0 (invalid)")); + } + + // Reliability: fallback providers + for fb in &config.reliability.fallback_providers { + // The runtime builds a fallback member other than the primary with no + // released credential (its own env/OAuth store, providers/mod.rs + // `create_provider_with_options(name, None, ..)`), so the check uses + // the same; a member that is the default provider runs on the primary. + let is_default = crate::providers::ProviderId::of(fb) + == crate::providers::ProviderId::of(crate::providers::selection::default_provider(config)); + let credential = if is_default { + crate::providers::selection::credential_for(config, fb) + } else { + crate::providers::credentials::CredentialRef::ProviderStore + }; + if let Some(reason) = provider_validation_error( + config, + fb, + crate::providers::selection::default_model(config), + credential, + ) { + items.push(DiagItem::warn( + cat, + format!("fallback provider \"{fb}\" is invalid: {reason}"), + )); + } + // A self-hosted fallback answers only `model_fallbacks` entries that + // name a model repository (D-076 N-1); without one it is never used. + let default_is_same = config + .default_provider + .as_deref() + .is_some_and(|default| default.trim().eq_ignore_ascii_case(fb.trim())); + if crate::providers::is_self_hosted_model_server(fb) + && !default_is_same + && !config + .reliability + .model_fallbacks + .values() + .flatten() + .any(|model| crate::providers::names_model_repository(model)) + { + items.push(DiagItem::warn( + cat, + format!( + "fallback provider \"{fb}\" is never used: as a fallback it answers only \ + reliability.model_fallbacks entries that name one of its model repositories \ + (org/repository), and none does" + ), + )); + } + } + let route_providers: HashSet = config + .model_routes + .iter() + .map(|route| route.provider.trim().to_string()) + .filter(|provider| !provider.is_empty()) + .collect(); + for (source_model, fallback_chain) in &config.reliability.model_fallbacks { + if fallback_chain.is_empty() { + items.push(DiagItem::warn( + cat, + format!( + "model_fallbacks entry \"{source_model}\" has an empty fallback chain; it will never take effect" + ), + )); + continue; + } + + for fallback_model in fallback_chain { + if !model_has_reachable_provider( + crate::providers::selection::default_provider(config), + &config.reliability.fallback_providers, + &route_providers, + fallback_model, + ) { + items.push(DiagItem::warn( + cat, + format!( + "model_fallbacks route mismatch: fallback model \"{fallback_model}\" has no compatible provider in default/fallback/model_routes" + ), + )); + } + } + } + + let availability = crate::providers::summarize_provider_availability( + crate::providers::selection::default_provider(config), + config.api_key.as_deref(), + &config.reliability, + &crate::providers::provider_runtime_options_from_config(config), + ); + if availability.degraded && !config.reliability.acknowledge_single_provider_risk { + items.push(DiagItem::warn( + cat, + format!( + "provider resilience degraded: only {} configured+available provider(s) (need >=2). available=[{}]", + availability.available.len(), + availability.available.join(", ") + ), + )); + } else { + items.push(DiagItem::ready( + cat, + format!( + "provider resilience ready: {} configured+available providers [{}]", + availability.available.len(), + availability.available.join(", ") + ), + )); + } + if !availability.unavailable.is_empty() { + items.push(DiagItem::warn( + cat, + format!( + "unavailable providers: {}", + availability + .unavailable + .iter() + .map(|(name, reason)| format!("{name}: {reason}")) + .collect::>() + .join("; ") + ), + )); + } + + // Model routes validation + for route in &config.model_routes { + if route.hint.is_empty() { + items.push(DiagItem::warn(cat, "model route with empty hint")); + } + let credential = route.credential_ref.as_deref().map_or_else( + || { + if route.api_key.as_deref().is_some_and(|key| !key.trim().is_empty()) { + crate::providers::credentials::CredentialRef::LegacyInline( + crate::providers::credentials::LegacySlot::ModelRoute(route.hint.clone()), + ) + } else { + crate::providers::selection::credential_for(config, &route.provider) + } + }, + |id| crate::providers::credentials::CredentialRef::Profile { id: id.to_string() }, + ); + if let Some(reason) = provider_validation_error(config, &route.provider, &route.model, credential) { + items.push(DiagItem::warn( + cat, + format!( + "model route \"{}\" uses invalid provider \"{}\": {}", + route.hint, route.provider, reason + ), + )); + } + if route.model.is_empty() { + items.push(DiagItem::warn( + cat, + format!("model route \"{}\" has empty model", route.hint), + )); + } + } + + // Embedding routes validation + for route in &config.embedding_routes { + if route.hint.trim().is_empty() { + items.push(DiagItem::warn(cat, "embedding route with empty hint")); + } + if let Some(reason) = embedding_provider_validation_error(&route.provider) { + items.push(DiagItem::warn( + cat, + format!( + "embedding route \"{}\" uses invalid provider \"{}\": {}", + route.hint, route.provider, reason + ), + )); + } + if route.model.trim().is_empty() { + items.push(DiagItem::warn( + cat, + format!("embedding route \"{}\" has empty model", route.hint), + )); + } + if route.dimensions.is_some_and(|value| value == 0) { + items.push(DiagItem::warn( + cat, + format!("embedding route \"{}\" has invalid dimensions=0", route.hint), + )); + } + } + + if let Some(hint) = config + .memory + .embedding_model + .strip_prefix("hint:") + .map(str::trim) + .filter(|value| !value.is_empty()) + { + if !config.embedding_routes.iter().any(|route| route.hint.trim() == hint) { + items.push(DiagItem::warn( + cat, + format!( + "memory.embedding_model uses hint \"{hint}\" but no matching [[embedding_routes]] entry exists" + ), + )); + } + } + + // Channel: at least one configured + let cc = &config.channels_config; + let has_channel = cc.telegram.is_some() + || cc.discord.is_some() + || cc.slack.is_some() + || cc.imessage.is_some() + || cc.whatsapp.is_some() + || cc.wacli.is_some() + || cc.nextcloud_talk.is_some() + || cc.email.is_some() + || cc.irc.is_some() + || cc.lark.is_some() + || cc.webhook.is_some(); + + if has_channel { + items.push(DiagItem::configured(cat, "at least one channel configured")); + } else { + items.push(DiagItem::warn( + cat, + "no channels configured — run `prx init` to set one up", + )); + } + + // Delegate agents: provider validity + let mut agent_names: Vec<_> = config.agents.keys().collect(); + agent_names.sort(); + for name in agent_names { + let Some(agent) = config.agents.get(name) else { + continue; + }; + let credential = agent.credential_ref.as_deref().map_or_else( + || { + if agent.api_key.as_deref().is_some_and(|key| !key.trim().is_empty()) { + crate::providers::credentials::CredentialRef::LegacyInline( + crate::providers::credentials::LegacySlot::Agent(name.clone()), + ) + } else { + crate::providers::selection::credential_for(config, &agent.provider) + } + }, + |id| crate::providers::credentials::CredentialRef::Profile { id: id.to_string() }, + ); + if let Some(reason) = provider_validation_error(config, &agent.provider, &agent.model, credential) { + items.push(DiagItem::warn( + cat, + format!( + "agent \"{name}\" uses invalid provider \"{}\": {}", + agent.provider, reason + ), + )); + } + if agent.agentic && agent.allowed_tools.iter().any(|tool| tool.trim() == "*") { + items.push(DiagItem::warn( + cat, + format!("agent \"{name}\" explicitly inherits all eligible parent tools"), + )); + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum AuthProfileCredentialStatus { + Present { profile_id: String }, + Missing, + Unreadable(String), +} + +fn active_auth_profile_credential_status(config: &Config, provider: &str) -> AuthProfileCredentialStatus { + let Some(openprx_dir) = config.config_path.parent() else { + return AuthProfileCredentialStatus::Missing; + }; + let canonical_provider = crate::providers::canonical_china_provider_name(provider) + .unwrap_or(provider) + .to_string(); + // Read-only: a diagnosis never rewrites the profiles file (D-084 E-3). + let store = crate::auth::profiles::AuthProfilesStore::new(openprx_dir, config.secrets.encrypt); + let data = match store.load_read_only() { + Ok(data) => data, + Err(error) => return AuthProfileCredentialStatus::Unreadable(error.to_string()), + }; + let Some(profile_id) = data.active_profiles.get(&canonical_provider) else { + return AuthProfileCredentialStatus::Missing; + }; + let Some(profile) = data.profiles.get(profile_id) else { + return AuthProfileCredentialStatus::Missing; + }; + let credential = profile + .token + .as_deref() + .or_else(|| profile.token_set.as_ref().map(|tokens| tokens.access_token.as_str())) + .map(str::trim); + if credential.is_some_and(|token| !token.is_empty()) { + AuthProfileCredentialStatus::Present { + profile_id: profile_id.clone(), + } + } else { + AuthProfileCredentialStatus::Missing + } +} + +fn provider_validation_error( + config: &Config, + name: &str, + model: &str, + credential: crate::providers::credentials::CredentialRef, +) -> Option { + let catalog = crate::providers::selection::catalog_for(config); + let resolved = match crate::providers::selection::check_with( + config, + &catalog, + name, + model, + credential, + &crate::providers::catalog::Requirement::chat(), + crate::providers::catalog::UnknownPolicy::Invocation, + ) { + Ok(resolved) => resolved, + Err(error @ crate::providers::catalog::ResolutionError::UnknownProvider { .. }) => { + return Some(format!("Unknown provider: {error}")); + } + Err(error) => return Some(error.to_string()), + }; + let mut reliability = config.reliability.clone(); + reliability.fallback_providers.clear(); + reliability.api_keys.clear(); + reliability.model_fallbacks.clear(); + match crate::providers::create_provider_for( + &resolved, + &catalog, + &reliability, + &config.cost, + &crate::providers::provider_runtime_options_from_config(config), + ) { + Ok(_) => None, + // A missing credential is reported by the credential checks, not + // as an invalid provider here. + Err(error) + if error + .downcast_ref::() + .is_some() => + { + None + } + Err(error) => Some(error.to_string().lines().next().unwrap_or("invalid provider").into()), + } +} + +fn model_has_reachable_provider( + default_provider: &str, + fallback_providers: &[String], + route_providers: &HashSet, + model: &str, +) -> bool { + // As the failover chain decides (D-075): a self-hosted model server + // serves any repository on its own route (the default provider, a model + // route) and never answers as a fallback for another provider's route. + let serves_own_route = |provider: &str| { + if crate::providers::is_self_hosted_model_server(provider) { + crate::providers::provider_serves_configured_model(provider, model) + } else { + crate::providers::provider_matches_model_prefix(provider, model) + } + }; + if serves_own_route(default_provider) { + return true; + } + if fallback_providers.iter().any(|provider| { + if crate::providers::is_self_hosted_model_server(provider) { + // A fallback model is a `model_fallbacks` entry (D-076 N-1). + crate::providers::names_model_repository(model) + } else { + crate::providers::provider_matches_model_prefix(provider, model) + } + }) { + return true; + } + route_providers.iter().any(|provider| serves_own_route(provider)) +} + +fn embedding_provider_validation_error(name: &str) -> Option { + let normalized = name.trim(); + if normalized.eq_ignore_ascii_case("local") + || normalized.eq_ignore_ascii_case("none") + || normalized.eq_ignore_ascii_case("openai") + { + return None; + } + + let Some(url) = normalized.strip_prefix("custom:") else { + return Some("supported values: local, none, openai, custom:".into()); + }; + + let url = url.trim(); + if url.is_empty() { + return Some("custom provider requires a non-empty URL after 'custom:'".into()); + } + + match reqwest::Url::parse(url) { + Ok(parsed) if matches!(parsed.scheme(), "http" | "https") => None, + Ok(parsed) => Some(format!( + "custom provider URL must use http/https, got '{}'", + parsed.scheme() + )), + Err(err) => Some(format!("invalid custom provider URL: {err}")), + } +} + +// ── Workspace integrity ────────────────────────────────────────── + +fn check_workspace(config: &Config, items: &mut Vec) { + let cat = "workspace"; + let ws = &config.workspace_dir; + + if ws.exists() { + items.push(DiagItem::ok(cat, format!("directory exists: {}", ws.display()))); + } else { + items.push(DiagItem::error(cat, format!("directory missing: {}", ws.display()))); + return; + } + + // Doctor is diagnostic-only: prove readability and report declared write + // permission without creating a probe file. + match std::fs::read_dir(ws) { + Ok(_) => items.push(DiagItem::ready(cat, "directory is readable; no write probe performed")), + Err(error) => items.push(DiagItem::error(cat, format!("directory is not readable: {error}"))), + } + #[cfg(unix)] + if let Ok(metadata) = std::fs::metadata(ws) { + use std::os::unix::fs::PermissionsExt; + if metadata.permissions().mode() & 0o222 == 0 { + items.push(DiagItem::with_state( + Severity::Warn, + DiagnosticState::Configured, + cat, + "directory has no declared write permission bits; write capability was not exercised", + )); + } else { + items.push(DiagItem::configured( + cat, + "directory declares write permission; capability was not exercised", + )); + } + } + + // Disk space (best-effort via `df`) + if let Some(avail_mb) = disk_available_mb(ws) { + if avail_mb >= 100 { + items.push(DiagItem::ok(cat, format!("disk space: {avail_mb} MB available"))); + } else { + items.push(DiagItem::warn( + cat, + format!("low disk space: only {avail_mb} MB available"), + )); + } + } + + // Key workspace files + for name in ["SOUL.md", "AGENTS.md"] { + check_file_exists( + &crate::identity::root::file_directory(ws, name), + name, + false, + cat, + items, + ); + } +} + +fn check_file_exists(base: &Path, name: &str, required: bool, cat: &'static str, items: &mut Vec) { + let path = base.join(name); + if path.is_file() { + items.push(DiagItem::ok(cat, format!("{name} present"))); + } else if required { + items.push(DiagItem::error(cat, format!("{name} missing"))); + } else { + items.push(DiagItem::warn(cat, format!("{name} not found (optional)"))); + } +} + +fn disk_available_mb(path: &Path) -> Option { + let output = std::process::Command::new("df").arg("-m").arg(path).output().ok()?; + if !output.status.success() { + return None; + } + let stdout = String::from_utf8_lossy(&output.stdout); + parse_df_available_mb(&stdout) +} + +fn parse_df_available_mb(stdout: &str) -> Option { + let line = stdout.lines().rev().find(|line| !line.trim().is_empty())?; + let avail = line.split_whitespace().nth(3)?; + avail.parse::().ok() +} + +// ── Daemon state (original logic, preserved) ───────────────────── + +fn check_daemon_state(config: &Config, items: &mut Vec) { + let cat = "daemon"; + let state_file = crate::daemon::state_file_path(config); + + if !state_file.exists() { + items.push(DiagItem::error( + cat, + format!( + "state file not found: {} — is the daemon running?", + state_file.display() + ), + )); + return; + } + + let raw = match std::fs::read_to_string(&state_file) { + Ok(r) => r, + Err(e) => { + items.push(DiagItem::error(cat, format!("cannot read state file: {e}"))); + return; + } + }; + + let snapshot: serde_json::Value = match serde_json::from_str(&raw) { + Ok(v) => v, + Err(e) => { + items.push(DiagItem::error(cat, format!("invalid state JSON: {e}"))); + return; + } + }; + + // Daemon heartbeat freshness + let updated_at = snapshot + .get("updated_at") + .and_then(serde_json::Value::as_str) + .unwrap_or(""); + + if let Ok(ts) = DateTime::parse_from_rfc3339(updated_at) { + let age = Utc::now().signed_duration_since(ts.with_timezone(&Utc)).num_seconds(); + if age <= DAEMON_STALE_SECONDS { + items.push(DiagItem::ok(cat, format!("heartbeat fresh ({age}s ago)"))); + } else { + items.push(DiagItem::error(cat, format!("heartbeat stale ({age}s ago)"))); + } + } else { + items.push(DiagItem::error(cat, format!("invalid daemon timestamp: {updated_at}"))); + } + + if let Some(generation) = snapshot.get("config_generation") { + let active = generation.get("active_generation").and_then(serde_json::Value::as_u64); + let desired_revision = generation + .get("desired_source_revision") + .and_then(|revision| revision.get("fingerprint_sha256")) + .and_then(serde_json::Value::as_str) + .unwrap_or("unknown"); + let in_progress = generation + .get("reload_in_progress") + .and_then(serde_json::Value::as_bool) + .unwrap_or(false); + items.push(DiagItem::ok( + "config-generation", + format!( + "active generation {} (desired revision {}, reload_in_progress={in_progress})", + active.map_or_else(|| "unknown".to_string(), |value| value.to_string()), + desired_revision + ), + )); + + if let Some(failure) = generation.get("last_failure").filter(|failure| !failure.is_null()) { + let error = failure + .get("error") + .and_then(serde_json::Value::as_str) + .unwrap_or("unknown reload failure"); + items.push(DiagItem::error( + "config-generation", + format!("last config reload failed: {error}"), + )); + } else if let Some(restart_required) = generation + .get("last_report") + .and_then(|report| report.get("restart_required")) + .and_then(serde_json::Value::as_array) + .filter(|fields| !fields.is_empty()) + { + let fields = restart_required + .iter() + .filter_map(serde_json::Value::as_str) + .collect::>() + .join(", "); + items.push(DiagItem::warn( + "config-generation", + format!("desired config requires process restart for: {fields}"), + )); + } + } else { + items.push(DiagItem::unknown( + "config-generation", + "daemon state does not expose config generation status", + )); + } + + // Components + if let Some(components) = snapshot.get("components").and_then(serde_json::Value::as_object) { + // Do not hard-code runtime truth to scheduler and channel:* only. Any + // tracked active owner that reports unhealthy must be visible in doctor. + for (name, component) in components { + if name == "scheduler" || name.starts_with("channel:") { + continue; + } + let status = component + .get("status") + .and_then(serde_json::Value::as_str) + .unwrap_or("unknown"); + if status == "ok" || status == "disabled" { + continue; + } + let detail = component + .get("last_error") + .and_then(serde_json::Value::as_str) + .unwrap_or("runtime component is not healthy"); + items.push(DiagItem::error(cat, format!("{name} unhealthy ({status}): {detail}"))); + } + + // Scheduler + if let Some(scheduler) = components.get("scheduler") { + { + let scheduler_ok = scheduler + .get("status") + .and_then(serde_json::Value::as_str) + .is_some_and(|s| s == "ok"); + let scheduler_age = scheduler + .get("last_ok") + .and_then(serde_json::Value::as_str) + .and_then(parse_rfc3339) + .map_or(i64::MAX, |dt| Utc::now().signed_duration_since(dt).num_seconds()); + + if scheduler_ok && scheduler_age <= SCHEDULER_STALE_SECONDS { + items.push(DiagItem::ok( + cat, + format!("scheduler healthy (last ok {scheduler_age}s ago)"), + )); + } else { + items.push(DiagItem::error( + cat, + format!("scheduler unhealthy (ok={scheduler_ok}, age={scheduler_age}s)"), + )); + } + } + } else { + items.push(DiagItem::unknown(cat, "scheduler component not tracked yet")); + } + + // Channels + let mut channel_count = 0u32; + let mut stale = 0u32; + for (name, component) in components { + if !name.starts_with("channel:") { + continue; + } + channel_count += 1; + let status_ok = component + .get("status") + .and_then(serde_json::Value::as_str) + .is_some_and(|s| s == "ok"); + let age = component + .get("last_ok") + .and_then(serde_json::Value::as_str) + .and_then(parse_rfc3339) + .map_or(i64::MAX, |dt| Utc::now().signed_duration_since(dt).num_seconds()); + + // Measured listener activity, when the channel publishes it. The + // supervisor derives health from real traffic rather than from its own + // heartbeat timer, so a wedged listener shows up here as a stall with + // the silence duration attached. Purely informational: `prx doctor` + // reports, it never restarts anything. + let activity = component.get("activity"); + let stalled = activity + .and_then(|activity| activity.get("stalled")) + .and_then(serde_json::Value::as_bool) + .unwrap_or(false); + let idle_seconds = activity + .and_then(|activity| activity.get("idle_seconds")) + .and_then(serde_json::Value::as_u64); + let liveness = activity + .and_then(|activity| activity.get("liveness")) + .and_then(serde_json::Value::as_str); + + if stalled { + stale += 1; + let idle = idle_seconds.unwrap_or_default(); + items.push(DiagItem::error( + cat, + format!("{name} listener stalled (no receive activity for {idle}s)"), + )); + } else if status_ok && age <= CHANNEL_STALE_SECONDS { + let detail = match (liveness, idle_seconds) { + (Some("passive"), Some(idle)) => { + // No cadence to measure against, so "fresh" here means the + // supervisor is alive, not that the channel proved itself. + format!("{name} fresh ({age}s ago, push-only, idle {idle}s)") + } + (_, Some(idle)) => format!("{name} fresh ({age}s ago, idle {idle}s)"), + (_, None) => format!("{name} fresh ({age}s ago)"), + }; + items.push(DiagItem::ok(cat, detail)); + } else { + stale += 1; + items.push(DiagItem::error( + cat, + format!("{name} stale (ok={status_ok}, age={age}s)"), + )); + } + } + + if channel_count == 0 { + items.push(DiagItem::unknown(cat, "no channel components tracked yet")); + } else if stale > 0 { + items.push(DiagItem::warn(cat, format!("{channel_count} channels, {stale} stale"))); + } + } +} + +// ── Daemon process PATH ────────────────────────────────────────── +// +// A hand-written unit without `Environment="PATH=…"` leaves the daemon with +// systemd's default PATH, which does not contain `~/.cargo/bin`. The model +// then gets `sh: prx: not found` from the shell tool while `prx doctor`, run +// from an interactive shell, sees a perfectly healthy PATH. The daemon's own +// environment is the only place that truth is visible, so read it from +// `/proc//environ` instead of trusting the doctor process. + +const DAEMON_PATH_CATEGORY: &str = "daemon"; + +/// Non-failing outcome: the daemon PATH could not be inspected at all. +/// Reported as `Ok`/`Unknown` so an uninspectable daemon never turns +/// `prx doctor` red. +fn daemon_path_skipped(msg: impl Into) -> DiagItem { + DiagItem::with_state(Severity::Ok, DiagnosticState::Unknown, DAEMON_PATH_CATEGORY, msg) +} + +#[cfg(any(target_os = "linux", test))] +fn canonical_or_owned(path: &Path) -> PathBuf { + path.canonicalize().unwrap_or_else(|_| path.to_path_buf()) +} + +/// True for a Cargo build output directory (`…//debug`, +/// `…/target/release`, `…/target//debug/deps`, …). +/// +/// Such a directory must never enter the required set: `cargo run -- doctor`, +/// `./target/release/prx doctor` and one-shot CI copies all run from one, and +/// the repair text would then tell the operator to put a build directory on the +/// daemon's `PATH` — an operational step that outlives the build tree. +#[cfg(any(target_os = "linux", test))] +fn is_cargo_build_dir(path: &Path) -> bool { + let profile_dir = if path.file_name().is_some_and(|name| name == "deps") { + path.parent().unwrap_or(path) + } else { + path + }; + if !profile_dir + .file_name() + .is_some_and(|name| name == "debug" || name == "release") + { + return false; + } + // `deps` is a Cargo artifact directory even when a copied layout no + // longer has its siblings. A profile directory itself needs layout proof. + path != profile_dir + || ["deps", "build", ".fingerprint"] + .iter() + .any(|name| profile_dir.join(name).is_dir()) +} + +/// The deployed daemon binary as the daemon itself recorded it in +/// `daemon_state.json`, when that field is present. +/// +/// This is the authoritative answer to "which directory must the daemon's PATH +/// contain": it is the daemon's own binary, not the doctor's. +#[cfg(any(target_os = "linux", test))] +fn daemon_binary_from_state(config: &Config) -> Option { + let raw = std::fs::read_to_string(crate::daemon::state_file_path(config)).ok()?; + let snapshot: serde_json::Value = serde_json::from_str(&raw).ok()?; + let recorded = snapshot.get("binary_path").and_then(serde_json::Value::as_str)?; + let trimmed = recorded.trim(); + if trimmed.is_empty() { + return None; + } + Some(PathBuf::from(trimmed)) +} + +/// Directories the daemon PATH must contain for a shell tool to resolve `prx`. +/// +/// The daemon's own binary directory (from `daemon_state.json`) when it is +/// recorded, otherwise this doctor's directory as a best-effort stand-in — and +/// then only when it is not a build output directory. Plus `~/.cargo/bin` when +/// it exists, the default `cargo install` target. +#[cfg(any(target_os = "linux", test))] +fn required_daemon_path_dirs(daemon_binary: Option<&Path>) -> Vec { + let mut dirs: Vec = Vec::new(); + let recorded_parent = daemon_binary.and_then(Path::parent).map(canonical_or_owned); + if let Some(parent) = recorded_parent { + dirs.push(parent); + } else if let Ok(current) = std::env::current_exe() { + if let Some(parent) = current.parent().map(canonical_or_owned) { + if !is_cargo_build_dir(&parent) { + dirs.push(parent); + } + } + } + if let Some(home) = crate::config::user_home_dir() { + let cargo_bin = home.join(".cargo").join("bin"); + if cargo_bin.is_dir() { + dirs.push(canonical_or_owned(&cargo_bin)); + } + } + let mut unique: Vec = Vec::with_capacity(dirs.len()); + for dir in dirs { + if !unique.contains(&dir) { + unique.push(dir); + } + } + unique +} + +/// True when a process identity (its `exe` link and/or its `cmdline` payload) +/// belongs to a prx binary. +/// +/// Only the *file name* is matched, never the whole path: a prx checkout lives +/// in a directory called `prx`, so a path match would call every process +/// started from that tree a daemon. +#[cfg(any(target_os = "linux", test))] +fn process_identity_looks_like_prx(exe: Option<&Path>, cmdline: &[u8]) -> bool { + let named_prx = |path: &Path| { + path.file_name() + .and_then(std::ffi::OsStr::to_str) + .is_some_and(|name| name.contains("prx")) + }; + if exe.is_some_and(named_prx) { + return true; + } + cmdline + .split(|byte| *byte == 0) + .find(|entry| !entry.is_empty()) + .and_then(|argv0| std::str::from_utf8(argv0).ok()) + .is_some_and(|argv0| named_prx(Path::new(argv0))) +} + +/// Extract `PATH` from a NUL-separated `/proc//environ` payload. +#[cfg(any(target_os = "linux", test))] +fn daemon_path_from_environ(bytes: &[u8]) -> Option { + bytes + .split(|byte| *byte == 0) + .filter_map(|entry| std::str::from_utf8(entry).ok()) + .find_map(|entry| entry.strip_prefix("PATH=").map(str::to_owned)) +} + +#[cfg(any(target_os = "linux", test))] +fn path_contains_dir(path: &str, dir: &Path) -> bool { + std::env::split_paths(path) + .filter(|entry| !entry.as_os_str().is_empty()) + .any(|entry| same_executable_path(&entry, dir)) +} + +/// Pure judgement over a daemon PATH value, so the decision is testable +/// without a live daemon. +#[cfg(any(target_os = "linux", test))] +fn evaluate_daemon_path(path: &str, required_dirs: &[PathBuf]) -> DiagItem { + let missing: Vec = required_dirs + .iter() + .filter(|dir| !path_contains_dir(path, dir)) + .map(|dir| dir.display().to_string()) + .collect(); + + if missing.is_empty() { + return DiagItem::ok( + DAEMON_PATH_CATEGORY, + format!("daemon process PATH resolves the deployed prx binary: {path}"), + ); + } + + let missing_list = missing.join(", "); + let suggested = if path.is_empty() { + missing.join(":") + } else { + format!("{}:{path}", missing.join(":")) + }; + DiagItem::warn( + DAEMON_PATH_CATEGORY, + format!( + "daemon PATH does not include {missing_list}; shell tool cannot find prx — \ + add Environment=\"PATH={suggested}\" to the unit or re-run `prx service install` \ + (daemon PATH: {path})" + ), + ) +} + +#[cfg(any(target_os = "linux", test))] +fn evaluate_daemon_environ(bytes: &[u8], required_dirs: &[PathBuf]) -> DiagItem { + daemon_path_from_environ(bytes).map_or_else( + || { + DiagItem::warn( + DAEMON_PATH_CATEGORY, + "daemon process environment carries no PATH entry; shell tool cannot find prx — \ + add Environment=\"PATH=…\" to the unit or re-run `prx service install`", + ) + }, + |path| evaluate_daemon_path(&path, required_dirs), + ) +} + +fn daemon_pid_from_state(config: &Config) -> Option { + let raw = std::fs::read_to_string(crate::daemon::state_file_path(config)).ok()?; + let snapshot: serde_json::Value = serde_json::from_str(&raw).ok()?; + snapshot + .get("pid") + .and_then(serde_json::Value::as_u64) + .and_then(|pid| u32::try_from(pid).ok()) +} + +#[cfg(target_os = "linux")] +fn read_daemon_environ(pid: u32) -> std::io::Result> { + std::fs::read(format!("/proc/{pid}/environ")) +} + +/// Best-effort ownership check for the pid recorded in `daemon_state.json`. +/// +/// A pid outlives the daemon that wrote it: after a crash the number is reused +/// by an unrelated process, and reading *that* process' environment would make +/// `prx doctor` judge the daemon PATH from a stranger's `PATH`. Unreadable +/// `/proc` entries (the process is gone, or is owned by another user) answer +/// `false`, which routes the check to its skip branch rather than a verdict. +#[cfg(target_os = "linux")] +fn pid_belongs_to_prx(pid: u32) -> bool { + let exe = std::fs::read_link(format!("/proc/{pid}/exe")).ok(); + let cmdline = std::fs::read(format!("/proc/{pid}/cmdline")).unwrap_or_default(); + process_identity_looks_like_prx(exe.as_deref(), &cmdline) +} + +fn check_daemon_process_path(config: &Config, items: &mut Vec) { + let Some(pid) = daemon_pid_from_state(config) else { + items.push(daemon_path_skipped( + "daemon state exposes no pid; skipped daemon PATH inspection", + )); + return; + }; + + #[cfg(target_os = "linux")] + if pid_belongs_to_prx(pid) { + let required = required_daemon_path_dirs(daemon_binary_from_state(config).as_deref()); + match read_daemon_environ(pid) { + Ok(bytes) => items.push(evaluate_daemon_environ(&bytes, &required)), + Err(error) => items.push(daemon_path_skipped(format!( + "cannot read /proc/{pid}/environ ({error}); skipped daemon PATH inspection" + ))), + } + } else { + items.push(daemon_path_skipped(format!( + "daemon state pid {pid} is not a live prx process (pid reuse or a stopped daemon); \ + skipped reading /proc/{pid}/environ" + ))); + } + + #[cfg(not(target_os = "linux"))] + items.push(daemon_path_skipped(format!( + "daemon PATH inspection is only supported on Linux; skipped for daemon pid {pid}" + ))); +} + +// ── Environment checks ─────────────────────────────────────────── + +fn check_environment(items: &mut Vec) { + let cat = "environment"; + + // git + check_command_available("git", &["--version"], cat, items); + + // Shell + let shell = std::env::var("SHELL").unwrap_or_default(); + if shell.is_empty() { + items.push(DiagItem::warn(cat, "$SHELL not set")); + } else { + items.push(DiagItem::ok(cat, format!("shell: {shell}"))); + } + + // HOME + if std::env::var("HOME").is_ok() || std::env::var("USERPROFILE").is_ok() { + items.push(DiagItem::ok(cat, "home directory env set")); + } else { + items.push(DiagItem::error(cat, "neither $HOME nor $USERPROFILE is set")); + } + + // Optional tools + check_command_available("curl", &["--version"], cat, items); +} + +fn check_command_available(cmd: &str, args: &[&str], cat: &'static str, items: &mut Vec) { + match std::process::Command::new(cmd) + .args(args) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .output() + { + Ok(output) if output.status.success() => { + let ver = String::from_utf8_lossy(&output.stdout); + let first_line = ver.lines().next().unwrap_or("").trim(); + let display = truncate_for_display(first_line, COMMAND_VERSION_PREVIEW_CHARS); + items.push(DiagItem::ok(cat, format!("{cmd}: {display}"))); + } + Ok(_) => { + items.push(DiagItem::warn(cat, format!("{cmd} found but returned non-zero"))); + } + Err(_) => { + items.push(DiagItem::warn(cat, format!("{cmd} not found in PATH"))); + } + } +} + +fn format_error_chain(error: &anyhow::Error) -> String { + let mut parts = Vec::new(); + for cause in error.chain() { + let message = cause.to_string(); + if !message.is_empty() { + parts.push(message); + } + } + + if parts.is_empty() { + return String::new(); + } + + parts.join(": ") +} + +fn truncate_for_display(input: &str, max_chars: usize) -> String { + let mut chars = input.chars(); + let preview: String = chars.by_ref().take(max_chars).collect(); + if chars.next().is_some() { + format!("{preview}…") + } else { + preview + } +} + +// ── Helpers ────────────────────────────────────────────────────── + +fn parse_rfc3339(raw: &str) -> Option> { + DateTime::parse_from_rfc3339(raw).ok().map(|dt| dt.with_timezone(&Utc)) +} diff --git a/src/doctor/mod.rs b/src/doctor/mod.rs index da6f08e92..023b5b8e2 100644 --- a/src/doctor/mod.rs +++ b/src/doctor/mod.rs @@ -3,4561 +3,10 @@ mod decision_engine; mod ingress; mod prompt_cache; -mod workers; -use crate::config::Config; -use anyhow::{Context, Result}; -use chrono::{DateTime, Utc}; -use std::collections::HashSet; -use std::net::TcpStream; -use std::path::{Path, PathBuf}; -use std::time::Duration; - mod provider_circuits; -pub use ingress::{diagnose_ingress, run_ingress}; -const DAEMON_STALE_SECONDS: i64 = 30; -const SCHEDULER_STALE_SECONDS: i64 = 120; -const CHANNEL_STALE_SECONDS: i64 = 300; -const COMMAND_VERSION_PREVIEW_CHARS: usize = 60; - -// ── Diagnostic item ────────────────────────────────────────────── - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Severity { - Ok, - Warn, - Error, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum DiagnosticState { - Declared, - Configured, - Ready, - Healthy, - Disabled, - Unknown, -} - -#[derive(Debug, Clone)] -pub struct DiagItem { - pub severity: Severity, - pub state: DiagnosticState, - pub category: &'static str, - pub message: String, -} - -impl DiagItem { - fn ok(category: &'static str, msg: impl Into) -> Self { - Self::with_state(Severity::Ok, DiagnosticState::Healthy, category, msg) - } - fn healthy(category: &'static str, msg: impl Into) -> Self { - Self::ok(category, msg) - } - fn declared(category: &'static str, msg: impl Into) -> Self { - Self::with_state(Severity::Ok, DiagnosticState::Declared, category, msg) - } - fn configured(category: &'static str, msg: impl Into) -> Self { - Self::with_state(Severity::Ok, DiagnosticState::Configured, category, msg) - } - fn ready(category: &'static str, msg: impl Into) -> Self { - Self::with_state(Severity::Ok, DiagnosticState::Ready, category, msg) - } - fn disabled(category: &'static str, msg: impl Into) -> Self { - Self::with_state(Severity::Ok, DiagnosticState::Disabled, category, msg) - } - fn unknown(category: &'static str, msg: impl Into) -> Self { - Self::with_state(Severity::Warn, DiagnosticState::Unknown, category, msg) - } - /// Every item is built here, so this is the one place a message is made - /// safe to print: doctor quotes configured provider labels and endpoint - /// URLs, and a `custom:` URL may carry `user:password@`. - fn with_state(severity: Severity, state: DiagnosticState, category: &'static str, msg: impl Into) -> Self { - let message = crate::security::redaction::redact_secrets(&msg.into()); - let message = match crate::security::redaction::redact_url_components(&message) { - std::borrow::Cow::Borrowed(_) => message, - std::borrow::Cow::Owned(redacted) => redacted, - }; - Self { - severity, - state, - category, - message, - } - } - fn warn(category: &'static str, msg: impl Into) -> Self { - Self::with_state(Severity::Warn, DiagnosticState::Unknown, category, msg) - } - fn error(category: &'static str, msg: impl Into) -> Self { - Self::with_state(Severity::Error, DiagnosticState::Unknown, category, msg) - } - - const fn icon(&self) -> &'static str { - match self.severity { - Severity::Ok => "✅", - Severity::Warn => "⚠️ ", - Severity::Error => "❌", - } - } - - const fn state_label(&self) -> &'static str { - match self.state { - DiagnosticState::Declared => "DECLARED", - DiagnosticState::Configured => "CONFIGURED", - DiagnosticState::Ready => "READY", - DiagnosticState::Healthy => "HEALTHY", - DiagnosticState::Disabled => "DISABLED", - DiagnosticState::Unknown => "UNKNOWN", - } - } -} - -#[derive(Debug, Clone)] -pub struct DoctorReport { - pub title: &'static str, - pub items: Vec, - pub ok_count: usize, - pub warning_count: usize, - pub error_count: usize, -} - -impl DoctorReport { - fn new(title: &'static str, items: Vec) -> Self { - let ok_count = items.iter().filter(|item| item.severity == Severity::Ok).count(); - let warning_count = items.iter().filter(|item| item.severity == Severity::Warn).count(); - let error_count = items.iter().filter(|item| item.severity == Severity::Error).count(); - Self { - title, - items, - ok_count, - warning_count, - error_count, - } - } - - pub const fn has_errors(&self) -> bool { - self.error_count > 0 - } - - fn print(&self) { - println!("🩺 {}", self.title); - println!(); - - let mut current_cat = ""; - for item in &self.items { - if item.category != current_cat { - current_cat = item.category; - println!(" [{current_cat}]"); - } - println!(" {} [{}] {}", item.icon(), item.state_label(), item.message); - } - - println!(); - println!( - " Summary: {} ok, {} warnings, {} errors", - self.ok_count, self.warning_count, self.error_count - ); - if self.has_errors() { - println!(" 💡 Fix the errors above, then run `prx doctor` again."); - } - } - - fn ensure_success(&self) -> Result<()> { - if self.has_errors() { - anyhow::bail!("doctor found {} error(s)", self.error_count); - } - Ok(()) - } -} - -// ── Public entry point ─────────────────────────────────────────── - -pub fn run(config: &Config) -> Result<()> { - let report = diagnose(config); - report.print(); - report.ensure_success() -} - -pub fn diagnose(config: &Config) -> DoctorReport { - let mut items: Vec = Vec::new(); - - check_config_semantics(config, &mut items); - check_model_selection(config, &mut items); - check_persisted_selections(config, &mut items); - #[cfg(feature = "llm-router")] - check_router_candidates(config, &mut items); - check_decision_plane(config, &mut items); - check_workspace(config, &mut items); - ingress::check_recovery_authority(config, &mut items); - workers::check_retained_worker_folders(config, &mut items); - check_legacy_fitness_telemetry(config, &mut items); - check_workspace_mcp_servers(config, &mut items); - check_workspace_hooks(config, &mut items); - check_unowned_shell_jobs(config, &mut items); - check_unfinished_config_changes(config, &mut items); - check_daemon_state(config, &mut items); - prompt_cache::check_prompt_cache(config, &mut items); - decision_engine::check(config, &mut items); - provider_circuits::check_provider_circuits(config, &mut items); - check_daemon_process_path(config, &mut items); - check_environment(&mut items); - - DoctorReport::new("OpenPRX Doctor", items) -} - -pub fn run_memory(config: &Config) -> Result<()> { - let report = diagnose_memory(config); - report.print(); - report.ensure_success() -} - -pub fn diagnose_memory(config: &Config) -> DoctorReport { - let mut items: Vec = Vec::new(); - check_memory_diagnostics(config, &mut items); - check_legacy_fitness_telemetry(config, &mut items); - DoctorReport::new("OpenPRX Doctor - Memory", items) -} - -/// Workspace command hooks (HOOKS-ENV): a `hooks.json` whose commands do -/// not run because `security.workspace_hooks` is off is named, with the one -/// line that allows them. Reads the file only. -fn check_workspace_hooks(config: &Config, items: &mut Vec) { - let category = "hooks"; - match crate::hooks::workspace_hook_actions(&config.workspace_dir) { - Ok(None | Some(0)) => items.push(DiagItem::healthy(category, "no workspace command hooks")), - Ok(Some(actions)) if config.security.workspace_hooks == crate::config::WorkspaceHooks::On => { - items.push(DiagItem::ok( - category, - format!( - "{actions} workspace command hook(s) run (security.workspace_hooks = \"on\"), in a cleared \ - environment and a dedicated directory beside config.toml" - ), - )) - } - Ok(Some(actions)) => { - if let Some(note) = crate::hooks::blocked_hooks_note(actions) { - items.push(DiagItem::warn(category, note)); - } - } - Err(error) => items.push(DiagItem::warn( - category, - format!("the workspace hooks.json is not valid: {error:#}"), - )), - } -} - -/// Shell jobs stored before PRX recorded who creates them (D-107 -/// amendment): they count as agent-created, so a command that runs git is -/// refused. Each is named with the one command that vouches for it. Opens -/// the stores read-only and runs no migration: a store whose table predates -/// the `created_via` column has only such rows. -fn check_unowned_shell_jobs(config: &Config, items: &mut Vec) { - let category = "git"; - let cron_in_postgres = config - .storage - .provider - .config - .provider - .trim() - .eq_ignore_ascii_case("postgres"); - let mut sources = vec![( - "xin shell task", - "prx xin mark-operator", - config.workspace_dir.join("xin").join("tasks.db"), - "xin_tasks", - "SELECT id, payload FROM xin_tasks - WHERE execution_mode = 'shell' AND kind <> 'system' AND created_via IS NULL ORDER BY id", - "SELECT id, payload FROM xin_tasks WHERE execution_mode = 'shell' AND kind <> 'system' ORDER BY id", - )]; - if cron_in_postgres { - items.push(DiagItem::ok( - category, - "cron jobs are stored in Postgres and not inspected here; a shell job created before PRX recorded its \ - creator runs no git until `prx cron mark-operator `", - )); - } else { - sources.push(( - "cron shell job", - "prx cron mark-operator", - config.workspace_dir.join("cron").join("jobs.db"), - "cron_jobs", - "SELECT id, command FROM cron_jobs WHERE job_type = 'shell' AND created_via IS NULL ORDER BY id", - "SELECT id, command FROM cron_jobs WHERE job_type = 'shell' ORDER BY id", - )); - } - let mut found = 0_usize; - for (what, mark, db_path, table, unowned_sql, legacy_sql) in sources { - match read_only_unowned_rows(&db_path, table, unowned_sql, legacy_sql) { - Ok(rows) => { - for (id, _) in rows { - found += 1; - items.push(DiagItem::warn( - category, - format!( - "{what} {id} predates creator tracking and counts as agent-created, so git in it is \ - refused; if you created it: `{mark} {id}`" - ), - )); - } - } - Err(error) => items.push(DiagItem::warn( - category, - format!("the {what}s could not be read: {error:#}"), - )), - } - } - if found == 0 { - items.push(DiagItem::healthy(category, "every shell job records who created it")); - } -} - -/// `(id, command)` of the shell rows of `table` whose `created_via` is NULL -/// (`unowned_sql`), or all of them (`legacy_sql`) when the column does not -/// exist yet; read-only, and empty when the database or the table is -/// missing. -fn read_only_unowned_rows( - db_path: &Path, - table: &str, - unowned_sql: &str, - legacy_sql: &str, -) -> Result> { - if !db_path.is_file() { - return Ok(Vec::new()); - } - let connection = rusqlite::Connection::open_with_flags(db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?; - let table_exists: bool = connection.query_row( - "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?1)", - [table], - |row| row.get(0), - )?; - if !table_exists { - return Ok(Vec::new()); - } - let has_creator: bool = connection.query_row( - "SELECT EXISTS(SELECT 1 FROM pragma_table_info(?1) WHERE name = 'created_via')", - [table], - |row| row.get(0), - )?; - let mut statement = connection.prepare(if has_creator { unowned_sql } else { legacy_sql })?; - let rows = statement.query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)))?; - Ok(rows.collect::, _>>()?) -} - -/// Unfinished configuration changes (SP-PMM §2.6, D-095 L-3): a `pending` -/// history record (the process stopped between commit and activation) or a -/// `not_restored` one (a refused change whose restore failed). Nothing is -/// applied automatically; the operator decides. Reads the history only. -fn check_unfinished_config_changes(config: &Config, items: &mut Vec) { - use crate::config::manage::{ConfigHistory, RecordStatus}; - let category = "config"; - let records = match ConfigHistory::for_config(&config.config_path).and_then(|history| history.list()) { - Ok(records) => records, - Err(error) => { - items.push(DiagItem::warn( - category, - format!("configuration history could not be read: {error:#}"), - )); - return; - } - }; - // A change `prx` wrote that a later write replaced before a running PRX - // settled it (D-101 F-7): superseded, never activated. - let current = crate::config::files::current_config_revision(&config.config_path).ok(); - for record in records.iter().filter(|record| { - record.status == RecordStatus::Superseded - || (record.status == RecordStatus::ActivationDeferred - && current.is_some() - && record.committed_revision != current) - }) { - items.push(DiagItem::warn( - category, - format!( - "configuration change {} written by `prx` was replaced by a later write before a running PRX \ - settled it (superseded); inspect it with `prx config history show {}`", - record.id, record.id - ), - )); - } - let unfinished = records - .iter() - .filter(|record| matches!(record.status, RecordStatus::Pending | RecordStatus::NotRestored)) - .collect::>(); - if unfinished.is_empty() { - items.push(DiagItem::healthy(category, "no unfinished configuration change")); - return; - } - for record in unfinished { - items.push(DiagItem::warn( - category, - format!( - "configuration change {} is {} (the process stopped, or a restore failed); it is never applied \ - automatically: inspect it with `prx config history show {}` and restore the configuration from \ - before it with `prx config rollback {} --yes`", - record.id, - record.status.as_str(), - record.id, - record.id - ), - )); - } -} - -/// Every workspace `mcp.json` entry that did not start as written (blocked -/// by `mcp.workspace_servers`, disabled, or trimmed), with its one-line -/// remedy (D-088 C-7). Reads the file only; starts nothing. -fn check_workspace_mcp_servers(config: &Config, items: &mut Vec) { - let category = "mcp"; - let notes = crate::tools::mcp::workspace_server_notes(&config.mcp, &config.workspace_dir, config.autonomy.level); - if notes.is_empty() { - items.push(DiagItem::healthy( - category, - "no workspace mcp.json server is blocked or disabled", - )); - } - for note in notes { - items.push(DiagItem::warn(category, note)); - } - // An operator's `working_dir` inside the agent's workspace lets the - // workspace file tools plant files the server loads at start (a - // `.npmrc`, a shadowing module): allowed, but worth saying (D-095 N-4). - let mut servers = config.mcp.servers.iter().collect::>(); - servers.sort_by(|left, right| left.0.cmp(right.0)); - for (name, server) in servers { - if let Some(dir) = server.working_dir.as_deref() { - if std::path::Path::new(dir.trim()).starts_with(&config.workspace_dir) { - items.push(DiagItem::warn( - category, - format!( - "server '{}' starts in {}, inside the agent's workspace: the workspace file tools can \ - change what it loads there; prefer a directory outside the workspace, or leave \ - `working_dir` unset for its dedicated one", - name.escape_default(), - dir.trim() - ), - )); - } - } - } -} - -fn check_legacy_fitness_telemetry(config: &Config, items: &mut Vec) { - const PREFIX: &str = "self/fitness/daily/"; - let category = "fitness"; - match legacy_fitness_counts(config, PREFIX) { - Ok((database, memory_projection, snapshot_projection)) => { - let total = database + memory_projection + snapshot_projection; - if total == 0 { - items.push(DiagItem::healthy( - category, - "legacy fitness telemetry absent from memory storage and projections", - )); - } else { - items.push(DiagItem::warn( - category, - format!( - "legacy fitness telemetry detected: database={database}, MEMORY.md={memory_projection}, \ - MEMORY_SNAPSHOT.md={snapshot_projection}; run `prx fitness migrate-legacy --apply`" - ), - )); - } - } - Err(error) => items.push(DiagItem::warn( - category, - format!("legacy fitness telemetry inspection failed: {error}"), - )), - } -} - -fn legacy_fitness_counts(config: &Config, prefix: &str) -> Result<(usize, usize, usize)> { - let backend = - crate::memory::effective_memory_backend_name(&config.memory.backend, Some(&config.storage.provider.config)); - let database = match crate::memory::classify_memory_backend(&backend) { - crate::memory::MemoryBackendKind::Sqlite | crate::memory::MemoryBackendKind::Lucid => { - read_only_sqlite_key_prefix_count(&crate::schema_migration::memory_db_path(config), prefix)? - } - crate::memory::MemoryBackendKind::Postgres => { - let storage = &config.storage.provider.config; - let db_url = storage - .db_url - .as_deref() - .map(str::trim) - .filter(|value| !value.is_empty()) - .context("postgres fitness inspection requires storage.provider.config.db_url")?; - crate::memory::PostgresMemory::read_key_prefix_read_only( - db_url, - &storage.schema, - &storage.table, - storage.connect_timeout_secs, - prefix, - )? - .len() - } - crate::memory::MemoryBackendKind::Markdown | crate::memory::MemoryBackendKind::None => 0, - crate::memory::MemoryBackendKind::Unknown => { - anyhow::bail!("unsupported configured memory backend '{backend}'") - } - }; - let memory_projection = count_projection_lines(&config.workspace_dir.join("MEMORY.md"), |line| { - line.strip_prefix("- [") - .and_then(|rest| rest.split_once("] **")) - .and_then(|(_, rest)| rest.split_once("**:")) - .is_some_and(|(key, _)| key.starts_with(prefix)) - })?; - let snapshot_projection = count_projection_lines( - &config.workspace_dir.join(crate::memory::snapshot::SNAPSHOT_FILENAME), - |line| { - line.strip_prefix("### 🔑 `") - .and_then(|rest| rest.strip_suffix('`')) - .is_some_and(|key| key.starts_with(prefix)) - }, - )?; - Ok((database, memory_projection, snapshot_projection)) -} - -fn read_only_sqlite_key_prefix_count(db_path: &Path, prefix: &str) -> Result { - if !db_path.is_file() { - return Ok(0); - } - let connection = rusqlite::Connection::open_with_flags(db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?; - let table_exists: bool = connection.query_row( - "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'memories')", - [], - |row| row.get(0), - )?; - if !table_exists { - return Ok(0); - } - let escaped = prefix.replace('\\', "\\\\").replace('%', "\\%").replace('_', "\\_"); - let pattern = format!("{escaped}%"); - let count: i64 = connection.query_row( - "SELECT COUNT(*) FROM memories WHERE key LIKE ?1 ESCAPE '\\'", - [pattern], - |row| row.get(0), - )?; - usize::try_from(count).context("SQLite returned a negative legacy fitness count") -} - -fn count_projection_lines(path: &Path, matches: impl Fn(&str) -> bool) -> Result { - match std::fs::read_to_string(path) { - Ok(content) => Ok(content.lines().filter(|line| matches(line)).count()), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(0), - Err(error) => Err(error.into()), - } -} - -pub async fn run_runtime(config: &Config) -> Result<()> { - let report = diagnose_runtime(config).await; - report.print(); - report.ensure_success() -} - -pub async fn diagnose_runtime(config: &Config) -> DoctorReport { - let mut items: Vec = Vec::new(); - check_deployed_binary(&mut items); - check_runtime_config(config, &mut items); - check_daemon_state(config, &mut items); - prompt_cache::check_prompt_cache(config, &mut items); - decision_engine::check(config, &mut items); - provider_circuits::check_provider_circuits(config, &mut items); - check_daemon_process_path(config, &mut items); - check_gateway_runtime(config, &mut items); - check_channel_runtime(config, &mut items); - check_console_runtime(config, &mut items); - check_runtime_memory_health(config, &mut items); - check_runtime_readiness(config, &mut items); - check_postgres_health(config, &mut items).await; - check_embedding_endpoint(config, &mut items).await; - DoctorReport::new("OpenPRX Doctor - Runtime Matrix", items) -} - -fn check_deployed_binary(items: &mut Vec) { - check_deployed_binary_paths(items, deployed_binary_from_path(), std::env::current_exe()); -} - -fn deployed_binary_from_path() -> Option { - let path = std::env::var_os("PATH")?; - let binary_name = format!("prx{}", std::env::consts::EXE_SUFFIX); - std::env::split_paths(&path) - .map(|directory| directory.join(&binary_name)) - .find(|candidate| candidate.is_file()) -} - -fn same_executable_path(left: &Path, right: &Path) -> bool { - match (left.canonicalize(), right.canonicalize()) { - (Ok(left), Ok(right)) => left == right, - _ => left == right, - } -} - -fn check_deployed_binary_paths( - items: &mut Vec, - deployed: Option, - current: std::io::Result, -) { - let cat = "deployed"; - let Some(deployed) = deployed else { - items.push(DiagItem::error(cat, "deployed prx binary not found on PATH")); - if let Ok(current) = current { - items.push(DiagItem::warn( - cat, - format!( - "doctor is running from {}, but no deployed prx binary was found on PATH", - current.display() - ), - )); - } - return; - }; - - if deployed.is_file() { - items.push(DiagItem::ok( - cat, - format!("deployed binary exists: {}", deployed.display()), - )); - } else { - items.push(DiagItem::error( - cat, - format!("deployed binary missing: {}", deployed.display()), - )); - } - - match current { - Ok(current) if same_executable_path(¤t, &deployed) => { - items.push(DiagItem::ok(cat, "doctor is running from deployed binary")); - } - Ok(current) => items.push(DiagItem::warn( - cat, - format!("doctor is running from {}, not deployed binary", current.display()), - )), - Err(error) => items.push(DiagItem::warn( - cat, - format!("cannot resolve current executable: {error}"), - )), - } -} - -fn check_runtime_config(config: &Config, items: &mut Vec) { - let cat = "config"; - if config.config_path.exists() { - items.push(DiagItem::configured( - cat, - format!("config path exists: {}", config.config_path.display()), - )); - } else { - items.push(DiagItem::error( - cat, - format!("config path missing: {}", config.config_path.display()), - )); - } - if config.workspace_dir.exists() { - items.push(DiagItem::configured( - cat, - format!("workspace exists: {}", config.workspace_dir.display()), - )); - } else { - items.push(DiagItem::error( - cat, - format!("workspace missing: {}", config.workspace_dir.display()), - )); - } -} - -fn check_gateway_runtime(config: &Config, items: &mut Vec) { - let cat = "gateway"; - items.push(DiagItem::configured( - cat, - format!( - "configured bind {}:{} (pairing required: {})", - config.gateway.host, config.gateway.port, config.gateway.require_pairing - ), - )); - - let address = format!("{}:{}", config.gateway.host, config.gateway.port); - match crate::tools::http_request::lookup_host_blocking(&config.gateway.host, config.gateway.port) - .ok() - .and_then(|addrs| addrs.into_iter().next()) - { - Some(socket) => match TcpStream::connect_timeout(&socket, Duration::from_millis(300)) { - Ok(_) => items.push(DiagItem::ok(cat, format!("gateway port reachable at {socket}"))), - Err(error) => items.push(DiagItem::warn( - cat, - format!("gateway port not reachable at {socket}: {error}"), - )), - }, - None => items.push(DiagItem::warn( - cat, - format!("cannot resolve gateway bind address {address}"), - )), - } -} - -fn check_channel_runtime(config: &Config, items: &mut Vec) { - let cat = "channels"; - let configured = configured_channel_names(config); - if configured.is_empty() { - items.push(DiagItem::warn(cat, "no IM channels are configured")); - } else { - items.push(DiagItem::configured( - cat, - format!("configured channels: {}", configured.join(", ")), - )); - } -} - -fn configured_channel_names(config: &Config) -> Vec<&'static str> { - let mut names = Vec::new(); - if config.channels_config.cli { - names.push("cli"); - } - if config.channels_config.telegram.is_some() { - names.push("telegram"); - } - if config.channels_config.discord.is_some() { - names.push("discord"); - } - if config.channels_config.slack.is_some() { - names.push("slack"); - } - if config.channels_config.webhook.is_some() { - names.push("webhook"); - } - if config.channels_config.signal.is_some() { - names.push("signal"); - } - if config.channels_config.whatsapp.is_some() { - names.push("whatsapp"); - } - if config.channels_config.wacli.is_some() { - names.push("wacli"); - } - if config.channels_config.nextcloud_talk.is_some() { - names.push("nextcloud-talk"); - } - if config.channels_config.email.is_some() { - names.push("email"); - } - if config.channels_config.irc.is_some() { - names.push("irc"); - } - if config.channels_config.lark.is_some() { - names.push("lark"); - } - names -} - -fn check_console_runtime(config: &Config, items: &mut Vec) { - let cat = "console"; - let backend = - crate::memory::effective_memory_backend_name(&config.memory.backend, Some(&config.storage.provider.config)); - match crate::memory::classify_memory_backend(&backend) { - crate::memory::MemoryBackendKind::Sqlite | crate::memory::MemoryBackendKind::Lucid => { - let db_path = crate::schema_migration::memory_db_path(config); - match read_only_sqlite_session_count(&db_path) { - Ok(Some(0)) => items.push(DiagItem::ready(cat, "no persisted console/channel sessions found")), - Ok(Some(count)) => items.push(DiagItem::healthy( - cat, - format!("persisted conversation sessions visible: {count}"), - )), - Ok(None) => items.push(DiagItem::unknown( - cat, - "sessions table is not present; session visibility is unknown", - )), - Err(error) => items.push(DiagItem::error( - cat, - format!("read-only console session probe failed: {error}"), - )), - } - } - crate::memory::MemoryBackendKind::Postgres => items.push(DiagItem::unknown( - cat, - "PostgreSQL console session count is not inferred; backend health is probed separately", - )), - crate::memory::MemoryBackendKind::Markdown | crate::memory::MemoryBackendKind::None => { - items.push(DiagItem::disabled( - cat, - format!("backend '{backend}' does not provide durable conversation sessions"), - )); - } - crate::memory::MemoryBackendKind::Unknown if backend.starts_with("wasm:") => items.push(DiagItem::unknown( - cat, - format!("WASM backend '{backend}' conversation persistence is defined by the plugin"), - )), - crate::memory::MemoryBackendKind::Unknown => items.push(DiagItem::error( - cat, - format!("unknown configured memory backend '{backend}'"), - )), - } -} - -fn check_runtime_memory_health(config: &Config, items: &mut Vec) { - let cat = "memory"; - let backend = - crate::memory::effective_memory_backend_name(&config.memory.backend, Some(&config.storage.provider.config)); - match crate::memory::classify_memory_backend(&backend) { - crate::memory::MemoryBackendKind::None => { - items.push(DiagItem::disabled(cat, "memory backend explicitly disabled")); - } - crate::memory::MemoryBackendKind::Markdown => { - if config.workspace_dir.is_dir() { - items.push(DiagItem::ready( - cat, - "markdown memory workspace is readable; no write probe performed", - )); - } else { - items.push(DiagItem::error(cat, "markdown memory workspace is missing")); - } - } - crate::memory::MemoryBackendKind::Sqlite - | crate::memory::MemoryBackendKind::Lucid - | crate::memory::MemoryBackendKind::Postgres => { - match crate::schema_migration::inspect_configured_backend(config) { - Ok(report) if report.status.pending.is_empty() => items.push(DiagItem::healthy( - cat, - format!( - "{} backend authoritative ledger verified ({} migrations)", - report.backend, - report.status.applied.len() - ), - )), - Ok(report) => items.push(DiagItem::with_state( - Severity::Warn, - DiagnosticState::Ready, - cat, - format!( - "{} backend ledger is readable with {} pending migration(s)", - report.backend, - report.status.pending.len() - ), - )), - Err(error) => items.push(DiagItem::error( - cat, - format!("read-only {backend} backend probe failed: {error}"), - )), - } - } - crate::memory::MemoryBackendKind::Unknown if backend.starts_with("wasm:") => { - items.push(DiagItem::ready( - cat, - format!("WASM memory backend '{backend}' will be health-checked by the live plugin runtime"), - )); - } - crate::memory::MemoryBackendKind::Unknown => { - items.push(DiagItem::error( - cat, - format!("unknown configured memory backend '{backend}'"), - )); - } - } -} - -fn read_only_sqlite_session_count(db_path: &Path) -> Result> { - if !db_path.is_file() { - anyhow::bail!("memory database is missing at {}", db_path.display()); - } - let conn = rusqlite::Connection::open_with_flags(db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?; - let exists: bool = conn.query_row( - "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sessions')", - [], - |row| row.get(0), - )?; - if !exists { - return Ok(None); - } - conn.query_row("SELECT COUNT(*) FROM sessions", [], |row| row.get(0)) - .map(Some) - .map_err(Into::into) -} - -/// FIX-P2-06: Read-only runtime readiness sub-checks. -/// -/// Each verifies that the configuration is internally consistent enough for the -/// corresponding subsystem to operate: owner ACL, topic scoping, task lineage, -/// document ingest, vector index, and the runtime-control ladder. These are -/// config-derived probes only -- they do not open the database or touch the -/// network. -fn check_runtime_readiness(config: &Config, items: &mut Vec) { - let cat = "readiness"; - let mem = &config.memory; - let backend = mem.backend.trim().to_ascii_lowercase(); - let persistent = !matches!(backend.as_str(), "none" | "markdown"); - let embeddings_enabled = !mem.embedding_provider.trim().eq_ignore_ascii_case("none"); - - // 1. owner readiness: ACL enforcement requires a persistent backend. - if !mem.acl_enabled { - items.push(DiagItem::warn( - cat, - "owner: memory.acl_enabled is false; owner/topic scoping is not enforced", - )); - } else if persistent { - items.push(DiagItem::ready(cat, "owner: ACL enforced on a persistent backend")); - } else { - items.push(DiagItem::warn( - cat, - format!("owner: ACL enabled but backend '{backend}' does not persist owner scopes"), - )); - } - - // 2. topic readiness: similarity/semantic scoping needs a persistent - // backend and embeddings. - if persistent && embeddings_enabled && mem.embedding_dimensions > 0 { - let mode = if mem.embedding_provider.trim().eq_ignore_ascii_case("local") { - "local similarity" - } else { - "semantic" - }; - items.push(DiagItem::ready( - cat, - format!("topic: {mode} topic scoping ready (dim {})", mem.embedding_dimensions), - )); - } else if !persistent { - items.push(DiagItem::warn( - cat, - format!("topic: backend '{backend}' does not persist topic scopes"), - )); - } else { - items.push(DiagItem::warn( - cat, - "topic: embeddings disabled; topic/semantic scoping falls back to keyword search", - )); - } - - items.push(DiagItem::ready(cat, "task: lifecycle/task event recording always on")); - - // 4. document readiness: document ingest needs a persistent backend. - if persistent { - items.push(DiagItem::ready(cat, "document: ingest backed by a persistent store")); - } else { - items.push(DiagItem::warn( - cat, - format!("document: backend '{backend}' does not persist ingested documents"), - )); - } - - // 5. vector readiness: vector recall needs embeddings + a sane dimension. - if !persistent { - items.push(DiagItem::warn( - cat, - format!("vector: backend '{backend}' does not persist a vector index"), - )); - } else if !embeddings_enabled { - items.push(DiagItem::warn( - cat, - "vector: embeddings disabled; vector recall unavailable (keyword/FTS only)", - )); - } else if mem.embedding_dimensions == 0 { - items.push(DiagItem::error( - cat, - "vector: embedding_dimensions is zero while embeddings are enabled", - )); - } else { - items.push(DiagItem::ready( - cat, - format!("vector: index ready (dim {})", mem.embedding_dimensions), - )); - } - - // 6. runtime-control readiness: autonomy posture is resolvable. - items.push(DiagItem::ready( - cat, - format!( - "runtime-control: control ladder ready (autonomy {:?})", - config.autonomy.level - ), - )); -} - -/// FIX-P2-07: Checks Postgres backend health when a Postgres backend is -/// selected: validates the DSN, runs `SELECT 1` under a 5s timeout, verifies the -/// `vector` (pgvector) extension is installed, and performs a lightweight column -/// parity probe against `information_schema`. Skips cleanly (no error) when -/// Postgres is not configured. -async fn check_postgres_health(config: &Config, items: &mut Vec) { - let cat = "postgres"; - let storage = &config.storage.provider.config; - let selects_postgres = storage.provider.trim().eq_ignore_ascii_case("postgres") - || config.memory.backend.trim().eq_ignore_ascii_case("postgres"); - if !selects_postgres { - // Not configured for Postgres -- nothing to check. - return; - } - - let Some(db_url) = storage.db_url.clone() else { - items.push(DiagItem::error( - cat, - "postgres backend selected but [storage.provider.config] db_url is unset", - )); - return; - }; - - // Validate the DSN scheme before attempting a connection. - let trimmed = db_url.trim(); - if !(trimmed.starts_with("postgres://") || trimmed.starts_with("postgresql://")) { - items.push(DiagItem::error( - cat, - "db_url must start with postgres:// or postgresql://", - )); - return; - } - - // The `postgres` crate is synchronous and blocking; run the probe on a - // blocking thread and bound the whole thing with a 5s timeout. - let probe_url = db_url.clone(); - let probe = crate::runtime::blocking::spawn_blocking(move || postgres_probe(&probe_url)); - let outcome = match tokio::time::timeout(Duration::from_secs(5), probe).await { - Ok(Ok(outcome)) => outcome, - Ok(Err(join_err)) => { - items.push(DiagItem::error(cat, format!("postgres probe task failed: {join_err}"))); - return; - } - Err(_) => { - items.push(DiagItem::error(cat, "postgres health probe timed out after 5s")); - return; - } - }; - - for item in outcome { - items.push(item); - } -} - -/// Result of the blocking Postgres probe, mapped to diagnostic items by the -/// caller. Runs `SELECT 1`, checks pgvector, and a column-parity probe. -fn postgres_probe(db_url: &str) -> Vec { - let cat = "postgres"; - let mut out = Vec::new(); - - let mut cfg = match db_url.parse::() { - Ok(cfg) => cfg, - Err(e) => { - out.push(DiagItem::error(cat, format!("invalid db_url: {e}"))); - return out; - } - }; - cfg.connect_timeout(Duration::from_secs(4)); - - let mut client = match cfg.connect(postgres::NoTls) { - Ok(client) => client, - Err(e) => { - out.push(DiagItem::error(cat, format!("could not connect to postgres: {e}"))); - return out; - } - }; - - // SELECT 1 connectivity probe. - match client.query_one("SELECT 1", &[]) { - Ok(_) => out.push(DiagItem::ok(cat, "SELECT 1 succeeded")), - Err(e) => { - out.push(DiagItem::error(cat, format!("SELECT 1 failed: {e}"))); - return out; - } - } - - // pgvector extension presence + version. - match client.query_opt("SELECT extversion FROM pg_extension WHERE extname = 'vector'", &[]) { - Ok(Some(row)) => { - let version: String = row.try_get(0).unwrap_or_else(|_| "unknown".to_string()); - out.push(DiagItem::ok( - cat, - format!("pgvector extension installed (version {version})"), - )); - } - Ok(None) => out.push(DiagItem::error( - cat, - "pgvector extension not installed (run: CREATE EXTENSION vector;)", - )), - Err(e) => out.push(DiagItem::warn(cat, format!("could not query pg_extension: {e}"))), - } - - // Column-parity probe: the ACL layer relies on memories.owner_id. A missing - // column indicates schema drift between the expected and deployed schema. - match client.query_opt( - "SELECT column_name FROM information_schema.columns \ - WHERE table_name = 'memories' AND column_name = 'owner_id'", - &[], - ) { - Ok(Some(_)) => out.push(DiagItem::ok(cat, "schema parity: memories.owner_id present")), - Ok(None) => out.push(DiagItem::warn( - cat, - "schema parity: memories.owner_id missing or table not yet migrated", - )), - Err(e) => out.push(DiagItem::warn( - cat, - format!("could not inspect information_schema: {e}"), - )), - } - - out -} - -/// FIX-P2-08: Probes the configured custom embedding endpoint with a -/// short-timeout HEAD request (falling back to OPTIONS), so `prx doctor` -/// surfaces an unreachable embedding service before recall silently degrades. -/// Only `custom:` providers expose a probe-able HTTP endpoint; other -/// providers (none/openai/built-in) are skipped. -async fn check_embedding_endpoint(config: &Config, items: &mut Vec) { - let cat = "embedding"; - let provider = config.memory.embedding_provider.trim(); - let Some(url) = provider.strip_prefix("custom:").map(str::trim) else { - // No custom endpoint configured -- nothing to probe here. The provider - // validity itself is reported by check_memory_diagnostics. - return; - }; - if url.is_empty() { - items.push(DiagItem::error(cat, "custom embedding endpoint URL is empty")); - return; - } - - let client = match reqwest::Client::builder().timeout(Duration::from_secs(2)).build() { - Ok(client) => client, - Err(e) => { - items.push(DiagItem::warn(cat, format!("could not build HTTP probe client: {e}"))); - return; - } - }; - - // Try HEAD first; fall back to OPTIONS for gateways that omit HEAD. Any HTTP - // response (including 4xx/405) proves reachability -- we check connectivity, - // not authorization. - let mut reachable = client.head(url).send().await.ok().map(|r| r.status()); - if reachable.is_none() { - reachable = client - .request(reqwest::Method::OPTIONS, url) - .send() - .await - .ok() - .map(|r| r.status()); - } - - match reachable { - Some(status) => items.push(DiagItem::ok( - cat, - format!("embedding endpoint reachable (HTTP {status})"), - )), - None => items.push(DiagItem::warn( - cat, - format!("embedding endpoint unreachable within 2s: {url}"), - )), - } -} - -fn check_memory_diagnostics(config: &Config, items: &mut Vec) { - let cat = "memory"; - items.push(DiagItem::declared(cat, "memory capability available")); - - let backend = - crate::memory::effective_memory_backend_name(&config.memory.backend, Some(&config.storage.provider.config)); - items.push(DiagItem::configured(cat, format!("backend configured as {backend}"))); - items.push(DiagItem::configured( - cat, - format!("workspace path {}", config.workspace_dir.display()), - )); - - let embedder = crate::memory::create_embedder_from_config(config); - if embedder.name() == "none" || embedder.dimensions() == 0 { - items.push(DiagItem::warn( - "embedding", - "embedding provider disabled or unresolved; keyword/FTS search remains the fallback", - )); - } else { - items.push(DiagItem::configured( - "embedding", - format!( - "embedding provider={} model={} dimensions={}", - embedder.name(), - embedder.model(), - embedder.dimensions() - ), - )); - } - - if let Some(notice) = config.embedding_default_upgrade_notice() { - items.push(DiagItem::warn("embedding", notice)); - } - - let provider = config.memory.embedding_provider.trim(); - if provider.starts_with("custom:") { - let url = provider.strip_prefix("custom:").unwrap_or("").trim(); - match reqwest::Url::parse(url) { - Ok(parsed) if matches!(parsed.scheme(), "http" | "https") => { - items.push(DiagItem::configured( - "embedding", - format!("custom embedding endpoint {url}"), - )); - } - _ => items.push(DiagItem::error( - "embedding", - format!("custom embedding endpoint is invalid: {url}"), - )), - } - } - - if config.memory.embedding_dimensions == 0 { - items.push(DiagItem::error( - "embedding", - "memory.embedding_dimensions must be greater than zero when embeddings are enabled", - )); - } - - items.push(DiagItem::declared( - "maintenance", - "run `prx memory reindex` to rebuild SQLite/Lucid memory and document chunk vectors", - )); -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum ModelProbeVerdict { - Skipped, - AuthOrAccess, - Error, -} - -fn classify_model_probe_error(err_message: &str) -> ModelProbeVerdict { - let lower = err_message.to_lowercase(); - - if lower.contains("does not support live model discovery") { - return ModelProbeVerdict::Skipped; - } - - if [ - "401", - "403", - "429", - "unauthorized", - "forbidden", - "api key", - "token", - "insufficient balance", - "insufficient quota", - "plan does not include", - "rate limit", - ] - .iter() - .any(|hint| lower.contains(hint)) - { - return ModelProbeVerdict::AuthOrAccess; - } - - ModelProbeVerdict::Error -} - -fn doctor_model_targets(provider_override: Option<&str>) -> Vec { - if let Some(provider) = provider_override.map(str::trim).filter(|p| !p.is_empty()) { - return vec![provider.to_string()]; - } - - crate::providers::list_providers() - .into_iter() - .map(|provider| provider.name.to_string()) - .collect() -} - -pub fn run_models(config: &Config, provider_override: Option<&str>, use_cache: bool) -> Result<()> { - let targets = doctor_model_targets(provider_override); - - if targets.is_empty() { - anyhow::bail!("No providers available for model probing"); - } - - println!("🩺 OpenPRX Doctor — Model Catalog Probe"); - println!(" Providers to probe: {}", targets.len()); - println!( - " Mode: {}", - if use_cache { "cache-first" } else { "force live refresh" } - ); - println!(); - - let mut ok_count = 0usize; - let mut skipped_count = 0usize; - let mut auth_count = 0usize; - let mut error_count = 0usize; - - for provider_name in &targets { - println!( - " [{}]", - crate::security::redaction::redact_provider_text(provider_name) - ); - - match crate::providers::model_discovery::run_models_probe_read_only(config, Some(provider_name), use_cache) { - Ok(()) => { - ok_count += 1; - println!(" ✅ model catalog check passed"); - } - Err(error) => { - let error_text = crate::security::redaction::redact_provider_text(&format_error_chain(&error)); - match classify_model_probe_error(&error_text) { - ModelProbeVerdict::Skipped => { - skipped_count += 1; - println!(" ⚪ skipped: {}", truncate_for_display(&error_text, 160)); - } - ModelProbeVerdict::AuthOrAccess => { - auth_count += 1; - println!(" ⚠️ auth/access: {}", truncate_for_display(&error_text, 160)); - } - ModelProbeVerdict::Error => { - error_count += 1; - println!(" ❌ error: {}", truncate_for_display(&error_text, 160)); - } - } - } - } - - println!(); - } - - println!( - " Summary: {} ok, {} skipped, {} auth/access, {} errors", - ok_count, skipped_count, auth_count, error_count - ); - - if auth_count > 0 { - println!(" 💡 Some providers need valid API keys/plan access before `/models` can be fetched."); - } - - if provider_override.is_some() && ok_count == 0 { - anyhow::bail!("Model probe failed for target provider") - } - - if error_count > 0 { - anyhow::bail!("Model probe found {error_count} provider error(s)") - } - - Ok(()) -} - -// ── Config semantic validation ─────────────────────────────────── - -/// Resolve the configured default for chat the way every surface does: -/// refused is an error (it will not start), id-only is a warning (it runs, -/// unverified), verified is fine. -fn check_model_selection(config: &Config, items: &mut Vec) { - let cat = "models"; - if let Ok(resolved) = crate::providers::selection::check( - config, - crate::providers::selection::default_provider(config), - crate::providers::selection::default_model(config), - &crate::providers::catalog::Requirement::chat(), - crate::providers::catalog::UnknownPolicy::Invocation, - ) { - if let Some(warning) = crate::providers::selection::pricing_warning(&resolved, &config.cost) { - items.push(DiagItem::warn(cat, warning)); - } else if let Some(notice) = crate::providers::selection::subscription_billing_notice( - resolved.provider_label(), - resolved.model(), - &config.cost, - ) { - items.push(DiagItem::ok(cat, notice)); - } - } - for warning in crate::config::schema::unmatched_cost_price_key_warnings(config) { - items.push(DiagItem::warn("cost", warning)); - } - - match crate::config::model_settings::warnings(config) { - Ok(warnings) => items.extend(warnings.into_iter().map(|warning| DiagItem::warn(cat, warning))), - Err(error) => items.push(DiagItem::error(cat, error.to_string())), - } - match crate::config::manage::lifecycle::diagnostics(config) { - Ok(notes) => items.extend(notes.into_iter().map(|note| { - if note.warning { - DiagItem::warn(cat, note.message) - } else { - DiagItem::with_state(Severity::Ok, DiagnosticState::Unknown, cat, note.message) - } - })), - Err(error) => items.push(DiagItem::error(cat, error.to_string())), - } - match crate::providers::selection::default_status(config) { - Ok((true, line)) => items.push(DiagItem::ok(cat, line)), - Ok((false, line)) => items.push(DiagItem::warn(cat, line)), - Err(line) => items.push(DiagItem::error(cat, line)), - } -} - -/// Every persisted selection besides the default (routes, agents, -/// fallbacks, embeddings, ...) resolved as an existing invocation (SP-PMM -/// H-4): one warning per selection the evidence does not verify, and an -/// error when one no longer resolves. The default is reported by -/// [`check_model_selection`]. Local only; no credential is read. -fn check_persisted_selections(config: &Config, items: &mut Vec) { - let cat = "models"; - // Two embedding routes sharing a hint load, but only the first is used - // (D-104 C-1 ruling): name each with the fix. - for note in crate::config::schema::duplicate_embedding_route_hints(config) { - items.push(DiagItem::warn(cat, note)); - } - match crate::config::manage::validate::check_existing_selections(config) { - Ok(warnings) => { - let unverified = warnings - .into_iter() - .filter(|warning| !warning.starts_with("default model ")) - .collect::>(); - if unverified.is_empty() { - items.push(DiagItem::healthy(cat, "every persisted selection is verified")); - } - for warning in unverified { - items.push(DiagItem::warn(cat, warning)); - } - } - Err(refused) => items.push(DiagItem::error( - cat, - format!("a persisted selection no longer resolves: {refused}"), - )), - } -} - -/// The decision plane reports refused backends and orphaned references. -fn check_decision_plane(config: &Config, items: &mut Vec) { - let cat = "decision"; - if let Some(warning) = crate::config::manage::validate::decision_startup_check(config) { - items.push(DiagItem::warn(cat, warning)); - } - if config.decision_engine.enabled - && let Some(warning) = crate::config::manage::validate::decision_orphans_warning(config) - { - items.push(DiagItem::warn(cat, warning)); - } -} - -/// Use the same registry expansion and provider filter as `RouterEngine::new`. -#[cfg(feature = "llm-router")] -fn check_router_candidates(config: &Config, items: &mut Vec) { - let reachable = crate::router::capability::reachable_provider_names( - crate::providers::selection::default_provider(config), - &config.model_routes, - ); - let candidates = if config.router.models.is_empty() { - crate::router::models::builtin_model_capabilities(&config.cost) - } else { - config.router.models.clone() - }; - let has_reachable_model = crate::router::capability::filter_models_by_providers(candidates, &reachable) - .into_iter() - .any(|model| { - crate::router::capability::is_model_reachable( - crate::providers::selection::default_provider(config), - &config.model_routes, - &model.provider, - &model.model_id, - ) - }); - if !has_reachable_model { - items.push(DiagItem::warn( - "router", - "Router has no reachable candidates after provider/model filtering; configure reachable [[router.models]] entries; the selected default is unchanged", - )); - } -} - -fn check_config_semantics(config: &Config, items: &mut Vec) { - let cat = "config"; - - if !config.autonomy.acknowledge_unrestricted_profile - && !config.autonomy.workspace_only - && config.autonomy.forbidden_paths.is_empty() - && config.autonomy.max_cost_per_day_cents == u32::MAX - { - items.push(DiagItem::warn( - cat, - "explicit unrestricted autonomy profile: host-wide paths and an unbounded cost ceiling", - )); - } - - // Config file exists - if config.config_path.exists() { - items.push(DiagItem::configured( - cat, - format!("config file: {}", config.config_path.display()), - )); - } else { - items.push(DiagItem::error( - cat, - format!("config file not found: {}", config.config_path.display()), - )); - } - - // Provider validity - if let Some(ref provider) = config.default_provider { - if let Some(reason) = provider_validation_error( - config, - provider, - crate::providers::selection::default_model(config), - crate::providers::selection::credential_for(config, provider), - ) { - items.push(DiagItem::error( - cat, - format!("default provider \"{provider}\" is invalid: {reason}"), - )); - } else { - items.push(DiagItem::configured(cat, format!("provider \"{provider}\" is valid"))); - } - } else { - items.push(DiagItem::error(cat, "no default_provider configured")); - } - - // API key / auth profile presence - if config.default_provider.as_deref() != Some("ollama") { - if config.api_key.is_some() { - items.push(DiagItem::configured(cat, "API key configured")); - } else if let Some(provider) = config.default_provider.as_deref() { - match active_auth_profile_credential_status(config, provider) { - AuthProfileCredentialStatus::Present { profile_id } => { - items.push(DiagItem::configured( - cat, - format!("auth profile credential configured for \"{provider}\" ({profile_id})"), - )); - } - AuthProfileCredentialStatus::Unreadable(error) => { - items.push(DiagItem::warn( - cat, - format!("auth profile check failed for \"{provider}\": {error}"), - )); - } - AuthProfileCredentialStatus::Missing => { - items.push(DiagItem::warn(cat, "no api_key or active auth profile credential set")); - } - } - } else { - items.push(DiagItem::warn(cat, "no api_key or default provider set")); - } - } - - // Model configured - if config.default_model.is_some() { - items.push(DiagItem::configured( - cat, - format!("default model: {}", config.default_model.as_deref().unwrap_or("?")), - )); - } else { - items.push(DiagItem::warn(cat, "no default_model configured")); - } - - // Temperature range - if config.default_temperature >= 0.0 && config.default_temperature <= 2.0 { - items.push(DiagItem::configured( - cat, - format!("temperature {:.1} (valid range 0.0–2.0)", config.default_temperature), - )); - } else { - items.push(DiagItem::error( - cat, - format!( - "temperature {:.1} is out of range (expected 0.0–2.0)", - config.default_temperature - ), - )); - } - - // Gateway port range - let port = config.gateway.port; - if port > 0 { - items.push(DiagItem::configured(cat, format!("gateway port: {port}"))); - } else { - items.push(DiagItem::error(cat, "gateway port is 0 (invalid)")); - } - - // Reliability: fallback providers - for fb in &config.reliability.fallback_providers { - // The runtime builds a fallback member other than the primary with no - // released credential (its own env/OAuth store, providers/mod.rs - // `create_provider_with_options(name, None, ..)`), so the check uses - // the same; a member that is the default provider runs on the primary. - let is_default = crate::providers::ProviderId::of(fb) - == crate::providers::ProviderId::of(crate::providers::selection::default_provider(config)); - let credential = if is_default { - crate::providers::selection::credential_for(config, fb) - } else { - crate::providers::credentials::CredentialRef::ProviderStore - }; - if let Some(reason) = provider_validation_error( - config, - fb, - crate::providers::selection::default_model(config), - credential, - ) { - items.push(DiagItem::warn( - cat, - format!("fallback provider \"{fb}\" is invalid: {reason}"), - )); - } - // A self-hosted fallback answers only `model_fallbacks` entries that - // name a model repository (D-076 N-1); without one it is never used. - let default_is_same = config - .default_provider - .as_deref() - .is_some_and(|default| default.trim().eq_ignore_ascii_case(fb.trim())); - if crate::providers::is_self_hosted_model_server(fb) - && !default_is_same - && !config - .reliability - .model_fallbacks - .values() - .flatten() - .any(|model| crate::providers::names_model_repository(model)) - { - items.push(DiagItem::warn( - cat, - format!( - "fallback provider \"{fb}\" is never used: as a fallback it answers only \ - reliability.model_fallbacks entries that name one of its model repositories \ - (org/repository), and none does" - ), - )); - } - } - let route_providers: HashSet = config - .model_routes - .iter() - .map(|route| route.provider.trim().to_string()) - .filter(|provider| !provider.is_empty()) - .collect(); - for (source_model, fallback_chain) in &config.reliability.model_fallbacks { - if fallback_chain.is_empty() { - items.push(DiagItem::warn( - cat, - format!( - "model_fallbacks entry \"{source_model}\" has an empty fallback chain; it will never take effect" - ), - )); - continue; - } - - for fallback_model in fallback_chain { - if !model_has_reachable_provider( - crate::providers::selection::default_provider(config), - &config.reliability.fallback_providers, - &route_providers, - fallback_model, - ) { - items.push(DiagItem::warn( - cat, - format!( - "model_fallbacks route mismatch: fallback model \"{fallback_model}\" has no compatible provider in default/fallback/model_routes" - ), - )); - } - } - } - - let availability = crate::providers::summarize_provider_availability( - crate::providers::selection::default_provider(config), - config.api_key.as_deref(), - &config.reliability, - &crate::providers::provider_runtime_options_from_config(config), - ); - if availability.degraded && !config.reliability.acknowledge_single_provider_risk { - items.push(DiagItem::warn( - cat, - format!( - "provider resilience degraded: only {} configured+available provider(s) (need >=2). available=[{}]", - availability.available.len(), - availability.available.join(", ") - ), - )); - } else { - items.push(DiagItem::ready( - cat, - format!( - "provider resilience ready: {} configured+available providers [{}]", - availability.available.len(), - availability.available.join(", ") - ), - )); - } - if !availability.unavailable.is_empty() { - items.push(DiagItem::warn( - cat, - format!( - "unavailable providers: {}", - availability - .unavailable - .iter() - .map(|(name, reason)| format!("{name}: {reason}")) - .collect::>() - .join("; ") - ), - )); - } - - // Model routes validation - for route in &config.model_routes { - if route.hint.is_empty() { - items.push(DiagItem::warn(cat, "model route with empty hint")); - } - let credential = route.credential_ref.as_deref().map_or_else( - || { - if route.api_key.as_deref().is_some_and(|key| !key.trim().is_empty()) { - crate::providers::credentials::CredentialRef::LegacyInline( - crate::providers::credentials::LegacySlot::ModelRoute(route.hint.clone()), - ) - } else { - crate::providers::selection::credential_for(config, &route.provider) - } - }, - |id| crate::providers::credentials::CredentialRef::Profile { id: id.to_string() }, - ); - if let Some(reason) = provider_validation_error(config, &route.provider, &route.model, credential) { - items.push(DiagItem::warn( - cat, - format!( - "model route \"{}\" uses invalid provider \"{}\": {}", - route.hint, route.provider, reason - ), - )); - } - if route.model.is_empty() { - items.push(DiagItem::warn( - cat, - format!("model route \"{}\" has empty model", route.hint), - )); - } - } - - // Embedding routes validation - for route in &config.embedding_routes { - if route.hint.trim().is_empty() { - items.push(DiagItem::warn(cat, "embedding route with empty hint")); - } - if let Some(reason) = embedding_provider_validation_error(&route.provider) { - items.push(DiagItem::warn( - cat, - format!( - "embedding route \"{}\" uses invalid provider \"{}\": {}", - route.hint, route.provider, reason - ), - )); - } - if route.model.trim().is_empty() { - items.push(DiagItem::warn( - cat, - format!("embedding route \"{}\" has empty model", route.hint), - )); - } - if route.dimensions.is_some_and(|value| value == 0) { - items.push(DiagItem::warn( - cat, - format!("embedding route \"{}\" has invalid dimensions=0", route.hint), - )); - } - } - - if let Some(hint) = config - .memory - .embedding_model - .strip_prefix("hint:") - .map(str::trim) - .filter(|value| !value.is_empty()) - { - if !config.embedding_routes.iter().any(|route| route.hint.trim() == hint) { - items.push(DiagItem::warn( - cat, - format!( - "memory.embedding_model uses hint \"{hint}\" but no matching [[embedding_routes]] entry exists" - ), - )); - } - } - - // Channel: at least one configured - let cc = &config.channels_config; - let has_channel = cc.telegram.is_some() - || cc.discord.is_some() - || cc.slack.is_some() - || cc.imessage.is_some() - || cc.whatsapp.is_some() - || cc.wacli.is_some() - || cc.nextcloud_talk.is_some() - || cc.email.is_some() - || cc.irc.is_some() - || cc.lark.is_some() - || cc.webhook.is_some(); - - if has_channel { - items.push(DiagItem::configured(cat, "at least one channel configured")); - } else { - items.push(DiagItem::warn( - cat, - "no channels configured — run `prx init` to set one up", - )); - } - - // Delegate agents: provider validity - let mut agent_names: Vec<_> = config.agents.keys().collect(); - agent_names.sort(); - for name in agent_names { - let Some(agent) = config.agents.get(name) else { - continue; - }; - let credential = agent.credential_ref.as_deref().map_or_else( - || { - if agent.api_key.as_deref().is_some_and(|key| !key.trim().is_empty()) { - crate::providers::credentials::CredentialRef::LegacyInline( - crate::providers::credentials::LegacySlot::Agent(name.clone()), - ) - } else { - crate::providers::selection::credential_for(config, &agent.provider) - } - }, - |id| crate::providers::credentials::CredentialRef::Profile { id: id.to_string() }, - ); - if let Some(reason) = provider_validation_error(config, &agent.provider, &agent.model, credential) { - items.push(DiagItem::warn( - cat, - format!( - "agent \"{name}\" uses invalid provider \"{}\": {}", - agent.provider, reason - ), - )); - } - if agent.agentic && agent.allowed_tools.iter().any(|tool| tool.trim() == "*") { - items.push(DiagItem::warn( - cat, - format!("agent \"{name}\" explicitly inherits all eligible parent tools"), - )); - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -enum AuthProfileCredentialStatus { - Present { profile_id: String }, - Missing, - Unreadable(String), -} - -fn active_auth_profile_credential_status(config: &Config, provider: &str) -> AuthProfileCredentialStatus { - let Some(openprx_dir) = config.config_path.parent() else { - return AuthProfileCredentialStatus::Missing; - }; - let canonical_provider = crate::providers::canonical_china_provider_name(provider) - .unwrap_or(provider) - .to_string(); - // Read-only: a diagnosis never rewrites the profiles file (D-084 E-3). - let store = crate::auth::profiles::AuthProfilesStore::new(openprx_dir, config.secrets.encrypt); - let data = match store.load_read_only() { - Ok(data) => data, - Err(error) => return AuthProfileCredentialStatus::Unreadable(error.to_string()), - }; - let Some(profile_id) = data.active_profiles.get(&canonical_provider) else { - return AuthProfileCredentialStatus::Missing; - }; - let Some(profile) = data.profiles.get(profile_id) else { - return AuthProfileCredentialStatus::Missing; - }; - let credential = profile - .token - .as_deref() - .or_else(|| profile.token_set.as_ref().map(|tokens| tokens.access_token.as_str())) - .map(str::trim); - if credential.is_some_and(|token| !token.is_empty()) { - AuthProfileCredentialStatus::Present { - profile_id: profile_id.clone(), - } - } else { - AuthProfileCredentialStatus::Missing - } -} - -fn provider_validation_error( - config: &Config, - name: &str, - model: &str, - credential: crate::providers::credentials::CredentialRef, -) -> Option { - let catalog = crate::providers::selection::catalog_for(config); - let resolved = match crate::providers::selection::check_with( - config, - &catalog, - name, - model, - credential, - &crate::providers::catalog::Requirement::chat(), - crate::providers::catalog::UnknownPolicy::Invocation, - ) { - Ok(resolved) => resolved, - Err(error @ crate::providers::catalog::ResolutionError::UnknownProvider { .. }) => { - return Some(format!("Unknown provider: {error}")); - } - Err(error) => return Some(error.to_string()), - }; - let mut reliability = config.reliability.clone(); - reliability.fallback_providers.clear(); - reliability.api_keys.clear(); - reliability.model_fallbacks.clear(); - match crate::providers::create_provider_for( - &resolved, - &catalog, - &reliability, - &config.cost, - &crate::providers::provider_runtime_options_from_config(config), - ) { - Ok(_) => None, - // A missing credential is reported by the credential checks, not - // as an invalid provider here. - Err(error) - if error - .downcast_ref::() - .is_some() => - { - None - } - Err(error) => Some(error.to_string().lines().next().unwrap_or("invalid provider").into()), - } -} - -fn model_has_reachable_provider( - default_provider: &str, - fallback_providers: &[String], - route_providers: &HashSet, - model: &str, -) -> bool { - // As the failover chain decides (D-075): a self-hosted model server - // serves any repository on its own route (the default provider, a model - // route) and never answers as a fallback for another provider's route. - let serves_own_route = |provider: &str| { - if crate::providers::is_self_hosted_model_server(provider) { - crate::providers::provider_serves_configured_model(provider, model) - } else { - crate::providers::provider_matches_model_prefix(provider, model) - } - }; - if serves_own_route(default_provider) { - return true; - } - if fallback_providers.iter().any(|provider| { - if crate::providers::is_self_hosted_model_server(provider) { - // A fallback model is a `model_fallbacks` entry (D-076 N-1). - crate::providers::names_model_repository(model) - } else { - crate::providers::provider_matches_model_prefix(provider, model) - } - }) { - return true; - } - route_providers.iter().any(|provider| serves_own_route(provider)) -} - -fn embedding_provider_validation_error(name: &str) -> Option { - let normalized = name.trim(); - if normalized.eq_ignore_ascii_case("local") - || normalized.eq_ignore_ascii_case("none") - || normalized.eq_ignore_ascii_case("openai") - { - return None; - } - - let Some(url) = normalized.strip_prefix("custom:") else { - return Some("supported values: local, none, openai, custom:".into()); - }; - - let url = url.trim(); - if url.is_empty() { - return Some("custom provider requires a non-empty URL after 'custom:'".into()); - } - - match reqwest::Url::parse(url) { - Ok(parsed) if matches!(parsed.scheme(), "http" | "https") => None, - Ok(parsed) => Some(format!( - "custom provider URL must use http/https, got '{}'", - parsed.scheme() - )), - Err(err) => Some(format!("invalid custom provider URL: {err}")), - } -} - -// ── Workspace integrity ────────────────────────────────────────── - -fn check_workspace(config: &Config, items: &mut Vec) { - let cat = "workspace"; - let ws = &config.workspace_dir; - - if ws.exists() { - items.push(DiagItem::ok(cat, format!("directory exists: {}", ws.display()))); - } else { - items.push(DiagItem::error(cat, format!("directory missing: {}", ws.display()))); - return; - } - - // Doctor is diagnostic-only: prove readability and report declared write - // permission without creating a probe file. - match std::fs::read_dir(ws) { - Ok(_) => items.push(DiagItem::ready(cat, "directory is readable; no write probe performed")), - Err(error) => items.push(DiagItem::error(cat, format!("directory is not readable: {error}"))), - } - #[cfg(unix)] - if let Ok(metadata) = std::fs::metadata(ws) { - use std::os::unix::fs::PermissionsExt; - if metadata.permissions().mode() & 0o222 == 0 { - items.push(DiagItem::with_state( - Severity::Warn, - DiagnosticState::Configured, - cat, - "directory has no declared write permission bits; write capability was not exercised", - )); - } else { - items.push(DiagItem::configured( - cat, - "directory declares write permission; capability was not exercised", - )); - } - } - - // Disk space (best-effort via `df`) - if let Some(avail_mb) = disk_available_mb(ws) { - if avail_mb >= 100 { - items.push(DiagItem::ok(cat, format!("disk space: {avail_mb} MB available"))); - } else { - items.push(DiagItem::warn( - cat, - format!("low disk space: only {avail_mb} MB available"), - )); - } - } - - // Key workspace files - for name in ["SOUL.md", "AGENTS.md"] { - check_file_exists( - &crate::identity::root::file_directory(ws, name), - name, - false, - cat, - items, - ); - } -} - -fn check_file_exists(base: &Path, name: &str, required: bool, cat: &'static str, items: &mut Vec) { - let path = base.join(name); - if path.is_file() { - items.push(DiagItem::ok(cat, format!("{name} present"))); - } else if required { - items.push(DiagItem::error(cat, format!("{name} missing"))); - } else { - items.push(DiagItem::warn(cat, format!("{name} not found (optional)"))); - } -} - -fn disk_available_mb(path: &Path) -> Option { - let output = std::process::Command::new("df").arg("-m").arg(path).output().ok()?; - if !output.status.success() { - return None; - } - let stdout = String::from_utf8_lossy(&output.stdout); - parse_df_available_mb(&stdout) -} - -fn parse_df_available_mb(stdout: &str) -> Option { - let line = stdout.lines().rev().find(|line| !line.trim().is_empty())?; - let avail = line.split_whitespace().nth(3)?; - avail.parse::().ok() -} - -// ── Daemon state (original logic, preserved) ───────────────────── - -fn check_daemon_state(config: &Config, items: &mut Vec) { - let cat = "daemon"; - let state_file = crate::daemon::state_file_path(config); - - if !state_file.exists() { - items.push(DiagItem::error( - cat, - format!( - "state file not found: {} — is the daemon running?", - state_file.display() - ), - )); - return; - } - - let raw = match std::fs::read_to_string(&state_file) { - Ok(r) => r, - Err(e) => { - items.push(DiagItem::error(cat, format!("cannot read state file: {e}"))); - return; - } - }; - - let snapshot: serde_json::Value = match serde_json::from_str(&raw) { - Ok(v) => v, - Err(e) => { - items.push(DiagItem::error(cat, format!("invalid state JSON: {e}"))); - return; - } - }; - - // Daemon heartbeat freshness - let updated_at = snapshot - .get("updated_at") - .and_then(serde_json::Value::as_str) - .unwrap_or(""); - - if let Ok(ts) = DateTime::parse_from_rfc3339(updated_at) { - let age = Utc::now().signed_duration_since(ts.with_timezone(&Utc)).num_seconds(); - if age <= DAEMON_STALE_SECONDS { - items.push(DiagItem::ok(cat, format!("heartbeat fresh ({age}s ago)"))); - } else { - items.push(DiagItem::error(cat, format!("heartbeat stale ({age}s ago)"))); - } - } else { - items.push(DiagItem::error(cat, format!("invalid daemon timestamp: {updated_at}"))); - } - - if let Some(generation) = snapshot.get("config_generation") { - let active = generation.get("active_generation").and_then(serde_json::Value::as_u64); - let desired_revision = generation - .get("desired_source_revision") - .and_then(|revision| revision.get("fingerprint_sha256")) - .and_then(serde_json::Value::as_str) - .unwrap_or("unknown"); - let in_progress = generation - .get("reload_in_progress") - .and_then(serde_json::Value::as_bool) - .unwrap_or(false); - items.push(DiagItem::ok( - "config-generation", - format!( - "active generation {} (desired revision {}, reload_in_progress={in_progress})", - active.map_or_else(|| "unknown".to_string(), |value| value.to_string()), - desired_revision - ), - )); - - if let Some(failure) = generation.get("last_failure").filter(|failure| !failure.is_null()) { - let error = failure - .get("error") - .and_then(serde_json::Value::as_str) - .unwrap_or("unknown reload failure"); - items.push(DiagItem::error( - "config-generation", - format!("last config reload failed: {error}"), - )); - } else if let Some(restart_required) = generation - .get("last_report") - .and_then(|report| report.get("restart_required")) - .and_then(serde_json::Value::as_array) - .filter(|fields| !fields.is_empty()) - { - let fields = restart_required - .iter() - .filter_map(serde_json::Value::as_str) - .collect::>() - .join(", "); - items.push(DiagItem::warn( - "config-generation", - format!("desired config requires process restart for: {fields}"), - )); - } - } else { - items.push(DiagItem::unknown( - "config-generation", - "daemon state does not expose config generation status", - )); - } - - // Components - if let Some(components) = snapshot.get("components").and_then(serde_json::Value::as_object) { - // Do not hard-code runtime truth to scheduler and channel:* only. Any - // tracked active owner that reports unhealthy must be visible in doctor. - for (name, component) in components { - if name == "scheduler" || name.starts_with("channel:") { - continue; - } - let status = component - .get("status") - .and_then(serde_json::Value::as_str) - .unwrap_or("unknown"); - if status == "ok" || status == "disabled" { - continue; - } - let detail = component - .get("last_error") - .and_then(serde_json::Value::as_str) - .unwrap_or("runtime component is not healthy"); - items.push(DiagItem::error(cat, format!("{name} unhealthy ({status}): {detail}"))); - } - - // Scheduler - if let Some(scheduler) = components.get("scheduler") { - { - let scheduler_ok = scheduler - .get("status") - .and_then(serde_json::Value::as_str) - .is_some_and(|s| s == "ok"); - let scheduler_age = scheduler - .get("last_ok") - .and_then(serde_json::Value::as_str) - .and_then(parse_rfc3339) - .map_or(i64::MAX, |dt| Utc::now().signed_duration_since(dt).num_seconds()); - - if scheduler_ok && scheduler_age <= SCHEDULER_STALE_SECONDS { - items.push(DiagItem::ok( - cat, - format!("scheduler healthy (last ok {scheduler_age}s ago)"), - )); - } else { - items.push(DiagItem::error( - cat, - format!("scheduler unhealthy (ok={scheduler_ok}, age={scheduler_age}s)"), - )); - } - } - } else { - items.push(DiagItem::unknown(cat, "scheduler component not tracked yet")); - } - - // Channels - let mut channel_count = 0u32; - let mut stale = 0u32; - for (name, component) in components { - if !name.starts_with("channel:") { - continue; - } - channel_count += 1; - let status_ok = component - .get("status") - .and_then(serde_json::Value::as_str) - .is_some_and(|s| s == "ok"); - let age = component - .get("last_ok") - .and_then(serde_json::Value::as_str) - .and_then(parse_rfc3339) - .map_or(i64::MAX, |dt| Utc::now().signed_duration_since(dt).num_seconds()); - - // Measured listener activity, when the channel publishes it. The - // supervisor derives health from real traffic rather than from its own - // heartbeat timer, so a wedged listener shows up here as a stall with - // the silence duration attached. Purely informational: `prx doctor` - // reports, it never restarts anything. - let activity = component.get("activity"); - let stalled = activity - .and_then(|activity| activity.get("stalled")) - .and_then(serde_json::Value::as_bool) - .unwrap_or(false); - let idle_seconds = activity - .and_then(|activity| activity.get("idle_seconds")) - .and_then(serde_json::Value::as_u64); - let liveness = activity - .and_then(|activity| activity.get("liveness")) - .and_then(serde_json::Value::as_str); - - if stalled { - stale += 1; - let idle = idle_seconds.unwrap_or_default(); - items.push(DiagItem::error( - cat, - format!("{name} listener stalled (no receive activity for {idle}s)"), - )); - } else if status_ok && age <= CHANNEL_STALE_SECONDS { - let detail = match (liveness, idle_seconds) { - (Some("passive"), Some(idle)) => { - // No cadence to measure against, so "fresh" here means the - // supervisor is alive, not that the channel proved itself. - format!("{name} fresh ({age}s ago, push-only, idle {idle}s)") - } - (_, Some(idle)) => format!("{name} fresh ({age}s ago, idle {idle}s)"), - (_, None) => format!("{name} fresh ({age}s ago)"), - }; - items.push(DiagItem::ok(cat, detail)); - } else { - stale += 1; - items.push(DiagItem::error( - cat, - format!("{name} stale (ok={status_ok}, age={age}s)"), - )); - } - } - - if channel_count == 0 { - items.push(DiagItem::unknown(cat, "no channel components tracked yet")); - } else if stale > 0 { - items.push(DiagItem::warn(cat, format!("{channel_count} channels, {stale} stale"))); - } - } -} - -// ── Daemon process PATH ────────────────────────────────────────── -// -// A hand-written unit without `Environment="PATH=…"` leaves the daemon with -// systemd's default PATH, which does not contain `~/.cargo/bin`. The model -// then gets `sh: prx: not found` from the shell tool while `prx doctor`, run -// from an interactive shell, sees a perfectly healthy PATH. The daemon's own -// environment is the only place that truth is visible, so read it from -// `/proc//environ` instead of trusting the doctor process. - -const DAEMON_PATH_CATEGORY: &str = "daemon"; - -/// Non-failing outcome: the daemon PATH could not be inspected at all. -/// Reported as `Ok`/`Unknown` so an uninspectable daemon never turns -/// `prx doctor` red. -fn daemon_path_skipped(msg: impl Into) -> DiagItem { - DiagItem::with_state(Severity::Ok, DiagnosticState::Unknown, DAEMON_PATH_CATEGORY, msg) -} - -#[cfg(any(target_os = "linux", test))] -fn canonical_or_owned(path: &Path) -> PathBuf { - path.canonicalize().unwrap_or_else(|_| path.to_path_buf()) -} - -/// True for a Cargo build output directory (`…//debug`, -/// `…/target/release`, `…/target//debug/deps`, …). -/// -/// Such a directory must never enter the required set: `cargo run -- doctor`, -/// `./target/release/prx doctor` and one-shot CI copies all run from one, and -/// the repair text would then tell the operator to put a build directory on the -/// daemon's `PATH` — an operational step that outlives the build tree. -#[cfg(any(target_os = "linux", test))] -fn is_cargo_build_dir(path: &Path) -> bool { - let profile_dir = if path.file_name().is_some_and(|name| name == "deps") { - path.parent().unwrap_or(path) - } else { - path - }; - if !profile_dir - .file_name() - .is_some_and(|name| name == "debug" || name == "release") - { - return false; - } - // `deps` is a Cargo artifact directory even when a copied layout no - // longer has its siblings. A profile directory itself needs layout proof. - path != profile_dir - || ["deps", "build", ".fingerprint"] - .iter() - .any(|name| profile_dir.join(name).is_dir()) -} - -/// The deployed daemon binary as the daemon itself recorded it in -/// `daemon_state.json`, when that field is present. -/// -/// This is the authoritative answer to "which directory must the daemon's PATH -/// contain": it is the daemon's own binary, not the doctor's. -#[cfg(any(target_os = "linux", test))] -fn daemon_binary_from_state(config: &Config) -> Option { - let raw = std::fs::read_to_string(crate::daemon::state_file_path(config)).ok()?; - let snapshot: serde_json::Value = serde_json::from_str(&raw).ok()?; - let recorded = snapshot.get("binary_path").and_then(serde_json::Value::as_str)?; - let trimmed = recorded.trim(); - if trimmed.is_empty() { - return None; - } - Some(PathBuf::from(trimmed)) -} - -/// Directories the daemon PATH must contain for a shell tool to resolve `prx`. -/// -/// The daemon's own binary directory (from `daemon_state.json`) when it is -/// recorded, otherwise this doctor's directory as a best-effort stand-in — and -/// then only when it is not a build output directory. Plus `~/.cargo/bin` when -/// it exists, the default `cargo install` target. -#[cfg(any(target_os = "linux", test))] -fn required_daemon_path_dirs(daemon_binary: Option<&Path>) -> Vec { - let mut dirs: Vec = Vec::new(); - let recorded_parent = daemon_binary.and_then(Path::parent).map(canonical_or_owned); - if let Some(parent) = recorded_parent { - dirs.push(parent); - } else if let Ok(current) = std::env::current_exe() { - if let Some(parent) = current.parent().map(canonical_or_owned) { - if !is_cargo_build_dir(&parent) { - dirs.push(parent); - } - } - } - if let Some(home) = crate::config::user_home_dir() { - let cargo_bin = home.join(".cargo").join("bin"); - if cargo_bin.is_dir() { - dirs.push(canonical_or_owned(&cargo_bin)); - } - } - let mut unique: Vec = Vec::with_capacity(dirs.len()); - for dir in dirs { - if !unique.contains(&dir) { - unique.push(dir); - } - } - unique -} - -/// True when a process identity (its `exe` link and/or its `cmdline` payload) -/// belongs to a prx binary. -/// -/// Only the *file name* is matched, never the whole path: a prx checkout lives -/// in a directory called `prx`, so a path match would call every process -/// started from that tree a daemon. -#[cfg(any(target_os = "linux", test))] -fn process_identity_looks_like_prx(exe: Option<&Path>, cmdline: &[u8]) -> bool { - let named_prx = |path: &Path| { - path.file_name() - .and_then(std::ffi::OsStr::to_str) - .is_some_and(|name| name.contains("prx")) - }; - if exe.is_some_and(named_prx) { - return true; - } - cmdline - .split(|byte| *byte == 0) - .find(|entry| !entry.is_empty()) - .and_then(|argv0| std::str::from_utf8(argv0).ok()) - .is_some_and(|argv0| named_prx(Path::new(argv0))) -} - -/// Extract `PATH` from a NUL-separated `/proc//environ` payload. -#[cfg(any(target_os = "linux", test))] -fn daemon_path_from_environ(bytes: &[u8]) -> Option { - bytes - .split(|byte| *byte == 0) - .filter_map(|entry| std::str::from_utf8(entry).ok()) - .find_map(|entry| entry.strip_prefix("PATH=").map(str::to_owned)) -} - -#[cfg(any(target_os = "linux", test))] -fn path_contains_dir(path: &str, dir: &Path) -> bool { - std::env::split_paths(path) - .filter(|entry| !entry.as_os_str().is_empty()) - .any(|entry| same_executable_path(&entry, dir)) -} - -/// Pure judgement over a daemon PATH value, so the decision is testable -/// without a live daemon. -#[cfg(any(target_os = "linux", test))] -fn evaluate_daemon_path(path: &str, required_dirs: &[PathBuf]) -> DiagItem { - let missing: Vec = required_dirs - .iter() - .filter(|dir| !path_contains_dir(path, dir)) - .map(|dir| dir.display().to_string()) - .collect(); - - if missing.is_empty() { - return DiagItem::ok( - DAEMON_PATH_CATEGORY, - format!("daemon process PATH resolves the deployed prx binary: {path}"), - ); - } - - let missing_list = missing.join(", "); - let suggested = if path.is_empty() { - missing.join(":") - } else { - format!("{}:{path}", missing.join(":")) - }; - DiagItem::warn( - DAEMON_PATH_CATEGORY, - format!( - "daemon PATH does not include {missing_list}; shell tool cannot find prx — \ - add Environment=\"PATH={suggested}\" to the unit or re-run `prx service install` \ - (daemon PATH: {path})" - ), - ) -} - -#[cfg(any(target_os = "linux", test))] -fn evaluate_daemon_environ(bytes: &[u8], required_dirs: &[PathBuf]) -> DiagItem { - daemon_path_from_environ(bytes).map_or_else( - || { - DiagItem::warn( - DAEMON_PATH_CATEGORY, - "daemon process environment carries no PATH entry; shell tool cannot find prx — \ - add Environment=\"PATH=…\" to the unit or re-run `prx service install`", - ) - }, - |path| evaluate_daemon_path(&path, required_dirs), - ) -} - -fn daemon_pid_from_state(config: &Config) -> Option { - let raw = std::fs::read_to_string(crate::daemon::state_file_path(config)).ok()?; - let snapshot: serde_json::Value = serde_json::from_str(&raw).ok()?; - snapshot - .get("pid") - .and_then(serde_json::Value::as_u64) - .and_then(|pid| u32::try_from(pid).ok()) -} - -#[cfg(target_os = "linux")] -fn read_daemon_environ(pid: u32) -> std::io::Result> { - std::fs::read(format!("/proc/{pid}/environ")) -} - -/// Best-effort ownership check for the pid recorded in `daemon_state.json`. -/// -/// A pid outlives the daemon that wrote it: after a crash the number is reused -/// by an unrelated process, and reading *that* process' environment would make -/// `prx doctor` judge the daemon PATH from a stranger's `PATH`. Unreadable -/// `/proc` entries (the process is gone, or is owned by another user) answer -/// `false`, which routes the check to its skip branch rather than a verdict. -#[cfg(target_os = "linux")] -fn pid_belongs_to_prx(pid: u32) -> bool { - let exe = std::fs::read_link(format!("/proc/{pid}/exe")).ok(); - let cmdline = std::fs::read(format!("/proc/{pid}/cmdline")).unwrap_or_default(); - process_identity_looks_like_prx(exe.as_deref(), &cmdline) -} - -fn check_daemon_process_path(config: &Config, items: &mut Vec) { - let Some(pid) = daemon_pid_from_state(config) else { - items.push(daemon_path_skipped( - "daemon state exposes no pid; skipped daemon PATH inspection", - )); - return; - }; - - #[cfg(target_os = "linux")] - if pid_belongs_to_prx(pid) { - let required = required_daemon_path_dirs(daemon_binary_from_state(config).as_deref()); - match read_daemon_environ(pid) { - Ok(bytes) => items.push(evaluate_daemon_environ(&bytes, &required)), - Err(error) => items.push(daemon_path_skipped(format!( - "cannot read /proc/{pid}/environ ({error}); skipped daemon PATH inspection" - ))), - } - } else { - items.push(daemon_path_skipped(format!( - "daemon state pid {pid} is not a live prx process (pid reuse or a stopped daemon); \ - skipped reading /proc/{pid}/environ" - ))); - } - - #[cfg(not(target_os = "linux"))] - items.push(daemon_path_skipped(format!( - "daemon PATH inspection is only supported on Linux; skipped for daemon pid {pid}" - ))); -} - -// ── Environment checks ─────────────────────────────────────────── - -fn check_environment(items: &mut Vec) { - let cat = "environment"; - - // git - check_command_available("git", &["--version"], cat, items); - - // Shell - let shell = std::env::var("SHELL").unwrap_or_default(); - if shell.is_empty() { - items.push(DiagItem::warn(cat, "$SHELL not set")); - } else { - items.push(DiagItem::ok(cat, format!("shell: {shell}"))); - } - - // HOME - if std::env::var("HOME").is_ok() || std::env::var("USERPROFILE").is_ok() { - items.push(DiagItem::ok(cat, "home directory env set")); - } else { - items.push(DiagItem::error(cat, "neither $HOME nor $USERPROFILE is set")); - } - - // Optional tools - check_command_available("curl", &["--version"], cat, items); -} - -fn check_command_available(cmd: &str, args: &[&str], cat: &'static str, items: &mut Vec) { - match std::process::Command::new(cmd) - .args(args) - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .output() - { - Ok(output) if output.status.success() => { - let ver = String::from_utf8_lossy(&output.stdout); - let first_line = ver.lines().next().unwrap_or("").trim(); - let display = truncate_for_display(first_line, COMMAND_VERSION_PREVIEW_CHARS); - items.push(DiagItem::ok(cat, format!("{cmd}: {display}"))); - } - Ok(_) => { - items.push(DiagItem::warn(cat, format!("{cmd} found but returned non-zero"))); - } - Err(_) => { - items.push(DiagItem::warn(cat, format!("{cmd} not found in PATH"))); - } - } -} - -fn format_error_chain(error: &anyhow::Error) -> String { - let mut parts = Vec::new(); - for cause in error.chain() { - let message = cause.to_string(); - if !message.is_empty() { - parts.push(message); - } - } - - if parts.is_empty() { - return String::new(); - } - - parts.join(": ") -} - -fn truncate_for_display(input: &str, max_chars: usize) -> String { - let mut chars = input.chars(); - let preview: String = chars.by_ref().take(max_chars).collect(); - if chars.next().is_some() { - format!("{preview}…") - } else { - preview - } -} - -// ── Helpers ────────────────────────────────────────────────────── - -fn parse_rfc3339(raw: &str) -> Option> { - DateTime::parse_from_rfc3339(raw).ok().map(|dt| dt.with_timezone(&Utc)) -} - #[cfg(test)] -mod tests { - #![allow( - clippy::indexing_slicing, - clippy::unwrap_used, - clippy::print_stdout, - clippy::print_stderr, - clippy::disallowed_types, - clippy::disallowed_methods, - clippy::needless_collect, - clippy::unreadable_literal - )] - use super::*; - use tempfile::TempDir; - - #[test] - fn doctor_names_subscription_billing_without_an_unpriced_refusal() { - let dir = TempDir::new().unwrap(); - let mut config = Config::default(); - config.workspace_dir = dir.path().join("workspace"); - config.config_path = dir.path().join("config.toml"); - config.default_provider = Some("kimi-code".into()); - config.default_model = Some("kimi-for-coding".into()); - let mut items = Vec::new(); - check_model_selection(&config, &mut items); - assert!(items.iter().any(|item| { - item.severity == Severity::Ok && item.message == "subscription-billed, no per-token cost recorded" - })); - assert!( - items - .iter() - .all(|item| !item.message.contains("G6 budget admission refuses")) - ); - - config.default_provider = Some("openrouter".into()); - config.default_model = Some("deepseek/deepseek-v3.2".into()); - items.clear(); - check_model_selection(&config, &mut items); - assert!(items.iter().any(|item| { - item.severity == Severity::Warn && item.message.contains(r#"[cost.prices."deepseek/deepseek-v3.2"]"#) - })); - } - - #[test] - fn doctor_warns_when_a_cost_price_key_matches_no_configured_model() { - let mut config = Config::default(); - config.default_provider = Some("custom:http://127.0.0.1:9/v1".into()); - config.default_model = Some("moonshotai/kimi-k2.5".into()); - config.cost.prices.insert( - "custom:http://127.0.0.1:9/v1/moonshotai/kimi-k2.5".into(), - crate::config::schema::ModelPricing { - input: 1.0, - output: 2.0, - cache_write: 1.0, - cache_read: 0.5, - }, - ); - let mut items = Vec::new(); - check_model_selection(&config, &mut items); - assert!(items.iter().any(|item| { - item.severity == Severity::Warn - && item.category == "cost" - && item.message.contains("expected key is \"moonshotai/kimi-k2.5\"") - })); - - config.cost.prices.clear(); - config.cost.prices.insert( - "moonshotai/kimi-k2.5".into(), - crate::config::schema::ModelPricing { - input: 1.0, - output: 2.0, - cache_write: 1.0, - cache_read: 0.5, - }, - ); - items.clear(); - check_model_selection(&config, &mut items); - assert!(items.iter().all(|item| item.category != "cost")); - } - - #[test] - fn doctor_reports_invalid_saved_model_settings_as_repairable_warnings() { - let mut config = Config::default(); - config.default_provider = Some("openai".into()); - config.default_model = Some("gpt-5.6".into()); - config.model_settings.insert( - "openai/gpt-5.6".into(), - serde_json::from_value(serde_json::json!({"level":"future"})).unwrap(), - ); - let mut items = Vec::new(); - check_model_selection(&config, &mut items); - assert!(items.iter().any(|item| item.message.contains("saved level"))); - } - - #[test] - fn absent_catalog_lifecycle_is_informational_without_claiming_model_health() { - let config = Config { - default_provider: Some("openai".into()), - default_model: Some("prx-unlisted-model".into()), - ..Default::default() - }; - let mut items = Vec::new(); - check_model_selection(&config, &mut items); - let note = items - .iter() - .find(|item| item.message.contains("deleted or custom")) - .unwrap(); - assert_eq!(note.severity, Severity::Ok); - assert_eq!(note.state, DiagnosticState::Unknown); - } - - #[cfg(feature = "llm-router")] - #[test] - fn doctor_surfaces_an_empty_router_registry_beyond_the_startup_log() { - let mut config = Config::default(); - config.default_provider = Some("openai".to_owned()); - config.default_model = Some("gpt-5.6".to_owned()); - let mut items = Vec::new(); - check_router_candidates(&config, &mut items); - assert_eq!(items.len(), 1); - assert!( - items - .iter() - .any(|item| item.message.contains("no reachable candidates")) - ); - assert_eq!(config.default_model.as_deref(), Some("gpt-5.6")); - - config.default_provider = Some("openrouter".to_owned()); - config.default_model = Some("anthropic/claude-sonnet-5".to_owned()); - items.clear(); - check_router_candidates(&config, &mut items); - assert!( - items.is_empty(), - "the published OpenRouter candidate must actually be reachable" - ); - } - - #[cfg(feature = "llm-router")] - #[test] - fn doctor_requires_a_reachable_model_in_a_non_default_provider_route() { - let mut config = Config { - default_provider: Some("openai".into()), - default_model: Some("gpt-5.6".into()), - ..Config::default() - }; - config.model_routes.push(crate::config::ModelRouteConfig { - hint: "quick".into(), - provider: "openrouter".into(), - model: "prx-absent-router-model".into(), - api_key: None, - credential_ref: None, - settings: Default::default(), - }); - let mut items = Vec::new(); - check_router_candidates(&config, &mut items); - assert_eq!(items.len(), 1); - assert!( - items - .iter() - .any(|item| item.message.contains("no reachable candidates")) - ); - config.model_routes.first_mut().unwrap().model = "anthropic/claude-sonnet-5".into(); - items.clear(); - check_router_candidates(&config, &mut items); - assert!(items.is_empty()); - } - - /// D-094 C-1, C-5: the doctor names a refused decision backend (which - /// runs builtin-only) and every decision credential nothing references, - /// by id, never by value. - #[test] - fn the_doctor_reports_a_refused_decision_backend_and_orphaned_credentials() { - let temp = TempDir::new().unwrap(); - let mut config = Config { - config_path: temp.path().join("config.toml"), - workspace_dir: temp.path().join("workspace"), - ..Config::default() - }; - config.decision_engine.enabled = true; - config.decision_engine.backend.get_or_insert_with(Default::default).kind = - crate::config::schema::decision_engine::BackendSelection::Fixed( - crate::config::schema::decision_engine::BackendKind::CompatibleHttp, - ); - config - .decision_engine - .backend - .get_or_insert_with(Default::default) - .endpoint = "http://127.0.0.1:8900/v1".to_string(); - config - .decision_engine - .backend - .get_or_insert_with(Default::default) - .model = "undeclared-model".to_string(); - let orphan = crate::config::manage::credentials::CredentialReferences::for_config(&config) - .unwrap() - .set( - "custom:http://127.0.0.1:8900/v1", - "decision-compatible-http-0badc0de", - "sk-DOCTOR-ORPHAN-SENTINEL-01", - ) - .unwrap(); - let mut items = Vec::new(); - check_decision_plane(&config, &mut items); - let text = items - .iter() - .map(|item| item.message.as_str()) - .collect::>() - .join("\n"); - assert_eq!(items.len(), 2, "{text}"); - assert!(text.contains("builtin-only") && text.contains(&orphan.id), "{text}"); - assert!(text.contains("prx providers credential remove "), "{text}"); - // Disabled, the credential store is not opened: a held lock does not - // delay the doctor, and nothing is reported from the store. - config.decision_engine.enabled = false; - std::fs::write(temp.path().join("auth-profiles.lock"), "pid=1\n").unwrap(); - let started = std::time::Instant::now(); - let mut items = Vec::new(); - check_decision_plane(&config, &mut items); - assert!( - items.is_empty(), - "{:?}", - items.iter().map(|item| &item.message).collect::>() - ); - assert!(started.elapsed() < std::time::Duration::from_secs(5)); - assert!(!text.contains("SENTINEL"), "{text}"); - } - - #[test] - fn memory_diagnostics_flag_vector_recall_inherited_from_the_flipped_default() { - let temp = TempDir::new().unwrap(); - let mut config = Config::default(); - config.workspace_dir = temp.path().to_path_buf(); - config.memory.embedding_provider = "local".to_string(); - config.memory.embedding_provider_explicit = false; - - let mut items = Vec::new(); - check_memory_diagnostics(&config, &mut items); - let notice = items - .iter() - .find(|item| item.message.contains("embedding_provider not set")) - .expect("doctor must report an inherited local vector recall default"); - assert_eq!(notice.severity, Severity::Warn); - assert_eq!(notice.category, "embedding"); - - config.memory.embedding_provider_explicit = true; - let mut items = Vec::new(); - check_memory_diagnostics(&config, &mut items); - assert!( - !items - .iter() - .any(|item| item.message.contains("embedding_provider not set")), - "an explicit provider must not be reported as an inherited default" - ); - } - - /// D-088 C-7: `prx doctor` names each blocked workspace MCP server with - /// the one-line opt-in, instead of leaving it to a log line. - #[test] - fn doctor_reports_a_workspace_mcp_server_blocked_by_the_opt_in() { - let temp = TempDir::new().unwrap(); - let mut config = Config::default(); - config.autonomy.level = crate::security::AutonomyLevel::Supervised; - config.workspace_dir = temp.path().to_path_buf(); - std::fs::write( - temp.path().join("mcp.json"), - r#"{"mcpServers": {"legacy": {"command": "npx", "args": ["some-mcp"]}}}"#, - ) - .unwrap(); - let mut items = Vec::new(); - check_workspace_mcp_servers(&config, &mut items); - let blocked = items - .iter() - .find(|item| { - item.message - .contains("workspace server 'legacy' (stdio) is not started") - }) - .expect("doctor must report the blocked workspace server"); - assert_eq!(blocked.severity, Severity::Warn); - assert!( - blocked.message.contains("workspace_servers = \"stdio\""), - "{}", - blocked.message - ); - - std::fs::remove_file(temp.path().join("mcp.json")).unwrap(); - let mut items = Vec::new(); - check_workspace_mcp_servers(&config, &mut items); - assert!(items.iter().all(|item| item.severity != Severity::Warn)); - } - - /// D-095 N-4: an operator `working_dir` inside the workspace is named. - #[test] - fn doctor_warns_about_a_working_dir_inside_the_workspace() { - let temp = TempDir::new().unwrap(); - let mut config = Config::default(); - config.workspace_dir = temp.path().to_path_buf(); - config.mcp.servers.insert( - "inside".into(), - crate::config::McpServerConfig { - command: Some("npx".into()), - working_dir: Some(temp.path().join("tools").display().to_string()), - ..crate::config::McpServerConfig::default() - }, - ); - let mut items = Vec::new(); - check_workspace_mcp_servers(&config, &mut items); - assert!( - items - .iter() - .any(|item| item.severity == Severity::Warn && item.message.contains("inside the agent's workspace")), - "{:?}", - items.iter().map(|item| &item.message).collect::>() - ); - } - - /// RED before PMME-h (D-095 L-3): a `pending` configuration record was - /// listed by `prx config status` but not by `prx doctor`. - #[test] - fn doctor_reports_an_unfinished_configuration_change() { - let temp = TempDir::new().unwrap(); - let config = Config { - config_path: temp.path().join("config.toml"), - workspace_dir: temp.path().join("workspace"), - ..Config::default() - }; - let record_dir = temp - .path() - .join(".config-history") - .join("0190a000-0000-7000-8000-000000000001"); - std::fs::create_dir_all(&record_dir).unwrap(); - let summary = crate::config::manage::ConfigChangeSummary::between(Some(&config), &config).unwrap(); - let now = chrono::Utc::now(); - let record = crate::config::manage::HistoryRecord { - version: 1, - id: "0190a000-0000-7000-8000-000000000001".into(), - created_at: now, - updated_at: now, - actor: crate::config::manage::ConfigActor::Cli, - status: crate::config::manage::RecordStatus::Pending, - base_revision: None, - committed_revision: None, - restores: None, - summary, - active_generation: None, - restart_required: Vec::new(), - reason: None, - }; - std::fs::write(record_dir.join("record.json"), serde_json::to_vec(&record).unwrap()).unwrap(); - - let mut items = Vec::new(); - check_unfinished_config_changes(&config, &mut items); - let pending = items - .iter() - .find(|item| item.message.contains("0190a000-0000-7000-8000-000000000001")) - .unwrap_or_else(|| { - panic!( - "doctor must report the pending record: {:?}", - items.iter().map(|item| &item.message).collect::>() - ) - }); - assert_eq!(pending.severity, Severity::Warn); - assert!(pending.message.contains("prx config rollback"), "{}", pending.message); - } - - /// D-107 amendment: a shell job stored before PRX recorded its creator - /// is named with the command that vouches for it; one with a recorded - /// creator is not; the check writes nothing. - #[test] - fn doctor_names_shell_jobs_without_a_recorded_creator() { - let temp = TempDir::new().unwrap(); - let mut config = Config::default(); - config.workspace_dir = temp.path().to_path_buf(); - let legacy = crate::cron::add_shell_job( - &config, - None, - crate::cron::Schedule::Cron { - expr: "*/5 * * * *".into(), - tz: None, - }, - "git pull project_payload_marker", - ) - .unwrap(); - let recorded = crate::cron::add_shell_job( - &config, - None, - crate::cron::Schedule::Cron { - expr: "*/5 * * * *".into(), - tz: None, - }, - "echo recorded", - ) - .unwrap(); - let db_path = temp.path().join("cron").join("jobs.db"); - rusqlite::Connection::open(&db_path) - .unwrap() - .execute( - "UPDATE cron_jobs SET created_via = NULL WHERE id = ?1", - [legacy.id.as_str()], - ) - .unwrap(); - let before = std::fs::read(&db_path).unwrap(); - - let mut items = Vec::new(); - check_unowned_shell_jobs(&config, &mut items); - let warnings = items - .iter() - .filter(|item| item.category == "git" && item.severity == Severity::Warn) - .collect::>(); - assert_eq!(warnings.len(), 1, "{warnings:?}"); - let warning = warnings.first().map(|item| item.message.as_str()).unwrap_or_default(); - assert!( - warning.contains(&format!("prx cron mark-operator {}", legacy.id)), - "{warning}" - ); - assert!(!warning.contains(&recorded.id), "{warning}"); - assert!(!warning.contains("project_payload_marker"), "{warning}"); - assert_eq!( - std::fs::read(&db_path).unwrap(), - before, - "doctor wrote to the cron store" - ); - - crate::cron::mark_job_operator(&config, &legacy.id).unwrap(); - let mut items = Vec::new(); - check_unowned_shell_jobs(&config, &mut items); - assert!( - !items - .iter() - .any(|item| item.category == "git" && item.severity == Severity::Warn), - "{items:?}" - ); - } - - /// SP-PMM H-4: a `pending` history record is reported with its - /// recovery commands and never applied (loading the configuration and - /// running the checks leave the files and the record as they were); a - /// persisted selection the evidence does not verify is listed by name. - #[tokio::test] - async fn a_pending_record_is_reported_never_applied_and_unverified_selections_are_listed() { - let temp = TempDir::new().unwrap(); - let mut config = Config { - config_path: temp.path().join("config.toml"), - workspace_dir: temp.path().join("workspace"), - default_provider: Some("openai".into()), - default_model: Some("gpt-4o".into()), - ..Config::default() - }; - config.model_routes.push(crate::config::ModelRouteConfig { - settings: Default::default(), - hint: "fast".into(), - provider: "openai".into(), - model: "pmmh-unlisted-route-model".into(), - api_key: None, - credential_ref: None, - }); - config.save().await.unwrap(); - let history = crate::config::manage::ConfigHistory::for_config(&config.config_path).unwrap(); - let mut other = config.clone(); - other.default_temperature = 0.1; - let before = crate::config::files::current_before_image(&config.config_path).unwrap(); - let record = history - .create_pending( - crate::config::manage::history::NewRecord { - actor: crate::config::manage::ConfigActor::Cli, - base_revision: None, - restores: None, - summary: crate::config::manage::ConfigChangeSummary::between(Some(&config), &other).unwrap(), - }, - &before, - ) - .unwrap(); - let config_bytes = std::fs::read(&config.config_path).unwrap(); - let record_bytes = std::fs::read(history.dir().join(&record.id).join("record.json")).unwrap(); - - let loaded = Config::load_from_path(&config.config_path, config.workspace_dir.clone()).unwrap(); - let mut items = Vec::new(); - check_unfinished_config_changes(&loaded, &mut items); - check_persisted_selections(&loaded, &mut items); - - let pending = items - .iter() - .find(|item| item.message.contains(&record.id)) - .expect("the pending record is reported"); - assert!( - pending.message.contains("is pending") && pending.message.contains("never applied"), - "{}", - pending.message - ); - let unverified = items - .iter() - .find(|item| item.message.contains("model route `hint:fast`")) - .expect("the unverified route is reported"); - assert_eq!(unverified.severity, Severity::Warn); - assert!( - unverified.message.contains("pmmh-unlisted-route-model"), - "{}", - unverified.message - ); - assert_eq!( - std::fs::read(&config.config_path).unwrap(), - config_bytes, - "a pending record was applied" - ); - assert_eq!( - std::fs::read(history.dir().join(&record.id).join("record.json")).unwrap(), - record_bytes, - "the pending record was rewritten" - ); - assert_eq!( - history.get(&record.id).unwrap().status, - crate::config::manage::RecordStatus::Pending - ); - } - - /// D-104 C-1 ruling: `prx doctor` names two embedding routes sharing a - /// hint, with the fix. - #[test] - fn doctor_reports_duplicate_embedding_route_hints() { - let route = |model: &str| crate::config::EmbeddingRouteConfig { - hint: "semantic".into(), - provider: "openai".into(), - model: model.into(), - dimensions: None, - api_key: None, - credential_ref: None, - }; - let mut config = Config::default(); - config.embedding_routes = vec![route("text-embedding-3-small"), route("text-embedding-3-large")]; - let mut items = Vec::new(); - check_persisted_selections(&config, &mut items); - let item = items - .iter() - .find(|item| item.message.contains("both use hint 'semantic'")) - .expect("the duplicate is reported"); - assert_eq!(item.severity, Severity::Warn); - assert!( - item.message.contains("Give each route its own hint"), - "{}", - item.message - ); - } - - /// HOOKS-ENV: `prx doctor` names blocked workspace hooks with the - /// one-line opt-in, and says when they run. - #[test] - fn doctor_reports_blocked_workspace_hooks_with_the_opt_in() { - let temp = TempDir::new().unwrap(); - let mut config = Config::default(); - config.workspace_dir = temp.path().to_path_buf(); - std::fs::write( - temp.path().join("hooks.json"), - r#"{"hooks": {"turn_complete": [{"command": "true"}]}}"#, - ) - .unwrap(); - let mut items = Vec::new(); - check_workspace_hooks(&config, &mut items); - let blocked = items - .iter() - .find(|item| item.category == "hooks") - .expect("test: a hooks item"); - assert_eq!(blocked.severity, Severity::Warn); - assert!( - blocked.message.contains(crate::hooks::WORKSPACE_HOOKS_OPT_IN), - "{}", - blocked.message - ); - - config.security.workspace_hooks = crate::config::WorkspaceHooks::On; - let mut items = Vec::new(); - check_workspace_hooks(&config, &mut items); - assert!(items.iter().all(|item| item.severity != Severity::Warn)); - } - - #[test] - fn deployed_binary_check_accepts_the_runtime_path() { - let temp = TempDir::new().unwrap(); - let deployed = temp.path().join("prx"); - std::fs::write(&deployed, b"binary").unwrap(); - let mut items = Vec::new(); - - check_deployed_binary_paths(&mut items, Some(deployed.clone()), Ok(deployed)); - - assert_eq!(items.len(), 2); - assert!(items.iter().all(|item| item.severity == Severity::Ok)); - assert!( - items - .iter() - .any(|item| item.message == "doctor is running from deployed binary") - ); - } - - #[test] - fn deployed_binary_check_reports_missing_path_lookup_without_linux_hardcode() { - let mut items = Vec::new(); - - check_deployed_binary_paths(&mut items, None, Ok(PathBuf::from("/opt/homebrew/bin/prx"))); - - assert_eq!(items.len(), 2); - assert_eq!(items[0].severity, Severity::Error); - assert_eq!(items[0].message, "deployed prx binary not found on PATH"); - assert!(items.iter().all(|item| !item.message.contains("/home/ck"))); - } - - struct EnvGuard { - key: &'static str, - original: Option, - } - - impl EnvGuard { - #[allow(unsafe_code)] - fn set(key: &'static str, value: Option<&str>) -> Self { - let original = std::env::var(key).ok(); - if key == "HOME" { - crate::config::schema::follow_test_home_env(value.map(std::ffi::OsStr::new)); - } - // SAFETY: test-only env manipulation; tests that use this must be serialized. - unsafe { - match value { - Some(next) => std::env::set_var(key, next), - None => std::env::remove_var(key), - } - } - Self { key, original } - } - } - - impl Drop for EnvGuard { - #[allow(unsafe_code)] - fn drop(&mut self) { - if self.key == "HOME" { - crate::config::schema::follow_test_home_env(self.original.as_deref().map(std::ffi::OsStr::new)); - } - // SAFETY: test-only env manipulation; restoring previous value. - unsafe { - if let Some(original) = self.original.as_deref() { - std::env::set_var(self.key, original); - } else { - std::env::remove_var(self.key); - } - } - } - } - - fn doctor_env_lock() -> std::sync::MutexGuard<'static, ()> { - static LOCK: std::sync::OnceLock> = std::sync::OnceLock::new(); - LOCK.get_or_init(|| std::sync::Mutex::new(())) - .lock() - .expect("doctor env lock poisoned") - } - - #[test] - fn provider_validation_checks_custom_url_shape() { - let config = Config::default(); - let validate = |provider: &str| { - provider_validation_error( - &config, - provider, - crate::providers::selection::default_model(&config), - crate::providers::selection::credential_for(&config, provider), - ) - }; - assert!(validate("openrouter").is_none()); - assert!(validate("custom:https://example.com").is_none()); - assert!(validate("anthropic-custom:https://example.com").is_none()); - - let invalid_custom = validate("custom:").unwrap_or_default(); - assert!(invalid_custom.contains("requires a URL")); - - let invalid_unknown = validate("totally-fake").unwrap_or_default(); - assert!(invalid_unknown.contains("Unknown provider")); - } - - #[test] - fn diag_item_icons() { - assert_eq!(DiagItem::ok("t", "m").icon(), "✅"); - assert_eq!(DiagItem::warn("t", "m").icon(), "⚠️ "); - assert_eq!(DiagItem::error("t", "m").icon(), "❌"); - } - - #[tokio::test] - async fn diagnostic_states_are_emitted_by_real_checks() { - let temp = TempDir::new().unwrap(); - let mut config = Config::default(); - config.config_path = temp.path().join("config.toml"); - config.workspace_dir = temp.path().to_path_buf(); - std::fs::write(&config.config_path, "configured").unwrap(); - - let mut items = Vec::new(); - check_memory_diagnostics(&config, &mut items); - check_runtime_readiness(&config, &mut items); - check_environment(&mut items); - check_daemon_state(&config, &mut items); - check_runtime_memory_health(&config, &mut items); - - let states: std::collections::HashSet<_> = items.iter().map(|item| item.state).collect(); - for expected in [ - DiagnosticState::Declared, - DiagnosticState::Configured, - DiagnosticState::Ready, - DiagnosticState::Healthy, - DiagnosticState::Unknown, - ] { - assert!(states.contains(&expected), "missing diagnostic state {expected:?}"); - } - } - - #[test] - fn doctor_reports_legacy_fitness_counts_and_repair_command() { - let temp = TempDir::new().unwrap(); - let mut config = Config::default(); - config.workspace_dir = temp.path().join("workspace"); - std::fs::create_dir_all(config.workspace_dir.join("memory")).unwrap(); - let connection = rusqlite::Connection::open(config.workspace_dir.join("memory/brain.db")).unwrap(); - connection - .execute_batch( - "CREATE TABLE memories (key TEXT NOT NULL, content TEXT NOT NULL); - INSERT INTO memories VALUES ('self/fitness/daily/2026-09-10', 'one'); - INSERT INTO memories VALUES ('self/fitness/daily/2026-09-11', 'two'); - INSERT INTO memories VALUES ('keep/key', 'keep');", - ) - .unwrap(); - std::fs::write( - config.workspace_dir.join("MEMORY.md"), - "- [t] **self/fitness/daily/2026-09-10**: legacy\n- [t] **keep/key**: keep\n", - ) - .unwrap(); - std::fs::write( - config.workspace_dir.join("MEMORY_SNAPSHOT.md"), - "### 🔑 `self/fitness/daily/2026-09-10`\n\nlegacy\n\n---\n", - ) - .unwrap(); - let mut items = Vec::new(); - - check_legacy_fitness_telemetry(&config, &mut items); - - assert_eq!(items.len(), 1); - assert_eq!(items[0].severity, Severity::Warn); - assert!(items[0].message.contains("database=2")); - assert!(items[0].message.contains("MEMORY.md=1")); - assert!(items[0].message.contains("MEMORY_SNAPSHOT.md=1")); - assert!(items[0].message.contains("prx fitness migrate-legacy --apply")); - } - - #[test] - fn doctor_clean_fitness_probe_is_read_only_on_missing_database() { - let temp = TempDir::new().unwrap(); - let mut config = Config::default(); - config.workspace_dir = temp.path().join("workspace"); - std::fs::create_dir_all(&config.workspace_dir).unwrap(); - let db_path = config.workspace_dir.join("memory/brain.db"); - let mut items = Vec::new(); - - check_legacy_fitness_telemetry(&config, &mut items); - - assert_eq!(items.len(), 1); - assert_eq!(items[0].severity, Severity::Ok); - assert!(items[0].message.contains("absent")); - assert!(!db_path.exists()); - } - - #[test] - fn classify_model_probe_error_marks_unsupported_as_skipped() { - let outcome = classify_model_probe_error("Provider 'copilot' does not support live model discovery yet"); - assert_eq!(outcome, ModelProbeVerdict::Skipped); - } - - #[test] - fn classify_model_probe_error_marks_auth_and_plan_issues() { - let auth_outcome = classify_model_probe_error("OpenAI API error (401): unauthorized"); - assert_eq!(auth_outcome, ModelProbeVerdict::AuthOrAccess); - - let plan_outcome = classify_model_probe_error("Z.AI API error (429): plan does not include requested model"); - assert_eq!(plan_outcome, ModelProbeVerdict::AuthOrAccess); - } - - #[test] - fn config_validation_catches_bad_temperature() { - let mut config = Config::default(); - config.default_temperature = 5.0; - let mut items = Vec::new(); - check_config_semantics(&config, &mut items); - let temp_item = items.iter().find(|i| i.message.contains("temperature")); - assert!(temp_item.is_some()); - assert_eq!(temp_item.unwrap().severity, Severity::Error); - } - - #[test] - fn config_validation_accepts_valid_temperature() { - let mut config = Config::default(); - config.default_temperature = 0.7; - let mut items = Vec::new(); - check_config_semantics(&config, &mut items); - let temp_item = items.iter().find(|i| i.message.contains("temperature")); - assert!(temp_item.is_some()); - assert_eq!(temp_item.unwrap().severity, Severity::Ok); - } - - #[test] - fn config_validation_warns_for_explicit_unrestricted_autonomy() { - let mut config = Config::default(); - config.autonomy.workspace_only = false; - config.autonomy.forbidden_paths.clear(); - config.autonomy.max_cost_per_day_cents = u32::MAX; - let mut items = Vec::new(); - - check_config_semantics(&config, &mut items); - - let item = items - .iter() - .find(|item| item.message.contains("explicit unrestricted autonomy profile")) - .expect("unrestricted posture warning"); - assert_eq!(item.severity, Severity::Warn); - } - - #[test] - fn config_validation_acknowledged_unrestricted_autonomy_is_quiet() { - let mut config = Config::default(); - config.autonomy.workspace_only = false; - config.autonomy.forbidden_paths.clear(); - config.autonomy.max_cost_per_day_cents = u32::MAX; - config.autonomy.acknowledge_unrestricted_profile = true; - let mut items = Vec::new(); - - check_config_semantics(&config, &mut items); - - assert!( - !items - .iter() - .any(|item| item.message.contains("explicit unrestricted autonomy profile")) - ); - } - - #[test] - fn config_validation_warns_for_explicit_delegate_wildcard() { - let mut config = Config::default(); - config.agents.insert( - "worker".into(), - crate::config::DelegateAgentConfig { - approval_wait_secs: 600, - limits: crate::config::AgentLimits::default(), - provider: "openrouter".into(), - model: "model-test".into(), - system_prompt: None, - api_key: None, - credential_ref: None, - temperature: None, - max_depth: 3, - agentic: true, - allowed_tools: vec!["*".into()], - identity_dir: None, - memory_scope: None, - spawn_enabled: None, - enabled: true, - autonomy: None, - }, - ); - let mut items = Vec::new(); - - check_config_semantics(&config, &mut items); - - let item = items - .iter() - .find(|item| item.message.contains("explicitly inherits all eligible parent tools")) - .expect("delegate wildcard warning"); - assert_eq!(item.severity, Severity::Warn); - } - - #[test] - fn config_validation_warns_no_channels() { - let config = Config::default(); - let mut items = Vec::new(); - check_config_semantics(&config, &mut items); - let ch_item = items.iter().find(|i| i.message.contains("channel")); - assert!(ch_item.is_some()); - assert_eq!(ch_item.unwrap().severity, Severity::Warn); - } - - #[test] - fn wacli_is_reported_as_a_configured_channel() { - let mut config = Config::default(); - config.channels_config.cli = false; - config.channels_config.wacli = Some(crate::config::WacliConfig::default()); - - assert_eq!(configured_channel_names(&config), vec!["wacli"]); - let mut items = Vec::new(); - check_channel_runtime(&config, &mut items); - assert!( - items - .iter() - .any(|item| item.message.contains("configured channels: wacli")) - ); - } - - #[test] - fn daemon_state_reports_stale_scheduler_as_unhealthy() { - let temp = TempDir::new().unwrap(); - let mut config = Config::default(); - config.config_path = temp.path().join("config.toml"); - - let stale = (Utc::now() - chrono::Duration::seconds(SCHEDULER_STALE_SECONDS + 60)).to_rfc3339(); - let state = serde_json::json!({ - "pid": std::process::id(), - "updated_at": Utc::now().to_rfc3339(), - "components": { - "scheduler": { - "status": "ok", - "updated_at": stale, - "last_ok": stale, - "last_error": null, - "restart_count": 0 - } - } - }); - std::fs::write( - crate::daemon::state_file_path(&config), - serde_json::to_vec(&state).unwrap(), - ) - .unwrap(); - - let mut items = Vec::new(); - check_daemon_state(&config, &mut items); - - let scheduler_item = items - .iter() - .find(|item| item.message.contains("scheduler unhealthy")) - .expect("stale always-on scheduler should be unhealthy"); - assert_eq!(scheduler_item.severity, Severity::Error); - } - - #[test] - fn config_validation_catches_unknown_provider() { - let mut config = Config::default(); - config.default_provider = Some("totally-fake".into()); - let mut items = Vec::new(); - check_config_semantics(&config, &mut items); - let prov_item = items.iter().find(|i| i.message.contains("default provider")); - assert!(prov_item.is_some()); - assert_eq!(prov_item.unwrap().severity, Severity::Error); - } - - #[test] - fn config_validation_catches_malformed_custom_provider() { - let mut config = Config::default(); - config.default_provider = Some("custom:".into()); - let mut items = Vec::new(); - check_config_semantics(&config, &mut items); - - let prov_item = items - .iter() - .find(|item| item.message.contains("default provider \"custom:\" is invalid")); - assert!(prov_item.is_some()); - assert_eq!(prov_item.unwrap().severity, Severity::Error); - } - - #[test] - fn config_validation_accepts_custom_provider() { - let mut config = Config::default(); - config.default_provider = Some("custom:https://my-api.com".into()); - let mut items = Vec::new(); - check_config_semantics(&config, &mut items); - let prov_item = items.iter().find(|i| i.message.contains("is valid")); - assert!(prov_item.is_some()); - assert_eq!(prov_item.unwrap().severity, Severity::Ok); - } - - #[test] - fn config_validation_accepts_active_auth_profile_credential() { - let tmp = TempDir::new().unwrap(); - std::fs::write(tmp.path().join("config.toml"), "").unwrap(); - let store = crate::auth::profiles::AuthProfilesStore::new(tmp.path(), false); - store - .upsert_profile( - crate::auth::profiles::AuthProfile::new_token("moonshot", "default", "moonshot-test-key".to_string()), - true, - ) - .unwrap(); - - let mut config = Config::default(); - config.config_path = tmp.path().join("config.toml"); - config.default_provider = Some("moonshot".into()); - config.api_key = None; - config.secrets.encrypt = false; - - let mut items = Vec::new(); - check_config_semantics(&config, &mut items); - - let auth_item = items - .iter() - .find(|item| item.message.contains("auth profile credential configured")); - assert!( - auth_item.is_some(), - "items: {:?}", - items.iter().map(|i| &i.message).collect::>() - ); - assert_eq!(auth_item.unwrap().severity, Severity::Ok); - assert!( - !items.iter().any(|item| item.message.contains("no api_key")), - "active auth profile should suppress missing api_key warning" - ); - } - - #[test] - fn config_validation_maps_kimi_alias_to_moonshot_auth_profile() { - let tmp = TempDir::new().unwrap(); - std::fs::write(tmp.path().join("config.toml"), "").unwrap(); - let store = crate::auth::profiles::AuthProfilesStore::new(tmp.path(), false); - store - .upsert_profile( - crate::auth::profiles::AuthProfile::new_token("moonshot", "default", "moonshot-test-key".to_string()), - true, - ) - .unwrap(); - - let mut config = Config::default(); - config.config_path = tmp.path().join("config.toml"); - config.default_provider = Some("kimi".into()); - config.api_key = None; - config.secrets.encrypt = false; - - let mut items = Vec::new(); - check_config_semantics(&config, &mut items); - - let auth_item = items - .iter() - .find(|item| item.message.contains("auth profile credential configured")); - assert!( - auth_item.is_some(), - "items: {:?}", - items.iter().map(|i| &i.message).collect::>() - ); - assert_eq!(auth_item.unwrap().severity, Severity::Ok); - } - - #[test] - fn config_validation_warns_bad_fallback() { - let mut config = Config::default(); - config.reliability.fallback_providers = vec!["fake-provider".into()]; - let mut items = Vec::new(); - check_config_semantics(&config, &mut items); - let fb_item = items.iter().find(|i| i.message.contains("fallback provider")); - assert!(fb_item.is_some()); - assert_eq!(fb_item.unwrap().severity, Severity::Warn); - } - - #[test] - fn config_validation_warns_bad_custom_fallback() { - let mut config = Config::default(); - config.reliability.fallback_providers = vec!["custom:".into()]; - let mut items = Vec::new(); - check_config_semantics(&config, &mut items); - - let fb_item = items - .iter() - .find(|item| item.message.contains("fallback provider \"custom:\" is invalid")); - assert!(fb_item.is_some()); - assert_eq!(fb_item.unwrap().severity, Severity::Warn); - } - - #[test] - fn config_validation_warns_provider_resilience_degraded_with_single_available_provider() { - let _guard = doctor_env_lock(); - - // Isolate from host credentials: override HOME to an empty temp dir so - // resolve_claude_code_context cannot find ~/.claude/.credentials.json, - // and clear any ambient Anthropic env vars. - let iso_home = std::env::temp_dir().join(format!("openprx-doctor-degrade-test-{}", std::process::id())); - std::fs::create_dir_all(&iso_home).unwrap(); - let _home_guard = EnvGuard::set("HOME", Some(iso_home.to_str().unwrap())); - let _anthropic_key_guard = EnvGuard::set("ANTHROPIC_API_KEY", None); - let _anthropic_oauth_guard = EnvGuard::set("ANTHROPIC_OAUTH_TOKEN", None); - - let mut config = Config::default(); - config.default_provider = Some("openai".into()); - config.api_key = Some("sk-test".into()); - config.reliability.fallback_providers = vec!["anthropic".into()]; - - let mut items = Vec::new(); - check_config_semantics(&config, &mut items); - - let _ = std::fs::remove_dir_all(&iso_home); - let degraded = items.iter().find(|item| { - item.message - .contains("provider resilience degraded: only 1 configured+available") - }); - assert!(degraded.is_some()); - assert_eq!(degraded.unwrap().severity, Severity::Warn); - } - - #[test] - fn config_validation_acknowledged_single_provider_risk_is_quiet() { - let _guard = doctor_env_lock(); - let iso_home = std::env::temp_dir().join(format!("openprx-doctor-ack-test-{}", std::process::id())); - std::fs::create_dir_all(&iso_home).unwrap(); - let _home_guard = EnvGuard::set("HOME", Some(iso_home.to_str().unwrap())); - let _anthropic_key_guard = EnvGuard::set("ANTHROPIC_API_KEY", None); - let _anthropic_oauth_guard = EnvGuard::set("ANTHROPIC_OAUTH_TOKEN", None); - - let mut config = Config::default(); - config.default_provider = Some("openai".into()); - config.api_key = Some("sk-test".into()); - config.reliability.fallback_providers = vec!["anthropic".into()]; - config.reliability.acknowledge_single_provider_risk = true; - - let mut items = Vec::new(); - check_config_semantics(&config, &mut items); - - assert!( - !items - .iter() - .any(|item| item.message.contains("provider resilience degraded")) - ); - let _ = std::fs::remove_dir_all(&iso_home); - } - - #[test] - fn config_validation_warns_model_fallback_route_mismatch() { - let mut config = Config::default(); - config.default_provider = Some("openai".into()); - config.reliability.model_fallbacks.insert( - "openai/gpt-4o".into(), - vec!["anthropic/claude-sonnet-4-20250514".into()], - ); - - let mut items = Vec::new(); - check_config_semantics(&config, &mut items); - - let mismatch = items - .iter() - .find(|item| item.message.contains("model_fallbacks route mismatch")); - assert!(mismatch.is_some()); - assert_eq!(mismatch.unwrap().severity, Severity::Warn); - } - - /// D-072 L-9 / D-075: doctor mirrors the failover chain. A llama.cpp - /// fallback never answers another provider's route, so a fallback model - /// only it could serve is a route mismatch; on its own route it serves - /// any repository, so no warning there. - #[test] - fn config_validation_follows_llamacpp_route_identity() { - let temp = tempfile::tempdir().expect("test: temp dir"); - let base = Config { - config_path: temp.path().join("config.toml"), - workspace_dir: temp.path().join("workspace"), - ..Config::default() - }; - let warning = |config: &Config, needle: &str| { - let mut items = Vec::new(); - check_config_semantics(config, &mut items); - items.into_iter().find(|item| item.message.contains(needle)) - }; - - // D-076 N-1: a llama.cpp fallback with nothing it may serve is never used. - let mut unused = base.clone(); - unused.default_provider = Some("anthropic".into()); - unused.reliability.fallback_providers = vec!["llamacpp".into()]; - assert!( - warning(&unused, "\"llamacpp\" is never used").is_some_and(|item| item.severity == Severity::Warn), - "a llama.cpp fallback without a repository entry is dead config" - ); - unused - .reliability - .model_fallbacks - .insert("anthropic/claude-sonnet-5".into(), vec!["claude-haiku-5".into()]); - assert!( - warning(&unused, "\"llamacpp\" is never used").is_some(), - "a bare id is routed to another provider" - ); - - // Named in model_fallbacks: the fallback serves it; no warning. - let mut named = base.clone(); - named.default_provider = Some("anthropic".into()); - named.reliability.fallback_providers = vec!["llamacpp".into()]; - named.reliability.model_fallbacks.insert( - "anthropic/claude-sonnet-5".into(), - vec!["ggml-org/gpt-oss-20b-GGUF".into()], - ); - assert!(warning(&named, "is never used").is_none()); - assert!(warning(&named, "model_fallbacks route mismatch").is_none()); - - // A `/…` fallback model only the llama.cpp fallback could - // take is routed to another provider: a mismatch. - let mut elsewhere = named.clone(); - elsewhere.reliability.model_fallbacks.insert( - "anthropic/claude-sonnet-5".into(), - vec!["openai/gpt-5".into(), "ggml-org/gpt-oss-20b-GGUF".into()], - ); - assert!( - warning(&elsewhere, "model_fallbacks route mismatch").is_some_and(|item| item.severity == Severity::Warn) - ); - - // On its own route llama.cpp serves any repository. - let mut own_route = base; - own_route.default_provider = Some("llamacpp".into()); - own_route.default_model = Some("ggml-org/gpt-oss-20b-GGUF".into()); - own_route.reliability.model_fallbacks.insert( - "ggml-org/gpt-oss-20b-GGUF".into(), - vec!["google/gemma-3-27b-it-GGUF".into()], - ); - assert!(warning(&own_route, "model_fallbacks route mismatch").is_none()); - } - - /// PMM-C: doctor resolves the configured default: refused is an error, - /// id-only is a warning (D-018 Q1: it keeps running, unverified), - /// declared is fine. - #[test] - fn doctor_reports_how_the_default_model_resolves() { - let temp = tempfile::tempdir().expect("test: temp dir"); - let mut config = Config::default(); - config.workspace_dir = temp.path().to_path_buf(); - config.config_path = temp.path().join("config.toml"); - config.default_provider = Some("openrouter".to_string()); - config.api_key = Some("PMMC-DOCTOR-ROOT".to_string()); - let models_item = |config: &Config| { - diagnose(config) - .items - .into_iter() - .find(|item| item.category == "models" && item.message.contains("default model")) - }; - - config.default_model = Some("jev-decision-test".to_string()); - config.providers.models.push( - toml::from_str( - "provider = \"openrouter\"\nmodel = \"jev-decision-test\"\noperations = [\"decision_endpoint\"]\n", - ) - .expect("test: declaration"), - ); - let item = models_item(&config).expect("a refused default is reported"); - assert_eq!(item.severity, Severity::Error, "{}", item.message); - assert!(item.message.contains("cannot be used for chat"), "{}", item.message); - assert!(!item.message.contains("PMMC-DOCTOR-ROOT")); - - config.default_model = Some("vendor/id-only".to_string()); - let item = models_item(&config).expect("an unverified default is reported"); - assert_eq!(item.severity, Severity::Warn, "{}", item.message); - assert!(item.message.contains("unverified"), "{}", item.message); - - config.providers.models.push( - toml::from_str("provider = \"openrouter\"\nmodel = \"vendor/id-only\"\noperations = [\"chat\"]\n") - .expect("test: declaration"), - ); - let item = models_item(&config).expect("a verified default is reported"); - assert_eq!(item.severity, Severity::Ok, "{}", item.message); - } - - #[test] - fn config_validation_warns_empty_model_route() { - let mut config = Config::default(); - config.model_routes = vec![crate::config::ModelRouteConfig { - settings: Default::default(), - hint: "fast".into(), - provider: "groq".into(), - model: String::new(), - api_key: None, - credential_ref: None, - }]; - let mut items = Vec::new(); - check_config_semantics(&config, &mut items); - let route_item = items.iter().find(|i| i.message.contains("empty model")); - assert!(route_item.is_some()); - assert_eq!(route_item.unwrap().severity, Severity::Warn); - } - - #[test] - fn config_validation_warns_empty_embedding_route_model() { - let mut config = Config::default(); - config.embedding_routes = vec![crate::config::EmbeddingRouteConfig { - hint: "semantic".into(), - provider: "openai".into(), - model: String::new(), - dimensions: Some(1536), - api_key: None, - credential_ref: None, - }]; - - let mut items = Vec::new(); - check_config_semantics(&config, &mut items); - let route_item = items - .iter() - .find(|item| item.message.contains("embedding route \"semantic\" has empty model")); - assert!(route_item.is_some()); - assert_eq!(route_item.unwrap().severity, Severity::Warn); - } - - #[test] - fn config_validation_warns_invalid_embedding_route_provider() { - let mut config = Config::default(); - config.embedding_routes = vec![crate::config::EmbeddingRouteConfig { - hint: "semantic".into(), - provider: "groq".into(), - model: "text-embedding-3-small".into(), - dimensions: None, - api_key: None, - credential_ref: None, - }]; - - let mut items = Vec::new(); - check_config_semantics(&config, &mut items); - let route_item = items - .iter() - .find(|item| item.message.contains("uses invalid provider \"groq\"")); - assert!(route_item.is_some()); - assert_eq!(route_item.unwrap().severity, Severity::Warn); - } - - #[test] - fn config_validation_warns_missing_embedding_hint_target() { - let mut config = Config::default(); - config.memory.embedding_model = "hint:semantic".into(); - - let mut items = Vec::new(); - check_config_semantics(&config, &mut items); - let route_item = items - .iter() - .find(|item| item.message.contains("no matching [[embedding_routes]] entry exists")); - assert!(route_item.is_some()); - assert_eq!(route_item.unwrap().severity, Severity::Warn); - } - - #[test] - fn environment_check_finds_git() { - let mut items = Vec::new(); - check_environment(&mut items); - let git_item = items.iter().find(|i| i.message.starts_with("git:")); - // git should be available in any CI/dev environment - assert!(git_item.is_some()); - assert_eq!(git_item.unwrap().severity, Severity::Ok); - } - - #[test] - fn parse_df_available_mb_uses_last_data_line() { - let stdout = "Filesystem 1M-blocks Used Available Use% Mounted on\n/dev/sda1 1000 500 500 50% /\n"; - assert_eq!(parse_df_available_mb(stdout), Some(500)); - } - - #[test] - fn truncate_for_display_preserves_utf8_boundaries() { - let preview = truncate_for_display("🙂example-alpha-build", 3); - assert_eq!(preview, "🙂ex…"); - } - - #[test] - fn workspace_check_does_not_create_probe_files() { - let tmp = TempDir::new().unwrap(); - let marker = tmp.path().join("marker.txt"); - std::fs::write(&marker, "existing").unwrap(); - let before: Vec<_> = std::fs::read_dir(tmp.path()) - .unwrap() - .map(|entry| entry.unwrap().file_name()) - .collect(); - let mut config = Config::default(); - config.workspace_dir = tmp.path().to_path_buf(); - let mut items = Vec::new(); - - check_workspace(&config, &mut items); - - let after: Vec<_> = std::fs::read_dir(tmp.path()) - .unwrap() - .map(|entry| entry.unwrap().file_name()) - .collect(); - assert_eq!(before, after); - assert!( - items - .iter() - .any(|item| item.message.contains("no write probe performed")) - ); - } - - #[test] - fn doctor_run_returns_error_when_report_contains_errors() { - let temp = TempDir::new().unwrap(); - let mut config = Config::default(); - config.config_path = temp.path().join("missing-config.toml"); - config.workspace_dir = temp.path().join("missing-workspace"); - - assert!( - run(&config).is_err(), - "doctor must return nonzero semantics for ERROR findings" - ); - } - - #[tokio::test] - async fn runtime_memory_probe_does_not_create_missing_sqlite_database() { - let temp = TempDir::new().unwrap(); - let mut config = Config::default(); - config.workspace_dir = temp.path().join("workspace"); - std::fs::create_dir_all(&config.workspace_dir).unwrap(); - let db_path = config.workspace_dir.join("memory").join("brain.db"); - - let mut items = Vec::new(); - check_runtime_memory_health(&config, &mut items); - - assert!(!db_path.exists(), "doctor memory probe must not create brain.db"); - } - - #[test] - fn config_validation_reports_delegate_agents_in_sorted_order() { - let mut config = Config::default(); - config.agents.insert( - "zeta".into(), - crate::config::DelegateAgentConfig { - approval_wait_secs: 600, - limits: crate::config::AgentLimits::default(), - provider: "totally-fake".into(), - model: "model-z".into(), - system_prompt: None, - api_key: None, - credential_ref: None, - temperature: None, - max_depth: 3, - agentic: false, - allowed_tools: Vec::new(), - identity_dir: None, - memory_scope: None, - spawn_enabled: None, - enabled: true, - autonomy: None, - }, - ); - config.agents.insert( - "alpha".into(), - crate::config::DelegateAgentConfig { - approval_wait_secs: 600, - limits: crate::config::AgentLimits::default(), - provider: "totally-fake".into(), - model: "model-a".into(), - system_prompt: None, - api_key: None, - credential_ref: None, - temperature: None, - max_depth: 3, - agentic: false, - allowed_tools: Vec::new(), - identity_dir: None, - memory_scope: None, - spawn_enabled: None, - enabled: true, - autonomy: None, - }, - ); - - let mut items = Vec::new(); - check_config_semantics(&config, &mut items); - - let agent_messages: Vec<_> = items - .iter() - .filter(|item| item.message.starts_with("agent \"")) - .map(|item| item.message.as_str()) - .collect(); - - assert_eq!(agent_messages.len(), 2); - assert!(agent_messages[0].contains("agent \"alpha\"")); - assert!(agent_messages[1].contains("agent \"zeta\"")); - } - - // ---- FIX-P2-06: runtime readiness sub-checks ------------------------ - - #[test] - fn runtime_readiness_emits_six_subchecks() { - let config = Config::default(); - let mut items = Vec::new(); - check_runtime_readiness(&config, &mut items); - let readiness: Vec<&str> = items - .iter() - .filter(|i| i.category == "readiness") - .map(|i| i.message.as_str()) - .collect(); - assert_eq!(readiness.len(), 6, "expected 6 readiness sub-checks"); - for prefix in ["owner:", "topic:", "task:", "document:", "vector:", "runtime-control:"] { - assert!( - readiness.iter().any(|m| m.starts_with(prefix)), - "missing readiness sub-check with prefix {prefix}" - ); - } - assert!(items.iter().any(|item| { - item.state == DiagnosticState::Ready && item.message.starts_with("topic: local similarity") - })); - assert!( - items.iter().any(|item| { - item.state == DiagnosticState::Ready && item.message.starts_with("vector: index ready") - }) - ); - } - - #[test] - fn runtime_readiness_flags_zero_dimension_with_embeddings() { - let mut config = Config::default(); - config.memory.embedding_provider = "openai".into(); - config.memory.embedding_dimensions = 0; - let mut items = Vec::new(); - check_runtime_readiness(&config, &mut items); - assert!( - items.iter().any(|i| i.category == "readiness" - && i.severity == Severity::Error - && i.message.starts_with("vector:")), - "expected vector readiness error for zero dimension" - ); - } - - // ---- FIX-P2-07: postgres health ------------------------------------- - - #[tokio::test] - async fn postgres_health_skips_when_not_selected() { - // Default backend is sqlite -> no postgres items emitted at all. - let config = Config::default(); - let mut items = Vec::new(); - check_postgres_health(&config, &mut items).await; - assert!(items.iter().all(|i| i.category != "postgres")); - } - - #[tokio::test] - async fn postgres_health_errors_on_missing_db_url() { - let mut config = Config::default(); - config.memory.backend = "postgres".into(); - let mut items = Vec::new(); - check_postgres_health(&config, &mut items).await; - assert!( - items - .iter() - .any(|i| i.category == "postgres" && i.severity == Severity::Error), - "expected error when postgres selected without db_url" - ); - } - - #[tokio::test] - async fn postgres_health_errors_on_bad_scheme() { - let mut config = Config::default(); - config.memory.backend = "postgres".into(); - config.storage.provider.config.db_url = Some("mysql://host/db".into()); - let mut items = Vec::new(); - check_postgres_health(&config, &mut items).await; - assert!( - items.iter().any(|i| i.category == "postgres" - && i.severity == Severity::Error - && i.message.contains("postgres://")), - "expected scheme validation error" - ); - } - - // ---- FIX-P2-08: embedding endpoint probe ---------------------------- - - #[tokio::test] - async fn embedding_probe_skips_without_custom_provider() { - // Default provider is "none" -> no embedding probe items. - let config = Config::default(); - let mut items = Vec::new(); - check_embedding_endpoint(&config, &mut items).await; - assert!(items.iter().all(|i| i.category != "embedding")); - } - - #[tokio::test] - async fn embedding_probe_warns_on_unreachable_custom_endpoint() { - let mut config = Config::default(); - // Port 1 on localhost is reserved and refuses connections quickly. - config.memory.embedding_provider = "custom:http://127.0.0.1:1/embed".into(); - let mut items = Vec::new(); - check_embedding_endpoint(&config, &mut items).await; - assert!( - items - .iter() - .any(|i| i.category == "embedding" && i.severity == Severity::Warn), - "expected warn for unreachable embedding endpoint" - ); - } - - // ---- daemon process PATH (v0.8.139) --------------------------------- - - fn environ_blob(entries: &[&str]) -> Vec { - let mut bytes = Vec::new(); - for entry in entries { - bytes.extend_from_slice(entry.as_bytes()); - bytes.push(0); - } - bytes - } - - fn path_value(dirs: &[&Path]) -> String { - std::env::join_paths(dirs).unwrap().to_string_lossy().into_owned() - } - - #[test] - fn daemon_path_from_environ_picks_the_path_entry() { - let blob = environ_blob(&["HOME=/home/ck", "PATH=/usr/bin:/bin", "LANG=C"]); - assert_eq!(daemon_path_from_environ(&blob).as_deref(), Some("/usr/bin:/bin")); - } - - #[test] - fn daemon_path_from_environ_ignores_path_lookalike_keys() { - let blob = environ_blob(&["LD_LIBRARY_PATH=/opt/lib", "MANPATH=/usr/share/man"]); - assert!(daemon_path_from_environ(&blob).is_none()); - } - - #[test] - fn daemon_path_ok_when_required_directory_is_present() { - let temp = TempDir::new().unwrap(); - let bin = temp.path().join("cargo-bin"); - std::fs::create_dir_all(&bin).unwrap(); - let other = temp.path().join("usr-bin"); - std::fs::create_dir_all(&other).unwrap(); - - let path = path_value(&[other.as_path(), bin.as_path()]); - let blob = environ_blob(&["HOME=/home/ck", &format!("PATH={path}")]); - let item = evaluate_daemon_environ(&blob, std::slice::from_ref(&bin)); - - assert_eq!(item.severity, Severity::Ok, "message: {}", item.message); - assert_eq!(item.category, "daemon"); - assert!( - item.message.contains(&path), - "ok message must print the daemon PATH, got: {}", - item.message - ); - } - - #[test] - fn daemon_path_warns_when_required_directory_is_missing() { - let temp = TempDir::new().unwrap(); - let bin = temp.path().join("cargo-bin"); - std::fs::create_dir_all(&bin).unwrap(); - let other = temp.path().join("usr-bin"); - std::fs::create_dir_all(&other).unwrap(); - - let path = path_value(&[other.as_path()]); - let blob = environ_blob(&[&format!("PATH={path}")]); - let item = evaluate_daemon_environ(&blob, std::slice::from_ref(&bin)); - - assert_eq!(item.severity, Severity::Warn, "message: {}", item.message); - assert!( - item.message.contains(&bin.display().to_string()), - "warn message must name the missing directory, got: {}", - item.message - ); - assert!( - item.message.contains("Environment=\"PATH="), - "warn message must carry the systemd fix, got: {}", - item.message - ); - assert!( - item.message.contains("prx service install"), - "warn message must carry the re-install fix, got: {}", - item.message - ); - } - - #[test] - fn daemon_path_warns_when_environ_has_no_path_key() { - let blob = environ_blob(&["HOME=/home/ck", "LANG=C"]); - let item = evaluate_daemon_environ(&blob, &[PathBuf::from("/home/ck/.cargo/bin")]); - - assert_eq!(item.severity, Severity::Warn, "message: {}", item.message); - assert!( - item.message.contains("no PATH entry"), - "warn message must explain the missing PATH key, got: {}", - item.message - ); - assert!( - item.message.contains("Environment="), - "warn message must carry the systemd fix, got: {}", - item.message - ); - } - - /// `prx doctor` is very often run from a build tree (`cargo run -- doctor`, - /// `./target/release/prx doctor`, a one-shot CI copy). Requiring the - /// doctor's own directory there produced a warning about a healthy daemon - /// *and* told the operator to put a build directory on the unit's PATH. - /// - /// MUTATION GUARD: drop the `is_cargo_build_dir` filter and this fails, - /// because the test binary itself lives in `target/debug/deps`. - #[test] - fn a_doctor_running_from_a_build_directory_never_demands_it_on_the_daemon_path() { - let required = required_daemon_path_dirs(None); - assert!( - required.iter().all(|dir| !is_cargo_build_dir(dir)), - "a build output directory must never be proposed for a systemd unit: {required:?}" - ); - let item = evaluate_daemon_path("/usr/local/bin:/usr/bin:/bin", &required); - assert!( - !item.message.contains("target/debug"), - "the repair text must not name a build directory: {}", - item.message - ); - } - - /// The directory that actually matters is the daemon's, and the daemon - /// records it. When it does, the doctor's own location is irrelevant. - #[test] - fn the_required_directory_comes_from_the_daemon_binary_the_state_file_records() { - let required = required_daemon_path_dirs(Some(Path::new("/usr/local/bin/prx"))); - assert!( - required.contains(&canonical_or_owned(Path::new("/usr/local/bin"))), - "the daemon's own directory must be required: {required:?}" - ); - assert!( - required.iter().all(|dir| !is_cargo_build_dir(dir)), - "a recorded daemon binary replaces the doctor's own directory: {required:?}" - ); - - let complete = required - .iter() - .map(|dir| dir.display().to_string()) - .collect::>() - .join(":"); - let item = evaluate_daemon_path(&complete, &required); - assert_eq!( - item.severity, - Severity::Ok, - "a PATH that holds every required directory is healthy: {}", - item.message - ); - - let item = evaluate_daemon_path("/usr/bin:/bin", &required); - assert_eq!(item.severity, Severity::Warn); - assert!( - item.message.contains("/usr/local/bin"), - "a PATH without the daemon's own directory must name it: {}", - item.message - ); - } - - #[test] - fn the_daemon_binary_is_read_back_from_the_state_file_when_it_is_recorded() { - let temp = TempDir::new().unwrap(); - let mut config = Config::default(); - config.config_path = temp.path().join("config.toml"); - assert_eq!(daemon_binary_from_state(&config), None, "no state file, no answer"); - - std::fs::write( - temp.path().join("daemon_state.json"), - br#"{"pid":1,"binary_path":"/usr/local/bin/prx"}"#, - ) - .unwrap(); - assert_eq!( - daemon_binary_from_state(&config), - Some(PathBuf::from("/usr/local/bin/prx")) - ); - - std::fs::write( - temp.path().join("daemon_state.json"), - br#"{"pid":1,"binary_path":" "}"#, - ) - .unwrap(); - assert_eq!(daemon_binary_from_state(&config), None, "a blank field is not a path"); - } - - #[test] - fn cargo_build_directories_are_recognized_and_ordinary_bin_directories_are_not() { - let temp = TempDir::new().unwrap(); - for layout in [ - "target/debug", - "target/debug/deps", - "target/release", - "target/x86_64-unknown-linux-gnu/release", - "prx-qa-output/debug", - "prx-qa-output/debug/deps", - "custom-output/aarch64-unknown-linux-gnu/release", - ] { - let build = temp.path().join(layout); - std::fs::create_dir_all(build.join(".fingerprint")).unwrap(); - let build = build.to_str().unwrap(); - assert!( - is_cargo_build_dir(Path::new(build)), - "must be a build directory: {build}" - ); - } - for deployed in ["/usr/local/bin", "/home/ck/.cargo/bin", "/opt/prx/target", "/srv/debug"] { - assert!( - !is_cargo_build_dir(Path::new(deployed)), - "must not be mistaken for a build directory: {deployed}" - ); - } - } - - /// A pid outlives the daemon that wrote it. Reading the environment of - /// whatever process inherited the number judges the daemon PATH from a - /// stranger's environment. - #[test] - fn only_a_process_that_is_prx_is_treated_as_the_daemon() { - assert!(process_identity_looks_like_prx( - Some(Path::new("/usr/local/bin/prx")), - b"" - )); - assert!(process_identity_looks_like_prx( - Some(Path::new("/usr/local/bin/prx-node")), - b"" - )); - assert!(process_identity_looks_like_prx( - None, - b"/usr/local/bin/prx\x00daemon\x00" - )); - assert!(!process_identity_looks_like_prx(Some(Path::new("/usr/bin/sleep")), b"")); - assert!(!process_identity_looks_like_prx(None, b"/usr/bin/sleep\x00600\x00")); - assert!( - !process_identity_looks_like_prx(Some(Path::new("/opt/worker/code/prx/target/debug/other")), b""), - "a checkout directory called prx is not a prx process" - ); - assert!(!process_identity_looks_like_prx(None, b""), "no evidence is not a yes"); - } - - #[test] - fn daemon_path_check_skips_when_state_has_no_pid() { - let temp = TempDir::new().unwrap(); - let mut config = Config::default(); - config.config_path = temp.path().join("config.toml"); - std::fs::write( - temp.path().join("daemon_state.json"), - br#"{"updated_at":"2026-09-17T00:00:00Z","components":{}}"#, - ) - .unwrap(); - - let mut items = Vec::new(); - check_daemon_process_path(&config, &mut items); - - assert_eq!(items.len(), 1); - let item = &items[0]; - assert_eq!(item.severity, Severity::Ok, "skip must not be an error or warning"); - assert_eq!(item.state, DiagnosticState::Unknown); - assert!( - item.message.contains("no pid"), - "skip message must explain why, got: {}", - item.message - ); - } - - #[test] - fn daemon_path_check_skips_when_state_file_is_absent() { - let temp = TempDir::new().unwrap(); - let mut config = Config::default(); - config.config_path = temp.path().join("config.toml"); - - let mut items = Vec::new(); - check_daemon_process_path(&config, &mut items); - - assert_eq!(items.len(), 1); - assert_eq!(items[0].severity, Severity::Ok); - assert_eq!(items[0].state, DiagnosticState::Unknown); - } - - #[cfg(target_os = "linux")] - #[test] - fn daemon_path_check_skips_for_a_pid_that_does_not_exist() { - let temp = TempDir::new().unwrap(); - let mut config = Config::default(); - config.config_path = temp.path().join("config.toml"); - // PID above the kernel maximum can never be live. - std::fs::write( - temp.path().join("daemon_state.json"), - br#"{"pid":4294967000,"updated_at":"2026-09-17T00:00:00Z"}"#, - ) - .unwrap(); - - let mut items = Vec::new(); - check_daemon_process_path(&config, &mut items); - - assert_eq!(items.len(), 1); - assert_eq!(items[0].severity, Severity::Ok, "message: {}", items[0].message); - assert!( - items[0].message.contains("environ"), - "skip message must name the unreadable source, got: {}", - items[0].message - ); - } - - /// USERINFO-2: `prx doctor` prints every configured provider label. Each - /// may be a `custom:` URL carrying `user:password@`. - #[test] - fn doctor_names_every_provider_without_url_userinfo() { - let tmp = tempfile::TempDir::new().unwrap(); - let label = |port: u16| format!("custom:http://u:SECRET-fixture-pw@127.0.0.1:{port}/v1"); - let mut config = Config { - workspace_dir: tmp.path().join("workspace"), - config_path: tmp.path().join("config.toml"), - default_provider: Some(label(1)), - ..Config::default() - }; - // An unparseable fallback and route make doctor print "invalid" lines too. - config.reliability.fallback_providers = - vec![label(2), "custom:http://u:SECRET-fixture-pw@127.0.0.1:99999/v1".into()]; - config.model_routes = vec![crate::config::ModelRouteConfig { - settings: Default::default(), - hint: "fast".into(), - provider: "custom:http://u:SECRET-fixture-pw@127.0.0.1:99998/v1".into(), - model: "m".into(), - api_key: None, - credential_ref: None, - }]; - let report = diagnose(&config); - let rendered = report - .items - .iter() - .map(|item| item.message.as_str()) - .collect::>() - .join("\n"); - assert!( - rendered.contains("[redacted]@127.0.0.1"), - "doctor no longer names the endpoints: {rendered}" - ); - assert!( - !rendered.contains("SECRET-fixture-pw"), - "doctor printed URL userinfo: {rendered}" - ); - } - - /// R-C2BUg G-1: doctor messages that start with a URL keep none of their - /// credentials. - #[test] - fn doctor_messages_redact_every_url_in_url_first_text() { - crate::providers::label_redaction_tests::assert_every_url_redacted("doctor", &|text| { - DiagItem::warn("fixture", text).message - }); - } - - /// D-063, RED before: the gateway probe resolved `(host, port)`, and a - /// bracketed IPv6 `gateway.host = "[::1]"` (the spelling a URL uses) did - /// not resolve, so doctor reported "cannot resolve gateway bind address". - /// After: the brackets are removed before resolution. - #[test] - fn the_gateway_probe_resolves_a_bracketed_ipv6_host() { - for host in ["[::1]", "::1", "127.0.0.1"] { - let mut config = Config::default(); - config.gateway.host = host.to_string(); - config.gateway.port = 9; - let mut items = Vec::new(); - check_gateway_runtime(&config, &mut items); - let messages: Vec<&str> = items.iter().map(|item| item.message.as_str()).collect(); - assert!( - !messages.iter().any(|message| message.contains("cannot resolve")), - "{host}: {messages:?}" - ); - } - } - - /// RED before PMMDtail-j (D-084 E-3): `prx doctor`'s auth-profile check - /// loaded through the migrating load, rewriting auth-profiles.json. - #[test] - fn doctor_never_rewrites_the_profiles_file() { - let tmp = TempDir::new().expect("test: temp dir"); - let path = crate::auth::profiles::write_legacy_token_profile(tmp.path(), "moonshot", "sentinel-moonshot"); - let before = std::fs::read_to_string(&path).expect("test: read"); - let mut config = Config::default(); - config.config_path = tmp.path().join("config.toml"); - config.secrets.encrypt = true; - - let status = active_auth_profile_credential_status(&config, "moonshot"); +mod tests; +mod workers; - assert!( - matches!(status, AuthProfileCredentialStatus::Present { .. }), - "{status:?}" - ); - assert_eq!( - std::fs::read_to_string(&path).expect("test: read"), - before, - "the file was rewritten" - ); - } - /// Mutation: remove secret scanning in DiagItem::with_state. - #[test] - fn diagnostic_items_hide_nested_error_credentials() { - let error = anyhow::anyhow!("token=opaque7credential").context("failed"); - let item = DiagItem::error("runtime", format!("{error:#}")); - assert_eq!(item.message, "failed: token=[REDACTED]"); - } -} +include!("implementation/section_1.rs"); +include!("implementation/section_2.rs"); diff --git a/src/doctor/tests.rs b/src/doctor/tests.rs new file mode 100644 index 000000000..3e9297d3c --- /dev/null +++ b/src/doctor/tests.rs @@ -0,0 +1,14 @@ +#![cfg(test)] +#![allow( + clippy::indexing_slicing, + clippy::unwrap_used, + clippy::print_stdout, + clippy::print_stderr, + clippy::disallowed_types, + clippy::disallowed_methods, + clippy::needless_collect, + clippy::unreadable_literal +)] + +include!("tests/section_1.rs"); +include!("tests/section_2.rs"); diff --git a/src/doctor/tests/section_1.rs b/src/doctor/tests/section_1.rs new file mode 100644 index 000000000..5e2c284ac --- /dev/null +++ b/src/doctor/tests/section_1.rs @@ -0,0 +1,1734 @@ + + use super::*; + use tempfile::TempDir; + + #[test] + fn doctor_names_subscription_billing_without_an_unpriced_refusal() { + let dir = TempDir::new().unwrap(); + let mut config = Config::default(); + config.workspace_dir = dir.path().join("workspace"); + config.config_path = dir.path().join("config.toml"); + config.default_provider = Some("kimi-code".into()); + config.default_model = Some("kimi-for-coding".into()); + let mut items = Vec::new(); + check_model_selection(&config, &mut items); + assert!(items.iter().any(|item| { + item.severity == Severity::Ok && item.message == "subscription-billed, no per-token cost recorded" + })); + assert!( + items + .iter() + .all(|item| !item.message.contains("G6 budget admission refuses")) + ); + + config.default_provider = Some("openrouter".into()); + config.default_model = Some("deepseek/deepseek-v3.2".into()); + items.clear(); + check_model_selection(&config, &mut items); + assert!(items.iter().any(|item| { + item.severity == Severity::Warn && item.message.contains(r#"[cost.prices."deepseek/deepseek-v3.2"]"#) + })); + } + + #[test] + fn doctor_warns_when_a_cost_price_key_matches_no_configured_model() { + let mut config = Config::default(); + config.default_provider = Some("custom:http://127.0.0.1:9/v1".into()); + config.default_model = Some("moonshotai/kimi-k2.5".into()); + config.cost.prices.insert( + "custom:http://127.0.0.1:9/v1/moonshotai/kimi-k2.5".into(), + crate::config::schema::ModelPricing { + input: 1.0, + output: 2.0, + cache_write: 1.0, + cache_read: 0.5, + }, + ); + let mut items = Vec::new(); + check_model_selection(&config, &mut items); + assert!(items.iter().any(|item| { + item.severity == Severity::Warn + && item.category == "cost" + && item.message.contains("expected key is \"moonshotai/kimi-k2.5\"") + })); + + config.cost.prices.clear(); + config.cost.prices.insert( + "moonshotai/kimi-k2.5".into(), + crate::config::schema::ModelPricing { + input: 1.0, + output: 2.0, + cache_write: 1.0, + cache_read: 0.5, + }, + ); + items.clear(); + check_model_selection(&config, &mut items); + assert!(items.iter().all(|item| item.category != "cost")); + } + + #[test] + fn doctor_reports_invalid_saved_model_settings_as_repairable_warnings() { + let mut config = Config::default(); + config.default_provider = Some("openai".into()); + config.default_model = Some("gpt-5.6".into()); + config.model_settings.insert( + "openai/gpt-5.6".into(), + serde_json::from_value(serde_json::json!({"level":"future"})).unwrap(), + ); + let mut items = Vec::new(); + check_model_selection(&config, &mut items); + assert!(items.iter().any(|item| item.message.contains("saved level"))); + } + + #[test] + fn absent_catalog_lifecycle_is_informational_without_claiming_model_health() { + let config = Config { + default_provider: Some("openai".into()), + default_model: Some("prx-unlisted-model".into()), + ..Default::default() + }; + let mut items = Vec::new(); + check_model_selection(&config, &mut items); + let note = items + .iter() + .find(|item| item.message.contains("deleted or custom")) + .unwrap(); + assert_eq!(note.severity, Severity::Ok); + assert_eq!(note.state, DiagnosticState::Unknown); + } + + #[cfg(feature = "llm-router")] + #[test] + fn doctor_surfaces_an_empty_router_registry_beyond_the_startup_log() { + let mut config = Config::default(); + config.default_provider = Some("openai".to_owned()); + config.default_model = Some("gpt-5.6".to_owned()); + let mut items = Vec::new(); + check_router_candidates(&config, &mut items); + assert_eq!(items.len(), 1); + assert!( + items + .iter() + .any(|item| item.message.contains("no reachable candidates")) + ); + assert_eq!(config.default_model.as_deref(), Some("gpt-5.6")); + + config.default_provider = Some("openrouter".to_owned()); + config.default_model = Some("anthropic/claude-sonnet-5".to_owned()); + items.clear(); + check_router_candidates(&config, &mut items); + assert!( + items.is_empty(), + "the published OpenRouter candidate must actually be reachable" + ); + } + + #[cfg(feature = "llm-router")] + #[test] + fn doctor_requires_a_reachable_model_in_a_non_default_provider_route() { + let mut config = Config { + default_provider: Some("openai".into()), + default_model: Some("gpt-5.6".into()), + ..Config::default() + }; + config.model_routes.push(crate::config::ModelRouteConfig { + hint: "quick".into(), + provider: "openrouter".into(), + model: "prx-absent-router-model".into(), + api_key: None, + credential_ref: None, + settings: Default::default(), + }); + let mut items = Vec::new(); + check_router_candidates(&config, &mut items); + assert_eq!(items.len(), 1); + assert!( + items + .iter() + .any(|item| item.message.contains("no reachable candidates")) + ); + config.model_routes.first_mut().unwrap().model = "anthropic/claude-sonnet-5".into(); + items.clear(); + check_router_candidates(&config, &mut items); + assert!(items.is_empty()); + } + + /// D-094 C-1, C-5: the doctor names a refused decision backend (which + /// runs builtin-only) and every decision credential nothing references, + /// by id, never by value. + #[test] + fn the_doctor_reports_a_refused_decision_backend_and_orphaned_credentials() { + let temp = TempDir::new().unwrap(); + let mut config = Config { + config_path: temp.path().join("config.toml"), + workspace_dir: temp.path().join("workspace"), + ..Config::default() + }; + config.decision_engine.enabled = true; + config.decision_engine.backend.get_or_insert_with(Default::default).kind = + crate::config::schema::decision_engine::BackendSelection::Fixed( + crate::config::schema::decision_engine::BackendKind::CompatibleHttp, + ); + config + .decision_engine + .backend + .get_or_insert_with(Default::default) + .endpoint = "http://127.0.0.1:8900/v1".to_string(); + config + .decision_engine + .backend + .get_or_insert_with(Default::default) + .model = "undeclared-model".to_string(); + let orphan = crate::config::manage::credentials::CredentialReferences::for_config(&config) + .unwrap() + .set( + "custom:http://127.0.0.1:8900/v1", + "decision-compatible-http-0badc0de", + "sk-DOCTOR-ORPHAN-SENTINEL-01", + ) + .unwrap(); + let mut items = Vec::new(); + check_decision_plane(&config, &mut items); + let text = items + .iter() + .map(|item| item.message.as_str()) + .collect::>() + .join("\n"); + assert_eq!(items.len(), 2, "{text}"); + assert!(text.contains("builtin-only") && text.contains(&orphan.id), "{text}"); + assert!(text.contains("prx providers credential remove "), "{text}"); + // Disabled, the credential store is not opened: a held lock does not + // delay the doctor, and nothing is reported from the store. + config.decision_engine.enabled = false; + std::fs::write(temp.path().join("auth-profiles.lock"), "pid=1\n").unwrap(); + let started = std::time::Instant::now(); + let mut items = Vec::new(); + check_decision_plane(&config, &mut items); + assert!( + items.is_empty(), + "{:?}", + items.iter().map(|item| &item.message).collect::>() + ); + assert!(started.elapsed() < std::time::Duration::from_secs(5)); + assert!(!text.contains("SENTINEL"), "{text}"); + } + + #[test] + fn memory_diagnostics_flag_vector_recall_inherited_from_the_flipped_default() { + let temp = TempDir::new().unwrap(); + let mut config = Config::default(); + config.workspace_dir = temp.path().to_path_buf(); + config.memory.embedding_provider = "local".to_string(); + config.memory.embedding_provider_explicit = false; + + let mut items = Vec::new(); + check_memory_diagnostics(&config, &mut items); + let notice = items + .iter() + .find(|item| item.message.contains("embedding_provider not set")) + .expect("doctor must report an inherited local vector recall default"); + assert_eq!(notice.severity, Severity::Warn); + assert_eq!(notice.category, "embedding"); + + config.memory.embedding_provider_explicit = true; + let mut items = Vec::new(); + check_memory_diagnostics(&config, &mut items); + assert!( + !items + .iter() + .any(|item| item.message.contains("embedding_provider not set")), + "an explicit provider must not be reported as an inherited default" + ); + } + + /// D-088 C-7: `prx doctor` names each blocked workspace MCP server with + /// the one-line opt-in, instead of leaving it to a log line. + #[test] + fn doctor_reports_a_workspace_mcp_server_blocked_by_the_opt_in() { + let temp = TempDir::new().unwrap(); + let mut config = Config::default(); + config.autonomy.level = crate::security::AutonomyLevel::Supervised; + config.workspace_dir = temp.path().to_path_buf(); + std::fs::write( + temp.path().join("mcp.json"), + r#"{"mcpServers": {"legacy": {"command": "npx", "args": ["some-mcp"]}}}"#, + ) + .unwrap(); + let mut items = Vec::new(); + check_workspace_mcp_servers(&config, &mut items); + let blocked = items + .iter() + .find(|item| { + item.message + .contains("workspace server 'legacy' (stdio) is not started") + }) + .expect("doctor must report the blocked workspace server"); + assert_eq!(blocked.severity, Severity::Warn); + assert!( + blocked.message.contains("workspace_servers = \"stdio\""), + "{}", + blocked.message + ); + + std::fs::remove_file(temp.path().join("mcp.json")).unwrap(); + let mut items = Vec::new(); + check_workspace_mcp_servers(&config, &mut items); + assert!(items.iter().all(|item| item.severity != Severity::Warn)); + } + + /// D-095 N-4: an operator `working_dir` inside the workspace is named. + #[test] + fn doctor_warns_about_a_working_dir_inside_the_workspace() { + let temp = TempDir::new().unwrap(); + let mut config = Config::default(); + config.workspace_dir = temp.path().to_path_buf(); + config.mcp.servers.insert( + "inside".into(), + crate::config::McpServerConfig { + command: Some("npx".into()), + working_dir: Some(temp.path().join("tools").display().to_string()), + ..crate::config::McpServerConfig::default() + }, + ); + let mut items = Vec::new(); + check_workspace_mcp_servers(&config, &mut items); + assert!( + items + .iter() + .any(|item| item.severity == Severity::Warn && item.message.contains("inside the agent's workspace")), + "{:?}", + items.iter().map(|item| &item.message).collect::>() + ); + } + + /// RED before PMME-h (D-095 L-3): a `pending` configuration record was + /// listed by `prx config status` but not by `prx doctor`. + #[test] + fn doctor_reports_an_unfinished_configuration_change() { + let temp = TempDir::new().unwrap(); + let config = Config { + config_path: temp.path().join("config.toml"), + workspace_dir: temp.path().join("workspace"), + ..Config::default() + }; + let record_dir = temp + .path() + .join(".config-history") + .join("0190a000-0000-7000-8000-000000000001"); + std::fs::create_dir_all(&record_dir).unwrap(); + let summary = crate::config::manage::ConfigChangeSummary::between(Some(&config), &config).unwrap(); + let now = chrono::Utc::now(); + let record = crate::config::manage::HistoryRecord { + version: 1, + id: "0190a000-0000-7000-8000-000000000001".into(), + created_at: now, + updated_at: now, + actor: crate::config::manage::ConfigActor::Cli, + status: crate::config::manage::RecordStatus::Pending, + base_revision: None, + committed_revision: None, + restores: None, + summary, + active_generation: None, + restart_required: Vec::new(), + reason: None, + }; + std::fs::write(record_dir.join("record.json"), serde_json::to_vec(&record).unwrap()).unwrap(); + + let mut items = Vec::new(); + check_unfinished_config_changes(&config, &mut items); + let pending = items + .iter() + .find(|item| item.message.contains("0190a000-0000-7000-8000-000000000001")) + .unwrap_or_else(|| { + panic!( + "doctor must report the pending record: {:?}", + items.iter().map(|item| &item.message).collect::>() + ) + }); + assert_eq!(pending.severity, Severity::Warn); + assert!(pending.message.contains("prx config rollback"), "{}", pending.message); + } + + /// D-107 amendment: a shell job stored before PRX recorded its creator + /// is named with the command that vouches for it; one with a recorded + /// creator is not; the check writes nothing. + #[test] + fn doctor_names_shell_jobs_without_a_recorded_creator() { + let temp = TempDir::new().unwrap(); + let mut config = Config::default(); + config.workspace_dir = temp.path().to_path_buf(); + let legacy = crate::cron::add_shell_job( + &config, + None, + crate::cron::Schedule::Cron { + expr: "*/5 * * * *".into(), + tz: None, + }, + "git pull project_payload_marker", + ) + .unwrap(); + let recorded = crate::cron::add_shell_job( + &config, + None, + crate::cron::Schedule::Cron { + expr: "*/5 * * * *".into(), + tz: None, + }, + "echo recorded", + ) + .unwrap(); + let db_path = temp.path().join("cron").join("jobs.db"); + rusqlite::Connection::open(&db_path) + .unwrap() + .execute( + "UPDATE cron_jobs SET created_via = NULL WHERE id = ?1", + [legacy.id.as_str()], + ) + .unwrap(); + let before = std::fs::read(&db_path).unwrap(); + + let mut items = Vec::new(); + check_unowned_shell_jobs(&config, &mut items); + let warnings = items + .iter() + .filter(|item| item.category == "git" && item.severity == Severity::Warn) + .collect::>(); + assert_eq!(warnings.len(), 1, "{warnings:?}"); + let warning = warnings.first().map(|item| item.message.as_str()).unwrap_or_default(); + assert!( + warning.contains(&format!("prx cron mark-operator {}", legacy.id)), + "{warning}" + ); + assert!(!warning.contains(&recorded.id), "{warning}"); + assert!(!warning.contains("project_payload_marker"), "{warning}"); + assert_eq!( + std::fs::read(&db_path).unwrap(), + before, + "doctor wrote to the cron store" + ); + + crate::cron::mark_job_operator(&config, &legacy.id).unwrap(); + let mut items = Vec::new(); + check_unowned_shell_jobs(&config, &mut items); + assert!( + !items + .iter() + .any(|item| item.category == "git" && item.severity == Severity::Warn), + "{items:?}" + ); + } + + /// SP-PMM H-4: a `pending` history record is reported with its + /// recovery commands and never applied (loading the configuration and + /// running the checks leave the files and the record as they were); a + /// persisted selection the evidence does not verify is listed by name. + #[tokio::test] + async fn a_pending_record_is_reported_never_applied_and_unverified_selections_are_listed() { + let temp = TempDir::new().unwrap(); + let mut config = Config { + config_path: temp.path().join("config.toml"), + workspace_dir: temp.path().join("workspace"), + default_provider: Some("openai".into()), + default_model: Some("gpt-4o".into()), + ..Config::default() + }; + config.model_routes.push(crate::config::ModelRouteConfig { + settings: Default::default(), + hint: "fast".into(), + provider: "openai".into(), + model: "pmmh-unlisted-route-model".into(), + api_key: None, + credential_ref: None, + }); + config.save().await.unwrap(); + let history = crate::config::manage::ConfigHistory::for_config(&config.config_path).unwrap(); + let mut other = config.clone(); + other.default_temperature = 0.1; + let before = crate::config::files::current_before_image(&config.config_path).unwrap(); + let record = history + .create_pending( + crate::config::manage::history::NewRecord { + actor: crate::config::manage::ConfigActor::Cli, + base_revision: None, + restores: None, + summary: crate::config::manage::ConfigChangeSummary::between(Some(&config), &other).unwrap(), + }, + &before, + ) + .unwrap(); + let config_bytes = std::fs::read(&config.config_path).unwrap(); + let record_bytes = std::fs::read(history.dir().join(&record.id).join("record.json")).unwrap(); + + let loaded = Config::load_from_path(&config.config_path, config.workspace_dir.clone()).unwrap(); + let mut items = Vec::new(); + check_unfinished_config_changes(&loaded, &mut items); + check_persisted_selections(&loaded, &mut items); + + let pending = items + .iter() + .find(|item| item.message.contains(&record.id)) + .expect("the pending record is reported"); + assert!( + pending.message.contains("is pending") && pending.message.contains("never applied"), + "{}", + pending.message + ); + let unverified = items + .iter() + .find(|item| item.message.contains("model route `hint:fast`")) + .expect("the unverified route is reported"); + assert_eq!(unverified.severity, Severity::Warn); + assert!( + unverified.message.contains("pmmh-unlisted-route-model"), + "{}", + unverified.message + ); + assert_eq!( + std::fs::read(&config.config_path).unwrap(), + config_bytes, + "a pending record was applied" + ); + assert_eq!( + std::fs::read(history.dir().join(&record.id).join("record.json")).unwrap(), + record_bytes, + "the pending record was rewritten" + ); + assert_eq!( + history.get(&record.id).unwrap().status, + crate::config::manage::RecordStatus::Pending + ); + } + + /// D-104 C-1 ruling: `prx doctor` names two embedding routes sharing a + /// hint, with the fix. + #[test] + fn doctor_reports_duplicate_embedding_route_hints() { + let route = |model: &str| crate::config::EmbeddingRouteConfig { + hint: "semantic".into(), + provider: "openai".into(), + model: model.into(), + dimensions: None, + api_key: None, + credential_ref: None, + }; + let mut config = Config::default(); + config.embedding_routes = vec![route("text-embedding-3-small"), route("text-embedding-3-large")]; + let mut items = Vec::new(); + check_persisted_selections(&config, &mut items); + let item = items + .iter() + .find(|item| item.message.contains("both use hint 'semantic'")) + .expect("the duplicate is reported"); + assert_eq!(item.severity, Severity::Warn); + assert!( + item.message.contains("Give each route its own hint"), + "{}", + item.message + ); + } + + /// HOOKS-ENV: `prx doctor` names blocked workspace hooks with the + /// one-line opt-in, and says when they run. + #[test] + fn doctor_reports_blocked_workspace_hooks_with_the_opt_in() { + let temp = TempDir::new().unwrap(); + let mut config = Config::default(); + config.workspace_dir = temp.path().to_path_buf(); + std::fs::write( + temp.path().join("hooks.json"), + r#"{"hooks": {"turn_complete": [{"command": "true"}]}}"#, + ) + .unwrap(); + let mut items = Vec::new(); + check_workspace_hooks(&config, &mut items); + let blocked = items + .iter() + .find(|item| item.category == "hooks") + .expect("test: a hooks item"); + assert_eq!(blocked.severity, Severity::Warn); + assert!( + blocked.message.contains(crate::hooks::WORKSPACE_HOOKS_OPT_IN), + "{}", + blocked.message + ); + + config.security.workspace_hooks = crate::config::WorkspaceHooks::On; + let mut items = Vec::new(); + check_workspace_hooks(&config, &mut items); + assert!(items.iter().all(|item| item.severity != Severity::Warn)); + } + + #[test] + fn deployed_binary_check_accepts_the_runtime_path() { + let temp = TempDir::new().unwrap(); + let deployed = temp.path().join("prx"); + std::fs::write(&deployed, b"binary").unwrap(); + let mut items = Vec::new(); + + check_deployed_binary_paths(&mut items, Some(deployed.clone()), Ok(deployed)); + + assert_eq!(items.len(), 2); + assert!(items.iter().all(|item| item.severity == Severity::Ok)); + assert!( + items + .iter() + .any(|item| item.message == "doctor is running from deployed binary") + ); + } + + #[test] + fn deployed_binary_check_reports_missing_path_lookup_without_linux_hardcode() { + let mut items = Vec::new(); + + check_deployed_binary_paths(&mut items, None, Ok(PathBuf::from("/opt/homebrew/bin/prx"))); + + assert_eq!(items.len(), 2); + assert_eq!(items[0].severity, Severity::Error); + assert_eq!(items[0].message, "deployed prx binary not found on PATH"); + assert!(items.iter().all(|item| !item.message.contains("/home/ck"))); + } + + struct EnvGuard { + key: &'static str, + original: Option, + } + + impl EnvGuard { + #[allow(unsafe_code)] + fn set(key: &'static str, value: Option<&str>) -> Self { + let original = std::env::var(key).ok(); + if key == "HOME" { + crate::config::schema::follow_test_home_env(value.map(std::ffi::OsStr::new)); + } + // SAFETY: test-only env manipulation; tests that use this must be serialized. + unsafe { + match value { + Some(next) => std::env::set_var(key, next), + None => std::env::remove_var(key), + } + } + Self { key, original } + } + } + + impl Drop for EnvGuard { + #[allow(unsafe_code)] + fn drop(&mut self) { + if self.key == "HOME" { + crate::config::schema::follow_test_home_env(self.original.as_deref().map(std::ffi::OsStr::new)); + } + // SAFETY: test-only env manipulation; restoring previous value. + unsafe { + if let Some(original) = self.original.as_deref() { + std::env::set_var(self.key, original); + } else { + std::env::remove_var(self.key); + } + } + } + } + + fn doctor_env_lock() -> std::sync::MutexGuard<'static, ()> { + static LOCK: std::sync::OnceLock> = std::sync::OnceLock::new(); + LOCK.get_or_init(|| std::sync::Mutex::new(())) + .lock() + .expect("doctor env lock poisoned") + } + + #[test] + fn provider_validation_checks_custom_url_shape() { + let config = Config::default(); + let validate = |provider: &str| { + provider_validation_error( + &config, + provider, + crate::providers::selection::default_model(&config), + crate::providers::selection::credential_for(&config, provider), + ) + }; + assert!(validate("openrouter").is_none()); + assert!(validate("custom:https://example.com").is_none()); + assert!(validate("anthropic-custom:https://example.com").is_none()); + + let invalid_custom = validate("custom:").unwrap_or_default(); + assert!(invalid_custom.contains("requires a URL")); + + let invalid_unknown = validate("totally-fake").unwrap_or_default(); + assert!(invalid_unknown.contains("Unknown provider")); + } + + #[test] + fn diag_item_icons() { + assert_eq!(DiagItem::ok("t", "m").icon(), "✅"); + assert_eq!(DiagItem::warn("t", "m").icon(), "⚠️ "); + assert_eq!(DiagItem::error("t", "m").icon(), "❌"); + } + + #[tokio::test] + async fn diagnostic_states_are_emitted_by_real_checks() { + let temp = TempDir::new().unwrap(); + let mut config = Config::default(); + config.config_path = temp.path().join("config.toml"); + config.workspace_dir = temp.path().to_path_buf(); + std::fs::write(&config.config_path, "configured").unwrap(); + + let mut items = Vec::new(); + check_memory_diagnostics(&config, &mut items); + check_runtime_readiness(&config, &mut items); + check_environment(&mut items); + check_daemon_state(&config, &mut items); + check_runtime_memory_health(&config, &mut items); + + let states: std::collections::HashSet<_> = items.iter().map(|item| item.state).collect(); + for expected in [ + DiagnosticState::Declared, + DiagnosticState::Configured, + DiagnosticState::Ready, + DiagnosticState::Healthy, + DiagnosticState::Unknown, + ] { + assert!(states.contains(&expected), "missing diagnostic state {expected:?}"); + } + } + + #[test] + fn doctor_reports_legacy_fitness_counts_and_repair_command() { + let temp = TempDir::new().unwrap(); + let mut config = Config::default(); + config.workspace_dir = temp.path().join("workspace"); + std::fs::create_dir_all(config.workspace_dir.join("memory")).unwrap(); + let connection = rusqlite::Connection::open(config.workspace_dir.join("memory/brain.db")).unwrap(); + connection + .execute_batch( + "CREATE TABLE memories (key TEXT NOT NULL, content TEXT NOT NULL); + INSERT INTO memories VALUES ('self/fitness/daily/2026-09-10', 'one'); + INSERT INTO memories VALUES ('self/fitness/daily/2026-09-11', 'two'); + INSERT INTO memories VALUES ('keep/key', 'keep');", + ) + .unwrap(); + std::fs::write( + config.workspace_dir.join("MEMORY.md"), + "- [t] **self/fitness/daily/2026-09-10**: legacy\n- [t] **keep/key**: keep\n", + ) + .unwrap(); + std::fs::write( + config.workspace_dir.join("MEMORY_SNAPSHOT.md"), + "### 🔑 `self/fitness/daily/2026-09-10`\n\nlegacy\n\n---\n", + ) + .unwrap(); + let mut items = Vec::new(); + + check_legacy_fitness_telemetry(&config, &mut items); + + assert_eq!(items.len(), 1); + assert_eq!(items[0].severity, Severity::Warn); + assert!(items[0].message.contains("database=2")); + assert!(items[0].message.contains("MEMORY.md=1")); + assert!(items[0].message.contains("MEMORY_SNAPSHOT.md=1")); + assert!(items[0].message.contains("prx fitness migrate-legacy --apply")); + } + + #[test] + fn doctor_clean_fitness_probe_is_read_only_on_missing_database() { + let temp = TempDir::new().unwrap(); + let mut config = Config::default(); + config.workspace_dir = temp.path().join("workspace"); + std::fs::create_dir_all(&config.workspace_dir).unwrap(); + let db_path = config.workspace_dir.join("memory/brain.db"); + let mut items = Vec::new(); + + check_legacy_fitness_telemetry(&config, &mut items); + + assert_eq!(items.len(), 1); + assert_eq!(items[0].severity, Severity::Ok); + assert!(items[0].message.contains("absent")); + assert!(!db_path.exists()); + } + + #[test] + fn classify_model_probe_error_marks_unsupported_as_skipped() { + let outcome = classify_model_probe_error("Provider 'copilot' does not support live model discovery yet"); + assert_eq!(outcome, ModelProbeVerdict::Skipped); + } + + #[test] + fn classify_model_probe_error_marks_auth_and_plan_issues() { + let auth_outcome = classify_model_probe_error("OpenAI API error (401): unauthorized"); + assert_eq!(auth_outcome, ModelProbeVerdict::AuthOrAccess); + + let plan_outcome = classify_model_probe_error("Z.AI API error (429): plan does not include requested model"); + assert_eq!(plan_outcome, ModelProbeVerdict::AuthOrAccess); + } + + #[test] + fn config_validation_catches_bad_temperature() { + let mut config = Config::default(); + config.default_temperature = 5.0; + let mut items = Vec::new(); + check_config_semantics(&config, &mut items); + let temp_item = items.iter().find(|i| i.message.contains("temperature")); + assert!(temp_item.is_some()); + assert_eq!(temp_item.unwrap().severity, Severity::Error); + } + + #[test] + fn config_validation_accepts_valid_temperature() { + let mut config = Config::default(); + config.default_temperature = 0.7; + let mut items = Vec::new(); + check_config_semantics(&config, &mut items); + let temp_item = items.iter().find(|i| i.message.contains("temperature")); + assert!(temp_item.is_some()); + assert_eq!(temp_item.unwrap().severity, Severity::Ok); + } + + #[test] + fn config_validation_warns_for_explicit_unrestricted_autonomy() { + let mut config = Config::default(); + config.autonomy.workspace_only = false; + config.autonomy.forbidden_paths.clear(); + config.autonomy.max_cost_per_day_cents = u32::MAX; + let mut items = Vec::new(); + + check_config_semantics(&config, &mut items); + + let item = items + .iter() + .find(|item| item.message.contains("explicit unrestricted autonomy profile")) + .expect("unrestricted posture warning"); + assert_eq!(item.severity, Severity::Warn); + } + + #[test] + fn config_validation_acknowledged_unrestricted_autonomy_is_quiet() { + let mut config = Config::default(); + config.autonomy.workspace_only = false; + config.autonomy.forbidden_paths.clear(); + config.autonomy.max_cost_per_day_cents = u32::MAX; + config.autonomy.acknowledge_unrestricted_profile = true; + let mut items = Vec::new(); + + check_config_semantics(&config, &mut items); + + assert!( + !items + .iter() + .any(|item| item.message.contains("explicit unrestricted autonomy profile")) + ); + } + + #[test] + fn config_validation_warns_for_explicit_delegate_wildcard() { + let mut config = Config::default(); + config.agents.insert( + "worker".into(), + crate::config::DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), + approval_wait_secs: 600, + limits: crate::config::AgentLimits::default(), + provider: "openrouter".into(), + model: "model-test".into(), + system_prompt: None, + api_key: None, + credential_ref: None, + temperature: None, + max_depth: 3, + agentic: true, + allowed_tools: vec!["*".into()], + identity_dir: None, + memory_scope: None, + spawn_enabled: None, + enabled: true, + autonomy: None, + }, + ); + let mut items = Vec::new(); + + check_config_semantics(&config, &mut items); + + let item = items + .iter() + .find(|item| item.message.contains("explicitly inherits all eligible parent tools")) + .expect("delegate wildcard warning"); + assert_eq!(item.severity, Severity::Warn); + } + + #[test] + fn config_validation_warns_no_channels() { + let config = Config::default(); + let mut items = Vec::new(); + check_config_semantics(&config, &mut items); + let ch_item = items.iter().find(|i| i.message.contains("channel")); + assert!(ch_item.is_some()); + assert_eq!(ch_item.unwrap().severity, Severity::Warn); + } + + #[test] + fn wacli_is_reported_as_a_configured_channel() { + let mut config = Config::default(); + config.channels_config.cli = false; + config.channels_config.wacli = Some(crate::config::WacliConfig::default()); + + assert_eq!(configured_channel_names(&config), vec!["wacli"]); + let mut items = Vec::new(); + check_channel_runtime(&config, &mut items); + assert!( + items + .iter() + .any(|item| item.message.contains("configured channels: wacli")) + ); + } + + #[test] + fn daemon_state_reports_stale_scheduler_as_unhealthy() { + let temp = TempDir::new().unwrap(); + let mut config = Config::default(); + config.config_path = temp.path().join("config.toml"); + + let stale = (Utc::now() - chrono::Duration::seconds(SCHEDULER_STALE_SECONDS + 60)).to_rfc3339(); + let state = serde_json::json!({ + "pid": std::process::id(), + "updated_at": Utc::now().to_rfc3339(), + "components": { + "scheduler": { + "status": "ok", + "updated_at": stale, + "last_ok": stale, + "last_error": null, + "restart_count": 0 + } + } + }); + std::fs::write( + crate::daemon::state_file_path(&config), + serde_json::to_vec(&state).unwrap(), + ) + .unwrap(); + + let mut items = Vec::new(); + check_daemon_state(&config, &mut items); + + let scheduler_item = items + .iter() + .find(|item| item.message.contains("scheduler unhealthy")) + .expect("stale always-on scheduler should be unhealthy"); + assert_eq!(scheduler_item.severity, Severity::Error); + } + + #[test] + fn config_validation_catches_unknown_provider() { + let mut config = Config::default(); + config.default_provider = Some("totally-fake".into()); + let mut items = Vec::new(); + check_config_semantics(&config, &mut items); + let prov_item = items.iter().find(|i| i.message.contains("default provider")); + assert!(prov_item.is_some()); + assert_eq!(prov_item.unwrap().severity, Severity::Error); + } + + #[test] + fn config_validation_catches_malformed_custom_provider() { + let mut config = Config::default(); + config.default_provider = Some("custom:".into()); + let mut items = Vec::new(); + check_config_semantics(&config, &mut items); + + let prov_item = items + .iter() + .find(|item| item.message.contains("default provider \"custom:\" is invalid")); + assert!(prov_item.is_some()); + assert_eq!(prov_item.unwrap().severity, Severity::Error); + } + + #[test] + fn config_validation_accepts_custom_provider() { + let mut config = Config::default(); + config.default_provider = Some("custom:https://my-api.com".into()); + let mut items = Vec::new(); + check_config_semantics(&config, &mut items); + let prov_item = items.iter().find(|i| i.message.contains("is valid")); + assert!(prov_item.is_some()); + assert_eq!(prov_item.unwrap().severity, Severity::Ok); + } + + #[test] + fn config_validation_accepts_active_auth_profile_credential() { + let tmp = TempDir::new().unwrap(); + std::fs::write(tmp.path().join("config.toml"), "").unwrap(); + let store = crate::auth::profiles::AuthProfilesStore::new(tmp.path(), false); + store + .upsert_profile( + crate::auth::profiles::AuthProfile::new_token("moonshot", "default", "moonshot-test-key".to_string()), + true, + ) + .unwrap(); + + let mut config = Config::default(); + config.config_path = tmp.path().join("config.toml"); + config.default_provider = Some("moonshot".into()); + config.api_key = None; + config.secrets.encrypt = false; + + let mut items = Vec::new(); + check_config_semantics(&config, &mut items); + + let auth_item = items + .iter() + .find(|item| item.message.contains("auth profile credential configured")); + assert!( + auth_item.is_some(), + "items: {:?}", + items.iter().map(|i| &i.message).collect::>() + ); + assert_eq!(auth_item.unwrap().severity, Severity::Ok); + assert!( + !items.iter().any(|item| item.message.contains("no api_key")), + "active auth profile should suppress missing api_key warning" + ); + } + + #[test] + fn config_validation_maps_kimi_alias_to_moonshot_auth_profile() { + let tmp = TempDir::new().unwrap(); + std::fs::write(tmp.path().join("config.toml"), "").unwrap(); + let store = crate::auth::profiles::AuthProfilesStore::new(tmp.path(), false); + store + .upsert_profile( + crate::auth::profiles::AuthProfile::new_token("moonshot", "default", "moonshot-test-key".to_string()), + true, + ) + .unwrap(); + + let mut config = Config::default(); + config.config_path = tmp.path().join("config.toml"); + config.default_provider = Some("kimi".into()); + config.api_key = None; + config.secrets.encrypt = false; + + let mut items = Vec::new(); + check_config_semantics(&config, &mut items); + + let auth_item = items + .iter() + .find(|item| item.message.contains("auth profile credential configured")); + assert!( + auth_item.is_some(), + "items: {:?}", + items.iter().map(|i| &i.message).collect::>() + ); + assert_eq!(auth_item.unwrap().severity, Severity::Ok); + } + + #[test] + fn config_validation_warns_bad_fallback() { + let mut config = Config::default(); + config.reliability.fallback_providers = vec!["fake-provider".into()]; + let mut items = Vec::new(); + check_config_semantics(&config, &mut items); + let fb_item = items.iter().find(|i| i.message.contains("fallback provider")); + assert!(fb_item.is_some()); + assert_eq!(fb_item.unwrap().severity, Severity::Warn); + } + + #[test] + fn config_validation_warns_bad_custom_fallback() { + let mut config = Config::default(); + config.reliability.fallback_providers = vec!["custom:".into()]; + let mut items = Vec::new(); + check_config_semantics(&config, &mut items); + + let fb_item = items + .iter() + .find(|item| item.message.contains("fallback provider \"custom:\" is invalid")); + assert!(fb_item.is_some()); + assert_eq!(fb_item.unwrap().severity, Severity::Warn); + } + + #[test] + fn config_validation_warns_provider_resilience_degraded_with_single_available_provider() { + let _guard = doctor_env_lock(); + + // Isolate from host credentials: override HOME to an empty temp dir so + // resolve_claude_code_context cannot find ~/.claude/.credentials.json, + // and clear any ambient Anthropic env vars. + let iso_home = std::env::temp_dir().join(format!("openprx-doctor-degrade-test-{}", std::process::id())); + std::fs::create_dir_all(&iso_home).unwrap(); + let _home_guard = EnvGuard::set("HOME", Some(iso_home.to_str().unwrap())); + let _anthropic_key_guard = EnvGuard::set("ANTHROPIC_API_KEY", None); + let _anthropic_oauth_guard = EnvGuard::set("ANTHROPIC_OAUTH_TOKEN", None); + + let mut config = Config::default(); + config.default_provider = Some("openai".into()); + config.api_key = Some("sk-test".into()); + config.reliability.fallback_providers = vec!["anthropic".into()]; + + let mut items = Vec::new(); + check_config_semantics(&config, &mut items); + + let _ = std::fs::remove_dir_all(&iso_home); + let degraded = items.iter().find(|item| { + item.message + .contains("provider resilience degraded: only 1 configured+available") + }); + assert!(degraded.is_some()); + assert_eq!(degraded.unwrap().severity, Severity::Warn); + } + + #[test] + fn config_validation_acknowledged_single_provider_risk_is_quiet() { + let _guard = doctor_env_lock(); + let iso_home = std::env::temp_dir().join(format!("openprx-doctor-ack-test-{}", std::process::id())); + std::fs::create_dir_all(&iso_home).unwrap(); + let _home_guard = EnvGuard::set("HOME", Some(iso_home.to_str().unwrap())); + let _anthropic_key_guard = EnvGuard::set("ANTHROPIC_API_KEY", None); + let _anthropic_oauth_guard = EnvGuard::set("ANTHROPIC_OAUTH_TOKEN", None); + + let mut config = Config::default(); + config.default_provider = Some("openai".into()); + config.api_key = Some("sk-test".into()); + config.reliability.fallback_providers = vec!["anthropic".into()]; + config.reliability.acknowledge_single_provider_risk = true; + + let mut items = Vec::new(); + check_config_semantics(&config, &mut items); + + assert!( + !items + .iter() + .any(|item| item.message.contains("provider resilience degraded")) + ); + let _ = std::fs::remove_dir_all(&iso_home); + } + + #[test] + fn config_validation_warns_model_fallback_route_mismatch() { + let mut config = Config::default(); + config.default_provider = Some("openai".into()); + config.reliability.model_fallbacks.insert( + "openai/gpt-4o".into(), + vec!["anthropic/claude-sonnet-4-20250514".into()], + ); + + let mut items = Vec::new(); + check_config_semantics(&config, &mut items); + + let mismatch = items + .iter() + .find(|item| item.message.contains("model_fallbacks route mismatch")); + assert!(mismatch.is_some()); + assert_eq!(mismatch.unwrap().severity, Severity::Warn); + } + + /// D-072 L-9 / D-075: doctor mirrors the failover chain. A llama.cpp + /// fallback never answers another provider's route, so a fallback model + /// only it could serve is a route mismatch; on its own route it serves + /// any repository, so no warning there. + #[test] + fn config_validation_follows_llamacpp_route_identity() { + let temp = tempfile::tempdir().expect("test: temp dir"); + let base = Config { + config_path: temp.path().join("config.toml"), + workspace_dir: temp.path().join("workspace"), + ..Config::default() + }; + let warning = |config: &Config, needle: &str| { + let mut items = Vec::new(); + check_config_semantics(config, &mut items); + items.into_iter().find(|item| item.message.contains(needle)) + }; + + // D-076 N-1: a llama.cpp fallback with nothing it may serve is never used. + let mut unused = base.clone(); + unused.default_provider = Some("anthropic".into()); + unused.reliability.fallback_providers = vec!["llamacpp".into()]; + assert!( + warning(&unused, "\"llamacpp\" is never used").is_some_and(|item| item.severity == Severity::Warn), + "a llama.cpp fallback without a repository entry is dead config" + ); + unused + .reliability + .model_fallbacks + .insert("anthropic/claude-sonnet-5".into(), vec!["claude-haiku-5".into()]); + assert!( + warning(&unused, "\"llamacpp\" is never used").is_some(), + "a bare id is routed to another provider" + ); + + // Named in model_fallbacks: the fallback serves it; no warning. + let mut named = base.clone(); + named.default_provider = Some("anthropic".into()); + named.reliability.fallback_providers = vec!["llamacpp".into()]; + named.reliability.model_fallbacks.insert( + "anthropic/claude-sonnet-5".into(), + vec!["ggml-org/gpt-oss-20b-GGUF".into()], + ); + assert!(warning(&named, "is never used").is_none()); + assert!(warning(&named, "model_fallbacks route mismatch").is_none()); + + // A `/…` fallback model only the llama.cpp fallback could + // take is routed to another provider: a mismatch. + let mut elsewhere = named.clone(); + elsewhere.reliability.model_fallbacks.insert( + "anthropic/claude-sonnet-5".into(), + vec!["openai/gpt-5".into(), "ggml-org/gpt-oss-20b-GGUF".into()], + ); + assert!( + warning(&elsewhere, "model_fallbacks route mismatch").is_some_and(|item| item.severity == Severity::Warn) + ); + + // On its own route llama.cpp serves any repository. + let mut own_route = base; + own_route.default_provider = Some("llamacpp".into()); + own_route.default_model = Some("ggml-org/gpt-oss-20b-GGUF".into()); + own_route.reliability.model_fallbacks.insert( + "ggml-org/gpt-oss-20b-GGUF".into(), + vec!["google/gemma-3-27b-it-GGUF".into()], + ); + assert!(warning(&own_route, "model_fallbacks route mismatch").is_none()); + } + + /// PMM-C: doctor resolves the configured default: refused is an error, + /// id-only is a warning (D-018 Q1: it keeps running, unverified), + /// declared is fine. + #[test] + fn doctor_reports_how_the_default_model_resolves() { + let temp = tempfile::tempdir().expect("test: temp dir"); + let mut config = Config::default(); + config.workspace_dir = temp.path().to_path_buf(); + config.config_path = temp.path().join("config.toml"); + config.default_provider = Some("openrouter".to_string()); + config.api_key = Some("PMMC-DOCTOR-ROOT".to_string()); + let models_item = |config: &Config| { + diagnose(config) + .items + .into_iter() + .find(|item| item.category == "models" && item.message.contains("default model")) + }; + + config.default_model = Some("jev-decision-test".to_string()); + config.providers.models.push( + toml::from_str( + "provider = \"openrouter\"\nmodel = \"jev-decision-test\"\noperations = [\"decision_endpoint\"]\n", + ) + .expect("test: declaration"), + ); + let item = models_item(&config).expect("a refused default is reported"); + assert_eq!(item.severity, Severity::Error, "{}", item.message); + assert!(item.message.contains("cannot be used for chat"), "{}", item.message); + assert!(!item.message.contains("PMMC-DOCTOR-ROOT")); + + config.default_model = Some("vendor/id-only".to_string()); + let item = models_item(&config).expect("an unverified default is reported"); + assert_eq!(item.severity, Severity::Warn, "{}", item.message); + assert!(item.message.contains("unverified"), "{}", item.message); + + config.providers.models.push( + toml::from_str("provider = \"openrouter\"\nmodel = \"vendor/id-only\"\noperations = [\"chat\"]\n") + .expect("test: declaration"), + ); + let item = models_item(&config).expect("a verified default is reported"); + assert_eq!(item.severity, Severity::Ok, "{}", item.message); + } + + #[test] + fn config_validation_warns_empty_model_route() { + let mut config = Config::default(); + config.model_routes = vec![crate::config::ModelRouteConfig { + settings: Default::default(), + hint: "fast".into(), + provider: "groq".into(), + model: String::new(), + api_key: None, + credential_ref: None, + }]; + let mut items = Vec::new(); + check_config_semantics(&config, &mut items); + let route_item = items.iter().find(|i| i.message.contains("empty model")); + assert!(route_item.is_some()); + assert_eq!(route_item.unwrap().severity, Severity::Warn); + } + + #[test] + fn config_validation_warns_empty_embedding_route_model() { + let mut config = Config::default(); + config.embedding_routes = vec![crate::config::EmbeddingRouteConfig { + hint: "semantic".into(), + provider: "openai".into(), + model: String::new(), + dimensions: Some(1536), + api_key: None, + credential_ref: None, + }]; + + let mut items = Vec::new(); + check_config_semantics(&config, &mut items); + let route_item = items + .iter() + .find(|item| item.message.contains("embedding route \"semantic\" has empty model")); + assert!(route_item.is_some()); + assert_eq!(route_item.unwrap().severity, Severity::Warn); + } + + #[test] + fn config_validation_warns_invalid_embedding_route_provider() { + let mut config = Config::default(); + config.embedding_routes = vec![crate::config::EmbeddingRouteConfig { + hint: "semantic".into(), + provider: "groq".into(), + model: "text-embedding-3-small".into(), + dimensions: None, + api_key: None, + credential_ref: None, + }]; + + let mut items = Vec::new(); + check_config_semantics(&config, &mut items); + let route_item = items + .iter() + .find(|item| item.message.contains("uses invalid provider \"groq\"")); + assert!(route_item.is_some()); + assert_eq!(route_item.unwrap().severity, Severity::Warn); + } + + #[test] + fn config_validation_warns_missing_embedding_hint_target() { + let mut config = Config::default(); + config.memory.embedding_model = "hint:semantic".into(); + + let mut items = Vec::new(); + check_config_semantics(&config, &mut items); + let route_item = items + .iter() + .find(|item| item.message.contains("no matching [[embedding_routes]] entry exists")); + assert!(route_item.is_some()); + assert_eq!(route_item.unwrap().severity, Severity::Warn); + } + + #[test] + fn environment_check_finds_git() { + let mut items = Vec::new(); + check_environment(&mut items); + let git_item = items.iter().find(|i| i.message.starts_with("git:")); + // git should be available in any CI/dev environment + assert!(git_item.is_some()); + assert_eq!(git_item.unwrap().severity, Severity::Ok); + } + + #[test] + fn parse_df_available_mb_uses_last_data_line() { + let stdout = "Filesystem 1M-blocks Used Available Use% Mounted on\n/dev/sda1 1000 500 500 50% /\n"; + assert_eq!(parse_df_available_mb(stdout), Some(500)); + } + + #[test] + fn truncate_for_display_preserves_utf8_boundaries() { + let preview = truncate_for_display("🙂example-alpha-build", 3); + assert_eq!(preview, "🙂ex…"); + } + + #[test] + fn workspace_check_does_not_create_probe_files() { + let tmp = TempDir::new().unwrap(); + let marker = tmp.path().join("marker.txt"); + std::fs::write(&marker, "existing").unwrap(); + let before: Vec<_> = std::fs::read_dir(tmp.path()) + .unwrap() + .map(|entry| entry.unwrap().file_name()) + .collect(); + let mut config = Config::default(); + config.workspace_dir = tmp.path().to_path_buf(); + let mut items = Vec::new(); + + check_workspace(&config, &mut items); + + let after: Vec<_> = std::fs::read_dir(tmp.path()) + .unwrap() + .map(|entry| entry.unwrap().file_name()) + .collect(); + assert_eq!(before, after); + assert!( + items + .iter() + .any(|item| item.message.contains("no write probe performed")) + ); + } + + #[test] + fn doctor_run_returns_error_when_report_contains_errors() { + let temp = TempDir::new().unwrap(); + let mut config = Config::default(); + config.config_path = temp.path().join("missing-config.toml"); + config.workspace_dir = temp.path().join("missing-workspace"); + + assert!( + run(&config).is_err(), + "doctor must return nonzero semantics for ERROR findings" + ); + } + + #[tokio::test] + async fn runtime_memory_probe_does_not_create_missing_sqlite_database() { + let temp = TempDir::new().unwrap(); + let mut config = Config::default(); + config.workspace_dir = temp.path().join("workspace"); + std::fs::create_dir_all(&config.workspace_dir).unwrap(); + let db_path = config.workspace_dir.join("memory").join("brain.db"); + + let mut items = Vec::new(); + check_runtime_memory_health(&config, &mut items); + + assert!(!db_path.exists(), "doctor memory probe must not create brain.db"); + } + + #[test] + fn config_validation_reports_delegate_agents_in_sorted_order() { + let mut config = Config::default(); + config.agents.insert( + "zeta".into(), + crate::config::DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), + approval_wait_secs: 600, + limits: crate::config::AgentLimits::default(), + provider: "totally-fake".into(), + model: "model-z".into(), + system_prompt: None, + api_key: None, + credential_ref: None, + temperature: None, + max_depth: 3, + agentic: false, + allowed_tools: Vec::new(), + identity_dir: None, + memory_scope: None, + spawn_enabled: None, + enabled: true, + autonomy: None, + }, + ); + config.agents.insert( + "alpha".into(), + crate::config::DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), + approval_wait_secs: 600, + limits: crate::config::AgentLimits::default(), + provider: "totally-fake".into(), + model: "model-a".into(), + system_prompt: None, + api_key: None, + credential_ref: None, + temperature: None, + max_depth: 3, + agentic: false, + allowed_tools: Vec::new(), + identity_dir: None, + memory_scope: None, + spawn_enabled: None, + enabled: true, + autonomy: None, + }, + ); + + let mut items = Vec::new(); + check_config_semantics(&config, &mut items); + + let agent_messages: Vec<_> = items + .iter() + .filter(|item| item.message.starts_with("agent \"")) + .map(|item| item.message.as_str()) + .collect(); + + assert_eq!(agent_messages.len(), 2); + assert!(agent_messages[0].contains("agent \"alpha\"")); + assert!(agent_messages[1].contains("agent \"zeta\"")); + } + + // ---- FIX-P2-06: runtime readiness sub-checks ------------------------ + + #[test] + fn runtime_readiness_emits_six_subchecks() { + let config = Config::default(); + let mut items = Vec::new(); + check_runtime_readiness(&config, &mut items); + let readiness: Vec<&str> = items + .iter() + .filter(|i| i.category == "readiness") + .map(|i| i.message.as_str()) + .collect(); + assert_eq!(readiness.len(), 6, "expected 6 readiness sub-checks"); + for prefix in ["owner:", "topic:", "task:", "document:", "vector:", "runtime-control:"] { + assert!( + readiness.iter().any(|m| m.starts_with(prefix)), + "missing readiness sub-check with prefix {prefix}" + ); + } + assert!(items.iter().any(|item| { + item.state == DiagnosticState::Ready && item.message.starts_with("topic: local similarity") + })); + assert!( + items.iter().any(|item| { + item.state == DiagnosticState::Ready && item.message.starts_with("vector: index ready") + }) + ); + } + + #[test] + fn runtime_readiness_flags_zero_dimension_with_embeddings() { + let mut config = Config::default(); + config.memory.embedding_provider = "openai".into(); + config.memory.embedding_dimensions = 0; + let mut items = Vec::new(); + check_runtime_readiness(&config, &mut items); + assert!( + items.iter().any(|i| i.category == "readiness" + && i.severity == Severity::Error + && i.message.starts_with("vector:")), + "expected vector readiness error for zero dimension" + ); + } + + // ---- FIX-P2-07: postgres health ------------------------------------- + + #[tokio::test] + async fn postgres_health_skips_when_not_selected() { + // Default backend is sqlite -> no postgres items emitted at all. + let config = Config::default(); + let mut items = Vec::new(); + check_postgres_health(&config, &mut items).await; + assert!(items.iter().all(|i| i.category != "postgres")); + } + + #[tokio::test] + async fn postgres_health_errors_on_missing_db_url() { + let mut config = Config::default(); + config.memory.backend = "postgres".into(); + let mut items = Vec::new(); + check_postgres_health(&config, &mut items).await; + assert!( + items + .iter() + .any(|i| i.category == "postgres" && i.severity == Severity::Error), + "expected error when postgres selected without db_url" + ); + } + + #[tokio::test] + async fn postgres_health_errors_on_bad_scheme() { + let mut config = Config::default(); + config.memory.backend = "postgres".into(); + config.storage.provider.config.db_url = Some("mysql://host/db".into()); + let mut items = Vec::new(); + check_postgres_health(&config, &mut items).await; + assert!( + items.iter().any(|i| i.category == "postgres" + && i.severity == Severity::Error + && i.message.contains("postgres://")), + "expected scheme validation error" + ); + } + + // ---- FIX-P2-08: embedding endpoint probe ---------------------------- + + #[tokio::test] + async fn embedding_probe_skips_without_custom_provider() { + // Default provider is "none" -> no embedding probe items. + let config = Config::default(); + let mut items = Vec::new(); + check_embedding_endpoint(&config, &mut items).await; + assert!(items.iter().all(|i| i.category != "embedding")); + } + + #[tokio::test] + async fn embedding_probe_warns_on_unreachable_custom_endpoint() { + let mut config = Config::default(); + // Port 1 on localhost is reserved and refuses connections quickly. + config.memory.embedding_provider = "custom:http://127.0.0.1:1/embed".into(); + let mut items = Vec::new(); + check_embedding_endpoint(&config, &mut items).await; + assert!( + items + .iter() + .any(|i| i.category == "embedding" && i.severity == Severity::Warn), + "expected warn for unreachable embedding endpoint" + ); + } + + // ---- daemon process PATH (v0.8.139) --------------------------------- + + fn environ_blob(entries: &[&str]) -> Vec { + let mut bytes = Vec::new(); + for entry in entries { + bytes.extend_from_slice(entry.as_bytes()); + bytes.push(0); + } + bytes + } + + fn path_value(dirs: &[&Path]) -> String { + std::env::join_paths(dirs).unwrap().to_string_lossy().into_owned() + } + + #[test] + fn daemon_path_from_environ_picks_the_path_entry() { + let blob = environ_blob(&["HOME=/home/ck", "PATH=/usr/bin:/bin", "LANG=C"]); + assert_eq!(daemon_path_from_environ(&blob).as_deref(), Some("/usr/bin:/bin")); + } + + #[test] + fn daemon_path_from_environ_ignores_path_lookalike_keys() { + let blob = environ_blob(&["LD_LIBRARY_PATH=/opt/lib", "MANPATH=/usr/share/man"]); + assert!(daemon_path_from_environ(&blob).is_none()); + } + + #[test] + fn daemon_path_ok_when_required_directory_is_present() { + let temp = TempDir::new().unwrap(); + let bin = temp.path().join("cargo-bin"); + std::fs::create_dir_all(&bin).unwrap(); + let other = temp.path().join("usr-bin"); + std::fs::create_dir_all(&other).unwrap(); + + let path = path_value(&[other.as_path(), bin.as_path()]); + let blob = environ_blob(&["HOME=/home/ck", &format!("PATH={path}")]); + let item = evaluate_daemon_environ(&blob, std::slice::from_ref(&bin)); + + assert_eq!(item.severity, Severity::Ok, "message: {}", item.message); + assert_eq!(item.category, "daemon"); + assert!( + item.message.contains(&path), + "ok message must print the daemon PATH, got: {}", + item.message + ); + } + + #[test] + fn daemon_path_warns_when_required_directory_is_missing() { + let temp = TempDir::new().unwrap(); + let bin = temp.path().join("cargo-bin"); + std::fs::create_dir_all(&bin).unwrap(); + let other = temp.path().join("usr-bin"); + std::fs::create_dir_all(&other).unwrap(); + + let path = path_value(&[other.as_path()]); + let blob = environ_blob(&[&format!("PATH={path}")]); + let item = evaluate_daemon_environ(&blob, std::slice::from_ref(&bin)); + + assert_eq!(item.severity, Severity::Warn, "message: {}", item.message); + assert!( + item.message.contains(&bin.display().to_string()), + "warn message must name the missing directory, got: {}", + item.message + ); + assert!( + item.message.contains("Environment=\"PATH="), + "warn message must carry the systemd fix, got: {}", + item.message + ); + assert!( + item.message.contains("prx service install"), + "warn message must carry the re-install fix, got: {}", + item.message + ); + } + + #[test] + fn daemon_path_warns_when_environ_has_no_path_key() { + let blob = environ_blob(&["HOME=/home/ck", "LANG=C"]); + let item = evaluate_daemon_environ(&blob, &[PathBuf::from("/home/ck/.cargo/bin")]); + + assert_eq!(item.severity, Severity::Warn, "message: {}", item.message); + assert!( + item.message.contains("no PATH entry"), + "warn message must explain the missing PATH key, got: {}", + item.message + ); + assert!( + item.message.contains("Environment="), + "warn message must carry the systemd fix, got: {}", + item.message + ); + } + + /// `prx doctor` is very often run from a build tree (`cargo run -- doctor`, + /// `./target/release/prx doctor`, a one-shot CI copy). Requiring the + /// doctor's own directory there produced a warning about a healthy daemon + /// *and* told the operator to put a build directory on the unit's PATH. + /// + /// MUTATION GUARD: drop the `is_cargo_build_dir` filter and this fails, + /// because the test binary itself lives in `target/debug/deps`. + #[test] + fn a_doctor_running_from_a_build_directory_never_demands_it_on_the_daemon_path() { + let required = required_daemon_path_dirs(None); + assert!( + required.iter().all(|dir| !is_cargo_build_dir(dir)), + "a build output directory must never be proposed for a systemd unit: {required:?}" + ); + let item = evaluate_daemon_path("/usr/local/bin:/usr/bin:/bin", &required); + assert!( + !item.message.contains("target/debug"), + "the repair text must not name a build directory: {}", + item.message + ); + } + + /// The directory that actually matters is the daemon's, and the daemon + /// records it. When it does, the doctor's own location is irrelevant. + #[test] + fn the_required_directory_comes_from_the_daemon_binary_the_state_file_records() { + let required = required_daemon_path_dirs(Some(Path::new("/usr/local/bin/prx"))); + assert!( + required.contains(&canonical_or_owned(Path::new("/usr/local/bin"))), + "the daemon's own directory must be required: {required:?}" + ); + assert!( + required.iter().all(|dir| !is_cargo_build_dir(dir)), + "a recorded daemon binary replaces the doctor's own directory: {required:?}" + ); + + let complete = required + .iter() + .map(|dir| dir.display().to_string()) + .collect::>() + .join(":"); + let item = evaluate_daemon_path(&complete, &required); + assert_eq!( + item.severity, + Severity::Ok, + "a PATH that holds every required directory is healthy: {}", + item.message + ); + + let item = evaluate_daemon_path("/usr/bin:/bin", &required); + assert_eq!(item.severity, Severity::Warn); + assert!( + item.message.contains("/usr/local/bin"), + "a PATH without the daemon's own directory must name it: {}", + item.message + ); + } + + #[test] + fn the_daemon_binary_is_read_back_from_the_state_file_when_it_is_recorded() { + let temp = TempDir::new().unwrap(); + let mut config = Config::default(); + config.config_path = temp.path().join("config.toml"); + assert_eq!(daemon_binary_from_state(&config), None, "no state file, no answer"); + + std::fs::write( + temp.path().join("daemon_state.json"), + br#"{"pid":1,"binary_path":"/usr/local/bin/prx"}"#, + ) + .unwrap(); + assert_eq!( + daemon_binary_from_state(&config), + Some(PathBuf::from("/usr/local/bin/prx")) + ); + + std::fs::write( + temp.path().join("daemon_state.json"), + br#"{"pid":1,"binary_path":" "}"#, + ) + .unwrap(); + assert_eq!(daemon_binary_from_state(&config), None, "a blank field is not a path"); + } diff --git a/src/doctor/tests/section_2.rs b/src/doctor/tests/section_2.rs new file mode 100644 index 000000000..6cacadf55 --- /dev/null +++ b/src/doctor/tests/section_2.rs @@ -0,0 +1,217 @@ + #[test] + fn cargo_build_directories_are_recognized_and_ordinary_bin_directories_are_not() { + let temp = TempDir::new().unwrap(); + for layout in [ + "target/debug", + "target/debug/deps", + "target/release", + "target/x86_64-unknown-linux-gnu/release", + "prx-qa-output/debug", + "prx-qa-output/debug/deps", + "custom-output/aarch64-unknown-linux-gnu/release", + ] { + let build = temp.path().join(layout); + std::fs::create_dir_all(build.join(".fingerprint")).unwrap(); + let build = build.to_str().unwrap(); + assert!( + is_cargo_build_dir(Path::new(build)), + "must be a build directory: {build}" + ); + } + for deployed in ["/usr/local/bin", "/home/ck/.cargo/bin", "/opt/prx/target", "/srv/debug"] { + assert!( + !is_cargo_build_dir(Path::new(deployed)), + "must not be mistaken for a build directory: {deployed}" + ); + } + } + + /// A pid outlives the daemon that wrote it. Reading the environment of + /// whatever process inherited the number judges the daemon PATH from a + /// stranger's environment. + #[test] + fn only_a_process_that_is_prx_is_treated_as_the_daemon() { + assert!(process_identity_looks_like_prx( + Some(Path::new("/usr/local/bin/prx")), + b"" + )); + assert!(process_identity_looks_like_prx( + Some(Path::new("/usr/local/bin/prx-node")), + b"" + )); + assert!(process_identity_looks_like_prx( + None, + b"/usr/local/bin/prx\x00daemon\x00" + )); + assert!(!process_identity_looks_like_prx(Some(Path::new("/usr/bin/sleep")), b"")); + assert!(!process_identity_looks_like_prx(None, b"/usr/bin/sleep\x00600\x00")); + assert!( + !process_identity_looks_like_prx(Some(Path::new("/opt/worker/code/prx/target/debug/other")), b""), + "a checkout directory called prx is not a prx process" + ); + assert!(!process_identity_looks_like_prx(None, b""), "no evidence is not a yes"); + } + + #[test] + fn daemon_path_check_skips_when_state_has_no_pid() { + let temp = TempDir::new().unwrap(); + let mut config = Config::default(); + config.config_path = temp.path().join("config.toml"); + std::fs::write( + temp.path().join("daemon_state.json"), + br#"{"updated_at":"2026-09-17T00:00:00Z","components":{}}"#, + ) + .unwrap(); + + let mut items = Vec::new(); + check_daemon_process_path(&config, &mut items); + + assert_eq!(items.len(), 1); + let item = &items[0]; + assert_eq!(item.severity, Severity::Ok, "skip must not be an error or warning"); + assert_eq!(item.state, DiagnosticState::Unknown); + assert!( + item.message.contains("no pid"), + "skip message must explain why, got: {}", + item.message + ); + } + + #[test] + fn daemon_path_check_skips_when_state_file_is_absent() { + let temp = TempDir::new().unwrap(); + let mut config = Config::default(); + config.config_path = temp.path().join("config.toml"); + + let mut items = Vec::new(); + check_daemon_process_path(&config, &mut items); + + assert_eq!(items.len(), 1); + assert_eq!(items[0].severity, Severity::Ok); + assert_eq!(items[0].state, DiagnosticState::Unknown); + } + + #[cfg(target_os = "linux")] + #[test] + fn daemon_path_check_skips_for_a_pid_that_does_not_exist() { + let temp = TempDir::new().unwrap(); + let mut config = Config::default(); + config.config_path = temp.path().join("config.toml"); + // PID above the kernel maximum can never be live. + std::fs::write( + temp.path().join("daemon_state.json"), + br#"{"pid":4294967000,"updated_at":"2026-09-17T00:00:00Z"}"#, + ) + .unwrap(); + + let mut items = Vec::new(); + check_daemon_process_path(&config, &mut items); + + assert_eq!(items.len(), 1); + assert_eq!(items[0].severity, Severity::Ok, "message: {}", items[0].message); + assert!( + items[0].message.contains("environ"), + "skip message must name the unreadable source, got: {}", + items[0].message + ); + } + + /// USERINFO-2: `prx doctor` prints every configured provider label. Each + /// may be a `custom:` URL carrying `user:password@`. + #[test] + fn doctor_names_every_provider_without_url_userinfo() { + let tmp = tempfile::TempDir::new().unwrap(); + let label = |port: u16| format!("custom:http://u:SECRET-fixture-pw@127.0.0.1:{port}/v1"); + let mut config = Config { + workspace_dir: tmp.path().join("workspace"), + config_path: tmp.path().join("config.toml"), + default_provider: Some(label(1)), + ..Config::default() + }; + // An unparseable fallback and route make doctor print "invalid" lines too. + config.reliability.fallback_providers = + vec![label(2), "custom:http://u:SECRET-fixture-pw@127.0.0.1:99999/v1".into()]; + config.model_routes = vec![crate::config::ModelRouteConfig { + settings: Default::default(), + hint: "fast".into(), + provider: "custom:http://u:SECRET-fixture-pw@127.0.0.1:99998/v1".into(), + model: "m".into(), + api_key: None, + credential_ref: None, + }]; + let report = diagnose(&config); + let rendered = report + .items + .iter() + .map(|item| item.message.as_str()) + .collect::>() + .join("\n"); + assert!( + rendered.contains("[redacted]@127.0.0.1"), + "doctor no longer names the endpoints: {rendered}" + ); + assert!( + !rendered.contains("SECRET-fixture-pw"), + "doctor printed URL userinfo: {rendered}" + ); + } + + /// R-C2BUg G-1: doctor messages that start with a URL keep none of their + /// credentials. + #[test] + fn doctor_messages_redact_every_url_in_url_first_text() { + crate::providers::label_redaction_tests::assert_every_url_redacted("doctor", &|text| { + DiagItem::warn("fixture", text).message + }); + } + + /// D-063, RED before: the gateway probe resolved `(host, port)`, and a + /// bracketed IPv6 `gateway.host = "[::1]"` (the spelling a URL uses) did + /// not resolve, so doctor reported "cannot resolve gateway bind address". + /// After: the brackets are removed before resolution. + #[test] + fn the_gateway_probe_resolves_a_bracketed_ipv6_host() { + for host in ["[::1]", "::1", "127.0.0.1"] { + let mut config = Config::default(); + config.gateway.host = host.to_string(); + config.gateway.port = 9; + let mut items = Vec::new(); + check_gateway_runtime(&config, &mut items); + let messages: Vec<&str> = items.iter().map(|item| item.message.as_str()).collect(); + assert!( + !messages.iter().any(|message| message.contains("cannot resolve")), + "{host}: {messages:?}" + ); + } + } + + /// RED before PMMDtail-j (D-084 E-3): `prx doctor`'s auth-profile check + /// loaded through the migrating load, rewriting auth-profiles.json. + #[test] + fn doctor_never_rewrites_the_profiles_file() { + let tmp = TempDir::new().expect("test: temp dir"); + let path = crate::auth::profiles::write_legacy_token_profile(tmp.path(), "moonshot", "sentinel-moonshot"); + let before = std::fs::read_to_string(&path).expect("test: read"); + let mut config = Config::default(); + config.config_path = tmp.path().join("config.toml"); + config.secrets.encrypt = true; + + let status = active_auth_profile_credential_status(&config, "moonshot"); + + assert!( + matches!(status, AuthProfileCredentialStatus::Present { .. }), + "{status:?}" + ); + assert_eq!( + std::fs::read_to_string(&path).expect("test: read"), + before, + "the file was rewritten" + ); + } + /// Mutation: remove secret scanning in DiagItem::with_state. + #[test] + fn diagnostic_items_hide_nested_error_credentials() { + let error = anyhow::anyhow!("token=opaque7credential").context("failed"); + let item = DiagItem::error("runtime", format!("{error:#}")); + assert_eq!(item.message, "failed: token=[REDACTED]"); + } diff --git a/src/gateway/api/chat_sessions.rs b/src/gateway/api/chat_sessions.rs index 8c312dec1..e5a90d527 100644 --- a/src/gateway/api/chat_sessions.rs +++ b/src/gateway/api/chat_sessions.rs @@ -328,6 +328,8 @@ pub async fn post_assign( #[derive(Deserialize, Default)] pub(super) struct PullRequest { + #[serde(default)] + message_target: Option, /// Assignment ids from the previous response that the caller now holds. #[serde(default)] ack: Vec, @@ -353,6 +355,7 @@ pub(super) struct PulledAssignment { #[derive(Serialize)] pub(super) struct PullResponse { + messages: Vec, assignments: Vec, acked: usize, requeued: usize, @@ -372,12 +375,38 @@ pub async fn post_pull( authorize_resource_mutation(&state, "chat_session_pull", ResourceRiskLevel::Low)?; let request = body.map(|Json(request)| request).unwrap_or_default(); let token = session_token(&headers); + let target = request.message_target.clone(); let pulled = offload("chat_session_pull", move || { chat_sessions::pull(&id, &token, &request.ack, request.max) }) .await? .map_err(|error| into_refusal(&error))?; + let messages = if let Some(target) = target { + let config = state.config.load_full(); + let runtime = crate::messaging::runtime::MessagingRuntime::for_config(&config) + .map_err(|_| refusal(StatusCode::SERVICE_UNAVAILABLE, "mailbox unavailable"))?; + let owner = crate::chat::chat_runtime_envelope(&config.workspace_dir.to_string_lossy(), &target.session) + .resolved_owner_id(); + if target.owner != owner { + return Err(refusal(StatusCode::FORBIDDEN, "peer_not_allowed")); + } + let scope = runtime + .resolve_scope(&target) + .map_err(|_| refusal(StatusCode::FORBIDDEN, "peer_not_allowed"))?; + if runtime + .store + .has_pending(&scope, &target) + .map_err(|_| refusal(StatusCode::SERVICE_UNAVAILABLE, "mailbox unavailable"))? + { + vec![serde_json::json!({"kind":"message"})] + } else { + Vec::new() + } + } else { + Vec::new() + }; Ok(Json(PullResponse { + messages, assignments: pulled .assignments .into_iter() diff --git a/src/gateway/api/sessions.rs b/src/gateway/api/sessions.rs index 709acef4c..51bcb5226 100644 --- a/src/gateway/api/sessions.rs +++ b/src/gateway/api/sessions.rs @@ -1,4489 +1,9 @@ -use super::{AppState, extract_resource_auth_token}; -use crate::agent::document_ingest::DocumentIngestRuntime; -use crate::agent::runtime_prompt::build_runtime_system_prompt; -use crate::agent::turn_contracts::ScopeContext; -use crate::agent::turn_engine::run_turn; -use crate::gateway::jobs; -use crate::memory::MemoryFabric; -use crate::observability::NoopObserver; -use crate::providers::ChatMessage; -use crate::runtime::envelope::RuntimeEnvelope; -use crate::security::policy::ResourceRiskLevel; -use axum::{ - Json, - body::Body, - extract::{FromRequest, Multipart, Path, Query, Request, State}, - http::{HeaderMap, HeaderValue, StatusCode, header}, - response::{IntoResponse, Response}, -}; -use chrono::Utc; -use serde::{Deserialize, Serialize}; -use std::path::{Path as StdPath, PathBuf}; -use tokio::fs; - -const DEFAULT_PAGE_LIMIT: usize = 50; -const MAX_PAGE_LIMIT: usize = 500; -const MAX_UPLOAD_FILES: usize = 10; -const MAX_UPLOAD_FILE_SIZE_BYTES: usize = 20 * 1024 * 1024; -const UPLOADS_DIR_NAME: &str = "uploads"; - +mod mailbox; mod rf_delete; -pub(super) use rf_delete::{post_batch_delete, post_message_delete, post_reply_delete}; mod rf_message; -pub(super) use rf_message::{create_route_auth, message_route_auth}; mod rf_replay; -pub(super) use rf_replay::{post_run_cancel, rf_job_cancel}; mod target; -pub(super) use target::TARGET_EXCLUDED_TOOLS; -use target::{ - AgentField, SelectedTurn, TargetError, TargetUnavailable, TargetedTurn, TurnTarget, prepare_target, - resolve_incarnation, resolve_target, -}; - -#[derive(Serialize)] -pub(super) struct SessionSummary { - #[serde(skip_serializing_if = "Option::is_none")] - metadata: Option, - session_id: String, - sender: String, - channel: String, - status: String, - created_at: String, - updated_at: String, - message_count: u64, - last_message_preview: String, -} - -#[derive(Serialize)] -pub(super) struct SessionMessage { - role: String, - content: String, - timestamp: String, - message_id: Option, - /// The agent the row belongs to (`main` or a name), on a caller-keyed - /// session only; a Console session's body keeps its previous shape. - #[serde(skip_serializing_if = "Option::is_none")] - agent: Option, -} - -#[derive(Deserialize)] -pub(super) struct SessionsQuery { - limit: Option, - offset: Option, - channel: Option, - status: Option, - search: Option, -} - -#[derive(Deserialize)] -pub(super) struct SessionMessagesQuery { - limit: Option, - offset: Option, - /// On a caller-keyed session: only the rows of this agent (`main` or a - /// configured name). - agent: Option, -} - -#[derive(Debug, Deserialize)] -pub(super) struct ApprovalInboxQuery { - limit: Option, - cursor: Option, -} - -#[derive(Deserialize)] -pub(super) struct SendMessageRequest { - message: String, - /// Present-or-absent is kept apart from `null`: an omitted field is Main, - /// an explicit `null` is refused. - #[serde(default, deserialize_with = "present_value")] - agent: Option, -} - -fn present_value<'de, D>(deserializer: D) -> Result, D::Error> -where - D: serde::Deserializer<'de>, -{ - serde_json::Value::deserialize(deserializer).map(Some) -} - -/// The files one multipart request creates. They are removed when the guard -/// drops (a parse error, a refused target, a failed admission, a cancelled -/// request) unless [`UploadGuard::release`] handed them over. -/// -/// Ownership precedes creation: a path is registered with [`UploadGuard::begin`] -/// before the file exists. Every path carries a per-request uuid, so it can only -/// ever name a file this request creates. Creation runs in a blocking worker that -/// outlives a cancelled future, so the guard also publishes an `abandoned` flag -/// that the worker checks right after creating the file: whichever of the -/// worker's create and the guard's drop comes last removes the file. -#[derive(Default)] -struct UploadGuard { - paths: Vec, - abandoned: std::sync::Arc, - released: bool, -} - -impl UploadGuard { - /// Register `path` for cleanup before it is created, and return the flag - /// the creating worker must hand to [`create_upload_file`]. - fn begin(&mut self, path: PathBuf) -> std::sync::Arc { - self.paths.push(path); - std::sync::Arc::clone(&self.abandoned) - } - - /// Settle the outcome of creating `path`. A failed create (including - /// `AlreadyExists`) means this request did not create the file, so the path - /// is unregistered and the guard can never unlink a file it does not own. - fn settle(&mut self, path: &StdPath, created: std::io::Result) -> std::io::Result { - if created.is_err() { - self.paths.retain(|registered| registered != path); - } - created - } - - /// The request was admitted: the files now belong to the turn. - fn release(mut self) { - self.released = true; - self.paths.clear(); - } -} - -impl Drop for UploadGuard { - fn drop(&mut self) { - if self.released { - return; - } - // Publish the abandonment before removing, so a worker that creates its - // file after the removal below sees the flag and removes it itself. - self.abandoned.store(true, std::sync::atomic::Ordering::SeqCst); - for path in self.paths.drain(..) { - match std::fs::remove_file(&path) { - Ok(()) => {} - // Never created, or already removed by its worker. - Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} - Err(error) => { - tracing::warn!(error = %error, "Failed to remove an upload of an unadmitted request"); - } - } - } - } -} - -/// Exclusively create an upload file. If the owning guard was abandoned -/// meanwhile (the request was cancelled while this worker was running), the -/// file is removed again instead of being orphaned. -fn create_upload_file(path: &StdPath, abandoned: &std::sync::atomic::AtomicBool) -> std::io::Result { - let file = std::fs::OpenOptions::new().write(true).create_new(true).open(path)?; - if abandoned.load(std::sync::atomic::Ordering::SeqCst) { - if let Err(error) = std::fs::remove_file(path) - && error.kind() != std::io::ErrorKind::NotFound - { - tracing::warn!(error = %error, "Failed to remove an upload of an abandoned request"); - } - return Err(std::io::Error::new( - std::io::ErrorKind::Interrupted, - "upload request was abandoned", - )); - } - Ok(file) -} - -/// A parsed message request. `uploads` are the files already stored for a -/// multipart request; they are removed again unless the request is admitted. -struct ParsedMessage { - message: String, - agent: AgentField, - uploads: UploadGuard, -} - -#[derive(Deserialize)] -pub(super) struct SessionMediaQuery { - path: String, -} - -#[derive(Serialize)] -pub(super) struct SendMessageResponse { - status: String, - reply: String, -} - -fn matches_session_filters( - session: &crate::memory::ConversationSessionSummary, - status_filter: Option<&str>, - search_filter: Option<&str>, -) -> bool { - let status = derive_session_status(&session.last_message_preview, session.message_count); - if let Some(filter) = status_filter { - if filter != status { - return false; - } - } - - if let Some(filter) = search_filter { - let haystack = format!( - "{}\n{}\n{}\n{}", - session.session_key, session.sender, session.channel, session.last_message_preview - ) - .to_ascii_lowercase(); - if !haystack.contains(filter) { - return false; - } - } - - true -} - -fn derive_session_status(last_message_preview: &str, message_count: u64) -> &'static str { - if message_count == 0 { - "empty" - } else if last_message_preview.trim().is_empty() { - "pending" - } else { - "active" - } -} - -fn normalize_limit(limit: Option) -> usize { - match limit { - Some(0) | None => DEFAULT_PAGE_LIMIT, - Some(value) => value.min(MAX_PAGE_LIMIT), - } -} - -fn normalize_offset(offset: Option) -> usize { - offset.unwrap_or(0) -} - -/// Content-free category of a Console request failure, safe to log. -/// -/// The error chain itself is never logged: a storage or decode error can quote -/// stored input. Only these static names leave this function. -fn console_error_kind(error: &anyhow::Error) -> &'static str { - if error.is::() - || error.is::() - { - return "conflict"; - } - if error.is::() { - return "unauthorized"; - } - for cause in error.chain() { - if cause.is::() { - return "decode"; - } - if cause.is::() || cause.is::() { - return "storage"; - } - if cause.is::() { - return "io"; - } - if cause.is::() { - return "timeout"; - } - } - "other" -} - -/// Logs a cleanup-owner refusal, at most once per throttle interval per owner. -/// -/// A failed owner refuses every request until recovery, so an unthrottled -/// warning would follow the request rate. Only a static category and the static -/// route name are logged. -fn warn_cleanup_refused( - owner: &crate::runtime::turn_cleanup::CleanupTracker, - route: &'static str, - error: &anyhow::Error, -) { - if owner.refusal_log_due() { - tracing::warn!( - error_kind = console_error_kind(error), - route, - "Console request refused by its runtime cleanup owner; repeats are logged at most once per minute" - ); - } -} - -fn json_error(status: StatusCode, message: &str) -> Response { - (status, Json(serde_json::json!({ "error": message }))).into_response() -} - -fn console_runtime_envelope(state: &AppState, session_id: &str, channel: &str, sender: &str) -> RuntimeEnvelope { - let generation = state.config.pin(); - let workspace_id = generation.effective.workspace_dir.to_string_lossy().to_string(); - console_runtime_envelope_for_workspace(workspace_id, session_id, channel, sender) - .with_config_generation(&generation) -} - -/// Build the console runtime envelope for a session. -/// -/// D4 C5 — console keeps its external session_id on the legacy basis. The console -/// `session_id` is a user-visible, external contract value: it is the path -/// parameter (`GET/POST /sessions/{session_id}/...`) and the id returned by the -/// session list. Unlike the gateway *fabric* path (C4), the console durable -/// `session_key` is therefore deliberately NOT canonicalized — doing so would -/// change the path/list id and break the frontend. The envelope passes the raw -/// `session_id` straight through as the durable key (no recipient component) and -/// carries no `legacy_session_key`, so console persistence and recall stay on the -/// single external id. Internal recall could read-merge in the future by setting -/// a legacy key on the principal, but the external id format never changes. -fn console_runtime_envelope_for_workspace( - workspace_id: impl Into, - session_id: &str, - channel: &str, - sender: &str, -) -> RuntimeEnvelope { - RuntimeEnvelope::console(workspace_id, session_id.to_string()) - .with_channel(channel.to_string()) - .with_sender(sender.to_string()) -} - -/// D-037 grants authenticated API tokens full operator access to the selected -/// transcript. This read principal never enters the turn envelope or tool scope. -fn operator_history_principal( - _authenticated: &super::ApiPrincipal, - envelope: &RuntimeEnvelope, -) -> crate::memory::MemoryPrincipal { - let mut principal = envelope.memory_principal(); - principal.owner_id = Some("system:*".to_owned()); - principal.agent_id = Some("system".to_owned()); - principal.require_owner_match = false; - principal -} - -fn history_partition( - envelope: &RuntimeEnvelope, - owner_id: &str, - targeted: Option<&TargetedTurn>, - incarnation: Option<&str>, -) -> Result> { - let key = match targeted { - None => crate::memory::PartitionKey::Main, - Some(turn) => { - let Some(raw) = incarnation else { - return Err(Box::new(json_error( - StatusCode::INTERNAL_SERVER_ERROR, - "Targeted agent incarnation is missing", - ))); - }; - let incarnation = uuid::Uuid::parse_str(raw).map_err(|_| { - // The parse error can quote a character of the stored value, so - // only a static category and the validated agent name are logged. - tracing::warn!( - error_kind = "invalid_uuid", - agent = turn.name.as_str(), - "Targeted agent incarnation is not a valid UUID" - ); - Box::new(json_error( - StatusCode::INTERNAL_SERVER_ERROR, - "Targeted agent incarnation is invalid", - )) - })?; - crate::memory::PartitionKey::Named { - name: turn.name.clone(), - incarnation, - } - } - }; - Ok(crate::memory::AgentPartition { - workspace_id: envelope.workspace_id.clone(), - owner_id: owner_id.to_owned(), - key, - }) -} - -/// OV-13: console turns are recorded, recovered and approved run-keyed only -/// with event recording on and a recovery repository present. -fn console_recordable(config: &crate::config::Config, memory: &dyn crate::memory::Memory) -> bool { - let recording = config.memory.event_recording_config(); - recording.enabled && recording.record_user_messages && memory.recovery_repository().is_some() -} - -/// Run-keyed approvals need recording on and a recovery repository (OV-13). -/// Recording turned off is the operator's choice (409, disabled); a memory -/// backend that keeps no repository fails closed (503), never "disabled". -fn approvals_unavailable(config: &crate::config::Config, memory: &dyn crate::memory::Memory) -> Option { - let recording = config.memory.event_recording_config(); - if !(recording.enabled && recording.record_user_messages) { - return Some(json_error(StatusCode::CONFLICT, "Decision approvals are disabled")); - } - if memory.recovery_repository().is_none() { - return Some(json_error( - StatusCode::SERVICE_UNAVAILABLE, - "Decision approvals are unavailable: the memory backend keeps no recovery repository", - )); - } - None -} - -async fn recover_console_history( - state: &AppState, - runtime: &crate::gateway::TurnRuntimeGeneration, - _authenticated: &super::ApiPrincipal, - session_key: &str, -) -> anyhow::Result<()> { - if !console_recordable(&runtime.config_generation.effective, state.mem.as_ref()) { - return Ok(()); - } - let workspace = runtime.config_generation.effective.workspace_dir.to_string_lossy(); - let cancellation = tokio_util::sync::CancellationToken::new(); - let mut cleanup = None; - let recovery = async { - let mut cursor = 0; - loop { - anyhow::ensure!( - !cancellation.is_cancelled(), - "Console recovery cancelled during shutdown" - ); - let events = state - .mem - .list_console_terminal_events(&workspace, session_key, cursor, 128) - .await?; - if events.is_empty() { - break; - } - for event in events { - anyhow::ensure!( - event.id > cursor - && event.workspace_id == workspace - && event.session_key.as_deref() == Some(session_key) - && event.source == crate::memory::MessageEventSource::Console - && event.event_type == "turn.finalized", - "Console recovery returned an invalid marker" - ); - cursor = event.id; - let payload: serde_json::Value = serde_json::from_str( - event - .raw_payload_json - .as_deref() - .ok_or_else(|| anyhow::anyhow!("Console terminal payload missing"))?, - )?; - if payload.get("decision_id").is_none_or(serde_json::Value::is_null) { - // A stripped marker must not masquerade as a legacy turn - // when a durable decision claim still identifies the run. - let claim = if let Some(run) = event.run_id.as_deref() { - state - .mem - .find_message_event_by_idempotency_key(&workspace, &format!("turn:{run}:decision-claim")) - .await? - } else { - None - }; - if claim.is_none() { - continue; - } - } - if cleanup.is_none() { - cleanup = Some(runtime.publication_slot.cleanup.register(cancellation.clone())?); - } - let terminal_id = event - .run_id - .as_deref() - .filter(|id| !id.is_empty()) - .ok_or_else(|| anyhow::anyhow!("Console terminal run missing"))?; - anyhow::ensure!( - event.idempotency_key.as_deref() == Some(format!("turn:{terminal_id}:final").as_str()), - "Console recovery marker identity changed" - ); - let owner = event - .owner_id - .as_deref() - .filter(|id| !id.is_empty()) - .ok_or_else(|| anyhow::anyhow!("Console terminal owner missing"))?; - let service = runtime.publication_slot.publish(runtime, state).await?; - service - .runtime_holder() - .recovery_scope() - .rejoin_terminal(terminal_id, owner) - .await - .map_err(|error| { - if error - .downcast_ref::() - .is_some() - { - error.context(ConsoleTerminalRefused { - run_id: terminal_id.to_owned(), - }) - } else { - error - } - })?; - } - } - Ok::<(), anyhow::Error>(()) - }; - let outcome = tokio::time::timeout(std::time::Duration::from_secs(30), recovery) - .await - .map_err(|_| anyhow::anyhow!("Console history recovery timed out; retry required")) - .and_then(|result| result); - match outcome { - Ok(()) => { - if let Some(ticket) = cleanup { - ticket.finish(true); - } - Ok(()) - } - Err(error) => { - if let Some(refused) = error.downcast_ref::() { - // Restart verification refuses before any write, so no write of - // this recovery is unconfirmed: the ticket ends confirmed and - // the refusal stays with its session. Store faults, timeouts - // and projection-write failures keep the unfinished ticket, - // which closes the owner until recovery (turn_cleanup). - let reason = error - .downcast_ref::() - .map_or("unspecified", |refusal| refusal.0); - tracing::error!( - run_id = %refused.run_id, - reason, - "Console terminal is not replayable; the refusal is isolated to its session" - ); - if let Some(ticket) = cleanup { - ticket.finish(true); - } - } - Err(error) - } - } -} - -/// A Console terminal that restart verification refused -/// (`TerminalNotReplayable`) during history recovery: an error of that -/// session only, already logged with its run id; admission stays open. -#[derive(Debug)] -struct ConsoleTerminalRefused { - run_id: String, -} - -impl std::fmt::Display for ConsoleTerminalRefused { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(formatter, "Console terminal {} is not replayable", self.run_id) - } -} - -/// The response of a failed history recovery. A session-isolated refusal was -/// logged where it was classified; every other failure is logged here. -fn history_recovery_failed(error: &anyhow::Error) -> Response { - if error.downcast_ref::().is_none() { - tracing::error!(error = %error, "Console history recovery failed"); - } - json_error( - StatusCode::INTERNAL_SERVER_ERROR, - "Console history recovery is incomplete", - ) -} - -async fn append_console_turn( - state: &AppState, - envelope: &RuntimeEnvelope, - role: &str, - content: &str, - record_message_event: bool, - durable_projection: bool, -) -> anyhow::Result { - append_console_turn_with( - state, - envelope, - role, - content, - record_message_event, - durable_projection, - None, - ) - .await -} - -/// An rf `context` input: its user event and its attempt row commit in one -/// transaction (AC-1b2a), then it is projected like any recorded input. -async fn append_admitted_console_turn( - state: &AppState, - envelope: &RuntimeEnvelope, - content: &str, - durable_projection: bool, - admission: crate::memory::RfAdmission, -) -> anyhow::Result { - append_console_turn_with( - state, - envelope, - "user", - content, - true, - durable_projection, - Some(admission), - ) - .await -} - -async fn append_console_turn_with( - state: &AppState, - envelope: &RuntimeEnvelope, - role: &str, - content: &str, - record_message_event: bool, - durable_projection: bool, - admission: Option, -) -> anyhow::Result { - // The console persists its reply twice, as a message event and as the - // transcript turn: both are redacted like the terminal commit (D-053). - let content: std::borrow::Cow<'_, str> = if role == "assistant" { - std::borrow::Cow::Owned(crate::agent::terminal::redact_persisted_text(content)) - } else { - std::borrow::Cow::Borrowed(content) - }; - let event = if record_message_event { - let fabric = MemoryFabric::new(state.mem.clone(), envelope.workspace_id.clone()); - Some(match admission { - _ if role == "assistant" => { - fabric - .record_assistant_message(envelope.message_scope(), &*content) - .await? - } - Some(admission) => { - fabric - .record_admitted_user_message(envelope.message_scope(), &*content, None, admission) - .await? - } - None => { - fabric - .record_inbound_user_message(envelope.message_scope(), &*content, None, None) - .await? - } - }) - } else { - None - }; - if matches!( - envelope.agent_partition.as_ref().map(|partition| &partition.key), - Some(crate::memory::PartitionKey::Named { .. }) - ) && event.is_none() - { - return Err(crate::memory::AgentScopeRefused.into()); - } - if durable_projection { - let event = event - .as_ref() - .ok_or_else(|| anyhow::anyhow!("Console projection requires a recorded event"))?; - state.mem.project_console_message(event).await?; - return Ok(event.event_id.clone()); - } - let owner_id = envelope.resolved_owner_id(); - - state - .mem - .append_conversation_turn( - &envelope.session_key, - envelope.channel.as_deref().unwrap_or("console"), - envelope.sender.as_deref().unwrap_or("console-user"), - role, - &content, - None, - event.as_ref().map(|event| event.event_id.as_str()), - Some(owner_id.as_str()), - envelope.agent_partition.as_ref(), - ) - .await?; - - Ok(event.map_or_else(String::new, |event| event.event_id)) -} - -struct ConsoleTurnResult { - reply: String, - awaiting_approval: bool, - trace: crate::agent::turn_contracts::ToolLoopTrace, - route_decision: crate::llm::route_decision::RouteDecision, - provider_started_at: chrono::DateTime, - history_commit_len: usize, - envelope: RuntimeEnvelope, -} - -struct ConsoleDecisionTurn<'a> { - service: std::sync::Arc, - context: std::sync::Arc, - advice: Option, - proof: &'a crate::gateway::turn_source::GatewayTurnProof, - cancellation: tokio_util::sync::CancellationToken, - provider_trace: Option<( - std::sync::Arc, - std::sync::Arc, - )>, -} - -fn console_route_decision( - runtime: &crate::gateway::TurnRuntimeGeneration, - envelope: &RuntimeEnvelope, - message: &str, -) -> anyhow::Result { - let provider = runtime - .provider_binding - .as_ref() - .ok_or_else(|| anyhow::anyhow!("Console provider binding missing"))?; - Ok(crate::llm::route_decision::RouteDecision::single_candidate_for_context( - provider.provider_name().to_string(), - runtime.model.clone(), - envelope.resolved_owner_id(), - envelope.session_key.clone(), - envelope.source_message_event_id.clone(), - None, - "console_message", - u32::try_from(message.chars().count() / 4).unwrap_or(u32::MAX), - !runtime.tools_registry.is_empty(), - false, - )) -} - -async fn run_console_runtime_turn( - turn_runtime: std::sync::Arc, - state: &AppState, - visible_message: &str, - previous_turns: Vec, - decision: &ConsoleDecisionTurn<'_>, - target: Option<&TargetedTurn>, -) -> anyhow::Result { - decision.proof.verify_runtime_input(&turn_runtime, visible_message)?; - let turn_envelope = decision.proof.envelope().clone(); - // D2: this runtime turn rebuilds a `SecurityPolicy` (below) that gates tool - // side-effects for the turn, so the config snapshot it derives from MUST be the - // pinned TurnRuntimeGeneration, not an independently cached config owner. This - // makes a reloaded autonomy / security.audit take effect for console-driven - // turns without a restart; all non-security fields used for the prompt come from - // the same snapshot, so the turn stays internally consistent. - let mut config_snapshot = (*turn_runtime.config_generation.effective).clone(); - if let Some(target) = target { - // The target's own level (`agent_level`); the same level the target's - // decision slot publishes its tool policy with. - config_snapshot.autonomy.level = target.autonomy; - } - let live_scope = - if let (Some(store), Some(source)) = (state.mem.sync_store(), turn_envelope.source_message_event_id.clone()) { - let owner = turn_envelope.resolved_owner_id(); - crate::runtime::blocking::spawn_blocking(move || store.live_scope(&owner, &source)).await?? - } else { - None - }; - let live = live_scope.map(|scope| { - let wait_secs = target - .and_then(|target| config_snapshot.agents.get(target.name.as_str())) - .map_or(config_snapshot.agent.approval_wait_secs, |agent| { - agent.approval_wait_secs - }); - std::sync::Arc::new(crate::gateway::run_approvals::RunApprovalResolver { - scope, - streams: std::sync::Arc::clone(&state.rf_streams), - approvals: std::sync::Arc::clone(&state.rf_approvals), - cancellation: decision.cancellation.clone(), - wait_secs, - }) as std::sync::Arc - }); - let live_frames = live.as_ref().map(|live| { - live.frames( - &turn_envelope, - &crate::agent::sanitize::known_tool_names(turn_runtime.tools_registry.as_ref()), - ) - }); - let stream_provider = live.is_some() && turn_runtime.provider.supports_streaming(); - let provider_label = turn_runtime - .provider_binding - .as_ref() - .ok_or_else(|| anyhow::anyhow!("Console provider binding missing"))? - .provider_name() - .to_string(); - let native_tools = turn_runtime - .provider - .capabilities_for( - &turn_runtime.model, - if stream_provider { - crate::providers::traits::ProviderRequestMode::Streaming - } else { - crate::providers::traits::ProviderRequestMode::NonStreaming - }, - ) - .native_tool_calling; - let system_prompt = if let Some(target) = target { - // The target's own identity; never the main persona. - target.system_prompt.clone() - } else { - let selected_skills = decision - .service - .agent_prompt_skills(decision.proof, &decision.context)?; - build_runtime_system_prompt(&config_snapshot, &turn_runtime.model, &selected_skills, native_tools) - }; - - let mem_context = crate::agent::context_recall::scoped_recall( - state.mem.as_ref(), - &crate::agent::context_recall::RecallScope::from_envelope(&turn_envelope, &config_snapshot.memory, "private"), - visible_message, - crate::agent::context_recall::RECALL_CONTEXT_BUDGET, - ) - .await; - let enriched_message = if mem_context.preamble.is_empty() { - visible_message.to_string() - } else { - format!("{}{}", mem_context.preamble, visible_message) - }; - - let mut history = Vec::with_capacity(previous_turns.len() + 2); - history.push(ChatMessage::system(system_prompt)); - // stored console turns are neutralised like fresh input - history.extend( - previous_turns - .into_iter() - .map(|turn| crate::agent::turn_contracts::stored_turn_message(turn.role, turn.content)), - ); - history.push(crate::agent::turn_contracts::inbound_user_message(&enriched_message)); - - // D2 / FIX-P1-31: build via the shared `build_security_policy` helper so this - // per-turn gateway authz site cannot drift from (or forget) the audit-config - // wiring — construction is byte-for-byte identical to the former local - // `from_config(&autonomy, &workspace_dir)` + audit-config of `security.audit`. - // `config_snapshot` is already the hot SharedConfig (D) snapshot (see above), so - // a reloaded autonomy / security.audit gates this console turn without a restart. - let security = crate::runtime::bootstrap::build_security_policy(&config_snapshot); - let scope_owner_id = turn_envelope.resolved_owner_id(); - let scope_ctx = ScopeContext { - policy: security.as_ref(), - sender: turn_envelope.sender.as_deref().unwrap_or("console-user"), - channel: turn_envelope.channel.as_deref().unwrap_or("console"), - chat_type: "private", - chat_id: &turn_envelope.session_key, - session_key: Some(&turn_envelope.session_key), - owner_id: Some(&scope_owner_id), - owner_isolated: turn_envelope.owner_isolated, - topic_id: turn_envelope.topic_id.as_deref(), - task_id: turn_envelope.resolved_task_id(), - source_message_event_id: turn_envelope.source_message_event_id.as_deref(), - config_generation_id: turn_envelope.config_generation_id, - config_source_revision: turn_envelope.config_source_revision.as_deref(), - }; - let noop_observer = NoopObserver; - - let route_decision = match &decision.provider_trace { - Some((_, route)) => route.as_ref().clone(), - None => console_route_decision(&turn_runtime, &turn_envelope, visible_message)?, - }; - // OQ-23 / R5: budget on the *effective* window of the model this turn - // serves (the operator/discovery/catalog model limits and - // `reserved_output_tokens`), with the same arguments the CLI, TUI and - // webhook resolve with, so one request is trimmed the same way on every - // surface of this process. - let mut effective_compaction = decision - .service - .effective_compaction(&provider_label, &turn_runtime.model); - effective_compaction.config = decision.context.main_compaction().clone(); - crate::providers::context_window::trace_effective_compaction_resolution(&effective_compaction); - let provider_started_at = chrono::Utc::now(); - let loop_result = run_turn( - &mut history, - crate::agent::turn_request::TurnRequest { - advice: decision.advice.clone(), - channel_name: "console", - scope: Some(&scope_ctx), - mode: crate::agent::turn_contracts::ChatMode::default(), - silent: true, - expose_stay_silent: false, - multimodal: &config_snapshot.multimodal, - schedule: crate::agent::turn_request::TurnSchedule { - read_only_tool_concurrency_window: config_snapshot.agent.read_only_tool_concurrency_window, - priority_scheduling_enabled: config_snapshot.agent.priority_scheduling_enabled, - low_priority_tool_names: config_snapshot.agent.low_priority_tools.clone(), - }, - compaction: Some(&effective_compaction.config), - decision: crate::agent::turn_request::TurnDecision { - service: &decision.service, - context: &decision.context, - runtime: decision.context.runtime(), - proof: decision.proof, - }, - }, - crate::agent::turn_request::TurnServices { - provider: turn_runtime.provider.as_ref(), - provider_name: &provider_label, - model: &turn_runtime.model, - temperature: turn_runtime.temperature, - tools_registry: std::sync::Arc::clone(&turn_runtime.tools_registry), - observer: &noop_observer, - hooks: state.hooks.as_ref(), - approval: None, - approval_resolver: None, - runtime_adapter: Some(crate::agent::turn_contracts::ToolLoopRuntimeAdapter { - live_frames, - guarded_delivery: false, - provider_trace: decision - .provider_trace - .as_ref() - .map(|(trace, _)| std::sync::Arc::clone(trace)), - events: None, - stream_provider, - tool_execution_service: None, - tool_execution_context: { - let mut context = crate::tools::ToolExecutionContext::new(turn_envelope.clone(), "private") - .with_dispatch_origin(crate::tools::DispatchOrigin::ModelTurn); - context.live_turn = live - .as_ref() - .map(|live| crate::agent::live_frames::LiveTurnRef(std::sync::Arc::clone(live))); - if target.is_some() && live.is_none() { - // Until MA-04 a targeted call that needs approval ends - // denied: no durable ledger route, no pending decision. - context.with_pending_approval_denied() - } else { - context.with_approval_ledger(decision.service.execution_approval_ledger()) - } - .with_chat_id(&turn_envelope.session_key) - }, - allowed_tool_names: None, - }), - memory: crate::agent::turn_request::ToolLoopMemory::new( - &state.mem, - &config_snapshot.workspace_dir, - Some( - DocumentIngestRuntime::from_envelope(state.mem.clone(), &turn_envelope) - .with_source_message_event_id(turn_envelope.source_message_event_id.clone()), - ), - ) - .with_event_fabric( - MemoryFabric::new(state.mem.clone(), turn_envelope.workspace_id.clone()) - .with_event_recording(config_snapshot.memory.event_recording_config()), - ) - .with_request_event_scope(turn_envelope.message_scope()), - }, - crate::agent::turn_request::TurnDelivery { - cancellation: Some(decision.cancellation.clone()), - on_delta: None, - on_tool_call: None, - }, - ) - .await; - let (outcome, trace) = loop_result?; - let awaiting_approval = matches!( - &outcome, - crate::agent::turn_contracts::ToolLoopOutcome::AwaitingApproval { .. } - ); - let reply = outcome.into_text(); - anyhow::ensure!( - trace.execution_trace.as_ref() == Some(&decision.context.terminal_execution_trace()), - "console execution trace differs from owning decision" - ); - Ok(ConsoleTurnResult { - reply, - awaiting_approval, - trace, - route_decision, - provider_started_at, - history_commit_len: history.len(), - envelope: turn_envelope, - }) -} - -fn sanitize_upload_filename(raw_name: &str) -> String { - let file_name = StdPath::new(raw_name) - .file_name() - .and_then(|value| value.to_str()) - .unwrap_or("upload.bin"); - - let mut sanitized = file_name - .chars() - .map(|ch| { - if ch.is_ascii_alphanumeric() || ch == '.' || ch == '-' || ch == '_' { - ch - } else { - '_' - } - }) - .collect::(); - - if sanitized.is_empty() { - sanitized.push_str("upload.bin"); - } - if sanitized.len() > 120 { - sanitized.truncate(120); - } - - sanitized -} - -fn has_extension(file_name: &str, candidates: &[&str]) -> bool { - let lower = file_name.to_ascii_lowercase(); - candidates - .iter() - .any(|candidate| lower.ends_with(candidate.trim_start_matches('*'))) -} - -fn is_image_upload(content_type: &str, file_name: &str) -> bool { - content_type.starts_with("image/") - || has_extension( - file_name, - &[ - ".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".svg", ".heic", ".heif", - ], - ) -} - -fn is_video_upload(content_type: &str, file_name: &str) -> bool { - content_type.starts_with("video/") - || has_extension(file_name, &[".mp4", ".webm", ".mov", ".m4v", ".avi", ".mkv", ".ogg"]) -} - -fn media_content_type_for_path(path: &StdPath) -> &'static str { - let lower = path - .extension() - .and_then(|value| value.to_str()) - .unwrap_or("") - .to_ascii_lowercase(); - - match lower.as_str() { - "png" => "image/png", - "jpg" | "jpeg" => "image/jpeg", - "gif" => "image/gif", - "webp" => "image/webp", - "bmp" => "image/bmp", - "svg" => "image/svg+xml", - "heic" | "heif" => "image/heic", - "mp4" | "m4v" => "video/mp4", - "webm" => "video/webm", - "mov" => "video/quicktime", - "avi" => "video/x-msvideo", - "mkv" => "video/x-matroska", - "ogg" => "video/ogg", - "pdf" => "application/pdf", - "txt" | "md" => "text/plain; charset=utf-8", - "json" => "application/json", - _ => "application/octet-stream", - } -} - -#[allow(clippy::result_large_err)] // the axum `Response` is the error contract of these parsers -async fn parse_json_message(state: &AppState, request: Request) -> Result { - let Json(payload) = Json::::from_request(request, state) - .await - .map_err(|_| json_error(StatusCode::BAD_REQUEST, "Invalid JSON payload"))?; - - let message = payload.message.trim().to_string(); - if message.is_empty() { - return Err(json_error(StatusCode::BAD_REQUEST, "message must not be empty")); - } - - Ok(ParsedMessage { - message, - agent: payload.agent.map_or(AgentField::Omitted, AgentField::from_json), - uploads: UploadGuard::default(), - }) -} - -#[allow(clippy::result_large_err)] -async fn parse_multipart_message(state: &AppState, request: Request) -> Result { - let owner_authenticated = super::owner_authenticated(state, request.headers()); - let mut multipart = Multipart::from_request(request, state) - .await - .map_err(|_| json_error(StatusCode::BAD_REQUEST, "Invalid multipart payload"))?; - - let uploads_root = { - let config = state.config.load_full(); - config.workspace_dir.join(UPLOADS_DIR_NAME) - }; - let mut uploads_root_prepared = false; - - let mut message = String::new(); - let mut agent = AgentField::Omitted; - let mut attachments = Vec::new(); - let mut uploads = UploadGuard::default(); - let mut file_count = 0usize; - - while let Some(field) = multipart - .next_field() - .await - .map_err(|_| json_error(StatusCode::BAD_REQUEST, "Failed to parse multipart form fields"))? - { - let field_name = field.name().unwrap_or_default().to_string(); - match field_name.as_str() { - "message" => { - message = field.text().await.map_err(|_| { - json_error( - StatusCode::BAD_REQUEST, - "Failed to decode message text from multipart payload", - ) - })?; - } - "agent" => { - let text = field.text().await.map_err(|_| { - json_error(StatusCode::BAD_REQUEST, "Failed to decode agent from multipart payload") - })?; - agent = AgentField::Text(text); - } - "files" => { - file_count += 1; - if file_count > MAX_UPLOAD_FILES { - return Err(json_error(StatusCode::BAD_REQUEST, "Too many files (max 10)")); - } - - let original_name = field.file_name().unwrap_or("upload.bin").to_string(); - let safe_name = sanitize_upload_filename(&original_name); - let content_type = field.content_type().unwrap_or("").to_string(); - let bytes = field - .bytes() - .await - .map_err(|_| json_error(StatusCode::BAD_REQUEST, "Failed to read uploaded file content"))?; - - if bytes.len() > MAX_UPLOAD_FILE_SIZE_BYTES { - return Err(json_error( - StatusCode::PAYLOAD_TOO_LARGE, - "File too large (max 20MB per file)", - )); - } - - if !owner_authenticated { - super::authorize_resource_mutation(state, "gateway_api:sessions:upload", ResourceRiskLevel::Low) - .map_err(|error| error.into_response())?; - } - - if !uploads_root_prepared { - fs::create_dir_all(&uploads_root).await.map_err(|error| { - tracing::error!("Failed to create uploads directory: {error}"); - json_error(StatusCode::INTERNAL_SERVER_ERROR, "Failed to prepare uploads directory") - })?; - uploads_root_prepared = true; - } - - // A per-request unique name, created exclusively: concurrent - // requests never share a path, and cleanup never reaches a file - // this request did not create. - let stored_name = format!( - "{}_{}_{}_{}", - Utc::now().timestamp_millis(), - uuid::Uuid::new_v4().simple(), - file_count, - safe_name - ); - let stored_path = uploads_root.join(stored_name); - - let persist_failed = |error: std::io::Error| { - tracing::error!("Failed to persist uploaded file: {error}"); - json_error(StatusCode::INTERNAL_SERVER_ERROR, "Failed to persist uploaded file") - }; - { - use tokio::io::AsyncWriteExt; - // Ownership first: the guard knows the path before the - // blocking worker can create it. - let abandoned = uploads.begin(stored_path.clone()); - let worker_path = stored_path.clone(); - let created = tokio::task::spawn_blocking(move || create_upload_file(&worker_path, &abandoned)) - .await - .map_err(|error| persist_failed(std::io::Error::other(error)))?; - let created = uploads.settle(&stored_path, created).map_err(persist_failed)?; - let mut file = fs::File::from_std(created); - file.write_all(&bytes).await.map_err(persist_failed)?; - file.flush().await.map_err(persist_failed)?; - } - - if is_image_upload(&content_type, &safe_name) { - attachments.push(format!("[IMAGE:{}]", stored_path.display())); - } else if is_video_upload(&content_type, &safe_name) { - attachments.push(format!("[VIDEO:{}]", stored_path.display())); - } else { - attachments.push(format!("[FILE:{}]", stored_path.display())); - } - } - _ => {} - } - } - - let message = message.trim(); - let combined = if attachments.is_empty() { - message.to_string() - } else if message.is_empty() { - attachments.join("\n") - } else { - format!("{message}\n{}", attachments.join("\n")) - }; - - if combined.trim().is_empty() { - return Err(json_error(StatusCode::BAD_REQUEST, "message must not be empty")); - } - - Ok(ParsedMessage { - message: combined, - agent, - uploads, - }) -} - -#[allow(clippy::result_large_err)] -async fn parse_message_from_request(state: &AppState, request: Request) -> Result { - let content_type = request - .headers() - .get(header::CONTENT_TYPE) - .and_then(|value| value.to_str().ok()) - .unwrap_or("") - .to_ascii_lowercase(); - - if content_type.contains("multipart/form-data") { - parse_multipart_message(state, request).await - } else { - parse_json_message(state, request).await - } -} - -/// `{}` creates a Console session as before; `{"session_key"}` is the rf -/// get-or-create (AC-1b1). Present-or-absent is kept apart from `null`. -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -pub(super) struct CreateSessionRequest { - #[serde(default, deserialize_with = "present_value")] - session_key: Option, -} - -pub async fn post_session( - State(state): State, - axum::Extension(principal): axum::Extension, - headers: HeaderMap, - uri: axum::http::Uri, - Json(body): Json, -) -> Response { - if let Some(key) = body.session_key { - return rf_message::post_keyed_session(&state, &principal, &headers, &uri, key).await; - } - if !super::owner_authenticated(&state, &headers) - && let Err(error) = - super::authorize_resource_mutation(&state, "gateway_api:sessions:create", ResourceRiskLevel::Low) - { - return error.into_response(); - } - let session_id = format!("console-{}", uuid::Uuid::new_v4()); - if let Err(error) = state - .mem - .create_conversation_session(&session_id, &principal.owner_id) - .await - { - tracing::error!(%error, "Failed to create Console session"); - return json_error(StatusCode::INTERNAL_SERVER_ERROR, "Failed to create session"); - } - ( - StatusCode::CREATED, - Json(serde_json::json!({"session_id": session_id, "status":"empty", "message_count":0})), - ) - .into_response() -} - -pub async fn get_sessions( - State(state): State, - Query(query): Query, - headers: axum::http::HeaderMap, - axum::Extension(api_principal): axum::Extension, -) -> impl IntoResponse { - // MA-01h: a paired bearer (the install owner) lists only its own - // sessions, so no preview shows another owner's content. With pairing - // off the listing is unchanged. - let owner_filter = super::owner_authenticated(&state, &headers).then_some(api_principal.owner_id.as_str()); - let limit = normalize_limit(query.limit); - let offset = normalize_offset(query.offset); - let status_filter = query - .status - .as_deref() - .map(str::trim) - .filter(|value| !value.is_empty()) - .map(str::to_ascii_lowercase); - let search_filter = query - .search - .as_deref() - .map(str::trim) - .filter(|value| !value.is_empty()) - .map(str::to_ascii_lowercase); - let fetch_batch = if limit == 0 { - DEFAULT_PAGE_LIMIT - } else { - limit.min(MAX_PAGE_LIMIT) - }; - let mut response = Vec::with_capacity(limit); - let mut source_offset = 0usize; - let mut filtered_offset = 0usize; - - loop { - let listed = match owner_filter { - Some(owner_id) => { - state - .mem - .list_owner_conversation_sessions(owner_id, fetch_batch, source_offset, query.channel.as_deref()) - .await - } - None => { - state - .mem - .list_conversation_sessions(fetch_batch, source_offset, query.channel.as_deref()) - .await - } - }; - let sessions = match listed { - Ok(sessions) => sessions, - Err(error) => { - tracing::error!("Failed to list conversation sessions from DB: {error}"); - return ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(serde_json::json!({ "error": "Failed to load sessions" })), - ) - .into_response(); - } - }; - - if sessions.is_empty() { - break; - } - - let batch_len = sessions.len(); - for session in sessions { - if !matches_session_filters(&session, status_filter.as_deref(), search_filter.as_deref()) { - continue; - } - - if filtered_offset < offset { - filtered_offset += 1; - continue; - } - - let status = derive_session_status(&session.last_message_preview, session.message_count); - let metadata = if matches!(session.channel.as_str(), "cron" | "xin") { - let memory = std::sync::Arc::clone(&state.mem); - let owner = api_principal.owner_id.clone(); - let key = session.session_key.clone(); - match crate::runtime::blocking::spawn_blocking(move || { - memory - .sync_store() - .map_or(Ok(None), |sync| sync.session_metadata(&owner, &key)) - }) - .await - { - Ok(Ok(metadata)) => metadata, - _ => { - return super::capabilities::coded_error( - StatusCode::SERVICE_UNAVAILABLE, - "storage_unavailable", - "scheduled session metadata unavailable", - ); - } - } - } else { - None - }; - response.push(SessionSummary { - metadata, - session_id: session.session_key, - sender: session.sender, - channel: session.channel, - status: status.to_string(), - created_at: session.created_at, - updated_at: session.updated_at, - message_count: session.message_count, - last_message_preview: session.last_message_preview, - }); - - if response.len() >= limit { - break; - } - } - - if response.len() >= limit || batch_len < fetch_batch { - break; - } - source_offset += batch_len; - } - - Json(response).into_response() -} - -pub async fn get_session_messages( - State(state): State, - Path(session_id): Path, - Query(query): Query, - axum::Extension(api_principal): axum::Extension, -) -> impl IntoResponse { - if rf_message::is_caller_session_key(&session_id) - && let Err(response) = - rf_message::require_session_owner(&state, &session_id, &api_principal.owner_id, false).await - { - return *response; - } - let Some(session) = (match state.mem.get_conversation_session(&session_id).await { - Ok(session) => session, - Err(error) => { - tracing::error!("Failed to load session metadata from DB: {error}"); - return ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(serde_json::json!({ "error": "Failed to load session" })), - ) - .into_response(); - } - }) else { - // An id in the caller-key grammar names an rf session (Console ids - // start with `console-`, which the grammar excludes): a missing one - // is the coded `404 session_unknown`, like another owner's. - if rf_message::is_caller_session_key(&session_id) { - return rf_message::session_unknown(); - } - return ( - StatusCode::NOT_FOUND, - Json(serde_json::json!({ "error": "Session not found" })), - ) - .into_response(); - }; - - let limit = normalize_limit(query.limit); - let offset = normalize_offset(query.offset); - // Recovery settles turns a ready runtime ran; a runtime standing by for a - // provider credential has run none since it started, and the stored - // history is still served. - if let Ok(runtime) = state.admit_turn_runtime() - && let Err(error) = recover_console_history(&state, &runtime, &api_principal, &session_id).await - { - return history_recovery_failed(&error); - } - if session.channel == crate::memory::CALLER_KEYED_SESSION_CHANNEL { - return rf_message::rf_history(&state, &session, &api_principal, query.agent.as_deref(), limit, offset).await; - } - if matches!(session.channel.as_str(), "cron" | "xin") { - let memory = std::sync::Arc::clone(&state.mem); - let owner = api_principal.owner_id.clone(); - let key = session.session_key.clone(); - let named = crate::runtime::blocking::spawn_blocking(move || { - memory.sync_store().map_or(Ok(false), |sync| { - sync.session_metadata(&owner, &key).map(|metadata| metadata.is_some()) - }) - }) - .await; - match named { - Ok(Ok(true)) => { - return rf_message::rf_history( - &state, - &session, - &api_principal, - query.agent.as_deref().or(Some(session.sender.as_str())), - limit, - offset, - ) - .await; - } - Ok(Ok(false)) => {} - _ => { - return super::capabilities::coded_error( - StatusCode::SERVICE_UNAVAILABLE, - "storage_unavailable", - "scheduled session metadata unavailable", - ); - } - } - } - let principal = operator_history_principal( - &api_principal, - &console_runtime_envelope(&state, &session_id, &session.channel, &session.sender), - ); - let turns = match state - .mem - .list_console_conversation_turns(&principal, &session_id, limit, offset) - .await - { - Ok(turns) => turns, - Err(error) => { - tracing::error!("Failed to load conversation turns from DB: {error}"); - return ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(serde_json::json!({ "error": "Failed to load session messages" })), - ) - .into_response(); - } - }; - - let response: Vec = turns - .into_iter() - .map(|turn| SessionMessage { - role: turn.role, - content: turn.content, - timestamp: turn.timestamp, - message_id: turn.message_id, - agent: None, - }) - .collect(); - - Json(response).into_response() -} - -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -pub(super) struct DecisionApprovalRequest { - approved: bool, -} - -pub(super) async fn get_decision_approval( - State(state): State, - Path((session_id, decision_id)): Path<(String, String)>, - axum::Extension(principal): axum::Extension, -) -> Response { - call_approval_action(state, session_id, decision_id, principal, None, false).await -} - -const INBOX_DEFAULT_LIMIT: usize = 50; -const INBOX_MAX_LIMIT: usize = 100; - -fn normalize_inbox_limit(limit: Option) -> usize { - match limit { - Some(0) | None => INBOX_DEFAULT_LIMIT, - Some(value) => value.min(INBOX_MAX_LIMIT), - } -} - -#[allow(clippy::result_large_err)] // the axum `Response` is the error contract of this parser -fn parse_inbox_cursor(cursor: Option<&str>) -> Result { - let Some(cursor) = cursor.map(str::trim).filter(|value| !value.is_empty()) else { - return Ok(0); - }; - cursor - .parse::() - .ok() - .filter(|id| *id >= 0) - .ok_or_else(|| json_error(StatusCode::BAD_REQUEST, "Invalid approval cursor")) -} - -#[derive(Serialize)] -struct ApprovalInboxItem { - session_id: String, - #[serde(flatten)] - view: crate::security::approval_ledger::view::DecisionApprovalView, -} - -#[derive(Serialize)] -struct ApprovalInboxResponse { - approvals: Vec, - next_cursor: Option, -} - -/// Owner-scoped pending approval inbox. Foreign rows are omitted. -pub(super) async fn get_session_approvals( - State(state): State, - Query(query): Query, - axum::Extension(principal): axum::Extension, -) -> Response { - let runtime = match state.admit_turn_runtime() { - Ok(runtime) => runtime, - Err(refusal) => return super::provider_not_ready(refusal), - }; - if let Some(response) = approvals_unavailable(&runtime.config_generation.effective, state.mem.as_ref()) { - return response; - } - let after_id = match parse_inbox_cursor(query.cursor.as_deref()) { - Ok(id) => id, - Err(response) => return response, - }; - let limit = normalize_inbox_limit(query.limit); - let cancellation = tokio_util::sync::CancellationToken::new(); - let cleanup = - match crate::runtime::turn_cleanup::CleanupScope::new(Some(&runtime.publication_slot.cleanup), cancellation) { - Ok(cleanup) => cleanup, - Err(error) => { - warn_cleanup_refused(&runtime.publication_slot.cleanup, "Console approval inbox", &error); - return json_error(StatusCode::SERVICE_UNAVAILABLE, "Gateway is draining"); - } - }; - let result = cleanup - .run(Box::pin(async { - let service = runtime.publication_slot.publish(&runtime, &state).await?; - let mut envelope = RuntimeEnvelope::console( - runtime - .config_generation - .effective - .workspace_dir - .to_string_lossy() - .as_ref(), - "approval-inbox", - ); - envelope.owner_id = Some(principal.owner_id.clone()); - let adapter = service.call_approval_strategy(envelope)?; - let calls = adapter - .port - .list_pending_calls(&principal.owner_id, after_id, limit) - .await?; - let mut rows = Vec::new(); - use crate::security::approval_ledger::keys::ApprovalAuthority; - for item in calls.items { - let event = service - .memory() - .find_message_event_by_idempotency_key(adapter.port.workspace, &item.authority().pending_key()) - .await? - .ok_or_else(|| anyhow::anyhow!("pending call disappeared"))?; - rows.push(( - event.id, - ApprovalInboxItem { - session_id: item.subject().session_key.clone().unwrap_or_default(), - view: item.view(), - }, - )); - } - // Do not advance past the reader's bounded scan frontier. - let frontier = calls.next_cursor; - if let Some(frontier) = frontier { - rows.retain(|(id, _)| *id <= frontier); - } - rows.sort_by_key(|(id, _)| *id); - let more = rows.len() > limit; - rows.truncate(limit); - let next_cursor = if more { - rows.last().map(|(id, _)| id.to_string()) - } else { - frontier.map(|id| id.to_string()) - }; - Ok::<_, anyhow::Error>(ApprovalInboxResponse { - approvals: rows.into_iter().map(|(_, item)| item).collect(), - next_cursor, - }) - })) - .await; - match result { - Ok(page) => Json(page).into_response(), - Err(error) => { - tracing::warn!(error = %error, "approval inbox failed"); - json_error(StatusCode::SERVICE_UNAVAILABLE, "Approval inbox is unavailable") - } - } -} - -pub(super) async fn post_decision_approval( - State(state): State, - Path((session_id, decision_id)): Path<(String, String)>, - axum::Extension(principal): axum::Extension, - headers: HeaderMap, - Json(request): Json, -) -> Response { - let owner_authenticated = super::owner_authenticated(&state, &headers); - match rf_message::keyed_session(&state, &session_id).await { - Some(true) => { - if !owner_authenticated { - return super::capabilities::coded_error( - StatusCode::UNAUTHORIZED, - "auth_failed", - "paired bearer required", - ); - } - return crate::gateway::run_approvals::decide( - &state, - &principal.owner_id, - &session_id, - &decision_id, - request, - ) - .await; - } - None => { - return super::capabilities::coded_error( - StatusCode::SERVICE_UNAVAILABLE, - "storage_unavailable", - "session lookup failed", - ); - } - Some(false) => {} - } - let Ok(request) = serde_json::from_value::(request) else { - return json_error(StatusCode::UNPROCESSABLE_ENTITY, "invalid approval body"); - }; - call_approval_action( - state, - session_id, - decision_id, - principal, - Some(DecisionApprovalChange::Review(request.approved)), - owner_authenticated, - ) - .await -} - -pub(super) async fn delete_decision_approval( - State(state): State, - Path((session_id, decision_id)): Path<(String, String)>, - axum::Extension(principal): axum::Extension, - headers: HeaderMap, -) -> Response { - let owner_authenticated = super::owner_authenticated(&state, &headers); - call_approval_action( - state, - session_id, - decision_id, - principal, - Some(DecisionApprovalChange::Revoke), - owner_authenticated, - ) - .await -} - -enum DecisionApprovalChange { - Review(bool), - Revoke, -} - -fn console_decision_control_policy(config: &crate::config::Config) -> Result<(), &'static str> { - crate::security::SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir) - .enforce_tool_operation(crate::security::policy::ToolOperation::Act, "console decision control") - .map_err(|_| "Decision control is not permitted by policy") -} - -pub async fn post_session_message( - State(state): State, - Path(session_id): Path, - request: Request, -) -> impl IntoResponse { - let principal = request.extensions().get::().cloned(); - // The runtime is pinned before the body is read, as before. - let admitted = state.admit_turn_runtime(); - // A message to a caller-keyed session, or a body with an rf field, is an - // rf message (AC-1b1); any other request takes the Console path below, - // unchanged. - let (request, unreadable) = match rf_message::classify(&state, &session_id, request).await { - rf_message::MessageShape::Rf(parts, body) => { - return rf_message::post_rf_message(state, session_id, parts, body, admitted).await; - } - rf_message::MessageShape::Console { request, unreadable } => (request, unreadable), - }; - let Some(api_principal) = principal else { - return json_error(StatusCode::UNAUTHORIZED, "Authenticated API principal missing"); - }; - let turn_runtime = match admitted { - Ok(runtime) => runtime, - Err(refusal) => return super::provider_not_ready(refusal), - }; - if unreadable { - // The body could not be buffered: the JSON parser's own refusal. - return json_error(StatusCode::BAD_REQUEST, "Invalid JSON payload"); - } - let headers = request.headers().clone(); - let owner_authenticated = super::owner_authenticated(&state, &headers); - let async_mode = jobs::wants_async(request.uri().query(), &headers); - let parsed = match parse_message_from_request(&state, request).await { - Ok(parsed) => parsed, - Err(error_response) => return error_response, - }; - let ParsedMessage { - message, - agent, - uploads, - } = parsed; - - let selected = match select_turn_target(&state, turn_runtime, &api_principal, agent, owner_authenticated) { - Ok(selected) => selected, - // A refused target leaves nothing behind: dropping the guard removes - // the files this request created, and only those. - Err(refusal) => return refusal.into_response(), - }; - // The guard stays alive through admission: a missing session, a failed - // history read, closed admission or cancellation removes the files. - submit_console_message( - state, - session_id, - api_principal, - ConsoleSubmission { - selected, - message, - async_mode, - uploads, - owner_authenticated, - rf: None, - }, - ) - .await -} - -/// Why `select_turn_target` refused the request. Each arm is one error type -/// the helper already returned; `IntoResponse` delegates so status, code and -/// body bytes stay unchanged. -#[derive(Debug)] -enum TargetRefusal { - Selector(TargetError), - Forbidden((StatusCode, Json)), - Unavailable(TargetUnavailable), - RegistryMissing, -} - -impl From for TargetRefusal { - fn from(error: TargetError) -> Self { - Self::Selector(error) - } -} - -impl From<(StatusCode, Json)> for TargetRefusal { - fn from(error: (StatusCode, Json)) -> Self { - Self::Forbidden(error) - } -} - -impl From for TargetRefusal { - fn from(error: TargetUnavailable) -> Self { - Self::Unavailable(error) - } -} - -impl IntoResponse for TargetRefusal { - fn into_response(self) -> Response { - match self { - Self::Selector(error) => error.into_response(), - Self::Forbidden(payload) => payload.into_response(), - Self::Unavailable(error) => error.into_response(), - Self::RegistryMissing => json_error(StatusCode::INTERNAL_SERVER_ERROR, "Agent registry is unavailable"), - } - } -} - -/// Resolve the request's `agent` against the pinned runtime generation, -/// before admission, input recording or provider access. -fn select_turn_target( - state: &AppState, - turn_runtime: std::sync::Arc, - principal: &super::ApiPrincipal, - agent: AgentField, - owner_authenticated: bool, -) -> Result { - let target = TurnTarget::from_field(agent)?; - if matches!(target, TurnTarget::Main) { - return Ok(SelectedTurn { - runtime: turn_runtime, - targeted: None, - incarnation: None, - }); - } - if !owner_authenticated { - // A caller who may not post messages learns nothing about which agents exist. - super::authorize_resource_mutation(state, "gateway_api:sessions:message", ResourceRiskLevel::Low)?; - } - let Some(plan) = resolve_target(&turn_runtime.config_generation.effective, &target)? else { - return Ok(SelectedTurn { - runtime: turn_runtime, - targeted: None, - incarnation: None, - }); - }; - if !state.mem.supports_agent_scope() { - return Err(TargetRefusal::Selector(TargetError::BackendUnsupported)); - } - let (runtime, turn) = prepare_target(&turn_runtime, &plan)?; - let registry = state.mem.agent_registry().ok_or(TargetRefusal::RegistryMissing)?; - let incarnation = resolve_incarnation(state, registry, &turn_runtime, &principal.owner_id, &plan)?; - Ok(SelectedTurn { - runtime, - targeted: Some(turn), - incarnation: Some(incarnation), - }) -} - -#[cfg_attr( - test, - expect( - clippy::large_enum_variant, - reason = "Test-only source variant must not add indirection to production admission" - ) -)] -enum ConsoleTurnSource { - #[cfg(test)] - Message(crate::gateway::turn_source::GatewayTurnProof), - Admitted { - proof: crate::gateway::turn_source::GatewayTurnProof, - guard: crate::gateway::turn_source::GatewayAdmissionGuard, - owner_authenticated: bool, - }, -} - -struct ConsolePendingInput { - state: AppState, - runtime: std::sync::Arc, - principal: super::ApiPrincipal, - envelope: RuntimeEnvelope, - ticket: crate::runtime::turn_cleanup::CleanupTicket, -} - -impl ConsolePendingInput { - async fn record( - self, - message: String, - rf_admission: Option, - ) -> anyhow::Result<( - crate::gateway::turn_source::GatewayTurnProof, - crate::gateway::turn_source::GatewayAdmissionGuard, - )> { - let run = self - .envelope - .run_id - .as_deref() - .ok_or_else(|| anyhow::anyhow!("Console input run is missing"))?; - let key = format!("console:{run}:input"); - let recording = self.runtime.config_generation.effective.memory.event_recording_config(); - let fabric = MemoryFabric::new(self.state.mem.clone(), self.envelope.workspace_id.clone()) - .with_event_recording(recording) - .with_ingress_recovery(&self.runtime.config_generation.effective, &self.ticket) - .await?; - let (sender, receiver) = tokio::sync::oneshot::channel(); - tokio::spawn(async move { - let mut ticket = Some(self.ticket); - let mut admission = None; - let operation = async { - let event = match rf_admission { - Some(rf_admission) => { - fabric - .record_admitted_user_message( - self.envelope.message_scope(), - message.clone(), - Some(key.clone()), - rf_admission, - ) - .await? - } - None => { - fabric - .record_inbound_user_message( - self.envelope.message_scope(), - message.clone(), - Some(key.clone()), - None, - ) - .await? - } - }; - anyhow::ensure!( - event.id <= 0 - || (event.idempotency_key.as_deref() == Some(key.as_str()) - && event.workspace_id == self.envelope.workspace_id - && event.owner_id.as_deref() == Some(self.principal.owner_id.as_str())), - "Console input identity changed during persistence" - ); - let event_id = if event.id > 0 { event.event_id.as_str() } else { "" }; - let proof = crate::gateway::turn_source::GatewaySourceReceipt::console_proof( - self.state.mem.as_ref(), - &self.runtime, - &self.principal, - &self.envelope, - &message, - event_id, - ) - .await?; - anyhow::ensure!( - event.id <= 0 - || proof.envelope().source_message_event_id.as_deref() == Some(event.event_id.as_str()), - "Console durable receipt lost its original input" - ); - admission = Some(crate::gateway::turn_source::GatewayAdmissionGuard::new( - &proof, - fabric.clone(), - ticket - .take() - .ok_or_else(|| anyhow::anyhow!("Console input cleanup ticket missing"))?, - None, - )); - if recording.enabled && recording.record_user_messages { - if console_recordable(&self.runtime.config_generation.effective, self.state.mem.as_ref()) { - self.state.mem.project_console_message(&event).await?; - } else { - self.state - .mem - .append_conversation_turn( - &self.envelope.session_key, - self.envelope.channel.as_deref().unwrap_or("console"), - self.envelope.sender.as_deref().unwrap_or("console-user"), - "user", - &message, - None, - Some(&event.event_id), - Some(&self.envelope.resolved_owner_id()), - self.envelope.agent_partition.as_ref(), - ) - .await?; - } - } - Ok::<_, anyhow::Error>(proof) - }; - let result = tokio::time::timeout(std::time::Duration::from_secs(15), operation) - .await - .map_err(|_| anyhow::anyhow!("Console input persistence timed out")) - .and_then(std::convert::identity); - let result = match result { - Ok(proof) => admission - .take() - .map(|guard| (proof, guard)) - .ok_or_else(|| anyhow::anyhow!("Console input owner did not issue a guard")), - // An rf admission refused inside its transaction rolled back: - // nothing was written, so no write is left unconfirmed. - Err(error) if crate::memory::RfAdmissionRefused::of(&error).is_some() => { - if let Some(ticket) = ticket.take() { - ticket.finish(true); - } - Err(error) - } - Err(_error) if fabric.ingress_already_accepted() => { - if let Some(ticket) = ticket.take() { - ticket.finish(true); - } - Err(crate::runtime::ingress_recovery::AlreadyAccepted.into()) - } - Err(error) => { - if admission.is_none() { - let recovery = async { - let event = self - .state - .mem - .find_owned_message_event_by_idempotency_key( - &self.envelope.workspace_id, - &self.principal.owner_id, - &key, - ) - .await? - .ok_or_else(|| anyhow::anyhow!("Console input commit is unconfirmed"))?; - anyhow::ensure!( - event.id > 0 - && !event.event_id.is_empty() - && event.idempotency_key.as_deref() == Some(key.as_str()) - && event.workspace_id == self.envelope.workspace_id - && event.owner_id.as_deref() == Some(self.principal.owner_id.as_str()), - "Console recovery input identity changed" - ); - let proof = crate::gateway::turn_source::GatewaySourceReceipt::console_proof( - self.state.mem.as_ref(), - &self.runtime, - &self.principal, - &self.envelope, - &message, - &event.event_id, - ) - .await?; - anyhow::ensure!( - proof.envelope().source_message_event_id.as_deref() == Some(event.event_id.as_str()), - "Console recovery input is not durable" - ); - Ok::<_, anyhow::Error>(proof) - }; - if let Ok(Ok(proof)) = tokio::time::timeout(std::time::Duration::from_secs(15), recovery).await - && let Some(ticket) = ticket.take() - { - admission = Some(crate::gateway::turn_source::GatewayAdmissionGuard::new( - &proof, fabric, ticket, None, - )); - } - } - if let Some(mut guard) = admission { - let _ = tokio::time::timeout( - std::time::Duration::from_secs(15), - guard.finish_failure(sender.is_closed(), "Console input admission failed"), - ) - .await; - } else if let Some(ticket) = ticket { - ticket.finish(false); - } - Err(error) - } - }; - // A disconnected HTTP request drops the guard carried by this - // response, retaining cleanup ownership even before job launch. - let _ = sender.send(result); - }); - receiver - .await - .map_err(|_| anyhow::anyhow!("Console input owner ended without a receipt"))? - } -} - -/// What one console submission carries into admission. `uploads` rides along -/// so the files are removed unless the input or job is accepted. -struct ConsoleSubmission { - selected: SelectedTurn, - message: String, - async_mode: bool, - uploads: UploadGuard, - /// [`super::owner_authenticated`]; when false, Main's level gates the - /// message and the saved reply as before A4, and the turn is - /// owner-isolated. - owner_authenticated: bool, - /// Set for an rf message turn: its (session, agent) slot, held until its - /// job ends, its run and job ids and its attempt row; it also selects the - /// `{run_id, job_id}` answer. - rf: Option, -} - -async fn submit_console_message( - state: AppState, - session_id: String, - api_principal: super::ApiPrincipal, - submission: ConsoleSubmission, -) -> Response { - let ConsoleSubmission { - selected, - message, - async_mode, - uploads, - owner_authenticated, - rf, - } = submission; - let SelectedTurn { - runtime: turn_runtime, - targeted: target, - incarnation, - } = selected; - tracing::debug!( - agent_incarnation = incarnation.as_deref(), - "console turn target resolved" - ); - let Some(session) = (match state.mem.get_conversation_session(&session_id).await { - Ok(session) => session, - Err(error) => { - tracing::error!("Failed to read session metadata from DB: {error}"); - return ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(serde_json::json!({ "error": "Failed to load session" })), - ) - .into_response(); - } - }) else { - return ( - StatusCode::NOT_FOUND, - Json(serde_json::json!({ "error": "Session not found" })), - ) - .into_response(); - }; - // Q10: the only place a Console turn's isolation is decided. A paired - // bearer is the install owner and gets the terminal's tool rules at the - // turn's own level; any other caller (pairing off) stays owner-isolated. - // A controlled H2 launch binds only isolated Gateway sources, so it keeps - // isolation. - let full_target = target - .as_ref() - .is_some_and(|target| target.autonomy == crate::security::AutonomyLevel::Full); - let owner_isolated = (!owner_authenticated && !full_target) || turn_runtime.publication_slot.controlled.is_some(); - let run_id = rf - .as_ref() - .map_or_else(|| uuid::Uuid::new_v4().to_string(), |rf| rf.run_id.clone()); - let runtime_envelope = console_runtime_envelope_for_workspace( - turn_runtime - .config_generation - .effective - .workspace_dir - .to_string_lossy() - .to_string(), - &session_id, - &session.channel, - &session.sender, - ) - .with_owner_id(api_principal.owner_id.clone()); - let runtime_envelope = if owner_isolated { - runtime_envelope.with_owner_isolation() - } else { - runtime_envelope - } - .with_run_id(run_id.clone()) - .with_config_generation(&turn_runtime.config_generation); - - if let Err(error) = recover_console_history(&state, &turn_runtime, &api_principal, &session_id).await { - return history_recovery_failed(&error); - } - let mut principal = operator_history_principal(&api_principal, &runtime_envelope); - let partition = match history_partition( - &runtime_envelope, - &api_principal.owner_id, - target.as_ref(), - incarnation.as_deref(), - ) { - Ok(partition) => partition, - Err(response) => return *response, - }; - principal.agent_partition = Some(partition.clone()); - // MA-01b3: the turn's writers stamp from the envelope; reads keep the principal. - let runtime_envelope = runtime_envelope.with_agent_partition(partition); - let turns = match state - .mem - .list_console_conversation_turns(&principal, &session_id, MAX_PAGE_LIMIT, 0) - .await - { - Ok(turns) => turns, - Err(error) => { - tracing::error!("Failed to load conversation history from DB: {error}"); - return ( - StatusCode::INTERNAL_SERVER_ERROR, - Json(serde_json::json!({ "error": "Failed to load session history" })), - ) - .into_response(); - } - }; - - if !owner_authenticated - && let Err(error) = - super::authorize_resource_mutation(&state, "gateway_api:sessions:message", ResourceRiskLevel::Low) - { - return error.into_response(); - } - - let input_cancellation = tokio_util::sync::CancellationToken::new(); - let ticket = match turn_runtime.publication_slot.cleanup.register(input_cancellation) { - Ok(ticket) => ticket, - Err(error) => { - warn_cleanup_refused( - &turn_runtime.publication_slot.cleanup, - "Console input admission", - &error, - ); - return json_error(StatusCode::SERVICE_UNAVAILABLE, "Console input admission is closed"); - } - }; - let pending = ConsolePendingInput { - state: state.clone(), - runtime: std::sync::Arc::clone(&turn_runtime), - principal: api_principal, - envelope: runtime_envelope, - ticket, - }; - let admission = rf.as_ref().map(|rf| rf.admission.clone()); - let (proof, mut guard) = match pending.record(message.clone(), admission).await { - Ok(admission) => admission, - Err(error) if crate::memory::RfAdmissionRefused::of(&error).is_some() => { - return rf_replay::refused_admission(&state, rf, &error).await; - } - Err(error) if error.is::() => { - return json_error( - StatusCode::CONFLICT, - "Input already accepted; execution was not repeated and outcome remains unconfirmed", - ); - } - Err(error) if error.is::() => { - return ( - StatusCode::CONFLICT, - Json(serde_json::json!({ "error": { "code": "agent_scope_refused" } })), - ) - .into_response(); - } - Err(error) => { - // The chain can quote stored input (a recovery capsule decode error - // does), so only its content-free category and the session id are logged. - tracing::warn!( - error_kind = console_error_kind(&error), - session_id = %session_id, - "Console input persistence failed before admission" - ); - return json_error( - StatusCode::INTERNAL_SERVER_ERROR, - "Console input persistence is unconfirmed", - ); - } - }; - // Establish monitor ownership synchronously, before constructing work that - // cancellation or registry abortion can drop without ever polling. - let (cleanup_sender, cleanup_receiver) = tokio::sync::oneshot::channel(); - if let Err(error) = guard.attach_acknowledgement(cleanup_sender) { - tracing::warn!( - error_kind = console_error_kind(&error), - session_id = %session_id, - "Console input cleanup ownership could not be attached" - ); - return json_error( - StatusCode::INTERNAL_SERVER_ERROR, - "Console input cleanup ownership is unconfirmed", - ); - } - let source = ConsoleTurnSource::Admitted { - proof, - guard, - owner_authenticated, - }; - - // Everything up to here is bounded bookkeeping. What follows is the agent - // turn itself, which has no upper bound — tool chains, sub-agents, and - // compaction can legitimately run for hours, and PRX no longer cuts them off - // on a clock. Awaiting it inside this handler would tie the turn's lifetime - // to the HTTP connection, so a closed tab or a proxy hang-up would destroy a - // turn mid-flight, after its side effects had already begun. It therefore - // runs as a detached job: visible in `prx tasks list`, killable by id, and - // still there when the client comes back. - let settle_state = rf.as_ref().map(|_| state.clone()); - let work = run_console_message_job(turn_runtime, state, message, turns, source, target); - let label = format!("gateway:session_message:{session_id}"); - if let Some(rf) = rf { - let accepted = rf.accepted(); - let (slot_key, job_id) = (rf.slot.key().to_owned(), rf.job_id); - let slot = rf.slot; - let in_flight = rf.in_flight; - let key = rf.admission.key; - // The slot is released exactly when the job's work ends or is dropped. - let job = jobs::submit_run_with_cleanup( - jobs::KIND_SESSION_MESSAGE, - label, - async move { - let _slot = slot; - work.await - }, - Some(cleanup_receiver), - Some((std::sync::Arc::from(run_id.as_str()), job_id)), - ); - // AC-1b2b: the run stays in flight until the job's terminal phase; - // a delete that arrived meanwhile is then applied to its rows. - if let Some(settle_state) = settle_state { - tokio::spawn(async move { - job.finished().await; - drop(in_flight); - rf_delete::settle_deleted(&settle_state, &key.workspace_id, &key.owner_id, &key.session_key).await; - }); - } - if rf_message::attach_job(&slot_key, job_id) - && let Some(work_id) = jobs::work_id_of(job_id) - { - // A cancel by run id arrived while the input was being admitted. - tokio::spawn(crate::runtime::registry::kill(work_id, true)); - } - return accepted; - } - let job = jobs::submit_with_cleanup(jobs::KIND_SESSION_MESSAGE, label, work, Some(cleanup_receiver)); - // The job owns the turn now; hand the uploaded files over with it. - uploads.release(); - - if async_mode { - return (StatusCode::ACCEPTED, Json(job.accepted_body())).into_response(); - } - job.wait().await.into_response() -} - -/// The unbounded half of `POST /sessions/{id}/message`, run as a job. -/// -/// Returns the exact `(status, body)` the synchronous handler used to produce, -/// so waiting clients see no contract change and polling clients see the same -/// payload under `result`. -fn run_console_message_job( - turn_runtime: std::sync::Arc, - state: AppState, - message: String, - turns: Vec, - source: ConsoleTurnSource, - target: Option, -) -> std::pin::Pin> + Send>> { - // Keep the owned Console work out of the generic job submitter's stack. - // Construction does not poll it; the same input guard retains its sender. - Box::pin(run_console_message_job_work( - turn_runtime, - state, - message, - turns, - source, - target, - )) -} - -async fn run_console_message_job_work( - turn_runtime: std::sync::Arc, - state: AppState, - message: String, - turns: Vec, - source: ConsoleTurnSource, - target: Option, -) -> Result { - let (source_proof, input_guard, owner_authenticated) = match source { - #[cfg(test)] - ConsoleTurnSource::Message(proof) => (proof, None, false), - ConsoleTurnSource::Admitted { - proof, - guard, - owner_authenticated, - } => (proof, Some(guard), owner_authenticated), - }; - let runtime_envelope = source_proof.envelope().clone(); - let cancellation = - jobs::current_cancellation().map_or_else(tokio_util::sync::CancellationToken::new, |token| token.child_token()); - let _cancel_guard = cancellation.clone().drop_guard(); - let config = &turn_runtime.config_generation.effective; - let cleanup_ticket = turn_runtime - .publication_slot - .cleanup - .register(cancellation.clone()) - .map_err(|_| "Console turn admission is closed".to_owned())?; - // Register the job's cancellation/acknowledgement owner before releasing - // the HTTP input ticket. This transfer has no await or unowned interval. - let inherited_fabric = input_guard.as_ref().map(|guard| guard.ingress_fabric()); - let admission_acknowledgement = if let Some(input_guard) = input_guard { - let (input_ticket, acknowledgement) = input_guard - .into_terminal_parts() - .map_err(|_| "Console input ownership transfer failed".to_owned())?; - input_ticket.finish(true); - acknowledgement - } else { - jobs::register_terminal_cleanup() - }; - let admission_fabric = inherited_fabric.unwrap_or_else(|| { - MemoryFabric::new(state.mem.clone(), runtime_envelope.workspace_id.clone()) - .with_event_recording(config.memory.event_recording_config()) - }); - let mut admission_guard = crate::gateway::turn_source::GatewayAdmissionGuard::new( - &source_proof, - admission_fabric, - cleanup_ticket, - admission_acknowledgement, - ); - // Prediction transport accounting and later work retain the same owner. - // Register its monitor acknowledgement before the first admission await. - let child_cleanup = match crate::runtime::turn_cleanup::CleanupScope::new( - Some(&turn_runtime.publication_slot.cleanup), - cancellation.child_token(), - ) { - Ok(scope) => scope.with_acknowledgement(jobs::register_terminal_cleanup()), - Err(_) => { - let error = "Console child cleanup admission is closed"; - admission_guard - .finish_failure(cancellation.is_cancelled(), error) - .await - .map_err(|_| "Console admission failure persistence is unconfirmed".to_owned())?; - return Err(error.to_owned()); - } - }; - let decision = { - let proof = &source_proof; - let admission = child_cleanup - .scope_admission(Box::pin(async { - let admitted: Result<_, String> = async { - proof - .verify_runtime_input(&turn_runtime, &message) - .map_err(|error| crate::providers::sanitize_api_error(&error.to_string()))?; - let service = turn_runtime - .publication_slot - .publish(&turn_runtime, &state) - .await - .map_err(|_| "Console decision publication failed".to_owned())?; - let kind = crate::runtime::turn_context::AgentTurnKind::SingleShot; - let context = service - .open_issued_turn_context(proof, kind, &cancellation) - .await - .map_err(|error| crate::providers::sanitize_api_error(&error.to_string()))?; - let advice = service.advisory().analyze_turn(context.runtime(), &cancellation).await; - Ok::<_, String>((service, context, advice)) - } - .await; - admitted.map_err(anyhow::Error::msg) - })) - .await; - let (service, context, advice) = match admission { - Ok(admitted) => admitted, - Err(error) => { - // No future is still polling admission. Close/drain its owned - // attempts before acknowledging the failed input terminal. - let admission_error = crate::providers::sanitize_api_error(&format!("{error:#}")); - let drained = child_cleanup.run(Box::pin(async { Err::<(), _>(error) })).await; - let error = match drained { - Err(error) if error.is::() => format!( - "{admission_error}; Console admission cleanup is unconfirmed: {}", - crate::providers::sanitize_api_error(&format!("{error:#}")), - ), - _ => admission_error, - }; - if admission_guard - .finish_failure(cancellation.is_cancelled(), &error) - .await - .is_err() - { - return Err(format!("{error}; Console admission failure persistence is unconfirmed")); - } - return Err(error); - } - }; - let provider_trace = None; - ConsoleDecisionTurn { - service: std::sync::Arc::clone(service), - provider_trace, - context, - advice, - proof, - cancellation: cancellation.clone(), - } - }; - let (cleanup_ticket, admission_acknowledgement) = admission_guard - .into_terminal_parts() - .map_err(|error| error.to_string())?; - let terminal_guard = crate::gateway::turn_source::publication_slot::GatewayTerminalGuard::new( - cleanup_ticket, - std::sync::Arc::clone(&decision.service), - std::sync::Arc::clone(&decision.context), - MemoryFabric::new(state.mem.clone(), runtime_envelope.workspace_id.clone()), - std::sync::Arc::clone(config), - runtime_envelope.clone(), - admission_acknowledgement, - ) - .map_err(|error| error.to_string())?; - let terminal_guard = if let Some((trace, route)) = &decision.provider_trace { - terminal_guard.with_provider_trace(std::sync::Arc::clone(trace), route.as_ref().clone()) - } else { - terminal_guard - }; - let work = async { - let turn = match run_console_runtime_turn( - std::sync::Arc::clone(&turn_runtime), - &state, - &message, - turns, - &decision, - target.as_ref(), - ) - .await - { - Ok(turn) => turn, - Err(error) => { - // A stable HTTP error response still represents a failed turn. - // Finalize it before returning a successful job transport result. - { - terminal_guard - .finish_failure(&error, cancellation.is_cancelled()) - .await - .map_err(|_| { - format!( - "Console terminal cleanup persistence is unconfirmed ({})", - terminal_guard.failure_reason() - ) - })?; - } - if let Some(tools) = crate::providers::tool_schema_refused_tools(&error) { - // A configuration problem, not a failed job: the caller - // gets a stable code with every refused tool, and the log - // keeps the whole refusal, unclipped. - tracing::error!( - error = %crate::security::redaction::redact_secrets(&format!("{error:#}")), - "Console turn refused before transport: the provider cannot accept some offered tool schemas" - ); - return Ok(jobs::JobOutput::new( - StatusCode::INTERNAL_SERVER_ERROR, - serde_json::json!({ - "error": "tool_schema_refused", - "tools": tools, - "message": "The configured provider cannot accept some of the tool schemas this turn \ - offered, so nothing was sent. The gateway log names the configuration \ - to change.", - }), - )); - } - return Err(crate::providers::sanitize_api_error(&error.to_string())); - } - }; - let reply = turn.reply.clone(); - - if !owner_authenticated - && let Err((status, body)) = crate::gateway::authorize_gateway_config_resource_mutation( - config, - "gateway_api:sessions:assistant_message", - ResourceRiskLevel::Low, - ) - { - { - terminal_guard - .finish_error(&anyhow::anyhow!("Console assistant persistence authorization denied")) - .await - .map_err(|_| { - format!( - "Console terminal cleanup persistence is unconfirmed ({})", - terminal_guard.failure_reason() - ) - })?; - } - return Ok(jobs::JobOutput::new(status, body.0)); - } - - let provider_outcome = crate::agent::terminal::provider_outcome_from_trace( - &turn.route_decision, - turn.provider_started_at, - turn.trace, - ); - let terminal_id = turn - .envelope - .run_id - .clone() - .ok_or_else(|| "Console admitted run missing".to_owned())?; - let terminal_fabric = MemoryFabric::new(state.mem.clone(), turn.envelope.workspace_id.clone()); - let config = &turn_runtime.config_generation.effective; - let terminal_binding = decision - .service - .terminal_binding(&decision.context) - .map_err(|error| error.to_string())?; - let receipt = match crate::gateway::turn_source::publication_slot::commit_terminal( - Some(&terminal_guard), - &terminal_fabric, - crate::agent::terminal::TurnTerminalDraft { - binding: Some(terminal_binding), - terminal_id, - scope: turn.envelope.message_scope(), - status: crate::agent::terminal::TurnTerminalStatus::Completed, - history: Some(crate::agent::terminal::TurnHistoryProjection { - assistant_content: reply.clone(), - history_commit_len: turn.history_commit_len, - }), - history_scope: None, - provider_outcome: Some(provider_outcome), - telemetry: crate::agent::terminal::TurnTerminalTelemetry { - summary: if turn.awaiting_approval { - "console turn awaiting human approval" - } else { - "console turn completed" - } - .to_string(), - started_at: turn.provider_started_at, - finished_at: chrono::Utc::now(), - }, - delivery_intent: crate::agent::terminal::TurnDeliveryIntent::ReturnToCaller, - }, - config, - ) - .await - { - Ok(receipt) => receipt, - Err(error) => { - let reason: crate::runtime::turn_terminal::TerminalPersistReason = terminal_guard.failure_reason(); - tracing::warn!( - reason = %reason, - error = %crate::agent::diagnostics::error_class(&error), - "Failed to commit shared console terminal event" - ); - return Err(format!("Console terminal persistence is unconfirmed ({reason})")); - } - }; - - if console_recordable(config, state.mem.as_ref()) { - // A recorded console turn's transcript is the projection of its - // committed, redacted assistant event, exactly as its input was - // projected at admission. - if let Some(assistant) = receipt.assistant_event.as_ref() { - if let Err(error) = state.mem.project_console_message(assistant).await { - tracing::error!("Failed to project assistant session turn: {error}"); - return Err("Failed to persist assistant response".to_string()); - } - } - } else { - let record_event = matches!( - turn.envelope.agent_partition.as_ref().map(|partition| &partition.key), - Some(crate::memory::PartitionKey::Named { .. }) - ); - if let Err(error) = - append_console_turn(&state, &turn.envelope, "assistant", &reply, record_event, false).await - { - tracing::error!("Failed to persist assistant session turn: {error}"); - return Err("Failed to persist assistant response".to_string()); - } - } - - let body = if turn.awaiting_approval { - serde_json::json!({ - "status": "awaiting_approval", - "reply": reply, - "decision_id": decision.context.decision_id().to_string(), - }) - } else { - serde_json::to_value(SendMessageResponse { - status: "ok".to_string(), - reply, - }) - .map_err(|error| format!("Failed to encode session reply: {error}"))? - }; - Ok(jobs::JobOutput::new(StatusCode::OK, body)) - }; - let result = child_cleanup - .run(Box::pin(async { - let result: Result = work.await; - result.map_err(anyhow::Error::msg) - })) - .await - .map_err(|error| crate::providers::sanitize_api_error(&error.to_string())); - if let Err(error) = &result { - terminal_guard - .finish_failure(&anyhow::anyhow!(error.clone()), cancellation.is_cancelled()) - .await - .map_err(|_| { - format!( - "Console terminal cleanup persistence is unconfirmed ({})", - terminal_guard.failure_reason() - ) - })?; - } - result -} - -pub async fn get_session_media( - State(state): State, - Query(query): Query, - headers: HeaderMap, -) -> impl IntoResponse { - let token = extract_resource_auth_token(&headers); - if state.pairing.require_pairing() && !state.pairing.is_authenticated(&token) { - return json_error(StatusCode::UNAUTHORIZED, "Unauthorized"); - } - - let requested_path = query.path.trim(); - if requested_path.is_empty() { - return json_error(StatusCode::BAD_REQUEST, "path is required"); - } - - let uploads_root = { - let config = state.config.load_full(); - config.workspace_dir.join(UPLOADS_DIR_NAME) - }; - - let uploads_root = match fs::canonicalize(&uploads_root).await { - Ok(path) => path, - Err(_) => return json_error(StatusCode::NOT_FOUND, "Upload not found"), - }; - - let raw_path = PathBuf::from(requested_path); - if raw_path.is_absolute() { - return json_error(StatusCode::BAD_REQUEST, "Absolute paths are not allowed"); - } - if raw_path - .components() - .any(|c| matches!(c, std::path::Component::ParentDir)) - { - return json_error(StatusCode::BAD_REQUEST, "Path traversal is not allowed"); - } - let candidate_path = uploads_root.join(raw_path); - - let resolved_path = match fs::canonicalize(&candidate_path).await { - Ok(path) => path, - Err(_) => return json_error(StatusCode::NOT_FOUND, "Upload not found"), - }; - - if !resolved_path.starts_with(&uploads_root) { - return json_error(StatusCode::FORBIDDEN, "Access denied"); - } - - let bytes = match fs::read(&resolved_path).await { - Ok(bytes) => bytes, - Err(_) => return json_error(StatusCode::NOT_FOUND, "Upload not found"), - }; - - let content_type = media_content_type_for_path(&resolved_path); - let mut response = Response::new(Body::from(bytes)); - response - .headers_mut() - .insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type)); - response - .headers_mut() - .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); - response -} - -#[cfg(test)] -pub(crate) async fn drive_disabled_engine_console_entry(workspace: &std::path::Path) { - tests::drive_disabled_engine_console_entry(workspace).await; -} - -#[cfg(test)] -pub(crate) async fn drive_search_console_entry(config: crate::config::Config, input: &str) -> anyhow::Result<()> { - tests::drive_search_console_entry(config, input).await -} - -#[cfg(test)] -mod tests { - mod console_recovery; - mod targeting; - use super::*; - use crate::config::Config; - use crate::gateway::{GatewayRateLimiter, IdempotencyStore}; - use crate::hooks::HookManager; - use crate::memory::{ConversationTurn, Memory, MemoryCategory, MemoryEntry}; - use crate::providers::{ChatRequest, ChatResponse, Provider}; - use crate::security::pairing::PairingGuard; - use async_trait::async_trait; - use std::sync::Arc; - use std::time::{Duration, Instant}; - use tokio::sync::broadcast; - - pub(super) async fn drive_search_console_entry(config: Config, input: &str) -> anyhow::Result<()> { - use crate::agent::turn_tests::reachability::{boxed_root_probe, provider, registry}; - let workspace = config.workspace_dir.clone(); - let memory: Arc = Arc::new(crate::memory::SqliteMemory::new(&workspace)?); - let provider: Arc = Arc::from(provider(&config)?); - let mut state = test_app_state_with_config(config.clone(), provider); - state.tools_registry = registry(&config, Arc::clone(&memory)); - state.mem = memory; - state.hooks = Arc::new(HookManager::new(workspace.clone())); - let cleanup = - crate::runtime::turn_cleanup::CleanupScope::new(None, tokio_util::sync::CancellationToken::new())?; - cleanup - .run(boxed_root_probe(|| async move { - let envelope = console_runtime_envelope_for_workspace( - workspace.to_string_lossy().to_string(), - "prx_search_console", - "console", - "prx_user", - ); - let (runtime, _, _, proof) = console_test_source(&mut state, envelope, input).await; - let _ = run_console_message_job( - runtime, - state, - input.to_owned(), - Vec::new(), - ConsoleTurnSource::Message(proof), - None, - ) - .await - .map_err(anyhow::Error::msg)?; - Ok(()) - })) - .await?; - Ok(()) - } - - pub(super) async fn drive_disabled_engine_console_entry(workspace: &std::path::Path) { - let cleanup = crate::runtime::turn_cleanup::CleanupScope::new(None, tokio_util::sync::CancellationToken::new()) - .expect("test: console engine-off cleanup"); - cleanup - .run(Box::pin(async { - let mut config = Config::default(); - config.workspace_dir = workspace.to_owned(); - config.config_path = workspace.join("config.toml"); - config.default_provider = Some("ollama".to_owned()); - config.default_model = Some("test-model".to_owned()); - config.providers.models.push( - toml::from_str( - "provider = \"ollama\"\nmodel = \"test-model\"\noperations = [\"chat\"]\nnative_tools = false\n", - ) - .expect("test: console model declaration"), - ); - config.cost.prices.insert( - "ollama/test-model".to_owned(), - crate::config::schema::ModelPricing { - input: 1.0, - output: 1.0, - cache_write: 1.0, - cache_read: 1.0, - }, - ); - let captured = Arc::new(CapturingProvider::default()); - let provider: Arc = captured.clone(); - let mut state = test_app_state_with_config(config, provider); - let envelope = console_runtime_envelope_for_workspace( - workspace.to_string_lossy().to_string(), - "console-engine-off", - "console", - "prx_user", - ); - let (runtime, _, _, proof) = console_test_source(&mut state, envelope, "hello").await; - run_console_message_job( - runtime, - state, - "hello".to_string(), - Vec::new(), - ConsoleTurnSource::Message(proof), - None, - ) - .await.map_err(anyhow::Error::msg)?; - assert_eq!(captured.requests.lock().len(), 1, "test: console provider called once"); - Ok::<(), anyhow::Error>(()) - })) - .await - .expect("test: console engine-off entry"); - } - - #[test] - fn console_error_kind_never_carries_error_text() { - const MARKER: &str = "PRIVATE-STORED-MARKER"; - let decode = serde_json::from_str::(&format!("\"{MARKER}\"")) - .expect_err("test: a string is not a valid integer capsule field"); - assert!( - decode.to_string().contains(MARKER), - "the fixture must reproduce a decode error that quotes stored text" - ); - let error = anyhow::Error::from(decode).context(format!("recovery scan failed for {MARKER}")); - assert!( - format!("{error:#}").contains(MARKER), - "the unrestricted chain carries the marker" - ); - let kind = console_error_kind(&error); - assert_eq!( - kind, "decode", - "a serde failure anywhere in the chain is a decode failure" - ); - assert!(!kind.contains(MARKER), "the logged category must not carry error text"); - - let untyped = anyhow::anyhow!("untyped failure quoting {MARKER}"); - assert_eq!( - console_error_kind(&untyped), - "other", - "an untyped error is reported by a static category only" - ); - let conflict = anyhow::Error::from(crate::runtime::ingress_recovery::AlreadyAccepted).context(MARKER); - assert_eq!( - console_error_kind(&conflict), - "conflict", - "a typed conflict keeps its category under added context" - ); - let io = anyhow::Error::from(std::io::Error::other(MARKER)); - assert_eq!(console_error_kind(&io), "io", "an I/O failure is reported as io"); - } - - #[test] - fn console_runtime_envelope_preserves_session_channel_and_sender() { - let envelope = console_runtime_envelope_for_workspace("workspace", "signal_alice", "signal", "alice"); - let scope = envelope.message_scope(); - - assert_eq!(scope.source, "console"); - assert_eq!(scope.session_key.as_deref(), Some("signal_alice")); - assert_eq!(scope.channel.as_deref(), Some("signal")); - assert_eq!(scope.sender.as_deref(), Some("alice")); - } - - // D4 C5: the console external session_id is NOT canonicalized. The durable - // session_key stays the raw external id (path/list contract value), and no - // legacy_session_key is carried (console persistence/recall stay single-key on - // the external id). This guards against accidentally migrating the console - // durable key the way the gateway *fabric* path was migrated in C4. - #[test] - fn d4_console_session_id_is_kept_legacy_not_canonicalized() { - let session_id = "signal_alice"; - let envelope = console_runtime_envelope_for_workspace("workspace", session_id, "signal", "alice"); - - // Durable write key == external id (no recipient-aware canonical). - assert_eq!(envelope.session_key, session_id); - assert_eq!(envelope.message_scope().session_key.as_deref(), Some(session_id)); - // No legacy key carried -> single-key recall on the external id. - let principal = envelope.memory_principal(); - assert_eq!(principal.session_key.as_deref(), Some(session_id)); - assert_eq!(principal.legacy_session_key, None); - assert_eq!(principal.session_key_candidates(), vec![session_id.to_string()]); - // The canonical derivation differs from the external id; C5 deliberately - // does NOT adopt it for the durable key (would break the path/list id). - assert_ne!(envelope.canonical_session_key(), session_id); - assert_eq!(envelope.canonical_session_key(), "console:signal:alice:-"); - } - - #[derive(Default)] - struct TestMemory; - - #[async_trait] - impl Memory for TestMemory { - fn name(&self) -> &str { - "test" - } - - async fn store( - &self, - _key: &str, - _content: &str, - _category: MemoryCategory, - _session_id: Option<&str>, - ) -> anyhow::Result<()> { - Ok(()) - } - - async fn recall( - &self, - _query: &str, - _limit: usize, - _session_id: Option<&str>, - ) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn get(&self, _key: &str) -> anyhow::Result> { - Ok(None) - } - - async fn list( - &self, - _category: Option<&MemoryCategory>, - _session_id: Option<&str>, - ) -> anyhow::Result> { - Ok(Vec::new()) - } - - async fn forget(&self, _key: &str) -> anyhow::Result { - Ok(false) - } - - async fn count(&self) -> anyhow::Result { - Ok(0) - } - - async fn health_check(&self) -> bool { - true - } - } - - #[derive(Default)] - struct CapturingProvider { - requests: parking_lot::Mutex>>, - } - - #[async_trait] - impl Provider for CapturingProvider { - async fn chat_with_system( - &self, - _system_prompt: Option<&str>, - _message: &str, - _model: &str, - _temperature: f64, - ) -> anyhow::Result { - anyhow::bail!("console runtime should use structured Provider::chat"); - } - - async fn chat( - &self, - request: ChatRequest<'_>, - _model: &str, - _temperature: f64, - ) -> anyhow::Result { - self.requests.lock().push(request.messages.to_vec()); - Ok(ChatResponse { - text: Some("console-runtime-ok".to_string()), - tool_calls: Vec::new(), - reasoning_content: None, - }) - } - } - - struct TestConfigParticipant; - struct TestPreparedConfig; - - impl crate::config::ConfigGenerationParticipant for TestConfigParticipant { - fn name(&self) -> &'static str { - "gateway_sessions_test_runtime" - } - - fn supports_rebuild_field(&self, _field: &str) -> bool { - true - } - - fn supports_controlled_restart_field(&self, _field: &str) -> bool { - true - } - - fn prepares_for_field(&self, _field: &str) -> bool { - true - } - - fn prepare( - &self, - _generation: Arc, - _changed_fields: &[String], - ) -> anyhow::Result> { - Ok(Box::new(TestPreparedConfig)) - } - } - - impl crate::config::PreparedConfigGeneration for TestPreparedConfig { - fn commit(&mut self) -> anyhow::Result<()> { - Ok(()) - } - - fn rollback(&mut self) {} - } - - fn test_app_state(mut config: Config, provider: Arc) -> AppState { - config.default_provider.get_or_insert_with(|| "ollama".to_owned()); - config.default_model.get_or_insert_with(|| "test-model".to_owned()); - test_app_state_with_config(config, provider) - } - - fn test_app_state_with_config(config: Config, provider: Arc) -> AppState { - let model = config.default_model.clone().expect("fixture config model"); - static PARTICIPANT: std::sync::OnceLock> = - std::sync::OnceLock::new(); - let config = crate::config::new_shared(config); - config.register_participant(PARTICIPANT.get_or_init(|| Arc::new(TestConfigParticipant))); - AppState { - rf_streams: Default::default(), - rf_approvals: Default::default(), - config, - provider, - model, - temperature: 0.0, - mem: Arc::new(TestMemory), - auto_save: false, - tools_registry: Arc::new(vec![]), - mcp_tool: None, - turn_runtime: None, - hooks: Arc::new(HookManager::new(std::env::temp_dir())), - webhook_token_hash: None, - webhook_signing_secret: None, - pairing: Arc::new(PairingGuard::new(false, &[])), - trust_forwarded_headers: false, - rate_limiter: Arc::new(GatewayRateLimiter::new(100, 100, 100, 100)), - idempotency_store: Arc::new(IdempotencyStore::new(Duration::from_mins(5), 1000)), - whatsapp: None, - signal: None, - whatsapp_app_secret: None, - linq: None, - linq_signing_secret: None, - nextcloud_talk: None, - nextcloud_talk_webhook_secret: None, - observer: Arc::new(NoopObserver), - start_time: Instant::now(), - gateway_port: 0, - logs_broadcast_tx: broadcast::channel(16).0, - #[cfg(feature = "wasm-plugins")] - plugin_runtime: None, - } - } - - #[tokio::test] - async fn session_creation_route_binds_owner_and_creates_no_message() { - use tower::ServiceExt; - let temp = tempfile::tempdir().unwrap(); - let mut config = Config::default(); - config.workspace_dir = temp.path().to_owned(); - config.autonomy.level = crate::security::AutonomyLevel::Full; - let mut state = test_app_state(config.clone(), Arc::new(CapturingProvider::default())); - let memory = Arc::new(crate::memory::SqliteMemory::new(temp.path()).unwrap()); - state.mem = memory.clone(); - let router = super::super::router(state.clone()).with_state(state.clone()); - let request = |body: &'static str| { - axum::http::Request::builder() - .method("POST") - .uri("/sessions") - .header("content-type", "application/json") - .body(Body::from(body)) - .unwrap() - }; - let response = router.clone().oneshot(request("{}")).await.unwrap(); - assert_eq!(response.status(), StatusCode::CREATED); - let body: serde_json::Value = - serde_json::from_slice(&axum::body::to_bytes(response.into_body(), 8192).await.unwrap()).unwrap(); - let id = body.get("session_id").unwrap().as_str().unwrap(); - let stored = memory.get_conversation_session(id).await.unwrap().unwrap(); - assert_eq!(stored.message_count, 0); - assert_eq!(stored.channel, "console"); - assert_eq!(stored.sender, "api:local"); - assert_eq!(stored.last_message_preview, ""); - assert!(memory.create_conversation_session(id, "api:other").await.is_err()); - assert_eq!( - memory.get_conversation_session(id).await.unwrap().unwrap().sender, - "api:local" - ); - assert_eq!( - router - .oneshot(request(r#"{"owner_id":"api:other"}"#)) - .await - .unwrap() - .status(), - StatusCode::UNPROCESSABLE_ENTITY - ); - config.autonomy.level = crate::security::AutonomyLevel::ReadOnly; - let mut denied = test_app_state(config, Arc::new(CapturingProvider::default())); - denied.mem = memory.clone(); - let response = super::super::router(denied.clone()) - .with_state(denied) - .oneshot(request("{}")) - .await - .unwrap(); - assert_eq!(response.status(), StatusCode::FORBIDDEN); - assert_eq!(memory.list_conversation_sessions(100, 0, None).await.unwrap().len(), 1); - } - - fn console_provider_fixture_config(config: &mut Config, workspace: &std::path::Path, model: &str, endpoint: &str) { - config.workspace_dir = workspace.to_owned(); - config.config_path = workspace.join("config.toml"); - config.default_provider = Some("ollama".to_owned()); - config.default_model = Some(model.to_owned()); - config.cost.prices.insert( - format!("ollama/{model}"), - crate::config::schema::ModelPricing { - input: 1.0, - output: 1.0, - cache_write: 1.0, - cache_read: 1.0, - }, - ); - assert!(matches!(crate::llm::route_decision::usage_cost_resolution( - "ollama", model, 1, 0, 0, 0, &config.cost, - ), crate::llm::route_decision::UsagePrice::Priced(value) if value > 0.0)); - let native_tools = model == CONSOLE_WINDOW_MODEL; - config.providers.models.push( - toml::from_str(&format!( - "provider = \"ollama\"\nmodel = {model:?}\noperations = [\"chat\"]\nnative_tools = {native_tools}\n" - )) - .unwrap(), - ); - let selected = crate::providers::selection::check( - config, - "ollama", - model, - &if native_tools { - crate::providers::catalog::Requirement::chat().with(crate::providers::catalog::Feature::NativeTools) - } else { - crate::providers::catalog::Requirement::chat() - }, - crate::providers::catalog::UnknownPolicy::Invocation, - ) - .unwrap(); - assert_eq!( - selected.verification(), - &crate::providers::catalog::Verification::Verified - ); - crate::agent::agent::native_decision_fixture::configure(config, endpoint).unwrap(); - } - - async fn console_test_source( - state: &mut AppState, - envelope: RuntimeEnvelope, - input: &str, - ) -> ( - Arc, - RuntimeEnvelope, - String, - crate::gateway::turn_source::GatewayTurnProof, - ) { - if state.mem.name() == "test" { - state.mem = - Arc::new(crate::memory::SqliteMemory::new(&state.config.pin().effective.workspace_dir).unwrap()); - } - let runtime = console_test_runtime(state); - let principal = super::super::ApiPrincipal::for_tests(); - let envelope = envelope - .with_run_id(uuid::Uuid::new_v4().to_string()) - .with_config_generation(&runtime.config_generation) - .with_owner_id(principal.owner_id.clone()) - .with_owner_isolation(); - let event_id = append_console_turn(state, &envelope, "user", input, true, false) - .await - .unwrap(); - let proof = crate::gateway::turn_source::GatewaySourceReceipt::console_proof( - state.mem.as_ref(), - &runtime, - &principal, - &envelope, - input, - &event_id, - ) - .await - .unwrap(); - (runtime, proof.envelope().clone(), event_id, proof) - } - - /// The Console turn runtime of `state`: its pinned generation with the - /// production provider binding and a fresh publication slot. - fn console_test_runtime(state: &AppState) -> Arc { - let mut runtime = state.pin_turn_runtime(); - let config = &runtime.config_generation.effective; - let provider_name = config.default_provider.as_deref().unwrap(); - let catalog = crate::providers::selection::catalog_for(config); - let resolved = crate::providers::selection::check_with( - config, - &catalog, - provider_name, - &runtime.model, - crate::providers::selection::credential_for(config, provider_name), - &crate::providers::catalog::Requirement::chat(), - crate::providers::catalog::UnknownPolicy::Invocation, - ) - .unwrap(); - let binding = crate::gateway::turn_source::GatewayProviderBinding::new(runtime.provider.clone(), resolved); - let security = Arc::new(crate::security::SecurityPolicy::from_config( - &config.autonomy, - &config.workspace_dir, - )); - let mutable = Arc::get_mut(&mut runtime).unwrap(); - mutable.provider_binding = Some(Arc::new(binding)); - mutable.publication_slot = - Arc::new(crate::gateway::turn_source::publication_slot::GatewayPublicationSlot::new(security, 0)); - runtime - } - - #[tokio::test] - async fn console_runtime_turn_uses_shared_tool_loop_history() { - let driver = crate::agent::agent::native_decision_fixture::Driver::start_answer() - .await - .unwrap(); - let endpoint = driver.endpoint().to_owned(); - driver - .run(async move { - let tmp = tempfile::tempdir().unwrap(); - let cleanup = - crate::runtime::turn_cleanup::CleanupScope::new(None, tokio_util::sync::CancellationToken::new()) - .unwrap(); - cleanup - .run(Box::pin(async { - let mut config = Config::default(); - console_provider_fixture_config(&mut config, tmp.path(), "test-model", &endpoint); - let provider_impl = Arc::new(CapturingProvider::default()); - let mut state = test_app_state_with_config(config, provider_impl.clone()); - let envelope = console_runtime_envelope_for_workspace( - tmp.path().to_string_lossy().to_string(), - "console-session", - "console", - "prx_user", - ); - let previous_turns = vec![ConversationTurn { - id: 1, - session_key: "console-session".to_string(), - role: "assistant".to_string(), - content: "previous answer".to_string(), - timestamp: "2026-05-27T00:00:00Z".to_string(), - message_id: Some("previous-event".to_string()), - }]; - - let (runtime, _, _, proof) = - console_test_source(&mut state, envelope, "current question").await; - let service = runtime - .publication_slot - .publish(&runtime, &state) - .await - .unwrap() - .clone(); - let cancellation = tokio_util::sync::CancellationToken::new(); - let context = service - .open_issued_turn_context( - &proof, - crate::runtime::turn_context::AgentTurnKind::SingleShot, - &cancellation, - ) - .await - .unwrap(); - let decision = ConsoleDecisionTurn { - service: service.clone(), - context, - advice: None, - proof: &proof, - cancellation, - provider_trace: None, - }; - assert!( - run_console_runtime_turn( - runtime.clone(), - &state, - "different unadmitted input", - Vec::new(), - &decision, - None, - ) - .await - .is_err() - ); - assert!( - provider_impl.requests.lock().is_empty(), - "source mismatch must fail before provider transport" - ); - let turn = run_console_runtime_turn( - runtime, - &state, - "current question", - previous_turns, - &decision, - None, - ) - .await - .unwrap(); - - service - .shutdown(std::time::Instant::now() + Duration::from_secs(2)) - .await; - assert_eq!(turn.reply, "console-runtime-ok"); - let requests = provider_impl.requests.lock(); - assert_eq!(requests.len(), 1); - let history = requests.first().expect("request should be recorded"); - assert_eq!(history.first().map(|m| m.role.as_str()), Some("system")); - assert!( - history - .iter() - .any(|m| m.role == "assistant" && m.content == "previous answer") - ); - assert_eq!(history.last().map(|m| m.role.as_str()), Some("user")); - assert!(history.last().is_some_and(|m| m.content.contains("current question"))); - Ok::<(), anyhow::Error>(()) - })) - .await - .expect("actual fixture decision transport and cleanup ownership"); - }) - .await; - } - - /// A plain Console message uses the default enabled builtin decision plane - /// and reaches the serving provider through the same admitted runtime as a - /// production Console request. - #[tokio::test] - async fn console_plain_message_reaches_the_provider_with_default_causal_config() { - let tmp = tempfile::tempdir().expect("test: tempdir"); - let cleanup = crate::runtime::turn_cleanup::CleanupScope::new(None, tokio_util::sync::CancellationToken::new()) - .expect("test: Console cleanup owner"); - cleanup - .run(Box::pin(async { - let mut config = Config::default(); - config.workspace_dir = tmp.path().to_owned(); - config.config_path = tmp.path().join("config.toml"); - config.default_provider = Some("ollama".to_owned()); - config.default_model = Some("test-model".to_owned()); - config.providers.models.push( - toml::from_str( - "provider = \"ollama\"\nmodel = \"test-model\"\noperations = [\"chat\"]\nnative_tools = false\n", - ) - .expect("test: Console model declaration"), - ); - config.cost.prices.insert( - "ollama/test-model".to_owned(), - crate::config::schema::ModelPricing { - input: 1.0, - output: 1.0, - cache_write: 1.0, - cache_read: 1.0, - }, - ); - assert_eq!( - config.decision_engine, - crate::config::schema::decision_engine::DecisionEngineConfig::default(), - "the Console proof must retain the default decision engine configuration" - ); - - let provider_impl = Arc::new(CapturingProvider::default()); - let mut state = test_app_state_with_config(config, provider_impl.clone()); - let envelope = console_runtime_envelope_for_workspace( - tmp.path().to_string_lossy().to_string(), - "console-plain-session", - "console", - "prx_user", - ); - let input = "hello"; - let (runtime, _, _, proof) = console_test_source(&mut state, envelope, input).await; - let service = runtime.publication_slot.publish(&runtime, &state).await?.clone(); - let cancellation = tokio_util::sync::CancellationToken::new(); - let context = service - .open_issued_turn_context( - &proof, - crate::runtime::turn_context::AgentTurnKind::SingleShot, - &cancellation, - ) - .await?; - let decision = ConsoleDecisionTurn { - service: Arc::clone(&service), - context, - advice: None, - proof: &proof, - cancellation, - provider_trace: None, - }; - let turn = run_console_runtime_turn(runtime, &state, input, Vec::new(), &decision, None).await?; - service - .shutdown(std::time::Instant::now() + Duration::from_secs(2)) - .await; - - assert_eq!(turn.reply, "console-runtime-ok"); - assert_eq!(provider_impl.requests.lock().len(), 1); - Ok::<(), anyhow::Error>(()) - })) - .await - .expect("test: default Console turn and cleanup complete"); - } - - // ── R5 / OQ-23: the Console turn budgets on the model's effective window ── - - const CONSOLE_BULKY_TOOL: &str = "file_read"; - const CONSOLE_BULKY_FILE: &str = "prx-console-window.txt"; - const CONSOLE_BULKY_MARKER: &str = "CONSOLE-BULKY"; - const CONSOLE_WINDOW_MODEL: &str = "narrow-window-model"; - const CONSOLE_WINDOW_PROVIDER: &str = "ollama"; - const CONSOLE_ROUTER_WINDOW: usize = 33_200; - - /// A read-only tool whose output overruns the narrow fixture window but - /// fits the 128,000-token base window and the unbudgeted inline cap. - struct ConsoleBulkyTool { - inner: crate::tools::file_read::FileReadTool, - executions: Arc, - expected: String, - } - - #[async_trait] - impl crate::tools::Tool for ConsoleBulkyTool { - fn name(&self) -> &str { - self.inner.name() - } - fn description(&self) -> &str { - self.inner.description() - } - fn parameters_schema(&self) -> serde_json::Value { - self.inner.parameters_schema() - } - fn tier(&self) -> crate::tools::traits::ToolTier { - self.inner.tier() - } - fn categories(&self) -> &'static [crate::tools::traits::ToolCategory] { - self.inner.categories() - } - fn supports_owner_filesystem(&self) -> bool { - self.inner.supports_owner_filesystem() - } - async fn execute_with_cancellation( - &self, - args: serde_json::Value, - cancellation: Option, - ) -> anyhow::Result { - self.executions.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - let result = self.inner.execute_with_cancellation(args, cancellation).await?; - assert!(result.success, "actual private FileRead must succeed: {result:?}"); - assert_eq!( - result.output, self.expected, - "the full physical file must reach budgeting" - ); - Ok(result) - } - async fn execute(&self, args: serde_json::Value) -> anyhow::Result { - self.execute_with_cancellation(args, None).await - } - } - - /// Native-tool spy: asks for the bulky tool on its first call, answers in - /// text afterwards, and records every request it serves. - #[derive(Default)] - struct ToolRoundSpyProvider { - requests: parking_lot::Mutex>>, - } - - #[async_trait] - impl Provider for ToolRoundSpyProvider { - fn capabilities(&self) -> crate::providers::ProviderCapabilities { - crate::providers::ProviderCapabilities { - native_tool_calling: true, - vision: false, - } - } - - async fn chat_with_system( - &self, - _system_prompt: Option<&str>, - _message: &str, - _model: &str, - _temperature: f64, - ) -> anyhow::Result { - Ok("summary".into()) - } - - async fn chat( - &self, - request: ChatRequest<'_>, - _model: &str, - _temperature: f64, - ) -> anyhow::Result { - let call_index = { - let mut requests = self.requests.lock(); - requests.push(request.messages.to_vec()); - requests.len() - }; - let tool_calls = if call_index == 1 { - vec![crate::providers::ToolCall { - id: "call-console-bulky-1".into(), - name: CONSOLE_BULKY_TOOL.into(), - arguments: serde_json::json!({"path": CONSOLE_BULKY_FILE}).to_string(), - }] - } else { - Vec::new() - }; - Ok(ChatResponse { - text: tool_calls.is_empty().then(|| "done".to_string()), - tool_calls, - reasoning_content: None, - }) - } - } - - /// Base config: the default 128,000-token window (not set explicitly), and - /// a `[[router.models]]` entry that gives the served model a narrow window. - /// Only the effective resolution sees the router entry. The fixture window - /// is large enough for the sealed decision request's existing reservation; - /// the paired payload remains larger than the main-turn share. - fn narrow_router_window_config(workspace: &std::path::Path) -> Config { - let mut config = Config::default(); - config.workspace_dir = workspace.to_path_buf(); - config.default_provider = Some(CONSOLE_WINDOW_PROVIDER.to_string()); - config.default_model = Some(CONSOLE_WINDOW_MODEL.to_string()); - config.agent.compaction = crate::config::AgentCompactionConfig { - mode: crate::config::AgentCompactionMode::Off, - ..crate::config::AgentCompactionConfig::default() - }; - config.router.models = vec![crate::config::RouterModelConfig { - model_id: CONSOLE_WINDOW_MODEL.to_string(), - provider: CONSOLE_WINDOW_PROVIDER.to_string(), - cost_per_million_tokens: 1.0, - max_context: CONSOLE_ROUTER_WINDOW, - reserved_output_tokens: Some(256), - latency_ms: 1_000, - categories: vec!["conversation".to_string()], - elo_rating: 1_000.0, - }]; - config.tool_tiering.always_include = vec![CONSOLE_BULKY_TOOL.to_string()]; - config - } - - /// A Console turn budgets on the served model's effective window, the one - /// the CLI, TUI and webhook budget on (OQ-23 / R5). - /// - /// The base config keeps the 128,000-token default, so a turn budgeted on - /// the base window forwards the whole token-dense tool payload to the - /// follow-up request. The router entry gives the served model a narrower - /// window; budgeted on that, the follow-up must fit it. - /// - /// MUTATION GUARD: pass `Some(&config_snapshot.agent.compaction)` to the - /// loop again and the follow-up request carries the whole payload. - #[tokio::test] - async fn console_turn_budgets_on_the_served_models_effective_window() { - let driver = crate::agent::agent::native_decision_fixture::Driver::start("filesystem") - .await - .unwrap(); - let endpoint = driver.endpoint().to_owned(); - driver - .run(async move { - let tmp = tempfile::tempdir().expect("test: tempdir"); - let cleanup = - crate::runtime::turn_cleanup::CleanupScope::new(None, tokio_util::sync::CancellationToken::new()) - .unwrap(); - cleanup.run(Box::pin(async { - let workspace = tmp.path().join("workspace"); - let private = tmp.path().join("private"); - std::fs::create_dir_all(&workspace).unwrap(); - std::fs::create_dir_all(&private).unwrap(); - let mut config = narrow_router_window_config(&workspace); - console_provider_fixture_config(&mut config, &workspace, CONSOLE_WINDOW_MODEL, &endpoint); - config.config_path = private.join("config.toml"); - let provider_impl = Arc::new(ToolRoundSpyProvider::default()); - // Keep the fixture's existing autonomy; owner isolation still gates - // the actual registered private-filesystem backend independently. - config.autonomy.level = crate::security::AutonomyLevel::Full; - let mut state = test_app_state_with_config(config, provider_impl.clone()); - state.model = CONSOLE_WINDOW_MODEL.into(); - let executions = Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let mut payload = String::with_capacity(47_000); - let mut index = 0usize; - while payload.len() < 47_000 { - use std::fmt::Write as _; - let _ = write!(payload, "{CONSOLE_BULKY_MARKER}-{index}-갇걇겇곇괇굇궇귇긇깇꺇껇꼇꽇꾇꿇뀇끇낇냇넇녇놇뇇 "); - index += 1; - } - assert!(payload.len() < 48_000, "fixture must remain below the native inline cap"); - assert!( - payload.matches(CONSOLE_BULKY_MARKER).count() > 500, - "the base-window mutation must retain enough payload segments to fail" - ); - assert!( - crate::tokens::count::count_tokens(&payload) > 31_000, - "the paired payload must overrun the narrow main-turn window" - ); - let principal = super::super::ApiPrincipal::for_tests(); - let filesystem = crate::tools::owner_filesystem::OwnerFilesystem::open( - &private, workspace.to_string_lossy().as_ref(), &principal.owner_id, &workspace, - ).unwrap(); - let target = filesystem.resolve(CONSOLE_BULKY_FILE).unwrap(); - filesystem.write_authorized(&target, payload.as_bytes()).unwrap(); - let security = Arc::new(crate::security::SecurityPolicy::from_config( - &state.config.pin().effective.autonomy, &workspace, - )); - state.tools_registry = Arc::new(vec![Box::new(ConsoleBulkyTool { - inner: crate::tools::file_read::FileReadTool::new(security, false), - executions: Arc::clone(&executions), expected: payload, - })]); - let envelope = console_runtime_envelope_for_workspace( - workspace.to_string_lossy().to_string(), - "console-window-session", - "console", - "prx_user", - ); - - // Tool publication is not selection authority. Name the actual - // fixture capability in the raw source admitted by the service. - const INPUT: &str = "file_read prx-console-window.txt: summarise the console bulky probe"; - let (runtime, _, _, proof) = - console_test_source(&mut state, envelope, INPUT).await; - let service = runtime.publication_slot.publish(&runtime, &state).await.unwrap().clone(); - let cancellation = tokio_util::sync::CancellationToken::new(); - let context = service - .open_issued_turn_context( - &proof, - crate::runtime::turn_context::AgentTurnKind::SingleShot, - &cancellation, - ) - .await - .expect("bounded actual Console decision"); - let decision = ConsoleDecisionTurn { - service: service.clone(), - context, - advice: None, - proof: &proof, - cancellation, - provider_trace: None, - }; - let turn = run_console_runtime_turn( - runtime, - &state, - INPUT, - Vec::new(), - &decision, - None, - ) - .await - .expect("test: console turn completes"); - service - .shutdown(std::time::Instant::now() + Duration::from_secs(2)) - .await; - assert_eq!(turn.reply, "done"); - assert_eq!( - executions.load(std::sync::atomic::Ordering::SeqCst), - 1, - "the full bulky payload must be physically produced once" - ); - - let requests = provider_impl.requests.lock().clone(); - assert_eq!(requests.len(), 2, "one tool round, then the answer"); - let follow_up = requests.get(1).expect("test: the follow-up request was recorded"); - let payload_occurrences: usize = follow_up - .iter() - .map(|message| message.content.matches(CONSOLE_BULKY_MARKER).count()) - .sum(); - assert!( - payload_occurrences < 500, - "the follow-up request must be budgeted on the model's {CONSOLE_ROUTER_WINDOW}-token window, \ - not the 128,000-token base window; found {payload_occurrences} payload segments" - ); - let follow_up_chars: usize = follow_up.iter().map(|message| message.content.chars().count()).sum(); - assert!( - follow_up_chars < CONSOLE_ROUTER_WINDOW * 4, - "the follow-up request must fit the effective window; it has {follow_up_chars} characters" - ); - assert!( - follow_up.iter().any(|message| message.role == "user" - && message.content.contains("summarise the console bulky probe")), - "the turn's own request must survive the budget (D-011)" - ); - Ok::<(), anyhow::Error>(()) - })).await.expect("actual fixture decision transport and cleanup ownership"); - }) - .await; - } - - /// C2b-2: the console session API returns a tool-schema refusal as a - /// stable code with every refused tool. Before, the job failed with the - /// aggregate clipped to 200 characters, which cut the tool list. - #[tokio::test] - async fn a_console_tool_schema_refusal_returns_a_stable_code_and_the_tools() { - let driver = crate::agent::agent::native_decision_fixture::Driver::start_answer() - .await - .unwrap(); - let endpoint = driver.endpoint().to_owned(); - driver - .run(async move { - let tmp = tempfile::tempdir().unwrap(); - let mut config = Config::default(); - console_provider_fixture_config(&mut config, tmp.path(), "test-model", &endpoint); - let mut state = test_app_state_with_config( - config, - Arc::new(crate::providers::tool_schema_refusal_tests::RefusingProvider), - ); - let envelope = console_runtime_envelope_for_workspace( - tmp.path().to_string_lossy().to_string(), - "console-session", - "console", - "prx_user", - ); - - let (runtime, _, _, proof) = console_test_source(&mut state, envelope, "hello").await; - let output = match run_console_message_job( - runtime, - state, - "hello".to_string(), - Vec::new(), - ConsoleTurnSource::Message(proof), - None, - ) - .await - { - Ok(output) => output, - Err(message) => { - panic!("the refusal must be answered with a stable code, not a failed job: {message}") - } - }; - assert_eq!(output.status, axum::http::StatusCode::INTERNAL_SERVER_ERROR); - assert_eq!( - output.body.get("error"), - Some(&serde_json::json!("tool_schema_refused")), - "{}", - output.body - ); - assert_eq!( - output.body.get("tools"), - Some(&serde_json::json!(["fixture_conditional", "fixture_alternatives"])), - "{}", - output.body - ); - }) - .await; - } - - // ── D-053 / REDACT-TURN: console turns persist no provider secret ── - - /// Answers every structured chat with a reply that echoes a secret. - struct SecretReplyProvider(Arc); - - #[async_trait] - impl Provider for SecretReplyProvider { - async fn chat_with_system( - &self, - _system_prompt: Option<&str>, - _message: &str, - _model: &str, - _temperature: f64, - ) -> anyhow::Result { - anyhow::bail!("console runtime should use structured Provider::chat"); - } - - async fn chat( - &self, - _request: ChatRequest<'_>, - _model: &str, - _temperature: f64, - ) -> anyhow::Result { - self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - let secret = crate::agent::terminal::persistence_probe::PROBE_SECRET; - Ok(ChatResponse { - text: Some(format!("Here is the key {secret} you asked for")), - tool_calls: Vec::new(), - reasoning_content: None, - }) - } - } - - /// Fails every structured chat with an error that echoes a secret. - struct SecretErrorProvider(Arc); - - #[async_trait] - impl Provider for SecretErrorProvider { - async fn chat_with_system( - &self, - _system_prompt: Option<&str>, - _message: &str, - _model: &str, - _temperature: f64, - ) -> anyhow::Result { - anyhow::bail!("console runtime should use structured Provider::chat"); - } - - async fn chat( - &self, - _request: ChatRequest<'_>, - _model: &str, - _temperature: f64, - ) -> anyhow::Result { - self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - let secret = crate::agent::terminal::persistence_probe::PROBE_SECRET; - anyhow::bail!("upstream rejected key {secret}"); - } - } - - /// A console state whose memory is a real SQLite store and whose - /// workspace (cost ledger, skills) is the same tempdir, so everything the - /// turn persists lands under `tmp`. The user turn is recorded first, as - /// `post_session_message` does, and its event id returned. - async fn console_probe_state( - tmp: &tempfile::TempDir, - provider: Arc, - session_id: &str, - endpoint: &str, - ) -> ( - AppState, - Arc, - RuntimeEnvelope, - String, - crate::gateway::turn_source::GatewayTurnProof, - ) { - let mut config = Config::default(); - console_provider_fixture_config(&mut config, tmp.path(), "test-model", endpoint); - let mut state = test_app_state_with_config(config, provider); - state.mem = Arc::new(crate::memory::SqliteMemory::new(tmp.path()).expect("test: sqlite memory")); - let envelope = console_runtime_envelope_for_workspace( - tmp.path().to_string_lossy().to_string(), - session_id, - "console", - "prx_user", - ); - let (runtime, envelope, event_id, proof) = console_test_source(&mut state, envelope, "what is my key?").await; - (state, runtime, envelope, event_id, proof) - } - - /// D-053 / REDACT-TURN probe: drives `run_console_message_job` through the - /// completed `finalize_turn` commit and the assistant `append_console_turn` - /// with a reply that echoes a secret; it must fail before the REDACT-TURN commits. - #[tokio::test] - async fn console_persists_no_secret_from_a_reply() { - let driver = crate::agent::agent::native_decision_fixture::Driver::start_answer() - .await - .unwrap(); - let endpoint = driver.endpoint().to_owned(); - driver - .run(async move { - let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let tmp = tempfile::tempdir().expect("test: tempdir"); - let session_id = "console-probe-reply"; - let (state, runtime, envelope, _, proof) = console_probe_state( - &tmp, - Arc::new(SecretReplyProvider(Arc::clone(&calls))), - session_id, - &endpoint, - ) - .await; - let mem = Arc::clone(&state.mem); - let principal = envelope.memory_principal(); - - // Keep the actual writer/runtime alive through the full file scan. - let retained_runtime = Arc::clone(&runtime); - let service = runtime - .publication_slot - .publish(&runtime, &state) - .await - .unwrap() - .clone(); - let output = run_console_message_job( - runtime, - state, - "what is my key?".to_string(), - Vec::new(), - ConsoleTurnSource::Message(proof), - None, - ) - .await - .expect("test: the console turn completes"); - assert_eq!(output.status, axum::http::StatusCode::OK, "{}", output.body); - - let turns = mem - .list_conversation_turns(&principal, session_id, 50, 0) - .await - .expect("test: list the console turns"); - assert!( - turns - .iter() - .any(|turn| turn.role == "assistant" && turn.content.contains("[REDACTED]")), - "the reply must be persisted as a redacted assistant turn: {turns:?}" - ); - - assert_eq!( - calls.load(std::sync::atomic::Ordering::SeqCst), - 1, - "the controlled provider must actually run once" - ); - retained_runtime - .publication_slot - .cleanup - .drain(tokio::time::Instant::now() + Duration::from_secs(5)) - .await - .expect("Console cleanup must drain before persisted-file inspection"); - assert!( - service.drain_writes(Instant::now() + Duration::from_secs(5)).await, - "actual decision writes must drain before persisted-file inspection" - ); - crate::agent::terminal::persistence_probe::assert_nothing_under_persists_the_probe_secret(tmp.path()); - service.shutdown(Instant::now() + Duration::from_secs(2)).await; - let retirement = Arc::clone(&retained_runtime.publication_slot.cleanup); - drop(retained_runtime); - retirement - .drain(tokio::time::Instant::now() + Duration::from_secs(5)) - .await - .expect("Console runtime retirement must drain before scratch removal"); - }) - .await; - } - - /// D-053 / REDACT-TURN probe: drives `run_console_message_job` into the - /// failed `finalize_turn` commit of `run_console_runtime_turn` with a provider - /// error that echoes a secret; it must fail before the REDACT-TURN commits. - #[tokio::test] - async fn console_persists_no_secret_from_a_provider_error() { - let driver = crate::agent::agent::native_decision_fixture::Driver::start_answer() - .await - .unwrap(); - let endpoint = driver.endpoint().to_owned(); - driver - .run(async move { - let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let tmp = tempfile::tempdir().expect("test: tempdir"); - let (state, runtime, _, _, proof) = console_probe_state( - &tmp, - Arc::new(SecretErrorProvider(Arc::clone(&calls))), - "console-probe-error", - &endpoint, - ) - .await; - - // Keep the actual writer/runtime alive through the full file scan. - let retained_runtime = Arc::clone(&runtime); - let service = runtime - .publication_slot - .publish(&runtime, &state) - .await - .unwrap() - .clone(); - let result = run_console_message_job( - runtime, - state, - "what is my key?".to_string(), - Vec::new(), - ConsoleTurnSource::Message(proof), - None, - ) - .await; - assert!( - result.is_err(), - "the provider failure must fail the console job, not answer it" - ); - - assert_eq!( - calls.load(std::sync::atomic::Ordering::SeqCst), - 1, - "the controlled provider must actually run once" - ); - retained_runtime - .publication_slot - .cleanup - .drain(tokio::time::Instant::now() + Duration::from_secs(5)) - .await - .expect("Console cleanup must drain before persisted-file inspection"); - assert!( - service.drain_writes(Instant::now() + Duration::from_secs(5)).await, - "actual decision writes must drain before persisted-file inspection" - ); - crate::agent::terminal::persistence_probe::assert_nothing_under_persists_the_probe_secret(tmp.path()); - service.shutdown(Instant::now() + Duration::from_secs(2)).await; - let retirement = Arc::clone(&retained_runtime.publication_slot.cleanup); - drop(retained_runtime); - retirement - .drain(tokio::time::Instant::now() + Duration::from_secs(5)) - .await - .expect("Console runtime retirement must drain before scratch removal"); - }) - .await; - } - - /// Gateway authorization reads the active ConfigGeneration, so a config - /// reload that lowers autonomy to ReadOnly flips a previously-allowed mutation - /// to denied without a process restart or a second cached config owner. - #[test] - fn authz_reads_hot_shared_config_after_reload() { - use crate::security::policy::{AutonomyLevel, ResourceRiskLevel}; - - // Start in the default autonomous policy: a low-risk gateway mutation is - // allowed. - let provider: Arc = Arc::new(CapturingProvider::default()); - let state = test_app_state(Config::default(), provider); - assert!( - crate::gateway::api::authorize_resource_mutation( - &state, - "gateway_api:config:update", - ResourceRiskLevel::Low, - ) - .is_ok(), - "default autonomous policy should allow a low-risk mutation" - ); - - // Hot-reload: publish a ReadOnly config into D only. C is intentionally left - // stale to prove authorization no longer depends on it. - let read_only = Config { - autonomy: crate::config::AutonomyConfig { - level: AutonomyLevel::ReadOnly, - ..crate::config::AutonomyConfig::default() - }, - ..Config::default() - }; - state - .config - .apply_runtime_config(read_only, crate::config::ConfigReloadTrigger::Test) - .expect("apply read-only config"); - - // Same call, same risk — now denied because the authz path reads D. - let denied = crate::gateway::api::authorize_resource_mutation( - &state, - "gateway_api:config:update", - ResourceRiskLevel::Low, - ) - .expect_err("ReadOnly autonomy published to SharedConfig must deny the mutation"); - assert_eq!(denied.0, axum::http::StatusCode::FORBIDDEN); - assert!( - denied - .1 - .0 - .get("error") - .and_then(serde_json::Value::as_str) - .unwrap_or_default() - .contains("read-only mode"), - "denial reason should reflect read-only autonomy" - ); - } - - /// D2 / fix 3 regression: `post_config` merges the incoming delta onto the hot - /// SharedConfig (D), NOT the cached C Mutex. We seed D with a hot field value that - /// differs from C, POST an unrelated delta, and assert the hot field SURVIVES — if - /// the merge had used stale C as its base it would silently revert the hot field. - #[tokio::test] - async fn post_config_merge_base_is_hot_shared_config_not_stale_cache() { - use super::super::config::post_config; - - let tmp = tempfile::tempdir().expect("tempdir"); - let config_path = tmp.path().join("config.toml"); - let workspace = tmp.path().join("workspace"); - - // C (cached) base: default temperature, valid config path on disk. - let mut cached = Config::default(); - cached.config_path = config_path.clone(); - cached.workspace_dir = workspace.clone(); - cached.default_temperature = 0.0; - - let provider: Arc = Arc::new(CapturingProvider::default()); - let state = test_app_state(cached, provider); - - // D (hot) holds a DIFFERENT default_temperature — simulating a prior hot - // reload that C has not yet observed. - let mut hot = Config::default(); - hot.config_path = config_path.clone(); - hot.workspace_dir = workspace; - hot.default_temperature = 0.42; - state - .config - .apply_runtime_config(hot, crate::config::ConfigReloadTrigger::Test) - .expect("apply hot config"); - - // POST a delta that does NOT touch default_temperature. - let resp = post_config( - axum::extract::State(state.clone()), - axum::extract::Query(crate::gateway::api::config::ConfigWriteQuery::default()), - axum::http::HeaderMap::new(), - axum::Json(serde_json::json!({ "auto_save": true })), - ) - .await; - assert_eq!(resp.status(), axum::http::StatusCode::OK); - - // The hot value from D survived the merge (would be 0.0 if C were the base). - let after = state.config.load_full(); - assert!( - (after.default_temperature - 0.42).abs() < 1e-9, - "merge base must be D: hot default_temperature should be preserved, got {}", - after.default_temperature - ); - // C is re-synced to D (C == D invariant restored). - assert!((state.config.load_full().default_temperature - 0.42).abs() < 1e-9); - } - - async fn response_json(response: Response) -> serde_json::Value { - let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024) - .await - .expect("test: approval inbox body"); - serde_json::from_slice(&bytes) - .unwrap_or_else(|_| serde_json::json!({ "raw": String::from_utf8_lossy(&bytes).to_string() })) - } - - #[tokio::test] - async fn approval_inbox_disabled_plane_is_conflict() { - let mut config = Config::default(); - config.workspace_dir = std::env::temp_dir(); - // OV-13: approvals are disabled when user-message recording is off. - config.memory.events.record_user_messages = false; - let state = test_app_state(config, Arc::new(CapturingProvider::default())); - let response = super::get_session_approvals( - State(state), - Query(ApprovalInboxQuery { - limit: None, - cursor: None, - }), - axum::Extension(super::super::ApiPrincipal::for_tests()), - ) - .await; - assert_eq!(response.status(), StatusCode::CONFLICT); - let body = response_json(response).await; - assert_eq!( - body.get("error").and_then(serde_json::Value::as_str), - Some("Decision approvals are disabled") - ); - } - - fn pending_event(workspace: &str, owner: &str, session: &str, decision: &str) -> crate::memory::MessageEventInput { - crate::memory::MessageEventInput { - agent_partition: None, - event_id: None, - idempotency_key: Some(format!("decision-approval:{decision}:pending")), - workspace_id: workspace.to_owned(), - owner_id: Some(owner.to_owned()), - source: crate::memory::MessageEventSource::Console, - channel: Some("console".to_owned()), - session_key: Some(session.to_owned()), - parent_session_key: None, - run_id: None, - parent_run_id: None, - agent_id: None, - persona_id: None, - sender: None, - recipient: None, - role: "system".to_owned(), - event_type: "approval.decision.pending".to_owned(), - subject: None, - goal_id: None, - causation_event_id: None, - correlation_id: None, - attempt_id: None, - lease_epoch: None, - config_generation_id: None, - config_source_revision: None, - content: "pending".to_owned(), - raw_payload_json: None, - visibility: crate::memory::MemoryVisibility::Session, - } - } - - #[tokio::test] - async fn approval_inbox_query_returns_only_the_requested_owner() { - let temp = tempfile::tempdir().expect("test: inbox scratch"); - let memory = crate::memory::SqliteMemory::new(temp.path()).expect("test: sqlite"); - let workspace = temp.path().to_string_lossy().to_string(); - memory - .append_message_event(pending_event( - &workspace, - "api:owner-a", - "session-a", - "11111111-1111-4111-8111-111111111111", - )) - .await - .expect("test: owner a event"); - memory - .append_message_event(pending_event( - &workspace, - "api:owner-b", - "session-b", - "22222222-2222-4222-8222-222222222222", - )) - .await - .expect("test: owner b event"); - let rows = memory - .list_owned_message_events_by_type(&workspace, "api:owner-a", "approval.decision.pending", 0, 20) - .await - .expect("test: owner query"); - assert_eq!(rows.len(), 1); - let row = rows.first().expect("test: owner row"); - assert_eq!(row.owner_id.as_deref(), Some("api:owner-a")); - assert_eq!(row.session_key.as_deref(), Some("session-a")); - let foreign = memory - .list_owned_message_events_by_type(&workspace, "api:owner-b", "approval.decision.pending", 0, 20) - .await - .expect("test: foreign query"); - assert_eq!(foreign.len(), 1); - let foreign_row = foreign.first().expect("test: foreign row"); - assert_eq!(foreign_row.session_key.as_deref(), Some("session-b")); - } - - #[tokio::test] - async fn approval_inbox_empty_when_the_owner_has_none() { - let temp = tempfile::tempdir().expect("test: inbox scratch"); - let mut config = Config::default(); - config.workspace_dir = temp.path().to_owned(); - config.config_path = temp.path().join("config.toml"); - config.autonomy.level = crate::security::AutonomyLevel::Supervised; - config.default_provider = Some("ollama".to_owned()); - config.default_model = Some("prx-local-model".to_owned()); - config.providers.models.push( - toml::from_str( - "provider = \"ollama\"\nmodel = \"prx-local-model\"\noperations = [\"chat\"]\nnative_tools = true\ncontext_window = 65536\n", - ) - .expect("test: model catalog"), - ); - crate::providers::selection::check( - &config, - "ollama", - "prx-local-model", - &crate::providers::catalog::Requirement::chat().with(crate::providers::catalog::Feature::NativeTools), - crate::providers::catalog::UnknownPolicy::Invocation, - ) - .expect("test: model resolves"); - let mut state = test_app_state_with_config(config, Arc::new(CapturingProvider::default())); - let memory = Arc::new(crate::memory::SqliteMemory::new(temp.path()).expect("test: sqlite")); - state.mem = memory.clone(); - let mut runtime = state.pin_turn_runtime(); - { - let security = Arc::new(crate::security::SecurityPolicy::from_config( - &runtime.config_generation.effective.autonomy, - &runtime.config_generation.effective.workspace_dir, - )); - let mutable = Arc::get_mut(&mut runtime).expect("test: runtime uniquely owned"); - mutable.publication_slot = - Arc::new(crate::gateway::turn_source::publication_slot::GatewayPublicationSlot::new(security, 0)); - } - let current = Arc::try_unwrap(runtime).unwrap_or_else(|_| panic!("test: runtime uniquely owned")); - state.turn_runtime = Some(Arc::new(crate::gateway::GatewayTurnRuntimeOwner::new( - current, - Arc::clone(&state.config), - Arc::clone(&state.mem), - None, - None, - None, - None, - Arc::clone(&state.hooks), - #[cfg(feature = "wasm-plugins")] - None, - ))); - let runtime = state.pin_turn_runtime(); - let service = runtime - .publication_slot - .publish(&runtime, &state) - .await - .expect("test: decision plane publishes"); - let principal = super::super::ApiPrincipal::for_tests(); - let response = super::get_session_approvals( - State(state.clone()), - Query(ApprovalInboxQuery { - limit: Some(0), - cursor: None, - }), - axum::Extension(principal.clone()), - ) - .await; - assert_eq!(response.status(), StatusCode::OK, "{}", response_json(response).await); - let response = super::get_session_approvals( - State(state.clone()), - Query(ApprovalInboxQuery { - limit: None, - cursor: None, - }), - axum::Extension(principal.clone()), - ) - .await; - let body = response_json(response).await; - assert_eq!( - body.get("approvals") - .and_then(serde_json::Value::as_array) - .map(Vec::len), - Some(0), - "{body}" - ); - assert!( - body.get("next_cursor").is_some_and(serde_json::Value::is_null), - "{body}" - ); - let workspace = state.config.pin().effective.workspace_dir.to_string_lossy().to_string(); - memory - .append_message_event(pending_event( - &workspace, - &principal.owner_id, - "session-own", - "33333333-3333-4333-8333-333333333333", - )) - .await - .expect("test: unsigned own event"); - memory - .append_message_event(pending_event( - &workspace, - "api:someone-else", - "session-foreign", - "44444444-4444-4444-8444-444444444444", - )) - .await - .expect("test: unsigned foreign event"); - let response = super::get_session_approvals( - State(state.clone()), - Query(ApprovalInboxQuery { - limit: None, - cursor: None, - }), - axum::Extension(principal), - ) - .await; - assert_eq!(response.status(), StatusCode::OK); - let body = response_json(response).await; - let rendered = body.to_string(); - assert!(!rendered.contains("session-own"), "{body}"); - assert!(!rendered.contains("session-foreign"), "{body}"); - assert_eq!( - body.get("approvals") - .and_then(serde_json::Value::as_array) - .map(Vec::len), - Some(0), - "{body}" - ); - let _ = service.drain_writes(Instant::now() + Duration::from_secs(5)).await; - let _ = runtime - .publication_slot - .cleanup - .drain(tokio::time::Instant::now() + Duration::from_secs(5)) - .await; - } - - #[tokio::test] - async fn approval_inbox_fail_closed_memory_is_not_conflict() { - let temp = tempfile::tempdir().expect("test: inbox scratch"); - let mut config = Config::default(); - config.workspace_dir = temp.path().to_owned(); - config.config_path = temp.path().join("config.toml"); - config.autonomy.level = crate::security::AutonomyLevel::Supervised; - config.default_provider = Some("ollama".to_owned()); - config.default_model = Some("prx-local-model".to_owned()); - let state = test_app_state_with_config(config, Arc::new(CapturingProvider::default())); - let response = super::get_session_approvals( - State(state), - Query(ApprovalInboxQuery { - limit: None, - cursor: None, - }), - axum::Extension(super::super::ApiPrincipal::for_tests()), - ) - .await; - assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); - let body = response_json(response).await; - let error = body.get("error").and_then(serde_json::Value::as_str).unwrap_or(""); - assert_ne!(error, "Decision approvals are disabled", "{body}"); - assert!(!error.to_ascii_lowercase().contains("disabled"), "{body}"); - } -} -async fn call_approval_action( - state: AppState, - session: String, - id: String, - principal: super::ApiPrincipal, - change: Option, - owner_authenticated: bool, -) -> Response { - use crate::security::approval_ledger::keys::RunCallAuthority; - let authority = match RunCallAuthority::parse_call_id(&id) { - Ok(value) => value, - Err(_) => return json_error(StatusCode::BAD_REQUEST, "Invalid call id"), - }; - let runtime = match state.admit_turn_runtime() { - Ok(runtime) => runtime, - Err(refusal) => return super::provider_not_ready(refusal), - }; - if let Some(response) = approvals_unavailable(&runtime.config_generation.effective, state.mem.as_ref()) { - return response; - } - if change.is_some() - && !owner_authenticated - && let Err(message) = console_decision_control_policy(&runtime.config_generation.effective) - { - return json_error(StatusCode::FORBIDDEN, message); - } - let cancellation = tokio_util::sync::CancellationToken::new(); - let cleanup = - match crate::runtime::turn_cleanup::CleanupScope::new(Some(&runtime.publication_slot.cleanup), cancellation) { - Ok(value) => value, - Err(error) => { - warn_cleanup_refused(&runtime.publication_slot.cleanup, "Console call approval", &error); - return json_error(StatusCode::SERVICE_UNAVAILABLE, "Gateway is draining"); - } - }; - let result = cleanup - .run(Box::pin(async { - let service = runtime.publication_slot.publish(&runtime, &state).await?; - let mut envelope = RuntimeEnvelope::console( - runtime - .config_generation - .effective - .workspace_dir - .to_string_lossy() - .as_ref(), - &session, - ); - envelope.owner_id = Some(principal.owner_id.clone()); - let adapter = service.call_approval_strategy(envelope)?; - let pending = adapter.port.inspect(&principal.owner_id, &session, &authority).await?; - let receipt = match change { - None => { - anyhow::ensure!(!adapter.port.is_rf_decided(&pending).await?, "approval already decided"); - serde_json::to_value(pending.view())? - } - Some(DecisionApprovalChange::Review(approved)) => { - let expires_at = adapter - .port - .review(&principal.owner_id, &session, &authority, approved) - .await?; - serde_json::json!({"decision_id":"", "call_id":id, "approved":approved, - "grant_count":usize::from(approved), "expires_at":expires_at}) - } - Some(DecisionApprovalChange::Revoke) => { - adapter.port.revoke(&principal.owner_id, &session, &authority).await?; - serde_json::json!({"decision_id":"", "call_id":id, "revoked_grants":1}) - } - }; - Ok::<_, anyhow::Error>(receipt) - })) - .await; - result.map_or_else( - |_| { - json_error( - StatusCode::CONFLICT, - "Call approval is unavailable, expired, or already resolved", - ) - }, - |view| Json(view).into_response(), - ) -} +include!("sessions/section_1.rs"); +include!("sessions/section_2.rs"); +include!("sessions/section_3.rs"); diff --git a/src/gateway/api/sessions/mailbox.rs b/src/gateway/api/sessions/mailbox.rs new file mode 100644 index 000000000..73ece083b --- /dev/null +++ b/src/gateway/api/sessions/mailbox.rs @@ -0,0 +1,98 @@ +//! Mailbox turns use the registered receiver's Console policy and provider. +use super::{ + AgentField, AppState, ConsolePendingInput, ConsoleTurnSource, MAX_PAGE_LIMIT, RuntimeEnvelope, TurnTarget, + prepare_target, resolve_target, run_console_message_job_work, +}; +use crate::messaging::runtime::{MessageInput, MessagingRuntime}; +use std::sync::Arc; + +pub(super) fn register( + state: &AppState, + envelope: RuntimeEnvelope, + principal: super::super::ApiPrincipal, +) -> anyhow::Result<()> { + let config = state.config.load_full(); + if config.memory.backend != "sqlite" { + return Ok(()); + } + let runtime = MessagingRuntime::for_config(&config)?; + let address = runtime.address( + &envelope.resolved_owner_id(), + &envelope.session_key, + envelope.agent_id.as_deref().unwrap_or("main"), + ); + let state = state.clone(); + crate::messaging::receiver::register( + runtime, + address, + Arc::new(move |input| { + let state = state.clone(); + let envelope = envelope.clone(); + let principal = principal.clone(); + Box::pin(run(state, envelope, principal, input)) + }), + ) +} +async fn run( + state: AppState, + mut envelope: RuntimeEnvelope, + principal: super::super::ApiPrincipal, + input: MessageInput, +) -> anyhow::Result<()> { + let parent = state + .admit_turn_runtime() + .map_err(|_| anyhow::anyhow!("receiver runtime unavailable"))?; + let runtime = MessagingRuntime::for_config(&parent.config_generation.effective)?; + input.verify(&runtime)?; + anyhow::ensure!( + input.message.to.owner == principal.owner_id && input.message.to.session == envelope.session_key, + "mailbox receiver differs from registered Console owner" + ); + let target = TurnTarget::from_field(AgentField::Text(input.message.to.agent.clone())) + .map_err(|_| anyhow::anyhow!("receiver agent unavailable"))?; + let plan = resolve_target(&parent.config_generation.effective, &target) + .map_err(|_| anyhow::anyhow!("receiver agent unavailable"))?; + let (turn_runtime, target) = if let Some(plan) = plan { + let (runtime, target) = + prepare_target(&parent, &plan).map_err(|_| anyhow::anyhow!("receiver provider unavailable"))?; + (runtime, Some(target)) + } else { + (parent, None) + }; + envelope.run_id = Some(uuid::Uuid::new_v4().to_string()); + envelope.source_message_event_id = input.receipt.adopted_message_event_id.map(|id| id.to_string()); + envelope = envelope.with_config_generation(&turn_runtime.config_generation); + // Only the verified adopted event supplies causation. Content never enters + // the HTTP approval parser or creates an owner-review adapter. + let _permit = crate::runtime::agent_admission::wait( + &turn_runtime.config_generation.effective, + &principal.owner_id, + &input.message.to.agent, + ) + .await?; + let cancellation = tokio_util::sync::CancellationToken::new(); + let ticket = turn_runtime.publication_slot.cleanup.register(cancellation)?; + let pending = ConsolePendingInput { + state: state.clone(), + runtime: turn_runtime.clone(), + principal, + envelope, + ticket, + }; + let (proof, guard) = pending.record(input.text.clone(), None).await?; + let principal = proof.envelope().memory_principal(); + let turns = state + .mem + .list_console_conversation_turns(&principal, &input.message.to.session, MAX_PAGE_LIMIT, 0) + .await?; + let source = ConsoleTurnSource::Admitted { + proof, + guard, + owner_authenticated: false, + }; + run_console_message_job_work(turn_runtime, state, input.text.clone(), turns, source, target) + .await + .map_err(anyhow::Error::msg)?; + drop(input); + Ok(()) +} diff --git a/src/gateway/api/sessions/section_1.rs b/src/gateway/api/sessions/section_1.rs new file mode 100644 index 000000000..a46138321 --- /dev/null +++ b/src/gateway/api/sessions/section_1.rs @@ -0,0 +1,1718 @@ +use super::{AppState, extract_resource_auth_token}; +use crate::agent::document_ingest::DocumentIngestRuntime; +use crate::agent::runtime_prompt::build_runtime_system_prompt; +use crate::agent::turn_contracts::ScopeContext; +use crate::agent::turn_engine::run_turn; +use crate::gateway::jobs; +use crate::memory::MemoryFabric; +use crate::observability::NoopObserver; +use crate::providers::ChatMessage; +use crate::runtime::envelope::RuntimeEnvelope; +use crate::security::policy::ResourceRiskLevel; +use axum::{ + Json, + body::Body, + extract::{FromRequest, Multipart, Path, Query, Request, State}, + http::{HeaderMap, HeaderValue, StatusCode, header}, + response::{IntoResponse, Response}, +}; +use chrono::Utc; +use serde::{Deserialize, Serialize}; +use std::path::{Path as StdPath, PathBuf}; +use tokio::fs; + +const DEFAULT_PAGE_LIMIT: usize = 50; +const MAX_PAGE_LIMIT: usize = 500; +const MAX_UPLOAD_FILES: usize = 10; +const MAX_UPLOAD_FILE_SIZE_BYTES: usize = 20 * 1024 * 1024; +const UPLOADS_DIR_NAME: &str = "uploads"; + +pub(super) use rf_delete::{post_batch_delete, post_message_delete, post_reply_delete}; + +pub(super) use rf_message::{create_route_auth, message_route_auth}; + +pub(super) use rf_replay::{post_run_cancel, rf_job_cancel}; + + +pub(super) use target::TARGET_EXCLUDED_TOOLS; +use target::{ + AgentField, SelectedTurn, TargetError, TargetUnavailable, TargetedTurn, TurnTarget, prepare_target, + resolve_incarnation, resolve_target, +}; + +#[derive(Serialize)] +pub(super) struct SessionSummary { + #[serde(skip_serializing_if = "Option::is_none")] + metadata: Option, + session_id: String, + sender: String, + channel: String, + status: String, + created_at: String, + updated_at: String, + message_count: u64, + last_message_preview: String, +} + +#[derive(Serialize)] +pub(super) struct SessionMessage { + role: String, + content: String, + timestamp: String, + message_id: Option, + /// The agent the row belongs to (`main` or a name), on a caller-keyed + /// session only; a Console session's body keeps its previous shape. + #[serde(skip_serializing_if = "Option::is_none")] + agent: Option, +} + +#[derive(Deserialize)] +pub(super) struct SessionsQuery { + limit: Option, + offset: Option, + channel: Option, + status: Option, + search: Option, +} + +#[derive(Deserialize)] +pub(super) struct SessionMessagesQuery { + limit: Option, + offset: Option, + /// On a caller-keyed session: only the rows of this agent (`main` or a + /// configured name). + agent: Option, +} + +#[derive(Debug, Deserialize)] +pub(super) struct ApprovalInboxQuery { + limit: Option, + cursor: Option, +} + +#[derive(Deserialize)] +pub(super) struct SendMessageRequest { + message: String, + /// Present-or-absent is kept apart from `null`: an omitted field is Main, + /// an explicit `null` is refused. + #[serde(default, deserialize_with = "present_value")] + agent: Option, +} + +fn present_value<'de, D>(deserializer: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + serde_json::Value::deserialize(deserializer).map(Some) +} + +/// The files one multipart request creates. They are removed when the guard +/// drops (a parse error, a refused target, a failed admission, a cancelled +/// request) unless [`UploadGuard::release`] handed them over. +/// +/// Ownership precedes creation: a path is registered with [`UploadGuard::begin`] +/// before the file exists. Every path carries a per-request uuid, so it can only +/// ever name a file this request creates. Creation runs in a blocking worker that +/// outlives a cancelled future, so the guard also publishes an `abandoned` flag +/// that the worker checks right after creating the file: whichever of the +/// worker's create and the guard's drop comes last removes the file. +#[derive(Default)] +struct UploadGuard { + paths: Vec, + abandoned: std::sync::Arc, + released: bool, +} + +impl UploadGuard { + /// Register `path` for cleanup before it is created, and return the flag + /// the creating worker must hand to [`create_upload_file`]. + fn begin(&mut self, path: PathBuf) -> std::sync::Arc { + self.paths.push(path); + std::sync::Arc::clone(&self.abandoned) + } + + /// Settle the outcome of creating `path`. A failed create (including + /// `AlreadyExists`) means this request did not create the file, so the path + /// is unregistered and the guard can never unlink a file it does not own. + fn settle(&mut self, path: &StdPath, created: std::io::Result) -> std::io::Result { + if created.is_err() { + self.paths.retain(|registered| registered != path); + } + created + } + + /// The request was admitted: the files now belong to the turn. + fn release(mut self) { + self.released = true; + self.paths.clear(); + } +} + +impl Drop for UploadGuard { + fn drop(&mut self) { + if self.released { + return; + } + // Publish the abandonment before removing, so a worker that creates its + // file after the removal below sees the flag and removes it itself. + self.abandoned.store(true, std::sync::atomic::Ordering::SeqCst); + for path in self.paths.drain(..) { + match std::fs::remove_file(&path) { + Ok(()) => {} + // Never created, or already removed by its worker. + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => { + tracing::warn!(error = %error, "Failed to remove an upload of an unadmitted request"); + } + } + } + } +} + +/// Exclusively create an upload file. If the owning guard was abandoned +/// meanwhile (the request was cancelled while this worker was running), the +/// file is removed again instead of being orphaned. +fn create_upload_file(path: &StdPath, abandoned: &std::sync::atomic::AtomicBool) -> std::io::Result { + let file = std::fs::OpenOptions::new().write(true).create_new(true).open(path)?; + if abandoned.load(std::sync::atomic::Ordering::SeqCst) { + if let Err(error) = std::fs::remove_file(path) + && error.kind() != std::io::ErrorKind::NotFound + { + tracing::warn!(error = %error, "Failed to remove an upload of an abandoned request"); + } + return Err(std::io::Error::new( + std::io::ErrorKind::Interrupted, + "upload request was abandoned", + )); + } + Ok(file) +} + +/// A parsed message request. `uploads` are the files already stored for a +/// multipart request; they are removed again unless the request is admitted. +struct ParsedMessage { + message: String, + agent: AgentField, + uploads: UploadGuard, +} + +#[derive(Deserialize)] +pub(super) struct SessionMediaQuery { + path: String, +} + +#[derive(Serialize)] +pub(super) struct SendMessageResponse { + status: String, + reply: String, +} + +fn matches_session_filters( + session: &crate::memory::ConversationSessionSummary, + status_filter: Option<&str>, + search_filter: Option<&str>, +) -> bool { + let status = derive_session_status(&session.last_message_preview, session.message_count); + if let Some(filter) = status_filter { + if filter != status { + return false; + } + } + + if let Some(filter) = search_filter { + let haystack = format!( + "{}\n{}\n{}\n{}", + session.session_key, session.sender, session.channel, session.last_message_preview + ) + .to_ascii_lowercase(); + if !haystack.contains(filter) { + return false; + } + } + + true +} + +fn derive_session_status(last_message_preview: &str, message_count: u64) -> &'static str { + if message_count == 0 { + "empty" + } else if last_message_preview.trim().is_empty() { + "pending" + } else { + "active" + } +} + +fn normalize_limit(limit: Option) -> usize { + match limit { + Some(0) | None => DEFAULT_PAGE_LIMIT, + Some(value) => value.min(MAX_PAGE_LIMIT), + } +} + +fn normalize_offset(offset: Option) -> usize { + offset.unwrap_or(0) +} + +/// Content-free category of a Console request failure, safe to log. +/// +/// The error chain itself is never logged: a storage or decode error can quote +/// stored input. Only these static names leave this function. +fn console_error_kind(error: &anyhow::Error) -> &'static str { + if error.is::() + || error.is::() + { + return "conflict"; + } + if error.is::() { + return "unauthorized"; + } + for cause in error.chain() { + if cause.is::() { + return "decode"; + } + if cause.is::() || cause.is::() { + return "storage"; + } + if cause.is::() { + return "io"; + } + if cause.is::() { + return "timeout"; + } + } + "other" +} + +/// Logs a cleanup-owner refusal, at most once per throttle interval per owner. +/// +/// A failed owner refuses every request until recovery, so an unthrottled +/// warning would follow the request rate. Only a static category and the static +/// route name are logged. +fn warn_cleanup_refused( + owner: &crate::runtime::turn_cleanup::CleanupTracker, + route: &'static str, + error: &anyhow::Error, +) { + if owner.refusal_log_due() { + tracing::warn!( + error_kind = console_error_kind(error), + route, + "Console request refused by its runtime cleanup owner; repeats are logged at most once per minute" + ); + } +} + +fn json_error(status: StatusCode, message: &str) -> Response { + (status, Json(serde_json::json!({ "error": message }))).into_response() +} + +fn console_runtime_envelope(state: &AppState, session_id: &str, channel: &str, sender: &str) -> RuntimeEnvelope { + let generation = state.config.pin(); + let workspace_id = generation.effective.workspace_dir.to_string_lossy().to_string(); + console_runtime_envelope_for_workspace(workspace_id, session_id, channel, sender) + .with_config_generation(&generation) +} + +/// Build the console runtime envelope for a session. +/// +/// D4 C5 — console keeps its external session_id on the legacy basis. The console +/// `session_id` is a user-visible, external contract value: it is the path +/// parameter (`GET/POST /sessions/{session_id}/...`) and the id returned by the +/// session list. Unlike the gateway *fabric* path (C4), the console durable +/// `session_key` is therefore deliberately NOT canonicalized — doing so would +/// change the path/list id and break the frontend. The envelope passes the raw +/// `session_id` straight through as the durable key (no recipient component) and +/// carries no `legacy_session_key`, so console persistence and recall stay on the +/// single external id. Internal recall could read-merge in the future by setting +/// a legacy key on the principal, but the external id format never changes. +fn console_runtime_envelope_for_workspace( + workspace_id: impl Into, + session_id: &str, + channel: &str, + sender: &str, +) -> RuntimeEnvelope { + RuntimeEnvelope::console(workspace_id, session_id.to_string()) + .with_channel(channel.to_string()) + .with_sender(sender.to_string()) +} + +/// D-037 grants authenticated API tokens full operator access to the selected +/// transcript. This read principal never enters the turn envelope or tool scope. +fn operator_history_principal( + _authenticated: &super::ApiPrincipal, + envelope: &RuntimeEnvelope, +) -> crate::memory::MemoryPrincipal { + let mut principal = envelope.memory_principal(); + principal.owner_id = Some("system:*".to_owned()); + principal.agent_id = Some("system".to_owned()); + principal.require_owner_match = false; + principal +} + +fn history_partition( + envelope: &RuntimeEnvelope, + owner_id: &str, + targeted: Option<&TargetedTurn>, + incarnation: Option<&str>, +) -> Result> { + let key = match targeted { + None => crate::memory::PartitionKey::Main, + Some(turn) => { + let Some(raw) = incarnation else { + return Err(Box::new(json_error( + StatusCode::INTERNAL_SERVER_ERROR, + "Targeted agent incarnation is missing", + ))); + }; + let incarnation = uuid::Uuid::parse_str(raw).map_err(|_| { + // The parse error can quote a character of the stored value, so + // only a static category and the validated agent name are logged. + tracing::warn!( + error_kind = "invalid_uuid", + agent = turn.name.as_str(), + "Targeted agent incarnation is not a valid UUID" + ); + Box::new(json_error( + StatusCode::INTERNAL_SERVER_ERROR, + "Targeted agent incarnation is invalid", + )) + })?; + crate::memory::PartitionKey::Named { + name: turn.name.clone(), + incarnation, + } + } + }; + Ok(crate::memory::AgentPartition { + workspace_id: envelope.workspace_id.clone(), + owner_id: owner_id.to_owned(), + key, + }) +} + +/// OV-13: console turns are recorded, recovered and approved run-keyed only +/// with event recording on and a recovery repository present. +fn console_recordable(config: &crate::config::Config, memory: &dyn crate::memory::Memory) -> bool { + let recording = config.memory.event_recording_config(); + recording.enabled && recording.record_user_messages && memory.recovery_repository().is_some() +} + +/// Run-keyed approvals need recording on and a recovery repository (OV-13). +/// Recording turned off is the operator's choice (409, disabled); a memory +/// backend that keeps no repository fails closed (503), never "disabled". +fn approvals_unavailable(config: &crate::config::Config, memory: &dyn crate::memory::Memory) -> Option { + let recording = config.memory.event_recording_config(); + if !(recording.enabled && recording.record_user_messages) { + return Some(json_error(StatusCode::CONFLICT, "Decision approvals are disabled")); + } + if memory.recovery_repository().is_none() { + return Some(json_error( + StatusCode::SERVICE_UNAVAILABLE, + "Decision approvals are unavailable: the memory backend keeps no recovery repository", + )); + } + None +} + +async fn recover_console_history( + state: &AppState, + runtime: &crate::gateway::TurnRuntimeGeneration, + _authenticated: &super::ApiPrincipal, + session_key: &str, +) -> anyhow::Result<()> { + if !console_recordable(&runtime.config_generation.effective, state.mem.as_ref()) { + return Ok(()); + } + let workspace = runtime.config_generation.effective.workspace_dir.to_string_lossy(); + let cancellation = tokio_util::sync::CancellationToken::new(); + let mut cleanup = None; + let recovery = async { + let mut cursor = 0; + loop { + anyhow::ensure!( + !cancellation.is_cancelled(), + "Console recovery cancelled during shutdown" + ); + let events = state + .mem + .list_console_terminal_events(&workspace, session_key, cursor, 128) + .await?; + if events.is_empty() { + break; + } + for event in events { + anyhow::ensure!( + event.id > cursor + && event.workspace_id == workspace + && event.session_key.as_deref() == Some(session_key) + && event.source == crate::memory::MessageEventSource::Console + && event.event_type == "turn.finalized", + "Console recovery returned an invalid marker" + ); + cursor = event.id; + let payload: serde_json::Value = serde_json::from_str( + event + .raw_payload_json + .as_deref() + .ok_or_else(|| anyhow::anyhow!("Console terminal payload missing"))?, + )?; + if payload.get("decision_id").is_none_or(serde_json::Value::is_null) { + // A stripped marker must not masquerade as a legacy turn + // when a durable decision claim still identifies the run. + let claim = if let Some(run) = event.run_id.as_deref() { + state + .mem + .find_message_event_by_idempotency_key(&workspace, &format!("turn:{run}:decision-claim")) + .await? + } else { + None + }; + if claim.is_none() { + continue; + } + } + if cleanup.is_none() { + cleanup = Some(runtime.publication_slot.cleanup.register(cancellation.clone())?); + } + let terminal_id = event + .run_id + .as_deref() + .filter(|id| !id.is_empty()) + .ok_or_else(|| anyhow::anyhow!("Console terminal run missing"))?; + anyhow::ensure!( + event.idempotency_key.as_deref() == Some(format!("turn:{terminal_id}:final").as_str()), + "Console recovery marker identity changed" + ); + let owner = event + .owner_id + .as_deref() + .filter(|id| !id.is_empty()) + .ok_or_else(|| anyhow::anyhow!("Console terminal owner missing"))?; + let service = runtime.publication_slot.publish(runtime, state).await?; + service + .runtime_holder() + .recovery_scope() + .rejoin_terminal(terminal_id, owner) + .await + .map_err(|error| { + if error + .downcast_ref::() + .is_some() + { + error.context(ConsoleTerminalRefused { + run_id: terminal_id.to_owned(), + }) + } else { + error + } + })?; + } + } + Ok::<(), anyhow::Error>(()) + }; + let outcome = tokio::time::timeout(std::time::Duration::from_secs(30), recovery) + .await + .map_err(|_| anyhow::anyhow!("Console history recovery timed out; retry required")) + .and_then(|result| result); + match outcome { + Ok(()) => { + if let Some(ticket) = cleanup { + ticket.finish(true); + } + Ok(()) + } + Err(error) => { + if let Some(refused) = error.downcast_ref::() { + // Restart verification refuses before any write, so no write of + // this recovery is unconfirmed: the ticket ends confirmed and + // the refusal stays with its session. Store faults, timeouts + // and projection-write failures keep the unfinished ticket, + // which closes the owner until recovery (turn_cleanup). + let reason = error + .downcast_ref::() + .map_or("unspecified", |refusal| refusal.0); + tracing::error!( + run_id = %refused.run_id, + reason, + "Console terminal is not replayable; the refusal is isolated to its session" + ); + if let Some(ticket) = cleanup { + ticket.finish(true); + } + } + Err(error) + } + } +} + +/// A Console terminal that restart verification refused +/// (`TerminalNotReplayable`) during history recovery: an error of that +/// session only, already logged with its run id; admission stays open. +#[derive(Debug)] +struct ConsoleTerminalRefused { + run_id: String, +} + +impl std::fmt::Display for ConsoleTerminalRefused { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(formatter, "Console terminal {} is not replayable", self.run_id) + } +} + +/// The response of a failed history recovery. A session-isolated refusal was +/// logged where it was classified; every other failure is logged here. +fn history_recovery_failed(error: &anyhow::Error) -> Response { + if error.downcast_ref::().is_none() { + tracing::error!(error = %error, "Console history recovery failed"); + } + json_error( + StatusCode::INTERNAL_SERVER_ERROR, + "Console history recovery is incomplete", + ) +} + +async fn append_console_turn( + state: &AppState, + envelope: &RuntimeEnvelope, + role: &str, + content: &str, + record_message_event: bool, + durable_projection: bool, +) -> anyhow::Result { + append_console_turn_with( + state, + envelope, + role, + content, + record_message_event, + durable_projection, + None, + ) + .await +} + +/// An rf `context` input: its user event and its attempt row commit in one +/// transaction (AC-1b2a), then it is projected like any recorded input. +async fn append_admitted_console_turn( + state: &AppState, + envelope: &RuntimeEnvelope, + content: &str, + durable_projection: bool, + admission: crate::memory::RfAdmission, +) -> anyhow::Result { + append_console_turn_with( + state, + envelope, + "user", + content, + true, + durable_projection, + Some(admission), + ) + .await +} + +async fn append_console_turn_with( + state: &AppState, + envelope: &RuntimeEnvelope, + role: &str, + content: &str, + record_message_event: bool, + durable_projection: bool, + admission: Option, +) -> anyhow::Result { + // The console persists its reply twice, as a message event and as the + // transcript turn: both are redacted like the terminal commit (D-053). + let content: std::borrow::Cow<'_, str> = if role == "assistant" { + std::borrow::Cow::Owned(crate::agent::terminal::redact_persisted_text(content)) + } else { + std::borrow::Cow::Borrowed(content) + }; + let event = if record_message_event { + let fabric = MemoryFabric::new(state.mem.clone(), envelope.workspace_id.clone()); + Some(match admission { + _ if role == "assistant" => { + fabric + .record_assistant_message(envelope.message_scope(), &*content) + .await? + } + Some(admission) => { + fabric + .record_admitted_user_message(envelope.message_scope(), &*content, None, admission) + .await? + } + None => { + fabric + .record_inbound_user_message(envelope.message_scope(), &*content, None, None) + .await? + } + }) + } else { + None + }; + if matches!( + envelope.agent_partition.as_ref().map(|partition| &partition.key), + Some(crate::memory::PartitionKey::Named { .. }) + ) && event.is_none() + { + return Err(crate::memory::AgentScopeRefused.into()); + } + if durable_projection { + let event = event + .as_ref() + .ok_or_else(|| anyhow::anyhow!("Console projection requires a recorded event"))?; + state.mem.project_console_message(event).await?; + return Ok(event.event_id.clone()); + } + let owner_id = envelope.resolved_owner_id(); + + state + .mem + .append_conversation_turn( + &envelope.session_key, + envelope.channel.as_deref().unwrap_or("console"), + envelope.sender.as_deref().unwrap_or("console-user"), + role, + &content, + None, + event.as_ref().map(|event| event.event_id.as_str()), + Some(owner_id.as_str()), + envelope.agent_partition.as_ref(), + ) + .await?; + + Ok(event.map_or_else(String::new, |event| event.event_id)) +} + +struct ConsoleTurnResult { + reply: String, + awaiting_approval: bool, + trace: crate::agent::turn_contracts::ToolLoopTrace, + route_decision: crate::llm::route_decision::RouteDecision, + provider_started_at: chrono::DateTime, + history_commit_len: usize, + envelope: RuntimeEnvelope, +} + +struct ConsoleDecisionTurn<'a> { + service: std::sync::Arc, + context: std::sync::Arc, + advice: Option, + proof: &'a crate::gateway::turn_source::GatewayTurnProof, + cancellation: tokio_util::sync::CancellationToken, + provider_trace: Option<( + std::sync::Arc, + std::sync::Arc, + )>, +} + +fn console_route_decision( + runtime: &crate::gateway::TurnRuntimeGeneration, + envelope: &RuntimeEnvelope, + message: &str, +) -> anyhow::Result { + let provider = runtime + .provider_binding + .as_ref() + .ok_or_else(|| anyhow::anyhow!("Console provider binding missing"))?; + Ok(crate::llm::route_decision::RouteDecision::single_candidate_for_context( + provider.provider_name().to_string(), + runtime.model.clone(), + envelope.resolved_owner_id(), + envelope.session_key.clone(), + envelope.source_message_event_id.clone(), + None, + "console_message", + u32::try_from(message.chars().count() / 4).unwrap_or(u32::MAX), + !runtime.tools_registry.is_empty(), + false, + )) +} + +async fn run_console_runtime_turn( + turn_runtime: std::sync::Arc, + state: &AppState, + visible_message: &str, + previous_turns: Vec, + decision: &ConsoleDecisionTurn<'_>, + target: Option<&TargetedTurn>, +) -> anyhow::Result { + decision.proof.verify_runtime_input(&turn_runtime, visible_message)?; + let turn_envelope = decision.proof.envelope().clone(); + // D2: this runtime turn rebuilds a `SecurityPolicy` (below) that gates tool + // side-effects for the turn, so the config snapshot it derives from MUST be the + // pinned TurnRuntimeGeneration, not an independently cached config owner. This + // makes a reloaded autonomy / security.audit take effect for console-driven + // turns without a restart; all non-security fields used for the prompt come from + // the same snapshot, so the turn stays internally consistent. + let mut config_snapshot = (*turn_runtime.config_generation.effective).clone(); + if let Some(target) = target { + // The target's own level (`agent_level`); the same level the target's + // decision slot publishes its tool policy with. + config_snapshot.autonomy.level = target.autonomy; + } + let live_scope = + if let (Some(store), Some(source)) = (state.mem.sync_store(), turn_envelope.source_message_event_id.clone()) { + let owner = turn_envelope.resolved_owner_id(); + crate::runtime::blocking::spawn_blocking(move || store.live_scope(&owner, &source)).await?? + } else { + None + }; + let live = live_scope.map(|scope| { + let wait_secs = target + .and_then(|target| config_snapshot.agents.get(target.name.as_str())) + .map_or(config_snapshot.agent.approval_wait_secs, |agent| { + agent.approval_wait_secs + }); + std::sync::Arc::new(crate::gateway::run_approvals::RunApprovalResolver { + scope, + streams: std::sync::Arc::clone(&state.rf_streams), + approvals: std::sync::Arc::clone(&state.rf_approvals), + cancellation: decision.cancellation.clone(), + wait_secs, + }) as std::sync::Arc + }); + let live_frames = live.as_ref().map(|live| { + live.frames( + &turn_envelope, + &crate::agent::sanitize::known_tool_names(turn_runtime.tools_registry.as_ref()), + ) + }); + let stream_provider = live.is_some() && turn_runtime.provider.supports_streaming(); + let provider_label = turn_runtime + .provider_binding + .as_ref() + .ok_or_else(|| anyhow::anyhow!("Console provider binding missing"))? + .provider_name() + .to_string(); + let native_tools = turn_runtime + .provider + .capabilities_for( + &turn_runtime.model, + if stream_provider { + crate::providers::traits::ProviderRequestMode::Streaming + } else { + crate::providers::traits::ProviderRequestMode::NonStreaming + }, + ) + .native_tool_calling; + let system_prompt = if let Some(target) = target { + // The target's own identity; never the main persona. + target.system_prompt.clone() + } else { + let selected_skills = decision + .service + .agent_prompt_skills(decision.proof, &decision.context)?; + build_runtime_system_prompt(&config_snapshot, &turn_runtime.model, &selected_skills, native_tools) + }; + + let mem_context = crate::agent::context_recall::scoped_recall( + state.mem.as_ref(), + &crate::agent::context_recall::RecallScope::from_envelope(&turn_envelope, &config_snapshot.memory, "private"), + visible_message, + crate::agent::context_recall::RECALL_CONTEXT_BUDGET, + ) + .await; + let enriched_message = if mem_context.preamble.is_empty() { + visible_message.to_string() + } else { + format!("{}{}", mem_context.preamble, visible_message) + }; + + let mut history = Vec::with_capacity(previous_turns.len() + 2); + history.push(ChatMessage::system(system_prompt)); + // stored console turns are neutralised like fresh input + history.extend( + previous_turns + .into_iter() + .map(|turn| crate::agent::turn_contracts::stored_turn_message(turn.role, turn.content)), + ); + history.push(crate::agent::turn_contracts::inbound_user_message(&enriched_message)); + + // D2 / FIX-P1-31: build via the shared `build_security_policy` helper so this + // per-turn gateway authz site cannot drift from (or forget) the audit-config + // wiring — construction is byte-for-byte identical to the former local + // `from_config(&autonomy, &workspace_dir)` + audit-config of `security.audit`. + // `config_snapshot` is already the hot SharedConfig (D) snapshot (see above), so + // a reloaded autonomy / security.audit gates this console turn without a restart. + let security = crate::runtime::bootstrap::build_security_policy(&config_snapshot); + let scope_owner_id = turn_envelope.resolved_owner_id(); + let scope_ctx = ScopeContext { + policy: security.as_ref(), + sender: turn_envelope.sender.as_deref().unwrap_or("console-user"), + channel: turn_envelope.channel.as_deref().unwrap_or("console"), + chat_type: "private", + chat_id: &turn_envelope.session_key, + session_key: Some(&turn_envelope.session_key), + owner_id: Some(&scope_owner_id), + owner_isolated: turn_envelope.owner_isolated, + topic_id: turn_envelope.topic_id.as_deref(), + task_id: turn_envelope.resolved_task_id(), + source_message_event_id: turn_envelope.source_message_event_id.as_deref(), + config_generation_id: turn_envelope.config_generation_id, + config_source_revision: turn_envelope.config_source_revision.as_deref(), + }; + let noop_observer = NoopObserver; + + let route_decision = match &decision.provider_trace { + Some((_, route)) => route.as_ref().clone(), + None => console_route_decision(&turn_runtime, &turn_envelope, visible_message)?, + }; + // OQ-23 / R5: budget on the *effective* window of the model this turn + // serves (the operator/discovery/catalog model limits and + // `reserved_output_tokens`), with the same arguments the CLI, TUI and + // webhook resolve with, so one request is trimmed the same way on every + // surface of this process. + let mut effective_compaction = decision + .service + .effective_compaction(&provider_label, &turn_runtime.model); + effective_compaction.config = decision.context.main_compaction().clone(); + crate::providers::context_window::trace_effective_compaction_resolution(&effective_compaction); + let provider_started_at = chrono::Utc::now(); + let loop_result = run_turn( + &mut history, + crate::agent::turn_request::TurnRequest { + advice: decision.advice.clone(), + channel_name: "console", + scope: Some(&scope_ctx), + mode: crate::agent::turn_contracts::ChatMode::default(), + silent: true, + expose_stay_silent: false, + multimodal: &config_snapshot.multimodal, + schedule: crate::agent::turn_request::TurnSchedule { + read_only_tool_concurrency_window: config_snapshot.agent.read_only_tool_concurrency_window, + priority_scheduling_enabled: config_snapshot.agent.priority_scheduling_enabled, + low_priority_tool_names: config_snapshot.agent.low_priority_tools.clone(), + }, + compaction: Some(&effective_compaction.config), + decision: crate::agent::turn_request::TurnDecision { + service: &decision.service, + context: &decision.context, + runtime: decision.context.runtime(), + proof: decision.proof, + }, + }, + crate::agent::turn_request::TurnServices { + provider: turn_runtime.provider.as_ref(), + provider_name: &provider_label, + model: &turn_runtime.model, + temperature: turn_runtime.temperature, + tools_registry: std::sync::Arc::clone(&turn_runtime.tools_registry), + observer: &noop_observer, + hooks: state.hooks.as_ref(), + approval: None, + approval_resolver: None, + runtime_adapter: Some(crate::agent::turn_contracts::ToolLoopRuntimeAdapter { + live_frames, + guarded_delivery: false, + provider_trace: decision + .provider_trace + .as_ref() + .map(|(trace, _)| std::sync::Arc::clone(trace)), + events: None, + stream_provider, + tool_execution_service: None, + tool_execution_context: { + let mut context = crate::tools::ToolExecutionContext::new(turn_envelope.clone(), "private") + .with_dispatch_origin(crate::tools::DispatchOrigin::ModelTurn); + context.live_turn = live + .as_ref() + .map(|live| crate::agent::live_frames::LiveTurnRef(std::sync::Arc::clone(live))); + if target.is_some() && live.is_none() { + // Until MA-04 a targeted call that needs approval ends + // denied: no durable ledger route, no pending decision. + context.with_pending_approval_denied() + } else { + context.with_approval_ledger(decision.service.execution_approval_ledger()) + } + .with_chat_id(&turn_envelope.session_key) + }, + allowed_tool_names: None, + }), + memory: crate::agent::turn_request::ToolLoopMemory::new( + &state.mem, + &config_snapshot.workspace_dir, + Some( + DocumentIngestRuntime::from_envelope(state.mem.clone(), &turn_envelope) + .with_source_message_event_id(turn_envelope.source_message_event_id.clone()), + ), + ) + .with_event_fabric( + MemoryFabric::new(state.mem.clone(), turn_envelope.workspace_id.clone()) + .with_event_recording(config_snapshot.memory.event_recording_config()), + ) + .with_request_event_scope(turn_envelope.message_scope()), + }, + crate::agent::turn_request::TurnDelivery { + cancellation: Some(decision.cancellation.clone()), + on_delta: None, + on_tool_call: None, + }, + ) + .await; + let (outcome, trace) = loop_result?; + let awaiting_approval = matches!( + &outcome, + crate::agent::turn_contracts::ToolLoopOutcome::AwaitingApproval { .. } + ); + let reply = outcome.into_text(); + anyhow::ensure!( + trace.execution_trace.as_ref() == Some(&decision.context.terminal_execution_trace()), + "console execution trace differs from owning decision" + ); + Ok(ConsoleTurnResult { + reply, + awaiting_approval, + trace, + route_decision, + provider_started_at, + history_commit_len: history.len(), + envelope: turn_envelope, + }) +} + +fn sanitize_upload_filename(raw_name: &str) -> String { + let file_name = StdPath::new(raw_name) + .file_name() + .and_then(|value| value.to_str()) + .unwrap_or("upload.bin"); + + let mut sanitized = file_name + .chars() + .map(|ch| { + if ch.is_ascii_alphanumeric() || ch == '.' || ch == '-' || ch == '_' { + ch + } else { + '_' + } + }) + .collect::(); + + if sanitized.is_empty() { + sanitized.push_str("upload.bin"); + } + if sanitized.len() > 120 { + sanitized.truncate(120); + } + + sanitized +} + +fn has_extension(file_name: &str, candidates: &[&str]) -> bool { + let lower = file_name.to_ascii_lowercase(); + candidates + .iter() + .any(|candidate| lower.ends_with(candidate.trim_start_matches('*'))) +} + +fn is_image_upload(content_type: &str, file_name: &str) -> bool { + content_type.starts_with("image/") + || has_extension( + file_name, + &[ + ".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".svg", ".heic", ".heif", + ], + ) +} + +fn is_video_upload(content_type: &str, file_name: &str) -> bool { + content_type.starts_with("video/") + || has_extension(file_name, &[".mp4", ".webm", ".mov", ".m4v", ".avi", ".mkv", ".ogg"]) +} + +fn media_content_type_for_path(path: &StdPath) -> &'static str { + let lower = path + .extension() + .and_then(|value| value.to_str()) + .unwrap_or("") + .to_ascii_lowercase(); + + match lower.as_str() { + "png" => "image/png", + "jpg" | "jpeg" => "image/jpeg", + "gif" => "image/gif", + "webp" => "image/webp", + "bmp" => "image/bmp", + "svg" => "image/svg+xml", + "heic" | "heif" => "image/heic", + "mp4" | "m4v" => "video/mp4", + "webm" => "video/webm", + "mov" => "video/quicktime", + "avi" => "video/x-msvideo", + "mkv" => "video/x-matroska", + "ogg" => "video/ogg", + "pdf" => "application/pdf", + "txt" | "md" => "text/plain; charset=utf-8", + "json" => "application/json", + _ => "application/octet-stream", + } +} + +#[allow(clippy::result_large_err)] // the axum `Response` is the error contract of these parsers +async fn parse_json_message(state: &AppState, request: Request) -> Result { + let Json(payload) = Json::::from_request(request, state) + .await + .map_err(|_| json_error(StatusCode::BAD_REQUEST, "Invalid JSON payload"))?; + + let message = payload.message.trim().to_string(); + if message.is_empty() { + return Err(json_error(StatusCode::BAD_REQUEST, "message must not be empty")); + } + + Ok(ParsedMessage { + message, + agent: payload.agent.map_or(AgentField::Omitted, AgentField::from_json), + uploads: UploadGuard::default(), + }) +} + +#[allow(clippy::result_large_err)] +async fn parse_multipart_message(state: &AppState, request: Request) -> Result { + let owner_authenticated = super::owner_authenticated(state, request.headers()); + let mut multipart = Multipart::from_request(request, state) + .await + .map_err(|_| json_error(StatusCode::BAD_REQUEST, "Invalid multipart payload"))?; + + let uploads_root = { + let config = state.config.load_full(); + config.workspace_dir.join(UPLOADS_DIR_NAME) + }; + let mut uploads_root_prepared = false; + + let mut message = String::new(); + let mut agent = AgentField::Omitted; + let mut attachments = Vec::new(); + let mut uploads = UploadGuard::default(); + let mut file_count = 0usize; + + while let Some(field) = multipart + .next_field() + .await + .map_err(|_| json_error(StatusCode::BAD_REQUEST, "Failed to parse multipart form fields"))? + { + let field_name = field.name().unwrap_or_default().to_string(); + match field_name.as_str() { + "message" => { + message = field.text().await.map_err(|_| { + json_error( + StatusCode::BAD_REQUEST, + "Failed to decode message text from multipart payload", + ) + })?; + } + "agent" => { + let text = field.text().await.map_err(|_| { + json_error(StatusCode::BAD_REQUEST, "Failed to decode agent from multipart payload") + })?; + agent = AgentField::Text(text); + } + "files" => { + file_count += 1; + if file_count > MAX_UPLOAD_FILES { + return Err(json_error(StatusCode::BAD_REQUEST, "Too many files (max 10)")); + } + + let original_name = field.file_name().unwrap_or("upload.bin").to_string(); + let safe_name = sanitize_upload_filename(&original_name); + let content_type = field.content_type().unwrap_or("").to_string(); + let bytes = field + .bytes() + .await + .map_err(|_| json_error(StatusCode::BAD_REQUEST, "Failed to read uploaded file content"))?; + + if bytes.len() > MAX_UPLOAD_FILE_SIZE_BYTES { + return Err(json_error( + StatusCode::PAYLOAD_TOO_LARGE, + "File too large (max 20MB per file)", + )); + } + + if !owner_authenticated { + super::authorize_resource_mutation(state, "gateway_api:sessions:upload", ResourceRiskLevel::Low) + .map_err(|error| error.into_response())?; + } + + if !uploads_root_prepared { + fs::create_dir_all(&uploads_root).await.map_err(|error| { + tracing::error!("Failed to create uploads directory: {error}"); + json_error(StatusCode::INTERNAL_SERVER_ERROR, "Failed to prepare uploads directory") + })?; + uploads_root_prepared = true; + } + + // A per-request unique name, created exclusively: concurrent + // requests never share a path, and cleanup never reaches a file + // this request did not create. + let stored_name = format!( + "{}_{}_{}_{}", + Utc::now().timestamp_millis(), + uuid::Uuid::new_v4().simple(), + file_count, + safe_name + ); + let stored_path = uploads_root.join(stored_name); + + let persist_failed = |error: std::io::Error| { + tracing::error!("Failed to persist uploaded file: {error}"); + json_error(StatusCode::INTERNAL_SERVER_ERROR, "Failed to persist uploaded file") + }; + { + use tokio::io::AsyncWriteExt; + // Ownership first: the guard knows the path before the + // blocking worker can create it. + let abandoned = uploads.begin(stored_path.clone()); + let worker_path = stored_path.clone(); + let created = tokio::task::spawn_blocking(move || create_upload_file(&worker_path, &abandoned)) + .await + .map_err(|error| persist_failed(std::io::Error::other(error)))?; + let created = uploads.settle(&stored_path, created).map_err(persist_failed)?; + let mut file = fs::File::from_std(created); + file.write_all(&bytes).await.map_err(persist_failed)?; + file.flush().await.map_err(persist_failed)?; + } + + if is_image_upload(&content_type, &safe_name) { + attachments.push(format!("[IMAGE:{}]", stored_path.display())); + } else if is_video_upload(&content_type, &safe_name) { + attachments.push(format!("[VIDEO:{}]", stored_path.display())); + } else { + attachments.push(format!("[FILE:{}]", stored_path.display())); + } + } + _ => {} + } + } + + let message = message.trim(); + let combined = if attachments.is_empty() { + message.to_string() + } else if message.is_empty() { + attachments.join("\n") + } else { + format!("{message}\n{}", attachments.join("\n")) + }; + + if combined.trim().is_empty() { + return Err(json_error(StatusCode::BAD_REQUEST, "message must not be empty")); + } + + Ok(ParsedMessage { + message: combined, + agent, + uploads, + }) +} + +#[allow(clippy::result_large_err)] +async fn parse_message_from_request(state: &AppState, request: Request) -> Result { + let content_type = request + .headers() + .get(header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .unwrap_or("") + .to_ascii_lowercase(); + + if content_type.contains("multipart/form-data") { + parse_multipart_message(state, request).await + } else { + parse_json_message(state, request).await + } +} + +/// `{}` creates a Console session as before; `{"session_key"}` is the rf +/// get-or-create (AC-1b1). Present-or-absent is kept apart from `null`. +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct CreateSessionRequest { + #[serde(default, deserialize_with = "present_value")] + session_key: Option, +} + +pub async fn post_session( + State(state): State, + axum::Extension(principal): axum::Extension, + headers: HeaderMap, + uri: axum::http::Uri, + Json(body): Json, +) -> Response { + if let Some(key) = body.session_key { + return rf_message::post_keyed_session(&state, &principal, &headers, &uri, key).await; + } + if !super::owner_authenticated(&state, &headers) + && let Err(error) = + super::authorize_resource_mutation(&state, "gateway_api:sessions:create", ResourceRiskLevel::Low) + { + return error.into_response(); + } + let session_id = format!("console-{}", uuid::Uuid::new_v4()); + if let Err(error) = state + .mem + .create_conversation_session(&session_id, &principal.owner_id) + .await + { + tracing::error!(%error, "Failed to create Console session"); + return json_error(StatusCode::INTERNAL_SERVER_ERROR, "Failed to create session"); + } + ( + StatusCode::CREATED, + Json(serde_json::json!({"session_id": session_id, "status":"empty", "message_count":0})), + ) + .into_response() +} + +pub async fn get_sessions( + State(state): State, + Query(query): Query, + headers: axum::http::HeaderMap, + axum::Extension(api_principal): axum::Extension, +) -> impl IntoResponse { + // MA-01h: a paired bearer (the install owner) lists only its own + // sessions, so no preview shows another owner's content. With pairing + // off the listing is unchanged. + let owner_filter = super::owner_authenticated(&state, &headers).then_some(api_principal.owner_id.as_str()); + let limit = normalize_limit(query.limit); + let offset = normalize_offset(query.offset); + let status_filter = query + .status + .as_deref() + .map(str::trim) + .filter(|value| !value.is_empty()) + .map(str::to_ascii_lowercase); + let search_filter = query + .search + .as_deref() + .map(str::trim) + .filter(|value| !value.is_empty()) + .map(str::to_ascii_lowercase); + let fetch_batch = if limit == 0 { + DEFAULT_PAGE_LIMIT + } else { + limit.min(MAX_PAGE_LIMIT) + }; + let mut response = Vec::with_capacity(limit); + let mut source_offset = 0usize; + let mut filtered_offset = 0usize; + + loop { + let listed = match owner_filter { + Some(owner_id) => { + state + .mem + .list_owner_conversation_sessions(owner_id, fetch_batch, source_offset, query.channel.as_deref()) + .await + } + None => { + state + .mem + .list_conversation_sessions(fetch_batch, source_offset, query.channel.as_deref()) + .await + } + }; + let sessions = match listed { + Ok(sessions) => sessions, + Err(error) => { + tracing::error!("Failed to list conversation sessions from DB: {error}"); + return ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({ "error": "Failed to load sessions" })), + ) + .into_response(); + } + }; + + if sessions.is_empty() { + break; + } + + let batch_len = sessions.len(); + for session in sessions { + if !matches_session_filters(&session, status_filter.as_deref(), search_filter.as_deref()) { + continue; + } + + if filtered_offset < offset { + filtered_offset += 1; + continue; + } + + let status = derive_session_status(&session.last_message_preview, session.message_count); + let metadata = if matches!(session.channel.as_str(), "cron" | "xin") { + let memory = std::sync::Arc::clone(&state.mem); + let owner = api_principal.owner_id.clone(); + let key = session.session_key.clone(); + match crate::runtime::blocking::spawn_blocking(move || { + memory + .sync_store() + .map_or(Ok(None), |sync| sync.session_metadata(&owner, &key)) + }) + .await + { + Ok(Ok(metadata)) => metadata, + _ => { + return super::capabilities::coded_error( + StatusCode::SERVICE_UNAVAILABLE, + "storage_unavailable", + "scheduled session metadata unavailable", + ); + } + } + } else { + None + }; + response.push(SessionSummary { + metadata, + session_id: session.session_key, + sender: session.sender, + channel: session.channel, + status: status.to_string(), + created_at: session.created_at, + updated_at: session.updated_at, + message_count: session.message_count, + last_message_preview: session.last_message_preview, + }); + + if response.len() >= limit { + break; + } + } + + if response.len() >= limit || batch_len < fetch_batch { + break; + } + source_offset += batch_len; + } + + Json(response).into_response() +} + +pub async fn get_session_messages( + State(state): State, + Path(session_id): Path, + Query(query): Query, + axum::Extension(api_principal): axum::Extension, +) -> impl IntoResponse { + if rf_message::is_caller_session_key(&session_id) + && let Err(response) = + rf_message::require_session_owner(&state, &session_id, &api_principal.owner_id, false).await + { + return *response; + } + let Some(session) = (match state.mem.get_conversation_session(&session_id).await { + Ok(session) => session, + Err(error) => { + tracing::error!("Failed to load session metadata from DB: {error}"); + return ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({ "error": "Failed to load session" })), + ) + .into_response(); + } + }) else { + // An id in the caller-key grammar names an rf session (Console ids + // start with `console-`, which the grammar excludes): a missing one + // is the coded `404 session_unknown`, like another owner's. + if rf_message::is_caller_session_key(&session_id) { + return rf_message::session_unknown(); + } + return ( + StatusCode::NOT_FOUND, + Json(serde_json::json!({ "error": "Session not found" })), + ) + .into_response(); + }; + + let limit = normalize_limit(query.limit); + let offset = normalize_offset(query.offset); + // Recovery settles turns a ready runtime ran; a runtime standing by for a + // provider credential has run none since it started, and the stored + // history is still served. + if let Ok(runtime) = state.admit_turn_runtime() + && let Err(error) = recover_console_history(&state, &runtime, &api_principal, &session_id).await + { + return history_recovery_failed(&error); + } + if session.channel == crate::memory::CALLER_KEYED_SESSION_CHANNEL { + return rf_message::rf_history(&state, &session, &api_principal, query.agent.as_deref(), limit, offset).await; + } + if matches!(session.channel.as_str(), "cron" | "xin") { + let memory = std::sync::Arc::clone(&state.mem); + let owner = api_principal.owner_id.clone(); + let key = session.session_key.clone(); + let named = crate::runtime::blocking::spawn_blocking(move || { + memory.sync_store().map_or(Ok(false), |sync| { + sync.session_metadata(&owner, &key).map(|metadata| metadata.is_some()) + }) + }) + .await; + match named { + Ok(Ok(true)) => { + return rf_message::rf_history( + &state, + &session, + &api_principal, + query.agent.as_deref().or(Some(session.sender.as_str())), + limit, + offset, + ) + .await; + } + Ok(Ok(false)) => {} + _ => { + return super::capabilities::coded_error( + StatusCode::SERVICE_UNAVAILABLE, + "storage_unavailable", + "scheduled session metadata unavailable", + ); + } + } + } + let principal = operator_history_principal( + &api_principal, + &console_runtime_envelope(&state, &session_id, &session.channel, &session.sender), + ); + let turns = match state + .mem + .list_console_conversation_turns(&principal, &session_id, limit, offset) + .await + { + Ok(turns) => turns, + Err(error) => { + tracing::error!("Failed to load conversation turns from DB: {error}"); + return ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({ "error": "Failed to load session messages" })), + ) + .into_response(); + } + }; + + let response: Vec = turns + .into_iter() + .map(|turn| SessionMessage { + role: turn.role, + content: turn.content, + timestamp: turn.timestamp, + message_id: turn.message_id, + agent: None, + }) + .collect(); + + Json(response).into_response() +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct DecisionApprovalRequest { + approved: bool, +} + +pub(super) async fn get_decision_approval( + State(state): State, + Path((session_id, decision_id)): Path<(String, String)>, + axum::Extension(principal): axum::Extension, +) -> Response { + call_approval_action(state, session_id, decision_id, principal, None, false).await +} + +const INBOX_DEFAULT_LIMIT: usize = 50; +const INBOX_MAX_LIMIT: usize = 100; + +fn normalize_inbox_limit(limit: Option) -> usize { + match limit { + Some(0) | None => INBOX_DEFAULT_LIMIT, + Some(value) => value.min(INBOX_MAX_LIMIT), + } +} + +#[allow(clippy::result_large_err)] // the axum `Response` is the error contract of this parser +fn parse_inbox_cursor(cursor: Option<&str>) -> Result { + let Some(cursor) = cursor.map(str::trim).filter(|value| !value.is_empty()) else { + return Ok(0); + }; + cursor + .parse::() + .ok() + .filter(|id| *id >= 0) + .ok_or_else(|| json_error(StatusCode::BAD_REQUEST, "Invalid approval cursor")) +} + +#[derive(Serialize)] +struct ApprovalInboxItem { + session_id: String, + #[serde(flatten)] + view: crate::security::approval_ledger::view::DecisionApprovalView, +} + +#[derive(Serialize)] +struct ApprovalInboxResponse { + approvals: Vec, + next_cursor: Option, +} + +/// Owner-scoped pending approval inbox. Foreign rows are omitted. +pub(super) async fn get_session_approvals( + State(state): State, + Query(query): Query, + axum::Extension(principal): axum::Extension, +) -> Response { + let runtime = match state.admit_turn_runtime() { + Ok(runtime) => runtime, + Err(refusal) => return super::provider_not_ready(refusal), + }; + if let Some(response) = approvals_unavailable(&runtime.config_generation.effective, state.mem.as_ref()) { + return response; + } + let after_id = match parse_inbox_cursor(query.cursor.as_deref()) { + Ok(id) => id, + Err(response) => return response, + }; + let limit = normalize_inbox_limit(query.limit); + let cancellation = tokio_util::sync::CancellationToken::new(); + let cleanup = + match crate::runtime::turn_cleanup::CleanupScope::new(Some(&runtime.publication_slot.cleanup), cancellation) { + Ok(cleanup) => cleanup, + Err(error) => { + warn_cleanup_refused(&runtime.publication_slot.cleanup, "Console approval inbox", &error); + return json_error(StatusCode::SERVICE_UNAVAILABLE, "Gateway is draining"); + } + }; + let result = cleanup + .run(Box::pin(async { + let service = runtime.publication_slot.publish(&runtime, &state).await?; + let mut envelope = RuntimeEnvelope::console( + runtime + .config_generation + .effective + .workspace_dir + .to_string_lossy() + .as_ref(), + "approval-inbox", + ); + envelope.owner_id = Some(principal.owner_id.clone()); + let adapter = service.call_approval_strategy(envelope)?; + let calls = adapter + .port + .list_pending_calls(&principal.owner_id, after_id, limit) + .await?; + let mut rows = Vec::new(); + use crate::security::approval_ledger::keys::ApprovalAuthority; + for item in calls.items { + let event = service + .memory() + .find_message_event_by_idempotency_key(adapter.port.workspace, &item.authority().pending_key()) + .await? + .ok_or_else(|| anyhow::anyhow!("pending call disappeared"))?; + rows.push(( + event.id, + ApprovalInboxItem { + session_id: item.subject().session_key.clone().unwrap_or_default(), + view: item.view(), + }, + )); + } + // Do not advance past the reader's bounded scan frontier. + let frontier = calls.next_cursor; + if let Some(frontier) = frontier { + rows.retain(|(id, _)| *id <= frontier); + } + rows.sort_by_key(|(id, _)| *id); + let more = rows.len() > limit; + rows.truncate(limit); + let next_cursor = if more { + rows.last().map(|(id, _)| id.to_string()) + } else { + frontier.map(|id| id.to_string()) + }; + Ok::<_, anyhow::Error>(ApprovalInboxResponse { + approvals: rows.into_iter().map(|(_, item)| item).collect(), + next_cursor, + }) + })) + .await; + match result { + Ok(page) => Json(page).into_response(), + Err(error) => { + tracing::warn!(error = %error, "approval inbox failed"); + json_error(StatusCode::SERVICE_UNAVAILABLE, "Approval inbox is unavailable") + } + } +} + +pub(super) async fn post_decision_approval( + State(state): State, + Path((session_id, decision_id)): Path<(String, String)>, + axum::Extension(principal): axum::Extension, + headers: HeaderMap, + Json(request): Json, +) -> Response { + let owner_authenticated = super::owner_authenticated(&state, &headers); + match rf_message::keyed_session(&state, &session_id).await { + Some(true) => { + if !owner_authenticated { + return super::capabilities::coded_error( + StatusCode::UNAUTHORIZED, + "auth_failed", + "paired bearer required", + ); + } + return crate::gateway::run_approvals::decide( + &state, + &principal.owner_id, + &session_id, + &decision_id, + request, + ) + .await; + } + None => { + return super::capabilities::coded_error( + StatusCode::SERVICE_UNAVAILABLE, + "storage_unavailable", + "session lookup failed", + ); + } + Some(false) => {} + } + let Ok(request) = serde_json::from_value::(request) else { + return json_error(StatusCode::UNPROCESSABLE_ENTITY, "invalid approval body"); + }; + call_approval_action( + state, + session_id, + decision_id, + principal, + Some(DecisionApprovalChange::Review(request.approved)), + owner_authenticated, + ) + .await +} + +pub(super) async fn delete_decision_approval( + State(state): State, + Path((session_id, decision_id)): Path<(String, String)>, + axum::Extension(principal): axum::Extension, + headers: HeaderMap, +) -> Response { + let owner_authenticated = super::owner_authenticated(&state, &headers); + call_approval_action( + state, + session_id, + decision_id, + principal, + Some(DecisionApprovalChange::Revoke), + owner_authenticated, + ) + .await +} + +enum DecisionApprovalChange { + Review(bool), + Revoke, +} + +fn console_decision_control_policy(config: &crate::config::Config) -> Result<(), &'static str> { + crate::security::SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir) + .enforce_tool_operation(crate::security::policy::ToolOperation::Act, "console decision control") + .map_err(|_| "Decision control is not permitted by policy") +} diff --git a/src/gateway/api/sessions/section_2.rs b/src/gateway/api/sessions/section_2.rs new file mode 100644 index 000000000..7a9bb7cad --- /dev/null +++ b/src/gateway/api/sessions/section_2.rs @@ -0,0 +1,1060 @@ +pub async fn post_session_message( + State(state): State, + Path(session_id): Path, + request: Request, +) -> impl IntoResponse { + let principal = request.extensions().get::().cloned(); + // The runtime is pinned before the body is read, as before. + let admitted = state.admit_turn_runtime(); + // A message to a caller-keyed session, or a body with an rf field, is an + // rf message (AC-1b1); any other request takes the Console path below, + // unchanged. + let (request, unreadable) = match rf_message::classify(&state, &session_id, request).await { + rf_message::MessageShape::Rf(parts, body) => { + return rf_message::post_rf_message(state, session_id, parts, body, admitted).await; + } + rf_message::MessageShape::Console { request, unreadable } => (request, unreadable), + }; + let Some(api_principal) = principal else { + return json_error(StatusCode::UNAUTHORIZED, "Authenticated API principal missing"); + }; + let turn_runtime = match admitted { + Ok(runtime) => runtime, + Err(refusal) => return super::provider_not_ready(refusal), + }; + if unreadable { + // The body could not be buffered: the JSON parser's own refusal. + return json_error(StatusCode::BAD_REQUEST, "Invalid JSON payload"); + } + let headers = request.headers().clone(); + let owner_authenticated = super::owner_authenticated(&state, &headers); + let async_mode = jobs::wants_async(request.uri().query(), &headers); + let parsed = match parse_message_from_request(&state, request).await { + Ok(parsed) => parsed, + Err(error_response) => return error_response, + }; + let ParsedMessage { + message, + agent, + uploads, + } = parsed; + + let selected = match select_turn_target(&state, turn_runtime, &api_principal, agent, owner_authenticated) { + Ok(selected) => selected, + // A refused target leaves nothing behind: dropping the guard removes + // the files this request created, and only those. + Err(refusal) => return refusal.into_response(), + }; + // The guard stays alive through admission: a missing session, a failed + // history read, closed admission or cancellation removes the files. + submit_console_message( + state, + session_id, + api_principal, + ConsoleSubmission { + selected, + message, + async_mode, + uploads, + owner_authenticated, + rf: None, + }, + ) + .await +} + +/// Why `select_turn_target` refused the request. Each arm is one error type +/// the helper already returned; `IntoResponse` delegates so status, code and +/// body bytes stay unchanged. +#[derive(Debug)] +enum TargetRefusal { + Selector(TargetError), + Forbidden((StatusCode, Json)), + Unavailable(TargetUnavailable), + RegistryMissing, +} + +impl From for TargetRefusal { + fn from(error: TargetError) -> Self { + Self::Selector(error) + } +} + +impl From<(StatusCode, Json)> for TargetRefusal { + fn from(error: (StatusCode, Json)) -> Self { + Self::Forbidden(error) + } +} + +impl From for TargetRefusal { + fn from(error: TargetUnavailable) -> Self { + Self::Unavailable(error) + } +} + +impl IntoResponse for TargetRefusal { + fn into_response(self) -> Response { + match self { + Self::Selector(error) => error.into_response(), + Self::Forbidden(payload) => payload.into_response(), + Self::Unavailable(error) => error.into_response(), + Self::RegistryMissing => json_error(StatusCode::INTERNAL_SERVER_ERROR, "Agent registry is unavailable"), + } + } +} + +/// Resolve the request's `agent` against the pinned runtime generation, +/// before admission, input recording or provider access. +fn select_turn_target( + state: &AppState, + turn_runtime: std::sync::Arc, + principal: &super::ApiPrincipal, + agent: AgentField, + owner_authenticated: bool, +) -> Result { + let target = TurnTarget::from_field(agent)?; + if matches!(target, TurnTarget::Main) { + return Ok(SelectedTurn { + runtime: turn_runtime, + targeted: None, + incarnation: None, + }); + } + if !owner_authenticated { + // A caller who may not post messages learns nothing about which agents exist. + super::authorize_resource_mutation(state, "gateway_api:sessions:message", ResourceRiskLevel::Low)?; + } + let Some(plan) = resolve_target(&turn_runtime.config_generation.effective, &target)? else { + return Ok(SelectedTurn { + runtime: turn_runtime, + targeted: None, + incarnation: None, + }); + }; + if !state.mem.supports_agent_scope() { + return Err(TargetRefusal::Selector(TargetError::BackendUnsupported)); + } + let (runtime, turn) = prepare_target(&turn_runtime, &plan)?; + let registry = state.mem.agent_registry().ok_or(TargetRefusal::RegistryMissing)?; + let incarnation = resolve_incarnation(state, registry, &turn_runtime, &principal.owner_id, &plan)?; + Ok(SelectedTurn { + runtime, + targeted: Some(turn), + incarnation: Some(incarnation), + }) +} + +#[cfg_attr( + test, + expect( + clippy::large_enum_variant, + reason = "Test-only source variant must not add indirection to production admission" + ) +)] +enum ConsoleTurnSource { + #[cfg(test)] + Message(crate::gateway::turn_source::GatewayTurnProof), + Admitted { + proof: crate::gateway::turn_source::GatewayTurnProof, + guard: crate::gateway::turn_source::GatewayAdmissionGuard, + owner_authenticated: bool, + }, +} + +struct ConsolePendingInput { + state: AppState, + runtime: std::sync::Arc, + principal: super::ApiPrincipal, + envelope: RuntimeEnvelope, + ticket: crate::runtime::turn_cleanup::CleanupTicket, +} + +impl ConsolePendingInput { + async fn record( + self, + message: String, + rf_admission: Option, + ) -> anyhow::Result<( + crate::gateway::turn_source::GatewayTurnProof, + crate::gateway::turn_source::GatewayAdmissionGuard, + )> { + let run = self + .envelope + .run_id + .as_deref() + .ok_or_else(|| anyhow::anyhow!("Console input run is missing"))?; + let key = format!("console:{run}:input"); + let recording = self.runtime.config_generation.effective.memory.event_recording_config(); + let fabric = MemoryFabric::new(self.state.mem.clone(), self.envelope.workspace_id.clone()) + .with_event_recording(recording) + .with_ingress_recovery(&self.runtime.config_generation.effective, &self.ticket) + .await?; + let (sender, receiver) = tokio::sync::oneshot::channel(); + tokio::spawn(async move { + let mut ticket = Some(self.ticket); + let mut admission = None; + let operation = async { + let event = match rf_admission { + Some(rf_admission) => { + fabric + .record_admitted_user_message( + self.envelope.message_scope(), + message.clone(), + Some(key.clone()), + rf_admission, + ) + .await? + } + None => { + fabric + .record_inbound_user_message( + self.envelope.message_scope(), + message.clone(), + Some(key.clone()), + None, + ) + .await? + } + }; + anyhow::ensure!( + event.id <= 0 + || (event.idempotency_key.as_deref() == Some(key.as_str()) + && event.workspace_id == self.envelope.workspace_id + && event.owner_id.as_deref() == Some(self.principal.owner_id.as_str())), + "Console input identity changed during persistence" + ); + let event_id = if event.id > 0 { event.event_id.as_str() } else { "" }; + let proof = crate::gateway::turn_source::GatewaySourceReceipt::console_proof( + self.state.mem.as_ref(), + &self.runtime, + &self.principal, + &self.envelope, + &message, + event_id, + ) + .await?; + anyhow::ensure!( + event.id <= 0 + || proof.envelope().source_message_event_id.as_deref() == Some(event.event_id.as_str()), + "Console durable receipt lost its original input" + ); + admission = Some(crate::gateway::turn_source::GatewayAdmissionGuard::new( + &proof, + fabric.clone(), + ticket + .take() + .ok_or_else(|| anyhow::anyhow!("Console input cleanup ticket missing"))?, + None, + )); + if recording.enabled && recording.record_user_messages { + if console_recordable(&self.runtime.config_generation.effective, self.state.mem.as_ref()) { + self.state.mem.project_console_message(&event).await?; + } else { + self.state + .mem + .append_conversation_turn( + &self.envelope.session_key, + self.envelope.channel.as_deref().unwrap_or("console"), + self.envelope.sender.as_deref().unwrap_or("console-user"), + "user", + &message, + None, + Some(&event.event_id), + Some(&self.envelope.resolved_owner_id()), + self.envelope.agent_partition.as_ref(), + ) + .await?; + } + } + Ok::<_, anyhow::Error>(proof) + }; + let result = tokio::time::timeout(std::time::Duration::from_secs(15), operation) + .await + .map_err(|_| anyhow::anyhow!("Console input persistence timed out")) + .and_then(std::convert::identity); + let result = match result { + Ok(proof) => admission + .take() + .map(|guard| (proof, guard)) + .ok_or_else(|| anyhow::anyhow!("Console input owner did not issue a guard")), + // An rf admission refused inside its transaction rolled back: + // nothing was written, so no write is left unconfirmed. + Err(error) if crate::memory::RfAdmissionRefused::of(&error).is_some() => { + if let Some(ticket) = ticket.take() { + ticket.finish(true); + } + Err(error) + } + Err(_error) if fabric.ingress_already_accepted() => { + if let Some(ticket) = ticket.take() { + ticket.finish(true); + } + Err(crate::runtime::ingress_recovery::AlreadyAccepted.into()) + } + Err(error) => { + if admission.is_none() { + let recovery = async { + let event = self + .state + .mem + .find_owned_message_event_by_idempotency_key( + &self.envelope.workspace_id, + &self.principal.owner_id, + &key, + ) + .await? + .ok_or_else(|| anyhow::anyhow!("Console input commit is unconfirmed"))?; + anyhow::ensure!( + event.id > 0 + && !event.event_id.is_empty() + && event.idempotency_key.as_deref() == Some(key.as_str()) + && event.workspace_id == self.envelope.workspace_id + && event.owner_id.as_deref() == Some(self.principal.owner_id.as_str()), + "Console recovery input identity changed" + ); + let proof = crate::gateway::turn_source::GatewaySourceReceipt::console_proof( + self.state.mem.as_ref(), + &self.runtime, + &self.principal, + &self.envelope, + &message, + &event.event_id, + ) + .await?; + anyhow::ensure!( + proof.envelope().source_message_event_id.as_deref() == Some(event.event_id.as_str()), + "Console recovery input is not durable" + ); + Ok::<_, anyhow::Error>(proof) + }; + if let Ok(Ok(proof)) = tokio::time::timeout(std::time::Duration::from_secs(15), recovery).await + && let Some(ticket) = ticket.take() + { + admission = Some(crate::gateway::turn_source::GatewayAdmissionGuard::new( + &proof, fabric, ticket, None, + )); + } + } + if let Some(mut guard) = admission { + let _ = tokio::time::timeout( + std::time::Duration::from_secs(15), + guard.finish_failure(sender.is_closed(), "Console input admission failed"), + ) + .await; + } else if let Some(ticket) = ticket { + ticket.finish(false); + } + Err(error) + } + }; + // A disconnected HTTP request drops the guard carried by this + // response, retaining cleanup ownership even before job launch. + let _ = sender.send(result); + }); + receiver + .await + .map_err(|_| anyhow::anyhow!("Console input owner ended without a receipt"))? + } +} + +/// What one console submission carries into admission. `uploads` rides along +/// so the files are removed unless the input or job is accepted. +struct ConsoleSubmission { + selected: SelectedTurn, + message: String, + async_mode: bool, + uploads: UploadGuard, + /// [`super::owner_authenticated`]; when false, Main's level gates the + /// message and the saved reply as before A4, and the turn is + /// owner-isolated. + owner_authenticated: bool, + /// Set for an rf message turn: its (session, agent) slot, held until its + /// job ends, its run and job ids and its attempt row; it also selects the + /// `{run_id, job_id}` answer. + rf: Option, +} + +async fn submit_console_message( + state: AppState, + session_id: String, + api_principal: super::ApiPrincipal, + submission: ConsoleSubmission, +) -> Response { + let ConsoleSubmission { + selected, + message, + async_mode, + uploads, + owner_authenticated, + rf, + } = submission; + let SelectedTurn { + runtime: turn_runtime, + targeted: target, + incarnation, + } = selected; + tracing::debug!( + agent_incarnation = incarnation.as_deref(), + "console turn target resolved" + ); + let Some(session) = (match state.mem.get_conversation_session(&session_id).await { + Ok(session) => session, + Err(error) => { + tracing::error!("Failed to read session metadata from DB: {error}"); + return ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({ "error": "Failed to load session" })), + ) + .into_response(); + } + }) else { + return ( + StatusCode::NOT_FOUND, + Json(serde_json::json!({ "error": "Session not found" })), + ) + .into_response(); + }; + // Q10: the only place a Console turn's isolation is decided. A paired + // bearer is the install owner and gets the terminal's tool rules at the + // turn's own level; any other caller (pairing off) stays owner-isolated. + // A controlled H2 launch binds only isolated Gateway sources, so it keeps + // isolation. + let full_target = target + .as_ref() + .is_some_and(|target| target.autonomy == crate::security::AutonomyLevel::Full); + let owner_isolated = (!owner_authenticated && !full_target) || turn_runtime.publication_slot.controlled.is_some(); + let run_id = rf + .as_ref() + .map_or_else(|| uuid::Uuid::new_v4().to_string(), |rf| rf.run_id.clone()); + let runtime_envelope = console_runtime_envelope_for_workspace( + turn_runtime + .config_generation + .effective + .workspace_dir + .to_string_lossy() + .to_string(), + &session_id, + &session.channel, + &session.sender, + ) + .with_owner_id(api_principal.owner_id.clone()); + let runtime_envelope = if owner_isolated { + runtime_envelope.with_owner_isolation() + } else { + runtime_envelope + } + .with_run_id(run_id.clone()) + .with_config_generation(&turn_runtime.config_generation); + + if let Err(error) = recover_console_history(&state, &turn_runtime, &api_principal, &session_id).await { + return history_recovery_failed(&error); + } + let mut principal = operator_history_principal(&api_principal, &runtime_envelope); + let partition = match history_partition( + &runtime_envelope, + &api_principal.owner_id, + target.as_ref(), + incarnation.as_deref(), + ) { + Ok(partition) => partition, + Err(response) => return *response, + }; + principal.agent_partition = Some(partition.clone()); + // MA-01b3: the turn's writers stamp from the envelope; reads keep the principal. + let runtime_envelope = runtime_envelope.with_agent_partition(partition); + let turns = match state + .mem + .list_console_conversation_turns(&principal, &session_id, MAX_PAGE_LIMIT, 0) + .await + { + Ok(turns) => turns, + Err(error) => { + tracing::error!("Failed to load conversation history from DB: {error}"); + return ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({ "error": "Failed to load session history" })), + ) + .into_response(); + } + }; + + if !owner_authenticated + && let Err(error) = + super::authorize_resource_mutation(&state, "gateway_api:sessions:message", ResourceRiskLevel::Low) + { + return error.into_response(); + } + + let input_cancellation = tokio_util::sync::CancellationToken::new(); + let ticket = match turn_runtime.publication_slot.cleanup.register(input_cancellation) { + Ok(ticket) => ticket, + Err(error) => { + warn_cleanup_refused( + &turn_runtime.publication_slot.cleanup, + "Console input admission", + &error, + ); + return json_error(StatusCode::SERVICE_UNAVAILABLE, "Console input admission is closed"); + } + }; + let mailbox_principal = api_principal.clone(); + let mailbox_envelope = runtime_envelope.clone(); + let pending = ConsolePendingInput { + state: state.clone(), + runtime: std::sync::Arc::clone(&turn_runtime), + principal: api_principal, + envelope: runtime_envelope, + ticket, + }; + let admission = rf.as_ref().map(|rf| rf.admission.clone()); + let (proof, mut guard) = match pending.record(message.clone(), admission).await { + Ok(admission) => admission, + Err(error) if crate::memory::RfAdmissionRefused::of(&error).is_some() => { + return rf_replay::refused_admission(&state, rf, &error).await; + } + Err(error) if error.is::() => { + return json_error( + StatusCode::CONFLICT, + "Input already accepted; execution was not repeated and outcome remains unconfirmed", + ); + } + Err(error) if error.is::() => { + return ( + StatusCode::CONFLICT, + Json(serde_json::json!({ "error": { "code": "agent_scope_refused" } })), + ) + .into_response(); + } + Err(error) => { + // The chain can quote stored input (a recovery capsule decode error + // does), so only its content-free category and the session id are logged. + tracing::warn!( + error_kind = console_error_kind(&error), + session_id = %session_id, + "Console input persistence failed before admission" + ); + return json_error( + StatusCode::INTERNAL_SERVER_ERROR, + "Console input persistence is unconfirmed", + ); + } + }; + if let Err(error) = mailbox::register(&state, mailbox_envelope, mailbox_principal) { + tracing::warn!(error=%crate::agent::diagnostics::error_class(&error),"Console mailbox registration refused"); + } + + // Establish monitor ownership synchronously, before constructing work that + // cancellation or registry abortion can drop without ever polling. + let (cleanup_sender, cleanup_receiver) = tokio::sync::oneshot::channel(); + if let Err(error) = guard.attach_acknowledgement(cleanup_sender) { + tracing::warn!( + error_kind = console_error_kind(&error), + session_id = %session_id, + "Console input cleanup ownership could not be attached" + ); + return json_error( + StatusCode::INTERNAL_SERVER_ERROR, + "Console input cleanup ownership is unconfirmed", + ); + } + let source = ConsoleTurnSource::Admitted { + proof, + guard, + owner_authenticated, + }; + + // Everything up to here is bounded bookkeeping. What follows is the agent + // turn itself, which has no upper bound — tool chains, sub-agents, and + // compaction can legitimately run for hours, and PRX no longer cuts them off + // on a clock. Awaiting it inside this handler would tie the turn's lifetime + // to the HTTP connection, so a closed tab or a proxy hang-up would destroy a + // turn mid-flight, after its side effects had already begun. It therefore + // runs as a detached job: visible in `prx tasks list`, killable by id, and + // still there when the client comes back. + let settle_state = rf.as_ref().map(|_| state.clone()); + let work = run_console_message_job(turn_runtime, state, message, turns, source, target); + let label = format!("gateway:session_message:{session_id}"); + if let Some(rf) = rf { + let accepted = rf.accepted(); + let (slot_key, job_id) = (rf.slot.key().to_owned(), rf.job_id); + let slot = rf.slot; + let in_flight = rf.in_flight; + let key = rf.admission.key; + // The slot is released exactly when the job's work ends or is dropped. + let job = jobs::submit_run_with_cleanup( + jobs::KIND_SESSION_MESSAGE, + label, + async move { + let _slot = slot; + work.await + }, + Some(cleanup_receiver), + Some((std::sync::Arc::from(run_id.as_str()), job_id)), + ); + // AC-1b2b: the run stays in flight until the job's terminal phase; + // a delete that arrived meanwhile is then applied to its rows. + if let Some(settle_state) = settle_state { + tokio::spawn(async move { + job.finished().await; + drop(in_flight); + rf_delete::settle_deleted(&settle_state, &key.workspace_id, &key.owner_id, &key.session_key).await; + }); + } + if rf_message::attach_job(&slot_key, job_id) + && let Some(work_id) = jobs::work_id_of(job_id) + { + // A cancel by run id arrived while the input was being admitted. + tokio::spawn(crate::runtime::registry::kill(work_id, true)); + } + return accepted; + } + let job = jobs::submit_with_cleanup(jobs::KIND_SESSION_MESSAGE, label, work, Some(cleanup_receiver)); + // The job owns the turn now; hand the uploaded files over with it. + uploads.release(); + + if async_mode { + return (StatusCode::ACCEPTED, Json(job.accepted_body())).into_response(); + } + job.wait().await.into_response() +} + +/// The unbounded half of `POST /sessions/{id}/message`, run as a job. +/// +/// Returns the exact `(status, body)` the synchronous handler used to produce, +/// so waiting clients see no contract change and polling clients see the same +/// payload under `result`. +fn run_console_message_job( + turn_runtime: std::sync::Arc, + state: AppState, + message: String, + turns: Vec, + source: ConsoleTurnSource, + target: Option, +) -> std::pin::Pin> + Send>> { + // Keep the owned Console work out of the generic job submitter's stack. + // Construction does not poll it; the same input guard retains its sender. + Box::pin(run_console_message_job_work( + turn_runtime, + state, + message, + turns, + source, + target, + )) +} + +async fn run_console_message_job_work( + turn_runtime: std::sync::Arc, + state: AppState, + message: String, + turns: Vec, + source: ConsoleTurnSource, + target: Option, +) -> Result { + let (source_proof, input_guard, owner_authenticated) = match source { + #[cfg(test)] + ConsoleTurnSource::Message(proof) => (proof, None, false), + ConsoleTurnSource::Admitted { + proof, + guard, + owner_authenticated, + } => (proof, Some(guard), owner_authenticated), + }; + let runtime_envelope = source_proof.envelope().clone(); + let runtime = + crate::messaging::runtime::MessagingRuntime::for_config(&turn_runtime.config_generation.effective).ok(); + let address = runtime.as_ref().map(|runtime| { + runtime.address( + &runtime_envelope.resolved_owner_id(), + &runtime_envelope.session_key, + runtime_envelope.agent_id.as_deref().unwrap_or("main"), + ) + }); + let _mailbox_gate = if let Some(address) = &address { + Some(crate::messaging::receiver::gate(address).lock_owned().await) + } else { + None + }; + let cancellation = + jobs::current_cancellation().map_or_else(tokio_util::sync::CancellationToken::new, |token| token.child_token()); + let _cancel_guard = cancellation.clone().drop_guard(); + let config = &turn_runtime.config_generation.effective; + let cleanup_ticket = turn_runtime + .publication_slot + .cleanup + .register(cancellation.clone()) + .map_err(|_| "Console turn admission is closed".to_owned())?; + // Register the job's cancellation/acknowledgement owner before releasing + // the HTTP input ticket. This transfer has no await or unowned interval. + let inherited_fabric = input_guard.as_ref().map(|guard| guard.ingress_fabric()); + let admission_acknowledgement = if let Some(input_guard) = input_guard { + let (input_ticket, acknowledgement) = input_guard + .into_terminal_parts() + .map_err(|_| "Console input ownership transfer failed".to_owned())?; + input_ticket.finish(true); + acknowledgement + } else { + jobs::register_terminal_cleanup() + }; + let admission_fabric = inherited_fabric.unwrap_or_else(|| { + MemoryFabric::new(state.mem.clone(), runtime_envelope.workspace_id.clone()) + .with_event_recording(config.memory.event_recording_config()) + }); + let mut admission_guard = crate::gateway::turn_source::GatewayAdmissionGuard::new( + &source_proof, + admission_fabric, + cleanup_ticket, + admission_acknowledgement, + ); + // Prediction transport accounting and later work retain the same owner. + // Register its monitor acknowledgement before the first admission await. + let child_cleanup = match crate::runtime::turn_cleanup::CleanupScope::new( + Some(&turn_runtime.publication_slot.cleanup), + cancellation.child_token(), + ) { + Ok(scope) => scope.with_acknowledgement(jobs::register_terminal_cleanup()), + Err(_) => { + let error = "Console child cleanup admission is closed"; + admission_guard + .finish_failure(cancellation.is_cancelled(), error) + .await + .map_err(|_| "Console admission failure persistence is unconfirmed".to_owned())?; + return Err(error.to_owned()); + } + }; + let decision = { + let proof = &source_proof; + let admission = child_cleanup + .scope_admission(Box::pin(async { + let admitted: Result<_, String> = async { + proof + .verify_runtime_input(&turn_runtime, &message) + .map_err(|error| crate::providers::sanitize_api_error(&error.to_string()))?; + let service = turn_runtime + .publication_slot + .publish(&turn_runtime, &state) + .await + .map_err(|_| "Console decision publication failed".to_owned())?; + let kind = crate::runtime::turn_context::AgentTurnKind::SingleShot; + let context = service + .open_issued_turn_context(proof, kind, &cancellation) + .await + .map_err(|error| crate::providers::sanitize_api_error(&error.to_string()))?; + let advice = service.advisory().analyze_turn(context.runtime(), &cancellation).await; + Ok::<_, String>((service, context, advice)) + } + .await; + admitted.map_err(anyhow::Error::msg) + })) + .await; + let (service, context, advice) = match admission { + Ok(admitted) => admitted, + Err(error) => { + // No future is still polling admission. Close/drain its owned + // attempts before acknowledging the failed input terminal. + let admission_error = crate::providers::sanitize_api_error(&format!("{error:#}")); + let drained = child_cleanup.run(Box::pin(async { Err::<(), _>(error) })).await; + let error = match drained { + Err(error) if error.is::() => format!( + "{admission_error}; Console admission cleanup is unconfirmed: {}", + crate::providers::sanitize_api_error(&format!("{error:#}")), + ), + _ => admission_error, + }; + if admission_guard + .finish_failure(cancellation.is_cancelled(), &error) + .await + .is_err() + { + return Err(format!("{error}; Console admission failure persistence is unconfirmed")); + } + return Err(error); + } + }; + let provider_trace = None; + ConsoleDecisionTurn { + service: std::sync::Arc::clone(service), + provider_trace, + context, + advice, + proof, + cancellation: cancellation.clone(), + } + }; + let (cleanup_ticket, admission_acknowledgement) = admission_guard + .into_terminal_parts() + .map_err(|error| error.to_string())?; + let terminal_guard = crate::gateway::turn_source::publication_slot::GatewayTerminalGuard::new( + cleanup_ticket, + std::sync::Arc::clone(&decision.service), + std::sync::Arc::clone(&decision.context), + MemoryFabric::new(state.mem.clone(), runtime_envelope.workspace_id.clone()), + std::sync::Arc::clone(config), + runtime_envelope.clone(), + admission_acknowledgement, + ) + .map_err(|error| error.to_string())?; + let terminal_guard = if let Some((trace, route)) = &decision.provider_trace { + terminal_guard.with_provider_trace(std::sync::Arc::clone(trace), route.as_ref().clone()) + } else { + terminal_guard + }; + let work = async { + let turn = match run_console_runtime_turn( + std::sync::Arc::clone(&turn_runtime), + &state, + &message, + turns, + &decision, + target.as_ref(), + ) + .await + { + Ok(turn) => turn, + Err(error) => { + // A stable HTTP error response still represents a failed turn. + // Finalize it before returning a successful job transport result. + { + terminal_guard + .finish_failure(&error, cancellation.is_cancelled()) + .await + .map_err(|_| { + format!( + "Console terminal cleanup persistence is unconfirmed ({})", + terminal_guard.failure_reason() + ) + })?; + } + if let Some(tools) = crate::providers::tool_schema_refused_tools(&error) { + // A configuration problem, not a failed job: the caller + // gets a stable code with every refused tool, and the log + // keeps the whole refusal, unclipped. + tracing::error!( + error = %crate::security::redaction::redact_secrets(&format!("{error:#}")), + "Console turn refused before transport: the provider cannot accept some offered tool schemas" + ); + return Ok(jobs::JobOutput::new( + StatusCode::INTERNAL_SERVER_ERROR, + serde_json::json!({ + "error": "tool_schema_refused", + "tools": tools, + "message": "The configured provider cannot accept some of the tool schemas this turn \ + offered, so nothing was sent. The gateway log names the configuration \ + to change.", + }), + )); + } + return Err(crate::providers::sanitize_api_error(&error.to_string())); + } + }; + let reply = turn.reply.clone(); + + if !owner_authenticated + && let Err((status, body)) = crate::gateway::authorize_gateway_config_resource_mutation( + config, + "gateway_api:sessions:assistant_message", + ResourceRiskLevel::Low, + ) + { + { + terminal_guard + .finish_error(&anyhow::anyhow!("Console assistant persistence authorization denied")) + .await + .map_err(|_| { + format!( + "Console terminal cleanup persistence is unconfirmed ({})", + terminal_guard.failure_reason() + ) + })?; + } + return Ok(jobs::JobOutput::new(status, body.0)); + } + + let provider_outcome = crate::agent::terminal::provider_outcome_from_trace( + &turn.route_decision, + turn.provider_started_at, + turn.trace, + ); + let terminal_id = turn + .envelope + .run_id + .clone() + .ok_or_else(|| "Console admitted run missing".to_owned())?; + let terminal_fabric = MemoryFabric::new(state.mem.clone(), turn.envelope.workspace_id.clone()); + let config = &turn_runtime.config_generation.effective; + let terminal_binding = decision + .service + .terminal_binding(&decision.context) + .map_err(|error| error.to_string())?; + let receipt = match crate::gateway::turn_source::publication_slot::commit_terminal( + Some(&terminal_guard), + &terminal_fabric, + crate::agent::terminal::TurnTerminalDraft { + binding: Some(terminal_binding), + terminal_id, + scope: turn.envelope.message_scope(), + status: crate::agent::terminal::TurnTerminalStatus::Completed, + history: Some(crate::agent::terminal::TurnHistoryProjection { + assistant_content: reply.clone(), + history_commit_len: turn.history_commit_len, + }), + history_scope: None, + provider_outcome: Some(provider_outcome), + telemetry: crate::agent::terminal::TurnTerminalTelemetry { + summary: if turn.awaiting_approval { + "console turn awaiting human approval" + } else { + "console turn completed" + } + .to_string(), + started_at: turn.provider_started_at, + finished_at: chrono::Utc::now(), + }, + delivery_intent: crate::agent::terminal::TurnDeliveryIntent::ReturnToCaller, + }, + config, + ) + .await + { + Ok(receipt) => receipt, + Err(error) => { + let reason: crate::runtime::turn_terminal::TerminalPersistReason = terminal_guard.failure_reason(); + tracing::warn!( + reason = %reason, + error = %crate::agent::diagnostics::error_class(&error), + "Failed to commit shared console terminal event" + ); + return Err(format!("Console terminal persistence is unconfirmed ({reason})")); + } + }; + + if console_recordable(config, state.mem.as_ref()) { + // A recorded console turn's transcript is the projection of its + // committed, redacted assistant event, exactly as its input was + // projected at admission. + if let Some(assistant) = receipt.assistant_event.as_ref() { + if let Err(error) = state.mem.project_console_message(assistant).await { + tracing::error!("Failed to project assistant session turn: {error}"); + return Err("Failed to persist assistant response".to_string()); + } + } + } else { + let record_event = matches!( + turn.envelope.agent_partition.as_ref().map(|partition| &partition.key), + Some(crate::memory::PartitionKey::Named { .. }) + ); + if let Err(error) = + append_console_turn(&state, &turn.envelope, "assistant", &reply, record_event, false).await + { + tracing::error!("Failed to persist assistant session turn: {error}"); + return Err("Failed to persist assistant response".to_string()); + } + } + + let body = if turn.awaiting_approval { + serde_json::json!({ + "status": "awaiting_approval", + "reply": reply, + "decision_id": decision.context.decision_id().to_string(), + }) + } else { + serde_json::to_value(SendMessageResponse { + status: "ok".to_string(), + reply, + }) + .map_err(|error| format!("Failed to encode session reply: {error}"))? + }; + Ok(jobs::JobOutput::new(StatusCode::OK, body)) + }; + let result = child_cleanup + .run(Box::pin(async { + let result: Result = work.await; + result.map_err(anyhow::Error::msg) + })) + .await + .map_err(|error| crate::providers::sanitize_api_error(&error.to_string())); + if let Err(error) = &result { + terminal_guard + .finish_failure(&anyhow::anyhow!(error.clone()), cancellation.is_cancelled()) + .await + .map_err(|_| { + format!( + "Console terminal cleanup persistence is unconfirmed ({})", + terminal_guard.failure_reason() + ) + })?; + } + result +} + +pub async fn get_session_media( + State(state): State, + Query(query): Query, + headers: HeaderMap, +) -> impl IntoResponse { + let token = extract_resource_auth_token(&headers); + if state.pairing.require_pairing() && !state.pairing.is_authenticated(&token) { + return json_error(StatusCode::UNAUTHORIZED, "Unauthorized"); + } + + let requested_path = query.path.trim(); + if requested_path.is_empty() { + return json_error(StatusCode::BAD_REQUEST, "path is required"); + } + + let uploads_root = { + let config = state.config.load_full(); + config.workspace_dir.join(UPLOADS_DIR_NAME) + }; + + let uploads_root = match fs::canonicalize(&uploads_root).await { + Ok(path) => path, + Err(_) => return json_error(StatusCode::NOT_FOUND, "Upload not found"), + }; + + let raw_path = PathBuf::from(requested_path); + if raw_path.is_absolute() { + return json_error(StatusCode::BAD_REQUEST, "Absolute paths are not allowed"); + } + if raw_path + .components() + .any(|c| matches!(c, std::path::Component::ParentDir)) + { + return json_error(StatusCode::BAD_REQUEST, "Path traversal is not allowed"); + } + let candidate_path = uploads_root.join(raw_path); + + let resolved_path = match fs::canonicalize(&candidate_path).await { + Ok(path) => path, + Err(_) => return json_error(StatusCode::NOT_FOUND, "Upload not found"), + }; + + if !resolved_path.starts_with(&uploads_root) { + return json_error(StatusCode::FORBIDDEN, "Access denied"); + } + + let bytes = match fs::read(&resolved_path).await { + Ok(bytes) => bytes, + Err(_) => return json_error(StatusCode::NOT_FOUND, "Upload not found"), + }; + + let content_type = media_content_type_for_path(&resolved_path); + let mut response = Response::new(Body::from(bytes)); + response + .headers_mut() + .insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type)); + response + .headers_mut() + .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); + response +} + +#[cfg(test)] +pub(crate) async fn drive_disabled_engine_console_entry(workspace: &std::path::Path) { + tests::drive_disabled_engine_console_entry(workspace).await; +} + +#[cfg(test)] +pub(crate) async fn drive_search_console_entry(config: crate::config::Config, input: &str) -> anyhow::Result<()> { + tests::drive_search_console_entry(config, input).await +} diff --git a/src/gateway/api/sessions/section_3.rs b/src/gateway/api/sessions/section_3.rs new file mode 100644 index 000000000..51f291cb3 --- /dev/null +++ b/src/gateway/api/sessions/section_3.rs @@ -0,0 +1,1731 @@ +#[cfg(test)] +mod tests { + mod console_recovery; + mod targeting; + + + use super::*; + use crate::config::Config; + use crate::gateway::{GatewayRateLimiter, IdempotencyStore}; + use crate::hooks::HookManager; + use crate::memory::{ConversationTurn, Memory, MemoryCategory, MemoryEntry}; + use crate::providers::{ChatRequest, ChatResponse, Provider}; + use crate::security::pairing::PairingGuard; + use async_trait::async_trait; + use std::sync::Arc; + use std::time::{Duration, Instant}; + use tokio::sync::broadcast; + + pub(super) async fn drive_search_console_entry(config: Config, input: &str) -> anyhow::Result<()> { + use crate::agent::turn_tests::reachability::{boxed_root_probe, provider, registry}; + let workspace = config.workspace_dir.clone(); + let memory: Arc = Arc::new(crate::memory::SqliteMemory::new(&workspace)?); + let provider: Arc = Arc::from(provider(&config)?); + let mut state = test_app_state_with_config(config.clone(), provider); + state.tools_registry = registry(&config, Arc::clone(&memory)); + state.mem = memory; + state.hooks = Arc::new(HookManager::new(workspace.clone())); + let cleanup = + crate::runtime::turn_cleanup::CleanupScope::new(None, tokio_util::sync::CancellationToken::new())?; + cleanup + .run(boxed_root_probe(|| async move { + let envelope = console_runtime_envelope_for_workspace( + workspace.to_string_lossy().to_string(), + "prx_search_console", + "console", + "prx_user", + ); + let (runtime, _, _, proof) = console_test_source(&mut state, envelope, input).await; + let _ = run_console_message_job( + runtime, + state, + input.to_owned(), + Vec::new(), + ConsoleTurnSource::Message(proof), + None, + ) + .await + .map_err(anyhow::Error::msg)?; + Ok(()) + })) + .await?; + Ok(()) + } + + pub(super) async fn drive_disabled_engine_console_entry(workspace: &std::path::Path) { + let cleanup = crate::runtime::turn_cleanup::CleanupScope::new(None, tokio_util::sync::CancellationToken::new()) + .expect("test: console engine-off cleanup"); + cleanup + .run(Box::pin(async { + let mut config = Config::default(); + config.workspace_dir = workspace.to_owned(); + config.config_path = workspace.join("config.toml"); + config.default_provider = Some("ollama".to_owned()); + config.default_model = Some("test-model".to_owned()); + config.providers.models.push( + toml::from_str( + "provider = \"ollama\"\nmodel = \"test-model\"\noperations = [\"chat\"]\nnative_tools = false\n", + ) + .expect("test: console model declaration"), + ); + config.cost.prices.insert( + "ollama/test-model".to_owned(), + crate::config::schema::ModelPricing { + input: 1.0, + output: 1.0, + cache_write: 1.0, + cache_read: 1.0, + }, + ); + let captured = Arc::new(CapturingProvider::default()); + let provider: Arc = captured.clone(); + let mut state = test_app_state_with_config(config, provider); + let envelope = console_runtime_envelope_for_workspace( + workspace.to_string_lossy().to_string(), + "console-engine-off", + "console", + "prx_user", + ); + let (runtime, _, _, proof) = console_test_source(&mut state, envelope, "hello").await; + run_console_message_job( + runtime, + state, + "hello".to_string(), + Vec::new(), + ConsoleTurnSource::Message(proof), + None, + ) + .await.map_err(anyhow::Error::msg)?; + assert_eq!(captured.requests.lock().len(), 1, "test: console provider called once"); + Ok::<(), anyhow::Error>(()) + })) + .await + .expect("test: console engine-off entry"); + } + + #[test] + fn console_error_kind_never_carries_error_text() { + const MARKER: &str = "PRIVATE-STORED-MARKER"; + let decode = serde_json::from_str::(&format!("\"{MARKER}\"")) + .expect_err("test: a string is not a valid integer capsule field"); + assert!( + decode.to_string().contains(MARKER), + "the fixture must reproduce a decode error that quotes stored text" + ); + let error = anyhow::Error::from(decode).context(format!("recovery scan failed for {MARKER}")); + assert!( + format!("{error:#}").contains(MARKER), + "the unrestricted chain carries the marker" + ); + let kind = console_error_kind(&error); + assert_eq!( + kind, "decode", + "a serde failure anywhere in the chain is a decode failure" + ); + assert!(!kind.contains(MARKER), "the logged category must not carry error text"); + + let untyped = anyhow::anyhow!("untyped failure quoting {MARKER}"); + assert_eq!( + console_error_kind(&untyped), + "other", + "an untyped error is reported by a static category only" + ); + let conflict = anyhow::Error::from(crate::runtime::ingress_recovery::AlreadyAccepted).context(MARKER); + assert_eq!( + console_error_kind(&conflict), + "conflict", + "a typed conflict keeps its category under added context" + ); + let io = anyhow::Error::from(std::io::Error::other(MARKER)); + assert_eq!(console_error_kind(&io), "io", "an I/O failure is reported as io"); + } + + #[test] + fn console_runtime_envelope_preserves_session_channel_and_sender() { + let envelope = console_runtime_envelope_for_workspace("workspace", "signal_alice", "signal", "alice"); + let scope = envelope.message_scope(); + + assert_eq!(scope.source, "console"); + assert_eq!(scope.session_key.as_deref(), Some("signal_alice")); + assert_eq!(scope.channel.as_deref(), Some("signal")); + assert_eq!(scope.sender.as_deref(), Some("alice")); + } + + // D4 C5: the console external session_id is NOT canonicalized. The durable + // session_key stays the raw external id (path/list contract value), and no + // legacy_session_key is carried (console persistence/recall stay single-key on + // the external id). This guards against accidentally migrating the console + // durable key the way the gateway *fabric* path was migrated in C4. + #[test] + fn d4_console_session_id_is_kept_legacy_not_canonicalized() { + let session_id = "signal_alice"; + let envelope = console_runtime_envelope_for_workspace("workspace", session_id, "signal", "alice"); + + // Durable write key == external id (no recipient-aware canonical). + assert_eq!(envelope.session_key, session_id); + assert_eq!(envelope.message_scope().session_key.as_deref(), Some(session_id)); + // No legacy key carried -> single-key recall on the external id. + let principal = envelope.memory_principal(); + assert_eq!(principal.session_key.as_deref(), Some(session_id)); + assert_eq!(principal.legacy_session_key, None); + assert_eq!(principal.session_key_candidates(), vec![session_id.to_string()]); + // The canonical derivation differs from the external id; C5 deliberately + // does NOT adopt it for the durable key (would break the path/list id). + assert_ne!(envelope.canonical_session_key(), session_id); + assert_eq!(envelope.canonical_session_key(), "console:signal:alice:-"); + } + + #[derive(Default)] + struct TestMemory; + + #[async_trait] + impl Memory for TestMemory { + fn name(&self) -> &str { + "test" + } + + async fn store( + &self, + _key: &str, + _content: &str, + _category: MemoryCategory, + _session_id: Option<&str>, + ) -> anyhow::Result<()> { + Ok(()) + } + + async fn recall( + &self, + _query: &str, + _limit: usize, + _session_id: Option<&str>, + ) -> anyhow::Result> { + Ok(Vec::new()) + } + + async fn get(&self, _key: &str) -> anyhow::Result> { + Ok(None) + } + + async fn list( + &self, + _category: Option<&MemoryCategory>, + _session_id: Option<&str>, + ) -> anyhow::Result> { + Ok(Vec::new()) + } + + async fn forget(&self, _key: &str) -> anyhow::Result { + Ok(false) + } + + async fn count(&self) -> anyhow::Result { + Ok(0) + } + + async fn health_check(&self) -> bool { + true + } + } + + #[derive(Default)] + struct CapturingProvider { + requests: parking_lot::Mutex>>, + } + + #[async_trait] + impl Provider for CapturingProvider { + async fn chat_with_system( + &self, + _system_prompt: Option<&str>, + _message: &str, + _model: &str, + _temperature: f64, + ) -> anyhow::Result { + anyhow::bail!("console runtime should use structured Provider::chat"); + } + + async fn chat( + &self, + request: ChatRequest<'_>, + _model: &str, + _temperature: f64, + ) -> anyhow::Result { + self.requests.lock().push(request.messages.to_vec()); + Ok(ChatResponse { + text: Some("console-runtime-ok".to_string()), + tool_calls: Vec::new(), + reasoning_content: None, + }) + } + } + + struct TestConfigParticipant; + struct TestPreparedConfig; + + impl crate::config::ConfigGenerationParticipant for TestConfigParticipant { + fn name(&self) -> &'static str { + "gateway_sessions_test_runtime" + } + + fn supports_rebuild_field(&self, _field: &str) -> bool { + true + } + + fn supports_controlled_restart_field(&self, _field: &str) -> bool { + true + } + + fn prepares_for_field(&self, _field: &str) -> bool { + true + } + + fn prepare( + &self, + _generation: Arc, + _changed_fields: &[String], + ) -> anyhow::Result> { + Ok(Box::new(TestPreparedConfig)) + } + } + + impl crate::config::PreparedConfigGeneration for TestPreparedConfig { + fn commit(&mut self) -> anyhow::Result<()> { + Ok(()) + } + + fn rollback(&mut self) {} + } + + fn test_app_state(mut config: Config, provider: Arc) -> AppState { + config.default_provider.get_or_insert_with(|| "ollama".to_owned()); + config.default_model.get_or_insert_with(|| "test-model".to_owned()); + test_app_state_with_config(config, provider) + } + + fn test_app_state_with_config(config: Config, provider: Arc) -> AppState { + let model = config.default_model.clone().expect("fixture config model"); + static PARTICIPANT: std::sync::OnceLock> = + std::sync::OnceLock::new(); + let config = crate::config::new_shared(config); + config.register_participant(PARTICIPANT.get_or_init(|| Arc::new(TestConfigParticipant))); + AppState { + rf_streams: Default::default(), + rf_approvals: Default::default(), + config, + provider, + model, + temperature: 0.0, + mem: Arc::new(TestMemory), + auto_save: false, + tools_registry: Arc::new(vec![]), + mcp_tool: None, + turn_runtime: None, + hooks: Arc::new(HookManager::new(std::env::temp_dir())), + webhook_token_hash: None, + webhook_signing_secret: None, + pairing: Arc::new(PairingGuard::new(false, &[])), + trust_forwarded_headers: false, + rate_limiter: Arc::new(GatewayRateLimiter::new(100, 100, 100, 100)), + idempotency_store: Arc::new(IdempotencyStore::new(Duration::from_mins(5), 1000)), + whatsapp: None, + signal: None, + whatsapp_app_secret: None, + linq: None, + linq_signing_secret: None, + nextcloud_talk: None, + nextcloud_talk_webhook_secret: None, + observer: Arc::new(NoopObserver), + start_time: Instant::now(), + gateway_port: 0, + logs_broadcast_tx: broadcast::channel(16).0, + #[cfg(feature = "wasm-plugins")] + plugin_runtime: None, + } + } + + #[tokio::test] + async fn session_creation_route_binds_owner_and_creates_no_message() { + use tower::ServiceExt; + let temp = tempfile::tempdir().unwrap(); + let mut config = Config::default(); + config.workspace_dir = temp.path().to_owned(); + config.autonomy.level = crate::security::AutonomyLevel::Full; + let mut state = test_app_state(config.clone(), Arc::new(CapturingProvider::default())); + let memory = Arc::new(crate::memory::SqliteMemory::new(temp.path()).unwrap()); + state.mem = memory.clone(); + let router = super::super::router(state.clone()).with_state(state.clone()); + let request = |body: &'static str| { + axum::http::Request::builder() + .method("POST") + .uri("/sessions") + .header("content-type", "application/json") + .body(Body::from(body)) + .unwrap() + }; + let response = router.clone().oneshot(request("{}")).await.unwrap(); + assert_eq!(response.status(), StatusCode::CREATED); + let body: serde_json::Value = + serde_json::from_slice(&axum::body::to_bytes(response.into_body(), 8192).await.unwrap()).unwrap(); + let id = body.get("session_id").unwrap().as_str().unwrap(); + let stored = memory.get_conversation_session(id).await.unwrap().unwrap(); + assert_eq!(stored.message_count, 0); + assert_eq!(stored.channel, "console"); + assert_eq!(stored.sender, "api:local"); + assert_eq!(stored.last_message_preview, ""); + assert!(memory.create_conversation_session(id, "api:other").await.is_err()); + assert_eq!( + memory.get_conversation_session(id).await.unwrap().unwrap().sender, + "api:local" + ); + assert_eq!( + router + .oneshot(request(r#"{"owner_id":"api:other"}"#)) + .await + .unwrap() + .status(), + StatusCode::UNPROCESSABLE_ENTITY + ); + config.autonomy.level = crate::security::AutonomyLevel::ReadOnly; + let mut denied = test_app_state(config, Arc::new(CapturingProvider::default())); + denied.mem = memory.clone(); + let response = super::super::router(denied.clone()) + .with_state(denied) + .oneshot(request("{}")) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert_eq!(memory.list_conversation_sessions(100, 0, None).await.unwrap().len(), 1); + } + + fn console_provider_fixture_config(config: &mut Config, workspace: &std::path::Path, model: &str, endpoint: &str) { + config.workspace_dir = workspace.to_owned(); + config.config_path = workspace.join("config.toml"); + config.default_provider = Some("ollama".to_owned()); + config.default_model = Some(model.to_owned()); + config.cost.prices.insert( + format!("ollama/{model}"), + crate::config::schema::ModelPricing { + input: 1.0, + output: 1.0, + cache_write: 1.0, + cache_read: 1.0, + }, + ); + assert!(matches!(crate::llm::route_decision::usage_cost_resolution( + "ollama", model, 1, 0, 0, 0, &config.cost, + ), crate::llm::route_decision::UsagePrice::Priced(value) if value > 0.0)); + let native_tools = model == CONSOLE_WINDOW_MODEL; + config.providers.models.push( + toml::from_str(&format!( + "provider = \"ollama\"\nmodel = {model:?}\noperations = [\"chat\"]\nnative_tools = {native_tools}\n" + )) + .unwrap(), + ); + let selected = crate::providers::selection::check( + config, + "ollama", + model, + &if native_tools { + crate::providers::catalog::Requirement::chat().with(crate::providers::catalog::Feature::NativeTools) + } else { + crate::providers::catalog::Requirement::chat() + }, + crate::providers::catalog::UnknownPolicy::Invocation, + ) + .unwrap(); + assert_eq!( + selected.verification(), + &crate::providers::catalog::Verification::Verified + ); + crate::agent::agent::native_decision_fixture::configure(config, endpoint).unwrap(); + } + + async fn console_test_source( + state: &mut AppState, + envelope: RuntimeEnvelope, + input: &str, + ) -> ( + Arc, + RuntimeEnvelope, + String, + crate::gateway::turn_source::GatewayTurnProof, + ) { + if state.mem.name() == "test" { + state.mem = + Arc::new(crate::memory::SqliteMemory::new(&state.config.pin().effective.workspace_dir).unwrap()); + } + let runtime = console_test_runtime(state); + let principal = super::super::ApiPrincipal::for_tests(); + let envelope = envelope + .with_run_id(uuid::Uuid::new_v4().to_string()) + .with_config_generation(&runtime.config_generation) + .with_owner_id(principal.owner_id.clone()) + .with_owner_isolation(); + let event_id = append_console_turn(state, &envelope, "user", input, true, false) + .await + .unwrap(); + let proof = crate::gateway::turn_source::GatewaySourceReceipt::console_proof( + state.mem.as_ref(), + &runtime, + &principal, + &envelope, + input, + &event_id, + ) + .await + .unwrap(); + (runtime, proof.envelope().clone(), event_id, proof) + } + + /// The Console turn runtime of `state`: its pinned generation with the + /// production provider binding and a fresh publication slot. + fn console_test_runtime(state: &AppState) -> Arc { + let mut runtime = state.pin_turn_runtime(); + let config = &runtime.config_generation.effective; + let provider_name = config.default_provider.as_deref().unwrap(); + let catalog = crate::providers::selection::catalog_for(config); + let resolved = crate::providers::selection::check_with( + config, + &catalog, + provider_name, + &runtime.model, + crate::providers::selection::credential_for(config, provider_name), + &crate::providers::catalog::Requirement::chat(), + crate::providers::catalog::UnknownPolicy::Invocation, + ) + .unwrap(); + let binding = crate::gateway::turn_source::GatewayProviderBinding::new(runtime.provider.clone(), resolved); + let security = Arc::new(crate::security::SecurityPolicy::from_config( + &config.autonomy, + &config.workspace_dir, + )); + let mutable = Arc::get_mut(&mut runtime).unwrap(); + mutable.provider_binding = Some(Arc::new(binding)); + mutable.publication_slot = + Arc::new(crate::gateway::turn_source::publication_slot::GatewayPublicationSlot::new(security, 0)); + runtime + } + + #[tokio::test] + async fn console_runtime_turn_uses_shared_tool_loop_history() { + let driver = crate::agent::agent::native_decision_fixture::Driver::start_answer() + .await + .unwrap(); + let endpoint = driver.endpoint().to_owned(); + driver + .run(async move { + let tmp = tempfile::tempdir().unwrap(); + let cleanup = + crate::runtime::turn_cleanup::CleanupScope::new(None, tokio_util::sync::CancellationToken::new()) + .unwrap(); + cleanup + .run(Box::pin(async { + let mut config = Config::default(); + console_provider_fixture_config(&mut config, tmp.path(), "test-model", &endpoint); + let provider_impl = Arc::new(CapturingProvider::default()); + let mut state = test_app_state_with_config(config, provider_impl.clone()); + let envelope = console_runtime_envelope_for_workspace( + tmp.path().to_string_lossy().to_string(), + "console-session", + "console", + "prx_user", + ); + let previous_turns = vec![ConversationTurn { + id: 1, + session_key: "console-session".to_string(), + role: "assistant".to_string(), + content: "previous answer".to_string(), + timestamp: "2026-05-27T00:00:00Z".to_string(), + message_id: Some("previous-event".to_string()), + }]; + + let (runtime, _, _, proof) = + console_test_source(&mut state, envelope, "current question").await; + let service = runtime + .publication_slot + .publish(&runtime, &state) + .await + .unwrap() + .clone(); + let cancellation = tokio_util::sync::CancellationToken::new(); + let context = service + .open_issued_turn_context( + &proof, + crate::runtime::turn_context::AgentTurnKind::SingleShot, + &cancellation, + ) + .await + .unwrap(); + let decision = ConsoleDecisionTurn { + service: service.clone(), + context, + advice: None, + proof: &proof, + cancellation, + provider_trace: None, + }; + assert!( + run_console_runtime_turn( + runtime.clone(), + &state, + "different unadmitted input", + Vec::new(), + &decision, + None, + ) + .await + .is_err() + ); + assert!( + provider_impl.requests.lock().is_empty(), + "source mismatch must fail before provider transport" + ); + let turn = run_console_runtime_turn( + runtime, + &state, + "current question", + previous_turns, + &decision, + None, + ) + .await + .unwrap(); + + service + .shutdown(std::time::Instant::now() + Duration::from_secs(2)) + .await; + assert_eq!(turn.reply, "console-runtime-ok"); + let requests = provider_impl.requests.lock(); + assert_eq!(requests.len(), 1); + let history = requests.first().expect("request should be recorded"); + assert_eq!(history.first().map(|m| m.role.as_str()), Some("system")); + assert!( + history + .iter() + .any(|m| m.role == "assistant" && m.content == "previous answer") + ); + assert_eq!(history.last().map(|m| m.role.as_str()), Some("user")); + assert!(history.last().is_some_and(|m| m.content.contains("current question"))); + Ok::<(), anyhow::Error>(()) + })) + .await + .expect("actual fixture decision transport and cleanup ownership"); + }) + .await; + } + + /// A plain Console message uses the default enabled builtin decision plane + /// and reaches the serving provider through the same admitted runtime as a + /// production Console request. + #[tokio::test] + async fn console_plain_message_reaches_the_provider_with_default_causal_config() { + let tmp = tempfile::tempdir().expect("test: tempdir"); + let cleanup = crate::runtime::turn_cleanup::CleanupScope::new(None, tokio_util::sync::CancellationToken::new()) + .expect("test: Console cleanup owner"); + cleanup + .run(Box::pin(async { + let mut config = Config::default(); + config.workspace_dir = tmp.path().to_owned(); + config.config_path = tmp.path().join("config.toml"); + config.default_provider = Some("ollama".to_owned()); + config.default_model = Some("test-model".to_owned()); + config.providers.models.push( + toml::from_str( + "provider = \"ollama\"\nmodel = \"test-model\"\noperations = [\"chat\"]\nnative_tools = false\n", + ) + .expect("test: Console model declaration"), + ); + config.cost.prices.insert( + "ollama/test-model".to_owned(), + crate::config::schema::ModelPricing { + input: 1.0, + output: 1.0, + cache_write: 1.0, + cache_read: 1.0, + }, + ); + assert_eq!( + config.decision_engine, + crate::config::schema::decision_engine::DecisionEngineConfig::default(), + "the Console proof must retain the default decision engine configuration" + ); + + let provider_impl = Arc::new(CapturingProvider::default()); + let mut state = test_app_state_with_config(config, provider_impl.clone()); + let envelope = console_runtime_envelope_for_workspace( + tmp.path().to_string_lossy().to_string(), + "console-plain-session", + "console", + "prx_user", + ); + let input = "hello"; + let (runtime, _, _, proof) = console_test_source(&mut state, envelope, input).await; + let service = runtime.publication_slot.publish(&runtime, &state).await?.clone(); + let cancellation = tokio_util::sync::CancellationToken::new(); + let context = service + .open_issued_turn_context( + &proof, + crate::runtime::turn_context::AgentTurnKind::SingleShot, + &cancellation, + ) + .await?; + let decision = ConsoleDecisionTurn { + service: Arc::clone(&service), + context, + advice: None, + proof: &proof, + cancellation, + provider_trace: None, + }; + let turn = run_console_runtime_turn(runtime, &state, input, Vec::new(), &decision, None).await?; + service + .shutdown(std::time::Instant::now() + Duration::from_secs(2)) + .await; + + assert_eq!(turn.reply, "console-runtime-ok"); + assert_eq!(provider_impl.requests.lock().len(), 1); + Ok::<(), anyhow::Error>(()) + })) + .await + .expect("test: default Console turn and cleanup complete"); + } + + // ── R5 / OQ-23: the Console turn budgets on the model's effective window ── + + const CONSOLE_BULKY_TOOL: &str = "file_read"; + const CONSOLE_BULKY_FILE: &str = "prx-console-window.txt"; + const CONSOLE_BULKY_MARKER: &str = "CONSOLE-BULKY"; + const CONSOLE_WINDOW_MODEL: &str = "narrow-window-model"; + const CONSOLE_WINDOW_PROVIDER: &str = "ollama"; + const CONSOLE_ROUTER_WINDOW: usize = 33_200; + + /// A read-only tool whose output overruns the narrow fixture window but + /// fits the 128,000-token base window and the unbudgeted inline cap. + struct ConsoleBulkyTool { + inner: crate::tools::file_read::FileReadTool, + executions: Arc, + expected: String, + } + + #[async_trait] + impl crate::tools::Tool for ConsoleBulkyTool { + fn name(&self) -> &str { + self.inner.name() + } + fn description(&self) -> &str { + self.inner.description() + } + fn parameters_schema(&self) -> serde_json::Value { + self.inner.parameters_schema() + } + fn tier(&self) -> crate::tools::traits::ToolTier { + self.inner.tier() + } + fn categories(&self) -> &'static [crate::tools::traits::ToolCategory] { + self.inner.categories() + } + fn supports_owner_filesystem(&self) -> bool { + self.inner.supports_owner_filesystem() + } + async fn execute_with_cancellation( + &self, + args: serde_json::Value, + cancellation: Option, + ) -> anyhow::Result { + self.executions.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let result = self.inner.execute_with_cancellation(args, cancellation).await?; + assert!(result.success, "actual private FileRead must succeed: {result:?}"); + assert_eq!( + result.output, self.expected, + "the full physical file must reach budgeting" + ); + Ok(result) + } + async fn execute(&self, args: serde_json::Value) -> anyhow::Result { + self.execute_with_cancellation(args, None).await + } + } + + /// Native-tool spy: asks for the bulky tool on its first call, answers in + /// text afterwards, and records every request it serves. + #[derive(Default)] + struct ToolRoundSpyProvider { + requests: parking_lot::Mutex>>, + } + + #[async_trait] + impl Provider for ToolRoundSpyProvider { + fn capabilities(&self) -> crate::providers::ProviderCapabilities { + crate::providers::ProviderCapabilities { + native_tool_calling: true, + vision: false, + } + } + + async fn chat_with_system( + &self, + _system_prompt: Option<&str>, + _message: &str, + _model: &str, + _temperature: f64, + ) -> anyhow::Result { + Ok("summary".into()) + } + + async fn chat( + &self, + request: ChatRequest<'_>, + _model: &str, + _temperature: f64, + ) -> anyhow::Result { + let call_index = { + let mut requests = self.requests.lock(); + requests.push(request.messages.to_vec()); + requests.len() + }; + let tool_calls = if call_index == 1 { + vec![crate::providers::ToolCall { + id: "call-console-bulky-1".into(), + name: CONSOLE_BULKY_TOOL.into(), + arguments: serde_json::json!({"path": CONSOLE_BULKY_FILE}).to_string(), + }] + } else { + Vec::new() + }; + Ok(ChatResponse { + text: tool_calls.is_empty().then(|| "done".to_string()), + tool_calls, + reasoning_content: None, + }) + } + } + + /// Base config: the default 128,000-token window (not set explicitly), and + /// a `[[router.models]]` entry that gives the served model a narrow window. + /// Only the effective resolution sees the router entry. The fixture window + /// is large enough for the sealed decision request's existing reservation; + /// the paired payload remains larger than the main-turn share. + fn narrow_router_window_config(workspace: &std::path::Path) -> Config { + let mut config = Config::default(); + config.workspace_dir = workspace.to_path_buf(); + config.default_provider = Some(CONSOLE_WINDOW_PROVIDER.to_string()); + config.default_model = Some(CONSOLE_WINDOW_MODEL.to_string()); + config.agent.compaction = crate::config::AgentCompactionConfig { + mode: crate::config::AgentCompactionMode::Off, + ..crate::config::AgentCompactionConfig::default() + }; + config.router.models = vec![crate::config::RouterModelConfig { + model_id: CONSOLE_WINDOW_MODEL.to_string(), + provider: CONSOLE_WINDOW_PROVIDER.to_string(), + cost_per_million_tokens: 1.0, + max_context: CONSOLE_ROUTER_WINDOW, + reserved_output_tokens: Some(256), + latency_ms: 1_000, + categories: vec!["conversation".to_string()], + elo_rating: 1_000.0, + }]; + config.tool_tiering.always_include = vec![CONSOLE_BULKY_TOOL.to_string()]; + config + } + + /// A Console turn budgets on the served model's effective window, the one + /// the CLI, TUI and webhook budget on (OQ-23 / R5). + /// + /// The base config keeps the 128,000-token default, so a turn budgeted on + /// the base window forwards the whole token-dense tool payload to the + /// follow-up request. The router entry gives the served model a narrower + /// window; budgeted on that, the follow-up must fit it. + /// + /// MUTATION GUARD: pass `Some(&config_snapshot.agent.compaction)` to the + /// loop again and the follow-up request carries the whole payload. + #[tokio::test] + async fn console_turn_budgets_on_the_served_models_effective_window() { + let driver = crate::agent::agent::native_decision_fixture::Driver::start("filesystem") + .await + .unwrap(); + let endpoint = driver.endpoint().to_owned(); + driver + .run(async move { + let tmp = tempfile::tempdir().expect("test: tempdir"); + let cleanup = + crate::runtime::turn_cleanup::CleanupScope::new(None, tokio_util::sync::CancellationToken::new()) + .unwrap(); + cleanup.run(Box::pin(async { + let workspace = tmp.path().join("workspace"); + let private = tmp.path().join("private"); + std::fs::create_dir_all(&workspace).unwrap(); + std::fs::create_dir_all(&private).unwrap(); + let mut config = narrow_router_window_config(&workspace); + console_provider_fixture_config(&mut config, &workspace, CONSOLE_WINDOW_MODEL, &endpoint); + config.config_path = private.join("config.toml"); + let provider_impl = Arc::new(ToolRoundSpyProvider::default()); + // Keep the fixture's existing autonomy; owner isolation still gates + // the actual registered private-filesystem backend independently. + config.autonomy.level = crate::security::AutonomyLevel::Full; + let mut state = test_app_state_with_config(config, provider_impl.clone()); + state.model = CONSOLE_WINDOW_MODEL.into(); + let executions = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let mut payload = String::with_capacity(47_000); + let mut index = 0usize; + while payload.len() < 47_000 { + use std::fmt::Write as _; + let _ = write!(payload, "{CONSOLE_BULKY_MARKER}-{index}-갇걇겇곇괇굇궇귇긇깇꺇껇꼇꽇꾇꿇뀇끇낇냇넇녇놇뇇 "); + index += 1; + } + assert!(payload.len() < 48_000, "fixture must remain below the native inline cap"); + assert!( + payload.matches(CONSOLE_BULKY_MARKER).count() > 500, + "the base-window mutation must retain enough payload segments to fail" + ); + assert!( + crate::tokens::count::count_tokens(&payload) > 31_000, + "the paired payload must overrun the narrow main-turn window" + ); + let principal = super::super::ApiPrincipal::for_tests(); + let filesystem = crate::tools::owner_filesystem::OwnerFilesystem::open( + &private, workspace.to_string_lossy().as_ref(), &principal.owner_id, &workspace, + ).unwrap(); + let target = filesystem.resolve(CONSOLE_BULKY_FILE).unwrap(); + filesystem.write_authorized(&target, payload.as_bytes()).unwrap(); + let security = Arc::new(crate::security::SecurityPolicy::from_config( + &state.config.pin().effective.autonomy, &workspace, + )); + state.tools_registry = Arc::new(vec![Box::new(ConsoleBulkyTool { + inner: crate::tools::file_read::FileReadTool::new(security, false), + executions: Arc::clone(&executions), expected: payload, + })]); + let envelope = console_runtime_envelope_for_workspace( + workspace.to_string_lossy().to_string(), + "console-window-session", + "console", + "prx_user", + ); + + // Tool publication is not selection authority. Name the actual + // fixture capability in the raw source admitted by the service. + const INPUT: &str = "file_read prx-console-window.txt: summarise the console bulky probe"; + let (runtime, _, _, proof) = + console_test_source(&mut state, envelope, INPUT).await; + let service = runtime.publication_slot.publish(&runtime, &state).await.unwrap().clone(); + let cancellation = tokio_util::sync::CancellationToken::new(); + let context = service + .open_issued_turn_context( + &proof, + crate::runtime::turn_context::AgentTurnKind::SingleShot, + &cancellation, + ) + .await + .expect("bounded actual Console decision"); + let decision = ConsoleDecisionTurn { + service: service.clone(), + context, + advice: None, + proof: &proof, + cancellation, + provider_trace: None, + }; + let turn = run_console_runtime_turn( + runtime, + &state, + INPUT, + Vec::new(), + &decision, + None, + ) + .await + .expect("test: console turn completes"); + service + .shutdown(std::time::Instant::now() + Duration::from_secs(2)) + .await; + assert_eq!(turn.reply, "done"); + assert_eq!( + executions.load(std::sync::atomic::Ordering::SeqCst), + 1, + "the full bulky payload must be physically produced once" + ); + + let requests = provider_impl.requests.lock().clone(); + assert_eq!(requests.len(), 2, "one tool round, then the answer"); + let follow_up = requests.get(1).expect("test: the follow-up request was recorded"); + let payload_occurrences: usize = follow_up + .iter() + .map(|message| message.content.matches(CONSOLE_BULKY_MARKER).count()) + .sum(); + assert!( + payload_occurrences < 500, + "the follow-up request must be budgeted on the model's {CONSOLE_ROUTER_WINDOW}-token window, \ + not the 128,000-token base window; found {payload_occurrences} payload segments" + ); + let follow_up_chars: usize = follow_up.iter().map(|message| message.content.chars().count()).sum(); + assert!( + follow_up_chars < CONSOLE_ROUTER_WINDOW * 4, + "the follow-up request must fit the effective window; it has {follow_up_chars} characters" + ); + assert!( + follow_up.iter().any(|message| message.role == "user" + && message.content.contains("summarise the console bulky probe")), + "the turn's own request must survive the budget (D-011)" + ); + Ok::<(), anyhow::Error>(()) + })).await.expect("actual fixture decision transport and cleanup ownership"); + }) + .await; + } + + /// C2b-2: the console session API returns a tool-schema refusal as a + /// stable code with every refused tool. Before, the job failed with the + /// aggregate clipped to 200 characters, which cut the tool list. + #[tokio::test] + async fn a_console_tool_schema_refusal_returns_a_stable_code_and_the_tools() { + let driver = crate::agent::agent::native_decision_fixture::Driver::start_answer() + .await + .unwrap(); + let endpoint = driver.endpoint().to_owned(); + driver + .run(async move { + let tmp = tempfile::tempdir().unwrap(); + let mut config = Config::default(); + console_provider_fixture_config(&mut config, tmp.path(), "test-model", &endpoint); + let mut state = test_app_state_with_config( + config, + Arc::new(crate::providers::tool_schema_refusal_tests::RefusingProvider), + ); + let envelope = console_runtime_envelope_for_workspace( + tmp.path().to_string_lossy().to_string(), + "console-session", + "console", + "prx_user", + ); + + let (runtime, _, _, proof) = console_test_source(&mut state, envelope, "hello").await; + let output = match run_console_message_job( + runtime, + state, + "hello".to_string(), + Vec::new(), + ConsoleTurnSource::Message(proof), + None, + ) + .await + { + Ok(output) => output, + Err(message) => { + panic!("the refusal must be answered with a stable code, not a failed job: {message}") + } + }; + assert_eq!(output.status, axum::http::StatusCode::INTERNAL_SERVER_ERROR); + assert_eq!( + output.body.get("error"), + Some(&serde_json::json!("tool_schema_refused")), + "{}", + output.body + ); + assert_eq!( + output.body.get("tools"), + Some(&serde_json::json!(["fixture_conditional", "fixture_alternatives"])), + "{}", + output.body + ); + }) + .await; + } + + // ── D-053 / REDACT-TURN: console turns persist no provider secret ── + + /// Answers every structured chat with a reply that echoes a secret. + struct SecretReplyProvider(Arc); + + #[async_trait] + impl Provider for SecretReplyProvider { + async fn chat_with_system( + &self, + _system_prompt: Option<&str>, + _message: &str, + _model: &str, + _temperature: f64, + ) -> anyhow::Result { + anyhow::bail!("console runtime should use structured Provider::chat"); + } + + async fn chat( + &self, + _request: ChatRequest<'_>, + _model: &str, + _temperature: f64, + ) -> anyhow::Result { + self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let secret = crate::agent::terminal::persistence_probe::PROBE_SECRET; + Ok(ChatResponse { + text: Some(format!("Here is the key {secret} you asked for")), + tool_calls: Vec::new(), + reasoning_content: None, + }) + } + } + + /// Fails every structured chat with an error that echoes a secret. + struct SecretErrorProvider(Arc); + + #[async_trait] + impl Provider for SecretErrorProvider { + async fn chat_with_system( + &self, + _system_prompt: Option<&str>, + _message: &str, + _model: &str, + _temperature: f64, + ) -> anyhow::Result { + anyhow::bail!("console runtime should use structured Provider::chat"); + } + + async fn chat( + &self, + _request: ChatRequest<'_>, + _model: &str, + _temperature: f64, + ) -> anyhow::Result { + self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let secret = crate::agent::terminal::persistence_probe::PROBE_SECRET; + anyhow::bail!("upstream rejected key {secret}"); + } + } + + /// A console state whose memory is a real SQLite store and whose + /// workspace (cost ledger, skills) is the same tempdir, so everything the + /// turn persists lands under `tmp`. The user turn is recorded first, as + /// `post_session_message` does, and its event id returned. + async fn console_probe_state( + tmp: &tempfile::TempDir, + provider: Arc, + session_id: &str, + endpoint: &str, + ) -> ( + AppState, + Arc, + RuntimeEnvelope, + String, + crate::gateway::turn_source::GatewayTurnProof, + ) { + let mut config = Config::default(); + console_provider_fixture_config(&mut config, tmp.path(), "test-model", endpoint); + let mut state = test_app_state_with_config(config, provider); + state.mem = Arc::new(crate::memory::SqliteMemory::new(tmp.path()).expect("test: sqlite memory")); + let envelope = console_runtime_envelope_for_workspace( + tmp.path().to_string_lossy().to_string(), + session_id, + "console", + "prx_user", + ); + let (runtime, envelope, event_id, proof) = console_test_source(&mut state, envelope, "what is my key?").await; + (state, runtime, envelope, event_id, proof) + } + + /// D-053 / REDACT-TURN probe: drives `run_console_message_job` through the + /// completed `finalize_turn` commit and the assistant `append_console_turn` + /// with a reply that echoes a secret; it must fail before the REDACT-TURN commits. + #[tokio::test] + async fn console_persists_no_secret_from_a_reply() { + let driver = crate::agent::agent::native_decision_fixture::Driver::start_answer() + .await + .unwrap(); + let endpoint = driver.endpoint().to_owned(); + driver + .run(async move { + let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let tmp = tempfile::tempdir().expect("test: tempdir"); + let session_id = "console-probe-reply"; + let (state, runtime, envelope, _, proof) = console_probe_state( + &tmp, + Arc::new(SecretReplyProvider(Arc::clone(&calls))), + session_id, + &endpoint, + ) + .await; + let mem = Arc::clone(&state.mem); + let principal = envelope.memory_principal(); + + // Keep the actual writer/runtime alive through the full file scan. + let retained_runtime = Arc::clone(&runtime); + let service = runtime + .publication_slot + .publish(&runtime, &state) + .await + .unwrap() + .clone(); + let output = run_console_message_job( + runtime, + state, + "what is my key?".to_string(), + Vec::new(), + ConsoleTurnSource::Message(proof), + None, + ) + .await + .expect("test: the console turn completes"); + assert_eq!(output.status, axum::http::StatusCode::OK, "{}", output.body); + + let turns = mem + .list_conversation_turns(&principal, session_id, 50, 0) + .await + .expect("test: list the console turns"); + assert!( + turns + .iter() + .any(|turn| turn.role == "assistant" && turn.content.contains("[REDACTED]")), + "the reply must be persisted as a redacted assistant turn: {turns:?}" + ); + + assert_eq!( + calls.load(std::sync::atomic::Ordering::SeqCst), + 1, + "the controlled provider must actually run once" + ); + retained_runtime + .publication_slot + .cleanup + .drain(tokio::time::Instant::now() + Duration::from_secs(5)) + .await + .expect("Console cleanup must drain before persisted-file inspection"); + assert!( + service.drain_writes(Instant::now() + Duration::from_secs(5)).await, + "actual decision writes must drain before persisted-file inspection" + ); + crate::agent::terminal::persistence_probe::assert_nothing_under_persists_the_probe_secret(tmp.path()); + service.shutdown(Instant::now() + Duration::from_secs(2)).await; + let retirement = Arc::clone(&retained_runtime.publication_slot.cleanup); + drop(retained_runtime); + retirement + .drain(tokio::time::Instant::now() + Duration::from_secs(5)) + .await + .expect("Console runtime retirement must drain before scratch removal"); + }) + .await; + } + + /// D-053 / REDACT-TURN probe: drives `run_console_message_job` into the + /// failed `finalize_turn` commit of `run_console_runtime_turn` with a provider + /// error that echoes a secret; it must fail before the REDACT-TURN commits. + #[tokio::test] + async fn console_persists_no_secret_from_a_provider_error() { + let driver = crate::agent::agent::native_decision_fixture::Driver::start_answer() + .await + .unwrap(); + let endpoint = driver.endpoint().to_owned(); + driver + .run(async move { + let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let tmp = tempfile::tempdir().expect("test: tempdir"); + let (state, runtime, _, _, proof) = console_probe_state( + &tmp, + Arc::new(SecretErrorProvider(Arc::clone(&calls))), + "console-probe-error", + &endpoint, + ) + .await; + + // Keep the actual writer/runtime alive through the full file scan. + let retained_runtime = Arc::clone(&runtime); + let service = runtime + .publication_slot + .publish(&runtime, &state) + .await + .unwrap() + .clone(); + let result = run_console_message_job( + runtime, + state, + "what is my key?".to_string(), + Vec::new(), + ConsoleTurnSource::Message(proof), + None, + ) + .await; + assert!( + result.is_err(), + "the provider failure must fail the console job, not answer it" + ); + + assert_eq!( + calls.load(std::sync::atomic::Ordering::SeqCst), + 1, + "the controlled provider must actually run once" + ); + retained_runtime + .publication_slot + .cleanup + .drain(tokio::time::Instant::now() + Duration::from_secs(5)) + .await + .expect("Console cleanup must drain before persisted-file inspection"); + assert!( + service.drain_writes(Instant::now() + Duration::from_secs(5)).await, + "actual decision writes must drain before persisted-file inspection" + ); + crate::agent::terminal::persistence_probe::assert_nothing_under_persists_the_probe_secret(tmp.path()); + service.shutdown(Instant::now() + Duration::from_secs(2)).await; + let retirement = Arc::clone(&retained_runtime.publication_slot.cleanup); + drop(retained_runtime); + retirement + .drain(tokio::time::Instant::now() + Duration::from_secs(5)) + .await + .expect("Console runtime retirement must drain before scratch removal"); + }) + .await; + } + + /// Gateway authorization reads the active ConfigGeneration, so a config + /// reload that lowers autonomy to ReadOnly flips a previously-allowed mutation + /// to denied without a process restart or a second cached config owner. + #[test] + fn authz_reads_hot_shared_config_after_reload() { + use crate::security::policy::{AutonomyLevel, ResourceRiskLevel}; + + // Start in the default autonomous policy: a low-risk gateway mutation is + // allowed. + let provider: Arc = Arc::new(CapturingProvider::default()); + let state = test_app_state(Config::default(), provider); + assert!( + crate::gateway::api::authorize_resource_mutation( + &state, + "gateway_api:config:update", + ResourceRiskLevel::Low, + ) + .is_ok(), + "default autonomous policy should allow a low-risk mutation" + ); + + // Hot-reload: publish a ReadOnly config into D only. C is intentionally left + // stale to prove authorization no longer depends on it. + let read_only = Config { + autonomy: crate::config::AutonomyConfig { + level: AutonomyLevel::ReadOnly, + ..crate::config::AutonomyConfig::default() + }, + ..Config::default() + }; + state + .config + .apply_runtime_config(read_only, crate::config::ConfigReloadTrigger::Test) + .expect("apply read-only config"); + + // Same call, same risk — now denied because the authz path reads D. + let denied = crate::gateway::api::authorize_resource_mutation( + &state, + "gateway_api:config:update", + ResourceRiskLevel::Low, + ) + .expect_err("ReadOnly autonomy published to SharedConfig must deny the mutation"); + assert_eq!(denied.0, axum::http::StatusCode::FORBIDDEN); + assert!( + denied + .1 + .0 + .get("error") + .and_then(serde_json::Value::as_str) + .unwrap_or_default() + .contains("read-only mode"), + "denial reason should reflect read-only autonomy" + ); + } + + /// D2 / fix 3 regression: `post_config` merges the incoming delta onto the hot + /// SharedConfig (D), NOT the cached C Mutex. We seed D with a hot field value that + /// differs from C, POST an unrelated delta, and assert the hot field SURVIVES — if + /// the merge had used stale C as its base it would silently revert the hot field. + #[tokio::test] + async fn post_config_merge_base_is_hot_shared_config_not_stale_cache() { + use super::super::config::post_config; + + let tmp = tempfile::tempdir().expect("tempdir"); + let config_path = tmp.path().join("config.toml"); + let workspace = tmp.path().join("workspace"); + + // C (cached) base: default temperature, valid config path on disk. + let mut cached = Config::default(); + cached.config_path = config_path.clone(); + cached.workspace_dir = workspace.clone(); + cached.default_temperature = 0.0; + + let provider: Arc = Arc::new(CapturingProvider::default()); + let state = test_app_state(cached, provider); + + // D (hot) holds a DIFFERENT default_temperature — simulating a prior hot + // reload that C has not yet observed. + let mut hot = Config::default(); + hot.config_path = config_path.clone(); + hot.workspace_dir = workspace; + hot.default_temperature = 0.42; + state + .config + .apply_runtime_config(hot, crate::config::ConfigReloadTrigger::Test) + .expect("apply hot config"); + + // POST a delta that does NOT touch default_temperature. + let resp = post_config( + axum::extract::State(state.clone()), + axum::extract::Query(crate::gateway::api::config::ConfigWriteQuery::default()), + axum::http::HeaderMap::new(), + axum::Json(serde_json::json!({ "auto_save": true })), + ) + .await; + assert_eq!(resp.status(), axum::http::StatusCode::OK); + + // The hot value from D survived the merge (would be 0.0 if C were the base). + let after = state.config.load_full(); + assert!( + (after.default_temperature - 0.42).abs() < 1e-9, + "merge base must be D: hot default_temperature should be preserved, got {}", + after.default_temperature + ); + // C is re-synced to D (C == D invariant restored). + assert!((state.config.load_full().default_temperature - 0.42).abs() < 1e-9); + } + + async fn response_json(response: Response) -> serde_json::Value { + let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024) + .await + .expect("test: approval inbox body"); + serde_json::from_slice(&bytes) + .unwrap_or_else(|_| serde_json::json!({ "raw": String::from_utf8_lossy(&bytes).to_string() })) + } + + #[tokio::test] + async fn approval_inbox_disabled_plane_is_conflict() { + let mut config = Config::default(); + config.workspace_dir = std::env::temp_dir(); + // OV-13: approvals are disabled when user-message recording is off. + config.memory.events.record_user_messages = false; + let state = test_app_state(config, Arc::new(CapturingProvider::default())); + let response = super::get_session_approvals( + State(state), + Query(ApprovalInboxQuery { + limit: None, + cursor: None, + }), + axum::Extension(super::super::ApiPrincipal::for_tests()), + ) + .await; + assert_eq!(response.status(), StatusCode::CONFLICT); + let body = response_json(response).await; + assert_eq!( + body.get("error").and_then(serde_json::Value::as_str), + Some("Decision approvals are disabled") + ); + } + + fn pending_event(workspace: &str, owner: &str, session: &str, decision: &str) -> crate::memory::MessageEventInput { + crate::memory::MessageEventInput { + agent_partition: None, + event_id: None, + idempotency_key: Some(format!("decision-approval:{decision}:pending")), + workspace_id: workspace.to_owned(), + owner_id: Some(owner.to_owned()), + source: crate::memory::MessageEventSource::Console, + channel: Some("console".to_owned()), + session_key: Some(session.to_owned()), + parent_session_key: None, + run_id: None, + parent_run_id: None, + agent_id: None, + persona_id: None, + sender: None, + recipient: None, + role: "system".to_owned(), + event_type: "approval.decision.pending".to_owned(), + subject: None, + goal_id: None, + causation_event_id: None, + correlation_id: None, + attempt_id: None, + lease_epoch: None, + config_generation_id: None, + config_source_revision: None, + content: "pending".to_owned(), + raw_payload_json: None, + visibility: crate::memory::MemoryVisibility::Session, + } + } + + #[tokio::test] + async fn approval_inbox_query_returns_only_the_requested_owner() { + let temp = tempfile::tempdir().expect("test: inbox scratch"); + let memory = crate::memory::SqliteMemory::new(temp.path()).expect("test: sqlite"); + let workspace = temp.path().to_string_lossy().to_string(); + memory + .append_message_event(pending_event( + &workspace, + "api:owner-a", + "session-a", + "11111111-1111-4111-8111-111111111111", + )) + .await + .expect("test: owner a event"); + memory + .append_message_event(pending_event( + &workspace, + "api:owner-b", + "session-b", + "22222222-2222-4222-8222-222222222222", + )) + .await + .expect("test: owner b event"); + let rows = memory + .list_owned_message_events_by_type(&workspace, "api:owner-a", "approval.decision.pending", 0, 20) + .await + .expect("test: owner query"); + assert_eq!(rows.len(), 1); + let row = rows.first().expect("test: owner row"); + assert_eq!(row.owner_id.as_deref(), Some("api:owner-a")); + assert_eq!(row.session_key.as_deref(), Some("session-a")); + let foreign = memory + .list_owned_message_events_by_type(&workspace, "api:owner-b", "approval.decision.pending", 0, 20) + .await + .expect("test: foreign query"); + assert_eq!(foreign.len(), 1); + let foreign_row = foreign.first().expect("test: foreign row"); + assert_eq!(foreign_row.session_key.as_deref(), Some("session-b")); + } + + #[tokio::test] + async fn approval_inbox_empty_when_the_owner_has_none() { + let temp = tempfile::tempdir().expect("test: inbox scratch"); + let mut config = Config::default(); + config.workspace_dir = temp.path().to_owned(); + config.config_path = temp.path().join("config.toml"); + config.autonomy.level = crate::security::AutonomyLevel::Supervised; + config.default_provider = Some("ollama".to_owned()); + config.default_model = Some("prx-local-model".to_owned()); + config.providers.models.push( + toml::from_str( + "provider = \"ollama\"\nmodel = \"prx-local-model\"\noperations = [\"chat\"]\nnative_tools = true\ncontext_window = 65536\n", + ) + .expect("test: model catalog"), + ); + crate::providers::selection::check( + &config, + "ollama", + "prx-local-model", + &crate::providers::catalog::Requirement::chat().with(crate::providers::catalog::Feature::NativeTools), + crate::providers::catalog::UnknownPolicy::Invocation, + ) + .expect("test: model resolves"); + let mut state = test_app_state_with_config(config, Arc::new(CapturingProvider::default())); + let memory = Arc::new(crate::memory::SqliteMemory::new(temp.path()).expect("test: sqlite")); + state.mem = memory.clone(); + let mut runtime = state.pin_turn_runtime(); + { + let security = Arc::new(crate::security::SecurityPolicy::from_config( + &runtime.config_generation.effective.autonomy, + &runtime.config_generation.effective.workspace_dir, + )); + let mutable = Arc::get_mut(&mut runtime).expect("test: runtime uniquely owned"); + mutable.publication_slot = + Arc::new(crate::gateway::turn_source::publication_slot::GatewayPublicationSlot::new(security, 0)); + } + let current = Arc::try_unwrap(runtime).unwrap_or_else(|_| panic!("test: runtime uniquely owned")); + state.turn_runtime = Some(Arc::new(crate::gateway::GatewayTurnRuntimeOwner::new( + current, + Arc::clone(&state.config), + Arc::clone(&state.mem), + None, + None, + None, + None, + Arc::clone(&state.hooks), + #[cfg(feature = "wasm-plugins")] + None, + ))); + let runtime = state.pin_turn_runtime(); + let service = runtime + .publication_slot + .publish(&runtime, &state) + .await + .expect("test: decision plane publishes"); + let principal = super::super::ApiPrincipal::for_tests(); + let response = super::get_session_approvals( + State(state.clone()), + Query(ApprovalInboxQuery { + limit: Some(0), + cursor: None, + }), + axum::Extension(principal.clone()), + ) + .await; + assert_eq!(response.status(), StatusCode::OK, "{}", response_json(response).await); + let response = super::get_session_approvals( + State(state.clone()), + Query(ApprovalInboxQuery { + limit: None, + cursor: None, + }), + axum::Extension(principal.clone()), + ) + .await; + let body = response_json(response).await; + assert_eq!( + body.get("approvals") + .and_then(serde_json::Value::as_array) + .map(Vec::len), + Some(0), + "{body}" + ); + assert!( + body.get("next_cursor").is_some_and(serde_json::Value::is_null), + "{body}" + ); + let workspace = state.config.pin().effective.workspace_dir.to_string_lossy().to_string(); + memory + .append_message_event(pending_event( + &workspace, + &principal.owner_id, + "session-own", + "33333333-3333-4333-8333-333333333333", + )) + .await + .expect("test: unsigned own event"); + memory + .append_message_event(pending_event( + &workspace, + "api:someone-else", + "session-foreign", + "44444444-4444-4444-8444-444444444444", + )) + .await + .expect("test: unsigned foreign event"); + let response = super::get_session_approvals( + State(state.clone()), + Query(ApprovalInboxQuery { + limit: None, + cursor: None, + }), + axum::Extension(principal), + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + let body = response_json(response).await; + let rendered = body.to_string(); + assert!(!rendered.contains("session-own"), "{body}"); + assert!(!rendered.contains("session-foreign"), "{body}"); + assert_eq!( + body.get("approvals") + .and_then(serde_json::Value::as_array) + .map(Vec::len), + Some(0), + "{body}" + ); + let _ = service.drain_writes(Instant::now() + Duration::from_secs(5)).await; + let _ = runtime + .publication_slot + .cleanup + .drain(tokio::time::Instant::now() + Duration::from_secs(5)) + .await; + } + + #[tokio::test] + async fn approval_inbox_fail_closed_memory_is_not_conflict() { + let temp = tempfile::tempdir().expect("test: inbox scratch"); + let mut config = Config::default(); + config.workspace_dir = temp.path().to_owned(); + config.config_path = temp.path().join("config.toml"); + config.autonomy.level = crate::security::AutonomyLevel::Supervised; + config.default_provider = Some("ollama".to_owned()); + config.default_model = Some("prx-local-model".to_owned()); + let state = test_app_state_with_config(config, Arc::new(CapturingProvider::default())); + let response = super::get_session_approvals( + State(state), + Query(ApprovalInboxQuery { + limit: None, + cursor: None, + }), + axum::Extension(super::super::ApiPrincipal::for_tests()), + ) + .await; + assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); + let body = response_json(response).await; + let error = body.get("error").and_then(serde_json::Value::as_str).unwrap_or(""); + assert_ne!(error, "Decision approvals are disabled", "{body}"); + assert!(!error.to_ascii_lowercase().contains("disabled"), "{body}"); + } +} + +async fn call_approval_action( + state: AppState, + session: String, + id: String, + principal: super::ApiPrincipal, + change: Option, + owner_authenticated: bool, +) -> Response { + use crate::security::approval_ledger::keys::RunCallAuthority; + let authority = match RunCallAuthority::parse_call_id(&id) { + Ok(value) => value, + Err(_) => return json_error(StatusCode::BAD_REQUEST, "Invalid call id"), + }; + let runtime = match state.admit_turn_runtime() { + Ok(runtime) => runtime, + Err(refusal) => return super::provider_not_ready(refusal), + }; + if let Some(response) = approvals_unavailable(&runtime.config_generation.effective, state.mem.as_ref()) { + return response; + } + if change.is_some() + && !owner_authenticated + && let Err(message) = console_decision_control_policy(&runtime.config_generation.effective) + { + return json_error(StatusCode::FORBIDDEN, message); + } + let cancellation = tokio_util::sync::CancellationToken::new(); + let cleanup = + match crate::runtime::turn_cleanup::CleanupScope::new(Some(&runtime.publication_slot.cleanup), cancellation) { + Ok(value) => value, + Err(error) => { + warn_cleanup_refused(&runtime.publication_slot.cleanup, "Console call approval", &error); + return json_error(StatusCode::SERVICE_UNAVAILABLE, "Gateway is draining"); + } + }; + let result = cleanup + .run(Box::pin(async { + let service = runtime.publication_slot.publish(&runtime, &state).await?; + let mut envelope = RuntimeEnvelope::console( + runtime + .config_generation + .effective + .workspace_dir + .to_string_lossy() + .as_ref(), + &session, + ); + envelope.owner_id = Some(principal.owner_id.clone()); + let adapter = service.call_approval_strategy(envelope)?; + let pending = adapter.port.inspect(&principal.owner_id, &session, &authority).await?; + let receipt = match change { + None => { + anyhow::ensure!(!adapter.port.is_rf_decided(&pending).await?, "approval already decided"); + serde_json::to_value(pending.view())? + } + Some(DecisionApprovalChange::Review(approved)) => { + let expires_at = adapter + .port + .review(&principal.owner_id, &session, &authority, approved) + .await?; + serde_json::json!({"decision_id":"", "call_id":id, "approved":approved, + "grant_count":usize::from(approved), "expires_at":expires_at}) + } + Some(DecisionApprovalChange::Revoke) => { + adapter.port.revoke(&principal.owner_id, &session, &authority).await?; + serde_json::json!({"decision_id":"", "call_id":id, "revoked_grants":1}) + } + }; + Ok::<_, anyhow::Error>(receipt) + })) + .await; + result.map_or_else( + |_| { + json_error( + StatusCode::CONFLICT, + "Call approval is unavailable, expired, or already resolved", + ) + }, + |view| Json(view).into_response(), + ) +} diff --git a/src/gateway/api/sessions/tests/targeting.rs b/src/gateway/api/sessions/tests/targeting.rs index 9f9a2dd14..930809f65 100644 --- a/src/gateway/api/sessions/tests/targeting.rs +++ b/src/gateway/api/sessions/tests/targeting.rs @@ -1,2866 +1,5 @@ #![cfg(test)] //! Targeted agent selection: selector, name grammar, rollout switch, autonomy //! cap and allowlist semantics. -use super::*; -use crate::config::DelegateAgentConfig; -use crate::config::agent_name::{AGENT_NAME_MAX_LEN, AgentName, AgentNameError, is_targetable}; -use crate::memory::embeddings::EmbeddingProvider; -use crate::memory::owner_predicate::OwnerScopedStoreRefusal; -use crate::memory::{ - AgentPartition, AgentScopeRefused, AgentScopeUnsupported, CompactionRunInput, Memory, MemoryCategory, - MemoryDraftInput, MemoryFabric, MemoryPrincipal, MemoryVisibility, MemoryWriteContext, NoneMemory, PartitionKey, - RetrievalTraceInput, -}; -use crate::security::AutonomyLevel; -use crate::tools::document_ingest::DocumentIngestTool; -use crate::tools::memory_store::MemoryStoreTool; -use std::sync::atomic::{AtomicUsize, Ordering}; - -use super::super::target::{AgentField, TargetError, TurnTarget, resolve_target}; -use crate::security::agent_level::agent_level as effective_autonomy; - -fn agent(agentic: bool, allowed_tools: &[&str]) -> DelegateAgentConfig { - DelegateAgentConfig { - approval_wait_secs: 600, - limits: crate::config::AgentLimits::default(), - provider: "ollama".to_owned(), - model: "test-model".to_owned(), - system_prompt: None, - api_key: None, - credential_ref: None, - temperature: None, - max_depth: 8, - agentic, - allowed_tools: allowed_tools.iter().map(|name| (*name).to_owned()).collect(), - identity_dir: None, - memory_scope: None, - spawn_enabled: None, - enabled: true, - autonomy: None, - } -} - -fn config_with(agents: Vec<(&str, DelegateAgentConfig)>, switch: bool) -> Config { - let mut config = Config::default(); - config.gateway.targeted_agents = switch; - config.agents = agents.into_iter().map(|(name, cfg)| (name.to_owned(), cfg)).collect(); - config -} - -fn named(raw: &str) -> TurnTarget { - TurnTarget::from_field(AgentField::Text(raw.to_owned())).expect("test: a valid name") -} - -fn http_request(body: serde_json::Value) -> Request { - let mut request = Request::builder() - .header(header::CONTENT_TYPE, "application/json") - .body(Body::from(body.to_string())) - .expect("test: request"); - request - .extensions_mut() - .insert(super::super::super::ApiPrincipal::for_tests()); - request -} - -struct Fixture { - state: AppState, - provider: Arc, - memory: Arc, - _temp: tempfile::TempDir, -} - -const SESSION: &str = "prx-target-session"; - -async fn fixture(config: impl FnOnce(&mut Config)) -> Fixture { - let temp = tempfile::tempdir().expect("test: tempdir"); - let mut base = Config::default(); - base.workspace_dir = temp.path().to_owned(); - config(&mut base); - let provider = Arc::new(CapturingProvider::default()); - let mut state = test_app_state(base, provider.clone()); - let memory = Arc::new(crate::memory::SqliteMemory::new(temp.path()).expect("test: sqlite memory")); - state.mem = memory.clone(); - memory - .create_conversation_session(SESSION, "api:local") - .await - .expect("test: session"); - Fixture { - state, - provider, - memory, - _temp: temp, - } -} - -/// Like [`fixture`], but keeps a caller-configured decision backend and the -/// Console private-filesystem layout `drive()` uses. -/// -/// `test_app_state` (`sessions.rs`) would drop -/// the native-tool surface this POST needs, even after `configure(...)`. -/// Default `config_path` is the user config dir; without a temp private root, -/// `console_filesystem` stays `None` and owner-isolated `file_read` is gated. -async fn fixture_with_decision_backend(config: impl FnOnce(&mut Config)) -> Fixture { - let temp = tempfile::tempdir().expect("test: tempdir"); - let workspace = temp.path().join("workspace"); - let private = temp.path().join("private"); - std::fs::create_dir_all(&workspace).expect("test: workspace"); - std::fs::create_dir_all(&private).expect("test: private root"); - let mut base = Config::default(); - base.workspace_dir = workspace.clone(); - base.config_path = private.join("config.toml"); - config(&mut base); - let provider = Arc::new(CapturingProvider::default()); - let mut state = test_app_state_with_config(base, provider.clone()); - let memory = Arc::new(crate::memory::SqliteMemory::new(&workspace).expect("test: sqlite memory")); - state.mem = memory.clone(); - memory - .create_conversation_session(SESSION, "api:local") - .await - .expect("test: session"); - Fixture { - state, - provider, - memory, - _temp: temp, - } -} - -async fn post(fixture: &Fixture, session: &str, body: serde_json::Value) -> (StatusCode, serde_json::Value) { - let response = post_session_message( - State(fixture.state.clone()), - Path(session.to_owned()), - http_request(body), - ) - .await - .into_response(); - let status = response.status(); - let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024) - .await - .expect("test: body"); - (status, serde_json::from_slice(&bytes).expect("test: json body")) -} - -fn error_code(body: &serde_json::Value) -> Option<&str> { - body.pointer("/error/code").and_then(serde_json::Value::as_str) -} - -async fn assert_untouched(fixture: &Fixture) { - assert!(fixture.provider.requests.lock().is_empty(), "no provider access"); - let stored = fixture - .memory - .get_conversation_session(SESSION) - .await - .expect("test: read session") - .expect("test: session exists"); - assert_eq!(stored.message_count, 0, "no input was recorded"); -} - -#[tokio::test] -async fn target_selector_preserves_main() { - // Omission and "main" reach the Main path (here: the session lookup, which - // answers a plain string error for a session that does not exist), with the - // switch off and on, and whatever `[agents.main]` holds. - for switch in [false, true] { - let fixture = fixture(|config| { - config.gateway.targeted_agents = switch; - config.agents.insert("main".to_owned(), agent(false, &[])); - }) - .await; - for body in [ - serde_json::json!({"message": "hello"}), - serde_json::json!({"message": "hello", "agent": "main"}), - ] { - let (status, value) = post(&fixture, "no-such-session", body).await; - assert_eq!(status, StatusCode::NOT_FOUND); - assert_eq!( - value.get("error").and_then(serde_json::Value::as_str), - Some("Session not found"), - "the Main path was entered: {value}" - ); - } - // Explicit null is the one refused spelling. - let (status, value) = post( - &fixture, - SESSION, - serde_json::json!({"message": "hello", "agent": null}), - ) - .await; - assert_eq!(status, StatusCode::BAD_REQUEST); - assert_eq!(error_code(&value), Some("agent_invalid")); - let (status, value) = post(&fixture, SESSION, serde_json::json!({"message": "hello", "agent": 7})).await; - assert_eq!(status, StatusCode::BAD_REQUEST); - assert_eq!(error_code(&value), Some("agent_invalid")); - assert_untouched(&fixture).await; - } - assert_eq!(TurnTarget::from_field(AgentField::Omitted), Ok(TurnTarget::Main)); - assert_eq!( - TurnTarget::from_field(AgentField::Text("main".to_owned())), - Ok(TurnTarget::Main) - ); - assert_eq!(TurnTarget::from_field(AgentField::Null), Err(TargetError::Invalid)); -} - -#[tokio::test] -async fn target_unknown_or_disabled_has_no_effects() { - let mut off = agent(false, &[]); - off.enabled = false; - // Switch off: every otherwise-valid named target is 409, existing or not, - // and never runs as Main. - let closed = fixture(|config| { - config.agents.insert("helper".to_owned(), agent(false, &[])); - }) - .await; - for name in ["helper", "ghost"] { - let (status, value) = post(&closed, SESSION, serde_json::json!({"message": "hi", "agent": name})).await; - assert_eq!(status, StatusCode::CONFLICT, "{name}: {value}"); - assert_eq!(error_code(&value), Some("agent_disabled")); - } - assert_untouched(&closed).await; - - // Switch on: unknown is 404, disabled is 409, both resolved before the - // session lookup, so even a missing session reports the target error. - let open = fixture(|config| { - config.gateway.targeted_agents = true; - config.agents.insert("helper".to_owned(), agent(false, &[])); - config.agents.insert("sleeper".to_owned(), off); - }) - .await; - for (name, session, status, code) in [ - ("ghost", SESSION, StatusCode::NOT_FOUND, "agent_unknown"), - ("sleeper", SESSION, StatusCode::CONFLICT, "agent_disabled"), - ("ghost", "no-such-session", StatusCode::NOT_FOUND, "agent_unknown"), - ] { - let (got, value) = post(&open, session, serde_json::json!({"message": "hi", "agent": name})).await; - assert_eq!(got, status, "{name}: {value}"); - assert_eq!(error_code(&value), Some(code)); - } - assert_untouched(&open).await; -} - -#[test] -fn target_autonomy_is_capped() { - use AutonomyLevel::{Full, ReadOnly, Supervised}; - for (agent_level, main, expected) in [ - (None, Supervised, Supervised), - (Some(Full), Supervised, Full), - (Some(ReadOnly), Full, ReadOnly), - (Some(Supervised), Full, Supervised), - (Some(Full), ReadOnly, Full), - (Some(Full), Full, Full), - ] { - assert_eq!(effective_autonomy(agent_level, main), expected); - } - - let mut capped = agent(false, &[]); - capped.autonomy = Some(Full); - let mut config = config_with(vec![("worker", capped)], true); - config.autonomy.level = Supervised; - let plan = resolve_target(&config, &named("worker")) - .expect("test: resolves") - .expect("test: a named plan"); - assert_eq!(plan.autonomy, Full, "a named agent runs at its own level"); - // The policy the target's turn is published with carries that level. - let mut snapshot = config.clone(); - snapshot.autonomy.level = plan.autonomy; - assert_eq!( - crate::runtime::bootstrap::build_security_policy(&snapshot).autonomy, - Full - ); - - config.agents.get_mut("worker").expect("test: worker").autonomy = Some(ReadOnly); - config.autonomy.level = Full; - let plan = resolve_target(&config, &named("worker")) - .expect("test: resolves") - .expect("test: a named plan"); - assert_eq!(plan.autonomy, ReadOnly, "a lower sub-agent level is kept"); -} - -#[test] -fn agent_name_rejects_invalid_start() { - for raw in [ - "", - "1agent", - "9", - "Agent", - "A", - "-agent", - "_agent", - " agent", - "\u{e9}agent", - ] { - assert_eq!(AgentName::parse(raw), Err(AgentNameError::InvalidStart), "{raw:?}"); - assert_eq!( - TurnTarget::from_field(AgentField::Text(raw.to_owned())), - Err(TargetError::Invalid), - "{raw:?}" - ); - } -} - -#[tokio::test] -async fn agent_name_rejects_invalid_characters() { - for raw in [ - "a b", "a/b", "a.b", "a\\b", "a\u{e9}", "a\u{3b1}", "aB", "a\u{0}", "a\n", "a%2Fb", - ] { - assert_eq!(AgentName::parse(raw), Err(AgentNameError::InvalidCharacter), "{raw:?}"); - } - let fixture = fixture(|config| config.gateway.targeted_agents = true).await; - let (status, value) = post(&fixture, SESSION, serde_json::json!({"message": "hi", "agent": "a b"})).await; - assert_eq!(status, StatusCode::BAD_REQUEST); - assert_eq!(error_code(&value), Some("agent_invalid")); - assert_untouched(&fixture).await; -} - -#[tokio::test] -async fn agent_name_rejects_overlength() { - assert!(AgentName::parse(&"a".repeat(AGENT_NAME_MAX_LEN)).is_ok()); - let long = "a".repeat(AGENT_NAME_MAX_LEN + 1); - assert_eq!(AgentName::parse(&long), Err(AgentNameError::TooLong)); - let fixture = fixture(|config| config.gateway.targeted_agents = true).await; - let (status, value) = post(&fixture, SESSION, serde_json::json!({"message": "hi", "agent": long})).await; - assert_eq!(status, StatusCode::BAD_REQUEST); - assert_eq!(error_code(&value), Some("agent_invalid")); - assert_untouched(&fixture).await; -} - -#[tokio::test] -async fn agent_name_is_exact_at_all_ingresses() { - // Config load: non-conforming and reserved legacy names load (with a - // warning) for delegate/spawn, but are never targetable. - let config = config_with( - vec![ - ("main", agent(false, &[])), - ("Researcher", agent(false, &[])), - ("white space", agent(false, &[])), - ("ok-agent", agent(false, &[])), - ], - true, - ); - config.validate().expect("test: legacy agent names still load"); - for key in config.agents.keys() { - assert_eq!(is_targetable(key), key == "ok-agent", "{key}"); - } - assert!( - resolve_target(&config, &named("ok-agent")) - .expect("test: resolves") - .is_some() - ); - - // Request field / decoded path segment: exact match, no folding or trimming. - for raw in [ - "Researcher", - "OK-AGENT", - "Ok-Agent", - " ok-agent", - "ok-agent ", - "ok-agent\n", - "white space", - ] { - assert_eq!( - TurnTarget::from_field(AgentField::Text(raw.to_owned())), - Err(TargetError::Invalid), - "{raw:?}" - ); - } - // `main` is the one explicit Main spelling; it never resolves to the legacy entry. - assert_eq!( - TurnTarget::from_field(AgentField::Text("main".to_owned())), - Ok(TurnTarget::Main) - ); - assert!( - resolve_target(&config, &TurnTarget::Main) - .expect("test: Main resolves") - .is_none() - ); - - // Over HTTP the same strings are refused before any effect. - let fixture = fixture(|cfg| { - cfg.gateway.targeted_agents = true; - cfg.agents.insert("ok-agent".to_owned(), agent(false, &[])); - }) - .await; - for raw in ["OK-AGENT", "Researcher", " ok-agent"] { - let (status, value) = post(&fixture, SESSION, serde_json::json!({"message": "hi", "agent": raw})).await; - assert_eq!(status, StatusCode::BAD_REQUEST, "{raw:?}"); - assert_eq!(error_code(&value), Some("agent_invalid")); - } - assert_untouched(&fixture).await; -} - -// ── Enforcement through the real targeted console turn ────────────────────── -// -// These tests run `run_console_runtime_turn` with a target built by the real -// `resolve_target` and `prepare_target` (capped policy, per-target decision -// slot and published tool surface). Only the model transport is scripted: the -// target's provider instance is replaced by a provider that emits fixed tool -// calls, and its binding is rebuilt around that instance. - -type ToolBox = Box; - -/// Queue of call batches. Each `chat` pops one; an empty queue answers in text. -struct ScriptedCalls { - batches: parking_lot::Mutex>>, - requests: parking_lot::Mutex>>, -} - -impl ScriptedCalls { - fn batches(batches: Vec>) -> Self { - Self { - batches: parking_lot::Mutex::new(batches), - requests: parking_lot::Mutex::new(Vec::new()), - } - } -} - -#[async_trait] -impl Provider for ScriptedCalls { - fn capabilities(&self) -> crate::providers::ProviderCapabilities { - crate::providers::ProviderCapabilities { - native_tool_calling: true, - vision: false, - } - } - - async fn chat_with_system( - &self, - _system_prompt: Option<&str>, - _message: &str, - _model: &str, - _temperature: f64, - ) -> anyhow::Result { - Ok("summary".to_owned()) - } - - async fn chat(&self, request: ChatRequest<'_>, _model: &str, _temperature: f64) -> anyhow::Result { - self.requests.lock().push(request.messages.to_vec()); - let batch = { - let mut batches = self.batches.lock(); - if batches.is_empty() { - None - } else { - Some(batches.remove(0)) - } - }; - let tool_calls: Vec = batch - .unwrap_or_default() - .iter() - .enumerate() - .map(|(index, (name, arguments))| crate::providers::ToolCall { - id: format!("call-targeted-{index}"), - name: (*name).to_owned(), - arguments: arguments.to_string(), - }) - .collect(); - Ok(ChatResponse { - text: tool_calls.is_empty().then(|| "done".to_owned()), - tool_calls, - reasoning_content: None, - }) - } -} - -/// A registered tool that counts backend executions. It borrows the published -/// metadata of `file_read` (or of `file_write` under that name), so it is -/// catalogued like a real filesystem tool. -struct CountingTool { - name: &'static str, - inner: ToolBox, - executions: Arc, -} - -#[async_trait] -impl crate::tools::Tool for CountingTool { - fn name(&self) -> &str { - self.name - } - fn description(&self) -> &str { - self.inner.description() - } - fn parameters_schema(&self) -> serde_json::Value { - self.inner.parameters_schema() - } - fn tier(&self) -> crate::tools::traits::ToolTier { - self.inner.tier() - } - fn categories(&self) -> &'static [crate::tools::traits::ToolCategory] { - self.inner.categories() - } - fn supports_owner_filesystem(&self) -> bool { - self.inner.supports_owner_filesystem() - } - async fn execute(&self, _args: serde_json::Value) -> anyhow::Result { - self.executions.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - Ok(crate::tools::ToolResult { - success: true, - output: "probe-output".to_owned(), - error: None, - }) - } -} - -const APPROVAL_DENIED: &str = "approval is not available for this agent"; -const APPROVAL_EVENT_TYPES: [&str; 8] = [ - "approval.call.pending", - "approval.call.reviewed", - "approval.decision.pending", - "approval.decision.reviewed", - "approval.decision.issued", - "approval.decision.resolved", - "approval.decision.resume_requested", - "approval.collection.declined", -]; - -impl Driven { - fn ran(&self, tool: &str) -> usize { - self.executions.get(tool).copied().expect("test: counted tool") - } -} - -struct Driven { - awaiting_approval: bool, - successful_attempts: u64, - denied_attempts: u64, - awaiting_approval_attempts: u64, - /// The text of every message of the request that followed the tool round. - follow_up: String, - executions: std::collections::BTreeMap<&'static str, usize>, - /// Durable approval rows by event type, read from the memory store. - rows: std::collections::BTreeMap<&'static str, usize>, - pending_calls: Option, - /// How often the channel approval resolver was consulted. - approval_asked: usize, -} - -/// Records every consultation and denies. -struct DenyingResolver { - asked: std::sync::atomic::AtomicUsize, -} - -#[async_trait] -impl crate::agent::turn_contracts::ApprovalResolver for DenyingResolver { - async fn resolve( - &self, - _request: &crate::approval::ApprovalRequest, - _channel: &str, - ) -> crate::agent::turn_contracts::ApprovalDecision { - self.asked.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - crate::agent::turn_contracts::ApprovalDecision::Deny - } -} - -/// Run one console turn. `agent_config` is `Some` for a targeted turn on agent -/// `worker`, `None` for a Main turn. Every name in `registry` is a registered -/// counting tool. With `ask_gate`, the run is installed with a channel approval -/// policy that makes every call ask first (the runtime route a read tool takes -/// to "needs approval" in a Run-disposition console turn). -async fn drive( - main_level: AutonomyLevel, - agent_config: Option, - registry: &[&'static str], - calls: Vec<(&'static str, serde_json::Value)>, - input: &'static str, - ask_gate: bool, -) -> Driven { - let driver = crate::agent::agent::native_decision_fixture::Driver::start("filesystem") - .await - .expect("test: decision fixture"); - let endpoint = driver.endpoint().to_owned(); - let registry = registry.to_vec(); - let targeted_request = agent_config.is_some(); - driver - .run(async move { - let tmp = tempfile::tempdir().expect("test: tempdir"); - let cleanup = - crate::runtime::turn_cleanup::CleanupScope::new(None, tokio_util::sync::CancellationToken::new()) - .expect("test: cleanup scope"); - let driven = cleanup - .run(Box::pin(async { - let workspace = tmp.path().join("workspace"); - let private = tmp.path().join("private"); - std::fs::create_dir_all(&workspace).expect("test: workspace"); - std::fs::create_dir_all(&private).expect("test: private root"); - let mut config = Config::default(); - console_provider_fixture_config(&mut config, &workspace, CONSOLE_WINDOW_MODEL, &endpoint); - config.config_path = private.join("config.toml"); - config.autonomy.level = main_level; - config.gateway.targeted_agents = true; - config.tool_tiering.always_include = registry.iter().map(|name| (*name).to_owned()).collect(); - if let Some(mut worker) = agent_config { - worker.model = CONSOLE_WINDOW_MODEL.to_owned(); - config.agents.insert("worker".to_owned(), worker); - } - let scripted = Arc::new(ScriptedCalls::batches(vec![calls])); - let mut state = test_app_state_with_config(config, Arc::new(CapturingProvider::default())); - state.mem = Arc::new( - crate::memory::SqliteMemory::new(&state.config.pin().effective.workspace_dir) - .expect("test: sqlite memory"), - ); - let security = Arc::new(crate::security::SecurityPolicy::from_config( - &state.config.pin().effective.autonomy, - &workspace, - )); - let counters: std::collections::BTreeMap<&'static str, Arc> = - registry - .iter() - .map(|name| (*name, Arc::new(std::sync::atomic::AtomicUsize::new(0)))) - .collect(); - state.tools_registry = Arc::new( - registry - .iter() - .map(|name| { - let inner: ToolBox = if *name == "file_write" { - Box::new(crate::tools::file_write::FileWriteTool::new(Arc::clone(&security))) - } else { - Box::new(crate::tools::file_read::FileReadTool::new(Arc::clone(&security), false)) - }; - Box::new(CountingTool { - name, - inner, - executions: Arc::clone(counters.get(name).expect("test: counter")), - }) as ToolBox - }) - .collect(), - ); - - // The parent runtime, exactly as the console fixtures build it. - let mut parent = state.pin_turn_runtime(); - let effective = Arc::clone(&parent.config_generation.effective); - let catalog = crate::providers::selection::catalog_for(&effective); - let resolve = |provider: &str| { - crate::providers::selection::check_with( - &effective, - &catalog, - provider, - CONSOLE_WINDOW_MODEL, - crate::providers::selection::credential_for(&effective, provider), - &crate::providers::catalog::Requirement::chat(), - crate::providers::catalog::UnknownPolicy::Invocation, - ) - .expect("test: model resolves") - }; - { - let parent = Arc::get_mut(&mut parent).expect("test: unshared runtime"); - parent.provider = scripted.clone(); - parent.model = CONSOLE_WINDOW_MODEL.to_owned(); - parent.provider_binding = - Some(Arc::new(crate::gateway::turn_source::GatewayProviderBinding::new( - scripted.clone(), - resolve("ollama"), - ))); - parent.publication_slot = Arc::new( - crate::gateway::turn_source::publication_slot::GatewayPublicationSlot::new( - Arc::new(crate::security::SecurityPolicy::from_config( - &effective.autonomy, - &workspace, - )), - 0, - ), - ); - } - - // The real target resolution and runtime derivation; only the - // provider instance is swapped for the scripted transport. - let plan = if targeted_request { - resolve_target(&effective, &named("worker")).expect("test: resolves") - } else { - None - }; - let (runtime, targeted) = match plan { - Some(plan) => { - let (mut runtime, turn) = prepare_target(&parent, &plan).expect("test: target runtime"); - { - let derived = Arc::get_mut(&mut runtime).expect("test: unshared target runtime"); - derived.provider = scripted.clone(); - derived.provider_binding = - Some(Arc::new(crate::gateway::turn_source::GatewayProviderBinding::new( - scripted.clone(), - resolve("ollama"), - ))); - } - (runtime, Some(turn)) - } - None => (parent, None), - }; - - let principal = super::super::super::ApiPrincipal::for_tests(); - let envelope = console_runtime_envelope_for_workspace( - workspace.to_string_lossy().to_string(), - "console-targeted-session", - "console", - "prx_user", - ) - .with_run_id(uuid::Uuid::new_v4().to_string()) - .with_config_generation(&runtime.config_generation) - .with_owner_id(principal.owner_id.clone()) - .with_owner_isolation(); - let event_id = append_console_turn(&state, &envelope, "user", input, true, false) - .await - .expect("test: record the input"); - let proof = crate::gateway::turn_source::GatewaySourceReceipt::console_proof( - state.mem.as_ref(), - &runtime, - &principal, - &envelope, - input, - &event_id, - ) - .await - .expect("test: admitted source"); - let resolver = Arc::new(DenyingResolver { - asked: std::sync::atomic::AtomicUsize::new(0), - }); - if ask_gate { - let run_id = envelope.run_id.clone().expect("test: run id"); - crate::agent::channel_approval::install(&run_id, resolver.clone(), true, false); - } - let service = runtime - .publication_slot - .publish(&runtime, &state) - .await - .expect("test: publish") - .clone(); - let cancellation = tokio_util::sync::CancellationToken::new(); - let context = service - .open_issued_turn_context( - &proof, - crate::runtime::turn_context::AgentTurnKind::SingleShot, - &cancellation, - ) - .await - .expect("test: decision"); - assert!( - context.is_run(), - "the turn must reach the tool loop, not collection or a direct reply" - ); - let decision = ConsoleDecisionTurn { - service: Arc::clone(&service), - context, - advice: None, - proof: &proof, - cancellation, - provider_trace: None, - }; - let turn = run_console_runtime_turn( - Arc::clone(&runtime), - &state, - input, - Vec::new(), - &decision, - targeted.as_ref(), - ) - .await - .expect("test: console turn completes"); - - let owner = principal.owner_id.clone(); - let workspace_id = proof.envelope().workspace_id.clone(); - let mut rows = std::collections::BTreeMap::new(); - for event_type in APPROVAL_EVENT_TYPES { - let found = state - .mem - .list_owned_message_events_by_type(&workspace_id, &owner, event_type, 0, 50) - .await - .expect("test: read approval rows"); - rows.insert(event_type, found.len()); - } - let pending_calls = match service.call_approval_strategy(proof.envelope().clone()) { - Ok(adapter) => Some( - adapter - .port - .list_pending_calls(&owner, 0, 10) - .await - .expect("test: pending call approvals") - .items - .len(), - ), - Err(_) => None, - }; - service - .shutdown(std::time::Instant::now() + Duration::from_secs(2)) - .await; - if let Some(run_id) = envelope.run_id.as_deref() { - crate::agent::channel_approval::clear(run_id); - } - - let requests = scripted.requests.lock().clone(); - let follow_up = requests - .get(1) - .map(|messages| { - messages - .iter() - .map(|message| message.content.as_str()) - .collect::>() - .join("\n") - }) - .unwrap_or_default(); - let snapshot = turn.trace.execution_trace.clone().expect("test: execution trace"); - Ok::<_, anyhow::Error>(Driven { - awaiting_approval: turn.awaiting_approval, - successful_attempts: snapshot.successful_attempts, - denied_attempts: snapshot.denied_attempts, - awaiting_approval_attempts: snapshot.awaiting_approval_attempts, - follow_up, - executions: counters - .iter() - .map(|(name, count)| (*name, count.load(std::sync::atomic::Ordering::SeqCst))) - .collect(), - rows, - pending_calls, - approval_asked: resolver.asked.load(std::sync::atomic::Ordering::SeqCst), - }) - })) - .await; - driven.expect("test: scripted turn and cleanup") - }) - .await -} - -#[tokio::test] -async fn targeted_turn_approval_call_ends_denied_without_pending_state() { - // The turn runs `file_read` under a run policy that makes every call ask - // first. The agent runs at its own Supervised level. - let mut worker = agent(true, &["file_read"]); - worker.autonomy = Some(AutonomyLevel::Supervised); - let calls = vec![("file_read", serde_json::json!({"path": "probe.txt"}))]; - let input = "file_read probe.txt: show the probe file"; - - let targeted = drive( - AutonomyLevel::Supervised, - Some(worker), - &["file_read"], - calls.clone(), - input, - true, - ) - .await; - assert_eq!(targeted.ran("file_read"), 0, "the backend never runs"); - assert!( - targeted.follow_up.contains(&format!("Denied: {APPROVAL_DENIED}")), - "the call ended ApprovalDenied: {}", - targeted.follow_up - ); - assert_eq!(targeted.approval_asked, 0, "no approval route was entered"); - assert_eq!(targeted.denied_attempts, 1); - assert_eq!(targeted.awaiting_approval_attempts, 0); - assert_eq!(targeted.successful_attempts, 0); - assert!(!targeted.awaiting_approval, "the turn is not waiting for anyone"); - assert_eq!(targeted.pending_calls.unwrap_or(0), 0, "no pending call"); - for (event_type, count) in &targeted.rows { - assert_eq!(*count, 0, "no {event_type} row was written"); - } - - // Control: the same call on a Main turn reaches the ordinary approval path. - let main = drive(AutonomyLevel::Supervised, None, &["file_read"], calls, input, true).await; - assert_eq!(main.approval_asked, 1, "Main consults the approval resolver"); - assert_eq!(main.ran("file_read"), 0, "the resolver denied the call"); - assert!(!main.follow_up.contains(APPROVAL_DENIED)); -} - -// ── Upload ownership ──────────────────────────────────────────────────────── - -const BOUNDARY: &str = "prx-test-boundary"; - -fn multipart_request(body: String) -> Request { - let mut request = Request::builder() - // Async mode answers 202 once the input is admitted, without waiting for the turn. - .uri("/?mode=async") - .header( - header::CONTENT_TYPE, - format!("multipart/form-data; boundary={BOUNDARY}"), - ) - .body(Body::from(body)) - .expect("test: request"); - request - .extensions_mut() - .insert(super::super::super::ApiPrincipal::for_tests()); - request -} - -fn text_part(name: &str, value: &str) -> String { - format!("--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n") -} - -fn file_part(file_name: &str, content: &str) -> String { - format!( - "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"files\"; filename=\"{file_name}\"\r\n\ - Content-Type: text/plain\r\n\r\n{content}\r\n" - ) -} - -async fn post_multipart(fixture: &Fixture, session: &str, body: String) -> (StatusCode, String) { - let response = post_session_message( - State(fixture.state.clone()), - Path(session.to_owned()), - multipart_request(body), - ) - .await - .into_response(); - let status = response.status(); - let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024) - .await - .expect("test: body"); - (status, String::from_utf8_lossy(&bytes).into_owned()) -} - -fn stored_uploads(fixture: &Fixture) -> Vec<(String, String)> { - let root = fixture.state.config.pin().effective.workspace_dir.join("uploads"); - let Ok(entries) = std::fs::read_dir(&root) else { - return Vec::new(); - }; - let mut files: Vec<(String, String)> = entries - .map(|entry| { - let path = entry.expect("test: entry").path(); - ( - path.file_name().expect("test: name").to_string_lossy().into_owned(), - std::fs::read_to_string(&path).expect("test: read upload"), - ) - }) - .collect(); - files.sort(); - files -} - -const ADMITTED_SESSION: &str = "prx-admitted-session"; - -/// Wire the fixture like a running gateway, so a Main request on -/// `ADMITTED_SESSION` is actually admitted (input recorded, job submitted). -async fn make_admissible(fixture: &mut Fixture) -> anyhow::Result<()> { - let workspace = fixture.state.config.pin().effective.workspace_dir.clone(); - let envelope = console_runtime_envelope_for_workspace( - workspace.to_string_lossy().as_ref(), - ADMITTED_SESSION, - "console", - "prx_user", - ); - let (runtime, _, _, anchor) = console_test_source(&mut fixture.state, envelope, "Admission fixture anchor").await; - drop(anchor); - let current = Arc::try_unwrap(runtime).map_err(|_| anyhow::anyhow!("fixture runtime unexpectedly shared"))?; - fixture.state.turn_runtime = Some(Arc::new(crate::gateway::GatewayTurnRuntimeOwner::new( - current, - Arc::clone(&fixture.state.config), - Arc::clone(&fixture.state.mem), - None, - None, - None, - None, - Arc::clone(&fixture.state.hooks), - #[cfg(feature = "wasm-plugins")] - None, - ))); - Ok(()) -} - -#[tokio::test] -async fn refused_target_cleanup_removes_only_its_own_upload() -> anyhow::Result<()> { - // The switch is off, so the named request is refused after its file is - // stored. An ADMITTED Main request sent the same file name (its session - // exists, so its file now belongs to the turn). The refusal must remove - // only the file the refused request created. - let mut fixture = fixture(|config| config.gateway.targeted_agents = false).await; - make_admissible(&mut fixture).await?; - let main_body = format!( - "{}{}--{BOUNDARY}--\r\n", - text_part("message", "main request"), - file_part("same.txt", "MAIN-CONTENT") - ); - let (status, reply) = post_multipart(&fixture, ADMITTED_SESSION, main_body).await; - assert_eq!(status, StatusCode::ACCEPTED, "{reply}"); - assert_eq!(stored_uploads(&fixture).len(), 1, "the admitted Main upload is stored"); - - let named_body = format!( - "{}{}{}--{BOUNDARY}--\r\n", - text_part("message", "named request"), - text_part("agent", "helper"), - file_part("same.txt", "NAMED-CONTENT") - ); - let (status, reply) = post_multipart(&fixture, SESSION, named_body).await; - assert_eq!(status, StatusCode::CONFLICT, "{reply}"); - let left = stored_uploads(&fixture); - assert_eq!(left.len(), 1, "only the refused request's file was removed: {left:?}"); - assert_eq!( - left.first().map(|(_, content)| content.as_str()), - Some("MAIN-CONTENT"), - "the admitted Main request's file is untouched" - ); - Ok(()) -} - -#[tokio::test] -async fn failed_main_admission_removes_its_upload() { - // A Main request whose session does not exist fails admission after its - // file is stored; the file must not outlive the request. - let fixture = fixture(|config| config.gateway.targeted_agents = false).await; - let body = format!( - "{}{}--{BOUNDARY}--\r\n", - text_part("message", "main request"), - file_part("gone.txt", "MAIN-CONTENT") - ); - let (status, reply) = post_multipart(&fixture, "no-such-session", body).await; - assert_eq!(status, StatusCode::NOT_FOUND, "{reply}"); - assert_eq!(stored_uploads(&fixture), Vec::new(), "no upload is left behind"); - assert_untouched(&fixture).await; -} - -#[test] -fn upload_path_is_owned_before_creation_and_cancellation_leaves_no_file() { - use std::sync::atomic::Ordering; - let temp = tempfile::tempdir().expect("test: tempdir"); - - // Ordering invariant: the guard knows the path while the file does not - // exist yet. - let early = temp.path().join("early.bin"); - let mut guard = UploadGuard::default(); - let abandoned = guard.begin(early.clone()); - assert!(guard.paths.contains(&early), "the path is registered"); - assert!(!early.exists(), "before the file exists"); - - // Cancellation between registration and creation: the guard drops first, - // the blocking worker runs afterwards and must not leave a file. - drop(guard); - assert!(abandoned.load(Ordering::SeqCst), "the abandonment is published"); - assert!(create_upload_file(&early, &abandoned).is_err()); - assert!(!early.exists(), "a worker running after the drop removes its own file"); - - // Cancellation after creation: the guard removes the file it registered. - let late = temp.path().join("late.bin"); - let mut guard = UploadGuard::default(); - let abandoned = guard.begin(late.clone()); - let file = create_upload_file(&late, &abandoned).expect("test: created"); - assert!(late.exists()); - drop(guard); - drop(file); - assert!(!late.exists(), "the guard removes a created file"); - - // A released guard hands the file over. - let kept = temp.path().join("kept.bin"); - let mut guard = UploadGuard::default(); - let abandoned = guard.begin(kept.clone()); - drop(create_upload_file(&kept, &abandoned).expect("test: created")); - guard.release(); - assert!(kept.exists(), "a released upload stays"); -} - -#[test] -fn upload_already_exists_preserves_the_existing_file() { - let temp = tempfile::tempdir().expect("test: tempdir"); - let sentinel = temp.path().join("sentinel.bin"); - std::fs::write(&sentinel, b"PRE-EXISTING").expect("test: sentinel"); - - let mut guard = UploadGuard::default(); - let abandoned = guard.begin(sentinel.clone()); - let outcome = guard.settle(&sentinel, create_upload_file(&sentinel, &abandoned)); - let error = outcome.expect_err("test: create_new must refuse an existing file"); - assert_eq!(error.kind(), std::io::ErrorKind::AlreadyExists); - assert!( - guard.paths.is_empty(), - "a path this request did not create is unregistered" - ); - - drop(guard); - assert_eq!( - std::fs::read(&sentinel).expect("test: sentinel must still exist"), - b"PRE-EXISTING" - ); -} - -#[tokio::test] -async fn multipart_parse_error_after_a_file_leaves_no_upload() { - // A completed file followed by a truncated `agent` field: the parser - // fails after the file is on disk, and nothing may remain. - let fixture = fixture(|config| config.gateway.targeted_agents = true).await; - let body = format!( - "{}{}--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"agent\"\r\n\r\nhelp", - text_part("message", "hi"), - file_part("kept.txt", "CONTENT") - ); - let (status, reply) = post_multipart(&fixture, SESSION, body).await; - assert_eq!(status, StatusCode::BAD_REQUEST, "{reply}"); - assert_eq!(stored_uploads(&fixture), Vec::new(), "no upload is left behind"); - assert_untouched(&fixture).await; -} - -const TARGET_U: &str = "00000000-0000-4000-8000-0000000000a1"; -const TARGET_SCOPE: &str = "00000000-0000-4000-8000-0000000000c1"; -const TARGET_MAIN_U: &str = "00000000-0000-4000-8000-0000000000b1"; -const TARGET_MAIN_SCOPE: &str = "00000000-0000-4000-8000-0000000000d1"; -const TARGET_REV: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; -const CAPTURE_PROVIDER: &str = "custom:http://127.0.0.1/prx-ma-01b2-partition"; -const PARTITION_PROVIDER: &str = "custom:http://127.0.0.1/prx-ma-01b3-partition"; -const WRITE_SCOPE_PROVIDER: &str = "custom:http://127.0.0.1/prx-ma-01b3-1-scope"; -const FENCE_ERASE: &str = "00000000-0000-4000-8000-0000000000e1"; -const FENCE_MAIN_ERASE: &str = "00000000-0000-4000-8000-0000000000e2"; -const RETIRED_U: &str = "00000000-0000-4000-8000-0000000000a9"; -const WRONG_U: &str = "00000000-0000-4000-8000-0000000000a8"; - -fn capture_provider_config(config: &mut Config, provider: &str, agent_cfg: DelegateAgentConfig) { - config.default_provider = Some(provider.to_owned()); - config.default_model = Some("test-model".to_owned()); - config.cost.prices.insert( - format!("{provider}/test-model"), - crate::config::schema::ModelPricing { - input: 1.0, - output: 1.0, - cache_write: 1.0, - cache_read: 1.0, - }, - ); - config.providers.models.push( - toml::from_str(&format!( - "provider = {provider:?}\nmodel = \"test-model\"\noperations = [\"chat\"]\nnative_tools = true\n" - )) - .expect("test: catalog"), - ); - let mut agent_cfg = agent_cfg; - agent_cfg.provider = provider.to_owned(); - agent_cfg.model = "test-model".to_owned(); - config.agents.insert("x".to_owned(), agent_cfg); -} - -fn captured_contents(provider: &CapturingProvider, index: usize) -> Vec { - provider - .requests - .lock() - .get(index) - .expect("test: captured request") - .iter() - .map(|message| message.content.clone()) - .collect() -} - -fn assert_history_partition(contents: &[String], present: &[&str], absent: &[&str], label: &str) { - for item in present { - assert!( - contents.iter().any(|content| content.contains(item)), - "{label} missing {item} in {contents:?}" - ); - } - for item in absent { - assert!( - !contents.iter().any(|content| content.contains(item)), - "{label} leaked {item} in {contents:?}" - ); - } -} - -fn named_partition(workspace: &str, owner: &str, name: &str, incarnation: &str) -> AgentPartition { - AgentPartition { - workspace_id: workspace.to_owned(), - owner_id: owner.to_owned(), - key: PartitionKey::Named { - name: AgentName::parse(name).expect("test: agent name"), - incarnation: incarnation.parse().expect("test: incarnation"), - }, - } -} - -fn main_partition(workspace: &str, owner: &str) -> AgentPartition { - AgentPartition { - workspace_id: workspace.to_owned(), - owner_id: owner.to_owned(), - key: PartitionKey::Main, - } -} - -fn history_reader(workspace: &str, session: &str, partition: AgentPartition) -> MemoryPrincipal { - MemoryPrincipal { - workspace_id: workspace.to_owned(), - agent_id: Some("system".to_owned()), - persona_id: None, - session_key: Some(session.to_owned()), - channel: Some("console".to_owned()), - sender: Some("api:local".to_owned()), - owner_id: Some("system:*".to_owned()), - require_owner_match: false, - legacy_session_key: None, - agent_partition: Some(partition), - } -} - -fn stamp_console_rows(dir: &std::path::Path, workspace: &str, owner: &str, session: &str) { - let conn = rusqlite::Connection::open(dir.join("memory").join("brain.db")).expect("test: open store"); - conn.pragma_update(None, "foreign_keys", "ON").expect("test: fk"); - conn.execute( - "INSERT INTO agent_incarnations VALUES (?1, ?2, 'n:x', ?3, 'active', ?4)", - rusqlite::params![workspace, owner, TARGET_U, TARGET_REV], - ) - .expect("test: incarnation x"); - conn.execute( - "INSERT INTO agent_incarnations VALUES (?1, ?2, 'm', ?3, 'active', ?4)", - rusqlite::params![workspace, owner, TARGET_MAIN_U, TARGET_REV], - ) - .expect("test: incarnation main"); - conn.execute( - "INSERT INTO agent_scopes VALUES (?1, ?2, ?3, ?4, 'n:x', ?5, 1)", - rusqlite::params![TARGET_SCOPE, workspace, owner, session, TARGET_U], - ) - .expect("test: scope x"); - conn.execute( - "INSERT INTO agent_scopes VALUES (?1, ?2, ?3, ?4, 'm', ?5, 1)", - rusqlite::params![TARGET_MAIN_SCOPE, workspace, owner, session, TARGET_MAIN_U], - ) - .expect("test: scope main"); - for (label, scope) in [ - ("x-only", Some(TARGET_SCOPE)), - ("main-row", Some(TARGET_MAIN_SCOPE)), - ("null-row", None), - ] { - conn.execute( - "INSERT INTO conversation_turns (session_key, owner_id, role, content, timestamp, ma_scope_id) - VALUES (?1, ?2, 'user', ?3, 't', ?4)", - rusqlite::params![session, owner, label, scope], - ) - .expect("test: stamp turn"); - } -} - -#[tokio::test] -async fn sqlite_targeted_scope_supported() { - let fixture = fixture(|config| { - config.gateway.targeted_agents = true; - config.autonomy.level = AutonomyLevel::Full; - capture_provider_config(config, CAPTURE_PROVIDER, agent(false, &[])); - }) - .await; - crate::providers::test_fixture::register( - CAPTURE_PROVIDER, - Arc::clone(&fixture.provider) as Arc, - ); - assert!(fixture.memory.supports_agent_scope()); - let workspace = fixture - .state - .config - .pin() - .effective - .workspace_dir - .to_string_lossy() - .into_owned(); - let owner = super::super::super::ApiPrincipal::for_tests().owner_id; - stamp_console_rows(std::path::Path::new(&workspace), &workspace, &owner, SESSION); - - let named = history_reader(&workspace, SESSION, named_partition(&workspace, &owner, "x", TARGET_U)); - let named_turns = fixture - .memory - .list_console_conversation_turns(&named, SESSION, 50, 0) - .await - .expect("test: named turns"); - let named_labels: Vec<&str> = named_turns.iter().map(|turn| turn.content.as_str()).collect(); - assert_eq!(named_labels, ["x-only"], "Named X sees no Y/Main/NULL rows"); - - let main = history_reader(&workspace, SESSION, main_partition(&workspace, &owner)); - let main_turns = fixture - .memory - .list_console_conversation_turns(&main, SESSION, 50, 0) - .await - .expect("test: main turns"); - let main_labels: Vec<&str> = main_turns.iter().map(|turn| turn.content.as_str()).collect(); - assert!(main_labels.contains(&"main-row") && main_labels.contains(&"null-row")); - assert!(!main_labels.contains(&"x-only")); - - let api_principal = super::super::super::ApiPrincipal::for_tests(); - let selected = super::super::select_turn_target( - &fixture.state, - fixture.state.pin_turn_runtime(), - &api_principal, - AgentField::Text("x".to_owned()), - false, - ) - .expect("test: named target"); - assert_eq!(selected.incarnation.as_deref(), Some(TARGET_U)); - - let (status, value) = post(&fixture, SESSION, serde_json::json!({"message": "hi", "agent": "x"})).await; - assert_eq!(status, StatusCode::OK, "{value}"); - assert_history_partition( - &captured_contents(&fixture.provider, 0), - &["x-only"], - &["main-row", "null-row"], - "Named POST", - ); - - let (status, value) = post(&fixture, SESSION, serde_json::json!({"message": "hi"})).await; - assert_eq!(status, StatusCode::OK, "{value}"); - assert_history_partition( - &captured_contents(&fixture.provider, 1), - &["main-row", "null-row"], - &["x-only"], - "Main POST", - ); -} - -const SCOPE_TOOL: &str = "file_read"; - -/// Records every argument set the runtime delivers to it, `_zc_scope` included. -/// Named and catalogued as `file_read` (CountingTool pattern) so the published -/// surface includes it. -struct ScopeRecorder { - seen: Arc>>, - inner: crate::tools::file_read::FileReadTool, -} - -#[async_trait] -impl crate::tools::Tool for ScopeRecorder { - fn name(&self) -> &str { - SCOPE_TOOL - } - fn description(&self) -> &str { - self.inner.description() - } - fn parameters_schema(&self) -> serde_json::Value { - self.inner.parameters_schema() - } - fn tier(&self) -> crate::tools::traits::ToolTier { - self.inner.tier() - } - fn categories(&self) -> &'static [crate::tools::traits::ToolCategory] { - self.inner.categories() - } - fn supports_owner_filesystem(&self) -> bool { - self.inner.supports_owner_filesystem() - } - async fn execute(&self, args: serde_json::Value) -> anyhow::Result { - self.seen.lock().push(args); - Ok(crate::tools::ToolResult { - success: true, - output: "recorded".to_owned(), - error: None, - }) - } -} - -/// A console input literal whose only varying field is the in-process partition (R0-2). -fn digest_cell_input(agent_partition: Option) -> crate::memory::MessageEventInput { - crate::memory::MessageEventInput { - agent_partition, - event_id: None, - idempotency_key: Some("console:run-1:input".to_owned()), - workspace_id: "workspace-a".to_owned(), - owner_id: Some("owner-a".to_owned()), - source: crate::memory::MessageEventSource::Console, - channel: Some("console".to_owned()), - session_key: Some(SESSION.to_owned()), - parent_session_key: None, - run_id: None, - parent_run_id: None, - agent_id: None, - persona_id: None, - sender: None, - recipient: None, - role: "user".to_owned(), - event_type: "message".to_owned(), - subject: None, - goal_id: None, - causation_event_id: None, - correlation_id: None, - attempt_id: None, - lease_epoch: None, - config_generation_id: None, - config_source_revision: None, - content: "hi".to_owned(), - raw_payload_json: None, - visibility: crate::memory::MemoryVisibility::Session, - } -} - -/// MA-01b3 part 0: the partition and session reach every writer input. The -/// envelope views are asserted directly; the POST views assert what the -/// runtime delivers to a tool (`_zc_scope`) and what `parse_scope_ctx` reads -/// back from it. -#[tokio::test] -async fn agent_partition_reaches_every_writer_input() { - let driver = crate::agent::agent::native_decision_fixture::Driver::start("filesystem") - .await - .expect("test: decision fixture"); - let endpoint = driver.endpoint().to_owned(); - driver - .run(async move { - let mut fixture = fixture_with_decision_backend(|config| { - config.gateway.targeted_agents = true; - config.autonomy.level = AutonomyLevel::Full; - config.tool_tiering.always_include = vec![SCOPE_TOOL.to_owned()]; - capture_provider_config(config, PARTITION_PROVIDER, agent(true, &[SCOPE_TOOL])); - crate::agent::agent::native_decision_fixture::configure(config, &endpoint) - .expect("test: decision backend"); - }) - .await; - let seen = Arc::new(parking_lot::Mutex::new(Vec::new())); - let workspace_dir = fixture.state.config.pin().effective.workspace_dir.clone(); - let security = Arc::new(crate::security::SecurityPolicy::from_config( - &fixture.state.config.pin().effective.autonomy, - &workspace_dir, - )); - fixture.state.tools_registry = Arc::new(vec![Box::new(ScopeRecorder { - seen: Arc::clone(&seen), - inner: crate::tools::file_read::FileReadTool::new(security, false), - }) as ToolBox]); - let workspace = workspace_dir.to_string_lossy().into_owned(); - let owner = super::super::super::ApiPrincipal::for_tests().owner_id; - stamp_console_rows(std::path::Path::new(&workspace), &workspace, &owner, SESSION); - - let named = named_partition(&workspace, &owner, "x", TARGET_U); - let envelope = crate::runtime::envelope::RuntimeEnvelope::console(workspace.clone(), SESSION.to_owned()) - .with_agent_partition(named.clone()); - let write_context = envelope.memory_write_context("direct"); - assert_eq!( - serde_json::to_vec(&digest_cell_input(Some(named.clone()))).expect("test: input json"), - serde_json::to_vec(&digest_cell_input(None)).expect("test: input json"), - "MessageEventInput serialisation (capsule digest input) ignores the partition" - ); - assert_eq!( - write_context.agent_partition.as_ref(), - Some(&named), - "write context carries the partition" - ); - assert_eq!( - write_context.session_key.as_deref(), - Some(SESSION), - "write context carries the session" - ); - assert_eq!( - envelope.message_scope().agent_partition.as_ref(), - Some(&named), - "message scope carries the partition" - ); - - for (label, body, expected) in [ - ( - "Named POST", - serde_json::json!({"message": "hi", "agent": "x"}), - named.clone(), - ), - ( - "Main POST", - serde_json::json!({"message": "hi"}), - main_partition(&workspace, &owner), - ), - ] { - let scripted = Arc::new(ScriptedCalls::batches(vec![vec![( - SCOPE_TOOL, - serde_json::json!({"path": "probe.txt"}), - )]])); - // The fixture holds only a Weak handle: keep this Arc alive for the POST. - let provider = Arc::clone(&scripted) as Arc; - crate::providers::test_fixture::register(PARTITION_PROVIDER, Arc::clone(&provider)); - // Main pins `AppState.provider`; Named builds through the factory. - fixture.state.provider = Arc::clone(&provider); - seen.lock().clear(); - let (status, value) = post(&fixture, SESSION, body).await; - drop(provider); - assert_eq!(status, StatusCode::OK, "{label}: {value}"); - let args = seen.lock().last().cloned().expect("test: recorder ran"); - let scope = args.get("_zc_scope").expect("test: runtime scope"); - assert_eq!( - scope.get("agent_partition"), - Some(&serde_json::to_value(&expected).expect("test: partition json")), - "{label}: _zc_scope carries the partition" - ); - assert_eq!( - scope.get("session_key").and_then(serde_json::Value::as_str), - Some(SESSION), - "{label}: _zc_scope carries the session" - ); - let context = crate::tools::memory_store::parse_scope_ctx(&args).expect("test: trusted scope"); - assert_eq!( - context.agent_partition.as_ref(), - Some(&expected), - "{label}: parsed partition" - ); - assert_eq!(context.session_key.as_deref(), Some(SESSION), "{label}: parsed session"); - } - }) - .await; -} - -fn brain(workspace: &str) -> rusqlite::Connection { - let conn = rusqlite::Connection::open(std::path::Path::new(workspace).join("memory").join("brain.db")) - .expect("test: brain"); - conn.pragma_update(None, "foreign_keys", "ON").expect("test: fk"); - conn -} - -fn seed_named_x(dir: &std::path::Path, workspace: &str, owner: &str, session: &str) { - let conn = rusqlite::Connection::open(dir.join("memory").join("brain.db")).expect("test: open store"); - conn.pragma_update(None, "foreign_keys", "ON").expect("test: fk"); - conn.execute( - "INSERT INTO agent_incarnations VALUES (?1, ?2, 'n:x', ?3, 'active', ?4)", - rusqlite::params![workspace, owner, TARGET_U, TARGET_REV], - ) - .expect("test: incarnation x"); - conn.execute( - "INSERT INTO agent_scopes VALUES (?1, ?2, ?3, ?4, 'n:x', ?5, 1)", - rusqlite::params![TARGET_SCOPE, workspace, owner, session, TARGET_U], - ) - .expect("test: scope x"); -} - -fn fence_scope(conn: &rusqlite::Connection, scope_id: &str, erase_id: &str) { - conn.execute( - "INSERT INTO agent_erase_fences VALUES (?1, ?2, 'draining', 2)", - rusqlite::params![scope_id, erase_id], - ) - .expect("test: fence"); -} - -fn table_columns(conn: &rusqlite::Connection, table: &str) -> Vec { - let sql = match table { - "message_events" | "conversation_turns" | "memory_events" | "memories" | "documents" | "document_chunks" - | "embedding_cache" | "memory_drafts" | "memory_trash" => { - format!("PRAGMA table_info({table})") - } - _ => panic!("test: unknown store {table}"), - }; - let mut statement = conn.prepare(&sql).expect("test: pragma"); - statement - .query_map([], |row| row.get::<_, String>(1)) - .expect("test: columns") - .map(|column| column.expect("test: column name")) - .collect() -} - -fn scope_rows(conn: &rusqlite::Connection, sql: &str, session: &str) -> Vec> { - let mut statement = conn.prepare(sql).expect("test: prepare"); - statement - .query_map([session], |row| row.get(0)) - .expect("test: query") - .map(|value| value.expect("test: scope")) - .collect() -} - -fn write_input( - workspace: &str, - owner: &str, - partition: Option, - session: Option<&str>, - content: &str, -) -> crate::memory::MessageEventInput { - let mut input = digest_cell_input(partition); - input.workspace_id = workspace.to_owned(); - input.owner_id = Some(owner.to_owned()); - input.session_key = session.map(str::to_owned); - input.idempotency_key = None; - input.content = content.to_owned(); - input -} - -/// MA-01b3 part 1: transcript/event writers stamp the resolved agent scope. -/// Real POST for Named X, Main mint (D-CR1), D-CR3 column probe, and refusals. -#[tokio::test] -async fn memory_writes_carry_scope() { - let fixture = fixture(|config| { - config.gateway.targeted_agents = true; - config.autonomy.level = AutonomyLevel::Full; - capture_provider_config(config, WRITE_SCOPE_PROVIDER, agent(false, &[])); - }) - .await; - crate::providers::test_fixture::register( - WRITE_SCOPE_PROVIDER, - Arc::clone(&fixture.provider) as Arc, - ); - let workspace = fixture - .state - .config - .pin() - .effective - .workspace_dir - .to_string_lossy() - .into_owned(); - let owner = super::super::super::ApiPrincipal::for_tests().owner_id; - seed_named_x(std::path::Path::new(&workspace), &workspace, &owner, SESSION); - let conn = brain(&workspace); - - const NINE: [&str; 9] = [ - "message_events", - "conversation_turns", - "memory_events", - "memories", - "documents", - "document_chunks", - "embedding_cache", - "memory_drafts", - "memory_trash", - ]; - let mut dcr3 = Vec::new(); - for table in NINE { - let columns = table_columns(&conn, table); - assert!( - columns.iter().any(|column| column == "ma_scope_id"), - "{table} has ma_scope_id" - ); - dcr3.push(format!("{table}: {}", columns.join(","))); - } - // D-CR3: no unambiguous FK identifies pre-01b3 targeted rows (target.rs has - // selector state only). Parent FKs (message_event_id, subject_id) serve D-CR2. - eprintln!("D-CR3 columns: {}", dcr3.join(" | ")); - - let (status, value) = post( - &fixture, - SESSION, - serde_json::json!({"message": "named-x", "agent": "x"}), - ) - .await; - assert_eq!(status, StatusCode::OK, "Named POST: {value}"); - - let named_events = scope_rows( - &conn, - "SELECT ma_scope_id FROM message_events - WHERE session_key = ?1 AND role IN ('user', 'assistant') - ORDER BY id", - SESSION, - ); - let named_turns = scope_rows( - &conn, - "SELECT ma_scope_id FROM conversation_turns - WHERE session_key = ?1 AND role IN ('user', 'assistant') - ORDER BY id", - SESSION, - ); - let named_mirrors = scope_rows( - &conn, - "SELECT ma_scope_id FROM memory_events - WHERE session_key = ?1 AND subject_table = 'message_events' - AND event_type IN ('message', 'message.created') - ORDER BY id", - SESSION, - ); - let named_user: i64 = conn - .query_row( - "SELECT count(*) FROM message_events WHERE session_key = ?1 AND role = 'user' AND ma_scope_id = ?2", - rusqlite::params![SESSION, TARGET_SCOPE], - |row| row.get(0), - ) - .expect("test: named user events"); - let named_assistant: i64 = conn - .query_row( - "SELECT count(*) FROM message_events WHERE session_key = ?1 AND role = 'assistant' AND ma_scope_id = ?2", - rusqlite::params![SESSION, TARGET_SCOPE], - |row| row.get(0), - ) - .expect("test: named assistant events"); - assert!(named_user >= 1, "Named POST wrote input message_events"); - assert!(named_assistant >= 1, "Named POST wrote assistant message_events"); - assert!(!named_events.is_empty(), "Named POST wrote message_events"); - assert!( - named_events.iter().all(|scope| scope.as_deref() == Some(TARGET_SCOPE)), - "message_events row carries X's scope: {named_events:?}" - ); - assert!( - named_turns.iter().all(|scope| scope.as_deref() == Some(TARGET_SCOPE)), - "conversation_turns row carries X's scope: {named_turns:?}" - ); - assert!( - named_mirrors.iter().all(|scope| scope.as_deref() == Some(TARGET_SCOPE)), - "memory_events row carries X's scope: {named_mirrors:?}" - ); - assert!( - named_events.iter().all(Option::is_some) - && named_turns.iter().all(Option::is_some) - && named_mirrors.iter().all(Option::is_some), - "Named X wrote zero NULL rows" - ); - - let main_incarnations: i64 = conn - .query_row( - "SELECT count(*) FROM agent_incarnations WHERE workspace_id = ?1 AND owner_id = ?2 AND agent_key = 'm'", - rusqlite::params![&workspace, &owner], - |row| row.get(0), - ) - .expect("test: main incarnation count"); - assert_eq!(main_incarnations, 0, "D-CR1: no Main incarnation before the Main POST"); - - let (status, value) = post(&fixture, SESSION, serde_json::json!({"message": "main-hi"})).await; - assert_eq!(status, StatusCode::OK, "Main POST: {value}"); - - let minted_u: String = conn - .query_row( - "SELECT incarnation FROM agent_incarnations - WHERE workspace_id = ?1 AND owner_id = ?2 AND agent_key = 'm' AND state = 'active'", - rusqlite::params![&workspace, &owner], - |row| row.get(0), - ) - .expect("test: D-CR1 minted m"); - let main_scopes: Vec = { - let mut statement = conn - .prepare( - "SELECT scope_id FROM agent_scopes - WHERE workspace_id = ?1 AND owner_id = ?2 AND session_key = ?3 AND agent_key = 'm'", - ) - .expect("test: main scopes"); - statement - .query_map(rusqlite::params![&workspace, &owner, SESSION], |row| row.get(0)) - .expect("test: main scope rows") - .map(|value| value.expect("test: scope id")) - .collect() - }; - assert_eq!(main_scopes.len(), 1, "D-CR1: one Main scope"); - let main_scope = main_scopes.first().expect("test: D-CR1 one Main scope"); - let main_event_scope: Option = conn - .query_row( - "SELECT ma_scope_id FROM message_events WHERE session_key = ?1 AND content = 'main-hi'", - [SESSION], - |row| row.get(0), - ) - .expect("test: main event"); - assert_eq!( - main_event_scope.as_deref(), - Some(main_scope.as_str()), - "Main rows carry the minted scope" - ); - assert_eq!(minted_u.len(), 36, "D-CR1 minted an incarnation UUID"); - - let events_before: i64 = conn - .query_row( - "SELECT count(*) FROM message_events WHERE session_key = ?1", - [SESSION], - |row| row.get(0), - ) - .expect("test: count"); - fence_scope(&conn, TARGET_SCOPE, FENCE_ERASE); - let (status, value) = post( - &fixture, - SESSION, - serde_json::json!({"message": "fenced-x", "agent": "x"}), - ) - .await; - assert_eq!(status, StatusCode::CONFLICT, "fenced Named: {value}"); - assert_eq!(error_code(&value), Some("agent_scope_refused")); - let events_after: i64 = conn - .query_row( - "SELECT count(*) FROM message_events WHERE session_key = ?1", - [SESSION], - |row| row.get(0), - ) - .expect("test: count after fence"); - assert_eq!(events_after, events_before, "fenced Named wrote zero rows"); - - fence_scope(&conn, main_scope, FENCE_MAIN_ERASE); - let (status, value) = post(&fixture, SESSION, serde_json::json!({"message": "fenced-main"})).await; - assert_eq!(status, StatusCode::CONFLICT, "fenced Main: {value}"); - assert_eq!(error_code(&value), Some("agent_scope_refused")); - let fenced_main: i64 = conn - .query_row( - "SELECT count(*) FROM message_events WHERE content = 'fenced-main'", - [], - |row| row.get(0), - ) - .expect("test: fenced main rows"); - assert_eq!(fenced_main, 0, "fenced Main wrote zero rows"); - - let named = named_partition(&workspace, &owner, "x", TARGET_U); - let envelope = crate::runtime::envelope::RuntimeEnvelope::console(workspace.clone(), SESSION.to_owned()) - .with_agent_partition(named.clone()) - .with_owner_id(owner.clone()); - let error = append_console_turn(&fixture.state, &envelope, "user", "no-parent", false, false) - .await - .expect_err("test: Named missing parent event"); - assert!( - error.downcast_ref::().is_some(), - "W4 Named + missing parent: {error:#}" - ); - - conn.execute( - "INSERT INTO agent_incarnations VALUES (?1, ?2, 'n:x', ?3, 'retired', ?4)", - rusqlite::params![&workspace, &owner, RETIRED_U, TARGET_REV], - ) - .expect("test: retired incarnation"); - for (label, input) in [ - ( - "retired incarnation", - write_input( - &workspace, - &owner, - Some(named_partition(&workspace, &owner, "x", RETIRED_U)), - Some(SESSION), - "retired", - ), - ), - ( - "wrong U", - write_input( - &workspace, - &owner, - Some(named_partition(&workspace, &owner, "x", WRONG_U)), - Some(SESSION), - "wrong-u", - ), - ), - ( - "missing session_key", - write_input(&workspace, &owner, Some(named.clone()), None, "no-session"), - ), - ( - "workspace mismatch", - write_input( - "other-workspace", - &owner, - Some(named.clone()), - Some(SESSION), - "mismatch", - ), - ), - ( - "owner mismatch", - write_input( - &workspace, - "other-owner", - Some(named.clone()), - Some(SESSION), - "owner-mismatch", - ), - ), - ] { - let error = fixture.memory.append_message_event(input).await.expect_err(label); - assert!( - error.downcast_ref::().is_some(), - "{label}: {error:#}" - ); - } - for content in ["retired", "wrong-u", "no-session", "mismatch", "owner-mismatch"] { - let leaked: i64 = conn - .query_row( - "SELECT count(*) FROM message_events WHERE content = ?1", - [content], - |row| row.get(0), - ) - .expect("test: leak"); - assert_eq!(leaked, 0, "{content} wrote zero rows"); - } - - complete_memory_family_scope_stamps().await; -} - -#[tokio::test] -async fn none_targeted_scope_rejected() { - let memory = NoneMemory::new(); - assert!(!memory.supports_agent_scope()); - let principal = history_reader( - "prx_workspace", - "session", - named_partition("prx_workspace", "prx_owner", "x", TARGET_U), - ); - let turns = memory - .list_console_conversation_turns(&principal, "session", 10, 0) - .await - .expect_err("test: named turns"); - assert!(turns.downcast_ref::().is_some(), "{turns:#}"); - let events = memory - .list_message_events_since(&principal, 0, 10) - .await - .expect_err("test: named events"); - assert!(events.downcast_ref::().is_some(), "{events:#}"); - - // Job snapshots span all fixtures in this process. Identify only this - // rejected request rather than another test's legitimately submitted job. - let session_key = format!("prx-rejected-scope-{}", uuid::Uuid::new_v4()); - let temp = tempfile::tempdir().expect("test: tempdir"); - let mut config = Config::default(); - config.workspace_dir = temp.path().to_owned(); - config.gateway.targeted_agents = true; - config.agents.insert("x".to_owned(), agent(false, &[])); - let provider = Arc::new(CapturingProvider::default()); - let mut state = test_app_state(config, provider.clone()); - state.mem = Arc::new(NoneMemory::new()); - let response = post_session_message( - State(state.clone()), - Path(session_key.clone()), - http_request(serde_json::json!({"message": "hi", "agent": "x"})), - ) - .await - .into_response(); - let status = response.status(); - let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024) - .await - .expect("test: body"); - let body: serde_json::Value = serde_json::from_slice(&bytes).expect("test: json"); - assert_eq!(status, StatusCode::CONFLICT, "{body}"); - assert_eq!(error_code(&body), Some("agent_backend_unsupported")); - assert!(provider.requests.lock().is_empty(), "no provider access"); - assert!(state.mem.agent_registry().is_none(), "no registry row"); - let session = state - .mem - .get_conversation_session(&session_key) - .await - .expect("test: read session"); - assert!(session.is_none(), "no input event"); - let job_label = format!("gateway:session_message:{session_key}"); - assert!( - crate::gateway::jobs::snapshot_all() - .iter() - .all(|job| job.label != job_label), - "no job" - ); -} - -const STORE_SCOPE_PROVIDER: &str = "custom:http://127.0.0.1/prx-ma-01b3-2-store"; -const DOC_SCOPE_PROVIDER: &str = "custom:http://127.0.0.1/prx-ma-01b3-3-docs"; -const TOPIC_SCOPE_PROVIDER: &str = "custom:http://127.0.0.1/prx-ma-01b3-3-topics"; -const SESSION_S2: &str = "prx-target-session-s2"; -const STORE_TOOL: &str = "memory_store"; -const INGEST_TOOL: &str = "document_ingest"; - -struct ScopeCountingEmbedder { - calls: Arc, -} - -#[async_trait] -impl EmbeddingProvider for ScopeCountingEmbedder { - fn name(&self) -> &str { - "counting" - } - - fn dimensions(&self) -> usize { - 4 - } - - fn model(&self) -> &str { - "counting-v1" - } - - async fn embed(&self, texts: &[&str]) -> anyhow::Result>> { - self.calls.fetch_add(texts.len(), Ordering::SeqCst); - Ok(texts.iter().map(|_| vec![0.1, 0.2, 0.3, 0.4]).collect()) - } -} - -async fn fixture_with_scope_embedder(config: impl FnOnce(&mut Config), embed_calls: Arc) -> Fixture { - let temp = tempfile::tempdir().expect("test: tempdir"); - let workspace = temp.path().join("workspace"); - let private = temp.path().join("private"); - std::fs::create_dir_all(&workspace).expect("test: workspace"); - std::fs::create_dir_all(&private).expect("test: private root"); - let mut base = Config::default(); - base.workspace_dir = workspace.clone(); - base.config_path = private.join("config.toml"); - config(&mut base); - let provider = Arc::new(CapturingProvider::default()); - let mut state = test_app_state_with_config(base, provider.clone()); - let memory = Arc::new( - crate::memory::SqliteMemory::with_embedder( - &workspace, - Arc::new(ScopeCountingEmbedder { calls: embed_calls }), - 0.7, - 0.3, - 1000, - None, - ) - .expect("test: sqlite memory"), - ); - state.mem = memory.clone(); - memory - .create_conversation_session(SESSION, "api:local") - .await - .expect("test: session"); - memory - .create_conversation_session(SESSION_S2, "api:local") - .await - .expect("test: session s2"); - Fixture { - state, - provider, - memory, - _temp: temp, - } -} - -fn install_scope_tools(fixture: &mut Fixture) { - let workspace_dir = fixture.state.config.pin().effective.workspace_dir.clone(); - let security = Arc::new(crate::security::SecurityPolicy::from_config( - &fixture.state.config.pin().effective.autonomy, - &workspace_dir, - )); - let memory: Arc = fixture.memory.clone(); - fixture.state.tools_registry = Arc::new(vec![ - Box::new(MemoryStoreTool::new(Arc::clone(&memory), Arc::clone(&security))) as ToolBox, - Box::new(DocumentIngestTool::new(workspace_dir, memory, security)) as ToolBox, - ]); -} - -async fn post_scripted( - fixture: &mut Fixture, - provider: &str, - session: &str, - body: serde_json::Value, - tool: &'static str, - args: serde_json::Value, -) -> (StatusCode, serde_json::Value) { - let scripted = Arc::new(ScriptedCalls::batches(vec![vec![(tool, args)]])); - let provider_arc = Arc::clone(&scripted) as Arc; - crate::providers::test_fixture::register(provider, Arc::clone(&provider_arc)); - fixture.state.provider = Arc::clone(&provider_arc); - let result = post(fixture, session, body).await; - drop(provider_arc); - result -} - -fn partitioned_write_ctx(workspace: &str, owner: &str, session: &str, partition: AgentPartition) -> MemoryWriteContext { - MemoryWriteContext { - workspace_id: Some(workspace.to_owned()), - owner_id: Some(owner.to_owned()), - session_key: Some(session.to_owned()), - agent_partition: Some(partition), - channel: Some("console".to_owned()), - ..Default::default() - } -} - -fn configure_stamped_scope(config: &mut Config, endpoint: &str, provider: &str, tools: &[&str]) { - config.gateway.targeted_agents = true; - config.autonomy.level = AutonomyLevel::Full; - config.tool_tiering.always_include = tools.iter().map(|tool| (*tool).to_owned()).collect(); - capture_provider_config(config, provider, agent(true, tools)); - crate::agent::agent::native_decision_fixture::configure(config, endpoint).expect("test: decision backend"); -} - -fn truncated_content_hash(text: &str) -> String { - use sha2::{Digest, Sha256}; - Sha256::digest(text.as_bytes()) - .iter() - .take(16) - .fold(String::with_capacity(32), |mut hex, byte| { - use std::fmt::Write; - let _ = write!(hex, "{byte:02x}"); - hex - }) -} - -fn assert_named_store_row(conn: &rusqlite::Connection, key: &str, content: &str) { - let (scope, topic): (Option, Option) = conn - .query_row( - "SELECT ma_scope_id, topic_id FROM memories WHERE key = ?1", - [key], - |row| Ok((row.get(0)?, row.get(1)?)), - ) - .expect("test: stored memories row"); - assert_eq!( - scope.as_deref(), - Some(TARGET_SCOPE), - "stored memories row carries X's scope" - ); - assert!(topic.is_none(), "X's memory has topic_id NULL"); - let fts: i64 = conn - .query_row( - "SELECT count(*) FROM memories_fts f JOIN memories m ON m.rowid = f.rowid WHERE m.key = ?1", - [key], - |row| row.get(0), - ) - .expect("test: memories_fts"); - assert_eq!(fts, 1, "memories_fts carries X's memory"); - let salted: i64 = conn - .query_row( - "SELECT count(*) FROM embedding_cache WHERE ma_scope_id = ?1 AND length(content_hash) = 64", - [TARGET_SCOPE], - |row| row.get(0), - ) - .expect("test: salted cache"); - assert!(salted >= 1, "salted embedding_cache row carries X's scope"); - let plain_hash = truncated_content_hash(content); - let plain: i64 = conn - .query_row( - "SELECT count(*) FROM embedding_cache WHERE content_hash = ?1", - [plain_hash], - |row| row.get(0), - ) - .expect("test: plain hash"); - assert_eq!(plain, 0, "no plain-hash embedding_cache row for the stored text"); -} - -/// Part 2 completion of `memory_writes_carry_scope`: memory-family writers. -async fn complete_memory_family_scope_stamps() { - let driver = crate::agent::agent::native_decision_fixture::Driver::start("memory") - .await - .expect("test: decision fixture"); - let endpoint = driver.endpoint().to_owned(); - driver - .run(async move { - let mut fixture = fixture_with_scope_embedder( - |config| configure_stamped_scope(config, &endpoint, STORE_SCOPE_PROVIDER, &[STORE_TOOL]), - Arc::new(AtomicUsize::new(0)), - ) - .await; - install_scope_tools(&mut fixture); - let workspace = fixture - .state - .config - .pin() - .effective - .workspace_dir - .to_string_lossy() - .into_owned(); - let owner = super::super::super::ApiPrincipal::for_tests().owner_id; - seed_named_x(std::path::Path::new(&workspace), &workspace, &owner, SESSION); - let named = named_partition(&workspace, &owner, "x", TARGET_U); - let main = main_partition(&workspace, &owner); - let named_ctx = partitioned_write_ctx(&workspace, &owner, SESSION, named.clone()); - let main_s1 = partitioned_write_ctx(&workspace, &owner, SESSION, main.clone()); - let main_s2 = partitioned_write_ctx(&workspace, &owner, SESSION_S2, main.clone()); - - let (status, value) = post_scripted( - &mut fixture, - STORE_SCOPE_PROVIDER, - SESSION, - serde_json::json!({"message": "store-x", "agent": "x"}), - STORE_TOOL, - serde_json::json!({"key": "named-core", "content": "hi", "category": "core"}), - ) - .await; - assert_eq!(status, StatusCode::OK, "Named store POST: {value}"); - let conn = brain(&workspace); - assert_named_store_row(&conn, "named-core", "hi"); - - let (status, value) = post_scripted( - &mut fixture, - STORE_SCOPE_PROVIDER, - SESSION, - serde_json::json!({"message": "store-main"}), - STORE_TOOL, - serde_json::json!({"key": "main-core", "content": "ok", "category": "core"}), - ) - .await; - assert_eq!(status, StatusCode::OK, "Main store POST: {value}"); - let main_scope: String = conn - .query_row( - "SELECT ma_scope_id FROM memories WHERE key = 'main-core'", - [], - |row| row.get::<_, Option>(0), - ) - .expect("test: main store") - .expect("test: main stamp"); - - fixture - .memory - .store_with_context("session-key", "s1", MemoryCategory::Core, None, Some(&main_s1)) - .await - .expect("test: Main S1"); - fixture - .memory - .store_with_context("session-key", "s2", MemoryCategory::Core, None, Some(&main_s2)) - .await - .expect("test: Main S2"); - let s2_scope: String = conn - .query_row( - "SELECT ma_scope_id FROM memories WHERE key = 'session-key'", - [], - |row| row.get::<_, Option>(0), - ) - .expect("test: S2 row") - .expect("test: S2 stamp"); - let s2_id: String = conn - .query_row( - "SELECT scope_id FROM agent_scopes WHERE session_key = ?1 AND agent_key = 'm'", - [SESSION_S2], - |row| row.get(0), - ) - .expect("test: S2 scope"); - assert_eq!(s2_scope, s2_id, "Main S2 write carries the S2 scope"); - - conn.execute( - "INSERT INTO memories (id, key, content, category, created_at, updated_at) VALUES ('legacy-1', 'legacy-null', 'old', 'core', 't', 't')", - [], - ) - .expect("test: null legacy"); - fixture - .memory - .store_with_context("legacy-null", "new", MemoryCategory::Core, None, Some(&main_s1)) - .await - .expect("test: Main over NULL"); - let stamped: Option = conn - .query_row("SELECT ma_scope_id FROM memories WHERE key = 'legacy-null'", [], |row| { - row.get(0) - }) - .expect("test: legacy stamp"); - assert!(stamped.is_some(), "Main over a NULL legacy row succeeds"); - - conn.execute( - "INSERT INTO memories (id, key, content, category, created_at, updated_at) VALUES ('null-2', 'named-over-null', 'keep', 'core', 't', 't')", - [], - ) - .expect("test: named-over-null seed"); - let cache_before: i64 = conn - .query_row("SELECT count(*) FROM embedding_cache", [], |row| row.get(0)) - .expect("test: cache before refuse"); - let refused = fixture - .memory - .store_with_context( - "named-over-null", - "take", - MemoryCategory::Core, - None, - Some(&named_ctx), - ) - .await - .expect_err("test: Named over NULL"); - assert!( - refused.downcast_ref::().is_some(), - "Named over NULL: {refused:#}" - ); - let kept: String = conn - .query_row("SELECT content FROM memories WHERE key = 'named-over-null'", [], |row| { - row.get(0) - }) - .expect("test: original"); - assert_eq!(kept, "keep", "original unchanged"); - let cache_after: i64 = conn - .query_row("SELECT count(*) FROM embedding_cache", [], |row| row.get(0)) - .expect("test: cache after refuse"); - assert_eq!(cache_after, cache_before, "a refused write leaves no embedding_cache row"); - - let foreign = fixture - .memory - .store_with_context("foreign-key", "main-owns", MemoryCategory::Core, None, Some(&main_s1)) - .await; - foreign.expect("test: foreign seed"); - let refused = fixture - .memory - .store_with_context("foreign-key", "named-take", MemoryCategory::Core, None, Some(&named_ctx)) - .await - .expect_err("test: Named over foreign"); - assert!( - refused.downcast_ref::().is_some(), - "Named over foreign: {refused:#}" - ); - - let refused = fixture - .memory - .store("named-core", "unstamped", MemoryCategory::Core, None) - .await - .expect_err("test: unstamped over Named"); - assert!( - refused.downcast_ref::().is_some(), - "unstamped over Named: {refused:#}" - ); - fixture - .memory - .store("main-core", "ctx-less-main", MemoryCategory::Core, None) - .await - .expect("test: ctx-less over Main"); - let kept_main: Option = conn - .query_row("SELECT ma_scope_id FROM memories WHERE key = 'main-core'", [], |row| { - row.get(0) - }) - .expect("test: ctx-less main stamp"); - assert_eq!(kept_main.as_deref(), Some(main_scope.as_str()), "ctx-less upsert keeps the Main stamp"); - - let draft = fixture - .memory - .create_memory_draft(MemoryDraftInput { - agent_partition: Some(named.clone()), - draft_id: Some("draft-named".to_owned()), - workspace_id: workspace.clone(), - owner_id: Some(owner.clone()), - worker_run_id: "run-1".to_owned(), - parent_run_id: None, - session_key: Some(SESSION.to_owned()), - agent_id: None, - persona_id: None, - key: "main-core".to_owned(), - content: "draft-take".to_owned(), - category: MemoryCategory::Core, - source_event_id: None, - visibility: MemoryVisibility::Workspace, - payload_json: None, - }) - .await - .expect("test: named draft"); - let principal = history_reader(&workspace, SESSION, named.clone()); - let merge_err = fixture - .memory - .merge_memory_draft(&principal, &draft.draft_id) - .await - .expect_err("test: Named draft merge over Main"); - assert!( - merge_err.downcast_ref::().is_some(), - "Named draft merge over Main: {merge_err:#}" - ); - - fixture - .memory - .append_retrieval_trace(RetrievalTraceInput { - agent_partition: Some(main.clone()), - trace_id: Some("trace-shared".to_owned()), - workspace_id: workspace.clone(), - owner_id: Some(owner.clone()), - session_key: Some(SESSION.to_owned()), - agent_id: None, - persona_id: None, - source: "test".to_owned(), - query: "q".to_owned(), - candidate_count: 1, - selected_count: 1, - dropped_count: 0, - budget_tokens: None, - selected_json: None, - dropped_json: None, - payload_json: None, - }) - .await - .expect("test: main trace"); - let trace_err = fixture - .memory - .append_retrieval_trace(RetrievalTraceInput { - agent_partition: Some(named.clone()), - trace_id: Some("trace-shared".to_owned()), - workspace_id: workspace.clone(), - owner_id: Some(owner.clone()), - session_key: Some(SESSION.to_owned()), - agent_id: None, - persona_id: None, - source: "test".to_owned(), - query: "q2".to_owned(), - candidate_count: 1, - selected_count: 1, - dropped_count: 0, - budget_tokens: None, - selected_json: None, - dropped_json: None, - payload_json: None, - }) - .await - .expect_err("test: trace collision"); - assert!( - trace_err.downcast_ref::().is_some(), - "trace_id collision: {trace_err:#}" - ); - - fixture - .memory - .append_compaction_run(CompactionRunInput { - agent_partition: Some(main.clone()), - run_id: Some("run-shared".to_owned()), - workspace_id: workspace.clone(), - owner_id: Some(owner.clone()), - session_key: Some(SESSION.to_owned()), - agent_id: None, - persona_id: None, - trigger: "test".to_owned(), - mode: "summary".to_owned(), - source_message_count: 1, - source_token_estimate: 1, - summary: "s".to_owned(), - summary_memory_key: None, - source_event_ids_json: None, - source_event_range_json: None, - source_document_refs_json: None, - fidelity_status: "full".to_owned(), - payload_json: None, - }) - .await - .expect("test: main compaction"); - let run_err = fixture - .memory - .append_compaction_run(CompactionRunInput { - agent_partition: Some(named.clone()), - run_id: Some("run-shared".to_owned()), - workspace_id: workspace.clone(), - owner_id: Some(owner.clone()), - session_key: Some(SESSION.to_owned()), - agent_id: None, - persona_id: None, - trigger: "test".to_owned(), - mode: "summary".to_owned(), - source_message_count: 1, - source_token_estimate: 1, - summary: "other".to_owned(), - summary_memory_key: None, - source_event_ids_json: None, - source_event_range_json: None, - source_document_refs_json: None, - fidelity_status: "full".to_owned(), - payload_json: None, - }) - .await - .expect_err("test: run collision"); - assert!( - run_err.downcast_ref::().is_some(), - "run_id collision: {run_err:#}" - ); - - let fabric = MemoryFabric::new(fixture.memory.clone(), workspace.clone()); - let envelope = crate::runtime::envelope::RuntimeEnvelope::console(workspace.clone(), SESSION.to_owned()) - .with_agent_partition(named.clone()) - .with_owner_id(owner.clone()); - let draft = fabric - .create_worker_memory_draft( - &envelope.message_scope(), - "run-fabric", - "fabric-draft", - "fabric body", - MemoryCategory::Core, - None, - None, - ) - .await - .expect("test: fabric draft"); - let draft_scope: Option = conn - .query_row( - "SELECT ma_scope_id FROM memory_drafts WHERE draft_id = ?1", - [&draft.draft_id], - |row| row.get(0), - ) - .expect("test: draft stamp"); - assert_eq!(draft_scope.as_deref(), Some(TARGET_SCOPE)); - fixture - .memory - .reject_memory_draft(&principal, &draft.draft_id, Some("no")) - .await - .expect("test: fabric reject"); - let event_scope: Option = conn - .query_row( - "SELECT ma_scope_id FROM memory_events WHERE subject_id = ?1 AND event_type = 'memory.draft.rejected'", - [&draft.draft_id], - |row| row.get(0), - ) - .expect("test: reject event"); - assert_eq!(event_scope.as_deref(), Some(TARGET_SCOPE), "derived draft event equals parent scope"); - - fixture - .memory - .move_to_trash("named-core", "test", 7) - .await - .expect("test: trash"); - let trash_scope: Option = conn - .query_row( - "SELECT ma_scope_id FROM memory_trash WHERE memory_key = 'named-core'", - [], - |row| row.get(0), - ) - .expect("test: trash stamp"); - assert_eq!(trash_scope.as_deref(), Some(TARGET_SCOPE)); - }) - .await; -} - -#[tokio::test] -async fn documents_writes_carry_scope() { - let driver = crate::agent::agent::native_decision_fixture::Driver::start("document") - .await - .expect("test: decision fixture"); - let endpoint = driver.endpoint().to_owned(); - driver - .run(async move { - let mut fixture = fixture_with_scope_embedder( - |config| configure_stamped_scope(config, &endpoint, DOC_SCOPE_PROVIDER, &[INGEST_TOOL]), - Arc::new(AtomicUsize::new(0)), - ) - .await; - install_scope_tools(&mut fixture); - let workspace = fixture - .state - .config - .pin() - .effective - .workspace_dir - .to_string_lossy() - .into_owned(); - let owner = super::super::super::ApiPrincipal::for_tests().owner_id; - seed_named_x(std::path::Path::new(&workspace), &workspace, &owner, SESSION); - let named = named_partition(&workspace, &owner, "x", TARGET_U); - let main = main_partition(&workspace, &owner); - let body = format!( - "# First heading\n{}\n\n# Second heading\n{}", - "alpha ".repeat(400), - "bravo ".repeat(400) - ); - let (status, value) = post_scripted( - &mut fixture, - DOC_SCOPE_PROVIDER, - SESSION, - serde_json::json!({"message": "ingest-x", "agent": "x"}), - INGEST_TOOL, - serde_json::json!({"content": body, "title": "named-doc", "document_id": "doc-x"}), - ) - .await; - assert_eq!(status, StatusCode::OK, "Named ingest POST: {value}"); - let conn = brain(&workspace); - let stored_docs: Vec<(String, Option)> = conn - .prepare("SELECT document_id, title FROM documents") - .expect("test: list documents") - .query_map([], |row| Ok((row.get(0)?, row.get(1)?))) - .expect("test: document rows") - .map(|row| row.expect("test: document row")) - .collect(); - let (doc_id, doc_scope): (String, Option) = conn - .query_row( - "SELECT document_id, ma_scope_id FROM documents WHERE title = 'named-doc'", - [], - |row| Ok((row.get(0)?, row.get(1)?)), - ) - .unwrap_or_else(|error| { - panic!("test: documents row: {error}; post={value}; stored={stored_docs:?}") - }); - assert_eq!( - doc_scope.as_deref(), - Some(TARGET_SCOPE), - "documents row carries X's scope" - ); - let chunks: i64 = conn - .query_row( - "SELECT count(*) FROM document_chunks WHERE document_id = ?1", - [&doc_id], - |row| row.get(0), - ) - .expect("test: chunks"); - assert!(chunks > 1, "multi-chunk body"); - let chunk_null: i64 = conn - .query_row( - "SELECT count(*) FROM document_chunks WHERE document_id = ?1 AND (ma_scope_id IS NULL OR ma_scope_id != ?2)", - rusqlite::params![&doc_id, TARGET_SCOPE], - |row| row.get(0), - ) - .expect("test: chunk stamps"); - assert_eq!(chunk_null, 0, "every document_chunks row carries X's scope"); - let events: i64 = conn - .query_row( - "SELECT count(*) FROM memory_events WHERE subject_table = 'documents' AND subject_id = ?1 AND ma_scope_id = ?2", - rusqlite::params![&doc_id, TARGET_SCOPE], - |row| row.get(0), - ) - .expect("test: document events"); - assert!(events >= 1, "document memory_events carry X's scope"); - let salted: i64 = conn - .query_row( - "SELECT count(*) FROM embedding_cache WHERE ma_scope_id = ?1 AND length(content_hash) = 64", - [TARGET_SCOPE], - |row| row.get(0), - ) - .expect("test: chunk cache"); - assert!(salted >= 1, "chunk embeddings are salted cache rows"); - let fts: i64 = conn - .query_row( - "SELECT count(*) FROM document_chunks_fts f JOIN document_chunks c ON c.rowid = f.rowid WHERE c.document_id = ?1", - [&doc_id], - |row| row.get(0), - ) - .expect("test: chunks fts"); - assert!(fts > 1, "document_chunks_fts matches"); - - let fabric = MemoryFabric::new(fixture.memory.clone(), workspace.clone()); - let marker = format!("[document_ingest_ref]\ndocument_id: {doc_id}\n[/document_ingest_ref]"); - fabric - .record_semantic_memory_from_event( - "semantic-x", - &marker, - MemoryCategory::Core, - Some(SESSION), - None, - None, - None, - Some(named.clone()), - ) - .await - .expect("test: semantic link"); - let link_scope: Option = conn - .query_row( - "SELECT ma_scope_id FROM memory_links WHERE document_id = ?1", - [&doc_id], - |row| row.get(0), - ) - .expect("test: link stamp"); - assert_eq!(link_scope.as_deref(), Some(TARGET_SCOPE), "memory_links row carries X's scope"); - let promoted_scope: Option = conn - .query_row( - "SELECT ma_scope_id FROM memories WHERE key = 'semantic-x'", - [], - |row| row.get(0), - ) - .expect("test: promoted memories stamp"); - assert_eq!( - promoted_scope.as_deref(), - Some(TARGET_SCOPE), - "promoted memories row carries X's scope" - ); - let promoted_event: Option = conn - .query_row( - "SELECT ma_scope_id FROM memory_events WHERE subject_id = 'semantic-x' AND event_type = 'memory.stored'", - [], - |row| row.get(0), - ) - .expect("test: promoted memory_events stamp"); - assert_eq!( - promoted_event.as_deref(), - Some(TARGET_SCOPE), - "promoted memory_events row carries X's scope" - ); - - fixture - .memory - .ingest_document(crate::memory::DocumentIngestInput { - agent_partition: None, - document_id: Some("doc-null".to_owned()), - workspace_id: workspace.clone(), - owner_id: Some(owner.clone()), - topic_id: None, - task_id: None, - source_message_event_id: None, - source_kind: "test".to_owned(), - source_uri: None, - title: Some("null".to_owned()), - content: "null document".to_owned(), - mime_type: None, - visibility: MemoryVisibility::Workspace, - metadata_json: None, - session_key: Some(SESSION.to_owned()), - agent_id: None, - persona_id: None, - }) - .await - .expect("test: null document"); - fixture - .memory - .link_memory_source(crate::memory::MemoryLinkInput { - agent_partition: Some(main.clone()), - session_key: Some(SESSION.to_owned()), - link_id: Some("link-main-null".to_owned()), - workspace_id: workspace.clone(), - owner_id: Some(owner.clone()), - memory_key: Some("semantic-x".to_owned()), - memory_event_id: None, - message_event_id: None, - document_id: "doc-null".to_owned(), - chunk_id: None, - link_type: "derived_from".to_owned(), - payload_json: None, - }) - .await - .expect("test: Main may link a NULL document"); - let named_null = fixture - .memory - .link_memory_source(crate::memory::MemoryLinkInput { - agent_partition: Some(named.clone()), - session_key: Some(SESSION.to_owned()), - link_id: Some("link-named-null".to_owned()), - workspace_id: workspace.clone(), - owner_id: Some(owner.clone()), - memory_key: Some("semantic-x".to_owned()), - memory_event_id: None, - message_event_id: None, - document_id: "doc-null".to_owned(), - chunk_id: None, - link_type: "derived_from".to_owned(), - payload_json: None, - }) - .await - .expect_err("test: Named may not link a NULL document"); - assert!( - named_null.downcast_ref::().is_some(), - "Named NULL document link: {named_null:#}" - ); - - fixture - .memory - .ingest_document(crate::memory::DocumentIngestInput { - agent_partition: Some(main.clone()), - document_id: Some("doc-collide".to_owned()), - workspace_id: workspace.clone(), - owner_id: Some(owner.clone()), - topic_id: None, - task_id: None, - source_message_event_id: None, - source_kind: "test".to_owned(), - source_uri: None, - title: Some("main".to_owned()), - content: "main document".to_owned(), - mime_type: None, - visibility: MemoryVisibility::Workspace, - metadata_json: None, - session_key: Some(SESSION.to_owned()), - agent_id: None, - persona_id: None, - }) - .await - .expect("test: main collide seed"); - let collide = fixture - .memory - .ingest_document(crate::memory::DocumentIngestInput { - agent_partition: Some(named.clone()), - document_id: Some("doc-collide".to_owned()), - workspace_id: workspace.clone(), - owner_id: Some(owner.clone()), - topic_id: None, - task_id: None, - source_message_event_id: None, - source_kind: "test".to_owned(), - source_uri: None, - title: Some("named".to_owned()), - content: "named document".to_owned(), - mime_type: None, - visibility: MemoryVisibility::Workspace, - metadata_json: None, - session_key: Some(SESSION.to_owned()), - agent_id: None, - persona_id: None, - }) - .await - .expect_err("test: cross-scope document_id"); - assert!( - collide.downcast_ref::().is_some(), - "cross-scope document_id: {collide:#}" - ); - let title: String = conn - .query_row("SELECT title FROM documents WHERE document_id = 'doc-collide'", [], |row| { - row.get(0) - }) - .expect("test: original title"); - assert_eq!(title, "main", "original unchanged"); - - let (status, value) = post_scripted( - &mut fixture, - DOC_SCOPE_PROVIDER, - SESSION, - serde_json::json!({"message": "ingest-main"}), - INGEST_TOOL, - serde_json::json!({"content": "main control document", "title": "main-doc", "document_id": "doc-main"}), - ) - .await; - assert_eq!(status, StatusCode::OK, "Main ingest POST: {value}"); - let main_doc: Option = conn - .query_row( - "SELECT ma_scope_id FROM documents WHERE title = 'main-doc'", - [], - |row| row.get(0), - ) - .expect("test: main document"); - assert!(main_doc.is_some(), "Main control document is stamped"); - }) - .await; -} - -#[tokio::test] -async fn topics_writes_carry_scope() { - let driver = crate::agent::agent::native_decision_fixture::Driver::start("memory") - .await - .expect("test: decision fixture"); - let endpoint = driver.endpoint().to_owned(); - driver - .run(async move { - let mut fixture = fixture_with_scope_embedder( - |config| configure_stamped_scope(config, &endpoint, TOPIC_SCOPE_PROVIDER, &[STORE_TOOL]), - Arc::new(AtomicUsize::new(0)), - ) - .await; - install_scope_tools(&mut fixture); - let workspace = fixture - .state - .config - .pin() - .effective - .workspace_dir - .to_string_lossy() - .into_owned(); - let owner = super::super::super::ApiPrincipal::for_tests().owner_id; - seed_named_x(std::path::Path::new(&workspace), &workspace, &owner, SESSION); - let main = main_partition(&workspace, &owner); - let shared = "prx shared topic collision body for named isolation"; - let seed_ctx = MemoryWriteContext { - workspace_id: Some(workspace.clone()), - owner_id: Some(owner.clone()), - session_key: Some(SESSION.to_owned()), - agent_partition: None, - channel: Some("console".to_owned()), - ..Default::default() - }; - fixture - .memory - .store_with_context( - "shared-topic-seed", - shared, - MemoryCategory::Core, - None, - Some(&seed_ctx), - ) - .await - .expect("test: shared topic seed"); - let conn = brain(&workspace); - let (shared_id, shared_updated, shared_scope): (String, String, Option) = conn - .query_row( - "SELECT id, updated_at, ma_scope_id FROM topics ORDER BY id LIMIT 1", - [], - |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), - ) - .expect("test: shared topic"); - - let (status, value) = post_scripted( - &mut fixture, - TOPIC_SCOPE_PROVIDER, - SESSION, - serde_json::json!({"message": "topic-x", "agent": "x"}), - STORE_TOOL, - serde_json::json!({"key": "named-shared", "content": shared, "category": "core"}), - ) - .await; - assert_eq!(status, StatusCode::OK, "Named shared-topic POST: {value}"); - let (updated_at, scope): (String, Option) = conn - .query_row( - "SELECT updated_at, ma_scope_id FROM topics WHERE id = ?1", - [&shared_id], - |row| Ok((row.get(0)?, row.get(1)?)), - ) - .expect("test: shared after"); - assert_eq!(updated_at, shared_updated, "shared-topic-unchanged updated_at"); - assert_eq!(scope, shared_scope, "shared-topic-unchanged ma_scope_id"); - let named_topic: Option = conn - .query_row( - "SELECT topic_id FROM memories WHERE key = 'named-shared'", - [], - |row| row.get(0), - ) - .expect("test: named topic_id"); - assert!(named_topic.is_none(), "X's memory has topic_id NULL"); - - let unique = "prx unique named topic body for isolation test"; - let (status, value) = post_scripted( - &mut fixture, - TOPIC_SCOPE_PROVIDER, - SESSION, - serde_json::json!({"message": "topic-x-unique", "agent": "x"}), - STORE_TOOL, - serde_json::json!({"key": "named-unique", "content": unique, "category": "core"}), - ) - .await; - assert_eq!(status, StatusCode::OK, "Named unique-topic POST: {value}"); - let x_topics: i64 = conn - .query_row( - "SELECT count(*) FROM topics WHERE ma_scope_id = ?1", - [TARGET_SCOPE], - |row| row.get(0), - ) - .expect("test: X topics"); - assert_eq!(x_topics, 1, "X's memory_store creates a topics row stamped X"); - let fts: i64 = conn - .query_row( - "SELECT count(*) FROM topics_fts f JOIN topics t ON t.rowid = f.rowid WHERE t.ma_scope_id = ?1", - [TARGET_SCOPE], - |row| row.get(0), - ) - .expect("test: topics_fts"); - assert_eq!(fts, 1, "topics_fts has X's topic only"); - let participants: i64 = conn - .query_row( - "SELECT count(*) FROM topic_participants WHERE topic_id IN (SELECT id FROM topics WHERE ma_scope_id = ?1)", - [TARGET_SCOPE], - |row| row.get(0), - ) - .expect("test: participants"); - assert_eq!(participants, 0, "topic_participants have no X rows"); - let aliases: i64 = conn - .query_row("SELECT count(*) FROM topic_aliases", [], |row| row.get(0)) - .expect("test: aliases"); - assert_eq!(aliases, 0, "topic_aliases have no X rows"); - - let main_ctx = partitioned_write_ctx(&workspace, &owner, SESSION, main); - fixture - .memory - .store_with_context("main-unique", "prx main unique topic body for reuse", MemoryCategory::Core, None, Some(&main_ctx)) - .await - .expect("test: Main unique topic"); - fixture - .memory - .store_with_context("main-shared", shared, MemoryCategory::Core, None, Some(&main_ctx)) - .await - .expect("test: Main reuses NULL/Main topic"); - let main_reuse: Option = conn - .query_row( - "SELECT topic_id FROM memories WHERE key = 'main-shared'", - [], - |row| row.get(0), - ) - .expect("test: main reuse"); - assert_eq!(main_reuse.as_deref(), Some(shared_id.as_str()), "Main reuses a NULL/Main topic as today"); - }) - .await; -} +include!("targeting/section_1.rs"); +include!("targeting/section_2.rs"); diff --git a/src/gateway/api/sessions/tests/targeting/section_1.rs b/src/gateway/api/sessions/tests/targeting/section_1.rs new file mode 100644 index 000000000..34e39bd45 --- /dev/null +++ b/src/gateway/api/sessions/tests/targeting/section_1.rs @@ -0,0 +1,1538 @@ +use super::*; +use crate::config::DelegateAgentConfig; +use crate::config::agent_name::{AGENT_NAME_MAX_LEN, AgentName, AgentNameError, is_targetable}; +use crate::memory::embeddings::EmbeddingProvider; +use crate::memory::owner_predicate::OwnerScopedStoreRefusal; +use crate::memory::{ + AgentPartition, AgentScopeRefused, AgentScopeUnsupported, CompactionRunInput, Memory, MemoryCategory, + MemoryDraftInput, MemoryFabric, MemoryPrincipal, MemoryVisibility, MemoryWriteContext, NoneMemory, PartitionKey, + RetrievalTraceInput, +}; +use crate::security::AutonomyLevel; +use crate::tools::document_ingest::DocumentIngestTool; +use crate::tools::memory_store::MemoryStoreTool; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use super::super::target::{AgentField, TargetError, TurnTarget, resolve_target}; +use crate::security::agent_level::agent_level as effective_autonomy; + +fn agent(agentic: bool, allowed_tools: &[&str]) -> DelegateAgentConfig { + DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), + approval_wait_secs: 600, + limits: crate::config::AgentLimits::default(), + provider: "ollama".to_owned(), + model: "test-model".to_owned(), + system_prompt: None, + api_key: None, + credential_ref: None, + temperature: None, + max_depth: 8, + agentic, + allowed_tools: allowed_tools.iter().map(|name| (*name).to_owned()).collect(), + identity_dir: None, + memory_scope: None, + spawn_enabled: None, + enabled: true, + autonomy: None, + } +} + +fn config_with(agents: Vec<(&str, DelegateAgentConfig)>, switch: bool) -> Config { + let mut config = Config::default(); + config.gateway.targeted_agents = switch; + config.agents = agents.into_iter().map(|(name, cfg)| (name.to_owned(), cfg)).collect(); + config +} + +fn named(raw: &str) -> TurnTarget { + TurnTarget::from_field(AgentField::Text(raw.to_owned())).expect("test: a valid name") +} + +fn http_request(body: serde_json::Value) -> Request { + let mut request = Request::builder() + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(body.to_string())) + .expect("test: request"); + request + .extensions_mut() + .insert(super::super::super::ApiPrincipal::for_tests()); + request +} + +struct Fixture { + state: AppState, + provider: Arc, + memory: Arc, + _temp: tempfile::TempDir, +} + +const SESSION: &str = "prx-target-session"; + +async fn fixture(config: impl FnOnce(&mut Config)) -> Fixture { + let temp = tempfile::tempdir().expect("test: tempdir"); + let mut base = Config::default(); + base.workspace_dir = temp.path().to_owned(); + config(&mut base); + let provider = Arc::new(CapturingProvider::default()); + let mut state = test_app_state(base, provider.clone()); + let memory = Arc::new(crate::memory::SqliteMemory::new(temp.path()).expect("test: sqlite memory")); + state.mem = memory.clone(); + memory + .create_conversation_session(SESSION, "api:local") + .await + .expect("test: session"); + Fixture { + state, + provider, + memory, + _temp: temp, + } +} + +/// Like [`fixture`], but keeps a caller-configured decision backend and the +/// Console private-filesystem layout `drive()` uses. +/// +/// `test_app_state` (`sessions.rs`) would drop +/// the native-tool surface this POST needs, even after `configure(...)`. +/// Default `config_path` is the user config dir; without a temp private root, +/// `console_filesystem` stays `None` and owner-isolated `file_read` is gated. +async fn fixture_with_decision_backend(config: impl FnOnce(&mut Config)) -> Fixture { + let temp = tempfile::tempdir().expect("test: tempdir"); + let workspace = temp.path().join("workspace"); + let private = temp.path().join("private"); + std::fs::create_dir_all(&workspace).expect("test: workspace"); + std::fs::create_dir_all(&private).expect("test: private root"); + let mut base = Config::default(); + base.workspace_dir = workspace.clone(); + base.config_path = private.join("config.toml"); + config(&mut base); + let provider = Arc::new(CapturingProvider::default()); + let mut state = test_app_state_with_config(base, provider.clone()); + let memory = Arc::new(crate::memory::SqliteMemory::new(&workspace).expect("test: sqlite memory")); + state.mem = memory.clone(); + memory + .create_conversation_session(SESSION, "api:local") + .await + .expect("test: session"); + Fixture { + state, + provider, + memory, + _temp: temp, + } +} + +async fn post(fixture: &Fixture, session: &str, body: serde_json::Value) -> (StatusCode, serde_json::Value) { + let response = post_session_message( + State(fixture.state.clone()), + Path(session.to_owned()), + http_request(body), + ) + .await + .into_response(); + let status = response.status(); + let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024) + .await + .expect("test: body"); + (status, serde_json::from_slice(&bytes).expect("test: json body")) +} + +fn error_code(body: &serde_json::Value) -> Option<&str> { + body.pointer("/error/code").and_then(serde_json::Value::as_str) +} + +async fn assert_untouched(fixture: &Fixture) { + assert!(fixture.provider.requests.lock().is_empty(), "no provider access"); + let stored = fixture + .memory + .get_conversation_session(SESSION) + .await + .expect("test: read session") + .expect("test: session exists"); + assert_eq!(stored.message_count, 0, "no input was recorded"); +} + +#[tokio::test] +async fn target_selector_preserves_main() { + // Omission and "main" reach the Main path (here: the session lookup, which + // answers a plain string error for a session that does not exist), with the + // switch off and on, and whatever `[agents.main]` holds. + for switch in [false, true] { + let fixture = fixture(|config| { + config.gateway.targeted_agents = switch; + config.agents.insert("main".to_owned(), agent(false, &[])); + }) + .await; + for body in [ + serde_json::json!({"message": "hello"}), + serde_json::json!({"message": "hello", "agent": "main"}), + ] { + let (status, value) = post(&fixture, "no-such-session", body).await; + assert_eq!(status, StatusCode::NOT_FOUND); + assert_eq!( + value.get("error").and_then(serde_json::Value::as_str), + Some("Session not found"), + "the Main path was entered: {value}" + ); + } + // Explicit null is the one refused spelling. + let (status, value) = post( + &fixture, + SESSION, + serde_json::json!({"message": "hello", "agent": null}), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(error_code(&value), Some("agent_invalid")); + let (status, value) = post(&fixture, SESSION, serde_json::json!({"message": "hello", "agent": 7})).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(error_code(&value), Some("agent_invalid")); + assert_untouched(&fixture).await; + } + assert_eq!(TurnTarget::from_field(AgentField::Omitted), Ok(TurnTarget::Main)); + assert_eq!( + TurnTarget::from_field(AgentField::Text("main".to_owned())), + Ok(TurnTarget::Main) + ); + assert_eq!(TurnTarget::from_field(AgentField::Null), Err(TargetError::Invalid)); +} + +#[tokio::test] +async fn target_unknown_or_disabled_has_no_effects() { + let mut off = agent(false, &[]); + off.enabled = false; + // Switch off: every otherwise-valid named target is 409, existing or not, + // and never runs as Main. + let closed = fixture(|config| { + config.agents.insert("helper".to_owned(), agent(false, &[])); + }) + .await; + for name in ["helper", "ghost"] { + let (status, value) = post(&closed, SESSION, serde_json::json!({"message": "hi", "agent": name})).await; + assert_eq!(status, StatusCode::CONFLICT, "{name}: {value}"); + assert_eq!(error_code(&value), Some("agent_disabled")); + } + assert_untouched(&closed).await; + + // Switch on: unknown is 404, disabled is 409, both resolved before the + // session lookup, so even a missing session reports the target error. + let open = fixture(|config| { + config.gateway.targeted_agents = true; + config.agents.insert("helper".to_owned(), agent(false, &[])); + config.agents.insert("sleeper".to_owned(), off); + }) + .await; + for (name, session, status, code) in [ + ("ghost", SESSION, StatusCode::NOT_FOUND, "agent_unknown"), + ("sleeper", SESSION, StatusCode::CONFLICT, "agent_disabled"), + ("ghost", "no-such-session", StatusCode::NOT_FOUND, "agent_unknown"), + ] { + let (got, value) = post(&open, session, serde_json::json!({"message": "hi", "agent": name})).await; + assert_eq!(got, status, "{name}: {value}"); + assert_eq!(error_code(&value), Some(code)); + } + assert_untouched(&open).await; +} + +#[test] +fn target_autonomy_is_capped() { + use AutonomyLevel::{Full, ReadOnly, Supervised}; + for (agent_level, main, expected) in [ + (None, Supervised, Supervised), + (Some(Full), Supervised, Full), + (Some(ReadOnly), Full, ReadOnly), + (Some(Supervised), Full, Supervised), + (Some(Full), ReadOnly, Full), + (Some(Full), Full, Full), + ] { + assert_eq!(effective_autonomy(agent_level, main), expected); + } + + let mut capped = agent(false, &[]); + capped.autonomy = Some(Full); + let mut config = config_with(vec![("worker", capped)], true); + config.autonomy.level = Supervised; + let plan = resolve_target(&config, &named("worker")) + .expect("test: resolves") + .expect("test: a named plan"); + assert_eq!(plan.autonomy, Full, "a named agent runs at its own level"); + // The policy the target's turn is published with carries that level. + let mut snapshot = config.clone(); + snapshot.autonomy.level = plan.autonomy; + assert_eq!( + crate::runtime::bootstrap::build_security_policy(&snapshot).autonomy, + Full + ); + + config.agents.get_mut("worker").expect("test: worker").autonomy = Some(ReadOnly); + config.autonomy.level = Full; + let plan = resolve_target(&config, &named("worker")) + .expect("test: resolves") + .expect("test: a named plan"); + assert_eq!(plan.autonomy, ReadOnly, "a lower sub-agent level is kept"); +} + +#[test] +fn agent_name_rejects_invalid_start() { + for raw in [ + "", + "1agent", + "9", + "Agent", + "A", + "-agent", + "_agent", + " agent", + "\u{e9}agent", + ] { + assert_eq!(AgentName::parse(raw), Err(AgentNameError::InvalidStart), "{raw:?}"); + assert_eq!( + TurnTarget::from_field(AgentField::Text(raw.to_owned())), + Err(TargetError::Invalid), + "{raw:?}" + ); + } +} + +#[tokio::test] +async fn agent_name_rejects_invalid_characters() { + for raw in [ + "a b", "a/b", "a.b", "a\\b", "a\u{e9}", "a\u{3b1}", "aB", "a\u{0}", "a\n", "a%2Fb", + ] { + assert_eq!(AgentName::parse(raw), Err(AgentNameError::InvalidCharacter), "{raw:?}"); + } + let fixture = fixture(|config| config.gateway.targeted_agents = true).await; + let (status, value) = post(&fixture, SESSION, serde_json::json!({"message": "hi", "agent": "a b"})).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(error_code(&value), Some("agent_invalid")); + assert_untouched(&fixture).await; +} + +#[tokio::test] +async fn agent_name_rejects_overlength() { + assert!(AgentName::parse(&"a".repeat(AGENT_NAME_MAX_LEN)).is_ok()); + let long = "a".repeat(AGENT_NAME_MAX_LEN + 1); + assert_eq!(AgentName::parse(&long), Err(AgentNameError::TooLong)); + let fixture = fixture(|config| config.gateway.targeted_agents = true).await; + let (status, value) = post(&fixture, SESSION, serde_json::json!({"message": "hi", "agent": long})).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(error_code(&value), Some("agent_invalid")); + assert_untouched(&fixture).await; +} + +#[tokio::test] +async fn agent_name_is_exact_at_all_ingresses() { + // Config load: non-conforming and reserved legacy names load (with a + // warning) for delegate/spawn, but are never targetable. + let config = config_with( + vec![ + ("main", agent(false, &[])), + ("Researcher", agent(false, &[])), + ("white space", agent(false, &[])), + ("ok-agent", agent(false, &[])), + ], + true, + ); + config.validate().expect("test: legacy agent names still load"); + for key in config.agents.keys() { + assert_eq!(is_targetable(key), key == "ok-agent", "{key}"); + } + assert!( + resolve_target(&config, &named("ok-agent")) + .expect("test: resolves") + .is_some() + ); + + // Request field / decoded path segment: exact match, no folding or trimming. + for raw in [ + "Researcher", + "OK-AGENT", + "Ok-Agent", + " ok-agent", + "ok-agent ", + "ok-agent\n", + "white space", + ] { + assert_eq!( + TurnTarget::from_field(AgentField::Text(raw.to_owned())), + Err(TargetError::Invalid), + "{raw:?}" + ); + } + // `main` is the one explicit Main spelling; it never resolves to the legacy entry. + assert_eq!( + TurnTarget::from_field(AgentField::Text("main".to_owned())), + Ok(TurnTarget::Main) + ); + assert!( + resolve_target(&config, &TurnTarget::Main) + .expect("test: Main resolves") + .is_none() + ); + + // Over HTTP the same strings are refused before any effect. + let fixture = fixture(|cfg| { + cfg.gateway.targeted_agents = true; + cfg.agents.insert("ok-agent".to_owned(), agent(false, &[])); + }) + .await; + for raw in ["OK-AGENT", "Researcher", " ok-agent"] { + let (status, value) = post(&fixture, SESSION, serde_json::json!({"message": "hi", "agent": raw})).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{raw:?}"); + assert_eq!(error_code(&value), Some("agent_invalid")); + } + assert_untouched(&fixture).await; +} + +// ── Enforcement through the real targeted console turn ────────────────────── +// +// These tests run `run_console_runtime_turn` with a target built by the real +// `resolve_target` and `prepare_target` (capped policy, per-target decision +// slot and published tool surface). Only the model transport is scripted: the +// target's provider instance is replaced by a provider that emits fixed tool +// calls, and its binding is rebuilt around that instance. + +type ToolBox = Box; + +/// Queue of call batches. Each `chat` pops one; an empty queue answers in text. +struct ScriptedCalls { + batches: parking_lot::Mutex>>, + requests: parking_lot::Mutex>>, +} + +impl ScriptedCalls { + fn batches(batches: Vec>) -> Self { + Self { + batches: parking_lot::Mutex::new(batches), + requests: parking_lot::Mutex::new(Vec::new()), + } + } +} + +#[async_trait] +impl Provider for ScriptedCalls { + fn capabilities(&self) -> crate::providers::ProviderCapabilities { + crate::providers::ProviderCapabilities { + native_tool_calling: true, + vision: false, + } + } + + async fn chat_with_system( + &self, + _system_prompt: Option<&str>, + _message: &str, + _model: &str, + _temperature: f64, + ) -> anyhow::Result { + Ok("summary".to_owned()) + } + + async fn chat(&self, request: ChatRequest<'_>, _model: &str, _temperature: f64) -> anyhow::Result { + self.requests.lock().push(request.messages.to_vec()); + let batch = { + let mut batches = self.batches.lock(); + if batches.is_empty() { + None + } else { + Some(batches.remove(0)) + } + }; + let tool_calls: Vec = batch + .unwrap_or_default() + .iter() + .enumerate() + .map(|(index, (name, arguments))| crate::providers::ToolCall { + id: format!("call-targeted-{index}"), + name: (*name).to_owned(), + arguments: arguments.to_string(), + }) + .collect(); + Ok(ChatResponse { + text: tool_calls.is_empty().then(|| "done".to_owned()), + tool_calls, + reasoning_content: None, + }) + } +} + +/// A registered tool that counts backend executions. It borrows the published +/// metadata of `file_read` (or of `file_write` under that name), so it is +/// catalogued like a real filesystem tool. +struct CountingTool { + name: &'static str, + inner: ToolBox, + executions: Arc, +} + +#[async_trait] +impl crate::tools::Tool for CountingTool { + fn name(&self) -> &str { + self.name + } + fn description(&self) -> &str { + self.inner.description() + } + fn parameters_schema(&self) -> serde_json::Value { + self.inner.parameters_schema() + } + fn tier(&self) -> crate::tools::traits::ToolTier { + self.inner.tier() + } + fn categories(&self) -> &'static [crate::tools::traits::ToolCategory] { + self.inner.categories() + } + fn supports_owner_filesystem(&self) -> bool { + self.inner.supports_owner_filesystem() + } + async fn execute(&self, _args: serde_json::Value) -> anyhow::Result { + self.executions.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(crate::tools::ToolResult { + success: true, + output: "probe-output".to_owned(), + error: None, + }) + } +} + +const APPROVAL_DENIED: &str = "approval is not available for this agent"; +const APPROVAL_EVENT_TYPES: [&str; 8] = [ + "approval.call.pending", + "approval.call.reviewed", + "approval.decision.pending", + "approval.decision.reviewed", + "approval.decision.issued", + "approval.decision.resolved", + "approval.decision.resume_requested", + "approval.collection.declined", +]; + +impl Driven { + fn ran(&self, tool: &str) -> usize { + self.executions.get(tool).copied().expect("test: counted tool") + } +} + +struct Driven { + awaiting_approval: bool, + successful_attempts: u64, + denied_attempts: u64, + awaiting_approval_attempts: u64, + /// The text of every message of the request that followed the tool round. + follow_up: String, + executions: std::collections::BTreeMap<&'static str, usize>, + /// Durable approval rows by event type, read from the memory store. + rows: std::collections::BTreeMap<&'static str, usize>, + pending_calls: Option, + /// How often the channel approval resolver was consulted. + approval_asked: usize, +} + +/// Records every consultation and denies. +struct DenyingResolver { + asked: std::sync::atomic::AtomicUsize, +} + +#[async_trait] +impl crate::agent::turn_contracts::ApprovalResolver for DenyingResolver { + async fn resolve( + &self, + _request: &crate::approval::ApprovalRequest, + _channel: &str, + ) -> crate::agent::turn_contracts::ApprovalDecision { + self.asked.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + crate::agent::turn_contracts::ApprovalDecision::Deny + } +} + +/// Run one console turn. `agent_config` is `Some` for a targeted turn on agent +/// `worker`, `None` for a Main turn. Every name in `registry` is a registered +/// counting tool. With `ask_gate`, the run is installed with a channel approval +/// policy that makes every call ask first (the runtime route a read tool takes +/// to "needs approval" in a Run-disposition console turn). +async fn drive( + main_level: AutonomyLevel, + agent_config: Option, + registry: &[&'static str], + calls: Vec<(&'static str, serde_json::Value)>, + input: &'static str, + ask_gate: bool, +) -> Driven { + let driver = crate::agent::agent::native_decision_fixture::Driver::start("filesystem") + .await + .expect("test: decision fixture"); + let endpoint = driver.endpoint().to_owned(); + let registry = registry.to_vec(); + let targeted_request = agent_config.is_some(); + driver + .run(async move { + let tmp = tempfile::tempdir().expect("test: tempdir"); + let cleanup = + crate::runtime::turn_cleanup::CleanupScope::new(None, tokio_util::sync::CancellationToken::new()) + .expect("test: cleanup scope"); + let driven = cleanup + .run(Box::pin(async { + let workspace = tmp.path().join("workspace"); + let private = tmp.path().join("private"); + std::fs::create_dir_all(&workspace).expect("test: workspace"); + std::fs::create_dir_all(&private).expect("test: private root"); + let mut config = Config::default(); + console_provider_fixture_config(&mut config, &workspace, CONSOLE_WINDOW_MODEL, &endpoint); + config.config_path = private.join("config.toml"); + config.autonomy.level = main_level; + config.gateway.targeted_agents = true; + config.tool_tiering.always_include = registry.iter().map(|name| (*name).to_owned()).collect(); + if let Some(mut worker) = agent_config { + worker.model = CONSOLE_WINDOW_MODEL.to_owned(); + config.agents.insert("worker".to_owned(), worker); + } + let scripted = Arc::new(ScriptedCalls::batches(vec![calls])); + let mut state = test_app_state_with_config(config, Arc::new(CapturingProvider::default())); + state.mem = Arc::new( + crate::memory::SqliteMemory::new(&state.config.pin().effective.workspace_dir) + .expect("test: sqlite memory"), + ); + let security = Arc::new(crate::security::SecurityPolicy::from_config( + &state.config.pin().effective.autonomy, + &workspace, + )); + let counters: std::collections::BTreeMap<&'static str, Arc> = + registry + .iter() + .map(|name| (*name, Arc::new(std::sync::atomic::AtomicUsize::new(0)))) + .collect(); + state.tools_registry = Arc::new( + registry + .iter() + .map(|name| { + let inner: ToolBox = if *name == "file_write" { + Box::new(crate::tools::file_write::FileWriteTool::new(Arc::clone(&security))) + } else { + Box::new(crate::tools::file_read::FileReadTool::new(Arc::clone(&security), false)) + }; + Box::new(CountingTool { + name, + inner, + executions: Arc::clone(counters.get(name).expect("test: counter")), + }) as ToolBox + }) + .collect(), + ); + + // The parent runtime, exactly as the console fixtures build it. + let mut parent = state.pin_turn_runtime(); + let effective = Arc::clone(&parent.config_generation.effective); + let catalog = crate::providers::selection::catalog_for(&effective); + let resolve = |provider: &str| { + crate::providers::selection::check_with( + &effective, + &catalog, + provider, + CONSOLE_WINDOW_MODEL, + crate::providers::selection::credential_for(&effective, provider), + &crate::providers::catalog::Requirement::chat(), + crate::providers::catalog::UnknownPolicy::Invocation, + ) + .expect("test: model resolves") + }; + { + let parent = Arc::get_mut(&mut parent).expect("test: unshared runtime"); + parent.provider = scripted.clone(); + parent.model = CONSOLE_WINDOW_MODEL.to_owned(); + parent.provider_binding = + Some(Arc::new(crate::gateway::turn_source::GatewayProviderBinding::new( + scripted.clone(), + resolve("ollama"), + ))); + parent.publication_slot = Arc::new( + crate::gateway::turn_source::publication_slot::GatewayPublicationSlot::new( + Arc::new(crate::security::SecurityPolicy::from_config( + &effective.autonomy, + &workspace, + )), + 0, + ), + ); + } + + // The real target resolution and runtime derivation; only the + // provider instance is swapped for the scripted transport. + let plan = if targeted_request { + resolve_target(&effective, &named("worker")).expect("test: resolves") + } else { + None + }; + let (runtime, targeted) = match plan { + Some(plan) => { + let (mut runtime, turn) = prepare_target(&parent, &plan).expect("test: target runtime"); + { + let derived = Arc::get_mut(&mut runtime).expect("test: unshared target runtime"); + derived.provider = scripted.clone(); + derived.provider_binding = + Some(Arc::new(crate::gateway::turn_source::GatewayProviderBinding::new( + scripted.clone(), + resolve("ollama"), + ))); + } + (runtime, Some(turn)) + } + None => (parent, None), + }; + + let principal = super::super::super::ApiPrincipal::for_tests(); + let envelope = console_runtime_envelope_for_workspace( + workspace.to_string_lossy().to_string(), + "console-targeted-session", + "console", + "prx_user", + ) + .with_run_id(uuid::Uuid::new_v4().to_string()) + .with_config_generation(&runtime.config_generation) + .with_owner_id(principal.owner_id.clone()) + .with_owner_isolation(); + let event_id = append_console_turn(&state, &envelope, "user", input, true, false) + .await + .expect("test: record the input"); + let proof = crate::gateway::turn_source::GatewaySourceReceipt::console_proof( + state.mem.as_ref(), + &runtime, + &principal, + &envelope, + input, + &event_id, + ) + .await + .expect("test: admitted source"); + let resolver = Arc::new(DenyingResolver { + asked: std::sync::atomic::AtomicUsize::new(0), + }); + if ask_gate { + let run_id = envelope.run_id.clone().expect("test: run id"); + crate::agent::channel_approval::install(&run_id, resolver.clone(), true, false); + } + let service = runtime + .publication_slot + .publish(&runtime, &state) + .await + .expect("test: publish") + .clone(); + let cancellation = tokio_util::sync::CancellationToken::new(); + let context = service + .open_issued_turn_context( + &proof, + crate::runtime::turn_context::AgentTurnKind::SingleShot, + &cancellation, + ) + .await + .expect("test: decision"); + assert!( + context.is_run(), + "the turn must reach the tool loop, not collection or a direct reply" + ); + let decision = ConsoleDecisionTurn { + service: Arc::clone(&service), + context, + advice: None, + proof: &proof, + cancellation, + provider_trace: None, + }; + let turn = run_console_runtime_turn( + Arc::clone(&runtime), + &state, + input, + Vec::new(), + &decision, + targeted.as_ref(), + ) + .await + .expect("test: console turn completes"); + + let owner = principal.owner_id.clone(); + let workspace_id = proof.envelope().workspace_id.clone(); + let mut rows = std::collections::BTreeMap::new(); + for event_type in APPROVAL_EVENT_TYPES { + let found = state + .mem + .list_owned_message_events_by_type(&workspace_id, &owner, event_type, 0, 50) + .await + .expect("test: read approval rows"); + rows.insert(event_type, found.len()); + } + let pending_calls = match service.call_approval_strategy(proof.envelope().clone()) { + Ok(adapter) => Some( + adapter + .port + .list_pending_calls(&owner, 0, 10) + .await + .expect("test: pending call approvals") + .items + .len(), + ), + Err(_) => None, + }; + service + .shutdown(std::time::Instant::now() + Duration::from_secs(2)) + .await; + if let Some(run_id) = envelope.run_id.as_deref() { + crate::agent::channel_approval::clear(run_id); + } + + let requests = scripted.requests.lock().clone(); + let follow_up = requests + .get(1) + .map(|messages| { + messages + .iter() + .map(|message| message.content.as_str()) + .collect::>() + .join("\n") + }) + .unwrap_or_default(); + let snapshot = turn.trace.execution_trace.clone().expect("test: execution trace"); + Ok::<_, anyhow::Error>(Driven { + awaiting_approval: turn.awaiting_approval, + successful_attempts: snapshot.successful_attempts, + denied_attempts: snapshot.denied_attempts, + awaiting_approval_attempts: snapshot.awaiting_approval_attempts, + follow_up, + executions: counters + .iter() + .map(|(name, count)| (*name, count.load(std::sync::atomic::Ordering::SeqCst))) + .collect(), + rows, + pending_calls, + approval_asked: resolver.asked.load(std::sync::atomic::Ordering::SeqCst), + }) + })) + .await; + driven.expect("test: scripted turn and cleanup") + }) + .await +} + +#[tokio::test] +async fn targeted_turn_approval_call_ends_denied_without_pending_state() { + // The turn runs `file_read` under a run policy that makes every call ask + // first. The agent runs at its own Supervised level. + let mut worker = agent(true, &["file_read"]); + worker.autonomy = Some(AutonomyLevel::Supervised); + let calls = vec![("file_read", serde_json::json!({"path": "probe.txt"}))]; + let input = "file_read probe.txt: show the probe file"; + + let targeted = drive( + AutonomyLevel::Supervised, + Some(worker), + &["file_read"], + calls.clone(), + input, + true, + ) + .await; + assert_eq!(targeted.ran("file_read"), 0, "the backend never runs"); + assert!( + targeted.follow_up.contains(&format!("Denied: {APPROVAL_DENIED}")), + "the call ended ApprovalDenied: {}", + targeted.follow_up + ); + assert_eq!(targeted.approval_asked, 0, "no approval route was entered"); + assert_eq!(targeted.denied_attempts, 1); + assert_eq!(targeted.awaiting_approval_attempts, 0); + assert_eq!(targeted.successful_attempts, 0); + assert!(!targeted.awaiting_approval, "the turn is not waiting for anyone"); + assert_eq!(targeted.pending_calls.unwrap_or(0), 0, "no pending call"); + for (event_type, count) in &targeted.rows { + assert_eq!(*count, 0, "no {event_type} row was written"); + } + + // Control: the same call on a Main turn reaches the ordinary approval path. + let main = drive(AutonomyLevel::Supervised, None, &["file_read"], calls, input, true).await; + assert_eq!(main.approval_asked, 1, "Main consults the approval resolver"); + assert_eq!(main.ran("file_read"), 0, "the resolver denied the call"); + assert!(!main.follow_up.contains(APPROVAL_DENIED)); +} + +// ── Upload ownership ──────────────────────────────────────────────────────── + +const BOUNDARY: &str = "prx-test-boundary"; + +fn multipart_request(body: String) -> Request { + let mut request = Request::builder() + // Async mode answers 202 once the input is admitted, without waiting for the turn. + .uri("/?mode=async") + .header( + header::CONTENT_TYPE, + format!("multipart/form-data; boundary={BOUNDARY}"), + ) + .body(Body::from(body)) + .expect("test: request"); + request + .extensions_mut() + .insert(super::super::super::ApiPrincipal::for_tests()); + request +} + +fn text_part(name: &str, value: &str) -> String { + format!("--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n") +} + +fn file_part(file_name: &str, content: &str) -> String { + format!( + "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"files\"; filename=\"{file_name}\"\r\n\ + Content-Type: text/plain\r\n\r\n{content}\r\n" + ) +} + +async fn post_multipart(fixture: &Fixture, session: &str, body: String) -> (StatusCode, String) { + let response = post_session_message( + State(fixture.state.clone()), + Path(session.to_owned()), + multipart_request(body), + ) + .await + .into_response(); + let status = response.status(); + let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024) + .await + .expect("test: body"); + (status, String::from_utf8_lossy(&bytes).into_owned()) +} + +fn stored_uploads(fixture: &Fixture) -> Vec<(String, String)> { + let root = fixture.state.config.pin().effective.workspace_dir.join("uploads"); + let Ok(entries) = std::fs::read_dir(&root) else { + return Vec::new(); + }; + let mut files: Vec<(String, String)> = entries + .map(|entry| { + let path = entry.expect("test: entry").path(); + ( + path.file_name().expect("test: name").to_string_lossy().into_owned(), + std::fs::read_to_string(&path).expect("test: read upload"), + ) + }) + .collect(); + files.sort(); + files +} + +const ADMITTED_SESSION: &str = "prx-admitted-session"; + +/// Wire the fixture like a running gateway, so a Main request on +/// `ADMITTED_SESSION` is actually admitted (input recorded, job submitted). +async fn make_admissible(fixture: &mut Fixture) -> anyhow::Result<()> { + let workspace = fixture.state.config.pin().effective.workspace_dir.clone(); + let envelope = console_runtime_envelope_for_workspace( + workspace.to_string_lossy().as_ref(), + ADMITTED_SESSION, + "console", + "prx_user", + ); + let (runtime, _, _, anchor) = console_test_source(&mut fixture.state, envelope, "Admission fixture anchor").await; + drop(anchor); + let current = Arc::try_unwrap(runtime).map_err(|_| anyhow::anyhow!("fixture runtime unexpectedly shared"))?; + fixture.state.turn_runtime = Some(Arc::new(crate::gateway::GatewayTurnRuntimeOwner::new( + current, + Arc::clone(&fixture.state.config), + Arc::clone(&fixture.state.mem), + None, + None, + None, + None, + Arc::clone(&fixture.state.hooks), + #[cfg(feature = "wasm-plugins")] + None, + ))); + Ok(()) +} + +#[tokio::test] +async fn refused_target_cleanup_removes_only_its_own_upload() -> anyhow::Result<()> { + // The switch is off, so the named request is refused after its file is + // stored. An ADMITTED Main request sent the same file name (its session + // exists, so its file now belongs to the turn). The refusal must remove + // only the file the refused request created. + let mut fixture = fixture(|config| config.gateway.targeted_agents = false).await; + make_admissible(&mut fixture).await?; + let main_body = format!( + "{}{}--{BOUNDARY}--\r\n", + text_part("message", "main request"), + file_part("same.txt", "MAIN-CONTENT") + ); + let (status, reply) = post_multipart(&fixture, ADMITTED_SESSION, main_body).await; + assert_eq!(status, StatusCode::ACCEPTED, "{reply}"); + assert_eq!(stored_uploads(&fixture).len(), 1, "the admitted Main upload is stored"); + + let named_body = format!( + "{}{}{}--{BOUNDARY}--\r\n", + text_part("message", "named request"), + text_part("agent", "helper"), + file_part("same.txt", "NAMED-CONTENT") + ); + let (status, reply) = post_multipart(&fixture, SESSION, named_body).await; + assert_eq!(status, StatusCode::CONFLICT, "{reply}"); + let left = stored_uploads(&fixture); + assert_eq!(left.len(), 1, "only the refused request's file was removed: {left:?}"); + assert_eq!( + left.first().map(|(_, content)| content.as_str()), + Some("MAIN-CONTENT"), + "the admitted Main request's file is untouched" + ); + Ok(()) +} + +#[tokio::test] +async fn failed_main_admission_removes_its_upload() { + // A Main request whose session does not exist fails admission after its + // file is stored; the file must not outlive the request. + let fixture = fixture(|config| config.gateway.targeted_agents = false).await; + let body = format!( + "{}{}--{BOUNDARY}--\r\n", + text_part("message", "main request"), + file_part("gone.txt", "MAIN-CONTENT") + ); + let (status, reply) = post_multipart(&fixture, "no-such-session", body).await; + assert_eq!(status, StatusCode::NOT_FOUND, "{reply}"); + assert_eq!(stored_uploads(&fixture), Vec::new(), "no upload is left behind"); + assert_untouched(&fixture).await; +} + +#[test] +fn upload_path_is_owned_before_creation_and_cancellation_leaves_no_file() { + use std::sync::atomic::Ordering; + let temp = tempfile::tempdir().expect("test: tempdir"); + + // Ordering invariant: the guard knows the path while the file does not + // exist yet. + let early = temp.path().join("early.bin"); + let mut guard = UploadGuard::default(); + let abandoned = guard.begin(early.clone()); + assert!(guard.paths.contains(&early), "the path is registered"); + assert!(!early.exists(), "before the file exists"); + + // Cancellation between registration and creation: the guard drops first, + // the blocking worker runs afterwards and must not leave a file. + drop(guard); + assert!(abandoned.load(Ordering::SeqCst), "the abandonment is published"); + assert!(create_upload_file(&early, &abandoned).is_err()); + assert!(!early.exists(), "a worker running after the drop removes its own file"); + + // Cancellation after creation: the guard removes the file it registered. + let late = temp.path().join("late.bin"); + let mut guard = UploadGuard::default(); + let abandoned = guard.begin(late.clone()); + let file = create_upload_file(&late, &abandoned).expect("test: created"); + assert!(late.exists()); + drop(guard); + drop(file); + assert!(!late.exists(), "the guard removes a created file"); + + // A released guard hands the file over. + let kept = temp.path().join("kept.bin"); + let mut guard = UploadGuard::default(); + let abandoned = guard.begin(kept.clone()); + drop(create_upload_file(&kept, &abandoned).expect("test: created")); + guard.release(); + assert!(kept.exists(), "a released upload stays"); +} + +#[test] +fn upload_already_exists_preserves_the_existing_file() { + let temp = tempfile::tempdir().expect("test: tempdir"); + let sentinel = temp.path().join("sentinel.bin"); + std::fs::write(&sentinel, b"PRE-EXISTING").expect("test: sentinel"); + + let mut guard = UploadGuard::default(); + let abandoned = guard.begin(sentinel.clone()); + let outcome = guard.settle(&sentinel, create_upload_file(&sentinel, &abandoned)); + let error = outcome.expect_err("test: create_new must refuse an existing file"); + assert_eq!(error.kind(), std::io::ErrorKind::AlreadyExists); + assert!( + guard.paths.is_empty(), + "a path this request did not create is unregistered" + ); + + drop(guard); + assert_eq!( + std::fs::read(&sentinel).expect("test: sentinel must still exist"), + b"PRE-EXISTING" + ); +} + +#[tokio::test] +async fn multipart_parse_error_after_a_file_leaves_no_upload() { + // A completed file followed by a truncated `agent` field: the parser + // fails after the file is on disk, and nothing may remain. + let fixture = fixture(|config| config.gateway.targeted_agents = true).await; + let body = format!( + "{}{}--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"agent\"\r\n\r\nhelp", + text_part("message", "hi"), + file_part("kept.txt", "CONTENT") + ); + let (status, reply) = post_multipart(&fixture, SESSION, body).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{reply}"); + assert_eq!(stored_uploads(&fixture), Vec::new(), "no upload is left behind"); + assert_untouched(&fixture).await; +} + +const TARGET_U: &str = "00000000-0000-4000-8000-0000000000a1"; +const TARGET_SCOPE: &str = "00000000-0000-4000-8000-0000000000c1"; +const TARGET_MAIN_U: &str = "00000000-0000-4000-8000-0000000000b1"; +const TARGET_MAIN_SCOPE: &str = "00000000-0000-4000-8000-0000000000d1"; +const TARGET_REV: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; +const CAPTURE_PROVIDER: &str = "custom:http://127.0.0.1/prx-ma-01b2-partition"; +const PARTITION_PROVIDER: &str = "custom:http://127.0.0.1/prx-ma-01b3-partition"; +const WRITE_SCOPE_PROVIDER: &str = "custom:http://127.0.0.1/prx-ma-01b3-1-scope"; +const FENCE_ERASE: &str = "00000000-0000-4000-8000-0000000000e1"; +const FENCE_MAIN_ERASE: &str = "00000000-0000-4000-8000-0000000000e2"; +const RETIRED_U: &str = "00000000-0000-4000-8000-0000000000a9"; +const WRONG_U: &str = "00000000-0000-4000-8000-0000000000a8"; + +fn capture_provider_config(config: &mut Config, provider: &str, agent_cfg: DelegateAgentConfig) { + config.default_provider = Some(provider.to_owned()); + config.default_model = Some("test-model".to_owned()); + config.cost.prices.insert( + format!("{provider}/test-model"), + crate::config::schema::ModelPricing { + input: 1.0, + output: 1.0, + cache_write: 1.0, + cache_read: 1.0, + }, + ); + config.providers.models.push( + toml::from_str(&format!( + "provider = {provider:?}\nmodel = \"test-model\"\noperations = [\"chat\"]\nnative_tools = true\n" + )) + .expect("test: catalog"), + ); + let mut agent_cfg = agent_cfg; + agent_cfg.provider = provider.to_owned(); + agent_cfg.model = "test-model".to_owned(); + config.agents.insert("x".to_owned(), agent_cfg); +} + +fn captured_contents(provider: &CapturingProvider, index: usize) -> Vec { + provider + .requests + .lock() + .get(index) + .expect("test: captured request") + .iter() + .map(|message| message.content.clone()) + .collect() +} + +fn assert_history_partition(contents: &[String], present: &[&str], absent: &[&str], label: &str) { + for item in present { + assert!( + contents.iter().any(|content| content.contains(item)), + "{label} missing {item} in {contents:?}" + ); + } + for item in absent { + assert!( + !contents.iter().any(|content| content.contains(item)), + "{label} leaked {item} in {contents:?}" + ); + } +} + +fn named_partition(workspace: &str, owner: &str, name: &str, incarnation: &str) -> AgentPartition { + AgentPartition { + workspace_id: workspace.to_owned(), + owner_id: owner.to_owned(), + key: PartitionKey::Named { + name: AgentName::parse(name).expect("test: agent name"), + incarnation: incarnation.parse().expect("test: incarnation"), + }, + } +} + +fn main_partition(workspace: &str, owner: &str) -> AgentPartition { + AgentPartition { + workspace_id: workspace.to_owned(), + owner_id: owner.to_owned(), + key: PartitionKey::Main, + } +} + +fn history_reader(workspace: &str, session: &str, partition: AgentPartition) -> MemoryPrincipal { + MemoryPrincipal { + workspace_id: workspace.to_owned(), + agent_id: Some("system".to_owned()), + persona_id: None, + session_key: Some(session.to_owned()), + channel: Some("console".to_owned()), + sender: Some("api:local".to_owned()), + owner_id: Some("system:*".to_owned()), + require_owner_match: false, + legacy_session_key: None, + agent_partition: Some(partition), + } +} + +fn stamp_console_rows(dir: &std::path::Path, workspace: &str, owner: &str, session: &str) { + let conn = rusqlite::Connection::open(dir.join("memory").join("brain.db")).expect("test: open store"); + conn.pragma_update(None, "foreign_keys", "ON").expect("test: fk"); + conn.execute( + "INSERT INTO agent_incarnations VALUES (?1, ?2, 'n:x', ?3, 'active', ?4)", + rusqlite::params![workspace, owner, TARGET_U, TARGET_REV], + ) + .expect("test: incarnation x"); + conn.execute( + "INSERT INTO agent_incarnations VALUES (?1, ?2, 'm', ?3, 'active', ?4)", + rusqlite::params![workspace, owner, TARGET_MAIN_U, TARGET_REV], + ) + .expect("test: incarnation main"); + conn.execute( + "INSERT INTO agent_scopes VALUES (?1, ?2, ?3, ?4, 'n:x', ?5, 1)", + rusqlite::params![TARGET_SCOPE, workspace, owner, session, TARGET_U], + ) + .expect("test: scope x"); + conn.execute( + "INSERT INTO agent_scopes VALUES (?1, ?2, ?3, ?4, 'm', ?5, 1)", + rusqlite::params![TARGET_MAIN_SCOPE, workspace, owner, session, TARGET_MAIN_U], + ) + .expect("test: scope main"); + for (label, scope) in [ + ("x-only", Some(TARGET_SCOPE)), + ("main-row", Some(TARGET_MAIN_SCOPE)), + ("null-row", None), + ] { + conn.execute( + "INSERT INTO conversation_turns (session_key, owner_id, role, content, timestamp, ma_scope_id) + VALUES (?1, ?2, 'user', ?3, 't', ?4)", + rusqlite::params![session, owner, label, scope], + ) + .expect("test: stamp turn"); + } +} + +#[tokio::test] +async fn sqlite_targeted_scope_supported() { + let fixture = fixture(|config| { + config.gateway.targeted_agents = true; + config.autonomy.level = AutonomyLevel::Full; + capture_provider_config(config, CAPTURE_PROVIDER, agent(false, &[])); + }) + .await; + crate::providers::test_fixture::register( + CAPTURE_PROVIDER, + Arc::clone(&fixture.provider) as Arc, + ); + assert!(fixture.memory.supports_agent_scope()); + let workspace = fixture + .state + .config + .pin() + .effective + .workspace_dir + .to_string_lossy() + .into_owned(); + let owner = super::super::super::ApiPrincipal::for_tests().owner_id; + stamp_console_rows(std::path::Path::new(&workspace), &workspace, &owner, SESSION); + + let named = history_reader(&workspace, SESSION, named_partition(&workspace, &owner, "x", TARGET_U)); + let named_turns = fixture + .memory + .list_console_conversation_turns(&named, SESSION, 50, 0) + .await + .expect("test: named turns"); + let named_labels: Vec<&str> = named_turns.iter().map(|turn| turn.content.as_str()).collect(); + assert_eq!(named_labels, ["x-only"], "Named X sees no Y/Main/NULL rows"); + + let main = history_reader(&workspace, SESSION, main_partition(&workspace, &owner)); + let main_turns = fixture + .memory + .list_console_conversation_turns(&main, SESSION, 50, 0) + .await + .expect("test: main turns"); + let main_labels: Vec<&str> = main_turns.iter().map(|turn| turn.content.as_str()).collect(); + assert!(main_labels.contains(&"main-row") && main_labels.contains(&"null-row")); + assert!(!main_labels.contains(&"x-only")); + + let api_principal = super::super::super::ApiPrincipal::for_tests(); + let selected = super::super::select_turn_target( + &fixture.state, + fixture.state.pin_turn_runtime(), + &api_principal, + AgentField::Text("x".to_owned()), + false, + ) + .expect("test: named target"); + assert_eq!(selected.incarnation.as_deref(), Some(TARGET_U)); + + let (status, value) = post(&fixture, SESSION, serde_json::json!({"message": "hi", "agent": "x"})).await; + assert_eq!(status, StatusCode::OK, "{value}"); + assert_history_partition( + &captured_contents(&fixture.provider, 0), + &["x-only"], + &["main-row", "null-row"], + "Named POST", + ); + + let (status, value) = post(&fixture, SESSION, serde_json::json!({"message": "hi"})).await; + assert_eq!(status, StatusCode::OK, "{value}"); + assert_history_partition( + &captured_contents(&fixture.provider, 1), + &["main-row", "null-row"], + &["x-only"], + "Main POST", + ); +} + +const SCOPE_TOOL: &str = "file_read"; + +/// Records every argument set the runtime delivers to it, `_zc_scope` included. +/// Named and catalogued as `file_read` (CountingTool pattern) so the published +/// surface includes it. +struct ScopeRecorder { + seen: Arc>>, + inner: crate::tools::file_read::FileReadTool, +} + +#[async_trait] +impl crate::tools::Tool for ScopeRecorder { + fn name(&self) -> &str { + SCOPE_TOOL + } + fn description(&self) -> &str { + self.inner.description() + } + fn parameters_schema(&self) -> serde_json::Value { + self.inner.parameters_schema() + } + fn tier(&self) -> crate::tools::traits::ToolTier { + self.inner.tier() + } + fn categories(&self) -> &'static [crate::tools::traits::ToolCategory] { + self.inner.categories() + } + fn supports_owner_filesystem(&self) -> bool { + self.inner.supports_owner_filesystem() + } + async fn execute(&self, args: serde_json::Value) -> anyhow::Result { + self.seen.lock().push(args); + Ok(crate::tools::ToolResult { + success: true, + output: "recorded".to_owned(), + error: None, + }) + } +} + +/// A console input literal whose only varying field is the in-process partition (R0-2). +fn digest_cell_input(agent_partition: Option) -> crate::memory::MessageEventInput { + crate::memory::MessageEventInput { + agent_partition, + event_id: None, + idempotency_key: Some("console:run-1:input".to_owned()), + workspace_id: "workspace-a".to_owned(), + owner_id: Some("owner-a".to_owned()), + source: crate::memory::MessageEventSource::Console, + channel: Some("console".to_owned()), + session_key: Some(SESSION.to_owned()), + parent_session_key: None, + run_id: None, + parent_run_id: None, + agent_id: None, + persona_id: None, + sender: None, + recipient: None, + role: "user".to_owned(), + event_type: "message".to_owned(), + subject: None, + goal_id: None, + causation_event_id: None, + correlation_id: None, + attempt_id: None, + lease_epoch: None, + config_generation_id: None, + config_source_revision: None, + content: "hi".to_owned(), + raw_payload_json: None, + visibility: crate::memory::MemoryVisibility::Session, + } +} + +/// MA-01b3 part 0: the partition and session reach every writer input. The +/// envelope views are asserted directly; the POST views assert what the +/// runtime delivers to a tool (`_zc_scope`) and what `parse_scope_ctx` reads +/// back from it. +#[tokio::test] +async fn agent_partition_reaches_every_writer_input() { + let driver = crate::agent::agent::native_decision_fixture::Driver::start("filesystem") + .await + .expect("test: decision fixture"); + let endpoint = driver.endpoint().to_owned(); + driver + .run(async move { + let mut fixture = fixture_with_decision_backend(|config| { + config.gateway.targeted_agents = true; + config.autonomy.level = AutonomyLevel::Full; + config.tool_tiering.always_include = vec![SCOPE_TOOL.to_owned()]; + capture_provider_config(config, PARTITION_PROVIDER, agent(true, &[SCOPE_TOOL])); + crate::agent::agent::native_decision_fixture::configure(config, &endpoint) + .expect("test: decision backend"); + }) + .await; + let seen = Arc::new(parking_lot::Mutex::new(Vec::new())); + let workspace_dir = fixture.state.config.pin().effective.workspace_dir.clone(); + let security = Arc::new(crate::security::SecurityPolicy::from_config( + &fixture.state.config.pin().effective.autonomy, + &workspace_dir, + )); + fixture.state.tools_registry = Arc::new(vec![Box::new(ScopeRecorder { + seen: Arc::clone(&seen), + inner: crate::tools::file_read::FileReadTool::new(security, false), + }) as ToolBox]); + let workspace = workspace_dir.to_string_lossy().into_owned(); + let owner = super::super::super::ApiPrincipal::for_tests().owner_id; + stamp_console_rows(std::path::Path::new(&workspace), &workspace, &owner, SESSION); + + let named = named_partition(&workspace, &owner, "x", TARGET_U); + let envelope = crate::runtime::envelope::RuntimeEnvelope::console(workspace.clone(), SESSION.to_owned()) + .with_agent_partition(named.clone()); + let write_context = envelope.memory_write_context("direct"); + assert_eq!( + serde_json::to_vec(&digest_cell_input(Some(named.clone()))).expect("test: input json"), + serde_json::to_vec(&digest_cell_input(None)).expect("test: input json"), + "MessageEventInput serialisation (capsule digest input) ignores the partition" + ); + assert_eq!( + write_context.agent_partition.as_ref(), + Some(&named), + "write context carries the partition" + ); + assert_eq!( + write_context.session_key.as_deref(), + Some(SESSION), + "write context carries the session" + ); + assert_eq!( + envelope.message_scope().agent_partition.as_ref(), + Some(&named), + "message scope carries the partition" + ); + + for (label, body, expected) in [ + ( + "Named POST", + serde_json::json!({"message": "hi", "agent": "x"}), + named.clone(), + ), + ( + "Main POST", + serde_json::json!({"message": "hi"}), + main_partition(&workspace, &owner), + ), + ] { + let scripted = Arc::new(ScriptedCalls::batches(vec![vec![( + SCOPE_TOOL, + serde_json::json!({"path": "probe.txt"}), + )]])); + // The fixture holds only a Weak handle: keep this Arc alive for the POST. + let provider = Arc::clone(&scripted) as Arc; + crate::providers::test_fixture::register(PARTITION_PROVIDER, Arc::clone(&provider)); + // Main pins `AppState.provider`; Named builds through the factory. + fixture.state.provider = Arc::clone(&provider); + seen.lock().clear(); + let (status, value) = post(&fixture, SESSION, body).await; + drop(provider); + assert_eq!(status, StatusCode::OK, "{label}: {value}"); + let args = seen.lock().last().cloned().expect("test: recorder ran"); + let scope = args.get("_zc_scope").expect("test: runtime scope"); + assert_eq!( + scope.get("agent_partition"), + Some(&serde_json::to_value(&expected).expect("test: partition json")), + "{label}: _zc_scope carries the partition" + ); + assert_eq!( + scope.get("session_key").and_then(serde_json::Value::as_str), + Some(SESSION), + "{label}: _zc_scope carries the session" + ); + let context = crate::tools::memory_store::parse_scope_ctx(&args).expect("test: trusted scope"); + assert_eq!( + context.agent_partition.as_ref(), + Some(&expected), + "{label}: parsed partition" + ); + assert_eq!(context.session_key.as_deref(), Some(SESSION), "{label}: parsed session"); + } + }) + .await; +} + +fn brain(workspace: &str) -> rusqlite::Connection { + let conn = rusqlite::Connection::open(std::path::Path::new(workspace).join("memory").join("brain.db")) + .expect("test: brain"); + conn.pragma_update(None, "foreign_keys", "ON").expect("test: fk"); + conn +} + +fn seed_named_x(dir: &std::path::Path, workspace: &str, owner: &str, session: &str) { + let conn = rusqlite::Connection::open(dir.join("memory").join("brain.db")).expect("test: open store"); + conn.pragma_update(None, "foreign_keys", "ON").expect("test: fk"); + conn.execute( + "INSERT INTO agent_incarnations VALUES (?1, ?2, 'n:x', ?3, 'active', ?4)", + rusqlite::params![workspace, owner, TARGET_U, TARGET_REV], + ) + .expect("test: incarnation x"); + conn.execute( + "INSERT INTO agent_scopes VALUES (?1, ?2, ?3, ?4, 'n:x', ?5, 1)", + rusqlite::params![TARGET_SCOPE, workspace, owner, session, TARGET_U], + ) + .expect("test: scope x"); +} + +fn fence_scope(conn: &rusqlite::Connection, scope_id: &str, erase_id: &str) { + conn.execute( + "INSERT INTO agent_erase_fences VALUES (?1, ?2, 'draining', 2)", + rusqlite::params![scope_id, erase_id], + ) + .expect("test: fence"); +} + +fn table_columns(conn: &rusqlite::Connection, table: &str) -> Vec { + let sql = match table { + "message_events" | "conversation_turns" | "memory_events" | "memories" | "documents" | "document_chunks" + | "embedding_cache" | "memory_drafts" | "memory_trash" => { + format!("PRAGMA table_info({table})") + } + _ => panic!("test: unknown store {table}"), + }; + let mut statement = conn.prepare(&sql).expect("test: pragma"); + statement + .query_map([], |row| row.get::<_, String>(1)) + .expect("test: columns") + .map(|column| column.expect("test: column name")) + .collect() +} + +fn scope_rows(conn: &rusqlite::Connection, sql: &str, session: &str) -> Vec> { + let mut statement = conn.prepare(sql).expect("test: prepare"); + statement + .query_map([session], |row| row.get(0)) + .expect("test: query") + .map(|value| value.expect("test: scope")) + .collect() +} + +fn write_input( + workspace: &str, + owner: &str, + partition: Option, + session: Option<&str>, + content: &str, +) -> crate::memory::MessageEventInput { + let mut input = digest_cell_input(partition); + input.workspace_id = workspace.to_owned(); + input.owner_id = Some(owner.to_owned()); + input.session_key = session.map(str::to_owned); + input.idempotency_key = None; + input.content = content.to_owned(); + input +} diff --git a/src/gateway/api/sessions/tests/targeting/section_2.rs b/src/gateway/api/sessions/tests/targeting/section_2.rs new file mode 100644 index 000000000..99a704f84 --- /dev/null +++ b/src/gateway/api/sessions/tests/targeting/section_2.rs @@ -0,0 +1,1325 @@ +/// MA-01b3 part 1: transcript/event writers stamp the resolved agent scope. +/// Real POST for Named X, Main mint (D-CR1), D-CR3 column probe, and refusals. +#[tokio::test] +async fn memory_writes_carry_scope() { + let fixture = fixture(|config| { + config.gateway.targeted_agents = true; + config.autonomy.level = AutonomyLevel::Full; + capture_provider_config(config, WRITE_SCOPE_PROVIDER, agent(false, &[])); + }) + .await; + crate::providers::test_fixture::register( + WRITE_SCOPE_PROVIDER, + Arc::clone(&fixture.provider) as Arc, + ); + let workspace = fixture + .state + .config + .pin() + .effective + .workspace_dir + .to_string_lossy() + .into_owned(); + let owner = super::super::super::ApiPrincipal::for_tests().owner_id; + seed_named_x(std::path::Path::new(&workspace), &workspace, &owner, SESSION); + let conn = brain(&workspace); + + const NINE: [&str; 9] = [ + "message_events", + "conversation_turns", + "memory_events", + "memories", + "documents", + "document_chunks", + "embedding_cache", + "memory_drafts", + "memory_trash", + ]; + let mut dcr3 = Vec::new(); + for table in NINE { + let columns = table_columns(&conn, table); + assert!( + columns.iter().any(|column| column == "ma_scope_id"), + "{table} has ma_scope_id" + ); + dcr3.push(format!("{table}: {}", columns.join(","))); + } + // D-CR3: no unambiguous FK identifies pre-01b3 targeted rows (target.rs has + // selector state only). Parent FKs (message_event_id, subject_id) serve D-CR2. + eprintln!("D-CR3 columns: {}", dcr3.join(" | ")); + + let (status, value) = post( + &fixture, + SESSION, + serde_json::json!({"message": "named-x", "agent": "x"}), + ) + .await; + assert_eq!(status, StatusCode::OK, "Named POST: {value}"); + + let named_events = scope_rows( + &conn, + "SELECT ma_scope_id FROM message_events + WHERE session_key = ?1 AND role IN ('user', 'assistant') + ORDER BY id", + SESSION, + ); + let named_turns = scope_rows( + &conn, + "SELECT ma_scope_id FROM conversation_turns + WHERE session_key = ?1 AND role IN ('user', 'assistant') + ORDER BY id", + SESSION, + ); + let named_mirrors = scope_rows( + &conn, + "SELECT ma_scope_id FROM memory_events + WHERE session_key = ?1 AND subject_table = 'message_events' + AND event_type IN ('message', 'message.created') + ORDER BY id", + SESSION, + ); + let named_user: i64 = conn + .query_row( + "SELECT count(*) FROM message_events WHERE session_key = ?1 AND role = 'user' AND ma_scope_id = ?2", + rusqlite::params![SESSION, TARGET_SCOPE], + |row| row.get(0), + ) + .expect("test: named user events"); + let named_assistant: i64 = conn + .query_row( + "SELECT count(*) FROM message_events WHERE session_key = ?1 AND role = 'assistant' AND ma_scope_id = ?2", + rusqlite::params![SESSION, TARGET_SCOPE], + |row| row.get(0), + ) + .expect("test: named assistant events"); + assert!(named_user >= 1, "Named POST wrote input message_events"); + assert!(named_assistant >= 1, "Named POST wrote assistant message_events"); + assert!(!named_events.is_empty(), "Named POST wrote message_events"); + assert!( + named_events.iter().all(|scope| scope.as_deref() == Some(TARGET_SCOPE)), + "message_events row carries X's scope: {named_events:?}" + ); + assert!( + named_turns.iter().all(|scope| scope.as_deref() == Some(TARGET_SCOPE)), + "conversation_turns row carries X's scope: {named_turns:?}" + ); + assert!( + named_mirrors.iter().all(|scope| scope.as_deref() == Some(TARGET_SCOPE)), + "memory_events row carries X's scope: {named_mirrors:?}" + ); + assert!( + named_events.iter().all(Option::is_some) + && named_turns.iter().all(Option::is_some) + && named_mirrors.iter().all(Option::is_some), + "Named X wrote zero NULL rows" + ); + + let main_incarnations: i64 = conn + .query_row( + "SELECT count(*) FROM agent_incarnations WHERE workspace_id = ?1 AND owner_id = ?2 AND agent_key = 'm'", + rusqlite::params![&workspace, &owner], + |row| row.get(0), + ) + .expect("test: main incarnation count"); + assert_eq!(main_incarnations, 0, "D-CR1: no Main incarnation before the Main POST"); + + let (status, value) = post(&fixture, SESSION, serde_json::json!({"message": "main-hi"})).await; + assert_eq!(status, StatusCode::OK, "Main POST: {value}"); + + let minted_u: String = conn + .query_row( + "SELECT incarnation FROM agent_incarnations + WHERE workspace_id = ?1 AND owner_id = ?2 AND agent_key = 'm' AND state = 'active'", + rusqlite::params![&workspace, &owner], + |row| row.get(0), + ) + .expect("test: D-CR1 minted m"); + let main_scopes: Vec = { + let mut statement = conn + .prepare( + "SELECT scope_id FROM agent_scopes + WHERE workspace_id = ?1 AND owner_id = ?2 AND session_key = ?3 AND agent_key = 'm'", + ) + .expect("test: main scopes"); + statement + .query_map(rusqlite::params![&workspace, &owner, SESSION], |row| row.get(0)) + .expect("test: main scope rows") + .map(|value| value.expect("test: scope id")) + .collect() + }; + assert_eq!(main_scopes.len(), 1, "D-CR1: one Main scope"); + let main_scope = main_scopes.first().expect("test: D-CR1 one Main scope"); + let main_event_scope: Option = conn + .query_row( + "SELECT ma_scope_id FROM message_events WHERE session_key = ?1 AND content = 'main-hi'", + [SESSION], + |row| row.get(0), + ) + .expect("test: main event"); + assert_eq!( + main_event_scope.as_deref(), + Some(main_scope.as_str()), + "Main rows carry the minted scope" + ); + assert_eq!(minted_u.len(), 36, "D-CR1 minted an incarnation UUID"); + + let events_before: i64 = conn + .query_row( + "SELECT count(*) FROM message_events WHERE session_key = ?1", + [SESSION], + |row| row.get(0), + ) + .expect("test: count"); + fence_scope(&conn, TARGET_SCOPE, FENCE_ERASE); + let (status, value) = post( + &fixture, + SESSION, + serde_json::json!({"message": "fenced-x", "agent": "x"}), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT, "fenced Named: {value}"); + assert_eq!(error_code(&value), Some("agent_scope_refused")); + let events_after: i64 = conn + .query_row( + "SELECT count(*) FROM message_events WHERE session_key = ?1", + [SESSION], + |row| row.get(0), + ) + .expect("test: count after fence"); + assert_eq!(events_after, events_before, "fenced Named wrote zero rows"); + + fence_scope(&conn, main_scope, FENCE_MAIN_ERASE); + let (status, value) = post(&fixture, SESSION, serde_json::json!({"message": "fenced-main"})).await; + assert_eq!(status, StatusCode::CONFLICT, "fenced Main: {value}"); + assert_eq!(error_code(&value), Some("agent_scope_refused")); + let fenced_main: i64 = conn + .query_row( + "SELECT count(*) FROM message_events WHERE content = 'fenced-main'", + [], + |row| row.get(0), + ) + .expect("test: fenced main rows"); + assert_eq!(fenced_main, 0, "fenced Main wrote zero rows"); + + let named = named_partition(&workspace, &owner, "x", TARGET_U); + let envelope = crate::runtime::envelope::RuntimeEnvelope::console(workspace.clone(), SESSION.to_owned()) + .with_agent_partition(named.clone()) + .with_owner_id(owner.clone()); + let error = append_console_turn(&fixture.state, &envelope, "user", "no-parent", false, false) + .await + .expect_err("test: Named missing parent event"); + assert!( + error.downcast_ref::().is_some(), + "W4 Named + missing parent: {error:#}" + ); + + conn.execute( + "INSERT INTO agent_incarnations VALUES (?1, ?2, 'n:x', ?3, 'retired', ?4)", + rusqlite::params![&workspace, &owner, RETIRED_U, TARGET_REV], + ) + .expect("test: retired incarnation"); + for (label, input) in [ + ( + "retired incarnation", + write_input( + &workspace, + &owner, + Some(named_partition(&workspace, &owner, "x", RETIRED_U)), + Some(SESSION), + "retired", + ), + ), + ( + "wrong U", + write_input( + &workspace, + &owner, + Some(named_partition(&workspace, &owner, "x", WRONG_U)), + Some(SESSION), + "wrong-u", + ), + ), + ( + "missing session_key", + write_input(&workspace, &owner, Some(named.clone()), None, "no-session"), + ), + ( + "workspace mismatch", + write_input( + "other-workspace", + &owner, + Some(named.clone()), + Some(SESSION), + "mismatch", + ), + ), + ( + "owner mismatch", + write_input( + &workspace, + "other-owner", + Some(named.clone()), + Some(SESSION), + "owner-mismatch", + ), + ), + ] { + let error = fixture.memory.append_message_event(input).await.expect_err(label); + assert!( + error.downcast_ref::().is_some(), + "{label}: {error:#}" + ); + } + for content in ["retired", "wrong-u", "no-session", "mismatch", "owner-mismatch"] { + let leaked: i64 = conn + .query_row( + "SELECT count(*) FROM message_events WHERE content = ?1", + [content], + |row| row.get(0), + ) + .expect("test: leak"); + assert_eq!(leaked, 0, "{content} wrote zero rows"); + } + + complete_memory_family_scope_stamps().await; +} + +#[tokio::test] +async fn none_targeted_scope_rejected() { + let memory = NoneMemory::new(); + assert!(!memory.supports_agent_scope()); + let principal = history_reader( + "prx_workspace", + "session", + named_partition("prx_workspace", "prx_owner", "x", TARGET_U), + ); + let turns = memory + .list_console_conversation_turns(&principal, "session", 10, 0) + .await + .expect_err("test: named turns"); + assert!(turns.downcast_ref::().is_some(), "{turns:#}"); + let events = memory + .list_message_events_since(&principal, 0, 10) + .await + .expect_err("test: named events"); + assert!(events.downcast_ref::().is_some(), "{events:#}"); + + // Job snapshots span all fixtures in this process. Identify only this + // rejected request rather than another test's legitimately submitted job. + let session_key = format!("prx-rejected-scope-{}", uuid::Uuid::new_v4()); + let temp = tempfile::tempdir().expect("test: tempdir"); + let mut config = Config::default(); + config.workspace_dir = temp.path().to_owned(); + config.gateway.targeted_agents = true; + config.agents.insert("x".to_owned(), agent(false, &[])); + let provider = Arc::new(CapturingProvider::default()); + let mut state = test_app_state(config, provider.clone()); + state.mem = Arc::new(NoneMemory::new()); + let response = post_session_message( + State(state.clone()), + Path(session_key.clone()), + http_request(serde_json::json!({"message": "hi", "agent": "x"})), + ) + .await + .into_response(); + let status = response.status(); + let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024) + .await + .expect("test: body"); + let body: serde_json::Value = serde_json::from_slice(&bytes).expect("test: json"); + assert_eq!(status, StatusCode::CONFLICT, "{body}"); + assert_eq!(error_code(&body), Some("agent_backend_unsupported")); + assert!(provider.requests.lock().is_empty(), "no provider access"); + assert!(state.mem.agent_registry().is_none(), "no registry row"); + let session = state + .mem + .get_conversation_session(&session_key) + .await + .expect("test: read session"); + assert!(session.is_none(), "no input event"); + let job_label = format!("gateway:session_message:{session_key}"); + assert!( + crate::gateway::jobs::snapshot_all() + .iter() + .all(|job| job.label != job_label), + "no job" + ); +} + +const STORE_SCOPE_PROVIDER: &str = "custom:http://127.0.0.1/prx-ma-01b3-2-store"; +const DOC_SCOPE_PROVIDER: &str = "custom:http://127.0.0.1/prx-ma-01b3-3-docs"; +const TOPIC_SCOPE_PROVIDER: &str = "custom:http://127.0.0.1/prx-ma-01b3-3-topics"; +const SESSION_S2: &str = "prx-target-session-s2"; +const STORE_TOOL: &str = "memory_store"; +const INGEST_TOOL: &str = "document_ingest"; + +struct ScopeCountingEmbedder { + calls: Arc, +} + +#[async_trait] +impl EmbeddingProvider for ScopeCountingEmbedder { + fn name(&self) -> &str { + "counting" + } + + fn dimensions(&self) -> usize { + 4 + } + + fn model(&self) -> &str { + "counting-v1" + } + + async fn embed(&self, texts: &[&str]) -> anyhow::Result>> { + self.calls.fetch_add(texts.len(), Ordering::SeqCst); + Ok(texts.iter().map(|_| vec![0.1, 0.2, 0.3, 0.4]).collect()) + } +} + +async fn fixture_with_scope_embedder(config: impl FnOnce(&mut Config), embed_calls: Arc) -> Fixture { + let temp = tempfile::tempdir().expect("test: tempdir"); + let workspace = temp.path().join("workspace"); + let private = temp.path().join("private"); + std::fs::create_dir_all(&workspace).expect("test: workspace"); + std::fs::create_dir_all(&private).expect("test: private root"); + let mut base = Config::default(); + base.workspace_dir = workspace.clone(); + base.config_path = private.join("config.toml"); + config(&mut base); + let provider = Arc::new(CapturingProvider::default()); + let mut state = test_app_state_with_config(base, provider.clone()); + let memory = Arc::new( + crate::memory::SqliteMemory::with_embedder( + &workspace, + Arc::new(ScopeCountingEmbedder { calls: embed_calls }), + 0.7, + 0.3, + 1000, + None, + ) + .expect("test: sqlite memory"), + ); + state.mem = memory.clone(); + memory + .create_conversation_session(SESSION, "api:local") + .await + .expect("test: session"); + memory + .create_conversation_session(SESSION_S2, "api:local") + .await + .expect("test: session s2"); + Fixture { + state, + provider, + memory, + _temp: temp, + } +} + +fn install_scope_tools(fixture: &mut Fixture) { + let workspace_dir = fixture.state.config.pin().effective.workspace_dir.clone(); + let security = Arc::new(crate::security::SecurityPolicy::from_config( + &fixture.state.config.pin().effective.autonomy, + &workspace_dir, + )); + let memory: Arc = fixture.memory.clone(); + fixture.state.tools_registry = Arc::new(vec![ + Box::new(MemoryStoreTool::new(Arc::clone(&memory), Arc::clone(&security))) as ToolBox, + Box::new(DocumentIngestTool::new(workspace_dir, memory, security)) as ToolBox, + ]); +} + +async fn post_scripted( + fixture: &mut Fixture, + provider: &str, + session: &str, + body: serde_json::Value, + tool: &'static str, + args: serde_json::Value, +) -> (StatusCode, serde_json::Value) { + let scripted = Arc::new(ScriptedCalls::batches(vec![vec![(tool, args)]])); + let provider_arc = Arc::clone(&scripted) as Arc; + crate::providers::test_fixture::register(provider, Arc::clone(&provider_arc)); + fixture.state.provider = Arc::clone(&provider_arc); + let result = post(fixture, session, body).await; + drop(provider_arc); + result +} + +fn partitioned_write_ctx(workspace: &str, owner: &str, session: &str, partition: AgentPartition) -> MemoryWriteContext { + MemoryWriteContext { + workspace_id: Some(workspace.to_owned()), + owner_id: Some(owner.to_owned()), + session_key: Some(session.to_owned()), + agent_partition: Some(partition), + channel: Some("console".to_owned()), + ..Default::default() + } +} + +fn configure_stamped_scope(config: &mut Config, endpoint: &str, provider: &str, tools: &[&str]) { + config.gateway.targeted_agents = true; + config.autonomy.level = AutonomyLevel::Full; + config.tool_tiering.always_include = tools.iter().map(|tool| (*tool).to_owned()).collect(); + capture_provider_config(config, provider, agent(true, tools)); + crate::agent::agent::native_decision_fixture::configure(config, endpoint).expect("test: decision backend"); +} + +fn truncated_content_hash(text: &str) -> String { + use sha2::{Digest, Sha256}; + Sha256::digest(text.as_bytes()) + .iter() + .take(16) + .fold(String::with_capacity(32), |mut hex, byte| { + use std::fmt::Write; + let _ = write!(hex, "{byte:02x}"); + hex + }) +} + +fn assert_named_store_row(conn: &rusqlite::Connection, key: &str, content: &str) { + let (scope, topic): (Option, Option) = conn + .query_row( + "SELECT ma_scope_id, topic_id FROM memories WHERE key = ?1", + [key], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .expect("test: stored memories row"); + assert_eq!( + scope.as_deref(), + Some(TARGET_SCOPE), + "stored memories row carries X's scope" + ); + assert!(topic.is_none(), "X's memory has topic_id NULL"); + let fts: i64 = conn + .query_row( + "SELECT count(*) FROM memories_fts f JOIN memories m ON m.rowid = f.rowid WHERE m.key = ?1", + [key], + |row| row.get(0), + ) + .expect("test: memories_fts"); + assert_eq!(fts, 1, "memories_fts carries X's memory"); + let salted: i64 = conn + .query_row( + "SELECT count(*) FROM embedding_cache WHERE ma_scope_id = ?1 AND length(content_hash) = 64", + [TARGET_SCOPE], + |row| row.get(0), + ) + .expect("test: salted cache"); + assert!(salted >= 1, "salted embedding_cache row carries X's scope"); + let plain_hash = truncated_content_hash(content); + let plain: i64 = conn + .query_row( + "SELECT count(*) FROM embedding_cache WHERE content_hash = ?1", + [plain_hash], + |row| row.get(0), + ) + .expect("test: plain hash"); + assert_eq!(plain, 0, "no plain-hash embedding_cache row for the stored text"); +} + +/// Part 2 completion of `memory_writes_carry_scope`: memory-family writers. +async fn complete_memory_family_scope_stamps() { + let driver = crate::agent::agent::native_decision_fixture::Driver::start("memory") + .await + .expect("test: decision fixture"); + let endpoint = driver.endpoint().to_owned(); + driver + .run(async move { + let mut fixture = fixture_with_scope_embedder( + |config| configure_stamped_scope(config, &endpoint, STORE_SCOPE_PROVIDER, &[STORE_TOOL]), + Arc::new(AtomicUsize::new(0)), + ) + .await; + install_scope_tools(&mut fixture); + let workspace = fixture + .state + .config + .pin() + .effective + .workspace_dir + .to_string_lossy() + .into_owned(); + let owner = super::super::super::ApiPrincipal::for_tests().owner_id; + seed_named_x(std::path::Path::new(&workspace), &workspace, &owner, SESSION); + let named = named_partition(&workspace, &owner, "x", TARGET_U); + let main = main_partition(&workspace, &owner); + let named_ctx = partitioned_write_ctx(&workspace, &owner, SESSION, named.clone()); + let main_s1 = partitioned_write_ctx(&workspace, &owner, SESSION, main.clone()); + let main_s2 = partitioned_write_ctx(&workspace, &owner, SESSION_S2, main.clone()); + + let (status, value) = post_scripted( + &mut fixture, + STORE_SCOPE_PROVIDER, + SESSION, + serde_json::json!({"message": "store-x", "agent": "x"}), + STORE_TOOL, + serde_json::json!({"key": "named-core", "content": "hi", "category": "core"}), + ) + .await; + assert_eq!(status, StatusCode::OK, "Named store POST: {value}"); + let conn = brain(&workspace); + assert_named_store_row(&conn, "named-core", "hi"); + + let (status, value) = post_scripted( + &mut fixture, + STORE_SCOPE_PROVIDER, + SESSION, + serde_json::json!({"message": "store-main"}), + STORE_TOOL, + serde_json::json!({"key": "main-core", "content": "ok", "category": "core"}), + ) + .await; + assert_eq!(status, StatusCode::OK, "Main store POST: {value}"); + let main_scope: String = conn + .query_row( + "SELECT ma_scope_id FROM memories WHERE key = 'main-core'", + [], + |row| row.get::<_, Option>(0), + ) + .expect("test: main store") + .expect("test: main stamp"); + + fixture + .memory + .store_with_context("session-key", "s1", MemoryCategory::Core, None, Some(&main_s1)) + .await + .expect("test: Main S1"); + fixture + .memory + .store_with_context("session-key", "s2", MemoryCategory::Core, None, Some(&main_s2)) + .await + .expect("test: Main S2"); + let s2_scope: String = conn + .query_row( + "SELECT ma_scope_id FROM memories WHERE key = 'session-key'", + [], + |row| row.get::<_, Option>(0), + ) + .expect("test: S2 row") + .expect("test: S2 stamp"); + let s2_id: String = conn + .query_row( + "SELECT scope_id FROM agent_scopes WHERE session_key = ?1 AND agent_key = 'm'", + [SESSION_S2], + |row| row.get(0), + ) + .expect("test: S2 scope"); + assert_eq!(s2_scope, s2_id, "Main S2 write carries the S2 scope"); + + conn.execute( + "INSERT INTO memories (id, key, content, category, created_at, updated_at) VALUES ('legacy-1', 'legacy-null', 'old', 'core', 't', 't')", + [], + ) + .expect("test: null legacy"); + fixture + .memory + .store_with_context("legacy-null", "new", MemoryCategory::Core, None, Some(&main_s1)) + .await + .expect("test: Main over NULL"); + let stamped: Option = conn + .query_row("SELECT ma_scope_id FROM memories WHERE key = 'legacy-null'", [], |row| { + row.get(0) + }) + .expect("test: legacy stamp"); + assert!(stamped.is_some(), "Main over a NULL legacy row succeeds"); + + conn.execute( + "INSERT INTO memories (id, key, content, category, created_at, updated_at) VALUES ('null-2', 'named-over-null', 'keep', 'core', 't', 't')", + [], + ) + .expect("test: named-over-null seed"); + let cache_before: i64 = conn + .query_row("SELECT count(*) FROM embedding_cache", [], |row| row.get(0)) + .expect("test: cache before refuse"); + let refused = fixture + .memory + .store_with_context( + "named-over-null", + "take", + MemoryCategory::Core, + None, + Some(&named_ctx), + ) + .await + .expect_err("test: Named over NULL"); + assert!( + refused.downcast_ref::().is_some(), + "Named over NULL: {refused:#}" + ); + let kept: String = conn + .query_row("SELECT content FROM memories WHERE key = 'named-over-null'", [], |row| { + row.get(0) + }) + .expect("test: original"); + assert_eq!(kept, "keep", "original unchanged"); + let cache_after: i64 = conn + .query_row("SELECT count(*) FROM embedding_cache", [], |row| row.get(0)) + .expect("test: cache after refuse"); + assert_eq!(cache_after, cache_before, "a refused write leaves no embedding_cache row"); + + let foreign = fixture + .memory + .store_with_context("foreign-key", "main-owns", MemoryCategory::Core, None, Some(&main_s1)) + .await; + foreign.expect("test: foreign seed"); + let refused = fixture + .memory + .store_with_context("foreign-key", "named-take", MemoryCategory::Core, None, Some(&named_ctx)) + .await + .expect_err("test: Named over foreign"); + assert!( + refused.downcast_ref::().is_some(), + "Named over foreign: {refused:#}" + ); + + let refused = fixture + .memory + .store("named-core", "unstamped", MemoryCategory::Core, None) + .await + .expect_err("test: unstamped over Named"); + assert!( + refused.downcast_ref::().is_some(), + "unstamped over Named: {refused:#}" + ); + fixture + .memory + .store("main-core", "ctx-less-main", MemoryCategory::Core, None) + .await + .expect("test: ctx-less over Main"); + let kept_main: Option = conn + .query_row("SELECT ma_scope_id FROM memories WHERE key = 'main-core'", [], |row| { + row.get(0) + }) + .expect("test: ctx-less main stamp"); + assert_eq!(kept_main.as_deref(), Some(main_scope.as_str()), "ctx-less upsert keeps the Main stamp"); + + let draft = fixture + .memory + .create_memory_draft(MemoryDraftInput { + agent_partition: Some(named.clone()), + draft_id: Some("draft-named".to_owned()), + workspace_id: workspace.clone(), + owner_id: Some(owner.clone()), + worker_run_id: "run-1".to_owned(), + parent_run_id: None, + session_key: Some(SESSION.to_owned()), + agent_id: None, + persona_id: None, + key: "main-core".to_owned(), + content: "draft-take".to_owned(), + category: MemoryCategory::Core, + source_event_id: None, + visibility: MemoryVisibility::Workspace, + payload_json: None, + }) + .await + .expect("test: named draft"); + let principal = history_reader(&workspace, SESSION, named.clone()); + let merge_err = fixture + .memory + .merge_memory_draft(&principal, &draft.draft_id) + .await + .expect_err("test: Named draft merge over Main"); + assert!( + merge_err.downcast_ref::().is_some(), + "Named draft merge over Main: {merge_err:#}" + ); + + fixture + .memory + .append_retrieval_trace(RetrievalTraceInput { + agent_partition: Some(main.clone()), + trace_id: Some("trace-shared".to_owned()), + workspace_id: workspace.clone(), + owner_id: Some(owner.clone()), + session_key: Some(SESSION.to_owned()), + agent_id: None, + persona_id: None, + source: "test".to_owned(), + query: "q".to_owned(), + candidate_count: 1, + selected_count: 1, + dropped_count: 0, + budget_tokens: None, + selected_json: None, + dropped_json: None, + payload_json: None, + }) + .await + .expect("test: main trace"); + let trace_err = fixture + .memory + .append_retrieval_trace(RetrievalTraceInput { + agent_partition: Some(named.clone()), + trace_id: Some("trace-shared".to_owned()), + workspace_id: workspace.clone(), + owner_id: Some(owner.clone()), + session_key: Some(SESSION.to_owned()), + agent_id: None, + persona_id: None, + source: "test".to_owned(), + query: "q2".to_owned(), + candidate_count: 1, + selected_count: 1, + dropped_count: 0, + budget_tokens: None, + selected_json: None, + dropped_json: None, + payload_json: None, + }) + .await + .expect_err("test: trace collision"); + assert!( + trace_err.downcast_ref::().is_some(), + "trace_id collision: {trace_err:#}" + ); + + fixture + .memory + .append_compaction_run(CompactionRunInput { + agent_partition: Some(main.clone()), + run_id: Some("run-shared".to_owned()), + workspace_id: workspace.clone(), + owner_id: Some(owner.clone()), + session_key: Some(SESSION.to_owned()), + agent_id: None, + persona_id: None, + trigger: "test".to_owned(), + mode: "summary".to_owned(), + source_message_count: 1, + source_token_estimate: 1, + summary: "s".to_owned(), + summary_memory_key: None, + source_event_ids_json: None, + source_event_range_json: None, + source_document_refs_json: None, + fidelity_status: "full".to_owned(), + payload_json: None, + }) + .await + .expect("test: main compaction"); + let run_err = fixture + .memory + .append_compaction_run(CompactionRunInput { + agent_partition: Some(named.clone()), + run_id: Some("run-shared".to_owned()), + workspace_id: workspace.clone(), + owner_id: Some(owner.clone()), + session_key: Some(SESSION.to_owned()), + agent_id: None, + persona_id: None, + trigger: "test".to_owned(), + mode: "summary".to_owned(), + source_message_count: 1, + source_token_estimate: 1, + summary: "other".to_owned(), + summary_memory_key: None, + source_event_ids_json: None, + source_event_range_json: None, + source_document_refs_json: None, + fidelity_status: "full".to_owned(), + payload_json: None, + }) + .await + .expect_err("test: run collision"); + assert!( + run_err.downcast_ref::().is_some(), + "run_id collision: {run_err:#}" + ); + + let fabric = MemoryFabric::new(fixture.memory.clone(), workspace.clone()); + let envelope = crate::runtime::envelope::RuntimeEnvelope::console(workspace.clone(), SESSION.to_owned()) + .with_agent_partition(named.clone()) + .with_owner_id(owner.clone()); + let draft = fabric + .create_worker_memory_draft( + &envelope.message_scope(), + "run-fabric", + "fabric-draft", + "fabric body", + MemoryCategory::Core, + None, + None, + ) + .await + .expect("test: fabric draft"); + let draft_scope: Option = conn + .query_row( + "SELECT ma_scope_id FROM memory_drafts WHERE draft_id = ?1", + [&draft.draft_id], + |row| row.get(0), + ) + .expect("test: draft stamp"); + assert_eq!(draft_scope.as_deref(), Some(TARGET_SCOPE)); + fixture + .memory + .reject_memory_draft(&principal, &draft.draft_id, Some("no")) + .await + .expect("test: fabric reject"); + let event_scope: Option = conn + .query_row( + "SELECT ma_scope_id FROM memory_events WHERE subject_id = ?1 AND event_type = 'memory.draft.rejected'", + [&draft.draft_id], + |row| row.get(0), + ) + .expect("test: reject event"); + assert_eq!(event_scope.as_deref(), Some(TARGET_SCOPE), "derived draft event equals parent scope"); + + fixture + .memory + .move_to_trash("named-core", "test", 7) + .await + .expect("test: trash"); + let trash_scope: Option = conn + .query_row( + "SELECT ma_scope_id FROM memory_trash WHERE memory_key = 'named-core'", + [], + |row| row.get(0), + ) + .expect("test: trash stamp"); + assert_eq!(trash_scope.as_deref(), Some(TARGET_SCOPE)); + }) + .await; +} + +#[tokio::test] +async fn documents_writes_carry_scope() { + let driver = crate::agent::agent::native_decision_fixture::Driver::start("document") + .await + .expect("test: decision fixture"); + let endpoint = driver.endpoint().to_owned(); + driver + .run(async move { + let mut fixture = fixture_with_scope_embedder( + |config| configure_stamped_scope(config, &endpoint, DOC_SCOPE_PROVIDER, &[INGEST_TOOL]), + Arc::new(AtomicUsize::new(0)), + ) + .await; + install_scope_tools(&mut fixture); + let workspace = fixture + .state + .config + .pin() + .effective + .workspace_dir + .to_string_lossy() + .into_owned(); + let owner = super::super::super::ApiPrincipal::for_tests().owner_id; + seed_named_x(std::path::Path::new(&workspace), &workspace, &owner, SESSION); + let named = named_partition(&workspace, &owner, "x", TARGET_U); + let main = main_partition(&workspace, &owner); + let body = format!( + "# First heading\n{}\n\n# Second heading\n{}", + "alpha ".repeat(400), + "bravo ".repeat(400) + ); + let (status, value) = post_scripted( + &mut fixture, + DOC_SCOPE_PROVIDER, + SESSION, + serde_json::json!({"message": "ingest-x", "agent": "x"}), + INGEST_TOOL, + serde_json::json!({"content": body, "title": "named-doc", "document_id": "doc-x"}), + ) + .await; + assert_eq!(status, StatusCode::OK, "Named ingest POST: {value}"); + let conn = brain(&workspace); + let stored_docs: Vec<(String, Option)> = conn + .prepare("SELECT document_id, title FROM documents") + .expect("test: list documents") + .query_map([], |row| Ok((row.get(0)?, row.get(1)?))) + .expect("test: document rows") + .map(|row| row.expect("test: document row")) + .collect(); + let (doc_id, doc_scope): (String, Option) = conn + .query_row( + "SELECT document_id, ma_scope_id FROM documents WHERE title = 'named-doc'", + [], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .unwrap_or_else(|error| { + panic!("test: documents row: {error}; post={value}; stored={stored_docs:?}") + }); + assert_eq!( + doc_scope.as_deref(), + Some(TARGET_SCOPE), + "documents row carries X's scope" + ); + let chunks: i64 = conn + .query_row( + "SELECT count(*) FROM document_chunks WHERE document_id = ?1", + [&doc_id], + |row| row.get(0), + ) + .expect("test: chunks"); + assert!(chunks > 1, "multi-chunk body"); + let chunk_null: i64 = conn + .query_row( + "SELECT count(*) FROM document_chunks WHERE document_id = ?1 AND (ma_scope_id IS NULL OR ma_scope_id != ?2)", + rusqlite::params![&doc_id, TARGET_SCOPE], + |row| row.get(0), + ) + .expect("test: chunk stamps"); + assert_eq!(chunk_null, 0, "every document_chunks row carries X's scope"); + let events: i64 = conn + .query_row( + "SELECT count(*) FROM memory_events WHERE subject_table = 'documents' AND subject_id = ?1 AND ma_scope_id = ?2", + rusqlite::params![&doc_id, TARGET_SCOPE], + |row| row.get(0), + ) + .expect("test: document events"); + assert!(events >= 1, "document memory_events carry X's scope"); + let salted: i64 = conn + .query_row( + "SELECT count(*) FROM embedding_cache WHERE ma_scope_id = ?1 AND length(content_hash) = 64", + [TARGET_SCOPE], + |row| row.get(0), + ) + .expect("test: chunk cache"); + assert!(salted >= 1, "chunk embeddings are salted cache rows"); + let fts: i64 = conn + .query_row( + "SELECT count(*) FROM document_chunks_fts f JOIN document_chunks c ON c.rowid = f.rowid WHERE c.document_id = ?1", + [&doc_id], + |row| row.get(0), + ) + .expect("test: chunks fts"); + assert!(fts > 1, "document_chunks_fts matches"); + + let fabric = MemoryFabric::new(fixture.memory.clone(), workspace.clone()); + let marker = format!("[document_ingest_ref]\ndocument_id: {doc_id}\n[/document_ingest_ref]"); + fabric + .record_semantic_memory_from_event( + "semantic-x", + &marker, + MemoryCategory::Core, + Some(SESSION), + None, + None, + None, + Some(named.clone()), + ) + .await + .expect("test: semantic link"); + let link_scope: Option = conn + .query_row( + "SELECT ma_scope_id FROM memory_links WHERE document_id = ?1", + [&doc_id], + |row| row.get(0), + ) + .expect("test: link stamp"); + assert_eq!(link_scope.as_deref(), Some(TARGET_SCOPE), "memory_links row carries X's scope"); + let promoted_scope: Option = conn + .query_row( + "SELECT ma_scope_id FROM memories WHERE key = 'semantic-x'", + [], + |row| row.get(0), + ) + .expect("test: promoted memories stamp"); + assert_eq!( + promoted_scope.as_deref(), + Some(TARGET_SCOPE), + "promoted memories row carries X's scope" + ); + let promoted_event: Option = conn + .query_row( + "SELECT ma_scope_id FROM memory_events WHERE subject_id = 'semantic-x' AND event_type = 'memory.stored'", + [], + |row| row.get(0), + ) + .expect("test: promoted memory_events stamp"); + assert_eq!( + promoted_event.as_deref(), + Some(TARGET_SCOPE), + "promoted memory_events row carries X's scope" + ); + + fixture + .memory + .ingest_document(crate::memory::DocumentIngestInput { + agent_partition: None, + document_id: Some("doc-null".to_owned()), + workspace_id: workspace.clone(), + owner_id: Some(owner.clone()), + topic_id: None, + task_id: None, + source_message_event_id: None, + source_kind: "test".to_owned(), + source_uri: None, + title: Some("null".to_owned()), + content: "null document".to_owned(), + mime_type: None, + visibility: MemoryVisibility::Workspace, + metadata_json: None, + session_key: Some(SESSION.to_owned()), + agent_id: None, + persona_id: None, + }) + .await + .expect("test: null document"); + fixture + .memory + .link_memory_source(crate::memory::MemoryLinkInput { + agent_partition: Some(main.clone()), + session_key: Some(SESSION.to_owned()), + link_id: Some("link-main-null".to_owned()), + workspace_id: workspace.clone(), + owner_id: Some(owner.clone()), + memory_key: Some("semantic-x".to_owned()), + memory_event_id: None, + message_event_id: None, + document_id: "doc-null".to_owned(), + chunk_id: None, + link_type: "derived_from".to_owned(), + payload_json: None, + }) + .await + .expect("test: Main may link a NULL document"); + let named_null = fixture + .memory + .link_memory_source(crate::memory::MemoryLinkInput { + agent_partition: Some(named.clone()), + session_key: Some(SESSION.to_owned()), + link_id: Some("link-named-null".to_owned()), + workspace_id: workspace.clone(), + owner_id: Some(owner.clone()), + memory_key: Some("semantic-x".to_owned()), + memory_event_id: None, + message_event_id: None, + document_id: "doc-null".to_owned(), + chunk_id: None, + link_type: "derived_from".to_owned(), + payload_json: None, + }) + .await + .expect_err("test: Named may not link a NULL document"); + assert!( + named_null.downcast_ref::().is_some(), + "Named NULL document link: {named_null:#}" + ); + + fixture + .memory + .ingest_document(crate::memory::DocumentIngestInput { + agent_partition: Some(main.clone()), + document_id: Some("doc-collide".to_owned()), + workspace_id: workspace.clone(), + owner_id: Some(owner.clone()), + topic_id: None, + task_id: None, + source_message_event_id: None, + source_kind: "test".to_owned(), + source_uri: None, + title: Some("main".to_owned()), + content: "main document".to_owned(), + mime_type: None, + visibility: MemoryVisibility::Workspace, + metadata_json: None, + session_key: Some(SESSION.to_owned()), + agent_id: None, + persona_id: None, + }) + .await + .expect("test: main collide seed"); + let collide = fixture + .memory + .ingest_document(crate::memory::DocumentIngestInput { + agent_partition: Some(named.clone()), + document_id: Some("doc-collide".to_owned()), + workspace_id: workspace.clone(), + owner_id: Some(owner.clone()), + topic_id: None, + task_id: None, + source_message_event_id: None, + source_kind: "test".to_owned(), + source_uri: None, + title: Some("named".to_owned()), + content: "named document".to_owned(), + mime_type: None, + visibility: MemoryVisibility::Workspace, + metadata_json: None, + session_key: Some(SESSION.to_owned()), + agent_id: None, + persona_id: None, + }) + .await + .expect_err("test: cross-scope document_id"); + assert!( + collide.downcast_ref::().is_some(), + "cross-scope document_id: {collide:#}" + ); + let title: String = conn + .query_row("SELECT title FROM documents WHERE document_id = 'doc-collide'", [], |row| { + row.get(0) + }) + .expect("test: original title"); + assert_eq!(title, "main", "original unchanged"); + + let (status, value) = post_scripted( + &mut fixture, + DOC_SCOPE_PROVIDER, + SESSION, + serde_json::json!({"message": "ingest-main"}), + INGEST_TOOL, + serde_json::json!({"content": "main control document", "title": "main-doc", "document_id": "doc-main"}), + ) + .await; + assert_eq!(status, StatusCode::OK, "Main ingest POST: {value}"); + let main_doc: Option = conn + .query_row( + "SELECT ma_scope_id FROM documents WHERE title = 'main-doc'", + [], + |row| row.get(0), + ) + .expect("test: main document"); + assert!(main_doc.is_some(), "Main control document is stamped"); + }) + .await; +} + +#[tokio::test] +async fn topics_writes_carry_scope() { + let driver = crate::agent::agent::native_decision_fixture::Driver::start("memory") + .await + .expect("test: decision fixture"); + let endpoint = driver.endpoint().to_owned(); + driver + .run(async move { + let mut fixture = fixture_with_scope_embedder( + |config| configure_stamped_scope(config, &endpoint, TOPIC_SCOPE_PROVIDER, &[STORE_TOOL]), + Arc::new(AtomicUsize::new(0)), + ) + .await; + install_scope_tools(&mut fixture); + let workspace = fixture + .state + .config + .pin() + .effective + .workspace_dir + .to_string_lossy() + .into_owned(); + let owner = super::super::super::ApiPrincipal::for_tests().owner_id; + seed_named_x(std::path::Path::new(&workspace), &workspace, &owner, SESSION); + let main = main_partition(&workspace, &owner); + let shared = "prx shared topic collision body for named isolation"; + let seed_ctx = MemoryWriteContext { + workspace_id: Some(workspace.clone()), + owner_id: Some(owner.clone()), + session_key: Some(SESSION.to_owned()), + agent_partition: None, + channel: Some("console".to_owned()), + ..Default::default() + }; + fixture + .memory + .store_with_context( + "shared-topic-seed", + shared, + MemoryCategory::Core, + None, + Some(&seed_ctx), + ) + .await + .expect("test: shared topic seed"); + let conn = brain(&workspace); + let (shared_id, shared_updated, shared_scope): (String, String, Option) = conn + .query_row( + "SELECT id, updated_at, ma_scope_id FROM topics ORDER BY id LIMIT 1", + [], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), + ) + .expect("test: shared topic"); + + let (status, value) = post_scripted( + &mut fixture, + TOPIC_SCOPE_PROVIDER, + SESSION, + serde_json::json!({"message": "topic-x", "agent": "x"}), + STORE_TOOL, + serde_json::json!({"key": "named-shared", "content": shared, "category": "core"}), + ) + .await; + assert_eq!(status, StatusCode::OK, "Named shared-topic POST: {value}"); + let (updated_at, scope): (String, Option) = conn + .query_row( + "SELECT updated_at, ma_scope_id FROM topics WHERE id = ?1", + [&shared_id], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .expect("test: shared after"); + assert_eq!(updated_at, shared_updated, "shared-topic-unchanged updated_at"); + assert_eq!(scope, shared_scope, "shared-topic-unchanged ma_scope_id"); + let named_topic: Option = conn + .query_row( + "SELECT topic_id FROM memories WHERE key = 'named-shared'", + [], + |row| row.get(0), + ) + .expect("test: named topic_id"); + assert!(named_topic.is_none(), "X's memory has topic_id NULL"); + + let unique = "prx unique named topic body for isolation test"; + let (status, value) = post_scripted( + &mut fixture, + TOPIC_SCOPE_PROVIDER, + SESSION, + serde_json::json!({"message": "topic-x-unique", "agent": "x"}), + STORE_TOOL, + serde_json::json!({"key": "named-unique", "content": unique, "category": "core"}), + ) + .await; + assert_eq!(status, StatusCode::OK, "Named unique-topic POST: {value}"); + let x_topics: i64 = conn + .query_row( + "SELECT count(*) FROM topics WHERE ma_scope_id = ?1", + [TARGET_SCOPE], + |row| row.get(0), + ) + .expect("test: X topics"); + assert_eq!(x_topics, 1, "X's memory_store creates a topics row stamped X"); + let fts: i64 = conn + .query_row( + "SELECT count(*) FROM topics_fts f JOIN topics t ON t.rowid = f.rowid WHERE t.ma_scope_id = ?1", + [TARGET_SCOPE], + |row| row.get(0), + ) + .expect("test: topics_fts"); + assert_eq!(fts, 1, "topics_fts has X's topic only"); + let participants: i64 = conn + .query_row( + "SELECT count(*) FROM topic_participants WHERE topic_id IN (SELECT id FROM topics WHERE ma_scope_id = ?1)", + [TARGET_SCOPE], + |row| row.get(0), + ) + .expect("test: participants"); + assert_eq!(participants, 0, "topic_participants have no X rows"); + let aliases: i64 = conn + .query_row("SELECT count(*) FROM topic_aliases", [], |row| row.get(0)) + .expect("test: aliases"); + assert_eq!(aliases, 0, "topic_aliases have no X rows"); + + let main_ctx = partitioned_write_ctx(&workspace, &owner, SESSION, main); + fixture + .memory + .store_with_context("main-unique", "prx main unique topic body for reuse", MemoryCategory::Core, None, Some(&main_ctx)) + .await + .expect("test: Main unique topic"); + fixture + .memory + .store_with_context("main-shared", shared, MemoryCategory::Core, None, Some(&main_ctx)) + .await + .expect("test: Main reuses NULL/Main topic"); + let main_reuse: Option = conn + .query_row( + "SELECT topic_id FROM memories WHERE key = 'main-shared'", + [], + |row| row.get(0), + ) + .expect("test: main reuse"); + assert_eq!(main_reuse.as_deref(), Some(shared_id.as_str()), "Main reuses a NULL/Main topic as today"); + }) + .await; +} diff --git a/src/gateway/implementation/section_1.rs b/src/gateway/implementation/section_1.rs new file mode 100644 index 000000000..147a36306 --- /dev/null +++ b/src/gateway/implementation/section_1.rs @@ -0,0 +1,1740 @@ + + +#[cfg(test)] +pub(crate) use api::{drive_disabled_engine_console_entry, drive_search_console_entry}; + + +pub use h2_control::run_gateway_controlled; + + + + + +/// The reserved issuer component of every built-in (non-bearer) MCP origin. +/// +/// Re-exported so `Config::validate` can refuse a `mcp_server.jwt_issuer` that +/// would collide with one of them inside the `:`-composed caller identity. +pub use compat::FIXED_EXTERNAL_ISSUERS; + + + + +use turn_failure::TurnFailureClass; +use turn_readiness::{GatewayTurnState, TurnNotReady, TurnNotReadyReason, TurnRuntimeStandby}; + +use crate::agent::document_ingest::DocumentIngestRuntime; +use crate::agent::turn_engine::run_turn; +use crate::channels::{Channel, LinqChannel, NextcloudTalkChannel, SendMessage, SignalChannel, WhatsAppChannel}; +use crate::config::Config; +use crate::hooks::HookManager; +use crate::memory::{self, Memory, MemoryCategory, MemoryFabric, MemoryVisibility}; +use crate::observability::NoopObserver; +use crate::providers::{self, ChatMessage, Provider, ProviderCapabilityError}; +use crate::runtime; +use crate::runtime::envelope::RuntimeEnvelope; +use crate::security::SideEffectGate; +use crate::security::pairing::{PairingGuard, constant_time_eq, is_public_bind}; +use crate::security::policy::ResourceRiskLevel; +use crate::tools::{self, McpTool, Tool}; +use crate::util::truncate_with_ellipsis; +use anyhow::{Context, Result}; +use arc_swap::ArcSwap; +use axum::{ + Router, + body::Bytes, + extract::{ConnectInfo, Query, State}, + http::{HeaderMap, StatusCode, header}, + response::{IntoResponse, Json}, + routing::{get, post}, +}; +use parking_lot::Mutex; +use std::collections::{HashMap, HashSet}; +use std::net::{IpAddr, SocketAddr}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::time::{Duration, Instant}; +use tokio::sync::broadcast; +use tokio_util::sync::CancellationToken; +use tower_http::limit::RequestBodyLimitLayer; +use uuid::Uuid; + +/// The gateway's own announce channel for `sessions_spawn`. +/// +/// `sessions_spawn` needs one `Arc` as the fallback destination for +/// a run's completion announcement (and for a kill receipt). Until now the +/// gateway only had one when Signal happened to be configured, so on a host with +/// no Signal account the tool was never registered at all and a webhook turn +/// could not spawn anything. +/// +/// The gateway is a request/response surface: it owns no conversation to push an +/// unsolicited message into, and inventing one would mean a new outbound +/// transport. So this channel deliberately accepts the announcement and drops the +/// outbound leg, recording it in the log instead. Nothing is lost: every run is +/// already recorded in the shared memory fabric by the tool itself, so the result +/// is collected the way a gateway caller collects it anyway — `sessions_spawn`'s +/// own `join`, `sessions_list` / `sessions_history`, or `GET /api/runtime/tasks`. +/// +/// `listen` refuses: this is an outbound sink, never an inbound listener (the +/// 2026-08-26 stage-c constraint — no new listeners, no new transports). +#[derive(Debug, Clone, Copy)] +struct GatewayAnnounceChannel; + +#[async_trait::async_trait] +impl Channel for GatewayAnnounceChannel { + fn name(&self) -> &str { + "gateway" + } + + async fn send(&self, message: &SendMessage) -> Result<()> { + tracing::info!( + recipient = %message.recipient, + body_len = message.content.len(), + "gateway sessions_spawn announcement has no outbound channel; \ + the run result stays retrievable via join / sessions_list" + ); + Ok(()) + } + + async fn listen(&self, _tx: tokio::sync::mpsc::Sender) -> Result<()> { + anyhow::bail!("gateway announce channel does not accept inbound messages") + } +} + +/// Pick the channel `sessions_spawn` announces on for a gateway process. +/// +/// Signal keeps priority whenever it is configured, so a deployment that has one +/// behaves exactly as before. Without it the gateway falls back to its own +/// [`GatewayAnnounceChannel`] rather than skipping the tool: registration of +/// `sessions_spawn` must not depend on an unrelated IM channel being present. +fn gateway_spawn_announce_channel(signal: Option>) -> Arc { + signal.unwrap_or_else(|| Arc::new(GatewayAnnounceChannel)) +} + +/// Maximum request body size (64KB) — prevents memory exhaustion +pub const MAX_BODY_SIZE: usize = 65_536; +/// Larger request body limit for `/api` routes to support media uploads +/// (`10 * 20MB` files plus multipart overhead). +pub const MAX_API_BODY_SIZE: usize = (10 * 20 * 1024 * 1024) + (1024 * 1024); +/// Sliding window used by gateway rate limiting. +pub const RATE_LIMIT_WINDOW_SECS: u64 = 60; +/// Fallback max distinct client keys tracked in gateway rate limiter. +pub const RATE_LIMIT_MAX_KEYS_DEFAULT: usize = 10_000; +/// Fallback max distinct idempotency keys retained in gateway memory. +pub const IDEMPOTENCY_MAX_KEYS_DEFAULT: usize = 10_000; +/// Maximum accepted idempotency-key header length. +const IDEMPOTENCY_MAX_KEY_BYTES: usize = 256; +/// Maximum replay payload retained for one successful request. +const IDEMPOTENCY_MAX_REPLAY_BYTES: usize = 1024 * 1024; +/// Process-wide payload budget reserved by in-flight and successful requests. +const IDEMPOTENCY_REPLAY_BUDGET_BYTES: usize = 32 * 1024 * 1024; +/// Upper bound on how long the gateway waits for in-flight requests to drain +/// after a shutdown signal before forcing exit (D5/D9 step 3). Gateway-local on +/// purpose: `main.rs`'s private `RUNTIME_SHUTDOWN_TIMEOUT` is unreachable from +/// the lib crate. +const GATEWAY_GRACEFUL_TIMEOUT: Duration = Duration::from_secs(30); +/// Refresh required gateway liveness independently of inbound traffic. This is +/// deliberately shorter than the daemon's 60-second core-health TTL. +const GATEWAY_HEALTH_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(20); + +async fn run_health_heartbeat(component: &'static str, interval: Duration, shutdown: CancellationToken) { + let mut ticker = tokio::time::interval(interval); + ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + loop { + tokio::select! { + _ = ticker.tick() => crate::health::touch_component(component), + () = shutdown.cancelled() => break, + } + } +} + +fn webhook_memory_key(idempotency_digest: Option<&str>) -> String { + idempotency_digest.map_or_else( + || format!("webhook_msg_{}", Uuid::new_v4()), + |digest| format!("webhook_msg_{digest}"), + ) +} + +fn whatsapp_memory_key(msg: &crate::channels::traits::ChannelMessage) -> String { + format!("whatsapp_{}_{}", msg.sender, msg.id) +} + +fn linq_memory_key(msg: &crate::channels::traits::ChannelMessage) -> String { + format!("linq_{}_{}", msg.sender, msg.id) +} + +fn nextcloud_talk_memory_key(msg: &crate::channels::traits::ChannelMessage) -> String { + format!("nextcloud_talk_{}_{}", msg.sender, msg.id) +} + +fn is_group_reply_target(reply_target: &str) -> bool { + reply_target.contains("group:") || reply_target.contains("@g.us") +} + +fn should_autosave_gateway_message(reply_target: Option<&str>, content: &str) -> bool { + if !memory::should_autosave_content(content) { + return false; + } + !reply_target.is_some_and(is_group_reply_target) +} + +#[derive(Debug, Clone)] +struct GatewayFabricContext { + channel: String, + session_key: String, + sender: String, + recipient: String, + idempotency_key: Option, + /// The authenticated webhook credential the request presented + /// (`bearer:{sha256}` for a paired token, `token:{sha256}` for the + /// standalone webhook token, `signing-secret:{sha256}` for HMAC, `public` + /// when the gateway requires none). `None` for platform channel messages, + /// whose sender the platform authenticates. + credential: Option, +} + +impl GatewayFabricContext { + /// `reply_target` is chosen by the client, so it never decides the owner + /// or the conversation on its own: the turn owner is the credential with + /// `reply_target` as a sub-namespace under it + /// ([`Self::webhook_owner_id`], R-MCPB F-2), and so is the conversation + /// session key, `gateway:webhook:{credential}:{reply_target}` (D-025). + fn generic_webhook(reply_target: Option<&str>, credential: &str, idempotency_key: Option) -> Self { + let target = reply_target.unwrap_or("webhook-client"); + Self { + channel: "webhook".to_string(), + session_key: format!("gateway:webhook:{credential}:{target}"), + sender: target.to_string(), + recipient: "prx".to_string(), + idempotency_key, + credential: Some(credential.to_string()), + } + } + + /// The owner a webhook turn acts for: + /// `owner:{workspace}:webhook:{credential}:{reply_target}`. Two different + /// credentials never compose the same owner, whatever `reply_target` they + /// send, so one token cannot reach another token's sub-agent runs or + /// owner-scoped rows. Holders of one credential remain one trust domain, + /// separated only by the `reply_target` they assert. `None` for a platform + /// channel message, which keeps its envelope-derived owner. + fn webhook_owner_id(&self, workspace_id: &str) -> Option { + let credential = self.credential.as_deref()?; + Some( + crate::memory::principal::OwnerPrincipal::new( + workspace_id, + self.channel.as_str(), + format!("{credential}:{}", self.sender), + self.session_key.as_str(), + vec![crate::memory::principal::Role::Anonymous], + ) + .owner_id, + ) + } + + fn channel_message(msg: &crate::channels::traits::ChannelMessage) -> Self { + Self { + channel: msg.channel.clone(), + session_key: format!("gateway:{}:{}", msg.channel, msg.sender), + sender: msg.sender.clone(), + recipient: msg.reply_target.clone(), + idempotency_key: Some(format!("gateway:{}:{}", msg.channel, msg.id)), + credential: None, + } + } +} + +/// Domain separator of the webhook owner digest (R-MCPBfg N-4). Bumping it +/// re-keys every webhook owner and conversation once. +const WEBHOOK_OWNER_DIGEST_DOMAIN: &str = "prx-webhook-owner-v1"; + +/// Hex digits of the webhook owner digest kept in owner ids and session keys: +/// 128 bits. +const WEBHOOK_OWNER_DIGEST_HEX: usize = 32; + +/// The credential part of a `/webhook` owner id and session key: +/// `{kind}:{digest}`, where the digest is SHA-256 over +/// `prx-webhook-owner-v1 \0 kind \0 secret`, truncated to 128 bits. +/// +/// Domain-separated on purpose. The plain SHA-256 of a paired token is the +/// at-rest verifier in `gateway.paired_tokens`, and the plain digest of an +/// operator-chosen `X-Webhook-Token` or signing secret is an offline-guessable +/// verifier; neither belongs in message events, run tags, session keys and +/// logs. The value only has to be stable per credential and distinct across +/// credentials. +fn webhook_owner_credential(kind: &str, secret: &str) -> String { + use sha2::{Digest, Sha256}; + + let mut hasher = Sha256::new(); + hasher.update(WEBHOOK_OWNER_DIGEST_DOMAIN.as_bytes()); + hasher.update([0u8]); + hasher.update(kind.as_bytes()); + hasher.update([0u8]); + hasher.update(secret.as_bytes()); + let digest = hex::encode(hasher.finalize()); + let digest = digest.get(..WEBHOOK_OWNER_DIGEST_HEX).unwrap_or(digest.as_str()); + format!("{kind}:{digest}") +} + +pub(super) fn hash_webhook_secret(value: &str) -> String { + use sha2::{Digest, Sha256}; + + let digest = Sha256::digest(value.as_bytes()); + hex::encode(digest) +} + +fn verify_webhook_hmac_signature(secret: &str, body: &[u8], signature_header: &str) -> bool { + use hmac::{Hmac, Mac}; + use sha2::Sha256; + + let signature_hex = signature_header + .trim() + .strip_prefix("sha256=") + .unwrap_or_else(|| signature_header.trim()); + let Ok(provided) = hex::decode(signature_hex) else { + return false; + }; + + let Ok(mut mac) = Hmac::::new_from_slice(secret.as_bytes()) else { + return false; + }; + mac.update(body); + mac.verify_slice(&provided).is_ok() +} + +/// How often the rate limiter sweeps stale IP entries from its map. +const RATE_LIMITER_SWEEP_INTERVAL_SECS: u64 = 300; // 5 minutes + +#[derive(Debug)] +struct SlidingWindowRateLimiter { + /// The budget, re-readable at runtime so a configuration reload can adopt a + /// new one **without** discarding the windows already recorded. Rebuilding + /// the limiter instead would hand every caller a fresh window, which is + /// precisely the moment a throttled caller must not be allowed to burst. + limit_per_window: AtomicU32, + window: Duration, + max_keys: usize, + requests: Mutex<(HashMap>, Instant)>, +} + +impl SlidingWindowRateLimiter { + fn new(limit_per_window: u32, window: Duration, max_keys: usize) -> Self { + Self { + limit_per_window: AtomicU32::new(limit_per_window), + window, + max_keys: max_keys.max(1), + requests: Mutex::new((HashMap::new(), Instant::now())), + } + } + + /// The budget this limiter currently enforces. + fn limit_per_window(&self) -> u32 { + self.limit_per_window.load(Ordering::Relaxed) + } + + /// Adopt a new budget, keeping every recorded window. + fn set_limit_per_window(&self, limit_per_window: u32) { + self.limit_per_window.store(limit_per_window, Ordering::Relaxed); + } + + fn prune_stale(requests: &mut HashMap>, cutoff: Instant) { + requests.retain(|_, timestamps| { + timestamps.retain(|t| *t > cutoff); + !timestamps.is_empty() + }); + } + + fn allow(&self, key: &str) -> bool { + let limit_per_window = self.limit_per_window(); + if limit_per_window == 0 { + return true; + } + + let now = Instant::now(); + let cutoff = now.checked_sub(self.window).unwrap_or(now); + + let mut guard = self.requests.lock(); + let (requests, last_sweep) = &mut *guard; + + // Periodic sweep: remove keys with no recent requests + if last_sweep.elapsed() >= Duration::from_secs(RATE_LIMITER_SWEEP_INTERVAL_SECS) { + Self::prune_stale(requests, cutoff); + *last_sweep = now; + } + + if !requests.contains_key(key) && requests.len() >= self.max_keys { + // Opportunistic stale cleanup before eviction under cardinality pressure. + Self::prune_stale(requests, cutoff); + *last_sweep = now; + + if requests.len() >= self.max_keys { + // Evict the key with the fewest recent requests. FIFO (oldest) + // eviction lets an attacker cycle through IPs and reset legitimate + // users' rate-limit counters. Evicting the least-active key is + // harder to weaponize. + let evict_key = requests + .iter() + .min_by_key(|(_, timestamps)| timestamps.len()) + .map(|(k, _)| k.clone()); + if let Some(evict_key) = evict_key { + requests.remove(&evict_key); + } + } + } + + let entry = requests.entry(key.to_owned()).or_default(); + entry.retain(|instant| *instant > cutoff); + + if entry.len() >= limit_per_window as usize { + return false; + } + + entry.push(now); + true + } +} + +#[derive(Debug)] +pub struct GatewayRateLimiter { + pair: SlidingWindowRateLimiter, + webhook: SlidingWindowRateLimiter, + webhook_credential: SlidingWindowRateLimiter, + api: SlidingWindowRateLimiter, +} + +impl GatewayRateLimiter { + pub fn new(pair_per_minute: u32, webhook_per_minute: u32, api_per_minute: u32, max_keys: usize) -> Self { + let window = Duration::from_secs(RATE_LIMIT_WINDOW_SECS); + Self { + pair: SlidingWindowRateLimiter::new(pair_per_minute, window, max_keys), + webhook: SlidingWindowRateLimiter::new(webhook_per_minute, window, max_keys), + webhook_credential: SlidingWindowRateLimiter::new(webhook_per_minute, window, max_keys), + api: SlidingWindowRateLimiter::new(api_per_minute, window, max_keys), + } + } + + fn allow_pair(&self, key: &str) -> bool { + self.pair.allow(key) + } + + pub fn allow_webhook(&self, key: &str) -> bool { + self.webhook.allow(key) + } + + fn allow_webhook_credential(&self, key: &str) -> bool { + self.webhook_credential.allow(key) + } + + pub(super) fn allow_api(&self, key: &str) -> bool { + self.api.allow(key) + } +} + +#[derive(Debug)] +pub struct IdempotencyStore { + ttl: Duration, + max_keys: usize, + state: Mutex, +} + +#[derive(Debug, Default)] +struct IdempotencyStoreState { + entries: HashMap, + next_generation: u64, + payload_bytes: usize, +} + +#[derive(Debug)] +enum IdempotencyEntry { + Processing { + generation: u64, + request_fingerprint: [u8; 32], + reserved_bytes: usize, + }, + Succeeded { + request_fingerprint: [u8; 32], + completed_at: Instant, + response_id: Uuid, + result_hash: String, + replay: Option, + }, + Failed { + request_fingerprint: [u8; 32], + failed_at: Instant, + retry_eligible: bool, + }, +} + +impl IdempotencyEntry { + const fn request_fingerprint(&self) -> &[u8; 32] { + match self { + Self::Processing { + request_fingerprint, .. + } + | Self::Succeeded { + request_fingerprint, .. + } + | Self::Failed { + request_fingerprint, .. + } => request_fingerprint, + } + } +} + +#[derive(Debug, Clone)] +struct IdempotencyReplay { + response_id: Uuid, + response: Arc, + model: Arc, +} + +impl IdempotencyReplay { + fn payload_bytes(&self) -> usize { + self.response.len().saturating_add(self.model.len()) + } + + fn json_body(&self) -> serde_json::Value { + serde_json::json!({ + "status": "duplicate", + "idempotent": true, + "response": self.response.as_ref(), + "model": self.model.as_ref(), + "response_id": self.response_id.to_string(), + }) + } +} + +#[derive(Debug)] +enum IdempotencyClaimOutcome { + Acquired(IdempotencyClaim), + Processing, + Replay(IdempotencyReplay), + ReplayUnavailable { response_id: Uuid, result_hash: String }, + RequestConflict, + RetryUnavailable, + AtCapacity, +} + +#[derive(Debug)] +struct IdempotencyClaim { + store: Arc, + key_digest: String, + generation: u64, + armed: bool, + /// Whether this attempt reached work that can produce observable side + /// effects — memory writes, tool calls, outbound messages. + /// + /// This is the only thing that decides whether a redelivery of the same key + /// is allowed to run again. Before dispatch a failed attempt is provably a + /// no-op, so re-running it is free. After dispatch nothing here knows how + /// far the attempt got, so re-running it could write the file, send the + /// message, or call the external API a second time. "Not known to be safe" + /// is therefore treated as "not retryable", never the other way round. + dispatched: bool, +} + +impl IdempotencyClaim { + /// Record that the attempt is about to start doing observable work. + /// + /// Call this immediately before the first side effect, not at claim + /// acquisition: everything up to that point is what makes a retry safe. + const fn mark_dispatched(&mut self) { + self.dispatched = true; + } + + /// Whether a redelivery of this key may re-execute the request. + const fn retry_eligible(&self) -> bool { + !self.dispatched + } + + fn succeed(mut self, replay: IdempotencyReplay, result_hash: String) -> bool { + let transitioned = self + .store + .complete_if_owner(&self.key_digest, self.generation, replay, result_hash); + if transitioned { + self.armed = false; + } + transitioned + } + + fn succeed_unavailable(mut self, response_id: Uuid, result_hash: String) -> bool { + let transitioned = + self.store + .complete_result_if_owner(&self.key_digest, self.generation, response_id, result_hash, None); + if transitioned { + self.armed = false; + } + transitioned + } + + fn fail(mut self) -> bool { + let retry_eligible = self.retry_eligible(); + let transitioned = self + .store + .fail_if_owner(&self.key_digest, self.generation, retry_eligible); + if transitioned { + self.armed = false; + } + transitioned + } +} + +impl Drop for IdempotencyClaim { + /// A claim that reaches `Drop` still armed was abandoned without anyone + /// deciding how the attempt ended: the task was cancelled or killed, a + /// caller took an early return path, or a panic unwound through it. + /// + /// This used to release the key as `retry_eligible = true`, which turned + /// every abandoned attempt into an invitation to run the whole request + /// again — while the original may still have been mid-flight, and after it + /// may already have written half its side effects. Abandonment carries no + /// information about how far the work got, so it resolves the same way any + /// other unknown does: dispatched work is not retryable. + fn drop(&mut self) { + if self.armed { + let retry_eligible = self.retry_eligible(); + let _ = self + .store + .fail_if_owner(&self.key_digest, self.generation, retry_eligible); + } + } +} + +impl IdempotencyStore { + pub fn new(ttl: Duration, max_keys: usize) -> Self { + Self { + ttl, + max_keys: max_keys.max(1), + state: Mutex::new(IdempotencyStoreState::default()), + } + } + + fn prune_expired_terminal(&self, state: &mut IdempotencyStoreState, now: Instant) { + let expired = state + .entries + .iter() + .filter_map(|(key, entry)| { + let terminal_at = match entry { + IdempotencyEntry::Processing { .. } => return None, + IdempotencyEntry::Succeeded { completed_at, .. } => *completed_at, + IdempotencyEntry::Failed { failed_at, .. } => *failed_at, + }; + (now.saturating_duration_since(terminal_at) >= self.ttl).then(|| key.clone()) + }) + .collect::>(); + + for key in expired { + if let Some(IdempotencyEntry::Succeeded { + replay: Some(replay), .. + }) = state.entries.remove(&key) + { + state.payload_bytes = state.payload_bytes.saturating_sub(replay.payload_bytes()); + } + } + } + + fn reserve_processing( + self: &Arc, + state: &mut IdempotencyStoreState, + key_digest: String, + request_fingerprint: [u8; 32], + ) -> IdempotencyClaimOutcome { + let Some(next_payload_bytes) = state.payload_bytes.checked_add(IDEMPOTENCY_MAX_REPLAY_BYTES) else { + return IdempotencyClaimOutcome::AtCapacity; + }; + if next_payload_bytes > IDEMPOTENCY_REPLAY_BUDGET_BYTES { + return IdempotencyClaimOutcome::AtCapacity; + } + let Some(generation) = state.next_generation.checked_add(1) else { + return IdempotencyClaimOutcome::AtCapacity; + }; + state.next_generation = generation; + state.payload_bytes = next_payload_bytes; + state.entries.insert( + key_digest.clone(), + IdempotencyEntry::Processing { + generation, + request_fingerprint, + reserved_bytes: IDEMPOTENCY_MAX_REPLAY_BYTES, + }, + ); + IdempotencyClaimOutcome::Acquired(IdempotencyClaim { + store: Arc::clone(self), + key_digest, + generation, + armed: true, + dispatched: false, + }) + } + + fn claim(self: &Arc, key_digest: String, request_fingerprint: [u8; 32]) -> IdempotencyClaimOutcome { + let now = Instant::now(); + let mut state = self.state.lock(); + self.prune_expired_terminal(&mut state, now); + + enum Existing { + Processing, + Replay(IdempotencyReplay), + ReplayUnavailable(Uuid, String), + Retry, + RetryUnavailable, + RequestConflict, + } + let existing = state.entries.get(&key_digest).map(|entry| { + if entry.request_fingerprint() != &request_fingerprint { + return Existing::RequestConflict; + } + match entry { + IdempotencyEntry::Processing { .. } => Existing::Processing, + IdempotencyEntry::Succeeded { + response_id, + result_hash, + replay, + .. + } => replay.as_ref().map_or_else( + || Existing::ReplayUnavailable(*response_id, result_hash.clone()), + |snapshot| Existing::Replay(snapshot.clone()), + ), + IdempotencyEntry::Failed { retry_eligible, .. } => { + if *retry_eligible { + Existing::Retry + } else { + Existing::RetryUnavailable + } + } + } + }); + + match existing { + Some(Existing::Processing) => IdempotencyClaimOutcome::Processing, + Some(Existing::Replay(replay)) => IdempotencyClaimOutcome::Replay(replay), + Some(Existing::ReplayUnavailable(response_id, result_hash)) => IdempotencyClaimOutcome::ReplayUnavailable { + response_id, + result_hash, + }, + Some(Existing::RetryUnavailable) => IdempotencyClaimOutcome::RetryUnavailable, + Some(Existing::RequestConflict) => IdempotencyClaimOutcome::RequestConflict, + Some(Existing::Retry) => self.reserve_processing(&mut state, key_digest, request_fingerprint), + None => { + if state.entries.len() >= self.max_keys { + return IdempotencyClaimOutcome::AtCapacity; + } + self.reserve_processing(&mut state, key_digest, request_fingerprint) + } + } + } + + fn complete_if_owner( + &self, + key_digest: &str, + generation: u64, + replay: IdempotencyReplay, + result_hash: String, + ) -> bool { + let response_id = replay.response_id; + let replay = (replay.payload_bytes() <= IDEMPOTENCY_MAX_REPLAY_BYTES).then_some(replay); + self.complete_result_if_owner(key_digest, generation, response_id, result_hash, replay) + } + + fn complete_result_if_owner( + &self, + key_digest: &str, + generation: u64, + response_id: Uuid, + result_hash: String, + replay: Option, + ) -> bool { + let mut state = self.state.lock(); + let Some(IdempotencyEntry::Processing { + generation: current_generation, + request_fingerprint, + reserved_bytes, + .. + }) = state.entries.get(key_digest) + else { + return false; + }; + if *current_generation != generation { + return false; + } + + let request_fingerprint = *request_fingerprint; + let reserved_bytes = *reserved_bytes; + state.payload_bytes = state.payload_bytes.saturating_sub(reserved_bytes); + state.payload_bytes = state + .payload_bytes + .saturating_add(replay.as_ref().map_or(0, IdempotencyReplay::payload_bytes)); + state.entries.insert( + key_digest.to_string(), + IdempotencyEntry::Succeeded { + request_fingerprint, + completed_at: Instant::now(), + response_id, + result_hash, + replay, + }, + ); + true + } + + fn fail_if_owner(&self, key_digest: &str, generation: u64, retry_eligible: bool) -> bool { + let mut state = self.state.lock(); + let Some(IdempotencyEntry::Processing { + generation: current_generation, + request_fingerprint, + reserved_bytes, + .. + }) = state.entries.get(key_digest) + else { + return false; + }; + if *current_generation != generation { + return false; + } + + let request_fingerprint = *request_fingerprint; + let reserved_bytes = *reserved_bytes; + state.payload_bytes = state.payload_bytes.saturating_sub(reserved_bytes); + state.entries.insert( + key_digest.to_string(), + IdempotencyEntry::Failed { + request_fingerprint, + failed_at: Instant::now(), + retry_eligible, + }, + ); + true + } +} + +fn webhook_request_fingerprint(body: &[u8]) -> [u8; 32] { + use sha2::{Digest, Sha256}; + Sha256::digest(body).into() +} + +/// Read an idempotency-key request header under a shared length cap. +/// +/// `/webhook` (`X-Idempotency-Key`) and `POST /mcp/v1/tools/call` +/// (`Idempotency-Key`) both accept a caller-supplied key, so both cap it the +/// same way: a non-UTF-8 or over-long value is a client error rather than +/// something silently truncated into a different key, and a blank value is +/// treated as "no key" rather than as the empty key. +fn idempotency_key_from_header(headers: &HeaderMap, header_name: &str) -> Result, String> { + let Some(value) = headers.get(header_name) else { + return Ok(None); + }; + let Ok(value) = value.to_str() else { + return Err(format!("{header_name} must be valid UTF-8")); + }; + let value = value.trim(); + if value.is_empty() { + return Ok(None); + } + if value.len() > IDEMPOTENCY_MAX_KEY_BYTES { + return Err(format!( + "{header_name} exceeds the {IDEMPOTENCY_MAX_KEY_BYTES}-byte limit" + )); + } + Ok(Some(value.to_string())) +} + +fn webhook_idempotency_digest(scope: &str, raw_key: &str) -> String { + use sha2::{Digest, Sha256}; + let mut hasher = Sha256::new(); + hasher.update(scope.as_bytes()); + hasher.update([0]); + hasher.update(raw_key.as_bytes()); + hex::encode(hasher.finalize()) +} + +fn webhook_result_hash(response: &str, model: &str) -> String { + crate::agent::terminal::oversized_reply::result_hash(response, model) +} + +fn replay_unavailable_body(response_id: Uuid, result_hash: &str) -> serde_json::Value { + serde_json::json!({ + "status": "replay_unavailable", "idempotent": true, + "response_id": response_id.to_string(), "result_hash": result_hash, + "message": "The original request succeeded, but its response is too large to replay" + }) +} + +fn parse_client_ip(value: &str) -> Option { + let value = value.trim().trim_matches('"').trim(); + if value.is_empty() { + return None; + } + + if let Ok(ip) = value.parse::() { + return Some(ip); + } + + if let Ok(addr) = value.parse::() { + return Some(addr.ip()); + } + + let value = value.trim_matches(['[', ']']); + value.parse::().ok() +} + +fn forwarded_client_ip(headers: &HeaderMap) -> Option { + // Prefer X-Real-IP (single trusted proxy) over X-Forwarded-For + if let Some(real_ip) = headers + .get("X-Real-IP") + .and_then(|v| v.to_str().ok()) + .and_then(parse_client_ip) + { + return Some(real_ip); + } + + // RFC 7239: use the LAST (rightmost) IP in X-Forwarded-For, which is the + // one added by the closest trusted proxy. Using the first IP is spoofable + // by the client and can bypass rate limiting. + if let Some(xff) = headers.get("X-Forwarded-For").and_then(|v| v.to_str().ok()) { + for candidate in xff.rsplit(',') { + if let Some(ip) = parse_client_ip(candidate) { + return Some(ip); + } + } + } + + None +} + +pub(super) fn client_key_from_request( + peer_addr: Option, + headers: &HeaderMap, + trust_forwarded_headers: bool, +) -> String { + if trust_forwarded_headers { + if let Some(ip) = forwarded_client_ip(headers) { + return ip.to_string(); + } + } + + peer_addr + .map(|addr| addr.ip().to_string()) + .unwrap_or_else(|| "unknown".to_string()) +} + +fn normalize_max_keys(configured: usize, fallback: usize) -> usize { + if configured == 0 { fallback.max(1) } else { configured } +} + +fn authorize_gateway_resource_mutation( + state: &AppState, + operation_name: &str, + risk: ResourceRiskLevel, +) -> Result<(), (StatusCode, Json)> { + let config = state.config.load_full(); + authorize_gateway_config_resource_mutation(&config, operation_name, risk) +} + +fn authorize_gateway_config_resource_mutation( + config: &Config, + operation_name: &str, + risk: ResourceRiskLevel, +) -> Result<(), (StatusCode, Json)> { + let policy = crate::runtime::bootstrap::build_security_policy(&config); + SideEffectGate::new(&policy) + .authorize_resource_operation("gateway", operation_name, risk, None) + .map(|_| ()) + .map_err(|error| (StatusCode::FORBIDDEN, Json(serde_json::json!({"error": error})))) +} + +fn gateway_channel_webhook_operation(channel: &str, action: &str) -> String { + format!("gateway:channel_webhook:{channel}:{action}") +} + +/// Shared state for all axum handlers +#[derive(Clone)] +pub struct AppState { + pub rf_streams: Arc, + pub rf_approvals: Arc, + /// Sole configuration generation owner used by every gateway path. + pub config: crate::config::SharedConfig, + /// Test fixtures' provider, served by `pin_turn_runtime` when a test + /// state has no turn runtime; every production turn takes its provider + /// from [`turn_runtime`](Self::turn_runtime). + #[cfg(test)] + pub provider: Arc, + pub model: String, + pub temperature: f64, + pub mem: Arc, + pub auto_save: bool, + /// Test fixtures' registry, served by `pin_turn_runtime` when a test + /// state has no turn runtime. Production state never holds one: every + /// handler pins [`turn_runtime`](Self::turn_runtime), and a registry kept + /// here would retain the startup generation, and its MCP children, for + /// the gateway's lifetime (D-098 F-1). + #[cfg(test)] + pub tools_registry: Arc>>, + /// Test fixtures' MCP tool (see [`tools_registry`](Self::tools_registry)). + #[cfg(test)] + pub mcp_tool: Option>, + /// Atomically rebuilt provider/model/tools bundle for newly admitted turns. + pub turn_runtime: Option>, + /// Hook manager for lifecycle events. + pub hooks: Arc, + /// SHA-256 hash of `webhook.token` for `X-Webhook-Token` auth. + pub webhook_token_hash: Option>, + /// HMAC signing secret for `X-Webhook-Signature` verification. + pub webhook_signing_secret: Option>, + pub pairing: Arc, + pub trust_forwarded_headers: bool, + pub rate_limiter: Arc, + pub idempotency_store: Arc, + pub whatsapp: Option>, + pub signal: Option>, + /// `WhatsApp` app secret for webhook signature verification (`X-Hub-Signature-256`) + pub whatsapp_app_secret: Option>, + pub linq: Option>, + /// Linq webhook signing secret for signature verification + pub linq_signing_secret: Option>, + pub nextcloud_talk: Option>, + /// Nextcloud Talk webhook secret for signature verification + pub nextcloud_talk_webhook_secret: Option>, + /// Observability backend for metrics scraping + pub observer: Arc, + /// Gateway boot instant used for uptime in Web Console status API. + pub start_time: Instant, + /// Actual bound gateway port (supports dynamic port assignment). + pub gateway_port: u16, + /// Web Console log stream broadcast channel. + pub logs_broadcast_tx: broadcast::Sender, + /// Sole process-level owner of the WASM registry and every derived adapter. + #[cfg(feature = "wasm-plugins")] + pub plugin_runtime: Option>, +} + +pub struct TurnRuntimeGeneration { + provider_binding: Option>, + publication_slot: Arc, + pub config_generation: Arc, + pub provider: Arc, + pub model: String, + pub temperature: f64, + pub tools_registry: Arc>>, + pub mcp_tool: Option>, +} + +struct ConfigGenerationMessageAuditSink { + memory: Arc, + workspace_id: String, + runtime_handle: tokio::runtime::Handle, +} + +impl crate::config::ConfigGenerationAuditSink for ConfigGenerationMessageAuditSink { + fn record(&self, event: crate::config::ConfigGenerationAuditEvent) { + let memory = Arc::clone(&self.memory); + let workspace_id = self.workspace_id.clone(); + self.runtime_handle.spawn(async move { + let source_revision = event + .source_revision + .as_ref() + .map(|revision| revision.fingerprint_sha256.clone()); + let raw_payload_json = serde_json::to_string(&event).ok(); + let input = crate::memory::MessageEventInput { + agent_partition: None, + event_id: None, + idempotency_key: None, + workspace_id, + owner_id: Some("system".to_string()), + source: crate::memory::MessageEventSource::Other("config".to_string()), + channel: Some("daemon".to_string()), + session_key: Some("config-generation".to_string()), + parent_session_key: None, + run_id: event.generation_id.map(|generation| format!("config:{}", generation.0)), + parent_run_id: None, + agent_id: Some("config-generation-manager".to_string()), + persona_id: None, + sender: Some("system".to_string()), + recipient: Some("runtime".to_string()), + role: "event".to_string(), + event_type: event.event_type.clone(), + subject: None, + goal_id: None, + causation_event_id: None, + correlation_id: None, + attempt_id: None, + lease_epoch: None, + config_generation_id: event.generation_id.map(|generation| generation.0), + config_source_revision: source_revision, + content: event.payload.to_string(), + raw_payload_json, + visibility: MemoryVisibility::Workspace, + }; + if let Err(error) = memory.append_message_event(input).await { + tracing::warn!( + event_type = %event.event_type, + "failed to append config generation audit event: {error}" + ); + } + }); + } +} + +pub struct GatewayTurnRuntimeOwner { + cleanup: Arc, + current: Arc>, + config: crate::config::SharedConfig, + memory: Arc, + signal: Option>, + whatsapp: Option>, + linq: Option>, + nextcloud_talk: Option>, + hooks: Arc, + agents: agent_lifecycle::AgentLifecycle, + #[cfg(feature = "wasm-plugins")] + plugin_runtime: Option>, +} + +impl GatewayTurnRuntimeOwner { + fn new( + current: impl Into, + config: crate::config::SharedConfig, + memory: Arc, + signal: Option>, + whatsapp: Option>, + linq: Option>, + nextcloud_talk: Option>, + hooks: Arc, + #[cfg(feature = "wasm-plugins")] plugin_runtime: Option>, + ) -> Self { + // Startup sweep, before any target is published: a failure latches + // every targeted resolve until a later reconcile succeeds. + let agents = agent_lifecycle::AgentLifecycle::default(); + agents.reconcile(memory.as_ref(), &config.pin().effective, true); + let current = current.into(); + Self { + cleanup: Arc::clone(¤t.publication_slot().cleanup), + current: Arc::new(ArcSwap::from_pointee(current)), + config, + memory, + signal, + whatsapp, + linq, + nextcloud_talk, + hooks, + agents, + #[cfg(feature = "wasm-plugins")] + plugin_runtime, + } + } + + fn pin_state(&self) -> Arc { + self.current.load_full() + } + + /// Test fixtures' ready generation. + #[cfg(test)] + fn pin(&self) -> Arc { + self.current + .load() + .ready() + .expect("test: the gateway turn runtime is ready") + } + + const fn agent_lifecycle(&self) -> &agent_lifecycle::AgentLifecycle { + &self.agents + } + + /// Whether the active generation was launched with a controlled H2 profile. + /// + /// The lifecycle experiment HTTP adapter uses this to refuse when the + /// process has no profile. It does not mint an invocation. + pub(crate) fn has_controlled_profile(&self) -> bool { + self.current.load().publication_slot().controlled.is_some() + } + + /// The runtime of `generation`. A ready runtime rejects a generation + /// whose default provider has no usable credential (the previous + /// generation stays active); a runtime standing by takes it and keeps + /// standing by, so the agent and configuration routes keep applying. + fn build(&self, generation: Arc) -> anyhow::Result { + let previous = self.current.load_full(); + if let Some(profile) = &previous.publication_slot().controlled { + profile.revoke(); + anyhow::bail!("controlled Gateway generation cannot be rebuilt"); + } + let chat = build_gateway_turn_provider( + &generation.effective, + &providers::provider_runtime_options_from_config(&generation.effective), + ); + let chat = match (chat, previous.as_ref()) { + (Ok(chat), _) => Ok(chat), + (Err(error), GatewayTurnState::NotReady(_)) => { + let reason = TurnNotReadyReason::of_provider_error(&error).ok_or(error)?; + tracing::warn!( + reason = reason.code(), + "Gateway turn runtime stays not ready after a configuration change" + ); + Err(reason) + } + (Err(error), GatewayTurnState::Ready(_)) => return Err(error), + }; + let mut runtime = build_gateway_turn_state( + generation, + chat, + Arc::clone(&self.config), + Arc::clone(&self.memory), + self.signal.clone(), + self.whatsapp.clone(), + self.linq.clone(), + self.nextcloud_talk.clone(), + Arc::clone(&self.hooks), + #[cfg(feature = "wasm-plugins")] + self.plugin_runtime.clone(), + )?; + let slot = runtime + .publication_slot_mut() + .ok_or_else(|| anyhow::anyhow!("new gateway turn runtime was unexpectedly shared"))?; + Arc::get_mut(slot) + .ok_or_else(|| anyhow::anyhow!("new gateway decision slot was unexpectedly shared"))? + .cleanup = Arc::clone(&self.cleanup); + Ok(runtime) + } + + /// Retry a runtime standing by against the active generation. Storing a + /// provider credential changes no configuration field, so the reload + /// that follows publishes no generation and prepares no participant; + /// the reload route calls this so that reload still makes the runtime + /// ready. A runtime that is ready, or that another reload replaced in + /// the meantime, is left as it is. `Ok(true)` when this call made the + /// runtime ready. + pub(crate) fn retry_standby(&self) -> anyhow::Result { + let previous = self.current.load_full(); + if previous.ready().is_ok() { + return Ok(false); + } + let next = self.build(self.config.pin())?; + if next.ready().is_err() { + return Ok(false); + } + let next = Arc::new(next); + let swapped = self.current.compare_and_swap(&previous, Arc::clone(&next)); + if !Arc::ptr_eq(&swapped, &previous) { + return Ok(false); + } + retire_replaced_mcp_servers(previous.mcp_tool(), next.mcp_tool()); + tracing::info!("Gateway turn runtime is ready: the default provider credential resolved"); + Ok(true) + } + + fn synchronize_to_active(&self) -> anyhow::Result<()> { + let active = self.config.pin(); + if self.current.load().config_generation().id == active.id { + return Ok(()); + } + self.current.store(Arc::new(self.build(active)?)); + Ok(()) + } +} + +/// Start the Gateway's turn runtime from its startup generation: the owner +/// that rebuilds it on every configuration change, registered with the +/// manager and synchronized to the active generation. The returned owner is +/// the startup generation's only holder, so the first configuration change +/// releases it and ends its stdio MCP children, and a change of a server's +/// definition stops the process that ran the old one (D-098 F-1). +#[allow(clippy::too_many_arguments)] +fn start_gateway_turn_runtime( + startup: impl Into, + shared: &crate::config::SharedConfig, + memory: Arc, + signal: Option>, + whatsapp: Option>, + linq: Option>, + nextcloud_talk: Option>, + hooks: Arc, + #[cfg(feature = "wasm-plugins")] plugin_runtime: Option>, +) -> anyhow::Result> { + let owner = Arc::new(GatewayTurnRuntimeOwner::new( + startup, + Arc::clone(shared), + memory, + signal, + whatsapp, + linq, + nextcloud_talk, + hooks, + #[cfg(feature = "wasm-plugins")] + plugin_runtime, + )); + let participant: Arc = owner.clone(); + shared.register_participant(&participant); + owner.synchronize_to_active()?; + Ok(owner) +} + +struct PreparedGatewayTurnRuntime { + current: Arc>, + previous: Arc, + generation: GatewayTurnState, + agents: agent_lifecycle::AgentReconcile, +} + +impl crate::config::PreparedConfigGeneration for PreparedGatewayTurnRuntime { + fn commit(&mut self) -> anyhow::Result<()> { + // First, so a failed retire rejects the reload before it is published. + self.agents.commit()?; + self.current.store(Arc::new(self.generation.clone())); + if self.previous.ready().is_err() && self.generation.ready().is_ok() { + tracing::info!("Gateway turn runtime is ready: the default provider credential resolved"); + } + retire_replaced_mcp_servers(self.previous.mcp_tool(), self.generation.mcp_tool()); + Ok(()) + } + + fn rollback(&mut self) { + self.current.store(Arc::clone(&self.previous)); + self.agents.rollback(); + } + + fn finalize(&mut self) { + self.agents + .finalize(&self.generation.config_generation().source_revision.fingerprint_sha256); + } +} + +/// When a new generation replaces the MCP tool, stop the old tool's +/// servers that the new one no longer runs as they were launched (a +/// narrowed `mcp.workspace_servers`, a removed or disabled server, a changed +/// command, arguments, environment or working directory), so the process +/// running the old definition ends now instead of when the old tool is +/// dropped (D-095 M-2, D-097 M-3). Servers both generations run alike keep +/// their sessions until the old tool is dropped, which happens when the +/// last turn pinned to the old generation ends, so such a turn keeps +/// working. The stop runs on the runtime; without one it is logged and left +/// to the tool's drop. +fn retire_replaced_mcp_servers(previous: Option<&Arc>, next: Option<&Arc>) { + let Some(previous) = previous.cloned() else { + return; + }; + if next.is_some_and(|next| Arc::ptr_eq(next, &previous)) { + return; + } + let keep = next + .map(|next| previous.servers_launched_alike(next)) + .unwrap_or_default(); + match tokio::runtime::Handle::try_current() { + Ok(handle) => { + handle.spawn(async move { + let stopped = previous.retire_servers_except(&keep).await; + if stopped > 0 { + tracing::info!( + stopped, + "Stopped MCP servers the new configuration no longer runs as launched" + ); + } + }); + } + Err(error) => tracing::warn!( + error = %error, + "No async runtime to stop the MCP servers the new configuration no longer runs" + ), + } +} + +impl crate::config::ConfigGenerationParticipant for GatewayTurnRuntimeOwner { + fn name(&self) -> &'static str { + "gateway_turn_runtime" + } + + fn supports_rebuild_field(&self, _field: &str) -> bool { + true + } + + fn prepares_for_field(&self, field: &str) -> bool { + !crate::config::generation::is_process_restart_only(field) + && !crate::config::generation::is_controlled_restart(field) + } + + fn prepare( + &self, + generation: Arc, + _changed_fields: &[String], + ) -> anyhow::Result> { + let previous = self.current.load_full(); + let agents = agent_lifecycle::AgentReconcile::prepare( + &self.agents, + &self.memory, + &previous.config_generation().effective, + &generation.effective, + ); + let runtime = self.build(generation)?; + Ok(Box::new(PreparedGatewayTurnRuntime { + current: Arc::clone(&self.current), + previous, + generation: runtime, + agents, + })) + } +} + +impl AppState { + /// The current turn runtime, ready or standing by. Routes that read the + /// tool surface or the configuration take this; routes that start or + /// continue a turn take [`admit_turn_runtime`](Self::admit_turn_runtime). + fn pin_turn_state(&self) -> Arc { + if let Some(runtime) = &self.turn_runtime { + return runtime.pin_state(); + } + #[cfg(not(test))] + { + tracing::error!("production gateway state is missing its TurnRuntimeGeneration; aborting"); + std::process::abort(); + } + #[cfg(test)] + { + Arc::new(GatewayTurnState::Ready(self.test_turn_runtime())) + } + } + + /// The admission check of every turn entry point: the ready generation + /// the turn runs on, or the typed refusal it answers with. + fn admit_turn_runtime(&self) -> Result, TurnNotReady> { + self.pin_turn_state().ready() + } + + /// Test fixtures' ready generation. + #[cfg(test)] + fn pin_turn_runtime(&self) -> Arc { + self.turn_runtime + .as_ref() + .map_or_else(|| self.test_turn_runtime(), |runtime| runtime.pin()) + } + + #[cfg(test)] + fn test_turn_runtime(&self) -> Arc { + { + let mut generation = TurnRuntimeGeneration { + provider_binding: None, + publication_slot: Arc::new(turn_source::publication_slot::GatewayPublicationSlot::default()), + config_generation: self.config.pin(), + provider: Arc::clone(&self.provider), + model: self.model.clone(), + temperature: self.temperature, + tools_registry: Arc::clone(&self.tools_registry), + mcp_tool: self.mcp_tool.clone(), + }; + let config = &generation.config_generation.effective; + if let Some(provider_name) = config.default_provider.as_deref() { + let catalog = crate::providers::selection::catalog_for(config); + if let Ok(resolved) = crate::providers::selection::check_with( + config, + &catalog, + provider_name, + &generation.model, + crate::providers::selection::credential_for(config, provider_name), + &crate::providers::catalog::Requirement::chat(), + crate::providers::catalog::UnknownPolicy::Invocation, + ) { + generation.provider_binding = Some(Arc::new(turn_source::GatewayProviderBinding::new( + Arc::clone(&generation.provider), + resolved, + ))); + let security = Arc::new(crate::security::SecurityPolicy::from_config( + &config.autonomy, + &config.workspace_dir, + )); + generation.publication_slot = + Arc::new(turn_source::publication_slot::GatewayPublicationSlot::new(security, 0)); + } + } + Arc::new(generation) + } + } +} + +/// Build the gateway's per-turn channel routing registry and register the +/// channel-aware tools that complete its tool surface. +/// +/// The gateway has two launch paths — [`build_gateway_turn_runtime`] (under the +/// daemon, and again on every hot reload) and [`run_gateway`] (`prx gateway`, +/// no daemon) — and each used to carry its own symmetric copy of this block. +/// Only the daemon copy had tests, so a change to one path silently gave the two +/// launch modes different tool surfaces. There is one body now, and +/// `both_gateway_launch_paths_publish_the_same_tool_surface` asserts the two +/// callers end up with the same tool names. +/// +/// `message_send` is registered only when Signal is configured; `sessions_spawn`, +/// `sessions_list`, `sessions_history` and `config_reload` are registered on +/// every gateway. The two session read tools share `sessions_spawn`'s own +/// active-run registry (`SessionsSpawnTool::active_runs_arc`) and the gateway's +/// memory, so they read back the runs this gateway actually started rather than +/// a registry of their own; they are also the default-exposed MCP capabilities +/// `POST /mcp/v1/tools/call` resolves against this list (V02-R7). Returns the +/// routing registry (the caller publishes it for +/// `POST /api/channels/{name}/send`) and the `sessions_spawn` tools handle, +/// which the caller must fill with the final registry once it is sealed. +#[allow(clippy::too_many_arguments)] +fn register_gateway_turn_tools( + tools_list: &mut Vec>, + config: &Config, + shared_config: &crate::config::SharedConfig, + security: &Arc, + hooks: &Arc, + _model: &str, + memory: &Arc, + provider_runtime_options: &providers::ProviderRuntimeOptions, + signal: Option<&Arc>, + whatsapp: Option<&Arc>, + linq: Option<&Arc>, + nextcloud_talk: Option<&Arc>, +) -> anyhow::Result<(Arc>>, Arc)> { + // One routing registry, keyed by `Channel::name`, shared by `message_send` + // (destination of an explicit `channel` argument) and `sessions_spawn` + // (announce/kill routing) so both address exactly the same channel set. + if shared_config.ensure_runtime_writable().is_err() { + return Ok((Arc::new(HashMap::new()), Arc::new(tools::ParentToolRegistry::default()))); + } + let mut registry: HashMap> = HashMap::new(); + if let Some(channel) = signal { + registry.insert(channel.name().to_string(), Arc::clone(channel) as Arc); + } + if let Some(channel) = whatsapp { + registry.insert(channel.name().to_string(), Arc::clone(channel) as Arc); + } + if let Some(channel) = linq { + registry.insert(channel.name().to_string(), Arc::clone(channel) as Arc); + } + if let Some(channel) = nextcloud_talk { + registry.insert(channel.name().to_string(), Arc::clone(channel) as Arc); + } + let channels_registry = Arc::new(registry); + + // `message_send` is backed by Signal when the channel is configured. Other + // channels are addressed through the routing registry above. + if let Some(signal_channel) = signal { + tools_list.push(Box::new( + tools::MessageSendTool::new_signal(Arc::clone(signal_channel), Arc::clone(security)) + .with_channels(Arc::clone(&channels_registry)), + )); + } + + // `sessions_spawn` is registered on every gateway, with or without Signal. + // The channel argument is only the fallback announce destination, so a + // missing IM channel is no reason to withhold the tool from a webhook turn. + // + // The per-turn announce/kill routing registry is the one built above: a + // webhook turn stamps its originating channel into the tool's per-turn + // scope, and the tool resolves the channel object from here at announce / + // kill time, so a result is never mis-routed under concurrent webhooks. + let spawn_tools_handle = { + let announce_channel = + gateway_spawn_announce_channel(signal.map(|channel| Arc::clone(channel) as Arc)); + let provider_name = providers::selection::default_provider(config).to_string(); + let spawn_tool = tools::SessionsSpawnTool::new( + announce_channel, + provider_name, + providers::selection::default_model(config).to_string(), + config.default_temperature, + Arc::clone(security), + config.workspace_dir.clone(), + config.multimodal.clone(), + config.agents_with_references().into_owned(), + config.api_key.clone(), + provider_runtime_options.clone(), + config.sessions_spawn.clone(), + ) + .with_configured_providers(&crate::providers::ConfiguredProviders::from_config(config)) + .with_model_catalog(providers::selection::catalog_for(config)) + .with_hint_config(config) + .with_parent_hooks(Arc::clone(hooks)) + .with_channels(Arc::clone(&channels_registry)) + .with_shared_memory(Arc::clone(memory)) + .with_event_recording(config.memory.event_recording_config()) + .with_process_recovery(true)?; + let handle = spawn_tool.tools_handle(); + + // `sessions_list` / `sessions_history` read back what `sessions_spawn` + // started, so they are bound to that tool's own run registry — the same + // `Arc` it writes to — and to the gateway's memory, exactly as the + // channel server wires them. A registry of their own would answer with + // an empty list instead of a 404, which is a worse failure than the one + // this registration fixes. Both are default-exposed MCP capabilities + // (`default_mcp_server_exposed_tools`), and without this registration + // `POST /mcp/v1/tools/call` answered 404 for a name + // `GET /mcp/v1/tools/list` advertises (V02-R7). Pushed before + // `spawn_tool` is moved into the list below. + let active_runs = spawn_tool.active_runs_arc(); + let workspace_id = config.workspace_dir.to_string_lossy().to_string(); + tools_list.push(Box::new( + tools::SessionsListTool::new(active_runs.clone()) + .with_shared_memory(Arc::clone(memory), workspace_id.clone()), + )); + tools_list.push(Box::new( + tools::SessionsSendTool::with_security(Arc::clone(&active_runs), Arc::clone(security)) + .with_messaging(config) + .with_shared_memory(Arc::clone(memory)) + .with_event_recording(config.memory.event_recording_config()), + )); + tools_list.push(Box::new( + tools::SessionStatusTool::new( + Arc::clone(&active_runs), + providers::selection::default_provider(config), + providers::selection::default_model(config), + channels_registry.keys().cloned().collect(), + ) + .with_shared_memory(Arc::clone(memory), workspace_id.clone()), + )); + tools_list.push(Box::new( + tools::SessionsHistoryTool::new(active_runs).with_shared_memory(Arc::clone(memory), workspace_id), + )); + + tools_list.push(Box::new(spawn_tool)); + handle + }; + + // The ConfigReloadTool and `/api/config/reload` route both submit candidates + // to the same manager; no gateway path can publish configuration directly. + tools_list.push(Box::new(tools::ConfigReloadTool::with_security( + shared_config.clone(), + Arc::clone(security), + ))); + + Ok((channels_registry, spawn_tools_handle)) +} + +/// A ready runtime of `generation`, or the error its default provider failed +/// with (test fixtures; production builds through [`build_gateway_turn_state`]). +#[cfg(test)] +#[allow(clippy::too_many_arguments)] +fn build_gateway_turn_runtime( + generation: Arc, + shared_config: crate::config::SharedConfig, + memory: Arc, + signal: Option>, + whatsapp: Option>, + linq: Option>, + nextcloud_talk: Option>, + hooks: Arc, + #[cfg(feature = "wasm-plugins")] plugin_runtime: Option>, +) -> anyhow::Result { + let config = generation.effective.as_ref(); + let chat = build_gateway_turn_provider(config, &providers::provider_runtime_options_from_config(config))?; + let state = build_gateway_turn_state( + generation, + Ok(chat), + shared_config, + memory, + signal, + whatsapp, + linq, + nextcloud_talk, + hooks, + #[cfg(feature = "wasm-plugins")] + plugin_runtime, + )?; + match state { + GatewayTurnState::Ready(generation) => { + Arc::try_unwrap(generation).map_err(|_| anyhow::anyhow!("new gateway turn runtime was unexpectedly shared")) + } + GatewayTurnState::NotReady(standby) => Err(TurnNotReady(standby.reason).into()), + } +} + +/// The runtime of `generation` around its already resolved default chat +/// connection, or a standby with the same tool surface when `chat` names +/// why there is none. The caller resolves the default before anything is +/// built, so a generation whose default model cannot chat is rejected first. +#[allow(clippy::too_many_arguments)] +fn build_gateway_turn_state( + generation: Arc, + chat: Result, + shared_config: crate::config::SharedConfig, + memory: Arc, + signal: Option>, + whatsapp: Option>, + linq: Option>, + nextcloud_talk: Option>, + hooks: Arc, + #[cfg(feature = "wasm-plugins")] plugin_runtime: Option>, +) -> anyhow::Result { + let config = generation.effective.as_ref(); + let provider_runtime_options = providers::provider_runtime_options_from_config(config); + let security = crate::runtime::bootstrap::build_security_policy(config); + let runtime: Arc = Arc::from(runtime::create_runtime(&config.runtime)?); + let (composio_key, composio_entity_id) = if config.composio.configured() { + ( + config.composio.api_key.as_deref(), + Some(config.composio.entity_id.as_str()), + ) + } else { + (None, None) + }; + let extensions = hooks.control_tool_arcs(Arc::clone(&security)); + #[cfg(feature = "wasm-plugins")] + let extensions = { + let mut extensions = extensions; + if let Some(runtime) = &plugin_runtime { + extensions.extend(runtime.control_tool_arcs(Arc::clone(&security))); + } + extensions + }; + let tools_result = tools::all_tools_with_runtime_ext_and_extensions( + Arc::clone(&generation.effective), + Arc::clone(&shared_config), + &security, + runtime, + Arc::clone(&memory), + composio_key, + composio_entity_id, + &config.browser, + &config.http_request, + &config.workspace_dir, + &config.agents_with_references(), + config.api_key.as_deref(), + config, + extensions, + Some(Arc::clone(&hooks)), + ); + let mut tools_list = tools_result.tools; + let mcp_tool = tools_result.mcp_tool; + + let (_channels_registry, spawn_tools_handle) = register_gateway_turn_tools( + &mut tools_list, + config, + &shared_config, + &security, + &hooks, + chat.as_ref().map_or("", |(_, model, _)| model.as_str()), + &memory, + &provider_runtime_options, + signal.as_ref(), + whatsapp.as_ref(), + linq.as_ref(), + nextcloud_talk.as_ref(), + )?; + let tools_registry = Arc::new(tools_list); + let _ = spawn_tools_handle.set(&tools_registry); + + let publication_slot = Arc::new(turn_source::publication_slot::GatewayPublicationSlot::new( + Arc::clone(&security), + { + #[cfg(feature = "wasm-plugins")] + { + plugin_runtime.as_ref().map_or(0, |runtime| runtime.generation_id()) + } + #[cfg(not(feature = "wasm-plugins"))] + { + 0 + } + }, + )); + Ok(turn_state_of( + chat, + publication_slot, + generation, + tools_registry, + mcp_tool, + )) +} + +/// The default chat connection of a ready generation: provider, model and +/// the binding that proves they are the resolved selection. +type GatewayTurnChat = ( + Arc, + String, + Option>, +); diff --git a/src/gateway/implementation/section_2.rs b/src/gateway/implementation/section_2.rs new file mode 100644 index 000000000..4649e56ae --- /dev/null +++ b/src/gateway/implementation/section_2.rs @@ -0,0 +1,1570 @@ +/// Assemble a ready generation, or a standby with the same surface. +fn turn_state_of( + chat: Result, + publication_slot: Arc, + config_generation: Arc, + tools_registry: Arc>>, + mcp_tool: Option>, +) -> GatewayTurnState { + match chat { + Ok((provider, model, provider_binding)) => GatewayTurnState::from(TurnRuntimeGeneration { + provider_binding, + temperature: config_generation.effective.default_temperature, + publication_slot, + config_generation, + provider, + model, + tools_registry, + mcp_tool, + }), + Err(reason) => GatewayTurnState::NotReady(TurnRuntimeStandby { + reason, + publication_slot, + config_generation, + tools_registry, + mcp_tool, + }), + } +} + +/// Build the pinned generation's default chat connection. The selected +/// provider, model and credential are resolved as one value before the exact +/// connection is constructed, including when the default names a route hint. +pub(crate) fn build_gateway_provider_selection( + config: &Config, + options: &providers::ProviderRuntimeOptions, +) -> anyhow::Result<(Arc, providers::catalog::ResolvedModel)> { + let resolved = providers::selection::check_default(config, providers::catalog::UnknownPolicy::Invocation)?; + let catalog = providers::selection::catalog_for(config); + let provider: Arc = Arc::from(providers::create_routed_provider_for( + &resolved, &catalog, config, options, + )?); + Ok((provider, resolved)) +} + +fn build_gateway_turn_provider( + config: &Config, + options: &providers::ProviderRuntimeOptions, +) -> anyhow::Result { + let (provider, resolved) = build_gateway_provider_selection(config, options)?; + let model = resolved.model().to_owned(); + let binding = Arc::new(turn_source::GatewayProviderBinding::new( + Arc::clone(&provider), + resolved, + )); + Ok((provider, model, Some(binding))) +} + +/// Run the HTTP gateway using axum with proper HTTP/1.1 compliance. +/// +/// `shared_config` is the single ConfigGeneration owner the gateway uses for all +/// authorization decisions. When the gateway runs under the daemon, the +/// daemon owns this handle and also wires it to the file-watch hot-reload manager, +/// so config.toml edits become visible at every gateway authz point. When invoked +/// directly via `prx gateway` (no daemon), `None` is passed and the gateway builds +/// its own fallback handle — in that mode only the in-gateway ConfigReloadTool / the +/// `/api/config/reload` route can update it (no file watcher). +#[allow(clippy::too_many_lines)] +pub async fn run_gateway( + host: &str, + port: u16, + config: Config, + shared_config: Option, + shutdown: CancellationToken, +) -> Result<()> { + run_gateway_inner(host, port, config, shared_config, shutdown, None).await +} +async fn run_gateway_inner( + host: &str, + port: u16, + config: Config, + shared_config: Option, + shutdown: CancellationToken, + mut producer: Option, +) -> Result<()> { + let _a2a_listener = crate::messaging::a2a::start(&config, shutdown.child_token()).await?; + let controlled = producer.as_ref().map(|producer| producer.profile()); + if let Some(profile) = &controlled { + profile.verify(&config)?; + anyhow::ensure!(shared_config.is_none(), "controlled Gateway requires direct OS launch"); + } + let start_time = Instant::now(); + crate::health::register_component( + "gateway", + "gateway", + true, + Duration::from_mins(1), + crate::health::ComponentState::Starting, + ); + // ── Security: refuse public bind without tunnel or explicit opt-in ── + if is_public_bind(host) && config.tunnel.provider == "none" && !config.gateway.allow_public_bind { + anyhow::bail!( + "🛑 Refusing to bind to {host} — gateway would be exposed to the internet.\n\ + Fix: use --host 127.0.0.1 (default), configure a tunnel, or set\n\ + [gateway] allow_public_bind = true in config.toml (NOT recommended)." + ); + } + // ── Install owner (HOST-1a): every paired bearer acts for it. Loaded + // before the listener binds, so an unusable id file leaves no route + // answering; it is never regenerated. + let install_owner = crate::security::install_owner::load_or_create(&config.workspace_dir) + .context("gateway start-up refused: the install owner id is unusable")?; + tracing::info!(owner_id = %install_owner, "install owner id loaded"); + let addr: SocketAddr = format!("{host}:{port}").parse()?; + let listener = tokio::net::TcpListener::bind(addr).await?; + let actual_port = listener.local_addr()?.port(); + let _runtime_file = + crate::runtime::host_bootstrap::RuntimeFile::write(&config, actual_port, install_owner.as_str())?; + let display_addr = format!("{host}:{actual_port}"); + + // The chat-session mailbox is durable, and this is the one startup path + // both launch modes share (`prx gateway`, and the daemon's supervised + // gateway), so it is the only place the store has to be attached. Attaching + // replays what the previous process left queued, and is idempotent: the + // daemon's supervisor restarts the gateway inside one process, and a replay + // never duplicates a session that is still live in memory. + if let Some(path) = runtime::chat_sessions::attach_workspace_store(&config.workspace_dir) { + tracing::debug!(path = %path.display(), "chat session mailbox is durable"); + } + + #[cfg(feature = "wasm-plugins")] + let wasm_early_runtime = if config + .default_provider + .as_deref() + .is_some_and(|provider| provider.starts_with("wasm:")) + || memory::effective_memory_backend_name(&config.memory.backend, Some(&config.storage.provider.config)) + .starts_with("wasm:") + { + crate::plugins::init_plugin_runtime(&config, None).await + } else { + None + }; + let provider_runtime_options = providers::provider_runtime_options_from_config(&config); + // A default provider without a usable credential leaves the turn runtime + // standing by instead of failing the start: every management route + // serves, and a reload after the credential is stored makes it ready. + let chat = match build_gateway_turn_provider(&config, &provider_runtime_options) { + Ok(chat) => Ok(chat), + Err(error) => { + let reason = TurnNotReadyReason::of_provider_error(&error).ok_or(error)?; + tracing::warn!( + reason = reason.code(), + "Gateway turn runtime is not ready; management routes serve and turns are refused" + ); + Err(reason) + } + }; + let model = chat.as_ref().map_or_else( + |_| config.default_model.clone().unwrap_or_default(), + |(_, model, _)| model.clone(), + ); + // Test builds keep the fixture field filled; no turn reads it, since + // this state always holds its turn runtime. + #[cfg(test)] + let fixture_provider: Arc = match &chat { + Ok((provider, _, _)) => Arc::clone(provider), + Err(_) => Arc::new(tests::MockProvider::default()), + }; + let temperature = config.default_temperature; + let shared_config_for_reload = shared_config.unwrap_or_else(|| crate::config::new_shared(config.clone())); + if controlled.is_some() { + shared_config_for_reload.freeze_runtime_writes(); + } + let mem: Arc = Arc::from(memory::create_memory_with_storage( + &config.memory, + Some(&config.storage.provider.config), + &config.workspace_dir, + memory::EmbeddingRootCredential::from_config(&config), + )?); + let scrub_memory = Arc::clone(&mem); + let runtime: Arc = Arc::from(runtime::create_runtime(&config.runtime)?); + // FIX-P1-31: honour the configured `security.audit` block on the gate audit path. + // Built via the shared `build_security_policy` helper so this site cannot drift + // from (or forget) the audit-config wiring — byte-for-byte identical to the + // former local from_config + audit-config construction. + // + // This policy bootstraps static gateway gates and the initial tool registry. + // Gateway turn tools are rebuilt from one candidate ConfigGeneration and swapped + // atomically by GatewayTurnRuntimeOwner. Resource-mutation routes independently + // pin the manager's active generation at each authorization decision. + let security = crate::runtime::bootstrap::build_security_policy(&config); + // Workspace command hooks follow the live `security.workspace_hooks` + // opt-in (HOOKS-ENV). + let hooks = + Arc::new(HookManager::new(config.workspace_dir.clone()).with_config(Arc::clone(&shared_config_for_reload))); + // Kept for the shutdown drain of queued hook events. + let hooks_for_shutdown = Arc::clone(&hooks); + #[cfg(feature = "wasm-plugins")] + let wasm_plugin_runtime = if let Some(runtime) = wasm_early_runtime { + runtime + .attach_memory(Arc::clone(&mem)) + .await + .map_err(|error| anyhow::anyhow!("failed to attach WASM memory backend in gateway: {error}"))?; + Some(runtime) + } else { + crate::plugins::init_plugin_runtime(&config, Some(Arc::clone(&mem))).await + }; + + let (composio_key, composio_entity_id) = if config.composio.configured() { + ( + config.composio.api_key.as_deref(), + Some(config.composio.entity_id.as_str()), + ) + } else { + (None, None) + }; + + // Build the base tool list (mutable so we can append channel-aware tools below) + let extensions = hooks.control_tool_arcs(Arc::clone(&security)); + #[cfg(feature = "wasm-plugins")] + let extensions = { + let mut extensions = extensions; + if let Some(runtime) = &wasm_plugin_runtime { + extensions.extend(runtime.control_tool_arcs(Arc::clone(&security))); + } + extensions + }; + let tools_result = if let Some(profile) = &controlled { + tools::ToolsRegistryResult { + tools: profile.registry(&config, &security)?, + mcp_tool: None, + } + } else { + tools::all_tools_with_runtime_ext_and_extensions( + Arc::new(config.clone()), + Arc::clone(&shared_config_for_reload), + &security, + runtime, + Arc::clone(&mem), + composio_key, + composio_entity_id, + &config.browser, + &config.http_request, + &config.workspace_dir, + &config.agents_with_references(), + config.api_key.as_deref(), + &config, + extensions, + Some(Arc::clone(&hooks)), + ) + }; + let mut tools_list = tools_result.tools; + let mcp_tool = tools_result.mcp_tool; + // Generic /webhook auth can require a standalone token and/or HMAC signature. + let webhook_token_hash: Option> = config.webhook.token.as_ref().and_then(|raw_token| { + let trimmed_token = raw_token.trim(); + (!trimmed_token.is_empty()).then(|| Arc::::from(hash_webhook_secret(trimmed_token))) + }); + let webhook_signing_secret: Option> = config.channels_config.webhook.as_ref().and_then(|webhook| { + webhook.secret.as_ref().and_then(|raw_secret| { + let trimmed_secret = raw_secret.trim(); + (!trimmed_secret.is_empty()).then(|| Arc::::from(trimmed_secret.to_string())) + }) + }); + + // WhatsApp channel (if configured) + let whatsapp_channel: Option> = config + .channels_config + .whatsapp + .as_ref() + .filter(|wa| wa.is_cloud_config()) + .map(|wa| { + Arc::new(WhatsAppChannel::new( + wa.access_token.clone().unwrap_or_default(), + wa.phone_number_id.clone().unwrap_or_default(), + wa.verify_token.clone().unwrap_or_default(), + wa.allowed_numbers.clone(), + )) + }); + let signal_media_config = config.media.clone(); + let signal_channel: Option> = config.channels_config.signal.as_ref().map(|sg| { + Arc::new( + SignalChannel::new_with_mode( + sg.effective_http_url(), + sg.account.clone(), + sg.group_id.clone(), + sg.allowed_from.clone(), + sg.ignore_attachments, + sg.ignore_stories, + signal_media_config.clone(), + sg.is_native_mode(), + sg.data_dir.clone(), + sg.storm_protection.clone(), + ) + .with_artifact_owner(crate::media::MediaArtifactOwner::for_workspace(&config.workspace_dir)), + ) + }); + + // Linq channel (if configured). Built here (ahead of message_send and the spawn + // tool) so it can join the shared per-turn channel routing registry below. + let linq_channel: Option> = config.channels_config.linq.as_ref().map(|lq| { + Arc::new(LinqChannel::new( + lq.api_token.clone(), + lq.from_phone.clone(), + lq.allowed_senders.clone(), + )) + }); + + // Nextcloud Talk channel (if configured). Built here (ahead of message_send and + // the spawn tool) so it can join the shared per-turn channel routing registry. + let nextcloud_talk_channel: Option> = + config.channels_config.nextcloud_talk.as_ref().map(|nc| { + Arc::new(NextcloudTalkChannel::new( + nc.base_url.clone(), + nc.app_token.clone(), + nc.allowed_users.clone(), + )) + }); + + let (channels_registry, spawn_tools_handle) = register_gateway_turn_tools( + &mut tools_list, + &config, + &shared_config_for_reload, + &security, + &hooks, + &model, + &mem, + &provider_runtime_options, + signal_channel.as_ref(), + whatsapp_channel.as_ref(), + linq_channel.as_ref(), + nextcloud_talk_channel.as_ref(), + )?; + // The process cost outbox projector (P2-R5): started eagerly before the + // first turn and cancelled with the gateway's shutdown token. + let cost_projector = shared_config_for_reload.ensure_runtime_writable().is_ok().then(|| { + crate::runtime::cost_recovery::warn_legacy_files_once(&config.workspace_dir); + crate::runtime::cost_recovery::CostOutboxProjector::start( + Arc::clone(&mem), + config.workspace_dir.clone(), + config.cost.clone(), + &shutdown, + ) + }); + // Publish the routing registry process-wide for as long as this gateway + // runs, so `POST /api/channels/{name}/send` can address the channels the + // gateway itself constructed. The channels supervisor publishes its own + // (larger) registry alongside this one; the two are merged at lookup time. + let _outbound_publication = crate::channels::outbound_registry::publish(Arc::clone(&channels_registry)); + #[cfg(feature = "wasm-plugins")] + if let Some(runtime) = &wasm_plugin_runtime { + tracing::debug!(generation = runtime.generation_id(), "WASM plugin runtime ready"); + } + + let tools_registry = Arc::new(tools_list); + + // Inject the tools registry into sessions_spawn so sub-agents can use tools. + let _ = spawn_tools_handle.set(&tools_registry); + + // WhatsApp app secret for webhook signature verification (from config) + let whatsapp_app_secret: Option> = config + .channels_config + .whatsapp + .as_ref() + .and_then(|wa| { + wa.app_secret + .as_deref() + .map(str::trim) + .filter(|secret| !secret.is_empty()) + .map(ToOwned::to_owned) + }) + .map(Arc::from); + + // Linq signing secret for webhook signature verification (from config). + // (The `linq_channel` object itself is built earlier, ahead of the spawn tool.) + let linq_signing_secret: Option> = config + .channels_config + .linq + .as_ref() + .and_then(|lq| { + lq.signing_secret + .as_deref() + .map(str::trim) + .filter(|secret| !secret.is_empty()) + .map(ToOwned::to_owned) + }) + .map(Arc::from); + + // Nextcloud Talk webhook secret for signature verification (from config). + // (The `nextcloud_talk_channel` object is built earlier, ahead of the spawn tool.) + let nextcloud_talk_webhook_secret: Option> = config + .channels_config + .nextcloud_talk + .as_ref() + .and_then(|nc| { + nc.webhook_secret + .as_deref() + .map(str::trim) + .filter(|secret| !secret.is_empty()) + .map(ToOwned::to_owned) + }) + .map(Arc::from); + + // ── Pairing guard ────────────────────────────────────── + let pairing = Arc::new( + PairingGuard::new(config.gateway.require_pairing, &config.gateway.paired_tokens) + .with_install_owner(install_owner), + ); + let rate_limit_max_keys = normalize_max_keys(config.gateway.rate_limit_max_keys, RATE_LIMIT_MAX_KEYS_DEFAULT); + let rate_limiter = Arc::new(GatewayRateLimiter::new( + config.gateway.pair_rate_limit_per_minute, + config.gateway.webhook_rate_limit_per_minute, + config.gateway.api_rate_limit_per_minute, + rate_limit_max_keys, + )); + let idempotency_max_keys = normalize_max_keys(config.gateway.idempotency_max_keys, IDEMPOTENCY_MAX_KEYS_DEFAULT); + let idempotency_store = Arc::new(IdempotencyStore::new( + Duration::from_secs(config.gateway.idempotency_ttl_secs.max(1)), + idempotency_max_keys, + )); + + // ── Tunnel ──────────────────────────────────────────────── + let tunnel = crate::tunnel::create_tunnel(&config.tunnel)?; + let mut tunnel_url: Option = None; + + if let Some(ref tun) = tunnel { + println!("🔗 Starting {} tunnel...", tun.name()); + match tun.start(host, actual_port).await { + Ok(url) => { + println!("🌐 Tunnel active: {url}"); + tunnel_url = Some(url); + } + Err(e) => { + println!("⚠️ Tunnel failed to start: {e}"); + println!(" Falling back to local-only mode."); + } + } + } + + println!("🦀 OpenPRX Gateway listening on http://{display_addr}"); + if let Some(ref url) = tunnel_url { + println!(" 🌐 Public URL: {url}"); + } + println!(" POST /pair — pair a new client (X-Pairing-Code header)"); + println!(" POST /webhook — {{\"message\": \"your prompt\"}}"); + if whatsapp_channel.is_some() { + println!(" GET /whatsapp — Meta webhook verification"); + println!(" POST /whatsapp — WhatsApp message webhook"); + } + if linq_channel.is_some() { + println!(" POST /linq — Linq message webhook (iMessage/RCS/SMS)"); + } + if nextcloud_talk_channel.is_some() { + println!(" POST /nextcloud-talk — Nextcloud Talk bot webhook"); + } + println!(" GET /health — health check"); + println!(" GET /metrics — Prometheus metrics"); + if let Some(code) = pairing.pairing_code() { + println!(); + println!(" 🔐 PAIRING REQUIRED — use this one-time code:"); + println!(" ┌──────────────┐"); + println!(" │ {code} │"); + println!(" └──────────────┘"); + println!(" Send: POST /pair with header X-Pairing-Code: {code}"); + } else if pairing.require_pairing() { + println!(" 🔒 Pairing: ACTIVE (bearer token required)"); + } else { + println!(" ⚠️ Pairing: DISABLED (all requests accepted)"); + } + println!(" Press Ctrl+C to stop.\n"); + + // Build shared state + let observer: Arc = + Arc::from(crate::observability::create_observer(&config.observability)); + let (logs_broadcast_tx, _) = broadcast::channel(1024); + // The startup registry and MCP tool move into the turn runtime: nothing + // else keeps them, so the first configuration change releases them and + // their stdio MCP children (D-098 F-1). + let turn_runtime_owner = start_gateway_turn_runtime( + turn_state_of( + chat, + Arc::new( + turn_source::publication_slot::GatewayPublicationSlot::new(Arc::clone(&security), { + #[cfg(feature = "wasm-plugins")] + { + wasm_plugin_runtime + .as_ref() + .map_or(0, |runtime| runtime.generation_id()) + } + #[cfg(not(feature = "wasm-plugins"))] + { + 0 + } + }) + .with_controlled(controlled.clone()), + ), + shared_config_for_reload.pin(), + tools_registry, + mcp_tool, + ), + &shared_config_for_reload, + Arc::clone(&mem), + signal_channel.clone(), + whatsapp_channel.clone(), + linq_channel.clone(), + nextcloud_talk_channel.clone(), + Arc::clone(&hooks), + #[cfg(feature = "wasm-plugins")] + wasm_plugin_runtime.clone(), + )?; + shared_config_for_reload.register_audit_sink(Arc::new(ConfigGenerationMessageAuditSink { + memory: Arc::clone(&mem), + workspace_id: config.workspace_dir.to_string_lossy().to_string(), + runtime_handle: tokio::runtime::Handle::current(), + })); + + let state = AppState { + rf_streams: Default::default(), + rf_approvals: Default::default(), + config: Arc::clone(&shared_config_for_reload), + #[cfg(test)] + provider: fixture_provider, + model, + temperature, + mem, + auto_save: config.memory.auto_save && config.memory.semantic.auto_promote_user_messages, + // Test fixtures only; this state serves every turn from `turn_runtime`. + #[cfg(test)] + tools_registry: Arc::new(Vec::new()), + #[cfg(test)] + mcp_tool: None, + turn_runtime: Some(Arc::clone(&turn_runtime_owner)), + hooks, + webhook_token_hash, + webhook_signing_secret, + pairing, + trust_forwarded_headers: config.gateway.trust_forwarded_headers, + rate_limiter, + idempotency_store, + whatsapp: whatsapp_channel, + signal: signal_channel, + whatsapp_app_secret, + linq: linq_channel, + linq_signing_secret, + nextcloud_talk: nextcloud_talk_channel, + nextcloud_talk_webhook_secret, + observer, + start_time, + gateway_port: actual_port, + logs_broadcast_tx, + #[cfg(feature = "wasm-plugins")] + plugin_runtime: wasm_plugin_runtime, + }; + + // HookManager resolves hooks and event delivery from this same generation owner. + #[cfg(feature = "wasm-plugins")] + if let Some(ref runtime) = state.plugin_runtime { + state.hooks.set_plugin_runtime(Arc::clone(runtime)).await; + } + + if controlled.is_some() { + let producer = producer + .take() + .ok_or_else(|| anyhow::anyhow!("local control producer missing"))?; + h2_control::start_local_control(producer, shutdown.clone())?; + } + let limited_public_routes = Router::new() + .route("/pair", post(handle_pair)) + .route("/webhook", post(handle_webhook)) + .route("/whatsapp", get(handle_whatsapp_verify)) + .route("/whatsapp", post(handle_whatsapp_message)) + .route("/linq", post(handle_linq_webhook)) + .route("/nextcloud-talk", post(handle_nextcloud_talk_webhook)) + .layer(RequestBodyLimitLayer::new(MAX_BODY_SIZE)); + + api::sync_startup::startup(&state, &shutdown).await?; + let api_routes = api::router(state.clone()).layer(RequestBodyLimitLayer::new(MAX_API_BODY_SIZE)); + + // Build router with middleware + let app = Router::new() + .route("/health", get(handle_health)) + .route("/metrics", get(handle_metrics)) + .route( + "/mcp/v1/initialize", + get(compat::mcp_initialize).post(compat::mcp_initialize), + ) + .route( + "/mcp/v1/list_servers", + get(compat::mcp_list_servers).post(compat::mcp_list_servers), + ) + .route( + "/mcp/v1/tools/list", + get(compat::mcp_tools_list).post(compat::mcp_tools_list), + ) + .route("/mcp/v1/tools/call", post(compat::mcp_tools_call)) + .route("/a2a/v1/identity", get(compat::a2a_identity).post(compat::a2a_identity)) + .route("/a2a/v1/discover", get(compat::a2a_discover).post(compat::a2a_discover)) + .route("/.well-known/agent.json", get(compat::well_known_agent_json)) + .route("/a2a/v1/.well-known/jwks.json", get(compat::a2a_jwks)) + .merge(limited_public_routes) + .nest("/api", api_routes) + .merge(ui::router()) + .with_state(state) + .layer(axum::middleware::from_fn( + move |request: axum::extract::Request, next: axum::middleware::Next| { + let controlled = controlled.clone(); + async move { + if let Some(profile) = controlled { + if profile.ensure_live().is_err() + || !crate::runtime::h2_entry::ControlledH2Profile::permits_route( + request.method().as_str(), + request.uri().path(), + ) + { + return ( + StatusCode::FORBIDDEN, + "route is outside the fixed controlled Gateway profile", + ) + .into_response(); + } + } + next.run(request).await + } + }, + )); + + // The listener is bound and every route/state dependency is now constructed. + // This explicit acknowledgement, rather than supervisor task survival, is the + // gateway readiness boundary. + crate::health::mark_component_ok("gateway"); + + // A quiet listener is still a live listener. Refresh gateway health from an + // owner-controlled heartbeat rather than relying on `/health` requests to + // keep the required component fresh. + let health_shutdown = CancellationToken::new(); + let health_heartbeat = tokio::spawn(run_health_heartbeat( + "gateway", + GATEWAY_HEALTH_HEARTBEAT_INTERVAL, + health_shutdown.clone(), + )); + + // Run the server with graceful shutdown (D5/D9 step 3, DEV-02). On root token + // cancellation axum stops accepting and drains in-flight requests. The drain + // bound must only start counting *after* shutdown is requested — never while + // the server is idle — otherwise the gateway would self-exit after the timeout + // on a quiet listener. We therefore arm the bounded timer inside a select! arm + // gated on `shutdown.cancelled()`, so the timeout window opens only post-shutdown. + let drain_deadline = shutdown.clone(); + let serve_fut = axum::serve(listener, app.into_make_service_with_connect_info::()) + .with_graceful_shutdown(async move { shutdown.cancelled().await }) + .into_future(); + tokio::pin!(serve_fut); + let serve_result = tokio::select! { + res = &mut serve_fut => res, + _ = async { + drain_deadline.cancelled().await; + tokio::time::sleep(GATEWAY_GRACEFUL_TIMEOUT).await; + } => { + tracing::warn!( + timeout_secs = GATEWAY_GRACEFUL_TIMEOUT.as_secs(), + "gateway graceful shutdown timed out; forcing exit" + ); + Ok(()) + } + }; + + let decision_cleanup_result = turn_runtime_owner + .cleanup + .drain(tokio::time::Instant::now() + Duration::from_secs(15)) + .await; + hooks_for_shutdown.drain_for_shutdown().await; + if let Some(projector) = cost_projector { + projector.stop().await; + } + // AC-1b2b: a clean stop leaves no deleted rf content in the WAL. + match scrub_memory.scrub_deleted_wal().await { + Ok(true) => {} + Ok(false) => { + tracing::warn!("deleted rf content stays in brain.db-wal at stop; it is scrubbed at the next open") + } + Err(error) => tracing::warn!( + error = %crate::agent::diagnostics::error_class(&error), + "deleted rf content WAL scrub failed at stop" + ), + } + health_shutdown.cancel(); + let _ = health_heartbeat.await; + serve_result?; + decision_cleanup_result?; + + crate::health::mark_component_stopping("gateway"); + crate::health::mark_component_stopped("gateway"); + Ok(()) +} + +// ══════════════════════════════════════════════════════════════════════════════ +// AXUM HANDLERS +// ══════════════════════════════════════════════════════════════════════════════ + +/// GET /health — always public (no secrets leaked) +async fn handle_health(State(state): State) -> impl IntoResponse { + // A successfully dispatched health request is also an explicit freshness + // acknowledgement from the gateway owner. + crate::health::mark_component_ok("gateway"); + let runtime = crate::health::snapshot(); + health_response(state.pairing.is_paired(), runtime) +} + +fn health_response(paired: bool, runtime: crate::health::HealthSnapshot) -> (StatusCode, Json) { + let readiness = crate::health::readiness_from_snapshot(&runtime); + let status = if readiness.ready { + StatusCode::OK + } else { + StatusCode::SERVICE_UNAVAILABLE + }; + let body = serde_json::json!({ + "status": readiness.status, + "paired": paired, + "readiness": readiness, + "runtime": runtime, + }); + (status, Json(body)) +} + +/// Prometheus content type for text exposition format. +const PROMETHEUS_CONTENT_TYPE: &str = "text/plain; version=0.0.4; charset=utf-8"; + +/// GET /metrics — Prometheus text exposition format +async fn handle_metrics(State(state): State) -> impl IntoResponse { + // Merge the PrometheusObserver's main registry with the separate + // chat_metrics registry (S2.5 P1-A). The four chat counters live in a + // registry that is physically isolated from the observer, so they have to + // be merged explicitly or a scrape never sees them. + let chat_reg = crate::observability::chat_metrics::chat_registry(); + let body = state + .observer + .as_ref() + .as_any() + .downcast_ref::() + .map_or_else( + || { + // The chat metrics still have to be exposed when the observer is not Prometheus. + format!( + "# Prometheus backend not enabled. Set [observability] backend = \"prometheus\" in config.\n{}", + crate::observability::prometheus::encode_registries(&[chat_reg]) + ) + }, + |prom| prom.encode_with_extras(&[chat_reg]), + ); + + (StatusCode::OK, [(header::CONTENT_TYPE, PROMETHEUS_CONTENT_TYPE)], body) +} + +/// POST /pair — exchange one-time code for bearer token +#[axum::debug_handler] +async fn handle_pair( + State(state): State, + ConnectInfo(peer_addr): ConnectInfo, + headers: HeaderMap, +) -> impl IntoResponse { + let rate_key = client_key_from_request(Some(peer_addr), &headers, state.trust_forwarded_headers); + if !state.rate_limiter.allow_pair(&rate_key) { + tracing::warn!("/pair rate limit exceeded"); + let err = serde_json::json!({ + "error": "Too many pairing requests. Please retry later.", + "retry_after": RATE_LIMIT_WINDOW_SECS, + }); + return (StatusCode::TOO_MANY_REQUESTS, Json(err)); + } + + let code = headers + .get("X-Pairing-Code") + .and_then(|v| v.to_str().ok()) + .unwrap_or(""); + + if let Err(error) = authorize_gateway_resource_mutation(&state, "gateway:pair", ResourceRiskLevel::Low) { + return error; + } + + match state.pairing.try_pair(code, &rate_key).await { + Ok(Some(token)) => { + tracing::info!("🔐 New client paired successfully"); + if let Err(err) = persist_pairing_tokens(&state.config, &state.pairing).await { + tracing::error!(error = %crate::security::redaction::redact_provider_text(&format!("{err:#}")), "🔐 Pairing succeeded but token persistence failed"); + let body = serde_json::json!({ + "paired": true, + "persisted": false, + "token": token, + "message": "Paired for this process, but failed to persist token to config.toml. Check config path and write permissions.", + }); + return (StatusCode::OK, Json(body)); + } + + let body = serde_json::json!({ + "paired": true, + "persisted": true, + "token": token, + "message": "Save this token — use it as Authorization: Bearer " + }); + (StatusCode::OK, Json(body)) + } + Ok(None) => { + tracing::warn!("🔐 Pairing attempt with invalid code"); + let err = serde_json::json!({"error": "Invalid pairing code"}); + (StatusCode::FORBIDDEN, Json(err)) + } + Err(lockout_secs) => { + tracing::warn!("🔐 Pairing locked out — too many failed attempts ({lockout_secs}s remaining)"); + let err = serde_json::json!({ + "error": format!("Too many failed attempts. Try again in {lockout_secs}s."), + "retry_after": lockout_secs + }); + (StatusCode::TOO_MANY_REQUESTS, Json(err)) + } + } +} + +/// Add what pairing learned to the configured list, **without rewriting the +/// entries an operator authored**. +/// +/// Persistence used to assign `pairing.tokens()` over the whole list, which +/// treated the in-memory set as authoritative over the file. It is not: +/// `gateway.paired_tokens` is a restart-only field, so between startup and the +/// next restart the file can legitimately hold entries the running guard never +/// loaded, and it can hold them in a *spelling* the guard cannot reproduce. +/// Both were destroyed silently. +/// +/// The spelling matters because [`PairingGuard`] stores only hashes: a +/// plaintext entry is hashed on load, so `tokens()` returns a hash for it and +/// the assignment wrote that hash back in its place. The token stays valid as a +/// bearer either way — but chat's `/sessions --daemon` takes its credential out +/// of this list and deliberately skips hashes (a stored hash, re-hashed by the +/// gateway on receipt, authenticates as nothing), so the entry it was reading +/// would have become useless to it with no edit by anyone and nothing in the +/// file to show what changed. +/// +/// That particular sequence turns out not to be reachable through `/pair`: +/// a pairing code is minted only when the token set is *empty*, so a config +/// that already carries a plaintext entry can never complete a pairing. What is +/// reachable is the same destruction one step earlier — an operator adds an +/// entry by hand while the gateway is up and a still-live code is later +/// redeemed, and the entry is dropped from disk outright rather than merely +/// rehashed. +/// +/// So nothing is rewritten or removed here. Every non-empty configured entry is +/// kept, in order and as written, and a live hash is appended only when no +/// configured entry already names that token. Revocation is not a thing this +/// gateway has, so there is nothing this would wrongly resurrect. +/// +/// This never puts a *generated* token into the file in plaintext: `/pair` +/// hands that to the client once and persists only its hash, unchanged. The +/// only plaintext preserved is plaintext the operator wrote themselves. +/// +/// MUTATION GUARD: assign `pairing.tokens()` wholesale again and +/// `a_configured_token_survives_a_later_pairing` fails. +fn merge_paired_tokens(configured: &[String], live: &[String]) -> Vec { + let mut merged: Vec = Vec::with_capacity(configured.len().saturating_add(live.len())); + let mut covered: HashSet = HashSet::new(); + for entry in configured { + let trimmed = entry.trim(); + if trimmed.is_empty() { + continue; + } + // Compared by hash, kept by spelling: a plaintext entry and the hash + // pairing holds for it are the same credential, and the operator's + // spelling is the one that stays. + let hash = if crate::security::pairing::is_token_hash(trimmed) { + trimmed.to_string() + } else { + crate::security::pairing::hash_token(trimmed) + }; + if covered.insert(hash) { + merged.push(trimmed.to_string()); + } + } + for token in live { + if covered.insert(token.clone()) { + merged.push(token.clone()); + } + } + merged +} + +async fn persist_pairing_tokens(config: &crate::config::SharedConfig, pairing: &PairingGuard) -> Result<()> { + let paired_tokens = pairing.tokens(); + let mut updated_cfg = (*config.desired().config).clone(); + updated_cfg.gateway.paired_tokens = merge_paired_tokens(&updated_cfg.gateway.paired_tokens, &paired_tokens); + updated_cfg + .save() + .await + .context("Failed to persist paired tokens to config.toml")?; + let manager = Arc::clone(config); + crate::runtime::blocking::spawn_blocking(move || { + manager.reload_from_disk(crate::config::ConfigReloadTrigger::PairingPersistence) + }) + .await + .context("Pairing config reload worker failed")??; + Ok(()) +} + +/// Build the turn-root spawn context for one gateway/webhook turn. +/// +/// Two things travel down from here into every sub-agent this turn starts: +/// +/// * `run_id` — the turn's own id becomes the child's `parent_run_id`, so a +/// webhook-launched run is attached to the turn that asked for it instead of +/// floating as a root. +/// * `channel_excluded_tools` — the names the turn's own surface hides. The +/// gateway is not an IM channel and has no `channel_exclude` list: it publishes +/// `tool_tiering` as configured, not `for_channel_surface()`. So the boundary a +/// child inherits here is exactly `always_exclude`: the child's surface is the +/// gateway's own surface minus the names the operator hid from the gateway, and +/// `spawn` is not a way to get one of them back. `always_include` is untouched, +/// exactly as on the channel path. +fn gateway_turn_spawn_context( + run_id: String, + fabric_ctx: &GatewayFabricContext, + tiering: &crate::config::ToolTieringConfig, +) -> crate::tools::sessions_spawn::SpawnExecutionContext { + crate::tools::sessions_spawn::SpawnExecutionContext::seed_turn_context( + run_id, + format!( + "{}:{}:{}", + fabric_ctx.channel, fabric_ctx.session_key, fabric_ctx.sender + ), + ) + .with_channel_excluded_tools(tiering.always_exclude.clone()) +} + +/// Run `inner` as the webhook turn itself: seeded with this turn's spawn +/// boundary, so anything it spawns inherits the gateway's own surface. +/// +/// This is the production seam. `gateway_turn_spawn_context` only builds the +/// context; nothing enforced that the value actually reached the tool loop, so +/// emptying the list at the call site (or shadowing the binding) left every +/// test green while `sessions_spawn` handed a child the tools the operator hid +/// from the gateway. Binding construction and scoping together here gives that +/// wiring one place to be tested, and +/// `the_gateway_webhook_turn_seeds_its_spawn_boundary` in `tests/architecture_boundaries/` +/// pins that `run_gateway_chat_with_multimodal` still goes through it. +async fn within_gateway_turn_spawn_context( + run_id: String, + fabric_ctx: &GatewayFabricContext, + tiering: &crate::config::ToolTieringConfig, + inner: F, +) -> F::Output +where + F: std::future::Future, +{ + let turn_spawn_ctx = gateway_turn_spawn_context(run_id, fabric_ctx, tiering); + crate::tools::sessions_spawn::SPAWN_EXECUTION_CONTEXT + .scope(turn_spawn_ctx, inner) + .await +} + +struct GatewayTurnResult { + response: String, + replay_unavailable: Option, +} + +async fn run_gateway_chat_with_multimodal( + state: &AppState, + provider_label: &str, + message: &str, + fabric_ctx: &GatewayFabricContext, + autosave_key: Option<&str>, + stage: &mut TurnFailureClass, +) -> anyhow::Result { + // `stage` names the step that runs next, so a returned error is reported + // by the step that failed and never by its text. + *stage = TurnFailureClass::TurnNotReady; + // The webhook routes admitted this turn; a typed refusal here only + // covers a job that outlived its admission check. + let turn_runtime = state.admit_turn_runtime()?; + *stage = TurnFailureClass::ProviderBinding; + turn_runtime + .provider_binding + .as_ref() + .ok_or_else(|| anyhow::anyhow!("gateway provider binding is missing"))? + .verify(&turn_runtime)?; + let provider_label = turn_runtime + .provider_binding + .as_ref() + .map_or(provider_label, |binding| binding.provider_name()); + let config_generation = Arc::clone(&turn_runtime.config_generation); + let config_snapshot = Arc::clone(&config_generation.effective); + let workspace_id = config_generation.effective.workspace_dir.to_string_lossy().to_string(); + let event_recording = config_generation.effective.memory.event_recording_config(); + let fabric = MemoryFabric::new(state.mem.clone(), workspace_id.clone()).with_event_recording(event_recording); + let run_id = Uuid::new_v4().to_string(); + // D4 C4: migrate the gateway fabric durable session_key to the recipient-aware + // canonical (`gateway:{channel}:{sender}:{recipient}`) while carrying the + // pre-cutover legacy key (`gateway:webhook:{target}` / `gateway:{ch}:{sender}`) + // for read-merge, so existing legacy history stays visible under the new key. + let webhook_owner_id = fabric_ctx.webhook_owner_id(&workspace_id); + // D-025: a `/webhook` turn's durable key is its credential-qualified + // `gateway:webhook:{credential}:{reply_target}` itself, with no legacy key: + // history under the old `gateway:webhook:{reply_target}` key cannot be + // attributed to a credential, so it is neither migrated nor read-merged, and + // continuity restarts once. Platform channel messages keep the canonical + // key and their legacy read-merge. + let (canonical_session_key, legacy_session_key) = if fabric_ctx.credential.is_some() { + (fabric_ctx.session_key.clone(), None) + } else { + let legacy_session_key = fabric_ctx.session_key.clone(); + let canonical_session_key = RuntimeEnvelope::gateway( + workspace_id.clone(), + legacy_session_key.clone(), + fabric_ctx.channel.clone(), + fabric_ctx.sender.clone(), + fabric_ctx.recipient.clone(), + MemoryVisibility::Session, + ) + .canonical_session_key(); + (canonical_session_key, Some(legacy_session_key)) + }; + let runtime_envelope = RuntimeEnvelope::gateway( + workspace_id, + canonical_session_key, + fabric_ctx.channel.clone(), + fabric_ctx.sender.clone(), + fabric_ctx.recipient.clone(), + // FIX-P1-04: webhook-driven gateway turns are session-scoped by default. + // Persisting them as workspace-visible would leak per-session conversation + // content to the whole workspace; Session keeps it bound to this session. + MemoryVisibility::Session, + ) + .with_run_id(run_id) + .with_config_generation(&config_generation); + let runtime_envelope = match legacy_session_key { + Some(legacy_session_key) => runtime_envelope.with_legacy_session_key(legacy_session_key), + None => runtime_envelope, + }; + let runtime_envelope = match webhook_owner_id.as_deref() { + Some(owner_id) => runtime_envelope.with_owner_id(owner_id), + None => runtime_envelope, + }; + *stage = TurnFailureClass::ReplayLookup; + if fabric.records_recovery_terminal() { + if let Some(key) = fabric_ctx.idempotency_key.as_deref() { + if let Some(unavailable) = crate::agent::terminal::oversized_reply::for_input( + fabric.memory(), + fabric.workspace_id(), + &runtime_envelope.message_scope(), + key, + message, + ) + .await? + { + return Err(unavailable.into()); + } + } + } + *stage = TurnFailureClass::ResourceDenied; + authorize_gateway_config_resource_mutation( + &config_snapshot, + "gateway:webhook:message_event:user", + ResourceRiskLevel::Low, + ) + .map_err(|(_, body)| { + let error = body + .0 + .get("error") + .and_then(|value| value.as_str()) + .unwrap_or("gateway resource mutation denied") + .to_string(); + anyhow::anyhow!(error) + })?; + let cancellation = jobs::current_cancellation().map_or_else(CancellationToken::new, |token| token.child_token()); + let _turn_cancel_guard = cancellation.clone().drop_guard(); + *stage = TurnFailureClass::InputRecord; + let pending_input = turn_source::GatewayPendingInput { + generation: Arc::clone(&config_generation), + fabric: fabric.clone(), + envelope: runtime_envelope, + // Arguments evaluate in order: a refused registration returns before + // any acknowledgement exists, and the owner holds both from here on. + owner: turn_source::PreInputOwner::new( + turn_runtime.publication_slot.cleanup.register(cancellation.clone())?, + jobs::register_terminal_cleanup(), + ), + }; + let (source_receipt, gateway_user_event, mut admission_guard) = pending_input + .record(message.to_owned(), fabric_ctx.idempotency_key.clone()) + .await?; + let runtime_envelope = source_receipt.envelope().clone(); + let base_scope = runtime_envelope.message_scope(); + *stage = TurnFailureClass::SourceBinding; + let gateway_proof = source_receipt.bind(&turn_runtime, fabric_ctx)?; + if let Some(key) = autosave_key { + let write_scope = runtime_envelope.memory_write_context(if fabric_ctx.channel == "webhook" { + "webhook" + } else { + "private" + }); + let _ = state + .mem + .store_with_context_and_metadata( + key, + message, + MemoryCategory::Conversation, + None, + Some(&write_scope), + crate::memory::MemoryStoreMetadata { + workspace_id: Some(runtime_envelope.workspace_id.clone()), + owner_id: Some(runtime_envelope.resolved_owner_id()), + source_event_id: runtime_envelope.source_message_event_id.clone(), + source: Some("semantic_promotion".into()), + channel: Some(fabric_ctx.channel.clone()), + ..Default::default() + }, + ) + .await; + } + // A spawned webhook job cannot inherit the caller's cleanup task-local. + // Prediction and later work must retain the same concrete cleanup owner. + *stage = TurnFailureClass::DecisionAdmission; + let child_cleanup = match crate::runtime::turn_cleanup::CleanupScope::new( + Some(&turn_runtime.publication_slot.cleanup), + cancellation.clone(), + ) { + Ok(scope) => scope.with_acknowledgement(jobs::register_terminal_cleanup()), + Err(error) => { + if let Err(record_error) = admission_guard + .finish_failure( + cancellation.is_cancelled(), + &format!("decision cleanup admission failed: {error}"), + ) + .await + { + return Err(error.context(format!( + "Gateway admission failure persistence is unconfirmed: {record_error}" + ))); + } + return Err(error); + } + }; + let admission = child_cleanup + .scope_admission(Box::pin(async { + let service = turn_runtime.publication_slot.publish(&turn_runtime, state).await?; + let context = service + .open_issued_turn_context( + &gateway_proof, + crate::runtime::turn_context::AgentTurnKind::SingleShot, + &cancellation, + ) + .await?; + Ok::<_, anyhow::Error>((service, context)) + })) + .await; + let (service, context) = match admission { + Ok(admitted) => admitted, + Err(error) => { + // Admission is no longer polled. Settle its owned accounting work + // before acknowledging the persisted input's failure. + let admission_error = format!("{error:#}"); + let error = match child_cleanup.run(Box::pin(async { Err::<(), _>(error) })).await { + Err(error) if error.is::() => { + let context = format!( + "decision admission failed: {admission_error}; Gateway admission cleanup is unconfirmed: {error:#}" + ); + error.context(context) + } + Err(error) => error, + Ok(()) => anyhow::anyhow!(admission_error), + }; + if let Err(record_error) = admission_guard + .finish_failure( + cancellation.is_cancelled(), + &format!("decision admission failed: {error}"), + ) + .await + { + return Err(error.context(format!( + "Gateway admission failure persistence is unconfirmed: {record_error}" + ))); + } + return Err(error); + } + }; + // Bind before the handoff: a refusal here still has the admission guard + // to record the failed input and answer the job monitor. + *stage = TurnFailureClass::TerminalBinding; + let terminal_binding = service.terminal_binding(&context)?; + let (cleanup_ticket, admission_acknowledgement) = admission_guard.into_terminal_parts()?; + let terminal_guard = turn_source::publication_slot::GatewayTerminalGuard::new( + cleanup_ticket, + Arc::clone(service), + Arc::clone(&context), + fabric.clone(), + Arc::clone(&config_snapshot), + runtime_envelope.clone(), + admission_acknowledgement, + )?; + *stage = TurnFailureClass::TurnPreparation; + let turn_result: anyhow::Result = child_cleanup + .run(async { + let mem_context = crate::agent::context_recall::scoped_recall( + state.mem.as_ref(), + &crate::agent::context_recall::RecallScope::from_envelope( + &runtime_envelope, + &config_snapshot.memory, + if fabric_ctx.channel == "webhook" { + "webhook" + } else { + "private" + }, + ) + .with_current_input_key(autosave_key.map(str::to_owned)), + message, + crate::agent::context_recall::RECALL_CONTEXT_BUDGET, + ) + .await; + let enriched_message = if mem_context.preamble.is_empty() { + message.to_string() + } else { + format!("{}{}", mem_context.preamble, message) + }; + + let user_messages = vec![crate::agent::turn_contracts::inbound_user_message(&enriched_message)]; + let image_marker_count = crate::multimodal::count_image_markers(&user_messages); + let adapter_capabilities = turn_runtime.provider.capabilities_for( + &turn_runtime.model, + crate::providers::traits::ProviderRequestMode::NonStreaming, + ); + let mode_capabilities = providers::selection::catalog_for(&config_snapshot) + .effective_provider_capabilities(provider_label, &turn_runtime.model, adapter_capabilities); + if image_marker_count > 0 && !mode_capabilities.vision { + return Err(ProviderCapabilityError { + provider: providers::redact_endpoint_userinfo(provider_label).into_owned(), + capability: "vision".to_string(), + message: format!( + "received {image_marker_count} image marker(s), but this provider does not support vision input" + ), + } + .into()); + } + + // Build system prompt with native_tools flag so the prompt instructs the + // LLM to use tools rather than emit XML tags. + let multimodal_config = config_snapshot.multimodal.clone(); + let native_tools = mode_capabilities.native_tool_calling; + let selected_skills = service.agent_prompt_skills(&gateway_proof, &context)?; + // The runtime prompt wrapper owns the whole prompt policy — the + // `skill_read` gate on the skill list and the `[agent] compact_context` + // bootstrap cap — so the webhook builds its prompt exactly as CLI, chat and + // Console sessions do. It used to call the canonical builder directly with + // a hardcoded `bootstrap_max_chars = None` (E3, webhook half). + let system_prompt = crate::agent::runtime_prompt::build_runtime_system_prompt( + &config_snapshot, + &turn_runtime.model, + &selected_skills, + native_tools, + ); + + let mut history = Vec::with_capacity(2 + user_messages.len()); + history.push(ChatMessage::system(system_prompt)); + history.extend(user_messages); + + let noop_observer = NoopObserver; + + // P1-a: route the webhook agent loop through the unified `SecurityPolicy::decide` + // gate instead of leaving `scope_ctx = None` (which short-circuits to `Allow` + // and bypasses both the scope ACL and the autonomy level entirely). + // + // Webhook turns are Bearer-token authenticated (`handle_webhook` rejects + // unauthenticated requests), so the request is a trusted principal and we can + // construct a `ScopeContext` from the gateway identity. This makes every tool + // call honour the configured autonomy level: under `supervised`, side-effecting + // tools resolve to `Ask`, and with no `ApprovalManager` wired on this path the + // tool loop fail-closes (deny) — only genuinely read-only tools run. Under + // `full` autonomy the behaviour is unchanged (everything allowed). + let gateway_policy = + crate::security::SecurityPolicy::from_config(&config_snapshot.autonomy, &config_snapshot.workspace_dir); + let gateway_scope_ctx = crate::agent::turn_contracts::ScopeContext { + policy: &gateway_policy, + sender: fabric_ctx.sender.as_str(), + channel: fabric_ctx.channel.as_str(), + // Gateway/webhook turns are 1:1 (no group semantics); use a stable + // chat_type so scope rules can target the gateway surface. + chat_type: "gateway", + chat_id: fabric_ctx.session_key.as_str(), + session_key: Some(runtime_envelope.session_key.as_str()), + // R-MCPB F-2: the credential-bound owner, so run views and owner-scoped + // rows follow the authenticated caller rather than its `reply_target`. + owner_id: webhook_owner_id.as_deref(), + owner_isolated: runtime_envelope.owner_isolated, + topic_id: None, + task_id: None, + source_message_event_id: None, + config_generation_id: runtime_envelope.config_generation_id, + config_source_revision: runtime_envelope.config_source_revision.as_deref(), + }; + + // OQ-23: the webhook turn runs the same bounded-request contract as every + // other execution surface — pre-turn flush/paging, the preflight before + // each provider call (with the published tool schemas reserved) and the + // reserved mid-turn trim. The window is the *effective* one, which applies + // the operator/discovery/catalog limits of the model this turn actually serves, as the + // CLI and TUI do. + let mut effective_compaction = service.effective_compaction(provider_label, &turn_runtime.model); + effective_compaction.config = context.main_compaction().clone(); + crate::providers::context_window::trace_effective_compaction_resolution(&effective_compaction); + + *stage = TurnFailureClass::TurnLoop; + let provider_started_at = chrono::Utc::now(); + let route_decision = crate::llm::route_decision::RouteDecision::single_candidate_for_context( + provider_label, + turn_runtime.model.clone(), + runtime_envelope.resolved_owner_id(), + runtime_envelope.session_key.clone(), + runtime_envelope.source_message_event_id.clone(), + None, + "gateway_webhook", + u32::try_from(message.chars().count() / 4).unwrap_or(u32::MAX), + !turn_runtime.tools_registry.is_empty(), + false, + ); + // R3: name this turn's real origin before any tool runs. The gateway owns no + // channel of its own — `message_send` falls back to whichever handle the + // daemon registered — so without this every webhook turn's outbound scope + // reads as that handle's channel and a rule written for the surface the + // message actually came from can never match. Reply routing is untouched; + // only rule matching changes. + // + // G2: the same turn also seeds the spawn execution context. A sub-agent the + // webhook turn starts inherits (a) this turn's run_id as its parent, and (b) + // the gateway surface's own hidden tool names. The gateway is not an IM + // channel, so it has no `channel_exclude` list of its own: it publishes + // `config_snapshot.tool_tiering` rather than `for_channel_surface()`. The + // boundary a child must therefore inherit is exactly `always_exclude` — the + // gateway's own tool set minus what the operator hid from it — so a spawn can + // never be a way to get back a tool the gateway itself may not call. + let loop_result = within_gateway_turn_spawn_context( + runtime_envelope + .run_id + .clone() + .unwrap_or_else(|| Uuid::new_v4().to_string()), + fabric_ctx, + &config_snapshot.tool_tiering, + crate::tools::message_send::with_outbound_origin_channel(fabric_ctx.channel.as_str(), async { + run_turn( + &mut history, + crate::agent::turn_request::TurnRequest { + advice: service.advisory().analyze_turn(context.runtime(), &cancellation).await, + // no approval manager + channel_name: "webhook", + // no streaming delta sender + scope: Some(&gateway_scope_ctx), + mode: crate::agent::turn_contracts::ChatMode::default(), + silent: true, + expose_stay_silent: false, + multimodal: &multimodal_config, + schedule: crate::agent::turn_request::TurnSchedule { + read_only_tool_concurrency_window: config_snapshot + .agent + .read_only_tool_concurrency_window, + priority_scheduling_enabled: config_snapshot.agent.priority_scheduling_enabled, + low_priority_tool_names: config_snapshot.agent.low_priority_tools.clone(), + }, + compaction: Some(&effective_compaction.config), + // no tool call notifications + decision: crate::agent::turn_request::TurnDecision { + service, + context: &context, + runtime: context.runtime(), + proof: &gateway_proof, + }, + }, + crate::agent::turn_request::TurnServices { + provider: turn_runtime.provider.as_ref(), + provider_name: provider_label, + model: &turn_runtime.model, + temperature: turn_runtime.temperature, + tools_registry: Arc::clone(&turn_runtime.tools_registry), + observer: &noop_observer, + hooks: state.hooks.as_ref(), + // silent + approval: None, + approval_resolver: None, + runtime_adapter: Some({ + crate::agent::turn_contracts::ToolLoopRuntimeAdapter { + live_frames: None, + guarded_delivery: false, + provider_trace: None, + events: None, + stream_provider: false, + tool_execution_service: None, + tool_execution_context: crate::tools::ToolExecutionContext::new( + runtime_envelope.clone(), + if fabric_ctx.channel == "webhook" { + "webhook" + } else { + "private" + }, + ) + .with_dispatch_origin(crate::tools::DispatchOrigin::ModelTurn) + .with_approval_ledger(service.execution_approval_ledger()) + .with_chat_id(&runtime_envelope.session_key), + allowed_tool_names: None, + } + }), + memory: crate::agent::turn_request::ToolLoopMemory::new( + &state.mem, + &config_snapshot.workspace_dir, + Some(DocumentIngestRuntime::from_envelope( + state.mem.clone(), + &runtime_envelope, + )), + ) + .with_event_fabric( + MemoryFabric::new(state.mem.clone(), runtime_envelope.workspace_id.clone()) + .with_event_recording(config_snapshot.memory.event_recording_config()), + ) + .with_request_event_scope({ + let mut scope = base_scope.clone(); + scope.causation_event_id = + gateway_user_event.as_ref().map(|event| event.event_id.clone()); + scope + }), + }, + crate::agent::turn_request::TurnDelivery { + cancellation: Some(cancellation.clone()), + // no cancellation token + on_delta: None, + // P1-a: gateway turns now route through decide() + on_tool_call: None, + }, + ) + .await + .map(|(outcome, trace)| (outcome.into_text(), trace)) + }), + ) + .await; + let (response, trace) = match loop_result { + Ok(result) => result, + Err(error) => { + let cancelled = + cancellation.is_cancelled() || crate::agent::turn_contracts::is_tool_loop_cancelled(&error); + *stage = TurnFailureClass::Internal; + let terminal_id = runtime_envelope + .run_id + .clone() + .ok_or_else(|| anyhow::anyhow!("gateway source run id is missing"))?; + if let Err(finalize_error) = turn_source::publication_slot::commit_terminal( + Some(&terminal_guard), + &fabric, + crate::agent::terminal::TurnTerminalDraft { + binding: Some(terminal_binding.clone()), + terminal_id, + scope: runtime_envelope.message_scope(), + status: if cancelled { + crate::agent::terminal::TurnTerminalStatus::Cancelled + } else { + crate::agent::terminal::TurnTerminalStatus::Failed + }, + history: None, + history_scope: None, + provider_outcome: None, + telemetry: crate::agent::terminal::TurnTerminalTelemetry { + summary: error.to_string(), + started_at: provider_started_at, + finished_at: chrono::Utc::now(), + }, + delivery_intent: crate::agent::terminal::TurnDeliveryIntent::ReturnToCaller, + }, + &config_snapshot, + ) + .await + { + *stage = terminal_guard.failure_reason().into(); + return Err(finalize_error); + } + *stage = if cancelled { + TurnFailureClass::Cancelled + } else { + TurnFailureClass::TurnLoop + }; + return Err(error); + } + }; + *stage = TurnFailureClass::Internal; + anyhow::ensure!( + trace.execution_trace.as_ref() == Some(&context.terminal_execution_trace()), + "gateway returned execution trace differs from its owning decision" + ); + + *stage = TurnFailureClass::ResourceDenied; + authorize_gateway_config_resource_mutation( + &config_snapshot, + "gateway:webhook:message_event:assistant", + ResourceRiskLevel::Low, + ) + .map_err(|(_, body)| { + let error = body + .0 + .get("error") + .and_then(|value| value.as_str()) + .unwrap_or("gateway resource mutation denied") + .to_string(); + anyhow::anyhow!(error) + })?; + let provider_outcome = + crate::agent::terminal::provider_outcome_from_trace(&route_decision, provider_started_at, trace); + let terminal_id = runtime_envelope + .run_id + .clone() + .unwrap_or_else(|| provider_outcome.decision_id.clone()); + let committed = turn_source::publication_slot::commit_terminal( + Some(&terminal_guard), + &fabric, + crate::agent::terminal::TurnTerminalDraft { + binding: Some(terminal_binding.clone()), + terminal_id, + scope: runtime_envelope.message_scope(), + status: crate::agent::terminal::TurnTerminalStatus::Completed, + history: Some(crate::agent::terminal::TurnHistoryProjection { + assistant_content: response.clone(), + history_commit_len: history.len(), + }), + history_scope: Some( + base_scope + .clone() + .with_sender(format!("{provider_label}/{}", turn_runtime.model)) + .with_recipient(fabric_ctx.sender.clone()), + ), + provider_outcome: Some(provider_outcome), + telemetry: crate::agent::terminal::TurnTerminalTelemetry { + summary: "gateway webhook completed".to_string(), + started_at: provider_started_at, + finished_at: chrono::Utc::now(), + }, + delivery_intent: crate::agent::terminal::TurnDeliveryIntent::ReturnToCaller, + }, + &config_snapshot, + ) + .await; + let receipt = match committed { + Ok(receipt) => receipt, + Err(error) => { + *stage = terminal_guard.failure_reason().into(); + return Err(error); + } + }; + *stage = TurnFailureClass::ReplayLookup; + let replay_unavailable = crate::agent::terminal::oversized_reply::from_receipt(&receipt)?; + // The turn's own work is done; what fails from here is its + // owned cleanup settling. + *stage = TurnFailureClass::TurnCleanup; + Ok(GatewayTurnResult { + response, + replay_unavailable, + }) + }) + .await; + if let Err(error) = &turn_result { + if let Err(finish_error) = terminal_guard.finish_failure(error, cancellation.is_cancelled()).await { + *stage = terminal_guard.failure_reason().into(); + return Err(finish_error); + } + } + turn_result +} + +/// Webhook request body +#[derive(serde::Deserialize)] +pub struct WebhookBody { + pub message: String, + #[serde(default)] + pub reply_target: Option, +} diff --git a/src/gateway/implementation/section_3.rs b/src/gateway/implementation/section_3.rs new file mode 100644 index 000000000..7a171aec1 --- /dev/null +++ b/src/gateway/implementation/section_3.rs @@ -0,0 +1,972 @@ +/// POST /webhook — main webhook endpoint +async fn handle_webhook( + State(state): State, + ConnectInfo(peer_addr): ConnectInfo, + uri: axum::http::Uri, + headers: HeaderMap, + body: Bytes, +) -> impl IntoResponse { + let async_mode = jobs::wants_async(uri.query(), &headers); + let bearer_token = headers + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|auth| auth.strip_prefix("Bearer ")) + .map(str::trim) + .unwrap_or(""); + let webhook_token_header = headers + .get("X-Webhook-Token") + .and_then(|v| v.to_str().ok()) + .map(str::trim) + .filter(|value| !value.is_empty()); + let webhook_signature_header = headers + .get("X-Webhook-Signature") + .and_then(|v| v.to_str().ok()) + .map(str::trim) + .filter(|value| !value.is_empty()); + + let rate_key = client_key_from_request(Some(peer_addr), &headers, state.trust_forwarded_headers); + if !state.rate_limiter.allow_webhook(&rate_key) { + tracing::warn!("/webhook rate limit exceeded"); + let err = serde_json::json!({ + "error": "Too many webhook requests. Please retry later.", + "retry_after": RATE_LIMIT_WINDOW_SECS, + }); + return (StatusCode::TOO_MANY_REQUESTS, Json(err)); + } + + // ── Bearer token auth (pairing) ── + if state.pairing.require_pairing() { + if !state.pairing.is_authenticated(bearer_token) { + tracing::warn!("Webhook: rejected — not paired / invalid bearer token"); + let err = serde_json::json!({ + "error": "Unauthorized — pair first via POST /pair, then send Authorization: Bearer " + }); + return (StatusCode::UNAUTHORIZED, Json(err)); + } + } + + // ── Standalone webhook token auth (optional, additional layer) ── + if let Some(ref token_hash) = state.webhook_token_hash { + let header_hash = webhook_token_header.map(hash_webhook_secret); + match header_hash { + Some(val) if constant_time_eq(&val, token_hash.as_ref()) => {} + _ => { + tracing::warn!("Webhook: rejected request — invalid or missing X-Webhook-Token"); + let err = serde_json::json!({"error": "Unauthorized — invalid or missing X-Webhook-Token header"}); + return (StatusCode::UNAUTHORIZED, Json(err)); + } + } + } + + // ── Webhook HMAC auth (optional, additional layer) ── + if let Some(ref signing_secret) = state.webhook_signing_secret { + match webhook_signature_header { + Some(signature) if verify_webhook_hmac_signature(signing_secret, &body, signature) => {} + _ => { + tracing::warn!("Webhook: rejected request — invalid or missing X-Webhook-Signature"); + let err = serde_json::json!({"error": "Unauthorized — invalid or missing X-Webhook-Signature header"}); + return (StatusCode::UNAUTHORIZED, Json(err)); + } + } + } + + // Additional credential-based limiter reduces distributed IP rotation bypass. + let credential_rate_key = if !bearer_token.is_empty() { + format!("bearer:{}", hash_webhook_secret(bearer_token)) + } else if let Some(token) = webhook_token_header { + format!("token:{}", hash_webhook_secret(token)) + } else if let Some(signature) = webhook_signature_header { + format!("signature:{}", hash_webhook_secret(signature)) + } else { + "public".to_string() + }; + // The authenticated credential this request presented, in two forms: the + // idempotency scope (process-local; hashed again into every stored + // idempotency key) and the owner credential of the webhook turn + // (`GatewayFabricContext::webhook_owner_id`, R-MCPB F-2), whose + // domain-separated digest is what reaches owner ids, session keys and logs + // (R-MCPBfg N-4). Both follow the same precedence. + let owner_credential = if state.pairing.require_pairing() { + webhook_owner_credential("bearer", bearer_token) + } else if let (Some(_), Some(token)) = (&state.webhook_token_hash, webhook_token_header) { + webhook_owner_credential("token", token) + } else if let Some(signing_secret) = state.webhook_signing_secret.as_deref() { + webhook_owner_credential("signing-secret", signing_secret) + } else { + "public".to_string() + }; + let idempotency_scope = if state.pairing.require_pairing() { + format!("bearer:{}", hash_webhook_secret(bearer_token)) + } else if let (Some(_), Some(token)) = (&state.webhook_token_hash, webhook_token_header) { + format!("token:{}", hash_webhook_secret(token)) + } else if let Some(signing_secret) = state.webhook_signing_secret.as_deref() { + format!("signing-secret:{}", hash_webhook_secret(signing_secret)) + } else { + "public".to_string() + }; + if !state.rate_limiter.allow_webhook_credential(&credential_rate_key) { + tracing::warn!("/webhook credential rate limit exceeded"); + let err = serde_json::json!({ + "error": "Too many webhook requests. Please retry later.", + "retry_after": RATE_LIMIT_WINDOW_SECS, + }); + return (StatusCode::TOO_MANY_REQUESTS, Json(err)); + } + // Admission, before any idempotency claim is taken. + if let Err(refusal) = state.admit_turn_runtime() { + return turn_not_ready_plain(refusal); + } + + // ── Parse body ── + let webhook_body: WebhookBody = match serde_json::from_slice(&body) { + Ok(b) => b, + Err(e) => { + tracing::warn!("Webhook JSON parse error: {e}"); + let err = serde_json::json!({ + "error": "Invalid JSON body. Expected: {\"message\": \"...\"}" + }); + return (StatusCode::BAD_REQUEST, Json(err)); + } + }; + + // ── Idempotency (optional) ── + let request_idempotency_key = match idempotency_key_from_header(&headers, "X-Idempotency-Key") { + Ok(key) => key, + Err(message) => { + let err = serde_json::json!({ "error": message }); + return (StatusCode::BAD_REQUEST, Json(err)); + } + }; + let mut idempotency_digest = None; + let mut idempotency_claim = None; + if let Some(raw_key) = request_idempotency_key.as_deref() { + if let Err(error) = + authorize_gateway_resource_mutation(&state, "gateway:webhook:idempotency", ResourceRiskLevel::Low) + { + return error; + } + let digest = webhook_idempotency_digest(&idempotency_scope, raw_key); + let fingerprint = webhook_request_fingerprint(&body); + match state.idempotency_store.claim(digest.clone(), fingerprint) { + IdempotencyClaimOutcome::Acquired(claim) => { + idempotency_digest = Some(digest); + idempotency_claim = Some(claim); + } + IdempotencyClaimOutcome::Processing => { + let body = serde_json::json!({ + "status": "processing", + "idempotent": true, + "message": "A request with this idempotency key is still processing" + }); + return (StatusCode::CONFLICT, Json(body)); + } + IdempotencyClaimOutcome::Replay(replay) => { + return (StatusCode::OK, Json(replay.json_body())); + } + IdempotencyClaimOutcome::ReplayUnavailable { + response_id, + result_hash, + } => { + let body = replay_unavailable_body(response_id, &result_hash); + return (StatusCode::CONFLICT, Json(body)); + } + IdempotencyClaimOutcome::RequestConflict => { + let body = serde_json::json!({ + "status": "request_conflict", + "idempotent": true, + "message": "This idempotency key was used with a different request body" + }); + return (StatusCode::CONFLICT, Json(body)); + } + IdempotencyClaimOutcome::RetryUnavailable => { + let body = serde_json::json!({ + "status": "retry_unavailable", + "idempotent": true, + "message": "This failed request is not eligible for retry" + }); + return (StatusCode::CONFLICT, Json(body)); + } + IdempotencyClaimOutcome::AtCapacity => { + let body = serde_json::json!({ + "error": "Idempotency capacity is temporarily exhausted", + "retryable": true + }); + return (StatusCode::SERVICE_UNAVAILABLE, Json(body)); + } + } + } + + // From here on the request may run for as long as the agent turn behind it + // needs, so it becomes a detached job rather than staying inside this + // handler's future. Two things follow from that. The turn survives a client + // that hangs up — a webhook sender's read timeout no longer destroys work + // that had already started writing memory and calling tools. And the + // idempotency claim travels *with* the work instead of with the connection, + // so a dropped connection can no longer release the claim underneath a run + // that is still going. + let job = jobs::submit( + jobs::KIND_WEBHOOK, + format!("gateway:webhook:{}", fabric_channel_label(&webhook_body)), + run_webhook_job( + state, + webhook_body, + owner_credential, + idempotency_digest, + idempotency_claim, + ), + ); + + if async_mode { + return (StatusCode::ACCEPTED, Json(job.accepted_body())); + } + job.wait().await.into_parts() +} + +/// Label for the registry row of a webhook job, so `prx tasks list` shows which +/// delivery target the run belongs to rather than a bare route name. +fn fabric_channel_label(body: &WebhookBody) -> &str { + body.reply_target.as_deref().unwrap_or("anonymous") +} + +/// The unbounded half of `POST /webhook`, run as a job. +/// +/// Owns the idempotency claim for the whole run: the claim is only resolved by +/// code that knows how the run ended, never by the request future going away. +fn run_webhook_job( + state: AppState, + webhook_body: WebhookBody, + credential: String, + idempotency_digest: Option, + idempotency_claim: Option, +) -> std::pin::Pin> + Send>> { + // Keep owned webhook work out of the generic job submitter's future. + // Construction does not poll it; the same idempotency claim moves with it. + Box::pin(run_webhook_job_work( + state, + webhook_body, + credential, + idempotency_digest, + idempotency_claim, + )) +} + +async fn run_webhook_job_work( + state: AppState, + webhook_body: WebhookBody, + credential: String, + idempotency_digest: Option, + idempotency_claim: Option, +) -> Result { + let mut idempotency_claim = idempotency_claim; + let message = webhook_body.message.as_str(); + + let autosave_key = + if state.auto_save && should_autosave_gateway_message(webhook_body.reply_target.as_deref(), message) { + if let Err((status, body)) = + authorize_gateway_resource_mutation(&state, "gateway:webhook:autosave", ResourceRiskLevel::Low) + { + return Ok(jobs::JobOutput::new(status, body.0)); + } + // First observable side effect of the attempt: past this point a + // redelivery of the same key would duplicate it. + if let Some(claim) = idempotency_claim.as_mut() { + claim.mark_dispatched(); + } + let key = webhook_memory_key(idempotency_digest.as_deref()); + Some(key) + } else { + None + }; + + let provider_label = state + .config + .load_full() + .default_provider + .clone() + .unwrap_or_else(|| "unknown".to_string()); + let model_label = state.model.clone(); + let started_at = Instant::now(); + + state + .observer + .record_event(&crate::observability::ObserverEvent::AgentStart { + provider: provider_label.clone(), + model: model_label.clone(), + }); + state + .observer + .record_event(&crate::observability::ObserverEvent::LlmRequest { + provider: provider_label.clone(), + model: model_label.clone(), + messages_count: 1, + }); + + let fabric_ctx = GatewayFabricContext::generic_webhook( + webhook_body.reply_target.as_deref(), + &credential, + idempotency_digest + .as_deref() + .map(|digest| format!("gateway:webhook:{digest}")), + ); + // The turn records the inbound message and may call tools, so from here the + // attempt is not replayable by re-execution — only by the stored result. + if let Some(claim) = idempotency_claim.as_mut() { + claim.mark_dispatched(); + } + let mut stage = TurnFailureClass::Internal; + match run_gateway_chat_with_multimodal( + &state, + &provider_label, + message, + &fabric_ctx, + autosave_key.as_deref(), + &mut stage, + ) + .await + { + Ok(GatewayTurnResult { + response, + replay_unavailable, + }) => { + let response_id = match replay_unavailable.as_ref() { + Some(reference) => { + Uuid::parse_str(&reference.terminal_id).map_err(|_| "invalid durable response id".to_owned())? + } + None => Uuid::new_v4(), + }; + if let Some(claim) = idempotency_claim.take() { + let completed = if let Some(reference) = replay_unavailable { + claim.succeed_unavailable(response_id, reference.result_hash) + } else { + let result_hash = webhook_result_hash(&response, &model_label); + let replay = IdempotencyReplay { + response_id, + response: Arc::from(response.as_str()), + model: Arc::from(model_label.as_str()), + }; + claim.succeed(replay, result_hash) + }; + if !completed { + tracing::error!("Webhook idempotency ownership was lost before success commit"); + let err = serde_json::json!({ + "error": "Request completed but its idempotency result could not be committed" + }); + return Ok(jobs::JobOutput::new(StatusCode::SERVICE_UNAVAILABLE, err)); + } + } + let duration = started_at.elapsed(); + state + .observer + .record_event(&crate::observability::ObserverEvent::LlmResponse { + provider: provider_label.clone(), + model: model_label.clone(), + duration, + success: true, + error_message: None, + }); + state + .observer + .record_metric(&crate::observability::traits::ObserverMetric::RequestLatency(duration)); + state + .observer + .record_event(&crate::observability::ObserverEvent::AgentEnd { + provider: provider_label, + model: model_label, + duration, + tokens_used: None, + cost_usd: None, + }); + + let body = serde_json::json!({ + "response": response, + "model": state.model, + "response_id": response_id.to_string(), + }); + Ok(jobs::JobOutput::new(StatusCode::OK, body)) + } + Err(e) => { + if let Some(unavailable) = e.downcast_ref::() { + let response_id = + Uuid::parse_str(&unavailable.terminal_id).map_err(|_| "invalid durable response id".to_owned())?; + if let Some(claim) = idempotency_claim.take() { + if !claim.succeed_unavailable(response_id, unavailable.result_hash.clone()) { + return Ok(jobs::JobOutput::new( + StatusCode::SERVICE_UNAVAILABLE, + serde_json::json!({"error":"Idempotency ownership was lost"}), + )); + } + } + return Ok(jobs::JobOutput::new( + StatusCode::CONFLICT, + replay_unavailable_body(response_id, &unavailable.result_hash), + )); + } + if let Some(claim) = idempotency_claim.take() { + let _ = claim.fail(); + } + if e.is::() { + return Ok(jobs::JobOutput::new( + StatusCode::CONFLICT, + serde_json::json!({"error":"input_already_accepted","status":"unconfirmed","message":"Execution was not repeated; the previously accepted input has an unconfirmed outcome."}), + )); + } + let duration = started_at.elapsed(); + let sanitized = providers::sanitize_api_error(&e.to_string()); + + state + .observer + .record_event(&crate::observability::ObserverEvent::LlmResponse { + provider: provider_label.clone(), + model: model_label.clone(), + duration, + success: false, + error_message: Some(sanitized.clone()), + }); + state + .observer + .record_metric(&crate::observability::traits::ObserverMetric::RequestLatency(duration)); + state + .observer + .record_event(&crate::observability::ObserverEvent::Error { + component: "gateway".to_string(), + message: sanitized, + }); + state + .observer + .record_event(&crate::observability::ObserverEvent::AgentEnd { + provider: provider_label, + model: model_label, + duration, + tokens_used: None, + cost_usd: None, + }); + + if let Some(tools) = providers::tool_schema_refused_tools(&e) { + // A configuration problem, not a transient one: the whole + // refusal (every tool, the configuration to add) is logged + // unclipped, and the authenticated caller gets a stable code + // with the refused tools. + tracing::error!( + error = %crate::security::redaction::redact_secrets(&format!("{e:#}")), + "Webhook turn refused before transport: the provider cannot accept some offered tool schemas" + ); + let err = serde_json::json!({ + "error": "tool_schema_refused", + "tools": tools, + "message": "The configured provider cannot accept some of the tool schemas this request \ + offered, so nothing was sent. The gateway log names the configuration to change.", + }); + return Ok(jobs::JobOutput::new(StatusCode::INTERNAL_SERVER_ERROR, err)); + } + // "LLM request failed" stands for a failed provider request only; + // every other failure answers the closed class of its step, never + // the error text. + let reason = TurnFailureClass::classify(stage, &e); + tracing::error!( + reason = %reason, + error = %crate::agent::diagnostics::error_class(&e), + "Webhook turn failed" + ); + let err = if reason == TurnFailureClass::Provider { + serde_json::json!({"error": "LLM request failed"}) + } else { + serde_json::json!({"error": "turn_failed", "reason": reason.code()}) + }; + Ok(jobs::JobOutput::new(StatusCode::INTERNAL_SERVER_ERROR, err)) + } + } +} + +/// Registry label for one accepted channel-webhook delivery. +/// +/// Named the way every other registry row names a correspondent: the channel in +/// the clear, the chat only as [`crate::security::op_id::ref_for_channel_recipient`]'s +/// fingerprint. `reply_target` on this route is a platform address — a Telegram +/// chat id, a WhatsApp JID — and this label is published verbatim by +/// `GET /api/runtime/tasks`, so writing it out would leak through the operator +/// plane the very address the send path takes care to fingerprint. Sharing that +/// one function is also what keeps the digest here equal to the digest an +/// outbound send to the same chat produces, so the two rows stay correlatable. +/// +/// MUTATION GUARD: interpolate `reply_target` directly and +/// `a_channel_webhook_job_label_fingerprints_the_chat` fails. +fn channel_webhook_job_label(channel_key: &str, first: Option<&crate::channels::traits::ChannelMessage>) -> String { + first.map_or_else( + || format!("gateway:{channel_key}"), + |msg| { + format!( + "gateway:{channel_key}:{}", + crate::security::op_id::ref_for_channel_recipient(channel_key, &msg.reply_target) + ) + }, + ) +} + +/// Shared tail of the three platform-pushed channel webhooks. +/// +/// These routes differ from `POST /webhook` in one decisive way: the sender is a +/// platform with a response deadline, not a client that chose to wait. Linq +/// documents "Response timeout: 10 seconds" and retries "up to 10 times over ~25 +/// minutes"; Meta retries a WhatsApp delivery "with decreasing frequency until +/// the request succeeds, for up to 7 days". An agent turn has no upper bound and +/// routinely exceeds any of those, so awaiting the turn inside the handler — as +/// these three did — guaranteed the platform would give up, mark the delivery +/// failed, and redeliver, running the whole turn again for every retry. +/// +/// The ack therefore reports that the work was *accepted*, not that it finished: +/// the turns run as a detached job, visible in `prx tasks list` and killable with +/// `prx tasks kill`, and the reply reaches the user through the channel's own +/// outbound API exactly as before. The delivery is claimed before submission, so +/// a retry that races the accepted run is answered as a duplicate instead of +/// starting a second copy of it. +/// The `503` a non-`/api` turn route answers while the turn runtime is not +/// ready, in those routes' own `{"error"}` shape. +fn turn_not_ready_plain(refusal: TurnNotReady) -> (StatusCode, Json) { + ( + StatusCode::SERVICE_UNAVAILABLE, + Json(serde_json::json!({ "error": refusal.to_string() })), + ) +} + +fn accept_channel_webhook_delivery( + state: &AppState, + channel: Arc, + channel_key: &'static str, + body: &Bytes, + messages: Vec, + memory_key: fn(&crate::channels::traits::ChannelMessage) -> String, +) -> (StatusCode, Json) { + // Admission, before the delivery is claimed: a refused delivery is + // redelivered by the platform once the runtime is ready. + if let Err(refusal) = state.admit_turn_runtime() { + return turn_not_ready_plain(refusal); + } + let dedup_ttl = Duration::from_secs(state.config.load_full().gateway.channel_webhook_dedup_ttl_secs.max(1)); + let claim = match webhook_dedup::claim(webhook_dedup::delivery_key(channel_key, body), dedup_ttl) { + webhook_dedup::DeliveryOutcome::Fresh(claim) => claim, + webhook_dedup::DeliveryOutcome::Duplicate => { + tracing::info!("{channel_key} webhook: redelivery of an already accepted payload — not run again"); + return ( + StatusCode::OK, + Json(serde_json::json!({ "status": "duplicate", "idempotent": true })), + ); + } + }; + + let label = channel_webhook_job_label(channel_key, messages.first()); + let job = jobs::submit( + jobs::KIND_CHANNEL_WEBHOOK, + label, + run_channel_webhook_job(state.clone(), channel, channel_key, messages, memory_key, claim), + ); + + // Every platform on this route treats any 2xx as delivered; 200 is the one + // status all three accept without special handling. + (StatusCode::OK, Json(job.accepted_body())) +} + +/// The unbounded half of a platform channel webhook, run as a job. +/// +/// Owns the delivery claim for the whole run, so the claim is resolved by code +/// that knows whether the turn reached a side effect — never by the request +/// future going away. +fn run_channel_webhook_job( + state: AppState, + channel: Arc, + channel_key: &'static str, + messages: Vec, + memory_key: fn(&crate::channels::traits::ChannelMessage) -> String, + claim: webhook_dedup::DeliveryClaim, +) -> std::pin::Pin> + Send>> { + // Keep owned channel work out of the generic job submitter's future. + // Construction does not poll it; the same delivery claim moves with it. + Box::pin(run_channel_webhook_job_work( + state, + channel, + channel_key, + messages, + memory_key, + claim, + )) +} + +async fn run_channel_webhook_job_work( + state: AppState, + channel: Arc, + channel_key: &'static str, + messages: Vec, + memory_key: fn(&crate::channels::traits::ChannelMessage) -> String, + mut claim: webhook_dedup::DeliveryClaim, +) -> Result { + let provider_label = state + .config + .load_full() + .default_provider + .clone() + .unwrap_or_else(|| "unknown".to_string()); + + for msg in &messages { + tracing::info!( + "{channel_key} message from {}: {}", + msg.sender, + truncate_with_ellipsis(&msg.content, 50) + ); + + // Auto-save to memory + let autosave_key = if state.auto_save && should_autosave_gateway_message(Some(&msg.reply_target), &msg.content) + { + if let Err((status, body)) = authorize_gateway_resource_mutation( + &state, + &gateway_channel_webhook_operation(channel_key, "autosave"), + ResourceRiskLevel::Low, + ) { + return Ok(jobs::JobOutput::new(status, body.0)); + } + // First observable side effect: past this point a redelivery would + // duplicate it, so the claim must outlive the run. + claim.mark_dispatched(); + let key = memory_key(msg); + Some(key) + } else { + None + }; + + let fabric_ctx = GatewayFabricContext::channel_message(msg); + // The turn records the inbound message and may call tools, so from here + // the delivery is not replayable by re-execution. + claim.mark_dispatched(); + let mut stage = TurnFailureClass::Internal; + match run_gateway_chat_with_multimodal( + &state, + &provider_label, + &msg.content, + &fabric_ctx, + autosave_key.as_deref(), + &mut stage, + ) + .await + { + Ok(GatewayTurnResult { response, .. }) => { + if let Err((status, body)) = authorize_gateway_resource_mutation( + &state, + &gateway_channel_webhook_operation(channel_key, "send"), + ResourceRiskLevel::Low, + ) { + return Ok(jobs::JobOutput::new(status, body.0)); + } + if let Err(e) = channel.send(&SendMessage::new(response, &msg.reply_target)).await { + tracing::error!("Failed to send {channel_key} reply: {e}"); + } + } + Err(e) => { + let reason = TurnFailureClass::classify(stage, &e); + tracing::error!(reason = %reason, error = %crate::security::redaction::redact_provider_text(&format!("{e:#}")), "Turn failed for {channel_key} message"); + if let Err((status, body)) = authorize_gateway_resource_mutation( + &state, + &gateway_channel_webhook_operation(channel_key, "send"), + ResourceRiskLevel::Low, + ) { + return Ok(jobs::JobOutput::new(status, body.0)); + } + let _ = channel + .send(&SendMessage::new( + if e.is::() {"This input was already accepted. Execution was not repeated; its outcome remains unconfirmed."} else {"Sorry, I couldn't process your message right now."}, + &msg.reply_target, + )) + .await; + } + } + } + + Ok(jobs::JobOutput::new( + StatusCode::OK, + serde_json::json!({ "status": "ok", "messages": messages.len() }), + )) +} + +/// `WhatsApp` verification query params +#[derive(serde::Deserialize)] +pub struct WhatsAppVerifyQuery { + #[serde(rename = "hub.mode")] + pub mode: Option, + #[serde(rename = "hub.verify_token")] + pub verify_token: Option, + #[serde(rename = "hub.challenge")] + pub challenge: Option, +} + +/// GET /whatsapp — Meta webhook verification +async fn handle_whatsapp_verify( + State(state): State, + Query(params): Query, +) -> impl IntoResponse { + let Some(ref wa) = state.whatsapp else { + return (StatusCode::NOT_FOUND, "WhatsApp not configured".to_string()); + }; + + // Verify the token matches (constant-time comparison to prevent timing attacks) + let token_matches = params + .verify_token + .as_deref() + .is_some_and(|t| constant_time_eq(t, wa.verify_token())); + if params.mode.as_deref() == Some("subscribe") && token_matches { + if let Some(ch) = params.challenge { + tracing::info!("WhatsApp webhook verified successfully"); + return (StatusCode::OK, ch); + } + return (StatusCode::BAD_REQUEST, "Missing hub.challenge".to_string()); + } + + tracing::warn!("WhatsApp webhook verification failed — token mismatch"); + (StatusCode::FORBIDDEN, "Forbidden".to_string()) +} + +/// Verify `WhatsApp` webhook signature (`X-Hub-Signature-256`). +/// +/// Returns true if the signature is valid, false otherwise. +/// See: +pub fn verify_whatsapp_signature(app_secret: &str, body: &[u8], signature_header: &str) -> bool { + use hmac::{Hmac, Mac}; + use sha2::Sha256; + + // Signature format: "sha256=" + let Some(hex_sig) = signature_header.strip_prefix("sha256=") else { + return false; + }; + + // Decode hex signature + let Ok(expected) = hex::decode(hex_sig) else { + return false; + }; + + // Compute HMAC-SHA256 + let Ok(mut mac) = Hmac::::new_from_slice(app_secret.as_bytes()) else { + return false; + }; + mac.update(body); + + // Constant-time comparison + mac.verify_slice(&expected).is_ok() +} + +/// POST /whatsapp — incoming message webhook +async fn handle_whatsapp_message(State(state): State, headers: HeaderMap, body: Bytes) -> impl IntoResponse { + let Some(ref wa) = state.whatsapp else { + return ( + StatusCode::NOT_FOUND, + Json(serde_json::json!({"error": "WhatsApp not configured"})), + ); + }; + + // ── Security: Verify X-Hub-Signature-256 — reject if signing secret not configured ── + let app_secret = match &state.whatsapp_app_secret { + Some(secret) => secret, + None => { + tracing::error!("WhatsApp webhook received but signing secret not configured — rejecting"); + return ( + StatusCode::SERVICE_UNAVAILABLE, + Json(serde_json::json!({"error": "Webhook signing secret not configured"})), + ); + } + }; + { + let signature = headers + .get("X-Hub-Signature-256") + .and_then(|v| v.to_str().ok()) + .unwrap_or(""); + + if !verify_whatsapp_signature(app_secret, &body, signature) { + tracing::warn!( + "WhatsApp webhook signature verification failed (signature: {})", + if signature.is_empty() { "missing" } else { "invalid" } + ); + return ( + StatusCode::UNAUTHORIZED, + Json(serde_json::json!({"error": "Invalid signature"})), + ); + } + } + + // Parse JSON body + let Ok(payload) = serde_json::from_slice::(&body) else { + return ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({"error": "Invalid JSON payload"})), + ); + }; + + // Parse messages from the webhook payload + let messages = wa.parse_webhook_payload(&payload); + + if messages.is_empty() { + // Acknowledge the webhook even if no messages (could be status updates) + return (StatusCode::OK, Json(serde_json::json!({"status": "ok"}))); + } + + // Webhook-delivered channels never pass through the channel dispatch loop, + // so their inbound activity is recorded here instead (see + // `channels::activity`). Reporting only — nothing acts on it. + crate::channels::activity::record_inbound(wa.name()); + + let channel: Arc = Arc::clone(wa) as Arc; + accept_channel_webhook_delivery(&state, channel, "whatsapp", &body, messages, whatsapp_memory_key) +} + +/// POST /linq — incoming message webhook (iMessage/RCS/SMS via Linq) +async fn handle_linq_webhook(State(state): State, headers: HeaderMap, body: Bytes) -> impl IntoResponse { + let Some(ref linq) = state.linq else { + return ( + StatusCode::NOT_FOUND, + Json(serde_json::json!({"error": "Linq not configured"})), + ); + }; + + let body_str = String::from_utf8_lossy(&body); + + // ── Security: Verify X-Webhook-Signature — reject if signing secret not configured ── + let signing_secret = match &state.linq_signing_secret { + Some(secret) => secret, + None => { + tracing::error!("Linq webhook received but signing secret not configured — rejecting"); + return ( + StatusCode::SERVICE_UNAVAILABLE, + Json(serde_json::json!({"error": "Webhook signing secret not configured"})), + ); + } + }; + { + let timestamp = headers + .get("X-Webhook-Timestamp") + .and_then(|v| v.to_str().ok()) + .unwrap_or(""); + + let signature = headers + .get("X-Webhook-Signature") + .and_then(|v| v.to_str().ok()) + .unwrap_or(""); + + if !crate::channels::linq::verify_linq_signature(signing_secret, &body_str, timestamp, signature) { + tracing::warn!( + "Linq webhook signature verification failed (signature: {})", + if signature.is_empty() { "missing" } else { "invalid" } + ); + return ( + StatusCode::UNAUTHORIZED, + Json(serde_json::json!({"error": "Invalid signature"})), + ); + } + } + + // Parse JSON body + let Ok(payload) = serde_json::from_slice::(&body) else { + return ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({"error": "Invalid JSON payload"})), + ); + }; + + // Parse messages from the webhook payload + let messages = linq.parse_webhook_payload(&payload); + + if messages.is_empty() { + // Acknowledge the webhook even if no messages (could be status/delivery events) + return (StatusCode::OK, Json(serde_json::json!({"status": "ok"}))); + } + + // Webhook-delivered channels never pass through the channel dispatch loop, + // so their inbound activity is recorded here instead (see + // `channels::activity`). Reporting only — nothing acts on it. + crate::channels::activity::record_inbound(linq.name()); + + let channel: Arc = Arc::clone(linq) as Arc; + accept_channel_webhook_delivery(&state, channel, "linq", &body, messages, linq_memory_key) +} + +/// POST /nextcloud-talk — incoming message webhook (Nextcloud Talk bot API) +async fn handle_nextcloud_talk_webhook( + State(state): State, + headers: HeaderMap, + body: Bytes, +) -> impl IntoResponse { + let Some(ref nextcloud_talk) = state.nextcloud_talk else { + return ( + StatusCode::NOT_FOUND, + Json(serde_json::json!({"error": "Nextcloud Talk not configured"})), + ); + }; + + let body_str = String::from_utf8_lossy(&body); + + // ── Security: Verify Nextcloud Talk HMAC signature — reject if secret not configured ── + let webhook_secret = match &state.nextcloud_talk_webhook_secret { + Some(secret) => secret, + None => { + tracing::error!("Nextcloud Talk webhook received but signing secret not configured — rejecting"); + return ( + StatusCode::SERVICE_UNAVAILABLE, + Json(serde_json::json!({"error": "Webhook signing secret not configured"})), + ); + } + }; + { + let random = headers + .get("X-Nextcloud-Talk-Random") + .and_then(|v| v.to_str().ok()) + .unwrap_or(""); + + let signature = headers + .get("X-Nextcloud-Talk-Signature") + .and_then(|v| v.to_str().ok()) + .unwrap_or(""); + + if !crate::channels::nextcloud_talk::verify_nextcloud_talk_signature( + webhook_secret, + random, + &body_str, + signature, + ) { + tracing::warn!( + "Nextcloud Talk webhook signature verification failed (signature: {})", + if signature.is_empty() { "missing" } else { "invalid" } + ); + return ( + StatusCode::UNAUTHORIZED, + Json(serde_json::json!({"error": "Invalid signature"})), + ); + } + } + + // Parse JSON body + let Ok(payload) = serde_json::from_slice::(&body) else { + return ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({"error": "Invalid JSON payload"})), + ); + }; + + // Parse messages from webhook payload + let messages = nextcloud_talk.parse_webhook_payload(&payload); + if messages.is_empty() { + // Acknowledge webhook even if payload does not contain actionable user messages. + return (StatusCode::OK, Json(serde_json::json!({"status": "ok"}))); + } + + // Webhook-delivered channels never pass through the channel dispatch loop, + // so their inbound activity is recorded here instead (see + // `channels::activity`). Reporting only — nothing acts on it. + crate::channels::activity::record_inbound(nextcloud_talk.name()); + + let channel: Arc = Arc::clone(nextcloud_talk) as Arc; + accept_channel_webhook_delivery( + &state, + channel, + "nextcloud_talk", + &body, + messages, + nextcloud_talk_memory_key, + ) +} + + +#[cfg(test)] +pub(crate) use tests::{drive_disabled_engine_webhook_entry, drive_search_webhook_entry}; diff --git a/src/gateway/mod.rs b/src/gateway/mod.rs index c91deea14..ac88f63a4 100644 --- a/src/gateway/mod.rs +++ b/src/gateway/mod.rs @@ -25,4288 +25,21 @@ mod agent_lifecycle; mod api; -#[cfg(test)] -pub(crate) use api::{drive_disabled_engine_console_entry, drive_search_console_entry}; mod compat; mod h2_control; -pub use h2_control::run_gateway_controlled; mod jobs; mod live_frames; +#[cfg(test)] +mod platform_test_transport; mod run_approvals; -pub(crate) mod turn_source; - -/// The reserved issuer component of every built-in (non-bearer) MCP origin. -/// -/// Re-exported so `Config::validate` can refuse a `mcp_server.jwt_issuer` that -/// would collide with one of them inside the `:`-composed caller identity. -pub use compat::FIXED_EXTERNAL_ISSUERS; - +#[cfg(test)] +mod tests; mod turn_failure; mod turn_readiness; +pub(crate) mod turn_source; mod ui; mod webhook_dedup; -use turn_failure::TurnFailureClass; -use turn_readiness::{GatewayTurnState, TurnNotReady, TurnNotReadyReason, TurnRuntimeStandby}; - -use crate::agent::document_ingest::DocumentIngestRuntime; -use crate::agent::turn_engine::run_turn; -use crate::channels::{Channel, LinqChannel, NextcloudTalkChannel, SendMessage, SignalChannel, WhatsAppChannel}; -use crate::config::Config; -use crate::hooks::HookManager; -use crate::memory::{self, Memory, MemoryCategory, MemoryFabric, MemoryVisibility}; -use crate::observability::NoopObserver; -use crate::providers::{self, ChatMessage, Provider, ProviderCapabilityError}; -use crate::runtime; -use crate::runtime::envelope::RuntimeEnvelope; -use crate::security::SideEffectGate; -use crate::security::pairing::{PairingGuard, constant_time_eq, is_public_bind}; -use crate::security::policy::ResourceRiskLevel; -use crate::tools::{self, McpTool, Tool}; -use crate::util::truncate_with_ellipsis; -use anyhow::{Context, Result}; -use arc_swap::ArcSwap; -use axum::{ - Router, - body::Bytes, - extract::{ConnectInfo, Query, State}, - http::{HeaderMap, StatusCode, header}, - response::{IntoResponse, Json}, - routing::{get, post}, -}; -use parking_lot::Mutex; -use std::collections::{HashMap, HashSet}; -use std::net::{IpAddr, SocketAddr}; -use std::sync::Arc; -use std::sync::atomic::{AtomicU32, Ordering}; -use std::time::{Duration, Instant}; -use tokio::sync::broadcast; -use tokio_util::sync::CancellationToken; -use tower_http::limit::RequestBodyLimitLayer; -use uuid::Uuid; - -/// The gateway's own announce channel for `sessions_spawn`. -/// -/// `sessions_spawn` needs one `Arc` as the fallback destination for -/// a run's completion announcement (and for a kill receipt). Until now the -/// gateway only had one when Signal happened to be configured, so on a host with -/// no Signal account the tool was never registered at all and a webhook turn -/// could not spawn anything. -/// -/// The gateway is a request/response surface: it owns no conversation to push an -/// unsolicited message into, and inventing one would mean a new outbound -/// transport. So this channel deliberately accepts the announcement and drops the -/// outbound leg, recording it in the log instead. Nothing is lost: every run is -/// already recorded in the shared memory fabric by the tool itself, so the result -/// is collected the way a gateway caller collects it anyway — `sessions_spawn`'s -/// own `join`, `sessions_list` / `sessions_history`, or `GET /api/runtime/tasks`. -/// -/// `listen` refuses: this is an outbound sink, never an inbound listener (the -/// 2026-08-26 stage-c constraint — no new listeners, no new transports). -#[derive(Debug, Clone, Copy)] -struct GatewayAnnounceChannel; - -#[async_trait::async_trait] -impl Channel for GatewayAnnounceChannel { - fn name(&self) -> &str { - "gateway" - } - - async fn send(&self, message: &SendMessage) -> Result<()> { - tracing::info!( - recipient = %message.recipient, - body_len = message.content.len(), - "gateway sessions_spawn announcement has no outbound channel; \ - the run result stays retrievable via join / sessions_list" - ); - Ok(()) - } - - async fn listen(&self, _tx: tokio::sync::mpsc::Sender) -> Result<()> { - anyhow::bail!("gateway announce channel does not accept inbound messages") - } -} - -/// Pick the channel `sessions_spawn` announces on for a gateway process. -/// -/// Signal keeps priority whenever it is configured, so a deployment that has one -/// behaves exactly as before. Without it the gateway falls back to its own -/// [`GatewayAnnounceChannel`] rather than skipping the tool: registration of -/// `sessions_spawn` must not depend on an unrelated IM channel being present. -fn gateway_spawn_announce_channel(signal: Option>) -> Arc { - signal.unwrap_or_else(|| Arc::new(GatewayAnnounceChannel)) -} - -/// Maximum request body size (64KB) — prevents memory exhaustion -pub const MAX_BODY_SIZE: usize = 65_536; -/// Larger request body limit for `/api` routes to support media uploads -/// (`10 * 20MB` files plus multipart overhead). -pub const MAX_API_BODY_SIZE: usize = (10 * 20 * 1024 * 1024) + (1024 * 1024); -/// Sliding window used by gateway rate limiting. -pub const RATE_LIMIT_WINDOW_SECS: u64 = 60; -/// Fallback max distinct client keys tracked in gateway rate limiter. -pub const RATE_LIMIT_MAX_KEYS_DEFAULT: usize = 10_000; -/// Fallback max distinct idempotency keys retained in gateway memory. -pub const IDEMPOTENCY_MAX_KEYS_DEFAULT: usize = 10_000; -/// Maximum accepted idempotency-key header length. -const IDEMPOTENCY_MAX_KEY_BYTES: usize = 256; -/// Maximum replay payload retained for one successful request. -const IDEMPOTENCY_MAX_REPLAY_BYTES: usize = 1024 * 1024; -/// Process-wide payload budget reserved by in-flight and successful requests. -const IDEMPOTENCY_REPLAY_BUDGET_BYTES: usize = 32 * 1024 * 1024; -/// Upper bound on how long the gateway waits for in-flight requests to drain -/// after a shutdown signal before forcing exit (D5/D9 step 3). Gateway-local on -/// purpose: `main.rs`'s private `RUNTIME_SHUTDOWN_TIMEOUT` is unreachable from -/// the lib crate. -const GATEWAY_GRACEFUL_TIMEOUT: Duration = Duration::from_secs(30); -/// Refresh required gateway liveness independently of inbound traffic. This is -/// deliberately shorter than the daemon's 60-second core-health TTL. -const GATEWAY_HEALTH_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(20); - -async fn run_health_heartbeat(component: &'static str, interval: Duration, shutdown: CancellationToken) { - let mut ticker = tokio::time::interval(interval); - ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); - loop { - tokio::select! { - _ = ticker.tick() => crate::health::touch_component(component), - () = shutdown.cancelled() => break, - } - } -} - -fn webhook_memory_key(idempotency_digest: Option<&str>) -> String { - idempotency_digest.map_or_else( - || format!("webhook_msg_{}", Uuid::new_v4()), - |digest| format!("webhook_msg_{digest}"), - ) -} - -fn whatsapp_memory_key(msg: &crate::channels::traits::ChannelMessage) -> String { - format!("whatsapp_{}_{}", msg.sender, msg.id) -} - -fn linq_memory_key(msg: &crate::channels::traits::ChannelMessage) -> String { - format!("linq_{}_{}", msg.sender, msg.id) -} - -fn nextcloud_talk_memory_key(msg: &crate::channels::traits::ChannelMessage) -> String { - format!("nextcloud_talk_{}_{}", msg.sender, msg.id) -} - -fn is_group_reply_target(reply_target: &str) -> bool { - reply_target.contains("group:") || reply_target.contains("@g.us") -} - -fn should_autosave_gateway_message(reply_target: Option<&str>, content: &str) -> bool { - if !memory::should_autosave_content(content) { - return false; - } - !reply_target.is_some_and(is_group_reply_target) -} - -#[derive(Debug, Clone)] -struct GatewayFabricContext { - channel: String, - session_key: String, - sender: String, - recipient: String, - idempotency_key: Option, - /// The authenticated webhook credential the request presented - /// (`bearer:{sha256}` for a paired token, `token:{sha256}` for the - /// standalone webhook token, `signing-secret:{sha256}` for HMAC, `public` - /// when the gateway requires none). `None` for platform channel messages, - /// whose sender the platform authenticates. - credential: Option, -} - -impl GatewayFabricContext { - /// `reply_target` is chosen by the client, so it never decides the owner - /// or the conversation on its own: the turn owner is the credential with - /// `reply_target` as a sub-namespace under it - /// ([`Self::webhook_owner_id`], R-MCPB F-2), and so is the conversation - /// session key, `gateway:webhook:{credential}:{reply_target}` (D-025). - fn generic_webhook(reply_target: Option<&str>, credential: &str, idempotency_key: Option) -> Self { - let target = reply_target.unwrap_or("webhook-client"); - Self { - channel: "webhook".to_string(), - session_key: format!("gateway:webhook:{credential}:{target}"), - sender: target.to_string(), - recipient: "prx".to_string(), - idempotency_key, - credential: Some(credential.to_string()), - } - } - - /// The owner a webhook turn acts for: - /// `owner:{workspace}:webhook:{credential}:{reply_target}`. Two different - /// credentials never compose the same owner, whatever `reply_target` they - /// send, so one token cannot reach another token's sub-agent runs or - /// owner-scoped rows. Holders of one credential remain one trust domain, - /// separated only by the `reply_target` they assert. `None` for a platform - /// channel message, which keeps its envelope-derived owner. - fn webhook_owner_id(&self, workspace_id: &str) -> Option { - let credential = self.credential.as_deref()?; - Some( - crate::memory::principal::OwnerPrincipal::new( - workspace_id, - self.channel.as_str(), - format!("{credential}:{}", self.sender), - self.session_key.as_str(), - vec![crate::memory::principal::Role::Anonymous], - ) - .owner_id, - ) - } - - fn channel_message(msg: &crate::channels::traits::ChannelMessage) -> Self { - Self { - channel: msg.channel.clone(), - session_key: format!("gateway:{}:{}", msg.channel, msg.sender), - sender: msg.sender.clone(), - recipient: msg.reply_target.clone(), - idempotency_key: Some(format!("gateway:{}:{}", msg.channel, msg.id)), - credential: None, - } - } -} - -/// Domain separator of the webhook owner digest (R-MCPBfg N-4). Bumping it -/// re-keys every webhook owner and conversation once. -const WEBHOOK_OWNER_DIGEST_DOMAIN: &str = "prx-webhook-owner-v1"; - -/// Hex digits of the webhook owner digest kept in owner ids and session keys: -/// 128 bits. -const WEBHOOK_OWNER_DIGEST_HEX: usize = 32; - -/// The credential part of a `/webhook` owner id and session key: -/// `{kind}:{digest}`, where the digest is SHA-256 over -/// `prx-webhook-owner-v1 \0 kind \0 secret`, truncated to 128 bits. -/// -/// Domain-separated on purpose. The plain SHA-256 of a paired token is the -/// at-rest verifier in `gateway.paired_tokens`, and the plain digest of an -/// operator-chosen `X-Webhook-Token` or signing secret is an offline-guessable -/// verifier; neither belongs in message events, run tags, session keys and -/// logs. The value only has to be stable per credential and distinct across -/// credentials. -fn webhook_owner_credential(kind: &str, secret: &str) -> String { - use sha2::{Digest, Sha256}; - - let mut hasher = Sha256::new(); - hasher.update(WEBHOOK_OWNER_DIGEST_DOMAIN.as_bytes()); - hasher.update([0u8]); - hasher.update(kind.as_bytes()); - hasher.update([0u8]); - hasher.update(secret.as_bytes()); - let digest = hex::encode(hasher.finalize()); - let digest = digest.get(..WEBHOOK_OWNER_DIGEST_HEX).unwrap_or(digest.as_str()); - format!("{kind}:{digest}") -} - -pub(super) fn hash_webhook_secret(value: &str) -> String { - use sha2::{Digest, Sha256}; - - let digest = Sha256::digest(value.as_bytes()); - hex::encode(digest) -} - -fn verify_webhook_hmac_signature(secret: &str, body: &[u8], signature_header: &str) -> bool { - use hmac::{Hmac, Mac}; - use sha2::Sha256; - - let signature_hex = signature_header - .trim() - .strip_prefix("sha256=") - .unwrap_or_else(|| signature_header.trim()); - let Ok(provided) = hex::decode(signature_hex) else { - return false; - }; - - let Ok(mut mac) = Hmac::::new_from_slice(secret.as_bytes()) else { - return false; - }; - mac.update(body); - mac.verify_slice(&provided).is_ok() -} - -/// How often the rate limiter sweeps stale IP entries from its map. -const RATE_LIMITER_SWEEP_INTERVAL_SECS: u64 = 300; // 5 minutes - -#[derive(Debug)] -struct SlidingWindowRateLimiter { - /// The budget, re-readable at runtime so a configuration reload can adopt a - /// new one **without** discarding the windows already recorded. Rebuilding - /// the limiter instead would hand every caller a fresh window, which is - /// precisely the moment a throttled caller must not be allowed to burst. - limit_per_window: AtomicU32, - window: Duration, - max_keys: usize, - requests: Mutex<(HashMap>, Instant)>, -} - -impl SlidingWindowRateLimiter { - fn new(limit_per_window: u32, window: Duration, max_keys: usize) -> Self { - Self { - limit_per_window: AtomicU32::new(limit_per_window), - window, - max_keys: max_keys.max(1), - requests: Mutex::new((HashMap::new(), Instant::now())), - } - } - - /// The budget this limiter currently enforces. - fn limit_per_window(&self) -> u32 { - self.limit_per_window.load(Ordering::Relaxed) - } - - /// Adopt a new budget, keeping every recorded window. - fn set_limit_per_window(&self, limit_per_window: u32) { - self.limit_per_window.store(limit_per_window, Ordering::Relaxed); - } - - fn prune_stale(requests: &mut HashMap>, cutoff: Instant) { - requests.retain(|_, timestamps| { - timestamps.retain(|t| *t > cutoff); - !timestamps.is_empty() - }); - } - - fn allow(&self, key: &str) -> bool { - let limit_per_window = self.limit_per_window(); - if limit_per_window == 0 { - return true; - } - - let now = Instant::now(); - let cutoff = now.checked_sub(self.window).unwrap_or(now); - - let mut guard = self.requests.lock(); - let (requests, last_sweep) = &mut *guard; - - // Periodic sweep: remove keys with no recent requests - if last_sweep.elapsed() >= Duration::from_secs(RATE_LIMITER_SWEEP_INTERVAL_SECS) { - Self::prune_stale(requests, cutoff); - *last_sweep = now; - } - - if !requests.contains_key(key) && requests.len() >= self.max_keys { - // Opportunistic stale cleanup before eviction under cardinality pressure. - Self::prune_stale(requests, cutoff); - *last_sweep = now; - - if requests.len() >= self.max_keys { - // Evict the key with the fewest recent requests. FIFO (oldest) - // eviction lets an attacker cycle through IPs and reset legitimate - // users' rate-limit counters. Evicting the least-active key is - // harder to weaponize. - let evict_key = requests - .iter() - .min_by_key(|(_, timestamps)| timestamps.len()) - .map(|(k, _)| k.clone()); - if let Some(evict_key) = evict_key { - requests.remove(&evict_key); - } - } - } - - let entry = requests.entry(key.to_owned()).or_default(); - entry.retain(|instant| *instant > cutoff); - - if entry.len() >= limit_per_window as usize { - return false; - } - - entry.push(now); - true - } -} - -#[derive(Debug)] -pub struct GatewayRateLimiter { - pair: SlidingWindowRateLimiter, - webhook: SlidingWindowRateLimiter, - webhook_credential: SlidingWindowRateLimiter, - api: SlidingWindowRateLimiter, -} - -impl GatewayRateLimiter { - pub fn new(pair_per_minute: u32, webhook_per_minute: u32, api_per_minute: u32, max_keys: usize) -> Self { - let window = Duration::from_secs(RATE_LIMIT_WINDOW_SECS); - Self { - pair: SlidingWindowRateLimiter::new(pair_per_minute, window, max_keys), - webhook: SlidingWindowRateLimiter::new(webhook_per_minute, window, max_keys), - webhook_credential: SlidingWindowRateLimiter::new(webhook_per_minute, window, max_keys), - api: SlidingWindowRateLimiter::new(api_per_minute, window, max_keys), - } - } - - fn allow_pair(&self, key: &str) -> bool { - self.pair.allow(key) - } - - pub fn allow_webhook(&self, key: &str) -> bool { - self.webhook.allow(key) - } - - fn allow_webhook_credential(&self, key: &str) -> bool { - self.webhook_credential.allow(key) - } - - pub(super) fn allow_api(&self, key: &str) -> bool { - self.api.allow(key) - } -} - -#[derive(Debug)] -pub struct IdempotencyStore { - ttl: Duration, - max_keys: usize, - state: Mutex, -} - -#[derive(Debug, Default)] -struct IdempotencyStoreState { - entries: HashMap, - next_generation: u64, - payload_bytes: usize, -} - -#[derive(Debug)] -enum IdempotencyEntry { - Processing { - generation: u64, - request_fingerprint: [u8; 32], - reserved_bytes: usize, - }, - Succeeded { - request_fingerprint: [u8; 32], - completed_at: Instant, - response_id: Uuid, - result_hash: String, - replay: Option, - }, - Failed { - request_fingerprint: [u8; 32], - failed_at: Instant, - retry_eligible: bool, - }, -} - -impl IdempotencyEntry { - const fn request_fingerprint(&self) -> &[u8; 32] { - match self { - Self::Processing { - request_fingerprint, .. - } - | Self::Succeeded { - request_fingerprint, .. - } - | Self::Failed { - request_fingerprint, .. - } => request_fingerprint, - } - } -} - -#[derive(Debug, Clone)] -struct IdempotencyReplay { - response_id: Uuid, - response: Arc, - model: Arc, -} - -impl IdempotencyReplay { - fn payload_bytes(&self) -> usize { - self.response.len().saturating_add(self.model.len()) - } - - fn json_body(&self) -> serde_json::Value { - serde_json::json!({ - "status": "duplicate", - "idempotent": true, - "response": self.response.as_ref(), - "model": self.model.as_ref(), - "response_id": self.response_id.to_string(), - }) - } -} - -#[derive(Debug)] -enum IdempotencyClaimOutcome { - Acquired(IdempotencyClaim), - Processing, - Replay(IdempotencyReplay), - ReplayUnavailable { response_id: Uuid, result_hash: String }, - RequestConflict, - RetryUnavailable, - AtCapacity, -} - -#[derive(Debug)] -struct IdempotencyClaim { - store: Arc, - key_digest: String, - generation: u64, - armed: bool, - /// Whether this attempt reached work that can produce observable side - /// effects — memory writes, tool calls, outbound messages. - /// - /// This is the only thing that decides whether a redelivery of the same key - /// is allowed to run again. Before dispatch a failed attempt is provably a - /// no-op, so re-running it is free. After dispatch nothing here knows how - /// far the attempt got, so re-running it could write the file, send the - /// message, or call the external API a second time. "Not known to be safe" - /// is therefore treated as "not retryable", never the other way round. - dispatched: bool, -} - -impl IdempotencyClaim { - /// Record that the attempt is about to start doing observable work. - /// - /// Call this immediately before the first side effect, not at claim - /// acquisition: everything up to that point is what makes a retry safe. - const fn mark_dispatched(&mut self) { - self.dispatched = true; - } - - /// Whether a redelivery of this key may re-execute the request. - const fn retry_eligible(&self) -> bool { - !self.dispatched - } - - fn succeed(mut self, replay: IdempotencyReplay, result_hash: String) -> bool { - let transitioned = self - .store - .complete_if_owner(&self.key_digest, self.generation, replay, result_hash); - if transitioned { - self.armed = false; - } - transitioned - } - fn succeed_unavailable(mut self, response_id: Uuid, result_hash: String) -> bool { - let transitioned = - self.store - .complete_result_if_owner(&self.key_digest, self.generation, response_id, result_hash, None); - if transitioned { - self.armed = false; - } - transitioned - } - - fn fail(mut self) -> bool { - let retry_eligible = self.retry_eligible(); - let transitioned = self - .store - .fail_if_owner(&self.key_digest, self.generation, retry_eligible); - if transitioned { - self.armed = false; - } - transitioned - } -} - -impl Drop for IdempotencyClaim { - /// A claim that reaches `Drop` still armed was abandoned without anyone - /// deciding how the attempt ended: the task was cancelled or killed, a - /// caller took an early return path, or a panic unwound through it. - /// - /// This used to release the key as `retry_eligible = true`, which turned - /// every abandoned attempt into an invitation to run the whole request - /// again — while the original may still have been mid-flight, and after it - /// may already have written half its side effects. Abandonment carries no - /// information about how far the work got, so it resolves the same way any - /// other unknown does: dispatched work is not retryable. - fn drop(&mut self) { - if self.armed { - let retry_eligible = self.retry_eligible(); - let _ = self - .store - .fail_if_owner(&self.key_digest, self.generation, retry_eligible); - } - } -} - -impl IdempotencyStore { - pub fn new(ttl: Duration, max_keys: usize) -> Self { - Self { - ttl, - max_keys: max_keys.max(1), - state: Mutex::new(IdempotencyStoreState::default()), - } - } - - fn prune_expired_terminal(&self, state: &mut IdempotencyStoreState, now: Instant) { - let expired = state - .entries - .iter() - .filter_map(|(key, entry)| { - let terminal_at = match entry { - IdempotencyEntry::Processing { .. } => return None, - IdempotencyEntry::Succeeded { completed_at, .. } => *completed_at, - IdempotencyEntry::Failed { failed_at, .. } => *failed_at, - }; - (now.saturating_duration_since(terminal_at) >= self.ttl).then(|| key.clone()) - }) - .collect::>(); - - for key in expired { - if let Some(IdempotencyEntry::Succeeded { - replay: Some(replay), .. - }) = state.entries.remove(&key) - { - state.payload_bytes = state.payload_bytes.saturating_sub(replay.payload_bytes()); - } - } - } - - fn reserve_processing( - self: &Arc, - state: &mut IdempotencyStoreState, - key_digest: String, - request_fingerprint: [u8; 32], - ) -> IdempotencyClaimOutcome { - let Some(next_payload_bytes) = state.payload_bytes.checked_add(IDEMPOTENCY_MAX_REPLAY_BYTES) else { - return IdempotencyClaimOutcome::AtCapacity; - }; - if next_payload_bytes > IDEMPOTENCY_REPLAY_BUDGET_BYTES { - return IdempotencyClaimOutcome::AtCapacity; - } - let Some(generation) = state.next_generation.checked_add(1) else { - return IdempotencyClaimOutcome::AtCapacity; - }; - state.next_generation = generation; - state.payload_bytes = next_payload_bytes; - state.entries.insert( - key_digest.clone(), - IdempotencyEntry::Processing { - generation, - request_fingerprint, - reserved_bytes: IDEMPOTENCY_MAX_REPLAY_BYTES, - }, - ); - IdempotencyClaimOutcome::Acquired(IdempotencyClaim { - store: Arc::clone(self), - key_digest, - generation, - armed: true, - dispatched: false, - }) - } - - fn claim(self: &Arc, key_digest: String, request_fingerprint: [u8; 32]) -> IdempotencyClaimOutcome { - let now = Instant::now(); - let mut state = self.state.lock(); - self.prune_expired_terminal(&mut state, now); - - enum Existing { - Processing, - Replay(IdempotencyReplay), - ReplayUnavailable(Uuid, String), - Retry, - RetryUnavailable, - RequestConflict, - } - let existing = state.entries.get(&key_digest).map(|entry| { - if entry.request_fingerprint() != &request_fingerprint { - return Existing::RequestConflict; - } - match entry { - IdempotencyEntry::Processing { .. } => Existing::Processing, - IdempotencyEntry::Succeeded { - response_id, - result_hash, - replay, - .. - } => replay.as_ref().map_or_else( - || Existing::ReplayUnavailable(*response_id, result_hash.clone()), - |snapshot| Existing::Replay(snapshot.clone()), - ), - IdempotencyEntry::Failed { retry_eligible, .. } => { - if *retry_eligible { - Existing::Retry - } else { - Existing::RetryUnavailable - } - } - } - }); - - match existing { - Some(Existing::Processing) => IdempotencyClaimOutcome::Processing, - Some(Existing::Replay(replay)) => IdempotencyClaimOutcome::Replay(replay), - Some(Existing::ReplayUnavailable(response_id, result_hash)) => IdempotencyClaimOutcome::ReplayUnavailable { - response_id, - result_hash, - }, - Some(Existing::RetryUnavailable) => IdempotencyClaimOutcome::RetryUnavailable, - Some(Existing::RequestConflict) => IdempotencyClaimOutcome::RequestConflict, - Some(Existing::Retry) => self.reserve_processing(&mut state, key_digest, request_fingerprint), - None => { - if state.entries.len() >= self.max_keys { - return IdempotencyClaimOutcome::AtCapacity; - } - self.reserve_processing(&mut state, key_digest, request_fingerprint) - } - } - } - - fn complete_if_owner( - &self, - key_digest: &str, - generation: u64, - replay: IdempotencyReplay, - result_hash: String, - ) -> bool { - let response_id = replay.response_id; - let replay = (replay.payload_bytes() <= IDEMPOTENCY_MAX_REPLAY_BYTES).then_some(replay); - self.complete_result_if_owner(key_digest, generation, response_id, result_hash, replay) - } - - fn complete_result_if_owner( - &self, - key_digest: &str, - generation: u64, - response_id: Uuid, - result_hash: String, - replay: Option, - ) -> bool { - let mut state = self.state.lock(); - let Some(IdempotencyEntry::Processing { - generation: current_generation, - request_fingerprint, - reserved_bytes, - .. - }) = state.entries.get(key_digest) - else { - return false; - }; - if *current_generation != generation { - return false; - } - - let request_fingerprint = *request_fingerprint; - let reserved_bytes = *reserved_bytes; - state.payload_bytes = state.payload_bytes.saturating_sub(reserved_bytes); - state.payload_bytes = state - .payload_bytes - .saturating_add(replay.as_ref().map_or(0, IdempotencyReplay::payload_bytes)); - state.entries.insert( - key_digest.to_string(), - IdempotencyEntry::Succeeded { - request_fingerprint, - completed_at: Instant::now(), - response_id, - result_hash, - replay, - }, - ); - true - } - - fn fail_if_owner(&self, key_digest: &str, generation: u64, retry_eligible: bool) -> bool { - let mut state = self.state.lock(); - let Some(IdempotencyEntry::Processing { - generation: current_generation, - request_fingerprint, - reserved_bytes, - .. - }) = state.entries.get(key_digest) - else { - return false; - }; - if *current_generation != generation { - return false; - } - - let request_fingerprint = *request_fingerprint; - let reserved_bytes = *reserved_bytes; - state.payload_bytes = state.payload_bytes.saturating_sub(reserved_bytes); - state.entries.insert( - key_digest.to_string(), - IdempotencyEntry::Failed { - request_fingerprint, - failed_at: Instant::now(), - retry_eligible, - }, - ); - true - } -} - -fn webhook_request_fingerprint(body: &[u8]) -> [u8; 32] { - use sha2::{Digest, Sha256}; - Sha256::digest(body).into() -} - -/// Read an idempotency-key request header under a shared length cap. -/// -/// `/webhook` (`X-Idempotency-Key`) and `POST /mcp/v1/tools/call` -/// (`Idempotency-Key`) both accept a caller-supplied key, so both cap it the -/// same way: a non-UTF-8 or over-long value is a client error rather than -/// something silently truncated into a different key, and a blank value is -/// treated as "no key" rather than as the empty key. -fn idempotency_key_from_header(headers: &HeaderMap, header_name: &str) -> Result, String> { - let Some(value) = headers.get(header_name) else { - return Ok(None); - }; - let Ok(value) = value.to_str() else { - return Err(format!("{header_name} must be valid UTF-8")); - }; - let value = value.trim(); - if value.is_empty() { - return Ok(None); - } - if value.len() > IDEMPOTENCY_MAX_KEY_BYTES { - return Err(format!( - "{header_name} exceeds the {IDEMPOTENCY_MAX_KEY_BYTES}-byte limit" - )); - } - Ok(Some(value.to_string())) -} - -fn webhook_idempotency_digest(scope: &str, raw_key: &str) -> String { - use sha2::{Digest, Sha256}; - let mut hasher = Sha256::new(); - hasher.update(scope.as_bytes()); - hasher.update([0]); - hasher.update(raw_key.as_bytes()); - hex::encode(hasher.finalize()) -} - -fn webhook_result_hash(response: &str, model: &str) -> String { - crate::agent::terminal::oversized_reply::result_hash(response, model) -} - -fn replay_unavailable_body(response_id: Uuid, result_hash: &str) -> serde_json::Value { - serde_json::json!({ - "status": "replay_unavailable", "idempotent": true, - "response_id": response_id.to_string(), "result_hash": result_hash, - "message": "The original request succeeded, but its response is too large to replay" - }) -} - -fn parse_client_ip(value: &str) -> Option { - let value = value.trim().trim_matches('"').trim(); - if value.is_empty() { - return None; - } - - if let Ok(ip) = value.parse::() { - return Some(ip); - } - - if let Ok(addr) = value.parse::() { - return Some(addr.ip()); - } - - let value = value.trim_matches(['[', ']']); - value.parse::().ok() -} - -fn forwarded_client_ip(headers: &HeaderMap) -> Option { - // Prefer X-Real-IP (single trusted proxy) over X-Forwarded-For - if let Some(real_ip) = headers - .get("X-Real-IP") - .and_then(|v| v.to_str().ok()) - .and_then(parse_client_ip) - { - return Some(real_ip); - } - - // RFC 7239: use the LAST (rightmost) IP in X-Forwarded-For, which is the - // one added by the closest trusted proxy. Using the first IP is spoofable - // by the client and can bypass rate limiting. - if let Some(xff) = headers.get("X-Forwarded-For").and_then(|v| v.to_str().ok()) { - for candidate in xff.rsplit(',') { - if let Some(ip) = parse_client_ip(candidate) { - return Some(ip); - } - } - } - - None -} - -pub(super) fn client_key_from_request( - peer_addr: Option, - headers: &HeaderMap, - trust_forwarded_headers: bool, -) -> String { - if trust_forwarded_headers { - if let Some(ip) = forwarded_client_ip(headers) { - return ip.to_string(); - } - } - - peer_addr - .map(|addr| addr.ip().to_string()) - .unwrap_or_else(|| "unknown".to_string()) -} - -fn normalize_max_keys(configured: usize, fallback: usize) -> usize { - if configured == 0 { fallback.max(1) } else { configured } -} - -fn authorize_gateway_resource_mutation( - state: &AppState, - operation_name: &str, - risk: ResourceRiskLevel, -) -> Result<(), (StatusCode, Json)> { - let config = state.config.load_full(); - authorize_gateway_config_resource_mutation(&config, operation_name, risk) -} - -fn authorize_gateway_config_resource_mutation( - config: &Config, - operation_name: &str, - risk: ResourceRiskLevel, -) -> Result<(), (StatusCode, Json)> { - let policy = crate::runtime::bootstrap::build_security_policy(&config); - SideEffectGate::new(&policy) - .authorize_resource_operation("gateway", operation_name, risk, None) - .map(|_| ()) - .map_err(|error| (StatusCode::FORBIDDEN, Json(serde_json::json!({"error": error})))) -} - -fn gateway_channel_webhook_operation(channel: &str, action: &str) -> String { - format!("gateway:channel_webhook:{channel}:{action}") -} - -/// Shared state for all axum handlers -#[derive(Clone)] -pub struct AppState { - pub rf_streams: Arc, - pub rf_approvals: Arc, - /// Sole configuration generation owner used by every gateway path. - pub config: crate::config::SharedConfig, - /// Test fixtures' provider, served by `pin_turn_runtime` when a test - /// state has no turn runtime; every production turn takes its provider - /// from [`turn_runtime`](Self::turn_runtime). - #[cfg(test)] - pub provider: Arc, - pub model: String, - pub temperature: f64, - pub mem: Arc, - pub auto_save: bool, - /// Test fixtures' registry, served by `pin_turn_runtime` when a test - /// state has no turn runtime. Production state never holds one: every - /// handler pins [`turn_runtime`](Self::turn_runtime), and a registry kept - /// here would retain the startup generation, and its MCP children, for - /// the gateway's lifetime (D-098 F-1). - #[cfg(test)] - pub tools_registry: Arc>>, - /// Test fixtures' MCP tool (see [`tools_registry`](Self::tools_registry)). - #[cfg(test)] - pub mcp_tool: Option>, - /// Atomically rebuilt provider/model/tools bundle for newly admitted turns. - pub turn_runtime: Option>, - /// Hook manager for lifecycle events. - pub hooks: Arc, - /// SHA-256 hash of `webhook.token` for `X-Webhook-Token` auth. - pub webhook_token_hash: Option>, - /// HMAC signing secret for `X-Webhook-Signature` verification. - pub webhook_signing_secret: Option>, - pub pairing: Arc, - pub trust_forwarded_headers: bool, - pub rate_limiter: Arc, - pub idempotency_store: Arc, - pub whatsapp: Option>, - pub signal: Option>, - /// `WhatsApp` app secret for webhook signature verification (`X-Hub-Signature-256`) - pub whatsapp_app_secret: Option>, - pub linq: Option>, - /// Linq webhook signing secret for signature verification - pub linq_signing_secret: Option>, - pub nextcloud_talk: Option>, - /// Nextcloud Talk webhook secret for signature verification - pub nextcloud_talk_webhook_secret: Option>, - /// Observability backend for metrics scraping - pub observer: Arc, - /// Gateway boot instant used for uptime in Web Console status API. - pub start_time: Instant, - /// Actual bound gateway port (supports dynamic port assignment). - pub gateway_port: u16, - /// Web Console log stream broadcast channel. - pub logs_broadcast_tx: broadcast::Sender, - /// Sole process-level owner of the WASM registry and every derived adapter. - #[cfg(feature = "wasm-plugins")] - pub plugin_runtime: Option>, -} - -pub struct TurnRuntimeGeneration { - provider_binding: Option>, - publication_slot: Arc, - pub config_generation: Arc, - pub provider: Arc, - pub model: String, - pub temperature: f64, - pub tools_registry: Arc>>, - pub mcp_tool: Option>, -} - -struct ConfigGenerationMessageAuditSink { - memory: Arc, - workspace_id: String, - runtime_handle: tokio::runtime::Handle, -} - -impl crate::config::ConfigGenerationAuditSink for ConfigGenerationMessageAuditSink { - fn record(&self, event: crate::config::ConfigGenerationAuditEvent) { - let memory = Arc::clone(&self.memory); - let workspace_id = self.workspace_id.clone(); - self.runtime_handle.spawn(async move { - let source_revision = event - .source_revision - .as_ref() - .map(|revision| revision.fingerprint_sha256.clone()); - let raw_payload_json = serde_json::to_string(&event).ok(); - let input = crate::memory::MessageEventInput { - agent_partition: None, - event_id: None, - idempotency_key: None, - workspace_id, - owner_id: Some("system".to_string()), - source: crate::memory::MessageEventSource::Other("config".to_string()), - channel: Some("daemon".to_string()), - session_key: Some("config-generation".to_string()), - parent_session_key: None, - run_id: event.generation_id.map(|generation| format!("config:{}", generation.0)), - parent_run_id: None, - agent_id: Some("config-generation-manager".to_string()), - persona_id: None, - sender: Some("system".to_string()), - recipient: Some("runtime".to_string()), - role: "event".to_string(), - event_type: event.event_type.clone(), - subject: None, - goal_id: None, - causation_event_id: None, - correlation_id: None, - attempt_id: None, - lease_epoch: None, - config_generation_id: event.generation_id.map(|generation| generation.0), - config_source_revision: source_revision, - content: event.payload.to_string(), - raw_payload_json, - visibility: MemoryVisibility::Workspace, - }; - if let Err(error) = memory.append_message_event(input).await { - tracing::warn!( - event_type = %event.event_type, - "failed to append config generation audit event: {error}" - ); - } - }); - } -} - -pub struct GatewayTurnRuntimeOwner { - cleanup: Arc, - current: Arc>, - config: crate::config::SharedConfig, - memory: Arc, - signal: Option>, - whatsapp: Option>, - linq: Option>, - nextcloud_talk: Option>, - hooks: Arc, - agents: agent_lifecycle::AgentLifecycle, - #[cfg(feature = "wasm-plugins")] - plugin_runtime: Option>, -} - -impl GatewayTurnRuntimeOwner { - fn new( - current: impl Into, - config: crate::config::SharedConfig, - memory: Arc, - signal: Option>, - whatsapp: Option>, - linq: Option>, - nextcloud_talk: Option>, - hooks: Arc, - #[cfg(feature = "wasm-plugins")] plugin_runtime: Option>, - ) -> Self { - // Startup sweep, before any target is published: a failure latches - // every targeted resolve until a later reconcile succeeds. - let agents = agent_lifecycle::AgentLifecycle::default(); - agents.reconcile(memory.as_ref(), &config.pin().effective, true); - let current = current.into(); - Self { - cleanup: Arc::clone(¤t.publication_slot().cleanup), - current: Arc::new(ArcSwap::from_pointee(current)), - config, - memory, - signal, - whatsapp, - linq, - nextcloud_talk, - hooks, - agents, - #[cfg(feature = "wasm-plugins")] - plugin_runtime, - } - } - - fn pin_state(&self) -> Arc { - self.current.load_full() - } - - /// Test fixtures' ready generation. - #[cfg(test)] - fn pin(&self) -> Arc { - self.current - .load() - .ready() - .expect("test: the gateway turn runtime is ready") - } - - const fn agent_lifecycle(&self) -> &agent_lifecycle::AgentLifecycle { - &self.agents - } - - /// Whether the active generation was launched with a controlled H2 profile. - /// - /// The lifecycle experiment HTTP adapter uses this to refuse when the - /// process has no profile. It does not mint an invocation. - pub(crate) fn has_controlled_profile(&self) -> bool { - self.current.load().publication_slot().controlled.is_some() - } - - /// The runtime of `generation`. A ready runtime rejects a generation - /// whose default provider has no usable credential (the previous - /// generation stays active); a runtime standing by takes it and keeps - /// standing by, so the agent and configuration routes keep applying. - fn build(&self, generation: Arc) -> anyhow::Result { - let previous = self.current.load_full(); - if let Some(profile) = &previous.publication_slot().controlled { - profile.revoke(); - anyhow::bail!("controlled Gateway generation cannot be rebuilt"); - } - let chat = build_gateway_turn_provider( - &generation.effective, - &providers::provider_runtime_options_from_config(&generation.effective), - ); - let chat = match (chat, previous.as_ref()) { - (Ok(chat), _) => Ok(chat), - (Err(error), GatewayTurnState::NotReady(_)) => { - let reason = TurnNotReadyReason::of_provider_error(&error).ok_or(error)?; - tracing::warn!( - reason = reason.code(), - "Gateway turn runtime stays not ready after a configuration change" - ); - Err(reason) - } - (Err(error), GatewayTurnState::Ready(_)) => return Err(error), - }; - let mut runtime = build_gateway_turn_state( - generation, - chat, - Arc::clone(&self.config), - Arc::clone(&self.memory), - self.signal.clone(), - self.whatsapp.clone(), - self.linq.clone(), - self.nextcloud_talk.clone(), - Arc::clone(&self.hooks), - #[cfg(feature = "wasm-plugins")] - self.plugin_runtime.clone(), - )?; - let slot = runtime - .publication_slot_mut() - .ok_or_else(|| anyhow::anyhow!("new gateway turn runtime was unexpectedly shared"))?; - Arc::get_mut(slot) - .ok_or_else(|| anyhow::anyhow!("new gateway decision slot was unexpectedly shared"))? - .cleanup = Arc::clone(&self.cleanup); - Ok(runtime) - } - - /// Retry a runtime standing by against the active generation. Storing a - /// provider credential changes no configuration field, so the reload - /// that follows publishes no generation and prepares no participant; - /// the reload route calls this so that reload still makes the runtime - /// ready. A runtime that is ready, or that another reload replaced in - /// the meantime, is left as it is. `Ok(true)` when this call made the - /// runtime ready. - pub(crate) fn retry_standby(&self) -> anyhow::Result { - let previous = self.current.load_full(); - if previous.ready().is_ok() { - return Ok(false); - } - let next = self.build(self.config.pin())?; - if next.ready().is_err() { - return Ok(false); - } - let next = Arc::new(next); - let swapped = self.current.compare_and_swap(&previous, Arc::clone(&next)); - if !Arc::ptr_eq(&swapped, &previous) { - return Ok(false); - } - retire_replaced_mcp_servers(previous.mcp_tool(), next.mcp_tool()); - tracing::info!("Gateway turn runtime is ready: the default provider credential resolved"); - Ok(true) - } - - fn synchronize_to_active(&self) -> anyhow::Result<()> { - let active = self.config.pin(); - if self.current.load().config_generation().id == active.id { - return Ok(()); - } - self.current.store(Arc::new(self.build(active)?)); - Ok(()) - } -} - -/// Start the Gateway's turn runtime from its startup generation: the owner -/// that rebuilds it on every configuration change, registered with the -/// manager and synchronized to the active generation. The returned owner is -/// the startup generation's only holder, so the first configuration change -/// releases it and ends its stdio MCP children, and a change of a server's -/// definition stops the process that ran the old one (D-098 F-1). -#[allow(clippy::too_many_arguments)] -fn start_gateway_turn_runtime( - startup: impl Into, - shared: &crate::config::SharedConfig, - memory: Arc, - signal: Option>, - whatsapp: Option>, - linq: Option>, - nextcloud_talk: Option>, - hooks: Arc, - #[cfg(feature = "wasm-plugins")] plugin_runtime: Option>, -) -> anyhow::Result> { - let owner = Arc::new(GatewayTurnRuntimeOwner::new( - startup, - Arc::clone(shared), - memory, - signal, - whatsapp, - linq, - nextcloud_talk, - hooks, - #[cfg(feature = "wasm-plugins")] - plugin_runtime, - )); - let participant: Arc = owner.clone(); - shared.register_participant(&participant); - owner.synchronize_to_active()?; - Ok(owner) -} - -struct PreparedGatewayTurnRuntime { - current: Arc>, - previous: Arc, - generation: GatewayTurnState, - agents: agent_lifecycle::AgentReconcile, -} - -impl crate::config::PreparedConfigGeneration for PreparedGatewayTurnRuntime { - fn commit(&mut self) -> anyhow::Result<()> { - // First, so a failed retire rejects the reload before it is published. - self.agents.commit()?; - self.current.store(Arc::new(self.generation.clone())); - if self.previous.ready().is_err() && self.generation.ready().is_ok() { - tracing::info!("Gateway turn runtime is ready: the default provider credential resolved"); - } - retire_replaced_mcp_servers(self.previous.mcp_tool(), self.generation.mcp_tool()); - Ok(()) - } - - fn rollback(&mut self) { - self.current.store(Arc::clone(&self.previous)); - self.agents.rollback(); - } - - fn finalize(&mut self) { - self.agents - .finalize(&self.generation.config_generation().source_revision.fingerprint_sha256); - } -} - -/// When a new generation replaces the MCP tool, stop the old tool's -/// servers that the new one no longer runs as they were launched (a -/// narrowed `mcp.workspace_servers`, a removed or disabled server, a changed -/// command, arguments, environment or working directory), so the process -/// running the old definition ends now instead of when the old tool is -/// dropped (D-095 M-2, D-097 M-3). Servers both generations run alike keep -/// their sessions until the old tool is dropped, which happens when the -/// last turn pinned to the old generation ends, so such a turn keeps -/// working. The stop runs on the runtime; without one it is logged and left -/// to the tool's drop. -fn retire_replaced_mcp_servers(previous: Option<&Arc>, next: Option<&Arc>) { - let Some(previous) = previous.cloned() else { - return; - }; - if next.is_some_and(|next| Arc::ptr_eq(next, &previous)) { - return; - } - let keep = next - .map(|next| previous.servers_launched_alike(next)) - .unwrap_or_default(); - match tokio::runtime::Handle::try_current() { - Ok(handle) => { - handle.spawn(async move { - let stopped = previous.retire_servers_except(&keep).await; - if stopped > 0 { - tracing::info!( - stopped, - "Stopped MCP servers the new configuration no longer runs as launched" - ); - } - }); - } - Err(error) => tracing::warn!( - error = %error, - "No async runtime to stop the MCP servers the new configuration no longer runs" - ), - } -} - -impl crate::config::ConfigGenerationParticipant for GatewayTurnRuntimeOwner { - fn name(&self) -> &'static str { - "gateway_turn_runtime" - } - - fn supports_rebuild_field(&self, _field: &str) -> bool { - true - } - - fn prepares_for_field(&self, field: &str) -> bool { - !crate::config::generation::is_process_restart_only(field) - && !crate::config::generation::is_controlled_restart(field) - } - - fn prepare( - &self, - generation: Arc, - _changed_fields: &[String], - ) -> anyhow::Result> { - let previous = self.current.load_full(); - let agents = agent_lifecycle::AgentReconcile::prepare( - &self.agents, - &self.memory, - &previous.config_generation().effective, - &generation.effective, - ); - let runtime = self.build(generation)?; - Ok(Box::new(PreparedGatewayTurnRuntime { - current: Arc::clone(&self.current), - previous, - generation: runtime, - agents, - })) - } -} - -impl AppState { - /// The current turn runtime, ready or standing by. Routes that read the - /// tool surface or the configuration take this; routes that start or - /// continue a turn take [`admit_turn_runtime`](Self::admit_turn_runtime). - fn pin_turn_state(&self) -> Arc { - if let Some(runtime) = &self.turn_runtime { - return runtime.pin_state(); - } - #[cfg(not(test))] - { - tracing::error!("production gateway state is missing its TurnRuntimeGeneration; aborting"); - std::process::abort(); - } - #[cfg(test)] - { - Arc::new(GatewayTurnState::Ready(self.test_turn_runtime())) - } - } - - /// The admission check of every turn entry point: the ready generation - /// the turn runs on, or the typed refusal it answers with. - fn admit_turn_runtime(&self) -> Result, TurnNotReady> { - self.pin_turn_state().ready() - } - - /// Test fixtures' ready generation. - #[cfg(test)] - fn pin_turn_runtime(&self) -> Arc { - self.turn_runtime - .as_ref() - .map_or_else(|| self.test_turn_runtime(), |runtime| runtime.pin()) - } - - #[cfg(test)] - fn test_turn_runtime(&self) -> Arc { - { - let mut generation = TurnRuntimeGeneration { - provider_binding: None, - publication_slot: Arc::new(turn_source::publication_slot::GatewayPublicationSlot::default()), - config_generation: self.config.pin(), - provider: Arc::clone(&self.provider), - model: self.model.clone(), - temperature: self.temperature, - tools_registry: Arc::clone(&self.tools_registry), - mcp_tool: self.mcp_tool.clone(), - }; - let config = &generation.config_generation.effective; - if let Some(provider_name) = config.default_provider.as_deref() { - let catalog = crate::providers::selection::catalog_for(config); - if let Ok(resolved) = crate::providers::selection::check_with( - config, - &catalog, - provider_name, - &generation.model, - crate::providers::selection::credential_for(config, provider_name), - &crate::providers::catalog::Requirement::chat(), - crate::providers::catalog::UnknownPolicy::Invocation, - ) { - generation.provider_binding = Some(Arc::new(turn_source::GatewayProviderBinding::new( - Arc::clone(&generation.provider), - resolved, - ))); - let security = Arc::new(crate::security::SecurityPolicy::from_config( - &config.autonomy, - &config.workspace_dir, - )); - generation.publication_slot = - Arc::new(turn_source::publication_slot::GatewayPublicationSlot::new(security, 0)); - } - } - Arc::new(generation) - } - } -} - -/// Build the gateway's per-turn channel routing registry and register the -/// channel-aware tools that complete its tool surface. -/// -/// The gateway has two launch paths — [`build_gateway_turn_runtime`] (under the -/// daemon, and again on every hot reload) and [`run_gateway`] (`prx gateway`, -/// no daemon) — and each used to carry its own symmetric copy of this block. -/// Only the daemon copy had tests, so a change to one path silently gave the two -/// launch modes different tool surfaces. There is one body now, and -/// `both_gateway_launch_paths_publish_the_same_tool_surface` asserts the two -/// callers end up with the same tool names. -/// -/// `message_send` is registered only when Signal is configured; `sessions_spawn`, -/// `sessions_list`, `sessions_history` and `config_reload` are registered on -/// every gateway. The two session read tools share `sessions_spawn`'s own -/// active-run registry (`SessionsSpawnTool::active_runs_arc`) and the gateway's -/// memory, so they read back the runs this gateway actually started rather than -/// a registry of their own; they are also the default-exposed MCP capabilities -/// `POST /mcp/v1/tools/call` resolves against this list (V02-R7). Returns the -/// routing registry (the caller publishes it for -/// `POST /api/channels/{name}/send`) and the `sessions_spawn` tools handle, -/// which the caller must fill with the final registry once it is sealed. -#[allow(clippy::too_many_arguments)] -fn register_gateway_turn_tools( - tools_list: &mut Vec>, - config: &Config, - shared_config: &crate::config::SharedConfig, - security: &Arc, - hooks: &Arc, - _model: &str, - memory: &Arc, - provider_runtime_options: &providers::ProviderRuntimeOptions, - signal: Option<&Arc>, - whatsapp: Option<&Arc>, - linq: Option<&Arc>, - nextcloud_talk: Option<&Arc>, -) -> anyhow::Result<(Arc>>, Arc)> { - // One routing registry, keyed by `Channel::name`, shared by `message_send` - // (destination of an explicit `channel` argument) and `sessions_spawn` - // (announce/kill routing) so both address exactly the same channel set. - if shared_config.ensure_runtime_writable().is_err() { - return Ok((Arc::new(HashMap::new()), Arc::new(tools::ParentToolRegistry::default()))); - } - let mut registry: HashMap> = HashMap::new(); - if let Some(channel) = signal { - registry.insert(channel.name().to_string(), Arc::clone(channel) as Arc); - } - if let Some(channel) = whatsapp { - registry.insert(channel.name().to_string(), Arc::clone(channel) as Arc); - } - if let Some(channel) = linq { - registry.insert(channel.name().to_string(), Arc::clone(channel) as Arc); - } - if let Some(channel) = nextcloud_talk { - registry.insert(channel.name().to_string(), Arc::clone(channel) as Arc); - } - let channels_registry = Arc::new(registry); - - // `message_send` is backed by Signal when the channel is configured. Other - // channels are addressed through the routing registry above. - if let Some(signal_channel) = signal { - tools_list.push(Box::new( - tools::MessageSendTool::new_signal(Arc::clone(signal_channel), Arc::clone(security)) - .with_channels(Arc::clone(&channels_registry)), - )); - } - - // `sessions_spawn` is registered on every gateway, with or without Signal. - // The channel argument is only the fallback announce destination, so a - // missing IM channel is no reason to withhold the tool from a webhook turn. - // - // The per-turn announce/kill routing registry is the one built above: a - // webhook turn stamps its originating channel into the tool's per-turn - // scope, and the tool resolves the channel object from here at announce / - // kill time, so a result is never mis-routed under concurrent webhooks. - let spawn_tools_handle = { - let announce_channel = - gateway_spawn_announce_channel(signal.map(|channel| Arc::clone(channel) as Arc)); - let provider_name = providers::selection::default_provider(config).to_string(); - let spawn_tool = tools::SessionsSpawnTool::new( - announce_channel, - provider_name, - providers::selection::default_model(config).to_string(), - config.default_temperature, - Arc::clone(security), - config.workspace_dir.clone(), - config.multimodal.clone(), - config.agents_with_references().into_owned(), - config.api_key.clone(), - provider_runtime_options.clone(), - config.sessions_spawn.clone(), - ) - .with_configured_providers(&crate::providers::ConfiguredProviders::from_config(config)) - .with_model_catalog(providers::selection::catalog_for(config)) - .with_hint_config(config) - .with_parent_hooks(Arc::clone(hooks)) - .with_channels(Arc::clone(&channels_registry)) - .with_shared_memory(Arc::clone(memory)) - .with_event_recording(config.memory.event_recording_config()) - .with_process_recovery(true)?; - let handle = spawn_tool.tools_handle(); - - // `sessions_list` / `sessions_history` read back what `sessions_spawn` - // started, so they are bound to that tool's own run registry — the same - // `Arc` it writes to — and to the gateway's memory, exactly as the - // channel server wires them. A registry of their own would answer with - // an empty list instead of a 404, which is a worse failure than the one - // this registration fixes. Both are default-exposed MCP capabilities - // (`default_mcp_server_exposed_tools`), and without this registration - // `POST /mcp/v1/tools/call` answered 404 for a name - // `GET /mcp/v1/tools/list` advertises (V02-R7). Pushed before - // `spawn_tool` is moved into the list below. - let active_runs = spawn_tool.active_runs_arc(); - let workspace_id = config.workspace_dir.to_string_lossy().to_string(); - tools_list.push(Box::new( - tools::SessionsListTool::new(active_runs.clone()) - .with_shared_memory(Arc::clone(memory), workspace_id.clone()), - )); - tools_list.push(Box::new( - tools::SessionsSendTool::with_security(Arc::clone(&active_runs), Arc::clone(security)) - .with_shared_memory(Arc::clone(memory)) - .with_event_recording(config.memory.event_recording_config()), - )); - tools_list.push(Box::new( - tools::SessionStatusTool::new( - Arc::clone(&active_runs), - providers::selection::default_provider(config), - providers::selection::default_model(config), - channels_registry.keys().cloned().collect(), - ) - .with_shared_memory(Arc::clone(memory), workspace_id.clone()), - )); - tools_list.push(Box::new( - tools::SessionsHistoryTool::new(active_runs).with_shared_memory(Arc::clone(memory), workspace_id), - )); - - tools_list.push(Box::new(spawn_tool)); - handle - }; - - // The ConfigReloadTool and `/api/config/reload` route both submit candidates - // to the same manager; no gateway path can publish configuration directly. - tools_list.push(Box::new(tools::ConfigReloadTool::with_security( - shared_config.clone(), - Arc::clone(security), - ))); - - Ok((channels_registry, spawn_tools_handle)) -} - -/// A ready runtime of `generation`, or the error its default provider failed -/// with (test fixtures; production builds through [`build_gateway_turn_state`]). -#[cfg(test)] -#[allow(clippy::too_many_arguments)] -fn build_gateway_turn_runtime( - generation: Arc, - shared_config: crate::config::SharedConfig, - memory: Arc, - signal: Option>, - whatsapp: Option>, - linq: Option>, - nextcloud_talk: Option>, - hooks: Arc, - #[cfg(feature = "wasm-plugins")] plugin_runtime: Option>, -) -> anyhow::Result { - let config = generation.effective.as_ref(); - let chat = build_gateway_turn_provider(config, &providers::provider_runtime_options_from_config(config))?; - let state = build_gateway_turn_state( - generation, - Ok(chat), - shared_config, - memory, - signal, - whatsapp, - linq, - nextcloud_talk, - hooks, - #[cfg(feature = "wasm-plugins")] - plugin_runtime, - )?; - match state { - GatewayTurnState::Ready(generation) => { - Arc::try_unwrap(generation).map_err(|_| anyhow::anyhow!("new gateway turn runtime was unexpectedly shared")) - } - GatewayTurnState::NotReady(standby) => Err(TurnNotReady(standby.reason).into()), - } -} - -/// The runtime of `generation` around its already resolved default chat -/// connection, or a standby with the same tool surface when `chat` names -/// why there is none. The caller resolves the default before anything is -/// built, so a generation whose default model cannot chat is rejected first. -#[allow(clippy::too_many_arguments)] -fn build_gateway_turn_state( - generation: Arc, - chat: Result, - shared_config: crate::config::SharedConfig, - memory: Arc, - signal: Option>, - whatsapp: Option>, - linq: Option>, - nextcloud_talk: Option>, - hooks: Arc, - #[cfg(feature = "wasm-plugins")] plugin_runtime: Option>, -) -> anyhow::Result { - let config = generation.effective.as_ref(); - let provider_runtime_options = providers::provider_runtime_options_from_config(config); - let security = crate::runtime::bootstrap::build_security_policy(config); - let runtime: Arc = Arc::from(runtime::create_runtime(&config.runtime)?); - let (composio_key, composio_entity_id) = if config.composio.configured() { - ( - config.composio.api_key.as_deref(), - Some(config.composio.entity_id.as_str()), - ) - } else { - (None, None) - }; - let extensions = hooks.control_tool_arcs(Arc::clone(&security)); - #[cfg(feature = "wasm-plugins")] - let extensions = { - let mut extensions = extensions; - if let Some(runtime) = &plugin_runtime { - extensions.extend(runtime.control_tool_arcs(Arc::clone(&security))); - } - extensions - }; - let tools_result = tools::all_tools_with_runtime_ext_and_extensions( - Arc::clone(&generation.effective), - Arc::clone(&shared_config), - &security, - runtime, - Arc::clone(&memory), - composio_key, - composio_entity_id, - &config.browser, - &config.http_request, - &config.workspace_dir, - &config.agents_with_references(), - config.api_key.as_deref(), - config, - extensions, - Some(Arc::clone(&hooks)), - ); - let mut tools_list = tools_result.tools; - let mcp_tool = tools_result.mcp_tool; - - let (_channels_registry, spawn_tools_handle) = register_gateway_turn_tools( - &mut tools_list, - config, - &shared_config, - &security, - &hooks, - chat.as_ref().map_or("", |(_, model, _)| model.as_str()), - &memory, - &provider_runtime_options, - signal.as_ref(), - whatsapp.as_ref(), - linq.as_ref(), - nextcloud_talk.as_ref(), - )?; - let tools_registry = Arc::new(tools_list); - let _ = spawn_tools_handle.set(&tools_registry); - - let publication_slot = Arc::new(turn_source::publication_slot::GatewayPublicationSlot::new( - Arc::clone(&security), - { - #[cfg(feature = "wasm-plugins")] - { - plugin_runtime.as_ref().map_or(0, |runtime| runtime.generation_id()) - } - #[cfg(not(feature = "wasm-plugins"))] - { - 0 - } - }, - )); - Ok(turn_state_of( - chat, - publication_slot, - generation, - tools_registry, - mcp_tool, - )) -} - -/// The default chat connection of a ready generation: provider, model and -/// the binding that proves they are the resolved selection. -type GatewayTurnChat = ( - Arc, - String, - Option>, -); - -/// Assemble a ready generation, or a standby with the same surface. -fn turn_state_of( - chat: Result, - publication_slot: Arc, - config_generation: Arc, - tools_registry: Arc>>, - mcp_tool: Option>, -) -> GatewayTurnState { - match chat { - Ok((provider, model, provider_binding)) => GatewayTurnState::from(TurnRuntimeGeneration { - provider_binding, - temperature: config_generation.effective.default_temperature, - publication_slot, - config_generation, - provider, - model, - tools_registry, - mcp_tool, - }), - Err(reason) => GatewayTurnState::NotReady(TurnRuntimeStandby { - reason, - publication_slot, - config_generation, - tools_registry, - mcp_tool, - }), - } -} - -/// Build the pinned generation's default chat connection. The selected -/// provider, model and credential are resolved as one value before the exact -/// connection is constructed, including when the default names a route hint. -pub(crate) fn build_gateway_provider_selection( - config: &Config, - options: &providers::ProviderRuntimeOptions, -) -> anyhow::Result<(Arc, providers::catalog::ResolvedModel)> { - let resolved = providers::selection::check_default(config, providers::catalog::UnknownPolicy::Invocation)?; - let catalog = providers::selection::catalog_for(config); - let provider: Arc = Arc::from(providers::create_routed_provider_for( - &resolved, &catalog, config, options, - )?); - Ok((provider, resolved)) -} - -fn build_gateway_turn_provider( - config: &Config, - options: &providers::ProviderRuntimeOptions, -) -> anyhow::Result { - let (provider, resolved) = build_gateway_provider_selection(config, options)?; - let model = resolved.model().to_owned(); - let binding = Arc::new(turn_source::GatewayProviderBinding::new( - Arc::clone(&provider), - resolved, - )); - Ok((provider, model, Some(binding))) -} - -/// Run the HTTP gateway using axum with proper HTTP/1.1 compliance. -/// -/// `shared_config` is the single ConfigGeneration owner the gateway uses for all -/// authorization decisions. When the gateway runs under the daemon, the -/// daemon owns this handle and also wires it to the file-watch hot-reload manager, -/// so config.toml edits become visible at every gateway authz point. When invoked -/// directly via `prx gateway` (no daemon), `None` is passed and the gateway builds -/// its own fallback handle — in that mode only the in-gateway ConfigReloadTool / the -/// `/api/config/reload` route can update it (no file watcher). -#[allow(clippy::too_many_lines)] -pub async fn run_gateway( - host: &str, - port: u16, - config: Config, - shared_config: Option, - shutdown: CancellationToken, -) -> Result<()> { - run_gateway_inner(host, port, config, shared_config, shutdown, None).await -} -async fn run_gateway_inner( - host: &str, - port: u16, - config: Config, - shared_config: Option, - shutdown: CancellationToken, - mut producer: Option, -) -> Result<()> { - let controlled = producer.as_ref().map(|producer| producer.profile()); - if let Some(profile) = &controlled { - profile.verify(&config)?; - anyhow::ensure!(shared_config.is_none(), "controlled Gateway requires direct OS launch"); - } - let start_time = Instant::now(); - crate::health::register_component( - "gateway", - "gateway", - true, - Duration::from_mins(1), - crate::health::ComponentState::Starting, - ); - // ── Security: refuse public bind without tunnel or explicit opt-in ── - if is_public_bind(host) && config.tunnel.provider == "none" && !config.gateway.allow_public_bind { - anyhow::bail!( - "🛑 Refusing to bind to {host} — gateway would be exposed to the internet.\n\ - Fix: use --host 127.0.0.1 (default), configure a tunnel, or set\n\ - [gateway] allow_public_bind = true in config.toml (NOT recommended)." - ); - } - // ── Install owner (HOST-1a): every paired bearer acts for it. Loaded - // before the listener binds, so an unusable id file leaves no route - // answering; it is never regenerated. - let install_owner = crate::security::install_owner::load_or_create(&config.workspace_dir) - .context("gateway start-up refused: the install owner id is unusable")?; - tracing::info!(owner_id = %install_owner, "install owner id loaded"); - let addr: SocketAddr = format!("{host}:{port}").parse()?; - let listener = tokio::net::TcpListener::bind(addr).await?; - let actual_port = listener.local_addr()?.port(); - let _runtime_file = - crate::runtime::host_bootstrap::RuntimeFile::write(&config, actual_port, install_owner.as_str())?; - let display_addr = format!("{host}:{actual_port}"); - - // The chat-session mailbox is durable, and this is the one startup path - // both launch modes share (`prx gateway`, and the daemon's supervised - // gateway), so it is the only place the store has to be attached. Attaching - // replays what the previous process left queued, and is idempotent: the - // daemon's supervisor restarts the gateway inside one process, and a replay - // never duplicates a session that is still live in memory. - if let Some(path) = runtime::chat_sessions::attach_workspace_store(&config.workspace_dir) { - tracing::debug!(path = %path.display(), "chat session mailbox is durable"); - } - - #[cfg(feature = "wasm-plugins")] - let wasm_early_runtime = if config - .default_provider - .as_deref() - .is_some_and(|provider| provider.starts_with("wasm:")) - || memory::effective_memory_backend_name(&config.memory.backend, Some(&config.storage.provider.config)) - .starts_with("wasm:") - { - crate::plugins::init_plugin_runtime(&config, None).await - } else { - None - }; - let provider_runtime_options = providers::provider_runtime_options_from_config(&config); - // A default provider without a usable credential leaves the turn runtime - // standing by instead of failing the start: every management route - // serves, and a reload after the credential is stored makes it ready. - let chat = match build_gateway_turn_provider(&config, &provider_runtime_options) { - Ok(chat) => Ok(chat), - Err(error) => { - let reason = TurnNotReadyReason::of_provider_error(&error).ok_or(error)?; - tracing::warn!( - reason = reason.code(), - "Gateway turn runtime is not ready; management routes serve and turns are refused" - ); - Err(reason) - } - }; - let model = chat.as_ref().map_or_else( - |_| config.default_model.clone().unwrap_or_default(), - |(_, model, _)| model.clone(), - ); - // Test builds keep the fixture field filled; no turn reads it, since - // this state always holds its turn runtime. - #[cfg(test)] - let fixture_provider: Arc = match &chat { - Ok((provider, _, _)) => Arc::clone(provider), - Err(_) => Arc::new(tests::MockProvider::default()), - }; - let temperature = config.default_temperature; - let shared_config_for_reload = shared_config.unwrap_or_else(|| crate::config::new_shared(config.clone())); - if controlled.is_some() { - shared_config_for_reload.freeze_runtime_writes(); - } - let mem: Arc = Arc::from(memory::create_memory_with_storage( - &config.memory, - Some(&config.storage.provider.config), - &config.workspace_dir, - memory::EmbeddingRootCredential::from_config(&config), - )?); - let scrub_memory = Arc::clone(&mem); - let runtime: Arc = Arc::from(runtime::create_runtime(&config.runtime)?); - // FIX-P1-31: honour the configured `security.audit` block on the gate audit path. - // Built via the shared `build_security_policy` helper so this site cannot drift - // from (or forget) the audit-config wiring — byte-for-byte identical to the - // former local from_config + audit-config construction. - // - // This policy bootstraps static gateway gates and the initial tool registry. - // Gateway turn tools are rebuilt from one candidate ConfigGeneration and swapped - // atomically by GatewayTurnRuntimeOwner. Resource-mutation routes independently - // pin the manager's active generation at each authorization decision. - let security = crate::runtime::bootstrap::build_security_policy(&config); - // Workspace command hooks follow the live `security.workspace_hooks` - // opt-in (HOOKS-ENV). - let hooks = - Arc::new(HookManager::new(config.workspace_dir.clone()).with_config(Arc::clone(&shared_config_for_reload))); - // Kept for the shutdown drain of queued hook events. - let hooks_for_shutdown = Arc::clone(&hooks); - #[cfg(feature = "wasm-plugins")] - let wasm_plugin_runtime = if let Some(runtime) = wasm_early_runtime { - runtime - .attach_memory(Arc::clone(&mem)) - .await - .map_err(|error| anyhow::anyhow!("failed to attach WASM memory backend in gateway: {error}"))?; - Some(runtime) - } else { - crate::plugins::init_plugin_runtime(&config, Some(Arc::clone(&mem))).await - }; - - let (composio_key, composio_entity_id) = if config.composio.configured() { - ( - config.composio.api_key.as_deref(), - Some(config.composio.entity_id.as_str()), - ) - } else { - (None, None) - }; - - // Build the base tool list (mutable so we can append channel-aware tools below) - let extensions = hooks.control_tool_arcs(Arc::clone(&security)); - #[cfg(feature = "wasm-plugins")] - let extensions = { - let mut extensions = extensions; - if let Some(runtime) = &wasm_plugin_runtime { - extensions.extend(runtime.control_tool_arcs(Arc::clone(&security))); - } - extensions - }; - let tools_result = if let Some(profile) = &controlled { - tools::ToolsRegistryResult { - tools: profile.registry(&config, &security)?, - mcp_tool: None, - } - } else { - tools::all_tools_with_runtime_ext_and_extensions( - Arc::new(config.clone()), - Arc::clone(&shared_config_for_reload), - &security, - runtime, - Arc::clone(&mem), - composio_key, - composio_entity_id, - &config.browser, - &config.http_request, - &config.workspace_dir, - &config.agents_with_references(), - config.api_key.as_deref(), - &config, - extensions, - Some(Arc::clone(&hooks)), - ) - }; - let mut tools_list = tools_result.tools; - let mcp_tool = tools_result.mcp_tool; - // Generic /webhook auth can require a standalone token and/or HMAC signature. - let webhook_token_hash: Option> = config.webhook.token.as_ref().and_then(|raw_token| { - let trimmed_token = raw_token.trim(); - (!trimmed_token.is_empty()).then(|| Arc::::from(hash_webhook_secret(trimmed_token))) - }); - let webhook_signing_secret: Option> = config.channels_config.webhook.as_ref().and_then(|webhook| { - webhook.secret.as_ref().and_then(|raw_secret| { - let trimmed_secret = raw_secret.trim(); - (!trimmed_secret.is_empty()).then(|| Arc::::from(trimmed_secret.to_string())) - }) - }); - - // WhatsApp channel (if configured) - let whatsapp_channel: Option> = config - .channels_config - .whatsapp - .as_ref() - .filter(|wa| wa.is_cloud_config()) - .map(|wa| { - Arc::new(WhatsAppChannel::new( - wa.access_token.clone().unwrap_or_default(), - wa.phone_number_id.clone().unwrap_or_default(), - wa.verify_token.clone().unwrap_or_default(), - wa.allowed_numbers.clone(), - )) - }); - let signal_media_config = config.media.clone(); - let signal_channel: Option> = config.channels_config.signal.as_ref().map(|sg| { - Arc::new( - SignalChannel::new_with_mode( - sg.effective_http_url(), - sg.account.clone(), - sg.group_id.clone(), - sg.allowed_from.clone(), - sg.ignore_attachments, - sg.ignore_stories, - signal_media_config.clone(), - sg.is_native_mode(), - sg.data_dir.clone(), - sg.storm_protection.clone(), - ) - .with_artifact_owner(crate::media::MediaArtifactOwner::for_workspace(&config.workspace_dir)), - ) - }); - - // Linq channel (if configured). Built here (ahead of message_send and the spawn - // tool) so it can join the shared per-turn channel routing registry below. - let linq_channel: Option> = config.channels_config.linq.as_ref().map(|lq| { - Arc::new(LinqChannel::new( - lq.api_token.clone(), - lq.from_phone.clone(), - lq.allowed_senders.clone(), - )) - }); - - // Nextcloud Talk channel (if configured). Built here (ahead of message_send and - // the spawn tool) so it can join the shared per-turn channel routing registry. - let nextcloud_talk_channel: Option> = - config.channels_config.nextcloud_talk.as_ref().map(|nc| { - Arc::new(NextcloudTalkChannel::new( - nc.base_url.clone(), - nc.app_token.clone(), - nc.allowed_users.clone(), - )) - }); - - let (channels_registry, spawn_tools_handle) = register_gateway_turn_tools( - &mut tools_list, - &config, - &shared_config_for_reload, - &security, - &hooks, - &model, - &mem, - &provider_runtime_options, - signal_channel.as_ref(), - whatsapp_channel.as_ref(), - linq_channel.as_ref(), - nextcloud_talk_channel.as_ref(), - )?; - // The process cost outbox projector (P2-R5): started eagerly before the - // first turn and cancelled with the gateway's shutdown token. - let cost_projector = shared_config_for_reload.ensure_runtime_writable().is_ok().then(|| { - crate::runtime::cost_recovery::warn_legacy_files_once(&config.workspace_dir); - crate::runtime::cost_recovery::CostOutboxProjector::start( - Arc::clone(&mem), - config.workspace_dir.clone(), - config.cost.clone(), - &shutdown, - ) - }); - // Publish the routing registry process-wide for as long as this gateway - // runs, so `POST /api/channels/{name}/send` can address the channels the - // gateway itself constructed. The channels supervisor publishes its own - // (larger) registry alongside this one; the two are merged at lookup time. - let _outbound_publication = crate::channels::outbound_registry::publish(Arc::clone(&channels_registry)); - #[cfg(feature = "wasm-plugins")] - if let Some(runtime) = &wasm_plugin_runtime { - tracing::debug!(generation = runtime.generation_id(), "WASM plugin runtime ready"); - } - - let tools_registry = Arc::new(tools_list); - - // Inject the tools registry into sessions_spawn so sub-agents can use tools. - let _ = spawn_tools_handle.set(&tools_registry); - - // WhatsApp app secret for webhook signature verification (from config) - let whatsapp_app_secret: Option> = config - .channels_config - .whatsapp - .as_ref() - .and_then(|wa| { - wa.app_secret - .as_deref() - .map(str::trim) - .filter(|secret| !secret.is_empty()) - .map(ToOwned::to_owned) - }) - .map(Arc::from); - - // Linq signing secret for webhook signature verification (from config). - // (The `linq_channel` object itself is built earlier, ahead of the spawn tool.) - let linq_signing_secret: Option> = config - .channels_config - .linq - .as_ref() - .and_then(|lq| { - lq.signing_secret - .as_deref() - .map(str::trim) - .filter(|secret| !secret.is_empty()) - .map(ToOwned::to_owned) - }) - .map(Arc::from); - - // Nextcloud Talk webhook secret for signature verification (from config). - // (The `nextcloud_talk_channel` object is built earlier, ahead of the spawn tool.) - let nextcloud_talk_webhook_secret: Option> = config - .channels_config - .nextcloud_talk - .as_ref() - .and_then(|nc| { - nc.webhook_secret - .as_deref() - .map(str::trim) - .filter(|secret| !secret.is_empty()) - .map(ToOwned::to_owned) - }) - .map(Arc::from); - - // ── Pairing guard ────────────────────────────────────── - let pairing = Arc::new( - PairingGuard::new(config.gateway.require_pairing, &config.gateway.paired_tokens) - .with_install_owner(install_owner), - ); - let rate_limit_max_keys = normalize_max_keys(config.gateway.rate_limit_max_keys, RATE_LIMIT_MAX_KEYS_DEFAULT); - let rate_limiter = Arc::new(GatewayRateLimiter::new( - config.gateway.pair_rate_limit_per_minute, - config.gateway.webhook_rate_limit_per_minute, - config.gateway.api_rate_limit_per_minute, - rate_limit_max_keys, - )); - let idempotency_max_keys = normalize_max_keys(config.gateway.idempotency_max_keys, IDEMPOTENCY_MAX_KEYS_DEFAULT); - let idempotency_store = Arc::new(IdempotencyStore::new( - Duration::from_secs(config.gateway.idempotency_ttl_secs.max(1)), - idempotency_max_keys, - )); - - // ── Tunnel ──────────────────────────────────────────────── - let tunnel = crate::tunnel::create_tunnel(&config.tunnel)?; - let mut tunnel_url: Option = None; - - if let Some(ref tun) = tunnel { - println!("🔗 Starting {} tunnel...", tun.name()); - match tun.start(host, actual_port).await { - Ok(url) => { - println!("🌐 Tunnel active: {url}"); - tunnel_url = Some(url); - } - Err(e) => { - println!("⚠️ Tunnel failed to start: {e}"); - println!(" Falling back to local-only mode."); - } - } - } - - println!("🦀 OpenPRX Gateway listening on http://{display_addr}"); - if let Some(ref url) = tunnel_url { - println!(" 🌐 Public URL: {url}"); - } - println!(" POST /pair — pair a new client (X-Pairing-Code header)"); - println!(" POST /webhook — {{\"message\": \"your prompt\"}}"); - if whatsapp_channel.is_some() { - println!(" GET /whatsapp — Meta webhook verification"); - println!(" POST /whatsapp — WhatsApp message webhook"); - } - if linq_channel.is_some() { - println!(" POST /linq — Linq message webhook (iMessage/RCS/SMS)"); - } - if nextcloud_talk_channel.is_some() { - println!(" POST /nextcloud-talk — Nextcloud Talk bot webhook"); - } - println!(" GET /health — health check"); - println!(" GET /metrics — Prometheus metrics"); - if let Some(code) = pairing.pairing_code() { - println!(); - println!(" 🔐 PAIRING REQUIRED — use this one-time code:"); - println!(" ┌──────────────┐"); - println!(" │ {code} │"); - println!(" └──────────────┘"); - println!(" Send: POST /pair with header X-Pairing-Code: {code}"); - } else if pairing.require_pairing() { - println!(" 🔒 Pairing: ACTIVE (bearer token required)"); - } else { - println!(" ⚠️ Pairing: DISABLED (all requests accepted)"); - } - println!(" Press Ctrl+C to stop.\n"); - - // Build shared state - let observer: Arc = - Arc::from(crate::observability::create_observer(&config.observability)); - let (logs_broadcast_tx, _) = broadcast::channel(1024); - // The startup registry and MCP tool move into the turn runtime: nothing - // else keeps them, so the first configuration change releases them and - // their stdio MCP children (D-098 F-1). - let turn_runtime_owner = start_gateway_turn_runtime( - turn_state_of( - chat, - Arc::new( - turn_source::publication_slot::GatewayPublicationSlot::new(Arc::clone(&security), { - #[cfg(feature = "wasm-plugins")] - { - wasm_plugin_runtime - .as_ref() - .map_or(0, |runtime| runtime.generation_id()) - } - #[cfg(not(feature = "wasm-plugins"))] - { - 0 - } - }) - .with_controlled(controlled.clone()), - ), - shared_config_for_reload.pin(), - tools_registry, - mcp_tool, - ), - &shared_config_for_reload, - Arc::clone(&mem), - signal_channel.clone(), - whatsapp_channel.clone(), - linq_channel.clone(), - nextcloud_talk_channel.clone(), - Arc::clone(&hooks), - #[cfg(feature = "wasm-plugins")] - wasm_plugin_runtime.clone(), - )?; - shared_config_for_reload.register_audit_sink(Arc::new(ConfigGenerationMessageAuditSink { - memory: Arc::clone(&mem), - workspace_id: config.workspace_dir.to_string_lossy().to_string(), - runtime_handle: tokio::runtime::Handle::current(), - })); - - let state = AppState { - rf_streams: Default::default(), - rf_approvals: Default::default(), - config: Arc::clone(&shared_config_for_reload), - #[cfg(test)] - provider: fixture_provider, - model, - temperature, - mem, - auto_save: config.memory.auto_save && config.memory.semantic.auto_promote_user_messages, - // Test fixtures only; this state serves every turn from `turn_runtime`. - #[cfg(test)] - tools_registry: Arc::new(Vec::new()), - #[cfg(test)] - mcp_tool: None, - turn_runtime: Some(Arc::clone(&turn_runtime_owner)), - hooks, - webhook_token_hash, - webhook_signing_secret, - pairing, - trust_forwarded_headers: config.gateway.trust_forwarded_headers, - rate_limiter, - idempotency_store, - whatsapp: whatsapp_channel, - signal: signal_channel, - whatsapp_app_secret, - linq: linq_channel, - linq_signing_secret, - nextcloud_talk: nextcloud_talk_channel, - nextcloud_talk_webhook_secret, - observer, - start_time, - gateway_port: actual_port, - logs_broadcast_tx, - #[cfg(feature = "wasm-plugins")] - plugin_runtime: wasm_plugin_runtime, - }; - - // HookManager resolves hooks and event delivery from this same generation owner. - #[cfg(feature = "wasm-plugins")] - if let Some(ref runtime) = state.plugin_runtime { - state.hooks.set_plugin_runtime(Arc::clone(runtime)).await; - } - - if controlled.is_some() { - let producer = producer - .take() - .ok_or_else(|| anyhow::anyhow!("local control producer missing"))?; - h2_control::start_local_control(producer, shutdown.clone())?; - } - let limited_public_routes = Router::new() - .route("/pair", post(handle_pair)) - .route("/webhook", post(handle_webhook)) - .route("/whatsapp", get(handle_whatsapp_verify)) - .route("/whatsapp", post(handle_whatsapp_message)) - .route("/linq", post(handle_linq_webhook)) - .route("/nextcloud-talk", post(handle_nextcloud_talk_webhook)) - .layer(RequestBodyLimitLayer::new(MAX_BODY_SIZE)); - - api::sync_startup::startup(&state, &shutdown).await?; - let api_routes = api::router(state.clone()).layer(RequestBodyLimitLayer::new(MAX_API_BODY_SIZE)); - - // Build router with middleware - let app = Router::new() - .route("/health", get(handle_health)) - .route("/metrics", get(handle_metrics)) - .route( - "/mcp/v1/initialize", - get(compat::mcp_initialize).post(compat::mcp_initialize), - ) - .route( - "/mcp/v1/list_servers", - get(compat::mcp_list_servers).post(compat::mcp_list_servers), - ) - .route( - "/mcp/v1/tools/list", - get(compat::mcp_tools_list).post(compat::mcp_tools_list), - ) - .route("/mcp/v1/tools/call", post(compat::mcp_tools_call)) - .route("/a2a/v1/identity", get(compat::a2a_identity).post(compat::a2a_identity)) - .route("/a2a/v1/discover", get(compat::a2a_discover).post(compat::a2a_discover)) - .route("/.well-known/agent.json", get(compat::well_known_agent_json)) - .route("/a2a/v1/.well-known/jwks.json", get(compat::a2a_jwks)) - .merge(limited_public_routes) - .nest("/api", api_routes) - .merge(ui::router()) - .with_state(state) - .layer(axum::middleware::from_fn( - move |request: axum::extract::Request, next: axum::middleware::Next| { - let controlled = controlled.clone(); - async move { - if let Some(profile) = controlled { - if profile.ensure_live().is_err() - || !crate::runtime::h2_entry::ControlledH2Profile::permits_route( - request.method().as_str(), - request.uri().path(), - ) - { - return ( - StatusCode::FORBIDDEN, - "route is outside the fixed controlled Gateway profile", - ) - .into_response(); - } - } - next.run(request).await - } - }, - )); - - // The listener is bound and every route/state dependency is now constructed. - // This explicit acknowledgement, rather than supervisor task survival, is the - // gateway readiness boundary. - crate::health::mark_component_ok("gateway"); - - // A quiet listener is still a live listener. Refresh gateway health from an - // owner-controlled heartbeat rather than relying on `/health` requests to - // keep the required component fresh. - let health_shutdown = CancellationToken::new(); - let health_heartbeat = tokio::spawn(run_health_heartbeat( - "gateway", - GATEWAY_HEALTH_HEARTBEAT_INTERVAL, - health_shutdown.clone(), - )); - - // Run the server with graceful shutdown (D5/D9 step 3, DEV-02). On root token - // cancellation axum stops accepting and drains in-flight requests. The drain - // bound must only start counting *after* shutdown is requested — never while - // the server is idle — otherwise the gateway would self-exit after the timeout - // on a quiet listener. We therefore arm the bounded timer inside a select! arm - // gated on `shutdown.cancelled()`, so the timeout window opens only post-shutdown. - let drain_deadline = shutdown.clone(); - let serve_fut = axum::serve(listener, app.into_make_service_with_connect_info::()) - .with_graceful_shutdown(async move { shutdown.cancelled().await }) - .into_future(); - tokio::pin!(serve_fut); - let serve_result = tokio::select! { - res = &mut serve_fut => res, - _ = async { - drain_deadline.cancelled().await; - tokio::time::sleep(GATEWAY_GRACEFUL_TIMEOUT).await; - } => { - tracing::warn!( - timeout_secs = GATEWAY_GRACEFUL_TIMEOUT.as_secs(), - "gateway graceful shutdown timed out; forcing exit" - ); - Ok(()) - } - }; - - let decision_cleanup_result = turn_runtime_owner - .cleanup - .drain(tokio::time::Instant::now() + Duration::from_secs(15)) - .await; - hooks_for_shutdown.drain_for_shutdown().await; - if let Some(projector) = cost_projector { - projector.stop().await; - } - // AC-1b2b: a clean stop leaves no deleted rf content in the WAL. - match scrub_memory.scrub_deleted_wal().await { - Ok(true) => {} - Ok(false) => { - tracing::warn!("deleted rf content stays in brain.db-wal at stop; it is scrubbed at the next open") - } - Err(error) => tracing::warn!( - error = %crate::agent::diagnostics::error_class(&error), - "deleted rf content WAL scrub failed at stop" - ), - } - health_shutdown.cancel(); - let _ = health_heartbeat.await; - serve_result?; - decision_cleanup_result?; - - crate::health::mark_component_stopping("gateway"); - crate::health::mark_component_stopped("gateway"); - Ok(()) -} - -// ══════════════════════════════════════════════════════════════════════════════ -// AXUM HANDLERS -// ══════════════════════════════════════════════════════════════════════════════ - -/// GET /health — always public (no secrets leaked) -async fn handle_health(State(state): State) -> impl IntoResponse { - // A successfully dispatched health request is also an explicit freshness - // acknowledgement from the gateway owner. - crate::health::mark_component_ok("gateway"); - let runtime = crate::health::snapshot(); - health_response(state.pairing.is_paired(), runtime) -} - -fn health_response(paired: bool, runtime: crate::health::HealthSnapshot) -> (StatusCode, Json) { - let readiness = crate::health::readiness_from_snapshot(&runtime); - let status = if readiness.ready { - StatusCode::OK - } else { - StatusCode::SERVICE_UNAVAILABLE - }; - let body = serde_json::json!({ - "status": readiness.status, - "paired": paired, - "readiness": readiness, - "runtime": runtime, - }); - (status, Json(body)) -} - -/// Prometheus content type for text exposition format. -const PROMETHEUS_CONTENT_TYPE: &str = "text/plain; version=0.0.4; charset=utf-8"; - -/// GET /metrics — Prometheus text exposition format -async fn handle_metrics(State(state): State) -> impl IntoResponse { - // Merge the PrometheusObserver's main registry with the separate - // chat_metrics registry (S2.5 P1-A). The four chat counters live in a - // registry that is physically isolated from the observer, so they have to - // be merged explicitly or a scrape never sees them. - let chat_reg = crate::observability::chat_metrics::chat_registry(); - let body = state - .observer - .as_ref() - .as_any() - .downcast_ref::() - .map_or_else( - || { - // The chat metrics still have to be exposed when the observer is not Prometheus. - format!( - "# Prometheus backend not enabled. Set [observability] backend = \"prometheus\" in config.\n{}", - crate::observability::prometheus::encode_registries(&[chat_reg]) - ) - }, - |prom| prom.encode_with_extras(&[chat_reg]), - ); - - (StatusCode::OK, [(header::CONTENT_TYPE, PROMETHEUS_CONTENT_TYPE)], body) -} - -/// POST /pair — exchange one-time code for bearer token -#[axum::debug_handler] -async fn handle_pair( - State(state): State, - ConnectInfo(peer_addr): ConnectInfo, - headers: HeaderMap, -) -> impl IntoResponse { - let rate_key = client_key_from_request(Some(peer_addr), &headers, state.trust_forwarded_headers); - if !state.rate_limiter.allow_pair(&rate_key) { - tracing::warn!("/pair rate limit exceeded"); - let err = serde_json::json!({ - "error": "Too many pairing requests. Please retry later.", - "retry_after": RATE_LIMIT_WINDOW_SECS, - }); - return (StatusCode::TOO_MANY_REQUESTS, Json(err)); - } - - let code = headers - .get("X-Pairing-Code") - .and_then(|v| v.to_str().ok()) - .unwrap_or(""); - - if let Err(error) = authorize_gateway_resource_mutation(&state, "gateway:pair", ResourceRiskLevel::Low) { - return error; - } - - match state.pairing.try_pair(code, &rate_key).await { - Ok(Some(token)) => { - tracing::info!("🔐 New client paired successfully"); - if let Err(err) = persist_pairing_tokens(&state.config, &state.pairing).await { - tracing::error!(error = %crate::security::redaction::redact_provider_text(&format!("{err:#}")), "🔐 Pairing succeeded but token persistence failed"); - let body = serde_json::json!({ - "paired": true, - "persisted": false, - "token": token, - "message": "Paired for this process, but failed to persist token to config.toml. Check config path and write permissions.", - }); - return (StatusCode::OK, Json(body)); - } - - let body = serde_json::json!({ - "paired": true, - "persisted": true, - "token": token, - "message": "Save this token — use it as Authorization: Bearer " - }); - (StatusCode::OK, Json(body)) - } - Ok(None) => { - tracing::warn!("🔐 Pairing attempt with invalid code"); - let err = serde_json::json!({"error": "Invalid pairing code"}); - (StatusCode::FORBIDDEN, Json(err)) - } - Err(lockout_secs) => { - tracing::warn!("🔐 Pairing locked out — too many failed attempts ({lockout_secs}s remaining)"); - let err = serde_json::json!({ - "error": format!("Too many failed attempts. Try again in {lockout_secs}s."), - "retry_after": lockout_secs - }); - (StatusCode::TOO_MANY_REQUESTS, Json(err)) - } - } -} - -/// Add what pairing learned to the configured list, **without rewriting the -/// entries an operator authored**. -/// -/// Persistence used to assign `pairing.tokens()` over the whole list, which -/// treated the in-memory set as authoritative over the file. It is not: -/// `gateway.paired_tokens` is a restart-only field, so between startup and the -/// next restart the file can legitimately hold entries the running guard never -/// loaded, and it can hold them in a *spelling* the guard cannot reproduce. -/// Both were destroyed silently. -/// -/// The spelling matters because [`PairingGuard`] stores only hashes: a -/// plaintext entry is hashed on load, so `tokens()` returns a hash for it and -/// the assignment wrote that hash back in its place. The token stays valid as a -/// bearer either way — but chat's `/sessions --daemon` takes its credential out -/// of this list and deliberately skips hashes (a stored hash, re-hashed by the -/// gateway on receipt, authenticates as nothing), so the entry it was reading -/// would have become useless to it with no edit by anyone and nothing in the -/// file to show what changed. -/// -/// That particular sequence turns out not to be reachable through `/pair`: -/// a pairing code is minted only when the token set is *empty*, so a config -/// that already carries a plaintext entry can never complete a pairing. What is -/// reachable is the same destruction one step earlier — an operator adds an -/// entry by hand while the gateway is up and a still-live code is later -/// redeemed, and the entry is dropped from disk outright rather than merely -/// rehashed. -/// -/// So nothing is rewritten or removed here. Every non-empty configured entry is -/// kept, in order and as written, and a live hash is appended only when no -/// configured entry already names that token. Revocation is not a thing this -/// gateway has, so there is nothing this would wrongly resurrect. -/// -/// This never puts a *generated* token into the file in plaintext: `/pair` -/// hands that to the client once and persists only its hash, unchanged. The -/// only plaintext preserved is plaintext the operator wrote themselves. -/// -/// MUTATION GUARD: assign `pairing.tokens()` wholesale again and -/// `a_configured_token_survives_a_later_pairing` fails. -fn merge_paired_tokens(configured: &[String], live: &[String]) -> Vec { - let mut merged: Vec = Vec::with_capacity(configured.len().saturating_add(live.len())); - let mut covered: HashSet = HashSet::new(); - for entry in configured { - let trimmed = entry.trim(); - if trimmed.is_empty() { - continue; - } - // Compared by hash, kept by spelling: a plaintext entry and the hash - // pairing holds for it are the same credential, and the operator's - // spelling is the one that stays. - let hash = if crate::security::pairing::is_token_hash(trimmed) { - trimmed.to_string() - } else { - crate::security::pairing::hash_token(trimmed) - }; - if covered.insert(hash) { - merged.push(trimmed.to_string()); - } - } - for token in live { - if covered.insert(token.clone()) { - merged.push(token.clone()); - } - } - merged -} - -async fn persist_pairing_tokens(config: &crate::config::SharedConfig, pairing: &PairingGuard) -> Result<()> { - let paired_tokens = pairing.tokens(); - let mut updated_cfg = (*config.desired().config).clone(); - updated_cfg.gateway.paired_tokens = merge_paired_tokens(&updated_cfg.gateway.paired_tokens, &paired_tokens); - updated_cfg - .save() - .await - .context("Failed to persist paired tokens to config.toml")?; - let manager = Arc::clone(config); - crate::runtime::blocking::spawn_blocking(move || { - manager.reload_from_disk(crate::config::ConfigReloadTrigger::PairingPersistence) - }) - .await - .context("Pairing config reload worker failed")??; - Ok(()) -} - -/// Build the turn-root spawn context for one gateway/webhook turn. -/// -/// Two things travel down from here into every sub-agent this turn starts: -/// -/// * `run_id` — the turn's own id becomes the child's `parent_run_id`, so a -/// webhook-launched run is attached to the turn that asked for it instead of -/// floating as a root. -/// * `channel_excluded_tools` — the names the turn's own surface hides. The -/// gateway is not an IM channel and has no `channel_exclude` list: it publishes -/// `tool_tiering` as configured, not `for_channel_surface()`. So the boundary a -/// child inherits here is exactly `always_exclude`: the child's surface is the -/// gateway's own surface minus the names the operator hid from the gateway, and -/// `spawn` is not a way to get one of them back. `always_include` is untouched, -/// exactly as on the channel path. -fn gateway_turn_spawn_context( - run_id: String, - fabric_ctx: &GatewayFabricContext, - tiering: &crate::config::ToolTieringConfig, -) -> crate::tools::sessions_spawn::SpawnExecutionContext { - crate::tools::sessions_spawn::SpawnExecutionContext::seed_turn_context( - run_id, - format!( - "{}:{}:{}", - fabric_ctx.channel, fabric_ctx.session_key, fabric_ctx.sender - ), - ) - .with_channel_excluded_tools(tiering.always_exclude.clone()) -} - -/// Run `inner` as the webhook turn itself: seeded with this turn's spawn -/// boundary, so anything it spawns inherits the gateway's own surface. -/// -/// This is the production seam. `gateway_turn_spawn_context` only builds the -/// context; nothing enforced that the value actually reached the tool loop, so -/// emptying the list at the call site (or shadowing the binding) left every -/// test green while `sessions_spawn` handed a child the tools the operator hid -/// from the gateway. Binding construction and scoping together here gives that -/// wiring one place to be tested, and -/// `the_gateway_webhook_turn_seeds_its_spawn_boundary` in `tests/architecture_boundaries/` -/// pins that `run_gateway_chat_with_multimodal` still goes through it. -async fn within_gateway_turn_spawn_context( - run_id: String, - fabric_ctx: &GatewayFabricContext, - tiering: &crate::config::ToolTieringConfig, - inner: F, -) -> F::Output -where - F: std::future::Future, -{ - let turn_spawn_ctx = gateway_turn_spawn_context(run_id, fabric_ctx, tiering); - crate::tools::sessions_spawn::SPAWN_EXECUTION_CONTEXT - .scope(turn_spawn_ctx, inner) - .await -} - -struct GatewayTurnResult { - response: String, - replay_unavailable: Option, -} - -async fn run_gateway_chat_with_multimodal( - state: &AppState, - provider_label: &str, - message: &str, - fabric_ctx: &GatewayFabricContext, - autosave_key: Option<&str>, - stage: &mut TurnFailureClass, -) -> anyhow::Result { - // `stage` names the step that runs next, so a returned error is reported - // by the step that failed and never by its text. - *stage = TurnFailureClass::TurnNotReady; - // The webhook routes admitted this turn; a typed refusal here only - // covers a job that outlived its admission check. - let turn_runtime = state.admit_turn_runtime()?; - *stage = TurnFailureClass::ProviderBinding; - turn_runtime - .provider_binding - .as_ref() - .ok_or_else(|| anyhow::anyhow!("gateway provider binding is missing"))? - .verify(&turn_runtime)?; - let provider_label = turn_runtime - .provider_binding - .as_ref() - .map_or(provider_label, |binding| binding.provider_name()); - let config_generation = Arc::clone(&turn_runtime.config_generation); - let config_snapshot = Arc::clone(&config_generation.effective); - let workspace_id = config_generation.effective.workspace_dir.to_string_lossy().to_string(); - let event_recording = config_generation.effective.memory.event_recording_config(); - let fabric = MemoryFabric::new(state.mem.clone(), workspace_id.clone()).with_event_recording(event_recording); - let run_id = Uuid::new_v4().to_string(); - // D4 C4: migrate the gateway fabric durable session_key to the recipient-aware - // canonical (`gateway:{channel}:{sender}:{recipient}`) while carrying the - // pre-cutover legacy key (`gateway:webhook:{target}` / `gateway:{ch}:{sender}`) - // for read-merge, so existing legacy history stays visible under the new key. - let webhook_owner_id = fabric_ctx.webhook_owner_id(&workspace_id); - // D-025: a `/webhook` turn's durable key is its credential-qualified - // `gateway:webhook:{credential}:{reply_target}` itself, with no legacy key: - // history under the old `gateway:webhook:{reply_target}` key cannot be - // attributed to a credential, so it is neither migrated nor read-merged, and - // continuity restarts once. Platform channel messages keep the canonical - // key and their legacy read-merge. - let (canonical_session_key, legacy_session_key) = if fabric_ctx.credential.is_some() { - (fabric_ctx.session_key.clone(), None) - } else { - let legacy_session_key = fabric_ctx.session_key.clone(); - let canonical_session_key = RuntimeEnvelope::gateway( - workspace_id.clone(), - legacy_session_key.clone(), - fabric_ctx.channel.clone(), - fabric_ctx.sender.clone(), - fabric_ctx.recipient.clone(), - MemoryVisibility::Session, - ) - .canonical_session_key(); - (canonical_session_key, Some(legacy_session_key)) - }; - let runtime_envelope = RuntimeEnvelope::gateway( - workspace_id, - canonical_session_key, - fabric_ctx.channel.clone(), - fabric_ctx.sender.clone(), - fabric_ctx.recipient.clone(), - // FIX-P1-04: webhook-driven gateway turns are session-scoped by default. - // Persisting them as workspace-visible would leak per-session conversation - // content to the whole workspace; Session keeps it bound to this session. - MemoryVisibility::Session, - ) - .with_run_id(run_id) - .with_config_generation(&config_generation); - let runtime_envelope = match legacy_session_key { - Some(legacy_session_key) => runtime_envelope.with_legacy_session_key(legacy_session_key), - None => runtime_envelope, - }; - let runtime_envelope = match webhook_owner_id.as_deref() { - Some(owner_id) => runtime_envelope.with_owner_id(owner_id), - None => runtime_envelope, - }; - *stage = TurnFailureClass::ReplayLookup; - if fabric.records_recovery_terminal() { - if let Some(key) = fabric_ctx.idempotency_key.as_deref() { - if let Some(unavailable) = crate::agent::terminal::oversized_reply::for_input( - fabric.memory(), - fabric.workspace_id(), - &runtime_envelope.message_scope(), - key, - message, - ) - .await? - { - return Err(unavailable.into()); - } - } - } - *stage = TurnFailureClass::ResourceDenied; - authorize_gateway_config_resource_mutation( - &config_snapshot, - "gateway:webhook:message_event:user", - ResourceRiskLevel::Low, - ) - .map_err(|(_, body)| { - let error = body - .0 - .get("error") - .and_then(|value| value.as_str()) - .unwrap_or("gateway resource mutation denied") - .to_string(); - anyhow::anyhow!(error) - })?; - let cancellation = jobs::current_cancellation().map_or_else(CancellationToken::new, |token| token.child_token()); - let _turn_cancel_guard = cancellation.clone().drop_guard(); - *stage = TurnFailureClass::InputRecord; - let pending_input = turn_source::GatewayPendingInput { - generation: Arc::clone(&config_generation), - fabric: fabric.clone(), - envelope: runtime_envelope, - // Arguments evaluate in order: a refused registration returns before - // any acknowledgement exists, and the owner holds both from here on. - owner: turn_source::PreInputOwner::new( - turn_runtime.publication_slot.cleanup.register(cancellation.clone())?, - jobs::register_terminal_cleanup(), - ), - }; - let (source_receipt, gateway_user_event, mut admission_guard) = pending_input - .record(message.to_owned(), fabric_ctx.idempotency_key.clone()) - .await?; - let runtime_envelope = source_receipt.envelope().clone(); - let base_scope = runtime_envelope.message_scope(); - *stage = TurnFailureClass::SourceBinding; - let gateway_proof = source_receipt.bind(&turn_runtime, fabric_ctx)?; - if let Some(key) = autosave_key { - let write_scope = runtime_envelope.memory_write_context(if fabric_ctx.channel == "webhook" { - "webhook" - } else { - "private" - }); - let _ = state - .mem - .store_with_context_and_metadata( - key, - message, - MemoryCategory::Conversation, - None, - Some(&write_scope), - crate::memory::MemoryStoreMetadata { - workspace_id: Some(runtime_envelope.workspace_id.clone()), - owner_id: Some(runtime_envelope.resolved_owner_id()), - source_event_id: runtime_envelope.source_message_event_id.clone(), - source: Some("semantic_promotion".into()), - channel: Some(fabric_ctx.channel.clone()), - ..Default::default() - }, - ) - .await; - } - // A spawned webhook job cannot inherit the caller's cleanup task-local. - // Prediction and later work must retain the same concrete cleanup owner. - *stage = TurnFailureClass::DecisionAdmission; - let child_cleanup = match crate::runtime::turn_cleanup::CleanupScope::new( - Some(&turn_runtime.publication_slot.cleanup), - cancellation.clone(), - ) { - Ok(scope) => scope.with_acknowledgement(jobs::register_terminal_cleanup()), - Err(error) => { - if let Err(record_error) = admission_guard - .finish_failure( - cancellation.is_cancelled(), - &format!("decision cleanup admission failed: {error}"), - ) - .await - { - return Err(error.context(format!( - "Gateway admission failure persistence is unconfirmed: {record_error}" - ))); - } - return Err(error); - } - }; - let admission = child_cleanup - .scope_admission(Box::pin(async { - let service = turn_runtime.publication_slot.publish(&turn_runtime, state).await?; - let context = service - .open_issued_turn_context( - &gateway_proof, - crate::runtime::turn_context::AgentTurnKind::SingleShot, - &cancellation, - ) - .await?; - Ok::<_, anyhow::Error>((service, context)) - })) - .await; - let (service, context) = match admission { - Ok(admitted) => admitted, - Err(error) => { - // Admission is no longer polled. Settle its owned accounting work - // before acknowledging the persisted input's failure. - let admission_error = format!("{error:#}"); - let error = match child_cleanup.run(Box::pin(async { Err::<(), _>(error) })).await { - Err(error) if error.is::() => { - let context = format!( - "decision admission failed: {admission_error}; Gateway admission cleanup is unconfirmed: {error:#}" - ); - error.context(context) - } - Err(error) => error, - Ok(()) => anyhow::anyhow!(admission_error), - }; - if let Err(record_error) = admission_guard - .finish_failure( - cancellation.is_cancelled(), - &format!("decision admission failed: {error}"), - ) - .await - { - return Err(error.context(format!( - "Gateway admission failure persistence is unconfirmed: {record_error}" - ))); - } - return Err(error); - } - }; - // Bind before the handoff: a refusal here still has the admission guard - // to record the failed input and answer the job monitor. - *stage = TurnFailureClass::TerminalBinding; - let terminal_binding = service.terminal_binding(&context)?; - let (cleanup_ticket, admission_acknowledgement) = admission_guard.into_terminal_parts()?; - let terminal_guard = turn_source::publication_slot::GatewayTerminalGuard::new( - cleanup_ticket, - Arc::clone(service), - Arc::clone(&context), - fabric.clone(), - Arc::clone(&config_snapshot), - runtime_envelope.clone(), - admission_acknowledgement, - )?; - *stage = TurnFailureClass::TurnPreparation; - let turn_result: anyhow::Result = child_cleanup - .run(async { - let mem_context = crate::agent::context_recall::scoped_recall( - state.mem.as_ref(), - &crate::agent::context_recall::RecallScope::from_envelope( - &runtime_envelope, - &config_snapshot.memory, - if fabric_ctx.channel == "webhook" { - "webhook" - } else { - "private" - }, - ) - .with_current_input_key(autosave_key.map(str::to_owned)), - message, - crate::agent::context_recall::RECALL_CONTEXT_BUDGET, - ) - .await; - let enriched_message = if mem_context.preamble.is_empty() { - message.to_string() - } else { - format!("{}{}", mem_context.preamble, message) - }; - - let user_messages = vec![crate::agent::turn_contracts::inbound_user_message(&enriched_message)]; - let image_marker_count = crate::multimodal::count_image_markers(&user_messages); - let adapter_capabilities = turn_runtime.provider.capabilities_for( - &turn_runtime.model, - crate::providers::traits::ProviderRequestMode::NonStreaming, - ); - let mode_capabilities = providers::selection::catalog_for(&config_snapshot) - .effective_provider_capabilities(provider_label, &turn_runtime.model, adapter_capabilities); - if image_marker_count > 0 && !mode_capabilities.vision { - return Err(ProviderCapabilityError { - provider: providers::redact_endpoint_userinfo(provider_label).into_owned(), - capability: "vision".to_string(), - message: format!( - "received {image_marker_count} image marker(s), but this provider does not support vision input" - ), - } - .into()); - } - - // Build system prompt with native_tools flag so the prompt instructs the - // LLM to use tools rather than emit XML tags. - let multimodal_config = config_snapshot.multimodal.clone(); - let native_tools = mode_capabilities.native_tool_calling; - let selected_skills = service.agent_prompt_skills(&gateway_proof, &context)?; - // The runtime prompt wrapper owns the whole prompt policy — the - // `skill_read` gate on the skill list and the `[agent] compact_context` - // bootstrap cap — so the webhook builds its prompt exactly as CLI, chat and - // Console sessions do. It used to call the canonical builder directly with - // a hardcoded `bootstrap_max_chars = None` (E3, webhook half). - let system_prompt = crate::agent::runtime_prompt::build_runtime_system_prompt( - &config_snapshot, - &turn_runtime.model, - &selected_skills, - native_tools, - ); - - let mut history = Vec::with_capacity(2 + user_messages.len()); - history.push(ChatMessage::system(system_prompt)); - history.extend(user_messages); - - let noop_observer = NoopObserver; - - // P1-a: route the webhook agent loop through the unified `SecurityPolicy::decide` - // gate instead of leaving `scope_ctx = None` (which short-circuits to `Allow` - // and bypasses both the scope ACL and the autonomy level entirely). - // - // Webhook turns are Bearer-token authenticated (`handle_webhook` rejects - // unauthenticated requests), so the request is a trusted principal and we can - // construct a `ScopeContext` from the gateway identity. This makes every tool - // call honour the configured autonomy level: under `supervised`, side-effecting - // tools resolve to `Ask`, and with no `ApprovalManager` wired on this path the - // tool loop fail-closes (deny) — only genuinely read-only tools run. Under - // `full` autonomy the behaviour is unchanged (everything allowed). - let gateway_policy = - crate::security::SecurityPolicy::from_config(&config_snapshot.autonomy, &config_snapshot.workspace_dir); - let gateway_scope_ctx = crate::agent::turn_contracts::ScopeContext { - policy: &gateway_policy, - sender: fabric_ctx.sender.as_str(), - channel: fabric_ctx.channel.as_str(), - // Gateway/webhook turns are 1:1 (no group semantics); use a stable - // chat_type so scope rules can target the gateway surface. - chat_type: "gateway", - chat_id: fabric_ctx.session_key.as_str(), - session_key: Some(runtime_envelope.session_key.as_str()), - // R-MCPB F-2: the credential-bound owner, so run views and owner-scoped - // rows follow the authenticated caller rather than its `reply_target`. - owner_id: webhook_owner_id.as_deref(), - owner_isolated: runtime_envelope.owner_isolated, - topic_id: None, - task_id: None, - source_message_event_id: None, - config_generation_id: runtime_envelope.config_generation_id, - config_source_revision: runtime_envelope.config_source_revision.as_deref(), - }; - - // OQ-23: the webhook turn runs the same bounded-request contract as every - // other execution surface — pre-turn flush/paging, the preflight before - // each provider call (with the published tool schemas reserved) and the - // reserved mid-turn trim. The window is the *effective* one, which applies - // the operator/discovery/catalog limits of the model this turn actually serves, as the - // CLI and TUI do. - let mut effective_compaction = service.effective_compaction(provider_label, &turn_runtime.model); - effective_compaction.config = context.main_compaction().clone(); - crate::providers::context_window::trace_effective_compaction_resolution(&effective_compaction); - - *stage = TurnFailureClass::TurnLoop; - let provider_started_at = chrono::Utc::now(); - let route_decision = crate::llm::route_decision::RouteDecision::single_candidate_for_context( - provider_label, - turn_runtime.model.clone(), - runtime_envelope.resolved_owner_id(), - runtime_envelope.session_key.clone(), - runtime_envelope.source_message_event_id.clone(), - None, - "gateway_webhook", - u32::try_from(message.chars().count() / 4).unwrap_or(u32::MAX), - !turn_runtime.tools_registry.is_empty(), - false, - ); - // R3: name this turn's real origin before any tool runs. The gateway owns no - // channel of its own — `message_send` falls back to whichever handle the - // daemon registered — so without this every webhook turn's outbound scope - // reads as that handle's channel and a rule written for the surface the - // message actually came from can never match. Reply routing is untouched; - // only rule matching changes. - // - // G2: the same turn also seeds the spawn execution context. A sub-agent the - // webhook turn starts inherits (a) this turn's run_id as its parent, and (b) - // the gateway surface's own hidden tool names. The gateway is not an IM - // channel, so it has no `channel_exclude` list of its own: it publishes - // `config_snapshot.tool_tiering` rather than `for_channel_surface()`. The - // boundary a child must therefore inherit is exactly `always_exclude` — the - // gateway's own tool set minus what the operator hid from it — so a spawn can - // never be a way to get back a tool the gateway itself may not call. - let loop_result = within_gateway_turn_spawn_context( - runtime_envelope - .run_id - .clone() - .unwrap_or_else(|| Uuid::new_v4().to_string()), - fabric_ctx, - &config_snapshot.tool_tiering, - crate::tools::message_send::with_outbound_origin_channel(fabric_ctx.channel.as_str(), async { - run_turn( - &mut history, - crate::agent::turn_request::TurnRequest { - advice: service.advisory().analyze_turn(context.runtime(), &cancellation).await, - // no approval manager - channel_name: "webhook", - // no streaming delta sender - scope: Some(&gateway_scope_ctx), - mode: crate::agent::turn_contracts::ChatMode::default(), - silent: true, - expose_stay_silent: false, - multimodal: &multimodal_config, - schedule: crate::agent::turn_request::TurnSchedule { - read_only_tool_concurrency_window: config_snapshot - .agent - .read_only_tool_concurrency_window, - priority_scheduling_enabled: config_snapshot.agent.priority_scheduling_enabled, - low_priority_tool_names: config_snapshot.agent.low_priority_tools.clone(), - }, - compaction: Some(&effective_compaction.config), - // no tool call notifications - decision: crate::agent::turn_request::TurnDecision { - service, - context: &context, - runtime: context.runtime(), - proof: &gateway_proof, - }, - }, - crate::agent::turn_request::TurnServices { - provider: turn_runtime.provider.as_ref(), - provider_name: provider_label, - model: &turn_runtime.model, - temperature: turn_runtime.temperature, - tools_registry: Arc::clone(&turn_runtime.tools_registry), - observer: &noop_observer, - hooks: state.hooks.as_ref(), - // silent - approval: None, - approval_resolver: None, - runtime_adapter: Some({ - crate::agent::turn_contracts::ToolLoopRuntimeAdapter { - live_frames: None, - guarded_delivery: false, - provider_trace: None, - events: None, - stream_provider: false, - tool_execution_service: None, - tool_execution_context: crate::tools::ToolExecutionContext::new( - runtime_envelope.clone(), - if fabric_ctx.channel == "webhook" { - "webhook" - } else { - "private" - }, - ) - .with_dispatch_origin(crate::tools::DispatchOrigin::ModelTurn) - .with_approval_ledger(service.execution_approval_ledger()) - .with_chat_id(&runtime_envelope.session_key), - allowed_tool_names: None, - } - }), - memory: crate::agent::turn_request::ToolLoopMemory::new( - &state.mem, - &config_snapshot.workspace_dir, - Some(DocumentIngestRuntime::from_envelope( - state.mem.clone(), - &runtime_envelope, - )), - ) - .with_event_fabric( - MemoryFabric::new(state.mem.clone(), runtime_envelope.workspace_id.clone()) - .with_event_recording(config_snapshot.memory.event_recording_config()), - ) - .with_request_event_scope({ - let mut scope = base_scope.clone(); - scope.causation_event_id = - gateway_user_event.as_ref().map(|event| event.event_id.clone()); - scope - }), - }, - crate::agent::turn_request::TurnDelivery { - cancellation: Some(cancellation.clone()), - // no cancellation token - on_delta: None, - // P1-a: gateway turns now route through decide() - on_tool_call: None, - }, - ) - .await - .map(|(outcome, trace)| (outcome.into_text(), trace)) - }), - ) - .await; - let (response, trace) = match loop_result { - Ok(result) => result, - Err(error) => { - let cancelled = - cancellation.is_cancelled() || crate::agent::turn_contracts::is_tool_loop_cancelled(&error); - *stage = TurnFailureClass::Internal; - let terminal_id = runtime_envelope - .run_id - .clone() - .ok_or_else(|| anyhow::anyhow!("gateway source run id is missing"))?; - if let Err(finalize_error) = turn_source::publication_slot::commit_terminal( - Some(&terminal_guard), - &fabric, - crate::agent::terminal::TurnTerminalDraft { - binding: Some(terminal_binding.clone()), - terminal_id, - scope: runtime_envelope.message_scope(), - status: if cancelled { - crate::agent::terminal::TurnTerminalStatus::Cancelled - } else { - crate::agent::terminal::TurnTerminalStatus::Failed - }, - history: None, - history_scope: None, - provider_outcome: None, - telemetry: crate::agent::terminal::TurnTerminalTelemetry { - summary: error.to_string(), - started_at: provider_started_at, - finished_at: chrono::Utc::now(), - }, - delivery_intent: crate::agent::terminal::TurnDeliveryIntent::ReturnToCaller, - }, - &config_snapshot, - ) - .await - { - *stage = terminal_guard.failure_reason().into(); - return Err(finalize_error); - } - *stage = if cancelled { - TurnFailureClass::Cancelled - } else { - TurnFailureClass::TurnLoop - }; - return Err(error); - } - }; - *stage = TurnFailureClass::Internal; - anyhow::ensure!( - trace.execution_trace.as_ref() == Some(&context.terminal_execution_trace()), - "gateway returned execution trace differs from its owning decision" - ); - - *stage = TurnFailureClass::ResourceDenied; - authorize_gateway_config_resource_mutation( - &config_snapshot, - "gateway:webhook:message_event:assistant", - ResourceRiskLevel::Low, - ) - .map_err(|(_, body)| { - let error = body - .0 - .get("error") - .and_then(|value| value.as_str()) - .unwrap_or("gateway resource mutation denied") - .to_string(); - anyhow::anyhow!(error) - })?; - let provider_outcome = - crate::agent::terminal::provider_outcome_from_trace(&route_decision, provider_started_at, trace); - let terminal_id = runtime_envelope - .run_id - .clone() - .unwrap_or_else(|| provider_outcome.decision_id.clone()); - let committed = turn_source::publication_slot::commit_terminal( - Some(&terminal_guard), - &fabric, - crate::agent::terminal::TurnTerminalDraft { - binding: Some(terminal_binding.clone()), - terminal_id, - scope: runtime_envelope.message_scope(), - status: crate::agent::terminal::TurnTerminalStatus::Completed, - history: Some(crate::agent::terminal::TurnHistoryProjection { - assistant_content: response.clone(), - history_commit_len: history.len(), - }), - history_scope: Some( - base_scope - .clone() - .with_sender(format!("{provider_label}/{}", turn_runtime.model)) - .with_recipient(fabric_ctx.sender.clone()), - ), - provider_outcome: Some(provider_outcome), - telemetry: crate::agent::terminal::TurnTerminalTelemetry { - summary: "gateway webhook completed".to_string(), - started_at: provider_started_at, - finished_at: chrono::Utc::now(), - }, - delivery_intent: crate::agent::terminal::TurnDeliveryIntent::ReturnToCaller, - }, - &config_snapshot, - ) - .await; - let receipt = match committed { - Ok(receipt) => receipt, - Err(error) => { - *stage = terminal_guard.failure_reason().into(); - return Err(error); - } - }; - *stage = TurnFailureClass::ReplayLookup; - let replay_unavailable = crate::agent::terminal::oversized_reply::from_receipt(&receipt)?; - // The turn's own work is done; what fails from here is its - // owned cleanup settling. - *stage = TurnFailureClass::TurnCleanup; - Ok(GatewayTurnResult { - response, - replay_unavailable, - }) - }) - .await; - if let Err(error) = &turn_result { - if let Err(finish_error) = terminal_guard.finish_failure(error, cancellation.is_cancelled()).await { - *stage = terminal_guard.failure_reason().into(); - return Err(finish_error); - } - } - turn_result -} - -/// Webhook request body -#[derive(serde::Deserialize)] -pub struct WebhookBody { - pub message: String, - #[serde(default)] - pub reply_target: Option, -} - -/// POST /webhook — main webhook endpoint -async fn handle_webhook( - State(state): State, - ConnectInfo(peer_addr): ConnectInfo, - uri: axum::http::Uri, - headers: HeaderMap, - body: Bytes, -) -> impl IntoResponse { - let async_mode = jobs::wants_async(uri.query(), &headers); - let bearer_token = headers - .get(header::AUTHORIZATION) - .and_then(|v| v.to_str().ok()) - .and_then(|auth| auth.strip_prefix("Bearer ")) - .map(str::trim) - .unwrap_or(""); - let webhook_token_header = headers - .get("X-Webhook-Token") - .and_then(|v| v.to_str().ok()) - .map(str::trim) - .filter(|value| !value.is_empty()); - let webhook_signature_header = headers - .get("X-Webhook-Signature") - .and_then(|v| v.to_str().ok()) - .map(str::trim) - .filter(|value| !value.is_empty()); - - let rate_key = client_key_from_request(Some(peer_addr), &headers, state.trust_forwarded_headers); - if !state.rate_limiter.allow_webhook(&rate_key) { - tracing::warn!("/webhook rate limit exceeded"); - let err = serde_json::json!({ - "error": "Too many webhook requests. Please retry later.", - "retry_after": RATE_LIMIT_WINDOW_SECS, - }); - return (StatusCode::TOO_MANY_REQUESTS, Json(err)); - } - - // ── Bearer token auth (pairing) ── - if state.pairing.require_pairing() { - if !state.pairing.is_authenticated(bearer_token) { - tracing::warn!("Webhook: rejected — not paired / invalid bearer token"); - let err = serde_json::json!({ - "error": "Unauthorized — pair first via POST /pair, then send Authorization: Bearer " - }); - return (StatusCode::UNAUTHORIZED, Json(err)); - } - } - - // ── Standalone webhook token auth (optional, additional layer) ── - if let Some(ref token_hash) = state.webhook_token_hash { - let header_hash = webhook_token_header.map(hash_webhook_secret); - match header_hash { - Some(val) if constant_time_eq(&val, token_hash.as_ref()) => {} - _ => { - tracing::warn!("Webhook: rejected request — invalid or missing X-Webhook-Token"); - let err = serde_json::json!({"error": "Unauthorized — invalid or missing X-Webhook-Token header"}); - return (StatusCode::UNAUTHORIZED, Json(err)); - } - } - } - - // ── Webhook HMAC auth (optional, additional layer) ── - if let Some(ref signing_secret) = state.webhook_signing_secret { - match webhook_signature_header { - Some(signature) if verify_webhook_hmac_signature(signing_secret, &body, signature) => {} - _ => { - tracing::warn!("Webhook: rejected request — invalid or missing X-Webhook-Signature"); - let err = serde_json::json!({"error": "Unauthorized — invalid or missing X-Webhook-Signature header"}); - return (StatusCode::UNAUTHORIZED, Json(err)); - } - } - } - - // Additional credential-based limiter reduces distributed IP rotation bypass. - let credential_rate_key = if !bearer_token.is_empty() { - format!("bearer:{}", hash_webhook_secret(bearer_token)) - } else if let Some(token) = webhook_token_header { - format!("token:{}", hash_webhook_secret(token)) - } else if let Some(signature) = webhook_signature_header { - format!("signature:{}", hash_webhook_secret(signature)) - } else { - "public".to_string() - }; - // The authenticated credential this request presented, in two forms: the - // idempotency scope (process-local; hashed again into every stored - // idempotency key) and the owner credential of the webhook turn - // (`GatewayFabricContext::webhook_owner_id`, R-MCPB F-2), whose - // domain-separated digest is what reaches owner ids, session keys and logs - // (R-MCPBfg N-4). Both follow the same precedence. - let owner_credential = if state.pairing.require_pairing() { - webhook_owner_credential("bearer", bearer_token) - } else if let (Some(_), Some(token)) = (&state.webhook_token_hash, webhook_token_header) { - webhook_owner_credential("token", token) - } else if let Some(signing_secret) = state.webhook_signing_secret.as_deref() { - webhook_owner_credential("signing-secret", signing_secret) - } else { - "public".to_string() - }; - let idempotency_scope = if state.pairing.require_pairing() { - format!("bearer:{}", hash_webhook_secret(bearer_token)) - } else if let (Some(_), Some(token)) = (&state.webhook_token_hash, webhook_token_header) { - format!("token:{}", hash_webhook_secret(token)) - } else if let Some(signing_secret) = state.webhook_signing_secret.as_deref() { - format!("signing-secret:{}", hash_webhook_secret(signing_secret)) - } else { - "public".to_string() - }; - if !state.rate_limiter.allow_webhook_credential(&credential_rate_key) { - tracing::warn!("/webhook credential rate limit exceeded"); - let err = serde_json::json!({ - "error": "Too many webhook requests. Please retry later.", - "retry_after": RATE_LIMIT_WINDOW_SECS, - }); - return (StatusCode::TOO_MANY_REQUESTS, Json(err)); - } - // Admission, before any idempotency claim is taken. - if let Err(refusal) = state.admit_turn_runtime() { - return turn_not_ready_plain(refusal); - } - - // ── Parse body ── - let webhook_body: WebhookBody = match serde_json::from_slice(&body) { - Ok(b) => b, - Err(e) => { - tracing::warn!("Webhook JSON parse error: {e}"); - let err = serde_json::json!({ - "error": "Invalid JSON body. Expected: {\"message\": \"...\"}" - }); - return (StatusCode::BAD_REQUEST, Json(err)); - } - }; - - // ── Idempotency (optional) ── - let request_idempotency_key = match idempotency_key_from_header(&headers, "X-Idempotency-Key") { - Ok(key) => key, - Err(message) => { - let err = serde_json::json!({ "error": message }); - return (StatusCode::BAD_REQUEST, Json(err)); - } - }; - let mut idempotency_digest = None; - let mut idempotency_claim = None; - if let Some(raw_key) = request_idempotency_key.as_deref() { - if let Err(error) = - authorize_gateway_resource_mutation(&state, "gateway:webhook:idempotency", ResourceRiskLevel::Low) - { - return error; - } - let digest = webhook_idempotency_digest(&idempotency_scope, raw_key); - let fingerprint = webhook_request_fingerprint(&body); - match state.idempotency_store.claim(digest.clone(), fingerprint) { - IdempotencyClaimOutcome::Acquired(claim) => { - idempotency_digest = Some(digest); - idempotency_claim = Some(claim); - } - IdempotencyClaimOutcome::Processing => { - let body = serde_json::json!({ - "status": "processing", - "idempotent": true, - "message": "A request with this idempotency key is still processing" - }); - return (StatusCode::CONFLICT, Json(body)); - } - IdempotencyClaimOutcome::Replay(replay) => { - return (StatusCode::OK, Json(replay.json_body())); - } - IdempotencyClaimOutcome::ReplayUnavailable { - response_id, - result_hash, - } => { - let body = replay_unavailable_body(response_id, &result_hash); - return (StatusCode::CONFLICT, Json(body)); - } - IdempotencyClaimOutcome::RequestConflict => { - let body = serde_json::json!({ - "status": "request_conflict", - "idempotent": true, - "message": "This idempotency key was used with a different request body" - }); - return (StatusCode::CONFLICT, Json(body)); - } - IdempotencyClaimOutcome::RetryUnavailable => { - let body = serde_json::json!({ - "status": "retry_unavailable", - "idempotent": true, - "message": "This failed request is not eligible for retry" - }); - return (StatusCode::CONFLICT, Json(body)); - } - IdempotencyClaimOutcome::AtCapacity => { - let body = serde_json::json!({ - "error": "Idempotency capacity is temporarily exhausted", - "retryable": true - }); - return (StatusCode::SERVICE_UNAVAILABLE, Json(body)); - } - } - } - - // From here on the request may run for as long as the agent turn behind it - // needs, so it becomes a detached job rather than staying inside this - // handler's future. Two things follow from that. The turn survives a client - // that hangs up — a webhook sender's read timeout no longer destroys work - // that had already started writing memory and calling tools. And the - // idempotency claim travels *with* the work instead of with the connection, - // so a dropped connection can no longer release the claim underneath a run - // that is still going. - let job = jobs::submit( - jobs::KIND_WEBHOOK, - format!("gateway:webhook:{}", fabric_channel_label(&webhook_body)), - run_webhook_job( - state, - webhook_body, - owner_credential, - idempotency_digest, - idempotency_claim, - ), - ); - - if async_mode { - return (StatusCode::ACCEPTED, Json(job.accepted_body())); - } - job.wait().await.into_parts() -} - -/// Label for the registry row of a webhook job, so `prx tasks list` shows which -/// delivery target the run belongs to rather than a bare route name. -fn fabric_channel_label(body: &WebhookBody) -> &str { - body.reply_target.as_deref().unwrap_or("anonymous") -} - -/// The unbounded half of `POST /webhook`, run as a job. -/// -/// Owns the idempotency claim for the whole run: the claim is only resolved by -/// code that knows how the run ended, never by the request future going away. -fn run_webhook_job( - state: AppState, - webhook_body: WebhookBody, - credential: String, - idempotency_digest: Option, - idempotency_claim: Option, -) -> std::pin::Pin> + Send>> { - // Keep owned webhook work out of the generic job submitter's future. - // Construction does not poll it; the same idempotency claim moves with it. - Box::pin(run_webhook_job_work( - state, - webhook_body, - credential, - idempotency_digest, - idempotency_claim, - )) -} - -async fn run_webhook_job_work( - state: AppState, - webhook_body: WebhookBody, - credential: String, - idempotency_digest: Option, - idempotency_claim: Option, -) -> Result { - let mut idempotency_claim = idempotency_claim; - let message = webhook_body.message.as_str(); - - let autosave_key = - if state.auto_save && should_autosave_gateway_message(webhook_body.reply_target.as_deref(), message) { - if let Err((status, body)) = - authorize_gateway_resource_mutation(&state, "gateway:webhook:autosave", ResourceRiskLevel::Low) - { - return Ok(jobs::JobOutput::new(status, body.0)); - } - // First observable side effect of the attempt: past this point a - // redelivery of the same key would duplicate it. - if let Some(claim) = idempotency_claim.as_mut() { - claim.mark_dispatched(); - } - let key = webhook_memory_key(idempotency_digest.as_deref()); - Some(key) - } else { - None - }; - - let provider_label = state - .config - .load_full() - .default_provider - .clone() - .unwrap_or_else(|| "unknown".to_string()); - let model_label = state.model.clone(); - let started_at = Instant::now(); - - state - .observer - .record_event(&crate::observability::ObserverEvent::AgentStart { - provider: provider_label.clone(), - model: model_label.clone(), - }); - state - .observer - .record_event(&crate::observability::ObserverEvent::LlmRequest { - provider: provider_label.clone(), - model: model_label.clone(), - messages_count: 1, - }); - - let fabric_ctx = GatewayFabricContext::generic_webhook( - webhook_body.reply_target.as_deref(), - &credential, - idempotency_digest - .as_deref() - .map(|digest| format!("gateway:webhook:{digest}")), - ); - // The turn records the inbound message and may call tools, so from here the - // attempt is not replayable by re-execution — only by the stored result. - if let Some(claim) = idempotency_claim.as_mut() { - claim.mark_dispatched(); - } - let mut stage = TurnFailureClass::Internal; - match run_gateway_chat_with_multimodal( - &state, - &provider_label, - message, - &fabric_ctx, - autosave_key.as_deref(), - &mut stage, - ) - .await - { - Ok(GatewayTurnResult { - response, - replay_unavailable, - }) => { - let response_id = match replay_unavailable.as_ref() { - Some(reference) => { - Uuid::parse_str(&reference.terminal_id).map_err(|_| "invalid durable response id".to_owned())? - } - None => Uuid::new_v4(), - }; - if let Some(claim) = idempotency_claim.take() { - let completed = if let Some(reference) = replay_unavailable { - claim.succeed_unavailable(response_id, reference.result_hash) - } else { - let result_hash = webhook_result_hash(&response, &model_label); - let replay = IdempotencyReplay { - response_id, - response: Arc::from(response.as_str()), - model: Arc::from(model_label.as_str()), - }; - claim.succeed(replay, result_hash) - }; - if !completed { - tracing::error!("Webhook idempotency ownership was lost before success commit"); - let err = serde_json::json!({ - "error": "Request completed but its idempotency result could not be committed" - }); - return Ok(jobs::JobOutput::new(StatusCode::SERVICE_UNAVAILABLE, err)); - } - } - let duration = started_at.elapsed(); - state - .observer - .record_event(&crate::observability::ObserverEvent::LlmResponse { - provider: provider_label.clone(), - model: model_label.clone(), - duration, - success: true, - error_message: None, - }); - state - .observer - .record_metric(&crate::observability::traits::ObserverMetric::RequestLatency(duration)); - state - .observer - .record_event(&crate::observability::ObserverEvent::AgentEnd { - provider: provider_label, - model: model_label, - duration, - tokens_used: None, - cost_usd: None, - }); - - let body = serde_json::json!({ - "response": response, - "model": state.model, - "response_id": response_id.to_string(), - }); - Ok(jobs::JobOutput::new(StatusCode::OK, body)) - } - Err(e) => { - if let Some(unavailable) = e.downcast_ref::() { - let response_id = - Uuid::parse_str(&unavailable.terminal_id).map_err(|_| "invalid durable response id".to_owned())?; - if let Some(claim) = idempotency_claim.take() { - if !claim.succeed_unavailable(response_id, unavailable.result_hash.clone()) { - return Ok(jobs::JobOutput::new( - StatusCode::SERVICE_UNAVAILABLE, - serde_json::json!({"error":"Idempotency ownership was lost"}), - )); - } - } - return Ok(jobs::JobOutput::new( - StatusCode::CONFLICT, - replay_unavailable_body(response_id, &unavailable.result_hash), - )); - } - if let Some(claim) = idempotency_claim.take() { - let _ = claim.fail(); - } - if e.is::() { - return Ok(jobs::JobOutput::new( - StatusCode::CONFLICT, - serde_json::json!({"error":"input_already_accepted","status":"unconfirmed","message":"Execution was not repeated; the previously accepted input has an unconfirmed outcome."}), - )); - } - let duration = started_at.elapsed(); - let sanitized = providers::sanitize_api_error(&e.to_string()); - - state - .observer - .record_event(&crate::observability::ObserverEvent::LlmResponse { - provider: provider_label.clone(), - model: model_label.clone(), - duration, - success: false, - error_message: Some(sanitized.clone()), - }); - state - .observer - .record_metric(&crate::observability::traits::ObserverMetric::RequestLatency(duration)); - state - .observer - .record_event(&crate::observability::ObserverEvent::Error { - component: "gateway".to_string(), - message: sanitized, - }); - state - .observer - .record_event(&crate::observability::ObserverEvent::AgentEnd { - provider: provider_label, - model: model_label, - duration, - tokens_used: None, - cost_usd: None, - }); - - if let Some(tools) = providers::tool_schema_refused_tools(&e) { - // A configuration problem, not a transient one: the whole - // refusal (every tool, the configuration to add) is logged - // unclipped, and the authenticated caller gets a stable code - // with the refused tools. - tracing::error!( - error = %crate::security::redaction::redact_secrets(&format!("{e:#}")), - "Webhook turn refused before transport: the provider cannot accept some offered tool schemas" - ); - let err = serde_json::json!({ - "error": "tool_schema_refused", - "tools": tools, - "message": "The configured provider cannot accept some of the tool schemas this request \ - offered, so nothing was sent. The gateway log names the configuration to change.", - }); - return Ok(jobs::JobOutput::new(StatusCode::INTERNAL_SERVER_ERROR, err)); - } - // "LLM request failed" stands for a failed provider request only; - // every other failure answers the closed class of its step, never - // the error text. - let reason = TurnFailureClass::classify(stage, &e); - tracing::error!( - reason = %reason, - error = %crate::agent::diagnostics::error_class(&e), - "Webhook turn failed" - ); - let err = if reason == TurnFailureClass::Provider { - serde_json::json!({"error": "LLM request failed"}) - } else { - serde_json::json!({"error": "turn_failed", "reason": reason.code()}) - }; - Ok(jobs::JobOutput::new(StatusCode::INTERNAL_SERVER_ERROR, err)) - } - } -} - -/// Registry label for one accepted channel-webhook delivery. -/// -/// Named the way every other registry row names a correspondent: the channel in -/// the clear, the chat only as [`crate::security::op_id::ref_for_channel_recipient`]'s -/// fingerprint. `reply_target` on this route is a platform address — a Telegram -/// chat id, a WhatsApp JID — and this label is published verbatim by -/// `GET /api/runtime/tasks`, so writing it out would leak through the operator -/// plane the very address the send path takes care to fingerprint. Sharing that -/// one function is also what keeps the digest here equal to the digest an -/// outbound send to the same chat produces, so the two rows stay correlatable. -/// -/// MUTATION GUARD: interpolate `reply_target` directly and -/// `a_channel_webhook_job_label_fingerprints_the_chat` fails. -fn channel_webhook_job_label(channel_key: &str, first: Option<&crate::channels::traits::ChannelMessage>) -> String { - first.map_or_else( - || format!("gateway:{channel_key}"), - |msg| { - format!( - "gateway:{channel_key}:{}", - crate::security::op_id::ref_for_channel_recipient(channel_key, &msg.reply_target) - ) - }, - ) -} - -/// Shared tail of the three platform-pushed channel webhooks. -/// -/// These routes differ from `POST /webhook` in one decisive way: the sender is a -/// platform with a response deadline, not a client that chose to wait. Linq -/// documents "Response timeout: 10 seconds" and retries "up to 10 times over ~25 -/// minutes"; Meta retries a WhatsApp delivery "with decreasing frequency until -/// the request succeeds, for up to 7 days". An agent turn has no upper bound and -/// routinely exceeds any of those, so awaiting the turn inside the handler — as -/// these three did — guaranteed the platform would give up, mark the delivery -/// failed, and redeliver, running the whole turn again for every retry. -/// -/// The ack therefore reports that the work was *accepted*, not that it finished: -/// the turns run as a detached job, visible in `prx tasks list` and killable with -/// `prx tasks kill`, and the reply reaches the user through the channel's own -/// outbound API exactly as before. The delivery is claimed before submission, so -/// a retry that races the accepted run is answered as a duplicate instead of -/// starting a second copy of it. -/// The `503` a non-`/api` turn route answers while the turn runtime is not -/// ready, in those routes' own `{"error"}` shape. -fn turn_not_ready_plain(refusal: TurnNotReady) -> (StatusCode, Json) { - ( - StatusCode::SERVICE_UNAVAILABLE, - Json(serde_json::json!({ "error": refusal.to_string() })), - ) -} - -fn accept_channel_webhook_delivery( - state: &AppState, - channel: Arc, - channel_key: &'static str, - body: &Bytes, - messages: Vec, - memory_key: fn(&crate::channels::traits::ChannelMessage) -> String, -) -> (StatusCode, Json) { - // Admission, before the delivery is claimed: a refused delivery is - // redelivered by the platform once the runtime is ready. - if let Err(refusal) = state.admit_turn_runtime() { - return turn_not_ready_plain(refusal); - } - let dedup_ttl = Duration::from_secs(state.config.load_full().gateway.channel_webhook_dedup_ttl_secs.max(1)); - let claim = match webhook_dedup::claim(webhook_dedup::delivery_key(channel_key, body), dedup_ttl) { - webhook_dedup::DeliveryOutcome::Fresh(claim) => claim, - webhook_dedup::DeliveryOutcome::Duplicate => { - tracing::info!("{channel_key} webhook: redelivery of an already accepted payload — not run again"); - return ( - StatusCode::OK, - Json(serde_json::json!({ "status": "duplicate", "idempotent": true })), - ); - } - }; - - let label = channel_webhook_job_label(channel_key, messages.first()); - let job = jobs::submit( - jobs::KIND_CHANNEL_WEBHOOK, - label, - run_channel_webhook_job(state.clone(), channel, channel_key, messages, memory_key, claim), - ); - - // Every platform on this route treats any 2xx as delivered; 200 is the one - // status all three accept without special handling. - (StatusCode::OK, Json(job.accepted_body())) -} - -/// The unbounded half of a platform channel webhook, run as a job. -/// -/// Owns the delivery claim for the whole run, so the claim is resolved by code -/// that knows whether the turn reached a side effect — never by the request -/// future going away. -fn run_channel_webhook_job( - state: AppState, - channel: Arc, - channel_key: &'static str, - messages: Vec, - memory_key: fn(&crate::channels::traits::ChannelMessage) -> String, - claim: webhook_dedup::DeliveryClaim, -) -> std::pin::Pin> + Send>> { - // Keep owned channel work out of the generic job submitter's future. - // Construction does not poll it; the same delivery claim moves with it. - Box::pin(run_channel_webhook_job_work( - state, - channel, - channel_key, - messages, - memory_key, - claim, - )) -} - -async fn run_channel_webhook_job_work( - state: AppState, - channel: Arc, - channel_key: &'static str, - messages: Vec, - memory_key: fn(&crate::channels::traits::ChannelMessage) -> String, - mut claim: webhook_dedup::DeliveryClaim, -) -> Result { - let provider_label = state - .config - .load_full() - .default_provider - .clone() - .unwrap_or_else(|| "unknown".to_string()); - - for msg in &messages { - tracing::info!( - "{channel_key} message from {}: {}", - msg.sender, - truncate_with_ellipsis(&msg.content, 50) - ); - - // Auto-save to memory - let autosave_key = if state.auto_save && should_autosave_gateway_message(Some(&msg.reply_target), &msg.content) - { - if let Err((status, body)) = authorize_gateway_resource_mutation( - &state, - &gateway_channel_webhook_operation(channel_key, "autosave"), - ResourceRiskLevel::Low, - ) { - return Ok(jobs::JobOutput::new(status, body.0)); - } - // First observable side effect: past this point a redelivery would - // duplicate it, so the claim must outlive the run. - claim.mark_dispatched(); - let key = memory_key(msg); - Some(key) - } else { - None - }; - - let fabric_ctx = GatewayFabricContext::channel_message(msg); - // The turn records the inbound message and may call tools, so from here - // the delivery is not replayable by re-execution. - claim.mark_dispatched(); - let mut stage = TurnFailureClass::Internal; - match run_gateway_chat_with_multimodal( - &state, - &provider_label, - &msg.content, - &fabric_ctx, - autosave_key.as_deref(), - &mut stage, - ) - .await - { - Ok(GatewayTurnResult { response, .. }) => { - if let Err((status, body)) = authorize_gateway_resource_mutation( - &state, - &gateway_channel_webhook_operation(channel_key, "send"), - ResourceRiskLevel::Low, - ) { - return Ok(jobs::JobOutput::new(status, body.0)); - } - if let Err(e) = channel.send(&SendMessage::new(response, &msg.reply_target)).await { - tracing::error!("Failed to send {channel_key} reply: {e}"); - } - } - Err(e) => { - let reason = TurnFailureClass::classify(stage, &e); - tracing::error!(reason = %reason, error = %crate::security::redaction::redact_provider_text(&format!("{e:#}")), "Turn failed for {channel_key} message"); - if let Err((status, body)) = authorize_gateway_resource_mutation( - &state, - &gateway_channel_webhook_operation(channel_key, "send"), - ResourceRiskLevel::Low, - ) { - return Ok(jobs::JobOutput::new(status, body.0)); - } - let _ = channel - .send(&SendMessage::new( - if e.is::() {"This input was already accepted. Execution was not repeated; its outcome remains unconfirmed."} else {"Sorry, I couldn't process your message right now."}, - &msg.reply_target, - )) - .await; - } - } - } - - Ok(jobs::JobOutput::new( - StatusCode::OK, - serde_json::json!({ "status": "ok", "messages": messages.len() }), - )) -} - -/// `WhatsApp` verification query params -#[derive(serde::Deserialize)] -pub struct WhatsAppVerifyQuery { - #[serde(rename = "hub.mode")] - pub mode: Option, - #[serde(rename = "hub.verify_token")] - pub verify_token: Option, - #[serde(rename = "hub.challenge")] - pub challenge: Option, -} - -/// GET /whatsapp — Meta webhook verification -async fn handle_whatsapp_verify( - State(state): State, - Query(params): Query, -) -> impl IntoResponse { - let Some(ref wa) = state.whatsapp else { - return (StatusCode::NOT_FOUND, "WhatsApp not configured".to_string()); - }; - - // Verify the token matches (constant-time comparison to prevent timing attacks) - let token_matches = params - .verify_token - .as_deref() - .is_some_and(|t| constant_time_eq(t, wa.verify_token())); - if params.mode.as_deref() == Some("subscribe") && token_matches { - if let Some(ch) = params.challenge { - tracing::info!("WhatsApp webhook verified successfully"); - return (StatusCode::OK, ch); - } - return (StatusCode::BAD_REQUEST, "Missing hub.challenge".to_string()); - } - - tracing::warn!("WhatsApp webhook verification failed — token mismatch"); - (StatusCode::FORBIDDEN, "Forbidden".to_string()) -} - -/// Verify `WhatsApp` webhook signature (`X-Hub-Signature-256`). -/// -/// Returns true if the signature is valid, false otherwise. -/// See: -pub fn verify_whatsapp_signature(app_secret: &str, body: &[u8], signature_header: &str) -> bool { - use hmac::{Hmac, Mac}; - use sha2::Sha256; - - // Signature format: "sha256=" - let Some(hex_sig) = signature_header.strip_prefix("sha256=") else { - return false; - }; - - // Decode hex signature - let Ok(expected) = hex::decode(hex_sig) else { - return false; - }; - - // Compute HMAC-SHA256 - let Ok(mut mac) = Hmac::::new_from_slice(app_secret.as_bytes()) else { - return false; - }; - mac.update(body); - - // Constant-time comparison - mac.verify_slice(&expected).is_ok() -} - -/// POST /whatsapp — incoming message webhook -async fn handle_whatsapp_message(State(state): State, headers: HeaderMap, body: Bytes) -> impl IntoResponse { - let Some(ref wa) = state.whatsapp else { - return ( - StatusCode::NOT_FOUND, - Json(serde_json::json!({"error": "WhatsApp not configured"})), - ); - }; - - // ── Security: Verify X-Hub-Signature-256 — reject if signing secret not configured ── - let app_secret = match &state.whatsapp_app_secret { - Some(secret) => secret, - None => { - tracing::error!("WhatsApp webhook received but signing secret not configured — rejecting"); - return ( - StatusCode::SERVICE_UNAVAILABLE, - Json(serde_json::json!({"error": "Webhook signing secret not configured"})), - ); - } - }; - { - let signature = headers - .get("X-Hub-Signature-256") - .and_then(|v| v.to_str().ok()) - .unwrap_or(""); - - if !verify_whatsapp_signature(app_secret, &body, signature) { - tracing::warn!( - "WhatsApp webhook signature verification failed (signature: {})", - if signature.is_empty() { "missing" } else { "invalid" } - ); - return ( - StatusCode::UNAUTHORIZED, - Json(serde_json::json!({"error": "Invalid signature"})), - ); - } - } - - // Parse JSON body - let Ok(payload) = serde_json::from_slice::(&body) else { - return ( - StatusCode::BAD_REQUEST, - Json(serde_json::json!({"error": "Invalid JSON payload"})), - ); - }; - - // Parse messages from the webhook payload - let messages = wa.parse_webhook_payload(&payload); - - if messages.is_empty() { - // Acknowledge the webhook even if no messages (could be status updates) - return (StatusCode::OK, Json(serde_json::json!({"status": "ok"}))); - } - - // Webhook-delivered channels never pass through the channel dispatch loop, - // so their inbound activity is recorded here instead (see - // `channels::activity`). Reporting only — nothing acts on it. - crate::channels::activity::record_inbound(wa.name()); - - let channel: Arc = Arc::clone(wa) as Arc; - accept_channel_webhook_delivery(&state, channel, "whatsapp", &body, messages, whatsapp_memory_key) -} - -/// POST /linq — incoming message webhook (iMessage/RCS/SMS via Linq) -async fn handle_linq_webhook(State(state): State, headers: HeaderMap, body: Bytes) -> impl IntoResponse { - let Some(ref linq) = state.linq else { - return ( - StatusCode::NOT_FOUND, - Json(serde_json::json!({"error": "Linq not configured"})), - ); - }; - - let body_str = String::from_utf8_lossy(&body); - - // ── Security: Verify X-Webhook-Signature — reject if signing secret not configured ── - let signing_secret = match &state.linq_signing_secret { - Some(secret) => secret, - None => { - tracing::error!("Linq webhook received but signing secret not configured — rejecting"); - return ( - StatusCode::SERVICE_UNAVAILABLE, - Json(serde_json::json!({"error": "Webhook signing secret not configured"})), - ); - } - }; - { - let timestamp = headers - .get("X-Webhook-Timestamp") - .and_then(|v| v.to_str().ok()) - .unwrap_or(""); - - let signature = headers - .get("X-Webhook-Signature") - .and_then(|v| v.to_str().ok()) - .unwrap_or(""); - - if !crate::channels::linq::verify_linq_signature(signing_secret, &body_str, timestamp, signature) { - tracing::warn!( - "Linq webhook signature verification failed (signature: {})", - if signature.is_empty() { "missing" } else { "invalid" } - ); - return ( - StatusCode::UNAUTHORIZED, - Json(serde_json::json!({"error": "Invalid signature"})), - ); - } - } - - // Parse JSON body - let Ok(payload) = serde_json::from_slice::(&body) else { - return ( - StatusCode::BAD_REQUEST, - Json(serde_json::json!({"error": "Invalid JSON payload"})), - ); - }; - - // Parse messages from the webhook payload - let messages = linq.parse_webhook_payload(&payload); - - if messages.is_empty() { - // Acknowledge the webhook even if no messages (could be status/delivery events) - return (StatusCode::OK, Json(serde_json::json!({"status": "ok"}))); - } - - // Webhook-delivered channels never pass through the channel dispatch loop, - // so their inbound activity is recorded here instead (see - // `channels::activity`). Reporting only — nothing acts on it. - crate::channels::activity::record_inbound(linq.name()); - - let channel: Arc = Arc::clone(linq) as Arc; - accept_channel_webhook_delivery(&state, channel, "linq", &body, messages, linq_memory_key) -} - -/// POST /nextcloud-talk — incoming message webhook (Nextcloud Talk bot API) -async fn handle_nextcloud_talk_webhook( - State(state): State, - headers: HeaderMap, - body: Bytes, -) -> impl IntoResponse { - let Some(ref nextcloud_talk) = state.nextcloud_talk else { - return ( - StatusCode::NOT_FOUND, - Json(serde_json::json!({"error": "Nextcloud Talk not configured"})), - ); - }; - - let body_str = String::from_utf8_lossy(&body); - - // ── Security: Verify Nextcloud Talk HMAC signature — reject if secret not configured ── - let webhook_secret = match &state.nextcloud_talk_webhook_secret { - Some(secret) => secret, - None => { - tracing::error!("Nextcloud Talk webhook received but signing secret not configured — rejecting"); - return ( - StatusCode::SERVICE_UNAVAILABLE, - Json(serde_json::json!({"error": "Webhook signing secret not configured"})), - ); - } - }; - { - let random = headers - .get("X-Nextcloud-Talk-Random") - .and_then(|v| v.to_str().ok()) - .unwrap_or(""); - - let signature = headers - .get("X-Nextcloud-Talk-Signature") - .and_then(|v| v.to_str().ok()) - .unwrap_or(""); - - if !crate::channels::nextcloud_talk::verify_nextcloud_talk_signature( - webhook_secret, - random, - &body_str, - signature, - ) { - tracing::warn!( - "Nextcloud Talk webhook signature verification failed (signature: {})", - if signature.is_empty() { "missing" } else { "invalid" } - ); - return ( - StatusCode::UNAUTHORIZED, - Json(serde_json::json!({"error": "Invalid signature"})), - ); - } - } - - // Parse JSON body - let Ok(payload) = serde_json::from_slice::(&body) else { - return ( - StatusCode::BAD_REQUEST, - Json(serde_json::json!({"error": "Invalid JSON payload"})), - ); - }; - - // Parse messages from webhook payload - let messages = nextcloud_talk.parse_webhook_payload(&payload); - if messages.is_empty() { - // Acknowledge webhook even if payload does not contain actionable user messages. - return (StatusCode::OK, Json(serde_json::json!({"status": "ok"}))); - } - - // Webhook-delivered channels never pass through the channel dispatch loop, - // so their inbound activity is recorded here instead (see - // `channels::activity`). Reporting only — nothing acts on it. - crate::channels::activity::record_inbound(nextcloud_talk.name()); - - let channel: Arc = Arc::clone(nextcloud_talk) as Arc; - accept_channel_webhook_delivery( - &state, - channel, - "nextcloud_talk", - &body, - messages, - nextcloud_talk_memory_key, - ) -} - -#[cfg(test)] -mod platform_test_transport; - -#[cfg(test)] -mod tests; -#[cfg(test)] -pub(crate) use tests::{drive_disabled_engine_webhook_entry, drive_search_webhook_entry}; +include!("implementation/section_1.rs"); +include!("implementation/section_2.rs"); +include!("implementation/section_3.rs"); diff --git a/src/gateway/tests/agent_registry.rs b/src/gateway/tests/agent_registry.rs index 5d3d5e487..a3a8e9e10 100644 --- a/src/gateway/tests/agent_registry.rs +++ b/src/gateway/tests/agent_registry.rs @@ -12,6 +12,7 @@ const SESSION: &str = "no-such-session"; fn agent(temperature: f64, enabled: bool) -> DelegateAgentConfig { DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), approval_wait_secs: 600, limits: crate::config::AgentLimits::default(), provider: "ollama".to_owned(), diff --git a/src/main.rs b/src/main.rs index 78a43e0c8..528529e38 100644 --- a/src/main.rs +++ b/src/main.rs @@ -84,4650 +84,13 @@ clippy::too_long_first_doc_paragraph )] -use anyhow::{Context, Result, bail}; -use chrono::Utc; -use clap::{Args, CommandFactory, Parser, Subcommand, ValueEnum}; -use dialoguer::{Input, Password}; -use openprx::{ - CHAT_TRACING_RELOAD, ChannelCommands, ChatFmtLayer, Config, CronCommands, EvolutionCommands, FitnessCommands, - IntegrationCommands, MigrateCommands, ServiceCommands, SkillCommands, XinCommands, acl, agent, auth, channels, - chat, cli_tracing, config, cron, daemon, doctor, evolution_cli, fitness_cli, gateway, handle_xin_command, - integrations, memory, migration, providers, runtime, security, service, session_worker, skills, -}; -use rusqlite::{Connection, OptionalExtension, params}; -use serde::{Deserialize, Serialize}; -use std::{fs, io::Write, path::PathBuf}; -use tracing::warn; -use tracing_subscriber::{EnvFilter, fmt}; - -fn parse_workdir(value: &str) -> Result { - openprx::config::RuntimeConfig::validate_workdir(std::path::Path::new(value)).map_err(|error| error.to_string()) -} - -fn parse_temperature(s: &str) -> std::result::Result { - let t: f64 = s.parse().map_err(|e| format!("{e}"))?; - if !(0.0..=2.0).contains(&t) { - return Err("temperature must be between 0.0 and 2.0".to_string()); - } - Ok(t) -} - -const fn cli_tracing_command(command: &Commands) -> cli_tracing::CliCommand { - match command { - Commands::Init { .. } | Commands::Token { .. } => cli_tracing::CliCommand::Init, - Commands::Go { .. } => cli_tracing::CliCommand::Go, - Commands::Chat { message: Some(_), .. } => cli_tracing::CliCommand::ChatMessage, - Commands::Chat { .. } => cli_tracing::CliCommand::Chat, - Commands::Gateway { .. } => cli_tracing::CliCommand::Gateway, - Commands::Daemon { .. } => cli_tracing::CliCommand::Daemon, - Commands::Service { .. } => cli_tracing::CliCommand::Service, - Commands::Doctor { .. } => cli_tracing::CliCommand::Doctor, - Commands::Status { .. } => cli_tracing::CliCommand::Status, - Commands::Tasks { .. } => cli_tracing::CliCommand::Tasks, - Commands::Memory { .. } => cli_tracing::CliCommand::Memory, - Commands::Evolution { .. } => cli_tracing::CliCommand::Evolution, - #[cfg(feature = "wasm-plugins")] - Commands::Plugin { .. } => cli_tracing::CliCommand::Plugin, - Commands::Cost { .. } => cli_tracing::CliCommand::Cost, - Commands::Fitness { .. } => cli_tracing::CliCommand::Fitness, - Commands::Cron { .. } => cli_tracing::CliCommand::Cron, - Commands::Xin { .. } => cli_tracing::CliCommand::Xin, - Commands::Causal { .. } => cli_tracing::CliCommand::Causal, - Commands::DecisionEngine { .. } => cli_tracing::CliCommand::DecisionEngine, - Commands::Models { .. } => cli_tracing::CliCommand::Models, - Commands::Providers { .. } => cli_tracing::CliCommand::Providers, - Commands::Routes { .. } => cli_tracing::CliCommand::Routes, - Commands::Channel { - channel_command: ChannelCommands::Start, - } => cli_tracing::CliCommand::ChannelStart, - Commands::Channel { .. } => cli_tracing::CliCommand::ChannelManage, - Commands::Integrations { .. } => cli_tracing::CliCommand::Integrations, - Commands::Skills { .. } => cli_tracing::CliCommand::Skills, - Commands::Migrate { .. } => cli_tracing::CliCommand::Migrate, - Commands::Auth { .. } => cli_tracing::CliCommand::Auth, - Commands::Approval { .. } => cli_tracing::CliCommand::Approval, - Commands::Audit { .. } => cli_tracing::CliCommand::Audit, - Commands::Config { .. } => cli_tracing::CliCommand::Config, - #[cfg(feature = "test-mock")] - Commands::MailboxHarness { .. } => cli_tracing::CliCommand::SessionWorker, - Commands::SessionWorker { .. } => cli_tracing::CliCommand::SessionWorker, - Commands::Completions { .. } => cli_tracing::CliCommand::Completions, - } -} - -// CLI dispatch remains binary-owned; every runtime subsystem it calls is owned -// and compiled once by the openprx library. #[path = "runtime/init_cli.rs"] mod init_cli; -#[path = "runtime/mode.rs"] -mod mode; - -// `prx providers|models|routes|config` management handlers: binary-owned, -// every operation calls the library's `config::manage` service in-process. #[path = "runtime/manage_cli.rs"] mod manage_cli; +#[path = "runtime/mode.rs"] +mod mode; -/// `OpenPRX` - 100% Rust. 100% Agnostic. Your AI, your rules. -#[derive(Parser, Debug)] -#[command(name = "prx")] -#[command(author = "g1e2x87")] -#[command(version = env!("CARGO_PKG_VERSION"))] -#[command(about = "The fastest, smallest AI assistant.", long_about = None)] -struct Cli { - #[arg(long, global = true)] - config_dir: Option, - - #[command(subcommand)] - command: Commands, -} - -#[derive(Subcommand, Debug)] -enum MemoryCommands { - /// Rebuild memory/document indexes and backfill stale embeddings where supported - Reindex { - /// Output machine-readable JSON - #[arg(long)] - json: bool, - }, -} - -#[derive(Subcommand, Debug)] -enum ApprovalCommands { - /// List runtime approval grants - List { - /// Filter by approval grant schema version - #[arg(long)] - version: Option, - }, - /// Verify runtime approval grants - Verify { - /// Verify all known grants - #[arg(long)] - all: bool, - /// Grant id to verify - grant_id: Option, - }, - /// Revoke a runtime approval grant - Revoke { - /// Grant id to revoke - grant_id: String, - /// Human-readable revocation reason - #[arg(long, default_value = "operator revoked")] - reason: String, - }, -} - -#[derive(Subcommand, Debug)] -enum AuditCommands { - /// Generate a local EU AI Act implementation attestation - #[command(name = "attest-eu-ai-act")] - AttestEuAiAct { - /// Emit JSON to stdout - #[arg(long)] - json: bool, - /// Output format - #[arg(long, value_enum, default_value_t = AuditOutputFormat::Markdown)] - format: AuditOutputFormat, - /// Write the attestation to a file - #[arg(long)] - output: Option, - /// Include implementation notes in markdown output - #[arg(long)] - verbose: bool, - /// Turn the report into a release gate at the selected severity - #[arg(long, value_enum)] - fail_on: Option, - }, - /// Generate a versioned Article 47 / Annex V declaration artifact from explicit operator inputs - #[command(name = "generate-eu-declaration")] - GenerateEuDeclaration { - /// Output path; defaults to compliance.eu_ai_act.declaration.artifact_path - #[arg(long)] - output: Option, - /// Reference to an operator-controlled external signature or signing receipt - #[arg(long)] - signature_reference: String, - }, - /// Create a durable Article 73 serious-incident record from a JSON input file - #[command(name = "incident-create")] - IncidentCreate { - /// JSON file containing the incident classification and ownership fields - #[arg(long)] - input: PathBuf, - }, - /// Record or replace the initial report for an open serious incident - #[command(name = "incident-initial-report")] - IncidentInitialReport { - incident_id: String, - /// UTF-8 file containing the initial report - #[arg(long)] - input: PathBuf, - }, - /// Append supplemental facts to a serious incident - #[command(name = "incident-supplement")] - IncidentSupplement { - incident_id: String, - /// UTF-8 file containing the supplement - #[arg(long)] - input: PathBuf, - }, - /// Close a serious incident with an explicit timestamp and summary - #[command(name = "incident-close")] - IncidentClose { - incident_id: String, - /// RFC 3339 closure timestamp - #[arg(long)] - closed_at: String, - /// UTF-8 file containing the closure summary - #[arg(long)] - summary: PathBuf, - }, - /// Export an incident, supplements, and immutable audit-event hashes - #[command(name = "incident-export")] - IncidentExport { - incident_id: String, - #[arg(long)] - output: PathBuf, - }, -} - -#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)] -enum AuditOutputFormat { - Markdown, - Json, -} - -#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)] -enum AuditFailOn { - Fail, - Warning, -} - -#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] -#[serde(rename_all = "snake_case")] -enum ControlStatus { - Pass, - Warning, - Fail, - NotApplicable, - Unknown, -} - -impl ControlStatus { - const fn as_str(self) -> &'static str { - match self { - Self::Pass => "pass", - Self::Warning => "warning", - Self::Fail => "fail", - Self::NotApplicable => "not_applicable", - Self::Unknown => "unknown", - } - } -} - -#[derive(Debug, Serialize)] -struct EvidenceReference { - kind: &'static str, - reference: String, -} - -#[derive(Debug, Serialize)] -struct ApplicabilityDecision { - status: ControlStatus, - classification: String, - owner: Option, - reviewed_at: Option, -} - -#[derive(Debug, Serialize)] -struct EuAiActAttestation { - report_type: &'static str, - evaluator_version: &'static str, - product_version: &'static str, - source_identity: Option, - config_generation: Option, - config_source_revision: Option, - generated_at: String, - applicability: ApplicabilityDecision, - default_provider: Option, - total_checks: usize, - passed_count: usize, - warning_count: usize, - failed_count: usize, - unknown_count: usize, - not_applicable_count: usize, - checks: Vec, -} - -#[derive(Debug, Serialize)] -struct EuAiActCheck { - id: &'static str, - framework_reference: &'static str, - control: &'static str, - applicability: &'static str, - severity: &'static str, - status: ControlStatus, - observed_at: String, - evidence: Vec, - explanation: String, - remediation: String, -} - -#[derive(Copy, Clone, Debug, Eq, PartialEq, ValueEnum)] -enum CompletionShell { - #[value(name = "bash")] - Bash, - #[value(name = "fish")] - Fish, - #[value(name = "zsh")] - Zsh, - #[value(name = "powershell")] - PowerShell, - #[value(name = "elvish")] - Elvish, -} - -#[derive(Subcommand, Debug)] -enum TokenCommands { - Issue { - #[arg(long)] - out: PathBuf, - #[arg(long)] - force: bool, - }, -} - -#[derive(Subcommand, Debug)] -enum Commands { - /// Issue an install-owner bearer into a private output file - Token { - #[command(subcommand)] - command: TokenCommands, - }, - /// Initialize or repair configuration, channels and agent identity - Init { - /// Configuration preset (default: minimal) - #[arg(long, value_enum)] - spec: Option, - /// Target configuration directory - #[arg(long)] - dir: Option, - /// Repair existing configuration while preserving explicit operator settings - #[arg(long)] - force: bool, - - /// Run the full interactive wizard (default is quick setup) - #[arg(long)] - interactive: bool, - - /// Reconfigure channels only (fast repair flow) - #[arg(long)] - channels_only: bool, - - /// API key (quick mode only). Deprecated: an - /// argument is visible in the process list; use --from-stdin or --from-env - #[arg(long)] - api_key: Option, - - /// Read the API key from standard input (quick mode) - #[arg(long, conflicts_with_all = ["api_key", "from_env"])] - from_stdin: bool, - - /// Read the API key from this environment variable (quick mode) - #[arg(long, value_name = "VAR", conflicts_with = "api_key")] - from_env: Option, - - /// Provider name (quick mode; otherwise preserve the preset or existing selection) - #[arg(long)] - provider: Option, - /// Model ID override (used in quick mode) - #[arg(short = 'm', long)] - model: Option, - /// Declare native tool support for a model outside the release catalog (quick mode) - #[arg(long, conflicts_with = "no_native_tools")] - native_tools: bool, - /// Declare that a model outside the release catalog has no native tools (quick mode) - #[arg(long, conflicts_with = "native_tools")] - no_native_tools: bool, - /// Memory backend (sqlite, lucid, markdown, none) - used in quick mode, default: sqlite - #[arg(long)] - memory: Option, - /// The decision backend (quick mode): builtin or compatible_http; a - /// hosted service also needs --decision-credential-stdin - #[arg(long, value_enum)] - decision_backend: Option, - /// The decision endpoint (quick mode, compatible_http) - #[arg(long, requires = "decision_backend")] - decision_endpoint: Option, - /// The decision model, one exact version (quick mode) - #[arg(long, requires = "decision_backend")] - decision_model: Option, - /// Enable the advisory decision engine (quick mode): sets decision_engine.enabled = true - #[arg(long, requires = "decision_backend")] - decision_enable: bool, - /// Read the hosted decision backend's credential (typesafe or - /// openrouter) from standard input, store it as `cred-decision-` - /// and reference it (quick mode). Remote processing stays off until - /// `backend.remote_enabled` is set with `prx decision-engine config set` - #[arg(long, requires = "decision_backend", conflicts_with = "from_stdin")] - decision_credential_stdin: bool, - }, - - /// Instant start: provide an API key and chat immediately. No config files written. - #[command(long_about = "\ -Zero-configuration instant start. - -Detects credentials from multiple file-based sources without reading \ -environment variables. Provide an API key directly, or let PRX find \ -one from auth-profiles, config.toml, or Claude Code OAuth. - -No permanent files are written. A temporary workspace is used for \ -the session. - -Examples: - prx go -k sk-ant-api03-xxx # Anthropic (auto-detected) - prx go -k sk-proj-xxx # OpenAI (auto-detected) - prx go -k sk-ant-xxx -m claude-sonnet-4-20250514 - prx go # use existing auth-profiles - prx go --message 'Summarize this' # single-shot mode")] - Go { - /// API key (required on first use, or use existing auth-profiles). Deprecated: - /// an argument is visible in the process list; use --from-env - #[arg(short = 'k', long = "key")] - api_key: Option, - - /// Read the API key from this environment variable - #[arg(long, value_name = "VAR", conflicts_with = "api_key")] - from_env: Option, - - /// Read the API key from standard input (then the session reads no further input from - /// it; use with --message, or --from-env for an interactive session) - #[arg(long, conflicts_with_all = ["api_key", "from_env"])] - from_stdin: bool, - - /// Provider (auto-detected from key prefix if omitted) - #[arg(short = 'p', long)] - provider: Option, - - /// Model (uses provider default if omitted) - #[arg(short = 'm', long)] - model: Option, - - /// Single message mode (non-interactive) - #[arg(long)] - message: Option, - }, - - /// Start an interactive chat session with streaming output - #[command(long_about = "\ -Start an interactive chat session with the fullscreen terminal UI. - -Features streaming responses, tool execution display, and session history. -Uses the full Agent pipeline: memory recall, LLM routing, built-in tools, -and all configured providers. - -The fullscreen UI keeps transcript history inside PRX rather than in native -terminal scrollback. Use in-app scrolling while chatting and `/export [md|json]` -to save a transcript. Use `--plain` or `PRX_TUI=0` for the non-TUI reedline -fallback. - -Examples: - prx chat # fullscreen interactive session - prx chat -p ollama -m llama3.3 # use local model - prx chat -p anthropic # use Anthropic - PRX_TUI=0 prx chat # plain reedline fallback - prx chat --plain # plain text fallback - prx chat --continue # resume last session - prx chat --session last # resume last session - prx chat --session abc123 # resume specific session - prx chat --list-sessions # list saved sessions - prx chat --message 'What is 2+2?' # one turn: the reply on stdout, then exit - prx chat -q 'Summarize x' --save # one turn, saved as a resumable session - prx chat --session abc123 -q 'More?' # one turn in a saved session - -With --message (-q) chat runs exactly one turn and prints only the reply on \ -stdout. The message is literal model input; slash text is not a command. \ -Exit status: 0 answered, 2 refused by policy (the refusal reply is still \ -printed), 1 any other failure (`Error: ...` on stderr). The turn is not saved \ -as a session unless --save, --session or --continue is given; --session or \ ---continue naming no saved session is an error. In Supervised mode tool \ -approvals are asked on the terminal ([y/N/a]); without a terminal only \ -OPENPRX_APPROVAL_OVERRIDE can allow.")] - Chat { - /// Controlled H2 root ceilings JSON (aggregate resources, per-root time/concurrency). - #[arg(long = "h2-controlled-limits", requires = "h2_authority_seconds", - conflicts_with_all = ["plain", "list_sessions", "provider", "model", "temperature"])] - h2_limits: Option, - - /// Lifetime of this foreground OS-launched H2 authority, in seconds. - #[arg(long, requires = "h2_limits")] - h2_authority_seconds: Option, - - /// Provider to use (openrouter, anthropic, openai, ollama, etc.) - #[arg(short, long)] - provider: Option, - - /// Model to use - #[arg(short = 'm', long)] - model: Option, - - /// Temperature (0.0 - 2.0) - #[arg(short, long, default_value = "0.7", value_parser = parse_temperature)] - temperature: f64, - - /// Plain text output (no ANSI escapes, for piping) - #[arg(long)] - plain: bool, - - /// Resume a session by ID, or "last" for the most recent - #[arg(short, long)] - session: Option, - - /// Resume the most recent saved session. Explicit --session wins if both are provided. - #[arg(long = "continue")] - continue_last: bool, - - /// List all saved sessions and exit - #[arg(long)] - list_sessions: bool, - - /// Run one turn with this message, print only the reply and exit - #[arg(short = 'q', long, conflicts_with_all = ["list_sessions", "h2_limits", "h2_authority_seconds"])] - message: Option, - - /// Save the --message turn as a resumable chat session - #[arg(long, requires = "message")] - save: bool, - - /// Absolute existing working directory for shell, file tools and git. - #[arg(long, value_parser = parse_workdir)] - workdir: Option, - }, - - /// Start the gateway server (webhooks, websockets) - #[command(long_about = "\ -Start the gateway server (webhooks, websockets). - -Runs the HTTP/WebSocket gateway that accepts incoming webhook events \ -and WebSocket connections. Bind address defaults to the values in \ -your config file (gateway.host / gateway.port). - -Examples: - prx gateway # use config defaults - prx gateway -p 8080 # listen on port 8080 - prx gateway --host 0.0.0.0 # bind to all interfaces - prx gateway -p 0 # random available port")] - Gateway { - /// Delegate only this exact authenticated principal to the existing owner. - #[arg(long, requires_all = ["h2_limits", "h2_authority_seconds"])] - h2_principal: Option, - - /// Controlled H2 root ceilings JSON; excludes ordinary conversational spending. - #[arg(long = "h2-controlled-limits", requires_all = ["h2_principal", "h2_authority_seconds"])] - h2_limits: Option, - - /// Lifetime of the foreground local-review authority, in seconds. - #[arg(long, requires_all = ["h2_principal", "h2_limits"])] - h2_authority_seconds: Option, - - /// Port to listen on (use 0 for random available port); defaults to config gateway.port - #[arg(short, long)] - port: Option, - - /// Host to bind to; defaults to config gateway.host - #[arg(long)] - host: Option, - }, - - /// Start long-running autonomous runtime (gateway + channels + heartbeat + scheduler) - #[command(long_about = "\ -Start the long-running autonomous daemon. - -Launches the full OpenPRX runtime: gateway server, all configured \ -channels (Telegram, Discord, Slack, etc.), heartbeat monitor, and \ -the cron scheduler. This is the recommended way to run OpenPRX in \ -production or as an always-on assistant. - -Use 'prx service install' to register the daemon as an OS \ -service (systemd/launchd) for auto-start on boot. - -Examples: - prx daemon # use config defaults - prx daemon -p 9090 # gateway on port 9090 - prx daemon --host 127.0.0.1 # localhost only")] - Daemon { - /// Port to listen on (use 0 for random available port); defaults to config gateway.port - #[arg(short, long)] - port: Option, - - /// Host to bind to; defaults to config gateway.host - #[arg(long)] - host: Option, - }, - - /// Manage OS service lifecycle (launchd/systemd user service) - Service { - /// Init system to use: auto (detect), systemd, or openrc - #[arg(long, default_value = "auto", value_parser = ["auto", "systemd", "openrc"])] - service_init: String, - - #[command(subcommand)] - service_command: ServiceCommands, - }, - - /// Run diagnostics for daemon/scheduler/channel freshness - Doctor { - #[command(subcommand)] - doctor_command: Option, - }, - - /// Show system status (full details) - Status { - #[arg(long)] - json: bool, - }, - - /// Inspect and terminate work running inside a live PRX process - #[command(long_about = "\ -Inspect and terminate work running inside a live PRX process. - -PRX does not cut work off on a clock: a long agent run is normal business, so -nothing expires by itself. That makes this command the operator's backstop — -it lists every tool call, sub-agent run and child process the runtime is -currently holding, together with parent/child lineage and elapsed time, and -ends any of them on request. - -The registry lives inside the process that owns the work, so these subcommands -talk to a running gateway over HTTP rather than inspecting this invocation. - -Examples: - prx tasks list # what is running right now - prx tasks list --json # machine-readable, includes unreaped children - prx tasks kill w42 # kill w42 and everything it started - prx tasks kill w42 --no-cascade # kill only w42 - prx tasks kill # same, addressed by run id - prx tasks kill # end every member of a spawn_batch fan-out - prx tasks send \"also check Y\" # steer a running task mid-flight - prx tasks pools # connection-pool saturation")] - Tasks { - #[command(subcommand)] - tasks_command: TasksCommands, - }, - - /// Manage memory indexes and maintenance operations - Memory { - #[command(subcommand)] - memory_command: MemoryCommands, - }, - - /// Evolution dashboard and operations - Evolution { - /// Output machine-readable JSON - #[arg(long, global = true)] - json: bool, - #[command(subcommand)] - evolution_command: EvolutionCommands, - }, - - /// Inspect, authorize, and reload trusted WASM plugin artifacts. - #[cfg(feature = "wasm-plugins")] - Plugin { - #[command(subcommand)] - command: openprx::plugins::cli::PluginCommand, - }, - - /// Read workspace costs and outstanding reservations without creating state. - Cost { - /// Output machine-readable JSON. - #[arg(long)] - json: bool, - }, - - /// Inspect, run, and migrate daily self-system fitness snapshots. - Fitness { - /// Output machine-readable JSON. - #[arg(long, global = true)] - json: bool, - #[command(subcommand)] - fitness_command: FitnessCommands, - }, - - /// Configure and manage scheduled tasks - #[command(long_about = "\ -Configure and manage scheduled tasks. - -Schedule recurring, one-shot, or interval-based tasks using cron \ -expressions, RFC 3339 timestamps, durations, or fixed intervals. - -Cron expressions use the standard 5-field format: \ -'min hour day month weekday'. Timezones default to UTC; \ -override with --tz and an IANA timezone name. - -Examples: - prx cron list - prx cron add '0 9 * * 1-5' 'Good morning' --tz America/New_York - prx cron add '*/30 * * * *' 'Check system health' - prx cron add-at 2025-01-15T14:00:00Z 'Send reminder' - prx cron add-every 60000 'Ping heartbeat' - prx cron once 30m 'Run backup in 30 minutes' - prx cron pause - prx cron update --expression '0 8 * * *' --tz Europe/London")] - Cron { - #[command(subcommand)] - cron_command: CronCommands, - }, - - /// Manage Xin autonomous tasks and durable goal workflows. - #[command(long_about = "\ -Manage Xin autonomous tasks, execution history, and durable Goal/Step workflows. - -Examples: - prx xin status - prx xin list - prx xin add nightly-check 'Inspect service health' --recurring --interval-secs 3600 - prx xin update --priority high - prx xin run - prx xin cancel - prx xin goals add release-checklist - prx xin steps add verify 'Verify the release artifacts'")] - Xin { - #[command(subcommand)] - xin_command: XinCommands, - }, - - /// Retired: prints one line pointing at `prx decision-engine` - #[command(hide = true)] - Causal { - /// Ignored arguments of the retired command. - #[arg(num_args = 0.., trailing_var_arg = true, allow_hyphen_values = true)] - args: Vec, - }, - - /// Inspect and configure the advisory decision engine - DecisionEngine { - /// Output machine-readable JSON. - #[arg(long, global = true)] - json: bool, - #[command(subcommand)] - command: openprx::decision_engine_cli::DecisionEngineCommands, - }, - - /// Manage provider model catalogs - Models { - #[command(subcommand)] - model_command: Option, - }, - - /// List, configure and test AI providers and their credentials - #[command(long_about = "\ -List, configure and test AI providers and their credentials. - -With no subcommand, lists the supported providers and the configured ones. \ -Every change prints its plan first and writes nothing without --yes. \ -A credential is never taken on the command line: it is read from a hidden \ -prompt, standard input (--from-stdin) or an environment variable (--from-env). - -Examples: - prx providers - prx providers show anthropic - prx providers add anthropic --fallback --yes - prx providers credential status openai # which key PRX uses today - prx auth paste-token --provider openai --from-stdin - prx providers test openrouter --live")] - Providers { - #[command(subcommand)] - providers_command: Option, - }, - - /// Manage model routes (`hint:` selections) - Routes { - #[command(subcommand)] - routes_command: RoutesCommands, - }, - - /// Manage channels (telegram, discord, slack, wacli) - #[command(long_about = "\ -Manage communication channels. - -Add, remove, list, and health-check channels that connect OpenPRX \ -to messaging platforms. Supported channel types: telegram, discord, \ -slack, whatsapp, wacli, imessage, and email. - -Examples: - prx channel list - prx channel doctor - prx channel add telegram '{\"bot_token\":\"...\",\"name\":\"my-bot\"}' - prx channel remove my-bot - prx channel bind-telegram prx_user")] - Channel { - #[command(subcommand)] - channel_command: ChannelCommands, - }, - - /// Browse 50+ integrations - Integrations { - #[command(subcommand)] - integration_command: Option, - }, - - /// Manage skills (user-defined capabilities) - Skills { - #[command(subcommand)] - skill_command: SkillCommands, - }, - - /// Migrate data from other agent runtimes - Migrate { - #[command(subcommand)] - migrate_command: MigrateCommands, - }, - - /// Manage provider subscription authentication profiles - Auth { - #[command(subcommand)] - auth_command: AuthCommands, - }, - - /// Manage runtime approval grants - Approval { - #[command(subcommand)] - approval_command: ApprovalCommands, - }, - - /// Generate runtime audit attestations - Audit { - #[command(subcommand)] - audit_command: AuditCommands, - }, - - /// Manage configuration - #[command(long_about = "\ -Manage OpenPRX configuration. - -Inspect and export configuration settings. Use 'schema' to dump \ -the full JSON Schema for the config file, which documents every \ -available key, type, and default value. - -Examples: - prx config show # print effective config as TOML - prx config show --format json # print effective config as JSON - prx config schema # print JSON Schema to stdout - prx config schema > schema.json")] - Config { - #[command(subcommand)] - config_command: ConfigCommands, - }, - - #[cfg(feature = "test-mock")] - // Bash completion uses `__` as its path separator. Keep the contracted - // fixture spelling as a hidden alias, outside completion's command tree. - #[command(name = "mailbox-harness", alias = "__mailbox-harness", hide = true)] - MailboxHarness { - #[arg(value_parser=["accept-adopt"])] - action: String, - #[arg(long)] - workspace: std::path::PathBuf, - #[arg(long)] - worker: bool, - #[arg(long, default_value_t = 1)] - turns: usize, - }, - - /// Internal worker entrypoint for process-isolated sessions - SessionWorker { - /// Optional task override (normally provided in stdin manifest) - #[arg(long)] - task: Option, - /// Optional workspace override (normally provided in stdin manifest) - #[arg(long)] - workspace: Option, - /// Optional memory DB override (normally provided in stdin manifest) - #[arg(long)] - memory_db: Option, - /// Optional allowed tools JSON array override (normally provided in stdin manifest) - #[arg(long)] - tools: Option, - }, - - /// Generate shell completion script to stdout - #[command(long_about = "\ -Generate shell completion scripts for `prx`. - -The script is printed to stdout so it can be sourced directly: - -Examples: - source <(prx completions bash) - prx completions zsh > ~/.zfunc/_prx - prx completions fish > ~/.config/fish/completions/prx.fish")] - Completions { - /// Target shell - #[arg(value_enum)] - shell: CompletionShell, - }, -} - -#[derive(Subcommand, Debug)] -enum TasksCommands { - /// List work items the running process is currently holding - List { - /// Output machine-readable JSON - #[arg(long)] - json: bool, - /// Gateway base URL (default: the configured gateway bind address) - #[arg(long)] - url: Option, - /// Bearer token, when the gateway requires pairing - #[arg(long)] - token: Option, - }, - /// Terminate one work item by id - Kill { - /// Run id, work item id as printed by `prx tasks list` (`w42` or `42`), - /// or the batch id of a `spawn_batch` fan-out (ends the whole batch) - id: String, - /// Kill only this item, leaving the tools and processes it started - /// running. Cascading is the default because nothing else will clean - /// those up. - #[arg(long)] - no_cascade: bool, - /// Output machine-readable JSON - #[arg(long)] - json: bool, - /// Gateway base URL (default: the configured gateway bind address) - #[arg(long)] - url: Option, - /// Bearer token, when the gateway requires pairing - #[arg(long)] - token: Option, - }, - /// Send a message to a running task, redirecting it mid-flight - /// - /// Addresses a run started from any entry point — a channel message, the - /// chat TUI, another `prx` — because the work registry is process-wide. - /// Use the run id from `prx tasks list`; `w42` works too but means nothing - /// outside this machine. - Send { - /// Run id (portable) or work item id as printed by `prx tasks list` - id: String, - /// The instruction to hand to the running task - message: String, - /// Output machine-readable JSON - #[arg(long)] - json: bool, - /// Gateway base URL (default: the configured gateway bind address) - #[arg(long)] - url: Option, - /// Bearer token, when the gateway requires pairing - #[arg(long)] - token: Option, - }, - /// Show connection-pool occupancy and saturation counters - Pools { - /// Output machine-readable JSON - #[arg(long)] - json: bool, - /// Gateway base URL (default: the configured gateway bind address) - #[arg(long)] - url: Option, - /// Bearer token, when the gateway requires pairing - #[arg(long)] - token: Option, - }, -} - -#[derive(Subcommand, Debug)] -enum ConfigCommands { - /// Set the Brave Search credential from stdin without an argument or echo - BraveKey { - #[arg(long, required = true)] - from_stdin: bool, - #[command(flatten)] - apply: ApplyArgs, - }, - /// Print the effective merged configuration - Show { - /// Output format - #[arg(long, value_enum, default_value_t = ConfigShowFormat::Toml)] - format: ConfigShowFormat, - }, - /// Dump the full configuration JSON Schema to stdout - Schema, - /// Split config.toml into config.d/*.toml fragments - Split { - /// Preview the generated files without writing them - #[arg(long)] - dry_run: bool, - }, - /// Merge config.d/*.toml back into a single config.toml - Merge, - /// Show the plan of writing a configuration file; nothing is written - Plan { - /// The new content of the file - #[arg(long, value_name = "PATH")] - file: PathBuf, - /// Which configuration file it replaces (`config.toml` or a `config.d` fragment name) - #[arg(long, default_value = "config.toml")] - target: String, - /// Permit this raw replacement to omit or empty stored secret slots - #[arg(long)] - allow_credential_clear: bool, - }, - /// Write a configuration file through the configuration transaction - Apply { - /// The new content of the file - #[arg(long, value_name = "PATH")] - file: PathBuf, - /// Which configuration file it replaces (`config.toml` or a `config.d` fragment name) - #[arg(long, default_value = "config.toml")] - target: String, - /// Permit this raw replacement to omit or empty stored secret slots - #[arg(long)] - allow_credential_clear: bool, - #[command(flatten)] - apply: ApplyArgs, - }, - /// List, show or purge the recorded configuration changes - History { - #[command(subcommand)] - history_command: Option, - }, - /// Restore the configuration from before a recorded change - Rollback { - /// The history record to undo (see `prx config history`) - #[arg(required_unless_present = "last", conflicts_with = "last")] - id: Option, - /// Undo the most recent recorded change - #[arg(long)] - last: bool, - /// Apply the rollback (without it, only what it would do is shown) - #[arg(long)] - yes: bool, - /// Allow restoring a credential the current configuration no longer holds - #[arg(long)] - restore_credentials: bool, - /// Allow a rollback that turns `secrets.encrypt` off - #[arg(long)] - disable_encryption: bool, - }, - /// Show the configuration revision, the default model's status and pending changes - Status, - /// Manage the model bindings of delegate agents - Agents { - #[command(subcommand)] - agents_command: AgentsCommands, - }, -} - -/// How a mutating management command applies its plan. -#[derive(Args, Debug, Clone, Default)] -struct ApplyArgs { - /// Apply the plan (without it, the plan is shown and nothing is written) - #[arg(long)] - yes: bool, - /// Confirm a high-risk plan; names the revision the plan reported - #[arg(long, value_name = "REVISION", requires = "yes")] - confirm_high_risk: Option, -} - -/// Which operation a default or a route serves. -#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, ValueEnum)] -enum OperationArg { - #[default] - Chat, - Embedding, -} - -#[derive(Subcommand, Debug)] -enum HistoryCommands { - /// List the recorded changes, newest first - List, - /// Show one recorded change - Show { - /// The history record id - id: String, - }, - /// Remove every history record (after a leaked credential was rotated) - Purge { - /// Remove them (required) - #[arg(long)] - yes: bool, - }, -} - -#[derive(Subcommand, Debug)] -enum AgentsCommands { - /// Create a role with a system-managed identity directory - New { - agent: String, - #[arg(long)] - provider: String, - #[arg(long)] - model: String, - #[command(flatten)] - apply: ApplyArgs, - }, - /// List the delegate agents and their model bindings - List, - /// Bind an existing agent to a provider and model - Set { - /// The agent name (`[agents.]`) - agent: String, - /// The provider - provider: String, - /// The model - model: String, - #[command(flatten)] - apply: ApplyArgs, - }, -} - -#[derive(Subcommand, Debug)] -enum ProvidersCommands { - /// List the supported providers and the configured ones - List, - /// Show one provider: identity, roles, uses, declarations and credential status - Show { - /// The provider (`openai`, `custom:`, ...) - provider: String, - }, - /// Add a provider to the configured set in a role; today the only role is the failover chain - /// (`--fallback`, `reliability.fallback_providers`) - Add { - /// The provider (`anthropic`, `custom:`, ...) - provider: String, - /// Add it to the failover chain (`reliability.fallback_providers`); required, so a later - /// role cannot change what an existing script does - #[arg(long, required = true)] - fallback: bool, - /// Append a model fallback for the current default model (shared by the provider chain) - #[arg(long)] - model: Option, - #[command(flatten)] - apply: ApplyArgs, - }, - /// Change the endpoint of the default provider (`api_url`) - Update { - /// The default provider - provider: String, - /// The new endpoint URL - #[arg(long, conflicts_with = "clear_api_url", required_unless_present = "clear_api_url")] - api_url: Option, - /// Remove the endpoint override - #[arg(long)] - clear_api_url: bool, - #[command(flatten)] - apply: ApplyArgs, - }, - /// Remove a provider (refused while any selection still uses it) - Remove { - /// The provider - provider: String, - #[command(flatten)] - apply: ApplyArgs, - }, - /// Check that a provider and model resolve; `--live` also requests the model list once - Test { - /// The provider (default: the configured default provider) - provider: Option, - /// The model (default: the configured default model) - #[arg(long)] - model: Option, - /// Also send one model-list request to the provider (never a generation) - #[arg(long)] - live: bool, - }, - /// Manage the credential references of a provider - Credential { - #[command(subcommand)] - credential_command: CredentialCommands, - }, - /// Report legacy provider configuration (inline route, embedding-route and agent keys, the - /// `[[providers.tool_dialects]]` table, unverified selections, tokens stored under an alias). - /// With --apply, plan moving the inline keys into credential references and the dialect rows - /// into `[[providers.models]]`; --yes writes it through the configuration transaction - /// (`prx config rollback` undoes it) - Migrate { - /// Plan the migration instead of only reporting - #[arg(long)] - apply: bool, - #[command(flatten)] - write: ApplyArgs, - }, -} - -/// Management commands that only read: they load an existing configuration -/// read-only, so neither loading nor the legacy-secret upgrade writes -/// anything (D-101 F-5). -const fn read_only_management_command(command: &Commands) -> bool { - match command { - Commands::Providers { providers_command } => { - matches!( - providers_command, - None | Some( - ProvidersCommands::List - | ProvidersCommands::Show { .. } - | ProvidersCommands::Test { .. } - | ProvidersCommands::Credential { - credential_command: CredentialCommands::Status { .. }, - } - ) - ) || matches!( - providers_command, - Some(ProvidersCommands::Migrate { - write: ApplyArgs { yes: false, .. }, - .. - }) - ) - } - Commands::Config { config_command } => matches!( - config_command, - ConfigCommands::Status - | ConfigCommands::Show { .. } - | ConfigCommands::Schema - | ConfigCommands::Plan { .. } - | ConfigCommands::Agents { - agents_command: AgentsCommands::List, - } - | ConfigCommands::History { - history_command: None | Some(HistoryCommands::List | HistoryCommands::Show { .. }), - } - ), - Commands::Routes { routes_command } => matches!(routes_command, RoutesCommands::List { .. }), - Commands::Models { model_command } => { - matches!( - model_command, - None | Some(ModelCommands::List { .. } | ModelCommands::Show { .. }) - ) - } - _ => false, - } -} - -#[derive(Subcommand, Debug)] -enum CredentialCommands { - /// Store a credential reference for a provider; a model route, embedding route or agent of that - /// provider uses it when its `credential_ref` names it. Read from a hidden prompt, --from-stdin - /// or --from-env; never an argument - Set { - /// The provider the credential is issued for - provider: String, - /// The reference name (stored as `cred-`; default: the catalog provider's name) - #[arg(long)] - name: Option, - /// Read the credential from standard input - #[arg(long, conflicts_with = "from_env")] - from_stdin: bool, - /// Read the credential from this environment variable - #[arg(long, value_name = "VAR")] - from_env: Option, - }, - /// Remove a credential reference (refused while the configuration names it) - Remove { - /// The reference (`cred-` or ``) - reference: String, - }, - /// Show credential status (never a value): every reference, or one provider's credentials - Status { - /// The provider (default: every credential reference) - provider: Option, - }, -} - -#[derive(Subcommand, Debug)] -enum RoutesCommands { - /// List the routes - List { - /// Which route table - #[arg(long, value_enum, default_value_t = OperationArg::Chat)] - operation: OperationArg, - }, - /// Add a route - Add { - /// The route hint (`hint:` selects it) - hint: String, - /// The provider - provider: String, - /// The model - model: String, - /// Which route table - #[arg(long, value_enum, default_value_t = OperationArg::Chat)] - operation: OperationArg, - #[command(flatten)] - apply: ApplyArgs, - }, - /// Change a route's provider or model - Update { - /// The route hint - hint: String, - /// The new provider - #[arg(long)] - provider: Option, - /// The new model - #[arg(long)] - model: Option, - /// Which route table - #[arg(long, value_enum, default_value_t = OperationArg::Chat)] - operation: OperationArg, - #[command(flatten)] - apply: ApplyArgs, - }, - /// Remove a route (refused while a selection names it) - Remove { - /// The route hint - hint: String, - /// Which route table - #[arg(long, value_enum, default_value_t = OperationArg::Chat)] - operation: OperationArg, - #[command(flatten)] - apply: ApplyArgs, - }, -} - -#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)] -enum ConfigShowFormat { - Toml, - Json, -} - -#[derive(Subcommand, Debug)] -enum AuthCommands { - /// Login with a subscription OAuth provider (`openai-codex` or `xai`) - Login { - /// Provider (`openai-codex` or `xai`) - #[arg(long)] - provider: String, - /// Profile name (default: default) - #[arg(long, default_value = "default")] - profile: String, - /// Use OAuth device-code flow - #[arg(long)] - device_code: bool, - }, - /// Complete OAuth by pasting redirect URL or auth code (`openai-codex` or `xai`) - PasteRedirect { - /// Provider (`openai-codex` or `xai`) - #[arg(long)] - provider: String, - /// Profile name (default: default) - #[arg(long, default_value = "default")] - profile: String, - /// Full redirect URL or raw OAuth code - #[arg(long)] - input: Option, - }, - /// Paste setup token / auth token (for Anthropic subscription auth) - PasteToken { - /// Provider (`anthropic`) - #[arg(long)] - provider: String, - /// Profile name (default: default) - #[arg(long, default_value = "default")] - profile: String, - /// Token value (if omitted, read interactively). Deprecated: an argument is - /// visible in the process list; use --from-stdin or the prompt - #[arg(long)] - token: Option, - /// Read the token from standard input - #[arg(long, conflicts_with = "token")] - from_stdin: bool, - /// Auth kind override (`authorization` or `api-key`) - #[arg(long)] - auth_kind: Option, - }, - /// Alias for `paste-token` (interactive by default) - SetupToken { - /// Provider (`anthropic`) - #[arg(long)] - provider: String, - /// Profile name (default: default) - #[arg(long, default_value = "default")] - profile: String, - }, - /// Refresh a subscription access token (`openai-codex` or `xai`) - Refresh { - /// Provider (`openai-codex` or `xai`) - #[arg(long)] - provider: String, - /// Profile name or profile id - #[arg(long)] - profile: Option, - }, - /// Remove auth profile - Logout { - /// Provider - #[arg(long)] - provider: String, - /// Profile name (default: default) - #[arg(long, default_value = "default")] - profile: String, - }, - /// Set active profile for a provider - Use { - /// Provider - #[arg(long)] - provider: String, - /// Profile name or full profile id - #[arg(long)] - profile: String, - }, - /// List auth profiles - List, - /// Show auth status with active profile and token expiry info - Status, -} - -#[derive(Subcommand, Debug)] -enum ModelCommands { - /// Inspect the embedded release catalog - Catalog { - #[command(subcommand)] - catalog_command: CatalogCommands, - }, - /// Plan published model replacements; --yes applies one PMM transaction - MigrateRetired { - #[command(flatten)] - apply: ApplyArgs, - }, - /// Show declared model levels and parameters from the release catalog - Levels { model: String }, - /// Show or update persisted model settings through a configuration transaction - Settings { - model: String, - #[arg(long, value_parser = ["low", "medium", "high"])] - level: Option, - /// Explicit override, repeated as --set name=JSON-value - #[arg(long = "set")] - overrides: Vec, - #[command(flatten)] - apply: ApplyArgs, - }, - /// List model catalogs; with --operation or --executable, every known model with what the - /// evidence says it can do - List { - /// Provider name (defaults to configured default provider) - #[arg(long)] - provider: Option, - /// Only models the evidence does not rule out for this operation (`chat`, `embedding`, ...) - #[arg(long)] - operation: Option, - /// Only models the evidence proves can execute the operation (chat when none is named) - #[arg(long)] - executable: bool, - }, - /// Show what the evidence says one model can do - Show { - /// The provider - provider: String, - /// The model - model: String, - }, - /// Refresh and cache provider models - Refresh { - /// Provider name (defaults to configured default provider) - #[arg(long)] - provider: Option, - - /// Force live refresh and ignore fresh cache - #[arg(long)] - force: bool, - }, - /// Declare what a model can do (`[[providers.models]]`) - Add(ModelDeclarationArgs), - /// Change a model declaration (only the facts given are replaced) - Update(ModelDeclarationArgs), - /// Remove a model declaration - Remove { - /// The provider - #[arg(long)] - provider: String, - /// The model (omit for the provider-wide declaration) - #[arg(long)] - model: Option, - #[command(flatten)] - apply: ApplyArgs, - }, - /// Show or set the default model of an operation - Default { - #[command(subcommand)] - default_command: DefaultCommands, - }, -} - -#[derive(Subcommand, Debug)] -enum CatalogCommands { - /// Show the embedded revision, content digest and lifecycle counts - Status, -} - -/// A `[[providers.models]]` declaration on the command line. -#[derive(Args, Debug)] -struct ModelDeclarationArgs { - /// The provider - #[arg(long)] - provider: String, - /// The model (omit to declare every model of the provider) - #[arg(long)] - model: Option, - /// The complete list of operations the model executes (comma-separated) - #[arg(long, value_delimiter = ',', value_parser = parse_setting::)] - operations: Option>, - /// Whether the model accepts native tool calls - #[arg(long)] - native_tools: Option, - /// Whether the model accepts image input - #[arg(long)] - vision_input: Option, - /// Whether the model streams responses - #[arg(long)] - streaming: Option, - /// Whether the model honours a JSON-schema response format - #[arg(long)] - structured_output: Option, - /// The tool-schema dialect the endpoint accepts (`raw`, `no_root_combinators`) - #[arg(long, value_parser = parse_setting::)] - tool_schema_dialect: Option, - /// The tool-call grammar the endpoint emits (`native`, `xml_function_tags`) - #[arg(long, value_parser = parse_setting::)] - tool_call_dialect: Option, - /// The context window in tokens - #[arg(long)] - context_window: Option, - #[command(flatten)] - apply: ApplyArgs, -} - -#[derive(Subcommand, Debug)] -enum DefaultCommands { - /// Show the default chat and embedding models and how they resolve - Show, - /// Set the default model of an operation - Set { - /// The provider - provider: String, - /// The model - model: String, - #[arg(long, value_parser = ["low", "medium", "high"])] - level: Option, - /// Explicit model parameter override, repeated as --set name=JSON-value - #[arg(long = "set")] - overrides: Vec, - /// Which default - #[arg(long, value_enum, default_value_t = OperationArg::Chat)] - operation: OperationArg, - /// The root connection (`api_key`, `api_url`, `reliability.api_keys`) belongs to the new - /// default provider (a high-risk change: the key is sent to it); chat only - #[arg(long, conflicts_with = "clear_root_credential")] - keep_root_credential: bool, - /// Clear the root connection (`api_key`, `api_url`, `reliability.api_keys`) with the switch; - /// chat only - #[arg(long)] - clear_root_credential: bool, - #[command(flatten)] - apply: ApplyArgs, - }, -} - -/// Parse a snake_case configuration setting (`no_root_combinators`) the way -/// the configuration file spells it. -fn parse_setting(text: &str) -> std::result::Result { - serde_json::from_value(serde_json::Value::String(text.trim().to_ascii_lowercase())) - .map_err(|_| format!("'{}' is not one of the accepted values", text.escape_default())) -} - -#[derive(Subcommand, Debug)] -enum DoctorCommands { - /// Probe model catalogs across providers and report availability - Models { - /// Probe a specific provider only (default: all known providers) - #[arg(long)] - provider: Option, - - /// Prefer cached catalogs when available (skip forced live refresh) - #[arg(long)] - use_cache: bool, - }, - /// Diagnose memory backend and embedding/vector configuration - Memory, - /// Report live runtime validation matrix readiness - Runtime, - /// List durable ingress rows that are not reconciled (read-only) - Ingress, -} - -/// Process-wide bound on how long the runtime drop will wait for stuck -/// blocking threads (notably the reedline `read_line` task that parks in -/// `spawn_blocking` reading from stdin). -/// -/// Without this bound, `#[tokio::main]`'s default runtime drop would -/// `join()` blocking threads forever; reedline's blocking stdin read does -/// not observe `CancellationToken`s, so e.g. the double-Ctrl-C exit path -/// (`shutdown.cancel()` → `chat::run` returns) would hang the process -/// until the user manually killed it. Capping the wait at 2 seconds gives -/// well-behaved shutdowns time to finish while preventing the foot-gun. -const RUNTIME_SHUTDOWN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2); - -/// Resolve the blocking-pool cap before the runtime exists. -/// -/// The pool size is fixed at `Builder` time, so it cannot come from the normal -/// config load (which is async and needs a runtime). We therefore do a -/// synchronous, read-only pre-read of `[runtime] max_blocking_threads`, falling -/// back to a cgroup-aware hardware-derived default. -/// -fn resolve_max_blocking_threads(cli: &Cli) -> usize { - openprx::config::bootstrap_max_blocking_threads(cli.config_dir.as_deref()) - .unwrap_or_else(openprx::runtime::blocking::default_max_blocking_threads) -} - -#[allow(unsafe_code)] -fn main() -> std::process::ExitCode { - // Build the runtime explicitly (instead of using `#[tokio::main]`) so - // that we can bound how long runtime drop waits for blocking threads. - // See `RUNTIME_SHUTDOWN_TIMEOUT` above for the rationale. - // - // The blocking pool is sized explicitly too. Tokio's default is a - // hardware-agnostic 512 threads, which is the process's last implicit - // concurrency gate now that turns, sub-agents and sessions are unbounded — - // and it fails by deadlock, not rejection: once every slot is held, further - // `spawn_blocking` calls queue forever with no timeout. - let cli = Cli::parse(); - let max_blocking_threads = resolve_max_blocking_threads(&cli); - let runtime = match tokio::runtime::Builder::new_multi_thread() - .enable_all() - .max_blocking_threads(max_blocking_threads) - .build() - .context("failed to build tokio runtime") - { - Ok(runtime) => runtime, - Err(err) => { - eprintln!("Error: {}", openprx::security::redaction::redacted_error_report(&err)); - return std::process::ExitCode::FAILURE; - } - }; - // Publish the real cap so blocking-pool saturation is measured against it. - openprx::runtime::blocking::configure(max_blocking_threads); - let result = runtime.block_on(async { - let result = Box::pin(async_main(cli)).await; - // Every exit path (REPL /exit, one-shot end, Ctrl-C/SIGTERM through the - // shutdown token, daemon shutdown, a process worker's own return) lands - // here: stop and reap the process-mode children this process owns, - // within the same bound, before the runtime drops their monitors. - openprx::tools::sessions_spawn::stop_owned_process_runs(RUNTIME_SHUTDOWN_TIMEOUT).await; - result - }); - runtime.shutdown_timeout(RUNTIME_SHUTDOWN_TIMEOUT); - match result { - Ok(()) => std::process::ExitCode::SUCCESS, - Err(err) => { - // A refused `prx chat --message` turn already printed its reply. - let code = openprx::chat::one_shot_exit_code(Some(&err)); - if code == openprx::chat::ONE_SHOT_REFUSAL_EXIT_CODE { - return std::process::ExitCode::from(code); - } - eprintln!("Error: {}", openprx::security::redaction::redacted_error_report(&err)); - std::process::ExitCode::FAILURE - } - } -} - -#[allow(clippy::too_many_lines)] -#[allow(unsafe_code)] -async fn async_main(cli: Cli) -> Result<()> { - // Install default crypto provider for Rustls TLS. - // This prevents the error: "could not automatically determine the process-level CryptoProvider" - // when both aws-lc-rs and ring features are available (or neither is explicitly selected). - if let Err(e) = rustls::crypto::ring::default_provider().install_default() { - eprintln!("Warning: Failed to install default crypto provider: {e:?}"); - } - - if let Some(warning) = argv_secret_warning(&cli.command) { - eprintln!("{warning}"); - } - - if let Some(config_dir) = &cli.config_dir { - if config_dir.trim().is_empty() { - bail!("--config-dir cannot be empty"); - } - // Publish the explicit directory before anything can lazily create - // process-global state (witness key, session-worker secret) that has no - // `Config` in hand and would otherwise anchor on `$HOME/.openprx`. - config::set_process_config_dir(std::path::absolute(config_dir.trim()).context("resolve --config-dir")?); - } - - #[cfg(feature = "test-mock")] - if let Commands::MailboxHarness { - workspace, - worker, - turns, - .. - } = &cli.command - { - if *worker { - return session_worker::mailbox_harness::run(workspace, *turns).await; - } - return memory::sqlite::mailbox::harness::accept_adopt(workspace); - } - - // session-worker must stay stdout-clean for IPC JSON. - if let Commands::SessionWorker { - task, - workspace, - memory_db, - tools, - } = &cli.command - { - return session_worker::runner::run_from_stdin( - task.clone(), - workspace.clone(), - memory_db.clone(), - tools.clone(), - cli.config_dir.clone(), - ) - .await; - } - - // Completions must remain stdout-only and should not load config or initialize logging. - // This avoids warnings/log lines corrupting sourced completion scripts. - if let Commands::Completions { shell } = &cli.command { - let mut stdout = std::io::stdout().lock(); - write_shell_completion(*shell, &mut stdout)?; - return Ok(()); - } - - if let Commands::Token { - command: TokenCommands::Issue { out, force }, - } = &cli.command - { - let config = Config::load_or_init_with_config_dir(cli.config_dir.as_deref()).await?; - let owner = runtime::host_bootstrap::issue_token(config, out, *force).await?; - println!("{}\n{}", out.display(), owner); - return Ok(()); - } - if matches!(&cli.command, Commands::Init { .. }) { - return init_cli::run(&cli).await; - } - - // Initialize logging. RUST_LOG always wins when set. Otherwise foreground - // commands (chat, go, ...) default to warn on stderr so a scripted - // `prx chat --message 'What is 2+2?'` prints only the reply on stdout. Long-running - // services (daemon, gateway, channel start) keep info on the process - // default writer. Chat still uses a reloadable stderr subscriber so - // tracing can move to chat.log before configuration is loaded. - let tracing_defaults = cli_tracing_command(&cli.command).defaults(); - let env_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(tracing_defaults.filter)); - if tracing_defaults.write_stderr { - use tracing_subscriber::layer::SubscriberExt as _; - use tracing_subscriber::util::SubscriberInitExt as _; - - let stderr_writer = tracing_subscriber::fmt::writer::BoxMakeWriter::new(std::io::stderr); - let fmt_layer: ChatFmtLayer = tracing_subscriber::fmt::Layer::default().with_writer(stderr_writer); - let (reload_layer, reload_handle) = tracing_subscriber::reload::Layer::new(fmt_layer); - if CHAT_TRACING_RELOAD.set(reload_handle).is_err() { - eprintln!("BUG: CHAT_TRACING_RELOAD already initialized"); - } - if let Err(e) = tracing_subscriber::registry() - .with(env_filter) - .with(reload_layer) - .try_init() - { - eprintln!("failed to set default tracing subscriber: {e}"); - } - } else { - let subscriber = fmt::Subscriber::builder().with_env_filter(env_filter).finish(); - if let Err(e) = tracing::subscriber::set_global_default(subscriber) { - eprintln!("failed to set default tracing subscriber: {e}"); - } - } - - // Acquire this before Config::load_* and hold it through command dispatch. - // Fatal startup errors are still returned through anyhow and printed by - // main after this guard restores stderr; routine tracing stays in chat.log. - // `prx chat --message` keeps warn-level tracing on stderr instead. - let _chat_tracing_guard = if matches!(&cli.command, Commands::Chat { message: None, .. }) { - match chat::setup_chat_tracing_to_file() { - Ok(guard) => Some(guard), - Err(error) => { - tracing::warn!(%error, "keeping chat tracing on stderr because chat.log is unavailable"); - None - } - } - } else { - None - }; - - // `prx go` — zero-config instant start. No permanent files written. - if let Commands::Go { - api_key, - from_env, - from_stdin, - provider, - model, - message, - } = &cli.command - { - let api_key = manage_cli::secret_from( - *from_stdin, - from_env.as_deref(), - &mut std::io::stdin(), - &|name: &str| std::env::var(name).ok(), - )? - .or_else(|| api_key.clone()); - let (detected_provider, detected_key, detected_model) = - auth::discovery::detect_credentials(api_key.as_deref(), provider.as_deref(), model.as_deref()).context( - "No API key found. Run `prx auth paste-token --provider anthropic`, or use: prx go -k ", - )?; - - let tmpdir = tempfile::tempdir().context("failed to create temporary workspace for `prx go`")?; - - let mut config = Config::default(); - config.default_provider = Some(detected_provider); - config.default_model = Some(detected_model); - config.api_key = Some(detected_key); - config.workspace_dir = tmpdir.path().to_path_buf(); - config.config_path = tmpdir.path().join("config.toml"); - // `prx go` persists nothing, so the detected model is an invocation, - // resolved once where each path builds its provider: the agent entry - // for `--message`, chat start-up otherwise. An id-only model runs - // with a warning; one that cannot chat is refused before any - // provider exists. - - if let Some(msg) = message { - // `prx go --message` is the chat one-shot (`prx chat --message`): - // chat owns ctrl_c internally, so the token is never cancelled. - let result = chat::run_message( - config, - None, // provider already set in config - None, // model already set in config - 0.7, - chat::ChatMessageRequest { - message: msg.clone(), - save: false, - session: None, - }, - crate::runtime::shutdown::never_cancelled_shutdown(), - ) - .await; - // Keep tmpdir alive until the turn finishes, then drop - drop(tmpdir); - return result; - } - - // Non-dispatch direct call (`prx go` interactive chat): chat owns ctrl_c - // internally; no dispatch-level signal source. Use the explicitly-named - // never-cancelled token so chat's internal handler stays the sole owner. - let result = chat::run( - config, - None, // provider already set in config - None, // model already set in config - 0.7, - false, // plain mode off - None, // no session resume - false, // don't list sessions - crate::runtime::shutdown::never_cancelled_shutdown(), - ) - .await; - // Keep tmpdir alive until chat finishes, then drop - drop(tmpdir); - return result; - } - - // Diagnostic/schema inspection must not initialize config/workspace state. - // Baseline is routed through the same read-only loader because it is - // retained only as an explicit compatibility error, never as a write. - let read_only_config_command = matches!( - &cli.command, - Commands::Migrate { - migrate_command: MigrateCommands::Status - | MigrateCommands::Verify - | MigrateCommands::DryRun - | MigrateCommands::Plan { .. } - | MigrateCommands::Baseline - } - ) || matches!( - &cli.command, - Commands::Doctor { .. } - | Commands::Tasks { .. } - | Commands::Causal { .. } - | Commands::DecisionEngine { - command: openprx::decision_engine_cli::DecisionEngineCommands::Status - | openprx::decision_engine_cli::DecisionEngineCommands::Analyses { .. } - | openprx::decision_engine_cli::DecisionEngineCommands::Backends, - .. - } - | Commands::Cost { .. } - ); - #[cfg(feature = "wasm-plugins")] - let read_only_config_command = read_only_config_command || matches!(&cli.command, Commands::Plugin { .. }); - let mut config = if read_only_config_command { - Config::load_existing_read_only_with_config_dir(cli.config_dir.as_deref()).await? - } else if read_only_management_command(&cli.command) { - // Without a configuration yet: the defaults, shown, nothing written - // (D-101 F-5). - let config = Config::load_existing_or_defaults_read_only(cli.config_dir.as_deref()).await?; - if !config.config_path.exists() { - eprintln!( - "no config yet; showing defaults (nothing is written; {} is created by the first command that \ - changes the configuration)", - config.config_path.display() - ); - } - config - } else { - Config::load_or_init_with_config_dir(cli.config_dir.as_deref()).await? - }; - - if let Commands::Chat { - workdir: Some(root), .. - } = &cli.command - { - config.runtime.workdir = Some(root.clone()); - config.validate()?; - } - - // Covers the resolutions the flag does not carry (`OPENPRX_CONFIG_DIR`, - // `OPENPRX_WORKSPACE`, the active-workspace marker). No-op when the flag - // already published the same directory. - if let Some(resolved_config_dir) = config.config_path.parent() { - config::set_process_config_dir(resolved_config_dir.to_path_buf()); - } - - // `dispatch` logs the inherited-embedding-default notice for every - // long-running runtime, but chat's tracing has already been redirected into - // chat.log by this point, so for the one interactive entry point the - // warning went somewhere nobody looks. The process stderr is untouched by - // that redirect and the TUI has not taken the screen yet. - if matches!(&cli.command, Commands::Chat { message: None, .. }) { - chat::print_embedding_upgrade_notice_to_stderr(&config); - } - - mode::dispatch(cli.command, config).await -} - -/// The deprecation warning for a secret given as a command-line argument -/// (D-018 Q3, SP-PMM E-4). The flag keeps working; the warning names the -/// alternative that keeps the secret out of the process list and the shell -/// history. Never contains the secret. -fn argv_secret_warning(command: &Commands) -> Option { - let (flag, alternative) = match command { - Commands::Init { api_key: Some(_), .. } => ( - "--api-key", - "--from-stdin (pipe the key in: `printf %s \"$KEY\" | prx init --from-stdin`) or --from-env VAR", - ), - Commands::Go { api_key: Some(_), .. } => ("-k/--key", "--from-stdin or --from-env VAR"), - Commands::Auth { - auth_command: AuthCommands::PasteToken { token: Some(_), .. }, - } => ( - "--token", - "--from-stdin (pipe the token in), or leave the flag out to be prompted without echo", - ), - _ => return None, - }; - Some(format!( - "warning: a secret passed with {flag} is visible to other local users in the process list and stays in \ - your shell history; the flag is deprecated. Use {alternative} instead." - )) -} - -/// `prx tasks` — talks to a running process's gateway rather than inspecting -/// this one, because the work registry is per-process state. -async fn handle_tasks_command(command: TasksCommands, config: &Config) -> anyhow::Result<()> { - use openprx::runtime::tasks_cli::{self, TasksEndpoint}; - - match command { - TasksCommands::List { json, url, token } => { - let endpoint = TasksEndpoint::resolve(config, url, token); - let listing = tasks_cli::fetch_tasks(&endpoint).await?; - if json { - println!("{}", serde_json::to_string_pretty(&listing)?); - return Ok(()); - } - if listing.running.is_empty() { - println!("No work items are currently running."); - } else { - println!("Running work items ({}):", listing.running.len()); - print_work_items(&listing.running); - } - if !listing.unreaped.is_empty() { - println!(); - println!( - "Spawned but not reaped ({}) — children that outlived their owner:", - listing.unreaped.len() - ); - print_work_items(&listing.unreaped); - } - } - TasksCommands::Kill { - id, - no_cascade, - json, - url, - token, - } => { - let endpoint = TasksEndpoint::resolve(config, url, token); - let report = tasks_cli::request_kill(&endpoint, &id, !no_cascade).await?; - if json { - println!("{}", serde_json::to_string_pretty(&report)?); - } else { - println!( - "Killed {} (cascade: {}) — {} target(s):", - report.requested, - if report.cascade { "on" } else { "off" }, - report.targets.len() - ); - for target in &report.targets { - println!( - " {:<8} {:<10} {:<14} {}", - target.id, target.kind, target.outcome, target.name - ); - } - if report.targets.iter().any(|target| target.outcome == "requested") { - println!(); - println!( - "Some targets had not gone away yet when this report was produced. Nothing \ - was abandoned — re-run `prx tasks list` to see the current state." - ); - } - } - // A target with no termination handle is a partial result, not a success. - if report.targets.iter().any(|target| target.outcome == "not_killable") { - bail!("one or more targets had no termination handle and could not be killed"); - } - } - TasksCommands::Send { - id, - message, - json, - url, - token, - } => { - let endpoint = TasksEndpoint::resolve(config, url, token); - let report = tasks_cli::request_message(&endpoint, &id, &message).await?; - if json { - println!("{}", serde_json::to_string_pretty(&report)?); - } else { - println!("{}", render_task_message(&report)); - } - } - TasksCommands::Pools { json, url, token } => { - let endpoint = TasksEndpoint::resolve(config, url, token); - let report = tasks_cli::fetch_pools(&endpoint).await?; - if json { - println!("{}", serde_json::to_string_pretty(&report)?); - return Ok(()); - } - for pool in &report.pools { - println!("[{}] {}", pool.kind, pool.name); - if let Some(metrics) = pool.metrics.as_object() { - let mut keys: Vec<&String> = metrics.keys().collect(); - keys.sort(); - for key in keys { - if let Some(value) = metrics.get(key) { - println!(" {key:<32} {value}"); - } - } - } - println!(); - } - } - } - Ok(()) -} - -/// Render one work-item table, shared by the running and unreaped sections. -/// -/// Members of one `spawn_batch` fan-out are pulled together under a header at -/// the position of the batch's first member: they are siblings rather than a -/// lineage, so nothing else in the table says they belong to one another. A -/// listing with no batches renders exactly as it always did. -/// Render `prx tasks send` for a human, saying only what the server said. -/// -/// The server reports `outcome: "queued"` because accepting a message onto a -/// run's bounded steering queue is the whole of what it can observe: an mpsc -/// send proves the queue had room and the receiver still exists, never that -/// anybody polls it. A task-mode sub-agent with no tools registers a steering -/// sender and never reads the receiver, so its messages are accepted and -/// consumed by nobody. -/// -/// This renderer therefore prints the server's tag verbatim, labelled as the -/// outcome, and appends the server's own note when it sent one. It states no -/// delivery of its own: the previous "Delivered to ..." headline was a claim -/// the CLI was in no position to make, and an operator who read it went on -/// waiting for a target that was never going to act. -/// -/// MUTATION GUARD: reinstate a fixed "Delivered" headline and -/// `a_sent_message_is_reported_as_the_server_tagged_it` fails. -fn render_task_message(report: &openprx::runtime::tasks_cli::MessageReport) -> String { - let run_id = report.run_id.as_deref().unwrap_or("-"); - let mut out = format!( - "Message to {} [{}] {} (run_id: {}) — outcome: {}", - report.id, report.kind, report.name, run_id, report.outcome - ); - // Absent on a gateway older than the `queued` outcome. Nothing is - // substituted for it: a note this CLI wrote would be a client-side guess at - // a server-side guarantee. - if let Some(note) = report.note.as_deref() { - out.push('\n'); - out.push_str(note); - } - out -} - -fn print_work_items(items: &[openprx::runtime::tasks_cli::WorkItem]) { - println!( - "{:<8} {:<10} {:>10} {:<14} {:<}", - "ID", "KIND", "ELAPSED", "STATE", "NAME" - ); - for (batch_id, members) in openprx::runtime::tasks_cli::group_by_batch(items) { - if let Some(batch_id) = batch_id { - println!(" batch {batch_id} — {} member(s):", members.len()); - } - for item in members { - print_work_item(item, batch_id.is_some()); - } - } -} - -/// Render one row. `indented` marks a row as belonging to the batch header -/// above it. -fn print_work_item(item: &openprx::runtime::tasks_cli::WorkItem, indented: bool) { - println!("{}", work_item_line(item, indented)); -} - -/// The text of one listing row, split out from the printing so what an operator -/// reads can be asserted rather than eyeballed. -fn work_item_line(item: &openprx::runtime::tasks_cli::WorkItem, indented: bool) -> String { - let mut name = item.name.clone(); - if let Some(parent) = &item.parent { - name.push_str(&format!(" (parent {parent})")); - } - if let Some(run_id) = &item.run_id { - name.push_str(&format!(" (run {run_id})")); - } - // Marked, not columned: only a minority of rows can take a message, and a - // column would spend width on the ones that cannot. The mark exists because - // the KIND column reads like an answer and is not one — a detached gateway - // job is listed `sub_agent` and has no steering channel — so without it the - // only way to learn an item is unsteerable is to send it a message and read - // the refusal. - // - // MUTATION GUARD: drop this and `a_steerable_row_is_marked_and_a_look_alike_is_not` fails. - if item.steerable { - name.push_str(" (steerable)"); - } - if let Some(pid) = item.pid { - name.push_str(&format!(" (pid {pid}")); - match item.pgid { - Some(pgid) => name.push_str(&format!(", pgid {pgid})")), - None => name.push(')'), - } - } - let id = if indented { - format!(" {}", item.id) - } else { - item.id.clone() - }; - format!( - "{:<8} {:<10} {:>10} {:<14} {name}", - id, - item.kind, - openprx::runtime::tasks_cli::format_elapsed(item.elapsed_secs), - item.state - ) -} - -async fn handle_memory_command(command: MemoryCommands, config: &Config) -> anyhow::Result<()> { - match command { - MemoryCommands::Reindex { json } => { - let memory = memory::create_memory_with_storage_and_routes_with_acl( - &config.memory, - &config.embedding_routes_with_references(), - Some(&config.storage.provider.config), - &config.workspace_dir, - memory::EmbeddingRootCredential::from_config(&config), - &config.identity_bindings, - &config.user_policies, - )?; - let backend = memory.name().to_string(); - let repaired = memory.reindex().await?; - if json { - println!( - "{}", - serde_json::json!({ - "backend": backend, - "reindexed": repaired, - }) - ); - } else { - println!("Memory reindex complete for {backend}: {repaired} stale vectors rebuilt"); - } - Ok(()) - } - } -} - -fn write_shell_completion(shell: CompletionShell, writer: &mut W) -> Result<()> { - use clap_complete::generate; - use clap_complete::shells; - - let mut cmd = Cli::command(); - let bin_name = cmd.get_name().to_string(); - - match shell { - CompletionShell::Bash => generate(shells::Bash, &mut cmd, bin_name, writer), - CompletionShell::Fish => generate(shells::Fish, &mut cmd, bin_name, writer), - CompletionShell::Zsh => generate(shells::Zsh, &mut cmd, bin_name, writer), - CompletionShell::PowerShell => { - generate(shells::PowerShell, &mut cmd, bin_name, writer); - } - CompletionShell::Elvish => generate(shells::Elvish, &mut cmd, bin_name, writer), - } - - writer.flush()?; - Ok(()) -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct PendingOpenAiLogin { - profile: String, - code_verifier: String, - state: String, - created_at: String, - host_id: String, - client_id: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct PendingOpenAiLoginFile { - profile: String, - #[serde(skip_serializing_if = "Option::is_none")] - code_verifier: Option, - #[serde(skip_serializing_if = "Option::is_none")] - encrypted_code_verifier: Option, - state: String, - created_at: String, - #[serde(default)] - host_id: String, - #[serde(default)] - client_id: String, -} - -fn pending_openai_login_path(config: &Config) -> std::path::PathBuf { - auth::state_dir_from_config(config).join("auth-openai-pending.json") -} - -fn pending_openai_secret_store(config: &Config) -> security::secrets::SecretStore { - security::secrets::SecretStore::new(&auth::state_dir_from_config(config), config.secrets.encrypt) -} - -#[cfg(unix)] -fn set_owner_only_permissions(path: &std::path::Path) -> Result<()> { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?; - Ok(()) -} - -#[cfg(not(unix))] -fn set_owner_only_permissions(_path: &std::path::Path) -> Result<()> { - Ok(()) -} - -fn save_pending_openai_login(config: &Config, pending: &PendingOpenAiLogin) -> Result<()> { - let path = pending_openai_login_path(config); - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent)?; - } - let secret_store = pending_openai_secret_store(config); - let encrypted_code_verifier = secret_store.encrypt(&pending.code_verifier)?; - let persisted = PendingOpenAiLoginFile { - profile: pending.profile.clone(), - code_verifier: None, - encrypted_code_verifier: Some(encrypted_code_verifier), - state: pending.state.clone(), - created_at: pending.created_at.clone(), - host_id: pending.host_id.clone(), - client_id: pending.client_id.clone(), - }; - let tmp = path.with_extension(format!( - "tmp.{}.{}", - std::process::id(), - chrono::Utc::now().timestamp_nanos_opt().unwrap_or_default() - )); - let json = serde_json::to_vec_pretty(&persisted)?; - std::fs::write(&tmp, json)?; - set_owner_only_permissions(&tmp)?; - std::fs::rename(tmp, &path)?; - set_owner_only_permissions(&path)?; - Ok(()) -} - -fn load_pending_openai_login(config: &Config) -> Result> { - let path = pending_openai_login_path(config); - if !path.exists() { - return Ok(None); - } - let bytes = std::fs::read(path)?; - if bytes.is_empty() { - return Ok(None); - } - let persisted: PendingOpenAiLoginFile = serde_json::from_slice(&bytes)?; - let secret_store = pending_openai_secret_store(config); - let code_verifier = if let Some(encrypted) = persisted.encrypted_code_verifier { - secret_store.decrypt(&encrypted)? - } else if let Some(plaintext) = persisted.code_verifier { - plaintext - } else { - bail!("Pending OpenAI login is missing code verifier"); - }; - Ok(Some(PendingOpenAiLogin { - profile: persisted.profile, - code_verifier, - state: persisted.state, - created_at: persisted.created_at, - host_id: persisted.host_id, - client_id: persisted.client_id, - })) -} - -fn clear_pending_openai_login(config: &Config) { - let path = pending_openai_login_path(config); - if let Ok(file) = std::fs::OpenOptions::new().write(true).open(&path) { - let _ = file.set_len(0); - let _ = file.sync_all(); - } - let _ = std::fs::remove_file(path); -} - -fn read_auth_input(prompt: &str) -> Result { - let input = Password::new() - .with_prompt(prompt) - .allow_empty_password(false) - .interact()?; - Ok(input.trim().to_string()) -} - -fn read_plain_input(prompt: &str) -> Result { - let input: String = Input::new().with_prompt(prompt).interact_text()?; - Ok(input.trim().to_string()) -} - -fn extract_openai_account_id_for_profile(access_token: &str, id_token: Option<&str>) -> Option { - let account_id = auth::openai_oauth::extract_account_id(access_token, id_token); - if account_id.is_none() { - warn!( - "Could not extract OpenAI account id from OAuth access token; \ - requests may fail until re-authentication." - ); - } - account_id -} - -fn format_expiry(profile: &auth::profiles::AuthProfile) -> String { - profile - .token_set - .as_ref() - .and_then(|token_set| token_set.expires_at) - .map_or_else( - || "n/a".to_string(), - |ts| { - let now = chrono::Utc::now(); - if ts <= now { - format!("expired at {}", ts.to_rfc3339()) - } else { - let mins = (ts - now).num_minutes(); - format!("expires in {mins}m ({})", ts.to_rfc3339()) - } - }, - ) -} - -fn attestation_check( - observed_at: &str, - id: &'static str, - framework_reference: &'static str, - control: &'static str, - status: ControlStatus, - evidence_kind: &'static str, - evidence_reference: impl Into, - explanation: impl Into, - remediation: impl Into, -) -> EuAiActCheck { - EuAiActCheck { - id, - framework_reference, - control, - applicability: "operator classification required", - severity: if matches!(status, ControlStatus::Fail) { - "release_blocking" - } else { - "advisory" - }, - status, - observed_at: observed_at.to_string(), - evidence: vec![EvidenceReference { - kind: evidence_kind, - reference: evidence_reference.into(), - }], - explanation: explanation.into(), - remediation: remediation.into(), - } -} - -fn config_source_revision(config: &Config) -> Option { - use sha2::{Digest, Sha256}; - let bytes = fs::read(&config.config_path).ok()?; - Some(format!("sha256:{:x}", Sha256::digest(bytes))) -} - -fn config_generation(config: &Config) -> Option { - let generation_path = config.config_path.parent()?.join(".config-generation"); - fs::read_to_string(generation_path).ok()?.trim().parse().ok() -} - -fn declaration_artifact_path(config: &Config) -> Option { - config - .compliance - .eu_ai_act - .declaration - .artifact_path - .as_ref() - .map(|path| { - if path.is_absolute() { - path.clone() - } else { - config.workspace_dir.join(path) - } - }) -} - -fn incident_store_path(config: &Config) -> Option { - config.compliance.eu_ai_act.incident_store_path.as_ref().map(|path| { - if path.is_absolute() { - path.clone() - } else { - config.workspace_dir.join(path) - } - }) -} - -fn verified_declaration_control(config: &Config) -> (ControlStatus, String, String) { - let Some(path) = declaration_artifact_path(config) else { - return ( - ControlStatus::Fail, - "declaration-of-conformity:path-missing".to_string(), - "High-risk classification is recorded, but no declaration artifact path is configured.".to_string(), - ); - }; - openprx::compliance::declaration::verify_declaration_artifact(&path).map_or_else( - |_| { - ( - ControlStatus::Fail, - "declaration-of-conformity:verification-failed".to_string(), - "The configured declaration artifact is missing, incomplete, or has a mismatched hash.".to_string(), - ) - }, - |evidence| { - ( - ControlStatus::Pass, - evidence, - "Artifact structure/hash and an operator-supplied external signature reference were verified; PRX did not validate signature authenticity or submission." - .to_string(), - ) - }, - ) -} - -fn verified_incident_control(config: &Config) -> (ControlStatus, String, String) { - let Some(path) = incident_store_path(config) else { - return ( - ControlStatus::Fail, - "article-73-incidents:path-missing".to_string(), - "High-risk classification is recorded, but no durable incident store path is configured.".to_string(), - ); - }; - openprx::compliance::incident::verify_incident_store(&path).map_or_else( - |_| { - ( - ControlStatus::Fail, - "article-73-incidents:verification-failed".to_string(), - "The configured incident store is missing, incompatible, or contains an overdue open incident without an initial report." - .to_string(), - ) - }, - |evidence| { - ( - ControlStatus::Pass, - evidence, - "The durable store schema and open-incident initial-report deadlines were verified read-only." - .to_string(), - ) - }, - ) -} - -fn build_eu_ai_act_attestation(config: &Config) -> EuAiActAttestation { - let observed_at = chrono::Utc::now().to_rfc3339(); - let config_revision = config_source_revision(config); - let config_evidence = config_revision - .clone() - .unwrap_or_else(|| "config:unavailable".to_string()); - let audit_status = ControlStatus::Pass; - let events_status = ControlStatus::Pass; - let postgres = config.memory.backend == "postgres" || config.storage.provider.config.provider == "postgres"; - let (vector_isolation_status, vector_isolation_evidence, vector_isolation_explanation) = if postgres { - let storage = &config.storage.provider.config; - match storage.db_url.as_deref().map(|db_url| { - memory::postgres::PostgresMemory::verify_vector_isolation( - db_url, - &storage.schema, - &storage.table, - storage.connect_timeout_secs, - ) - }) { - Some(Ok(evidence)) => ( - ControlStatus::Pass, - evidence, - "Migrations 21, 23 and 24 and the exact set of forced, permissive RLS policies were verified read-only on all PostgreSQL vector tables." - .to_string(), - ), - Some(Err(_)) => ( - ControlStatus::Fail, - "postgres:vector-isolation:verification-failed".to_string(), - "PostgreSQL is configured, but live migration/RLS evidence could not be verified.".to_string(), - ), - None => ( - ControlStatus::Fail, - "postgres:vector-isolation:db-url-missing".to_string(), - "PostgreSQL is configured without the connection data required for read-only evidence verification." - .to_string(), - ), - } - } else { - ( - ControlStatus::NotApplicable, - "backend:not-postgres".to_string(), - "PostgreSQL vector RLS is not applicable to this backend; application owner isolation is evaluated separately." - .to_string(), - ) - }; - let notice = &config.compliance.interaction_notice; - let (notice_status, notice_explanation) = match notice.applicability { - config::schema::InteractionNoticeApplicability::NotApplicable => ( - ControlStatus::NotApplicable, - format!( - "Operator exception owner={} reviewed_at={}", - notice.exception_owner.as_deref().unwrap_or("missing"), - notice.exception_reviewed_at.as_deref().unwrap_or("missing") - ), - ), - config::schema::InteractionNoticeApplicability::Required => ( - ControlStatus::Pass, - format!( - "versioned notice {} is enabled before channel response routing", - notice.version - ), - ), - }; - let eu_classification = &config.compliance.eu_ai_act.classification; - let (declaration_status, declaration_evidence, declaration_explanation) = match eu_classification.status { - config::schema::EuAiActRiskClassification::Unclassified => ( - ControlStatus::Unknown, - "classification:unclassified".to_string(), - "No named owner has classified this deployment for the high-risk declaration requirement.".to_string(), - ), - config::schema::EuAiActRiskClassification::NotHighRisk => ( - ControlStatus::NotApplicable, - format!( - "classification:owner={}:assessed_at={}", - eu_classification.owner.as_deref().unwrap_or("missing"), - eu_classification.assessed_at.as_deref().unwrap_or("missing") - ), - "The recorded operator/legal classification says this deployment is not a high-risk AI system.".to_string(), - ), - config::schema::EuAiActRiskClassification::HighRisk => verified_declaration_control(config), - }; - let (incident_status, incident_evidence, incident_explanation) = match eu_classification.status { - config::schema::EuAiActRiskClassification::Unclassified => ( - ControlStatus::Unknown, - "classification:unclassified".to_string(), - "The incident workflow cannot be evaluated until a named owner classifies the deployment.".to_string(), - ), - config::schema::EuAiActRiskClassification::NotHighRisk => ( - ControlStatus::NotApplicable, - format!( - "classification:owner={}:assessed_at={}", - eu_classification.owner.as_deref().unwrap_or("missing"), - eu_classification.assessed_at.as_deref().unwrap_or("missing") - ), - "The recorded operator/legal classification says Article 73 is not applicable to this deployment." - .to_string(), - ), - config::schema::EuAiActRiskClassification::HighRisk => verified_incident_control(config), - }; - - let mut checks = vec![ - attestation_check( - &observed_at, - "L01", - "Article 12", - "Side-effect audit logging enabled", - audit_status, - "config_revision", - &config_evidence, - "security.audit=always_on".to_string(), - "Retain signed audit evidence.", - ), - attestation_check( - &observed_at, - "L02", - "Article 12", - "Audit retention floor", - ControlStatus::Warning, - "config_revision", - &config_evidence, - format!( - "audit rotation size is {} MiB; no time-based floor is enforced", - config.security.audit.max_size_mb - ), - "Define and enforce an operator-approved retention period.", - ), - attestation_check( - &observed_at, - "L03", - "Article 12", - "Control-ladder trace rotation", - ControlStatus::Unknown, - "runtime_diagnostic", - "doctor:runtime/control_ladder_traces", - "No runtime trace-archive evidence was evaluated by this command.", - "Attach trace rotation and archival evidence.", - ), - attestation_check( - &observed_at, - "L04", - "Article 12", - "Message timeline recording", - events_status, - "config_revision", - &config_evidence, - "memory.events=always_on".to_string(), - "Attach retention evidence.", - ), - attestation_check( - &observed_at, - "T01", - "Article 13", - "Provider routing transparency", - ControlStatus::Warning, - "config_revision", - &config_evidence, - format!( - "default provider is {:?}; runtime route evidence was not queried", - config.default_provider - ), - "Attach route-decision and final-outcome event references.", - ), - attestation_check( - &observed_at, - "T02", - "Article 13", - "Third-party provider data-policy disclosure", - ControlStatus::Unknown, - "operator_assertion", - "provider-policy-owner:missing", - "Provider policy URL and review ownership were not supplied.", - "Record policy URLs, owner, and review expiry for each provider.", - ), - attestation_check( - &observed_at, - "T04", - "Article 50", - "AI interaction notice", - notice_status, - "config_revision", - &config_evidence, - notice_explanation, - "Emit and minimally acknowledge a versioned AI identity notice before the first response.", - ), - attestation_check( - &observed_at, - "H01", - "Article 14", - "Approval grant cryptographic witness", - ControlStatus::Unknown, - "runtime_diagnostic", - "approval-ledger:not_evaluated", - "Source presence alone is not execution evidence.", - "Attach a verified ApprovalGrant v2 ledger receipt.", - ), - attestation_check( - &observed_at, - "H02", - "Article 14", - "Side-effect authorization coverage", - ControlStatus::Unknown, - "runtime_diagnostic", - "tool-gate-coverage:not_evaluated", - "This report did not execute tool-gate coverage tests.", - "Attach release test receipts for every side-effect tool.", - ), - attestation_check( - &observed_at, - "H03", - "Article 14", - "High-risk operation supervision", - ControlStatus::Warning, - "config_revision", - &config_evidence, - format!("autonomy level is {:?}", config.autonomy.level), - "Use supervised policy and attach approval receipts where applicable.", - ), - attestation_check( - &observed_at, - "H04", - "Article 14", - "Inbound listener human oversight", - ControlStatus::Unknown, - "runtime_diagnostic", - "channel-oversight:not_evaluated", - "No live inbound-channel oversight evidence was evaluated.", - "Run adapter-level supervised-mode conformance tests.", - ), - attestation_check( - &observed_at, - "A01", - "Article 15", - "Retrieval traceability", - ControlStatus::Unknown, - "runtime_diagnostic", - "retrieval-traces:not_evaluated", - "No retrieval trace was sampled.", - "Attach immutable retrieval-trace identifiers.", - ), - attestation_check( - &observed_at, - "A02", - "Article 15", - "Compaction provenance", - ControlStatus::Unknown, - "runtime_diagnostic", - "compaction-runs:not_evaluated", - "No compaction run was sampled.", - "Attach completed compaction-run identifiers and fidelity evidence.", - ), - attestation_check( - &observed_at, - "A03", - "Article 15", - "Prompt-injection content boundaries", - ControlStatus::Unknown, - "runtime_diagnostic", - "content-boundary:not_evaluated", - "Static implementation claims are insufficient evidence.", - "Attach adversarial content-boundary test results.", - ), - attestation_check( - &observed_at, - "A04", - "Article 15 internal security control", - "Vector owner/tenant isolation", - vector_isolation_status, - "postgres_runtime_evidence", - vector_isolation_evidence, - vector_isolation_explanation, - "Install authoritative RLS policies and attach cross-owner negative-test evidence.", - ), - attestation_check( - &observed_at, - "Q01", - "Article 16", - "Dependency vulnerability gate", - ControlStatus::Unknown, - "release_receipt", - "cargo-audit:missing", - "No cargo-audit receipt was supplied to this invocation.", - "Attach a timestamped cargo-audit release receipt.", - ), - attestation_check( - &observed_at, - "Q02", - "Article 16", - "Rust engineering gate", - ControlStatus::Unknown, - "release_receipt", - "engineering-gate:missing", - "No fmt/clippy/check/test receipt was supplied.", - "Attach source-identity-bound engineering gate results.", - ), - attestation_check( - &observed_at, - "Q03", - "Article 16", - "Quality management documentation", - ControlStatus::Unknown, - "operator_assertion", - "qms-owner:missing", - "No QMS owner or reviewed document set was supplied.", - "Record the QMS owner, document versions, and review date.", - ), - attestation_check( - &observed_at, - "C01", - "Article 17", - "Quality management system", - ControlStatus::Unknown, - "operator_assertion", - "qms-classification:missing", - "Applicability and operator evidence are unresolved.", - "Complete legal classification and QMS evidence review.", - ), - attestation_check( - &observed_at, - "C02", - "Article 47 and Annex V", - "EU declaration of conformity artifact", - declaration_status, - "artifact", - declaration_evidence, - declaration_explanation, - "Generate a versioned artifact only from explicit operator declarations.", - ), - attestation_check( - &observed_at, - "M01", - "Article 72", - "Post-market monitoring inputs", - ControlStatus::Unknown, - "runtime_diagnostic", - "monitoring-evidence:not_evaluated", - "Runtime health and trace data were not sampled.", - "Attach monitoring evidence and an operator-approved plan.", - ), - attestation_check( - &observed_at, - "M02", - "Article 73", - "Incident response ownership", - ControlStatus::Unknown, - "operator_assertion", - "incident-owner:missing", - "No incident owner or jurisdiction matrix was supplied.", - "Record the incident owner, jurisdictions, and escalation runbook.", - ), - attestation_check( - &observed_at, - "M03", - "Article 72", - "Post-market report cadence", - ControlStatus::Unknown, - "operator_assertion", - "monitoring-cadence:missing", - "No reviewed monitoring cadence was supplied.", - "Record cadence, owner, review date, and report references.", - ), - attestation_check( - &observed_at, - "M04", - "Article 73", - "Serious-incident workflow", - incident_status, - "incident_store", - incident_evidence, - incident_explanation, - "Configure the durable incident store and use the incident CLI to record awareness, classification, reports, supplements, and closure.", - ), - ]; - checks.sort_by_key(|check| check.id); - - let passed_count = checks - .iter() - .filter(|check| check.status == ControlStatus::Pass) - .count(); - let warning_count = checks - .iter() - .filter(|check| check.status == ControlStatus::Warning) - .count(); - let failed_count = checks - .iter() - .filter(|check| check.status == ControlStatus::Fail) - .count(); - let unknown_count = checks - .iter() - .filter(|check| check.status == ControlStatus::Unknown) - .count(); - let not_applicable_count = checks - .iter() - .filter(|check| check.status == ControlStatus::NotApplicable) - .count(); - - EuAiActAttestation { - report_type: "EU AI Act implementation attestation", - evaluator_version: "prx-eu-ai-act-controls/v2", - product_version: env!("CARGO_PKG_VERSION"), - source_identity: option_env!("PRX_BUILD_SOURCE_REVISION").map(str::to_string), - config_generation: config_generation(config), - config_source_revision: config_revision, - generated_at: observed_at, - applicability: ApplicabilityDecision { - status: ControlStatus::Unknown, - classification: "unclassified; operator and legal review required".to_string(), - owner: None, - reviewed_at: None, - }, - default_provider: config.default_provider.clone(), - total_checks: checks.len(), - passed_count, - warning_count, - failed_count, - unknown_count, - not_applicable_count, - checks, - } -} - -fn render_eu_ai_act_attestation_markdown(attestation: &EuAiActAttestation, verbose: bool) -> String { - let mut output = String::new(); - output.push_str("# PRX EU AI Act Implementation Attestation\n\n"); - output.push_str("This is an implementation attestation, not a regulator-issued certification.\n\n"); - output.push_str(&format!("- Product version: {}\n", attestation.product_version)); - output.push_str(&format!( - "- Source identity: {}\n", - attestation.source_identity.as_deref().unwrap_or("unavailable") - )); - output.push_str(&format!("- Generated at: {}\n", attestation.generated_at)); - output.push_str(&format!( - "- Classification: {}\n", - attestation.applicability.classification - )); - output.push_str(&format!( - "- Checks: {} total, {} pass, {} warning, {} fail, {} unknown, {} not applicable\n\n", - attestation.total_checks, - attestation.passed_count, - attestation.warning_count, - attestation.failed_count, - attestation.unknown_count, - attestation.not_applicable_count - )); - output.push_str("| ID | Article | Status | Control |\n"); - output.push_str("|----|---------|--------|---------|\n"); - for check in &attestation.checks { - output.push_str(&format!( - "| {} | {} | {} | {} |\n", - check.id, - check.framework_reference, - check.status.as_str(), - check.control - )); - if verbose { - output.push_str(&format!( - "\n{} evidence: {}\n\n{} explanation: {}\n\n{} remediation: {}\n\n", - check.id, - check - .evidence - .iter() - .map(|evidence| format!("{}={}", evidence.kind, evidence.reference)) - .collect::>() - .join(", "), - check.id, - check.explanation, - check.id, - check.remediation - )); - } - } - output -} - -fn render_eu_ai_act_attestation_json(attestation: &EuAiActAttestation) -> Result { - serde_json::to_string_pretty(attestation).context("Failed to serialize EU AI Act attestation") -} - -fn attestation_fails_gate(attestation: &EuAiActAttestation, fail_on: AuditFailOn) -> bool { - attestation.checks.iter().any(|check| match fail_on { - AuditFailOn::Fail => check.status == ControlStatus::Fail, - AuditFailOn::Warning => matches!( - check.status, - ControlStatus::Warning | ControlStatus::Unknown | ControlStatus::Fail - ), - }) -} - -fn handle_audit_command(audit_command: AuditCommands, config: &Config) -> Result<()> { - match audit_command { - AuditCommands::AttestEuAiAct { - json, - format, - output, - verbose, - fail_on, - } => { - let attestation = build_eu_ai_act_attestation(config); - let stdout_json = json || format == AuditOutputFormat::Json; - let stdout_rendered = if stdout_json { - render_eu_ai_act_attestation_json(&attestation)? - } else { - render_eu_ai_act_attestation_markdown(&attestation, verbose) - }; - - if let Some(path) = output { - let write_json = path.extension().and_then(|ext| ext.to_str()) == Some("json") || stdout_json; - let file_rendered = if write_json { - render_eu_ai_act_attestation_json(&attestation)? - } else { - render_eu_ai_act_attestation_markdown(&attestation, verbose) - }; - fs::write(&path, file_rendered) - .with_context(|| format!("Failed to write EU AI Act attestation to {}", path.display()))?; - } - - println!("{stdout_rendered}"); - if fail_on.is_some_and(|threshold| attestation_fails_gate(&attestation, threshold)) { - bail!("EU AI Act implementation attestation did not satisfy --fail-on threshold"); - } - Ok(()) - } - AuditCommands::GenerateEuDeclaration { - output, - signature_reference, - } => { - let configured_path = declaration_artifact_path(config); - let output = output - .map(|path| { - if path.is_absolute() { - path - } else { - config.workspace_dir.join(path) - } - }) - .or_else(|| configured_path.clone()) - .context( - "declaration output is required via --output or compliance.eu_ai_act.declaration.artifact_path", - )?; - if let Some(configured_path) = configured_path { - anyhow::ensure!( - output == configured_path, - "--output must match compliance.eu_ai_act.declaration.artifact_path so attestation can verify it" - ); - } - let artifact = openprx::compliance::declaration::build_declaration_artifact( - config.compliance.eu_ai_act.classification.status, - &config.compliance.eu_ai_act.declaration, - &signature_reference, - )?; - openprx::compliance::declaration::write_declaration_artifact(&output, &artifact)?; - println!( - "{}", - serde_json::json!({ - "artifact": output, - "payload_sha256": artifact.payload_sha256, - "signature_status": artifact.signature.status, - "submitted": artifact.signature.submitted, - }) - ); - Ok(()) - } - AuditCommands::IncidentCreate { input } => { - let path = incident_store_path(config).context("compliance.eu_ai_act.incident_store_path is required")?; - let bytes = - fs::read(&input).with_context(|| format!("Failed to read incident input {}", input.display()))?; - let request = serde_json::from_slice(&bytes).context("Failed to parse incident input JSON")?; - let mut store = openprx::compliance::incident::IncidentStore::open(&path)?; - let record = store.create(request)?; - println!("{}", serde_json::to_string_pretty(&record)?); - Ok(()) - } - AuditCommands::IncidentInitialReport { incident_id, input } => { - let path = incident_store_path(config).context("compliance.eu_ai_act.incident_store_path is required")?; - let report = fs::read_to_string(&input) - .with_context(|| format!("Failed to read initial report {}", input.display()))?; - let mut store = openprx::compliance::incident::IncidentStore::open(&path)?; - let record = store.set_initial_report(&incident_id, &report)?; - println!("{}", serde_json::to_string_pretty(&record)?); - Ok(()) - } - AuditCommands::IncidentSupplement { incident_id, input } => { - let path = incident_store_path(config).context("compliance.eu_ai_act.incident_store_path is required")?; - let content = fs::read_to_string(&input) - .with_context(|| format!("Failed to read incident supplement {}", input.display()))?; - let mut store = openprx::compliance::incident::IncidentStore::open(&path)?; - let supplement = store.add_supplement(&incident_id, &content)?; - println!("{}", serde_json::to_string_pretty(&supplement)?); - Ok(()) - } - AuditCommands::IncidentClose { - incident_id, - closed_at, - summary, - } => { - let path = incident_store_path(config).context("compliance.eu_ai_act.incident_store_path is required")?; - let closed_at = chrono::DateTime::parse_from_rfc3339(&closed_at) - .context("--closed-at must be RFC 3339")? - .with_timezone(&Utc); - let summary = fs::read_to_string(&summary) - .with_context(|| format!("Failed to read closure summary {}", summary.display()))?; - let mut store = openprx::compliance::incident::IncidentStore::open(&path)?; - let record = store.close(&incident_id, closed_at, &summary)?; - println!("{}", serde_json::to_string_pretty(&record)?); - Ok(()) - } - AuditCommands::IncidentExport { incident_id, output } => { - let path = incident_store_path(config).context("compliance.eu_ai_act.incident_store_path is required")?; - let output = if output.is_absolute() { - output - } else { - config.workspace_dir.join(output) - }; - let store = openprx::compliance::incident::IncidentStore::open(&path)?; - let export = store.export(&incident_id)?; - openprx::compliance::incident::write_incident_export(&output, &export)?; - println!( - "{}", - serde_json::json!({ - "artifact": output, - "incident_id": incident_id, - "automatically_submitted": export.automatically_submitted, - }) - ); - Ok(()) - } - } -} - -fn handle_approval_command(approval_command: ApprovalCommands, config: &Config) -> Result<()> { - let conn = open_approval_ledger(config)?; - match approval_command { - ApprovalCommands::List { version } => { - let version = version.unwrap_or(2); - if version == acl::approval_grant::ApprovalGrantV2::VERSION { - let mut stmt = conn.prepare( - "SELECT grant_id, owner_id, principal_id, capability_op_id, expires_at, revoked_at - FROM approval_grants - WHERE version = ?1 - ORDER BY issued_at DESC - LIMIT 50", - )?; - let rows = stmt.query_map([i64::from(version)], |row| { - Ok(( - row.get::<_, String>(0)?, - row.get::<_, String>(1)?, - row.get::<_, String>(2)?, - row.get::<_, String>(3)?, - row.get::<_, String>(4)?, - row.get::<_, Option>(5)?, - )) - })?; - let grants = rows.collect::>>()?; - if grants.is_empty() { - println!("no approval grants found (version: 2)"); - } else { - for (grant_id, owner_id, principal_id, op_id, expires_at, revoked_at) in grants { - let status = if revoked_at.is_some() { "revoked" } else { "active" }; - println!( - "{grant_id}\t{status}\towner={owner_id}\tprincipal={principal_id}\top={op_id}\texpires={expires_at}" - ); - } - } - Ok(()) - } else { - bail!("unsupported approval grant version: {version}") - } - } - ApprovalCommands::Verify { all, grant_id } => { - if all { - let total: i64 = conn.query_row("SELECT COUNT(*) FROM approval_grants", [], |row| row.get(0))?; - let malformed: i64 = conn.query_row( - "SELECT COUNT(*) FROM approval_grants - WHERE grant_json = '' OR signature_alg = '' OR signed_payload_sha256 = ''", - [], - |row| row.get(0), - )?; - if total == 0 { - println!("no approval grants found to verify"); - } else if malformed == 0 { - println!("approval grant ledger metadata verified: {total} grants"); - } else { - bail!("approval grant ledger metadata verification failed: {malformed}/{total} malformed grants"); - } - return Ok(()); - } - let Some(grant_id) = grant_id else { - bail!("provide a grant id or --all"); - }; - let found: Option<(String, String, String)> = conn - .query_row( - "SELECT grant_id, signature_alg, signed_payload_sha256 - FROM approval_grants - WHERE grant_id = ?1", - [grant_id.as_str()], - |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), - ) - .optional()?; - let Some((grant_id, signature_alg, payload_sha)) = found else { - bail!("approval grant not found: {grant_id}"); - }; - if signature_alg.trim().is_empty() || payload_sha.trim().is_empty() { - bail!("approval grant metadata verification failed: {grant_id}"); - } - println!("approval grant metadata verified: {grant_id} ({signature_alg})"); - Ok(()) - } - ApprovalCommands::Revoke { grant_id, reason } => { - let now = Utc::now().to_rfc3339(); - let updated = conn.execute( - "UPDATE approval_grants - SET revoked_at = COALESCE(revoked_at, ?2), - revocation_reason = COALESCE(revocation_reason, ?3), - updated_at = ?2 - WHERE grant_id = ?1", - params![grant_id, now, reason], - )?; - if updated == 0 { - bail!("approval grant not found: {grant_id}"); - } - conn.execute( - "INSERT INTO approval_grant_events (event_id, grant_id, event_type, actor, occurred_at, payload_json) - VALUES (?1, ?2, 'grant.revoked', 'cli', ?3, ?4)", - params![ - uuid::Uuid::new_v4().to_string(), - grant_id, - now, - serde_json::json!({ "reason": reason }).to_string() - ], - )?; - println!("approval grant revoked: {grant_id}"); - Ok(()) - } - } -} - -fn open_approval_ledger(config: &Config) -> Result { - let db_path = config.workspace_dir.join("memory").join("brain.db"); - if let Some(parent) = db_path.parent() { - fs::create_dir_all(parent) - .with_context(|| format!("Failed to create approval ledger directory: {}", parent.display()))?; - } - let conn = - Connection::open(&db_path).with_context(|| format!("Failed to open approval ledger: {}", db_path.display()))?; - memory::sqlite::init_approval_grant_schema(&conn)?; - Ok(conn) -} - -async fn login_openrouter(auth_service: &auth::AuthService, profile: &str, headless: bool) -> Result<()> { - let pkce = auth::openrouter_oauth::generate_pkce(); - let client = openprx::prx_http_client(); - let code = if headless { - println!("Open this URL. It shows a code to paste back (no browser callback):"); - println!("{}", auth::openrouter_oauth::headless_authorize_url(&pkce)); - read_plain_input("Paste OpenRouter code")? - } else { - let (listener, callback) = auth::openrouter_oauth::bind_loopback().await?; - println!("Open this URL in your browser and authorize access:"); - println!("{}", auth::openrouter_oauth::browser_authorize_url(&callback, &pkce)); - println!("Waiting for the loopback callback..."); - auth::openrouter_oauth::receive_loopback_code(listener, std::time::Duration::from_mins(3)).await? - }; - let key = auth::openrouter_oauth::exchange_code(&client, &code, &pkce.verifier).await?; - auth_service.store_provider_token("openrouter", profile, &key, std::collections::HashMap::new(), true)?; - println!("Saved profile {profile}"); - println!("Active profile for openrouter: {profile}"); - Ok(()) -} - -async fn login_xai(auth_service: &auth::AuthService, config: &Config, profile: &str, device_code: bool) -> Result<()> { - let client = openprx::prx_http_client(); - let state_dir = auth::state_dir_from_config(config); - - if device_code { - let device = auth::xai_oauth::start_device_code_flow(&client).await?; - println!("xAI device-code login started."); - println!("Visit: {}", device.verification_uri); - println!("Code: {}", device.user_code); - if let Some(uri_complete) = &device.verification_uri_complete { - println!("Fast link: {uri_complete}"); - } - let token_set = auth::xai_oauth::poll_device_code_tokens(&client, &device).await?; - auth_service.store_xai_tokens(profile, token_set, true)?; - println!("Saved profile {profile}"); - println!("Active profile for xai: {profile}"); - return Ok(()); - } - - let pkce = auth::xai_oauth::generate_pkce(); - let pending = auth::xai_oauth::PendingXaiLogin { - profile: profile.to_string(), - code_verifier: pkce.code_verifier.clone(), - state: pkce.state.clone(), - created_at: chrono::Utc::now().to_rfc3339(), - }; - auth::xai_oauth::save_pending_login(&state_dir, config.secrets.encrypt, &pending)?; - let authorize_url = auth::xai_oauth::build_authorize_url(&pkce); - println!("Open this URL in your browser and authorize access:"); - println!("{authorize_url}"); - println!(); - println!( - "Waiting for callback at {} ...", - auth::xai_oauth::XAI_OAUTH_REDIRECT_URI - ); - - let code = match auth::xai_oauth::receive_loopback_code(&pkce.state, std::time::Duration::from_secs(180)).await { - Ok(code) => code, - Err(error) => { - println!("Callback capture failed: {error}"); - println!("Run `prx auth paste-redirect --provider xai --profile {profile}`"); - return Ok(()); - } - }; - let token_set = auth::xai_oauth::exchange_code_for_tokens(&client, &code, &pkce.code_verifier).await?; - auth_service.store_xai_tokens(profile, token_set, true)?; - auth::xai_oauth::clear_pending_login(&state_dir); - println!("Saved profile {profile}"); - println!("Active profile for xai: {profile}"); - Ok(()) -} - -async fn paste_xai_redirect( - auth_service: &auth::AuthService, - config: &Config, - profile: &str, - input: Option, -) -> Result<()> { - let state_dir = auth::state_dir_from_config(config); - let pending = auth::xai_oauth::load_pending_login(&state_dir, config.secrets.encrypt)? - .ok_or_else(|| anyhow::anyhow!("No pending xAI login found. Run `prx auth login --provider xai` first."))?; - if pending.profile != profile { - bail!( - "Pending login profile mismatch: pending={}, requested={}", - pending.profile, - profile - ); - } - let redirect_input = match input { - Some(value) => value, - None => read_plain_input("Paste redirect URL or OAuth code")?, - }; - let code = auth::xai_oauth::parse_code_from_redirect(&redirect_input, Some(&pending.state))?; - let client = openprx::prx_http_client(); - let token_set = auth::xai_oauth::exchange_code_for_tokens(&client, &code, &pending.code_verifier).await?; - auth_service.store_xai_tokens(profile, token_set, true)?; - auth::xai_oauth::clear_pending_login(&state_dir); - println!("Saved profile {profile}"); - println!("Active profile for xai: {profile}"); - Ok(()) -} - -#[allow(clippy::too_many_lines)] -async fn handle_auth_command(auth_command: AuthCommands, config: &Config) -> Result<()> { - let auth_service = auth::AuthService::from_config(config); - - match auth_command { - AuthCommands::Login { - provider, - profile, - device_code, - } => { - let provider = auth::normalize_provider(&provider)?; - if provider == "xai" { - return login_xai(&auth_service, config, &profile, device_code).await; - } - if provider == "openrouter" { - return login_openrouter(&auth_service, &profile, device_code).await; - } - if provider != "openai-codex" { - bail!("`auth login` supports --provider openai-codex, --provider openrouter, and --provider xai"); - } - - let client = openprx::prx_http_client(); - - if device_code { - auth::openai_oauth::start_device_code_flow(&client)?; - } - - let state_dir = auth::state_dir_from_config(config); - let host_id = auth::openai_oauth::load_or_create_host_id(&state_dir)?; - let saved_client_id = auth_service - .get_profile("openai-codex", Some(&profile))? - .and_then(|profile| { - profile - .metadata - .get(auth::openai_oauth::OPENAI_CLIENT_ID_METADATA) - .cloned() - }); - let pkce = auth::openai_oauth::generate_pkce_state(); - let client_id_sent = saved_client_id - .as_deref() - .filter(|value| value.starts_with("oaiapp_")) - .unwrap_or(auth::openai_oauth::OPENAI_OAUTH_DYNAMIC_CLIENT_ID) - .to_string(); - let pending = PendingOpenAiLogin { - profile: profile.clone(), - code_verifier: pkce.code_verifier.clone(), - state: pkce.state.clone(), - created_at: chrono::Utc::now().to_rfc3339(), - host_id: host_id.clone(), - client_id: client_id_sent.clone(), - }; - save_pending_openai_login(config, &pending)?; - - let authorize_url = - auth::openai_oauth::build_authorize_url(&pkce, &host_id, saved_client_id.as_deref(), None); - println!("Open this URL in your browser and authorize access:"); - println!("{authorize_url}"); - println!(); - println!( - "Waiting for callback at {} ...", - auth::openai_oauth::OPENAI_OAUTH_REDIRECT_URI - ); - - let callback = - match auth::openai_oauth::receive_loopback_code(&pkce.state, std::time::Duration::from_mins(3)).await { - Ok(callback) => callback, - Err(e) => { - println!("Callback capture failed: {e}"); - println!("Run `prx auth paste-redirect --provider openai-codex --profile {profile}`"); - return Ok(()); - } - }; - let code = auth::openai_oauth::parse_code_from_redirect(&callback, Some(&pkce.state))?; - - let issued = auth::openai_oauth::issued_client_id_from_callback(&callback) - .or_else(|| client_id_sent.starts_with("oaiapp_").then(|| client_id_sent.clone())); - let Some(exchange_client_id) = issued else { - bail!( - "Sign in with ChatGPT did not return an issued oaiapp_ client id. Run `prx auth login --provider openai-codex` again." - ); - }; - let token_set = - auth::openai_oauth::exchange_code_for_tokens(&client, &code, &pkce, &exchange_client_id).await?; - let account_id = - extract_openai_account_id_for_profile(&token_set.access_token, token_set.id_token.as_deref()); - - auth_service.store_openai_siwc_tokens(&profile, token_set, account_id, &exchange_client_id, true)?; - clear_pending_openai_login(config); - - println!("Saved profile {profile}"); - println!("Active profile for openai-codex: {profile}"); - Ok(()) - } - - AuthCommands::PasteRedirect { - provider, - profile, - input, - } => { - let provider = auth::normalize_provider(&provider)?; - if provider == "xai" { - return paste_xai_redirect(&auth_service, config, &profile, input).await; - } - if provider != "openai-codex" { - bail!("`auth paste-redirect` supports --provider openai-codex and --provider xai"); - } - - let pending = load_pending_openai_login(config)?.ok_or_else(|| { - anyhow::anyhow!("No pending OpenAI login found. Run `prx auth login --provider openai-codex` first.") - })?; - - if pending.profile != profile { - bail!( - "Pending login profile mismatch: pending={}, requested={}", - pending.profile, - profile - ); - } - - let redirect_input = match input { - Some(value) => value, - None => read_plain_input("Paste redirect URL or OAuth code")?, - }; - - let code = auth::openai_oauth::parse_code_from_redirect(&redirect_input, Some(&pending.state))?; - let issued = auth::openai_oauth::issued_client_id_from_callback(&redirect_input).or_else(|| { - pending - .client_id - .starts_with("oaiapp_") - .then(|| pending.client_id.clone()) - }); - let Some(exchange_client_id) = issued else { - bail!( - "Sign in with ChatGPT did not return an issued oaiapp_ client id. Run `prx auth login --provider openai-codex` again." - ); - }; - - let pkce = auth::openai_oauth::PkceState { - code_verifier: pending.code_verifier.clone(), - code_challenge: String::new(), - state: pending.state.clone(), - nonce: String::new(), - }; - - let client = openprx::prx_http_client(); - let token_set = - auth::openai_oauth::exchange_code_for_tokens(&client, &code, &pkce, &exchange_client_id).await?; - let account_id = - extract_openai_account_id_for_profile(&token_set.access_token, token_set.id_token.as_deref()); - - auth_service.store_openai_siwc_tokens(&profile, token_set, account_id, &exchange_client_id, true)?; - clear_pending_openai_login(config); - - println!("Saved profile {profile}"); - println!("Active profile for openai-codex: {profile}"); - Ok(()) - } - - AuthCommands::PasteToken { - provider, - profile, - token, - from_stdin, - auth_kind, - } => { - let provider = auth::normalize_provider(&provider)?; - let piped = manage_cli::secret_from(from_stdin, None, &mut std::io::stdin(), &|_: &str| None)?; - let token = match (token, piped) { - (_, Some(piped)) => piped.trim().to_string(), - (Some(token), None) => token.trim().to_string(), - (None, None) => read_auth_input("Paste token")?, - }; - if token.is_empty() { - bail!("Token cannot be empty"); - } - if auth::discovery::is_claude_code_oauth_setup_token(&token) { - bail!("{}", auth::terms::ANTHROPIC_SUBSCRIPTION_REMOVED); - } - - let kind = auth::anthropic_token::detect_auth_kind(&token, auth_kind.as_deref()); - let mut metadata = std::collections::HashMap::new(); - metadata.insert("auth_kind".to_string(), kind.as_metadata_value().to_string()); - - auth_service.store_provider_token(&provider, &profile, &token, metadata, true)?; - println!("Saved profile {profile}"); - println!("Active profile for {provider}: {profile}"); - Ok(()) - } - - AuthCommands::SetupToken { provider, profile } => { - let provider = auth::normalize_provider(&provider)?; - let token = read_auth_input("Paste token")?; - if token.is_empty() { - bail!("Token cannot be empty"); - } - if auth::discovery::is_claude_code_oauth_setup_token(&token) { - bail!("{}", auth::terms::ANTHROPIC_SUBSCRIPTION_REMOVED); - } - - let kind = auth::anthropic_token::detect_auth_kind(&token, Some("authorization")); - let mut metadata = std::collections::HashMap::new(); - metadata.insert("auth_kind".to_string(), kind.as_metadata_value().to_string()); - - auth_service.store_provider_token(&provider, &profile, &token, metadata, true)?; - println!("Saved profile {profile}"); - println!("Active profile for {provider}: {profile}"); - Ok(()) - } - - AuthCommands::Refresh { provider, profile } => { - let provider = auth::normalize_provider(&provider)?; - if provider == "xai" { - return match auth_service.get_valid_xai_access_token(profile.as_deref()).await? { - Some(_) => { - println!("xAI Grok token is valid (refresh completed if needed)."); - Ok(()) - } - None => { - bail!("No xAI auth profile found. Run `prx auth login --provider xai`.") - } - }; - } - if provider != "openai-codex" { - bail!("`auth refresh` supports --provider openai-codex and --provider xai"); - } - - match auth_service.get_valid_openai_access_token(profile.as_deref()).await? { - Some(_) => { - println!("OpenAI Codex token is valid (refresh completed if needed)."); - Ok(()) - } - None => { - bail!("No OpenAI Codex auth profile found. Run `prx auth login --provider openai-codex`.") - } - } - } - - AuthCommands::Logout { provider, profile } => { - let provider = auth::normalize_provider(&provider)?; - let removed = auth_service.remove_profile(&provider, &profile)?; - if removed { - println!("Removed auth profile {provider}:{profile}"); - } else { - println!("Auth profile not found: {provider}:{profile}"); - } - Ok(()) - } - - AuthCommands::Use { provider, profile } => { - let provider = auth::normalize_provider(&provider)?; - auth_service.set_active_profile(&provider, &profile)?; - println!("Active profile for {provider}: {profile}"); - Ok(()) - } - - AuthCommands::List => { - let data = auth_service.load_profiles()?; - if data.profiles.is_empty() { - println!("No auth profiles configured."); - return Ok(()); - } - - for (id, profile) in &data.profiles { - let active = data - .active_profiles - .get(&profile.provider) - .is_some_and(|active_id| active_id == id); - let marker = if active { "*" } else { " " }; - println!("{marker} {id}"); - } - - Ok(()) - } - - AuthCommands::Status => { - let data = auth_service.load_profiles()?; - if data.profiles.is_empty() { - println!("No auth profiles configured."); - return Ok(()); - } - - for (id, profile) in &data.profiles { - let active = data - .active_profiles - .get(&profile.provider) - .is_some_and(|active_id| active_id == id); - let marker = if active { "*" } else { " " }; - println!( - "{} {} kind={:?} account={} expires={}", - marker, - id, - profile.kind, - crate::security::redact(profile.account_id.as_deref().unwrap_or("unknown")), - format_expiry(profile) - ); - } - - println!(); - println!("Active profiles:"); - for (provider, profile_id) in &data.active_profiles { - println!(" {provider}: {profile_id}"); - } - - Ok(()) - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use clap::{CommandFactory, Parser}; - - #[test] - fn cli_definition_has_no_flag_conflicts() { - Cli::command().debug_assert(); - } - - /// Oracle is clap argv, not a copy of `cli_tracing_command`. Mapping - /// `Commands::Gateway` to `CliCommand::Chat` fails the gateway row. - fn commands_coverage_tag(command: &Commands) -> &'static str { - match command { - Commands::Init { .. } | Commands::Token { .. } => "Init", - Commands::Go { .. } => "Go", - Commands::Chat { message: Some(_), .. } => "ChatMessage", - Commands::Chat { .. } => "Chat", - Commands::Gateway { .. } => "Gateway", - Commands::Daemon { .. } => "Daemon", - Commands::Service { .. } => "Service", - Commands::Doctor { .. } => "Doctor", - Commands::Status { .. } => "Status", - Commands::Tasks { .. } => "Tasks", - Commands::Memory { .. } => "Memory", - Commands::Evolution { .. } => "Evolution", - #[cfg(feature = "wasm-plugins")] - Commands::Plugin { .. } => "Plugin", - Commands::Cost { .. } => "Cost", - Commands::Fitness { .. } => "Fitness", - Commands::Cron { .. } => "Cron", - Commands::Xin { .. } => "Xin", - Commands::Causal { .. } => "Causal", - Commands::DecisionEngine { .. } => "DecisionEngine", - Commands::Models { .. } => "Models", - Commands::Providers { .. } => "Providers", - Commands::Routes { .. } => "Routes", - Commands::Channel { - channel_command: ChannelCommands::Start, - } => "ChannelStart", - Commands::Channel { .. } => "ChannelManage", - Commands::Integrations { .. } => "Integrations", - Commands::Skills { .. } => "Skills", - Commands::Migrate { .. } => "Migrate", - Commands::Auth { .. } => "Auth", - Commands::Approval { .. } => "Approval", - Commands::Audit { .. } => "Audit", - Commands::Config { .. } => "Config", - #[cfg(feature = "test-mock")] - Commands::MailboxHarness { .. } => "MailboxHarness", - Commands::SessionWorker { .. } => "SessionWorker", - Commands::Completions { .. } => "Completions", - } - } - - #[test] - fn cli_tracing_clap_argv_maps_every_command() { - let cases: &[(&[&str], cli_tracing::CliCommand)] = &[ - (&["prx", "init"], cli_tracing::CliCommand::Init), - (&["prx", "go"], cli_tracing::CliCommand::Go), - (&["prx", "chat"], cli_tracing::CliCommand::Chat), - ( - &["prx", "chat", "--message", "hi"], - cli_tracing::CliCommand::ChatMessage, - ), - (&["prx", "gateway"], cli_tracing::CliCommand::Gateway), - (&["prx", "daemon"], cli_tracing::CliCommand::Daemon), - (&["prx", "service", "status"], cli_tracing::CliCommand::Service), - (&["prx", "doctor"], cli_tracing::CliCommand::Doctor), - (&["prx", "status"], cli_tracing::CliCommand::Status), - (&["prx", "tasks", "list"], cli_tracing::CliCommand::Tasks), - (&["prx", "memory", "reindex"], cli_tracing::CliCommand::Memory), - (&["prx", "evolution", "status"], cli_tracing::CliCommand::Evolution), - (&["prx", "cost"], cli_tracing::CliCommand::Cost), - (&["prx", "fitness", "status"], cli_tracing::CliCommand::Fitness), - (&["prx", "cron", "list"], cli_tracing::CliCommand::Cron), - (&["prx", "xin", "status"], cli_tracing::CliCommand::Xin), - (&["prx", "causal", "status"], cli_tracing::CliCommand::Causal), - ( - &["prx", "decision-engine", "status"], - cli_tracing::CliCommand::DecisionEngine, - ), - (&["prx", "models"], cli_tracing::CliCommand::Models), - (&["prx", "providers"], cli_tracing::CliCommand::Providers), - (&["prx", "routes", "list"], cli_tracing::CliCommand::Routes), - (&["prx", "channel", "start"], cli_tracing::CliCommand::ChannelStart), - (&["prx", "channel", "list"], cli_tracing::CliCommand::ChannelManage), - (&["prx", "integrations"], cli_tracing::CliCommand::Integrations), - (&["prx", "skills", "list"], cli_tracing::CliCommand::Skills), - (&["prx", "migrate", "status"], cli_tracing::CliCommand::Migrate), - ( - &["prx", "auth", "login", "--provider", "openai-codex"], - cli_tracing::CliCommand::Auth, - ), - (&["prx", "approval", "list"], cli_tracing::CliCommand::Approval), - (&["prx", "audit", "attest-eu-ai-act"], cli_tracing::CliCommand::Audit), - (&["prx", "config", "show"], cli_tracing::CliCommand::Config), - (&["prx", "session-worker"], cli_tracing::CliCommand::SessionWorker), - (&["prx", "completions", "bash"], cli_tracing::CliCommand::Completions), - #[cfg(feature = "test-mock")] - ( - &[ - "prx", - "__mailbox-harness", - "accept-adopt", - "--workspace", - "prx_workspace", - ], - cli_tracing::CliCommand::SessionWorker, - ), - ]; - #[cfg(feature = "wasm-plugins")] - let plugin_case: &[(&[&str], cli_tracing::CliCommand)] = - &[(&["prx", "plugin", "list"], cli_tracing::CliCommand::Plugin)]; - #[cfg(not(feature = "wasm-plugins"))] - let plugin_case: &[(&[&str], cli_tracing::CliCommand)] = &[]; - - let mut seen = Vec::new(); - for (argv, want) in cases.iter().chain(plugin_case.iter()) { - let cli = Cli::try_parse_from(*argv).unwrap_or_else(|error| panic!("{argv:?}: {error}")); - assert_eq!(cli_tracing_command(&cli.command), *want, "{argv:?}"); - seen.push(commands_coverage_tag(&cli.command)); - } - let mut expected_tags = vec![ - "Init", - "Go", - "Chat", - "ChatMessage", - "Gateway", - "Daemon", - "Service", - "Doctor", - "Status", - "Tasks", - "Memory", - "Evolution", - "Cost", - "Fitness", - "Cron", - "Xin", - "Causal", - "DecisionEngine", - "Models", - "Providers", - "Routes", - "ChannelStart", - "ChannelManage", - "Integrations", - "Skills", - "Migrate", - "Auth", - "Approval", - "Audit", - "Config", - "SessionWorker", - "Completions", - ]; - #[cfg(feature = "wasm-plugins")] - expected_tags.push("Plugin"); - #[cfg(feature = "test-mock")] - expected_tags.push("MailboxHarness"); - expected_tags.sort_unstable(); - seen.sort_unstable(); - assert_eq!(seen, expected_tags); - } - - /// E-4 (RED before PMM-E): a secret on the command line draws a warning - /// that names the alternative and never repeats the secret; the stdin - /// and environment alternatives draw none. - #[test] - fn a_secret_argument_draws_a_warning_naming_the_alternative() { - const SENTINEL: &str = "sk-pmme-warning-sentinel"; - for (args, flag, alternative) in [ - (vec!["prx", "init", "--api-key", SENTINEL], "--api-key", "--from-stdin"), - (vec!["prx", "go", "-k", SENTINEL], "-k/--key", "--from-stdin"), - ( - vec![ - "prx", - "auth", - "paste-token", - "--provider", - "anthropic", - "--token", - SENTINEL, - ], - "--token", - "--from-stdin", - ), - ] { - let cli = Cli::try_parse_from(&args).unwrap_or_else(|error| panic!("{args:?}: {error}")); - let warning = argv_secret_warning(&cli.command).unwrap_or_else(|| panic!("{args:?}: no warning")); - assert!(warning.contains(flag) && warning.contains(alternative), "{warning}"); - assert!(!warning.contains(SENTINEL), "{warning}"); - } - for args in [ - vec!["prx", "init", "--from-stdin"], - vec!["prx", "init", "--from-env", "OPENROUTER_API_KEY"], - vec!["prx", "go", "--from-env", "ANTHROPIC_API_KEY"], - vec!["prx", "go", "--from-stdin", "--message", "hi"], - vec!["prx", "auth", "paste-token", "--provider", "anthropic", "--from-stdin"], - vec!["prx", "auth", "paste-token", "--provider", "anthropic"], - ] { - let cli = Cli::try_parse_from(&args).unwrap_or_else(|error| panic!("{args:?}: {error}")); - assert_eq!(argv_secret_warning(&cli.command), None, "{args:?}"); - } - // The argument and its alternative are exclusive. - assert!(Cli::try_parse_from(["prx", "init", "--api-key", SENTINEL, "--from-stdin"]).is_err()); - assert!(Cli::try_parse_from(["prx", "go", "-k", SENTINEL, "--from-env", "X"]).is_err()); - } - - /// `prx tasks send` must repeat the server's outcome, not upgrade it. - /// - /// The endpoint tags a success `queued` because it can only see that the - /// message reached the target's steering queue. This renderer used to print - /// "Delivered to ..." unconditionally and never printed the outcome at all, - /// so an operator steering a run that never drains its queue was told the - /// instruction had landed. - /// - /// MUTATION GUARD: restore a fixed "Delivered" headline in - /// `render_task_message` and the first two assertions fail. - #[test] - fn a_sent_message_is_reported_as_the_server_tagged_it() { - let report = openprx::runtime::tasks_cli::MessageReport { - requested: "w3".to_string(), - id: "w3".to_string(), - run_id: Some("d9671848-1111-2222-3333-444444444444".to_string()), - kind: "sub_agent".to_string(), - name: "sub-agent".to_string(), - outcome: "queued".to_string(), - note: Some("the message is on the target's steering queue".to_string()), - }; - - let rendered = render_task_message(&report); - assert!( - !rendered.to_lowercase().contains("deliver"), - "the CLI must not claim a delivery the server did not report: {rendered}" - ); - assert!( - rendered.contains("outcome: queued"), - "the server's own tag must be on screen: {rendered}" - ); - assert!(rendered.contains("w3"), "{rendered}"); - assert!( - rendered.contains("run_id: d9671848-1111-2222-3333-444444444444"), - "{rendered}" - ); - assert!( - rendered.contains("the message is on the target's steering queue"), - "the server's note explains why queued is not read: {rendered}" - ); - } - - /// A gateway that sends no note gets no invented one. - #[test] - fn a_missing_note_is_not_replaced_by_a_client_side_guess() { - let report = openprx::runtime::tasks_cli::MessageReport { - requested: "w3".to_string(), - id: "w3".to_string(), - run_id: None, - kind: "sub_agent".to_string(), - name: "sub-agent".to_string(), - outcome: "queued".to_string(), - note: None, - }; - - let rendered = render_task_message(&report); - assert_eq!( - rendered, "Message to w3 [sub_agent] sub-agent (run_id: -) — outcome: queued", - "with no note the renderer prints one line and nothing else" - ); - } - - fn listed(kind: &str, name: &str, steerable: bool) -> openprx::runtime::tasks_cli::WorkItem { - openprx::runtime::tasks_cli::WorkItem { - id: "w2".to_string(), - kind: kind.to_string(), - name: name.to_string(), - state: "running".to_string(), - parent: None, - run_id: None, - batch_id: None, - elapsed_secs: 3, - pid: None, - pgid: None, - steerable, - } - } - - /// The listing has to separate the rows that accept a message from the ones - /// that only look like they do. - /// - /// The KIND column cannot do it: a detached gateway job is registered as - /// `sub_agent` and has no steering channel at all, so an operator reading - /// the kind as permission sends a message, gets a 409, and has no way to - /// tell a wrong address from an unsteerable target. Both rows below are - /// `sub_agent`; only one of them can be steered. - /// - /// MUTATION GUARD: drop the `(steerable)` mark from `work_item_line` and - /// the first assertion fails. - #[test] - fn a_steerable_row_is_marked_and_a_look_alike_is_not() { - let run = work_item_line(&listed("sub_agent", "researcher", true), false); - assert!( - run.contains("(steerable)"), - "a run that takes messages must say so: {run}" - ); - - let job = work_item_line(&listed("sub_agent", "gateway:webhook:anonymous", false), false); - assert!( - !job.contains("steerable"), - "a gateway job is listed sub_agent but takes no messages, so it must not be marked: {job}" - ); - assert!(job.contains("sub_agent"), "the kind is still reported as it is: {job}"); - } - - #[test] - fn init_help_includes_model_flag() { - let cmd = Cli::command(); - let init = cmd - .get_subcommands() - .find(|subcommand| subcommand.get_name() == "init") - .expect("init subcommand must exist"); - - let has_model_flag = init - .get_arguments() - .any(|arg| arg.get_id().as_str() == "model" && arg.get_long() == Some("model")); - - assert!( - has_model_flag, - "init help should include --model for quick setup overrides" - ); - } - - #[test] - fn init_cli_accepts_model_provider_and_api_key_in_quick_mode() { - let cli = Cli::try_parse_from([ - "prx", - "init", - "--provider", - "openrouter", - "--model", - "custom-model-946", - "--api-key", - "sk-issue946", - ]) - .expect("quick init invocation should parse"); - - match cli.command { - Commands::Init { - interactive, - channels_only, - api_key, - provider, - model, - .. - } => { - assert!(!interactive); - assert!(!channels_only); - assert_eq!(provider.as_deref(), Some("openrouter")); - assert_eq!(model.as_deref(), Some("custom-model-946")); - assert_eq!(api_key.as_deref(), Some("sk-issue946")); - } - other => panic!("expected init command, got {other:?}"), - } - } - - #[test] - fn chat_continue_flag_parses_as_resume_last_intent() { - let cli = Cli::try_parse_from(["prx", "chat", "--continue"]).expect("chat --continue should parse"); - match cli.command { - Commands::Chat { - continue_last, session, .. - } => { - assert!(continue_last); - assert!(session.is_none()); - } - other => panic!("expected chat command, got {other:?}"), - } - } - - #[test] - fn chat_explicit_session_can_coexist_with_continue() { - let cli = Cli::try_parse_from(["prx", "chat", "--continue", "--session", "abc"]) - .expect("explicit --session with --continue should parse"); - match cli.command { - Commands::Chat { - continue_last, session, .. - } => { - assert!(continue_last); - assert_eq!(session.as_deref(), Some("abc")); - } - other => panic!("expected chat command, got {other:?}"), - } - } - - #[test] - fn chat_message_parses_short_flag_save_and_workdir() { - let root = tempfile::tempdir().expect("test: root"); - let workdir = root.path().to_str().expect("test: root path"); - let cli = Cli::try_parse_from([ - "prx", - "chat", - "-q", - "/compact", - "--save", - "--workdir", - workdir, - "-m", - "m1", - ]) - .expect("test: chat one-shot flags"); - match cli.command { - Commands::Chat { - message, - save, - workdir: Some(parsed), - model, - .. - } => { - assert_eq!(message.as_deref(), Some("/compact")); - assert!(save); - assert_eq!(model.as_deref(), Some("m1")); - assert_eq!(parsed, root.path().canonicalize().expect("test: canonical root")); - } - other => panic!("expected chat command, got {other:?}"), - } - for argv in [ - &["prx", "chat", "--save"][..], - &["prx", "chat", "--message", "x", "--list-sessions"], - &["prx", "chat", "--workdir", "relative"], - ] { - let error = Cli::try_parse_from(argv).expect_err("test: invalid one-shot usage"); - assert_eq!(error.exit_code(), 2, "test: clap usage exit for {argv:?}"); - } - } - - #[test] - fn chat_workdir_is_canonical_and_requires_an_existing_absolute_directory() { - let root = tempfile::tempdir().expect("test: root"); - let alias = root.path().join("."); - let cli = Cli::try_parse_from(["prx", "chat", "--workdir", alias.to_str().expect("test: root path")]) - .expect("test: canonical workdir"); - assert!( - matches!(cli.command, Commands::Chat { workdir: Some(ref workdir), .. } if *workdir == root.path().canonicalize().expect("test: canonical root")), - "test: parsed root canonicalized" - ); - for path in [ - "relative", - root.path().join("missing").to_str().expect("test: missing path"), - ] { - let error = Cli::try_parse_from(["prx", "chat", "--workdir", path]).expect_err("test: invalid root"); - assert_eq!(error.exit_code(), 2, "test: clap usage exit"); - } - } - - #[test] - fn prx_causal_parses_any_arguments_and_decision_engine_replaces_it() { - for args in [ - &["prx", "causal"][..], - &["prx", "causal", "status", "--json"], - &["prx", "causal", "config", "set", "backend", "--kind", "builtin"], - ] { - let cli = Cli::try_parse_from(args).expect("retired causal command still parses"); - assert!(matches!(cli.command, Commands::Causal { .. }), "{args:?}"); - } - let cli = Cli::try_parse_from(["prx", "decision-engine", "status", "--json"]).expect("status parses"); - assert!(matches!( - cli.command, - Commands::DecisionEngine { - json: true, - command: openprx::decision_engine_cli::DecisionEngineCommands::Status, - } - )); - let cli = Cli::try_parse_from(["prx", "decision-engine", "config", "set", "enabled", "true", "--yes"]) - .expect("config set parses"); - assert!(matches!( - cli.command, - Commands::DecisionEngine { - command: openprx::decision_engine_cli::DecisionEngineCommands::Config { .. }, - .. - } - )); - assert!( - Cli::try_parse_from([ - "prx", - "decision-engine", - "config", - "set", - "enabled", - "true", - "--confirm-high-risk", - "r" - ]) - .is_err(), - "a confirmation without --yes" - ); - } - - /// No `prx decision-engine` subcommand takes a secret on the command line. - #[test] - fn no_decision_engine_subcommand_accepts_a_secret_argument() { - fn check(command: &clap::Command, path: &str, violations: &mut Vec) { - for arg in command.get_arguments() { - let names = std::iter::once(arg.get_id().as_str().to_string()) - .chain(arg.get_long().map(str::to_string)) - .map(|name| name.to_ascii_lowercase()); - for name in names { - if ["key", "token", "secret", "password", "credential", "bearer"] - .iter() - .any(|word| name.contains(word)) - && name != "key" - { - violations.push(format!("{path} --{name}")); - } - } - } - for sub in command.get_subcommands() { - check(sub, &format!("{path} {}", sub.get_name()), violations); - } - } - let root = Cli::command(); - let engine = root - .find_subcommand("decision-engine") - .expect("prx decision-engine exists"); - let mut violations = Vec::new(); - check(engine, "decision-engine", &mut violations); - assert!(violations.is_empty(), "secret-shaped arguments: {violations:?}"); - } - - #[test] - fn completions_cli_parses_supported_shells() { - for shell in ["bash", "fish", "zsh", "powershell", "elvish"] { - let cli = Cli::try_parse_from(["prx", "completions", shell]).expect("completions invocation should parse"); - match cli.command { - Commands::Completions { .. } => {} - other => panic!("expected completions command, got {other:?}"), - } - } - } - - #[test] - fn config_show_cli_parses_default_and_json_format() { - let cli = Cli::try_parse_from(["prx", "config", "show"]).expect("config show should parse"); - match cli.command { - Commands::Config { - config_command: ConfigCommands::Show { format }, - } => assert_eq!(format, ConfigShowFormat::Toml), - other => panic!("expected config show command, got {other:?}"), - } - - let cli = Cli::try_parse_from(["prx", "config", "show", "--format", "json"]) - .expect("config show --format json should parse"); - match cli.command { - Commands::Config { - config_command: ConfigCommands::Show { format }, - } => assert_eq!(format, ConfigShowFormat::Json), - other => panic!("expected config show json command, got {other:?}"), - } - } - - #[test] - fn memory_reindex_cli_parses() { - let cli = Cli::try_parse_from(["prx", "memory", "reindex"]).expect("memory reindex should parse"); - match cli.command { - Commands::Memory { - memory_command: MemoryCommands::Reindex { json }, - } => assert!(!json), - other => panic!("expected memory reindex command, got {other:?}"), - } - - let cli = - Cli::try_parse_from(["prx", "memory", "reindex", "--json"]).expect("memory reindex --json should parse"); - match cli.command { - Commands::Memory { - memory_command: MemoryCommands::Reindex { json }, - } => assert!(json), - other => panic!("expected memory reindex command, got {other:?}"), - } - } - - #[test] - fn approval_revoke_cli_parses() { - let cli = Cli::try_parse_from([ - "prx", - "approval", - "revoke", - "grant-test", - "--reason", - "operator requested", - ]) - .expect("approval revoke should parse"); - match cli.command { - Commands::Approval { - approval_command: ApprovalCommands::Revoke { grant_id, reason }, - } => { - assert_eq!(grant_id, "grant-test"); - assert_eq!(reason, "operator requested"); - } - other => panic!("expected approval revoke command, got {other:?}"), - } - } - - #[test] - fn eu_ai_act_audit_cli_parses_json_and_output() { - let cli = Cli::try_parse_from([ - "prx", - "audit", - "attest-eu-ai-act", - "--json", - "--output", - "/tmp/eu-ai-act-test.json", - ]) - .expect("eu ai act attestation should parse"); - - match cli.command { - Commands::Audit { - audit_command: - AuditCommands::AttestEuAiAct { - json, - format, - output, - verbose, - fail_on, - }, - } => { - assert!(json); - assert_eq!(format, AuditOutputFormat::Markdown); - assert_eq!( - output.as_deref(), - Some(std::path::Path::new("/tmp/eu-ai-act-test.json")) - ); - assert!(!verbose); - assert_eq!(fail_on, None); - } - other => panic!("expected audit attest-eu-ai-act command, got {other:?}"), - } - } - - #[test] - fn eu_declaration_cli_requires_explicit_signature_reference() { - let cli = Cli::try_parse_from([ - "prx", - "audit", - "generate-eu-declaration", - "--output", - "declaration.json", - "--signature-reference", - "external:receipt-1", - ]) - .expect("declaration generator should parse"); - match cli.command { - Commands::Audit { - audit_command: - AuditCommands::GenerateEuDeclaration { - output, - signature_reference, - }, - } => { - assert_eq!(output.as_deref(), Some(std::path::Path::new("declaration.json"))); - assert_eq!(signature_reference, "external:receipt-1"); - } - other => panic!("expected declaration generator, got {other:?}"), - } - assert!( - Cli::try_parse_from([ - "prx", - "audit", - "generate-eu-declaration", - "--output", - "declaration.json", - ]) - .is_err() - ); - } - - #[test] - fn incident_audit_cli_parses_mutating_and_export_commands() { - let create = Cli::try_parse_from(["prx", "audit", "incident-create", "--input", "incident.json"]) - .expect("incident create should parse"); - assert!(matches!( - create.command, - Commands::Audit { - audit_command: AuditCommands::IncidentCreate { input } - } if input == std::path::Path::new("incident.json") - )); - - let export = Cli::try_parse_from([ - "prx", - "audit", - "incident-export", - "incident-7", - "--output", - "incident-7-export.json", - ]) - .expect("incident export should parse"); - assert!(matches!( - export.command, - Commands::Audit { - audit_command: AuditCommands::IncidentExport { - incident_id, - output, - } - } if incident_id == "incident-7" && output == std::path::Path::new("incident-7-export.json") - )); - } - - /// A default config whose files live in `dir`. The binary's tests link the - /// production library, where the default paths name the real - /// `~/.openprx`, and the attestation reads the workspace (D-070). - fn scratch_config(dir: &std::path::Path) -> Config { - Config { - config_path: dir.join("config.toml"), - workspace_dir: dir.join("workspace"), - ..Config::default() - } - } - - #[test] - fn declaration_attestation_respects_operator_classification() { - let temp = tempfile::TempDir::new().unwrap(); - let mut config = scratch_config(temp.path()); - let c02_status = |config: &Config| { - build_eu_ai_act_attestation(config) - .checks - .into_iter() - .find(|check| check.id == "C02") - .expect("C02 control") - .status - }; - assert_eq!(c02_status(&config), ControlStatus::Unknown); - - config.compliance.eu_ai_act.classification.status = config::schema::EuAiActRiskClassification::NotHighRisk; - config.compliance.eu_ai_act.classification.owner = Some("legal-owner".to_string()); - config.compliance.eu_ai_act.classification.assessed_at = Some("2026-07-18".to_string()); - assert_eq!(c02_status(&config), ControlStatus::NotApplicable); - - config.compliance.eu_ai_act.classification.status = config::schema::EuAiActRiskClassification::HighRisk; - assert_eq!(c02_status(&config), ControlStatus::Fail); - } - - #[test] - fn incident_attestation_requires_and_verifies_durable_store_for_high_risk() { - let temp = tempfile::TempDir::new().unwrap(); - let store_path = temp.path().join("article-73.sqlite3"); - let mut config = scratch_config(temp.path()); - config.compliance.eu_ai_act.classification.status = config::schema::EuAiActRiskClassification::HighRisk; - - let m04_status = |config: &Config| { - build_eu_ai_act_attestation(config) - .checks - .into_iter() - .find(|check| check.id == "M04") - .expect("M04 control") - .status - }; - assert_eq!(m04_status(&config), ControlStatus::Fail); - - config.compliance.eu_ai_act.incident_store_path = Some(store_path.clone()); - openprx::compliance::incident::IncidentStore::open(&store_path).unwrap(); - assert_eq!(m04_status(&config), ControlStatus::Pass); - } - - #[test] - fn eu_ai_act_attestation_has_required_check_counts() { - let temp = tempfile::TempDir::new().unwrap(); - let attestation = build_eu_ai_act_attestation(&scratch_config(temp.path())); - - assert_eq!(attestation.total_checks, 24); - assert_eq!(attestation.checks.len(), 24); - assert_eq!( - attestation.total_checks, - attestation.passed_count - + attestation.warning_count - + attestation.failed_count - + attestation.unknown_count - + attestation.not_applicable_count - ); - - let json = render_eu_ai_act_attestation_json(&attestation).expect("attestation should serialize"); - let value: serde_json::Value = serde_json::from_str(&json).expect("attestation json should parse"); - assert_eq!(value.get("total_checks").and_then(serde_json::Value::as_u64), Some(24)); - assert_eq!( - value.get("report_type").and_then(serde_json::Value::as_str), - Some("EU AI Act implementation attestation") - ); - let c02 = value - .get("checks") - .and_then(serde_json::Value::as_array) - .and_then(|checks| { - checks - .iter() - .find(|check| check.get("id").and_then(serde_json::Value::as_str) == Some("C02")) - }) - .expect("C02 control should exist"); - assert_eq!( - c02.get("framework_reference").and_then(serde_json::Value::as_str), - Some("Article 47 and Annex V") - ); - } - - #[test] - fn eu_ai_act_audit_cli_parses_fail_on_and_gate_semantics() { - let cli = Cli::try_parse_from(["prx", "audit", "attest-eu-ai-act", "--json", "--fail-on", "warning"]) - .expect("strict attestation gate should parse"); - let Commands::Audit { - audit_command: AuditCommands::AttestEuAiAct { fail_on, .. }, - } = cli.command - else { - panic!("expected audit command"); - }; - assert_eq!(fail_on, Some(AuditFailOn::Warning)); - - let temp = tempfile::TempDir::new().unwrap(); - let attestation = build_eu_ai_act_attestation(&scratch_config(temp.path())); - assert!(!attestation_fails_gate(&attestation, AuditFailOn::Fail)); - assert!(attestation_fails_gate(&attestation, AuditFailOn::Warning)); - } - - #[test] - fn doctor_memory_cli_parses() { - let cli = Cli::try_parse_from(["prx", "doctor", "memory"]).expect("doctor memory should parse"); - match cli.command { - Commands::Doctor { - doctor_command: Some(DoctorCommands::Memory), - } => {} - other => panic!("expected doctor memory command, got {other:?}"), - } - } - - #[test] - fn doctor_runtime_cli_parses() { - let cli = Cli::try_parse_from(["prx", "doctor", "runtime"]).expect("doctor runtime should parse"); - match cli.command { - Commands::Doctor { - doctor_command: Some(DoctorCommands::Runtime), - } => {} - other => panic!("expected doctor runtime command, got {other:?}"), - } - } - - #[test] - fn config_show_redacts_sensitive_toml_values() { - let mut value = toml::Value::Table(toml::toml! { - default_provider = "kimi-code" - api_key = "enc2:encrypted-root" - - [storage.provider.config] - db_url = "postgres://user:secret@example/prx" - - [agents.worker] - api_key = "sk-agent" - model = "kimi-k2" - - [channels.slack] - bot_token = "xoxb-token" - allowed_users = ["alice"] - - [nested] - api_keys = ["sk-one", "sk-two"] - credential = { username = "user", password = "pass" } - }); - - config::secret_paths::redact(&mut value); - - let root = value.as_table().expect("redacted value should remain a table"); - assert_eq!(root.get("api_key").and_then(toml::Value::as_str), Some("***")); - assert_eq!( - root.get("default_provider").and_then(toml::Value::as_str), - Some("kimi-code") - ); - - let nested = root - .get("nested") - .and_then(toml::Value::as_table) - .expect("nested table should remain"); - assert_eq!( - nested - .get("api_keys") - .and_then(toml::Value::as_array) - .expect("api_keys should remain an array") - .iter() - .filter_map(toml::Value::as_str) - .collect::>(), - vec!["***", "***"] - ); - - let rendered = toml::to_string_pretty(&value).expect("redacted config should serialize"); - assert!(rendered.contains("default_provider = \"kimi-code\"")); - assert!(rendered.contains("model = \"kimi-k2\"")); - assert!(rendered.contains("allowed_users = [\"alice\"]")); - assert!(rendered.contains("api_key = \"***\"")); - assert!(rendered.contains("db_url = \"***\"")); - assert!(rendered.contains("bot_token = \"***\"")); - assert!(!rendered.contains("enc2:encrypted-root")); - assert!(!rendered.contains("postgres://user:secret@example/prx")); - assert!(!rendered.contains("sk-agent")); - assert!(!rendered.contains("xoxb-token")); - assert!(!rendered.contains("sk-one")); - assert!(!rendered.contains("password = \"pass\"")); - } - - #[test] - fn models_and_integrations_accept_bare_and_list_commands() { - let cli = Cli::try_parse_from(["prx", "models"]).expect("bare models should parse"); - match cli.command { - Commands::Models { model_command } => assert!(model_command.is_none()), - other => panic!("expected bare models command, got {other:?}"), - } - - let cli = - Cli::try_parse_from(["prx", "models", "list", "--provider", "openai"]).expect("models list should parse"); - match cli.command { - Commands::Models { - model_command: Some(ModelCommands::List { provider, .. }), - } => assert_eq!(provider.as_deref(), Some("openai")), - other => panic!("expected models list command, got {other:?}"), - } - - let cli = Cli::try_parse_from(["prx", "integrations"]).expect("bare integrations should parse"); - match cli.command { - Commands::Integrations { integration_command } => assert!(integration_command.is_none()), - other => panic!("expected bare integrations command, got {other:?}"), - } - - let cli = Cli::try_parse_from(["prx", "integrations", "list"]).expect("integrations list should parse"); - match cli.command { - Commands::Integrations { - integration_command: Some(IntegrationCommands::List), - } => {} - other => panic!("expected integrations list command, got {other:?}"), - } - } - - #[test] - fn migrate_plan_uses_the_library_owned_dto() { - let cli = Cli::try_parse_from(["prx", "migrate", "plan", "--target-version", "7"]) - .expect("migrate plan should parse"); - match cli.command { - Commands::Migrate { - migrate_command: MigrateCommands::Plan { target_version }, - } => assert_eq!(target_version, "7"), - other => panic!("expected migrate plan command, got {other:?}"), - } - } - - #[test] - fn xin_task_and_goal_step_commands_parse() { - let cli = Cli::try_parse_from([ - "prx", - "xin", - "add", - "health-watch", - "inspect health", - "--recurring", - "--interval-secs", - "300", - ]) - .expect("xin add should parse"); - assert!(matches!( - cli.command, - Commands::Xin { - xin_command: XinCommands::Add { - recurring: true, - interval_secs: 300, - .. - } - } - )); - - let cli = Cli::try_parse_from([ - "prx", - "xin", - "steps", - "add", - "goal-1", - "verify", - "verify artifacts", - "--sequence", - "2", - ]) - .expect("xin steps add should parse"); - assert!(matches!( - cli.command, - Commands::Xin { - xin_command: XinCommands::Steps { - step_command: openprx::XinStepCommands::Add { sequence: Some(2), .. } - } - } - )); - } - - #[test] - fn completion_generation_mentions_binary_name() -> Result<()> { - const SHELLS: [CompletionShell; 5] = [ - CompletionShell::Bash, - CompletionShell::Fish, - CompletionShell::Zsh, - CompletionShell::PowerShell, - CompletionShell::Elvish, - ]; - for shell in SHELLS { - let mut output = Vec::new(); - write_shell_completion(shell, &mut output) - .with_context(|| format!("test: generate {shell:?} completion for the complete CLI tree"))?; - let script = String::from_utf8(output).context("test: completion output must be UTF-8")?; - assert!(script.contains("prx"), "{shell:?} completion lost the binary name"); - } - Ok(()) - } -} +include!("main/section_1.rs"); +include!("main/section_2.rs"); +include!("main/section_3.rs"); diff --git a/src/main/section_1.rs b/src/main/section_1.rs new file mode 100644 index 000000000..86680d718 --- /dev/null +++ b/src/main/section_1.rs @@ -0,0 +1,1647 @@ +use anyhow::{Context, Result, bail}; +use chrono::Utc; +use clap::{Args, CommandFactory, Parser, Subcommand, ValueEnum}; +use dialoguer::{Input, Password}; +use openprx::{ + CHAT_TRACING_RELOAD, ChannelCommands, ChatFmtLayer, Config, CronCommands, EvolutionCommands, FitnessCommands, + IntegrationCommands, MigrateCommands, ServiceCommands, SkillCommands, XinCommands, acl, agent, auth, channels, + chat, cli_tracing, config, cron, daemon, doctor, evolution_cli, fitness_cli, gateway, handle_xin_command, + integrations, memory, migration, providers, runtime, security, service, session_worker, skills, +}; +use rusqlite::{Connection, OptionalExtension, params}; +use serde::{Deserialize, Serialize}; +use std::{fs, io::Write, path::PathBuf}; +use tracing::warn; +use tracing_subscriber::{EnvFilter, fmt}; + +fn parse_workdir(value: &str) -> Result { + openprx::config::RuntimeConfig::validate_workdir(std::path::Path::new(value)).map_err(|error| error.to_string()) +} + +fn parse_temperature(s: &str) -> std::result::Result { + let t: f64 = s.parse().map_err(|e| format!("{e}"))?; + if !(0.0..=2.0).contains(&t) { + return Err("temperature must be between 0.0 and 2.0".to_string()); + } + Ok(t) +} + +const fn cli_tracing_command(command: &Commands) -> cli_tracing::CliCommand { + match command { + Commands::Init { .. } | Commands::Token { .. } => cli_tracing::CliCommand::Init, + Commands::Go { .. } => cli_tracing::CliCommand::Go, + Commands::Chat { message: Some(_), .. } => cli_tracing::CliCommand::ChatMessage, + Commands::Chat { .. } => cli_tracing::CliCommand::Chat, + Commands::Gateway { .. } => cli_tracing::CliCommand::Gateway, + Commands::Daemon { .. } => cli_tracing::CliCommand::Daemon, + Commands::Service { .. } => cli_tracing::CliCommand::Service, + Commands::Doctor { .. } => cli_tracing::CliCommand::Doctor, + Commands::A2a { .. } => cli_tracing::CliCommand::Status, + Commands::Status { .. } => cli_tracing::CliCommand::Status, + Commands::Tasks { .. } => cli_tracing::CliCommand::Tasks, + Commands::Memory { .. } => cli_tracing::CliCommand::Memory, + Commands::Evolution { .. } => cli_tracing::CliCommand::Evolution, + #[cfg(feature = "wasm-plugins")] + Commands::Plugin { .. } => cli_tracing::CliCommand::Plugin, + Commands::Cost { .. } => cli_tracing::CliCommand::Cost, + Commands::Fitness { .. } => cli_tracing::CliCommand::Fitness, + Commands::Cron { .. } => cli_tracing::CliCommand::Cron, + Commands::Xin { .. } => cli_tracing::CliCommand::Xin, + Commands::Causal { .. } => cli_tracing::CliCommand::Causal, + Commands::DecisionEngine { .. } => cli_tracing::CliCommand::DecisionEngine, + Commands::Models { .. } => cli_tracing::CliCommand::Models, + Commands::Providers { .. } => cli_tracing::CliCommand::Providers, + Commands::Routes { .. } => cli_tracing::CliCommand::Routes, + Commands::Channel { + channel_command: ChannelCommands::Start, + } => cli_tracing::CliCommand::ChannelStart, + Commands::Channel { .. } => cli_tracing::CliCommand::ChannelManage, + Commands::Integrations { .. } => cli_tracing::CliCommand::Integrations, + Commands::Skills { .. } => cli_tracing::CliCommand::Skills, + Commands::Migrate { .. } => cli_tracing::CliCommand::Migrate, + Commands::Auth { .. } => cli_tracing::CliCommand::Auth, + Commands::Approval { .. } => cli_tracing::CliCommand::Approval, + Commands::Audit { .. } => cli_tracing::CliCommand::Audit, + Commands::Config { .. } => cli_tracing::CliCommand::Config, + #[cfg(feature = "test-mock")] + Commands::MailboxHarness { .. } => cli_tracing::CliCommand::SessionWorker, + Commands::SessionWorker { .. } => cli_tracing::CliCommand::SessionWorker, + Commands::Completions { .. } => cli_tracing::CliCommand::Completions, + } +} + +// CLI dispatch remains binary-owned; every runtime subsystem it calls is owned +// and compiled once by the openprx library. + + + +// `prx providers|models|routes|config` management handlers: binary-owned, +// every operation calls the library's `config::manage` service in-process. + + +/// `OpenPRX` - 100% Rust. 100% Agnostic. Your AI, your rules. +#[derive(Parser, Debug)] +#[command(name = "prx")] +#[command(author = "g1e2x87")] +#[command(version = env!("CARGO_PKG_VERSION"))] +#[command(about = "The fastest, smallest AI assistant.", long_about = None)] +struct Cli { + #[arg(long, global = true)] + config_dir: Option, + + #[command(subcommand)] + command: Commands, +} + +#[derive(Subcommand, Debug)] +enum MemoryCommands { + /// Rebuild memory/document indexes and backfill stale embeddings where supported + Reindex { + /// Output machine-readable JSON + #[arg(long)] + json: bool, + }, +} + +#[derive(Subcommand, Debug)] +enum ApprovalCommands { + /// List runtime approval grants + List { + /// Filter by approval grant schema version + #[arg(long)] + version: Option, + }, + /// Verify runtime approval grants + Verify { + /// Verify all known grants + #[arg(long)] + all: bool, + /// Grant id to verify + grant_id: Option, + }, + /// Revoke a runtime approval grant + Revoke { + /// Grant id to revoke + grant_id: String, + /// Human-readable revocation reason + #[arg(long, default_value = "operator revoked")] + reason: String, + }, +} + +#[derive(Subcommand, Debug)] +enum AuditCommands { + /// Generate a local EU AI Act implementation attestation + #[command(name = "attest-eu-ai-act")] + AttestEuAiAct { + /// Emit JSON to stdout + #[arg(long)] + json: bool, + /// Output format + #[arg(long, value_enum, default_value_t = AuditOutputFormat::Markdown)] + format: AuditOutputFormat, + /// Write the attestation to a file + #[arg(long)] + output: Option, + /// Include implementation notes in markdown output + #[arg(long)] + verbose: bool, + /// Turn the report into a release gate at the selected severity + #[arg(long, value_enum)] + fail_on: Option, + }, + /// Generate a versioned Article 47 / Annex V declaration artifact from explicit operator inputs + #[command(name = "generate-eu-declaration")] + GenerateEuDeclaration { + /// Output path; defaults to compliance.eu_ai_act.declaration.artifact_path + #[arg(long)] + output: Option, + /// Reference to an operator-controlled external signature or signing receipt + #[arg(long)] + signature_reference: String, + }, + /// Create a durable Article 73 serious-incident record from a JSON input file + #[command(name = "incident-create")] + IncidentCreate { + /// JSON file containing the incident classification and ownership fields + #[arg(long)] + input: PathBuf, + }, + /// Record or replace the initial report for an open serious incident + #[command(name = "incident-initial-report")] + IncidentInitialReport { + incident_id: String, + /// UTF-8 file containing the initial report + #[arg(long)] + input: PathBuf, + }, + /// Append supplemental facts to a serious incident + #[command(name = "incident-supplement")] + IncidentSupplement { + incident_id: String, + /// UTF-8 file containing the supplement + #[arg(long)] + input: PathBuf, + }, + /// Close a serious incident with an explicit timestamp and summary + #[command(name = "incident-close")] + IncidentClose { + incident_id: String, + /// RFC 3339 closure timestamp + #[arg(long)] + closed_at: String, + /// UTF-8 file containing the closure summary + #[arg(long)] + summary: PathBuf, + }, + /// Export an incident, supplements, and immutable audit-event hashes + #[command(name = "incident-export")] + IncidentExport { + incident_id: String, + #[arg(long)] + output: PathBuf, + }, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)] +enum AuditOutputFormat { + Markdown, + Json, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)] +enum AuditFailOn { + Fail, + Warning, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +enum ControlStatus { + Pass, + Warning, + Fail, + NotApplicable, + Unknown, +} + +impl ControlStatus { + const fn as_str(self) -> &'static str { + match self { + Self::Pass => "pass", + Self::Warning => "warning", + Self::Fail => "fail", + Self::NotApplicable => "not_applicable", + Self::Unknown => "unknown", + } + } +} + +#[derive(Debug, Serialize)] +struct EvidenceReference { + kind: &'static str, + reference: String, +} + +#[derive(Debug, Serialize)] +struct ApplicabilityDecision { + status: ControlStatus, + classification: String, + owner: Option, + reviewed_at: Option, +} + +#[derive(Debug, Serialize)] +struct EuAiActAttestation { + report_type: &'static str, + evaluator_version: &'static str, + product_version: &'static str, + source_identity: Option, + config_generation: Option, + config_source_revision: Option, + generated_at: String, + applicability: ApplicabilityDecision, + default_provider: Option, + total_checks: usize, + passed_count: usize, + warning_count: usize, + failed_count: usize, + unknown_count: usize, + not_applicable_count: usize, + checks: Vec, +} + +#[derive(Debug, Serialize)] +struct EuAiActCheck { + id: &'static str, + framework_reference: &'static str, + control: &'static str, + applicability: &'static str, + severity: &'static str, + status: ControlStatus, + observed_at: String, + evidence: Vec, + explanation: String, + remediation: String, +} + +#[derive(Copy, Clone, Debug, Eq, PartialEq, ValueEnum)] +enum CompletionShell { + #[value(name = "bash")] + Bash, + #[value(name = "fish")] + Fish, + #[value(name = "zsh")] + Zsh, + #[value(name = "powershell")] + PowerShell, + #[value(name = "elvish")] + Elvish, +} + +#[derive(Subcommand, Debug)] +enum TokenCommands { + Issue { + #[arg(long)] + out: PathBuf, + #[arg(long)] + force: bool, + }, +} + +#[derive(Subcommand, Debug)] +enum Commands { + /// Manage pinned mTLS messaging identities and peers. + A2a { + #[command(subcommand)] + command: openprx::messaging::a2a::cli::A2aCommand, + }, + /// Issue an install-owner bearer into a private output file + Token { + #[command(subcommand)] + command: TokenCommands, + }, + /// Initialize or repair configuration, channels and agent identity + Init { + /// Configuration preset (default: minimal) + #[arg(long, value_enum)] + spec: Option, + /// Target configuration directory + #[arg(long)] + dir: Option, + /// Repair existing configuration while preserving explicit operator settings + #[arg(long)] + force: bool, + + /// Run the full interactive wizard (default is quick setup) + #[arg(long)] + interactive: bool, + + /// Reconfigure channels only (fast repair flow) + #[arg(long)] + channels_only: bool, + + /// API key (quick mode only). Deprecated: an + /// argument is visible in the process list; use --from-stdin or --from-env + #[arg(long)] + api_key: Option, + + /// Read the API key from standard input (quick mode) + #[arg(long, conflicts_with_all = ["api_key", "from_env"])] + from_stdin: bool, + + /// Read the API key from this environment variable (quick mode) + #[arg(long, value_name = "VAR", conflicts_with = "api_key")] + from_env: Option, + + /// Provider name (quick mode; otherwise preserve the preset or existing selection) + #[arg(long)] + provider: Option, + /// Model ID override (used in quick mode) + #[arg(short = 'm', long)] + model: Option, + /// Declare native tool support for a model outside the release catalog (quick mode) + #[arg(long, conflicts_with = "no_native_tools")] + native_tools: bool, + /// Declare that a model outside the release catalog has no native tools (quick mode) + #[arg(long, conflicts_with = "native_tools")] + no_native_tools: bool, + /// Memory backend (sqlite, lucid, markdown, none) - used in quick mode, default: sqlite + #[arg(long)] + memory: Option, + /// The decision backend (quick mode): builtin or compatible_http; a + /// hosted service also needs --decision-credential-stdin + #[arg(long, value_enum)] + decision_backend: Option, + /// The decision endpoint (quick mode, compatible_http) + #[arg(long, requires = "decision_backend")] + decision_endpoint: Option, + /// The decision model, one exact version (quick mode) + #[arg(long, requires = "decision_backend")] + decision_model: Option, + /// Enable the advisory decision engine (quick mode): sets decision_engine.enabled = true + #[arg(long, requires = "decision_backend")] + decision_enable: bool, + /// Read the hosted decision backend's credential (typesafe or + /// openrouter) from standard input, store it as `cred-decision-` + /// and reference it (quick mode). Remote processing stays off until + /// `backend.remote_enabled` is set with `prx decision-engine config set` + #[arg(long, requires = "decision_backend", conflicts_with = "from_stdin")] + decision_credential_stdin: bool, + }, + + /// Instant start: provide an API key and chat immediately. No config files written. + #[command(long_about = "\ +Zero-configuration instant start. + +Detects credentials from multiple file-based sources without reading \ +environment variables. Provide an API key directly, or let PRX find \ +one from auth-profiles, config.toml, or Claude Code OAuth. + +No permanent files are written. A temporary workspace is used for \ +the session. + +Examples: + prx go -k sk-ant-api03-xxx # Anthropic (auto-detected) + prx go -k sk-proj-xxx # OpenAI (auto-detected) + prx go -k sk-ant-xxx -m claude-sonnet-4-20250514 + prx go # use existing auth-profiles + prx go --message 'Summarize this' # single-shot mode")] + Go { + /// API key (required on first use, or use existing auth-profiles). Deprecated: + /// an argument is visible in the process list; use --from-env + #[arg(short = 'k', long = "key")] + api_key: Option, + + /// Read the API key from this environment variable + #[arg(long, value_name = "VAR", conflicts_with = "api_key")] + from_env: Option, + + /// Read the API key from standard input (then the session reads no further input from + /// it; use with --message, or --from-env for an interactive session) + #[arg(long, conflicts_with_all = ["api_key", "from_env"])] + from_stdin: bool, + + /// Provider (auto-detected from key prefix if omitted) + #[arg(short = 'p', long)] + provider: Option, + + /// Model (uses provider default if omitted) + #[arg(short = 'm', long)] + model: Option, + + /// Single message mode (non-interactive) + #[arg(long)] + message: Option, + }, + + /// Start an interactive chat session with streaming output + #[command(long_about = "\ +Start an interactive chat session with the fullscreen terminal UI. + +Features streaming responses, tool execution display, and session history. +Uses the full Agent pipeline: memory recall, LLM routing, built-in tools, +and all configured providers. + +The fullscreen UI keeps transcript history inside PRX rather than in native +terminal scrollback. Use in-app scrolling while chatting and `/export [md|json]` +to save a transcript. Use `--plain` or `PRX_TUI=0` for the non-TUI reedline +fallback. + +Examples: + prx chat # fullscreen interactive session + prx chat -p ollama -m llama3.3 # use local model + prx chat -p anthropic # use Anthropic + PRX_TUI=0 prx chat # plain reedline fallback + prx chat --plain # plain text fallback + prx chat --continue # resume last session + prx chat --session last # resume last session + prx chat --session abc123 # resume specific session + prx chat --list-sessions # list saved sessions + prx chat --message 'What is 2+2?' # one turn: the reply on stdout, then exit + prx chat -q 'Summarize x' --save # one turn, saved as a resumable session + prx chat --session abc123 -q 'More?' # one turn in a saved session + +With --message (-q) chat runs exactly one turn and prints only the reply on \ +stdout. The message is literal model input; slash text is not a command. \ +Exit status: 0 answered, 2 refused by policy (the refusal reply is still \ +printed), 1 any other failure (`Error: ...` on stderr). The turn is not saved \ +as a session unless --save, --session or --continue is given; --session or \ +--continue naming no saved session is an error. In Supervised mode tool \ +approvals are asked on the terminal ([y/N/a]); without a terminal only \ +OPENPRX_APPROVAL_OVERRIDE can allow.")] + Chat { + /// Controlled H2 root ceilings JSON (aggregate resources, per-root time/concurrency). + #[arg(long = "h2-controlled-limits", requires = "h2_authority_seconds", + conflicts_with_all = ["plain", "list_sessions", "provider", "model", "temperature"])] + h2_limits: Option, + + /// Lifetime of this foreground OS-launched H2 authority, in seconds. + #[arg(long, requires = "h2_limits")] + h2_authority_seconds: Option, + + /// Provider to use (openrouter, anthropic, openai, ollama, etc.) + #[arg(short, long)] + provider: Option, + + /// Model to use + #[arg(short = 'm', long)] + model: Option, + + /// Temperature (0.0 - 2.0) + #[arg(short, long, default_value = "0.7", value_parser = parse_temperature)] + temperature: f64, + + /// Plain text output (no ANSI escapes, for piping) + #[arg(long)] + plain: bool, + + /// Resume a session by ID, or "last" for the most recent + #[arg(short, long)] + session: Option, + + /// Resume the most recent saved session. Explicit --session wins if both are provided. + #[arg(long = "continue")] + continue_last: bool, + + /// List all saved sessions and exit + #[arg(long)] + list_sessions: bool, + + /// Run one turn with this message, print only the reply and exit + #[arg(short = 'q', long, conflicts_with_all = ["list_sessions", "h2_limits", "h2_authority_seconds"])] + message: Option, + + /// Save the --message turn as a resumable chat session + #[arg(long, requires = "message")] + save: bool, + + /// Absolute existing working directory for shell, file tools and git. + #[arg(long, value_parser = parse_workdir)] + workdir: Option, + }, + + /// Start the gateway server (webhooks, websockets) + #[command(long_about = "\ +Start the gateway server (webhooks, websockets). + +Runs the HTTP/WebSocket gateway that accepts incoming webhook events \ +and WebSocket connections. Bind address defaults to the values in \ +your config file (gateway.host / gateway.port). + +Examples: + prx gateway # use config defaults + prx gateway -p 8080 # listen on port 8080 + prx gateway --host 0.0.0.0 # bind to all interfaces + prx gateway -p 0 # random available port")] + Gateway { + /// Delegate only this exact authenticated principal to the existing owner. + #[arg(long, requires_all = ["h2_limits", "h2_authority_seconds"])] + h2_principal: Option, + + /// Controlled H2 root ceilings JSON; excludes ordinary conversational spending. + #[arg(long = "h2-controlled-limits", requires_all = ["h2_principal", "h2_authority_seconds"])] + h2_limits: Option, + + /// Lifetime of the foreground local-review authority, in seconds. + #[arg(long, requires_all = ["h2_principal", "h2_limits"])] + h2_authority_seconds: Option, + + /// Port to listen on (use 0 for random available port); defaults to config gateway.port + #[arg(short, long)] + port: Option, + + /// Host to bind to; defaults to config gateway.host + #[arg(long)] + host: Option, + }, + + /// Start long-running autonomous runtime (gateway + channels + heartbeat + scheduler) + #[command(long_about = "\ +Start the long-running autonomous daemon. + +Launches the full OpenPRX runtime: gateway server, all configured \ +channels (Telegram, Discord, Slack, etc.), heartbeat monitor, and \ +the cron scheduler. This is the recommended way to run OpenPRX in \ +production or as an always-on assistant. + +Use 'prx service install' to register the daemon as an OS \ +service (systemd/launchd) for auto-start on boot. + +Examples: + prx daemon # use config defaults + prx daemon -p 9090 # gateway on port 9090 + prx daemon --host 127.0.0.1 # localhost only")] + Daemon { + /// Port to listen on (use 0 for random available port); defaults to config gateway.port + #[arg(short, long)] + port: Option, + + /// Host to bind to; defaults to config gateway.host + #[arg(long)] + host: Option, + }, + + /// Manage OS service lifecycle (launchd/systemd user service) + Service { + /// Init system to use: auto (detect), systemd, or openrc + #[arg(long, default_value = "auto", value_parser = ["auto", "systemd", "openrc"])] + service_init: String, + + #[command(subcommand)] + service_command: ServiceCommands, + }, + + /// Run diagnostics for daemon/scheduler/channel freshness + Doctor { + #[command(subcommand)] + doctor_command: Option, + }, + + /// Show system status (full details) + Status { + #[arg(long)] + json: bool, + }, + + /// Inspect and terminate work running inside a live PRX process + #[command(long_about = "\ +Inspect and terminate work running inside a live PRX process. + +PRX does not cut work off on a clock: a long agent run is normal business, so +nothing expires by itself. That makes this command the operator's backstop — +it lists every tool call, sub-agent run and child process the runtime is +currently holding, together with parent/child lineage and elapsed time, and +ends any of them on request. + +The registry lives inside the process that owns the work, so these subcommands +talk to a running gateway over HTTP rather than inspecting this invocation. + +Examples: + prx tasks list # what is running right now + prx tasks list --json # machine-readable, includes unreaped children + prx tasks kill w42 # kill w42 and everything it started + prx tasks kill w42 --no-cascade # kill only w42 + prx tasks kill # same, addressed by run id + prx tasks kill # end every member of a spawn_batch fan-out + prx tasks send \"also check Y\" # steer a running task mid-flight + prx tasks pools # connection-pool saturation")] + Tasks { + #[command(subcommand)] + tasks_command: TasksCommands, + }, + + /// Manage memory indexes and maintenance operations + Memory { + #[command(subcommand)] + memory_command: MemoryCommands, + }, + + /// Evolution dashboard and operations + Evolution { + /// Output machine-readable JSON + #[arg(long, global = true)] + json: bool, + #[command(subcommand)] + evolution_command: EvolutionCommands, + }, + + /// Inspect, authorize, and reload trusted WASM plugin artifacts. + #[cfg(feature = "wasm-plugins")] + Plugin { + #[command(subcommand)] + command: openprx::plugins::cli::PluginCommand, + }, + + /// Read workspace costs and outstanding reservations without creating state. + Cost { + /// Output machine-readable JSON. + #[arg(long)] + json: bool, + }, + + /// Inspect, run, and migrate daily self-system fitness snapshots. + Fitness { + /// Output machine-readable JSON. + #[arg(long, global = true)] + json: bool, + #[command(subcommand)] + fitness_command: FitnessCommands, + }, + + /// Configure and manage scheduled tasks + #[command(long_about = "\ +Configure and manage scheduled tasks. + +Schedule recurring, one-shot, or interval-based tasks using cron \ +expressions, RFC 3339 timestamps, durations, or fixed intervals. + +Cron expressions use the standard 5-field format: \ +'min hour day month weekday'. Timezones default to UTC; \ +override with --tz and an IANA timezone name. + +Examples: + prx cron list + prx cron add '0 9 * * 1-5' 'Good morning' --tz America/New_York + prx cron add '*/30 * * * *' 'Check system health' + prx cron add-at 2025-01-15T14:00:00Z 'Send reminder' + prx cron add-every 60000 'Ping heartbeat' + prx cron once 30m 'Run backup in 30 minutes' + prx cron pause + prx cron update --expression '0 8 * * *' --tz Europe/London")] + Cron { + #[command(subcommand)] + cron_command: CronCommands, + }, + + /// Manage Xin autonomous tasks and durable goal workflows. + #[command(long_about = "\ +Manage Xin autonomous tasks, execution history, and durable Goal/Step workflows. + +Examples: + prx xin status + prx xin list + prx xin add nightly-check 'Inspect service health' --recurring --interval-secs 3600 + prx xin update --priority high + prx xin run + prx xin cancel + prx xin goals add release-checklist + prx xin steps add verify 'Verify the release artifacts'")] + Xin { + #[command(subcommand)] + xin_command: XinCommands, + }, + + /// Retired: prints one line pointing at `prx decision-engine` + #[command(hide = true)] + Causal { + /// Ignored arguments of the retired command. + #[arg(num_args = 0.., trailing_var_arg = true, allow_hyphen_values = true)] + args: Vec, + }, + + /// Inspect and configure the advisory decision engine + DecisionEngine { + /// Output machine-readable JSON. + #[arg(long, global = true)] + json: bool, + #[command(subcommand)] + command: openprx::decision_engine_cli::DecisionEngineCommands, + }, + + /// Manage provider model catalogs + Models { + #[command(subcommand)] + model_command: Option, + }, + + /// List, configure and test AI providers and their credentials + #[command(long_about = "\ +List, configure and test AI providers and their credentials. + +With no subcommand, lists the supported providers and the configured ones. \ +Every change prints its plan first and writes nothing without --yes. \ +A credential is never taken on the command line: it is read from a hidden \ +prompt, standard input (--from-stdin) or an environment variable (--from-env). + +Examples: + prx providers + prx providers show anthropic + prx providers add anthropic --fallback --yes + prx providers credential status openai # which key PRX uses today + prx auth paste-token --provider openai --from-stdin + prx providers test openrouter --live")] + Providers { + #[command(subcommand)] + providers_command: Option, + }, + + /// Manage model routes (`hint:` selections) + Routes { + #[command(subcommand)] + routes_command: RoutesCommands, + }, + + /// Manage channels (telegram, discord, slack, wacli) + #[command(long_about = "\ +Manage communication channels. + +Add, remove, list, and health-check channels that connect OpenPRX \ +to messaging platforms. Supported channel types: telegram, discord, \ +slack, whatsapp, wacli, imessage, and email. + +Examples: + prx channel list + prx channel doctor + prx channel add telegram '{\"bot_token\":\"...\",\"name\":\"my-bot\"}' + prx channel remove my-bot + prx channel bind-telegram prx_user")] + Channel { + #[command(subcommand)] + channel_command: ChannelCommands, + }, + + /// Browse 50+ integrations + Integrations { + #[command(subcommand)] + integration_command: Option, + }, + + /// Manage skills (user-defined capabilities) + Skills { + #[command(subcommand)] + skill_command: SkillCommands, + }, + + /// Migrate data from other agent runtimes + Migrate { + #[command(subcommand)] + migrate_command: MigrateCommands, + }, + + /// Manage provider subscription authentication profiles + Auth { + #[command(subcommand)] + auth_command: AuthCommands, + }, + + /// Manage runtime approval grants + Approval { + #[command(subcommand)] + approval_command: ApprovalCommands, + }, + + /// Generate runtime audit attestations + Audit { + #[command(subcommand)] + audit_command: AuditCommands, + }, + + /// Manage configuration + #[command(long_about = "\ +Manage OpenPRX configuration. + +Inspect and export configuration settings. Use 'schema' to dump \ +the full JSON Schema for the config file, which documents every \ +available key, type, and default value. + +Examples: + prx config show # print effective config as TOML + prx config show --format json # print effective config as JSON + prx config schema # print JSON Schema to stdout + prx config schema > schema.json")] + Config { + #[command(subcommand)] + config_command: ConfigCommands, + }, + + #[cfg(feature = "test-mock")] + // Bash completion uses `__` as its path separator. Keep the contracted + // fixture spelling as a hidden alias, outside completion's command tree. + #[command(name = "mailbox-harness", alias = "__mailbox-harness", hide = true)] + MailboxHarness { + #[arg(value_parser=["accept-adopt"])] + action: String, + #[arg(long)] + workspace: std::path::PathBuf, + #[arg(long)] + worker: bool, + #[arg(long, default_value_t = 1)] + turns: usize, + }, + + /// Internal worker entrypoint for process-isolated sessions + SessionWorker { + /// Optional task override (normally provided in stdin manifest) + #[arg(long)] + task: Option, + /// Optional workspace override (normally provided in stdin manifest) + #[arg(long)] + workspace: Option, + /// Optional memory DB override (normally provided in stdin manifest) + #[arg(long)] + memory_db: Option, + /// Optional allowed tools JSON array override (normally provided in stdin manifest) + #[arg(long)] + tools: Option, + }, + + /// Generate shell completion script to stdout + #[command(long_about = "\ +Generate shell completion scripts for `prx`. + +The script is printed to stdout so it can be sourced directly: + +Examples: + source <(prx completions bash) + prx completions zsh > ~/.zfunc/_prx + prx completions fish > ~/.config/fish/completions/prx.fish")] + Completions { + /// Target shell + #[arg(value_enum)] + shell: CompletionShell, + }, +} + +#[derive(Subcommand, Debug)] +enum TasksCommands { + /// List work items the running process is currently holding + List { + /// Output machine-readable JSON + #[arg(long)] + json: bool, + /// Gateway base URL (default: the configured gateway bind address) + #[arg(long)] + url: Option, + /// Bearer token, when the gateway requires pairing + #[arg(long)] + token: Option, + }, + /// Terminate one work item by id + Kill { + /// Run id, work item id as printed by `prx tasks list` (`w42` or `42`), + /// or the batch id of a `spawn_batch` fan-out (ends the whole batch) + id: String, + /// Kill only this item, leaving the tools and processes it started + /// running. Cascading is the default because nothing else will clean + /// those up. + #[arg(long)] + no_cascade: bool, + /// Output machine-readable JSON + #[arg(long)] + json: bool, + /// Gateway base URL (default: the configured gateway bind address) + #[arg(long)] + url: Option, + /// Bearer token, when the gateway requires pairing + #[arg(long)] + token: Option, + }, + /// Send a message to a running task, redirecting it mid-flight + /// + /// Addresses a run started from any entry point — a channel message, the + /// chat TUI, another `prx` — because the work registry is process-wide. + /// Use the run id from `prx tasks list`; `w42` works too but means nothing + /// outside this machine. + Send { + /// Run id (portable) or work item id as printed by `prx tasks list` + id: String, + /// The instruction to hand to the running task + message: String, + /// Output machine-readable JSON + #[arg(long)] + json: bool, + /// Gateway base URL (default: the configured gateway bind address) + #[arg(long)] + url: Option, + /// Bearer token, when the gateway requires pairing + #[arg(long)] + token: Option, + }, + /// Show connection-pool occupancy and saturation counters + Pools { + /// Output machine-readable JSON + #[arg(long)] + json: bool, + /// Gateway base URL (default: the configured gateway bind address) + #[arg(long)] + url: Option, + /// Bearer token, when the gateway requires pairing + #[arg(long)] + token: Option, + }, +} + +#[derive(Subcommand, Debug)] +enum ConfigCommands { + /// Set the Brave Search credential from stdin without an argument or echo + BraveKey { + #[arg(long, required = true)] + from_stdin: bool, + #[command(flatten)] + apply: ApplyArgs, + }, + /// Print the effective merged configuration + Show { + /// Output format + #[arg(long, value_enum, default_value_t = ConfigShowFormat::Toml)] + format: ConfigShowFormat, + }, + /// Dump the full configuration JSON Schema to stdout + Schema, + /// Split config.toml into config.d/*.toml fragments + Split { + /// Preview the generated files without writing them + #[arg(long)] + dry_run: bool, + }, + /// Merge config.d/*.toml back into a single config.toml + Merge, + /// Show the plan of writing a configuration file; nothing is written + Plan { + /// The new content of the file + #[arg(long, value_name = "PATH")] + file: PathBuf, + /// Which configuration file it replaces (`config.toml` or a `config.d` fragment name) + #[arg(long, default_value = "config.toml")] + target: String, + /// Permit this raw replacement to omit or empty stored secret slots + #[arg(long)] + allow_credential_clear: bool, + }, + /// Write a configuration file through the configuration transaction + Apply { + /// The new content of the file + #[arg(long, value_name = "PATH")] + file: PathBuf, + /// Which configuration file it replaces (`config.toml` or a `config.d` fragment name) + #[arg(long, default_value = "config.toml")] + target: String, + /// Permit this raw replacement to omit or empty stored secret slots + #[arg(long)] + allow_credential_clear: bool, + #[command(flatten)] + apply: ApplyArgs, + }, + /// List, show or purge the recorded configuration changes + History { + #[command(subcommand)] + history_command: Option, + }, + /// Restore the configuration from before a recorded change + Rollback { + /// The history record to undo (see `prx config history`) + #[arg(required_unless_present = "last", conflicts_with = "last")] + id: Option, + /// Undo the most recent recorded change + #[arg(long)] + last: bool, + /// Apply the rollback (without it, only what it would do is shown) + #[arg(long)] + yes: bool, + /// Allow restoring a credential the current configuration no longer holds + #[arg(long)] + restore_credentials: bool, + /// Allow a rollback that turns `secrets.encrypt` off + #[arg(long)] + disable_encryption: bool, + }, + /// Show the configuration revision, the default model's status and pending changes + Status, + /// Manage the model bindings of delegate agents + Agents { + #[command(subcommand)] + agents_command: AgentsCommands, + }, +} + +/// How a mutating management command applies its plan. +#[derive(Args, Debug, Clone, Default)] +struct ApplyArgs { + /// Apply the plan (without it, the plan is shown and nothing is written) + #[arg(long)] + yes: bool, + /// Confirm a high-risk plan; names the revision the plan reported + #[arg(long, value_name = "REVISION", requires = "yes")] + confirm_high_risk: Option, +} + +/// Which operation a default or a route serves. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, ValueEnum)] +enum OperationArg { + #[default] + Chat, + Embedding, +} + +#[derive(Subcommand, Debug)] +enum HistoryCommands { + /// List the recorded changes, newest first + List, + /// Show one recorded change + Show { + /// The history record id + id: String, + }, + /// Remove every history record (after a leaked credential was rotated) + Purge { + /// Remove them (required) + #[arg(long)] + yes: bool, + }, +} + +#[derive(Subcommand, Debug)] +enum AgentsCommands { + /// Create a role with a system-managed identity directory + New { + agent: String, + #[arg(long)] + provider: String, + #[arg(long)] + model: String, + #[command(flatten)] + apply: ApplyArgs, + }, + /// List the delegate agents and their model bindings + List, + /// Bind an existing agent to a provider and model + Set { + /// The agent name (`[agents.]`) + agent: String, + /// The provider + provider: String, + /// The model + model: String, + #[command(flatten)] + apply: ApplyArgs, + }, +} + +#[derive(Subcommand, Debug)] +enum ProvidersCommands { + /// List the supported providers and the configured ones + List, + /// Show one provider: identity, roles, uses, declarations and credential status + Show { + /// The provider (`openai`, `custom:`, ...) + provider: String, + }, + /// Add a provider to the configured set in a role; today the only role is the failover chain + /// (`--fallback`, `reliability.fallback_providers`) + Add { + /// The provider (`anthropic`, `custom:`, ...) + provider: String, + /// Add it to the failover chain (`reliability.fallback_providers`); required, so a later + /// role cannot change what an existing script does + #[arg(long, required = true)] + fallback: bool, + /// Append a model fallback for the current default model (shared by the provider chain) + #[arg(long)] + model: Option, + #[command(flatten)] + apply: ApplyArgs, + }, + /// Change the endpoint of the default provider (`api_url`) + Update { + /// The default provider + provider: String, + /// The new endpoint URL + #[arg(long, conflicts_with = "clear_api_url", required_unless_present = "clear_api_url")] + api_url: Option, + /// Remove the endpoint override + #[arg(long)] + clear_api_url: bool, + #[command(flatten)] + apply: ApplyArgs, + }, + /// Remove a provider (refused while any selection still uses it) + Remove { + /// The provider + provider: String, + #[command(flatten)] + apply: ApplyArgs, + }, + /// Check that a provider and model resolve; `--live` also requests the model list once + Test { + /// The provider (default: the configured default provider) + provider: Option, + /// The model (default: the configured default model) + #[arg(long)] + model: Option, + /// Also send one model-list request to the provider (never a generation) + #[arg(long)] + live: bool, + }, + /// Manage the credential references of a provider + Credential { + #[command(subcommand)] + credential_command: CredentialCommands, + }, + /// Report legacy provider configuration (inline route, embedding-route and agent keys, the + /// `[[providers.tool_dialects]]` table, unverified selections, tokens stored under an alias). + /// With --apply, plan moving the inline keys into credential references and the dialect rows + /// into `[[providers.models]]`; --yes writes it through the configuration transaction + /// (`prx config rollback` undoes it) + Migrate { + /// Plan the migration instead of only reporting + #[arg(long)] + apply: bool, + #[command(flatten)] + write: ApplyArgs, + }, +} + +/// Management commands that only read: they load an existing configuration +/// read-only, so neither loading nor the legacy-secret upgrade writes +/// anything (D-101 F-5). +const fn read_only_management_command(command: &Commands) -> bool { + match command { + Commands::Providers { providers_command } => { + matches!( + providers_command, + None | Some( + ProvidersCommands::List + | ProvidersCommands::Show { .. } + | ProvidersCommands::Test { .. } + | ProvidersCommands::Credential { + credential_command: CredentialCommands::Status { .. }, + } + ) + ) || matches!( + providers_command, + Some(ProvidersCommands::Migrate { + write: ApplyArgs { yes: false, .. }, + .. + }) + ) + } + Commands::Config { config_command } => matches!( + config_command, + ConfigCommands::Status + | ConfigCommands::Show { .. } + | ConfigCommands::Schema + | ConfigCommands::Plan { .. } + | ConfigCommands::Agents { + agents_command: AgentsCommands::List, + } + | ConfigCommands::History { + history_command: None | Some(HistoryCommands::List | HistoryCommands::Show { .. }), + } + ), + Commands::Routes { routes_command } => matches!(routes_command, RoutesCommands::List { .. }), + Commands::Models { model_command } => { + matches!( + model_command, + None | Some(ModelCommands::List { .. } | ModelCommands::Show { .. }) + ) + } + _ => false, + } +} + +#[derive(Subcommand, Debug)] +enum CredentialCommands { + /// Store a credential reference for a provider; a model route, embedding route or agent of that + /// provider uses it when its `credential_ref` names it. Read from a hidden prompt, --from-stdin + /// or --from-env; never an argument + Set { + /// The provider the credential is issued for + provider: String, + /// The reference name (stored as `cred-`; default: the catalog provider's name) + #[arg(long)] + name: Option, + /// Read the credential from standard input + #[arg(long, conflicts_with = "from_env")] + from_stdin: bool, + /// Read the credential from this environment variable + #[arg(long, value_name = "VAR")] + from_env: Option, + }, + /// Remove a credential reference (refused while the configuration names it) + Remove { + /// The reference (`cred-` or ``) + reference: String, + }, + /// Show credential status (never a value): every reference, or one provider's credentials + Status { + /// The provider (default: every credential reference) + provider: Option, + }, +} + +#[derive(Subcommand, Debug)] +enum RoutesCommands { + /// List the routes + List { + /// Which route table + #[arg(long, value_enum, default_value_t = OperationArg::Chat)] + operation: OperationArg, + }, + /// Add a route + Add { + /// The route hint (`hint:` selects it) + hint: String, + /// The provider + provider: String, + /// The model + model: String, + /// Which route table + #[arg(long, value_enum, default_value_t = OperationArg::Chat)] + operation: OperationArg, + #[command(flatten)] + apply: ApplyArgs, + }, + /// Change a route's provider or model + Update { + /// The route hint + hint: String, + /// The new provider + #[arg(long)] + provider: Option, + /// The new model + #[arg(long)] + model: Option, + /// Which route table + #[arg(long, value_enum, default_value_t = OperationArg::Chat)] + operation: OperationArg, + #[command(flatten)] + apply: ApplyArgs, + }, + /// Remove a route (refused while a selection names it) + Remove { + /// The route hint + hint: String, + /// Which route table + #[arg(long, value_enum, default_value_t = OperationArg::Chat)] + operation: OperationArg, + #[command(flatten)] + apply: ApplyArgs, + }, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)] +enum ConfigShowFormat { + Toml, + Json, +} + +#[derive(Subcommand, Debug)] +enum AuthCommands { + /// Login with a subscription OAuth provider (`openai-codex` or `xai`) + Login { + /// Provider (`openai-codex` or `xai`) + #[arg(long)] + provider: String, + /// Profile name (default: default) + #[arg(long, default_value = "default")] + profile: String, + /// Use OAuth device-code flow + #[arg(long)] + device_code: bool, + }, + /// Complete OAuth by pasting redirect URL or auth code (`openai-codex` or `xai`) + PasteRedirect { + /// Provider (`openai-codex` or `xai`) + #[arg(long)] + provider: String, + /// Profile name (default: default) + #[arg(long, default_value = "default")] + profile: String, + /// Full redirect URL or raw OAuth code + #[arg(long)] + input: Option, + }, + /// Paste setup token / auth token (for Anthropic subscription auth) + PasteToken { + /// Provider (`anthropic`) + #[arg(long)] + provider: String, + /// Profile name (default: default) + #[arg(long, default_value = "default")] + profile: String, + /// Token value (if omitted, read interactively). Deprecated: an argument is + /// visible in the process list; use --from-stdin or the prompt + #[arg(long)] + token: Option, + /// Read the token from standard input + #[arg(long, conflicts_with = "token")] + from_stdin: bool, + /// Auth kind override (`authorization` or `api-key`) + #[arg(long)] + auth_kind: Option, + }, + /// Alias for `paste-token` (interactive by default) + SetupToken { + /// Provider (`anthropic`) + #[arg(long)] + provider: String, + /// Profile name (default: default) + #[arg(long, default_value = "default")] + profile: String, + }, + /// Refresh a subscription access token (`openai-codex` or `xai`) + Refresh { + /// Provider (`openai-codex` or `xai`) + #[arg(long)] + provider: String, + /// Profile name or profile id + #[arg(long)] + profile: Option, + }, + /// Remove auth profile + Logout { + /// Provider + #[arg(long)] + provider: String, + /// Profile name (default: default) + #[arg(long, default_value = "default")] + profile: String, + }, + /// Set active profile for a provider + Use { + /// Provider + #[arg(long)] + provider: String, + /// Profile name or full profile id + #[arg(long)] + profile: String, + }, + /// List auth profiles + List, + /// Show auth status with active profile and token expiry info + Status, +} + +#[derive(Subcommand, Debug)] +enum ModelCommands { + /// Inspect the embedded release catalog + Catalog { + #[command(subcommand)] + catalog_command: CatalogCommands, + }, + /// Plan published model replacements; --yes applies one PMM transaction + MigrateRetired { + #[command(flatten)] + apply: ApplyArgs, + }, + /// Show declared model levels and parameters from the release catalog + Levels { model: String }, + /// Show or update persisted model settings through a configuration transaction + Settings { + model: String, + #[arg(long, value_parser = ["low", "medium", "high"])] + level: Option, + /// Explicit override, repeated as --set name=JSON-value + #[arg(long = "set")] + overrides: Vec, + #[command(flatten)] + apply: ApplyArgs, + }, + /// List model catalogs; with --operation or --executable, every known model with what the + /// evidence says it can do + List { + /// Provider name (defaults to configured default provider) + #[arg(long)] + provider: Option, + /// Only models the evidence does not rule out for this operation (`chat`, `embedding`, ...) + #[arg(long)] + operation: Option, + /// Only models the evidence proves can execute the operation (chat when none is named) + #[arg(long)] + executable: bool, + }, + /// Show what the evidence says one model can do + Show { + /// The provider + provider: String, + /// The model + model: String, + }, + /// Refresh and cache provider models + Refresh { + /// Provider name (defaults to configured default provider) + #[arg(long)] + provider: Option, + + /// Force live refresh and ignore fresh cache + #[arg(long)] + force: bool, + }, + /// Declare what a model can do (`[[providers.models]]`) + Add(ModelDeclarationArgs), + /// Change a model declaration (only the facts given are replaced) + Update(ModelDeclarationArgs), + /// Remove a model declaration + Remove { + /// The provider + #[arg(long)] + provider: String, + /// The model (omit for the provider-wide declaration) + #[arg(long)] + model: Option, + #[command(flatten)] + apply: ApplyArgs, + }, + /// Show or set the default model of an operation + Default { + #[command(subcommand)] + default_command: DefaultCommands, + }, +} + +#[derive(Subcommand, Debug)] +enum CatalogCommands { + /// Show the embedded revision, content digest and lifecycle counts + Status, +} + +/// A `[[providers.models]]` declaration on the command line. +#[derive(Args, Debug)] +struct ModelDeclarationArgs { + /// The provider + #[arg(long)] + provider: String, + /// The model (omit to declare every model of the provider) + #[arg(long)] + model: Option, + /// The complete list of operations the model executes (comma-separated) + #[arg(long, value_delimiter = ',', value_parser = parse_setting::)] + operations: Option>, + /// Whether the model accepts native tool calls + #[arg(long)] + native_tools: Option, + /// Whether the model accepts image input + #[arg(long)] + vision_input: Option, + /// Whether the model streams responses + #[arg(long)] + streaming: Option, + /// Whether the model honours a JSON-schema response format + #[arg(long)] + structured_output: Option, + /// The tool-schema dialect the endpoint accepts (`raw`, `no_root_combinators`) + #[arg(long, value_parser = parse_setting::)] + tool_schema_dialect: Option, + /// The tool-call grammar the endpoint emits (`native`, `xml_function_tags`) + #[arg(long, value_parser = parse_setting::)] + tool_call_dialect: Option, + /// The context window in tokens + #[arg(long)] + context_window: Option, + #[command(flatten)] + apply: ApplyArgs, +} + +#[derive(Subcommand, Debug)] +enum DefaultCommands { + /// Show the default chat and embedding models and how they resolve + Show, + /// Set the default model of an operation + Set { + /// The provider + provider: String, + /// The model + model: String, + #[arg(long, value_parser = ["low", "medium", "high"])] + level: Option, + /// Explicit model parameter override, repeated as --set name=JSON-value + #[arg(long = "set")] + overrides: Vec, + /// Which default + #[arg(long, value_enum, default_value_t = OperationArg::Chat)] + operation: OperationArg, + /// The root connection (`api_key`, `api_url`, `reliability.api_keys`) belongs to the new + /// default provider (a high-risk change: the key is sent to it); chat only + #[arg(long, conflicts_with = "clear_root_credential")] + keep_root_credential: bool, + /// Clear the root connection (`api_key`, `api_url`, `reliability.api_keys`) with the switch; + /// chat only + #[arg(long)] + clear_root_credential: bool, + #[command(flatten)] + apply: ApplyArgs, + }, +} + +/// Parse a snake_case configuration setting (`no_root_combinators`) the way +/// the configuration file spells it. +fn parse_setting(text: &str) -> std::result::Result { + serde_json::from_value(serde_json::Value::String(text.trim().to_ascii_lowercase())) + .map_err(|_| format!("'{}' is not one of the accepted values", text.escape_default())) +} + +#[derive(Subcommand, Debug)] +enum DoctorCommands { + /// Probe model catalogs across providers and report availability + Models { + /// Probe a specific provider only (default: all known providers) + #[arg(long)] + provider: Option, + + /// Prefer cached catalogs when available (skip forced live refresh) + #[arg(long)] + use_cache: bool, + }, + /// Diagnose memory backend and embedding/vector configuration + Memory, + /// Report live runtime validation matrix readiness + Runtime, + /// List durable ingress rows that are not reconciled (read-only) + Ingress, +} + +/// Process-wide bound on how long the runtime drop will wait for stuck +/// blocking threads (notably the reedline `read_line` task that parks in +/// `spawn_blocking` reading from stdin). +/// +/// Without this bound, `#[tokio::main]`'s default runtime drop would +/// `join()` blocking threads forever; reedline's blocking stdin read does +/// not observe `CancellationToken`s, so e.g. the double-Ctrl-C exit path +/// (`shutdown.cancel()` → `chat::run` returns) would hang the process +/// until the user manually killed it. Capping the wait at 2 seconds gives +/// well-behaved shutdowns time to finish while preventing the foot-gun. +const RUNTIME_SHUTDOWN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2); + +/// Resolve the blocking-pool cap before the runtime exists. +/// +/// The pool size is fixed at `Builder` time, so it cannot come from the normal +/// config load (which is async and needs a runtime). We therefore do a +/// synchronous, read-only pre-read of `[runtime] max_blocking_threads`, falling +/// back to a cgroup-aware hardware-derived default. +/// +fn resolve_max_blocking_threads(cli: &Cli) -> usize { + openprx::config::bootstrap_max_blocking_threads(cli.config_dir.as_deref()) + .unwrap_or_else(openprx::runtime::blocking::default_max_blocking_threads) +} + +#[allow(unsafe_code)] +fn main() -> std::process::ExitCode { + // Build the runtime explicitly (instead of using `#[tokio::main]`) so + // that we can bound how long runtime drop waits for blocking threads. + // See `RUNTIME_SHUTDOWN_TIMEOUT` above for the rationale. + // + // The blocking pool is sized explicitly too. Tokio's default is a + // hardware-agnostic 512 threads, which is the process's last implicit + // concurrency gate now that turns, sub-agents and sessions are unbounded — + // and it fails by deadlock, not rejection: once every slot is held, further + // `spawn_blocking` calls queue forever with no timeout. + let cli = Cli::parse(); + let max_blocking_threads = resolve_max_blocking_threads(&cli); + let runtime = match tokio::runtime::Builder::new_multi_thread() + .enable_all() + .max_blocking_threads(max_blocking_threads) + .build() + .context("failed to build tokio runtime") + { + Ok(runtime) => runtime, + Err(err) => { + eprintln!("Error: {}", openprx::security::redaction::redacted_error_report(&err)); + return std::process::ExitCode::FAILURE; + } + }; + // Publish the real cap so blocking-pool saturation is measured against it. + openprx::runtime::blocking::configure(max_blocking_threads); + let result = runtime.block_on(async { + let result = Box::pin(async_main(cli)).await; + // Every exit path (REPL /exit, one-shot end, Ctrl-C/SIGTERM through the + // shutdown token, daemon shutdown, a process worker's own return) lands + // here: stop and reap the process-mode children this process owns, + // within the same bound, before the runtime drops their monitors. + openprx::tools::sessions_spawn::stop_owned_process_runs(RUNTIME_SHUTDOWN_TIMEOUT).await; + result + }); + runtime.shutdown_timeout(RUNTIME_SHUTDOWN_TIMEOUT); + match result { + Ok(()) => std::process::ExitCode::SUCCESS, + Err(err) => { + // A refused `prx chat --message` turn already printed its reply. + let code = openprx::chat::one_shot_exit_code(Some(&err)); + if code == openprx::chat::ONE_SHOT_REFUSAL_EXIT_CODE { + return std::process::ExitCode::from(code); + } + eprintln!("Error: {}", openprx::security::redaction::redacted_error_report(&err)); + std::process::ExitCode::FAILURE + } + } +} diff --git a/src/main/section_2.rs b/src/main/section_2.rs new file mode 100644 index 000000000..0b956f0ed --- /dev/null +++ b/src/main/section_2.rs @@ -0,0 +1,1683 @@ +#[allow(clippy::too_many_lines)] +#[allow(unsafe_code)] +async fn async_main(cli: Cli) -> Result<()> { + // Install default crypto provider for Rustls TLS. + // This prevents the error: "could not automatically determine the process-level CryptoProvider" + // when both aws-lc-rs and ring features are available (or neither is explicitly selected). + if let Err(e) = rustls::crypto::ring::default_provider().install_default() { + eprintln!("Warning: Failed to install default crypto provider: {e:?}"); + } + + if let Some(warning) = argv_secret_warning(&cli.command) { + eprintln!("{warning}"); + } + + if let Some(config_dir) = &cli.config_dir { + if config_dir.trim().is_empty() { + bail!("--config-dir cannot be empty"); + } + // Publish the explicit directory before anything can lazily create + // process-global state (witness key, session-worker secret) that has no + // `Config` in hand and would otherwise anchor on `$HOME/.openprx`. + config::set_process_config_dir(std::path::absolute(config_dir.trim()).context("resolve --config-dir")?); + } + + #[cfg(feature = "test-mock")] + if let Commands::MailboxHarness { + workspace, + worker, + turns, + .. + } = &cli.command + { + if *worker { + return session_worker::mailbox_harness::run(workspace, *turns).await; + } + return memory::sqlite::mailbox::harness::accept_adopt(workspace); + } + + // session-worker must stay stdout-clean for IPC JSON. + if let Commands::SessionWorker { + task, + workspace, + memory_db, + tools, + } = &cli.command + { + return session_worker::runner::run_from_stdin( + task.clone(), + workspace.clone(), + memory_db.clone(), + tools.clone(), + cli.config_dir.clone(), + ) + .await; + } + + // Completions must remain stdout-only and should not load config or initialize logging. + // This avoids warnings/log lines corrupting sourced completion scripts. + if let Commands::Completions { shell } = &cli.command { + let mut stdout = std::io::stdout().lock(); + write_shell_completion(*shell, &mut stdout)?; + return Ok(()); + } + + if let Commands::Token { + command: TokenCommands::Issue { out, force }, + } = &cli.command + { + let config = Config::load_or_init_with_config_dir(cli.config_dir.as_deref()).await?; + let owner = runtime::host_bootstrap::issue_token(config, out, *force).await?; + println!("{}\n{}", out.display(), owner); + return Ok(()); + } + if matches!(&cli.command, Commands::Init { .. }) { + return init_cli::run(&cli).await; + } + + // Initialize logging. RUST_LOG always wins when set. Otherwise foreground + // commands (chat, go, ...) default to warn on stderr so a scripted + // `prx chat --message 'What is 2+2?'` prints only the reply on stdout. Long-running + // services (daemon, gateway, channel start) keep info on the process + // default writer. Chat still uses a reloadable stderr subscriber so + // tracing can move to chat.log before configuration is loaded. + let tracing_defaults = cli_tracing_command(&cli.command).defaults(); + let env_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(tracing_defaults.filter)); + if tracing_defaults.write_stderr { + use tracing_subscriber::layer::SubscriberExt as _; + use tracing_subscriber::util::SubscriberInitExt as _; + + let stderr_writer = tracing_subscriber::fmt::writer::BoxMakeWriter::new(std::io::stderr); + let fmt_layer: ChatFmtLayer = tracing_subscriber::fmt::Layer::default().with_writer(stderr_writer); + let (reload_layer, reload_handle) = tracing_subscriber::reload::Layer::new(fmt_layer); + if CHAT_TRACING_RELOAD.set(reload_handle).is_err() { + eprintln!("BUG: CHAT_TRACING_RELOAD already initialized"); + } + if let Err(e) = tracing_subscriber::registry() + .with(env_filter) + .with(reload_layer) + .try_init() + { + eprintln!("failed to set default tracing subscriber: {e}"); + } + } else { + let subscriber = fmt::Subscriber::builder().with_env_filter(env_filter).finish(); + if let Err(e) = tracing::subscriber::set_global_default(subscriber) { + eprintln!("failed to set default tracing subscriber: {e}"); + } + } + + // Acquire this before Config::load_* and hold it through command dispatch. + // Fatal startup errors are still returned through anyhow and printed by + // main after this guard restores stderr; routine tracing stays in chat.log. + // `prx chat --message` keeps warn-level tracing on stderr instead. + let _chat_tracing_guard = if matches!(&cli.command, Commands::Chat { message: None, .. }) { + match chat::setup_chat_tracing_to_file() { + Ok(guard) => Some(guard), + Err(error) => { + tracing::warn!(%error, "keeping chat tracing on stderr because chat.log is unavailable"); + None + } + } + } else { + None + }; + + // `prx go` — zero-config instant start. No permanent files written. + if let Commands::Go { + api_key, + from_env, + from_stdin, + provider, + model, + message, + } = &cli.command + { + let api_key = manage_cli::secret_from( + *from_stdin, + from_env.as_deref(), + &mut std::io::stdin(), + &|name: &str| std::env::var(name).ok(), + )? + .or_else(|| api_key.clone()); + let (detected_provider, detected_key, detected_model) = + auth::discovery::detect_credentials(api_key.as_deref(), provider.as_deref(), model.as_deref()).context( + "No API key found. Run `prx auth paste-token --provider anthropic`, or use: prx go -k ", + )?; + + let tmpdir = tempfile::tempdir().context("failed to create temporary workspace for `prx go`")?; + + let mut config = Config::default(); + config.default_provider = Some(detected_provider); + config.default_model = Some(detected_model); + config.api_key = Some(detected_key); + config.workspace_dir = tmpdir.path().to_path_buf(); + config.config_path = tmpdir.path().join("config.toml"); + // `prx go` persists nothing, so the detected model is an invocation, + // resolved once where each path builds its provider: the agent entry + // for `--message`, chat start-up otherwise. An id-only model runs + // with a warning; one that cannot chat is refused before any + // provider exists. + + if let Some(msg) = message { + // `prx go --message` is the chat one-shot (`prx chat --message`): + // chat owns ctrl_c internally, so the token is never cancelled. + let result = chat::run_message( + config, + None, // provider already set in config + None, // model already set in config + 0.7, + chat::ChatMessageRequest { + message: msg.clone(), + save: false, + session: None, + }, + crate::runtime::shutdown::never_cancelled_shutdown(), + ) + .await; + // Keep tmpdir alive until the turn finishes, then drop + drop(tmpdir); + return result; + } + + // Non-dispatch direct call (`prx go` interactive chat): chat owns ctrl_c + // internally; no dispatch-level signal source. Use the explicitly-named + // never-cancelled token so chat's internal handler stays the sole owner. + let result = chat::run( + config, + None, // provider already set in config + None, // model already set in config + 0.7, + false, // plain mode off + None, // no session resume + false, // don't list sessions + crate::runtime::shutdown::never_cancelled_shutdown(), + ) + .await; + // Keep tmpdir alive until chat finishes, then drop + drop(tmpdir); + return result; + } + + // Diagnostic/schema inspection must not initialize config/workspace state. + // Baseline is routed through the same read-only loader because it is + // retained only as an explicit compatibility error, never as a write. + let read_only_config_command = matches!( + &cli.command, + Commands::Migrate { + migrate_command: MigrateCommands::Status + | MigrateCommands::Verify + | MigrateCommands::DryRun + | MigrateCommands::Plan { .. } + | MigrateCommands::Baseline + } + ) || matches!( + &cli.command, + Commands::Doctor { .. } + | Commands::Tasks { .. } + | Commands::Causal { .. } + | Commands::DecisionEngine { + command: openprx::decision_engine_cli::DecisionEngineCommands::Status + | openprx::decision_engine_cli::DecisionEngineCommands::Analyses { .. } + | openprx::decision_engine_cli::DecisionEngineCommands::Backends, + .. + } + | Commands::Cost { .. } + ); + #[cfg(feature = "wasm-plugins")] + let read_only_config_command = read_only_config_command || matches!(&cli.command, Commands::Plugin { .. }); + let mut config = if read_only_config_command { + Config::load_existing_read_only_with_config_dir(cli.config_dir.as_deref()).await? + } else if read_only_management_command(&cli.command) { + // Without a configuration yet: the defaults, shown, nothing written + // (D-101 F-5). + let config = Config::load_existing_or_defaults_read_only(cli.config_dir.as_deref()).await?; + if !config.config_path.exists() { + eprintln!( + "no config yet; showing defaults (nothing is written; {} is created by the first command that \ + changes the configuration)", + config.config_path.display() + ); + } + config + } else { + Config::load_or_init_with_config_dir(cli.config_dir.as_deref()).await? + }; + + if let Commands::Chat { + workdir: Some(root), .. + } = &cli.command + { + config.runtime.workdir = Some(root.clone()); + config.validate()?; + } + + // Covers the resolutions the flag does not carry (`OPENPRX_CONFIG_DIR`, + // `OPENPRX_WORKSPACE`, the active-workspace marker). No-op when the flag + // already published the same directory. + if let Some(resolved_config_dir) = config.config_path.parent() { + config::set_process_config_dir(resolved_config_dir.to_path_buf()); + } + + // `dispatch` logs the inherited-embedding-default notice for every + // long-running runtime, but chat's tracing has already been redirected into + // chat.log by this point, so for the one interactive entry point the + // warning went somewhere nobody looks. The process stderr is untouched by + // that redirect and the TUI has not taken the screen yet. + if matches!(&cli.command, Commands::Chat { message: None, .. }) { + chat::print_embedding_upgrade_notice_to_stderr(&config); + } + + mode::dispatch(cli.command, config).await +} + +/// The deprecation warning for a secret given as a command-line argument +/// (D-018 Q3, SP-PMM E-4). The flag keeps working; the warning names the +/// alternative that keeps the secret out of the process list and the shell +/// history. Never contains the secret. +fn argv_secret_warning(command: &Commands) -> Option { + let (flag, alternative) = match command { + Commands::Init { api_key: Some(_), .. } => ( + "--api-key", + "--from-stdin (pipe the key in: `printf %s \"$KEY\" | prx init --from-stdin`) or --from-env VAR", + ), + Commands::Go { api_key: Some(_), .. } => ("-k/--key", "--from-stdin or --from-env VAR"), + Commands::Auth { + auth_command: AuthCommands::PasteToken { token: Some(_), .. }, + } => ( + "--token", + "--from-stdin (pipe the token in), or leave the flag out to be prompted without echo", + ), + _ => return None, + }; + Some(format!( + "warning: a secret passed with {flag} is visible to other local users in the process list and stays in \ + your shell history; the flag is deprecated. Use {alternative} instead." + )) +} + +/// `prx tasks` — talks to a running process's gateway rather than inspecting +/// this one, because the work registry is per-process state. +async fn handle_tasks_command(command: TasksCommands, config: &Config) -> anyhow::Result<()> { + use openprx::runtime::tasks_cli::{self, TasksEndpoint}; + + match command { + TasksCommands::List { json, url, token } => { + let endpoint = TasksEndpoint::resolve(config, url, token); + let listing = tasks_cli::fetch_tasks(&endpoint).await?; + if json { + println!("{}", serde_json::to_string_pretty(&listing)?); + return Ok(()); + } + if listing.running.is_empty() { + println!("No work items are currently running."); + } else { + println!("Running work items ({}):", listing.running.len()); + print_work_items(&listing.running); + } + if !listing.unreaped.is_empty() { + println!(); + println!( + "Spawned but not reaped ({}) — children that outlived their owner:", + listing.unreaped.len() + ); + print_work_items(&listing.unreaped); + } + } + TasksCommands::Kill { + id, + no_cascade, + json, + url, + token, + } => { + let endpoint = TasksEndpoint::resolve(config, url, token); + let report = tasks_cli::request_kill(&endpoint, &id, !no_cascade).await?; + if json { + println!("{}", serde_json::to_string_pretty(&report)?); + } else { + println!( + "Killed {} (cascade: {}) — {} target(s):", + report.requested, + if report.cascade { "on" } else { "off" }, + report.targets.len() + ); + for target in &report.targets { + println!( + " {:<8} {:<10} {:<14} {}", + target.id, target.kind, target.outcome, target.name + ); + } + if report.targets.iter().any(|target| target.outcome == "requested") { + println!(); + println!( + "Some targets had not gone away yet when this report was produced. Nothing \ + was abandoned — re-run `prx tasks list` to see the current state." + ); + } + } + // A target with no termination handle is a partial result, not a success. + if report.targets.iter().any(|target| target.outcome == "not_killable") { + bail!("one or more targets had no termination handle and could not be killed"); + } + } + TasksCommands::Send { + id, + message, + json, + url, + token, + } => { + let endpoint = TasksEndpoint::resolve(config, url, token); + let report = tasks_cli::request_message(&endpoint, &id, &message).await?; + if json { + println!("{}", serde_json::to_string_pretty(&report)?); + } else { + println!("{}", render_task_message(&report)); + } + } + TasksCommands::Pools { json, url, token } => { + let endpoint = TasksEndpoint::resolve(config, url, token); + let report = tasks_cli::fetch_pools(&endpoint).await?; + if json { + println!("{}", serde_json::to_string_pretty(&report)?); + return Ok(()); + } + for pool in &report.pools { + println!("[{}] {}", pool.kind, pool.name); + if let Some(metrics) = pool.metrics.as_object() { + let mut keys: Vec<&String> = metrics.keys().collect(); + keys.sort(); + for key in keys { + if let Some(value) = metrics.get(key) { + println!(" {key:<32} {value}"); + } + } + } + println!(); + } + } + } + Ok(()) +} + +/// Render one work-item table, shared by the running and unreaped sections. +/// +/// Members of one `spawn_batch` fan-out are pulled together under a header at +/// the position of the batch's first member: they are siblings rather than a +/// lineage, so nothing else in the table says they belong to one another. A +/// listing with no batches renders exactly as it always did. +/// Render `prx tasks send` for a human, saying only what the server said. +/// +/// The server reports `outcome: "queued"` because accepting a message onto a +/// run's bounded steering queue is the whole of what it can observe: an mpsc +/// send proves the queue had room and the receiver still exists, never that +/// anybody polls it. A task-mode sub-agent with no tools registers a steering +/// sender and never reads the receiver, so its messages are accepted and +/// consumed by nobody. +/// +/// This renderer therefore prints the server's tag verbatim, labelled as the +/// outcome, and appends the server's own note when it sent one. It states no +/// delivery of its own: the previous "Delivered to ..." headline was a claim +/// the CLI was in no position to make, and an operator who read it went on +/// waiting for a target that was never going to act. +/// +/// MUTATION GUARD: reinstate a fixed "Delivered" headline and +/// `a_sent_message_is_reported_as_the_server_tagged_it` fails. +fn render_task_message(report: &openprx::runtime::tasks_cli::MessageReport) -> String { + let run_id = report.run_id.as_deref().unwrap_or("-"); + let mut out = format!( + "Message to {} [{}] {} (run_id: {}) — outcome: {}", + report.id, report.kind, report.name, run_id, report.outcome + ); + // Absent on a gateway older than the `queued` outcome. Nothing is + // substituted for it: a note this CLI wrote would be a client-side guess at + // a server-side guarantee. + if let Some(note) = report.note.as_deref() { + out.push('\n'); + out.push_str(note); + } + out +} + +fn print_work_items(items: &[openprx::runtime::tasks_cli::WorkItem]) { + println!( + "{:<8} {:<10} {:>10} {:<14} {:<}", + "ID", "KIND", "ELAPSED", "STATE", "NAME" + ); + for (batch_id, members) in openprx::runtime::tasks_cli::group_by_batch(items) { + if let Some(batch_id) = batch_id { + println!(" batch {batch_id} — {} member(s):", members.len()); + } + for item in members { + print_work_item(item, batch_id.is_some()); + } + } +} + +/// Render one row. `indented` marks a row as belonging to the batch header +/// above it. +fn print_work_item(item: &openprx::runtime::tasks_cli::WorkItem, indented: bool) { + println!("{}", work_item_line(item, indented)); +} + +/// The text of one listing row, split out from the printing so what an operator +/// reads can be asserted rather than eyeballed. +fn work_item_line(item: &openprx::runtime::tasks_cli::WorkItem, indented: bool) -> String { + let mut name = item.name.clone(); + if let Some(parent) = &item.parent { + name.push_str(&format!(" (parent {parent})")); + } + if let Some(run_id) = &item.run_id { + name.push_str(&format!(" (run {run_id})")); + } + // Marked, not columned: only a minority of rows can take a message, and a + // column would spend width on the ones that cannot. The mark exists because + // the KIND column reads like an answer and is not one — a detached gateway + // job is listed `sub_agent` and has no steering channel — so without it the + // only way to learn an item is unsteerable is to send it a message and read + // the refusal. + // + // MUTATION GUARD: drop this and `a_steerable_row_is_marked_and_a_look_alike_is_not` fails. + if item.steerable { + name.push_str(" (steerable)"); + } + if let Some(pid) = item.pid { + name.push_str(&format!(" (pid {pid}")); + match item.pgid { + Some(pgid) => name.push_str(&format!(", pgid {pgid})")), + None => name.push(')'), + } + } + let id = if indented { + format!(" {}", item.id) + } else { + item.id.clone() + }; + format!( + "{:<8} {:<10} {:>10} {:<14} {name}", + id, + item.kind, + openprx::runtime::tasks_cli::format_elapsed(item.elapsed_secs), + item.state + ) +} + +async fn handle_memory_command(command: MemoryCommands, config: &Config) -> anyhow::Result<()> { + match command { + MemoryCommands::Reindex { json } => { + let memory = memory::create_memory_with_storage_and_routes_with_acl( + &config.memory, + &config.embedding_routes_with_references(), + Some(&config.storage.provider.config), + &config.workspace_dir, + memory::EmbeddingRootCredential::from_config(&config), + &config.identity_bindings, + &config.user_policies, + )?; + let backend = memory.name().to_string(); + let repaired = memory.reindex().await?; + if json { + println!( + "{}", + serde_json::json!({ + "backend": backend, + "reindexed": repaired, + }) + ); + } else { + println!("Memory reindex complete for {backend}: {repaired} stale vectors rebuilt"); + } + Ok(()) + } + } +} + +fn write_shell_completion(shell: CompletionShell, writer: &mut W) -> Result<()> { + use clap_complete::generate; + use clap_complete::shells; + + let mut cmd = Cli::command(); + let bin_name = cmd.get_name().to_string(); + + match shell { + CompletionShell::Bash => generate(shells::Bash, &mut cmd, bin_name, writer), + CompletionShell::Fish => generate(shells::Fish, &mut cmd, bin_name, writer), + CompletionShell::Zsh => generate(shells::Zsh, &mut cmd, bin_name, writer), + CompletionShell::PowerShell => { + generate(shells::PowerShell, &mut cmd, bin_name, writer); + } + CompletionShell::Elvish => generate(shells::Elvish, &mut cmd, bin_name, writer), + } + + writer.flush()?; + Ok(()) +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct PendingOpenAiLogin { + profile: String, + code_verifier: String, + state: String, + created_at: String, + host_id: String, + client_id: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct PendingOpenAiLoginFile { + profile: String, + #[serde(skip_serializing_if = "Option::is_none")] + code_verifier: Option, + #[serde(skip_serializing_if = "Option::is_none")] + encrypted_code_verifier: Option, + state: String, + created_at: String, + #[serde(default)] + host_id: String, + #[serde(default)] + client_id: String, +} + +fn pending_openai_login_path(config: &Config) -> std::path::PathBuf { + auth::state_dir_from_config(config).join("auth-openai-pending.json") +} + +fn pending_openai_secret_store(config: &Config) -> security::secrets::SecretStore { + security::secrets::SecretStore::new(&auth::state_dir_from_config(config), config.secrets.encrypt) +} + +#[cfg(unix)] +fn set_owner_only_permissions(path: &std::path::Path) -> Result<()> { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?; + Ok(()) +} + +#[cfg(not(unix))] +fn set_owner_only_permissions(_path: &std::path::Path) -> Result<()> { + Ok(()) +} + +fn save_pending_openai_login(config: &Config, pending: &PendingOpenAiLogin) -> Result<()> { + let path = pending_openai_login_path(config); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + let secret_store = pending_openai_secret_store(config); + let encrypted_code_verifier = secret_store.encrypt(&pending.code_verifier)?; + let persisted = PendingOpenAiLoginFile { + profile: pending.profile.clone(), + code_verifier: None, + encrypted_code_verifier: Some(encrypted_code_verifier), + state: pending.state.clone(), + created_at: pending.created_at.clone(), + host_id: pending.host_id.clone(), + client_id: pending.client_id.clone(), + }; + let tmp = path.with_extension(format!( + "tmp.{}.{}", + std::process::id(), + chrono::Utc::now().timestamp_nanos_opt().unwrap_or_default() + )); + let json = serde_json::to_vec_pretty(&persisted)?; + std::fs::write(&tmp, json)?; + set_owner_only_permissions(&tmp)?; + std::fs::rename(tmp, &path)?; + set_owner_only_permissions(&path)?; + Ok(()) +} + +fn load_pending_openai_login(config: &Config) -> Result> { + let path = pending_openai_login_path(config); + if !path.exists() { + return Ok(None); + } + let bytes = std::fs::read(path)?; + if bytes.is_empty() { + return Ok(None); + } + let persisted: PendingOpenAiLoginFile = serde_json::from_slice(&bytes)?; + let secret_store = pending_openai_secret_store(config); + let code_verifier = if let Some(encrypted) = persisted.encrypted_code_verifier { + secret_store.decrypt(&encrypted)? + } else if let Some(plaintext) = persisted.code_verifier { + plaintext + } else { + bail!("Pending OpenAI login is missing code verifier"); + }; + Ok(Some(PendingOpenAiLogin { + profile: persisted.profile, + code_verifier, + state: persisted.state, + created_at: persisted.created_at, + host_id: persisted.host_id, + client_id: persisted.client_id, + })) +} + +fn clear_pending_openai_login(config: &Config) { + let path = pending_openai_login_path(config); + if let Ok(file) = std::fs::OpenOptions::new().write(true).open(&path) { + let _ = file.set_len(0); + let _ = file.sync_all(); + } + let _ = std::fs::remove_file(path); +} + +fn read_auth_input(prompt: &str) -> Result { + let input = Password::new() + .with_prompt(prompt) + .allow_empty_password(false) + .interact()?; + Ok(input.trim().to_string()) +} + +fn read_plain_input(prompt: &str) -> Result { + let input: String = Input::new().with_prompt(prompt).interact_text()?; + Ok(input.trim().to_string()) +} + +fn extract_openai_account_id_for_profile(access_token: &str, id_token: Option<&str>) -> Option { + let account_id = auth::openai_oauth::extract_account_id(access_token, id_token); + if account_id.is_none() { + warn!( + "Could not extract OpenAI account id from OAuth access token; \ + requests may fail until re-authentication." + ); + } + account_id +} + +fn format_expiry(profile: &auth::profiles::AuthProfile) -> String { + profile + .token_set + .as_ref() + .and_then(|token_set| token_set.expires_at) + .map_or_else( + || "n/a".to_string(), + |ts| { + let now = chrono::Utc::now(); + if ts <= now { + format!("expired at {}", ts.to_rfc3339()) + } else { + let mins = (ts - now).num_minutes(); + format!("expires in {mins}m ({})", ts.to_rfc3339()) + } + }, + ) +} + +fn attestation_check( + observed_at: &str, + id: &'static str, + framework_reference: &'static str, + control: &'static str, + status: ControlStatus, + evidence_kind: &'static str, + evidence_reference: impl Into, + explanation: impl Into, + remediation: impl Into, +) -> EuAiActCheck { + EuAiActCheck { + id, + framework_reference, + control, + applicability: "operator classification required", + severity: if matches!(status, ControlStatus::Fail) { + "release_blocking" + } else { + "advisory" + }, + status, + observed_at: observed_at.to_string(), + evidence: vec![EvidenceReference { + kind: evidence_kind, + reference: evidence_reference.into(), + }], + explanation: explanation.into(), + remediation: remediation.into(), + } +} + +fn config_source_revision(config: &Config) -> Option { + use sha2::{Digest, Sha256}; + let bytes = fs::read(&config.config_path).ok()?; + Some(format!("sha256:{:x}", Sha256::digest(bytes))) +} + +fn config_generation(config: &Config) -> Option { + let generation_path = config.config_path.parent()?.join(".config-generation"); + fs::read_to_string(generation_path).ok()?.trim().parse().ok() +} + +fn declaration_artifact_path(config: &Config) -> Option { + config + .compliance + .eu_ai_act + .declaration + .artifact_path + .as_ref() + .map(|path| { + if path.is_absolute() { + path.clone() + } else { + config.workspace_dir.join(path) + } + }) +} + +fn incident_store_path(config: &Config) -> Option { + config.compliance.eu_ai_act.incident_store_path.as_ref().map(|path| { + if path.is_absolute() { + path.clone() + } else { + config.workspace_dir.join(path) + } + }) +} + +fn verified_declaration_control(config: &Config) -> (ControlStatus, String, String) { + let Some(path) = declaration_artifact_path(config) else { + return ( + ControlStatus::Fail, + "declaration-of-conformity:path-missing".to_string(), + "High-risk classification is recorded, but no declaration artifact path is configured.".to_string(), + ); + }; + openprx::compliance::declaration::verify_declaration_artifact(&path).map_or_else( + |_| { + ( + ControlStatus::Fail, + "declaration-of-conformity:verification-failed".to_string(), + "The configured declaration artifact is missing, incomplete, or has a mismatched hash.".to_string(), + ) + }, + |evidence| { + ( + ControlStatus::Pass, + evidence, + "Artifact structure/hash and an operator-supplied external signature reference were verified; PRX did not validate signature authenticity or submission." + .to_string(), + ) + }, + ) +} + +fn verified_incident_control(config: &Config) -> (ControlStatus, String, String) { + let Some(path) = incident_store_path(config) else { + return ( + ControlStatus::Fail, + "article-73-incidents:path-missing".to_string(), + "High-risk classification is recorded, but no durable incident store path is configured.".to_string(), + ); + }; + openprx::compliance::incident::verify_incident_store(&path).map_or_else( + |_| { + ( + ControlStatus::Fail, + "article-73-incidents:verification-failed".to_string(), + "The configured incident store is missing, incompatible, or contains an overdue open incident without an initial report." + .to_string(), + ) + }, + |evidence| { + ( + ControlStatus::Pass, + evidence, + "The durable store schema and open-incident initial-report deadlines were verified read-only." + .to_string(), + ) + }, + ) +} + +fn build_eu_ai_act_attestation(config: &Config) -> EuAiActAttestation { + let observed_at = chrono::Utc::now().to_rfc3339(); + let config_revision = config_source_revision(config); + let config_evidence = config_revision + .clone() + .unwrap_or_else(|| "config:unavailable".to_string()); + let audit_status = ControlStatus::Pass; + let events_status = ControlStatus::Pass; + let postgres = config.memory.backend == "postgres" || config.storage.provider.config.provider == "postgres"; + let (vector_isolation_status, vector_isolation_evidence, vector_isolation_explanation) = if postgres { + let storage = &config.storage.provider.config; + match storage.db_url.as_deref().map(|db_url| { + memory::postgres::PostgresMemory::verify_vector_isolation( + db_url, + &storage.schema, + &storage.table, + storage.connect_timeout_secs, + ) + }) { + Some(Ok(evidence)) => ( + ControlStatus::Pass, + evidence, + "Migrations 21, 23 and 24 and the exact set of forced, permissive RLS policies were verified read-only on all PostgreSQL vector tables." + .to_string(), + ), + Some(Err(_)) => ( + ControlStatus::Fail, + "postgres:vector-isolation:verification-failed".to_string(), + "PostgreSQL is configured, but live migration/RLS evidence could not be verified.".to_string(), + ), + None => ( + ControlStatus::Fail, + "postgres:vector-isolation:db-url-missing".to_string(), + "PostgreSQL is configured without the connection data required for read-only evidence verification." + .to_string(), + ), + } + } else { + ( + ControlStatus::NotApplicable, + "backend:not-postgres".to_string(), + "PostgreSQL vector RLS is not applicable to this backend; application owner isolation is evaluated separately." + .to_string(), + ) + }; + let notice = &config.compliance.interaction_notice; + let (notice_status, notice_explanation) = match notice.applicability { + config::schema::InteractionNoticeApplicability::NotApplicable => ( + ControlStatus::NotApplicable, + format!( + "Operator exception owner={} reviewed_at={}", + notice.exception_owner.as_deref().unwrap_or("missing"), + notice.exception_reviewed_at.as_deref().unwrap_or("missing") + ), + ), + config::schema::InteractionNoticeApplicability::Required => ( + ControlStatus::Pass, + format!( + "versioned notice {} is enabled before channel response routing", + notice.version + ), + ), + }; + let eu_classification = &config.compliance.eu_ai_act.classification; + let (declaration_status, declaration_evidence, declaration_explanation) = match eu_classification.status { + config::schema::EuAiActRiskClassification::Unclassified => ( + ControlStatus::Unknown, + "classification:unclassified".to_string(), + "No named owner has classified this deployment for the high-risk declaration requirement.".to_string(), + ), + config::schema::EuAiActRiskClassification::NotHighRisk => ( + ControlStatus::NotApplicable, + format!( + "classification:owner={}:assessed_at={}", + eu_classification.owner.as_deref().unwrap_or("missing"), + eu_classification.assessed_at.as_deref().unwrap_or("missing") + ), + "The recorded operator/legal classification says this deployment is not a high-risk AI system.".to_string(), + ), + config::schema::EuAiActRiskClassification::HighRisk => verified_declaration_control(config), + }; + let (incident_status, incident_evidence, incident_explanation) = match eu_classification.status { + config::schema::EuAiActRiskClassification::Unclassified => ( + ControlStatus::Unknown, + "classification:unclassified".to_string(), + "The incident workflow cannot be evaluated until a named owner classifies the deployment.".to_string(), + ), + config::schema::EuAiActRiskClassification::NotHighRisk => ( + ControlStatus::NotApplicable, + format!( + "classification:owner={}:assessed_at={}", + eu_classification.owner.as_deref().unwrap_or("missing"), + eu_classification.assessed_at.as_deref().unwrap_or("missing") + ), + "The recorded operator/legal classification says Article 73 is not applicable to this deployment." + .to_string(), + ), + config::schema::EuAiActRiskClassification::HighRisk => verified_incident_control(config), + }; + + let mut checks = vec![ + attestation_check( + &observed_at, + "L01", + "Article 12", + "Side-effect audit logging enabled", + audit_status, + "config_revision", + &config_evidence, + "security.audit=always_on".to_string(), + "Retain signed audit evidence.", + ), + attestation_check( + &observed_at, + "L02", + "Article 12", + "Audit retention floor", + ControlStatus::Warning, + "config_revision", + &config_evidence, + format!( + "audit rotation size is {} MiB; no time-based floor is enforced", + config.security.audit.max_size_mb + ), + "Define and enforce an operator-approved retention period.", + ), + attestation_check( + &observed_at, + "L03", + "Article 12", + "Control-ladder trace rotation", + ControlStatus::Unknown, + "runtime_diagnostic", + "doctor:runtime/control_ladder_traces", + "No runtime trace-archive evidence was evaluated by this command.", + "Attach trace rotation and archival evidence.", + ), + attestation_check( + &observed_at, + "L04", + "Article 12", + "Message timeline recording", + events_status, + "config_revision", + &config_evidence, + "memory.events=always_on".to_string(), + "Attach retention evidence.", + ), + attestation_check( + &observed_at, + "T01", + "Article 13", + "Provider routing transparency", + ControlStatus::Warning, + "config_revision", + &config_evidence, + format!( + "default provider is {:?}; runtime route evidence was not queried", + config.default_provider + ), + "Attach route-decision and final-outcome event references.", + ), + attestation_check( + &observed_at, + "T02", + "Article 13", + "Third-party provider data-policy disclosure", + ControlStatus::Unknown, + "operator_assertion", + "provider-policy-owner:missing", + "Provider policy URL and review ownership were not supplied.", + "Record policy URLs, owner, and review expiry for each provider.", + ), + attestation_check( + &observed_at, + "T04", + "Article 50", + "AI interaction notice", + notice_status, + "config_revision", + &config_evidence, + notice_explanation, + "Emit and minimally acknowledge a versioned AI identity notice before the first response.", + ), + attestation_check( + &observed_at, + "H01", + "Article 14", + "Approval grant cryptographic witness", + ControlStatus::Unknown, + "runtime_diagnostic", + "approval-ledger:not_evaluated", + "Source presence alone is not execution evidence.", + "Attach a verified ApprovalGrant v2 ledger receipt.", + ), + attestation_check( + &observed_at, + "H02", + "Article 14", + "Side-effect authorization coverage", + ControlStatus::Unknown, + "runtime_diagnostic", + "tool-gate-coverage:not_evaluated", + "This report did not execute tool-gate coverage tests.", + "Attach release test receipts for every side-effect tool.", + ), + attestation_check( + &observed_at, + "H03", + "Article 14", + "High-risk operation supervision", + ControlStatus::Warning, + "config_revision", + &config_evidence, + format!("autonomy level is {:?}", config.autonomy.level), + "Use supervised policy and attach approval receipts where applicable.", + ), + attestation_check( + &observed_at, + "H04", + "Article 14", + "Inbound listener human oversight", + ControlStatus::Unknown, + "runtime_diagnostic", + "channel-oversight:not_evaluated", + "No live inbound-channel oversight evidence was evaluated.", + "Run adapter-level supervised-mode conformance tests.", + ), + attestation_check( + &observed_at, + "A01", + "Article 15", + "Retrieval traceability", + ControlStatus::Unknown, + "runtime_diagnostic", + "retrieval-traces:not_evaluated", + "No retrieval trace was sampled.", + "Attach immutable retrieval-trace identifiers.", + ), + attestation_check( + &observed_at, + "A02", + "Article 15", + "Compaction provenance", + ControlStatus::Unknown, + "runtime_diagnostic", + "compaction-runs:not_evaluated", + "No compaction run was sampled.", + "Attach completed compaction-run identifiers and fidelity evidence.", + ), + attestation_check( + &observed_at, + "A03", + "Article 15", + "Prompt-injection content boundaries", + ControlStatus::Unknown, + "runtime_diagnostic", + "content-boundary:not_evaluated", + "Static implementation claims are insufficient evidence.", + "Attach adversarial content-boundary test results.", + ), + attestation_check( + &observed_at, + "A04", + "Article 15 internal security control", + "Vector owner/tenant isolation", + vector_isolation_status, + "postgres_runtime_evidence", + vector_isolation_evidence, + vector_isolation_explanation, + "Install authoritative RLS policies and attach cross-owner negative-test evidence.", + ), + attestation_check( + &observed_at, + "Q01", + "Article 16", + "Dependency vulnerability gate", + ControlStatus::Unknown, + "release_receipt", + "cargo-audit:missing", + "No cargo-audit receipt was supplied to this invocation.", + "Attach a timestamped cargo-audit release receipt.", + ), + attestation_check( + &observed_at, + "Q02", + "Article 16", + "Rust engineering gate", + ControlStatus::Unknown, + "release_receipt", + "engineering-gate:missing", + "No fmt/clippy/check/test receipt was supplied.", + "Attach source-identity-bound engineering gate results.", + ), + attestation_check( + &observed_at, + "Q03", + "Article 16", + "Quality management documentation", + ControlStatus::Unknown, + "operator_assertion", + "qms-owner:missing", + "No QMS owner or reviewed document set was supplied.", + "Record the QMS owner, document versions, and review date.", + ), + attestation_check( + &observed_at, + "C01", + "Article 17", + "Quality management system", + ControlStatus::Unknown, + "operator_assertion", + "qms-classification:missing", + "Applicability and operator evidence are unresolved.", + "Complete legal classification and QMS evidence review.", + ), + attestation_check( + &observed_at, + "C02", + "Article 47 and Annex V", + "EU declaration of conformity artifact", + declaration_status, + "artifact", + declaration_evidence, + declaration_explanation, + "Generate a versioned artifact only from explicit operator declarations.", + ), + attestation_check( + &observed_at, + "M01", + "Article 72", + "Post-market monitoring inputs", + ControlStatus::Unknown, + "runtime_diagnostic", + "monitoring-evidence:not_evaluated", + "Runtime health and trace data were not sampled.", + "Attach monitoring evidence and an operator-approved plan.", + ), + attestation_check( + &observed_at, + "M02", + "Article 73", + "Incident response ownership", + ControlStatus::Unknown, + "operator_assertion", + "incident-owner:missing", + "No incident owner or jurisdiction matrix was supplied.", + "Record the incident owner, jurisdictions, and escalation runbook.", + ), + attestation_check( + &observed_at, + "M03", + "Article 72", + "Post-market report cadence", + ControlStatus::Unknown, + "operator_assertion", + "monitoring-cadence:missing", + "No reviewed monitoring cadence was supplied.", + "Record cadence, owner, review date, and report references.", + ), + attestation_check( + &observed_at, + "M04", + "Article 73", + "Serious-incident workflow", + incident_status, + "incident_store", + incident_evidence, + incident_explanation, + "Configure the durable incident store and use the incident CLI to record awareness, classification, reports, supplements, and closure.", + ), + ]; + checks.sort_by_key(|check| check.id); + + let passed_count = checks + .iter() + .filter(|check| check.status == ControlStatus::Pass) + .count(); + let warning_count = checks + .iter() + .filter(|check| check.status == ControlStatus::Warning) + .count(); + let failed_count = checks + .iter() + .filter(|check| check.status == ControlStatus::Fail) + .count(); + let unknown_count = checks + .iter() + .filter(|check| check.status == ControlStatus::Unknown) + .count(); + let not_applicable_count = checks + .iter() + .filter(|check| check.status == ControlStatus::NotApplicable) + .count(); + + EuAiActAttestation { + report_type: "EU AI Act implementation attestation", + evaluator_version: "prx-eu-ai-act-controls/v2", + product_version: env!("CARGO_PKG_VERSION"), + source_identity: option_env!("PRX_BUILD_SOURCE_REVISION").map(str::to_string), + config_generation: config_generation(config), + config_source_revision: config_revision, + generated_at: observed_at, + applicability: ApplicabilityDecision { + status: ControlStatus::Unknown, + classification: "unclassified; operator and legal review required".to_string(), + owner: None, + reviewed_at: None, + }, + default_provider: config.default_provider.clone(), + total_checks: checks.len(), + passed_count, + warning_count, + failed_count, + unknown_count, + not_applicable_count, + checks, + } +} + +fn render_eu_ai_act_attestation_markdown(attestation: &EuAiActAttestation, verbose: bool) -> String { + let mut output = String::new(); + output.push_str("# PRX EU AI Act Implementation Attestation\n\n"); + output.push_str("This is an implementation attestation, not a regulator-issued certification.\n\n"); + output.push_str(&format!("- Product version: {}\n", attestation.product_version)); + output.push_str(&format!( + "- Source identity: {}\n", + attestation.source_identity.as_deref().unwrap_or("unavailable") + )); + output.push_str(&format!("- Generated at: {}\n", attestation.generated_at)); + output.push_str(&format!( + "- Classification: {}\n", + attestation.applicability.classification + )); + output.push_str(&format!( + "- Checks: {} total, {} pass, {} warning, {} fail, {} unknown, {} not applicable\n\n", + attestation.total_checks, + attestation.passed_count, + attestation.warning_count, + attestation.failed_count, + attestation.unknown_count, + attestation.not_applicable_count + )); + output.push_str("| ID | Article | Status | Control |\n"); + output.push_str("|----|---------|--------|---------|\n"); + for check in &attestation.checks { + output.push_str(&format!( + "| {} | {} | {} | {} |\n", + check.id, + check.framework_reference, + check.status.as_str(), + check.control + )); + if verbose { + output.push_str(&format!( + "\n{} evidence: {}\n\n{} explanation: {}\n\n{} remediation: {}\n\n", + check.id, + check + .evidence + .iter() + .map(|evidence| format!("{}={}", evidence.kind, evidence.reference)) + .collect::>() + .join(", "), + check.id, + check.explanation, + check.id, + check.remediation + )); + } + } + output +} + +fn render_eu_ai_act_attestation_json(attestation: &EuAiActAttestation) -> Result { + serde_json::to_string_pretty(attestation).context("Failed to serialize EU AI Act attestation") +} + +fn attestation_fails_gate(attestation: &EuAiActAttestation, fail_on: AuditFailOn) -> bool { + attestation.checks.iter().any(|check| match fail_on { + AuditFailOn::Fail => check.status == ControlStatus::Fail, + AuditFailOn::Warning => matches!( + check.status, + ControlStatus::Warning | ControlStatus::Unknown | ControlStatus::Fail + ), + }) +} + +fn handle_audit_command(audit_command: AuditCommands, config: &Config) -> Result<()> { + match audit_command { + AuditCommands::AttestEuAiAct { + json, + format, + output, + verbose, + fail_on, + } => { + let attestation = build_eu_ai_act_attestation(config); + let stdout_json = json || format == AuditOutputFormat::Json; + let stdout_rendered = if stdout_json { + render_eu_ai_act_attestation_json(&attestation)? + } else { + render_eu_ai_act_attestation_markdown(&attestation, verbose) + }; + + if let Some(path) = output { + let write_json = path.extension().and_then(|ext| ext.to_str()) == Some("json") || stdout_json; + let file_rendered = if write_json { + render_eu_ai_act_attestation_json(&attestation)? + } else { + render_eu_ai_act_attestation_markdown(&attestation, verbose) + }; + fs::write(&path, file_rendered) + .with_context(|| format!("Failed to write EU AI Act attestation to {}", path.display()))?; + } + + println!("{stdout_rendered}"); + if fail_on.is_some_and(|threshold| attestation_fails_gate(&attestation, threshold)) { + bail!("EU AI Act implementation attestation did not satisfy --fail-on threshold"); + } + Ok(()) + } + AuditCommands::GenerateEuDeclaration { + output, + signature_reference, + } => { + let configured_path = declaration_artifact_path(config); + let output = output + .map(|path| { + if path.is_absolute() { + path + } else { + config.workspace_dir.join(path) + } + }) + .or_else(|| configured_path.clone()) + .context( + "declaration output is required via --output or compliance.eu_ai_act.declaration.artifact_path", + )?; + if let Some(configured_path) = configured_path { + anyhow::ensure!( + output == configured_path, + "--output must match compliance.eu_ai_act.declaration.artifact_path so attestation can verify it" + ); + } + let artifact = openprx::compliance::declaration::build_declaration_artifact( + config.compliance.eu_ai_act.classification.status, + &config.compliance.eu_ai_act.declaration, + &signature_reference, + )?; + openprx::compliance::declaration::write_declaration_artifact(&output, &artifact)?; + println!( + "{}", + serde_json::json!({ + "artifact": output, + "payload_sha256": artifact.payload_sha256, + "signature_status": artifact.signature.status, + "submitted": artifact.signature.submitted, + }) + ); + Ok(()) + } + AuditCommands::IncidentCreate { input } => { + let path = incident_store_path(config).context("compliance.eu_ai_act.incident_store_path is required")?; + let bytes = + fs::read(&input).with_context(|| format!("Failed to read incident input {}", input.display()))?; + let request = serde_json::from_slice(&bytes).context("Failed to parse incident input JSON")?; + let mut store = openprx::compliance::incident::IncidentStore::open(&path)?; + let record = store.create(request)?; + println!("{}", serde_json::to_string_pretty(&record)?); + Ok(()) + } + AuditCommands::IncidentInitialReport { incident_id, input } => { + let path = incident_store_path(config).context("compliance.eu_ai_act.incident_store_path is required")?; + let report = fs::read_to_string(&input) + .with_context(|| format!("Failed to read initial report {}", input.display()))?; + let mut store = openprx::compliance::incident::IncidentStore::open(&path)?; + let record = store.set_initial_report(&incident_id, &report)?; + println!("{}", serde_json::to_string_pretty(&record)?); + Ok(()) + } + AuditCommands::IncidentSupplement { incident_id, input } => { + let path = incident_store_path(config).context("compliance.eu_ai_act.incident_store_path is required")?; + let content = fs::read_to_string(&input) + .with_context(|| format!("Failed to read incident supplement {}", input.display()))?; + let mut store = openprx::compliance::incident::IncidentStore::open(&path)?; + let supplement = store.add_supplement(&incident_id, &content)?; + println!("{}", serde_json::to_string_pretty(&supplement)?); + Ok(()) + } + AuditCommands::IncidentClose { + incident_id, + closed_at, + summary, + } => { + let path = incident_store_path(config).context("compliance.eu_ai_act.incident_store_path is required")?; + let closed_at = chrono::DateTime::parse_from_rfc3339(&closed_at) + .context("--closed-at must be RFC 3339")? + .with_timezone(&Utc); + let summary = fs::read_to_string(&summary) + .with_context(|| format!("Failed to read closure summary {}", summary.display()))?; + let mut store = openprx::compliance::incident::IncidentStore::open(&path)?; + let record = store.close(&incident_id, closed_at, &summary)?; + println!("{}", serde_json::to_string_pretty(&record)?); + Ok(()) + } + AuditCommands::IncidentExport { incident_id, output } => { + let path = incident_store_path(config).context("compliance.eu_ai_act.incident_store_path is required")?; + let output = if output.is_absolute() { + output + } else { + config.workspace_dir.join(output) + }; + let store = openprx::compliance::incident::IncidentStore::open(&path)?; + let export = store.export(&incident_id)?; + openprx::compliance::incident::write_incident_export(&output, &export)?; + println!( + "{}", + serde_json::json!({ + "artifact": output, + "incident_id": incident_id, + "automatically_submitted": export.automatically_submitted, + }) + ); + Ok(()) + } + } +} + +fn handle_approval_command(approval_command: ApprovalCommands, config: &Config) -> Result<()> { + let conn = open_approval_ledger(config)?; + match approval_command { + ApprovalCommands::List { version } => { + let version = version.unwrap_or(2); + if version == acl::approval_grant::ApprovalGrantV2::VERSION { + let mut stmt = conn.prepare( + "SELECT grant_id, owner_id, principal_id, capability_op_id, expires_at, revoked_at + FROM approval_grants + WHERE version = ?1 + ORDER BY issued_at DESC + LIMIT 50", + )?; + let rows = stmt.query_map([i64::from(version)], |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, String>(1)?, + row.get::<_, String>(2)?, + row.get::<_, String>(3)?, + row.get::<_, String>(4)?, + row.get::<_, Option>(5)?, + )) + })?; + let grants = rows.collect::>>()?; + if grants.is_empty() { + println!("no approval grants found (version: 2)"); + } else { + for (grant_id, owner_id, principal_id, op_id, expires_at, revoked_at) in grants { + let status = if revoked_at.is_some() { "revoked" } else { "active" }; + println!( + "{grant_id}\t{status}\towner={owner_id}\tprincipal={principal_id}\top={op_id}\texpires={expires_at}" + ); + } + } + Ok(()) + } else { + bail!("unsupported approval grant version: {version}") + } + } + ApprovalCommands::Verify { all, grant_id } => { + if all { + let total: i64 = conn.query_row("SELECT COUNT(*) FROM approval_grants", [], |row| row.get(0))?; + let malformed: i64 = conn.query_row( + "SELECT COUNT(*) FROM approval_grants + WHERE grant_json = '' OR signature_alg = '' OR signed_payload_sha256 = ''", + [], + |row| row.get(0), + )?; + if total == 0 { + println!("no approval grants found to verify"); + } else if malformed == 0 { + println!("approval grant ledger metadata verified: {total} grants"); + } else { + bail!("approval grant ledger metadata verification failed: {malformed}/{total} malformed grants"); + } + return Ok(()); + } + let Some(grant_id) = grant_id else { + bail!("provide a grant id or --all"); + }; + let found: Option<(String, String, String)> = conn + .query_row( + "SELECT grant_id, signature_alg, signed_payload_sha256 + FROM approval_grants + WHERE grant_id = ?1", + [grant_id.as_str()], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), + ) + .optional()?; + let Some((grant_id, signature_alg, payload_sha)) = found else { + bail!("approval grant not found: {grant_id}"); + }; + if signature_alg.trim().is_empty() || payload_sha.trim().is_empty() { + bail!("approval grant metadata verification failed: {grant_id}"); + } + println!("approval grant metadata verified: {grant_id} ({signature_alg})"); + Ok(()) + } + ApprovalCommands::Revoke { grant_id, reason } => { + let now = Utc::now().to_rfc3339(); + let updated = conn.execute( + "UPDATE approval_grants + SET revoked_at = COALESCE(revoked_at, ?2), + revocation_reason = COALESCE(revocation_reason, ?3), + updated_at = ?2 + WHERE grant_id = ?1", + params![grant_id, now, reason], + )?; + if updated == 0 { + bail!("approval grant not found: {grant_id}"); + } + conn.execute( + "INSERT INTO approval_grant_events (event_id, grant_id, event_type, actor, occurred_at, payload_json) + VALUES (?1, ?2, 'grant.revoked', 'cli', ?3, ?4)", + params![ + uuid::Uuid::new_v4().to_string(), + grant_id, + now, + serde_json::json!({ "reason": reason }).to_string() + ], + )?; + println!("approval grant revoked: {grant_id}"); + Ok(()) + } + } +} + +fn open_approval_ledger(config: &Config) -> Result { + let db_path = config.workspace_dir.join("memory").join("brain.db"); + if let Some(parent) = db_path.parent() { + fs::create_dir_all(parent) + .with_context(|| format!("Failed to create approval ledger directory: {}", parent.display()))?; + } + let conn = + Connection::open(&db_path).with_context(|| format!("Failed to open approval ledger: {}", db_path.display()))?; + memory::sqlite::init_approval_grant_schema(&conn)?; + Ok(conn) +} + +async fn login_openrouter(auth_service: &auth::AuthService, profile: &str, headless: bool) -> Result<()> { + let pkce = auth::openrouter_oauth::generate_pkce(); + let client = openprx::prx_http_client(); + let code = if headless { + println!("Open this URL. It shows a code to paste back (no browser callback):"); + println!("{}", auth::openrouter_oauth::headless_authorize_url(&pkce)); + read_plain_input("Paste OpenRouter code")? + } else { + let (listener, callback) = auth::openrouter_oauth::bind_loopback().await?; + println!("Open this URL in your browser and authorize access:"); + println!("{}", auth::openrouter_oauth::browser_authorize_url(&callback, &pkce)); + println!("Waiting for the loopback callback..."); + auth::openrouter_oauth::receive_loopback_code(listener, std::time::Duration::from_mins(3)).await? + }; + let key = auth::openrouter_oauth::exchange_code(&client, &code, &pkce.verifier).await?; + auth_service.store_provider_token("openrouter", profile, &key, std::collections::HashMap::new(), true)?; + println!("Saved profile {profile}"); + println!("Active profile for openrouter: {profile}"); + Ok(()) +} + +async fn login_xai(auth_service: &auth::AuthService, config: &Config, profile: &str, device_code: bool) -> Result<()> { + let client = openprx::prx_http_client(); + let state_dir = auth::state_dir_from_config(config); + + if device_code { + let device = auth::xai_oauth::start_device_code_flow(&client).await?; + println!("xAI device-code login started."); + println!("Visit: {}", device.verification_uri); + println!("Code: {}", device.user_code); + if let Some(uri_complete) = &device.verification_uri_complete { + println!("Fast link: {uri_complete}"); + } + let token_set = auth::xai_oauth::poll_device_code_tokens(&client, &device).await?; + auth_service.store_xai_tokens(profile, token_set, true)?; + println!("Saved profile {profile}"); + println!("Active profile for xai: {profile}"); + return Ok(()); + } + + let pkce = auth::xai_oauth::generate_pkce(); + let pending = auth::xai_oauth::PendingXaiLogin { + profile: profile.to_string(), + code_verifier: pkce.code_verifier.clone(), + state: pkce.state.clone(), + created_at: chrono::Utc::now().to_rfc3339(), + }; + auth::xai_oauth::save_pending_login(&state_dir, config.secrets.encrypt, &pending)?; + let authorize_url = auth::xai_oauth::build_authorize_url(&pkce); + println!("Open this URL in your browser and authorize access:"); + println!("{authorize_url}"); + println!(); + println!( + "Waiting for callback at {} ...", + auth::xai_oauth::XAI_OAUTH_REDIRECT_URI + ); + + let code = match auth::xai_oauth::receive_loopback_code(&pkce.state, std::time::Duration::from_secs(180)).await { + Ok(code) => code, + Err(error) => { + println!("Callback capture failed: {error}"); + println!("Run `prx auth paste-redirect --provider xai --profile {profile}`"); + return Ok(()); + } + }; + let token_set = auth::xai_oauth::exchange_code_for_tokens(&client, &code, &pkce.code_verifier).await?; + auth_service.store_xai_tokens(profile, token_set, true)?; + auth::xai_oauth::clear_pending_login(&state_dir); + println!("Saved profile {profile}"); + println!("Active profile for xai: {profile}"); + Ok(()) +} + +async fn paste_xai_redirect( + auth_service: &auth::AuthService, + config: &Config, + profile: &str, + input: Option, +) -> Result<()> { + let state_dir = auth::state_dir_from_config(config); + let pending = auth::xai_oauth::load_pending_login(&state_dir, config.secrets.encrypt)? + .ok_or_else(|| anyhow::anyhow!("No pending xAI login found. Run `prx auth login --provider xai` first."))?; + if pending.profile != profile { + bail!( + "Pending login profile mismatch: pending={}, requested={}", + pending.profile, + profile + ); + } + let redirect_input = match input { + Some(value) => value, + None => read_plain_input("Paste redirect URL or OAuth code")?, + }; + let code = auth::xai_oauth::parse_code_from_redirect(&redirect_input, Some(&pending.state))?; + let client = openprx::prx_http_client(); + let token_set = auth::xai_oauth::exchange_code_for_tokens(&client, &code, &pending.code_verifier).await?; + auth_service.store_xai_tokens(profile, token_set, true)?; + auth::xai_oauth::clear_pending_login(&state_dir); + println!("Saved profile {profile}"); + println!("Active profile for xai: {profile}"); + Ok(()) +} diff --git a/src/main/section_3.rs b/src/main/section_3.rs new file mode 100644 index 000000000..ac60f4059 --- /dev/null +++ b/src/main/section_3.rs @@ -0,0 +1,1319 @@ +#[allow(clippy::too_many_lines)] +async fn handle_auth_command(auth_command: AuthCommands, config: &Config) -> Result<()> { + let auth_service = auth::AuthService::from_config(config); + + match auth_command { + AuthCommands::Login { + provider, + profile, + device_code, + } => { + let provider = auth::normalize_provider(&provider)?; + if provider == "xai" { + return login_xai(&auth_service, config, &profile, device_code).await; + } + if provider == "openrouter" { + return login_openrouter(&auth_service, &profile, device_code).await; + } + if provider != "openai-codex" { + bail!("`auth login` supports --provider openai-codex, --provider openrouter, and --provider xai"); + } + + let client = openprx::prx_http_client(); + + if device_code { + auth::openai_oauth::start_device_code_flow(&client)?; + } + + let state_dir = auth::state_dir_from_config(config); + let host_id = auth::openai_oauth::load_or_create_host_id(&state_dir)?; + let saved_client_id = auth_service + .get_profile("openai-codex", Some(&profile))? + .and_then(|profile| { + profile + .metadata + .get(auth::openai_oauth::OPENAI_CLIENT_ID_METADATA) + .cloned() + }); + let pkce = auth::openai_oauth::generate_pkce_state(); + let client_id_sent = saved_client_id + .as_deref() + .filter(|value| value.starts_with("oaiapp_")) + .unwrap_or(auth::openai_oauth::OPENAI_OAUTH_DYNAMIC_CLIENT_ID) + .to_string(); + let pending = PendingOpenAiLogin { + profile: profile.clone(), + code_verifier: pkce.code_verifier.clone(), + state: pkce.state.clone(), + created_at: chrono::Utc::now().to_rfc3339(), + host_id: host_id.clone(), + client_id: client_id_sent.clone(), + }; + save_pending_openai_login(config, &pending)?; + + let authorize_url = + auth::openai_oauth::build_authorize_url(&pkce, &host_id, saved_client_id.as_deref(), None); + println!("Open this URL in your browser and authorize access:"); + println!("{authorize_url}"); + println!(); + println!( + "Waiting for callback at {} ...", + auth::openai_oauth::OPENAI_OAUTH_REDIRECT_URI + ); + + let callback = + match auth::openai_oauth::receive_loopback_code(&pkce.state, std::time::Duration::from_mins(3)).await { + Ok(callback) => callback, + Err(e) => { + println!("Callback capture failed: {e}"); + println!("Run `prx auth paste-redirect --provider openai-codex --profile {profile}`"); + return Ok(()); + } + }; + let code = auth::openai_oauth::parse_code_from_redirect(&callback, Some(&pkce.state))?; + + let issued = auth::openai_oauth::issued_client_id_from_callback(&callback) + .or_else(|| client_id_sent.starts_with("oaiapp_").then(|| client_id_sent.clone())); + let Some(exchange_client_id) = issued else { + bail!( + "Sign in with ChatGPT did not return an issued oaiapp_ client id. Run `prx auth login --provider openai-codex` again." + ); + }; + let token_set = + auth::openai_oauth::exchange_code_for_tokens(&client, &code, &pkce, &exchange_client_id).await?; + let account_id = + extract_openai_account_id_for_profile(&token_set.access_token, token_set.id_token.as_deref()); + + auth_service.store_openai_siwc_tokens(&profile, token_set, account_id, &exchange_client_id, true)?; + clear_pending_openai_login(config); + + println!("Saved profile {profile}"); + println!("Active profile for openai-codex: {profile}"); + Ok(()) + } + + AuthCommands::PasteRedirect { + provider, + profile, + input, + } => { + let provider = auth::normalize_provider(&provider)?; + if provider == "xai" { + return paste_xai_redirect(&auth_service, config, &profile, input).await; + } + if provider != "openai-codex" { + bail!("`auth paste-redirect` supports --provider openai-codex and --provider xai"); + } + + let pending = load_pending_openai_login(config)?.ok_or_else(|| { + anyhow::anyhow!("No pending OpenAI login found. Run `prx auth login --provider openai-codex` first.") + })?; + + if pending.profile != profile { + bail!( + "Pending login profile mismatch: pending={}, requested={}", + pending.profile, + profile + ); + } + + let redirect_input = match input { + Some(value) => value, + None => read_plain_input("Paste redirect URL or OAuth code")?, + }; + + let code = auth::openai_oauth::parse_code_from_redirect(&redirect_input, Some(&pending.state))?; + let issued = auth::openai_oauth::issued_client_id_from_callback(&redirect_input).or_else(|| { + pending + .client_id + .starts_with("oaiapp_") + .then(|| pending.client_id.clone()) + }); + let Some(exchange_client_id) = issued else { + bail!( + "Sign in with ChatGPT did not return an issued oaiapp_ client id. Run `prx auth login --provider openai-codex` again." + ); + }; + + let pkce = auth::openai_oauth::PkceState { + code_verifier: pending.code_verifier.clone(), + code_challenge: String::new(), + state: pending.state.clone(), + nonce: String::new(), + }; + + let client = openprx::prx_http_client(); + let token_set = + auth::openai_oauth::exchange_code_for_tokens(&client, &code, &pkce, &exchange_client_id).await?; + let account_id = + extract_openai_account_id_for_profile(&token_set.access_token, token_set.id_token.as_deref()); + + auth_service.store_openai_siwc_tokens(&profile, token_set, account_id, &exchange_client_id, true)?; + clear_pending_openai_login(config); + + println!("Saved profile {profile}"); + println!("Active profile for openai-codex: {profile}"); + Ok(()) + } + + AuthCommands::PasteToken { + provider, + profile, + token, + from_stdin, + auth_kind, + } => { + let provider = auth::normalize_provider(&provider)?; + let piped = manage_cli::secret_from(from_stdin, None, &mut std::io::stdin(), &|_: &str| None)?; + let token = match (token, piped) { + (_, Some(piped)) => piped.trim().to_string(), + (Some(token), None) => token.trim().to_string(), + (None, None) => read_auth_input("Paste token")?, + }; + if token.is_empty() { + bail!("Token cannot be empty"); + } + if auth::discovery::is_claude_code_oauth_setup_token(&token) { + bail!("{}", auth::terms::ANTHROPIC_SUBSCRIPTION_REMOVED); + } + + let kind = auth::anthropic_token::detect_auth_kind(&token, auth_kind.as_deref()); + let mut metadata = std::collections::HashMap::new(); + metadata.insert("auth_kind".to_string(), kind.as_metadata_value().to_string()); + + auth_service.store_provider_token(&provider, &profile, &token, metadata, true)?; + println!("Saved profile {profile}"); + println!("Active profile for {provider}: {profile}"); + Ok(()) + } + + AuthCommands::SetupToken { provider, profile } => { + let provider = auth::normalize_provider(&provider)?; + let token = read_auth_input("Paste token")?; + if token.is_empty() { + bail!("Token cannot be empty"); + } + if auth::discovery::is_claude_code_oauth_setup_token(&token) { + bail!("{}", auth::terms::ANTHROPIC_SUBSCRIPTION_REMOVED); + } + + let kind = auth::anthropic_token::detect_auth_kind(&token, Some("authorization")); + let mut metadata = std::collections::HashMap::new(); + metadata.insert("auth_kind".to_string(), kind.as_metadata_value().to_string()); + + auth_service.store_provider_token(&provider, &profile, &token, metadata, true)?; + println!("Saved profile {profile}"); + println!("Active profile for {provider}: {profile}"); + Ok(()) + } + + AuthCommands::Refresh { provider, profile } => { + let provider = auth::normalize_provider(&provider)?; + if provider == "xai" { + return match auth_service.get_valid_xai_access_token(profile.as_deref()).await? { + Some(_) => { + println!("xAI Grok token is valid (refresh completed if needed)."); + Ok(()) + } + None => { + bail!("No xAI auth profile found. Run `prx auth login --provider xai`.") + } + }; + } + if provider != "openai-codex" { + bail!("`auth refresh` supports --provider openai-codex and --provider xai"); + } + + match auth_service.get_valid_openai_access_token(profile.as_deref()).await? { + Some(_) => { + println!("OpenAI Codex token is valid (refresh completed if needed)."); + Ok(()) + } + None => { + bail!("No OpenAI Codex auth profile found. Run `prx auth login --provider openai-codex`.") + } + } + } + + AuthCommands::Logout { provider, profile } => { + let provider = auth::normalize_provider(&provider)?; + let removed = auth_service.remove_profile(&provider, &profile)?; + if removed { + println!("Removed auth profile {provider}:{profile}"); + } else { + println!("Auth profile not found: {provider}:{profile}"); + } + Ok(()) + } + + AuthCommands::Use { provider, profile } => { + let provider = auth::normalize_provider(&provider)?; + auth_service.set_active_profile(&provider, &profile)?; + println!("Active profile for {provider}: {profile}"); + Ok(()) + } + + AuthCommands::List => { + let data = auth_service.load_profiles()?; + if data.profiles.is_empty() { + println!("No auth profiles configured."); + return Ok(()); + } + + for (id, profile) in &data.profiles { + let active = data + .active_profiles + .get(&profile.provider) + .is_some_and(|active_id| active_id == id); + let marker = if active { "*" } else { " " }; + println!("{marker} {id}"); + } + + Ok(()) + } + + AuthCommands::Status => { + let data = auth_service.load_profiles()?; + if data.profiles.is_empty() { + println!("No auth profiles configured."); + return Ok(()); + } + + for (id, profile) in &data.profiles { + let active = data + .active_profiles + .get(&profile.provider) + .is_some_and(|active_id| active_id == id); + let marker = if active { "*" } else { " " }; + println!( + "{} {} kind={:?} account={} expires={}", + marker, + id, + profile.kind, + crate::security::redact(profile.account_id.as_deref().unwrap_or("unknown")), + format_expiry(profile) + ); + } + + println!(); + println!("Active profiles:"); + for (provider, profile_id) in &data.active_profiles { + println!(" {provider}: {profile_id}"); + } + + Ok(()) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use clap::{CommandFactory, Parser}; + + #[test] + fn cli_definition_has_no_flag_conflicts() { + Cli::command().debug_assert(); + } + + /// Oracle is clap argv, not a copy of `cli_tracing_command`. Mapping + /// `Commands::Gateway` to `CliCommand::Chat` fails the gateway row. + fn commands_coverage_tag(command: &Commands) -> &'static str { + match command { + Commands::Init { .. } | Commands::Token { .. } => "Init", + Commands::Go { .. } => "Go", + Commands::Chat { message: Some(_), .. } => "ChatMessage", + Commands::Chat { .. } => "Chat", + Commands::Gateway { .. } => "Gateway", + Commands::Daemon { .. } => "Daemon", + Commands::Service { .. } => "Service", + Commands::Doctor { .. } => "Doctor", + Commands::A2a { .. } => "A2a", + Commands::Status { .. } => "Status", + Commands::Tasks { .. } => "Tasks", + Commands::Memory { .. } => "Memory", + Commands::Evolution { .. } => "Evolution", + #[cfg(feature = "wasm-plugins")] + Commands::Plugin { .. } => "Plugin", + Commands::Cost { .. } => "Cost", + Commands::Fitness { .. } => "Fitness", + Commands::Cron { .. } => "Cron", + Commands::Xin { .. } => "Xin", + Commands::Causal { .. } => "Causal", + Commands::DecisionEngine { .. } => "DecisionEngine", + Commands::Models { .. } => "Models", + Commands::Providers { .. } => "Providers", + Commands::Routes { .. } => "Routes", + Commands::Channel { + channel_command: ChannelCommands::Start, + } => "ChannelStart", + Commands::Channel { .. } => "ChannelManage", + Commands::Integrations { .. } => "Integrations", + Commands::Skills { .. } => "Skills", + Commands::Migrate { .. } => "Migrate", + Commands::Auth { .. } => "Auth", + Commands::Approval { .. } => "Approval", + Commands::Audit { .. } => "Audit", + Commands::Config { .. } => "Config", + #[cfg(feature = "test-mock")] + Commands::MailboxHarness { .. } => "MailboxHarness", + Commands::SessionWorker { .. } => "SessionWorker", + Commands::Completions { .. } => "Completions", + } + } + + #[test] + fn cli_tracing_clap_argv_maps_every_command() { + let cases: &[(&[&str], cli_tracing::CliCommand)] = &[ + (&["prx", "init"], cli_tracing::CliCommand::Init), + (&["prx", "go"], cli_tracing::CliCommand::Go), + (&["prx", "chat"], cli_tracing::CliCommand::Chat), + ( + &["prx", "chat", "--message", "hi"], + cli_tracing::CliCommand::ChatMessage, + ), + (&["prx", "gateway"], cli_tracing::CliCommand::Gateway), + (&["prx", "daemon"], cli_tracing::CliCommand::Daemon), + (&["prx", "service", "status"], cli_tracing::CliCommand::Service), + (&["prx", "doctor"], cli_tracing::CliCommand::Doctor), + (&["prx", "status"], cli_tracing::CliCommand::Status), + (&["prx", "tasks", "list"], cli_tracing::CliCommand::Tasks), + (&["prx", "memory", "reindex"], cli_tracing::CliCommand::Memory), + (&["prx", "evolution", "status"], cli_tracing::CliCommand::Evolution), + (&["prx", "cost"], cli_tracing::CliCommand::Cost), + (&["prx", "fitness", "status"], cli_tracing::CliCommand::Fitness), + (&["prx", "cron", "list"], cli_tracing::CliCommand::Cron), + (&["prx", "xin", "status"], cli_tracing::CliCommand::Xin), + (&["prx", "causal", "status"], cli_tracing::CliCommand::Causal), + ( + &["prx", "decision-engine", "status"], + cli_tracing::CliCommand::DecisionEngine, + ), + (&["prx", "models"], cli_tracing::CliCommand::Models), + (&["prx", "providers"], cli_tracing::CliCommand::Providers), + (&["prx", "routes", "list"], cli_tracing::CliCommand::Routes), + (&["prx", "channel", "start"], cli_tracing::CliCommand::ChannelStart), + (&["prx", "channel", "list"], cli_tracing::CliCommand::ChannelManage), + (&["prx", "integrations"], cli_tracing::CliCommand::Integrations), + (&["prx", "skills", "list"], cli_tracing::CliCommand::Skills), + (&["prx", "migrate", "status"], cli_tracing::CliCommand::Migrate), + ( + &["prx", "auth", "login", "--provider", "openai-codex"], + cli_tracing::CliCommand::Auth, + ), + (&["prx", "approval", "list"], cli_tracing::CliCommand::Approval), + (&["prx", "audit", "attest-eu-ai-act"], cli_tracing::CliCommand::Audit), + (&["prx", "config", "show"], cli_tracing::CliCommand::Config), + (&["prx", "session-worker"], cli_tracing::CliCommand::SessionWorker), + (&["prx", "completions", "bash"], cli_tracing::CliCommand::Completions), + #[cfg(feature = "test-mock")] + ( + &[ + "prx", + "__mailbox-harness", + "accept-adopt", + "--workspace", + "prx_workspace", + ], + cli_tracing::CliCommand::SessionWorker, + ), + ]; + #[cfg(feature = "wasm-plugins")] + let plugin_case: &[(&[&str], cli_tracing::CliCommand)] = + &[(&["prx", "plugin", "list"], cli_tracing::CliCommand::Plugin)]; + #[cfg(not(feature = "wasm-plugins"))] + let plugin_case: &[(&[&str], cli_tracing::CliCommand)] = &[]; + + let mut seen = Vec::new(); + for (argv, want) in cases.iter().chain(plugin_case.iter()) { + let cli = Cli::try_parse_from(*argv).unwrap_or_else(|error| panic!("{argv:?}: {error}")); + assert_eq!(cli_tracing_command(&cli.command), *want, "{argv:?}"); + seen.push(commands_coverage_tag(&cli.command)); + } + let mut expected_tags = vec![ + "Init", + "Go", + "Chat", + "ChatMessage", + "Gateway", + "Daemon", + "Service", + "Doctor", + "Status", + "Tasks", + "Memory", + "Evolution", + "Cost", + "Fitness", + "Cron", + "Xin", + "Causal", + "DecisionEngine", + "Models", + "Providers", + "Routes", + "ChannelStart", + "ChannelManage", + "Integrations", + "Skills", + "Migrate", + "Auth", + "Approval", + "Audit", + "Config", + "SessionWorker", + "Completions", + ]; + #[cfg(feature = "wasm-plugins")] + expected_tags.push("Plugin"); + #[cfg(feature = "test-mock")] + expected_tags.push("MailboxHarness"); + expected_tags.sort_unstable(); + seen.sort_unstable(); + assert_eq!(seen, expected_tags); + } + + /// E-4 (RED before PMM-E): a secret on the command line draws a warning + /// that names the alternative and never repeats the secret; the stdin + /// and environment alternatives draw none. + #[test] + fn a_secret_argument_draws_a_warning_naming_the_alternative() { + const SENTINEL: &str = "sk-pmme-warning-sentinel"; + for (args, flag, alternative) in [ + (vec!["prx", "init", "--api-key", SENTINEL], "--api-key", "--from-stdin"), + (vec!["prx", "go", "-k", SENTINEL], "-k/--key", "--from-stdin"), + ( + vec![ + "prx", + "auth", + "paste-token", + "--provider", + "anthropic", + "--token", + SENTINEL, + ], + "--token", + "--from-stdin", + ), + ] { + let cli = Cli::try_parse_from(&args).unwrap_or_else(|error| panic!("{args:?}: {error}")); + let warning = argv_secret_warning(&cli.command).unwrap_or_else(|| panic!("{args:?}: no warning")); + assert!(warning.contains(flag) && warning.contains(alternative), "{warning}"); + assert!(!warning.contains(SENTINEL), "{warning}"); + } + for args in [ + vec!["prx", "init", "--from-stdin"], + vec!["prx", "init", "--from-env", "OPENROUTER_API_KEY"], + vec!["prx", "go", "--from-env", "ANTHROPIC_API_KEY"], + vec!["prx", "go", "--from-stdin", "--message", "hi"], + vec!["prx", "auth", "paste-token", "--provider", "anthropic", "--from-stdin"], + vec!["prx", "auth", "paste-token", "--provider", "anthropic"], + ] { + let cli = Cli::try_parse_from(&args).unwrap_or_else(|error| panic!("{args:?}: {error}")); + assert_eq!(argv_secret_warning(&cli.command), None, "{args:?}"); + } + // The argument and its alternative are exclusive. + assert!(Cli::try_parse_from(["prx", "init", "--api-key", SENTINEL, "--from-stdin"]).is_err()); + assert!(Cli::try_parse_from(["prx", "go", "-k", SENTINEL, "--from-env", "X"]).is_err()); + } + + /// `prx tasks send` must repeat the server's outcome, not upgrade it. + /// + /// The endpoint tags a success `queued` because it can only see that the + /// message reached the target's steering queue. This renderer used to print + /// "Delivered to ..." unconditionally and never printed the outcome at all, + /// so an operator steering a run that never drains its queue was told the + /// instruction had landed. + /// + /// MUTATION GUARD: restore a fixed "Delivered" headline in + /// `render_task_message` and the first two assertions fail. + #[test] + fn a_sent_message_is_reported_as_the_server_tagged_it() { + let report = openprx::runtime::tasks_cli::MessageReport { + requested: "w3".to_string(), + id: "w3".to_string(), + run_id: Some("d9671848-1111-2222-3333-444444444444".to_string()), + kind: "sub_agent".to_string(), + name: "sub-agent".to_string(), + outcome: "queued".to_string(), + note: Some("the message is on the target's steering queue".to_string()), + }; + + let rendered = render_task_message(&report); + assert!( + !rendered.to_lowercase().contains("deliver"), + "the CLI must not claim a delivery the server did not report: {rendered}" + ); + assert!( + rendered.contains("outcome: queued"), + "the server's own tag must be on screen: {rendered}" + ); + assert!(rendered.contains("w3"), "{rendered}"); + assert!( + rendered.contains("run_id: d9671848-1111-2222-3333-444444444444"), + "{rendered}" + ); + assert!( + rendered.contains("the message is on the target's steering queue"), + "the server's note explains why queued is not read: {rendered}" + ); + } + + /// A gateway that sends no note gets no invented one. + #[test] + fn a_missing_note_is_not_replaced_by_a_client_side_guess() { + let report = openprx::runtime::tasks_cli::MessageReport { + requested: "w3".to_string(), + id: "w3".to_string(), + run_id: None, + kind: "sub_agent".to_string(), + name: "sub-agent".to_string(), + outcome: "queued".to_string(), + note: None, + }; + + let rendered = render_task_message(&report); + assert_eq!( + rendered, "Message to w3 [sub_agent] sub-agent (run_id: -) — outcome: queued", + "with no note the renderer prints one line and nothing else" + ); + } + + fn listed(kind: &str, name: &str, steerable: bool) -> openprx::runtime::tasks_cli::WorkItem { + openprx::runtime::tasks_cli::WorkItem { + id: "w2".to_string(), + kind: kind.to_string(), + name: name.to_string(), + state: "running".to_string(), + parent: None, + run_id: None, + batch_id: None, + elapsed_secs: 3, + pid: None, + pgid: None, + steerable, + } + } + + /// The listing has to separate the rows that accept a message from the ones + /// that only look like they do. + /// + /// The KIND column cannot do it: a detached gateway job is registered as + /// `sub_agent` and has no steering channel at all, so an operator reading + /// the kind as permission sends a message, gets a 409, and has no way to + /// tell a wrong address from an unsteerable target. Both rows below are + /// `sub_agent`; only one of them can be steered. + /// + /// MUTATION GUARD: drop the `(steerable)` mark from `work_item_line` and + /// the first assertion fails. + #[test] + fn a_steerable_row_is_marked_and_a_look_alike_is_not() { + let run = work_item_line(&listed("sub_agent", "researcher", true), false); + assert!( + run.contains("(steerable)"), + "a run that takes messages must say so: {run}" + ); + + let job = work_item_line(&listed("sub_agent", "gateway:webhook:anonymous", false), false); + assert!( + !job.contains("steerable"), + "a gateway job is listed sub_agent but takes no messages, so it must not be marked: {job}" + ); + assert!(job.contains("sub_agent"), "the kind is still reported as it is: {job}"); + } + + #[test] + fn init_help_includes_model_flag() { + let cmd = Cli::command(); + let init = cmd + .get_subcommands() + .find(|subcommand| subcommand.get_name() == "init") + .expect("init subcommand must exist"); + + let has_model_flag = init + .get_arguments() + .any(|arg| arg.get_id().as_str() == "model" && arg.get_long() == Some("model")); + + assert!( + has_model_flag, + "init help should include --model for quick setup overrides" + ); + } + + #[test] + fn init_cli_accepts_model_provider_and_api_key_in_quick_mode() { + let cli = Cli::try_parse_from([ + "prx", + "init", + "--provider", + "openrouter", + "--model", + "custom-model-946", + "--api-key", + "sk-issue946", + ]) + .expect("quick init invocation should parse"); + + match cli.command { + Commands::Init { + interactive, + channels_only, + api_key, + provider, + model, + .. + } => { + assert!(!interactive); + assert!(!channels_only); + assert_eq!(provider.as_deref(), Some("openrouter")); + assert_eq!(model.as_deref(), Some("custom-model-946")); + assert_eq!(api_key.as_deref(), Some("sk-issue946")); + } + other => panic!("expected init command, got {other:?}"), + } + } + + #[test] + fn chat_continue_flag_parses_as_resume_last_intent() { + let cli = Cli::try_parse_from(["prx", "chat", "--continue"]).expect("chat --continue should parse"); + match cli.command { + Commands::Chat { + continue_last, session, .. + } => { + assert!(continue_last); + assert!(session.is_none()); + } + other => panic!("expected chat command, got {other:?}"), + } + } + + #[test] + fn chat_explicit_session_can_coexist_with_continue() { + let cli = Cli::try_parse_from(["prx", "chat", "--continue", "--session", "abc"]) + .expect("explicit --session with --continue should parse"); + match cli.command { + Commands::Chat { + continue_last, session, .. + } => { + assert!(continue_last); + assert_eq!(session.as_deref(), Some("abc")); + } + other => panic!("expected chat command, got {other:?}"), + } + } + + #[test] + fn chat_message_parses_short_flag_save_and_workdir() { + let root = tempfile::tempdir().expect("test: root"); + let workdir = root.path().to_str().expect("test: root path"); + let cli = Cli::try_parse_from([ + "prx", + "chat", + "-q", + "/compact", + "--save", + "--workdir", + workdir, + "-m", + "m1", + ]) + .expect("test: chat one-shot flags"); + match cli.command { + Commands::Chat { + message, + save, + workdir: Some(parsed), + model, + .. + } => { + assert_eq!(message.as_deref(), Some("/compact")); + assert!(save); + assert_eq!(model.as_deref(), Some("m1")); + assert_eq!(parsed, root.path().canonicalize().expect("test: canonical root")); + } + other => panic!("expected chat command, got {other:?}"), + } + for argv in [ + &["prx", "chat", "--save"][..], + &["prx", "chat", "--message", "x", "--list-sessions"], + &["prx", "chat", "--workdir", "relative"], + ] { + let error = Cli::try_parse_from(argv).expect_err("test: invalid one-shot usage"); + assert_eq!(error.exit_code(), 2, "test: clap usage exit for {argv:?}"); + } + } + + #[test] + fn chat_workdir_is_canonical_and_requires_an_existing_absolute_directory() { + let root = tempfile::tempdir().expect("test: root"); + let alias = root.path().join("."); + let cli = Cli::try_parse_from(["prx", "chat", "--workdir", alias.to_str().expect("test: root path")]) + .expect("test: canonical workdir"); + assert!( + matches!(cli.command, Commands::Chat { workdir: Some(ref workdir), .. } if *workdir == root.path().canonicalize().expect("test: canonical root")), + "test: parsed root canonicalized" + ); + for path in [ + "relative", + root.path().join("missing").to_str().expect("test: missing path"), + ] { + let error = Cli::try_parse_from(["prx", "chat", "--workdir", path]).expect_err("test: invalid root"); + assert_eq!(error.exit_code(), 2, "test: clap usage exit"); + } + } + + #[test] + fn prx_causal_parses_any_arguments_and_decision_engine_replaces_it() { + for args in [ + &["prx", "causal"][..], + &["prx", "causal", "status", "--json"], + &["prx", "causal", "config", "set", "backend", "--kind", "builtin"], + ] { + let cli = Cli::try_parse_from(args).expect("retired causal command still parses"); + assert!(matches!(cli.command, Commands::Causal { .. }), "{args:?}"); + } + let cli = Cli::try_parse_from(["prx", "decision-engine", "status", "--json"]).expect("status parses"); + assert!(matches!( + cli.command, + Commands::DecisionEngine { + json: true, + command: openprx::decision_engine_cli::DecisionEngineCommands::Status, + } + )); + let cli = Cli::try_parse_from(["prx", "decision-engine", "config", "set", "enabled", "true", "--yes"]) + .expect("config set parses"); + assert!(matches!( + cli.command, + Commands::DecisionEngine { + command: openprx::decision_engine_cli::DecisionEngineCommands::Config { .. }, + .. + } + )); + assert!( + Cli::try_parse_from([ + "prx", + "decision-engine", + "config", + "set", + "enabled", + "true", + "--confirm-high-risk", + "r" + ]) + .is_err(), + "a confirmation without --yes" + ); + } + + /// No `prx decision-engine` subcommand takes a secret on the command line. + #[test] + fn no_decision_engine_subcommand_accepts_a_secret_argument() { + fn check(command: &clap::Command, path: &str, violations: &mut Vec) { + for arg in command.get_arguments() { + let names = std::iter::once(arg.get_id().as_str().to_string()) + .chain(arg.get_long().map(str::to_string)) + .map(|name| name.to_ascii_lowercase()); + for name in names { + if ["key", "token", "secret", "password", "credential", "bearer"] + .iter() + .any(|word| name.contains(word)) + && name != "key" + { + violations.push(format!("{path} --{name}")); + } + } + } + for sub in command.get_subcommands() { + check(sub, &format!("{path} {}", sub.get_name()), violations); + } + } + let root = Cli::command(); + let engine = root + .find_subcommand("decision-engine") + .expect("prx decision-engine exists"); + let mut violations = Vec::new(); + check(engine, "decision-engine", &mut violations); + assert!(violations.is_empty(), "secret-shaped arguments: {violations:?}"); + } + + #[test] + fn completions_cli_parses_supported_shells() { + for shell in ["bash", "fish", "zsh", "powershell", "elvish"] { + let cli = Cli::try_parse_from(["prx", "completions", shell]).expect("completions invocation should parse"); + match cli.command { + Commands::Completions { .. } => {} + other => panic!("expected completions command, got {other:?}"), + } + } + } + + #[test] + fn config_show_cli_parses_default_and_json_format() { + let cli = Cli::try_parse_from(["prx", "config", "show"]).expect("config show should parse"); + match cli.command { + Commands::Config { + config_command: ConfigCommands::Show { format }, + } => assert_eq!(format, ConfigShowFormat::Toml), + other => panic!("expected config show command, got {other:?}"), + } + + let cli = Cli::try_parse_from(["prx", "config", "show", "--format", "json"]) + .expect("config show --format json should parse"); + match cli.command { + Commands::Config { + config_command: ConfigCommands::Show { format }, + } => assert_eq!(format, ConfigShowFormat::Json), + other => panic!("expected config show json command, got {other:?}"), + } + } + + #[test] + fn memory_reindex_cli_parses() { + let cli = Cli::try_parse_from(["prx", "memory", "reindex"]).expect("memory reindex should parse"); + match cli.command { + Commands::Memory { + memory_command: MemoryCommands::Reindex { json }, + } => assert!(!json), + other => panic!("expected memory reindex command, got {other:?}"), + } + + let cli = + Cli::try_parse_from(["prx", "memory", "reindex", "--json"]).expect("memory reindex --json should parse"); + match cli.command { + Commands::Memory { + memory_command: MemoryCommands::Reindex { json }, + } => assert!(json), + other => panic!("expected memory reindex command, got {other:?}"), + } + } + + #[test] + fn approval_revoke_cli_parses() { + let cli = Cli::try_parse_from([ + "prx", + "approval", + "revoke", + "grant-test", + "--reason", + "operator requested", + ]) + .expect("approval revoke should parse"); + match cli.command { + Commands::Approval { + approval_command: ApprovalCommands::Revoke { grant_id, reason }, + } => { + assert_eq!(grant_id, "grant-test"); + assert_eq!(reason, "operator requested"); + } + other => panic!("expected approval revoke command, got {other:?}"), + } + } + + #[test] + fn eu_ai_act_audit_cli_parses_json_and_output() { + let cli = Cli::try_parse_from([ + "prx", + "audit", + "attest-eu-ai-act", + "--json", + "--output", + "/tmp/eu-ai-act-test.json", + ]) + .expect("eu ai act attestation should parse"); + + match cli.command { + Commands::Audit { + audit_command: + AuditCommands::AttestEuAiAct { + json, + format, + output, + verbose, + fail_on, + }, + } => { + assert!(json); + assert_eq!(format, AuditOutputFormat::Markdown); + assert_eq!( + output.as_deref(), + Some(std::path::Path::new("/tmp/eu-ai-act-test.json")) + ); + assert!(!verbose); + assert_eq!(fail_on, None); + } + other => panic!("expected audit attest-eu-ai-act command, got {other:?}"), + } + } + + #[test] + fn eu_declaration_cli_requires_explicit_signature_reference() { + let cli = Cli::try_parse_from([ + "prx", + "audit", + "generate-eu-declaration", + "--output", + "declaration.json", + "--signature-reference", + "external:receipt-1", + ]) + .expect("declaration generator should parse"); + match cli.command { + Commands::Audit { + audit_command: + AuditCommands::GenerateEuDeclaration { + output, + signature_reference, + }, + } => { + assert_eq!(output.as_deref(), Some(std::path::Path::new("declaration.json"))); + assert_eq!(signature_reference, "external:receipt-1"); + } + other => panic!("expected declaration generator, got {other:?}"), + } + assert!( + Cli::try_parse_from([ + "prx", + "audit", + "generate-eu-declaration", + "--output", + "declaration.json", + ]) + .is_err() + ); + } + + #[test] + fn incident_audit_cli_parses_mutating_and_export_commands() { + let create = Cli::try_parse_from(["prx", "audit", "incident-create", "--input", "incident.json"]) + .expect("incident create should parse"); + assert!(matches!( + create.command, + Commands::Audit { + audit_command: AuditCommands::IncidentCreate { input } + } if input == std::path::Path::new("incident.json") + )); + + let export = Cli::try_parse_from([ + "prx", + "audit", + "incident-export", + "incident-7", + "--output", + "incident-7-export.json", + ]) + .expect("incident export should parse"); + assert!(matches!( + export.command, + Commands::Audit { + audit_command: AuditCommands::IncidentExport { + incident_id, + output, + } + } if incident_id == "incident-7" && output == std::path::Path::new("incident-7-export.json") + )); + } + + /// A default config whose files live in `dir`. The binary's tests link the + /// production library, where the default paths name the real + /// `~/.openprx`, and the attestation reads the workspace (D-070). + fn scratch_config(dir: &std::path::Path) -> Config { + Config { + config_path: dir.join("config.toml"), + workspace_dir: dir.join("workspace"), + ..Config::default() + } + } + + #[test] + fn declaration_attestation_respects_operator_classification() { + let temp = tempfile::TempDir::new().unwrap(); + let mut config = scratch_config(temp.path()); + let c02_status = |config: &Config| { + build_eu_ai_act_attestation(config) + .checks + .into_iter() + .find(|check| check.id == "C02") + .expect("C02 control") + .status + }; + assert_eq!(c02_status(&config), ControlStatus::Unknown); + + config.compliance.eu_ai_act.classification.status = config::schema::EuAiActRiskClassification::NotHighRisk; + config.compliance.eu_ai_act.classification.owner = Some("legal-owner".to_string()); + config.compliance.eu_ai_act.classification.assessed_at = Some("2026-07-18".to_string()); + assert_eq!(c02_status(&config), ControlStatus::NotApplicable); + + config.compliance.eu_ai_act.classification.status = config::schema::EuAiActRiskClassification::HighRisk; + assert_eq!(c02_status(&config), ControlStatus::Fail); + } + + #[test] + fn incident_attestation_requires_and_verifies_durable_store_for_high_risk() { + let temp = tempfile::TempDir::new().unwrap(); + let store_path = temp.path().join("article-73.sqlite3"); + let mut config = scratch_config(temp.path()); + config.compliance.eu_ai_act.classification.status = config::schema::EuAiActRiskClassification::HighRisk; + + let m04_status = |config: &Config| { + build_eu_ai_act_attestation(config) + .checks + .into_iter() + .find(|check| check.id == "M04") + .expect("M04 control") + .status + }; + assert_eq!(m04_status(&config), ControlStatus::Fail); + + config.compliance.eu_ai_act.incident_store_path = Some(store_path.clone()); + openprx::compliance::incident::IncidentStore::open(&store_path).unwrap(); + assert_eq!(m04_status(&config), ControlStatus::Pass); + } + + #[test] + fn eu_ai_act_attestation_has_required_check_counts() { + let temp = tempfile::TempDir::new().unwrap(); + let attestation = build_eu_ai_act_attestation(&scratch_config(temp.path())); + + assert_eq!(attestation.total_checks, 24); + assert_eq!(attestation.checks.len(), 24); + assert_eq!( + attestation.total_checks, + attestation.passed_count + + attestation.warning_count + + attestation.failed_count + + attestation.unknown_count + + attestation.not_applicable_count + ); + + let json = render_eu_ai_act_attestation_json(&attestation).expect("attestation should serialize"); + let value: serde_json::Value = serde_json::from_str(&json).expect("attestation json should parse"); + assert_eq!(value.get("total_checks").and_then(serde_json::Value::as_u64), Some(24)); + assert_eq!( + value.get("report_type").and_then(serde_json::Value::as_str), + Some("EU AI Act implementation attestation") + ); + let c02 = value + .get("checks") + .and_then(serde_json::Value::as_array) + .and_then(|checks| { + checks + .iter() + .find(|check| check.get("id").and_then(serde_json::Value::as_str) == Some("C02")) + }) + .expect("C02 control should exist"); + assert_eq!( + c02.get("framework_reference").and_then(serde_json::Value::as_str), + Some("Article 47 and Annex V") + ); + } + + #[test] + fn eu_ai_act_audit_cli_parses_fail_on_and_gate_semantics() { + let cli = Cli::try_parse_from(["prx", "audit", "attest-eu-ai-act", "--json", "--fail-on", "warning"]) + .expect("strict attestation gate should parse"); + let Commands::Audit { + audit_command: AuditCommands::AttestEuAiAct { fail_on, .. }, + } = cli.command + else { + panic!("expected audit command"); + }; + assert_eq!(fail_on, Some(AuditFailOn::Warning)); + + let temp = tempfile::TempDir::new().unwrap(); + let attestation = build_eu_ai_act_attestation(&scratch_config(temp.path())); + assert!(!attestation_fails_gate(&attestation, AuditFailOn::Fail)); + assert!(attestation_fails_gate(&attestation, AuditFailOn::Warning)); + } + + #[test] + fn doctor_memory_cli_parses() { + let cli = Cli::try_parse_from(["prx", "doctor", "memory"]).expect("doctor memory should parse"); + match cli.command { + Commands::Doctor { + doctor_command: Some(DoctorCommands::Memory), + } => {} + other => panic!("expected doctor memory command, got {other:?}"), + } + } + + #[test] + fn doctor_runtime_cli_parses() { + let cli = Cli::try_parse_from(["prx", "doctor", "runtime"]).expect("doctor runtime should parse"); + match cli.command { + Commands::Doctor { + doctor_command: Some(DoctorCommands::Runtime), + } => {} + other => panic!("expected doctor runtime command, got {other:?}"), + } + } + + #[test] + fn config_show_redacts_sensitive_toml_values() { + let mut value = toml::Value::Table(toml::toml! { + default_provider = "kimi-code" + api_key = "enc2:encrypted-root" + + [storage.provider.config] + db_url = "postgres://user:secret@example/prx" + + [agents.worker] + api_key = "sk-agent" + model = "kimi-k2" + + [channels.slack] + bot_token = "xoxb-token" + allowed_users = ["alice"] + + [nested] + api_keys = ["sk-one", "sk-two"] + credential = { username = "user", password = "pass" } + }); + + config::secret_paths::redact(&mut value); + + let root = value.as_table().expect("redacted value should remain a table"); + assert_eq!(root.get("api_key").and_then(toml::Value::as_str), Some("***")); + assert_eq!( + root.get("default_provider").and_then(toml::Value::as_str), + Some("kimi-code") + ); + + let nested = root + .get("nested") + .and_then(toml::Value::as_table) + .expect("nested table should remain"); + assert_eq!( + nested + .get("api_keys") + .and_then(toml::Value::as_array) + .expect("api_keys should remain an array") + .iter() + .filter_map(toml::Value::as_str) + .collect::>(), + vec!["***", "***"] + ); + + let rendered = toml::to_string_pretty(&value).expect("redacted config should serialize"); + assert!(rendered.contains("default_provider = \"kimi-code\"")); + assert!(rendered.contains("model = \"kimi-k2\"")); + assert!(rendered.contains("allowed_users = [\"alice\"]")); + assert!(rendered.contains("api_key = \"***\"")); + assert!(rendered.contains("db_url = \"***\"")); + assert!(rendered.contains("bot_token = \"***\"")); + assert!(!rendered.contains("enc2:encrypted-root")); + assert!(!rendered.contains("postgres://user:secret@example/prx")); + assert!(!rendered.contains("sk-agent")); + assert!(!rendered.contains("xoxb-token")); + assert!(!rendered.contains("sk-one")); + assert!(!rendered.contains("password = \"pass\"")); + } + + #[test] + fn models_and_integrations_accept_bare_and_list_commands() { + let cli = Cli::try_parse_from(["prx", "models"]).expect("bare models should parse"); + match cli.command { + Commands::Models { model_command } => assert!(model_command.is_none()), + other => panic!("expected bare models command, got {other:?}"), + } + + let cli = + Cli::try_parse_from(["prx", "models", "list", "--provider", "openai"]).expect("models list should parse"); + match cli.command { + Commands::Models { + model_command: Some(ModelCommands::List { provider, .. }), + } => assert_eq!(provider.as_deref(), Some("openai")), + other => panic!("expected models list command, got {other:?}"), + } + + let cli = Cli::try_parse_from(["prx", "integrations"]).expect("bare integrations should parse"); + match cli.command { + Commands::Integrations { integration_command } => assert!(integration_command.is_none()), + other => panic!("expected bare integrations command, got {other:?}"), + } + + let cli = Cli::try_parse_from(["prx", "integrations", "list"]).expect("integrations list should parse"); + match cli.command { + Commands::Integrations { + integration_command: Some(IntegrationCommands::List), + } => {} + other => panic!("expected integrations list command, got {other:?}"), + } + } + + #[test] + fn migrate_plan_uses_the_library_owned_dto() { + let cli = Cli::try_parse_from(["prx", "migrate", "plan", "--target-version", "7"]) + .expect("migrate plan should parse"); + match cli.command { + Commands::Migrate { + migrate_command: MigrateCommands::Plan { target_version }, + } => assert_eq!(target_version, "7"), + other => panic!("expected migrate plan command, got {other:?}"), + } + } + + #[test] + fn xin_task_and_goal_step_commands_parse() { + let cli = Cli::try_parse_from([ + "prx", + "xin", + "add", + "health-watch", + "inspect health", + "--recurring", + "--interval-secs", + "300", + ]) + .expect("xin add should parse"); + assert!(matches!( + cli.command, + Commands::Xin { + xin_command: XinCommands::Add { + recurring: true, + interval_secs: 300, + .. + } + } + )); + + let cli = Cli::try_parse_from([ + "prx", + "xin", + "steps", + "add", + "goal-1", + "verify", + "verify artifacts", + "--sequence", + "2", + ]) + .expect("xin steps add should parse"); + assert!(matches!( + cli.command, + Commands::Xin { + xin_command: XinCommands::Steps { + step_command: openprx::XinStepCommands::Add { sequence: Some(2), .. } + } + } + )); + } + + #[test] + fn completion_generation_mentions_binary_name() -> Result<()> { + const SHELLS: [CompletionShell; 5] = [ + CompletionShell::Bash, + CompletionShell::Fish, + CompletionShell::Zsh, + CompletionShell::PowerShell, + CompletionShell::Elvish, + ]; + for shell in SHELLS { + let mut output = Vec::new(); + write_shell_completion(shell, &mut output) + .with_context(|| format!("test: generate {shell:?} completion for the complete CLI tree"))?; + let script = String::from_utf8(output).context("test: completion output must be UTF-8")?; + assert!(script.contains("prx"), "{shell:?} completion lost the binary name"); + } + Ok(()) + } +} diff --git a/src/memory/sqlite/child_turns.rs b/src/memory/sqlite/child_turns.rs index dc4b19a58..b6b45f71a 100644 --- a/src/memory/sqlite/child_turns.rs +++ b/src/memory/sqlite/child_turns.rs @@ -126,6 +126,7 @@ pub(super) fn history(memory: &SqliteMemory, record: &ChildSessionRecord) -> any AND EXISTS(SELECT 1 FROM agent_incarnations i WHERE i.workspace_id=s.workspace_id AND i.owner_id=s.owner_id AND i.agent_key=s.agent_key AND i.incarnation=s.incarnation AND i.state='active') AND NOT EXISTS(SELECT 1 FROM agent_erase_fences f WHERE f.scope_id=s.scope_id) AND e.id>?4 AND e.role IN('user','assistant','tool') AND e.event_type='message.created' + AND NOT EXISTS(SELECT 1 FROM message_events p WHERE p.event_id=e.causation_event_id AND p.workspace_id=e.workspace_id AND p.owner_id=e.owner_id AND p.session_key=e.session_key AND p.source='prx_mailbox' AND e.role='user') AND NOT EXISTS(SELECT 1 FROM message_events p WHERE p.workspace_id=e.workspace_id AND p.owner_id=e.owner_id AND p.id`, incarnation). Main: -/// unstamped rows and rows of a Main scope in the workspace. `placeholder` -/// yields the next bind marker (`?N` or `?`); `column` is a constant. -pub(crate) fn partition_conjunct( - column: &str, - partition: Option<&crate::memory::AgentPartition>, - mut placeholder: impl FnMut() -> String, -) -> (String, Vec) { - let Some(partition) = partition else { - return (String::new(), Vec::new()); - }; - match &partition.key { - PartitionKey::Named { name, incarnation } => { - let (workspace, owner, key, generation) = (placeholder(), placeholder(), placeholder(), placeholder()); - ( - format!( - " AND ({column} IN (SELECT scope_id FROM agent_scopes WHERE workspace_id={workspace} AND owner_id={owner} AND agent_key={key} AND incarnation={generation}))" - ), - vec![ - partition.workspace_id.clone(), - partition.owner_id.clone(), - format!("n:{}", name.as_str()), - incarnation.to_string(), - ], - ) - } - PartitionKey::Main => { - let workspace = placeholder(); - ( - format!( - " AND ({column} IS NULL OR {column} IN (SELECT scope_id FROM agent_scopes WHERE workspace_id={workspace} AND agent_key='m'))" - ), - vec![partition.workspace_id.clone()], - ) - } - } -} - -/// Numbered bind markers `?first`, `?first+1`, ... -pub(crate) fn numbered_placeholders(first: usize) -> impl FnMut() -> String { - let mut next = first; - move || { - let marker = format!("?{next}"); - next += 1; - marker - } -} - -/// [`partition_conjunct`] on `ma_scope_id` for the principal's partition. -pub(crate) fn agent_partition_clause(principal: &MemoryPrincipal, first_placeholder: usize) -> (String, Vec) { - partition_conjunct( - MA_SCOPE_COLUMN, - principal.agent_partition.as_ref(), - numbered_placeholders(first_placeholder), - ) -} - -pub(crate) const fn conversation_turns_ordering(recorded_order: bool) -> &'static str { - if recorded_order { - "julianday(timestamp) DESC, COALESCE((SELECT event.id FROM message_events event WHERE event.event_id = conversation_turns.message_event_id), id) DESC, id DESC" - } else { - "id DESC" - } -} - -/// The seventh column says whether the row is a deleted tombstone -/// (AC-1b2b). Only a caller-keyed history listing (`tombstones`) reads -/// tombstones; every other reader, model context included, skips them. -pub(crate) fn conversation_turns_select_sql( - session_fragment: &str, - partition_sql: &str, - ordering: &str, - tombstones: bool, -) -> String { - let deleted_sql = if tombstones { - "" - } else { - "\n AND deleted_at IS NULL" - }; - format!( - "SELECT id, session_key, role, content, timestamp, message_id, deleted_at IS NOT NULL - FROM conversation_turns - WHERE {session_fragment} - AND ( - ?4 = 'system:*' - OR - owner_id = ?4 - OR (?5 = 1 AND (owner_id IS NULL OR owner_id = 'legacy:' || session_key)) - ){partition_sql}{deleted_sql} - ORDER BY {ordering} - LIMIT ?2 OFFSET ?3" - ) -} - -pub(crate) fn message_events_since_select_sql( - session_fragment: &str, - owner_fragment: &str, - owner_required_fragment: &str, - partition_sql: &str, -) -> String { - format!( - "SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, - parent_session_key, run_id, parent_run_id, agent_id, persona_id, - sender, recipient, role, event_type, source_ref_json, subject_ref_json, - goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, - content, content_hash, raw_payload_json, visibility, created_at, updated_at - FROM message_events - WHERE id > ?1 - AND ( - visibility = 'global' - OR ( - workspace_id = ?2 - AND ( - visibility = 'workspace'{owner_fragment} - OR (visibility = 'agent' AND ( - (?3 IS NOT NULL AND agent_id = ?3) - OR (?4 IS NOT NULL AND persona_id = ?4) - )) - OR (visibility = 'session' AND {session_fragment}{owner_fragment}) - OR (visibility = 'private' AND ( - (?3 IS NOT NULL AND agent_id = ?3) - OR (?4 IS NOT NULL AND persona_id = ?4) - OR (?6 IS NOT NULL AND sender = ?6) - ){owner_required_fragment}) - OR (visibility = 'system' AND ?7) - ) - ) - ){partition_sql} - ORDER BY id ASC - LIMIT ?8" - ) -} - -pub(crate) struct MessageEventsSinceStatement { - pub sql: String, - pub partition_values: Vec, - pub legacy_session_keys: Vec, - pub bind_owner: bool, -} - -/// Production conversation-turns statement, including the partition conjunct. -/// Returns `(sql, partition_values, legacy_session_keys)`. -#[cfg(test)] -pub(crate) fn conversation_turns_statement( - principal: &MemoryPrincipal, - session_key: &str, - recorded_order: bool, -) -> (String, Vec, Vec) { - conversation_turns_statement_with(principal, session_key, recorded_order, false) -} - -/// [`conversation_turns_statement`], optionally reading deleted tombstones. -fn conversation_turns_statement_with( - principal: &MemoryPrincipal, - session_key: &str, - recorded_order: bool, - tombstones: bool, -) -> (String, Vec, Vec) { - let legacy_session_keys: Vec = principal - .legacy_session_key - .as_deref() - .map(str::trim) - .filter(|key| !key.is_empty() && *key != session_key.trim()) - .map(|key| vec![key.to_string()]) - .unwrap_or_default(); - let mut session_indices = vec![1usize]; - for offset_idx in 0..legacy_session_keys.len() { - session_indices.push(6 + offset_idx); - } - let session_fragment = - crate::memory::session_predicate::session_key_match_fragment(super::SQLITE_DIALECT, &session_indices); - let (partition_sql, partition_values) = agent_partition_clause(principal, 6 + legacy_session_keys.len()); - ( - conversation_turns_select_sql( - &session_fragment.sql, - &partition_sql, - conversation_turns_ordering(recorded_order), - tombstones, - ), - partition_values, - legacy_session_keys, - ) -} - -use super::ingress_recovery; -use super::{SQLITE_DIALECT, SqliteMemory}; -use crate::memory::ingress_recovery::AtomicIngressMutation; - -impl SqliteMemory { - pub(super) async fn list_conversation_turns_ordered( - &self, - principal: &MemoryPrincipal, - session_key: &str, - limit: usize, - offset: usize, - recorded_order: bool, - ) -> anyhow::Result> { - Ok(self - .conversation_turns_page(principal, session_key, limit, offset, recorded_order, false) - .await? - .into_iter() - .map(|row| row.turn) - .collect()) - } - - /// A Console history page in event-time order with deleted tombstones - /// (AC-1b2b): the caller-keyed history listing. - pub(super) async fn list_rf_history_turns_impl( - &self, - principal: &MemoryPrincipal, - session_key: &str, - limit: usize, - offset: usize, - ) -> anyhow::Result> { - self.conversation_turns_page(principal, session_key, limit, offset, true, true) - .await - } - - async fn conversation_turns_page( - &self, - principal: &MemoryPrincipal, - session_key: &str, - limit: usize, - offset: usize, - recorded_order: bool, - tombstones: bool, - ) -> anyhow::Result> { - let pool = self.pool.clone(); - let owner_id = principal - .owner_id - .as_deref() - .filter(|owner| !owner.trim().is_empty()) - .map(str::to_string); - let session_key = session_key.to_string(); - let limit = Self::sanitize_conversation_limit(limit); - let offset = Self::sanitize_conversation_offset(offset); - let legacy_visible = 1_i64; - // D4 read-merge: the explicit `session_key` arg is the canonical key - // (bound at `?1`); the principal may carry a distinct legacy key bound - // at trailing placeholders starting at `?6`. With no legacy key the - // predicate degrades to the byte-identical `session_key = ?1`. - let (sql, partition_values, legacy_session_keys) = - conversation_turns_statement_with(principal, &session_key, recorded_order, tombstones); - - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { - let reader = pool.read()?; - let conn = reader.connection()?; - let mut stmt = conn.prepare(&sql)?; - let mut bind: Vec<&dyn rusqlite::types::ToSql> = - vec![&session_key, &limit, &offset, &owner_id, &legacy_visible]; - for key in &legacy_session_keys { - bind.push(key); - } - for value in &partition_values { - bind.push(value); - } - let rows = stmt.query_map(bind.as_slice(), |row| { - Ok(crate::memory::RfHistoryTurn { - turn: ConversationTurn { - id: row.get(0)?, - session_key: row.get(1)?, - role: row.get(2)?, - content: row.get(3)?, - timestamp: row.get(4)?, - message_id: row.get(5)?, - }, - deleted: row.get(6)?, - }) - })?; - - let mut turns = Vec::new(); - for row in rows { - turns.push(row?); - } - turns.reverse(); - Ok(turns) - }) - .await? - } - - pub(super) async fn project_console_message_with_deadline( - &self, - event: &MessageEvent, - deadline: Option, - ) -> anyhow::Result<()> { - if let Some(deadline) = deadline { - crate::memory::ingress_recovery::remaining(deadline)?; - ingress_recovery::validate_event_bounds(event)?; - } - event.validate_console_projection()?; - let repair_owner = deadline.map(|_| self.repair_owner(&event.workspace_id)).transpose()?; - let event = event.clone(); - let pool = self.pool.clone(); - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result<()> { - let mut write = match deadline { Some(deadline) => pool.write_until(deadline)?, None => pool.write() }; - let conn = ingress_recovery::DeadlineConn::wrap(&mut write, deadline)?; - let tx = rusqlite::Transaction::new_unchecked(&conn, TransactionBehavior::Immediate)?; - if let (Some(owner), Some(deadline)) = (&repair_owner, deadline) { - ingress_recovery::validate_owner(&tx, owner, &event.workspace_id, deadline)?; - ingress_recovery::check_receipt_size(&tx, &event.event_id, None, &event.workspace_id)?; - ingress_recovery::check_console_projection_size(&tx, &event.event_id)?; - } - let durable = tx.query_row( - "SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, - parent_session_key, run_id, parent_run_id, agent_id, persona_id, - sender, recipient, role, event_type, source_ref_json, subject_ref_json, - goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, - content, content_hash, raw_payload_json, visibility, created_at, updated_at - FROM message_events WHERE event_id = ?1 AND workspace_id = ?2 AND owner_id = ?3", - params![event.event_id, event.workspace_id, event.owner_id], Self::message_event_from_row, - )?; - anyhow::ensure!(serde_json::to_value(&durable)? == serde_json::to_value(&event)?, - "console projection differs from its durable event"); - let existing: Vec<(String, Option, String, String, bool)> = { - let mut stmt = tx.prepare("SELECT session_key, owner_id, role, content, deleted_at IS NOT NULL - FROM conversation_turns WHERE message_event_id = ?1 OR message_id = ?1 LIMIT 2")?; - stmt.query_map(params![event.event_id], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?, row.get(4)?)))? - .collect::>>()? - }; - if let Some(row) = existing.first() { - // A deleted message (AC-1b2b) keeps its tombstone: nothing to project. - let tombstone = row.4 && row.1 == event.owner_id; - anyhow::ensure!(existing.len() == 1 && Some(&row.0) == event.session_key.as_ref() - && (tombstone || (row.1 == event.owner_id && row.2 == event.role && row.3 == event.content)), - "console message projection conflicts with its durable event"); - if let (Some(owner), Some(deadline)) = (&repair_owner, deadline) { - ingress_recovery::validate_owner(&tx, owner, &event.workspace_id, deadline)?; - } - return Ok(()); - } - let preview = Self::conversation_preview(&event.content); - tx.execute("INSERT INTO sessions - (session_key, channel, sender, owner_id, created_at, updated_at, message_count, last_message_preview) - VALUES (?1, ?2, ?3, ?4, ?5, ?5, 1, ?6) - ON CONFLICT(session_key) DO UPDATE SET - message_count = COALESCE(sessions.message_count, 0) + 1, - channel = CASE WHEN excluded.updated_at >= sessions.updated_at THEN excluded.channel ELSE sessions.channel END, - sender = CASE WHEN excluded.updated_at >= sessions.updated_at THEN excluded.sender ELSE sessions.sender END, - owner_id = CASE WHEN excluded.updated_at >= sessions.updated_at THEN excluded.owner_id ELSE sessions.owner_id END, - last_message_preview = CASE WHEN excluded.updated_at >= sessions.updated_at THEN excluded.last_message_preview ELSE sessions.last_message_preview END, - updated_at = MAX(sessions.updated_at, excluded.updated_at)", - params![event.session_key, event.channel, event.sender, event.owner_id, event.created_at, preview])?; - tx.execute("INSERT INTO conversation_turns - (session_key, owner_id, role, content, timestamp, message_id, message_event_id, agent_id, persona_id, visibility, ma_scope_id) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6, ?7, ?8, 'session', - (SELECT ma_scope_id FROM message_events WHERE event_id = ?6))", - params![event.session_key, event.owner_id, event.role, event.content, event.created_at, - event.event_id, event.agent_id, event.persona_id])?; - if let (Some(owner), Some(deadline)) = (&repair_owner, deadline) { - ingress_recovery::validate_owner(&tx, owner, &event.workspace_id, deadline)?; - } - tx.commit()?; - if let Some(deadline) = deadline { crate::memory::ingress_recovery::remaining(deadline)?; } - Ok(()) - }).await? - } - - pub(super) async fn upsert_chat_profile_metadata_impl( - &self, - channel: &str, - chat_id: &str, - chat_kind: &str, - title: Option<&str>, - ) -> anyhow::Result<()> { - let pool = self.pool.clone(); - let channel = channel.to_string(); - let chat_id = chat_id.to_string(); - let chat_kind = chat_kind.to_string(); - let title = title.map(str::to_string); - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result<()> { - let now = Utc::now().to_rfc3339(); - let id = Uuid::new_v4().to_string(); - let conn = pool.write(); - conn.execute( - "INSERT INTO chat_profiles - (id, channel, chat_id, chat_kind, title, purpose, notes, tags, updated_by, created_at, updated_at) - VALUES (?1, ?2, ?3, ?4, ?5, NULL, NULL, '[]', 'auto', ?6, ?6) - ON CONFLICT(channel, chat_id) DO UPDATE SET - chat_kind = excluded.chat_kind, - title = CASE - WHEN excluded.title IS NOT NULL THEN excluded.title - ELSE chat_profiles.title - END, - updated_at = excluded.updated_at", - params![id, channel, chat_id, chat_kind, title, now], - )?; - Ok(()) - }) - .await? - } - - pub(super) async fn get_chat_profile_impl( - &self, - channel: &str, - chat_id: &str, - ) -> anyhow::Result> { - let pool = self.pool.clone(); - let channel = channel.to_string(); - let chat_id = chat_id.to_string(); - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { - let reader = pool.read()?; - let conn = reader.connection()?; - let profile = conn - .query_row( - "SELECT id, channel, chat_id, chat_kind, title, purpose, notes, tags, updated_by, created_at, updated_at - FROM chat_profiles - WHERE channel = ?1 AND chat_id = ?2", - params![channel, chat_id], - Self::chat_profile_from_row, - ) - .optional()?; - Ok(profile) - }) - .await? - } - - pub(super) async fn list_console_terminal_events_impl( - &self, - workspace_id: &str, - session_key: &str, - after_id: i64, - limit: usize, - ) -> anyhow::Result> { - anyhow::ensure!( - !workspace_id.is_empty() && !session_key.is_empty(), - "console recovery scope is empty" - ); - let workspace_id = workspace_id.to_owned(); - let session_key = session_key.to_owned(); - let limit = i64::try_from(limit.clamp(1, 128))?; - let pool = self.pool.clone(); - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { - let reader = pool.read()?; - let conn = reader.connection()?; - let mut stmt = conn.prepare("SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, - parent_session_key, run_id, parent_run_id, agent_id, persona_id, - sender, recipient, role, event_type, source_ref_json, subject_ref_json, - goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, - content, content_hash, raw_payload_json, visibility, created_at, updated_at - FROM message_events WHERE workspace_id = ?1 AND session_key = ?2 - AND source = 'console' AND event_type = 'turn.finalized' AND id > ?3 - AND NOT EXISTS(SELECT 1 FROM rf_message_attempts a WHERE a.workspace_id = message_events.workspace_id - AND a.run_id = message_events.run_id - AND (a.deleted_at IS NOT NULL OR a.reply_deleted_at IS NOT NULL)) - ORDER BY id ASC LIMIT ?4")?; - Ok(stmt.query_map(params![workspace_id, session_key, after_id, limit], Self::message_event_from_row)? - .collect::>>()?) - }).await? - } - - pub(super) async fn list_conversation_sessions_impl( - &self, - limit: usize, - offset: usize, - channel: Option<&str>, - ) -> anyhow::Result> { - let pool = self.pool.clone(); - let limit = Self::sanitize_conversation_limit(limit); - let offset = Self::sanitize_conversation_offset(offset); - let channel = channel.map(str::to_string); - - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { - let reader = pool.read()?; - let conn = reader.connection()?; - let mut sessions = Vec::new(); - - if let Some(channel_filter) = channel { - let mut stmt = conn.prepare( - "SELECT session_key, channel, sender, created_at, updated_at, message_count, last_message_preview - FROM sessions - WHERE channel = ?1 - ORDER BY updated_at DESC - LIMIT ?2 OFFSET ?3", - )?; - let rows = stmt.query_map(params![channel_filter, limit, offset], |row| { - let message_count: i64 = row.get(5)?; - #[allow(clippy::cast_sign_loss)] - let message_count = message_count.max(0) as u64; - Ok(ConversationSessionSummary { - session_key: row.get(0)?, - channel: row.get(1)?, - sender: row.get(2)?, - created_at: row.get(3)?, - updated_at: row.get(4)?, - message_count, - last_message_preview: row.get(6)?, - }) - })?; - for row in rows { - sessions.push(row?); - } - } else { - let mut stmt = conn.prepare( - "SELECT session_key, channel, sender, created_at, updated_at, message_count, last_message_preview - FROM sessions - ORDER BY updated_at DESC - LIMIT ?1 OFFSET ?2", - )?; - let rows = stmt.query_map(params![limit, offset], |row| { - let message_count: i64 = row.get(5)?; - #[allow(clippy::cast_sign_loss)] - let message_count = message_count.max(0) as u64; - Ok(ConversationSessionSummary { - session_key: row.get(0)?, - channel: row.get(1)?, - sender: row.get(2)?, - created_at: row.get(3)?, - updated_at: row.get(4)?, - message_count, - last_message_preview: row.get(6)?, - }) - })?; - for row in rows { - sessions.push(row?); - } - } - - Ok(sessions) - }) - .await? - } - - /// `list_conversation_sessions_impl` restricted to the sessions whose - /// stored owner is `owner_id`. - pub(super) async fn list_owner_conversation_sessions_impl( - &self, - owner_id: &str, - limit: usize, - offset: usize, - channel: Option<&str>, - ) -> anyhow::Result> { - let pool = self.pool.clone(); - let limit = Self::sanitize_conversation_limit(limit); - let offset = Self::sanitize_conversation_offset(offset); - let owner_id = owner_id.to_string(); - let channel = channel.map(str::to_string); - - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { - let reader = pool.read()?; - let conn = reader.connection()?; - let mut stmt = conn.prepare( - "SELECT session_key, channel, sender, created_at, updated_at, message_count, last_message_preview - FROM sessions - WHERE owner_id = ?1 AND (?2 IS NULL OR channel = ?2) - ORDER BY updated_at DESC - LIMIT ?3 OFFSET ?4", - )?; - let rows = stmt.query_map(params![owner_id, channel, limit, offset], |row| { - let message_count: i64 = row.get(5)?; - Ok(ConversationSessionSummary { - session_key: row.get(0)?, - channel: row.get(1)?, - sender: row.get(2)?, - created_at: row.get(3)?, - updated_at: row.get(4)?, - message_count: u64::try_from(message_count).unwrap_or(0), - last_message_preview: row.get(6)?, - }) - })?; - rows.collect::, _>>().map_err(Into::into) - }) - .await? - } - - /// The agent key of each conversation turn among `turn_ids`: the key of its - /// stamped scope, or `m` for an unstamped (Main) row. - pub(super) async fn conversation_turn_agent_keys_impl( - &self, - turn_ids: &[i64], - ) -> anyhow::Result> { - if turn_ids.is_empty() { - return Ok(std::collections::HashMap::new()); - } - let pool = self.pool.clone(); - let turn_ids = turn_ids.to_vec(); - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { - let reader = pool.read()?; - let conn = reader.connection()?; - let placeholders = vec!["?"; turn_ids.len()].join(","); - let mut stmt = conn.prepare(&format!( - "SELECT turn.id, COALESCE(scope.agent_key, 'm') - FROM conversation_turns turn - LEFT JOIN agent_scopes scope ON scope.scope_id = turn.ma_scope_id - WHERE turn.id IN ({placeholders})" - ))?; - let rows = stmt.query_map(rusqlite::params_from_iter(turn_ids.iter()), |row| { - Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?)) - })?; - rows.collect::, _>>() - .map_err(Into::into) - }) - .await? - } - - pub(super) async fn get_conversation_session_impl( - &self, - session_key: &str, - ) -> anyhow::Result> { - let pool = self.pool.clone(); - let session_key = session_key.to_string(); - - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { - let reader = pool.read()?; - let conn = reader.connection()?; - let mut stmt = conn.prepare( - "SELECT session_key, channel, sender, created_at, updated_at, message_count, last_message_preview - FROM sessions WHERE session_key = ?1", - )?; - let row = stmt.query_row(params![session_key], |row| { - let message_count: i64 = row.get(5)?; - #[allow(clippy::cast_sign_loss)] - let message_count = message_count.max(0) as u64; - Ok(ConversationSessionSummary { - session_key: row.get(0)?, - channel: row.get(1)?, - sender: row.get(2)?, - created_at: row.get(3)?, - updated_at: row.get(4)?, - message_count, - last_message_preview: row.get(6)?, - }) - }); - - match row { - Ok(summary) => Ok(Some(summary)), - Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None), - Err(error) => Err(error.into()), - } - }) - .await? - } - - pub(super) async fn load_recent_conversation_histories_impl( - &self, - principal: &MemoryPrincipal, - max_turns_per_session: usize, - max_sessions: usize, - ) -> anyhow::Result>> { - let pool = self.pool.clone(); - let owner_id = principal - .owner_id - .as_deref() - .filter(|owner| !owner.trim().is_empty()) - .map(str::to_string); - let max_turns_per_session = Self::sanitize_conversation_limit(max_turns_per_session); - let max_sessions = Self::sanitize_hydrated_sessions_limit(max_sessions); - let legacy_visible = 1_i64; - - crate::runtime::blocking::spawn_blocking( - move || -> anyhow::Result>> { - let reader = pool.read()?; - let conn = reader.connection()?; - let mut stmt = conn.prepare( - "SELECT id, session_key, role, content, timestamp, message_id - FROM ( - SELECT - ct.id, - ct.session_key, - ct.role, - ct.content, - ct.timestamp, - ct.message_id, - ROW_NUMBER() OVER (PARTITION BY ct.session_key ORDER BY ct.id DESC) AS row_num - FROM conversation_turns ct - INNER JOIN ( - SELECT session_key - FROM sessions - WHERE ?3 = 'system:*' - OR owner_id = ?3 - OR (?4 = 1 AND (owner_id IS NULL OR owner_id = 'legacy:' || session_key)) - ORDER BY updated_at DESC - LIMIT ?2 - ) recent_sessions - ON recent_sessions.session_key = ct.session_key - WHERE ct.deleted_at IS NULL AND (?3 = 'system:*' - OR ct.owner_id = ?3 - OR (?4 = 1 AND (ct.owner_id IS NULL OR ct.owner_id = 'legacy:' || ct.session_key))) - ) - WHERE row_num <= ?1 - ORDER BY session_key ASC, id ASC", - )?; - let rows = stmt.query_map( - params![max_turns_per_session, max_sessions, owner_id, legacy_visible], - |row| { - Ok(ConversationTurn { - id: row.get(0)?, - session_key: row.get(1)?, - role: row.get(2)?, - content: row.get(3)?, - timestamp: row.get(4)?, - message_id: row.get(5)?, - }) - }, - )?; - - let mut histories: std::collections::HashMap> = - std::collections::HashMap::new(); - for row in rows { - let turn = row?; - histories.entry(turn.session_key.clone()).or_default().push(turn); - } - Ok(histories) - }, - ) - .await? - } - - pub(super) async fn acquire_ingress_lifetime_impl( - &self, - workspace_id: &str, - token: &str, - deadline: std::time::Instant, - ) -> anyhow::Result> { - crate::memory::ingress_recovery::remaining(deadline)?; - let entry = self.ingress_owners.cell(workspace_id)?; - let lifetime = if let Some(lifetime) = entry.cell.get() { - lifetime.clone() - } else { - // Only queueing for initialization is timed out. Once this caller - // owns the gate, admission's registered owner task awaits the real - // backend completion, including a late blocking open/write. - let _gate = tokio::time::timeout_at( - tokio::time::Instant::from_std(deadline), - entry.init_gate.clone().lock_owned(), - ) - .await - .map_err(|_| anyhow::anyhow!("ingress owner initialization queue deadline elapsed"))?; - crate::memory::ingress_recovery::remaining(deadline)?; - entry - .cell - .get_or_try_init(|| async { - ingress_recovery::acquire( - self.pool.clone(), - self.db_path.clone(), - workspace_id.to_owned(), - token.to_owned(), - deadline, - false, - ) - .await? - .ok_or_else(|| anyhow::anyhow!("ingress lifetime is already owned")) - }) - .await? - .clone() - }; - // Validation failures retain the original cell: no token replacement or - // implicit authority renewal after loss of the issued owner. - lifetime.validate(deadline).await?; - Ok(lifetime) - } - - pub(super) async fn append_ingress_input_impl( - &self, - input: MessageEventInput, - capsule: crate::memory::ingress_recovery::IngressCapsule, - lifetime: Arc, - deadline: std::time::Instant, - attestation: Option, - admission: Option, - ) -> anyhow::Result { - use crate::memory::ingress_recovery::IngressAppendOutcome; - let mut attestation = attestation; - if let Some(attestation) = attestation.as_mut().filter(|attestation| !attestation.is_verified()) { - // Bare SQLite (or Lucid) is the first layer holding the plaintext input. - crate::memory::ingress_recovery::verify_transport(self, &input, &capsule, attestation)?; - } - Ok( - match Box::pin(self.append_attested_event( - input, - Some(AtomicIngressMutation::Input { - capsule, - lifetime, - deadline, - attestation, - }), - None, - admission, - )) - .await? - { - Some((event, true)) => IngressAppendOutcome::Inserted(event), - Some((event, false)) => IngressAppendOutcome::AlreadyAccepted(event), - None => IngressAppendOutcome::Tombstoned, - }, - ) - } - - pub(super) async fn find_message_event_by_idempotency_key_impl( - &self, - workspace_id: &str, - idempotency_key: &str, - ) -> anyhow::Result> { - let workspace_id = workspace_id.to_string(); - let idempotency_key = idempotency_key.to_string(); - let pool = self.pool.clone(); - crate::runtime::blocking::spawn_blocking(move || { - let reader = pool.read()?; - let conn = reader.connection()?; - conn.query_row( - "SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, - parent_session_key, run_id, parent_run_id, agent_id, persona_id, - sender, recipient, role, event_type, source_ref_json, subject_ref_json, - goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, - content, content_hash, raw_payload_json, visibility, created_at, updated_at - FROM message_events - WHERE workspace_id = ?1 AND idempotency_key = ?2 - LIMIT 1", - params![workspace_id, idempotency_key], - Self::message_event_from_row, - ) - .optional() - .map_err(Into::into) - }) - .await? - } - - pub(super) async fn list_worker_launch_events_impl( - &self, - workspace_id: &str, - after_id: i64, - limit: usize, - ) -> anyhow::Result> { - anyhow::ensure!( - !workspace_id.is_empty() && after_id >= 0 && (1..=128).contains(&limit), - "worker launch discovery requires workspace, nonnegative cursor and limit 1..=128" - ); - let workspace_id = workspace_id.to_owned(); - let limit = i64::try_from(limit)?; - let pool = self.pool.clone(); - crate::runtime::blocking::spawn_blocking(move || { - let reader = pool.read()?; - let conn = reader.connection()?; - let mut stmt = conn.prepare( - "SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, - parent_session_key, run_id, parent_run_id, agent_id, persona_id, - sender, recipient, role, event_type, source_ref_json, subject_ref_json, - goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, - content, content_hash, raw_payload_json, visibility, created_at, updated_at - FROM message_events - WHERE workspace_id = ?1 AND event_type IN ('worker.recovery.registered', 'worker.ordinary.recovery.registered', 'worker.operator.recovery.registered') AND id > ?2 - ORDER BY id ASC LIMIT ?3", - )?; - stmt.query_map(params![workspace_id, after_id, limit], Self::message_event_from_row)? - .collect::>>() - .map_err(Into::into) - }) - .await? - } - - pub(super) async fn list_owned_message_events_by_type_impl( - &self, - workspace_id: &str, - owner_id: &str, - event_type: &str, - after_id: i64, - limit: usize, - ) -> anyhow::Result> { - anyhow::ensure!( - !workspace_id.is_empty() - && !owner_id.is_empty() - && !event_type.is_empty() - && after_id >= 0 - && (1..=100).contains(&limit), - "owned event listing requires workspace, owner, type, nonnegative cursor and limit 1..=100" - ); - let workspace_id = workspace_id.to_owned(); - let owner_id = owner_id.to_owned(); - let event_type = event_type.to_owned(); - let limit = i64::try_from(limit)?; - let pool = self.pool.clone(); - crate::runtime::blocking::spawn_blocking(move || { - let reader = pool.read()?; - let conn = reader.connection()?; - let mut stmt = conn.prepare( - "SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, - parent_session_key, run_id, parent_run_id, agent_id, persona_id, - sender, recipient, role, event_type, source_ref_json, subject_ref_json, - goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, - content, content_hash, raw_payload_json, visibility, created_at, updated_at - FROM message_events - WHERE workspace_id = ?1 AND owner_id = ?2 AND event_type = ?3 AND id > ?4 - ORDER BY id ASC LIMIT ?5", - )?; - stmt.query_map( - params![workspace_id, owner_id, event_type, after_id, limit], - Self::message_event_from_row, - )? - .collect::>>() - .map_err(Into::into) - }) - .await? - } - - pub(super) async fn find_owned_message_event_impl( - &self, - workspace_id: &str, - owner_id: &str, - event_id: &str, - ) -> anyhow::Result> { - let workspace_id = workspace_id.to_string(); - if workspace_id.is_empty() || owner_id.is_empty() || event_id.is_empty() { - return Ok(None); - } - let owner_id = owner_id.to_string(); - let event_id = event_id.to_string(); - let pool = self.pool.clone(); - crate::runtime::blocking::spawn_blocking(move || { - let reader = pool.read()?; - let conn = reader.connection()?; - conn.query_row( - "SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, - parent_session_key, run_id, parent_run_id, agent_id, persona_id, - sender, recipient, role, event_type, source_ref_json, subject_ref_json, - goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, - content, content_hash, raw_payload_json, visibility, created_at, updated_at - FROM message_events - WHERE workspace_id = ?1 AND owner_id = ?2 AND event_id = ?3 - LIMIT 1", - params![workspace_id, owner_id, event_id], - Self::message_event_from_row, - ) - .optional() - .map_err(Into::into) - }) - .await? - } - - /// Production message-events-since statement, including the partition conjunct. - pub(crate) fn message_events_since_statement(principal: &MemoryPrincipal) -> MessageEventsSinceStatement { - let legacy_session_keys = Self::legacy_session_key_params(principal); - // Canonical key keeps its original `?5` binding; legacy key(s) bind to - // new trailing placeholders starting at `?9` (after limit at `?8`). - let session_indices = Self::session_indices(5, 9, principal, &legacy_session_keys); - let session_fragment = - crate::memory::session_predicate::session_visibility_or_fragment(SQLITE_DIALECT, &session_indices); - let owner_fragment = crate::memory::owner_predicate::owner_match_suffix( - SQLITE_DIALECT, - Self::owner_index(9, legacy_session_keys.len()), - principal.require_owner_match, - crate::memory::owner_predicate::has_owner_id(principal), - ); - // OV-E (OQ-1): the `private` arm requires the owner for every reader, - // isolated or not, and admits nothing to a reader without one. Same - // placeholder as `owner_fragment`, so one bound value serves both. - let owner_required_fragment = crate::memory::owner_predicate::owner_match_suffix( - SQLITE_DIALECT, - Self::owner_index(9, legacy_session_keys.len()), - true, - crate::memory::owner_predicate::has_owner_id(principal), - ); - let partition_first = 9 + legacy_session_keys.len() + usize::from(owner_required_fragment.bound_owner); - let (partition_sql, partition_values) = agent_partition_clause(principal, partition_first); - MessageEventsSinceStatement { - sql: message_events_since_select_sql( - &session_fragment.sql, - &owner_fragment.sql, - &owner_required_fragment.sql, - &partition_sql, - ), - partition_values, - legacy_session_keys, - bind_owner: owner_required_fragment.bound_owner, - } - } - - pub(super) async fn list_message_events_since_impl( - &self, - principal: &MemoryPrincipal, - after_id: i64, - limit: usize, - ) -> anyhow::Result> { - let pool = self.pool.clone(); - let principal = principal.clone(); - let limit = Self::sanitize_conversation_limit(limit); - let system_allowed = Self::is_system_principal(&principal); - let statement = Self::message_events_since_statement(&principal); - - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { - let reader = pool.read()?; - let conn = reader.connection()?; - let mut stmt = conn.prepare(&statement.sql)?; - let mut bind: Vec<&dyn rusqlite::types::ToSql> = vec![ - &after_id, - &principal.workspace_id, - &principal.agent_id, - &principal.persona_id, - &principal.session_key, - &principal.sender, - &system_allowed, - &limit, - ]; - for key in &statement.legacy_session_keys { - bind.push(key); - } - if statement.bind_owner { - bind.push(&principal.owner_id); - } - for value in &statement.partition_values { - bind.push(value); - } - let rows = stmt.query_map(bind.as_slice(), Self::message_event_from_row)?; - - rows.collect::, _>>().map_err(Into::into) - }) - .await? - } - - pub(super) async fn list_message_events_recent_impl( - &self, - principal: &MemoryPrincipal, - limit: usize, - ) -> anyhow::Result> { - let pool = self.pool.clone(); - let principal = principal.clone(); - let limit = Self::sanitize_conversation_limit(limit); - let system_allowed = Self::is_system_principal(&principal); - - let legacy_session_keys = Self::legacy_session_key_params(&principal); - // Canonical key keeps its `?4` binding; legacy key(s) bind at trailing - // placeholders starting at `?8` (after limit at `?7`). - let session_indices = Self::session_indices(4, 8, &principal, &legacy_session_keys); - let session_fragment = - crate::memory::session_predicate::session_visibility_or_fragment(SQLITE_DIALECT, &session_indices); - let owner_fragment = crate::memory::owner_predicate::owner_match_suffix( - SQLITE_DIALECT, - Self::owner_index(8, legacy_session_keys.len()), - principal.require_owner_match, - crate::memory::owner_predicate::has_owner_id(&principal), - ); - // OV-E (OQ-1): the `private` arm requires the owner for every reader, - // isolated or not, and admits nothing to a reader without one. Same - // placeholder as `owner_fragment`, so one bound value serves both. - let owner_required_fragment = crate::memory::owner_predicate::owner_match_suffix( - SQLITE_DIALECT, - Self::owner_index(8, legacy_session_keys.len()), - true, - crate::memory::owner_predicate::has_owner_id(&principal), - ); - - // MA-01h: the partition binds after every other placeholder. - let (partition_sql, partition_values) = agent_partition_clause( - &principal, - Self::owner_index(8, legacy_session_keys.len()) + usize::from(owner_required_fragment.bound_owner), - ); - - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { - let reader = pool.read()?; - let conn = reader.connection()?; - let mut stmt = conn.prepare(&format!( - "SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, - parent_session_key, run_id, parent_run_id, agent_id, persona_id, - sender, recipient, role, event_type, source_ref_json, subject_ref_json, - goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, - content, content_hash, raw_payload_json, visibility, created_at, updated_at - FROM message_events - WHERE ( - visibility = 'global' - OR ( - workspace_id = ?1 - AND ( - visibility = 'workspace'{owner_fragment} - OR (visibility = 'agent' AND ( - (?2 IS NOT NULL AND agent_id = ?2) - OR (?3 IS NOT NULL AND persona_id = ?3) - )) - OR (visibility = 'session' AND {session_fragment}{owner_fragment}) - OR (visibility = 'private' AND ( - (?2 IS NOT NULL AND agent_id = ?2) - OR (?3 IS NOT NULL AND persona_id = ?3) - OR (?5 IS NOT NULL AND sender = ?5) - ){owner_required_fragment}) - OR (visibility = 'system' AND ?6) - ) - ) - ){partition_sql} - ORDER BY id DESC - LIMIT ?7", - session_fragment = session_fragment.sql, - owner_fragment = owner_fragment.sql, - owner_required_fragment = owner_required_fragment.sql, - ))?; - let mut bind: Vec<&dyn rusqlite::types::ToSql> = vec![ - &principal.workspace_id, - &principal.agent_id, - &principal.persona_id, - &principal.session_key, - &principal.sender, - &system_allowed, - &limit, - ]; - for key in &legacy_session_keys { - bind.push(key); - } - if owner_required_fragment.bound_owner { - bind.push(&principal.owner_id); - } - for value in &partition_values { - bind.push(value); - } - let rows = stmt.query_map(bind.as_slice(), Self::message_event_from_row)?; - - rows.collect::, _>>().map_err(Into::into) - }) - .await? - } - - pub(super) async fn list_message_events_time_range_impl( - &self, - principal: &MemoryPrincipal, - descendant_workspace_root: Option<&str>, - start: &str, - end: &str, - limit: usize, - ) -> anyhow::Result> { - let pool = self.pool.clone(); - let principal = principal.clone(); - let descendant_workspace_root = descendant_workspace_root.map(str::to_string); - let start = start.to_string(); - let end = end.to_string(); - let limit = i64::try_from(limit.min(100_000)).unwrap_or(100_000); - let system_allowed = Self::is_system_principal(&principal); - anyhow::ensure!( - descendant_workspace_root.is_none() || system_allowed, - "descendant workspace event queries require a system principal" - ); - let descendant_pattern = descendant_workspace_root.as_ref().map(|root| { - let escaped = root.replace('\\', "\\\\").replace('%', "\\%").replace('_', "\\_"); - format!("{escaped}{}%", std::path::MAIN_SEPARATOR) - }); - let legacy_session_keys = Self::legacy_session_key_params(&principal); - let session_indices = Self::session_indices(4, 12, &principal, &legacy_session_keys); - let session_fragment = - crate::memory::session_predicate::session_visibility_or_fragment(SQLITE_DIALECT, &session_indices); - let owner_fragment = crate::memory::owner_predicate::owner_match_suffix( - SQLITE_DIALECT, - Self::owner_index(12, legacy_session_keys.len()), - principal.require_owner_match, - crate::memory::owner_predicate::has_owner_id(&principal), - ); - // OV-E (OQ-1): the `private` arm requires the owner for every reader, - // isolated or not, and admits nothing to a reader without one. Same - // placeholder as `owner_fragment`, so one bound value serves both. - let owner_required_fragment = crate::memory::owner_predicate::owner_match_suffix( - SQLITE_DIALECT, - Self::owner_index(12, legacy_session_keys.len()), - true, - crate::memory::owner_predicate::has_owner_id(&principal), - ); - - let (partition_sql, partition_values) = agent_partition_clause( - &principal, - Self::owner_index(12, legacy_session_keys.len()) + usize::from(owner_required_fragment.bound_owner), - ); - - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { - let reader = pool.read()?; - let conn = reader.connection()?; - let mut stmt = conn.prepare(&format!( - "SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, - parent_session_key, run_id, parent_run_id, agent_id, persona_id, - sender, recipient, role, event_type, source_ref_json, subject_ref_json, - goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, - content, content_hash, raw_payload_json, visibility, created_at, updated_at - FROM message_events - WHERE created_at >= ?9 AND created_at < ?10 - AND ( - visibility = 'global' - OR ( - ( - workspace_id = ?1 - OR (?6 AND ?7 IS NOT NULL AND ( - workspace_id = ?7 OR workspace_id LIKE ?8 ESCAPE '\\' - )) - ) - AND ( - (?6 AND ?7 IS NOT NULL) - OR visibility = 'workspace'{owner_fragment} - OR (visibility = 'agent' AND ( - (?2 IS NOT NULL AND agent_id = ?2) - OR (?3 IS NOT NULL AND persona_id = ?3) - )) - OR (visibility = 'session' AND {session_fragment}{owner_fragment}) - OR (visibility = 'private' AND ( - (?2 IS NOT NULL AND agent_id = ?2) - OR (?3 IS NOT NULL AND persona_id = ?3) - OR (?5 IS NOT NULL AND sender = ?5) - ){owner_required_fragment}) - OR (visibility = 'system' AND ?6) - ) - ) - ){partition_sql} - ORDER BY created_at ASC, id ASC - LIMIT ?11", - session_fragment = session_fragment.sql, - owner_fragment = owner_fragment.sql, - owner_required_fragment = owner_required_fragment.sql, - ))?; - let mut bind: Vec<&dyn rusqlite::types::ToSql> = vec![ - &principal.workspace_id, - &principal.agent_id, - &principal.persona_id, - &principal.session_key, - &principal.sender, - &system_allowed, - &descendant_workspace_root, - &descendant_pattern, - &start, - &end, - &limit, - ]; - for key in &legacy_session_keys { - bind.push(key); - } - if owner_required_fragment.bound_owner { - bind.push(&principal.owner_id); - } - for value in &partition_values { - bind.push(value); - } - let rows = stmt.query_map(bind.as_slice(), Self::message_event_from_row)?; - rows.collect::, _>>().map_err(Into::into) - }) - .await? - } - - pub(super) async fn load_recent_shared_context_impl( - &self, - query: SharedContextQuery, - ) -> anyhow::Result> { - let pool = self.pool.clone(); - let principal = query.principal; - let limit = Self::sanitize_conversation_limit(query.limit); - let after_id = query.since_event_id.unwrap_or(0); - let system_allowed = Self::is_system_principal(&principal); - let include_roles = query - .include_roles - .into_iter() - .map(|role| role.trim().to_ascii_lowercase()) - .filter(|role| !role.is_empty()) - .collect::>(); - - let legacy_session_keys = Self::legacy_session_key_params(&principal); - // Canonical key keeps its `?5` binding; legacy key(s) bind at trailing - // placeholders starting at `?9` (after limit at `?8`). - let session_indices = Self::session_indices(5, 9, &principal, &legacy_session_keys); - let session_fragment = - crate::memory::session_predicate::session_visibility_or_fragment(SQLITE_DIALECT, &session_indices); - let owner_fragment = crate::memory::owner_predicate::owner_match_suffix( - SQLITE_DIALECT, - Self::owner_index(9, legacy_session_keys.len()), - principal.require_owner_match, - crate::memory::owner_predicate::has_owner_id(&principal), - ); - // OV-E (OQ-1): the `private` arm requires the owner for every reader, - // isolated or not, and admits nothing to a reader without one. Same - // placeholder as `owner_fragment`, so one bound value serves both. - let owner_required_fragment = crate::memory::owner_predicate::owner_match_suffix( - SQLITE_DIALECT, - Self::owner_index(9, legacy_session_keys.len()), - true, - crate::memory::owner_predicate::has_owner_id(&principal), - ); - - let (partition_sql, partition_values) = agent_partition_clause( - &principal, - Self::owner_index(9, legacy_session_keys.len()) + usize::from(owner_required_fragment.bound_owner), - ); - - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { - let reader = pool.read()?; - let conn = reader.connection()?; - let mut stmt = conn.prepare(&format!( - "SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, - parent_session_key, run_id, parent_run_id, agent_id, persona_id, - sender, recipient, role, event_type, source_ref_json, subject_ref_json, - goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, - content, content_hash, raw_payload_json, visibility, created_at, updated_at - FROM message_events - WHERE id > ?1 - AND ( - visibility = 'global' - OR ( - workspace_id = ?2 - AND ( - visibility = 'workspace'{owner_required_fragment} - OR (visibility = 'agent' AND ( - (?3 IS NOT NULL AND agent_id = ?3) - OR (?4 IS NOT NULL AND persona_id = ?4) - )) - OR (visibility = 'session' AND {session_fragment}{owner_fragment}) - OR (visibility = 'private' AND ( - (?3 IS NOT NULL AND agent_id = ?3) - OR (?4 IS NOT NULL AND persona_id = ?4) - OR (?6 IS NOT NULL AND sender = ?6) - ){owner_required_fragment}) - OR (visibility = 'system' AND ?7) - ) - ) - ){partition_sql} - ORDER BY id DESC - LIMIT ?8", - session_fragment = session_fragment.sql, - owner_fragment = owner_fragment.sql, - owner_required_fragment = owner_required_fragment.sql, - ))?; - let mut bind: Vec<&dyn rusqlite::types::ToSql> = vec![ - &after_id, - &principal.workspace_id, - &principal.agent_id, - &principal.persona_id, - &principal.session_key, - &principal.sender, - &system_allowed, - &limit, - ]; - for key in &legacy_session_keys { - bind.push(key); - } - if owner_required_fragment.bound_owner { - bind.push(&principal.owner_id); - } - for value in &partition_values { - bind.push(value); - } - let rows = stmt.query_map(bind.as_slice(), Self::message_event_from_row)?; - - let mut events = rows.collect::, _>>()?; - events.reverse(); - if include_roles.is_empty() { - return Ok(events); - } - Ok(events - .into_iter() - .filter(|event| include_roles.contains(&event.role.to_ascii_lowercase())) - .collect()) - }) - .await? - } - - pub(super) async fn retrieve_decision_session_impl( - &self, - principal: &MemoryPrincipal, - before_event_id: &str, - limit: u8, - deadline: std::time::Instant, - ) -> anyhow::Result> { - anyhow::ensure!( - (1..=5).contains(&limit) && !before_event_id.is_empty() && before_event_id.len() <= 128, - "invalid decision Session bounds" - ); - anyhow::ensure!( - std::time::Instant::now() < deadline, - "decision Session deadline expired" - ); - let session_key = principal - .session_key - .as_ref() - .filter(|key| !key.trim().is_empty()) - .ok_or_else(|| anyhow::anyhow!("selected Session requires a session"))? - .clone(); - anyhow::ensure!( - crate::memory::owner_predicate::has_owner_id(principal), - "selected Session requires an authenticated owner" - ); - let principal = principal.clone(); - let before_event_id = before_event_id.to_owned(); - let db_path = self.db_path.clone(); - let limit = i64::from(limit); - let system_allowed = Self::is_system_principal(&principal); - let legacy_session_keys = Self::legacy_session_key_params(&principal); - // Canonical key keeps its `?3` binding; legacy key(s) bind at trailing - // placeholders starting at `?9` (after limit at `?8`). The top-level - // `session_key` hard filter becomes an `IN (...)` read-merge union. - let mut session_indices = vec![3usize]; - for offset in 0..legacy_session_keys.len() { - session_indices.push(9 + offset); - } - let session_fragment = - crate::memory::session_predicate::session_key_match_fragment(SQLITE_DIALECT, &session_indices); - let owner_fragment = crate::memory::owner_predicate::owner_match_suffix( - SQLITE_DIALECT, - Self::owner_index(9, legacy_session_keys.len()), - principal.require_owner_match, - crate::memory::owner_predicate::has_owner_id(&principal), - ); - // OV-E (OQ-1): the `private` arm requires the owner for every reader, - // isolated or not, and admits nothing to a reader without one. Same - // placeholder as `owner_fragment`, so one bound value serves both. - let owner_required_fragment = crate::memory::owner_predicate::owner_match_suffix( - SQLITE_DIALECT, - Self::owner_index(9, legacy_session_keys.len()), - true, - crate::memory::owner_predicate::has_owner_id(&principal), - ); - // OV-C: `workspace` is owner-qualified for an owner-isolated reader; - // every other reader's statement is byte-identical. - let shared_tiers_arm = crate::memory::owner_predicate::session_context_shared_tiers(&owner_fragment); - - let (partition_sql, partition_values) = agent_partition_clause( - &principal, - Self::owner_index(9, legacy_session_keys.len()) + usize::from(owner_required_fragment.bound_owner), - ); - - crate::runtime::blocking::spawn_blocking( - move || -> anyhow::Result> { - let conn = Self::open_rehearsal_reader(&db_path, deadline)?; - let before_id: i64 = conn - .query_row( - "SELECT id FROM message_events WHERE event_id = ?1 AND workspace_id = ?2 - AND session_key = ?3 AND owner_id = ?4 AND role = 'user' AND event_type = 'message.created'", - params![before_event_id, principal.workspace_id, session_key, principal.owner_id], - |row| row.get(0), - ) - .optional()? - .ok_or_else(|| anyhow::anyhow!("selected Session source event is unavailable"))?; - let mut stmt = conn.prepare(&format!( - "SELECT event_id, role, content, created_at - FROM message_events - WHERE id < ?1 - AND workspace_id = ?2 - AND {session_fragment} - AND ( - {shared_tiers_arm} - OR (visibility = 'agent' AND ( - (?4 IS NOT NULL AND agent_id = ?4) - OR (?5 IS NOT NULL AND persona_id = ?5) - )) - OR (visibility = 'session'{owner_fragment}) - OR (visibility = 'private' AND ( - (?4 IS NOT NULL AND agent_id = ?4) - OR (?5 IS NOT NULL AND persona_id = ?5) - OR (?6 IS NOT NULL AND sender = ?6) - ){owner_required_fragment}) - OR (visibility = 'system' AND ?7) - ) - AND role IN ('user', 'assistant') AND event_type = 'message.created'{partition_sql} - AND length(CAST(event_id AS BLOB)) <= 128 - AND length(CAST(content AS BLOB)) <= 4096 - AND length(CAST(created_at AS BLOB)) <= 64 - ORDER BY id DESC - LIMIT ?8", - session_fragment = session_fragment.sql, - owner_fragment = owner_fragment.sql, - owner_required_fragment = owner_required_fragment.sql, - ))?; - let mut bind: Vec<&dyn rusqlite::types::ToSql> = vec![ - &before_id, - &principal.workspace_id, - &session_key, - &principal.agent_id, - &principal.persona_id, - &principal.sender, - &system_allowed, - &limit, - ]; - for key in &legacy_session_keys { - bind.push(key); - } - if owner_required_fragment.bound_owner { - bind.push(&principal.owner_id); - } - for value in &partition_values { - bind.push(value); - } - let rows = stmt.query_map(bind.as_slice(), |row| { - Ok(crate::memory::traits::DecisionSessionHit { - event_id: row.get(0)?, - role: row.get(1)?, - content: row.get(2)?, - created_at: row.get(3)?, - }) - })?; - let mut hits = rows.collect::>>()?; - anyhow::ensure!( - std::time::Instant::now() < deadline, - "decision Session deadline expired" - ); - hits.reverse(); - Ok(hits) - }, - ) - .await? - } - - pub(super) async fn load_recent_session_context_impl( - &self, - query: SessionContextQuery, - ) -> anyhow::Result> { - let mut events = self.session_context_page(query, None).await?; - events.reverse(); - Ok(events) - } - - /// `load_recent_session_context` restricted to rows below `before_id`, - /// newest first (the paging read of a complete provenance pool). - pub(super) async fn load_session_context_before_impl( - &self, - query: SessionContextQuery, - before_id: i64, - ) -> anyhow::Result> { - self.session_context_page(query, Some(before_id)).await - } - - /// The session-context statement, newest first. `before_id` adds one - /// trailing bind (`AND id < ?N`) after every other placeholder. - async fn session_context_page( - &self, - query: SessionContextQuery, - before_id: Option, - ) -> anyhow::Result> { - let Some(session_key) = query.principal.session_key.clone() else { - return Ok(Vec::new()); - }; - let pool = self.pool.clone(); - let principal = query.principal; - let limit = Self::sanitize_conversation_limit(query.limit); - let after_id = query.since_event_id.unwrap_or(0); - let system_allowed = Self::is_system_principal(&principal); - let include_roles = query - .include_roles - .into_iter() - .map(|role| role.trim().to_ascii_lowercase()) - .filter(|role| !role.is_empty()) - .collect::>(); - - let legacy_session_keys = Self::legacy_session_key_params(&principal); - // Canonical key keeps its `?3` binding; legacy key(s) bind at trailing - // placeholders starting at `?9` (after limit at `?8`). The top-level - // `session_key` hard filter becomes an `IN (...)` read-merge union. - let mut session_indices = vec![3usize]; - for offset in 0..legacy_session_keys.len() { - session_indices.push(9 + offset); - } - let session_fragment = - crate::memory::session_predicate::session_key_match_fragment(SQLITE_DIALECT, &session_indices); - let owner_index = Self::owner_index(9, legacy_session_keys.len()); - let owner_fragment = crate::memory::owner_predicate::owner_match_suffix( - SQLITE_DIALECT, - owner_index, - principal.require_owner_match, - crate::memory::owner_predicate::has_owner_id(&principal), - ); - // OV-E (OQ-1): the `private` arm requires the owner for every reader, - // isolated or not, and admits nothing to a reader without one. Same - // placeholder as `owner_fragment`, so one bound value serves both. - let owner_required_fragment = crate::memory::owner_predicate::owner_match_suffix( - SQLITE_DIALECT, - owner_index, - true, - crate::memory::owner_predicate::has_owner_id(&principal), - ); - let first_role_index = owner_index + usize::from(owner_required_fragment.bound_owner); - let role_fragment = if include_roles.is_empty() { - "1 = 1".to_string() - } else { - format!( - "role IN ({})", - (first_role_index..first_role_index + include_roles.len()) - .map(|index| format!("?{index}")) - .collect::>() - .join(", ") - ) - }; - // OV-C: `workspace` is owner-qualified for an owner-isolated reader; - // every other reader's statement is byte-identical. - let shared_tiers_arm = crate::memory::owner_predicate::session_context_shared_tiers(&owner_fragment); - let before_fragment = before_id.map_or_else(String::new, |_| { - format!(" AND id < ?{}", first_role_index + include_roles.len()) - }); - // MA-01h: the partition binds after every other placeholder. - let (partition_sql, partition_values) = agent_partition_clause( - &principal, - first_role_index + include_roles.len() + usize::from(before_id.is_some()), - ); - - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { - let reader = pool.read()?; - let conn = reader.connection()?; - let mut stmt = conn.prepare(&format!( - "SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, - parent_session_key, run_id, parent_run_id, agent_id, persona_id, - sender, recipient, role, event_type, source_ref_json, subject_ref_json, - goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, - content, content_hash, raw_payload_json, visibility, created_at, updated_at - FROM message_events - WHERE id > ?1 - AND workspace_id = ?2 - AND {session_fragment} - AND {role_fragment} - AND ( - {shared_tiers_arm} - OR (visibility = 'agent' AND ( - (?4 IS NOT NULL AND agent_id = ?4) - OR (?5 IS NOT NULL AND persona_id = ?5) - )) - OR (visibility = 'session'{owner_fragment}) - OR (visibility = 'private' AND ( - (?4 IS NOT NULL AND agent_id = ?4) - OR (?5 IS NOT NULL AND persona_id = ?5) - OR (?6 IS NOT NULL AND sender = ?6) - ){owner_required_fragment}) - OR (visibility = 'system' AND ?7) - ){before_fragment}{partition_sql} - ORDER BY id DESC - LIMIT ?8", - session_fragment = session_fragment.sql, - role_fragment = role_fragment, - owner_fragment = owner_fragment.sql, - owner_required_fragment = owner_required_fragment.sql, - ))?; - let mut bind: Vec<&dyn rusqlite::types::ToSql> = vec![ - &after_id, - &principal.workspace_id, - &session_key, - &principal.agent_id, - &principal.persona_id, - &principal.sender, - &system_allowed, - &limit, - ]; - for key in &legacy_session_keys { - bind.push(key); - } - if owner_required_fragment.bound_owner { - bind.push(&principal.owner_id); - } - for role in &include_roles { - bind.push(role); - } - if let Some(before_id) = &before_id { - bind.push(before_id); - } - for value in &partition_values { - bind.push(value); - } - let rows = stmt.query_map(bind.as_slice(), Self::message_event_from_row)?; - - Ok(rows.collect::, _>>()?) - }) - .await? - } - - pub(super) async fn append_memory_event_impl(&self, input: MemoryEventInput) -> anyhow::Result { - let pool = self.pool.clone(); - - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result { - let conn = pool.write(); - let tx = begin_immediate(&conn)?; - let now = Utc::now().to_rfc3339(); - let event_id = input.event_id.unwrap_or_else(|| Uuid::new_v4().to_string()); - let bound_scope = super::agent_migration::resolve_input_scope( - &tx, - input.agent_partition.as_ref(), - input.session_key.as_deref(), - &input.workspace_id, - input.owner_id.as_deref(), - )?; - tx.execute( - "INSERT OR IGNORE INTO memory_events ( - event_id, workspace_id, owner_id, event_type, subject_table, subject_id, - session_key, run_id, parent_run_id, agent_id, persona_id, visibility, payload_json, created_at, ma_scope_id - ) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)", - params![ - event_id, - input.workspace_id, - input.owner_id, - input.event_type, - input.subject_table, - input.subject_id, - input.session_key, - input.run_id, - input.parent_run_id, - input.agent_id, - input.persona_id, - input.visibility.as_str(), - input.payload_json, - now, - bound_scope - ], - )?; - super::agent_migration::refuse_if_stored_scope_differs( - &tx, - "memory_events", - "event_id", - &event_id, - &bound_scope, - )?; - - let event = tx.query_row( - "SELECT id, event_id, workspace_id, owner_id, event_type, subject_table, subject_id, - session_key, run_id, parent_run_id, agent_id, persona_id, visibility, payload_json, created_at - FROM memory_events - WHERE event_id = ?1 - LIMIT 1", - params![event_id], - Self::memory_event_from_row, - )?; - super::sync_lifecycle::memory_written(&tx,&event)?; - tx.commit()?; - Ok(event) - }) - .await? - } - - pub(super) async fn list_memory_events_since_impl( - &self, - principal: &MemoryPrincipal, - after_id: i64, - limit: usize, - ) -> anyhow::Result> { - let pool = self.pool.clone(); - let principal = principal.clone(); - let limit = i64::try_from(limit.max(1)).unwrap_or(i64::MAX); - - // C03: the owner parameter binds at the first free trailing slot (`?8`). - let owner_fragment = crate::memory::owner_predicate::owner_match_suffix( - SQLITE_DIALECT, - 8, - principal.require_owner_match, - crate::memory::owner_predicate::has_owner_id(&principal), - ); - // OV-E (OQ-1): the `private` arm requires the owner for every reader, - // isolated or not, and admits nothing to a reader without one. Same - // placeholder as `owner_fragment`, so one bound value serves both. - let owner_required_fragment = crate::memory::owner_predicate::owner_match_suffix( - SQLITE_DIALECT, - 8, - true, - crate::memory::owner_predicate::has_owner_id(&principal), - ); - - let (partition_sql, partition_values) = - agent_partition_clause(&principal, 8 + usize::from(owner_required_fragment.bound_owner)); - - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { - let reader = pool.read()?; - let conn = reader.connection()?; - let system_allowed = - principal.agent_id.as_deref() == Some("system") || principal.persona_id.as_deref() == Some("system"); - let mut stmt = conn.prepare(&format!( - "SELECT id, event_id, workspace_id, owner_id, event_type, subject_table, subject_id, - session_key, run_id, parent_run_id, agent_id, persona_id, visibility, payload_json, created_at - FROM memory_events - WHERE id > ?1 - AND ( - visibility = 'global' - OR ( - workspace_id = ?2 - AND ( - visibility = 'workspace'{owner_fragment} - OR (visibility = 'agent' AND ( - (?3 IS NOT NULL AND agent_id = ?3) - OR (?4 IS NOT NULL AND persona_id = ?4) - )) - OR (visibility = 'session' AND ?5 IS NOT NULL AND session_key = ?5{owner_fragment}) - OR (visibility = 'private' AND ( - (?3 IS NOT NULL AND agent_id = ?3) - OR (?4 IS NOT NULL AND persona_id = ?4) - OR (event_type = 'document.ingested' AND agent_id IS NULL AND persona_id IS NULL) - ){owner_required_fragment}) - OR (visibility = 'system' AND ?6) - ) - ) - ){partition_sql} - ORDER BY id ASC - LIMIT ?7", - owner_fragment = owner_fragment.sql, - owner_required_fragment = owner_required_fragment.sql, - ))?; - let mut bind: Vec<&dyn rusqlite::types::ToSql> = vec![ - &after_id, - &principal.workspace_id, - &principal.agent_id, - &principal.persona_id, - &principal.session_key, - &system_allowed, - &limit, - ]; - if owner_required_fragment.bound_owner { - bind.push(&principal.owner_id); - } - for value in &partition_values { - bind.push(value); - } - let rows = stmt.query_map(bind.as_slice(), Self::memory_event_from_row)?; - rows.collect::, _>>().map_err(Into::into) - }) - .await? - } - - pub(super) async fn list_memory_events_recent_impl( - &self, - principal: &MemoryPrincipal, - limit: usize, - ) -> anyhow::Result> { - let pool = self.pool.clone(); - let principal = principal.clone(); - let limit = i64::try_from(limit.max(1)).unwrap_or(i64::MAX); - - // C03: the owner parameter binds at the first free trailing slot (`?7`). - let owner_fragment = crate::memory::owner_predicate::owner_match_suffix( - SQLITE_DIALECT, - 7, - principal.require_owner_match, - crate::memory::owner_predicate::has_owner_id(&principal), - ); - // OV-E (OQ-1): the `private` arm requires the owner for every reader, - // isolated or not, and admits nothing to a reader without one. Same - // placeholder as `owner_fragment`, so one bound value serves both. - let owner_required_fragment = crate::memory::owner_predicate::owner_match_suffix( - SQLITE_DIALECT, - 7, - true, - crate::memory::owner_predicate::has_owner_id(&principal), - ); - - let (partition_sql, partition_values) = - agent_partition_clause(&principal, 7 + usize::from(owner_required_fragment.bound_owner)); - - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { - let reader = pool.read()?; - let conn = reader.connection()?; - let system_allowed = - principal.agent_id.as_deref() == Some("system") || principal.persona_id.as_deref() == Some("system"); - let mut stmt = conn.prepare(&format!( - "SELECT id, event_id, workspace_id, owner_id, event_type, subject_table, subject_id, - session_key, run_id, parent_run_id, agent_id, persona_id, visibility, payload_json, created_at - FROM memory_events - WHERE ( - visibility = 'global' - OR ( - workspace_id = ?1 - AND ( - visibility = 'workspace'{owner_fragment} - OR (visibility = 'agent' AND ( - (?2 IS NOT NULL AND agent_id = ?2) - OR (?3 IS NOT NULL AND persona_id = ?3) - )) - OR (visibility = 'session' AND ?4 IS NOT NULL AND session_key = ?4{owner_fragment}) - OR (visibility = 'private' AND ( - (?2 IS NOT NULL AND agent_id = ?2) - OR (?3 IS NOT NULL AND persona_id = ?3) - OR (event_type = 'document.ingested' AND agent_id IS NULL AND persona_id IS NULL) - ){owner_required_fragment}) - OR (visibility = 'system' AND ?5) - ) - ) - ){partition_sql} - ORDER BY id DESC - LIMIT ?6", - owner_fragment = owner_fragment.sql, - owner_required_fragment = owner_required_fragment.sql, - ))?; - let mut bind: Vec<&dyn rusqlite::types::ToSql> = vec![ - &principal.workspace_id, - &principal.agent_id, - &principal.persona_id, - &principal.session_key, - &system_allowed, - &limit, - ]; - if owner_required_fragment.bound_owner { - bind.push(&principal.owner_id); - } - for value in &partition_values { - bind.push(value); - } - let rows = stmt.query_map(bind.as_slice(), Self::memory_event_from_row)?; - rows.collect::, _>>().map_err(Into::into) - }) - .await? - } -} - -#[cfg(test)] -struct AppendSnapshotHoldInner { - db_path: std::path::PathBuf, - run_id: String, - idempotency_key: String, - entered: std::sync::mpsc::SyncSender<()>, - release: std::sync::mpsc::Receiver<()>, -} - -#[cfg(test)] -static APPEND_SNAPSHOT_HOLD: parking_lot::Mutex> = parking_lot::Mutex::new(None); - -#[cfg(test)] -pub(crate) struct AppendSnapshotHold { - pub entered: std::sync::mpsc::Receiver<()>, - pub release: std::sync::mpsc::SyncSender<()>, -} - -#[cfg(test)] -pub(crate) struct AppendSnapshotHoldGuard; - -#[cfg(test)] -impl Drop for AppendSnapshotHoldGuard { - fn drop(&mut self) { - *APPEND_SNAPSHOT_HOLD.lock() = None; - } -} - -/// Park the matching child-segment append after its real tombstone-fence -/// SELECT so a concurrent opener can commit. Unrelated appends leave the -/// hook in place. `BEGIN DEFERRED` then fails the INSERT with -/// SQLITE_BUSY_SNAPSHOT; `BEGIN IMMEDIATE` already holds the write lock, -/// so the others wait. -#[cfg(test)] -#[must_use] -pub(crate) fn arm_append_snapshot_hold( - db_path: std::path::PathBuf, - run_id: impl Into, - idempotency_key: impl Into, -) -> (AppendSnapshotHold, AppendSnapshotHoldGuard) { - let (entered_tx, entered_rx) = std::sync::mpsc::sync_channel(1); - let (release_tx, release_rx) = std::sync::mpsc::sync_channel(1); - *APPEND_SNAPSHOT_HOLD.lock() = Some(AppendSnapshotHoldInner { - db_path, - run_id: run_id.into(), - idempotency_key: idempotency_key.into(), - entered: entered_tx, - release: release_rx, - }); - ( - AppendSnapshotHold { - entered: entered_rx, - release: release_tx, - }, - AppendSnapshotHoldGuard, - ) -} - -#[cfg(test)] -fn hold_paths_match(left: &std::path::Path, right: &std::path::Path) -> bool { - if left == right { - return true; - } - match (left.canonicalize(), right.canonicalize()) { - (Ok(left), Ok(right)) => left == right, - _ => false, - } -} - -#[cfg(test)] -pub(super) fn hold_append_snapshot_for_test( - input: &MessageEventInput, - db_path: &std::path::Path, -) -> anyhow::Result<()> { - let mut slot = APPEND_SNAPSHOT_HOLD.lock(); - let matched = slot.as_ref().is_some_and(|hold| { - input.run_id.as_deref() == Some(hold.run_id.as_str()) - && input.idempotency_key.as_deref() == Some(hold.idempotency_key.as_str()) - && hold_paths_match(&hold.db_path, db_path) - }); - if !matched { - return Ok(()); - } - let hold = slot - .take() - .ok_or_else(|| anyhow::anyhow!("test: snapshot hold vanished after identity match"))?; - drop(slot); - let _ = hold.entered.send(()); - let _ = hold.release.recv_timeout(std::time::Duration::from_secs(60)); - Ok(()) -} +include!("events/section_1.rs"); +include!("events/section_2.rs"); +include!("events/section_3.rs"); diff --git a/src/memory/sqlite/events/section_1.rs b/src/memory/sqlite/events/section_1.rs new file mode 100644 index 000000000..8814e3532 --- /dev/null +++ b/src/memory/sqlite/events/section_1.rs @@ -0,0 +1,203 @@ +use crate::memory::traits::{ + ChatProfile, ConversationSessionSummary, ConversationTurn, MemoryEvent, MemoryEventInput, MemoryPrincipal, + MessageEvent, MessageEventInput, PartitionKey, SessionContextQuery, SharedContextQuery, +}; +use crate::runtime::sqlite_pool::begin_immediate; +use chrono::Utc; +use rusqlite::{OptionalExtension, TransactionBehavior, params}; +use std::sync::Arc; +use uuid::Uuid; + +/// The agent-scope column every partitioned store carries. +pub(crate) const MA_SCOPE_COLUMN: &str = "ma_scope_id"; + +/// One parenthesised conjunct on `column` after existing predicates, with its +/// bound values in placeholder order. Empty when `partition` is `None`. +/// +/// Named: rows of exactly (workspace, owner, `n:`, incarnation). Main: +/// unstamped rows and rows of a Main scope in the workspace. `placeholder` +/// yields the next bind marker (`?N` or `?`); `column` is a constant. +pub(crate) fn partition_conjunct( + column: &str, + partition: Option<&crate::memory::AgentPartition>, + mut placeholder: impl FnMut() -> String, +) -> (String, Vec) { + let Some(partition) = partition else { + return (String::new(), Vec::new()); + }; + match &partition.key { + PartitionKey::Named { name, incarnation } => { + let (workspace, owner, key, generation) = (placeholder(), placeholder(), placeholder(), placeholder()); + ( + format!( + " AND ({column} IN (SELECT scope_id FROM agent_scopes WHERE workspace_id={workspace} AND owner_id={owner} AND agent_key={key} AND incarnation={generation}))" + ), + vec![ + partition.workspace_id.clone(), + partition.owner_id.clone(), + format!("n:{}", name.as_str()), + incarnation.to_string(), + ], + ) + } + PartitionKey::Main => { + let workspace = placeholder(); + ( + format!( + " AND ({column} IS NULL OR {column} IN (SELECT scope_id FROM agent_scopes WHERE workspace_id={workspace} AND agent_key='m'))" + ), + vec![partition.workspace_id.clone()], + ) + } + } +} + +/// Numbered bind markers `?first`, `?first+1`, ... +pub(crate) fn numbered_placeholders(first: usize) -> impl FnMut() -> String { + let mut next = first; + move || { + let marker = format!("?{next}"); + next += 1; + marker + } +} + +/// [`partition_conjunct`] on `ma_scope_id` for the principal's partition. +pub(crate) fn agent_partition_clause(principal: &MemoryPrincipal, first_placeholder: usize) -> (String, Vec) { + partition_conjunct( + MA_SCOPE_COLUMN, + principal.agent_partition.as_ref(), + numbered_placeholders(first_placeholder), + ) +} + +pub(crate) const fn conversation_turns_ordering(recorded_order: bool) -> &'static str { + if recorded_order { + "julianday(timestamp) DESC, COALESCE((SELECT event.id FROM message_events event WHERE event.event_id = conversation_turns.message_event_id), id) DESC, id DESC" + } else { + "id DESC" + } +} + +/// The seventh column says whether the row is a deleted tombstone +/// (AC-1b2b). Only a caller-keyed history listing (`tombstones`) reads +/// tombstones; every other reader, model context included, skips them. +pub(crate) fn conversation_turns_select_sql( + session_fragment: &str, + partition_sql: &str, + ordering: &str, + tombstones: bool, +) -> String { + let deleted_sql = if tombstones { + "" + } else { + "\n AND deleted_at IS NULL" + }; + format!( + "SELECT id, session_key, role, content, timestamp, message_id, deleted_at IS NOT NULL + FROM conversation_turns + WHERE {session_fragment} + AND ( + ?4 = 'system:*' + OR + owner_id = ?4 + OR (?5 = 1 AND (owner_id IS NULL OR owner_id = 'legacy:' || session_key)) + ){partition_sql}{deleted_sql} + ORDER BY {ordering} + LIMIT ?2 OFFSET ?3" + ) +} + +pub(crate) fn message_events_since_select_sql( + session_fragment: &str, + owner_fragment: &str, + owner_required_fragment: &str, + partition_sql: &str, +) -> String { + format!( + "SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, + parent_session_key, run_id, parent_run_id, agent_id, persona_id, + sender, recipient, role, event_type, source_ref_json, subject_ref_json, + goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, + content, content_hash, raw_payload_json, visibility, created_at, updated_at + FROM message_events + WHERE id > ?1 + AND ( + visibility = 'global' + OR ( + workspace_id = ?2 + AND ( + visibility = 'workspace'{owner_fragment} + OR (visibility = 'agent' AND ( + (?3 IS NOT NULL AND agent_id = ?3) + OR (?4 IS NOT NULL AND persona_id = ?4) + )) + OR (visibility = 'session' AND {session_fragment}{owner_fragment}) + OR (visibility = 'private' AND ( + (?3 IS NOT NULL AND agent_id = ?3) + OR (?4 IS NOT NULL AND persona_id = ?4) + OR (?6 IS NOT NULL AND sender = ?6) + ){owner_required_fragment}) + OR (visibility = 'system' AND ?7) + ) + ) + ){partition_sql} + ORDER BY id ASC + LIMIT ?8" + ) +} + +pub(crate) struct MessageEventsSinceStatement { + pub sql: String, + pub partition_values: Vec, + pub legacy_session_keys: Vec, + pub bind_owner: bool, +} + +/// Production conversation-turns statement, including the partition conjunct. +/// Returns `(sql, partition_values, legacy_session_keys)`. +#[cfg(test)] +pub(crate) fn conversation_turns_statement( + principal: &MemoryPrincipal, + session_key: &str, + recorded_order: bool, +) -> (String, Vec, Vec) { + conversation_turns_statement_with(principal, session_key, recorded_order, false) +} + +/// [`conversation_turns_statement`], optionally reading deleted tombstones. +fn conversation_turns_statement_with( + principal: &MemoryPrincipal, + session_key: &str, + recorded_order: bool, + tombstones: bool, +) -> (String, Vec, Vec) { + let legacy_session_keys: Vec = principal + .legacy_session_key + .as_deref() + .map(str::trim) + .filter(|key| !key.is_empty() && *key != session_key.trim()) + .map(|key| vec![key.to_string()]) + .unwrap_or_default(); + let mut session_indices = vec![1usize]; + for offset_idx in 0..legacy_session_keys.len() { + session_indices.push(6 + offset_idx); + } + let session_fragment = + crate::memory::session_predicate::session_key_match_fragment(super::SQLITE_DIALECT, &session_indices); + let (partition_sql, partition_values) = agent_partition_clause(principal, 6 + legacy_session_keys.len()); + ( + conversation_turns_select_sql( + &session_fragment.sql, + &partition_sql, + conversation_turns_ordering(recorded_order), + tombstones, + ), + partition_values, + legacy_session_keys, + ) +} + +use super::ingress_recovery; +use super::{SQLITE_DIALECT, SqliteMemory}; +use crate::memory::ingress_recovery::AtomicIngressMutation; diff --git a/src/memory/sqlite/events/section_2.rs b/src/memory/sqlite/events/section_2.rs new file mode 100644 index 000000000..3ecc6194b --- /dev/null +++ b/src/memory/sqlite/events/section_2.rs @@ -0,0 +1,1744 @@ +impl SqliteMemory { + pub(super) async fn list_conversation_turns_ordered( + &self, + principal: &MemoryPrincipal, + session_key: &str, + limit: usize, + offset: usize, + recorded_order: bool, + ) -> anyhow::Result> { + Ok(self + .conversation_turns_page(principal, session_key, limit, offset, recorded_order, false) + .await? + .into_iter() + .map(|row| row.turn) + .collect()) + } + + /// A Console history page in event-time order with deleted tombstones + /// (AC-1b2b): the caller-keyed history listing. + pub(super) async fn list_rf_history_turns_impl( + &self, + principal: &MemoryPrincipal, + session_key: &str, + limit: usize, + offset: usize, + ) -> anyhow::Result> { + self.conversation_turns_page(principal, session_key, limit, offset, true, true) + .await + } + + async fn conversation_turns_page( + &self, + principal: &MemoryPrincipal, + session_key: &str, + limit: usize, + offset: usize, + recorded_order: bool, + tombstones: bool, + ) -> anyhow::Result> { + let pool = self.pool.clone(); + let owner_id = principal + .owner_id + .as_deref() + .filter(|owner| !owner.trim().is_empty()) + .map(str::to_string); + let session_key = session_key.to_string(); + let limit = Self::sanitize_conversation_limit(limit); + let offset = Self::sanitize_conversation_offset(offset); + let legacy_visible = 1_i64; + // D4 read-merge: the explicit `session_key` arg is the canonical key + // (bound at `?1`); the principal may carry a distinct legacy key bound + // at trailing placeholders starting at `?6`. With no legacy key the + // predicate degrades to the byte-identical `session_key = ?1`. + let (sql, partition_values, legacy_session_keys) = + conversation_turns_statement_with(principal, &session_key, recorded_order, tombstones); + + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { + let reader = pool.read()?; + let conn = reader.connection()?; + let mut stmt = conn.prepare(&sql)?; + let mut bind: Vec<&dyn rusqlite::types::ToSql> = + vec![&session_key, &limit, &offset, &owner_id, &legacy_visible]; + for key in &legacy_session_keys { + bind.push(key); + } + for value in &partition_values { + bind.push(value); + } + let rows = stmt.query_map(bind.as_slice(), |row| { + Ok(crate::memory::RfHistoryTurn { + turn: ConversationTurn { + id: row.get(0)?, + session_key: row.get(1)?, + role: row.get(2)?, + content: row.get(3)?, + timestamp: row.get(4)?, + message_id: row.get(5)?, + }, + deleted: row.get(6)?, + }) + })?; + + let mut turns = Vec::new(); + for row in rows { + turns.push(row?); + } + turns.reverse(); + Ok(turns) + }) + .await? + } + + pub(super) async fn project_console_message_with_deadline( + &self, + event: &MessageEvent, + deadline: Option, + ) -> anyhow::Result<()> { + if let Some(deadline) = deadline { + crate::memory::ingress_recovery::remaining(deadline)?; + ingress_recovery::validate_event_bounds(event)?; + } + event.validate_console_projection()?; + let repair_owner = deadline.map(|_| self.repair_owner(&event.workspace_id)).transpose()?; + let event = event.clone(); + let pool = self.pool.clone(); + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result<()> { + let mut write = match deadline { Some(deadline) => pool.write_until(deadline)?, None => pool.write() }; + let conn = ingress_recovery::DeadlineConn::wrap(&mut write, deadline)?; + let tx = rusqlite::Transaction::new_unchecked(&conn, TransactionBehavior::Immediate)?; + if let (Some(owner), Some(deadline)) = (&repair_owner, deadline) { + ingress_recovery::validate_owner(&tx, owner, &event.workspace_id, deadline)?; + ingress_recovery::check_receipt_size(&tx, &event.event_id, None, &event.workspace_id)?; + ingress_recovery::check_console_projection_size(&tx, &event.event_id)?; + } + let durable = tx.query_row( + "SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, + parent_session_key, run_id, parent_run_id, agent_id, persona_id, + sender, recipient, role, event_type, source_ref_json, subject_ref_json, + goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, + content, content_hash, raw_payload_json, visibility, created_at, updated_at + FROM message_events WHERE event_id = ?1 AND workspace_id = ?2 AND owner_id = ?3", + params![event.event_id, event.workspace_id, event.owner_id], Self::message_event_from_row, + )?; + anyhow::ensure!(serde_json::to_value(&durable)? == serde_json::to_value(&event)?, + "console projection differs from its durable event"); + let existing: Vec<(String, Option, String, String, bool)> = { + let mut stmt = tx.prepare("SELECT session_key, owner_id, role, content, deleted_at IS NOT NULL + FROM conversation_turns WHERE message_event_id = ?1 OR message_id = ?1 LIMIT 2")?; + stmt.query_map(params![event.event_id], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?, row.get(4)?)))? + .collect::>>()? + }; + if let Some(row) = existing.first() { + // A deleted message (AC-1b2b) keeps its tombstone: nothing to project. + let tombstone = row.4 && row.1 == event.owner_id; + anyhow::ensure!(existing.len() == 1 && Some(&row.0) == event.session_key.as_ref() + && (tombstone || (row.1 == event.owner_id && row.2 == event.role && row.3 == event.content)), + "console message projection conflicts with its durable event"); + if let (Some(owner), Some(deadline)) = (&repair_owner, deadline) { + ingress_recovery::validate_owner(&tx, owner, &event.workspace_id, deadline)?; + } + return Ok(()); + } + let preview = Self::conversation_preview(&event.content); + tx.execute("INSERT INTO sessions + (session_key, channel, sender, owner_id, created_at, updated_at, message_count, last_message_preview) + VALUES (?1, ?2, ?3, ?4, ?5, ?5, 1, ?6) + ON CONFLICT(session_key) DO UPDATE SET + message_count = COALESCE(sessions.message_count, 0) + 1, + channel = CASE WHEN excluded.updated_at >= sessions.updated_at THEN excluded.channel ELSE sessions.channel END, + sender = CASE WHEN excluded.updated_at >= sessions.updated_at THEN excluded.sender ELSE sessions.sender END, + owner_id = CASE WHEN excluded.updated_at >= sessions.updated_at THEN excluded.owner_id ELSE sessions.owner_id END, + last_message_preview = CASE WHEN excluded.updated_at >= sessions.updated_at THEN excluded.last_message_preview ELSE sessions.last_message_preview END, + updated_at = MAX(sessions.updated_at, excluded.updated_at)", + params![event.session_key, event.channel, event.sender, event.owner_id, event.created_at, preview])?; + tx.execute("INSERT INTO conversation_turns + (session_key, owner_id, role, content, timestamp, message_id, message_event_id, agent_id, persona_id, visibility, ma_scope_id) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6, ?7, ?8, 'session', + (SELECT ma_scope_id FROM message_events WHERE event_id = ?6))", + params![event.session_key, event.owner_id, event.role, event.content, event.created_at, + event.event_id, event.agent_id, event.persona_id])?; + if let (Some(owner), Some(deadline)) = (&repair_owner, deadline) { + ingress_recovery::validate_owner(&tx, owner, &event.workspace_id, deadline)?; + } + tx.commit()?; + if let Some(deadline) = deadline { crate::memory::ingress_recovery::remaining(deadline)?; } + Ok(()) + }).await? + } + + pub(super) async fn upsert_chat_profile_metadata_impl( + &self, + channel: &str, + chat_id: &str, + chat_kind: &str, + title: Option<&str>, + ) -> anyhow::Result<()> { + let pool = self.pool.clone(); + let channel = channel.to_string(); + let chat_id = chat_id.to_string(); + let chat_kind = chat_kind.to_string(); + let title = title.map(str::to_string); + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result<()> { + let now = Utc::now().to_rfc3339(); + let id = Uuid::new_v4().to_string(); + let conn = pool.write(); + conn.execute( + "INSERT INTO chat_profiles + (id, channel, chat_id, chat_kind, title, purpose, notes, tags, updated_by, created_at, updated_at) + VALUES (?1, ?2, ?3, ?4, ?5, NULL, NULL, '[]', 'auto', ?6, ?6) + ON CONFLICT(channel, chat_id) DO UPDATE SET + chat_kind = excluded.chat_kind, + title = CASE + WHEN excluded.title IS NOT NULL THEN excluded.title + ELSE chat_profiles.title + END, + updated_at = excluded.updated_at", + params![id, channel, chat_id, chat_kind, title, now], + )?; + Ok(()) + }) + .await? + } + + pub(super) async fn get_chat_profile_impl( + &self, + channel: &str, + chat_id: &str, + ) -> anyhow::Result> { + let pool = self.pool.clone(); + let channel = channel.to_string(); + let chat_id = chat_id.to_string(); + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { + let reader = pool.read()?; + let conn = reader.connection()?; + let profile = conn + .query_row( + "SELECT id, channel, chat_id, chat_kind, title, purpose, notes, tags, updated_by, created_at, updated_at + FROM chat_profiles + WHERE channel = ?1 AND chat_id = ?2", + params![channel, chat_id], + Self::chat_profile_from_row, + ) + .optional()?; + Ok(profile) + }) + .await? + } + + pub(super) async fn list_console_terminal_events_impl( + &self, + workspace_id: &str, + session_key: &str, + after_id: i64, + limit: usize, + ) -> anyhow::Result> { + anyhow::ensure!( + !workspace_id.is_empty() && !session_key.is_empty(), + "console recovery scope is empty" + ); + let workspace_id = workspace_id.to_owned(); + let session_key = session_key.to_owned(); + let limit = i64::try_from(limit.clamp(1, 128))?; + let pool = self.pool.clone(); + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { + let reader = pool.read()?; + let conn = reader.connection()?; + let mut stmt = conn.prepare("SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, + parent_session_key, run_id, parent_run_id, agent_id, persona_id, + sender, recipient, role, event_type, source_ref_json, subject_ref_json, + goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, + content, content_hash, raw_payload_json, visibility, created_at, updated_at + FROM message_events WHERE workspace_id = ?1 AND session_key = ?2 + AND source = 'console' AND event_type = 'turn.finalized' AND id > ?3 + AND NOT EXISTS(SELECT 1 FROM rf_message_attempts a WHERE a.workspace_id = message_events.workspace_id + AND a.run_id = message_events.run_id + AND (a.deleted_at IS NOT NULL OR a.reply_deleted_at IS NOT NULL)) + ORDER BY id ASC LIMIT ?4")?; + Ok(stmt.query_map(params![workspace_id, session_key, after_id, limit], Self::message_event_from_row)? + .collect::>>()?) + }).await? + } + + pub(super) async fn list_conversation_sessions_impl( + &self, + limit: usize, + offset: usize, + channel: Option<&str>, + ) -> anyhow::Result> { + let pool = self.pool.clone(); + let limit = Self::sanitize_conversation_limit(limit); + let offset = Self::sanitize_conversation_offset(offset); + let channel = channel.map(str::to_string); + + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { + let reader = pool.read()?; + let conn = reader.connection()?; + let mut sessions = Vec::new(); + + if let Some(channel_filter) = channel { + let mut stmt = conn.prepare( + "SELECT session_key, channel, sender, created_at, updated_at, message_count, last_message_preview + FROM sessions + WHERE channel = ?1 + ORDER BY updated_at DESC + LIMIT ?2 OFFSET ?3", + )?; + let rows = stmt.query_map(params![channel_filter, limit, offset], |row| { + let message_count: i64 = row.get(5)?; + #[allow(clippy::cast_sign_loss)] + let message_count = message_count.max(0) as u64; + Ok(ConversationSessionSummary { + session_key: row.get(0)?, + channel: row.get(1)?, + sender: row.get(2)?, + created_at: row.get(3)?, + updated_at: row.get(4)?, + message_count, + last_message_preview: row.get(6)?, + }) + })?; + for row in rows { + sessions.push(row?); + } + } else { + let mut stmt = conn.prepare( + "SELECT session_key, channel, sender, created_at, updated_at, message_count, last_message_preview + FROM sessions + ORDER BY updated_at DESC + LIMIT ?1 OFFSET ?2", + )?; + let rows = stmt.query_map(params![limit, offset], |row| { + let message_count: i64 = row.get(5)?; + #[allow(clippy::cast_sign_loss)] + let message_count = message_count.max(0) as u64; + Ok(ConversationSessionSummary { + session_key: row.get(0)?, + channel: row.get(1)?, + sender: row.get(2)?, + created_at: row.get(3)?, + updated_at: row.get(4)?, + message_count, + last_message_preview: row.get(6)?, + }) + })?; + for row in rows { + sessions.push(row?); + } + } + + Ok(sessions) + }) + .await? + } + + /// `list_conversation_sessions_impl` restricted to the sessions whose + /// stored owner is `owner_id`. + pub(super) async fn list_owner_conversation_sessions_impl( + &self, + owner_id: &str, + limit: usize, + offset: usize, + channel: Option<&str>, + ) -> anyhow::Result> { + let pool = self.pool.clone(); + let limit = Self::sanitize_conversation_limit(limit); + let offset = Self::sanitize_conversation_offset(offset); + let owner_id = owner_id.to_string(); + let channel = channel.map(str::to_string); + + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { + let reader = pool.read()?; + let conn = reader.connection()?; + let mut stmt = conn.prepare( + "SELECT session_key, channel, sender, created_at, updated_at, message_count, last_message_preview + FROM sessions + WHERE owner_id = ?1 AND (?2 IS NULL OR channel = ?2) + ORDER BY updated_at DESC + LIMIT ?3 OFFSET ?4", + )?; + let rows = stmt.query_map(params![owner_id, channel, limit, offset], |row| { + let message_count: i64 = row.get(5)?; + Ok(ConversationSessionSummary { + session_key: row.get(0)?, + channel: row.get(1)?, + sender: row.get(2)?, + created_at: row.get(3)?, + updated_at: row.get(4)?, + message_count: u64::try_from(message_count).unwrap_or(0), + last_message_preview: row.get(6)?, + }) + })?; + rows.collect::, _>>().map_err(Into::into) + }) + .await? + } + + /// The agent key of each conversation turn among `turn_ids`: the key of its + /// stamped scope, or `m` for an unstamped (Main) row. + pub(super) async fn conversation_turn_agent_keys_impl( + &self, + turn_ids: &[i64], + ) -> anyhow::Result> { + if turn_ids.is_empty() { + return Ok(std::collections::HashMap::new()); + } + let pool = self.pool.clone(); + let turn_ids = turn_ids.to_vec(); + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { + let reader = pool.read()?; + let conn = reader.connection()?; + let placeholders = vec!["?"; turn_ids.len()].join(","); + let mut stmt = conn.prepare(&format!( + "SELECT turn.id, COALESCE(scope.agent_key, 'm') + FROM conversation_turns turn + LEFT JOIN agent_scopes scope ON scope.scope_id = turn.ma_scope_id + WHERE turn.id IN ({placeholders})" + ))?; + let rows = stmt.query_map(rusqlite::params_from_iter(turn_ids.iter()), |row| { + Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?)) + })?; + rows.collect::, _>>() + .map_err(Into::into) + }) + .await? + } + + pub(super) async fn get_conversation_session_impl( + &self, + session_key: &str, + ) -> anyhow::Result> { + let pool = self.pool.clone(); + let session_key = session_key.to_string(); + + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { + let reader = pool.read()?; + let conn = reader.connection()?; + let mut stmt = conn.prepare( + "SELECT session_key, channel, sender, created_at, updated_at, message_count, last_message_preview + FROM sessions WHERE session_key = ?1", + )?; + let row = stmt.query_row(params![session_key], |row| { + let message_count: i64 = row.get(5)?; + #[allow(clippy::cast_sign_loss)] + let message_count = message_count.max(0) as u64; + Ok(ConversationSessionSummary { + session_key: row.get(0)?, + channel: row.get(1)?, + sender: row.get(2)?, + created_at: row.get(3)?, + updated_at: row.get(4)?, + message_count, + last_message_preview: row.get(6)?, + }) + }); + + match row { + Ok(summary) => Ok(Some(summary)), + Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None), + Err(error) => Err(error.into()), + } + }) + .await? + } + + pub(super) async fn load_recent_conversation_histories_impl( + &self, + principal: &MemoryPrincipal, + max_turns_per_session: usize, + max_sessions: usize, + ) -> anyhow::Result>> { + let pool = self.pool.clone(); + let owner_id = principal + .owner_id + .as_deref() + .filter(|owner| !owner.trim().is_empty()) + .map(str::to_string); + let max_turns_per_session = Self::sanitize_conversation_limit(max_turns_per_session); + let max_sessions = Self::sanitize_hydrated_sessions_limit(max_sessions); + let legacy_visible = 1_i64; + + crate::runtime::blocking::spawn_blocking( + move || -> anyhow::Result>> { + let reader = pool.read()?; + let conn = reader.connection()?; + let mut stmt = conn.prepare( + "SELECT id, session_key, role, content, timestamp, message_id + FROM ( + SELECT + ct.id, + ct.session_key, + ct.role, + ct.content, + ct.timestamp, + ct.message_id, + ROW_NUMBER() OVER (PARTITION BY ct.session_key ORDER BY ct.id DESC) AS row_num + FROM conversation_turns ct + INNER JOIN ( + SELECT session_key + FROM sessions + WHERE ?3 = 'system:*' + OR owner_id = ?3 + OR (?4 = 1 AND (owner_id IS NULL OR owner_id = 'legacy:' || session_key)) + ORDER BY updated_at DESC + LIMIT ?2 + ) recent_sessions + ON recent_sessions.session_key = ct.session_key + WHERE ct.deleted_at IS NULL AND (?3 = 'system:*' + OR ct.owner_id = ?3 + OR (?4 = 1 AND (ct.owner_id IS NULL OR ct.owner_id = 'legacy:' || ct.session_key))) + ) + WHERE row_num <= ?1 + ORDER BY session_key ASC, id ASC", + )?; + let rows = stmt.query_map( + params![max_turns_per_session, max_sessions, owner_id, legacy_visible], + |row| { + Ok(ConversationTurn { + id: row.get(0)?, + session_key: row.get(1)?, + role: row.get(2)?, + content: row.get(3)?, + timestamp: row.get(4)?, + message_id: row.get(5)?, + }) + }, + )?; + + let mut histories: std::collections::HashMap> = + std::collections::HashMap::new(); + for row in rows { + let turn = row?; + histories.entry(turn.session_key.clone()).or_default().push(turn); + } + Ok(histories) + }, + ) + .await? + } + + pub(super) async fn acquire_ingress_lifetime_impl( + &self, + workspace_id: &str, + token: &str, + deadline: std::time::Instant, + ) -> anyhow::Result> { + crate::memory::ingress_recovery::remaining(deadline)?; + let entry = self.ingress_owners.cell(workspace_id)?; + let lifetime = if let Some(lifetime) = entry.cell.get() { + lifetime.clone() + } else { + // Only queueing for initialization is timed out. Once this caller + // owns the gate, admission's registered owner task awaits the real + // backend completion, including a late blocking open/write. + let _gate = tokio::time::timeout_at( + tokio::time::Instant::from_std(deadline), + entry.init_gate.clone().lock_owned(), + ) + .await + .map_err(|_| anyhow::anyhow!("ingress owner initialization queue deadline elapsed"))?; + crate::memory::ingress_recovery::remaining(deadline)?; + entry + .cell + .get_or_try_init(|| async { + ingress_recovery::acquire( + self.pool.clone(), + self.db_path.clone(), + workspace_id.to_owned(), + token.to_owned(), + deadline, + false, + ) + .await? + .ok_or_else(|| anyhow::anyhow!("ingress lifetime is already owned")) + }) + .await? + .clone() + }; + // Validation failures retain the original cell: no token replacement or + // implicit authority renewal after loss of the issued owner. + lifetime.validate(deadline).await?; + Ok(lifetime) + } + + pub(super) async fn append_ingress_input_impl( + &self, + input: MessageEventInput, + capsule: crate::memory::ingress_recovery::IngressCapsule, + lifetime: Arc, + deadline: std::time::Instant, + attestation: Option, + admission: Option, + ) -> anyhow::Result { + use crate::memory::ingress_recovery::IngressAppendOutcome; + let mut attestation = attestation; + if let Some(attestation) = attestation.as_mut().filter(|attestation| !attestation.is_verified()) { + // Bare SQLite (or Lucid) is the first layer holding the plaintext input. + crate::memory::ingress_recovery::verify_transport(self, &input, &capsule, attestation)?; + } + Ok( + match Box::pin(self.append_attested_event( + input, + Some(AtomicIngressMutation::Input { + capsule, + lifetime, + deadline, + attestation, + }), + None, + admission, + )) + .await? + { + Some((event, true)) => IngressAppendOutcome::Inserted(event), + Some((event, false)) => IngressAppendOutcome::AlreadyAccepted(event), + None => IngressAppendOutcome::Tombstoned, + }, + ) + } + + pub(super) async fn find_message_event_by_idempotency_key_impl( + &self, + workspace_id: &str, + idempotency_key: &str, + ) -> anyhow::Result> { + let workspace_id = workspace_id.to_string(); + let idempotency_key = idempotency_key.to_string(); + let pool = self.pool.clone(); + crate::runtime::blocking::spawn_blocking(move || { + let reader = pool.read()?; + let conn = reader.connection()?; + conn.query_row( + "SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, + parent_session_key, run_id, parent_run_id, agent_id, persona_id, + sender, recipient, role, event_type, source_ref_json, subject_ref_json, + goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, + content, content_hash, raw_payload_json, visibility, created_at, updated_at + FROM message_events + WHERE workspace_id = ?1 AND idempotency_key = ?2 + LIMIT 1", + params![workspace_id, idempotency_key], + Self::message_event_from_row, + ) + .optional() + .map_err(Into::into) + }) + .await? + } + + pub(super) async fn list_worker_launch_events_impl( + &self, + workspace_id: &str, + after_id: i64, + limit: usize, + ) -> anyhow::Result> { + anyhow::ensure!( + !workspace_id.is_empty() && after_id >= 0 && (1..=128).contains(&limit), + "worker launch discovery requires workspace, nonnegative cursor and limit 1..=128" + ); + let workspace_id = workspace_id.to_owned(); + let limit = i64::try_from(limit)?; + let pool = self.pool.clone(); + crate::runtime::blocking::spawn_blocking(move || { + let reader = pool.read()?; + let conn = reader.connection()?; + let mut stmt = conn.prepare( + "SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, + parent_session_key, run_id, parent_run_id, agent_id, persona_id, + sender, recipient, role, event_type, source_ref_json, subject_ref_json, + goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, + content, content_hash, raw_payload_json, visibility, created_at, updated_at + FROM message_events + WHERE workspace_id = ?1 AND event_type IN ('worker.recovery.registered', 'worker.ordinary.recovery.registered', 'worker.operator.recovery.registered') AND id > ?2 + ORDER BY id ASC LIMIT ?3", + )?; + stmt.query_map(params![workspace_id, after_id, limit], Self::message_event_from_row)? + .collect::>>() + .map_err(Into::into) + }) + .await? + } + + pub(super) async fn list_owned_message_events_by_type_impl( + &self, + workspace_id: &str, + owner_id: &str, + event_type: &str, + after_id: i64, + limit: usize, + ) -> anyhow::Result> { + anyhow::ensure!( + !workspace_id.is_empty() + && !owner_id.is_empty() + && !event_type.is_empty() + && after_id >= 0 + && (1..=100).contains(&limit), + "owned event listing requires workspace, owner, type, nonnegative cursor and limit 1..=100" + ); + let workspace_id = workspace_id.to_owned(); + let owner_id = owner_id.to_owned(); + let event_type = event_type.to_owned(); + let limit = i64::try_from(limit)?; + let pool = self.pool.clone(); + crate::runtime::blocking::spawn_blocking(move || { + let reader = pool.read()?; + let conn = reader.connection()?; + let mut stmt = conn.prepare( + "SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, + parent_session_key, run_id, parent_run_id, agent_id, persona_id, + sender, recipient, role, event_type, source_ref_json, subject_ref_json, + goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, + content, content_hash, raw_payload_json, visibility, created_at, updated_at + FROM message_events + WHERE workspace_id = ?1 AND owner_id = ?2 AND event_type = ?3 AND id > ?4 + ORDER BY id ASC LIMIT ?5", + )?; + stmt.query_map( + params![workspace_id, owner_id, event_type, after_id, limit], + Self::message_event_from_row, + )? + .collect::>>() + .map_err(Into::into) + }) + .await? + } + + pub(super) async fn find_owned_message_event_impl( + &self, + workspace_id: &str, + owner_id: &str, + event_id: &str, + ) -> anyhow::Result> { + let workspace_id = workspace_id.to_string(); + if workspace_id.is_empty() || owner_id.is_empty() || event_id.is_empty() { + return Ok(None); + } + let owner_id = owner_id.to_string(); + let event_id = event_id.to_string(); + let pool = self.pool.clone(); + crate::runtime::blocking::spawn_blocking(move || { + let reader = pool.read()?; + let conn = reader.connection()?; + conn.query_row( + "SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, + parent_session_key, run_id, parent_run_id, agent_id, persona_id, + sender, recipient, role, event_type, source_ref_json, subject_ref_json, + goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, + content, content_hash, raw_payload_json, visibility, created_at, updated_at + FROM message_events + WHERE workspace_id = ?1 AND owner_id = ?2 AND event_id = ?3 + LIMIT 1", + params![workspace_id, owner_id, event_id], + Self::message_event_from_row, + ) + .optional() + .map_err(Into::into) + }) + .await? + } + + /// Production message-events-since statement, including the partition conjunct. + pub(crate) fn message_events_since_statement(principal: &MemoryPrincipal) -> MessageEventsSinceStatement { + let legacy_session_keys = Self::legacy_session_key_params(principal); + // Canonical key keeps its original `?5` binding; legacy key(s) bind to + // new trailing placeholders starting at `?9` (after limit at `?8`). + let session_indices = Self::session_indices(5, 9, principal, &legacy_session_keys); + let session_fragment = + crate::memory::session_predicate::session_visibility_or_fragment(SQLITE_DIALECT, &session_indices); + let owner_fragment = crate::memory::owner_predicate::owner_match_suffix( + SQLITE_DIALECT, + Self::owner_index(9, legacy_session_keys.len()), + principal.require_owner_match, + crate::memory::owner_predicate::has_owner_id(principal), + ); + // OV-E (OQ-1): the `private` arm requires the owner for every reader, + // isolated or not, and admits nothing to a reader without one. Same + // placeholder as `owner_fragment`, so one bound value serves both. + let owner_required_fragment = crate::memory::owner_predicate::owner_match_suffix( + SQLITE_DIALECT, + Self::owner_index(9, legacy_session_keys.len()), + true, + crate::memory::owner_predicate::has_owner_id(principal), + ); + let partition_first = 9 + legacy_session_keys.len() + usize::from(owner_required_fragment.bound_owner); + let (partition_sql, partition_values) = agent_partition_clause(principal, partition_first); + MessageEventsSinceStatement { + sql: message_events_since_select_sql( + &session_fragment.sql, + &owner_fragment.sql, + &owner_required_fragment.sql, + &partition_sql, + ), + partition_values, + legacy_session_keys, + bind_owner: owner_required_fragment.bound_owner, + } + } + + pub(super) async fn list_message_events_since_impl( + &self, + principal: &MemoryPrincipal, + after_id: i64, + limit: usize, + ) -> anyhow::Result> { + let pool = self.pool.clone(); + let principal = principal.clone(); + let limit = Self::sanitize_conversation_limit(limit); + let system_allowed = Self::is_system_principal(&principal); + let statement = Self::message_events_since_statement(&principal); + + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { + let reader = pool.read()?; + let conn = reader.connection()?; + let mut stmt = conn.prepare(&statement.sql)?; + let mut bind: Vec<&dyn rusqlite::types::ToSql> = vec![ + &after_id, + &principal.workspace_id, + &principal.agent_id, + &principal.persona_id, + &principal.session_key, + &principal.sender, + &system_allowed, + &limit, + ]; + for key in &statement.legacy_session_keys { + bind.push(key); + } + if statement.bind_owner { + bind.push(&principal.owner_id); + } + for value in &statement.partition_values { + bind.push(value); + } + let rows = stmt.query_map(bind.as_slice(), Self::message_event_from_row)?; + + rows.collect::, _>>().map_err(Into::into) + }) + .await? + } + + pub(super) async fn list_message_events_recent_impl( + &self, + principal: &MemoryPrincipal, + limit: usize, + ) -> anyhow::Result> { + let pool = self.pool.clone(); + let principal = principal.clone(); + let limit = Self::sanitize_conversation_limit(limit); + let system_allowed = Self::is_system_principal(&principal); + + let legacy_session_keys = Self::legacy_session_key_params(&principal); + // Canonical key keeps its `?4` binding; legacy key(s) bind at trailing + // placeholders starting at `?8` (after limit at `?7`). + let session_indices = Self::session_indices(4, 8, &principal, &legacy_session_keys); + let session_fragment = + crate::memory::session_predicate::session_visibility_or_fragment(SQLITE_DIALECT, &session_indices); + let owner_fragment = crate::memory::owner_predicate::owner_match_suffix( + SQLITE_DIALECT, + Self::owner_index(8, legacy_session_keys.len()), + principal.require_owner_match, + crate::memory::owner_predicate::has_owner_id(&principal), + ); + // OV-E (OQ-1): the `private` arm requires the owner for every reader, + // isolated or not, and admits nothing to a reader without one. Same + // placeholder as `owner_fragment`, so one bound value serves both. + let owner_required_fragment = crate::memory::owner_predicate::owner_match_suffix( + SQLITE_DIALECT, + Self::owner_index(8, legacy_session_keys.len()), + true, + crate::memory::owner_predicate::has_owner_id(&principal), + ); + + // MA-01h: the partition binds after every other placeholder. + let (partition_sql, partition_values) = agent_partition_clause( + &principal, + Self::owner_index(8, legacy_session_keys.len()) + usize::from(owner_required_fragment.bound_owner), + ); + + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { + let reader = pool.read()?; + let conn = reader.connection()?; + let mut stmt = conn.prepare(&format!( + "SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, + parent_session_key, run_id, parent_run_id, agent_id, persona_id, + sender, recipient, role, event_type, source_ref_json, subject_ref_json, + goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, + content, content_hash, raw_payload_json, visibility, created_at, updated_at + FROM message_events + WHERE ( + visibility = 'global' + OR ( + workspace_id = ?1 + AND ( + visibility = 'workspace'{owner_fragment} + OR (visibility = 'agent' AND ( + (?2 IS NOT NULL AND agent_id = ?2) + OR (?3 IS NOT NULL AND persona_id = ?3) + )) + OR (visibility = 'session' AND {session_fragment}{owner_fragment}) + OR (visibility = 'private' AND ( + (?2 IS NOT NULL AND agent_id = ?2) + OR (?3 IS NOT NULL AND persona_id = ?3) + OR (?5 IS NOT NULL AND sender = ?5) + ){owner_required_fragment}) + OR (visibility = 'system' AND ?6) + ) + ) + ){partition_sql} + ORDER BY id DESC + LIMIT ?7", + session_fragment = session_fragment.sql, + owner_fragment = owner_fragment.sql, + owner_required_fragment = owner_required_fragment.sql, + ))?; + let mut bind: Vec<&dyn rusqlite::types::ToSql> = vec![ + &principal.workspace_id, + &principal.agent_id, + &principal.persona_id, + &principal.session_key, + &principal.sender, + &system_allowed, + &limit, + ]; + for key in &legacy_session_keys { + bind.push(key); + } + if owner_required_fragment.bound_owner { + bind.push(&principal.owner_id); + } + for value in &partition_values { + bind.push(value); + } + let rows = stmt.query_map(bind.as_slice(), Self::message_event_from_row)?; + + rows.collect::, _>>().map_err(Into::into) + }) + .await? + } + + pub(super) async fn list_message_events_time_range_impl( + &self, + principal: &MemoryPrincipal, + descendant_workspace_root: Option<&str>, + start: &str, + end: &str, + limit: usize, + ) -> anyhow::Result> { + let pool = self.pool.clone(); + let principal = principal.clone(); + let descendant_workspace_root = descendant_workspace_root.map(str::to_string); + let start = start.to_string(); + let end = end.to_string(); + let limit = i64::try_from(limit.min(100_000)).unwrap_or(100_000); + let system_allowed = Self::is_system_principal(&principal); + anyhow::ensure!( + descendant_workspace_root.is_none() || system_allowed, + "descendant workspace event queries require a system principal" + ); + let descendant_pattern = descendant_workspace_root.as_ref().map(|root| { + let escaped = root.replace('\\', "\\\\").replace('%', "\\%").replace('_', "\\_"); + format!("{escaped}{}%", std::path::MAIN_SEPARATOR) + }); + let legacy_session_keys = Self::legacy_session_key_params(&principal); + let session_indices = Self::session_indices(4, 12, &principal, &legacy_session_keys); + let session_fragment = + crate::memory::session_predicate::session_visibility_or_fragment(SQLITE_DIALECT, &session_indices); + let owner_fragment = crate::memory::owner_predicate::owner_match_suffix( + SQLITE_DIALECT, + Self::owner_index(12, legacy_session_keys.len()), + principal.require_owner_match, + crate::memory::owner_predicate::has_owner_id(&principal), + ); + // OV-E (OQ-1): the `private` arm requires the owner for every reader, + // isolated or not, and admits nothing to a reader without one. Same + // placeholder as `owner_fragment`, so one bound value serves both. + let owner_required_fragment = crate::memory::owner_predicate::owner_match_suffix( + SQLITE_DIALECT, + Self::owner_index(12, legacy_session_keys.len()), + true, + crate::memory::owner_predicate::has_owner_id(&principal), + ); + + let (partition_sql, partition_values) = agent_partition_clause( + &principal, + Self::owner_index(12, legacy_session_keys.len()) + usize::from(owner_required_fragment.bound_owner), + ); + + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { + let reader = pool.read()?; + let conn = reader.connection()?; + let mut stmt = conn.prepare(&format!( + "SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, + parent_session_key, run_id, parent_run_id, agent_id, persona_id, + sender, recipient, role, event_type, source_ref_json, subject_ref_json, + goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, + content, content_hash, raw_payload_json, visibility, created_at, updated_at + FROM message_events + WHERE created_at >= ?9 AND created_at < ?10 + AND ( + visibility = 'global' + OR ( + ( + workspace_id = ?1 + OR (?6 AND ?7 IS NOT NULL AND ( + workspace_id = ?7 OR workspace_id LIKE ?8 ESCAPE '\\' + )) + ) + AND ( + (?6 AND ?7 IS NOT NULL) + OR visibility = 'workspace'{owner_fragment} + OR (visibility = 'agent' AND ( + (?2 IS NOT NULL AND agent_id = ?2) + OR (?3 IS NOT NULL AND persona_id = ?3) + )) + OR (visibility = 'session' AND {session_fragment}{owner_fragment}) + OR (visibility = 'private' AND ( + (?2 IS NOT NULL AND agent_id = ?2) + OR (?3 IS NOT NULL AND persona_id = ?3) + OR (?5 IS NOT NULL AND sender = ?5) + ){owner_required_fragment}) + OR (visibility = 'system' AND ?6) + ) + ) + ){partition_sql} + ORDER BY created_at ASC, id ASC + LIMIT ?11", + session_fragment = session_fragment.sql, + owner_fragment = owner_fragment.sql, + owner_required_fragment = owner_required_fragment.sql, + ))?; + let mut bind: Vec<&dyn rusqlite::types::ToSql> = vec![ + &principal.workspace_id, + &principal.agent_id, + &principal.persona_id, + &principal.session_key, + &principal.sender, + &system_allowed, + &descendant_workspace_root, + &descendant_pattern, + &start, + &end, + &limit, + ]; + for key in &legacy_session_keys { + bind.push(key); + } + if owner_required_fragment.bound_owner { + bind.push(&principal.owner_id); + } + for value in &partition_values { + bind.push(value); + } + let rows = stmt.query_map(bind.as_slice(), Self::message_event_from_row)?; + rows.collect::, _>>().map_err(Into::into) + }) + .await? + } + + pub(super) async fn load_recent_shared_context_impl( + &self, + query: SharedContextQuery, + ) -> anyhow::Result> { + let pool = self.pool.clone(); + let principal = query.principal; + let limit = Self::sanitize_conversation_limit(query.limit); + let after_id = query.since_event_id.unwrap_or(0); + let system_allowed = Self::is_system_principal(&principal); + let include_roles = query + .include_roles + .into_iter() + .map(|role| role.trim().to_ascii_lowercase()) + .filter(|role| !role.is_empty()) + .collect::>(); + + let legacy_session_keys = Self::legacy_session_key_params(&principal); + // Canonical key keeps its `?5` binding; legacy key(s) bind at trailing + // placeholders starting at `?9` (after limit at `?8`). + let session_indices = Self::session_indices(5, 9, &principal, &legacy_session_keys); + let session_fragment = + crate::memory::session_predicate::session_visibility_or_fragment(SQLITE_DIALECT, &session_indices); + let owner_fragment = crate::memory::owner_predicate::owner_match_suffix( + SQLITE_DIALECT, + Self::owner_index(9, legacy_session_keys.len()), + principal.require_owner_match, + crate::memory::owner_predicate::has_owner_id(&principal), + ); + // OV-E (OQ-1): the `private` arm requires the owner for every reader, + // isolated or not, and admits nothing to a reader without one. Same + // placeholder as `owner_fragment`, so one bound value serves both. + let owner_required_fragment = crate::memory::owner_predicate::owner_match_suffix( + SQLITE_DIALECT, + Self::owner_index(9, legacy_session_keys.len()), + true, + crate::memory::owner_predicate::has_owner_id(&principal), + ); + + let (partition_sql, partition_values) = agent_partition_clause( + &principal, + Self::owner_index(9, legacy_session_keys.len()) + usize::from(owner_required_fragment.bound_owner), + ); + + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { + let reader = pool.read()?; + let conn = reader.connection()?; + let mut stmt = conn.prepare(&format!( + "SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, + parent_session_key, run_id, parent_run_id, agent_id, persona_id, + sender, recipient, role, event_type, source_ref_json, subject_ref_json, + goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, + content, content_hash, raw_payload_json, visibility, created_at, updated_at + FROM message_events + WHERE id > ?1 + AND ( + visibility = 'global' + OR ( + workspace_id = ?2 + AND ( + visibility = 'workspace'{owner_required_fragment} + OR (visibility = 'agent' AND ( + (?3 IS NOT NULL AND agent_id = ?3) + OR (?4 IS NOT NULL AND persona_id = ?4) + )) + OR (visibility = 'session' AND {session_fragment}{owner_fragment}) + OR (visibility = 'private' AND ( + (?3 IS NOT NULL AND agent_id = ?3) + OR (?4 IS NOT NULL AND persona_id = ?4) + OR (?6 IS NOT NULL AND sender = ?6) + ){owner_required_fragment}) + OR (visibility = 'system' AND ?7) + ) + ) + ){partition_sql} + ORDER BY id DESC + LIMIT ?8", + session_fragment = session_fragment.sql, + owner_fragment = owner_fragment.sql, + owner_required_fragment = owner_required_fragment.sql, + ))?; + let mut bind: Vec<&dyn rusqlite::types::ToSql> = vec![ + &after_id, + &principal.workspace_id, + &principal.agent_id, + &principal.persona_id, + &principal.session_key, + &principal.sender, + &system_allowed, + &limit, + ]; + for key in &legacy_session_keys { + bind.push(key); + } + if owner_required_fragment.bound_owner { + bind.push(&principal.owner_id); + } + for value in &partition_values { + bind.push(value); + } + let rows = stmt.query_map(bind.as_slice(), Self::message_event_from_row)?; + + let mut events = rows.collect::, _>>()?; + events.reverse(); + if include_roles.is_empty() { + return Ok(events); + } + Ok(events + .into_iter() + .filter(|event| include_roles.contains(&event.role.to_ascii_lowercase())) + .collect()) + }) + .await? + } + + pub(super) async fn retrieve_decision_session_impl( + &self, + principal: &MemoryPrincipal, + before_event_id: &str, + limit: u8, + deadline: std::time::Instant, + ) -> anyhow::Result> { + anyhow::ensure!( + (1..=5).contains(&limit) && !before_event_id.is_empty() && before_event_id.len() <= 128, + "invalid decision Session bounds" + ); + anyhow::ensure!( + std::time::Instant::now() < deadline, + "decision Session deadline expired" + ); + let session_key = principal + .session_key + .as_ref() + .filter(|key| !key.trim().is_empty()) + .ok_or_else(|| anyhow::anyhow!("selected Session requires a session"))? + .clone(); + anyhow::ensure!( + crate::memory::owner_predicate::has_owner_id(principal), + "selected Session requires an authenticated owner" + ); + let principal = principal.clone(); + let before_event_id = before_event_id.to_owned(); + let db_path = self.db_path.clone(); + let limit = i64::from(limit); + let system_allowed = Self::is_system_principal(&principal); + let legacy_session_keys = Self::legacy_session_key_params(&principal); + // Canonical key keeps its `?3` binding; legacy key(s) bind at trailing + // placeholders starting at `?9` (after limit at `?8`). The top-level + // `session_key` hard filter becomes an `IN (...)` read-merge union. + let mut session_indices = vec![3usize]; + for offset in 0..legacy_session_keys.len() { + session_indices.push(9 + offset); + } + let session_fragment = + crate::memory::session_predicate::session_key_match_fragment(SQLITE_DIALECT, &session_indices); + let owner_fragment = crate::memory::owner_predicate::owner_match_suffix( + SQLITE_DIALECT, + Self::owner_index(9, legacy_session_keys.len()), + principal.require_owner_match, + crate::memory::owner_predicate::has_owner_id(&principal), + ); + // OV-E (OQ-1): the `private` arm requires the owner for every reader, + // isolated or not, and admits nothing to a reader without one. Same + // placeholder as `owner_fragment`, so one bound value serves both. + let owner_required_fragment = crate::memory::owner_predicate::owner_match_suffix( + SQLITE_DIALECT, + Self::owner_index(9, legacy_session_keys.len()), + true, + crate::memory::owner_predicate::has_owner_id(&principal), + ); + // OV-C: `workspace` is owner-qualified for an owner-isolated reader; + // every other reader's statement is byte-identical. + let shared_tiers_arm = crate::memory::owner_predicate::session_context_shared_tiers(&owner_fragment); + + let (partition_sql, partition_values) = agent_partition_clause( + &principal, + Self::owner_index(9, legacy_session_keys.len()) + usize::from(owner_required_fragment.bound_owner), + ); + + crate::runtime::blocking::spawn_blocking( + move || -> anyhow::Result> { + let conn = Self::open_rehearsal_reader(&db_path, deadline)?; + let before_id: i64 = conn + .query_row( + "SELECT id FROM message_events WHERE event_id = ?1 AND workspace_id = ?2 + AND session_key = ?3 AND owner_id = ?4 AND role = 'user' AND event_type = 'message.created'", + params![before_event_id, principal.workspace_id, session_key, principal.owner_id], + |row| row.get(0), + ) + .optional()? + .ok_or_else(|| anyhow::anyhow!("selected Session source event is unavailable"))?; + let mut stmt = conn.prepare(&format!( + "SELECT event_id, role, content, created_at + FROM message_events + WHERE id < ?1 + AND workspace_id = ?2 + AND {session_fragment} + AND ( + {shared_tiers_arm} + OR (visibility = 'agent' AND ( + (?4 IS NOT NULL AND agent_id = ?4) + OR (?5 IS NOT NULL AND persona_id = ?5) + )) + OR (visibility = 'session'{owner_fragment}) + OR (visibility = 'private' AND ( + (?4 IS NOT NULL AND agent_id = ?4) + OR (?5 IS NOT NULL AND persona_id = ?5) + OR (?6 IS NOT NULL AND sender = ?6) + ){owner_required_fragment}) + OR (visibility = 'system' AND ?7) + ) + AND role IN ('user', 'assistant') AND event_type = 'message.created'{partition_sql} + AND length(CAST(event_id AS BLOB)) <= 128 + AND length(CAST(content AS BLOB)) <= 4096 + AND length(CAST(created_at AS BLOB)) <= 64 + ORDER BY id DESC + LIMIT ?8", + session_fragment = session_fragment.sql, + owner_fragment = owner_fragment.sql, + owner_required_fragment = owner_required_fragment.sql, + ))?; + let mut bind: Vec<&dyn rusqlite::types::ToSql> = vec![ + &before_id, + &principal.workspace_id, + &session_key, + &principal.agent_id, + &principal.persona_id, + &principal.sender, + &system_allowed, + &limit, + ]; + for key in &legacy_session_keys { + bind.push(key); + } + if owner_required_fragment.bound_owner { + bind.push(&principal.owner_id); + } + for value in &partition_values { + bind.push(value); + } + let rows = stmt.query_map(bind.as_slice(), |row| { + Ok(crate::memory::traits::DecisionSessionHit { + event_id: row.get(0)?, + role: row.get(1)?, + content: row.get(2)?, + created_at: row.get(3)?, + }) + })?; + let mut hits = rows.collect::>>()?; + anyhow::ensure!( + std::time::Instant::now() < deadline, + "decision Session deadline expired" + ); + hits.reverse(); + Ok(hits) + }, + ) + .await? + } + + pub(super) async fn load_recent_session_context_impl( + &self, + query: SessionContextQuery, + ) -> anyhow::Result> { + let mut events = self.session_context_page(query, None).await?; + events.reverse(); + Ok(events) + } + + /// `load_recent_session_context` restricted to rows below `before_id`, + /// newest first (the paging read of a complete provenance pool). + pub(super) async fn load_session_context_before_impl( + &self, + query: SessionContextQuery, + before_id: i64, + ) -> anyhow::Result> { + self.session_context_page(query, Some(before_id)).await + } + + /// The session-context statement, newest first. `before_id` adds one + /// trailing bind (`AND id < ?N`) after every other placeholder. + async fn session_context_page( + &self, + query: SessionContextQuery, + before_id: Option, + ) -> anyhow::Result> { + let Some(session_key) = query.principal.session_key.clone() else { + return Ok(Vec::new()); + }; + let pool = self.pool.clone(); + let principal = query.principal; + let limit = Self::sanitize_conversation_limit(query.limit); + let after_id = query.since_event_id.unwrap_or(0); + let system_allowed = Self::is_system_principal(&principal); + let include_roles = query + .include_roles + .into_iter() + .map(|role| role.trim().to_ascii_lowercase()) + .filter(|role| !role.is_empty()) + .collect::>(); + + let legacy_session_keys = Self::legacy_session_key_params(&principal); + // Canonical key keeps its `?3` binding; legacy key(s) bind at trailing + // placeholders starting at `?9` (after limit at `?8`). The top-level + // `session_key` hard filter becomes an `IN (...)` read-merge union. + let mut session_indices = vec![3usize]; + for offset in 0..legacy_session_keys.len() { + session_indices.push(9 + offset); + } + let session_fragment = + crate::memory::session_predicate::session_key_match_fragment(SQLITE_DIALECT, &session_indices); + let owner_index = Self::owner_index(9, legacy_session_keys.len()); + let owner_fragment = crate::memory::owner_predicate::owner_match_suffix( + SQLITE_DIALECT, + owner_index, + principal.require_owner_match, + crate::memory::owner_predicate::has_owner_id(&principal), + ); + // OV-E (OQ-1): the `private` arm requires the owner for every reader, + // isolated or not, and admits nothing to a reader without one. Same + // placeholder as `owner_fragment`, so one bound value serves both. + let owner_required_fragment = crate::memory::owner_predicate::owner_match_suffix( + SQLITE_DIALECT, + owner_index, + true, + crate::memory::owner_predicate::has_owner_id(&principal), + ); + let first_role_index = owner_index + usize::from(owner_required_fragment.bound_owner); + let role_fragment = if include_roles.is_empty() { + "1 = 1".to_string() + } else { + format!( + "role IN ({})", + (first_role_index..first_role_index + include_roles.len()) + .map(|index| format!("?{index}")) + .collect::>() + .join(", ") + ) + }; + // OV-C: `workspace` is owner-qualified for an owner-isolated reader; + // every other reader's statement is byte-identical. + let shared_tiers_arm = crate::memory::owner_predicate::session_context_shared_tiers(&owner_fragment); + let before_fragment = before_id.map_or_else(String::new, |_| { + format!(" AND id < ?{}", first_role_index + include_roles.len()) + }); + // MA-01h: the partition binds after every other placeholder. + let (partition_sql, partition_values) = agent_partition_clause( + &principal, + first_role_index + include_roles.len() + usize::from(before_id.is_some()), + ); + + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { + let reader = pool.read()?; + let conn = reader.connection()?; + let mut stmt = conn.prepare(&format!( + "SELECT id, event_id, idempotency_key, workspace_id, owner_id, source, channel, session_key, + parent_session_key, run_id, parent_run_id, agent_id, persona_id, + sender, recipient, role, event_type, source_ref_json, subject_ref_json, + goal_id, causation_event_id, correlation_id, attempt_id, lease_epoch, config_generation_id, config_source_revision, + content, content_hash, raw_payload_json, visibility, created_at, updated_at + FROM message_events + WHERE id > ?1 + AND workspace_id = ?2 + AND {session_fragment} + AND {role_fragment} + AND ( + {shared_tiers_arm} + OR (visibility = 'agent' AND ( + (?4 IS NOT NULL AND agent_id = ?4) + OR (?5 IS NOT NULL AND persona_id = ?5) + )) + OR (visibility = 'session'{owner_fragment}) + OR (visibility = 'private' AND ( + (?4 IS NOT NULL AND agent_id = ?4) + OR (?5 IS NOT NULL AND persona_id = ?5) + OR (?6 IS NOT NULL AND sender = ?6) + ){owner_required_fragment}) + OR (visibility = 'system' AND ?7) + ){before_fragment}{partition_sql} + ORDER BY id DESC + LIMIT ?8", + session_fragment = session_fragment.sql, + role_fragment = role_fragment, + owner_fragment = owner_fragment.sql, + owner_required_fragment = owner_required_fragment.sql, + ))?; + let mut bind: Vec<&dyn rusqlite::types::ToSql> = vec![ + &after_id, + &principal.workspace_id, + &session_key, + &principal.agent_id, + &principal.persona_id, + &principal.sender, + &system_allowed, + &limit, + ]; + for key in &legacy_session_keys { + bind.push(key); + } + if owner_required_fragment.bound_owner { + bind.push(&principal.owner_id); + } + for role in &include_roles { + bind.push(role); + } + if let Some(before_id) = &before_id { + bind.push(before_id); + } + for value in &partition_values { + bind.push(value); + } + let rows = stmt.query_map(bind.as_slice(), Self::message_event_from_row)?; + + Ok(rows.collect::, _>>()?) + }) + .await? + } + + pub(super) async fn append_memory_event_impl(&self, input: MemoryEventInput) -> anyhow::Result { + let pool = self.pool.clone(); + + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result { + let conn = pool.write(); + let tx = begin_immediate(&conn)?; + let now = Utc::now().to_rfc3339(); + let event_id = input.event_id.unwrap_or_else(|| Uuid::new_v4().to_string()); + let bound_scope = super::agent_migration::resolve_input_scope( + &tx, + input.agent_partition.as_ref(), + input.session_key.as_deref(), + &input.workspace_id, + input.owner_id.as_deref(), + )?; + tx.execute( + "INSERT OR IGNORE INTO memory_events ( + event_id, workspace_id, owner_id, event_type, subject_table, subject_id, + session_key, run_id, parent_run_id, agent_id, persona_id, visibility, payload_json, created_at, ma_scope_id + ) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)", + params![ + event_id, + input.workspace_id, + input.owner_id, + input.event_type, + input.subject_table, + input.subject_id, + input.session_key, + input.run_id, + input.parent_run_id, + input.agent_id, + input.persona_id, + input.visibility.as_str(), + input.payload_json, + now, + bound_scope + ], + )?; + super::agent_migration::refuse_if_stored_scope_differs( + &tx, + "memory_events", + "event_id", + &event_id, + &bound_scope, + )?; + + let event = tx.query_row( + "SELECT id, event_id, workspace_id, owner_id, event_type, subject_table, subject_id, + session_key, run_id, parent_run_id, agent_id, persona_id, visibility, payload_json, created_at + FROM memory_events + WHERE event_id = ?1 + LIMIT 1", + params![event_id], + Self::memory_event_from_row, + )?; + super::sync_lifecycle::memory_written(&tx,&event)?; + tx.commit()?; + Ok(event) + }) + .await? + } + + pub(super) async fn list_memory_events_since_impl( + &self, + principal: &MemoryPrincipal, + after_id: i64, + limit: usize, + ) -> anyhow::Result> { + let pool = self.pool.clone(); + let principal = principal.clone(); + let limit = i64::try_from(limit.max(1)).unwrap_or(i64::MAX); + + // C03: the owner parameter binds at the first free trailing slot (`?8`). + let owner_fragment = crate::memory::owner_predicate::owner_match_suffix( + SQLITE_DIALECT, + 8, + principal.require_owner_match, + crate::memory::owner_predicate::has_owner_id(&principal), + ); + // OV-E (OQ-1): the `private` arm requires the owner for every reader, + // isolated or not, and admits nothing to a reader without one. Same + // placeholder as `owner_fragment`, so one bound value serves both. + let owner_required_fragment = crate::memory::owner_predicate::owner_match_suffix( + SQLITE_DIALECT, + 8, + true, + crate::memory::owner_predicate::has_owner_id(&principal), + ); + + let (partition_sql, partition_values) = + agent_partition_clause(&principal, 8 + usize::from(owner_required_fragment.bound_owner)); + + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { + let reader = pool.read()?; + let conn = reader.connection()?; + let system_allowed = + principal.agent_id.as_deref() == Some("system") || principal.persona_id.as_deref() == Some("system"); + let mut stmt = conn.prepare(&format!( + "SELECT id, event_id, workspace_id, owner_id, event_type, subject_table, subject_id, + session_key, run_id, parent_run_id, agent_id, persona_id, visibility, payload_json, created_at + FROM memory_events + WHERE id > ?1 + AND ( + visibility = 'global' + OR ( + workspace_id = ?2 + AND ( + visibility = 'workspace'{owner_fragment} + OR (visibility = 'agent' AND ( + (?3 IS NOT NULL AND agent_id = ?3) + OR (?4 IS NOT NULL AND persona_id = ?4) + )) + OR (visibility = 'session' AND ?5 IS NOT NULL AND session_key = ?5{owner_fragment}) + OR (visibility = 'private' AND ( + (?3 IS NOT NULL AND agent_id = ?3) + OR (?4 IS NOT NULL AND persona_id = ?4) + OR (event_type = 'document.ingested' AND agent_id IS NULL AND persona_id IS NULL) + ){owner_required_fragment}) + OR (visibility = 'system' AND ?6) + ) + ) + ){partition_sql} + ORDER BY id ASC + LIMIT ?7", + owner_fragment = owner_fragment.sql, + owner_required_fragment = owner_required_fragment.sql, + ))?; + let mut bind: Vec<&dyn rusqlite::types::ToSql> = vec![ + &after_id, + &principal.workspace_id, + &principal.agent_id, + &principal.persona_id, + &principal.session_key, + &system_allowed, + &limit, + ]; + if owner_required_fragment.bound_owner { + bind.push(&principal.owner_id); + } + for value in &partition_values { + bind.push(value); + } + let rows = stmt.query_map(bind.as_slice(), Self::memory_event_from_row)?; + rows.collect::, _>>().map_err(Into::into) + }) + .await? + } + + pub(super) async fn list_memory_events_recent_impl( + &self, + principal: &MemoryPrincipal, + limit: usize, + ) -> anyhow::Result> { + let pool = self.pool.clone(); + let principal = principal.clone(); + let limit = i64::try_from(limit.max(1)).unwrap_or(i64::MAX); + + // C03: the owner parameter binds at the first free trailing slot (`?7`). + let owner_fragment = crate::memory::owner_predicate::owner_match_suffix( + SQLITE_DIALECT, + 7, + principal.require_owner_match, + crate::memory::owner_predicate::has_owner_id(&principal), + ); + // OV-E (OQ-1): the `private` arm requires the owner for every reader, + // isolated or not, and admits nothing to a reader without one. Same + // placeholder as `owner_fragment`, so one bound value serves both. + let owner_required_fragment = crate::memory::owner_predicate::owner_match_suffix( + SQLITE_DIALECT, + 7, + true, + crate::memory::owner_predicate::has_owner_id(&principal), + ); + + let (partition_sql, partition_values) = + agent_partition_clause(&principal, 7 + usize::from(owner_required_fragment.bound_owner)); + + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { + let reader = pool.read()?; + let conn = reader.connection()?; + let system_allowed = + principal.agent_id.as_deref() == Some("system") || principal.persona_id.as_deref() == Some("system"); + let mut stmt = conn.prepare(&format!( + "SELECT id, event_id, workspace_id, owner_id, event_type, subject_table, subject_id, + session_key, run_id, parent_run_id, agent_id, persona_id, visibility, payload_json, created_at + FROM memory_events + WHERE ( + visibility = 'global' + OR ( + workspace_id = ?1 + AND ( + visibility = 'workspace'{owner_fragment} + OR (visibility = 'agent' AND ( + (?2 IS NOT NULL AND agent_id = ?2) + OR (?3 IS NOT NULL AND persona_id = ?3) + )) + OR (visibility = 'session' AND ?4 IS NOT NULL AND session_key = ?4{owner_fragment}) + OR (visibility = 'private' AND ( + (?2 IS NOT NULL AND agent_id = ?2) + OR (?3 IS NOT NULL AND persona_id = ?3) + OR (event_type = 'document.ingested' AND agent_id IS NULL AND persona_id IS NULL) + ){owner_required_fragment}) + OR (visibility = 'system' AND ?5) + ) + ) + ){partition_sql} + ORDER BY id DESC + LIMIT ?6", + owner_fragment = owner_fragment.sql, + owner_required_fragment = owner_required_fragment.sql, + ))?; + let mut bind: Vec<&dyn rusqlite::types::ToSql> = vec![ + &principal.workspace_id, + &principal.agent_id, + &principal.persona_id, + &principal.session_key, + &system_allowed, + &limit, + ]; + if owner_required_fragment.bound_owner { + bind.push(&principal.owner_id); + } + for value in &partition_values { + bind.push(value); + } + let rows = stmt.query_map(bind.as_slice(), Self::memory_event_from_row)?; + rows.collect::, _>>().map_err(Into::into) + }) + .await? + } +} + +#[cfg(test)] +struct AppendSnapshotHoldInner { + db_path: std::path::PathBuf, + run_id: String, + idempotency_key: String, + entered: std::sync::mpsc::SyncSender<()>, + release: std::sync::mpsc::Receiver<()>, +} + +#[cfg(test)] +static APPEND_SNAPSHOT_HOLD: parking_lot::Mutex> = parking_lot::Mutex::new(None); + +#[cfg(test)] +pub(crate) struct AppendSnapshotHold { + pub entered: std::sync::mpsc::Receiver<()>, + pub release: std::sync::mpsc::SyncSender<()>, +} + +#[cfg(test)] +pub(crate) struct AppendSnapshotHoldGuard; + +#[cfg(test)] +impl Drop for AppendSnapshotHoldGuard { + fn drop(&mut self) { + *APPEND_SNAPSHOT_HOLD.lock() = None; + } +} + +/// Park the matching child-segment append after its real tombstone-fence +/// SELECT so a concurrent opener can commit. Unrelated appends leave the +/// hook in place. `BEGIN DEFERRED` then fails the INSERT with +/// SQLITE_BUSY_SNAPSHOT; `BEGIN IMMEDIATE` already holds the write lock, +/// so the others wait. +#[cfg(test)] +#[must_use] +pub(crate) fn arm_append_snapshot_hold( + db_path: std::path::PathBuf, + run_id: impl Into, + idempotency_key: impl Into, +) -> (AppendSnapshotHold, AppendSnapshotHoldGuard) { + let (entered_tx, entered_rx) = std::sync::mpsc::sync_channel(1); + let (release_tx, release_rx) = std::sync::mpsc::sync_channel(1); + *APPEND_SNAPSHOT_HOLD.lock() = Some(AppendSnapshotHoldInner { + db_path, + run_id: run_id.into(), + idempotency_key: idempotency_key.into(), + entered: entered_tx, + release: release_rx, + }); + ( + AppendSnapshotHold { + entered: entered_rx, + release: release_tx, + }, + AppendSnapshotHoldGuard, + ) +} diff --git a/src/memory/sqlite/events/section_3.rs b/src/memory/sqlite/events/section_3.rs new file mode 100644 index 000000000..a526c837b --- /dev/null +++ b/src/memory/sqlite/events/section_3.rs @@ -0,0 +1,33 @@ +#[cfg(test)] +fn hold_paths_match(left: &std::path::Path, right: &std::path::Path) -> bool { + if left == right { + return true; + } + match (left.canonicalize(), right.canonicalize()) { + (Ok(left), Ok(right)) => left == right, + _ => false, + } +} + +#[cfg(test)] +pub(super) fn hold_append_snapshot_for_test( + input: &MessageEventInput, + db_path: &std::path::Path, +) -> anyhow::Result<()> { + let mut slot = APPEND_SNAPSHOT_HOLD.lock(); + let matched = slot.as_ref().is_some_and(|hold| { + input.run_id.as_deref() == Some(hold.run_id.as_str()) + && input.idempotency_key.as_deref() == Some(hold.idempotency_key.as_str()) + && hold_paths_match(&hold.db_path, db_path) + }); + if !matched { + return Ok(()); + } + let hold = slot + .take() + .ok_or_else(|| anyhow::anyhow!("test: snapshot hold vanished after identity match"))?; + drop(slot); + let _ = hold.entered.send(()); + let _ = hold.release.recv_timeout(std::time::Duration::from_secs(60)); + Ok(()) +} diff --git a/src/memory/sqlite/mailbox.rs b/src/memory/sqlite/mailbox.rs index 69e642dd3..d3f8f595e 100644 --- a/src/memory/sqlite/mailbox.rs +++ b/src/memory/sqlite/mailbox.rs @@ -5,11 +5,13 @@ mod accept; mod adopt; pub(super) mod child_projection; mod deliver; +mod local_runtime; mod model; mod outbox; pub(super) mod pin; mod publish; mod receipt; +mod retry; mod stream; pub use outbox::MailboxOutbound; mod erase; @@ -31,10 +33,13 @@ pub struct SqliteMailbox { local_instance: String, secret: Arc<[u8; 32]>, clock: Arc, - limits: crate::config::schema::RemoteTreeLimits, } impl SqliteMailbox { + pub(crate) fn register_drainer(&self, drainer: &Arc) { + self.memory.mailbox_runtime.register_drainer(drainer); + } + pub fn validate_scope( &self, scope: &crate::messaging::mailbox::MailboxScope, @@ -52,7 +57,6 @@ impl SqliteMailbox { local_instance: String, secret: [u8; 32], clock: Arc, - limits: crate::config::schema::RemoteTreeLimits, ) -> MailboxResult { crate::messaging::mailbox::bounded(&local_instance, 512)?; if clock.now() < 0 { @@ -63,7 +67,6 @@ impl SqliteMailbox { local_instance, secret: Arc::new(secret), clock, - limits, }) } } diff --git a/src/memory/sqlite/mailbox/adopt.rs b/src/memory/sqlite/mailbox/adopt.rs index 97adfe014..ce901fe8d 100644 --- a/src/memory/sqlite/mailbox/adopt.rs +++ b/src/memory/sqlite/mailbox/adopt.rs @@ -1,6 +1,6 @@ //! Transcript and checkpoint have exactly one commit boundary. use base64::{Engine as _, engine::general_purpose::STANDARD}; -use rusqlite::{Transaction, TransactionBehavior, params}; +use rusqlite::{OptionalExtension, Transaction, TransactionBehavior, params}; use uuid::Uuid; use super::{ @@ -91,7 +91,12 @@ impl SqliteMailbox { if pin.to_pin_token.is_empty() { return Err(MailboxError::CorruptState); } - let content = project_body(&mime, &bytes)?; + let content = format!( + "[message from {}/{}]\n{}", + stream.from.session, + stream.from.agent, + project_body(&mime, &bytes)? + ); let timestamp = chrono::DateTime::from_timestamp(now, 0) .ok_or(MailboxError::InvalidMetadata)? .to_rfc3339(); @@ -122,7 +127,72 @@ impl SqliteMailbox { common: saved.meta.common.clone(), }; let agent = (stream.to.agent != "main").then_some(stream.to.agent.as_str()); - tx.execute("INSERT INTO message_events(event_id,idempotency_key,workspace_id,owner_id,source,session_key,role,event_type,source_ref_json,content,visibility,created_at,updated_at,agent_id,ma_scope_id) VALUES (?1,?2,?3,?4,'prx_mailbox',?5,'user','message.created',?6,?7,'private',?8,?8,?9,?10)",params![event_id.to_string(),format!("prx_mailbox/{}/{}",saved.message_id,saved.meta.acceptance_id),scope.workspace_id,scope.owner_id,key,encode(&reference)?,content,timestamp,agent,scope.scope_id.to_string()]).map_err(storage_error)?; + let source:Option<(Option,Option,Option)>=tx.query_row( + "SELECT run_id,parent_session_key,parent_run_id FROM message_events WHERE workspace_id=?1 AND owner_id=?2 AND session_key=?3 AND source!='prx_mailbox' ORDER BY id DESC LIMIT 1", + params![scope.workspace_id,scope.owner_id,key],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?))).optional().map_err(storage_error)?; + let (run, parent_session, parent_run) = source.unwrap_or_default(); + let scope_agent: String = tx + .query_row( + "SELECT agent_key FROM agent_scopes WHERE scope_id=?1", + [scope.scope_id.to_string()], + |r| r.get(0), + ) + .map_err(storage_error)?; + let partition = crate::memory::AgentPartition { + workspace_id: scope.workspace_id.clone(), + owner_id: scope.owner_id.clone(), + key: if let Some(name) = scope_agent.strip_prefix("n:") { + crate::memory::PartitionKey::Named { + name: crate::config::agent_name::AgentName::parse(name).map_err(|_| MailboxError::CorruptState)?, + incarnation: scope.incarnation, + } + } else { + crate::memory::PartitionKey::Main + }, + }; + let remote = saved.meta.common.origin == crate::messaging::MessageOrigin::RemotePeer; + let from = if remote { + serde_json::json!({"session_key":stream.from.session,"session":stream.from.session,"agent":stream.from.agent,"instance":stream.from.instance,"spiffe_id":saved.meta.common.auth.as_ref().map(|auth|auth.subject.clone())}) + } else { + serde_json::json!({"session_key":stream.from.session,"agent":stream.from.agent}) + }; + let metadata = serde_json::json!({"provenance":if remote {"peer"}else{"session"},"from":from,"message_id":saved.message_id,"chain":saved.meta.common.chain(saved.message_id)}); + let input = crate::memory::MessageEventInput { + event_id: Some(event_id.to_string()), + idempotency_key: Some(format!("prx_mailbox/{}/{}", saved.message_id, saved.meta.acceptance_id)), + workspace_id: scope.workspace_id.clone(), + owner_id: Some(scope.owner_id.clone()), + source: crate::memory::MessageEventSource::Other("prx_mailbox".into()), + channel: Some("mailbox".into()), + session_key: Some(key.clone()), + parent_session_key: parent_session, + run_id: run, + parent_run_id: parent_run, + agent_id: agent.map(str::to_owned), + persona_id: None, + sender: Some(stream.from.session.clone()), + recipient: Some(key.clone()), + role: "user".into(), + event_type: "message.created".into(), + subject: None, + goal_id: None, + causation_event_id: None, + correlation_id: None, + attempt_id: None, + lease_epoch: None, + config_generation_id: None, + config_source_revision: None, + content: content.clone(), + raw_payload_json: Some(metadata.to_string()), + visibility: crate::memory::MemoryVisibility::Private, + agent_partition: Some(partition), + }; + super::super::SqliteMemory::append_event_row(&tx, input, false).map_err(storage_error)?; + tx.execute( + "UPDATE message_events SET source_ref_json=?2 WHERE event_id=?1", + params![event_id.to_string(), encode(&reference)?], + ) + .map_err(storage_error)?; tx.execute("INSERT INTO conversation_turns(session_key,owner_id,role,content,timestamp,message_id,message_event_id,agent_id,visibility,ma_scope_id) VALUES (?1,?2,'user',?3,?4,?5,?6,?7,'private',?8)",params![key,scope.owner_id,content,timestamp,saved.message_id.to_string(),event_id.to_string(),agent,scope.scope_id.to_string()]).map_err(storage_error)?; saved.adopted_turn_id = Some(tx.last_insert_rowid()); tx.execute( diff --git a/src/memory/sqlite/mailbox/harness.rs b/src/memory/sqlite/mailbox/harness.rs index fbd57692e..912d9517b 100644 --- a/src/memory/sqlite/mailbox/harness.rs +++ b/src/memory/sqlite/mailbox/harness.rs @@ -34,13 +34,7 @@ pub fn accept_adopt(workspace: &Path) -> anyhow::Result<()> { tx.commit()?; scope }; - let store = SqliteMailbox::new( - memory, - "prx_harness".into(), - [31; 32], - Arc::new(SystemMailboxClock), - crate::config::schema::RemoteTreeLimits::default(), - )?; + let store = SqliteMailbox::new(memory, "prx_harness".into(), [31; 32], Arc::new(SystemMailboxClock))?; let authority = MailboxAuthority::local(workspace_id, source.clone(), target.clone())?; let request_path = workspace.join("mailbox-harness-request.json"); let message: PrxMessage = if request_path.exists() { diff --git a/src/memory/sqlite/mailbox/local_runtime.rs b/src/memory/sqlite/mailbox/local_runtime.rs new file mode 100644 index 000000000..aa868deb0 --- /dev/null +++ b/src/memory/sqlite/mailbox/local_runtime.rs @@ -0,0 +1,137 @@ +//! Trusted runtime resolution of owner-scoped session addresses. +use super::{SqliteMailbox, pin, storage_error}; +use crate::memory::{AgentPartition, PartitionKey}; +use crate::messaging::mailbox::{MailboxError, MailboxResult, MailboxScope}; +use crate::messaging::{CausalChain, SessionAddr}; +use rusqlite::{OptionalExtension, Transaction, TransactionBehavior, params}; + +impl SqliteMailbox { + pub(crate) fn hold_input( + &self, + scope: &MailboxScope, + target: &SessionAddr, + ) -> MailboxResult> { + let writer = self.memory.pool.write(); + pin::check_scope(&writer, scope, target, None, true)?; + Ok(std::sync::Arc::new( + self.memory.mailbox_runtime.cache_lease(scope.scope_id), + )) + } + pub(crate) fn validate_input( + &self, + workspace: &str, + target: &SessionAddr, + event: uuid::Uuid, + text: &str, + ) -> MailboxResult<()> { + let scope = self.session_scope(workspace, target, false)?; + self.validate_scope(&scope, target)?; + let writer = self.memory.pool.write(); + let present:bool=writer.query_row("SELECT EXISTS(SELECT 1 FROM message_events WHERE event_id=?1 AND workspace_id=?2 AND owner_id=?3 AND session_key=?4 AND source='prx_mailbox' AND role='user' AND content=?5 AND ma_scope_id=?6)",params![event.to_string(),scope.workspace_id,target.owner,target.session,text,scope.scope_id.to_string()],|r|r.get(0)).map_err(storage_error)?; + if present { Ok(()) } else { Err(MailboxError::Fenced) } + } + + pub fn has_pending(&self, scope: &MailboxScope, target: &SessionAddr) -> MailboxResult { + self.validate_scope(scope, target)?; + let writer = self.memory.pool.write(); + writer.query_row("SELECT EXISTS(SELECT 1 FROM prx_mailbox_messages m JOIN prx_mailbox_seq s ON s.stream_id=m.stream_id WHERE m.ma_scope_id=?1 AND s.to_addr=?2 AND m.state IN(0,1))", params![scope.scope_id.to_string(),serde_json::to_string(target).map_err(storage_error)?], |r| r.get(0)).map_err(storage_error) + } + + pub fn session_scope( + &self, + workspace: &str, + address: &SessionAddr, + registered: bool, + ) -> MailboxResult { + crate::messaging::mailbox::validate_address(address)?; + if address.instance != self.local_instance { + return Err(MailboxError::Unauthorized); + } + let writer = self.memory.pool.write(); + let tx = Transaction::new_unchecked(&writer, TransactionBehavior::Immediate).map_err(storage_error)?; + let child:Option<(String,String,i64)>=tx.query_row("SELECT ma_scope_id,incarnation,generation FROM child_sessions WHERE workspace_id=?1 AND owner_id=?2 AND session_id=?3 AND json_extract(record,'$.agent')=?4", + params![workspace,address.owner,address.session,address.agent],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?))).optional().map_err(storage_error)?; + if let Some((scope, inc, generation)) = child { + let scope = pin::scope_from_row(workspace.into(), address.owner.clone(), scope, inc, generation)?; + pin::check_scope(&tx, &scope, address, Some(&address.session), true)?; + tx.commit().map_err(storage_error)?; + return Ok(scope); + } + let actual:Option=tx.query_row("SELECT CASE WHEN s.agent_key='m' THEN 'main' ELSE substr(s.agent_key,3) END FROM message_events e JOIN agent_scopes s ON s.scope_id=e.ma_scope_id WHERE e.workspace_id=?1 AND e.owner_id=?2 AND e.session_key=?3 ORDER BY e.id DESC LIMIT 1",params![workspace,address.owner,address.session],|r|r.get(0)).optional().map_err(storage_error)?; + if actual.as_deref().is_some_and(|agent| agent != address.agent) { + return Err(MailboxError::Unauthorized); + } + let known:bool=tx.query_row("SELECT EXISTS(SELECT 1 FROM message_events WHERE workspace_id=?1 AND owner_id=?2 AND session_key=?3) OR EXISTS(SELECT 1 FROM sessions WHERE owner_id=?2 AND session_key=?3) OR EXISTS(SELECT 1 FROM child_sessions WHERE workspace_id=?1 AND owner_id=?2 AND session_id=?3)",params![workspace,address.owner,address.session],|r|r.get(0)).map_err(storage_error)?; + if !known && !registered { + return Err(MailboxError::Unauthorized); + } + let key = if address.agent == "main" { + PartitionKey::Main + } else { + let agent = crate::config::agent_name::AgentName::parse(&address.agent) + .map_err(|_| MailboxError::InvalidAddress)?; + let incarnation:String=tx.query_row("SELECT incarnation FROM agent_incarnations WHERE workspace_id=?1 AND owner_id=?2 AND agent_key=?3 AND state='active'",params![workspace,address.owner,format!("n:{}",address.agent)],|r|r.get(0)).optional().map_err(storage_error)?.ok_or(MailboxError::Unauthorized)?; + PartitionKey::Named { + name: agent, + incarnation: uuid::Uuid::parse_str(&incarnation).map_err(|_| MailboxError::CorruptState)?, + } + }; + let scope = super::super::agent_migration::resolve_write_scope( + &tx, + &AgentPartition { + workspace_id: workspace.into(), + owner_id: address.owner.clone(), + key, + }, + Some(&address.session), + ) + .map_err(storage_error)?; + let (inc, generation): (String, i64) = tx + .query_row( + "SELECT incarnation,generation FROM agent_scopes WHERE scope_id=?1", + [&scope], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .map_err(storage_error)?; + let scope = pin::scope_from_row(workspace.into(), address.owner.clone(), scope, inc, generation)?; + pin::check_scope(&tx, &scope, address, Some(&address.session), true)?; + tx.commit().map_err(storage_error)?; + Ok(scope) + } + pub fn logical_agent(&self, workspace: &str, owner: &str, session: &str) -> MailboxResult> { + let writer = self.memory.pool.write(); + let child:Option>=writer.query_row("SELECT json_extract(record,'$.agent') FROM child_sessions WHERE workspace_id=?1 AND owner_id=?2 AND session_id=?3",params![workspace,owner,session],|r|r.get(0)).optional().map_err(storage_error)?; + if let Some(agent) = child.flatten() { + return Ok(Some(agent)); + } + writer.query_row("SELECT CASE WHEN s.agent_key='m' THEN 'main' ELSE substr(s.agent_key,3) END FROM message_events e JOIN agent_scopes s ON s.scope_id=e.ma_scope_id WHERE e.workspace_id=?1 AND e.owner_id=?2 AND e.session_key=?3 ORDER BY e.id DESC LIMIT 1",params![workspace,owner,session],|r|r.get(0)).optional().map_err(storage_error) + } + + pub fn parent_session(&self, workspace: &str, owner: &str, session: &str) -> MailboxResult> { + let writer = self.memory.pool.write(); + writer.query_row("SELECT json_extract(record,'$.parent_session') FROM child_sessions WHERE workspace_id=?1 AND owner_id=?2 AND session_id=?3",params![workspace,owner,session],|r|r.get(0)).optional().map_err(storage_error).map(Option::flatten) + } + + pub fn source_chain(&self, workspace: &str, owner: &str, event: &str) -> MailboxResult> { + let writer = self.memory.pool.write(); + let parent: Option = writer + .query_row( + "SELECT causation_event_id FROM message_events WHERE workspace_id=?1 AND owner_id=?2 AND event_id=?3", + params![workspace, owner, event], + |r| r.get(0), + ) + .optional() + .map_err(storage_error)? + .flatten(); + let Some(parent) = parent else { + return Ok(None); + }; + let raw:Option=writer.query_row("SELECT source_ref_json FROM message_events WHERE workspace_id=?1 AND owner_id=?2 AND event_id=?3 AND source='prx_mailbox'",params![workspace,owner,parent],|r|r.get(0)).optional().map_err(storage_error)?; + let Some(raw) = raw else { + return Ok(None); + }; + let reference: super::model::EventRef = super::model::decode(&raw)?; + reference.common.validate(reference.message_id)?; + Ok(Some(reference.common.chain(reference.message_id))) + } +} diff --git a/src/memory/sqlite/mailbox/model.rs b/src/memory/sqlite/mailbox/model.rs index e439c914f..f590cecb6 100644 --- a/src/memory/sqlite/mailbox/model.rs +++ b/src/memory/sqlite/mailbox/model.rs @@ -59,7 +59,7 @@ impl Common { return Err(MailboxError::InvalidMetadata); } if self.ancestry.len() != usize::from(self.hop_count) - || self.ancestry.len() > 8 + || self.ancestry.len() > usize::from(u8::MAX) || self.in_reply_to != self.ancestry.last().copied() || self.ancestry.contains(&id) { @@ -70,7 +70,7 @@ impl Common { return Err(MailboxError::InvalidMetadata); } if let Some(auth) = &self.auth { - if !matches!(auth.method.as_str(), "jwt" | "mtls") || self.remote_peer.is_none() { + if auth.method != "mtls" || self.remote_peer.is_none() { return Err(MailboxError::InvalidMetadata); } } @@ -115,6 +115,8 @@ pub(super) struct TargetPin { #[derive(Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub(super) struct OutboxMeta { + #[serde(default)] + pub attempts: u32, pub common: Common, pub to_pin: TargetPin, pub wire_ts: i64, diff --git a/src/memory/sqlite/mailbox/outbox.rs b/src/memory/sqlite/mailbox/outbox.rs index 64abe4eb1..252d56926 100644 --- a/src/memory/sqlite/mailbox/outbox.rs +++ b/src/memory/sqlite/mailbox/outbox.rs @@ -47,7 +47,11 @@ impl SqliteMailbox { .collect::>>() .map_err(storage_error)?; let mut messages = Vec::new(); + let mut first = std::collections::HashSet::new(); for (_, stream_id, seq, idempotency, id, bytes, json) in rows { + if !first.insert(stream_id) { + continue; + } let stream = stream::load(&tx, stream_id)?; if stream.sender.as_ref() != Some(scope) { return Err(MailboxError::StaleIncarnation); @@ -58,7 +62,10 @@ impl SqliteMailbox { if meta.body_erased_at.is_some() { return Err(MailboxError::Fenced); } - if meta.next_attempt_at.is_some_and(|when| when > self.clock.now()) { + // Retry-After cannot postpone the terminal 24-hour deadline. + if self.clock.now().saturating_sub(meta.created_at) < 86400 + && meta.next_attempt_at.is_some_and(|when| when > self.clock.now()) + { continue; } let mime = meta.body_mime.ok_or(MailboxError::CorruptState)?; diff --git a/src/memory/sqlite/mailbox/pin.rs b/src/memory/sqlite/mailbox/pin.rs index c2a8a5303..a0ad649f7 100644 --- a/src/memory/sqlite/mailbox/pin.rs +++ b/src/memory/sqlite/mailbox/pin.rs @@ -125,7 +125,11 @@ pub(in crate::memory::sqlite) fn check_scope( params![scope.scope_id.to_string(),scope.workspace_id,scope.owner_id,scope.incarnation.to_string(),scope.generation], |row|Ok((row.get::<_,String>(0)?,row.get::<_,Option>(1)?,row.get::<_,String>(2)?,row.get::<_,Option>(3)?)) ).optional().map_err(storage_error)?.ok_or(MailboxError::StaleIncarnation)?; - if row.0 != key || canonical.is_some_and(|expected| row.1.as_deref().is_some_and(|actual| actual != expected)) { + let child:bool=conn.query_row("SELECT EXISTS(SELECT 1 FROM child_sessions WHERE ma_scope_id=?1 AND owner_id=?2 AND workspace_id=?3 AND session_id=?4 AND json_extract(record,'$.agent')=?5)", + params![scope.scope_id.to_string(),scope.owner_id,scope.workspace_id,address.session,address.agent],|r|r.get(0)).map_err(storage_error)?; + if (row.0 != key && !child) + || canonical.is_some_and(|expected| row.1.as_deref().is_some_and(|actual| actual != expected)) + { return Err(MailboxError::StaleIncarnation); } if live { diff --git a/src/memory/sqlite/mailbox/publish.rs b/src/memory/sqlite/mailbox/publish.rs index d6e2dd251..92a53a831 100644 --- a/src/memory/sqlite/mailbox/publish.rs +++ b/src/memory/sqlite/mailbox/publish.rs @@ -8,7 +8,6 @@ use super::{ receipt, storage_error, stream::{self, Role}, }; -use crate::memory::sqlite::remote_tree::{self, RemoteTreeCaps, RemoteTreeError, RemoteTreeId, RemoteTreeResource}; use crate::messaging::mailbox::{ MAX_BYTES, MAX_ROWS, MailboxAuthority, MailboxError, MailboxPublished, MailboxResult, MailboxScope, MailboxSendState, outbox_key, validate_address, validate_body, @@ -203,32 +202,7 @@ impl SqliteMailbox { receipt::derive_chain(&tx, &sender.workspace_id, &sender.owner_id, &mut message)?; let common = Common::from_message(&message, inherited.map(|p| p.remote.clone()))?; common.validate(message.id)?; - if let Some(inherited) = inherited { - let tree = RemoteTreeId { - workspace_id: sender.workspace_id.clone(), - owner_id: sender.owner_id.clone(), - trigger_message_id: inherited.chain.trigger.to_string(), - }; - let caps = RemoteTreeCaps { - max_spawned: self.limits.max_spawned, - max_scheduled: self.limits.max_scheduled, - max_connections: self.limits.max_connections, - max_sends: self.limits.max_sends, - }; - remote_tree::charge_in_transaction( - &tx, - &tree, - RemoteTreeResource::Send, - "", - Some(&sender.scope_id.to_string()), - caps, - ) - .map_err(|error| match error { - RemoteTreeError::Closed => MailboxError::RemoteTreeClosed, - RemoteTreeError::Exhausted { .. } => MailboxError::RemoteSendExhausted, - RemoteTreeError::Storage => MailboxError::Storage, - })?; - } + let parent = ParentMeta { request_digest: common.request_digest.clone(), hop_count: common.hop_count, @@ -243,6 +217,7 @@ impl SqliteMailbox { tx.execute("INSERT INTO prx_mailbox_parents(stream_id,seq,workspace_id,owner_id,ma_scope_id,incarnation,generation,message_id,expires_at,parent_meta) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10)",params![stream.id,message.seq.to_be_bytes().as_slice(),sender.workspace_id,sender.owner_id,sender.scope_id.to_string(),sender.incarnation.to_string(),sender.generation,message.id.as_bytes().as_slice(),expiry,encode(&parent)?]).map_err(storage_error)?; let id = tx.last_insert_rowid(); let meta = OutboxMeta { + attempts: 0, common, to_pin: TargetPin { incarnation: message.to_pin.incarnation, diff --git a/src/memory/sqlite/mailbox/receipt.rs b/src/memory/sqlite/mailbox/receipt.rs index c9d7434b1..6e92f0b4e 100644 --- a/src/memory/sqlite/mailbox/receipt.rs +++ b/src/memory/sqlite/mailbox/receipt.rs @@ -203,7 +203,6 @@ pub(super) fn parent_chain( || meta.created_at < 0 || unique.len() != meta.ancestry.len() || meta.ancestry.len() != usize::from(meta.hop_count) - || meta.hop_count > 8 || meta.ancestry.contains(&id) { return Err(MailboxError::CorruptState); @@ -242,7 +241,7 @@ pub(super) fn derive_chain( return Ok(()); }; let (depth, mut ancestry) = parent_chain(conn, workspace, owner, parent)?; - if depth >= 8 || ancestry.contains(&message.id) || parent == message.id { + if ancestry.contains(&message.id) || parent == message.id { return Err(MailboxError::ChainDepth); } ancestry.push(parent); diff --git a/src/memory/sqlite/mailbox/retry.rs b/src/memory/sqlite/mailbox/retry.rs new file mode 100644 index 000000000..b1351950e --- /dev/null +++ b/src/memory/sqlite/mailbox/retry.rs @@ -0,0 +1,166 @@ +//! Durable outbox scheduling and first-pin binding. No payload leaves unleased. +use super::{ + SqliteMailbox, + model::{OutboxMeta, ParentMeta, decode, encode}, + pin, storage_error, +}; +use crate::messaging::{ + PrxMessage, RecipientPin, SessionAddr, + mailbox::{MailboxError, MailboxResult, MailboxScope}, +}; +use rusqlite::{Transaction, TransactionBehavior, params}; +impl SqliteMailbox { + pub(crate) fn outbox_sources(&self) -> MailboxResult> { + let writer = self.memory.pool.write(); + let mut query = writer.prepare("SELECT DISTINCT a.workspace_id,a.owner_id,a.scope_id,a.incarnation,a.generation,s.from_addr FROM prx_mailbox_seq s JOIN agent_scopes a ON s.sender_ma_scope_id=a.scope_id WHERE EXISTS(SELECT 1 FROM prx_mailbox_outbox o WHERE o.stream_id=s.stream_id AND o.state IN(0,1)) LIMIT 4096").map_err(storage_error)?; + let rows = query + .query_map([], |r| { + Ok(( + r.get::<_, String>(0)?, + r.get::<_, String>(1)?, + r.get::<_, String>(2)?, + r.get::<_, String>(3)?, + r.get::<_, i64>(4)?, + r.get::<_, String>(5)?, + )) + }) + .map_err(storage_error)? + .collect::>>() + .map_err(storage_error)?; + rows.into_iter() + .map(|(workspace, owner, scope, inc, generation, source)| { + Ok(( + pin::scope_from_row(workspace, owner, scope, inc, generation)?, + decode(&source)?, + )) + }) + .collect() + } + pub(crate) fn retry_outbox( + &self, + scope: &MailboxScope, + source: &SessionAddr, + message: &PrxMessage, + next: Option, + error: &str, + ) -> MailboxResult<()> { + let writer = self.memory.pool.write(); + let tx = Transaction::new_unchecked(&writer, TransactionBehavior::Immediate).map_err(storage_error)?; + pin::check_scope(&tx, scope, source, None, true)?; + let (id,raw):(i64,String)=tx.query_row("SELECT id,envelope_meta FROM prx_mailbox_outbox WHERE message_id=?1 AND ma_scope_id=?2 AND state IN(0,1)", params![message.id.as_bytes().as_slice(),scope.scope_id.to_string()], |r| Ok((r.get(0)?,r.get(1)?))).map_err(storage_error)?; + let mut meta: OutboxMeta = decode(&raw)?; + let now = self.clock.now(); + meta.updated_at = now; + meta.last_error = Some(error.into()); + meta.next_attempt_at = next; + meta.attempts = meta.attempts.saturating_add(1); + let expired = now.saturating_sub(meta.created_at) >= 86400; + let terminal = expired || next.is_none(); + if expired { + meta.last_error = Some("expired".into()); + } + if terminal { + meta.terminal_at = Some(now); + } + tx.execute( + "UPDATE prx_mailbox_outbox SET state=?1,envelope_meta=?2,expires_at=?3 WHERE id=?4", + params![ + if terminal { 3 } else { 0 }, + encode(&meta)?, + if terminal { + Some(now + crate::messaging::mailbox::REPLAY_SECONDS) + } else { + None + }, + id + ], + ) + .map_err(storage_error)?; + tx.commit().map_err(storage_error) + } + pub(crate) fn outbox_retry(&self, scope: &MailboxScope, message: &PrxMessage) -> MailboxResult<(u32, i64)> { + let writer = self.memory.pool.write(); + let raw: String = writer + .query_row( + "SELECT envelope_meta FROM prx_mailbox_outbox WHERE message_id=?1 AND ma_scope_id=?2", + params![message.id.as_bytes().as_slice(), scope.scope_id.to_string()], + |r| r.get(0), + ) + .map_err(storage_error)?; + let meta: OutboxMeta = decode(&raw)?; + Ok((meta.attempts, meta.created_at)) + } + pub(crate) fn refresh_outbox_pin( + &self, + scope: &MailboxScope, + source: &SessionAddr, + message: &mut PrxMessage, + pin: RecipientPin, + expires: i64, + ) -> MailboxResult<()> { + let writer = self.memory.pool.write(); + let tx = Transaction::new_unchecked(&writer, TransactionBehavior::Immediate).map_err(storage_error)?; + pin::check_scope(&tx, scope, source, None, true)?; + let (id,raw):(i64,String)=tx.query_row("SELECT id,envelope_meta FROM prx_mailbox_outbox WHERE message_id=?1 AND ma_scope_id=?2 AND state IN(0,1)",params![message.id.as_bytes().as_slice(),scope.scope_id.to_string()],|r|Ok((r.get(0)?,r.get(1)?))).map_err(storage_error)?; + let mut meta: OutboxMeta = decode(&raw)?; + if !meta.to_pin.incarnation.is_nil() + && (meta.to_pin.incarnation != pin.incarnation || meta.to_pin.generation != pin.generation) + { + return Err(MailboxError::StaleIncarnation); + } + message.to_pin = pin; + let digest = crate::messaging::request_digest(message); + meta.to_pin.incarnation = message.to_pin.incarnation; + meta.to_pin.generation = message.to_pin.generation; + meta.to_pin_token = Some(message.to_pin.token.clone()); + meta.pin_expires_at = expires; + meta.common.request_digest = digest.clone(); + tx.execute( + "UPDATE prx_mailbox_outbox SET envelope_meta=?1 WHERE id=?2", + params![encode(&meta)?, id], + ) + .map_err(storage_error)?; + let raw: String = tx + .query_row("SELECT parent_meta FROM prx_mailbox_parents WHERE id=?1", [id], |r| { + r.get(0) + }) + .map_err(storage_error)?; + let mut parent: ParentMeta = decode(&raw)?; + parent.request_digest = digest; + tx.execute( + "UPDATE prx_mailbox_parents SET parent_meta=?1 WHERE id=?2", + params![encode(&parent)?, id], + ) + .map_err(storage_error)?; + tx.commit().map_err(storage_error) + } +} + +impl crate::memory::SqliteMemory { + /// Owner-scoped send states without message payloads or recipient pins. + pub(crate) fn mailbox_send_status( + &self, + workspace: &str, + owner: &str, + session: &str, + ) -> anyhow::Result> { + let reader = self.pool.read()?; + let conn = reader.connection()?; + let mut query=conn.prepare("SELECT o.message_id,o.state,o.envelope_meta,s.to_addr FROM prx_mailbox_outbox o JOIN prx_mailbox_seq s ON s.stream_id=o.stream_id JOIN agent_scopes a ON a.scope_id=o.ma_scope_id WHERE a.workspace_id=?1 AND a.owner_id=?2 AND s.from_addr IN(SELECT from_addr FROM prx_mailbox_seq WHERE json_extract(from_addr,'$.session')=?3) AND NOT EXISTS(SELECT 1 FROM agent_erase_fences f WHERE f.scope_id=a.scope_id) ORDER BY o.id DESC LIMIT 64")?; + let rows = query + .query_map(params![workspace, owner, session], |r| { + Ok(( + r.get::<_, Vec>(0)?, + r.get::<_, i64>(1)?, + r.get::<_, String>(2)?, + r.get::<_, String>(3)?, + )) + })? + .collect::>>()?; + rows.into_iter().map(|(id,state,raw,target)| { + let meta:OutboxMeta=decode(&raw)?; + let status=if meta.last_error.as_deref()==Some("expired") {"expired"} else {match state {0|1=>"queued",2=>"accepted",_=>"failed"}}; + Ok(serde_json::json!({"message_id":uuid::Uuid::from_slice(&id)?,"to":serde_json::from_str::(&target)?,"status":status,"error":meta.last_error})) + }).collect() + } +} diff --git a/src/memory/sqlite/mailbox/runtime.rs b/src/memory/sqlite/mailbox/runtime.rs index 1102eb26d..e5c30ce7b 100644 --- a/src/memory/sqlite/mailbox/runtime.rs +++ b/src/memory/sqlite/mailbox/runtime.rs @@ -26,6 +26,7 @@ pub(in crate::memory::sqlite) fn for_database(path: &std::path::Path) -> anyhow: #[derive(Default)] pub(in crate::memory::sqlite) struct Runtime { + drainers: Mutex>>, state: Mutex, changed: Condvar, } @@ -108,7 +109,22 @@ impl Runtime { pub fn has_scope_leases(&self, scope: Uuid) -> bool { self.state.lock().leases.contains_key(&scope) } + pub fn register_drainer(&self, drainer: &Arc) { + let mut drainers = self.drainers.lock(); + drainers.retain(|drainer| drainer.strong_count() > 0); + drainers.push(Arc::downgrade(drainer)); + } pub fn drain_and_join(&self, scope: Uuid, deadline: std::time::Duration) -> bool { + let drainers: Vec<_> = self + .drainers + .lock() + .iter() + .filter_map(std::sync::Weak::upgrade) + .collect(); + for drainer in drainers { + drainer.drain(scope); + } + let Some(until) = std::time::Instant::now().checked_add(deadline) else { return false; }; diff --git a/src/memory/sqlite/mailbox/sender.rs b/src/memory/sqlite/mailbox/sender.rs index f6d8f264c..8b93753d2 100644 --- a/src/memory/sqlite/mailbox/sender.rs +++ b/src/memory/sqlite/mailbox/sender.rs @@ -15,6 +15,7 @@ struct PendingSend { } pub struct SqliteMailboxSender { + chain: Option, store: SqliteMailbox, source: SessionAddr, scope: MailboxScope, @@ -35,6 +36,7 @@ impl SqliteMailboxSender { } store.validate_scope(&scope, &source)?; Ok(Self { + chain: None, store, source, scope, @@ -42,6 +44,10 @@ impl SqliteMailboxSender { inherited, }) } + pub fn with_chain(mut self, chain: Option) -> Self { + self.chain = chain; + self + } } #[async_trait] impl MailboxSender for SqliteMailboxSender { @@ -49,6 +55,17 @@ impl MailboxSender for SqliteMailboxSender { &self.source } async fn send(&self, target: SessionAddr, text: String, mime: String) -> MailboxResult { + self.send_with_id(target, text, mime, Uuid::new_v4()).await + } +} +impl SqliteMailboxSender { + pub(crate) async fn send_with_id( + &self, + target: SessionAddr, + text: String, + mime: String, + id: Uuid, + ) -> MailboxResult { crate::messaging::mailbox::validate_body(&mime, text.as_bytes())?; if text.is_empty() { return Err(MailboxError::InvalidMetadata); @@ -68,8 +85,7 @@ impl MailboxSender for SqliteMailboxSender { { return Err(MailboxError::Unauthorized); } - let id = Uuid::new_v4(); - let message = PrxMessage { + let mut message = PrxMessage { id, idempotency: IdempotencyKey::parse(&id.to_string()).map_err(|_| MailboxError::InvalidMetadata)?, stream_id: None, @@ -91,6 +107,9 @@ impl MailboxSender for SqliteMailboxSender { exec: None, canonical_hash: None, }; + if let Some(chain) = &self.chain { + crate::messaging::stamp_outbound(chain, &mut message); + } self.store.publish_current( &resolved.authority, message, diff --git a/src/memory/sqlite/sync_journal.rs b/src/memory/sqlite/sync_journal.rs index 59c3df4c7..8237317de 100644 --- a/src/memory/sqlite/sync_journal.rs +++ b/src/memory/sqlite/sync_journal.rs @@ -283,7 +283,10 @@ pub(super) fn event_written(conn: &Connection, event: &crate::memory::MessageEve append(conn, &h)?; } } - if event.role == "user" && h.parent_run_id.is_some() { + if event.role == "user" + && (h.parent_run_id.is_some() || event.source.as_str() == "prx_mailbox") + && !mailbox_continuation(conn, event)? + { h.kind = "turn.appended".into(); h.event_id = format!("turn.appended:{}", h.source_ref); append(conn, &h)?; @@ -360,6 +363,9 @@ pub(super) fn admission( if h.run_id.is_some() { append(conn, &h)?; } + if mailbox_continuation(conn, event)? { + return Ok(()); + } h.kind = "turn.appended".into(); h.source_ref = format!("event:{}", event.event_id); h.event_id = format!("turn.appended:{}", h.source_ref); @@ -525,3 +531,7 @@ impl SyncStore for SqliteMemory { self.sync_runtime.shutdown.lock().clone() } } + +fn mailbox_continuation(conn: &Connection, event: &crate::memory::MessageEvent) -> anyhow::Result { + Ok(conn.query_row("SELECT EXISTS(SELECT 1 FROM message_events WHERE event_id=?1 AND workspace_id=?2 AND owner_id=?3 AND session_key=?4 AND source='prx_mailbox' AND role='user')",params![event.causation_event_id,event.workspace_id,event.owner_id,event.session_key],|row|row.get(0))?) +} diff --git a/src/memory/sqlite/sync_projection.rs b/src/memory/sqlite/sync_projection.rs index c78017d91..20e3226eb 100644 --- a/src/memory/sqlite/sync_projection.rs +++ b/src/memory/sqlite/sync_projection.rs @@ -254,6 +254,18 @@ pub(super) fn payload(conn: &Connection, h: &Header) -> anyhow::Result { } let input:Option<(String,bool)>=conn.query_row("SELECT client_message_id,run_id IS NOT NULL FROM rf_message_attempts WHERE message_event_id=?1 AND owner_id=?2",params![id,h.owner],|r|Ok((r.get(0)?,r.get(1)?))).optional()?; let mut value = json!({"message_id":message_id,"role":role,"content":content,"final":role=="assistant","timestamp":timestamp}); + if let Some(provenance) = raw.get("provenance") { + let object = value + .as_object_mut() + .ok_or(crate::memory::sync::SyncError::InvalidSource)?; + object.insert("provenance".into(), provenance.clone()); + object.insert( + "from".into(), + raw.get("from") + .cloned() + .ok_or(crate::memory::sync::SyncError::InvalidSource)?, + ); + } if let Some((client, turn)) = input { let obj = value .as_object_mut() diff --git a/src/memory/sqlite/tests/mailbox.rs b/src/memory/sqlite/tests/mailbox.rs index d6bb49910..7632b53db 100644 --- a/src/memory/sqlite/tests/mailbox.rs +++ b/src/memory/sqlite/tests/mailbox.rs @@ -1,3533 +1,4 @@ //! Real SQLite mailbox/store tests. The only injected component is the clock. -use super::*; -use crate::memory::sqlite::mailbox::{MailboxDelivery, SqliteMailbox}; -use crate::messaging::mailbox::{MailboxAuthority, MailboxClock, MailboxError, MailboxScope}; -use crate::messaging::{DeliveryState, ExecRef, IdempotencyKey, MessageBody, MessageKind, PrxMessage, SessionAddr}; -use std::sync::atomic::{AtomicI64, Ordering as AtomicOrdering}; -use uuid::Uuid; - -const W: &str = "prx_workspace"; -const O: &str = "prx_owner"; -const INC: u128 = 1; -const SCOPE_SOURCE: u128 = 10; -const SCOPE_TARGET: u128 = 20; -const STREAM: u128 = 500; -struct Clock(AtomicI64); -impl Clock { - fn advance(&self, seconds: i64) { - self.0.fetch_add(seconds, AtomicOrdering::SeqCst); - } -} -impl MailboxClock for Clock { - fn now(&self) -> i64 { - self.0.load(AtomicOrdering::SeqCst) - } -} - -struct Fixture { - memory: SqliteMemory, - store: SqliteMailbox, - clock: Arc, - source: SessionAddr, - target: SessionAddr, - sender: MailboxScope, - recipient: MailboxScope, - authority: MailboxAuthority, - // Close every owned connection before removing its database directory. - _dir: TempDir, -} -impl Fixture { - fn new() -> Self { - let dir = TempDir::new().expect("test: new: fixture setup succeeds"); - let memory = SqliteMemory::new(dir.path()).expect("test: new: SqliteMemory::new succeeds"); - { - let writer = memory.pool.write(); - writer - .execute( - "INSERT INTO agent_incarnations VALUES (?1,?2,'m',?3,'active',?4)", - params![W, O, Uuid::from_u128(INC).to_string(), "0".repeat(64)], - ) - .expect("test: new: execute succeeds"); - for (id, canonical) in [(SCOPE_SOURCE, "canonical-source"), (SCOPE_TARGET, "canonical-target")] { - writer - .execute( - "INSERT INTO agent_scopes VALUES (?1,?2,?3,?4,'m',?5,1)", - params![ - Uuid::from_u128(id).to_string(), - W, - O, - canonical, - Uuid::from_u128(INC).to_string() - ], - ) - .expect("test: new: execute succeeds"); - } - } - let clock = Arc::new(Clock(AtomicI64::new(1000))); - let store = SqliteMailbox::new( - memory.clone(), - "prx-node".into(), - [7; 32], - clock.clone(), - crate::config::schema::RemoteTreeLimits::default(), - ) - .expect("test: new: SqliteMailbox::new succeeds"); - let source = SessionAddr::new("prx-node", O, "source", None); - let target = SessionAddr::new("prx-node", O, "target", None); - let sender = MailboxScope { - workspace_id: W.into(), - owner_id: O.into(), - scope_id: Uuid::from_u128(SCOPE_SOURCE), - incarnation: Uuid::from_u128(INC), - generation: 1, - }; - let recipient = MailboxScope { - scope_id: Uuid::from_u128(SCOPE_TARGET), - ..sender.clone() - }; - let authority = MailboxAuthority::local(W.into(), source.clone(), target.clone()) - .expect("test: new: MailboxAuthority::local succeeds"); - store - .set_execution(&recipient, &target, Some("run-target".into())) - .expect("test: new: set_execution succeeds"); - Self { - _dir: dir, - memory, - store, - clock, - source, - target, - sender, - recipient, - authority, - } - } - fn message(&self, n: u64, seq: u64) -> PrxMessage { - let canonical: String = self - .memory - .pool - .write() - .query_row( - "SELECT session_key FROM agent_scopes WHERE scope_id=?1", - [self.recipient.scope_id.to_string()], - |row| row.get(0), - ) - .expect("test: read recipient canonical key"); - let pin = self - .store - .recipient_pin(&self.authority, &self.recipient, &canonical) - .expect("test: message: recipient_pin succeeds"); - PrxMessage { - id: Uuid::from_u128(1000 + u128::from(n)), - idempotency: IdempotencyKey::parse(&format!("mailbox-key-{n:08}")) - .expect("test: message: fixture setup succeeds"), - stream_id: Some(Uuid::from_u128(STREAM)), - seq, - ts: self.clock.now(), - from: self.source.clone(), - to: self.target.clone(), - to_pin: pin, - in_reply_to: None, - hop_count: 0, - ancestry: Vec::new(), - kind: MessageKind::Data, - body: MessageBody { - mime: "text/plain".into(), - bytes: format!("request-{n}").into_bytes(), - }, - origin: None, - auth: None, - exec: None, - canonical_hash: None, - } - } - fn receive(&self, n: u64, seq: u64) -> crate::messaging::mailbox::MailboxReceipt { - self.store - .accept(&self.authority, self.message(n, seq)) - .expect("test: receive: accept succeeds") - } - fn deliver(&self) -> MailboxDelivery { - self.store - .deliver(&self.recipient, &self.target) - .expect("test: deliver: deliver succeeds") - .expect("test: deliver: deliver returns a value") - } - fn scalar(&self, sql: &str) -> i64 { - self.memory - .pool - .write() - .query_row(sql, [], |r| r.get(0)) - .expect("test: scalar: query_row succeeds") - } -} - -#[test] -fn in_process_send_is_durable_and_acked() { - let f = Fixture::new(); - let provisional = f.message(1, 0); - let published = f - .store - .publish(&f.authority, provisional, &f.sender, f.clock.now() + 300, None) - .expect("test: in_process_send_is_durable_and_acked: publish succeeds"); - assert_eq!( - published.seq, 1, - "in process send is durable and acked: IPC identity or delivery state changed" - ); - let outgoing = f - .store - .pending_outbox(&f.sender, &f.source) - .expect("test: in_process_send_is_durable_and_acked: pending_outbox succeeds"); - let sent = outgoing - .first() - .expect("test: in_process_send_is_durable_and_acked: first succeeds") - .message() - .clone(); - let accepted = f - .store - .accept(&f.authority, sent.clone()) - .expect("test: in_process_send_is_durable_and_acked: accept succeeds"); - f.store - .acknowledge(&f.sender, &f.target, sent.id, accepted.state) - .expect("test: in_process_send_is_durable_and_acked: acknowledge succeeds"); - let retry = f - .store - .publish(&f.authority, sent, &f.sender, f.clock.now() + 300, None) - .expect("test: in_process_send_is_durable_and_acked: publish succeeds"); - assert_eq!( - retry.ack_state, - Some(DeliveryState::Accepted), - "in process send is durable and acked: IPC identity or delivery state changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), - 1, - "in process send is durable and acked: IPC identity or delivery state changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_messages"), - 1, - "in process send is durable and acked: IPC identity or delivery state changed" - ); -} - -#[test] -fn adopt_is_atomic_transcript_and_consume() { - let f = Fixture::new(); - f.receive(1, 1); - let delivery = f.deliver(); - let first = f - .store - .adopt(&delivery) - .expect("test: adopt_is_atomic_transcript_and_consume: adopt succeeds"); - let again = f - .store - .adopt(&delivery) - .expect("test: adopt_is_atomic_transcript_and_consume: adopt succeeds"); - assert_eq!( - first, again, - "adopt is atomic transcript and consume: atomic adoption or history projection changed" - ); - assert_eq!( - first.state, - DeliveryState::Consumed, - "adopt is atomic transcript and consume: atomic adoption or history projection changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM conversation_turns"), - 1, - "adopt is atomic transcript and consume: atomic adoption or history projection changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM message_events WHERE source='prx_mailbox'"), - 1, - "adopt is atomic transcript and consume: atomic adoption or history projection changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_receipts WHERE state=2 AND adopted_turn_id IS NOT NULL"), - 1, - "adopt is atomic transcript and consume: atomic adoption or history projection changed" - ); -} - -#[test] -fn same_id_different_key_different_body_is_id_reuse() { - let f = Fixture::new(); - let original = f.message(1, 1); - f.store - .accept(&f.authority, original.clone()) - .expect("test: same_id_different_key_different_body_is_id_reuse: accept succeeds"); - let mut other = original; - other.idempotency = IdempotencyKey::parse("another-mailbox-key") - .expect("test: same_id_different_key_different_body_is_id_reuse: IdempotencyKey::parse succeeds"); - other.seq = 2; - other.body.bytes = b"changed".to_vec(); - assert_eq!( - f.store.accept(&f.authority, other).unwrap_err(), - MailboxError::IdReuse, - "same id different key different body is id reuse: payload retention and erasure boundary changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_messages"), - 1, - "same id different key different body is id reuse: payload retention and erasure boundary changed" - ); -} - -#[test] -fn same_key_changed_exec_is_idempotency_conflict() { - let f = Fixture::new(); - let original = f.message(1, 1); - f.store - .accept(&f.authority, original.clone()) - .expect("test: same_key_changed_exec_is_idempotency_conflict: accept succeeds"); - let mut retry = original; - retry.exec = Some(ExecRef { - run: Some("different-run".into()), - }); - assert_eq!( - f.store.accept(&f.authority, retry).unwrap_err(), - MailboxError::IdempotencyConflict, - "same key changed exec is idempotency conflict: replay identity or receipt stability changed" - ); -} - -#[test] -fn reordered_duplicate_seq_holds_fifo() { - let f = Fixture::new(); - let second = f.message(2, 2); - let accepted = f - .store - .accept(&f.authority, second.clone()) - .expect("test: reordered_duplicate_seq_holds_fifo: accept succeeds"); - assert!( - f.store - .deliver(&f.recipient, &f.target) - .expect("test: reordered_duplicate_seq_holds_fifo: deliver succeeds") - .is_none(), - "reordered duplicate seq holds fifo: expected messaging contract changed" - ); - assert_eq!( - f.store - .accept(&f.authority, second) - .expect("test: reordered_duplicate_seq_holds_fifo: accept succeeds"), - accepted, - "reordered duplicate seq holds fifo: expected messaging contract changed" - ); - f.receive(1, 1); - let first = f.deliver(); - assert_eq!( - first.message().seq, - 1, - "reordered duplicate seq holds fifo: expected messaging contract changed" - ); - f.store - .adopt(&first) - .expect("test: reordered_duplicate_seq_holds_fifo: adopt succeeds"); - drop(first); - let second = f.deliver(); - assert_eq!( - second.message().seq, - 2, - "reordered duplicate seq holds fifo: expected messaging contract changed" - ); - f.store - .adopt(&second) - .expect("test: reordered_duplicate_seq_holds_fifo: adopt succeeds"); -} - -#[test] -fn permanent_seq_gap_retires_and_unblocks() { - let f = Fixture::new(); - f.receive(2, 2); - assert!( - f.store - .deliver(&f.recipient, &f.target) - .expect("test: permanent_seq_gap_retires_and_unblocks: deliver succeeds") - .is_none(), - "permanent seq gap retires and unblocks: expected messaging contract changed" - ); - f.clock.advance(30); - let delivery = f.deliver(); - assert_eq!( - delivery.message().seq, - 2, - "permanent seq gap retires and unblocks: expected messaging contract changed" - ); - f.store - .adopt(&delivery) - .expect("test: permanent_seq_gap_retires_and_unblocks: adopt succeeds"); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_receipts WHERE state=2"), - 1, - "permanent seq gap retires and unblocks: expected messaging contract changed" - ); -} - -#[test] -fn late_seq_at_or_below_consume_cursor_is_rejected_after_hole_gc() { - let f = Fixture::new(); - f.receive(2, 2); - f.clock.advance(30); - let delivery = f.deliver(); - f.store - .adopt(&delivery) - .expect("test: late_seq_at_or_below_consume_cursor_is_rejected_after_hole_gc: adopt succeeds"); - drop(delivery); - f.clock.advance(crate::messaging::mailbox::REPLAY_SECONDS + 1); - // Fresh pending work keeps the stream initialized while eligible old - // bodies/receipts/holes are collected. No forbidden same-UUID reset. - f.receive(3, 3); - f.store - .gc_scope(&f.recipient) - .expect("test: late_seq_at_or_below_consume_cursor_is_rejected_after_hole_gc: gc_scope succeeds"); - assert_eq!( - f.scalar("SELECT json_array_length(progress,'$.seq_skipped') FROM prx_mailbox_seq"), - 0, - "late seq at or below consume cursor is rejected after hole gc: atomic adoption or history projection changed" - ); - assert_eq!( - f.store.accept(&f.authority, f.message(4, 1)).unwrap_err(), - MailboxError::SeqAlreadyConsumed, - "late seq at or below consume cursor is rejected after hole gc: atomic adoption or history projection changed" - ); -} - -#[test] -fn outbox_parent_id_is_not_reused_after_outbox_gc() { - let f = Fixture::new(); - let published = f - .store - .publish(&f.authority, f.message(1, 0), &f.sender, f.clock.now() + 300, None) - .expect("test: outbox_parent_id_is_not_reused_after_outbox_gc: publish succeeds"); - f.store - .acknowledge(&f.sender, &f.target, published.message_id, DeliveryState::Accepted) - .expect("test: outbox_parent_id_is_not_reused_after_outbox_gc: acknowledge succeeds"); - f.clock.advance(crate::messaging::mailbox::REPLAY_SECONDS + 1); - let gc = f - .store - .gc_scope(&f.sender) - .expect("test: outbox_parent_id_is_not_reused_after_outbox_gc: gc_scope succeeds"); - assert_eq!( - gc.outboxes, 1, - "outbox parent id is not reused after outbox gc: expected messaging contract changed" - ); - assert_eq!( - gc.parents, 0, - "outbox parent id is not reused after outbox gc: expected messaging contract changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_parents"), - 1, - "outbox parent id is not reused after outbox gc: expected messaging contract changed" - ); - let mut next = f.message(2, 0); - next.stream_id = Some(Uuid::from_u128(STREAM + 1)); - let published2 = f - .store - .publish(&f.authority, next, &f.sender, f.clock.now() + 300, None) - .expect("test: outbox_parent_id_is_not_reused_after_outbox_gc: publish succeeds"); - assert!( - published2.row_id > published.row_id, - "outbox parent id is not reused after outbox gc: expected messaging contract changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_parents"), - 2, - "outbox parent id is not reused after outbox gc: expected messaging contract changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_outbox"), - 1, - "outbox parent id is not reused after outbox gc: expected messaging contract changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_messages WHERE id NOT IN(SELECT id FROM prx_mailbox_receipts)"), - 0, - "outbox parent id is not reused after outbox gc: expected messaging contract changed" - ); -} - -#[test] -fn crash_before_adopt_redelivers_once() { - let f = Fixture::new(); - f.receive(1, 1); - let delivery = f.deliver(); - let id = delivery.message().id; - drop(delivery); - f.store - .recover_delivery(&f.recipient, &f.target) - .expect("test: crash_before_adopt_redelivers_once: recover_delivery succeeds"); - let retry = f.deliver(); - assert_eq!( - retry.message().id, - id, - "crash before adopt redelivers once: atomic adoption or history projection changed" - ); - f.store - .adopt(&retry) - .expect("test: crash_before_adopt_redelivers_once: adopt succeeds"); - drop(retry); - f.store - .recover_delivery(&f.recipient, &f.target) - .expect("test: crash_before_adopt_redelivers_once: recover_delivery succeeds"); - assert!( - f.store - .deliver(&f.recipient, &f.target) - .expect("test: crash_before_adopt_redelivers_once: deliver succeeds") - .is_none(), - "crash before adopt redelivers once: atomic adoption or history projection changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM conversation_turns"), - 1, - "crash before adopt redelivers once: atomic adoption or history projection changed" - ); -} - -#[test] -fn crash_during_adopt_rolls_back() { - let f = Fixture::new(); - f.receive(1, 1); - let delivery = f.deliver(); - f.memory.pool.write().execute_batch("CREATE TEMP TRIGGER test_refuse_consume BEFORE UPDATE OF state ON prx_mailbox_receipts WHEN NEW.state=2 BEGIN SELECT RAISE(ABORT,'fixture consume refusal'); END;").expect("test: crash_during_adopt_rolls_back: fixture setup succeeds"); - assert_eq!( - f.store.adopt(&delivery).unwrap_err(), - MailboxError::Storage, - "crash during adopt rolls back: atomic adoption or history projection changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM conversation_turns"), - 0, - "crash during adopt rolls back: atomic adoption or history projection changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM message_events WHERE source='prx_mailbox'"), - 0, - "crash during adopt rolls back: atomic adoption or history projection changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_receipts WHERE state=1 AND adopted_turn_id IS NULL"), - 1, - "crash during adopt rolls back: atomic adoption or history projection changed" - ); - f.memory - .pool - .write() - .execute_batch("DROP TRIGGER test_refuse_consume") - .expect("test: crash_during_adopt_rolls_back: execute_batch succeeds"); - f.store - .adopt(&delivery) - .expect("test: crash_during_adopt_rolls_back: adopt succeeds"); - assert_eq!( - f.scalar("SELECT count(*) FROM conversation_turns"), - 1, - "crash during adopt rolls back: atomic adoption or history projection changed" - ); -} - -#[test] -fn mailbox_shared_ids_survive_rowid_reuse_after_gc() { - let f = Fixture::new(); - f.memory.pool.write().execute_batch("CREATE TEMP TRIGGER test_refuse_body BEFORE INSERT ON prx_mailbox_messages BEGIN SELECT RAISE(ABORT,'fixture body refusal'); END;").expect("test: mailbox_shared_ids_survive_rowid_reuse_after_gc: execute_batch succeeds"); - assert_eq!( - f.store.accept(&f.authority, f.message(1, 1)).unwrap_err(), - MailboxError::Storage, - "mailbox shared ids survive rowid reuse after gc: expected messaging contract changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), - 0, - "mailbox shared ids survive rowid reuse after gc: expected messaging contract changed" - ); - f.memory - .pool - .write() - .execute_batch("DROP TRIGGER test_refuse_body") - .expect("test: mailbox_shared_ids_survive_rowid_reuse_after_gc: execute_batch succeeds"); - let accepted = f.receive(1, 1); - let delivery = f.deliver(); - f.store - .adopt(&delivery) - .expect("test: mailbox_shared_ids_survive_rowid_reuse_after_gc: adopt succeeds"); - drop(delivery); - f.clock.advance(crate::messaging::mailbox::REPLAY_SECONDS + 1); - f.receive(2, 2); - // Observe the required lifetime order, rather than a zero-row assertion. - f.memory.pool.write().execute_batch("CREATE TEMP TRIGGER test_require_body_first BEFORE DELETE ON prx_mailbox_receipts WHEN EXISTS(SELECT 1 FROM prx_mailbox_messages WHERE id=OLD.id) BEGIN SELECT RAISE(ABORT,'body still references receipt'); END;").expect("test: mailbox_shared_ids_survive_rowid_reuse_after_gc: fixture setup succeeds"); - let gc = f - .store - .gc_scope(&f.recipient) - .expect("test: mailbox_shared_ids_survive_rowid_reuse_after_gc: gc_scope succeeds"); - assert_eq!( - gc.bodies, 1, - "mailbox shared ids survive rowid reuse after gc: expected messaging contract changed" - ); - assert_eq!( - gc.receipts, 1, - "mailbox shared ids survive rowid reuse after gc: expected messaging contract changed" - ); - assert_eq!( - f.scalar(&format!( - "SELECT count(*) FROM prx_mailbox_messages WHERE id={}", - accepted.row_id - )), - 0, - "mailbox shared ids survive rowid reuse after gc: expected messaging contract changed" - ); - assert_eq!( - f.scalar(&format!( - "SELECT count(*) FROM prx_mailbox_receipts WHERE id={}", - accepted.row_id - )), - 0, - "mailbox shared ids survive rowid reuse after gc: expected messaging contract changed" - ); -} - -#[test] -fn missing_recipient_pin_is_rejected_not_filled() { - let f = Fixture::new(); - let mut message = f.message(1, 1); - message.to_pin.token.clear(); - assert_eq!( - f.store.accept(&f.authority, message.clone()).unwrap_err(), - MailboxError::PinRequired, - "missing recipient pin is rejected not filled: recipient authority or scope isolation changed" - ); - assert_eq!( - f.store - .publish(&f.authority, message, &f.sender, i64::MAX, None) - .expect_err("test: publish requires a recipient pin"), - MailboxError::PinRequired, - "missing authority must use the same required-pin code before publishing or accepting" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_outbox"), - 0, - "publication without a pin must not retain an outgoing payload" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), - 0, - "missing recipient pin is rejected not filled: recipient authority or scope isolation changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_seq"), - 0, - "missing recipient pin is rejected not filled: recipient authority or scope isolation changed" - ); -} - -#[test] -fn unknown_parent_is_nacked() { - let f = Fixture::new(); - let mut message = f.message(1, 1); - message.in_reply_to = Some(Uuid::from_u128(999)); - assert_eq!( - f.store.accept(&f.authority, message).unwrap_err(), - MailboxError::UnknownParent, - "unknown parent is nacked: expected messaging contract changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_messages"), - 0, - "unknown parent is nacked: expected messaging contract changed" - ); -} - -#[test] -fn retry_with_altered_in_reply_to_is_idempotency_conflict() { - let f = Fixture::new(); - let original = f.message(1, 1); - f.store - .accept(&f.authority, original.clone()) - .expect("test: retry_with_altered_in_reply_to_is_idempotency_conflict: accept succeeds"); - let mut changed = original; - changed.in_reply_to = Some(Uuid::from_u128(999)); - assert_eq!( - f.store.accept(&f.authority, changed).unwrap_err(), - MailboxError::IdempotencyConflict, - "retry with altered in reply to is idempotency conflict: replay identity or receipt stability changed" - ); -} - -#[test] -fn ack_does_not_emit_ack() { - let f = Fixture::new(); - let published = f - .store - .publish(&f.authority, f.message(1, 0), &f.sender, f.clock.now() + 300, None) - .expect("test: ack_does_not_emit_ack: publish succeeds"); - f.store - .acknowledge(&f.sender, &f.target, published.message_id, DeliveryState::Accepted) - .expect("test: ack_does_not_emit_ack: acknowledge succeeds"); - f.store - .acknowledge(&f.sender, &f.target, published.message_id, DeliveryState::Consumed) - .expect("test: ack_does_not_emit_ack: acknowledge succeeds"); - f.store - .acknowledge(&f.sender, &f.target, published.message_id, DeliveryState::Accepted) - .expect("test: ack_does_not_emit_ack: acknowledge succeeds"); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_messages"), - 0, - "ack does not emit ack: expected messaging contract changed" - ); - assert!( - f.store - .pending_outbox(&f.sender, &f.source) - .expect("test: ack_does_not_emit_ack: pending_outbox succeeds") - .is_empty(), - "ack does not emit ack: expected messaging contract changed" - ); - let retry = f - .store - .publish(&f.authority, f.message(1, 0), &f.sender, f.clock.now() + 300, None) - .expect("test: ack_does_not_emit_ack: publish succeeds"); - assert_eq!( - retry.ack_state, - Some(DeliveryState::Consumed), - "ack does not emit ack: expected messaging contract changed" - ); -} - -#[test] -fn offline_session_receives_after_attach() { - let f = Fixture::new(); - f.store - .close_execution(&f.recipient, &f.target, "run-target") - .expect("test: offline_session_receives_after_attach: close_execution succeeds"); - f.receive(1, 1); - assert!( - f.store - .deliver(&f.recipient, &f.target) - .expect("test: offline_session_receives_after_attach: deliver succeeds") - .is_none(), - "offline session receives after attach: expected messaging contract changed" - ); - f.store - .set_execution(&f.recipient, &f.target, Some("reopened-target".into())) - .expect("test: offline_session_receives_after_attach: set_execution succeeds"); - let delivered = f.deliver(); - assert_eq!( - delivered.message().body.bytes, - b"request-1", - "offline session receives after attach: expected messaging contract changed" - ); -} - -#[test] -fn mailbox_erase_drops_bodies_keeps_receipts() { - let f = Fixture::new(); - f.receive(1, 1); - let queued = f.message(2, 2); - let report = f - .store - .erase_scope(&f.recipient, Duration::from_secs(5), &|| Ok(())) - .expect("test: mailbox_erase_drops_bodies_keeps_receipts: erase_scope succeeds"); - assert_eq!( - report.remaining, 0, - "mailbox erase drops bodies keeps receipts: payload retention and erasure boundary changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_messages"), - 0, - "mailbox erase drops bodies keeps receipts: payload retention and erasure boundary changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), - 1, - "mailbox erase drops bodies keeps receipts: payload retention and erasure boundary changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_seq WHERE state=1"), - 1, - "mailbox erase drops bodies keeps receipts: payload retention and erasure boundary changed" - ); - assert_eq!( - f.store.accept(&f.authority, queued).unwrap_err(), - MailboxError::ScopeErasing, - "mailbox erase drops bodies keeps receipts: payload retention and erasure boundary changed" - ); -} - -#[test] -fn outbox_erase_drops_bodies_keeps_status() { - let f = Fixture::new(); - f.store - .publish(&f.authority, f.message(1, 0), &f.sender, f.clock.now() + 300, None) - .expect("test: outbox_erase_drops_bodies_keeps_status: publish succeeds"); - f.store - .erase_scope(&f.sender, Duration::from_secs(5), &|| Ok(())) - .expect("test: outbox_erase_drops_bodies_keeps_status: erase_scope succeeds"); - assert_eq!(f.scalar("SELECT count(*) FROM prx_mailbox_outbox WHERE state=3 AND body_bytes IS NULL AND json_extract(envelope_meta,'$.to_pin_token') IS NULL AND json_extract(envelope_meta,'$.body_mime') IS NULL"),1, "outbox erase drops bodies keeps status: payload retention and erasure boundary changed"); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_parents"), - 1, - "outbox erase drops bodies keeps status: payload retention and erasure boundary changed" - ); - let replay = f - .store - .publish(&f.authority, f.message(1, 0), &f.sender, f.clock.now() + 300, None) - .expect("test: outbox_erase_drops_bodies_keeps_status: publish succeeds"); - assert_eq!( - replay.state, - crate::messaging::mailbox::MailboxSendState::Failed, - "outbox erase drops bodies keeps status: payload retention and erasure boundary changed" - ); -} - -#[test] -fn held_delivery_across_erase_recreate_does_not_resurrect_body() { - let f = Fixture::new(); - f.receive(1, 1); - let delivery = f.deliver(); - let (fenced_tx, fenced_rx) = std::sync::mpsc::sync_channel(1); - let (done_tx, done_rx) = std::sync::mpsc::sync_channel(1); - let store = f.store.clone(); - let scope = f.recipient.clone(); - let erase = std::thread::spawn(move || { - let result = store.erase_scope(&scope, Duration::from_secs(5), &|| { - fenced_tx - .send(()) - .expect("test: held_delivery_across_erase_recreate_does_not_resurrect_body: send succeeds"); - Ok(()) - }); - done_tx - .send(result) - .expect("test: held_delivery_across_erase_recreate_does_not_resurrect_body: send succeeds"); - }); - fenced_rx - .recv_timeout(Duration::from_secs(5)) - .expect("test: held_delivery_across_erase_recreate_does_not_resurrect_body: recv_timeout succeeds"); - assert_eq!( - f.store.adopt(&delivery).unwrap_err(), - MailboxError::ScopeErasing, - "held delivery across erase recreate does not resurrect body: payload retention and erasure boundary changed" - ); - assert!( - done_rx.try_recv().is_err(), - "erase cannot finish while queue/IPC owns the payload" - ); - drop(delivery); - assert_eq!( - done_rx - .recv_timeout(Duration::from_secs(5)) - .expect("test: held_delivery_across_erase_recreate_does_not_resurrect_body: recv_timeout succeeds") - .expect("test: held_delivery_across_erase_recreate_does_not_resurrect_body: recv_timeout returns a value") - .remaining, - 0, - "held delivery across erase recreate does not resurrect body: payload retention and erasure boundary changed" - ); - erase - .join() - .expect("test: held_delivery_across_erase_recreate_does_not_resurrect_body: join succeeds"); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_messages"), - 0, - "held delivery across erase recreate does not resurrect body: payload retention and erasure boundary changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM conversation_turns"), - 0, - "held delivery across erase recreate does not resurrect body: payload retention and erasure boundary changed" - ); -} - -fn new_target_generation(f: &Fixture) -> MailboxScope { - let writer = f.memory.pool.write(); - writer - .execute( - "UPDATE agent_incarnations SET state='retired' WHERE workspace_id=?1 AND owner_id=?2 AND agent_key='m'", - params![W, O], - ) - .expect("test: new_target_generation: fixture setup succeeds"); - writer - .execute( - "INSERT INTO agent_incarnations VALUES (?1,?2,'m',?3,'active',?4)", - params![W, O, Uuid::from_u128(2).to_string(), "1".repeat(64)], - ) - .expect("test: new_target_generation: execute succeeds"); - let scope = MailboxScope { - scope_id: Uuid::from_u128(30), - incarnation: Uuid::from_u128(2), - ..f.recipient.clone() - }; - writer - .execute( - "INSERT INTO agent_scopes VALUES (?1,?2,?3,'canonical-target','m',?4,1)", - params![scope.scope_id.to_string(), W, O, scope.incarnation.to_string()], - ) - .expect("test: new_target_generation: execute succeeds"); - scope -} - -#[test] -fn recipient_rebind_with_unconsumed_old_scope_retires_stream() { - let f = Fixture::new(); - f.receive(1, 1); - let mut second = f.message(2, 2); - let new_scope = new_target_generation(&f); - second.to_pin = f - .store - .recipient_pin(&f.authority, &new_scope, "canonical-target") - .expect("test: recipient_rebind_with_unconsumed_old_scope_retires_stream: recipient_pin succeeds"); - assert_eq!( - f.store.accept(&f.authority, second.clone()).unwrap_err(), - MailboxError::SeqStreamRetired, - "recipient rebind with unconsumed old scope retires stream: recipient authority or scope isolation changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), - 1, - "recipient rebind with unconsumed old scope retires stream: recipient authority or scope isolation changed" - ); - f.store - .set_execution(&new_scope, &f.target, Some("new-run".into())) - .expect("test: recipient_rebind_with_unconsumed_old_scope_retires_stream: set_execution succeeds"); - second.stream_id = Some(Uuid::from_u128(STREAM + 1)); - second.seq = 1; - f.store - .accept(&f.authority, second) - .expect("test: recipient_rebind_with_unconsumed_old_scope_retires_stream: accept succeeds"); - let delivered = f - .store - .deliver(&new_scope, &f.target) - .expect("test: recipient_rebind_with_unconsumed_old_scope_retires_stream: deliver succeeds") - .expect("test: recipient_rebind_with_unconsumed_old_scope_retires_stream: deliver returns a value"); - assert_eq!( - delivered.message().seq, - 1, - "recipient rebind with unconsumed old scope retires stream: recipient authority or scope isolation changed" - ); - f.store - .adopt(&delivered) - .expect("test: recipient_rebind_with_unconsumed_old_scope_retires_stream: adopt succeeds"); - drop(delivered); - f.store - .erase_scope(&f.recipient, Duration::from_secs(5), &|| Ok(())) - .expect("test: recipient_rebind_with_unconsumed_old_scope_retires_stream: erase_scope succeeds"); - assert_eq!(f.scalar(&format!("SELECT count(*) FROM prx_mailbox_seq s JOIN prx_mailbox_receipts r ON r.stream_id=s.stream_id WHERE s.state=0 AND r.state<>2 AND r.ma_scope_id='{}'",f.recipient.scope_id)),0, "recipient rebind with unconsumed old scope retires stream: recipient authority or scope isolation changed"); -} - -#[test] -fn recipient_erase_retires_stream_before_recreated_scope_accept() { - let f = Fixture::new(); - f.receive(3, 3); - let mut fourth = f.message(4, 4); - // Represent a row left by the pre-fix rebind bug: its current role is Y, - // but an accepted X-pinned slot is still present. Erase must enumerate X - // receipts, not only the current recipient role. - let new_scope = new_target_generation(&f); - f.memory - .pool - .write() - .execute( - "UPDATE prx_mailbox_seq SET recipient_ma_scope_id=?1,recipient_incarnation=?2,recipient_generation=1", - params![new_scope.scope_id.to_string(), new_scope.incarnation.to_string()], - ) - .expect("test: recipient_erase_retires_stream_before_recreated_scope_accept: execute succeeds"); - f.store - .erase_scope(&f.recipient, Duration::from_secs(5), &|| Ok(())) - .expect("test: recipient_erase_retires_stream_before_recreated_scope_accept: erase_scope succeeds"); - fourth.to_pin = f - .store - .recipient_pin(&f.authority, &new_scope, "canonical-target") - .expect("test: recipient_erase_retires_stream_before_recreated_scope_accept: recipient_pin succeeds"); - assert_eq!( - f.store.accept(&f.authority, fourth.clone()).unwrap_err(), - MailboxError::SeqStreamRetired, - "recipient erase retires stream before recreated scope accept: payload retention and erasure boundary changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_messages"), - 0, - "recipient erase retires stream before recreated scope accept: payload retention and erasure boundary changed" - ); - fourth.stream_id = Some(Uuid::from_u128(STREAM + 1)); - fourth.seq = 1; - f.store - .accept(&f.authority, fourth) - .expect("test: recipient_erase_retires_stream_before_recreated_scope_accept: accept succeeds"); - f.store - .set_execution(&new_scope, &f.target, Some("new-run".into())) - .expect("test: recipient_erase_retires_stream_before_recreated_scope_accept: set_execution succeeds"); - assert_eq!( - f.store - .deliver(&new_scope, &f.target) - .expect("test: recipient_erase_retires_stream_before_recreated_scope_accept: deliver succeeds") - .expect("test: recipient_erase_retires_stream_before_recreated_scope_accept: deliver returns a value") - .message() - .seq, - 1, - "recipient erase retires stream before recreated scope accept: payload retention and erasure boundary changed" - ); -} - -#[test] -fn mailbox_mime_and_payload_share_byte_limits() { - let f = Fixture::new(); - for mime in [ - String::new(), - "x".repeat(256), - "text/plain\0bad".into(), - "text/\u{e9}".into(), - ] { - let mut message = f.message(1, 1); - message.body.mime = mime; - assert_eq!( - f.store.accept(&f.authority, message).unwrap_err(), - MailboxError::InvalidMime, - "mailbox mime and payload share byte limits: expected messaging contract changed" - ); - } - let mut too_large = f.message(1, 1); - too_large.body.bytes = vec![0; crate::messaging::MAX_BODY_BYTES]; - assert_eq!( - f.store.accept(&f.authority, too_large).unwrap_err(), - MailboxError::BodyTooLarge, - "mailbox mime and payload share byte limits: expected messaging contract changed" - ); - let mut fits = f.message(1, 1); - fits.body.mime = "x".repeat(255); - fits.body.bytes = vec![0; crate::messaging::MAX_BODY_BYTES - 255]; - f.store - .accept(&f.authority, fits) - .expect("test: mailbox_mime_and_payload_share_byte_limits: accept succeeds"); - assert_eq!( - f.scalar("SELECT length(body_bytes)+length(CAST(body_mime AS BLOB)) FROM prx_mailbox_messages"), - 262144, - "mailbox mime and payload share byte limits: expected messaging contract changed" - ); -} - -#[tokio::test] -async fn child_session_reconstructs_mailbox_cursor() { - use crate::chat::sessions::child::{ChildSession, ChildSessionRegistry}; - let f = Fixture::new(); - let registry = ChildSessionRegistry::new(Arc::new(f.memory.clone())).with_workspace(W.into()); - registry - .insert(&ChildSession::new(f.target.clone(), None, None)) - .await - .expect("test: child_session_reconstructs_mailbox_cursor: insert succeeds"); - let empty = registry - .reconstruct(&f.target) - .await - .expect("test: child_session_reconstructs_mailbox_cursor: reconstruct succeeds"); - let scope = empty - .mailbox_scope() - .expect("test: child_session_reconstructs_mailbox_cursor: mailbox_scope succeeds") - .clone(); - drop(empty); - let canonical = ChildSessionRegistry::canonical_session_key(&f.target).expect( - "test: child_session_reconstructs_mailbox_cursor: ChildSessionRegistry::canonical_session_key succeeds", - ); - let mut message = f.message(1, 1); - message.to_pin = f - .store - .recipient_pin(&f.authority, &scope, &canonical) - .expect("test: child_session_reconstructs_mailbox_cursor: recipient_pin succeeds"); - f.store - .set_execution(&scope, &f.target, Some("child-run".into())) - .expect("test: child_session_reconstructs_mailbox_cursor: set_execution succeeds"); - f.store - .accept(&f.authority, message) - .expect("test: child_session_reconstructs_mailbox_cursor: accept succeeds"); - let delivery = f - .store - .deliver(&scope, &f.target) - .expect("test: child_session_reconstructs_mailbox_cursor: deliver succeeds") - .expect("test: child_session_reconstructs_mailbox_cursor: deliver returns a value"); - f.store - .adopt(&delivery) - .expect("test: child_session_reconstructs_mailbox_cursor: adopt succeeds"); - drop(delivery); - let restored = registry - .reconstruct(&f.target) - .await - .expect("test: child_session_reconstructs_mailbox_cursor: reconstruct succeeds"); - assert_eq!( - restored.mailbox_cursor().streams.get(&1), - Some(&1), - "child session reconstructs mailbox cursor: atomic adoption or history projection changed" - ); - assert_eq!( - restored.history().len(), - 1, - "child session reconstructs mailbox cursor: atomic adoption or history projection changed" - ); - assert_eq!( - restored - .history() - .first() - .expect("test: child_session_reconstructs_mailbox_cursor: first succeeds") - .content, - "request-1", - "child session reconstructs mailbox cursor: atomic adoption or history projection changed" - ); - registry - .insert(&restored) - .await - .expect("test: child_session_reconstructs_mailbox_cursor: insert succeeds"); - drop(restored); - let again = registry - .reconstruct(&f.target) - .await - .expect("test: child_session_reconstructs_mailbox_cursor: reconstruct succeeds"); - assert_eq!( - again.history().len(), - 1, - "snapshot projection must merge by event identity exactly once" - ); - drop(again); - f.clock.advance(crate::messaging::mailbox::REPLAY_SECONDS + 1); - f.store - .gc_scope(&scope) - .expect("test: child_session_reconstructs_mailbox_cursor: gc_scope succeeds"); - let after_gc = registry - .reconstruct(&f.target) - .await - .expect("test: child_session_reconstructs_mailbox_cursor: reconstruct succeeds"); - assert_eq!(after_gc.history().len(), 1, "source_ref and seq survive receipt GC"); - assert_eq!( - after_gc.mailbox_cursor().streams.get(&1), - Some(&1), - "child session reconstructs mailbox cursor: atomic adoption or history projection changed" - ); -} - -#[tokio::test] -async fn child_sessions_owner_and_agent_erase_remove_records() { - use crate::chat::sessions::child::{ChildSession, ChildSessionRegistry}; - let f = Fixture::new(); - { - let writer = f.memory.pool.write(); - for (key, inc) in [("n:prx_agent_a", 40), ("n:prx_agent_b", 50)] { - writer - .execute( - "INSERT INTO agent_incarnations VALUES (?1,?2,?3,?4,'active',?5)", - params![W, O, key, Uuid::from_u128(inc).to_string(), "2".repeat(64)], - ) - .expect("test: child_sessions_owner_and_agent_erase_remove_records: execute succeeds"); - } - } - let registry = ChildSessionRegistry::new(Arc::new(f.memory.clone())).with_workspace(W.into()); - let a = SessionAddr::new("prx-node", O, "child-a", Some("prx_agent_a")); - let b = SessionAddr::new("prx-node", O, "child-b", Some("prx_agent_b")); - registry - .insert(&ChildSession::new(a.clone(), None, None)) - .await - .expect("test: child_sessions_owner_and_agent_erase_remove_records: insert succeeds"); - registry - .insert(&ChildSession::new(b.clone(), None, None)) - .await - .expect("test: child_sessions_owner_and_agent_erase_remove_records: insert succeeds"); - let active = registry - .reconstruct(&a) - .await - .expect("test: child_sessions_owner_and_agent_erase_remove_records: reconstruct succeeds"); - let scope = active - .mailbox_scope() - .expect("test: child_sessions_owner_and_agent_erase_remove_records: mailbox_scope succeeds") - .clone(); - drop(active); - f.store - .erase_scope(&scope, Duration::from_secs(5), &|| Ok(())) - .expect("test: child_sessions_owner_and_agent_erase_remove_records: erase_scope succeeds"); - assert!( - registry.reconstruct(&a).await.is_err(), - "child sessions owner and agent erase remove records: payload retention and erasure boundary changed" - ); - let other = registry - .reconstruct(&b) - .await - .expect("test: child_sessions_owner_and_agent_erase_remove_records: reconstruct succeeds"); - assert_eq!( - other.addr(), - &b, - "child sessions owner and agent erase remove records: payload retention and erasure boundary changed" - ); - drop(other); - // The global MA owner eraser enumerates all owner snapshots. Exercise its - // mailbox/child adapter for that complete historical set. - let scopes = { - let writer = f.memory.pool.write(); - let mut query = writer - .prepare("SELECT scope_id,incarnation,generation FROM agent_scopes WHERE workspace_id=?1 AND owner_id=?2") - .expect("test: child_sessions_owner_and_agent_erase_remove_records: prepare succeeds"); - query - .query_map(params![W, O], |r| { - Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, i64>(2)?)) - }) - .expect("test: child_sessions_owner_and_agent_erase_remove_records: query_map succeeds") - .collect::>>() - .expect("test: child_sessions_owner_and_agent_erase_remove_records: collect succeeds") - }; - for (id, incarnation, generation) in scopes { - f.store - .erase_scope( - &MailboxScope { - workspace_id: W.into(), - owner_id: O.into(), - scope_id: Uuid::parse_str(&id) - .expect("test: child_sessions_owner_and_agent_erase_remove_records: Uuid::parse_str succeeds"), - incarnation: Uuid::parse_str(&incarnation) - .expect("test: child_sessions_owner_and_agent_erase_remove_records: Uuid::parse_str succeeds"), - generation, - }, - Duration::from_secs(5), - &|| Ok(()), - ) - .expect("test: child_sessions_owner_and_agent_erase_remove_records: erase_scope succeeds"); - } - assert_eq!( - f.scalar("SELECT count(*) FROM child_sessions"), - 0, - "child sessions owner and agent erase remove records: payload retention and erasure boundary changed" - ); - assert!( - registry.reconstruct(&b).await.is_err(), - "child sessions owner and agent erase remove records: payload retention and erasure boundary changed" - ); - // A quarantined legacy/orphan cannot be silently omitted by scope SQL. - f.memory - .pool - .write() - .execute("INSERT INTO child_sessions(key,record) VALUES ('legacy','{}')", []) - .expect("test: child_sessions_owner_and_agent_erase_remove_records: execute succeeds"); - assert_eq!( - f.store - .erase_scope(&f.sender, Duration::from_secs(5), &|| Ok(())) - .unwrap_err(), - MailboxError::Fenced, - "child sessions owner and agent erase remove records: payload retention and erasure boundary changed" - ); -} - -#[test] -fn mailbox_scope_and_address_validation_is_transactional() { - let f = Fixture::new(); - let mut forged = f.message(1, 1); - forged.to.owner = "prx_other_owner".into(); - assert_eq!( - f.store.accept(&f.authority, forged).unwrap_err(), - MailboxError::Unauthorized, - "mailbox scope and address validation is transactional: recipient authority or scope isolation changed" - ); - let wrong = MailboxScope { - generation: 2, - ..f.recipient.clone() - }; - assert_eq!( - f.store - .recipient_pin(&f.authority, &wrong, "canonical-target") - .unwrap_err(), - MailboxError::StaleIncarnation, - "mailbox scope and address validation is transactional: recipient authority or scope isolation changed" - ); - assert_eq!( - f.store - .recipient_pin(&f.authority, &f.recipient, "wrong-canonical") - .unwrap_err(), - MailboxError::StaleIncarnation, - "mailbox scope and address validation is transactional: recipient authority or scope isolation changed" - ); - assert!( - MailboxAuthority::local( - W.into(), - f.source.clone(), - SessionAddr::new("prx-node", O, "x".repeat(513), None) - ) - .is_err(), - "mailbox scope and address validation is transactional: recipient authority or scope isolation changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), - 0, - "mailbox scope and address validation is transactional: recipient authority or scope isolation changed" - ); -} - -#[test] -fn queued_outbox_first_post_after_recipient_recreate_is_stale_incarnation() { - let f = Fixture::new(); - f.store - .publish(&f.authority, f.message(1, 0), &f.sender, f.clock.now() + 300, None) - .expect("test: queued_outbox_first_post_after_recipient_recreate_is_stale_incarnation: publish succeeds"); - let pending = f.store.pending_outbox(&f.sender, &f.source).expect( - "test: queued_outbox_first_post_after_recipient_recreate_is_stale_incarnation: pending_outbox succeeds", - ); - let held = pending - .first() - .expect("test: queued_outbox_first_post_after_recipient_recreate_is_stale_incarnation: first succeeds") - .message() - .clone(); - f.store - .erase_scope(&f.recipient, Duration::from_secs(5), &|| Ok(())) - .expect("test: queued_outbox_first_post_after_recipient_recreate_is_stale_incarnation: erase_scope succeeds"); - let _new = new_target_generation(&f); - assert_eq!( - f.store.accept(&f.authority, held).unwrap_err(), - MailboxError::StaleIncarnation, - "queued outbox first post after recipient recreate is stale incarnation: capacity enforcement or bounded delivery changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_messages"), - 0, - "queued outbox first post after recipient recreate is stale incarnation: capacity enforcement or bounded delivery changed" - ); -} - -#[test] -fn stale_incarnation_delayed_send_is_rejected() { - let f = Fixture::new(); - let held = f.message(1, 1); - let _new = new_target_generation(&f); - assert_eq!( - f.store.accept(&f.authority, held).unwrap_err(), - MailboxError::StaleIncarnation, - "stale incarnation delayed send is rejected: recipient authority or scope isolation changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_messages"), - 0, - "stale incarnation delayed send is rejected: recipient authority or scope isolation changed" - ); -} - -#[test] -fn mailbox_row_requires_scope() { - let f = Fixture::new(); - let mut message = f.message(1, 1); - message.to_pin.generation = 99; - assert_eq!( - f.store.accept(&f.authority, message).unwrap_err(), - MailboxError::StaleIncarnation, - "mailbox row requires scope: recipient authority or scope isolation changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_messages"), - 0, - "mailbox row requires scope: recipient authority or scope isolation changed" - ); - let error = f.memory.pool.write().execute( - "INSERT INTO prx_mailbox_messages(id,stream_id,seq,workspace_id,owner_id,incarnation,generation,state,body_mime,body_bytes,delivery_meta) VALUES (1,1,x'0000000000000001',?1,?2,?3,1,0,'text/plain',x'00','{}')", - params![W,O,Uuid::from_u128(INC).to_string()], - ).unwrap_err(); - assert!( - error - .to_string() - .contains("NOT NULL constraint failed: prx_mailbox_messages.ma_scope_id"), - "mailbox row requires scope: recipient authority or scope isolation changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_messages"), - 0, - "mailbox row requires scope: recipient authority or scope isolation changed" - ); -} - -#[test] -fn mailbox_pk_includes_from_instance() { - let f = Fixture::new(); - f.receive(1, 1); - let mut source = f.source.clone(); - source.instance = "peer-two".into(); - let authority = MailboxAuthority::verified_peer( - W.into(), - source, - f.target.clone(), - crate::messaging::MessageAuth { - issuer: "prx-issuer".into(), - subject: "prx-peer".into(), - method: "jwt".into(), - }, - ) - .expect("test: mailbox_pk_includes_from_instance: MailboxAuthority::verified_peer succeeds"); - let mut message = f.message(1, 1); - message.to_pin = f - .store - .recipient_pin(&authority, &f.recipient, "canonical-target") - .expect("test: mailbox_pk_includes_from_instance: recipient_pin succeeds"); - message.id = Uuid::from_u128(9001); - f.store - .accept(&authority, message) - .expect("test: mailbox_pk_includes_from_instance: accept succeeds"); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), - 2, - "mailbox pk includes from instance: expected messaging contract changed" - ); -} - -#[test] -fn mailbox_pk_omits_run() { - let f = Fixture::new(); - let message = f.message(1, 1); - let saved = f - .store - .accept(&f.authority, message.clone()) - .expect("test: mailbox_pk_omits_run: accept succeeds"); - f.store - .set_execution(&f.recipient, &f.target, Some("replacement-run".into())) - .expect("test: mailbox_pk_omits_run: set_execution succeeds"); - assert_eq!( - f.store - .accept(&f.authority, message) - .expect("test: mailbox_pk_omits_run: accept succeeds"), - saved, - "mailbox pk omits run: expected messaging contract changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), - 1, - "mailbox pk omits run: expected messaging contract changed" - ); -} - -#[test] -fn mailbox_seq_pk_includes_stream_id() { - let f = Fixture::new(); - f.receive(1, 1); - let mut other = f.message(2, 1); - other.stream_id = Some(Uuid::from_u128(501)); - f.store - .accept(&f.authority, other) - .expect("test: mailbox_seq_pk_includes_stream_id: accept succeeds"); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_seq"), - 2, - "mailbox seq pk includes stream id: expected messaging contract changed" - ); -} - -#[test] -fn idempotency_does_not_collide_across_senders() { - mailbox_pk_includes_from_instance(); -} - -#[test] -fn seq_is_allocated_in_outbox_transaction() { - let f = Fixture::new(); - f.memory.pool.write().execute_batch("CREATE TEMP TRIGGER reject_publish BEFORE INSERT ON prx_mailbox_outbox BEGIN SELECT RAISE(ABORT,'injected write failure'); END;").expect("test: seq_is_allocated_in_outbox_transaction: execute_batch succeeds"); - assert_eq!( - f.store - .publish(&f.authority, f.message(1, 0), &f.sender, f.clock.now() + 300, None) - .unwrap_err(), - MailboxError::Storage, - "seq is allocated in outbox transaction: expected messaging contract changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_seq"), - 0, - "seq is allocated in outbox transaction: expected messaging contract changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_parents"), - 0, - "seq is allocated in outbox transaction: expected messaging contract changed" - ); - f.memory - .pool - .write() - .execute_batch("DROP TRIGGER reject_publish") - .expect("test: seq_is_allocated_in_outbox_transaction: execute_batch succeeds"); - let first = f - .store - .publish(&f.authority, f.message(1, 0), &f.sender, f.clock.now() + 300, None) - .expect("test: seq_is_allocated_in_outbox_transaction: publish succeeds"); - assert_eq!( - first.seq, 1, - "seq is allocated in outbox transaction: expected messaging contract changed" - ); - let again = f - .store - .publish(&f.authority, f.message(1, 0), &f.sender, f.clock.now() + 300, None) - .expect("test: seq_is_allocated_in_outbox_transaction: publish succeeds"); - assert_eq!( - again, first, - "seq is allocated in outbox transaction: expected messaging contract changed" - ); - assert_eq!( - f.store - .publish(&f.authority, f.message(2, 0), &f.sender, f.clock.now() + 300, None) - .expect("test: seq_is_allocated_in_outbox_transaction: publish succeeds") - .seq, - 2, - "seq is allocated in outbox transaction: expected messaging contract changed" - ); -} - -#[test] -fn seq2_before_seq1_on_never_seen_stream_is_held_fifo() { - let f = Fixture::new(); - f.receive(2, 2); - assert!( - f.store - .deliver(&f.recipient, &f.target) - .expect("test: seq2_before_seq1_on_never_seen_stream_is_held_fifo: deliver succeeds") - .is_none(), - "seq2 before seq1 on never seen stream is held fifo: expected messaging contract changed" - ); - f.receive(1, 1); - let first = f.deliver(); - assert_eq!( - first.message().seq, - 1, - "seq2 before seq1 on never seen stream is held fifo: expected messaging contract changed" - ); - f.store - .adopt(&first) - .expect("test: seq2_before_seq1_on_never_seen_stream_is_held_fifo: adopt succeeds"); - drop(first); - assert_eq!( - f.deliver().message().seq, - 2, - "seq2 before seq1 on never seen stream is held fifo: expected messaging contract changed" - ); -} - -#[test] -fn late_seq_after_stream_retirement_is_seq_stream_retired() { - let f = Fixture::new(); - let pending = f.message(2, 2); - f.store - .accept(&f.authority, pending) - .expect("test: late_seq_after_stream_retirement_is_seq_stream_retired: accept succeeds"); - f.memory - .pool - .write() - .execute( - "UPDATE prx_mailbox_seq SET state=1,progress=json_set(progress,'$.retired_at',1000)", - [], - ) - .expect("test: late_seq_after_stream_retirement_is_seq_stream_retired: execute succeeds"); - assert_eq!( - f.store.accept(&f.authority, f.message(1, 1)).unwrap_err(), - MailboxError::SeqStreamRetired, - "late seq after stream retirement is seq stream retired: expected messaging contract changed" - ); -} - -#[test] -fn delayed_old_epoch_message_is_rejected_after_stream_reopen() { - let f = Fixture::new(); - f.receive(1, 1); - let first = f.deliver(); - f.store - .adopt(&first) - .expect("test: delayed_old_epoch_message_is_rejected_after_stream_reopen: adopt succeeds"); - drop(first); - f.clock.advance(604801); - f.store - .gc_scope(&f.recipient) - .expect("test: delayed_old_epoch_message_is_rejected_after_stream_reopen: gc_scope succeeds"); - let mut reopened = f.message(3, 1); - reopened.stream_id = Some(Uuid::from_u128(501)); - f.store - .accept(&f.authority, reopened) - .expect("test: delayed_old_epoch_message_is_rejected_after_stream_reopen: accept succeeds"); - assert_eq!( - f.store.accept(&f.authority, f.message(2, 2)).unwrap_err(), - MailboxError::SeqStreamRetired, - "delayed old epoch message is rejected after stream reopen: expected messaging contract changed" - ); -} - -#[test] -fn mailbox_accept_nacks_while_fenced() { - let f = Fixture::new(); - let queued = f.message(1, 1); - f.store - .erase_scope(&f.recipient, Duration::from_secs(5), &|| Ok(())) - .expect("test: mailbox_accept_nacks_while_fenced: erase_scope succeeds"); - assert_eq!( - f.store.accept(&f.authority, queued).unwrap_err(), - MailboxError::ScopeErasing, - "mailbox accept nacks while fenced: expected messaging contract changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_messages"), - 0, - "mailbox accept nacks while fenced: expected messaging contract changed" - ); -} - -#[test] -fn full_queue_nacks_without_drop() { - let f = Fixture::new(); - for n in 1..=64 { - f.clock.advance(1); - f.receive(n, n); - } - f.clock.advance(1); - assert_eq!( - f.store.accept(&f.authority, f.message(65, 65)).unwrap_err(), - MailboxError::QueueFull, - "full queue nacks without drop: capacity enforcement or bounded delivery changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_messages"), - 64, - "full queue nacks without drop: capacity enforcement or bounded delivery changed" - ); - assert_eq!( - f.deliver().message().seq, - 1, - "full queue nacks without drop: capacity enforcement or bounded delivery changed" - ); -} - -#[test] -fn fast_consumer_hits_retained_body_quota() { - let f = Fixture::new(); - // 257 near-limit bodies exceed 64 MiB even though every row is consumed. - for n in 1..=256 { - f.clock.advance(1); - let mut message = f.message(n, n); - message.body.bytes = vec![b'x'; crate::messaging::MAX_BODY_BYTES - 10]; - f.store - .accept(&f.authority, message) - .expect("test: fast_consumer_hits_retained_body_quota: accept succeeds"); - let selected = f.deliver(); - f.store - .adopt(&selected) - .expect("test: fast_consumer_hits_retained_body_quota: adopt succeeds"); - } - f.clock.advance(1); - let mut over = f.message(257, 257); - over.body.bytes = vec![b'x'; crate::messaging::MAX_BODY_BYTES - 10]; - assert_eq!( - f.store.accept(&f.authority, over).unwrap_err(), - MailboxError::Quota("bodies"), - "fast consumer hits retained body quota: payload retention and erasure boundary changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_messages"), - 256, - "fast consumer hits retained body quota: payload retention and erasure boundary changed" - ); - f.clock.advance(604801); - let mut fresh = f.message(258, 1); - fresh.stream_id = Some(Uuid::from_u128(501)); - f.store - .accept(&f.authority, fresh) - .expect("test: fast_consumer_hits_retained_body_quota: accept succeeds"); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_messages"), - 1, - "expired consumed bodies must be GCed before quota refusal" - ); -} - -#[test] -fn cross_instance_chain_depth_is_capped() { - let f = Fixture::new(); - let mut parent = None; - for n in 1..=9 { - f.clock.advance(1); - let mut message = f.message(n, n); - message.in_reply_to = parent; - // Wire depth is maliciously reset; receiver must derive it. - message.hop_count = 0; - message.ancestry.clear(); - let accepted = f - .store - .accept(&f.authority, message.clone()) - .expect("test: cross_instance_chain_depth_is_capped: accept succeeds"); - assert_eq!( - accepted.chain.depth, - n as u8 - 1, - "cross instance chain depth is capped: capacity enforcement or bounded delivery changed" - ); - parent = Some(message.id); - } - let mut too_deep = f.message(10, 10); - too_deep.in_reply_to = parent; - assert_eq!( - f.store.accept(&f.authority, too_deep).unwrap_err(), - MailboxError::ChainDepth, - "cross instance chain depth is capped: capacity enforcement or bounded delivery changed" - ); -} - -#[test] -fn send_reply_resolves_parent_from_outbox_without_transcript() { - let f = Fixture::new(); - let sent = f - .store - .publish(&f.authority, f.message(1, 0), &f.sender, f.clock.now() + 300, None) - .expect("test: send_reply_resolves_parent_from_outbox_without_transcript: publish succeeds"); - let mut reply = f.message(2, 1); - reply.in_reply_to = Some(sent.message_id); - reply.stream_id = Some(Uuid::from_u128(502)); - let received = f - .store - .accept(&f.authority, reply) - .expect("test: send_reply_resolves_parent_from_outbox_without_transcript: accept succeeds"); - assert_eq!( - received.chain.depth, 1, - "send reply resolves parent from outbox without transcript: atomic adoption or history projection changed" - ); - assert_eq!( - received.chain.ancestry, - vec![sent.message_id], - "send reply resolves parent from outbox without transcript: atomic adoption or history projection changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM conversation_turns"), - 0, - "send reply resolves parent from outbox without transcript: atomic adoption or history projection changed" - ); -} - -#[test] -fn idempotent_retry_after_parent_erase_reports_scope_erasing() { - let f = Fixture::new(); - f.receive(1, 1); - let mut reply = f.message(2, 2); - reply.in_reply_to = Some(Uuid::from_u128(1001)); - f.store - .accept(&f.authority, reply.clone()) - .expect("test: idempotent_retry_after_parent_erase_reports_scope_erasing: accept succeeds"); - f.store - .erase_scope(&f.recipient, Duration::from_secs(5), &|| Ok(())) - .expect("test: idempotent_retry_after_parent_erase_reports_scope_erasing: erase_scope succeeds"); - assert_eq!( - f.store - .accept(&f.authority, reply) - .expect_err("test: erased nonconsumed replay is terminal"), - MailboxError::ScopeErasing, - "erased nonconsumed replay must report scope erasure" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_outbox"), - 0, - "erased nonconsumed replay must report scope erasure" - ); -} - -#[test] -fn altered_parent_retry_after_erase_is_idempotency_conflict() { - let f = Fixture::new(); - f.receive(1, 1); - let mut reply = f.message(2, 2); - reply.in_reply_to = Some(Uuid::from_u128(1001)); - f.store - .accept(&f.authority, reply.clone()) - .expect("test: altered_parent_retry_after_erase_is_idempotency_conflict: accept succeeds"); - f.store - .erase_scope(&f.recipient, Duration::from_secs(5), &|| Ok(())) - .expect("test: altered_parent_retry_after_erase_is_idempotency_conflict: erase_scope succeeds"); - reply.in_reply_to = None; - assert_eq!( - f.store.accept(&f.authority, reply).unwrap_err(), - MailboxError::IdempotencyConflict, - "altered parent retry after erase is idempotency conflict: payload retention and erasure boundary changed" - ); -} - -struct LocalResolver { - store: SqliteMailbox, - authority: MailboxAuthority, - scope: MailboxScope, -} -#[async_trait::async_trait] -impl crate::messaging::send::MailboxResolver for LocalResolver { - async fn resolve( - &self, - target: &SessionAddr, - ) -> crate::messaging::mailbox::MailboxResult { - if *target != self.authority.destination { - return Err(MailboxError::Unauthorized); - } - Ok(crate::messaging::send::MailboxDestination { - authority: self.authority.clone(), - pin: self - .store - .recipient_pin(&self.authority, &self.scope, "canonical-target")?, - pin_expires_at: 10_000, - }) - } -} -impl Fixture { - fn sender_port( - &self, - inherited: Option, - ) -> Arc { - Arc::new( - crate::memory::sqlite::mailbox::SqliteMailboxSender::new( - self.store.clone(), - self.source.clone(), - self.sender.clone(), - Arc::new(LocalResolver { - store: self.store.clone(), - authority: self.authority.clone(), - scope: self.recipient.clone(), - }), - inherited, - ) - .expect("test: sender_port: SqliteMailboxSender::new succeeds"), - ) - } -} - -#[tokio::test] -async fn prx_message_tool_emits_one_external_send_envelope() { - use crate::tools::Tool; - let f = Fixture::new(); - let tool = crate::tools::prx_message::PrxMessageTool::new(f.sender_port(None)); - let registry: Vec> = vec![Box::new(crate::tools::prx_message::PrxMessageTool::new( - f.sender_port(None), - ))]; - let catalog = crate::tools::capability::catalog::CapabilityCatalog::build( - ®istry, - &crate::tools::capability::catalog::CatalogSources::default(), - &crate::tools::capability::catalog::SurfacePolicy::default(), - ) - .expect("test: prx_message_tool_emits_one_external_send_envelope: fixture setup succeeds"); - assert_eq!( - catalog - .entry_for_public_name("prx_message") - .expect("test: prx_message_tool_emits_one_external_send_envelope: entry_for_public_name succeeds") - .effect, - crate::tools::capability::contract::SideEffectClass::ExternalSend, - "prx message tool emits one external send envelope: expected messaging contract changed" - ); - let result = tool - .execute(serde_json::json!({"to":{"session":"target"},"text":"ordinary Data"})) - .await - .expect("test: prx_message_tool_emits_one_external_send_envelope: execute succeeds"); - assert!(result.success, "{}", result.output); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_outbox"), - 1, - "prx message tool emits one external send envelope: expected messaging contract changed" - ); - let out = f - .store - .pending_outbox(&f.sender, &f.source) - .expect("test: prx_message_tool_emits_one_external_send_envelope: pending_outbox succeeds"); - assert_eq!( - out[0].message().kind, - MessageKind::Data, - "prx message tool emits one external send envelope: expected messaging contract changed" - ); - assert_eq!( - out[0].message().body.bytes, - b"ordinary Data", - "prx message tool emits one external send envelope: expected messaging contract changed" - ); - assert_eq!( - out[0].message().from, - f.source, - "prx message tool emits one external send envelope: expected messaging contract changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_messages"), - 0, - "sender tool does not execute the recipient" - ); - for invalid in [ - serde_json::json!({"to":{"session":"target","owner":null},"text":"x"}), - serde_json::json!({"to":{"session":"target"},"text":"x","in_reply_to":null}), - ] { - assert!( - tool.execute(invalid).await.is_err(), - "prx message tool emits one external send envelope: expected messaging contract changed" - ); - } - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_outbox"), - 1, - "prx message tool emits one external send envelope: expected messaging contract changed" - ); -} - -#[tokio::test] -async fn prx_message_tool_send_is_stamped_with_runtime_causal_chain() { - use crate::tools::Tool; - let f = Fixture::new(); - let accepted = f.receive(1, 1); - let inherited = crate::messaging::InheritedProvenance { - remote: crate::messaging::RemotePeerAttr { - issuer: "prx-issuer".into(), - subject: "prx-peer".into(), - message_id: accepted.message_id, - }, - chain: accepted.chain, - }; - let tool = crate::tools::prx_message::PrxMessageTool::new(f.sender_port(Some(inherited.clone()))); - let result = tool - .execute(serde_json::json!({"to":{"session":"target"},"text":"reply"})) - .await - .expect("test: prx_message_tool_send_is_stamped_with_runtime_causal_chain: execute succeeds"); - assert!(result.success, "{}", result.output); - let out = f - .store - .pending_outbox(&f.sender, &f.source) - .expect("test: prx_message_tool_send_is_stamped_with_runtime_causal_chain: pending_outbox succeeds"); - assert_eq!( - out[0].message().in_reply_to, - Some(inherited.chain.trigger), - "prx message tool send is stamped with runtime causal chain: expected messaging contract changed" - ); - assert_eq!( - out[0].message().hop_count, - 1, - "prx message tool send is stamped with runtime causal chain: expected messaging contract changed" - ); - assert_eq!( - f.scalar("SELECT sends FROM prx_remote_trees"), - 1, - "prx message tool send is stamped with runtime causal chain: expected messaging contract changed" - ); -} - -#[tokio::test] -async fn sessions_send_remote_addr_is_not_steer() { - use crate::tools::Tool; - let f = Fixture::new(); - let tool = crate::tools::sessions_send::SessionsSendTool::new(Arc::new(tokio::sync::RwLock::new(Vec::new()))) - .with_mailbox(f.sender_port(None)); - assert!( - tool.parameters_schema().get("oneOf").is_some(), - "sessions send remote addr is not steer: expected messaging contract changed" - ); - assert!( - tool.execute(serde_json::json!({"to":{"session":"target"},"message":"mailbox Data"})) - .await - .expect("test: sessions_send_remote_addr_is_not_steer: execute succeeds") - .success, - "sessions send remote addr is not steer: expected messaging contract changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_outbox"), - 1, - "sessions send remote addr is not steer: expected messaging contract changed" - ); - assert!( - tool.execute(serde_json::json!({"run_id":"run-target","to":{"session":"target"},"message":"ambiguous"})) - .await - .is_err(), - "sessions send remote addr is not steer: expected messaging contract changed" - ); -} - -#[test] -fn slash_msg_builds_envelope_to_peer_session() { - let f = Fixture::new(); - let (target, text) = crate::chat::commands::msg::parse("/msg peer-node target/prx_agent hello peer", &f.source) - .expect("test: slash_msg_builds_envelope_to_peer_session: fixture setup succeeds"); - assert_eq!( - target, - SessionAddr::new("peer-node", O, "target", Some("prx_agent")), - "slash msg builds envelope to peer session: expected messaging contract changed" - ); - assert_eq!( - text, "hello peer", - "slash msg builds envelope to peer session: expected messaging contract changed" - ); - assert!( - crate::chat::commands::msg::parse("/msg local target/ ", &f.source).is_err(), - "slash msg builds envelope to peer session: expected messaging contract changed" - ); -} - -#[test] -fn mailbox_formats_and_natural_key_collisions_fail_closed() { - let f = Fixture::new(); - let original = f.message(1, 1); - f.store - .accept(&f.authority, original.clone()) - .expect("test: mailbox_formats_and_natural_key_collisions_fail_closed: accept succeeds"); - f.memory - .pool - .write() - .execute( - "UPDATE prx_mailbox_receipts SET receipt_meta=json_set(receipt_meta,'$.unknown',1)", - [], - ) - .expect("test: mailbox_formats_and_natural_key_collisions_fail_closed: execute succeeds"); - assert_eq!( - f.store.accept(&f.authority, original.clone()).unwrap_err(), - MailboxError::InvalidMetadata, - "mailbox formats and natural key collisions fail closed: expected messaging contract changed" - ); - f.memory - .pool - .write() - .execute( - "UPDATE prx_mailbox_receipts SET receipt_meta=json_remove(receipt_meta,'$.unknown')", - [], - ) - .expect("test: mailbox_formats_and_natural_key_collisions_fail_closed: execute succeeds"); - let canonical = f - .memory - .pool - .write() - .query_row("SELECT receipt_meta FROM prx_mailbox_receipts", [], |r| { - r.get::<_, String>(0) - }) - .expect("test: mailbox_formats_and_natural_key_collisions_fail_closed: query_row succeeds"); - f.memory - .pool - .write() - .execute( - "UPDATE prx_mailbox_receipts SET receipt_meta=?1", - [format!(" {canonical}")], - ) - .expect("test: mailbox_formats_and_natural_key_collisions_fail_closed: execute succeeds"); - assert_eq!( - f.store.accept(&f.authority, original.clone()).unwrap_err(), - MailboxError::InvalidMetadata, - "mailbox formats and natural key collisions fail closed: expected messaging contract changed" - ); - f.memory - .pool - .write() - .execute("UPDATE prx_mailbox_receipts SET receipt_meta=?1", [canonical]) - .expect("test: mailbox_formats_and_natural_key_collisions_fail_closed: execute succeeds"); - f.memory - .pool - .write() - .execute("UPDATE prx_mailbox_seq SET wire_stream_id=zeroblob(15)", []) - .expect("test: mailbox_formats_and_natural_key_collisions_fail_closed: execute succeeds"); - assert_eq!( - f.store.accept(&f.authority, original.clone()).unwrap_err(), - MailboxError::CorruptState, - "mailbox formats and natural key collisions fail closed: expected messaging contract changed" - ); - f.memory - .pool - .write() - .execute( - "UPDATE prx_mailbox_seq SET wire_stream_id=?1", - [Uuid::from_u128(STREAM).as_bytes().as_slice()], - ) - .expect("test: mailbox_formats_and_natural_key_collisions_fail_closed: execute succeeds"); - let mut changed = f.target.clone(); - changed.session = "other-target".into(); - f.memory - .pool - .write() - .execute( - "UPDATE prx_mailbox_seq SET to_addr=?1", - [serde_json::to_string(&changed).expect( - "test: mailbox_formats_and_natural_key_collisions_fail_closed: serde_json::to_string succeeds", - )], - ) - .expect("test: mailbox_formats_and_natural_key_collisions_fail_closed: execute succeeds"); - assert_eq!( - f.store.accept(&f.authority, original).unwrap_err(), - MailboxError::NaturalKeyCollision, - "mailbox formats and natural key collisions fail closed: expected messaging contract changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), - 1, - "mailbox formats and natural key collisions fail closed: expected messaging contract changed" - ); -} - -#[test] -fn mailbox_scope_pin_role_and_run_checks_fail_closed() { - let f = Fixture::new(); - let mut message = f.message(1, 1); - message.exec = Some(ExecRef { - run: Some("replaced-run".into()), - }); - assert_eq!( - f.store.accept(&f.authority, message).unwrap_err(), - MailboxError::StaleRun, - "mailbox scope pin role and run checks fail closed: recipient authority or scope isolation changed" - ); - f.receive(1, 1); - f.memory - .pool - .write() - .execute("UPDATE prx_mailbox_seq SET recipient_generation=NULL", []) - .expect("test: mailbox_scope_pin_role_and_run_checks_fail_closed: execute succeeds"); - assert!( - matches!( - f.store.deliver(&f.recipient, &f.target), - Err(MailboxError::CorruptState) - ), - "mailbox scope pin role and run checks fail closed: recipient authority or scope isolation changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM conversation_turns"), - 0, - "mailbox scope pin role and run checks fail closed: recipient authority or scope isolation changed" - ); -} - -#[test] -fn mailbox_identity_and_state_transitions_are_immutable() { - let f = Fixture::new(); - f.receive(1, 1); - let delivery = f.deliver(); - f.memory - .pool - .write() - .execute( - "UPDATE prx_mailbox_messages SET body_bytes=?1", - [b"tampered".as_slice()], - ) - .expect("test: mailbox_identity_and_state_transitions_are_immutable: execute succeeds"); - assert_eq!( - f.store.adopt(&delivery).unwrap_err(), - MailboxError::IdentityImmutable, - "mailbox identity and state transitions are immutable: replay identity or receipt stability changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM conversation_turns"), - 0, - "mailbox identity and state transitions are immutable: replay identity or receipt stability changed" - ); - assert_eq!( - f.scalar("SELECT state FROM prx_mailbox_receipts"), - 1, - "mailbox identity and state transitions are immutable: replay identity or receipt stability changed" - ); -} - -#[test] -fn mailbox_transport_and_chain_metadata_is_runtime_owned() { - let f = Fixture::new(); - let mut message = f.message(1, 1); - message.from = SessionAddr::new("forged-instance", "forged-owner", "forged-session", None); - message.origin = Some(crate::messaging::MessageOrigin::RemotePeer); - message.auth = Some(crate::messaging::MessageAuth { - issuer: "forged".into(), - subject: "forged".into(), - method: "jwt".into(), - }); - message.hop_count = 8; - message.ancestry = vec![Uuid::nil(); 8]; - let receipt = f - .store - .accept(&f.authority, message) - .expect("test: mailbox_transport_and_chain_metadata_is_runtime_owned: accept succeeds"); - assert_eq!( - receipt.chain.depth, 0, - "mailbox transport and chain metadata is runtime owned: expected messaging contract changed" - ); - assert!( - receipt.remote.is_none(), - "mailbox transport and chain metadata is runtime owned: expected messaging contract changed" - ); - let delivered = f.deliver(); - assert_eq!( - delivered.message().from, - f.source, - "mailbox transport and chain metadata is runtime owned: expected messaging contract changed" - ); - assert_eq!( - delivered.message().origin, - Some(crate::messaging::MessageOrigin::LocalModel), - "mailbox transport and chain metadata is runtime owned: expected messaging contract changed" - ); - assert!( - delivered.message().auth.is_none(), - "mailbox transport and chain metadata is runtime owned: expected messaging contract changed" - ); -} - -#[test] -fn mailbox_replay_slot_and_message_id_reuse_are_checked() { - let f = Fixture::new(); - let message = f.message(1, 1); - let first = f - .store - .accept(&f.authority, message.clone()) - .expect("test: mailbox_replay_slot_and_message_id_reuse_are_checked: accept succeeds"); - let mut occupied = f.message(2, 1); - assert_eq!( - f.store.accept(&f.authority, occupied.clone()).unwrap_err(), - MailboxError::SeqConflict, - "mailbox replay slot and message id reuse are checked: replay identity or receipt stability changed" - ); - occupied.seq = 2; - occupied.id = message.id; - assert_eq!( - f.store.accept(&f.authority, occupied).unwrap_err(), - MailboxError::IdReuse, - "mailbox replay slot and message id reuse are checked: replay identity or receipt stability changed" - ); - assert_eq!( - f.store - .accept(&f.authority, message) - .expect("test: mailbox_replay_slot_and_message_id_reuse_are_checked: accept succeeds"), - first, - "mailbox replay slot and message id reuse are checked: replay identity or receipt stability changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), - 1, - "mailbox replay slot and message id reuse are checked: replay identity or receipt stability changed" - ); -} - -#[test] -fn mailbox_progress_and_gap_transitions_are_checked() { - let f = Fixture::new(); - let message = f.message(1, 1026); - assert_eq!( - f.store.accept(&f.authority, message).unwrap_err(), - MailboxError::Quota("seq"), - "mailbox progress and gap transitions are checked: expected messaging contract changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_seq"), - 0, - "gap reservation rolls back stream insert" - ); - f.receive(1, 1); - let delivery = f.deliver(); - assert_eq!( - f.store.recover_delivery(&f.recipient, &f.target).unwrap_err(), - MailboxError::RoleBusy, - "mailbox progress and gap transitions are checked: expected messaging contract changed" - ); - f.store - .adopt(&delivery) - .expect("test: mailbox_progress_and_gap_transitions_are_checked: adopt succeeds"); - drop(delivery); - f.store - .recover_delivery(&f.recipient, &f.target) - .expect("test: mailbox_progress_and_gap_transitions_are_checked: recover_delivery succeeds"); - assert!( - f.store - .deliver(&f.recipient, &f.target) - .expect("test: mailbox_progress_and_gap_transitions_are_checked: deliver succeeds") - .is_none(), - "mailbox progress and gap transitions are checked: expected messaging contract changed" - ); - f.memory - .pool - .write() - .execute( - "UPDATE prx_mailbox_seq SET progress=json_set(progress,'$.next_seq',0)", - [], - ) - .expect("test: mailbox_progress_and_gap_transitions_are_checked: execute succeeds"); - assert!( - matches!( - f.store.deliver(&f.recipient, &f.target), - Err(MailboxError::CorruptState) - ), - "mailbox progress and gap transitions are checked: expected messaging contract changed" - ); -} - -#[test] -fn fresh_sender_session_labels_after_receipt_gc_hit_stream_quota() { - let f = Fixture::new(); - f.receive(1, 1); - let delivery = f.deliver(); - f.store - .adopt(&delivery) - .expect("test: fresh_sender_session_labels_after_receipt_gc_hit_stream_quota: adopt succeeds"); - drop(delivery); - f.clock.advance(604801); - f.store - .gc_scope(&f.recipient) - .expect("test: fresh_sender_session_labels_after_receipt_gc_hit_stream_quota: gc_scope succeeds"); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), - 0, - "fresh sender session labels after receipt gc hit stream quota: capacity enforcement or bounded delivery changed" - ); - // Populate the remaining bounded tombstone inventory from the real retired - // row; no messages/receipts remain to provide accidental quota coverage. - f.memory.pool.write().execute_batch("WITH RECURSIVE n(v) AS (SELECT 1 UNION ALL SELECT v+1 FROM n WHERE v<4095) INSERT INTO prx_mailbox_seq(workspace_id,owner_id,sender_ma_scope_id,sender_incarnation,sender_generation,recipient_ma_scope_id,recipient_incarnation,recipient_generation,from_addr,to_addr,wire_stream_id,state,progress,updated_at) SELECT workspace_id,owner_id,sender_ma_scope_id,sender_incarnation,sender_generation,recipient_ma_scope_id,recipient_incarnation,recipient_generation,json_set(from_addr,'$.session','retired-'||v),to_addr,randomblob(16),state,progress,updated_at FROM prx_mailbox_seq,n WHERE stream_id=1;").expect("test: fresh_sender_session_labels_after_receipt_gc_hit_stream_quota: fixture setup succeeds"); - let mut source = f.source.clone(); - source.session = "fresh-sender-label".into(); - let authority = MailboxAuthority::local(W.into(), source, f.target.clone()).expect( - "test: fresh_sender_session_labels_after_receipt_gc_hit_stream_quota: MailboxAuthority::local succeeds", - ); - let mut message = f.message(2, 1); - message.stream_id = Some(Uuid::new_v4()); - message.to_pin = f - .store - .recipient_pin(&authority, &f.recipient, "canonical-target") - .expect("test: fresh_sender_session_labels_after_receipt_gc_hit_stream_quota: recipient_pin succeeds"); - assert_eq!( - f.store.accept(&authority, message).unwrap_err(), - MailboxError::Quota("streams"), - "fresh sender session labels after receipt gc hit stream quota: capacity enforcement or bounded delivery changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_seq"), - 4096, - "fresh sender session labels after receipt gc hit stream quota: capacity enforcement or bounded delivery changed" - ); -} - -#[tokio::test] -async fn child_message_reaches_main_mailbox() { - use crate::chat::sessions::child::{ChildSession, ChildSessionRegistry}; - let mut f = Fixture::new(); - let registry = ChildSessionRegistry::new(Arc::new(f.memory.clone())).with_workspace(W.into()); - registry - .insert(&ChildSession::new(f.source.clone(), None, None)) - .await - .expect("test: child_message_reaches_main_mailbox: insert succeeds"); - let child = registry - .reconstruct(&f.source) - .await - .expect("test: child_message_reaches_main_mailbox: reconstruct succeeds"); - f.sender = child - .mailbox_scope() - .expect("test: child_message_reaches_main_mailbox: mailbox_scope succeeds") - .clone(); - let provisional = f.message(1, 0); - f.store - .publish(&f.authority, provisional, &f.sender, f.clock.now() + 300, None) - .expect("test: child_message_reaches_main_mailbox: publish succeeds"); - let outgoing = f - .store - .pending_outbox(&f.sender, &f.source) - .expect("test: child_message_reaches_main_mailbox: pending_outbox succeeds"); - f.store - .accept(&f.authority, outgoing[0].message().clone()) - .expect("test: child_message_reaches_main_mailbox: accept succeeds"); - let delivery = f.deliver(); - let receipt = f - .store - .adopt(&delivery) - .expect("test: child_message_reaches_main_mailbox: adopt succeeds"); - assert_eq!( - receipt.state, - DeliveryState::Consumed, - "child message reaches main mailbox: expected messaging contract changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM conversation_turns"), - 1, - "child message reaches main mailbox: expected messaging contract changed" - ); -} - -#[tokio::test] -async fn sibling_message_is_owner_scoped() { - use crate::chat::sessions::child::{ChildSession, ChildSessionRegistry}; - let f = Fixture::new(); - let registry = ChildSessionRegistry::new(Arc::new(f.memory.clone())).with_workspace(W.into()); - for address in [&f.source, &f.target] { - registry - .insert(&ChildSession::new(address.clone(), None, None)) - .await - .expect("test: sibling_message_is_owner_scoped: insert succeeds"); - } - let target = registry - .reconstruct(&f.target) - .await - .expect("test: sibling_message_is_owner_scoped: reconstruct succeeds"); - let scope = target - .mailbox_scope() - .expect("test: sibling_message_is_owner_scoped: mailbox_scope succeeds") - .clone(); - let canonical = ChildSessionRegistry::canonical_session_key(&f.target) - .expect("test: sibling_message_is_owner_scoped: ChildSessionRegistry::canonical_session_key succeeds"); - let mut message = f.message(1, 1); - message.to_pin = f - .store - .recipient_pin(&f.authority, &scope, &canonical) - .expect("test: sibling_message_is_owner_scoped: recipient_pin succeeds"); - f.store - .accept(&f.authority, message.clone()) - .expect("test: sibling_message_is_owner_scoped: accept succeeds"); - let mut foreign = f.source.clone(); - foreign.owner = "other-owner".into(); - assert!( - matches!( - MailboxAuthority::local(W.into(), foreign, f.target.clone()), - Err(MailboxError::Unauthorized) - ), - "sibling message is owner scoped: recipient authority or scope isolation changed" - ); - let mut foreign_target = f.target.clone(); - foreign_target.owner = "other-owner".into(); - message.to = foreign_target; - assert_eq!( - f.store.accept(&f.authority, message).unwrap_err(), - MailboxError::Unauthorized, - "sibling message is owner scoped: recipient authority or scope isolation changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), - 1, - "sibling message is owner scoped: recipient authority or scope isolation changed" - ); -} - -#[tokio::test] -async fn child_sessions_migration_22_preserves_records_and_quarantines_unbound_rows() { - use crate::chat::sessions::child::{ChildSession, ChildSessionRegistry}; - use crate::memory::child_sessions::{ChildSessionContext, ChildSessionError, ChildSessionStore}; - let f = Fixture::new(); - let registry = ChildSessionRegistry::new(Arc::new(f.memory.clone())).with_workspace(W.into()); - registry - .insert(&ChildSession::new(f.target.clone(), None, None)) - .await - .expect("test: child_sessions_migration_22_preserves_records_and_quarantines_unbound_rows: insert succeeds"); - let key = ChildSessionRegistry::canonical_session_key(&f.target) - .expect("test: child_sessions_migration_22_preserves_records_and_quarantines_unbound_rows: ChildSessionRegistry::canonical_session_key succeeds"); - let context = ChildSessionContext { - workspace_id: W.into(), - addr: f.target.clone(), - }; - let original = f - .memory - .pool - .write() - .query_row("SELECT record FROM child_sessions WHERE key=?1", [&key], |r| { - r.get::<_, String>(0) - }) - .expect("test: child_sessions_migration_22_preserves_records_and_quarantines_unbound_rows: query_row succeeds"); - f.memory.pool.write().execute("UPDATE child_sessions SET workspace_id=NULL,owner_id=NULL,instance_id=NULL,session_id=NULL,agent_key=NULL,ma_scope_id=NULL,incarnation=NULL,generation=NULL WHERE key=?1",[&key]).expect("test: child_sessions_migration_22_preserves_records_and_quarantines_unbound_rows: fixture setup succeeds"); - let refused = match ChildSessionStore::load(&f.memory, &key, &context) { - Ok(_) => panic!("quarantined legacy row loaded"), - Err(error) => error, - }; - assert!( - refused.is::(), - "child sessions migration 22 preserves records and quarantines unbound rows: capacity enforcement or bounded delivery changed" - ); - let recovered = - ChildSessionStore::update(&f.memory, &key, &context, &mut |old| Ok(old.expect("test: child_sessions_migration_22_preserves_records_and_quarantines_unbound_rows: fixture setup succeeds").to_owned())).expect("test: child_sessions_migration_22_preserves_records_and_quarantines_unbound_rows: ChildSessionStore::update succeeds"); - assert_eq!( - recovered.record, original, - "child sessions migration 22 preserves records and quarantines unbound rows: capacity enforcement or bounded delivery changed" - ); - drop(recovered); - // A partially populated row is never a backfill candidate. - f.memory - .pool - .write() - .execute("UPDATE child_sessions SET generation=NULL WHERE key=?1", [&key]) - .expect("test: child_sessions_migration_22_preserves_records_and_quarantines_unbound_rows: execute succeeds"); - assert!( - ChildSessionStore::update(&f.memory, &key, &context, &mut |_| Ok(original.clone())).is_err(), - "child sessions migration 22 preserves records and quarantines unbound rows: capacity enforcement or bounded delivery changed" - ); - assert_eq!( - f.memory - .pool - .write() - .query_row("SELECT record FROM child_sessions WHERE key=?1", [&key], |r| r - .get::<_, String>(0)) - .expect( - "test: child_sessions_migration_22_preserves_records_and_quarantines_unbound_rows: query_row succeeds" - ), - original, - "child sessions migration 22 preserves records and quarantines unbound rows: capacity enforcement or bounded delivery changed" - ); -} - -#[test] -fn mailbox_index_plans_use_scope_and_stream_prefixes() { - let f = Fixture::new(); - let writer = f.memory.pool.write(); - for (query, index) in [ - ( - "SELECT message_id FROM prx_mailbox_receipts WHERE ma_scope_id='scope' AND expires_at>=0", - "mailbox_receipt_scope_expiry", - ), - ( - "SELECT id FROM prx_mailbox_messages WHERE stream_id=1 AND state=0 AND seq>x'0000000000000000' ORDER BY seq", - "mailbox_message_delivery", - ), - ( - "SELECT id FROM prx_mailbox_outbox WHERE stream_id=1 AND state=0 ORDER BY seq", - "mailbox_outbox_delivery", - ), - ( - "SELECT stream_id FROM prx_mailbox_seq WHERE recipient_ma_scope_id='scope'", - "mailbox_seq_recipient", - ), - ( - "SELECT key FROM child_sessions WHERE ma_scope_id='scope'", - "child_sessions_scope", - ), - ] { - let mut statement = writer - .prepare(&format!("EXPLAIN QUERY PLAN {query}")) - .expect("test: mailbox_index_plans_use_scope_and_stream_prefixes: prepare succeeds"); - let details = statement - .query_map([], |r| r.get::<_, String>(3)) - .expect("test: mailbox_index_plans_use_scope_and_stream_prefixes: query_map succeeds") - .collect::>>() - .expect("test: mailbox_index_plans_use_scope_and_stream_prefixes: collect succeeds") - .join(" "); - assert!(details.contains(index), "{query}: {details}"); - if index == "mailbox_receipt_scope_expiry" { - assert!( - details.contains("COVERING"), - "id-reuse probe must not load receipt bodies: {details}" - ); - } - } -} - -#[test] -fn mailbox_u64_sequence_exhaustion_never_wraps_or_truncates() { - let f = Fixture::new(); - f.store - .publish(&f.authority, f.message(1, 0), &f.sender, f.clock.now() + 300, None) - .expect("test: mailbox_u64_sequence_exhaustion_never_wraps_or_truncates: publish succeeds"); - let progress = f - .memory - .pool - .write() - .query_row("SELECT progress FROM prx_mailbox_seq", [], |r| r.get::<_, String>(0)) - .expect("test: mailbox_u64_sequence_exhaustion_never_wraps_or_truncates: query_row succeeds"); - let progress = progress.replacen("\"next_seq\":2", &format!("\"next_seq\":{}", u64::MAX), 1); - f.memory - .pool - .write() - .execute("UPDATE prx_mailbox_seq SET progress=?1", [progress]) - .expect("test: mailbox_u64_sequence_exhaustion_never_wraps_or_truncates: execute succeeds"); - let last = f - .store - .publish(&f.authority, f.message(2, 0), &f.sender, f.clock.now() + 300, None) - .expect("test: mailbox_u64_sequence_exhaustion_never_wraps_or_truncates: publish succeeds"); - assert_eq!( - last.seq, - u64::MAX, - "mailbox u64 sequence exhaustion never wraps or truncates: expected messaging contract changed" - ); - assert_eq!( - f.store - .publish(&f.authority, f.message(3, 0), &f.sender, f.clock.now() + 300, None) - .unwrap_err(), - MailboxError::Quota("seq"), - "mailbox u64 sequence exhaustion never wraps or truncates: expected messaging contract changed" - ); - let raw = f - .memory - .pool - .write() - .query_row( - "SELECT hex(seq) FROM prx_mailbox_outbox WHERE id=?1", - [last.row_id], - |r| r.get::<_, String>(0), - ) - .expect("test: mailbox_u64_sequence_exhaustion_never_wraps_or_truncates: fixture setup succeeds"); - assert_eq!( - raw, "FFFFFFFFFFFFFFFF", - "mailbox u64 sequence exhaustion never wraps or truncates: expected messaging contract changed" - ); -} - -#[tokio::test] -async fn process_worker_message_frame_roundtrips() { - use crate::session_worker::protocol::{WorkerControlFrame, WorkerOutputFrame}; - let f = Fixture::new(); - let published = f - .store - .publish(&f.authority, f.message(1, 0), &f.sender, f.clock.now() + 300, None) - .expect("test: process_worker_message_frame_roundtrips: publish succeeds"); - let outgoing = f - .store - .pending_outbox(&f.sender, &f.source) - .expect("test: process_worker_message_frame_roundtrips: pending_outbox succeeds"); - let message = outgoing - .first() - .expect("test: process_worker_message_frame_roundtrips: first succeeds") - .message() - .clone(); - f.store - .accept(&f.authority, message.clone()) - .expect("test: process_worker_message_frame_roundtrips: accept succeeds"); - let delivered = f.deliver(); - let frame = WorkerControlFrame::Message { - envelope: Box::new(delivered.message().clone()), - }; - let decoded: WorkerControlFrame = serde_json::from_slice( - &serde_json::to_vec(&frame) - .expect("test: process_worker_message_frame_roundtrips: serde_json::to_vec succeeds"), - ) - .expect("test: process_worker_message_frame_roundtrips: serde_json::from_slice succeeds"); - let (mut sender, mut inbox) = crate::session_worker::mailbox::worker_mailbox(f.target.clone(), "run-target".into()) - .expect("test: process_worker_message_frame_roundtrips: mailbox::worker_mailbox succeeds"); - let (sender, ack) = tokio::task::spawn_blocking(move || { - let WorkerControlFrame::Message { envelope } = decoded else { - panic!("Data frame became another control kind"); - }; - let ack = sender - .enqueue(*envelope) - .expect("test: process_worker_message_frame_roundtrips: enqueue succeeds"); - (sender, ack) - }) - .await - .expect("test: process_worker_message_frame_roundtrips: task::spawn_blocking succeeds"); - assert_eq!( - ack, - WorkerOutputFrame::Ack { - message_id: published.message_id, - state: DeliveryState::Delivered - }, - "process worker message frame roundtrips: IPC identity or delivery state changed" - ); - let queued = inbox - .try_next() - .expect("test: process_worker_message_frame_roundtrips: try_next succeeds"); - assert_eq!( - crate::session_worker::mailbox::user_text(&queued) - .expect("test: process_worker_message_frame_roundtrips: mailbox::user_text succeeds"), - "request-1", - "process worker message frame roundtrips: IPC identity or delivery state changed" - ); - let consumed = inbox - .consumed(&queued) - .expect("test: process_worker_message_frame_roundtrips: consumed succeeds"); - let saved = f - .store - .adopt(&delivered) - .expect("test: process_worker_message_frame_roundtrips: adopt succeeds"); - assert_eq!( - consumed, - WorkerOutputFrame::Ack { - message_id: saved.message_id, - state: saved.state - }, - "process worker message frame roundtrips: IPC identity or delivery state changed" - ); - let duplicate = tokio::task::spawn_blocking(move || { - let mut sender = sender; - sender - .enqueue(message) - .expect("test: process_worker_message_frame_roundtrips: enqueue succeeds") - }) - .await - .expect("test: process_worker_message_frame_roundtrips: task::spawn_blocking succeeds"); - assert_eq!( - duplicate, ack, - "a pruned worker slot may requeue a transport replay; durable adoption remains idempotent" - ); - assert!( - inbox.try_next().is_some(), - "process worker message frame roundtrips: IPC identity or delivery state changed" - ); - assert_eq!( - f.store - .adopt(&delivered) - .expect("test: process_worker_message_frame_roundtrips: adopt succeeds"), - saved, - "process worker message frame roundtrips: IPC identity or delivery state changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM conversation_turns"), - 1, - "process worker message frame roundtrips: IPC identity or delivery state changed" - ); -} - -#[test] -fn worker_data_reaches_parent_mailbox() { - use crate::session_worker::protocol::WorkerOutputFrame; - let f = Fixture::new(); - // This worker is the source endpoint; the destination parent is bound by - // its real MA scope and an HMAC recipient pin, not by asserted frame.from. - let parent_key = crate::chat::sessions::child::ChildSessionRegistry::canonical_session_key(&f.target) - .expect("test: canonical parent key"); - f.memory - .pool - .write() - .execute( - "UPDATE agent_scopes SET session_key=?1 WHERE scope_id=?2", - params![parent_key, f.recipient.scope_id.to_string()], - ) - .expect("test: bind parent canonical scope"); - let mut parent = crate::session_worker::mailbox_parent::WorkerMailboxParent::new( - f.store.clone(), - f.source.clone(), - f.sender.clone(), - f.target.clone(), - f.recipient.clone(), - "run-source".into(), - None, - ) - .expect("test: worker_data_reaches_parent_mailbox: WorkerMailboxParent::new succeeds"); - let mut message = f.message(1, 0); - message.to_pin.token.clear(); - message.from = SessionAddr::new("forged-instance", "forged-owner", "forged-session", None); - let receipt = parent - .receive(WorkerOutputFrame::Message { - envelope: Box::new(message.clone()), - }) - .expect("test: worker_data_reaches_parent_mailbox: receive succeeds") - .expect("test: worker_data_reaches_parent_mailbox: receive returns a value"); - assert_eq!( - receipt.state, - DeliveryState::Accepted, - "worker data reaches parent mailbox: IPC identity or delivery state changed" - ); - assert_eq!( - receipt.seq, 1, - "worker data reaches parent mailbox: IPC identity or delivery state changed" - ); - let duplicate = parent - .receive(WorkerOutputFrame::Message { - envelope: Box::new(message), - }) - .expect("test: worker_data_reaches_parent_mailbox: receive succeeds") - .expect("test: worker_data_reaches_parent_mailbox: receive returns a value"); - assert_eq!( - duplicate, receipt, - "worker data reaches parent mailbox: IPC identity or delivery state changed" - ); - let delivered = f.deliver(); - assert_eq!( - delivered.message().from, - f.source, - "worker data reaches parent mailbox: IPC identity or delivery state changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_messages"), - 1, - "worker data reaches parent mailbox: IPC identity or delivery state changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_outbox"), - 1, - "worker data reaches parent mailbox: IPC identity or delivery state changed" - ); -} - -#[test] -fn worker_data_keeps_sealed_provenance_and_cannot_reset_parent() { - use crate::session_worker::protocol::WorkerOutputFrame; - let f = Fixture::new(); - let parent_key = crate::chat::sessions::child::ChildSessionRegistry::canonical_session_key(&f.target) - .expect("test: canonical parent key"); - f.memory - .pool - .write() - .execute( - "UPDATE agent_scopes SET session_key=?1 WHERE scope_id=?2", - params![parent_key, f.recipient.scope_id.to_string()], - ) - .expect("test: bind parent canonical scope"); - let mut remote = f.source.clone(); - remote.instance = "prx-peer".into(); - let peer = MailboxAuthority::verified_peer( - W.into(), - remote, - f.target.clone(), - crate::messaging::MessageAuth { - issuer: "prx-issuer".into(), - subject: "prx-peer".into(), - method: "jwt".into(), - }, - ) - .expect( - "test: worker_data_keeps_sealed_provenance_and_cannot_reset_parent: MailboxAuthority::verified_peer succeeds", - ); - let mut root = f.message(1, 1); - root.to_pin = f - .store - .recipient_pin(&peer, &f.recipient, &parent_key) - .expect("test: worker_data_keeps_sealed_provenance_and_cannot_reset_parent: recipient_pin succeeds"); - let accepted = f - .store - .accept(&peer, root) - .expect("test: worker_data_keeps_sealed_provenance_and_cannot_reset_parent: accept succeeds"); - let inherited = crate::messaging::InheritedProvenance { - remote: accepted.remote.expect( - "test: worker_data_keeps_sealed_provenance_and_cannot_reset_parent: required fixture value is present", - ), - chain: accepted.chain, - }; - let mut actor = crate::session_worker::mailbox_parent::WorkerMailboxParent::new( - f.store.clone(), - f.source.clone(), - f.sender.clone(), - f.target.clone(), - f.recipient.clone(), - "run-source".into(), - Some(inherited.clone()), - ) - .expect("test: worker_data_keeps_sealed_provenance_and_cannot_reset_parent: WorkerMailboxParent::new succeeds"); - let forged_root = f.message(2, 0); - assert!( - forged_root.in_reply_to.is_none(), - "worker data keeps sealed provenance and cannot reset parent: IPC identity or delivery state changed" - ); - let receipt = actor - .receive(WorkerOutputFrame::Message { - envelope: Box::new(forged_root), - }) - .expect("test: worker_data_keeps_sealed_provenance_and_cannot_reset_parent: receive succeeds") - .expect("test: worker_data_keeps_sealed_provenance_and_cannot_reset_parent: receive returns a value"); - assert_eq!( - receipt.chain.ancestry, - vec![inherited.chain.trigger], - "worker data keeps sealed provenance and cannot reset parent: IPC identity or delivery state changed" - ); - assert_eq!( - receipt.remote, - Some(inherited.remote), - "worker data keeps sealed provenance and cannot reset parent: IPC identity or delivery state changed" - ); - assert_eq!( - f.scalar("SELECT sends FROM prx_remote_trees"), - 1, - "worker data keeps sealed provenance and cannot reset parent: IPC identity or delivery state changed" - ); -} - -#[test] -fn permanent_seq_gap_nacks_reachable_sender_outbox() { - let f = Fixture::new(); - let first = f.message(1, 0); - f.store - .publish(&f.authority, first.clone(), &f.sender, f.clock.now() + 300, None) - .expect("test: permanent_seq_gap_nacks_reachable_sender_outbox: publish succeeds"); - let second = f - .store - .publish(&f.authority, f.message(2, 0), &f.sender, f.clock.now() + 300, None) - .expect("test: permanent_seq_gap_nacks_reachable_sender_outbox: publish succeeds"); - let pending = f - .store - .pending_outbox(&f.sender, &f.source) - .expect("test: permanent_seq_gap_nacks_reachable_sender_outbox: pending_outbox succeeds"); - let message = pending - .iter() - .find(|item| item.message().id == second.message_id) - .expect("test: permanent_seq_gap_nacks_reachable_sender_outbox: find succeeds") - .message() - .clone(); - drop(pending); - f.store - .accept(&f.authority, message) - .expect("test: permanent_seq_gap_nacks_reachable_sender_outbox: accept succeeds"); - assert!( - f.store - .deliver(&f.recipient, &f.target) - .expect("test: permanent_seq_gap_nacks_reachable_sender_outbox: deliver succeeds") - .is_none(), - "permanent seq gap nacks reachable sender outbox: expected messaging contract changed" - ); - f.clock.advance(crate::messaging::mailbox::GAP_SECONDS); - let delivered = f.deliver(); - assert_eq!( - delivered.message().seq, - 2, - "permanent seq gap nacks reachable sender outbox: expected messaging contract changed" - ); - f.store - .adopt(&delivered) - .expect("test: permanent_seq_gap_nacks_reachable_sender_outbox: adopt succeeds"); - let failed = f - .store - .publish(&f.authority, first, &f.sender, f.clock.now() + 300, None) - .expect("test: permanent_seq_gap_nacks_reachable_sender_outbox: publish succeeds"); - assert_eq!( - failed.state, - crate::messaging::mailbox::MailboxSendState::Failed, - "permanent seq gap nacks reachable sender outbox: expected messaging contract changed" - ); - assert_eq!( - failed.error.as_deref(), - Some("seq_gap"), - "permanent seq gap nacks reachable sender outbox: expected messaging contract changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), - 1, - "Nack must not create an Ack receipt" - ); -} - -#[test] -fn worker_mime_projection_matches_durable_transcript() { - let f = Fixture::new(); - for (index, (mime, bytes)) in [ - ("text/plain", b"/approve remains ordinary input".to_vec()), - ("text/markdown", b"**ordinary input**".to_vec()), - ("text/plain", vec![0xff, 0]), - ("application/octet-stream", vec![0, 1, 0xff]), - ] - .into_iter() - .enumerate() - { - let seq = u64::try_from(index + 1) - .expect("test: worker_mime_projection_matches_durable_transcript: u64::try_from succeeds"); - let mut message = f.message(seq, seq); - message.body = MessageBody { - mime: mime.into(), - bytes, - }; - f.store - .accept(&f.authority, message) - .expect("test: worker_mime_projection_matches_durable_transcript: accept succeeds"); - let delivered = f.deliver(); - let worker_text = crate::session_worker::mailbox::user_text(delivered.message()) - .expect("test: worker_mime_projection_matches_durable_transcript: mailbox::user_text succeeds"); - f.store - .adopt(&delivered) - .expect("test: worker_mime_projection_matches_durable_transcript: adopt succeeds"); - let durable_text: String = f - .memory - .pool - .write() - .query_row( - "SELECT content FROM conversation_turns WHERE message_id=?1", - [delivered.message().id.to_string()], - |row| row.get(0), - ) - .expect("test: worker_mime_projection_matches_durable_transcript: query_row succeeds"); - assert_eq!( - worker_text, durable_text, - "worker mime projection matches durable transcript: atomic adoption or history projection changed" - ); - } -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn concurrent_sender_ports_share_one_durable_stream() { - let f = Fixture::new(); - let barrier = Arc::new(tokio::sync::Barrier::new(2)); - let mut tasks = Vec::new(); - for text in ["first", "second"] { - let port = f.sender_port(None); - let target = f.target.clone(); - let barrier = Arc::clone(&barrier); - tasks.push(tokio::spawn(async move { - barrier.wait().await; - port.send(target, text.into(), "text/plain".into()) - .await - .expect("test: concurrent_sender_ports_share_one_durable_stream: send succeeds") - })); - } - let mut published = Vec::new(); - for task in tasks { - published.push( - task.await - .expect("test: concurrent_sender_ports_share_one_durable_stream: awaited task completes"), - ); - } - published.sort_by_key(|sent| sent.seq); - assert_eq!( - published.iter().map(|sent| sent.seq).collect::>(), - vec![1, 2], - "concurrent sender ports share one durable stream: expected messaging contract changed" - ); - let wire = published - .first() - .expect("test: concurrent_sender_ports_share_one_durable_stream: first succeeds") - .stream_id; - assert!( - published.iter().all(|sent| sent.stream_id == wire), - "concurrent sender ports share one durable stream: expected messaging contract changed" - ); - let reopened = f - .sender_port(None) - .send(f.target.clone(), "reopened port".into(), "text/plain".into()) - .await - .expect("test: concurrent_sender_ports_share_one_durable_stream: send succeeds"); - assert_eq!( - reopened.stream_id, wire, - "concurrent sender ports share one durable stream: expected messaging contract changed" - ); - assert_eq!( - reopened.seq, 3, - "concurrent sender ports share one durable stream: expected messaging contract changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_seq"), - 1, - "concurrent sender ports share one durable stream: expected messaging contract changed" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_outbox"), - 3, - "concurrent sender ports share one durable stream: expected messaging contract changed" - ); -} - -#[tokio::test] -async fn pending_send_resolver_keeps_payload_in_scope_until_cancel_join() { - struct PausedResolver { - inner: LocalResolver, - entered: parking_lot::Mutex>>, - release: tokio::sync::Notify, - } - #[async_trait::async_trait] - impl crate::messaging::send::MailboxResolver for PausedResolver { - async fn resolve( - &self, - target: &SessionAddr, - ) -> crate::messaging::mailbox::MailboxResult { - let resolved = crate::messaging::send::MailboxResolver::resolve(&self.inner, target).await?; - let entered = self.entered.lock().take(); - if let Some(entered) = entered { - let _ = entered.send(()); - } - self.release.notified().await; - Ok(resolved) - } - } - use crate::messaging::send::MailboxSender as _; - let f = Fixture::new(); - let (entered, ready) = tokio::sync::oneshot::channel(); - let resolver = Arc::new(PausedResolver { - inner: LocalResolver { - store: f.store.clone(), - authority: f.authority.clone(), - scope: f.recipient.clone(), - }, - entered: parking_lot::Mutex::new(Some(entered)), - release: tokio::sync::Notify::new(), - }); - let port = crate::memory::sqlite::mailbox::SqliteMailboxSender::new( - f.store.clone(), - f.source.clone(), - f.sender.clone(), - resolver, - None, - ) - .expect("test: resolve: SqliteMailboxSender::new succeeds"); - let target = f.target.clone(); - let sending = tokio::spawn(async move { - port.send(target, "pending scoped payload".into(), "text/plain".into()) - .await - }); - tokio::time::timeout(std::time::Duration::from_secs(10), ready) - .await - .expect("test: resolve: time::timeout succeeds") - .expect("test: resolve: time::timeout returns a value"); - let kept_payload_scope = f.memory.mailbox_runtime.has_scope_leases(f.sender.scope_id); - sending.abort(); - assert!( - sending.await.unwrap_err().is_cancelled(), - "pending resolver task must join after cancellation" - ); - assert!( - kept_payload_scope, - "queued send lost its body lease while resolver was pending" - ); - assert!( - !f.memory.mailbox_runtime.has_scope_leases(f.sender.scope_id), - "cancel join retained the send payload" - ); - let erased = f - .store - .erase_scope(&f.sender, Duration::from_secs(5), &|| Ok(())) - .expect("test: resolve: erase_scope succeeds"); - assert_eq!( - erased.remaining, 0, - "joining the cancelled resolver must allow complete scope erasure" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_outbox"), - 0, - "cancelled resolver must not persist an outbox body" - ); -} - -fn mailbox_parent(f: &Fixture) -> crate::session_worker::mailbox_parent::WorkerMailboxParent { - crate::session_worker::mailbox_parent::WorkerMailboxParent::new( - f.store.clone(), - f.target.clone(), - f.recipient.clone(), - f.source.clone(), - f.sender.clone(), - "run-target".into(), - None, - ) - .expect("test: construct persistent parent") -} - -fn stale_parent_releases_delivery_before_erase() { - use crate::session_worker::protocol::{WorkerControlFrame, WorkerOutputFrame}; - let f = Fixture::new(); - let mut parent = mailbox_parent(&f); - let mut message = f.message(1, 1); - message.exec = Some(ExecRef { - run: Some("run-target".into()), - }); - f.store - .accept(&f.authority, message) - .expect("test: accept pinned parent input"); - let Some(WorkerControlFrame::Message { envelope }) = parent.next_delivery().expect("test: parent delivery") else { - panic!("test: parent must hold the delivered input"); - }; - let ack = WorkerOutputFrame::Ack { - message_id: envelope.id, - state: DeliveryState::Consumed, - }; - drop(envelope); - f.store - .set_execution(&f.recipient, &f.target, Some("run-next".into())) - .expect("test: change parent run"); - let result = parent.receive(ack.clone()); - let repeated = parent.receive(ack); - // Quiesce the parent's execution cache but retain any leaked deliveries. - // The old early ? must still fail at the erase deadline, not a cache lease. - let pending = parent.into_pending(); - let erased = f - .store - .erase_scope(&f.recipient, Duration::from_millis(20), &|| Ok(())) - .expect("test: terminal parent adoption must release its lease before erase deadline"); - assert_eq!(erased.remaining, 0, "terminal parent input must be fully erased"); - assert!( - result.expect("test: stale parent Ack is harmless").is_none(), - "stale Ack must return no receipt" - ); - assert_eq!(pending.len(), 0, "terminal adoption retained a pending delivery"); - assert!( - repeated.expect("test: repeat stale Ack").is_none(), - "repeated Ack must be harmless" - ); -} - -#[test] -fn parent_terminal_adopt_errors_release_pending_and_retryable_errors_retain_it() { - for error in [ - MailboxError::ReceiptExpired, - MailboxError::Unauthorized, - MailboxError::Fenced, - MailboxError::IdentityImmutable, - MailboxError::ScopeErasing, - MailboxError::SeqConflict, - MailboxError::Storage, - MailboxError::CorruptState, - ] { - let f = Fixture::new(); - let mut parent = mailbox_parent(&f); - let message = f.message(1, 1); - let id = message.id; - f.store - .accept(&f.authority, message) - .expect("test: accept matrix input"); - parent - .next_delivery() - .expect("test: hold matrix input") - .expect("test: pending matrix frame"); - assert_eq!( - parent.pending_count(), - 1, - "matrix must start with a real delivery lease" - ); - let sql = match error { - MailboxError::ReceiptExpired => Some("DELETE FROM prx_mailbox_receipts"), - MailboxError::Unauthorized => Some( - "UPDATE prx_mailbox_receipts SET ma_scope_id='00000000-0000-0000-0000-00000000000a',receipt_meta=json_set(receipt_meta,'$.canonical_session_key','canonical-source')", - ), - MailboxError::IdentityImmutable => Some("UPDATE prx_mailbox_messages SET body_bytes=x'6368616e676564'"), - MailboxError::ScopeErasing => Some( - "INSERT INTO agent_erase_fences VALUES ('00000000-0000-0000-0000-000000000014','00000000-0000-0000-0000-000000000063','draining',2)", - ), - _ => None, - }; - let result = if let Some(sql) = sql { - f.memory - .pool - .write() - .execute(sql, []) - .expect("test: set terminal store condition"); - parent.receive(crate::session_worker::protocol::WorkerOutputFrame::Ack { - message_id: id, - state: DeliveryState::Consumed, - }) - } else { - // Fenced is no longer emitted by adopt after L7. Keep its parent - // policy covered, along with injected retryable storage outcomes. - parent.finish_adopt(id, Err(error.clone())) - }; - assert_eq!( - result.expect_err("test: propagate typed adopt error"), - error, - "parent changed the terminal error" - ); - let retryable = matches!( - error, - MailboxError::SeqConflict | MailboxError::Storage | MailboxError::CorruptState - ); - assert_eq!( - parent.pending_count(), - usize::from(retryable), - "wrong lease policy for {error:?}" - ); - assert_eq!( - f.memory.mailbox_runtime.has_leases(f.recipient.scope_id), - retryable, - "wrong runtime lease policy for {error:?}" - ); - } -} - -#[test] -fn parent_acknowledge_error_after_adopt_releases_pending() { - let f = Fixture::new(); - let mut parent = mailbox_parent(&f); - let message = f.message(1, 1); - let id = message.id; - f.store - .accept(&f.authority, message) - .expect("test: accept without local outbox"); - parent - .next_delivery() - .expect("test: deliver without outbox") - .expect("test: pending delivery"); - let error = parent - .receive(crate::session_worker::protocol::WorkerOutputFrame::Ack { - message_id: id, - state: DeliveryState::Consumed, - }) - .expect_err("test: acknowledge requires a sender outbox"); - assert_eq!( - error, - MailboxError::InvalidMetadata, - "adoption must finish before missing-outbox Ack fails" - ); - assert_eq!( - parent.pending_count(), - 0, - "committed adoption retained a pending lease after Ack error" - ); - assert!( - !f.memory.mailbox_runtime.has_leases(f.recipient.scope_id), - "Ack error retained the consumed body" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM prx_mailbox_receipts WHERE state=2"), - 1, - "Ack failure must follow committed adoption" - ); -} - -#[test] -fn consumed_then_erased_adopt_replays_saved_result() { - let f = Fixture::new(); - f.receive(1, 1); - let held = f.deliver(); - let saved = f.store.adopt(&held).expect("test: consume receipt before erasure"); - // Erasure normally joins the holder. Preserve this delivery solely to exercise replay. - f.memory - .pool - .write() - .execute( - "UPDATE prx_mailbox_receipts SET receipt_meta=json_set(receipt_meta,'$.body_erased_at',1000) WHERE id=?1", - [saved.row_id], - ) - .expect("test: mark consumed receipt erased"); - f.memory - .pool - .write() - .execute("DELETE FROM prx_mailbox_messages WHERE id=?1", [saved.row_id]) - .expect("test: remove consumed receipt body"); - let replay = f.store.adopt(&held).expect("test: replay erased consumed receipt"); - assert_eq!(replay, saved, "erasure must preserve the saved adoption checkpoint"); -} - -#[test] -fn erased_nonconsumed_replays_report_scope_erasing_when_fenced() { - let f = Fixture::new(); - let message = f.message(1, 1); - f.store - .accept(&f.authority, message.clone()) - .expect("test: accept fenced replay input"); - let held = f.deliver(); - { - let writer = f.memory.pool.write(); - writer - .execute( - "UPDATE prx_mailbox_receipts SET receipt_meta=json_set(receipt_meta,'$.body_erased_at',1000)", - [], - ) - .expect("test: erase replay body metadata"); - writer - .execute( - "INSERT INTO agent_erase_fences VALUES (?1,?2,'draining',2)", - params![f.recipient.scope_id.to_string(), Uuid::new_v4().to_string()], - ) - .expect("test: fence erased receipt scope"); - } - assert_eq!( - f.store - .accept(&f.authority, message) - .expect_err("test: replay fenced accept"), - MailboxError::ScopeErasing, - "fenced replay must report erasure instead of stale run" - ); - assert_eq!( - f.store.adopt(&held).expect_err("test: replay fenced adopt"), - MailboxError::ScopeErasing, - "fenced adoption must report erasure instead of stale run" - ); -} - -fn stale_slot_case(adopt_race: bool) { - if adopt_race { - stale_parent_releases_delivery_before_erase(); - } - let f = Fixture::new(); - let mut first = f.message(1, 0); - first.exec = Some(ExecRef { - run: Some("run-target".into()), - }); - let published = f - .store - .publish(&f.authority, first, &f.sender, i64::MAX, None) - .expect("test: publish run-pinned slot"); - f.store - .publish(&f.authority, f.message(2, 0), &f.sender, i64::MAX, None) - .expect("test: publish later unpinned slot"); - let outgoing = f - .store - .pending_outbox(&f.sender, &f.source) - .expect("test: load accepted work"); - for slot in &outgoing { - let accepted = f - .store - .accept(&f.authority, slot.message().clone()) - .expect("test: accept pending slot"); - f.store - .acknowledge(&f.sender, &f.target, slot.message().id, accepted.state) - .expect("test: acknowledge accepted work before the run changes"); - } - let replay = outgoing.first().expect("test: first published slot").message().clone(); - drop(outgoing); - let held = if adopt_race { - let held = f.deliver(); - f.store - .acknowledge(&f.sender, &f.target, held.message().id, DeliveryState::Delivered) - .expect("test: acknowledge delivery before the adoption race"); - Some(held) - } else { - None - }; - f.store - .set_execution(&f.recipient, &f.target, Some("run-next".into())) - .expect("test: switch recipient execution"); - if let Some(held) = held { - assert_eq!( - f.store.adopt(&held).expect_err("test: stale adoption is refused"), - MailboxError::StaleRun, - "run change must terminalize only the held slot" - ); - assert_eq!( - f.store.adopt(&held).expect_err("test: replay stale adoption"), - MailboxError::StaleRun, - "an erased stale receipt must replay its terminal outcome" - ); - drop(held); - } - let next = f.deliver(); - assert_eq!( - f.store - .accept(&f.authority, replay) - .expect_err("test: replay stale accept"), - MailboxError::StaleRun, - "re-accept must report the stale slot instead of its old delivery state" - ); - assert_eq!(next.message().seq, 2, "later accepted work must survive a stale run"); - assert_eq!( - f.store.adopt(&next).expect("test: adopt surviving slot").state, - DeliveryState::Consumed, - "later unpinned slot must reach its transcript" - ); - let writer = f.memory.pool.write(); - let (state, meta): (i64, String) = writer - .query_row( - "SELECT state,envelope_meta FROM prx_mailbox_outbox WHERE id=?1", - [published.row_id], - |row| Ok((row.get(0)?, row.get(1)?)), - ) - .expect("test: inspect local sender nack"); - assert_eq!(state, 3, "stale slot must terminate its local sender outbox"); - let failed: i64 = writer - .query_row("SELECT count(*) FROM prx_mailbox_outbox WHERE state=3", [], |row| { - row.get(0) - }) - .expect("test: inspect the single targeted nack"); - assert_eq!(failed, 1, "a stale run must nack only its own slot"); - let meta: serde_json::Value = serde_json::from_str(&meta).expect("test: decode nack metadata"); - assert_eq!( - meta.get("last_error").and_then(serde_json::Value::as_str), - Some("stale_run"), - "sender must see the one-slot stale_run nack" - ); - let live: i64 = writer - .query_row("SELECT count(*) FROM prx_mailbox_seq WHERE state=0", [], |row| { - row.get(0) - }) - .expect("test: inspect stream lifetime"); - assert_eq!(live, 1, "stale work must not retire the shared stream"); - let erased: i64 = writer.query_row("SELECT count(*) FROM prx_mailbox_receipts WHERE seq=?1 AND json_extract(receipt_meta,'$.body_erased_at') IS NOT NULL", [1u64.to_be_bytes().as_slice()],|row|row.get(0)) - .expect("test: inspect terminal receipt"); - assert_eq!( - erased, 1, - "stale payload must be erased in the terminal-slot transaction" - ); -} - -#[test] -fn stale_run_slot_is_nacked_and_later_unpinned_slots_still_deliver() { - stale_slot_case(false); -} - -#[test] -fn stale_run_during_adopt_is_nacked_and_later_unpinned_slots_still_deliver() { - stale_slot_case(true); -} - -#[test] -fn worker_run_and_parent_binding_survive_more_than_max_rows_frames() { - use crate::session_worker::protocol::{WorkerControlFrame, WorkerOutputFrame}; - const FRAMES: i64 = crate::messaging::mailbox::MAX_ROWS + 1; - let f = Fixture::new(); - let mut parent = crate::session_worker::mailbox_parent::WorkerMailboxParent::new( - f.store.clone(), - f.target.clone(), - f.recipient.clone(), - f.source.clone(), - f.sender.clone(), - "run-target".into(), - None, - ) - .expect("test: one persistent parent binding"); - let (mut sender, mut inbox) = crate::session_worker::mailbox::worker_mailbox(f.target.clone(), "run-target".into()) - .expect("test: one persistent worker inbox"); - f.store - .publish(&f.authority, f.message(1, 0), &f.sender, i64::MAX, None) - .expect("test: publish first long-lived worker frame"); - let deadline = std::time::Instant::now() + Duration::from_secs(240); - for index in 1..=FRAMES { - assert!( - std::time::Instant::now() < deadline, - "bounded long-lived worker regression exceeded deadline" - ); - let pending = f - .store - .pending_outbox(&f.sender, &f.source) - .expect("test: pending single slot"); - let message = pending.first().expect("test: one pending envelope").message().clone(); - f.store.accept(&f.authority, message).expect("test: accept next frame"); - drop(pending); - let WorkerControlFrame::Message { envelope } = parent - .next_delivery() - .expect("test: next parent delivery") - .expect("test: queued frame") - else { - panic!("test: parent produced non-Data control"); - }; - let delivered = sender - .enqueue(*envelope) - .expect("test: bounded inbox must not grow by run lifetime"); - parent.receive(delivered).expect("test: parent accepts delivered ack"); - let message = inbox.try_next().expect("test: one in-flight worker input"); - let consumed = inbox - .consumed(&message) - .expect("test: consume prunes the in-flight dedupe entry"); - parent - .receive(consumed.clone()) - .expect("test: parent must not fail after committed adoption"); - parent - .receive(consumed) - .expect("test: consumed acknowledgement replay is harmless"); - parent - .receive(WorkerOutputFrame::Ack { - message_id: message.id, - state: DeliveryState::Consumed, - }) - .expect("test: late acknowledgement remains idempotent"); - f.clock.advance(crate::messaging::mailbox::REPLAY_SECONDS + 1); - // Keep the stream live while expiring old ledger rows; only the - // worker's in-flight window, rather than durable storage quota, is tested. - if index < FRAMES { - let next = u64::try_from(index + 1).expect("test: bounded frame index"); - f.store - .publish(&f.authority, f.message(next, 0), &f.sender, i64::MAX, None) - .expect("test: publish next frame before retention GC"); - } - f.store - .gc_scope(&f.sender) - .expect("test: expire sender's durable replay records"); - f.store - .gc_scope(&f.recipient) - .expect("test: expire consumed receiver records"); - } -} - -#[tokio::test] -async fn erase_scope_deadline_preserves_fence_until_child_lease_drops() { - use crate::chat::sessions::child::{ChildSession, ChildSessionRegistry}; - let f = Fixture::new(); - let registry = ChildSessionRegistry::new(Arc::new(f.memory.clone())).with_workspace(W.into()); - registry - .insert(&ChildSession::new(f.target.clone(), None, None)) - .await - .expect("test: persist child session"); - let child = registry - .reconstruct(&f.target) - .await - .expect("test: hold reconstructed history lease"); - let scope = child.mailbox_scope().expect("test: reconstructed scope").clone(); - let store = f.store.clone(); - let pending_scope = scope.clone(); - let pending = - tokio::task::spawn_blocking(move || store.erase_scope(&pending_scope, Duration::from_millis(20), &|| Ok(()))); - let result = tokio::time::timeout(Duration::from_secs(5), pending) - .await - .expect("test: erase wait has a hard deadline") - .expect("test: erase task joins"); - assert_eq!( - result.expect_err("test: retained child history cannot be erased"), - MailboxError::Fenced, - "incomplete quiescence must return history_pending" - ); - assert_eq!( - f.scalar("SELECT count(*) FROM agent_erase_fences WHERE state='draining'"), - 1, - "timeout must keep the durable erasure fence in place" - ); - drop(child); - let erased = f - .store - .erase_scope(&scope, Duration::from_secs(5), &|| Ok(())) - .expect("test: retry after holder joins"); - assert_eq!( - erased.remaining, 0, - "released history lease must allow complete erasure" - ); -} - -#[test] -fn mailbox_wire_errors_and_unacknowledged_result_preserve_contract() { - use crate::messaging::mailbox::{MailboxPublished, MailboxSendState}; - for (error, code) in [ - (MailboxError::PinRequired, "recipient_pin_required"), - (MailboxError::InvalidPin, "pin_invalid"), - (MailboxError::PinExpired, "pin_invalid"), - (MailboxError::ScopeErasing, "scope_erasing"), - (MailboxError::Fenced, "history_pending"), - ] { - assert_eq!( - error.to_string(), - code, - "wire error must distinguish authority, admission fence and erase retry" - ); - } - for state in [MailboxSendState::Pending, MailboxSendState::Failed] { - let result = crate::messaging::send::send_result(Ok(MailboxPublished { - row_id: 1, - message_id: Uuid::from_u128(1), - stream_id: Uuid::from_u128(STREAM), - seq: 1, - state, - ack_state: None, - error: None, - })); - assert_eq!( - result.get("state"), - Some(&serde_json::Value::Null), - "without an Ack the result must not claim accepted delivery" - ); - } -} +include!("mailbox/section_1.rs"); +include!("mailbox/section_2.rs"); +include!("mailbox/section_3.rs"); diff --git a/src/memory/sqlite/tests/mailbox/section_1.rs b/src/memory/sqlite/tests/mailbox/section_1.rs new file mode 100644 index 000000000..9156af0a7 --- /dev/null +++ b/src/memory/sqlite/tests/mailbox/section_1.rs @@ -0,0 +1,1733 @@ +use super::*; +use crate::memory::sqlite::mailbox::{MailboxDelivery, SqliteMailbox}; +use crate::messaging::mailbox::{MailboxAuthority, MailboxClock, MailboxError, MailboxScope}; +use crate::messaging::{DeliveryState, ExecRef, IdempotencyKey, MessageBody, MessageKind, PrxMessage, SessionAddr}; +use std::sync::atomic::{AtomicI64, Ordering as AtomicOrdering}; +use uuid::Uuid; + +const W: &str = "prx_workspace"; +const O: &str = "prx_owner"; +const INC: u128 = 1; +const SCOPE_SOURCE: u128 = 10; +const SCOPE_TARGET: u128 = 20; +const STREAM: u128 = 500; +struct Clock(AtomicI64); +impl Clock { + fn advance(&self, seconds: i64) { + self.0.fetch_add(seconds, AtomicOrdering::SeqCst); + } +} +impl MailboxClock for Clock { + fn now(&self) -> i64 { + self.0.load(AtomicOrdering::SeqCst) + } +} + +struct Fixture { + memory: SqliteMemory, + store: SqliteMailbox, + clock: Arc, + source: SessionAddr, + target: SessionAddr, + sender: MailboxScope, + recipient: MailboxScope, + authority: MailboxAuthority, + // Close every owned connection before removing its database directory. + _dir: TempDir, +} +impl Fixture { + fn new() -> Self { + let dir = TempDir::new().expect("test: new: fixture setup succeeds"); + let memory = SqliteMemory::new(dir.path()).expect("test: new: SqliteMemory::new succeeds"); + { + let writer = memory.pool.write(); + writer + .execute( + "INSERT INTO agent_incarnations VALUES (?1,?2,'m',?3,'active',?4)", + params![W, O, Uuid::from_u128(INC).to_string(), "0".repeat(64)], + ) + .expect("test: new: execute succeeds"); + for (id, canonical) in [(SCOPE_SOURCE, "canonical-source"), (SCOPE_TARGET, "canonical-target")] { + writer + .execute( + "INSERT INTO agent_scopes VALUES (?1,?2,?3,?4,'m',?5,1)", + params![ + Uuid::from_u128(id).to_string(), + W, + O, + canonical, + Uuid::from_u128(INC).to_string() + ], + ) + .expect("test: new: execute succeeds"); + } + } + let clock = Arc::new(Clock(AtomicI64::new(1000))); + let store = SqliteMailbox::new( + memory.clone(), + "prx-node".into(), + [7; 32], + clock.clone(), + ) + .expect("test: new: SqliteMailbox::new succeeds"); + let source = SessionAddr::new("prx-node", O, "source", None); + let target = SessionAddr::new("prx-node", O, "target", None); + let sender = MailboxScope { + workspace_id: W.into(), + owner_id: O.into(), + scope_id: Uuid::from_u128(SCOPE_SOURCE), + incarnation: Uuid::from_u128(INC), + generation: 1, + }; + let recipient = MailboxScope { + scope_id: Uuid::from_u128(SCOPE_TARGET), + ..sender.clone() + }; + let authority = MailboxAuthority::local(W.into(), source.clone(), target.clone()) + .expect("test: new: MailboxAuthority::local succeeds"); + store + .set_execution(&recipient, &target, Some("run-target".into())) + .expect("test: new: set_execution succeeds"); + Self { + _dir: dir, + memory, + store, + clock, + source, + target, + sender, + recipient, + authority, + } + } + fn message(&self, n: u64, seq: u64) -> PrxMessage { + let canonical: String = self + .memory + .pool + .write() + .query_row( + "SELECT session_key FROM agent_scopes WHERE scope_id=?1", + [self.recipient.scope_id.to_string()], + |row| row.get(0), + ) + .expect("test: read recipient canonical key"); + let pin = self + .store + .recipient_pin(&self.authority, &self.recipient, &canonical) + .expect("test: message: recipient_pin succeeds"); + PrxMessage { + id: Uuid::from_u128(1000 + u128::from(n)), + idempotency: IdempotencyKey::parse(&format!("mailbox-key-{n:08}")) + .expect("test: message: fixture setup succeeds"), + stream_id: Some(Uuid::from_u128(STREAM)), + seq, + ts: self.clock.now(), + from: self.source.clone(), + to: self.target.clone(), + to_pin: pin, + in_reply_to: None, + hop_count: 0, + ancestry: Vec::new(), + kind: MessageKind::Data, + body: MessageBody { + mime: "text/plain".into(), + bytes: format!("request-{n}").into_bytes(), + }, + origin: None, + auth: None, + exec: None, + canonical_hash: None, + } + } + fn receive(&self, n: u64, seq: u64) -> crate::messaging::mailbox::MailboxReceipt { + self.store + .accept(&self.authority, self.message(n, seq)) + .expect("test: receive: accept succeeds") + } + fn deliver(&self) -> MailboxDelivery { + self.store + .deliver(&self.recipient, &self.target) + .expect("test: deliver: deliver succeeds") + .expect("test: deliver: deliver returns a value") + } + fn scalar(&self, sql: &str) -> i64 { + self.memory + .pool + .write() + .query_row(sql, [], |r| r.get(0)) + .expect("test: scalar: query_row succeeds") + } +} + +#[test] +fn in_process_send_is_durable_and_acked() { + let f = Fixture::new(); + let provisional = f.message(1, 0); + let published = f + .store + .publish(&f.authority, provisional, &f.sender, f.clock.now() + 300, None) + .expect("test: in_process_send_is_durable_and_acked: publish succeeds"); + assert_eq!( + published.seq, 1, + "in process send is durable and acked: IPC identity or delivery state changed" + ); + let outgoing = f + .store + .pending_outbox(&f.sender, &f.source) + .expect("test: in_process_send_is_durable_and_acked: pending_outbox succeeds"); + let sent = outgoing + .first() + .expect("test: in_process_send_is_durable_and_acked: first succeeds") + .message() + .clone(); + let accepted = f + .store + .accept(&f.authority, sent.clone()) + .expect("test: in_process_send_is_durable_and_acked: accept succeeds"); + f.store + .acknowledge(&f.sender, &f.target, sent.id, accepted.state) + .expect("test: in_process_send_is_durable_and_acked: acknowledge succeeds"); + let retry = f + .store + .publish(&f.authority, sent, &f.sender, f.clock.now() + 300, None) + .expect("test: in_process_send_is_durable_and_acked: publish succeeds"); + assert_eq!( + retry.ack_state, + Some(DeliveryState::Accepted), + "in process send is durable and acked: IPC identity or delivery state changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), + 1, + "in process send is durable and acked: IPC identity or delivery state changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_messages"), + 1, + "in process send is durable and acked: IPC identity or delivery state changed" + ); +} + +#[test] +fn adopt_is_atomic_transcript_and_consume() { + let f = Fixture::new(); + f.receive(1, 1); + let delivery = f.deliver(); + let first = f + .store + .adopt(&delivery) + .expect("test: adopt_is_atomic_transcript_and_consume: adopt succeeds"); + let again = f + .store + .adopt(&delivery) + .expect("test: adopt_is_atomic_transcript_and_consume: adopt succeeds"); + assert_eq!( + first, again, + "adopt is atomic transcript and consume: atomic adoption or history projection changed" + ); + assert_eq!( + first.state, + DeliveryState::Consumed, + "adopt is atomic transcript and consume: atomic adoption or history projection changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM conversation_turns"), + 1, + "adopt is atomic transcript and consume: atomic adoption or history projection changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM message_events WHERE source='prx_mailbox'"), + 1, + "adopt is atomic transcript and consume: atomic adoption or history projection changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_receipts WHERE state=2 AND adopted_turn_id IS NOT NULL"), + 1, + "adopt is atomic transcript and consume: atomic adoption or history projection changed" + ); +} + +#[test] +fn same_id_different_key_different_body_is_id_reuse() { + let f = Fixture::new(); + let original = f.message(1, 1); + f.store + .accept(&f.authority, original.clone()) + .expect("test: same_id_different_key_different_body_is_id_reuse: accept succeeds"); + let mut other = original; + other.idempotency = IdempotencyKey::parse("another-mailbox-key") + .expect("test: same_id_different_key_different_body_is_id_reuse: IdempotencyKey::parse succeeds"); + other.seq = 2; + other.body.bytes = b"changed".to_vec(); + assert_eq!( + f.store.accept(&f.authority, other).unwrap_err(), + MailboxError::IdReuse, + "same id different key different body is id reuse: payload retention and erasure boundary changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_messages"), + 1, + "same id different key different body is id reuse: payload retention and erasure boundary changed" + ); +} + +#[test] +fn same_key_changed_exec_is_idempotency_conflict() { + let f = Fixture::new(); + let original = f.message(1, 1); + f.store + .accept(&f.authority, original.clone()) + .expect("test: same_key_changed_exec_is_idempotency_conflict: accept succeeds"); + let mut retry = original; + retry.exec = Some(ExecRef { + run: Some("different-run".into()), + }); + assert_eq!( + f.store.accept(&f.authority, retry).unwrap_err(), + MailboxError::IdempotencyConflict, + "same key changed exec is idempotency conflict: replay identity or receipt stability changed" + ); +} + +#[test] +fn reordered_duplicate_seq_holds_fifo() { + let f = Fixture::new(); + let second = f.message(2, 2); + let accepted = f + .store + .accept(&f.authority, second.clone()) + .expect("test: reordered_duplicate_seq_holds_fifo: accept succeeds"); + assert!( + f.store + .deliver(&f.recipient, &f.target) + .expect("test: reordered_duplicate_seq_holds_fifo: deliver succeeds") + .is_none(), + "reordered duplicate seq holds fifo: expected messaging contract changed" + ); + assert_eq!( + f.store + .accept(&f.authority, second) + .expect("test: reordered_duplicate_seq_holds_fifo: accept succeeds"), + accepted, + "reordered duplicate seq holds fifo: expected messaging contract changed" + ); + f.receive(1, 1); + let first = f.deliver(); + assert_eq!( + first.message().seq, + 1, + "reordered duplicate seq holds fifo: expected messaging contract changed" + ); + f.store + .adopt(&first) + .expect("test: reordered_duplicate_seq_holds_fifo: adopt succeeds"); + drop(first); + let second = f.deliver(); + assert_eq!( + second.message().seq, + 2, + "reordered duplicate seq holds fifo: expected messaging contract changed" + ); + f.store + .adopt(&second) + .expect("test: reordered_duplicate_seq_holds_fifo: adopt succeeds"); +} + +#[test] +fn permanent_seq_gap_retires_and_unblocks() { + let f = Fixture::new(); + f.receive(2, 2); + assert!( + f.store + .deliver(&f.recipient, &f.target) + .expect("test: permanent_seq_gap_retires_and_unblocks: deliver succeeds") + .is_none(), + "permanent seq gap retires and unblocks: expected messaging contract changed" + ); + f.clock.advance(30); + let delivery = f.deliver(); + assert_eq!( + delivery.message().seq, + 2, + "permanent seq gap retires and unblocks: expected messaging contract changed" + ); + f.store + .adopt(&delivery) + .expect("test: permanent_seq_gap_retires_and_unblocks: adopt succeeds"); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_receipts WHERE state=2"), + 1, + "permanent seq gap retires and unblocks: expected messaging contract changed" + ); +} + +#[test] +fn late_seq_at_or_below_consume_cursor_is_rejected_after_hole_gc() { + let f = Fixture::new(); + f.receive(2, 2); + f.clock.advance(30); + let delivery = f.deliver(); + f.store + .adopt(&delivery) + .expect("test: late_seq_at_or_below_consume_cursor_is_rejected_after_hole_gc: adopt succeeds"); + drop(delivery); + f.clock.advance(crate::messaging::mailbox::REPLAY_SECONDS + 1); + // Fresh pending work keeps the stream initialized while eligible old + // bodies/receipts/holes are collected. No forbidden same-UUID reset. + f.receive(3, 3); + f.store + .gc_scope(&f.recipient) + .expect("test: late_seq_at_or_below_consume_cursor_is_rejected_after_hole_gc: gc_scope succeeds"); + assert_eq!( + f.scalar("SELECT json_array_length(progress,'$.seq_skipped') FROM prx_mailbox_seq"), + 0, + "late seq at or below consume cursor is rejected after hole gc: atomic adoption or history projection changed" + ); + assert_eq!( + f.store.accept(&f.authority, f.message(4, 1)).unwrap_err(), + MailboxError::SeqAlreadyConsumed, + "late seq at or below consume cursor is rejected after hole gc: atomic adoption or history projection changed" + ); +} + +#[test] +fn outbox_parent_id_is_not_reused_after_outbox_gc() { + let f = Fixture::new(); + let published = f + .store + .publish(&f.authority, f.message(1, 0), &f.sender, f.clock.now() + 300, None) + .expect("test: outbox_parent_id_is_not_reused_after_outbox_gc: publish succeeds"); + f.store + .acknowledge(&f.sender, &f.target, published.message_id, DeliveryState::Accepted) + .expect("test: outbox_parent_id_is_not_reused_after_outbox_gc: acknowledge succeeds"); + f.clock.advance(crate::messaging::mailbox::REPLAY_SECONDS + 1); + let gc = f + .store + .gc_scope(&f.sender) + .expect("test: outbox_parent_id_is_not_reused_after_outbox_gc: gc_scope succeeds"); + assert_eq!( + gc.outboxes, 1, + "outbox parent id is not reused after outbox gc: expected messaging contract changed" + ); + assert_eq!( + gc.parents, 0, + "outbox parent id is not reused after outbox gc: expected messaging contract changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_parents"), + 1, + "outbox parent id is not reused after outbox gc: expected messaging contract changed" + ); + let mut next = f.message(2, 0); + next.stream_id = Some(Uuid::from_u128(STREAM + 1)); + let published2 = f + .store + .publish(&f.authority, next, &f.sender, f.clock.now() + 300, None) + .expect("test: outbox_parent_id_is_not_reused_after_outbox_gc: publish succeeds"); + assert!( + published2.row_id > published.row_id, + "outbox parent id is not reused after outbox gc: expected messaging contract changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_parents"), + 2, + "outbox parent id is not reused after outbox gc: expected messaging contract changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_outbox"), + 1, + "outbox parent id is not reused after outbox gc: expected messaging contract changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_messages WHERE id NOT IN(SELECT id FROM prx_mailbox_receipts)"), + 0, + "outbox parent id is not reused after outbox gc: expected messaging contract changed" + ); +} + +#[test] +fn crash_before_adopt_redelivers_once() { + let f = Fixture::new(); + f.receive(1, 1); + let delivery = f.deliver(); + let id = delivery.message().id; + drop(delivery); + f.store + .recover_delivery(&f.recipient, &f.target) + .expect("test: crash_before_adopt_redelivers_once: recover_delivery succeeds"); + let retry = f.deliver(); + assert_eq!( + retry.message().id, + id, + "crash before adopt redelivers once: atomic adoption or history projection changed" + ); + f.store + .adopt(&retry) + .expect("test: crash_before_adopt_redelivers_once: adopt succeeds"); + drop(retry); + f.store + .recover_delivery(&f.recipient, &f.target) + .expect("test: crash_before_adopt_redelivers_once: recover_delivery succeeds"); + assert!( + f.store + .deliver(&f.recipient, &f.target) + .expect("test: crash_before_adopt_redelivers_once: deliver succeeds") + .is_none(), + "crash before adopt redelivers once: atomic adoption or history projection changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM conversation_turns"), + 1, + "crash before adopt redelivers once: atomic adoption or history projection changed" + ); +} + +#[test] +fn crash_during_adopt_rolls_back() { + let f = Fixture::new(); + f.receive(1, 1); + let delivery = f.deliver(); + f.memory.pool.write().execute_batch("CREATE TEMP TRIGGER test_refuse_consume BEFORE UPDATE OF state ON prx_mailbox_receipts WHEN NEW.state=2 BEGIN SELECT RAISE(ABORT,'fixture consume refusal'); END;").expect("test: crash_during_adopt_rolls_back: fixture setup succeeds"); + assert_eq!( + f.store.adopt(&delivery).unwrap_err(), + MailboxError::Storage, + "crash during adopt rolls back: atomic adoption or history projection changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM conversation_turns"), + 0, + "crash during adopt rolls back: atomic adoption or history projection changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM message_events WHERE source='prx_mailbox'"), + 0, + "crash during adopt rolls back: atomic adoption or history projection changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_receipts WHERE state=1 AND adopted_turn_id IS NULL"), + 1, + "crash during adopt rolls back: atomic adoption or history projection changed" + ); + f.memory + .pool + .write() + .execute_batch("DROP TRIGGER test_refuse_consume") + .expect("test: crash_during_adopt_rolls_back: execute_batch succeeds"); + f.store + .adopt(&delivery) + .expect("test: crash_during_adopt_rolls_back: adopt succeeds"); + assert_eq!( + f.scalar("SELECT count(*) FROM conversation_turns"), + 1, + "crash during adopt rolls back: atomic adoption or history projection changed" + ); +} + +#[test] +fn mailbox_shared_ids_survive_rowid_reuse_after_gc() { + let f = Fixture::new(); + f.memory.pool.write().execute_batch("CREATE TEMP TRIGGER test_refuse_body BEFORE INSERT ON prx_mailbox_messages BEGIN SELECT RAISE(ABORT,'fixture body refusal'); END;").expect("test: mailbox_shared_ids_survive_rowid_reuse_after_gc: execute_batch succeeds"); + assert_eq!( + f.store.accept(&f.authority, f.message(1, 1)).unwrap_err(), + MailboxError::Storage, + "mailbox shared ids survive rowid reuse after gc: expected messaging contract changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), + 0, + "mailbox shared ids survive rowid reuse after gc: expected messaging contract changed" + ); + f.memory + .pool + .write() + .execute_batch("DROP TRIGGER test_refuse_body") + .expect("test: mailbox_shared_ids_survive_rowid_reuse_after_gc: execute_batch succeeds"); + let accepted = f.receive(1, 1); + let delivery = f.deliver(); + f.store + .adopt(&delivery) + .expect("test: mailbox_shared_ids_survive_rowid_reuse_after_gc: adopt succeeds"); + drop(delivery); + f.clock.advance(crate::messaging::mailbox::REPLAY_SECONDS + 1); + f.receive(2, 2); + // Observe the required lifetime order, rather than a zero-row assertion. + f.memory.pool.write().execute_batch("CREATE TEMP TRIGGER test_require_body_first BEFORE DELETE ON prx_mailbox_receipts WHEN EXISTS(SELECT 1 FROM prx_mailbox_messages WHERE id=OLD.id) BEGIN SELECT RAISE(ABORT,'body still references receipt'); END;").expect("test: mailbox_shared_ids_survive_rowid_reuse_after_gc: fixture setup succeeds"); + let gc = f + .store + .gc_scope(&f.recipient) + .expect("test: mailbox_shared_ids_survive_rowid_reuse_after_gc: gc_scope succeeds"); + assert_eq!( + gc.bodies, 1, + "mailbox shared ids survive rowid reuse after gc: expected messaging contract changed" + ); + assert_eq!( + gc.receipts, 1, + "mailbox shared ids survive rowid reuse after gc: expected messaging contract changed" + ); + assert_eq!( + f.scalar(&format!( + "SELECT count(*) FROM prx_mailbox_messages WHERE id={}", + accepted.row_id + )), + 0, + "mailbox shared ids survive rowid reuse after gc: expected messaging contract changed" + ); + assert_eq!( + f.scalar(&format!( + "SELECT count(*) FROM prx_mailbox_receipts WHERE id={}", + accepted.row_id + )), + 0, + "mailbox shared ids survive rowid reuse after gc: expected messaging contract changed" + ); +} + +#[test] +fn missing_recipient_pin_is_rejected_not_filled() { + let f = Fixture::new(); + let mut message = f.message(1, 1); + message.to_pin.token.clear(); + assert_eq!( + f.store.accept(&f.authority, message.clone()).unwrap_err(), + MailboxError::PinRequired, + "missing recipient pin is rejected not filled: recipient authority or scope isolation changed" + ); + assert_eq!( + f.store + .publish(&f.authority, message, &f.sender, i64::MAX, None) + .expect_err("test: publish requires a recipient pin"), + MailboxError::PinRequired, + "missing authority must use the same required-pin code before publishing or accepting" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_outbox"), + 0, + "publication without a pin must not retain an outgoing payload" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), + 0, + "missing recipient pin is rejected not filled: recipient authority or scope isolation changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_seq"), + 0, + "missing recipient pin is rejected not filled: recipient authority or scope isolation changed" + ); +} + +#[test] +fn unknown_parent_is_nacked() { + let f = Fixture::new(); + let mut message = f.message(1, 1); + message.in_reply_to = Some(Uuid::from_u128(999)); + assert_eq!( + f.store.accept(&f.authority, message).unwrap_err(), + MailboxError::UnknownParent, + "unknown parent is nacked: expected messaging contract changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_messages"), + 0, + "unknown parent is nacked: expected messaging contract changed" + ); +} + +#[test] +fn retry_with_altered_in_reply_to_is_idempotency_conflict() { + let f = Fixture::new(); + let original = f.message(1, 1); + f.store + .accept(&f.authority, original.clone()) + .expect("test: retry_with_altered_in_reply_to_is_idempotency_conflict: accept succeeds"); + let mut changed = original; + changed.in_reply_to = Some(Uuid::from_u128(999)); + assert_eq!( + f.store.accept(&f.authority, changed).unwrap_err(), + MailboxError::IdempotencyConflict, + "retry with altered in reply to is idempotency conflict: replay identity or receipt stability changed" + ); +} + +#[test] +fn ack_does_not_emit_ack() { + let f = Fixture::new(); + let published = f + .store + .publish(&f.authority, f.message(1, 0), &f.sender, f.clock.now() + 300, None) + .expect("test: ack_does_not_emit_ack: publish succeeds"); + f.store + .acknowledge(&f.sender, &f.target, published.message_id, DeliveryState::Accepted) + .expect("test: ack_does_not_emit_ack: acknowledge succeeds"); + f.store + .acknowledge(&f.sender, &f.target, published.message_id, DeliveryState::Consumed) + .expect("test: ack_does_not_emit_ack: acknowledge succeeds"); + f.store + .acknowledge(&f.sender, &f.target, published.message_id, DeliveryState::Accepted) + .expect("test: ack_does_not_emit_ack: acknowledge succeeds"); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_messages"), + 0, + "ack does not emit ack: expected messaging contract changed" + ); + assert!( + f.store + .pending_outbox(&f.sender, &f.source) + .expect("test: ack_does_not_emit_ack: pending_outbox succeeds") + .is_empty(), + "ack does not emit ack: expected messaging contract changed" + ); + let retry = f + .store + .publish(&f.authority, f.message(1, 0), &f.sender, f.clock.now() + 300, None) + .expect("test: ack_does_not_emit_ack: publish succeeds"); + assert_eq!( + retry.ack_state, + Some(DeliveryState::Consumed), + "ack does not emit ack: expected messaging contract changed" + ); +} + +#[test] +fn offline_session_receives_after_attach() { + let f = Fixture::new(); + f.store + .close_execution(&f.recipient, &f.target, "run-target") + .expect("test: offline_session_receives_after_attach: close_execution succeeds"); + f.receive(1, 1); + assert!( + f.store + .deliver(&f.recipient, &f.target) + .expect("test: offline_session_receives_after_attach: deliver succeeds") + .is_none(), + "offline session receives after attach: expected messaging contract changed" + ); + f.store + .set_execution(&f.recipient, &f.target, Some("reopened-target".into())) + .expect("test: offline_session_receives_after_attach: set_execution succeeds"); + let delivered = f.deliver(); + assert_eq!( + delivered.message().body.bytes, + b"request-1", + "offline session receives after attach: expected messaging contract changed" + ); +} + +#[test] +fn mailbox_erase_drops_bodies_keeps_receipts() { + let f = Fixture::new(); + f.receive(1, 1); + let queued = f.message(2, 2); + let report = f + .store + .erase_scope(&f.recipient, Duration::from_secs(5), &|| Ok(())) + .expect("test: mailbox_erase_drops_bodies_keeps_receipts: erase_scope succeeds"); + assert_eq!( + report.remaining, 0, + "mailbox erase drops bodies keeps receipts: payload retention and erasure boundary changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_messages"), + 0, + "mailbox erase drops bodies keeps receipts: payload retention and erasure boundary changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), + 1, + "mailbox erase drops bodies keeps receipts: payload retention and erasure boundary changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_seq WHERE state=1"), + 1, + "mailbox erase drops bodies keeps receipts: payload retention and erasure boundary changed" + ); + assert_eq!( + f.store.accept(&f.authority, queued).unwrap_err(), + MailboxError::ScopeErasing, + "mailbox erase drops bodies keeps receipts: payload retention and erasure boundary changed" + ); +} + +#[test] +fn outbox_erase_drops_bodies_keeps_status() { + let f = Fixture::new(); + f.store + .publish(&f.authority, f.message(1, 0), &f.sender, f.clock.now() + 300, None) + .expect("test: outbox_erase_drops_bodies_keeps_status: publish succeeds"); + f.store + .erase_scope(&f.sender, Duration::from_secs(5), &|| Ok(())) + .expect("test: outbox_erase_drops_bodies_keeps_status: erase_scope succeeds"); + assert_eq!(f.scalar("SELECT count(*) FROM prx_mailbox_outbox WHERE state=3 AND body_bytes IS NULL AND json_extract(envelope_meta,'$.to_pin_token') IS NULL AND json_extract(envelope_meta,'$.body_mime') IS NULL"),1, "outbox erase drops bodies keeps status: payload retention and erasure boundary changed"); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_parents"), + 1, + "outbox erase drops bodies keeps status: payload retention and erasure boundary changed" + ); + let replay = f + .store + .publish(&f.authority, f.message(1, 0), &f.sender, f.clock.now() + 300, None) + .expect("test: outbox_erase_drops_bodies_keeps_status: publish succeeds"); + assert_eq!( + replay.state, + crate::messaging::mailbox::MailboxSendState::Failed, + "outbox erase drops bodies keeps status: payload retention and erasure boundary changed" + ); +} + +#[test] +fn held_delivery_across_erase_recreate_does_not_resurrect_body() { + let f = Fixture::new(); + f.receive(1, 1); + let delivery = f.deliver(); + let (fenced_tx, fenced_rx) = std::sync::mpsc::sync_channel(1); + let (done_tx, done_rx) = std::sync::mpsc::sync_channel(1); + let store = f.store.clone(); + let scope = f.recipient.clone(); + let erase = std::thread::spawn(move || { + let result = store.erase_scope(&scope, Duration::from_secs(5), &|| { + fenced_tx + .send(()) + .expect("test: held_delivery_across_erase_recreate_does_not_resurrect_body: send succeeds"); + Ok(()) + }); + done_tx + .send(result) + .expect("test: held_delivery_across_erase_recreate_does_not_resurrect_body: send succeeds"); + }); + fenced_rx + .recv_timeout(Duration::from_secs(5)) + .expect("test: held_delivery_across_erase_recreate_does_not_resurrect_body: recv_timeout succeeds"); + assert_eq!( + f.store.adopt(&delivery).unwrap_err(), + MailboxError::ScopeErasing, + "held delivery across erase recreate does not resurrect body: payload retention and erasure boundary changed" + ); + assert!( + done_rx.try_recv().is_err(), + "erase cannot finish while queue/IPC owns the payload" + ); + drop(delivery); + assert_eq!( + done_rx + .recv_timeout(Duration::from_secs(5)) + .expect("test: held_delivery_across_erase_recreate_does_not_resurrect_body: recv_timeout succeeds") + .expect("test: held_delivery_across_erase_recreate_does_not_resurrect_body: recv_timeout returns a value") + .remaining, + 0, + "held delivery across erase recreate does not resurrect body: payload retention and erasure boundary changed" + ); + erase + .join() + .expect("test: held_delivery_across_erase_recreate_does_not_resurrect_body: join succeeds"); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_messages"), + 0, + "held delivery across erase recreate does not resurrect body: payload retention and erasure boundary changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM conversation_turns"), + 0, + "held delivery across erase recreate does not resurrect body: payload retention and erasure boundary changed" + ); +} + +fn new_target_generation(f: &Fixture) -> MailboxScope { + let writer = f.memory.pool.write(); + writer + .execute( + "UPDATE agent_incarnations SET state='retired' WHERE workspace_id=?1 AND owner_id=?2 AND agent_key='m'", + params![W, O], + ) + .expect("test: new_target_generation: fixture setup succeeds"); + writer + .execute( + "INSERT INTO agent_incarnations VALUES (?1,?2,'m',?3,'active',?4)", + params![W, O, Uuid::from_u128(2).to_string(), "1".repeat(64)], + ) + .expect("test: new_target_generation: execute succeeds"); + let scope = MailboxScope { + scope_id: Uuid::from_u128(30), + incarnation: Uuid::from_u128(2), + ..f.recipient.clone() + }; + writer + .execute( + "INSERT INTO agent_scopes VALUES (?1,?2,?3,'canonical-target','m',?4,1)", + params![scope.scope_id.to_string(), W, O, scope.incarnation.to_string()], + ) + .expect("test: new_target_generation: execute succeeds"); + scope +} + +#[test] +fn recipient_rebind_with_unconsumed_old_scope_retires_stream() { + let f = Fixture::new(); + f.receive(1, 1); + let mut second = f.message(2, 2); + let new_scope = new_target_generation(&f); + second.to_pin = f + .store + .recipient_pin(&f.authority, &new_scope, "canonical-target") + .expect("test: recipient_rebind_with_unconsumed_old_scope_retires_stream: recipient_pin succeeds"); + assert_eq!( + f.store.accept(&f.authority, second.clone()).unwrap_err(), + MailboxError::SeqStreamRetired, + "recipient rebind with unconsumed old scope retires stream: recipient authority or scope isolation changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), + 1, + "recipient rebind with unconsumed old scope retires stream: recipient authority or scope isolation changed" + ); + f.store + .set_execution(&new_scope, &f.target, Some("new-run".into())) + .expect("test: recipient_rebind_with_unconsumed_old_scope_retires_stream: set_execution succeeds"); + second.stream_id = Some(Uuid::from_u128(STREAM + 1)); + second.seq = 1; + f.store + .accept(&f.authority, second) + .expect("test: recipient_rebind_with_unconsumed_old_scope_retires_stream: accept succeeds"); + let delivered = f + .store + .deliver(&new_scope, &f.target) + .expect("test: recipient_rebind_with_unconsumed_old_scope_retires_stream: deliver succeeds") + .expect("test: recipient_rebind_with_unconsumed_old_scope_retires_stream: deliver returns a value"); + assert_eq!( + delivered.message().seq, + 1, + "recipient rebind with unconsumed old scope retires stream: recipient authority or scope isolation changed" + ); + f.store + .adopt(&delivered) + .expect("test: recipient_rebind_with_unconsumed_old_scope_retires_stream: adopt succeeds"); + drop(delivered); + f.store + .erase_scope(&f.recipient, Duration::from_secs(5), &|| Ok(())) + .expect("test: recipient_rebind_with_unconsumed_old_scope_retires_stream: erase_scope succeeds"); + assert_eq!(f.scalar(&format!("SELECT count(*) FROM prx_mailbox_seq s JOIN prx_mailbox_receipts r ON r.stream_id=s.stream_id WHERE s.state=0 AND r.state<>2 AND r.ma_scope_id='{}'",f.recipient.scope_id)),0, "recipient rebind with unconsumed old scope retires stream: recipient authority or scope isolation changed"); +} + +#[test] +fn recipient_erase_retires_stream_before_recreated_scope_accept() { + let f = Fixture::new(); + f.receive(3, 3); + let mut fourth = f.message(4, 4); + // Represent a row left by the pre-fix rebind bug: its current role is Y, + // but an accepted X-pinned slot is still present. Erase must enumerate X + // receipts, not only the current recipient role. + let new_scope = new_target_generation(&f); + f.memory + .pool + .write() + .execute( + "UPDATE prx_mailbox_seq SET recipient_ma_scope_id=?1,recipient_incarnation=?2,recipient_generation=1", + params![new_scope.scope_id.to_string(), new_scope.incarnation.to_string()], + ) + .expect("test: recipient_erase_retires_stream_before_recreated_scope_accept: execute succeeds"); + f.store + .erase_scope(&f.recipient, Duration::from_secs(5), &|| Ok(())) + .expect("test: recipient_erase_retires_stream_before_recreated_scope_accept: erase_scope succeeds"); + fourth.to_pin = f + .store + .recipient_pin(&f.authority, &new_scope, "canonical-target") + .expect("test: recipient_erase_retires_stream_before_recreated_scope_accept: recipient_pin succeeds"); + assert_eq!( + f.store.accept(&f.authority, fourth.clone()).unwrap_err(), + MailboxError::SeqStreamRetired, + "recipient erase retires stream before recreated scope accept: payload retention and erasure boundary changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_messages"), + 0, + "recipient erase retires stream before recreated scope accept: payload retention and erasure boundary changed" + ); + fourth.stream_id = Some(Uuid::from_u128(STREAM + 1)); + fourth.seq = 1; + f.store + .accept(&f.authority, fourth) + .expect("test: recipient_erase_retires_stream_before_recreated_scope_accept: accept succeeds"); + f.store + .set_execution(&new_scope, &f.target, Some("new-run".into())) + .expect("test: recipient_erase_retires_stream_before_recreated_scope_accept: set_execution succeeds"); + assert_eq!( + f.store + .deliver(&new_scope, &f.target) + .expect("test: recipient_erase_retires_stream_before_recreated_scope_accept: deliver succeeds") + .expect("test: recipient_erase_retires_stream_before_recreated_scope_accept: deliver returns a value") + .message() + .seq, + 1, + "recipient erase retires stream before recreated scope accept: payload retention and erasure boundary changed" + ); +} + +#[test] +fn mailbox_mime_and_payload_have_separate_byte_limits() { + let f = Fixture::new(); + for mime in [ + String::new(), + "x".repeat(256), + "text/plain\0bad".into(), + "text/\u{e9}".into(), + ] { + let mut message = f.message(1, 1); + message.body.mime = mime; + assert_eq!( + f.store.accept(&f.authority, message).unwrap_err(), + MailboxError::InvalidMime, + "mailbox mime and payload share byte limits: expected messaging contract changed" + ); + } + let mut too_large = f.message(1, 1); + too_large.body.bytes = vec![0; crate::messaging::MAX_BODY_BYTES + 1]; + assert_eq!( + f.store.accept(&f.authority, too_large).unwrap_err(), + MailboxError::BodyTooLarge, + "mailbox mime and payload share byte limits: expected messaging contract changed" + ); + let mut fits = f.message(1, 1); + fits.body.mime = "x".repeat(255); + fits.body.bytes = vec![0; crate::messaging::MAX_BODY_BYTES]; + f.store + .accept(&f.authority, fits) + .expect("test: mailbox_mime_and_payload_have_separate_byte_limits: accept succeeds"); + assert_eq!( + f.scalar("SELECT length(body_bytes)+length(CAST(body_mime AS BLOB)) FROM prx_mailbox_messages"), + 262399, + "mailbox mime and payload share byte limits: expected messaging contract changed" + ); +} + +#[tokio::test] +async fn child_session_reconstructs_mailbox_cursor() { + use crate::chat::sessions::child::{ChildSession, ChildSessionRegistry}; + let f = Fixture::new(); + let registry = ChildSessionRegistry::new(Arc::new(f.memory.clone())).with_workspace(W.into()); + registry + .insert(&ChildSession::new(f.target.clone(), None)) + .await + .expect("test: child_session_reconstructs_mailbox_cursor: insert succeeds"); + let empty = registry + .reconstruct(&f.target) + .await + .expect("test: child_session_reconstructs_mailbox_cursor: reconstruct succeeds"); + let scope = empty + .mailbox_scope() + .expect("test: child_session_reconstructs_mailbox_cursor: mailbox_scope succeeds") + .clone(); + drop(empty); + let canonical = ChildSessionRegistry::canonical_session_key(&f.target).expect( + "test: child_session_reconstructs_mailbox_cursor: ChildSessionRegistry::canonical_session_key succeeds", + ); + let mut message = f.message(1, 1); + message.to_pin = f + .store + .recipient_pin(&f.authority, &scope, &canonical) + .expect("test: child_session_reconstructs_mailbox_cursor: recipient_pin succeeds"); + f.store + .set_execution(&scope, &f.target, Some("child-run".into())) + .expect("test: child_session_reconstructs_mailbox_cursor: set_execution succeeds"); + f.store + .accept(&f.authority, message) + .expect("test: child_session_reconstructs_mailbox_cursor: accept succeeds"); + let delivery = f + .store + .deliver(&scope, &f.target) + .expect("test: child_session_reconstructs_mailbox_cursor: deliver succeeds") + .expect("test: child_session_reconstructs_mailbox_cursor: deliver returns a value"); + f.store + .adopt(&delivery) + .expect("test: child_session_reconstructs_mailbox_cursor: adopt succeeds"); + drop(delivery); + let restored = registry + .reconstruct(&f.target) + .await + .expect("test: child_session_reconstructs_mailbox_cursor: reconstruct succeeds"); + assert_eq!( + restored.history().len(), + 1, + "child session reconstructs mailbox cursor: atomic adoption or history projection changed" + ); + assert_eq!( + restored + .history() + .first() + .expect("test: child_session_reconstructs_mailbox_cursor: first succeeds") + .content, + "request-1", + "child session reconstructs mailbox cursor: atomic adoption or history projection changed" + ); + registry + .insert(&restored) + .await + .expect("test: child_session_reconstructs_mailbox_cursor: insert succeeds"); + drop(restored); + let again = registry + .reconstruct(&f.target) + .await + .expect("test: child_session_reconstructs_mailbox_cursor: reconstruct succeeds"); + assert_eq!( + again.history().len(), + 1, + "snapshot projection must merge by event identity exactly once" + ); + drop(again); + f.clock.advance(crate::messaging::mailbox::REPLAY_SECONDS + 1); + f.store + .gc_scope(&scope) + .expect("test: child_session_reconstructs_mailbox_cursor: gc_scope succeeds"); + let after_gc = registry + .reconstruct(&f.target) + .await + .expect("test: child_session_reconstructs_mailbox_cursor: reconstruct succeeds"); + assert_eq!(after_gc.history().len(), 1, "source_ref and seq survive receipt GC"); +} + +#[tokio::test] +async fn child_sessions_owner_and_agent_erase_remove_records() { + use crate::chat::sessions::child::{ChildSession, ChildSessionRegistry}; + let f = Fixture::new(); + { + let writer = f.memory.pool.write(); + for (key, inc) in [("n:prx_agent_a", 40), ("n:prx_agent_b", 50)] { + writer + .execute( + "INSERT INTO agent_incarnations VALUES (?1,?2,?3,?4,'active',?5)", + params![W, O, key, Uuid::from_u128(inc).to_string(), "2".repeat(64)], + ) + .expect("test: child_sessions_owner_and_agent_erase_remove_records: execute succeeds"); + } + } + let registry = ChildSessionRegistry::new(Arc::new(f.memory.clone())).with_workspace(W.into()); + let a = SessionAddr::new("prx-node", O, "child-a", Some("prx_agent_a")); + let b = SessionAddr::new("prx-node", O, "child-b", Some("prx_agent_b")); + registry + .insert(&ChildSession::new(a.clone(), None)) + .await + .expect("test: child_sessions_owner_and_agent_erase_remove_records: insert succeeds"); + registry + .insert(&ChildSession::new(b.clone(), None)) + .await + .expect("test: child_sessions_owner_and_agent_erase_remove_records: insert succeeds"); + let active = registry + .reconstruct(&a) + .await + .expect("test: child_sessions_owner_and_agent_erase_remove_records: reconstruct succeeds"); + let scope = active + .mailbox_scope() + .expect("test: child_sessions_owner_and_agent_erase_remove_records: mailbox_scope succeeds") + .clone(); + drop(active); + f.store + .erase_scope(&scope, Duration::from_secs(5), &|| Ok(())) + .expect("test: child_sessions_owner_and_agent_erase_remove_records: erase_scope succeeds"); + assert!( + registry.reconstruct(&a).await.is_err(), + "child sessions owner and agent erase remove records: payload retention and erasure boundary changed" + ); + let other = registry + .reconstruct(&b) + .await + .expect("test: child_sessions_owner_and_agent_erase_remove_records: reconstruct succeeds"); + assert_eq!( + other.addr(), + &b, + "child sessions owner and agent erase remove records: payload retention and erasure boundary changed" + ); + drop(other); + // The global MA owner eraser enumerates all owner snapshots. Exercise its + // mailbox/child adapter for that complete historical set. + let scopes = { + let writer = f.memory.pool.write(); + let mut query = writer + .prepare("SELECT scope_id,incarnation,generation FROM agent_scopes WHERE workspace_id=?1 AND owner_id=?2") + .expect("test: child_sessions_owner_and_agent_erase_remove_records: prepare succeeds"); + query + .query_map(params![W, O], |r| { + Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, i64>(2)?)) + }) + .expect("test: child_sessions_owner_and_agent_erase_remove_records: query_map succeeds") + .collect::>>() + .expect("test: child_sessions_owner_and_agent_erase_remove_records: collect succeeds") + }; + for (id, incarnation, generation) in scopes { + f.store + .erase_scope( + &MailboxScope { + workspace_id: W.into(), + owner_id: O.into(), + scope_id: Uuid::parse_str(&id) + .expect("test: child_sessions_owner_and_agent_erase_remove_records: Uuid::parse_str succeeds"), + incarnation: Uuid::parse_str(&incarnation) + .expect("test: child_sessions_owner_and_agent_erase_remove_records: Uuid::parse_str succeeds"), + generation, + }, + Duration::from_secs(5), + &|| Ok(()), + ) + .expect("test: child_sessions_owner_and_agent_erase_remove_records: erase_scope succeeds"); + } + assert_eq!( + f.scalar("SELECT count(*) FROM child_sessions"), + 0, + "child sessions owner and agent erase remove records: payload retention and erasure boundary changed" + ); + assert!( + registry.reconstruct(&b).await.is_err(), + "child sessions owner and agent erase remove records: payload retention and erasure boundary changed" + ); + // A quarantined legacy/orphan cannot be silently omitted by scope SQL. + f.memory + .pool + .write() + .execute("INSERT INTO child_sessions(key,record) VALUES ('legacy','{}')", []) + .expect("test: child_sessions_owner_and_agent_erase_remove_records: execute succeeds"); + assert_eq!( + f.store + .erase_scope(&f.sender, Duration::from_secs(5), &|| Ok(())) + .unwrap_err(), + MailboxError::Fenced, + "child sessions owner and agent erase remove records: payload retention and erasure boundary changed" + ); +} + +#[test] +fn mailbox_scope_and_address_validation_is_transactional() { + let f = Fixture::new(); + let mut forged = f.message(1, 1); + forged.to.owner = "prx_other_owner".into(); + assert_eq!( + f.store.accept(&f.authority, forged).unwrap_err(), + MailboxError::Unauthorized, + "mailbox scope and address validation is transactional: recipient authority or scope isolation changed" + ); + let wrong = MailboxScope { + generation: 2, + ..f.recipient.clone() + }; + assert_eq!( + f.store + .recipient_pin(&f.authority, &wrong, "canonical-target") + .unwrap_err(), + MailboxError::StaleIncarnation, + "mailbox scope and address validation is transactional: recipient authority or scope isolation changed" + ); + assert_eq!( + f.store + .recipient_pin(&f.authority, &f.recipient, "wrong-canonical") + .unwrap_err(), + MailboxError::StaleIncarnation, + "mailbox scope and address validation is transactional: recipient authority or scope isolation changed" + ); + assert!( + MailboxAuthority::local( + W.into(), + f.source.clone(), + SessionAddr::new("prx-node", O, "x".repeat(513), None) + ) + .is_err(), + "mailbox scope and address validation is transactional: recipient authority or scope isolation changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), + 0, + "mailbox scope and address validation is transactional: recipient authority or scope isolation changed" + ); +} + +#[test] +fn queued_outbox_first_post_after_recipient_recreate_is_stale_incarnation() { + let f = Fixture::new(); + f.store + .publish(&f.authority, f.message(1, 0), &f.sender, f.clock.now() + 300, None) + .expect("test: queued_outbox_first_post_after_recipient_recreate_is_stale_incarnation: publish succeeds"); + let pending = f.store.pending_outbox(&f.sender, &f.source).expect( + "test: queued_outbox_first_post_after_recipient_recreate_is_stale_incarnation: pending_outbox succeeds", + ); + let held = pending + .first() + .expect("test: queued_outbox_first_post_after_recipient_recreate_is_stale_incarnation: first succeeds") + .message() + .clone(); + f.store + .erase_scope(&f.recipient, Duration::from_secs(5), &|| Ok(())) + .expect("test: queued_outbox_first_post_after_recipient_recreate_is_stale_incarnation: erase_scope succeeds"); + let _new = new_target_generation(&f); + assert_eq!( + f.store.accept(&f.authority, held).unwrap_err(), + MailboxError::StaleIncarnation, + "queued outbox first post after recipient recreate is stale incarnation: capacity enforcement or bounded delivery changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_messages"), + 0, + "queued outbox first post after recipient recreate is stale incarnation: capacity enforcement or bounded delivery changed" + ); +} + +#[test] +fn stale_incarnation_delayed_send_is_rejected() { + let f = Fixture::new(); + let held = f.message(1, 1); + let _new = new_target_generation(&f); + assert_eq!( + f.store.accept(&f.authority, held).unwrap_err(), + MailboxError::StaleIncarnation, + "stale incarnation delayed send is rejected: recipient authority or scope isolation changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_messages"), + 0, + "stale incarnation delayed send is rejected: recipient authority or scope isolation changed" + ); +} + +#[test] +fn mailbox_row_requires_scope() { + let f = Fixture::new(); + let mut message = f.message(1, 1); + message.to_pin.generation = 99; + assert_eq!( + f.store.accept(&f.authority, message).unwrap_err(), + MailboxError::StaleIncarnation, + "mailbox row requires scope: recipient authority or scope isolation changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_messages"), + 0, + "mailbox row requires scope: recipient authority or scope isolation changed" + ); + let error = f.memory.pool.write().execute( + "INSERT INTO prx_mailbox_messages(id,stream_id,seq,workspace_id,owner_id,incarnation,generation,state,body_mime,body_bytes,delivery_meta) VALUES (1,1,x'0000000000000001',?1,?2,?3,1,0,'text/plain',x'00','{}')", + params![W,O,Uuid::from_u128(INC).to_string()], + ).unwrap_err(); + assert!( + error + .to_string() + .contains("NOT NULL constraint failed: prx_mailbox_messages.ma_scope_id"), + "mailbox row requires scope: recipient authority or scope isolation changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_messages"), + 0, + "mailbox row requires scope: recipient authority or scope isolation changed" + ); +} + +#[test] +fn mailbox_pk_includes_from_instance() { + let f = Fixture::new(); + f.receive(1, 1); + let mut source = f.source.clone(); + source.instance = "peer-two".into(); + let authority = MailboxAuthority::verified_peer( + W.into(), + source, + f.target.clone(), + crate::messaging::MessageAuth { + issuer: "prx-issuer".into(), + subject: "prx-peer".into(), + method: "mtls".into(), + }, + ) + .expect("test: mailbox_pk_includes_from_instance: MailboxAuthority::verified_peer succeeds"); + let mut message = f.message(1, 1); + message.to_pin = f + .store + .recipient_pin(&authority, &f.recipient, "canonical-target") + .expect("test: mailbox_pk_includes_from_instance: recipient_pin succeeds"); + message.id = Uuid::from_u128(9001); + f.store + .accept(&authority, message) + .expect("test: mailbox_pk_includes_from_instance: accept succeeds"); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), + 2, + "mailbox pk includes from instance: expected messaging contract changed" + ); +} + +#[test] +fn mailbox_pk_omits_run() { + let f = Fixture::new(); + let message = f.message(1, 1); + let saved = f + .store + .accept(&f.authority, message.clone()) + .expect("test: mailbox_pk_omits_run: accept succeeds"); + f.store + .set_execution(&f.recipient, &f.target, Some("replacement-run".into())) + .expect("test: mailbox_pk_omits_run: set_execution succeeds"); + assert_eq!( + f.store + .accept(&f.authority, message) + .expect("test: mailbox_pk_omits_run: accept succeeds"), + saved, + "mailbox pk omits run: expected messaging contract changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), + 1, + "mailbox pk omits run: expected messaging contract changed" + ); +} + +#[test] +fn mailbox_seq_pk_includes_stream_id() { + let f = Fixture::new(); + f.receive(1, 1); + let mut other = f.message(2, 1); + other.stream_id = Some(Uuid::from_u128(501)); + f.store + .accept(&f.authority, other) + .expect("test: mailbox_seq_pk_includes_stream_id: accept succeeds"); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_seq"), + 2, + "mailbox seq pk includes stream id: expected messaging contract changed" + ); +} + +#[test] +fn idempotency_does_not_collide_across_senders() { + mailbox_pk_includes_from_instance(); +} + +#[test] +fn seq_is_allocated_in_outbox_transaction() { + let f = Fixture::new(); + f.memory.pool.write().execute_batch("CREATE TEMP TRIGGER reject_publish BEFORE INSERT ON prx_mailbox_outbox BEGIN SELECT RAISE(ABORT,'injected write failure'); END;").expect("test: seq_is_allocated_in_outbox_transaction: execute_batch succeeds"); + assert_eq!( + f.store + .publish(&f.authority, f.message(1, 0), &f.sender, f.clock.now() + 300, None) + .unwrap_err(), + MailboxError::Storage, + "seq is allocated in outbox transaction: expected messaging contract changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_seq"), + 0, + "seq is allocated in outbox transaction: expected messaging contract changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_parents"), + 0, + "seq is allocated in outbox transaction: expected messaging contract changed" + ); + f.memory + .pool + .write() + .execute_batch("DROP TRIGGER reject_publish") + .expect("test: seq_is_allocated_in_outbox_transaction: execute_batch succeeds"); + let first = f + .store + .publish(&f.authority, f.message(1, 0), &f.sender, f.clock.now() + 300, None) + .expect("test: seq_is_allocated_in_outbox_transaction: publish succeeds"); + assert_eq!( + first.seq, 1, + "seq is allocated in outbox transaction: expected messaging contract changed" + ); + let again = f + .store + .publish(&f.authority, f.message(1, 0), &f.sender, f.clock.now() + 300, None) + .expect("test: seq_is_allocated_in_outbox_transaction: publish succeeds"); + assert_eq!( + again, first, + "seq is allocated in outbox transaction: expected messaging contract changed" + ); + assert_eq!( + f.store + .publish(&f.authority, f.message(2, 0), &f.sender, f.clock.now() + 300, None) + .expect("test: seq_is_allocated_in_outbox_transaction: publish succeeds") + .seq, + 2, + "seq is allocated in outbox transaction: expected messaging contract changed" + ); +} + +#[test] +fn seq2_before_seq1_on_never_seen_stream_is_held_fifo() { + let f = Fixture::new(); + f.receive(2, 2); + assert!( + f.store + .deliver(&f.recipient, &f.target) + .expect("test: seq2_before_seq1_on_never_seen_stream_is_held_fifo: deliver succeeds") + .is_none(), + "seq2 before seq1 on never seen stream is held fifo: expected messaging contract changed" + ); + f.receive(1, 1); + let first = f.deliver(); + assert_eq!( + first.message().seq, + 1, + "seq2 before seq1 on never seen stream is held fifo: expected messaging contract changed" + ); + f.store + .adopt(&first) + .expect("test: seq2_before_seq1_on_never_seen_stream_is_held_fifo: adopt succeeds"); + drop(first); + assert_eq!( + f.deliver().message().seq, + 2, + "seq2 before seq1 on never seen stream is held fifo: expected messaging contract changed" + ); +} + +#[test] +fn late_seq_after_stream_retirement_is_seq_stream_retired() { + let f = Fixture::new(); + let pending = f.message(2, 2); + f.store + .accept(&f.authority, pending) + .expect("test: late_seq_after_stream_retirement_is_seq_stream_retired: accept succeeds"); + f.memory + .pool + .write() + .execute( + "UPDATE prx_mailbox_seq SET state=1,progress=json_set(progress,'$.retired_at',1000)", + [], + ) + .expect("test: late_seq_after_stream_retirement_is_seq_stream_retired: execute succeeds"); + assert_eq!( + f.store.accept(&f.authority, f.message(1, 1)).unwrap_err(), + MailboxError::SeqStreamRetired, + "late seq after stream retirement is seq stream retired: expected messaging contract changed" + ); +} + +#[test] +fn delayed_old_epoch_message_is_rejected_after_stream_reopen() { + let f = Fixture::new(); + f.receive(1, 1); + let first = f.deliver(); + f.store + .adopt(&first) + .expect("test: delayed_old_epoch_message_is_rejected_after_stream_reopen: adopt succeeds"); + drop(first); + f.clock.advance(604801); + f.store + .gc_scope(&f.recipient) + .expect("test: delayed_old_epoch_message_is_rejected_after_stream_reopen: gc_scope succeeds"); + let mut reopened = f.message(3, 1); + reopened.stream_id = Some(Uuid::from_u128(501)); + f.store + .accept(&f.authority, reopened) + .expect("test: delayed_old_epoch_message_is_rejected_after_stream_reopen: accept succeeds"); + assert_eq!( + f.store.accept(&f.authority, f.message(2, 2)).unwrap_err(), + MailboxError::SeqStreamRetired, + "delayed old epoch message is rejected after stream reopen: expected messaging contract changed" + ); +} + +#[test] +fn mailbox_accept_nacks_while_fenced() { + let f = Fixture::new(); + let queued = f.message(1, 1); + f.store + .erase_scope(&f.recipient, Duration::from_secs(5), &|| Ok(())) + .expect("test: mailbox_accept_nacks_while_fenced: erase_scope succeeds"); + assert_eq!( + f.store.accept(&f.authority, queued).unwrap_err(), + MailboxError::ScopeErasing, + "mailbox accept nacks while fenced: expected messaging contract changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_messages"), + 0, + "mailbox accept nacks while fenced: expected messaging contract changed" + ); +} + +#[test] +fn full_queue_nacks_without_drop() { + let f = Fixture::new(); + for n in 1..=64 { + f.clock.advance(1); + f.receive(n, n); + } + f.clock.advance(1); + assert_eq!( + f.store.accept(&f.authority, f.message(65, 65)).unwrap_err(), + MailboxError::QueueFull, + "full queue nacks without drop: capacity enforcement or bounded delivery changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_messages"), + 64, + "full queue nacks without drop: capacity enforcement or bounded delivery changed" + ); + assert_eq!( + f.deliver().message().seq, + 1, + "full queue nacks without drop: capacity enforcement or bounded delivery changed" + ); +} + +#[test] +fn fast_consumer_hits_retained_body_quota() { + let f = Fixture::new(); + // 257 near-limit bodies exceed 64 MiB even though every row is consumed. + for n in 1..=256 { + f.clock.advance(1); + let mut message = f.message(n, n); + message.body.bytes = vec![b'x'; crate::messaging::MAX_BODY_BYTES - 10]; + f.store + .accept(&f.authority, message) + .expect("test: fast_consumer_hits_retained_body_quota: accept succeeds"); + let selected = f.deliver(); + f.store + .adopt(&selected) + .expect("test: fast_consumer_hits_retained_body_quota: adopt succeeds"); + } + f.clock.advance(1); + let mut over = f.message(257, 257); + over.body.bytes = vec![b'x'; crate::messaging::MAX_BODY_BYTES - 10]; + assert_eq!( + f.store.accept(&f.authority, over).unwrap_err(), + MailboxError::Quota("bodies"), + "fast consumer hits retained body quota: payload retention and erasure boundary changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_messages"), + 256, + "fast consumer hits retained body quota: payload retention and erasure boundary changed" + ); + f.clock.advance(604801); + let mut fresh = f.message(258, 1); + fresh.stream_id = Some(Uuid::from_u128(501)); + f.store + .accept(&f.authority, fresh) + .expect("test: fast_consumer_hits_retained_body_quota: accept succeeds"); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_messages"), + 1, + "expired consumed bodies must be GCed before quota refusal" + ); +} + +#[test] +fn cross_instance_chain_depth_is_receiver_owned() { + let f = Fixture::new(); + let mut parent = None; + for n in 1..=9 { + f.clock.advance(1); + let mut message = f.message(n, n); + message.in_reply_to = parent; + // Wire depth is maliciously reset; receiver must derive it. + message.hop_count = 0; + message.ancestry.clear(); + let accepted = f + .store + .accept(&f.authority, message.clone()) + .expect("test: cross_instance_chain_depth_is_receiver_owned: accept succeeds"); + assert_eq!( + accepted.chain.depth, + n as u8 - 1, + "cross instance chain depth is capped: capacity enforcement or bounded delivery changed" + ); + parent = Some(message.id); + } + +} + +#[test] +fn send_reply_resolves_parent_from_outbox_without_transcript() { + let f = Fixture::new(); + let sent = f + .store + .publish(&f.authority, f.message(1, 0), &f.sender, f.clock.now() + 300, None) + .expect("test: send_reply_resolves_parent_from_outbox_without_transcript: publish succeeds"); + let mut reply = f.message(2, 1); + reply.in_reply_to = Some(sent.message_id); + reply.stream_id = Some(Uuid::from_u128(502)); + let received = f + .store + .accept(&f.authority, reply) + .expect("test: send_reply_resolves_parent_from_outbox_without_transcript: accept succeeds"); + assert_eq!( + received.chain.depth, 1, + "send reply resolves parent from outbox without transcript: atomic adoption or history projection changed" + ); + assert_eq!( + received.chain.ancestry, + vec![sent.message_id], + "send reply resolves parent from outbox without transcript: atomic adoption or history projection changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM conversation_turns"), + 0, + "send reply resolves parent from outbox without transcript: atomic adoption or history projection changed" + ); +} + +#[test] +fn idempotent_retry_after_parent_erase_reports_scope_erasing() { + let f = Fixture::new(); + f.receive(1, 1); + let mut reply = f.message(2, 2); + reply.in_reply_to = Some(Uuid::from_u128(1001)); + f.store + .accept(&f.authority, reply.clone()) + .expect("test: idempotent_retry_after_parent_erase_reports_scope_erasing: accept succeeds"); + f.store + .erase_scope(&f.recipient, Duration::from_secs(5), &|| Ok(())) + .expect("test: idempotent_retry_after_parent_erase_reports_scope_erasing: erase_scope succeeds"); + assert_eq!( + f.store + .accept(&f.authority, reply) + .expect_err("test: erased nonconsumed replay is terminal"), + MailboxError::ScopeErasing, + "erased nonconsumed replay must report scope erasure" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_outbox"), + 0, + "erased nonconsumed replay must report scope erasure" + ); +} + +#[test] +fn altered_parent_retry_after_erase_is_idempotency_conflict() { + let f = Fixture::new(); + f.receive(1, 1); + let mut reply = f.message(2, 2); + reply.in_reply_to = Some(Uuid::from_u128(1001)); + f.store + .accept(&f.authority, reply.clone()) + .expect("test: altered_parent_retry_after_erase_is_idempotency_conflict: accept succeeds"); + f.store + .erase_scope(&f.recipient, Duration::from_secs(5), &|| Ok(())) + .expect("test: altered_parent_retry_after_erase_is_idempotency_conflict: erase_scope succeeds"); + reply.in_reply_to = None; + assert_eq!( + f.store.accept(&f.authority, reply).unwrap_err(), + MailboxError::IdempotencyConflict, + "altered parent retry after erase is idempotency conflict: payload retention and erasure boundary changed" + ); +} + +struct LocalResolver { + store: SqliteMailbox, + authority: MailboxAuthority, + scope: MailboxScope, +} +#[async_trait::async_trait] +impl crate::messaging::send::MailboxResolver for LocalResolver { + async fn resolve( + &self, + target: &SessionAddr, + ) -> crate::messaging::mailbox::MailboxResult { + if *target != self.authority.destination { + return Err(MailboxError::Unauthorized); + } + Ok(crate::messaging::send::MailboxDestination { + authority: self.authority.clone(), + pin: self + .store + .recipient_pin(&self.authority, &self.scope, "canonical-target")?, + pin_expires_at: 10_000, + }) + } +} diff --git a/src/memory/sqlite/tests/mailbox/section_2.rs b/src/memory/sqlite/tests/mailbox/section_2.rs new file mode 100644 index 000000000..8efc2875a --- /dev/null +++ b/src/memory/sqlite/tests/mailbox/section_2.rs @@ -0,0 +1,1698 @@ +impl Fixture { + fn sender_port( + &self, + inherited: Option, + ) -> Arc { + Arc::new( + crate::memory::sqlite::mailbox::SqliteMailboxSender::new( + self.store.clone(), + self.source.clone(), + self.sender.clone(), + Arc::new(LocalResolver { + store: self.store.clone(), + authority: self.authority.clone(), + scope: self.recipient.clone(), + }), + inherited, + ) + .expect("test: sender_port: SqliteMailboxSender::new succeeds"), + ) + } +} + +#[tokio::test] +async fn sessions_send_tool_emits_one_external_send_envelope() { + use crate::tools::Tool; + let f = Fixture::new(); + let tool = crate::tools::SessionsSendTool::new(Arc::new(tokio::sync::RwLock::new(Vec::new()))) + .with_mailbox(f.sender_port(None)); + let registry: Vec> = vec![Box::new( + crate::tools::SessionsSendTool::new(Arc::new(tokio::sync::RwLock::new(Vec::new()))) + .with_mailbox(f.sender_port(None)), + )]; + let catalog = crate::tools::capability::catalog::CapabilityCatalog::build( + ®istry, + &crate::tools::capability::catalog::CatalogSources::default(), + &crate::tools::capability::catalog::SurfacePolicy::default(), + ) + .expect("test: sessions_send_tool_emits_one_external_send_envelope: fixture setup succeeds"); + assert_eq!( + catalog + .entry_for_public_name("sessions_send") + .expect("test: sessions_send_tool_emits_one_external_send_envelope: entry_for_public_name succeeds") + .effect, + crate::tools::capability::contract::SideEffectClass::ExternalSend, + "prx message tool emits one external send envelope: expected messaging contract changed" + ); + let result = tool + .execute(serde_json::json!({"to":{"session":"target"},"message":"ordinary Data"})) + .await + .expect("test: sessions_send_tool_emits_one_external_send_envelope: execute succeeds"); + assert!(result.success, "{}", result.output); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_outbox"), + 1, + "prx message tool emits one external send envelope: expected messaging contract changed" + ); + let out = f + .store + .pending_outbox(&f.sender, &f.source) + .expect("test: sessions_send_tool_emits_one_external_send_envelope: pending_outbox succeeds"); + assert_eq!( + out[0].message().kind, + MessageKind::Data, + "prx message tool emits one external send envelope: expected messaging contract changed" + ); + assert_eq!( + out[0].message().body.bytes, + b"ordinary Data", + "prx message tool emits one external send envelope: expected messaging contract changed" + ); + assert_eq!( + out[0].message().from, + f.source, + "prx message tool emits one external send envelope: expected messaging contract changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_messages"), + 0, + "sender tool does not execute the recipient" + ); + for invalid in [ + serde_json::json!({"to":{"session":"target","owner":null},"text":"x"}), + serde_json::json!({"to":{"session":"target"},"text":"x","in_reply_to":null}), + ] { + assert!( + tool.execute(invalid).await.is_err(), + "prx message tool emits one external send envelope: expected messaging contract changed" + ); + } + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_outbox"), + 1, + "prx message tool emits one external send envelope: expected messaging contract changed" + ); +} + +#[tokio::test] +async fn sessions_send_tool_send_is_stamped_with_runtime_causal_chain() { + use crate::tools::Tool; + let f = Fixture::new(); + let accepted = f.receive(1, 1); + let inherited = crate::messaging::InheritedProvenance { + remote: crate::messaging::RemotePeerAttr { + issuer: "prx-issuer".into(), + subject: "prx-peer".into(), + message_id: accepted.message_id, + }, + chain: accepted.chain, + }; + let tool = crate::tools::SessionsSendTool::new(Arc::new(tokio::sync::RwLock::new(Vec::new()))) + .with_mailbox(f.sender_port(Some(inherited.clone()))); + let result = tool + .execute(serde_json::json!({"to":{"session":"target"},"message":"reply"})) + .await + .expect("test: sessions_send_tool_send_is_stamped_with_runtime_causal_chain: execute succeeds"); + assert!(result.success, "{}", result.output); + let out = f + .store + .pending_outbox(&f.sender, &f.source) + .expect("test: sessions_send_tool_send_is_stamped_with_runtime_causal_chain: pending_outbox succeeds"); + assert_eq!( + out[0].message().in_reply_to, + Some(inherited.chain.trigger), + "prx message tool send is stamped with runtime causal chain: expected messaging contract changed" + ); + assert_eq!( + out[0].message().hop_count, + 1, + "prx message tool send is stamped with runtime causal chain: expected messaging contract changed" + ); +} + +#[tokio::test] +async fn sessions_send_remote_addr_is_not_steer() { + use crate::tools::Tool; + let f = Fixture::new(); + let tool = crate::tools::sessions_send::SessionsSendTool::new(Arc::new(tokio::sync::RwLock::new(Vec::new()))) + .with_mailbox(f.sender_port(None)); + assert!( + tool.parameters_schema().get("oneOf").is_some(), + "sessions send remote addr is not steer: expected messaging contract changed" + ); + assert!( + tool.execute(serde_json::json!({"to":{"session":"target"},"message":"mailbox Data"})) + .await + .expect("test: sessions_send_remote_addr_is_not_steer: execute succeeds") + .success, + "sessions send remote addr is not steer: expected messaging contract changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_outbox"), + 1, + "sessions send remote addr is not steer: expected messaging contract changed" + ); + assert!( + tool.execute(serde_json::json!({"run_id":"run-target","to":{"session":"target"},"message":"ambiguous"})) + .await + .is_err(), + "sessions send remote addr is not steer: expected messaging contract changed" + ); +} + +#[test] +fn slash_msg_builds_envelope_to_peer_session() { + let f = Fixture::new(); + let (target, text) = crate::chat::commands::msg::parse("/msg peer-node target/prx_agent hello peer", &f.source) + .expect("test: slash_msg_builds_envelope_to_peer_session: fixture setup succeeds"); + assert_eq!( + target, + SessionAddr::new("peer-node", O, "target", Some("prx_agent")), + "slash msg builds envelope to peer session: expected messaging contract changed" + ); + assert_eq!( + text, "hello peer", + "slash msg builds envelope to peer session: expected messaging contract changed" + ); + assert!( + crate::chat::commands::msg::parse("/msg local target/ ", &f.source).is_err(), + "slash msg builds envelope to peer session: expected messaging contract changed" + ); +} + +#[test] +fn mailbox_formats_and_natural_key_collisions_fail_closed() { + let f = Fixture::new(); + let original = f.message(1, 1); + f.store + .accept(&f.authority, original.clone()) + .expect("test: mailbox_formats_and_natural_key_collisions_fail_closed: accept succeeds"); + f.memory + .pool + .write() + .execute( + "UPDATE prx_mailbox_receipts SET receipt_meta=json_set(receipt_meta,'$.unknown',1)", + [], + ) + .expect("test: mailbox_formats_and_natural_key_collisions_fail_closed: execute succeeds"); + assert_eq!( + f.store.accept(&f.authority, original.clone()).unwrap_err(), + MailboxError::InvalidMetadata, + "mailbox formats and natural key collisions fail closed: expected messaging contract changed" + ); + f.memory + .pool + .write() + .execute( + "UPDATE prx_mailbox_receipts SET receipt_meta=json_remove(receipt_meta,'$.unknown')", + [], + ) + .expect("test: mailbox_formats_and_natural_key_collisions_fail_closed: execute succeeds"); + let canonical = f + .memory + .pool + .write() + .query_row("SELECT receipt_meta FROM prx_mailbox_receipts", [], |r| { + r.get::<_, String>(0) + }) + .expect("test: mailbox_formats_and_natural_key_collisions_fail_closed: query_row succeeds"); + f.memory + .pool + .write() + .execute( + "UPDATE prx_mailbox_receipts SET receipt_meta=?1", + [format!(" {canonical}")], + ) + .expect("test: mailbox_formats_and_natural_key_collisions_fail_closed: execute succeeds"); + assert_eq!( + f.store.accept(&f.authority, original.clone()).unwrap_err(), + MailboxError::InvalidMetadata, + "mailbox formats and natural key collisions fail closed: expected messaging contract changed" + ); + f.memory + .pool + .write() + .execute("UPDATE prx_mailbox_receipts SET receipt_meta=?1", [canonical]) + .expect("test: mailbox_formats_and_natural_key_collisions_fail_closed: execute succeeds"); + f.memory + .pool + .write() + .execute("UPDATE prx_mailbox_seq SET wire_stream_id=zeroblob(15)", []) + .expect("test: mailbox_formats_and_natural_key_collisions_fail_closed: execute succeeds"); + assert_eq!( + f.store.accept(&f.authority, original.clone()).unwrap_err(), + MailboxError::CorruptState, + "mailbox formats and natural key collisions fail closed: expected messaging contract changed" + ); + f.memory + .pool + .write() + .execute( + "UPDATE prx_mailbox_seq SET wire_stream_id=?1", + [Uuid::from_u128(STREAM).as_bytes().as_slice()], + ) + .expect("test: mailbox_formats_and_natural_key_collisions_fail_closed: execute succeeds"); + let mut changed = f.target.clone(); + changed.session = "other-target".into(); + f.memory + .pool + .write() + .execute( + "UPDATE prx_mailbox_seq SET to_addr=?1", + [serde_json::to_string(&changed).expect( + "test: mailbox_formats_and_natural_key_collisions_fail_closed: serde_json::to_string succeeds", + )], + ) + .expect("test: mailbox_formats_and_natural_key_collisions_fail_closed: execute succeeds"); + assert_eq!( + f.store.accept(&f.authority, original).unwrap_err(), + MailboxError::NaturalKeyCollision, + "mailbox formats and natural key collisions fail closed: expected messaging contract changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), + 1, + "mailbox formats and natural key collisions fail closed: expected messaging contract changed" + ); +} + +#[test] +fn mailbox_scope_pin_role_and_run_checks_fail_closed() { + let f = Fixture::new(); + let mut message = f.message(1, 1); + message.exec = Some(ExecRef { + run: Some("replaced-run".into()), + }); + assert_eq!( + f.store.accept(&f.authority, message).unwrap_err(), + MailboxError::StaleRun, + "mailbox scope pin role and run checks fail closed: recipient authority or scope isolation changed" + ); + f.receive(1, 1); + f.memory + .pool + .write() + .execute("UPDATE prx_mailbox_seq SET recipient_generation=NULL", []) + .expect("test: mailbox_scope_pin_role_and_run_checks_fail_closed: execute succeeds"); + assert!( + matches!( + f.store.deliver(&f.recipient, &f.target), + Err(MailboxError::CorruptState) + ), + "mailbox scope pin role and run checks fail closed: recipient authority or scope isolation changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM conversation_turns"), + 0, + "mailbox scope pin role and run checks fail closed: recipient authority or scope isolation changed" + ); +} + +#[test] +fn mailbox_identity_and_state_transitions_are_immutable() { + let f = Fixture::new(); + f.receive(1, 1); + let delivery = f.deliver(); + f.memory + .pool + .write() + .execute( + "UPDATE prx_mailbox_messages SET body_bytes=?1", + [b"tampered".as_slice()], + ) + .expect("test: mailbox_identity_and_state_transitions_are_immutable: execute succeeds"); + assert_eq!( + f.store.adopt(&delivery).unwrap_err(), + MailboxError::IdentityImmutable, + "mailbox identity and state transitions are immutable: replay identity or receipt stability changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM conversation_turns"), + 0, + "mailbox identity and state transitions are immutable: replay identity or receipt stability changed" + ); + assert_eq!( + f.scalar("SELECT state FROM prx_mailbox_receipts"), + 1, + "mailbox identity and state transitions are immutable: replay identity or receipt stability changed" + ); +} + +#[test] +fn mailbox_transport_and_chain_metadata_is_runtime_owned() { + let f = Fixture::new(); + let mut message = f.message(1, 1); + message.from = SessionAddr::new("forged-instance", "forged-owner", "forged-session", None); + message.origin = Some(crate::messaging::MessageOrigin::RemotePeer); + message.auth = Some(crate::messaging::MessageAuth { + issuer: "forged".into(), + subject: "forged".into(), + method: "mtls".into(), + }); + message.hop_count = 8; + message.ancestry = vec![Uuid::nil(); 8]; + let receipt = f + .store + .accept(&f.authority, message) + .expect("test: mailbox_transport_and_chain_metadata_is_runtime_owned: accept succeeds"); + assert_eq!( + receipt.chain.depth, 0, + "mailbox transport and chain metadata is runtime owned: expected messaging contract changed" + ); + assert!( + receipt.remote.is_none(), + "mailbox transport and chain metadata is runtime owned: expected messaging contract changed" + ); + let delivered = f.deliver(); + assert_eq!( + delivered.message().from, + f.source, + "mailbox transport and chain metadata is runtime owned: expected messaging contract changed" + ); + assert_eq!( + delivered.message().origin, + Some(crate::messaging::MessageOrigin::LocalModel), + "mailbox transport and chain metadata is runtime owned: expected messaging contract changed" + ); + assert!( + delivered.message().auth.is_none(), + "mailbox transport and chain metadata is runtime owned: expected messaging contract changed" + ); +} + +#[test] +fn mailbox_replay_slot_and_message_id_reuse_are_checked() { + let f = Fixture::new(); + let message = f.message(1, 1); + let first = f + .store + .accept(&f.authority, message.clone()) + .expect("test: mailbox_replay_slot_and_message_id_reuse_are_checked: accept succeeds"); + let mut occupied = f.message(2, 1); + assert_eq!( + f.store.accept(&f.authority, occupied.clone()).unwrap_err(), + MailboxError::SeqConflict, + "mailbox replay slot and message id reuse are checked: replay identity or receipt stability changed" + ); + occupied.seq = 2; + occupied.id = message.id; + assert_eq!( + f.store.accept(&f.authority, occupied).unwrap_err(), + MailboxError::IdReuse, + "mailbox replay slot and message id reuse are checked: replay identity or receipt stability changed" + ); + assert_eq!( + f.store + .accept(&f.authority, message) + .expect("test: mailbox_replay_slot_and_message_id_reuse_are_checked: accept succeeds"), + first, + "mailbox replay slot and message id reuse are checked: replay identity or receipt stability changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), + 1, + "mailbox replay slot and message id reuse are checked: replay identity or receipt stability changed" + ); +} + +#[test] +fn mailbox_progress_and_gap_transitions_are_checked() { + let f = Fixture::new(); + let message = f.message(1, 1026); + assert_eq!( + f.store.accept(&f.authority, message).unwrap_err(), + MailboxError::Quota("seq"), + "mailbox progress and gap transitions are checked: expected messaging contract changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_seq"), + 0, + "gap reservation rolls back stream insert" + ); + f.receive(1, 1); + let delivery = f.deliver(); + assert_eq!( + f.store.recover_delivery(&f.recipient, &f.target).unwrap_err(), + MailboxError::RoleBusy, + "mailbox progress and gap transitions are checked: expected messaging contract changed" + ); + f.store + .adopt(&delivery) + .expect("test: mailbox_progress_and_gap_transitions_are_checked: adopt succeeds"); + drop(delivery); + f.store + .recover_delivery(&f.recipient, &f.target) + .expect("test: mailbox_progress_and_gap_transitions_are_checked: recover_delivery succeeds"); + assert!( + f.store + .deliver(&f.recipient, &f.target) + .expect("test: mailbox_progress_and_gap_transitions_are_checked: deliver succeeds") + .is_none(), + "mailbox progress and gap transitions are checked: expected messaging contract changed" + ); + f.memory + .pool + .write() + .execute( + "UPDATE prx_mailbox_seq SET progress=json_set(progress,'$.next_seq',0)", + [], + ) + .expect("test: mailbox_progress_and_gap_transitions_are_checked: execute succeeds"); + assert!( + matches!( + f.store.deliver(&f.recipient, &f.target), + Err(MailboxError::CorruptState) + ), + "mailbox progress and gap transitions are checked: expected messaging contract changed" + ); +} + +#[test] +fn fresh_sender_session_labels_after_receipt_gc_hit_stream_quota() { + let f = Fixture::new(); + f.receive(1, 1); + let delivery = f.deliver(); + f.store + .adopt(&delivery) + .expect("test: fresh_sender_session_labels_after_receipt_gc_hit_stream_quota: adopt succeeds"); + drop(delivery); + f.clock.advance(604801); + f.store + .gc_scope(&f.recipient) + .expect("test: fresh_sender_session_labels_after_receipt_gc_hit_stream_quota: gc_scope succeeds"); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), + 0, + "fresh sender session labels after receipt gc hit stream quota: capacity enforcement or bounded delivery changed" + ); + // Populate the remaining bounded tombstone inventory from the real retired + // row; no messages/receipts remain to provide accidental quota coverage. + f.memory.pool.write().execute_batch("WITH RECURSIVE n(v) AS (SELECT 1 UNION ALL SELECT v+1 FROM n WHERE v<4095) INSERT INTO prx_mailbox_seq(workspace_id,owner_id,sender_ma_scope_id,sender_incarnation,sender_generation,recipient_ma_scope_id,recipient_incarnation,recipient_generation,from_addr,to_addr,wire_stream_id,state,progress,updated_at) SELECT workspace_id,owner_id,sender_ma_scope_id,sender_incarnation,sender_generation,recipient_ma_scope_id,recipient_incarnation,recipient_generation,json_set(from_addr,'$.session','retired-'||v),to_addr,randomblob(16),state,progress,updated_at FROM prx_mailbox_seq,n WHERE stream_id=1;").expect("test: fresh_sender_session_labels_after_receipt_gc_hit_stream_quota: fixture setup succeeds"); + let mut source = f.source.clone(); + source.session = "fresh-sender-label".into(); + let authority = MailboxAuthority::local(W.into(), source, f.target.clone()).expect( + "test: fresh_sender_session_labels_after_receipt_gc_hit_stream_quota: MailboxAuthority::local succeeds", + ); + let mut message = f.message(2, 1); + message.stream_id = Some(Uuid::new_v4()); + message.to_pin = f + .store + .recipient_pin(&authority, &f.recipient, "canonical-target") + .expect("test: fresh_sender_session_labels_after_receipt_gc_hit_stream_quota: recipient_pin succeeds"); + assert_eq!( + f.store.accept(&authority, message).unwrap_err(), + MailboxError::Quota("streams"), + "fresh sender session labels after receipt gc hit stream quota: capacity enforcement or bounded delivery changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_seq"), + 4096, + "fresh sender session labels after receipt gc hit stream quota: capacity enforcement or bounded delivery changed" + ); +} + +#[tokio::test] +async fn child_message_reaches_main_mailbox() { + use crate::chat::sessions::child::{ChildSession, ChildSessionRegistry}; + let mut f = Fixture::new(); + let registry = ChildSessionRegistry::new(Arc::new(f.memory.clone())).with_workspace(W.into()); + registry + .insert(&ChildSession::new(f.source.clone(), None)) + .await + .expect("test: child_message_reaches_main_mailbox: insert succeeds"); + let child = registry + .reconstruct(&f.source) + .await + .expect("test: child_message_reaches_main_mailbox: reconstruct succeeds"); + f.sender = child + .mailbox_scope() + .expect("test: child_message_reaches_main_mailbox: mailbox_scope succeeds") + .clone(); + let provisional = f.message(1, 0); + f.store + .publish(&f.authority, provisional, &f.sender, f.clock.now() + 300, None) + .expect("test: child_message_reaches_main_mailbox: publish succeeds"); + let outgoing = f + .store + .pending_outbox(&f.sender, &f.source) + .expect("test: child_message_reaches_main_mailbox: pending_outbox succeeds"); + f.store + .accept(&f.authority, outgoing[0].message().clone()) + .expect("test: child_message_reaches_main_mailbox: accept succeeds"); + let delivery = f.deliver(); + let receipt = f + .store + .adopt(&delivery) + .expect("test: child_message_reaches_main_mailbox: adopt succeeds"); + assert_eq!( + receipt.state, + DeliveryState::Consumed, + "child message reaches main mailbox: expected messaging contract changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM conversation_turns"), + 1, + "child message reaches main mailbox: expected messaging contract changed" + ); +} + +#[tokio::test] +async fn sibling_message_is_owner_scoped() { + use crate::chat::sessions::child::{ChildSession, ChildSessionRegistry}; + let f = Fixture::new(); + let registry = ChildSessionRegistry::new(Arc::new(f.memory.clone())).with_workspace(W.into()); + for address in [&f.source, &f.target] { + registry + .insert(&ChildSession::new(address.clone(), None)) + .await + .expect("test: sibling_message_is_owner_scoped: insert succeeds"); + } + let target = registry + .reconstruct(&f.target) + .await + .expect("test: sibling_message_is_owner_scoped: reconstruct succeeds"); + let scope = target + .mailbox_scope() + .expect("test: sibling_message_is_owner_scoped: mailbox_scope succeeds") + .clone(); + let canonical = ChildSessionRegistry::canonical_session_key(&f.target) + .expect("test: sibling_message_is_owner_scoped: ChildSessionRegistry::canonical_session_key succeeds"); + let mut message = f.message(1, 1); + message.to_pin = f + .store + .recipient_pin(&f.authority, &scope, &canonical) + .expect("test: sibling_message_is_owner_scoped: recipient_pin succeeds"); + f.store + .accept(&f.authority, message.clone()) + .expect("test: sibling_message_is_owner_scoped: accept succeeds"); + let mut foreign = f.source.clone(); + foreign.owner = "other-owner".into(); + assert!( + matches!( + MailboxAuthority::local(W.into(), foreign, f.target.clone()), + Err(MailboxError::Unauthorized) + ), + "sibling message is owner scoped: recipient authority or scope isolation changed" + ); + let mut foreign_target = f.target.clone(); + foreign_target.owner = "other-owner".into(); + message.to = foreign_target; + assert_eq!( + f.store.accept(&f.authority, message).unwrap_err(), + MailboxError::Unauthorized, + "sibling message is owner scoped: recipient authority or scope isolation changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), + 1, + "sibling message is owner scoped: recipient authority or scope isolation changed" + ); +} + +#[tokio::test] +async fn child_sessions_migration_22_preserves_records_and_quarantines_unbound_rows() { + use crate::chat::sessions::child::{ChildSession, ChildSessionRegistry}; + use crate::memory::child_sessions::{ChildSessionContext, ChildSessionError, ChildSessionStore}; + let f = Fixture::new(); + let registry = ChildSessionRegistry::new(Arc::new(f.memory.clone())).with_workspace(W.into()); + registry + .insert(&ChildSession::new(f.target.clone(), None)) + .await + .expect("test: child_sessions_migration_22_preserves_records_and_quarantines_unbound_rows: insert succeeds"); + let key = ChildSessionRegistry::canonical_session_key(&f.target) + .expect("test: child_sessions_migration_22_preserves_records_and_quarantines_unbound_rows: ChildSessionRegistry::canonical_session_key succeeds"); + let context = ChildSessionContext { + workspace_id: W.into(), + addr: f.target.clone(), + }; + let original = f + .memory + .pool + .write() + .query_row("SELECT record FROM child_sessions WHERE key=?1", [&key], |r| { + r.get::<_, String>(0) + }) + .expect("test: child_sessions_migration_22_preserves_records_and_quarantines_unbound_rows: query_row succeeds"); + f.memory.pool.write().execute("UPDATE child_sessions SET workspace_id=NULL,owner_id=NULL,instance_id=NULL,session_id=NULL,agent_key=NULL,ma_scope_id=NULL,incarnation=NULL,generation=NULL WHERE key=?1",[&key]).expect("test: child_sessions_migration_22_preserves_records_and_quarantines_unbound_rows: fixture setup succeeds"); + let refused = match ChildSessionStore::load(&f.memory, &key, &context) { + Ok(_) => panic!("quarantined legacy row loaded"), + Err(error) => error, + }; + assert!( + refused.is::(), + "child sessions migration 22 preserves records and quarantines unbound rows: capacity enforcement or bounded delivery changed" + ); + let recovered = + ChildSessionStore::update(&f.memory, &key, &context, &mut |old| Ok(old.expect("test: child_sessions_migration_22_preserves_records_and_quarantines_unbound_rows: fixture setup succeeds").to_owned())).expect("test: child_sessions_migration_22_preserves_records_and_quarantines_unbound_rows: ChildSessionStore::update succeeds"); + assert_eq!( + recovered.record, original, + "child sessions migration 22 preserves records and quarantines unbound rows: capacity enforcement or bounded delivery changed" + ); + drop(recovered); + // A partially populated row is never a backfill candidate. + f.memory + .pool + .write() + .execute("UPDATE child_sessions SET generation=NULL WHERE key=?1", [&key]) + .expect("test: child_sessions_migration_22_preserves_records_and_quarantines_unbound_rows: execute succeeds"); + assert!( + ChildSessionStore::update(&f.memory, &key, &context, &mut |_| Ok(original.clone())).is_err(), + "child sessions migration 22 preserves records and quarantines unbound rows: capacity enforcement or bounded delivery changed" + ); + assert_eq!( + f.memory + .pool + .write() + .query_row("SELECT record FROM child_sessions WHERE key=?1", [&key], |r| r + .get::<_, String>(0)) + .expect( + "test: child_sessions_migration_22_preserves_records_and_quarantines_unbound_rows: query_row succeeds" + ), + original, + "child sessions migration 22 preserves records and quarantines unbound rows: capacity enforcement or bounded delivery changed" + ); +} + +#[test] +fn mailbox_index_plans_use_scope_and_stream_prefixes() { + let f = Fixture::new(); + let writer = f.memory.pool.write(); + for (query, index) in [ + ( + "SELECT message_id FROM prx_mailbox_receipts WHERE ma_scope_id='scope' AND expires_at>=0", + "mailbox_receipt_scope_expiry", + ), + ( + "SELECT id FROM prx_mailbox_messages WHERE stream_id=1 AND state=0 AND seq>x'0000000000000000' ORDER BY seq", + "mailbox_message_delivery", + ), + ( + "SELECT id FROM prx_mailbox_outbox WHERE stream_id=1 AND state=0 ORDER BY seq", + "mailbox_outbox_delivery", + ), + ( + "SELECT stream_id FROM prx_mailbox_seq WHERE recipient_ma_scope_id='scope'", + "mailbox_seq_recipient", + ), + ( + "SELECT key FROM child_sessions WHERE ma_scope_id='scope'", + "child_sessions_scope", + ), + ] { + let mut statement = writer + .prepare(&format!("EXPLAIN QUERY PLAN {query}")) + .expect("test: mailbox_index_plans_use_scope_and_stream_prefixes: prepare succeeds"); + let details = statement + .query_map([], |r| r.get::<_, String>(3)) + .expect("test: mailbox_index_plans_use_scope_and_stream_prefixes: query_map succeeds") + .collect::>>() + .expect("test: mailbox_index_plans_use_scope_and_stream_prefixes: collect succeeds") + .join(" "); + assert!(details.contains(index), "{query}: {details}"); + if index == "mailbox_receipt_scope_expiry" { + assert!( + details.contains("COVERING"), + "id-reuse probe must not load receipt bodies: {details}" + ); + } + } +} + +#[test] +fn mailbox_u64_sequence_exhaustion_never_wraps_or_truncates() { + let f = Fixture::new(); + f.store + .publish(&f.authority, f.message(1, 0), &f.sender, f.clock.now() + 300, None) + .expect("test: mailbox_u64_sequence_exhaustion_never_wraps_or_truncates: publish succeeds"); + let progress = f + .memory + .pool + .write() + .query_row("SELECT progress FROM prx_mailbox_seq", [], |r| r.get::<_, String>(0)) + .expect("test: mailbox_u64_sequence_exhaustion_never_wraps_or_truncates: query_row succeeds"); + let progress = progress.replacen("\"next_seq\":2", &format!("\"next_seq\":{}", u64::MAX), 1); + f.memory + .pool + .write() + .execute("UPDATE prx_mailbox_seq SET progress=?1", [progress]) + .expect("test: mailbox_u64_sequence_exhaustion_never_wraps_or_truncates: execute succeeds"); + let last = f + .store + .publish(&f.authority, f.message(2, 0), &f.sender, f.clock.now() + 300, None) + .expect("test: mailbox_u64_sequence_exhaustion_never_wraps_or_truncates: publish succeeds"); + assert_eq!( + last.seq, + u64::MAX, + "mailbox u64 sequence exhaustion never wraps or truncates: expected messaging contract changed" + ); + assert_eq!( + f.store + .publish(&f.authority, f.message(3, 0), &f.sender, f.clock.now() + 300, None) + .unwrap_err(), + MailboxError::Quota("seq"), + "mailbox u64 sequence exhaustion never wraps or truncates: expected messaging contract changed" + ); + let raw = f + .memory + .pool + .write() + .query_row( + "SELECT hex(seq) FROM prx_mailbox_outbox WHERE id=?1", + [last.row_id], + |r| r.get::<_, String>(0), + ) + .expect("test: mailbox_u64_sequence_exhaustion_never_wraps_or_truncates: fixture setup succeeds"); + assert_eq!( + raw, "FFFFFFFFFFFFFFFF", + "mailbox u64 sequence exhaustion never wraps or truncates: expected messaging contract changed" + ); +} + +#[tokio::test] +async fn process_worker_message_frame_roundtrips() { + use crate::session_worker::protocol::{WorkerControlFrame, WorkerOutputFrame}; + let f = Fixture::new(); + let published = f + .store + .publish(&f.authority, f.message(1, 0), &f.sender, f.clock.now() + 300, None) + .expect("test: process_worker_message_frame_roundtrips: publish succeeds"); + let outgoing = f + .store + .pending_outbox(&f.sender, &f.source) + .expect("test: process_worker_message_frame_roundtrips: pending_outbox succeeds"); + let message = outgoing + .first() + .expect("test: process_worker_message_frame_roundtrips: first succeeds") + .message() + .clone(); + f.store + .accept(&f.authority, message.clone()) + .expect("test: process_worker_message_frame_roundtrips: accept succeeds"); + let delivered = f.deliver(); + let frame = WorkerControlFrame::Message { + envelope: Box::new(delivered.message().clone()), + }; + let decoded: WorkerControlFrame = serde_json::from_slice( + &serde_json::to_vec(&frame) + .expect("test: process_worker_message_frame_roundtrips: serde_json::to_vec succeeds"), + ) + .expect("test: process_worker_message_frame_roundtrips: serde_json::from_slice succeeds"); + let (mut sender, mut inbox) = crate::session_worker::mailbox::worker_mailbox(f.target.clone(), "run-target".into()) + .expect("test: process_worker_message_frame_roundtrips: mailbox::worker_mailbox succeeds"); + let (sender, ack) = tokio::task::spawn_blocking(move || { + let WorkerControlFrame::Message { envelope } = decoded else { + panic!("Data frame became another control kind"); + }; + let ack = sender + .enqueue(*envelope) + .expect("test: process_worker_message_frame_roundtrips: enqueue succeeds"); + (sender, ack) + }) + .await + .expect("test: process_worker_message_frame_roundtrips: task::spawn_blocking succeeds"); + assert_eq!( + ack, + WorkerOutputFrame::Ack { + message_id: published.message_id, + state: DeliveryState::Delivered + }, + "process worker message frame roundtrips: IPC identity or delivery state changed" + ); + let queued = inbox + .try_next() + .expect("test: process_worker_message_frame_roundtrips: try_next succeeds"); + assert_eq!( + crate::session_worker::mailbox::user_text(&queued) + .expect("test: process_worker_message_frame_roundtrips: mailbox::user_text succeeds"), + "request-1", + "process worker message frame roundtrips: IPC identity or delivery state changed" + ); + let consumed = inbox + .consumed(&queued) + .expect("test: process_worker_message_frame_roundtrips: consumed succeeds"); + let saved = f + .store + .adopt(&delivered) + .expect("test: process_worker_message_frame_roundtrips: adopt succeeds"); + assert_eq!( + consumed, + WorkerOutputFrame::Ack { + message_id: saved.message_id, + state: saved.state + }, + "process worker message frame roundtrips: IPC identity or delivery state changed" + ); + let duplicate = tokio::task::spawn_blocking(move || { + let mut sender = sender; + sender + .enqueue(message) + .expect("test: process_worker_message_frame_roundtrips: enqueue succeeds") + }) + .await + .expect("test: process_worker_message_frame_roundtrips: task::spawn_blocking succeeds"); + assert_eq!( + duplicate, ack, + "a pruned worker slot may requeue a transport replay; durable adoption remains idempotent" + ); + assert!( + inbox.try_next().is_some(), + "process worker message frame roundtrips: IPC identity or delivery state changed" + ); + assert_eq!( + f.store + .adopt(&delivered) + .expect("test: process_worker_message_frame_roundtrips: adopt succeeds"), + saved, + "process worker message frame roundtrips: IPC identity or delivery state changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM conversation_turns"), + 1, + "process worker message frame roundtrips: IPC identity or delivery state changed" + ); +} + +#[test] +fn worker_data_reaches_parent_mailbox() { + use crate::session_worker::protocol::WorkerOutputFrame; + let f = Fixture::new(); + // This worker is the source endpoint; the destination parent is bound by + // its real MA scope and an HMAC recipient pin, not by asserted frame.from. + let parent_key = crate::chat::sessions::child::ChildSessionRegistry::canonical_session_key(&f.target) + .expect("test: canonical parent key"); + f.memory + .pool + .write() + .execute( + "UPDATE agent_scopes SET session_key=?1 WHERE scope_id=?2", + params![parent_key, f.recipient.scope_id.to_string()], + ) + .expect("test: bind parent canonical scope"); + let mut parent = crate::session_worker::mailbox_parent::WorkerMailboxParent::new( + f.store.clone(), + f.source.clone(), + f.sender.clone(), + f.target.clone(), + f.recipient.clone(), + "run-source".into(), + None, + ) + .expect("test: worker_data_reaches_parent_mailbox: WorkerMailboxParent::new succeeds"); + let mut message = f.message(1, 0); + message.to_pin.token.clear(); + message.from = SessionAddr::new("forged-instance", "forged-owner", "forged-session", None); + let receipt = parent + .receive(WorkerOutputFrame::Message { + envelope: Box::new(message.clone()), + }) + .expect("test: worker_data_reaches_parent_mailbox: receive succeeds") + .expect("test: worker_data_reaches_parent_mailbox: receive returns a value"); + assert_eq!( + receipt.state, + DeliveryState::Accepted, + "worker data reaches parent mailbox: IPC identity or delivery state changed" + ); + assert_eq!( + receipt.seq, 1, + "worker data reaches parent mailbox: IPC identity or delivery state changed" + ); + let duplicate = parent + .receive(WorkerOutputFrame::Message { + envelope: Box::new(message), + }) + .expect("test: worker_data_reaches_parent_mailbox: receive succeeds") + .expect("test: worker_data_reaches_parent_mailbox: receive returns a value"); + assert_eq!( + duplicate, receipt, + "worker data reaches parent mailbox: IPC identity or delivery state changed" + ); + let delivered = f.deliver(); + assert_eq!( + delivered.message().from, + f.source, + "worker data reaches parent mailbox: IPC identity or delivery state changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_messages"), + 1, + "worker data reaches parent mailbox: IPC identity or delivery state changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_outbox"), + 1, + "worker data reaches parent mailbox: IPC identity or delivery state changed" + ); +} + +#[test] +fn worker_data_keeps_sealed_provenance_and_cannot_reset_parent() { + use crate::session_worker::protocol::WorkerOutputFrame; + let f = Fixture::new(); + let parent_key = crate::chat::sessions::child::ChildSessionRegistry::canonical_session_key(&f.target) + .expect("test: canonical parent key"); + f.memory + .pool + .write() + .execute( + "UPDATE agent_scopes SET session_key=?1 WHERE scope_id=?2", + params![parent_key, f.recipient.scope_id.to_string()], + ) + .expect("test: bind parent canonical scope"); + let mut remote = f.source.clone(); + remote.instance = "prx-peer".into(); + let peer = MailboxAuthority::verified_peer( + W.into(), + remote, + f.target.clone(), + crate::messaging::MessageAuth { + issuer: "prx-issuer".into(), + subject: "prx-peer".into(), + method: "mtls".into(), + }, + ) + .expect( + "test: worker_data_keeps_sealed_provenance_and_cannot_reset_parent: MailboxAuthority::verified_peer succeeds", + ); + let mut root = f.message(1, 1); + root.to_pin = f + .store + .recipient_pin(&peer, &f.recipient, &parent_key) + .expect("test: worker_data_keeps_sealed_provenance_and_cannot_reset_parent: recipient_pin succeeds"); + let accepted = f + .store + .accept(&peer, root) + .expect("test: worker_data_keeps_sealed_provenance_and_cannot_reset_parent: accept succeeds"); + let inherited = crate::messaging::InheritedProvenance { + remote: accepted.remote.expect( + "test: worker_data_keeps_sealed_provenance_and_cannot_reset_parent: required fixture value is present", + ), + chain: accepted.chain, + }; + let mut actor = crate::session_worker::mailbox_parent::WorkerMailboxParent::new( + f.store.clone(), + f.source.clone(), + f.sender.clone(), + f.target.clone(), + f.recipient.clone(), + "run-source".into(), + Some(inherited.clone()), + ) + .expect("test: worker_data_keeps_sealed_provenance_and_cannot_reset_parent: WorkerMailboxParent::new succeeds"); + let forged_root = f.message(2, 0); + assert!( + forged_root.in_reply_to.is_none(), + "worker data keeps sealed provenance and cannot reset parent: IPC identity or delivery state changed" + ); + let receipt = actor + .receive(WorkerOutputFrame::Message { + envelope: Box::new(forged_root), + }) + .expect("test: worker_data_keeps_sealed_provenance_and_cannot_reset_parent: receive succeeds") + .expect("test: worker_data_keeps_sealed_provenance_and_cannot_reset_parent: receive returns a value"); + assert_eq!( + receipt.chain.ancestry, + vec![inherited.chain.trigger], + "worker data keeps sealed provenance and cannot reset parent: IPC identity or delivery state changed" + ); + assert_eq!( + receipt.remote, + Some(inherited.remote), + "worker data keeps sealed provenance and cannot reset parent: IPC identity or delivery state changed" + ); +} + +#[test] +fn permanent_seq_gap_nacks_reachable_sender_outbox() { + let f = Fixture::new(); + let first = f.message(1, 0); + f.store + .publish(&f.authority, first.clone(), &f.sender, f.clock.now() + 300, None) + .expect("test: permanent_seq_gap_nacks_reachable_sender_outbox: publish succeeds"); + let second = f + .store + .publish(&f.authority, f.message(2, 0), &f.sender, f.clock.now() + 300, None) + .expect("test: permanent_seq_gap_nacks_reachable_sender_outbox: publish succeeds"); + let pending = f + .store + .pending_outbox(&f.sender, &f.source) + .expect("test: permanent_seq_gap_nacks_reachable_sender_outbox: pending_outbox succeeds"); + let message = pending + .iter() + .find(|item| item.message().id == second.message_id) + .expect("test: permanent_seq_gap_nacks_reachable_sender_outbox: find succeeds") + .message() + .clone(); + drop(pending); + f.store + .accept(&f.authority, message) + .expect("test: permanent_seq_gap_nacks_reachable_sender_outbox: accept succeeds"); + assert!( + f.store + .deliver(&f.recipient, &f.target) + .expect("test: permanent_seq_gap_nacks_reachable_sender_outbox: deliver succeeds") + .is_none(), + "permanent seq gap nacks reachable sender outbox: expected messaging contract changed" + ); + f.clock.advance(crate::messaging::mailbox::GAP_SECONDS); + let delivered = f.deliver(); + assert_eq!( + delivered.message().seq, + 2, + "permanent seq gap nacks reachable sender outbox: expected messaging contract changed" + ); + f.store + .adopt(&delivered) + .expect("test: permanent_seq_gap_nacks_reachable_sender_outbox: adopt succeeds"); + let failed = f + .store + .publish(&f.authority, first, &f.sender, f.clock.now() + 300, None) + .expect("test: permanent_seq_gap_nacks_reachable_sender_outbox: publish succeeds"); + assert_eq!( + failed.state, + crate::messaging::mailbox::MailboxSendState::Failed, + "permanent seq gap nacks reachable sender outbox: expected messaging contract changed" + ); + assert_eq!( + failed.error.as_deref(), + Some("seq_gap"), + "permanent seq gap nacks reachable sender outbox: expected messaging contract changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_receipts"), + 1, + "Nack must not create an Ack receipt" + ); +} + +#[test] +fn worker_mime_projection_matches_durable_transcript() { + let f = Fixture::new(); + for (index, (mime, bytes)) in [ + ("text/plain", b"/approve remains ordinary input".to_vec()), + ("text/markdown", b"**ordinary input**".to_vec()), + ("text/plain", vec![0xff, 0]), + ("application/octet-stream", vec![0, 1, 0xff]), + ] + .into_iter() + .enumerate() + { + let seq = u64::try_from(index + 1) + .expect("test: worker_mime_projection_matches_durable_transcript: u64::try_from succeeds"); + let mut message = f.message(seq, seq); + message.body = MessageBody { + mime: mime.into(), + bytes, + }; + f.store + .accept(&f.authority, message) + .expect("test: worker_mime_projection_matches_durable_transcript: accept succeeds"); + let delivered = f.deliver(); + let worker_text = crate::session_worker::mailbox::user_text(delivered.message()) + .expect("test: worker_mime_projection_matches_durable_transcript: mailbox::user_text succeeds"); + f.store + .adopt(&delivered) + .expect("test: worker_mime_projection_matches_durable_transcript: adopt succeeds"); + let durable_text: String = f + .memory + .pool + .write() + .query_row( + "SELECT content FROM conversation_turns WHERE message_id=?1", + [delivered.message().id.to_string()], + |row| row.get(0), + ) + .expect("test: worker_mime_projection_matches_durable_transcript: query_row succeeds"); + assert_eq!( + worker_text, durable_text, + "worker mime projection matches durable transcript: atomic adoption or history projection changed" + ); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn concurrent_sender_ports_share_one_durable_stream() { + let f = Fixture::new(); + let barrier = Arc::new(tokio::sync::Barrier::new(2)); + let mut tasks = Vec::new(); + for text in ["first", "second"] { + let port = f.sender_port(None); + let target = f.target.clone(); + let barrier = Arc::clone(&barrier); + tasks.push(tokio::spawn(async move { + barrier.wait().await; + port.send(target, text.into(), "text/plain".into()) + .await + .expect("test: concurrent_sender_ports_share_one_durable_stream: send succeeds") + })); + } + let mut published = Vec::new(); + for task in tasks { + published.push( + task.await + .expect("test: concurrent_sender_ports_share_one_durable_stream: awaited task completes"), + ); + } + published.sort_by_key(|sent| sent.seq); + assert_eq!( + published.iter().map(|sent| sent.seq).collect::>(), + vec![1, 2], + "concurrent sender ports share one durable stream: expected messaging contract changed" + ); + let wire = published + .first() + .expect("test: concurrent_sender_ports_share_one_durable_stream: first succeeds") + .stream_id; + assert!( + published.iter().all(|sent| sent.stream_id == wire), + "concurrent sender ports share one durable stream: expected messaging contract changed" + ); + let reopened = f + .sender_port(None) + .send(f.target.clone(), "reopened port".into(), "text/plain".into()) + .await + .expect("test: concurrent_sender_ports_share_one_durable_stream: send succeeds"); + assert_eq!( + reopened.stream_id, wire, + "concurrent sender ports share one durable stream: expected messaging contract changed" + ); + assert_eq!( + reopened.seq, 3, + "concurrent sender ports share one durable stream: expected messaging contract changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_seq"), + 1, + "concurrent sender ports share one durable stream: expected messaging contract changed" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_outbox"), + 3, + "concurrent sender ports share one durable stream: expected messaging contract changed" + ); +} + +#[tokio::test] +async fn pending_send_resolver_keeps_payload_in_scope_until_cancel_join() { + struct PausedResolver { + inner: LocalResolver, + entered: parking_lot::Mutex>>, + release: tokio::sync::Notify, + } + #[async_trait::async_trait] + impl crate::messaging::send::MailboxResolver for PausedResolver { + async fn resolve( + &self, + target: &SessionAddr, + ) -> crate::messaging::mailbox::MailboxResult { + let resolved = crate::messaging::send::MailboxResolver::resolve(&self.inner, target).await?; + let entered = self.entered.lock().take(); + if let Some(entered) = entered { + let _ = entered.send(()); + } + self.release.notified().await; + Ok(resolved) + } + } + use crate::messaging::send::MailboxSender as _; + let f = Fixture::new(); + let (entered, ready) = tokio::sync::oneshot::channel(); + let resolver = Arc::new(PausedResolver { + inner: LocalResolver { + store: f.store.clone(), + authority: f.authority.clone(), + scope: f.recipient.clone(), + }, + entered: parking_lot::Mutex::new(Some(entered)), + release: tokio::sync::Notify::new(), + }); + let port = crate::memory::sqlite::mailbox::SqliteMailboxSender::new( + f.store.clone(), + f.source.clone(), + f.sender.clone(), + resolver, + None, + ) + .expect("test: resolve: SqliteMailboxSender::new succeeds"); + let target = f.target.clone(); + let sending = tokio::spawn(async move { + port.send(target, "pending scoped payload".into(), "text/plain".into()) + .await + }); + tokio::time::timeout(std::time::Duration::from_secs(10), ready) + .await + .expect("test: resolve: time::timeout succeeds") + .expect("test: resolve: time::timeout returns a value"); + let kept_payload_scope = f.memory.mailbox_runtime.has_scope_leases(f.sender.scope_id); + sending.abort(); + assert!( + sending.await.unwrap_err().is_cancelled(), + "pending resolver task must join after cancellation" + ); + assert!( + kept_payload_scope, + "queued send lost its body lease while resolver was pending" + ); + assert!( + !f.memory.mailbox_runtime.has_scope_leases(f.sender.scope_id), + "cancel join retained the send payload" + ); + let erased = f + .store + .erase_scope(&f.sender, Duration::from_secs(5), &|| Ok(())) + .expect("test: resolve: erase_scope succeeds"); + assert_eq!( + erased.remaining, 0, + "joining the cancelled resolver must allow complete scope erasure" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_outbox"), + 0, + "cancelled resolver must not persist an outbox body" + ); +} + +fn mailbox_parent(f: &Fixture) -> crate::session_worker::mailbox_parent::WorkerMailboxParent { + crate::session_worker::mailbox_parent::WorkerMailboxParent::new( + f.store.clone(), + f.target.clone(), + f.recipient.clone(), + f.source.clone(), + f.sender.clone(), + "run-target".into(), + None, + ) + .expect("test: construct persistent parent") +} + +fn stale_parent_releases_delivery_before_erase() { + use crate::session_worker::protocol::{WorkerControlFrame, WorkerOutputFrame}; + let f = Fixture::new(); + let mut parent = mailbox_parent(&f); + let mut message = f.message(1, 1); + message.exec = Some(ExecRef { + run: Some("run-target".into()), + }); + f.store + .accept(&f.authority, message) + .expect("test: accept pinned parent input"); + let Some(WorkerControlFrame::Message { envelope }) = parent.next_delivery().expect("test: parent delivery") else { + panic!("test: parent must hold the delivered input"); + }; + let ack = WorkerOutputFrame::Ack { + message_id: envelope.id, + state: DeliveryState::Consumed, + }; + drop(envelope); + f.store + .set_execution(&f.recipient, &f.target, Some("run-next".into())) + .expect("test: change parent run"); + let result = parent.receive(ack.clone()); + let repeated = parent.receive(ack); + // Quiesce the parent's execution cache but retain any leaked deliveries. + // The old early ? must still fail at the erase deadline, not a cache lease. + let pending = parent.into_pending(); + let erased = f + .store + .erase_scope(&f.recipient, Duration::from_millis(20), &|| Ok(())) + .expect("test: terminal parent adoption must release its lease before erase deadline"); + assert_eq!(erased.remaining, 0, "terminal parent input must be fully erased"); + assert!( + result.expect("test: stale parent Ack is harmless").is_none(), + "stale Ack must return no receipt" + ); + assert_eq!(pending.len(), 0, "terminal adoption retained a pending delivery"); + assert!( + repeated.expect("test: repeat stale Ack").is_none(), + "repeated Ack must be harmless" + ); +} + +#[test] +fn parent_terminal_adopt_errors_release_pending_and_retryable_errors_retain_it() { + for error in [ + MailboxError::ReceiptExpired, + MailboxError::Unauthorized, + MailboxError::Fenced, + MailboxError::IdentityImmutable, + MailboxError::ScopeErasing, + MailboxError::SeqConflict, + MailboxError::Storage, + MailboxError::CorruptState, + ] { + let f = Fixture::new(); + let mut parent = mailbox_parent(&f); + let message = f.message(1, 1); + let id = message.id; + f.store + .accept(&f.authority, message) + .expect("test: accept matrix input"); + parent + .next_delivery() + .expect("test: hold matrix input") + .expect("test: pending matrix frame"); + assert_eq!( + parent.pending_count(), + 1, + "matrix must start with a real delivery lease" + ); + let sql = match error { + MailboxError::ReceiptExpired => Some("DELETE FROM prx_mailbox_receipts"), + MailboxError::Unauthorized => Some( + "UPDATE prx_mailbox_receipts SET ma_scope_id='00000000-0000-0000-0000-00000000000a',receipt_meta=json_set(receipt_meta,'$.canonical_session_key','canonical-source')", + ), + MailboxError::IdentityImmutable => Some("UPDATE prx_mailbox_messages SET body_bytes=x'6368616e676564'"), + MailboxError::ScopeErasing => Some( + "INSERT INTO agent_erase_fences VALUES ('00000000-0000-0000-0000-000000000014','00000000-0000-0000-0000-000000000063','draining',2)", + ), + _ => None, + }; + let result = if let Some(sql) = sql { + f.memory + .pool + .write() + .execute(sql, []) + .expect("test: set terminal store condition"); + parent.receive(crate::session_worker::protocol::WorkerOutputFrame::Ack { + message_id: id, + state: DeliveryState::Consumed, + }) + } else { + // Fenced is no longer emitted by adopt after L7. Keep its parent + // policy covered, along with injected retryable storage outcomes. + parent.finish_adopt(id, Err(error.clone())) + }; + assert_eq!( + result.expect_err("test: propagate typed adopt error"), + error, + "parent changed the terminal error" + ); + let retryable = matches!( + error, + MailboxError::SeqConflict | MailboxError::Storage | MailboxError::CorruptState + ); + assert_eq!( + parent.pending_count(), + usize::from(retryable), + "wrong lease policy for {error:?}" + ); + assert_eq!( + f.memory.mailbox_runtime.has_leases(f.recipient.scope_id), + retryable, + "wrong runtime lease policy for {error:?}" + ); + } +} + +#[test] +fn parent_acknowledge_error_after_adopt_releases_pending() { + let f = Fixture::new(); + let mut parent = mailbox_parent(&f); + let message = f.message(1, 1); + let id = message.id; + f.store + .accept(&f.authority, message) + .expect("test: accept without local outbox"); + parent + .next_delivery() + .expect("test: deliver without outbox") + .expect("test: pending delivery"); + let error = parent + .receive(crate::session_worker::protocol::WorkerOutputFrame::Ack { + message_id: id, + state: DeliveryState::Consumed, + }) + .expect_err("test: acknowledge requires a sender outbox"); + assert_eq!( + error, + MailboxError::InvalidMetadata, + "adoption must finish before missing-outbox Ack fails" + ); + assert_eq!( + parent.pending_count(), + 0, + "committed adoption retained a pending lease after Ack error" + ); + assert!( + !f.memory.mailbox_runtime.has_leases(f.recipient.scope_id), + "Ack error retained the consumed body" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM prx_mailbox_receipts WHERE state=2"), + 1, + "Ack failure must follow committed adoption" + ); +} + +#[test] +fn consumed_then_erased_adopt_replays_saved_result() { + let f = Fixture::new(); + f.receive(1, 1); + let held = f.deliver(); + let saved = f.store.adopt(&held).expect("test: consume receipt before erasure"); + // Erasure normally joins the holder. Preserve this delivery solely to exercise replay. + f.memory + .pool + .write() + .execute( + "UPDATE prx_mailbox_receipts SET receipt_meta=json_set(receipt_meta,'$.body_erased_at',1000) WHERE id=?1", + [saved.row_id], + ) + .expect("test: mark consumed receipt erased"); + f.memory + .pool + .write() + .execute("DELETE FROM prx_mailbox_messages WHERE id=?1", [saved.row_id]) + .expect("test: remove consumed receipt body"); + let replay = f.store.adopt(&held).expect("test: replay erased consumed receipt"); + assert_eq!(replay, saved, "erasure must preserve the saved adoption checkpoint"); +} + +#[test] +fn erased_nonconsumed_replays_report_scope_erasing_when_fenced() { + let f = Fixture::new(); + let message = f.message(1, 1); + f.store + .accept(&f.authority, message.clone()) + .expect("test: accept fenced replay input"); + let held = f.deliver(); + { + let writer = f.memory.pool.write(); + writer + .execute( + "UPDATE prx_mailbox_receipts SET receipt_meta=json_set(receipt_meta,'$.body_erased_at',1000)", + [], + ) + .expect("test: erase replay body metadata"); + writer + .execute( + "INSERT INTO agent_erase_fences VALUES (?1,?2,'draining',2)", + params![f.recipient.scope_id.to_string(), Uuid::new_v4().to_string()], + ) + .expect("test: fence erased receipt scope"); + } + assert_eq!( + f.store + .accept(&f.authority, message) + .expect_err("test: replay fenced accept"), + MailboxError::ScopeErasing, + "fenced replay must report erasure instead of stale run" + ); + assert_eq!( + f.store.adopt(&held).expect_err("test: replay fenced adopt"), + MailboxError::ScopeErasing, + "fenced adoption must report erasure instead of stale run" + ); +} + +fn stale_slot_case(adopt_race: bool) { + if adopt_race { + stale_parent_releases_delivery_before_erase(); + } + let f = Fixture::new(); + let mut first = f.message(1, 0); + first.exec = Some(ExecRef { + run: Some("run-target".into()), + }); + let published = f + .store + .publish(&f.authority, first, &f.sender, i64::MAX, None) + .expect("test: publish run-pinned slot"); + f.store + .publish(&f.authority, f.message(2, 0), &f.sender, i64::MAX, None) + .expect("test: publish later unpinned slot"); + let outgoing = f + .store + .pending_outbox(&f.sender, &f.source) + .expect("test: load accepted work"); + for slot in &outgoing { + let accepted = f + .store + .accept(&f.authority, slot.message().clone()) + .expect("test: accept pending slot"); + f.store + .acknowledge(&f.sender, &f.target, slot.message().id, accepted.state) + .expect("test: acknowledge accepted work before the run changes"); + } + let replay = outgoing.first().expect("test: first published slot").message().clone(); + drop(outgoing); + let held = if adopt_race { + let held = f.deliver(); + f.store + .acknowledge(&f.sender, &f.target, held.message().id, DeliveryState::Delivered) + .expect("test: acknowledge delivery before the adoption race"); + Some(held) + } else { + None + }; + f.store + .set_execution(&f.recipient, &f.target, Some("run-next".into())) + .expect("test: switch recipient execution"); + if let Some(held) = held { + assert_eq!( + f.store.adopt(&held).expect_err("test: stale adoption is refused"), + MailboxError::StaleRun, + "run change must terminalize only the held slot" + ); + assert_eq!( + f.store.adopt(&held).expect_err("test: replay stale adoption"), + MailboxError::StaleRun, + "an erased stale receipt must replay its terminal outcome" + ); + drop(held); + } + let next = f.deliver(); + assert_eq!( + f.store + .accept(&f.authority, replay) + .expect_err("test: replay stale accept"), + MailboxError::StaleRun, + "re-accept must report the stale slot instead of its old delivery state" + ); + assert_eq!(next.message().seq, 2, "later accepted work must survive a stale run"); + assert_eq!( + f.store.adopt(&next).expect("test: adopt surviving slot").state, + DeliveryState::Consumed, + "later unpinned slot must reach its transcript" + ); + let writer = f.memory.pool.write(); + let (state, meta): (i64, String) = writer + .query_row( + "SELECT state,envelope_meta FROM prx_mailbox_outbox WHERE id=?1", + [published.row_id], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .expect("test: inspect local sender nack"); + assert_eq!(state, 3, "stale slot must terminate its local sender outbox"); + let failed: i64 = writer + .query_row("SELECT count(*) FROM prx_mailbox_outbox WHERE state=3", [], |row| { + row.get(0) + }) + .expect("test: inspect the single targeted nack"); + assert_eq!(failed, 1, "a stale run must nack only its own slot"); + let meta: serde_json::Value = serde_json::from_str(&meta).expect("test: decode nack metadata"); + assert_eq!( + meta.get("last_error").and_then(serde_json::Value::as_str), + Some("stale_run"), + "sender must see the one-slot stale_run nack" + ); + let live: i64 = writer + .query_row("SELECT count(*) FROM prx_mailbox_seq WHERE state=0", [], |row| { + row.get(0) + }) + .expect("test: inspect stream lifetime"); + assert_eq!(live, 1, "stale work must not retire the shared stream"); + let erased: i64 = writer.query_row("SELECT count(*) FROM prx_mailbox_receipts WHERE seq=?1 AND json_extract(receipt_meta,'$.body_erased_at') IS NOT NULL", [1u64.to_be_bytes().as_slice()],|row|row.get(0)) + .expect("test: inspect terminal receipt"); + assert_eq!( + erased, 1, + "stale payload must be erased in the terminal-slot transaction" + ); +} + +#[test] +fn stale_run_slot_is_nacked_and_later_unpinned_slots_still_deliver() { + stale_slot_case(false); +} + +#[test] +fn stale_run_during_adopt_is_nacked_and_later_unpinned_slots_still_deliver() { + stale_slot_case(true); +} + +#[test] +fn worker_run_and_parent_binding_survive_more_than_max_rows_frames() { + use crate::session_worker::protocol::{WorkerControlFrame, WorkerOutputFrame}; + const FRAMES: i64 = crate::messaging::mailbox::MAX_ROWS + 1; + let f = Fixture::new(); + let mut parent = crate::session_worker::mailbox_parent::WorkerMailboxParent::new( + f.store.clone(), + f.target.clone(), + f.recipient.clone(), + f.source.clone(), + f.sender.clone(), + "run-target".into(), + None, + ) + .expect("test: one persistent parent binding"); + let (mut sender, mut inbox) = crate::session_worker::mailbox::worker_mailbox(f.target.clone(), "run-target".into()) + .expect("test: one persistent worker inbox"); + f.store + .publish(&f.authority, f.message(1, 0), &f.sender, i64::MAX, None) + .expect("test: publish first long-lived worker frame"); + let deadline = std::time::Instant::now() + Duration::from_secs(240); + for index in 1..=FRAMES { + assert!( + std::time::Instant::now() < deadline, + "bounded long-lived worker regression exceeded deadline" + ); + let pending = f + .store + .pending_outbox(&f.sender, &f.source) + .expect("test: pending single slot"); + let message = pending.first().expect("test: one pending envelope").message().clone(); + f.store.accept(&f.authority, message).expect("test: accept next frame"); + drop(pending); + let WorkerControlFrame::Message { envelope } = parent + .next_delivery() + .expect("test: next parent delivery") + .expect("test: queued frame") + else { + panic!("test: parent produced non-Data control"); + }; + let delivered = sender + .enqueue(*envelope) + .expect("test: bounded inbox must not grow by run lifetime"); + parent.receive(delivered).expect("test: parent accepts delivered ack"); + let message = inbox.try_next().expect("test: one in-flight worker input"); + let consumed = inbox + .consumed(&message) + .expect("test: consume prunes the in-flight dedupe entry"); + parent + .receive(consumed.clone()) + .expect("test: parent must not fail after committed adoption"); + parent + .receive(consumed) + .expect("test: consumed acknowledgement replay is harmless"); + parent + .receive(WorkerOutputFrame::Ack { + message_id: message.id, + state: DeliveryState::Consumed, + }) + .expect("test: late acknowledgement remains idempotent"); + f.clock.advance(crate::messaging::mailbox::REPLAY_SECONDS + 1); + // Keep the stream live while expiring old ledger rows; only the + // worker's in-flight window, rather than durable storage quota, is tested. + if index < FRAMES { + let next = u64::try_from(index + 1).expect("test: bounded frame index"); + f.store + .publish(&f.authority, f.message(next, 0), &f.sender, i64::MAX, None) + .expect("test: publish next frame before retention GC"); + } + f.store + .gc_scope(&f.sender) + .expect("test: expire sender's durable replay records"); + f.store + .gc_scope(&f.recipient) + .expect("test: expire consumed receiver records"); + } +} diff --git a/src/memory/sqlite/tests/mailbox/section_3.rs b/src/memory/sqlite/tests/mailbox/section_3.rs new file mode 100644 index 000000000..cd1a52937 --- /dev/null +++ b/src/memory/sqlite/tests/mailbox/section_3.rs @@ -0,0 +1,76 @@ +#[tokio::test] +async fn erase_scope_deadline_preserves_fence_until_child_lease_drops() { + use crate::chat::sessions::child::{ChildSession, ChildSessionRegistry}; + let f = Fixture::new(); + let registry = ChildSessionRegistry::new(Arc::new(f.memory.clone())).with_workspace(W.into()); + registry + .insert(&ChildSession::new(f.target.clone(), None)) + .await + .expect("test: persist child session"); + let child = registry + .reconstruct(&f.target) + .await + .expect("test: hold reconstructed history lease"); + let scope = child.mailbox_scope().expect("test: reconstructed scope").clone(); + let store = f.store.clone(); + let pending_scope = scope.clone(); + let pending = + tokio::task::spawn_blocking(move || store.erase_scope(&pending_scope, Duration::from_millis(20), &|| Ok(()))); + let result = tokio::time::timeout(Duration::from_secs(5), pending) + .await + .expect("test: erase wait has a hard deadline") + .expect("test: erase task joins"); + assert_eq!( + result.expect_err("test: retained child history cannot be erased"), + MailboxError::Fenced, + "incomplete quiescence must return history_pending" + ); + assert_eq!( + f.scalar("SELECT count(*) FROM agent_erase_fences WHERE state='draining'"), + 1, + "timeout must keep the durable erasure fence in place" + ); + drop(child); + let erased = f + .store + .erase_scope(&scope, Duration::from_secs(5), &|| Ok(())) + .expect("test: retry after holder joins"); + assert_eq!( + erased.remaining, 0, + "released history lease must allow complete erasure" + ); +} + +#[test] +fn mailbox_wire_errors_and_unacknowledged_result_preserve_contract() { + use crate::messaging::mailbox::{MailboxPublished, MailboxSendState}; + for (error, code) in [ + (MailboxError::PinRequired, "recipient_pin_required"), + (MailboxError::InvalidPin, "pin_invalid"), + (MailboxError::PinExpired, "pin_invalid"), + (MailboxError::ScopeErasing, "scope_erasing"), + (MailboxError::Fenced, "history_pending"), + ] { + assert_eq!( + error.to_string(), + code, + "wire error must distinguish authority, admission fence and erase retry" + ); + } + for state in [MailboxSendState::Pending, MailboxSendState::Failed] { + let result = crate::messaging::send::send_result(Ok(MailboxPublished { + row_id: 1, + message_id: Uuid::from_u128(1), + stream_id: Uuid::from_u128(STREAM), + seq: 1, + state, + ack_state: None, + error: None, + })); + assert_eq!( + result.get("state"), + Some(&serde_json::Value::Null), + "without an Ack the result must not claim accepted delivery" + ); + } +} diff --git a/src/messaging/a2a/cli.rs b/src/messaging/a2a/cli.rs new file mode 100644 index 000000000..2a45982cc --- /dev/null +++ b/src/messaging/a2a/cli.rs @@ -0,0 +1,174 @@ +//! Explicit identity initialization and pinned peer grant management. +use anyhow::{Result, ensure}; +use clap::Subcommand; + +#[derive(Debug, Subcommand)] +pub enum A2aCommand { + /// Create the persisted instance identity, or rotate its Ed25519 key. + Init { + #[arg(long)] + rotate: bool, + /// Stage a new identity so peers can pre-pin it before activation. + #[arg(long, conflicts_with = "rotate")] + prepare_rotate: bool, + }, + Peer { + #[command(subcommand)] + command: PeerCommand, + }, +} +#[derive(Debug, Subcommand)] +pub enum PeerCommand { + Add { + name: String, + #[arg(long)] + spiffe: String, + #[arg(long)] + fingerprint: String, + #[arg(long)] + address: String, + #[arg(long)] + owner: Option, + #[arg(long = "session", default_value = "*")] + sessions: Vec, + #[arg(long = "agent", default_value = "*")] + agents: Vec, + }, + List, + Remove { + name: String, + #[arg(long)] + fingerprint: Option, + }, +} +pub async fn run(command: A2aCommand, mut config: crate::config::Config) -> Result { + let original = config.clone(); + match command { + A2aCommand::Init { rotate, prepare_rotate } => { + let identity = if prepare_rotate { + super::identity::prepare_rotation(&config)? + } else { + super::identity::init(&config, rotate)? + }; + Ok(format!( + "{}\nfingerprint {}\nexpires {}", + identity.spiffe_id, identity.fingerprint, identity.expires_at + )) + } + A2aCommand::Peer { + command: PeerCommand::List, + } => { + let local = super::identity::load(&config)?; + let mut rows = vec![format!("local {} expires {}", local.spiffe_id, local.expires_at)]; + let mut peers: Vec<_> = config.a2a.peers.iter().collect(); + peers.sort_by_key(|(name, _)| *name); + for (name, peer) in peers { + let expires = super::tls::peer_expiry(&config, peer).await.map_or_else( + |_| "unavailable (peer unreachable or refused)".into(), + |expiry| expiry.to_string(), + ); + rows.push(format!( + "{name} {} {} owner={} expires={expires} fingerprints={}", + peer.spiffe_id, + peer.address, + peer.owner, + peer.fingerprints + .iter() + .map(|value| value.get(..16).unwrap_or(value)) + .collect::>() + .join(",") + )); + } + Ok(rows.join("\n")) + } + A2aCommand::Peer { + command: + PeerCommand::Add { + name, + spiffe, + fingerprint, + address, + owner, + sessions, + agents, + }, + } => { + let local = super::identity::load(&config)?; + super::peers::instance(&spiffe)?; + ensure!( + spiffe != local.spiffe_id && fingerprint != local.fingerprint, + "local identity cannot be a peer" + ); + ensure!( + !name.is_empty() + && name.len() <= 128 + && name + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_')), + "invalid peer name" + ); + let owner = owner.unwrap_or_else(|| { + crate::runtime::envelope::RuntimeEnvelope::chat_canonical( + config.workspace_dir.to_string_lossy().into_owned(), + "peer-management", + crate::memory::MemoryVisibility::Workspace, + ) + .resolved_owner_id() + }); + let mut fingerprints = vec![fingerprint.clone()]; + if let Some(old) = config.a2a.peers.get(&name) { + ensure!( + old.spiffe_id == spiffe, + "remove existing peer before changing its identity" + ); + fingerprints = old.fingerprints.clone(); + if !fingerprints.contains(&fingerprint) { + fingerprints.push(fingerprint); + } + } + config.a2a.peers.insert( + name, + crate::config::A2aPeer { + spiffe_id: spiffe, + fingerprints, + address, + owner, + sessions, + agents, + }, + ); + config.a2a.validate()?; + persist(original, config).await?; + Ok("Peer grant saved; both instances must pin each other.".into()) + } + A2aCommand::Peer { + command: PeerCommand::Remove { name, fingerprint }, + } => { + if let Some(fingerprint) = fingerprint { + let peer = config + .a2a + .peers + .get_mut(&name) + .ok_or_else(|| anyhow::anyhow!("peer not found"))?; + peer.fingerprints.retain(|value| value != &fingerprint); + if peer.fingerprints.is_empty() { + config.a2a.peers.remove(&name); + } + } else { + ensure!(config.a2a.peers.remove(&name).is_some(), "peer not found"); + } + config.a2a.validate()?; + persist(original, config).await?; + Ok("Peer grant removed; live connections will close.".into()) + } + } +} + +async fn persist(before: crate::config::Config, after: crate::config::Config) -> Result<()> { + use crate::config::manage::{ConfigActor, ManagementService}; + let service = ManagementService::deferred(crate::config::new_shared(before)); + let plan = service.plan_candidate(after, None, ConfigActor::Cli).await?; + let revision = plan.revision().map(str::to_owned); + service.apply(plan, ConfigActor::Cli, revision.as_deref()).await?; + Ok(()) +} diff --git a/src/messaging/a2a/clients.rs b/src/messaging/a2a/clients.rs new file mode 100644 index 000000000..afa90c15b --- /dev/null +++ b/src/messaging/a2a/clients.rs @@ -0,0 +1,98 @@ +//! One revocable HTTP client per pinned peer and local key generation. +use super::{ + identity, + tls::{self, Trust}, +}; +use crate::config::A2aPeer; +use anyhow::Result; +use parking_lot::Mutex; +use std::{collections::HashMap, sync::Arc, time::Duration}; +use tokio_util::sync::CancellationToken; +#[derive(Clone)] +pub(crate) struct Clients { + trust: Trust, + entries: Arc>>, + states: Arc>>, +} +struct Entry { + peer: A2aPeer, + local_fingerprint: String, + client: reqwest::Client, + cancellation: CancellationToken, +} +impl Clients { + pub(crate) fn new(trust: Trust) -> Self { + Self { + trust, + entries: Default::default(), + states: Default::default(), + } + } + pub(crate) fn get(&self, peer: &A2aPeer) -> Result<(reqwest::Client, CancellationToken)> { + let local = identity::load(&self.trust.config)?; + let mut entries = self.entries.lock(); + if let Some(entry) = entries.get(&peer.spiffe_id) { + if same(&entry.peer, peer) && entry.local_fingerprint == local.fingerprint { + return Ok((entry.client.clone(), entry.cancellation.clone())); + } + entry.cancellation.cancel(); + } + let client = tls::client(self.trust.clone(), peer)?; + let cancellation = CancellationToken::new(); + entries.insert( + peer.spiffe_id.clone(), + Entry { + peer: peer.clone(), + local_fingerprint: local.fingerprint, + client: client.clone(), + cancellation: cancellation.clone(), + }, + ); + Ok((client, cancellation)) + } + pub(crate) fn monitor(&self) -> tokio_util::sync::DropGuard { + let stop = CancellationToken::new(); + let guard = stop.clone().drop_guard(); + let cache = self.clone(); + tokio::spawn(async move { + let mut interval = tokio::time::interval(Duration::from_millis(250)); + loop { + tokio::select! { + ()=stop.cancelled()=>break, + _=interval.tick()=> { + let config=cache.trust.current();let local=identity::load(&cache.trust.config); + cache.states.lock().retain(|spiffe,_|config.as_ref().is_ok_and(|config|config.peers.values().any(|peer|&peer.spiffe_id==spiffe))); + cache.entries.lock().retain(|spiffe,entry| { + let current=config.as_ref().ok().and_then(|config|config.peers.values().find(|peer|&peer.spiffe_id==spiffe)); + let valid=current.is_some_and(|peer|same(&entry.peer,peer)) && local.as_ref().is_ok_and(|identity|identity.fingerprint==entry.local_fingerprint); + if !valid {entry.cancellation.cancel();}valid + }); + } + } + } + for entry in cache.entries.lock().values() { + entry.cancellation.cancel(); + } + cache.entries.lock().clear(); + }); + guard + } + pub(crate) fn state(&self, peer: &A2aPeer, state: &'static str) { + if self.states.lock().insert(peer.spiffe_id.clone(), state) != Some(state) { + let fingerprint = peer + .fingerprints + .first() + .and_then(|value| value.get(..16)) + .unwrap_or_default(); + tracing::info!(spiffe_id=%peer.spiffe_id,fingerprint,state,"A2A peer delivery state changed"); + } + } +} +fn same(left: &A2aPeer, right: &A2aPeer) -> bool { + left.spiffe_id == right.spiffe_id + && left.fingerprints == right.fingerprints + && left.address == right.address + && left.owner == right.owner + && left.sessions == right.sessions + && left.agents == right.agents +} diff --git a/src/messaging/a2a/connections.rs b/src/messaging/a2a/connections.rs new file mode 100644 index 000000000..da402468b --- /dev/null +++ b/src/messaging/a2a/connections.rs @@ -0,0 +1,96 @@ +//! Connections indexed by certificate, with a shared limit per SPIFFE peer. +use crate::config::{A2aConfig, A2aPeer}; +use std::{collections::HashMap, sync::Arc}; +use tokio_util::sync::CancellationToken; +#[derive(Default)] +pub(super) struct Connections { + state: parking_lot::Mutex, +} +#[derive(Default)] +struct State { + counts: HashMap, + certificates: HashMap>, +} +struct Connection { + peer: A2aPeer, + local_fingerprint: String, + cancellation: CancellationToken, +} +pub(super) struct Permit { + registry: Arc, + peer: String, + fingerprint: String, + id: uuid::Uuid, + cancellation: CancellationToken, +} +impl Permit { + pub(super) fn cancellation(&self) -> CancellationToken { + self.cancellation.clone() + } +} +impl Drop for Permit { + fn drop(&mut self) { + let mut state = self.registry.state.lock(); + if let Some(count) = state.counts.get_mut(&self.peer) { + *count = count.saturating_sub(1); + if *count == 0 { + state.counts.remove(&self.peer); + } + } + if let Some(connections) = state.certificates.get_mut(&self.fingerprint) { + connections.remove(&self.id); + if connections.is_empty() { + state.certificates.remove(&self.fingerprint); + } + } + } +} +impl Connections { + pub(super) fn register( + self: &Arc, + peer: A2aPeer, + fingerprint: String, + local_fingerprint: String, + ) -> Option { + let mut state = self.state.lock(); + let count = state.counts.entry(peer.spiffe_id.clone()).or_default(); + if *count >= 8 { + return None; + } + *count += 1; + let id = uuid::Uuid::new_v4(); + let cancellation = CancellationToken::new(); + let name = peer.spiffe_id.clone(); + state.certificates.entry(fingerprint.clone()).or_default().insert( + id, + Connection { + peer, + local_fingerprint, + cancellation: cancellation.clone(), + }, + ); + Some(Permit { + registry: self.clone(), + peer: name, + fingerprint, + id, + cancellation, + }) + } + pub(super) fn recheck(&self, config: Option<&A2aConfig>, local_fingerprint: Option<&str>) { + let state = self.state.lock(); + for (fingerprint, connections) in &state.certificates { + for entry in connections.values() { + let peer = config.and_then(|config| { + config + .peers + .values() + .find(|peer| peer.fingerprints.contains(fingerprint) && peer.spiffe_id == entry.peer.spiffe_id) + }); + if peer != Some(&entry.peer) || local_fingerprint != Some(entry.local_fingerprint.as_str()) { + entry.cancellation.cancel(); + } + } + } + } +} diff --git a/src/messaging/a2a/identity.rs b/src/messaging/a2a/identity.rs new file mode 100644 index 000000000..96fe773b0 --- /dev/null +++ b/src/messaging/a2a/identity.rs @@ -0,0 +1,228 @@ +//! Atomic, private, persisted Ed25519 instance identities. +use anyhow::{Context, Result, ensure}; +use rustls::pki_types::{CertificateDer, PrivateKeyDer}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{ + fs::{self, OpenOptions}, + io::{Read, Write}, + path::{Path, PathBuf}, +}; + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Record { + instance_id: uuid::Uuid, + generation: uuid::Uuid, + spiffe_id: String, +} +pub struct Identity { + pub instance_id: uuid::Uuid, + pub spiffe_id: String, + pub fingerprint: String, + pub expires_at: i64, + pub cert: CertificateDer<'static>, + pub key: PrivateKeyDer<'static>, +} +fn directory(config: &crate::config::Config) -> PathBuf { + config.workspace_dir.join("a2a") +} +fn read(path: &Path, private: bool) -> Result> { + let file = fs::File::open(path)?; + let meta = file.metadata()?; + ensure!( + meta.is_file() && meta.len() <= 65536 && !fs::symlink_metadata(path)?.file_type().is_symlink(), + "invalid A2A identity file" + ); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + if private { + ensure!( + meta.permissions().mode().trailing_zeros() >= 7, + "A2A private file permissions exceed 0600" + ); + } + } + #[cfg(not(unix))] + let _ = private; + let mut bytes = Vec::new(); + file.take(65537).read_to_end(&mut bytes)?; + ensure!(bytes.len() <= 65536, "A2A identity exceeds file bound"); + Ok(bytes) +} +fn write(dir: &Path, name: &str, bytes: &[u8]) -> Result<()> { + let temp = dir.join(format!(".{}", uuid::Uuid::new_v4())); + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut file = options.open(&temp)?; + file.write_all(bytes)?; + file.sync_all()?; + drop(file); + fs::rename(&temp, dir.join(name))?; + fs::File::open(dir)?.sync_all()?; + Ok(()) +} +pub(crate) fn optional(config: &crate::config::Config) -> Result> { + if directory(config).join("identity.toml").try_exists()? { + Ok(Some(load(config)?)) + } else { + Ok(None) + } +} +pub fn load(config: &crate::config::Config) -> Result { + load_named(config, "identity.toml") +} +fn load_named(config: &crate::config::Config, name: &str) -> Result { + let dir = directory(config); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + ensure!( + fs::metadata(&dir)?.permissions().mode().trailing_zeros() >= 6, + "A2A directory permissions exceed 0700" + ); + } + ensure!( + !fs::symlink_metadata(&dir)?.file_type().is_symlink(), + "A2A directory cannot be a symlink" + ); + let record: Record = toml::from_str(std::str::from_utf8(&read(&dir.join(name), true)?)?)?; + ensure!( + super::peers::instance(&record.spiffe_id)? == record.instance_id, + "A2A identity instance mismatch" + ); + let cert = read(&dir.join(format!("{}.der", record.generation)), false)?; + let key = read(&dir.join(format!("{}.key.pem", record.generation)), true)?; + let (_, parsed) = + x509_parser::parse_x509_certificate(&cert).map_err(|_| anyhow::anyhow!("invalid A2A certificate"))?; + let expires_at = parsed.validity().not_after.timestamp(); + let fingerprint = fingerprint(&cert); + let cert = CertificateDer::from(cert); + use rustls::pki_types::pem::PemObject as _; + let key = PrivateKeyDer::from_pem_slice(&key).context("invalid A2A private key")?; + let identity = Identity { + instance_id: record.instance_id, + spiffe_id: record.spiffe_id, + fingerprint, + expires_at, + cert, + key, + }; + let _ = rustls::sign::CertifiedKey::from_der( + vec![identity.cert.clone()], + identity.key.clone_key(), + &rustls::crypto::ring::default_provider(), + )?; + Ok(identity) +} +pub fn init(config: &crate::config::Config, rotate: bool) -> Result { + let dir = directory(config); + if dir.join("identity.toml").exists() && !rotate { + return load(config); + } + let old = if dir.join("identity.toml").exists() { + Some(load(config)?) + } else { + None + }; + if rotate && dir.join("pending.toml").exists() { + let pending = load_named(config, "pending.toml")?; + let current = load(config)?; + ensure!( + pending.instance_id == current.instance_id && pending.spiffe_id == current.spiffe_id, + "staged identity differs from current instance" + ); + super::tls::check_certificate(&pending.cert, &pending.spiffe_id, rustls::pki_types::UnixTime::now())?; + ensure!( + !config + .a2a + .peers + .values() + .any(|peer| peer.spiffe_id == pending.spiffe_id || peer.fingerprints.contains(&pending.fingerprint)), + "local identity cannot be its own peer" + ); + fs::rename(dir.join("pending.toml"), dir.join("identity.toml"))?; + fs::File::open(&dir)?.sync_all()?; + return load(config); + } + generate(config, "identity.toml", old) +} +pub fn prepare_rotation(config: &crate::config::Config) -> Result { + let current = load(config)?; + if directory(config).join("pending.toml").exists() { + return load_named(config, "pending.toml"); + } + generate(config, "pending.toml", Some(current)) +} +fn generate(config: &crate::config::Config, name: &str, old: Option) -> Result { + let dir = directory(config); + fs::create_dir_all(&config.workspace_dir)?; + let mut builder = fs::DirBuilder::new(); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + builder.mode(0o700); + } + match builder.create(&dir) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(error) => return Err(error.into()), + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + ensure!( + fs::metadata(&dir)?.permissions().mode().trailing_zeros() >= 6, + "A2A directory permissions exceed 0700" + ); + } + ensure!( + !fs::symlink_metadata(&dir)?.file_type().is_symlink(), + "A2A directory cannot be a symlink" + ); + let instance_id = old + .as_ref() + .map_or_else(uuid::Uuid::new_v4, |identity| identity.instance_id); + let spiffe_id = old.map_or_else( + || format!("spiffe://{}/prx/{instance_id}", config.a2a.trust_domain), + |identity| identity.spiffe_id, + ); + super::peers::instance(&spiffe_id)?; + let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ED25519)?; + let mut params = rcgen::CertificateParams::default(); + params.subject_alt_names = vec![rcgen::SanType::URI(spiffe_id.clone().try_into()?)]; + params.is_ca = rcgen::IsCa::NoCa; + let time = chrono::Utc::now(); + let now = u64::try_from(time.timestamp())?; + let expires = u64::try_from( + time.checked_add_months(chrono::Months::new(60)) + .context("certificate expiry overflow")? + .timestamp(), + )?; + params.not_before = rcgen::date_time_ymd(1970, 1, 1) + std::time::Duration::from_secs(now.saturating_sub(300)); + params.not_after = rcgen::date_time_ymd(1970, 1, 1) + std::time::Duration::from_secs(expires); + let cert = params.self_signed(&key)?; + let generation = uuid::Uuid::new_v4(); + write(&dir, &format!("{generation}.key.pem"), key.serialize_pem().as_bytes())?; + write(&dir, &format!("{generation}.der"), cert.der())?; + write( + &dir, + name, + toml::to_string(&Record { + instance_id, + generation, + spiffe_id, + })? + .as_bytes(), + )?; + load_named(config, name) +} +pub(crate) fn fingerprint(der: &[u8]) -> String { + hex::encode(Sha256::digest(der)) +} diff --git a/src/messaging/a2a/listener.rs b/src/messaging/a2a/listener.rs new file mode 100644 index 000000000..612df1c3f --- /dev/null +++ b/src/messaging/a2a/listener.rs @@ -0,0 +1,285 @@ +//! Dedicated HTTP/1.1 listener with identity from the TLS connection only. +use super::{ + identity, peers, + tls::{self, Trust}, +}; +use crate::messaging::{ + MessageAuth, PrxMessage, SessionAddr, + mailbox::{MailboxAuthority, MailboxError}, + runtime::MessagingRuntime, +}; +use anyhow::{Context, Result}; +use http_body_util::{BodyExt as _, Full, Limited}; +use hyper::{ + Request, Response, StatusCode, + body::{Bytes, Incoming}, +}; +use std::{convert::Infallible, sync::Arc, time::Duration}; +use tokio_util::sync::CancellationToken; + +type Body = Full; +pub struct Listener { + task: tokio::task::JoinHandle<()>, +} +impl Drop for Listener { + fn drop(&mut self) { + self.task.abort(); + } +} +fn response(status: StatusCode, value: serde_json::Value) -> Response { + let mut response = Response::new(Full::new(Bytes::from(value.to_string()))); + *response.status_mut() = status; + response.headers_mut().insert( + hyper::header::CONTENT_TYPE, + hyper::header::HeaderValue::from_static("application/json"), + ); + response +} +fn refused(status: StatusCode, code: &str) -> Response { + response(status, serde_json::json!({"error":code})) +} +fn target_authority( + runtime: &MessagingRuntime, + peer: &crate::config::A2aPeer, + target: &SessionAddr, + mut source: SessionAddr, +) -> Result { + anyhow::ensure!(peers::allows(peer, target, &runtime.instance), "peer_not_allowed"); + runtime.resolve_scope(target)?; + crate::messaging::mailbox::validate_address(&source)?; + source.instance = peers::instance(&peer.spiffe_id)?.to_string(); + source.owner = peer.owner.clone(); + Ok(MailboxAuthority::verified_peer( + runtime.workspace.clone(), + source, + target.clone(), + MessageAuth { + issuer: peer.spiffe_id.clone(), + subject: peer.spiffe_id.clone(), + method: "mtls".into(), + }, + )?) +} +async fn request( + trust: Trust, + _runtime: Arc, + cert: rustls::pki_types::CertificateDer<'static>, + rate: Arc, + request: Request, +) -> Response { + let Ok(effective) = trust.effective() else { + return refused(StatusCode::UNAUTHORIZED, "peer_unauthenticated"); + }; + if !effective.a2a.messaging_enabled { + return refused(StatusCode::UNAUTHORIZED, "peer_unauthenticated"); + } + let Ok(runtime) = MessagingRuntime::for_config(&effective) else { + return refused(StatusCode::SERVICE_UNAVAILABLE, "mailbox_unavailable"); + }; + let Ok(peer) = trust.resolve(&cert, rustls::pki_types::UnixTime::now()) else { + return refused(StatusCode::UNAUTHORIZED, "peer_unauthenticated"); + }; + if !rate.admit(&peer.spiffe_id) { + let mut response = refused(StatusCode::TOO_MANY_REQUESTS, "inbox_full"); + response + .headers_mut() + .insert(hyper::header::RETRY_AFTER, hyper::header::HeaderValue::from_static("1")); + return response; + } + if request.method() != hyper::Method::POST || !matches!(request.uri().path(), "/a2a/v1/pins" | "/a2a/v1/messages") { + return refused(StatusCode::NOT_FOUND, "not_found"); + } + let pins = request.uri().path() == "/a2a/v1/pins"; + let bytes = match Limited::new(request.into_body(), 352 * 1024).collect().await { + Ok(body) => body.to_bytes(), + Err(_) => return refused(StatusCode::PAYLOAD_TOO_LARGE, "message_too_large"), + }; + if pins { + #[derive(serde::Deserialize)] + #[serde(deny_unknown_fields)] + struct PinRequest { + to: SessionAddr, + } + let Ok(input) = serde_json::from_slice::(&bytes) else { + return refused(StatusCode::FORBIDDEN, "peer_not_allowed"); + }; + let source = SessionAddr::new( + peers::instance(&peer.spiffe_id).map_or_else(|_| String::new(), |id| id.to_string()), + &peer.owner, + "peer", + None, + ); + let Ok(authority) = target_authority(&runtime, &peer, &input.to, source) else { + return refused(StatusCode::FORBIDDEN, "peer_not_allowed"); + }; + let result = runtime + .resolve_scope(&input.to) + .and_then(|scope| runtime.store.recipient_pin(&authority, &scope, &input.to.session)); + return result.map_or_else( + |_| refused(StatusCode::FORBIDDEN, "peer_not_allowed"), + |pin| { + response( + StatusCode::OK, + serde_json::json!({"pin":pin,"expires_at":chrono::Utc::now().timestamp()+300}), + ) + }, + ); + } + let mut message: PrxMessage = match serde_json::from_slice(&bytes) { + Ok(message) => message, + Err(_) => return refused(StatusCode::UNPROCESSABLE_ENTITY, "chain_limit_reached"), + }; + if message.body.bytes.len() > crate::messaging::MAX_BODY_BYTES { + return refused(StatusCode::PAYLOAD_TOO_LARGE, "message_too_large"); + } + let Ok(authority) = target_authority(&runtime, &peer, &message.to, message.from.clone()) else { + return refused(StatusCode::FORBIDDEN, "peer_not_allowed"); + }; + message.hop_count = 0; + message.ancestry.clear(); + let target = message.to.clone(); + match runtime.store.accept(&authority, message) { + Ok(receipt) => { + runtime.wake(&target); + response( + StatusCode::ACCEPTED, + serde_json::json!({"message_id":receipt.message_id,"state":receipt.state,"auto_start":receipt.chain.depth<8}), + ) + } + Err(MailboxError::BodyTooLarge) => refused(StatusCode::PAYLOAD_TOO_LARGE, "message_too_large"), + Err(MailboxError::QueueFull | MailboxError::Quota(_) | MailboxError::RateLimited) => { + let mut result = refused(StatusCode::TOO_MANY_REQUESTS, "inbox_full"); + result + .headers_mut() + .insert(hyper::header::RETRY_AFTER, hyper::header::HeaderValue::from_static("1")); + result + } + Err( + MailboxError::ChainDepth + | MailboxError::UnknownParent + | MailboxError::InvalidMetadata + | MailboxError::IdempotencyConflict + | MailboxError::IdReuse, + ) => refused(StatusCode::UNPROCESSABLE_ENTITY, "chain_limit_reached"), + Err(_) => refused(StatusCode::FORBIDDEN, "peer_not_allowed"), + } +} +pub async fn start(config: &crate::config::Config, shutdown: CancellationToken) -> Result> { + if !config.a2a.messaging_enabled { + return Ok(None); + } + config.a2a.validate()?; + let identity = identity::load(config).context("run prx a2a init before enabling messaging")?; + anyhow::ensure!( + !config + .a2a + .peers + .values() + .any(|peer| peer.spiffe_id == identity.spiffe_id || peer.fingerprints.contains(&identity.fingerprint)), + "local identity cannot be its own peer" + ); + let trust = Trust { + config: Arc::new(config.clone()), + }; + let _ = tls::server(trust.clone())?; + let runtime = MessagingRuntime::for_config(config)?; + let listener = tokio::net::TcpListener::bind(&config.a2a.bind).await?; + let total = Arc::new(tokio::sync::Semaphore::new(128)); + let registry = Arc::new(super::connections::Connections::default()); + let rate = Arc::new(super::resources::RequestRate::default()); + let task = tokio::spawn(async move { + let mut connections = tokio::task::JoinSet::new(); + let mut refresh = tokio::time::interval(Duration::from_millis(250)); + loop { + let accepted = tokio::select! { + () = shutdown.cancelled() => break, + _ = connections.join_next(), if !connections.is_empty() => continue, + _=refresh.tick()=> { + let config=trust.current();let local=identity::load(&trust.config); + registry.recheck(config.as_ref().ok(),local.as_ref().ok().map(|identity|identity.fingerprint.as_str())); + continue; + } + accepted = listener.accept() => accepted, + }; + let (socket, _) = match accepted { + Ok(value) => value, + Err(_) => { + tokio::time::sleep(Duration::from_millis(100)).await; + continue; + } + }; + let Ok(permit) = total.clone().try_acquire_owned() else { + continue; + }; + let trust = trust.clone(); + let runtime = runtime.clone(); + let registry = registry.clone(); + let rate = rate.clone(); + let shutdown = shutdown.clone(); + connections.spawn(async move { + let _permit = permit; + let Ok(local) = identity::load(&trust.config) else { + return; + }; + let Ok(server) = tls::server(trust.clone()) else { + return; + }; + let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(server)); + let Ok(Ok(tls)) = tokio::time::timeout(Duration::from_secs(10), acceptor.accept(socket)).await else { + return; + }; + let Some(cert) = tls + .get_ref() + .1 + .peer_certificates() + .and_then(|chain| chain.first()) + .cloned() + else { + return; + }; + let Ok(peer) = trust.resolve(&cert, rustls::pki_types::UnixTime::now()) else { + return; + }; + let fingerprint = identity::fingerprint(cert.as_ref()); + let Some(permit) = registry.register(peer, fingerprint, local.fingerprint) else { + return; + }; + let cancellation = permit.cancellation(); + let _peer = permit; + let service_trust = trust.clone(); + let service = hyper::service::service_fn(move |req| { + let trust = service_trust.clone(); + let runtime = runtime.clone(); + let cert = cert.clone(); + let rate = rate.clone(); + async move { + Ok::<_, Infallible>( + tokio::time::timeout(Duration::from_secs(30), request(trust, runtime, cert, rate, req)) + .await + .unwrap_or_else(|_| refused(StatusCode::REQUEST_TIMEOUT, "request_timeout")), + ) + } + }); + let mut builder = hyper::server::conn::http1::Builder::new(); + builder + .timer(hyper_util::rt::TokioTimer::new()) + .header_read_timeout(Duration::from_secs(10)) + .keep_alive(true) + .max_buf_size(64 * 1024); + let connection = builder.serve_connection( + hyper_util::rt::TokioIo::new(super::resources::IdleIo::new(tls)), + service, + ); + tokio::pin!(connection); + tokio::select! { + _=&mut connection=>{}, + ()=shutdown.cancelled()=>{}, + ()=cancellation.cancelled()=>{}, + } + }); + } + connections.abort_all(); + while connections.join_next().await.is_some() {} + }); + Ok(Some(Listener { task })) +} diff --git a/src/messaging/a2a/mod.rs b/src/messaging/a2a/mod.rs new file mode 100644 index 000000000..b1c841ff9 --- /dev/null +++ b/src/messaging/a2a/mod.rs @@ -0,0 +1,12 @@ +//! Dedicated pinned mTLS messaging; independent of gateway compatibility APIs. +pub mod cli; +mod clients; +mod connections; +pub mod identity; +mod listener; +mod outbound; +pub mod peers; +mod resources; +mod tls; +pub use listener::start; +pub(crate) use outbound::RemoteTransport; diff --git a/src/messaging/a2a/outbound.rs b/src/messaging/a2a/outbound.rs new file mode 100644 index 000000000..08416ac75 --- /dev/null +++ b/src/messaging/a2a/outbound.rs @@ -0,0 +1,193 @@ +//! Durable remote publication and receiver-pin refresh before every attempt. +use super::{peers, tls::Trust}; +use crate::messaging::{ + DeliveryState, RecipientPin, SessionAddr, + mailbox::{MailboxAuthority, MailboxError, MailboxResult}, + runtime::MessagingRuntime, + send::MailboxDestination, +}; +use std::{collections::HashSet, sync::Arc, time::Duration}; + +pub(crate) struct RemoteTransport { + trust: Trust, + clients: super::clients::Clients, +} +impl RemoteTransport { + pub(crate) fn new(config: &crate::config::Config) -> Self { + let trust = Trust { + config: Arc::new(config.clone()), + }; + Self { + clients: super::clients::Clients::new(trust.clone()), + trust, + } + } + fn peer(&self, target: &SessionAddr) -> anyhow::Result { + let config = self.trust.current()?; + config + .peers + .values() + .find(|peer| peers::instance(&peer.spiffe_id).is_ok_and(|id| id.to_string() == target.instance)) + .cloned() + .ok_or_else(|| anyhow::anyhow!("peer_not_allowed")) + } + pub(crate) fn destination( + &self, + runtime: &MessagingRuntime, + source: &SessionAddr, + target: &SessionAddr, + ) -> MailboxResult { + self.peer(target).map_err(|_| MailboxError::RemoteNotEnabled)?; + Ok(MailboxDestination { + authority: MailboxAuthority::outbound(runtime.workspace.clone(), source.clone(), target.clone())?, + pin: RecipientPin { + incarnation: uuid::Uuid::nil(), + generation: 1, + token: "pending-peer-pin".into(), + }, + pin_expires_at: chrono::Utc::now().timestamp() + 86400, + }) + } + async fn attempt( + &self, + runtime: &MessagingRuntime, + scope: &crate::messaging::mailbox::MailboxScope, + source: &SessionAddr, + message: &mut crate::messaging::PrxMessage, + ) -> anyhow::Result<(u16, Option)> { + let peer = self.peer(&message.to).map_err(|_| MailboxError::Unauthorized)?; + let (client, cancellation) = self.clients.get(&peer)?; + let request = async { + let response = client + .post(format!("https://{}/a2a/v1/pins", peer.address)) + .json(&serde_json::json!({"to":message.to})) + .send() + .await?; + let status = response.status().as_u16(); + let retry = retry_after(&response); + if status != 200 { + return Ok((status, retry)); + } + #[derive(serde::Deserialize)] + struct Pin { + pin: RecipientPin, + expires_at: i64, + } + let pin: Pin = serde_json::from_slice(&bounded_response(response).await?)?; + runtime + .store + .refresh_outbox_pin(scope, source, message, pin.pin, pin.expires_at)?; + // Re-read grants between the two requests; no cached bearer authority. + let current = self.peer(&message.to)?; + anyhow::ensure!( + current.spiffe_id == peer.spiffe_id + && current.fingerprints == peer.fingerprints + && current.address == peer.address, + "peer changed" + ); + let response = client + .post(format!("https://{}/a2a/v1/messages", peer.address)) + .json(message) + .send() + .await?; + Ok((response.status().as_u16(), retry_after(&response))) + }; + tokio::select! { + ()=cancellation.cancelled()=>Err(MailboxError::Unauthorized.into()), + result=request=>result, + } + } + pub(crate) fn start(self, runtime: Arc) { + tokio::spawn(async move { + let _monitor = self.clients.monitor(); + let mut interval = tokio::time::interval(Duration::from_secs(1)); + loop { + interval.tick().await; + let Ok(sources) = runtime.store.outbox_sources() else { + continue; + }; + let mut peers = HashSet::new(); + for (scope, source) in sources { + let Ok(pending) = runtime.store.pending_outbox(&scope, &source) else { + continue; + }; + for outbound in pending { + let mut message = outbound.message().clone(); + if message.to.instance == runtime.instance || !peers.insert(message.to.instance.clone()) { + continue; + } + let Ok((attempts, created)) = runtime.store.outbox_retry(&scope, &message) else { + continue; + }; + let now = chrono::Utc::now().timestamp(); + if now.saturating_sub(created) >= 86400 { + let _ = runtime.store.retry_outbox(&scope, &source, &message, None, "expired"); + continue; + } + let result = self.attempt(&runtime, &scope, &source, &mut message).await; + let (status, retry) = match result { + Ok(value) => value, + Err(error) + if error.downcast_ref::() == Some(&MailboxError::StaleIncarnation) + || error.downcast_ref::() == Some(&MailboxError::Unauthorized) => + { + (403, None) + } + Err(_) => (0, None), + }; + if let Ok(peer) = self.peer(&message.to) { + self.clients + .state(&peer, if status == 202 { "available" } else { "unavailable" }); + } + if status == 202 { + let _ = runtime + .store + .acknowledge(&scope, &message.to, message.id, DeliveryState::Accepted); + continue; + } + let permanent = + matches!(status, 401 | 403 | 413 | 422) || (400..500).contains(&status) && status != 429; + let delay = backoff(attempts).max(retry.unwrap_or(0)); + let next = if permanent { + None + } else { + Some(now.saturating_add(i64::try_from(delay).unwrap_or(300))) + }; + let error = match status { + 401 => "peer_unauthenticated", + 403 => "peer_not_allowed", + 413 => "message_too_large", + 422 => "chain_limit_reached", + 429 => "inbox_full", + _ => "peer_unavailable", + }; + let _ = runtime.store.retry_outbox(&scope, &source, &message, next, error); + } + } + } + }); + } +} +fn retry_after(response: &reqwest::Response) -> Option { + let value = response.headers().get(reqwest::header::RETRY_AFTER)?.to_str().ok()?; + value.parse().ok().or_else(|| { + chrono::DateTime::parse_from_rfc2822(value) + .ok() + .and_then(|date| u64::try_from(date.timestamp().saturating_sub(chrono::Utc::now().timestamp())).ok()) + }) +} +async fn bounded_response(mut response: reqwest::Response) -> anyhow::Result> { + let mut bytes = Vec::new(); + while let Some(chunk) = response.chunk().await? { + anyhow::ensure!( + bytes.len().saturating_add(chunk.len()) <= 8192, + "peer pin response exceeds byte bound" + ); + bytes.extend_from_slice(&chunk); + } + Ok(bytes) +} +fn backoff(attempts: u32) -> u64 { + let ceiling = 1_u64.checked_shl(attempts.min(9)).unwrap_or(300).min(300); + rand::random_range(0..=ceiling) +} diff --git a/src/messaging/a2a/peers.rs b/src/messaging/a2a/peers.rs new file mode 100644 index 000000000..39e8c10e7 --- /dev/null +++ b/src/messaging/a2a/peers.rs @@ -0,0 +1,78 @@ +//! Pinned peer configuration and SPIFFE instance names. +//! Trust-domain syntax follows https://spiffe.io/docs/latest/spiffe-specs/spiffe-id/#21-trust-domain. +use crate::config::schema::{A2aConfig, A2aPeer}; +use anyhow::{Result, ensure}; +use std::collections::HashSet; + +pub fn instance(spiffe: &str) -> Result { + ensure!(spiffe.len() <= 2048, "SPIFFE ID exceeds 2048 bytes"); + let rest = spiffe + .strip_prefix("spiffe://") + .ok_or_else(|| anyhow::anyhow!("invalid SPIFFE scheme"))?; + let (domain, path) = rest + .split_once('/') + .ok_or_else(|| anyhow::anyhow!("SPIFFE path missing"))?; + ensure!( + !domain.is_empty() + && domain.len() <= 255 + && domain + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'.' | b'-' | b'_')), + "invalid SPIFFE trust domain" + ); + let id = path + .strip_prefix("prx/") + .ok_or_else(|| anyhow::anyhow!("invalid SPIFFE instance path"))?; + let uuid = uuid::Uuid::parse_str(id)?; + ensure!(id == uuid.to_string(), "SPIFFE instance must be a canonical UUID"); + Ok(uuid) +} +pub fn validate(config: &A2aConfig) -> Result<()> { + let mut identities = HashSet::new(); + let mut fingerprints = HashSet::new(); + instance(&format!("spiffe://{}/prx/{}", config.trust_domain, uuid::Uuid::nil()))?; + for peer in config.peers.values() { + instance(&peer.spiffe_id)?; + ensure!(identities.insert(&peer.spiffe_id), "duplicate peer SPIFFE ID"); + ensure!(!peer.owner.trim().is_empty(), "peer owner is required"); + ensure!( + !peer.sessions.is_empty() && !peer.agents.is_empty(), + "peer recipient allowlists cannot be empty" + ); + ensure!( + (1..=2).contains(&peer.fingerprints.len()), + "peer requires one or two fingerprints" + ); + for fingerprint in &peer.fingerprints { + ensure!( + fingerprint.len() == 64 + && fingerprint + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)), + "fingerprint must be 64 lowercase hex characters" + ); + ensure!(fingerprints.insert(fingerprint), "duplicate peer fingerprint"); + } + let url = reqwest::Url::parse(&format!("https://{}", peer.address))?; + ensure!( + url.host_str().is_some() + && url.port().is_some() + && url.username().is_empty() + && url.password().is_none() + && url.path() == "/" + && url.query().is_none() + && url.fragment().is_none(), + "peer address must be host:port" + ); + } + Ok(()) +} +pub(crate) fn allows(peer: &A2aPeer, target: &crate::messaging::SessionAddr, local: &str) -> bool { + target.instance == local + && target.owner == peer.owner + && peer + .sessions + .iter() + .any(|value| value == "*" || value == &target.session) + && peer.agents.iter().any(|value| value == "*" || value == &target.agent) +} diff --git a/src/messaging/a2a/resources.rs b/src/messaging/a2a/resources.rs new file mode 100644 index 000000000..9f4ccc08a --- /dev/null +++ b/src/messaging/a2a/resources.rs @@ -0,0 +1,101 @@ +//! Connection inactivity and per-peer request resource protection. +use std::{ + collections::HashMap, + future::Future as _, + pin::Pin, + task::{Context, Poll}, + time::Duration, +}; +use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; +const IDLE: Duration = Duration::from_secs(60); +pub(super) struct IdleIo { + stream: S, + timer: Pin>, +} +impl IdleIo { + pub(super) fn new(stream: S) -> Self { + Self { + stream, + timer: Box::pin(tokio::time::sleep(IDLE)), + } + } + fn expired(&mut self, cx: &mut Context<'_>) -> bool { + self.timer.as_mut().poll(cx).is_ready() + } + fn progress(&mut self) { + self.timer.as_mut().reset(tokio::time::Instant::now() + IDLE); + } +} +impl AsyncRead for IdleIo { + fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buffer: &mut ReadBuf<'_>) -> Poll> { + let this = self.get_mut(); + if this.expired(cx) { + return Poll::Ready(Err(std::io::Error::new( + std::io::ErrorKind::TimedOut, + "A2A connection idle", + ))); + } + let before = buffer.filled().len(); + let result = Pin::new(&mut this.stream).poll_read(cx, buffer); + if buffer.filled().len() > before { + this.progress(); + } + result + } +} +impl AsyncWrite for IdleIo { + fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, bytes: &[u8]) -> Poll> { + let this = self.get_mut(); + if this.expired(cx) { + return Poll::Ready(Err(std::io::Error::new( + std::io::ErrorKind::TimedOut, + "A2A connection idle", + ))); + } + let result = Pin::new(&mut this.stream).poll_write(cx, bytes); + if matches!(result,Poll::Ready(Ok(count)) if count>0) { + this.progress(); + } + result + } + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + if this.expired(cx) { + return Poll::Ready(Err(std::io::Error::new( + std::io::ErrorKind::TimedOut, + "A2A connection idle", + ))); + } + Pin::new(&mut this.stream).poll_flush(cx) + } + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + if this.expired(cx) { + return Poll::Ready(Err(std::io::Error::new( + std::io::ErrorKind::TimedOut, + "A2A connection idle", + ))); + } + Pin::new(&mut this.stream).poll_shutdown(cx) + } +} +#[derive(Default)] +pub(super) struct RequestRate { + counts: parking_lot::Mutex>, +} +impl RequestRate { + pub(super) fn admit(&self, spiffe: &str) -> bool { + let now = chrono::Utc::now().timestamp(); + let mut counts = self.counts.lock(); + counts.retain(|_, (second, _)| *second >= now); + if !counts.contains_key(spiffe) && counts.len() >= 128 { + return false; + } + let (_, count) = counts.entry(spiffe.into()).or_insert((now, 0)); + if *count >= 10 { + return false; + } + *count += 1; + true + } +} diff --git a/src/messaging/a2a/tls.rs b/src/messaging/a2a/tls.rs new file mode 100644 index 000000000..6de1fd01d --- /dev/null +++ b/src/messaging/a2a/tls.rs @@ -0,0 +1,240 @@ +//! Pinned Ed25519 verification plus real TLS CertificateVerify signatures. +use super::{identity, peers}; +use crate::config::{A2aConfig, A2aPeer, Config}; +use anyhow::{Result, ensure}; +use rustls::{ + DigitallySignedStruct, DistinguishedName, Error, SignatureScheme, + client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}, + pki_types::{CertificateDer, ServerName, UnixTime}, + server::danger::{ClientCertVerified, ClientCertVerifier}, +}; +use std::sync::Arc; + +#[derive(Clone)] +pub(crate) struct Trust { + pub config: Arc, +} +impl std::fmt::Debug for Trust { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("PinnedA2aTrust") + } +} +impl Trust { + pub(crate) fn effective(&self) -> Result { + // CLI edits revoke connections immediately, independently of runtime reload. + let merged = crate::config::files::read_merged_toml_with_gate(&self.config.config_path)?; + let mut config: Config = merged.try_into()?; + config.config_path.clone_from(&self.config.config_path); + config.workspace_dir.clone_from(&self.config.workspace_dir); + config.a2a.validate()?; + Ok(config) + } + pub(crate) fn current(&self) -> Result { + let config = self.effective()?.a2a; + ensure!(config.messaging_enabled, "A2A messaging disabled"); + Ok(config) + } + pub(crate) fn resolve(&self, cert: &CertificateDer<'_>, now: UnixTime) -> Result { + let config = self.effective()?.a2a; + let fingerprint = identity::fingerprint(cert.as_ref()); + let peer = config + .peers + .values() + .find(|peer| peer.fingerprints.contains(&fingerprint)) + .ok_or_else(|| anyhow::anyhow!("peer unauthenticated"))?; + check_certificate(cert, &peer.spiffe_id, now)?; + Ok(peer.clone()) + } +} +const fn rejected() -> Error { + Error::InvalidCertificate(rustls::CertificateError::ApplicationVerificationFailure) +} +pub(crate) fn check_certificate(cert: &CertificateDer<'_>, spiffe: &str, now: UnixTime) -> Result<()> { + peers::instance(spiffe)?; + let (rest, parsed) = + x509_parser::parse_x509_certificate(cert.as_ref()).map_err(|_| anyhow::anyhow!("invalid peer certificate"))?; + ensure!(rest.is_empty(), "trailing certificate DER"); + let seconds = i64::try_from(now.as_secs())?; + ensure!( + parsed.validity().not_before.timestamp() <= seconds && seconds <= parsed.validity().not_after.timestamp(), + "peer certificate outside validity window" + ); + ensure!( + parsed.public_key().algorithm.algorithm.to_id_string() == "1.3.101.112", + "peer key must be Ed25519" + ); + ensure!( + parsed.basic_constraints()?.is_none_or(|basic| !basic.value.ca), + "peer certificate cannot be a CA" + ); + let san = parsed + .subject_alternative_name()? + .ok_or_else(|| anyhow::anyhow!("SPIFFE URI SAN missing"))?; + let uris: Vec<_> = san + .value + .general_names + .iter() + .filter_map(|name| match name { + x509_parser::extensions::GeneralName::URI(uri) => Some(*uri), + _ => None, + }) + .collect(); + ensure!( + uris.as_slice() == [spiffe], + "peer requires exactly the pinned SPIFFE URI SAN" + ); + Ok(()) +} +fn signature( + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, +) -> std::result::Result { + if dss.scheme != SignatureScheme::ED25519 { + return Err(rejected()); + } + rustls::crypto::verify_tls13_signature( + message, + cert, + dss, + &rustls::crypto::ring::default_provider().signature_verification_algorithms, + ) +} +impl ClientCertVerifier for Trust { + fn offer_client_auth(&self) -> bool { + true + } + fn client_auth_mandatory(&self) -> bool { + true + } + fn root_hint_subjects(&self) -> &[DistinguishedName] { + &[] + } + fn verify_client_cert( + &self, + cert: &CertificateDer<'_>, + intermediates: &[CertificateDer<'_>], + now: UnixTime, + ) -> std::result::Result { + if !intermediates.is_empty() { + return Err(rejected()); + } + self.resolve(cert, now).map_err(|_| rejected())?; + Ok(ClientCertVerified::assertion()) + } + fn verify_tls12_signature( + &self, + _: &[u8], + _: &CertificateDer<'_>, + _: &DigitallySignedStruct, + ) -> std::result::Result { + Err(rejected()) + } + fn verify_tls13_signature( + &self, + msg: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, + ) -> std::result::Result { + signature(msg, cert, dss) + } + fn supported_verify_schemes(&self) -> Vec { + vec![SignatureScheme::ED25519] + } +} +#[derive(Debug)] +struct ServerPin { + trust: Trust, + spiffe: String, +} +impl ServerCertVerifier for ServerPin { + fn verify_server_cert( + &self, + cert: &CertificateDer<'_>, + intermediates: &[CertificateDer<'_>], + _: &ServerName<'_>, + _: &[u8], + now: UnixTime, + ) -> std::result::Result { + if !intermediates.is_empty() { + return Err(rejected()); + } + let peer = self.trust.resolve(cert, now).map_err(|_| rejected())?; + if peer.spiffe_id != self.spiffe { + return Err(rejected()); + } + Ok(ServerCertVerified::assertion()) + } + fn verify_tls12_signature( + &self, + _: &[u8], + _: &CertificateDer<'_>, + _: &DigitallySignedStruct, + ) -> std::result::Result { + Err(rejected()) + } + fn verify_tls13_signature( + &self, + msg: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, + ) -> std::result::Result { + signature(msg, cert, dss) + } + fn supported_verify_schemes(&self) -> Vec { + vec![SignatureScheme::ED25519] + } +} +pub(crate) fn server(trust: Trust) -> Result { + let identity = identity::load(&trust.config)?; + check_certificate(&identity.cert, &identity.spiffe_id, UnixTime::now())?; + let mut config = rustls::ServerConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider())) + .with_protocol_versions(&[&rustls::version::TLS13])? + .with_client_cert_verifier(Arc::new(trust)) + .with_single_cert(vec![identity.cert], identity.key)?; + config.session_storage = Arc::new(rustls::server::NoServerSessionStorage {}); + config.send_tls13_tickets = 0; + config.alpn_protocols = vec![b"http/1.1".to_vec()]; + Ok(config) +} +pub(crate) fn client(trust: Trust, peer: &A2aPeer) -> Result { + let identity = identity::load(&trust.config)?; + let mut config = rustls::ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider())) + .with_protocol_versions(&[&rustls::version::TLS13])? + .dangerous() + .with_custom_certificate_verifier(Arc::new(ServerPin { + trust, + spiffe: peer.spiffe_id.clone(), + })) + .with_client_auth_cert(vec![identity.cert], identity.key)?; + config.resumption = rustls::client::Resumption::disabled(); + config.alpn_protocols = vec![b"http/1.1".to_vec()]; + Ok(reqwest::Client::builder() + .use_preconfigured_tls(config) + .redirect(reqwest::redirect::Policy::none()) + .no_proxy() + .http1_only() + .pool_max_idle_per_host(1) + .tls_info(true) + .connect_timeout(std::time::Duration::from_secs(10)) + .timeout(std::time::Duration::from_secs(30)) + .build()?) +} + +pub(crate) async fn peer_expiry(config: &Config, peer: &A2aPeer) -> Result { + let trust = Trust { + config: Arc::new(config.clone()), + }; + let response = client(trust, peer)? + .head(format!("https://{}/a2a/v1/pins", peer.address)) + .send() + .await?; + let certificate = response + .extensions() + .get::() + .and_then(reqwest::tls::TlsInfo::peer_certificate) + .ok_or_else(|| anyhow::anyhow!("peer certificate missing"))?; + let (_, parsed) = + x509_parser::parse_x509_certificate(certificate).map_err(|_| anyhow::anyhow!("invalid peer certificate"))?; + Ok(parsed.validity().not_after.timestamp()) +} diff --git a/src/messaging/mailbox.rs b/src/messaging/mailbox.rs index 467103fa7..bc2868d48 100644 --- a/src/messaging/mailbox.rs +++ b/src/messaging/mailbox.rs @@ -19,6 +19,8 @@ pub const MAX_BYTES: i64 = 64 * 1024 * 1024; /// Stable refusals, shared by store, IPC and dormant send adapters. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum MailboxError { + #[error("remote_not_enabled")] + RemoteNotEnabled, #[error("invalid_address")] InvalidAddress, #[error("stream_id_required")] @@ -151,7 +153,7 @@ impl MailboxAuthority { bounded(&workspace_id, 4096)?; validate_address(&source)?; validate_address(&destination)?; - if !matches!(auth.method.as_str(), "jwt" | "mtls") { + if auth.method != "mtls" { return Err(MailboxError::Unauthorized); } Ok(Self { @@ -262,7 +264,7 @@ pub(crate) fn validate_body(mime: &str, bytes: &[u8]) -> MailboxResult<()> { if mime.is_empty() || mime.len() > 255 || !mime.bytes().all(|byte| (0x20..=0x7e).contains(&byte)) { return Err(MailboxError::InvalidMime); } - if mime.len().saturating_add(bytes.len()) > super::MAX_BODY_BYTES { + if bytes.len() > super::MAX_BODY_BYTES { return Err(MailboxError::BodyTooLarge); } Ok(()) @@ -306,3 +308,8 @@ pub(crate) fn outbox_key(workspace: &str, message: &PrxMessage) -> MailboxResult ], ) } + +/// Runtime cache owners release erased payloads before the durable erase joins. +pub trait MailboxCacheDrainer: Send + Sync { + fn drain(&self, scope: Uuid); +} diff --git a/src/messaging/mod.rs b/src/messaging/mod.rs index bb5b9fb1e..e28dfd822 100644 --- a/src/messaging/mod.rs +++ b/src/messaging/mod.rs @@ -15,4 +15,11 @@ pub use types::{ PrxMessage, RecipientPin, SessionAddr, }; +pub mod runtime; pub mod send; + +pub(crate) mod worker; + +pub mod a2a; + +pub(crate) mod receiver; diff --git a/src/messaging/receiver.rs b/src/messaging/receiver.rs new file mode 100644 index 000000000..69814433c --- /dev/null +++ b/src/messaging/receiver.rs @@ -0,0 +1,48 @@ +//! Per-session execution serialization and durable backend inbox drivers. +use super::{ + SessionAddr, + runtime::{MessageInput, MessagingRuntime}, +}; +use std::{ + collections::HashMap, + future::Future, + pin::Pin, + sync::{Arc, OnceLock, Weak}, +}; +type Callback = Arc Pin> + Send>> + Send + Sync>; +pub(crate) fn gate(address: &SessionAddr) -> Arc> { + static GATES: OnceLock>>>> = OnceLock::new(); + let mut gates = GATES.get_or_init(Default::default).lock(); + gates.retain(|_, gate| gate.strong_count() > 0); + if let Some(gate) = gates.get(address).and_then(Weak::upgrade) { + return gate; + } + let gate = Arc::new(tokio::sync::Mutex::new(())); + gates.insert(address.clone(), Arc::downgrade(&gate)); + gate +} +pub(crate) fn register(runtime: Arc, address: SessionAddr, callback: Callback) -> anyhow::Result<()> { + // Registration is idempotent for the currently running backend owner. + let Some(mut inbox) = runtime.register_backend(address)? else { + return Ok(()); + }; + tokio::spawn(async move { + let mut interval = tokio::time::interval(std::time::Duration::from_millis(100)); + loop { + interval.tick().await; + match inbox.poll() { + Ok(inputs) => { + for input in inputs { + if input.auto_start() + && let Err(error) = callback(input).await + { + tracing::warn!(error=%crate::agent::diagnostics::error_class(&error),"session mailbox turn refused"); + } + } + } + Err(_) => break, + } + } + }); + Ok(()) +} diff --git a/src/messaging/runtime.rs b/src/messaging/runtime.rs new file mode 100644 index 000000000..033dd69a7 --- /dev/null +++ b/src/messaging/runtime.rs @@ -0,0 +1,389 @@ +//! Runtime-owned sender identity, durable local delivery and inbox wakeups. +use super::mailbox::{MailboxAuthority, MailboxError, MailboxPublished, MailboxReceipt, MailboxResult, MailboxScope}; +use super::send::{MailboxDestination, MailboxResolver, MailboxSender}; +use super::{PrxMessage, SessionAddr}; +use crate::memory::sqlite::mailbox::{SqliteMailbox, SqliteMailboxSender}; +use async_trait::async_trait; +use parking_lot::{Mutex, RwLock}; +use std::{ + collections::HashMap, + path::PathBuf, + sync::{Arc, OnceLock, Weak}, +}; +use tokio::sync::mpsc; + +type RuntimeRegistry = Mutex>>; +static RUNTIMES: OnceLock = OnceLock::new(); + +pub struct MessagingRuntime { + pub(crate) store: SqliteMailbox, + pub(crate) workspace: String, + pub(crate) instance: String, + config: RwLock>, + inboxes: Mutex)>>, + ready: Mutex>>, +} + +#[derive(Clone)] +pub struct MessageInput { + _lease: Arc, + scope: uuid::Uuid, + pub message: PrxMessage, + pub receipt: MailboxReceipt, + pub text: String, +} +impl MessageInput { + pub(crate) fn verify(&self, runtime: &MessagingRuntime) -> MailboxResult<()> { + let event = self + .receipt + .adopted_message_event_id + .ok_or(MailboxError::CorruptState)?; + runtime + .store + .validate_input(&runtime.workspace, &self.message.to, event, &self.text) + } + + pub const fn auto_start(&self) -> bool { + self.receipt.chain.depth < 8 + } +} + +pub struct SessionInbox { + runtime: Arc, + address: SessionAddr, + scope: MailboxScope, + receiver: mpsc::Receiver<()>, +} +impl Drop for SessionInbox { + fn drop(&mut self) { + let mut inboxes = self.runtime.inboxes.lock(); + if inboxes + .get(&self.address) + .is_some_and(|(scope, _)| *scope == self.scope.scope_id) + { + inboxes.remove(&self.address); + } + } +} + +impl MessagingRuntime { + pub fn for_config(config: &crate::config::Config) -> anyhow::Result> { + anyhow::ensure!( + config.memory.backend == "sqlite", + "session messaging requires the SQLite mailbox backend" + ); + let path = config.workspace_dir.clone(); + let mut runtimes = RUNTIMES.get_or_init(Mutex::default).lock(); + if let Some(runtime) = runtimes.get(&path).and_then(Weak::upgrade) { + *runtime.config.write() = Arc::new(config.clone()); + return Ok(runtime); + } + let memory = crate::memory::SqliteMemory::new(&path)?; + let key = crate::security::runtime_key::DecisionKey::load_or_create(&path)?; + let secret = key.hmac( + crate::security::runtime_key::KeyDomain::StateFingerprint, + &[b"prx-mailbox-pins-v1"], + ); + let instance = if config.a2a.messaging_enabled { + super::a2a::identity::load(config)?.instance_id.to_string() + } else { + super::a2a::identity::optional(config)?.map_or_else( + || config.a2a.agent_id.clone(), + |identity| identity.instance_id.to_string(), + ) + }; + let store = SqliteMailbox::new( + memory, + instance.clone(), + secret, + Arc::new(super::mailbox::SystemMailboxClock), + )?; + let runtime = Arc::new(Self { + store, + workspace: path.to_string_lossy().into_owned(), + instance, + config: RwLock::new(Arc::new(config.clone())), + inboxes: Mutex::new(HashMap::new()), + ready: Mutex::new(HashMap::new()), + }); + let drainer: Arc = runtime.clone(); + runtime.store.register_drainer(&drainer); + if config.a2a.messaging_enabled { + super::a2a::RemoteTransport::new(config).start(runtime.clone()); + } + runtimes.insert(path, Arc::downgrade(&runtime)); + Ok(runtime) + } + + pub fn address(&self, owner: &str, session: &str, agent: &str) -> SessionAddr { + SessionAddr::new(&self.instance, owner, session, Some(agent)) + } + + pub fn register(self: &Arc, address: SessionAddr) -> MailboxResult { + let scope = self.store.session_scope(&self.workspace, &address, true)?; + let (sender, receiver) = mpsc::channel(1); + match self.inboxes.lock().entry(address.clone()) { + std::collections::hash_map::Entry::Vacant(entry) => { + entry.insert((scope.scope_id, sender)); + } + std::collections::hash_map::Entry::Occupied(_) => return Err(MailboxError::IdentityImmutable), + } + Ok(SessionInbox { + runtime: Arc::clone(self), + address, + scope, + receiver, + }) + } + + pub(crate) fn register_backend(self: &Arc, address: SessionAddr) -> MailboxResult> { + match self.register(address) { + Ok(inbox) => Ok(Some(inbox)), + Err(MailboxError::IdentityImmutable) => Ok(None), + Err(error) => Err(error), + } + } + pub fn inbound(&self, target: &SessionAddr) -> bool { + let configured = self.config.read().clone(); + let config: crate::config::Config = if configured.config_path.exists() { + match crate::config::files::read_merged_toml_with_gate(&configured.config_path) + .and_then(|tree| tree.try_into().map_err(Into::into)) + { + Ok(config) => config, + Err(_) => return false, + } + } else { + (*configured).clone() + }; + if target.agent == "main" { + config.agent.messaging.inbound + } else { + config + .agents + .get(&target.agent) + .is_some_and(|agent| agent.enabled && agent.messaging.inbound) + } + } + + pub fn resolve_scope(&self, target: &SessionAddr) -> MailboxResult { + if !self.inbound(target) { + return Err(MailboxError::Unauthorized); + } + let registered = self.inboxes.lock().contains_key(target); + self.store.session_scope(&self.workspace, target, registered) + } + + pub(crate) fn adopted(&self, message: PrxMessage, receipt: MailboxReceipt) -> MailboxResult<()> { + let text = crate::session_worker::mailbox::user_text(&message)?; + let target = message.to.clone(); + let mut ready = self.ready.lock(); + let queue = ready.entry(target.clone()).or_default(); + if queue.len() >= usize::try_from(super::mailbox::MAX_QUEUE).map_err(|_| MailboxError::CorruptState)? { + return Err(MailboxError::QueueFull); + } + let scope = self.store.session_scope(&self.workspace, &message.to, false)?; + let lease = self.store.hold_input(&scope, &message.to)?; + queue.push_back(MessageInput { + _lease: lease, + scope: scope.scope_id, + message, + receipt, + text, + }); + drop(ready); + self.wake(&target); + Ok(()) + } + pub fn wake(&self, target: &SessionAddr) { + if let Some((_, sender)) = self.inboxes.lock().get(target) { + let _ = sender.try_send(()); + } + } + + pub fn bind(self: &Arc, source: SessionAddr, event: Option<&str>) -> MailboxResult { + let mut source = source; + if let Some(agent) = self + .store + .logical_agent(&self.workspace, &source.owner, &source.session)? + { + source.agent = agent; + } + let scope = self.store.session_scope(&self.workspace, &source, true)?; + let chain = event + .map(|event| self.store.source_chain(&self.workspace, &source.owner, event)) + .transpose()? + .flatten(); + let sender = SqliteMailboxSender::new( + self.store.clone(), + source.clone(), + scope.clone(), + Arc::new(LocalResolver { + runtime: Arc::clone(self), + source, + }), + None, + )? + .with_chain(chain); + Ok(RuntimeSender { + runtime: Arc::clone(self), + sender, + scope, + }) + } + + pub fn alias(&self, source: &SessionAddr, target: &serde_json::Value) -> MailboxResult { + let mut address = match target { + serde_json::Value::String(value) => SessionAddr::new(&source.instance, &source.owner, value, None), + _ => super::send::parse_target(target, source)?, + }; + if address.instance != self.instance { + super::mailbox::validate_address(&address)?; + return Ok(address); + } + if address.owner != source.owner { + return Err(MailboxError::Unauthorized); + } + if matches!(address.session.as_str(), "main" | "parent") { + address.session = self + .store + .parent_session(&self.workspace, &source.owner, &source.session)? + .unwrap_or_else(|| source.session.clone()); + address.agent = "main".into(); + } + if let Some(agent) = self + .store + .logical_agent(&self.workspace, &source.owner, &address.session)? + { + address.agent = agent; + } + Ok(address) + } +} + +struct LocalResolver { + runtime: Arc, + source: SessionAddr, +} +#[async_trait] +impl MailboxResolver for LocalResolver { + async fn resolve(&self, target: &SessionAddr) -> MailboxResult { + if target.instance != self.runtime.instance { + return super::a2a::RemoteTransport::new(&self.runtime.config.read()).destination( + &self.runtime, + &self.source, + target, + ); + } + let authority = MailboxAuthority::local(self.runtime.workspace.clone(), self.source.clone(), target.clone())?; + let scope = self.runtime.resolve_scope(target)?; + let pin = self.runtime.store.recipient_pin(&authority, &scope, &target.session)?; + Ok(MailboxDestination { + authority, + pin, + pin_expires_at: chrono::Utc::now().timestamp() + 300, + }) + } +} + +pub struct RuntimeSender { + runtime: Arc, + sender: SqliteMailboxSender, + scope: MailboxScope, +} +#[async_trait] +impl MailboxSender for RuntimeSender { + fn source(&self) -> &SessionAddr { + self.sender.source() + } + async fn send(&self, target: SessionAddr, text: String, mime: String) -> MailboxResult { + self.send_with_id(target, text, mime, uuid::Uuid::new_v4()).await + } +} +impl RuntimeSender { + pub(crate) async fn send_with_id( + &self, + target: SessionAddr, + text: String, + mime: String, + id: uuid::Uuid, + ) -> MailboxResult { + let mut published = self.sender.send_with_id(target.clone(), text, mime, id).await?; + if target.instance != self.runtime.instance { + return Ok(published); + } + let authority = MailboxAuthority::local(self.runtime.workspace.clone(), self.source().clone(), target.clone())?; + let pending = self.runtime.store.pending_outbox(&self.scope, self.source())?; + let outbound = pending + .iter() + .find(|pending| pending.message().id == published.message_id) + .ok_or(MailboxError::CorruptState)?; + let receipt = self.runtime.store.accept(&authority, outbound.message().clone())?; + self.runtime + .store + .acknowledge(&self.scope, &target, published.message_id, receipt.state)?; + published.ack_state = Some(receipt.state); + self.runtime.wake(&target); + Ok(published) + } +} + +impl SessionInbox { + pub(crate) fn live(&self) -> bool { + self.runtime.store.validate_scope(&self.scope, &self.address).is_ok() + } + pub fn take_notification(&mut self) -> bool { + self.receiver.try_recv().is_ok() + } + pub async fn notified(&mut self) { + let _ = self.receiver.recv().await; + } + pub fn poll(&mut self) -> MailboxResult> { + self.runtime.store.validate_scope(&self.scope, &self.address)?; + let execution = + self.runtime + .store + .execution_guard(&self.scope, &self.address, uuid::Uuid::new_v4().to_string())?; + let mut inputs: Vec<_> = self + .runtime + .ready + .lock() + .remove(&self.address) + .unwrap_or_default() + .into_iter() + .collect(); + for _ in 0..1 { + let Some(delivery) = self.runtime.store.deliver(&self.scope, &self.address)? else { + break; + }; + let message = delivery.message().clone(); + let receipt = self.runtime.store.adopt(&delivery)?; + let text = crate::session_worker::mailbox::user_text(&message)?; + inputs.push(MessageInput { + _lease: self.runtime.store.hold_input(&self.scope, &self.address)?, + scope: self.scope.scope_id, + text, + message, + receipt, + }); + } + drop(execution); + Ok(inputs) + } +} + +impl super::mailbox::MailboxCacheDrainer for MessagingRuntime { + fn drain(&self, scope: uuid::Uuid) { + self.ready.lock().retain(|_, inputs| { + inputs.retain(|input| input.scope != scope); + !inputs.is_empty() + }); + self.inboxes.lock().retain(|_, (registered, sender)| { + if *registered == scope { + let _ = sender.try_send(()); + false + } else { + true + } + }); + } +} diff --git a/src/messaging/types.rs b/src/messaging/types.rs index a5212188f..8cb845698 100644 --- a/src/messaging/types.rs +++ b/src/messaging/types.rs @@ -140,7 +140,7 @@ pub struct MessageAuth { pub issuer: String, /// Verified subject. pub subject: String, - /// Key-possession method (`jwt` or `mtls`). + /// Key-possession method (`mtls`). pub method: String, } @@ -152,6 +152,7 @@ pub struct MessageBody { pub mime: String, /// Raw body bytes. #[serde(default)] + #[serde(with = "body_base64")] pub bytes: Vec, } @@ -326,3 +327,20 @@ mod tests { assert_ne!(request_digest(&a), request_digest(&b)); } } + +mod body_base64 { + use base64::Engine as _; + use serde::{Deserialize, Deserializer, Serializer}; + pub fn serialize(bytes: &[u8], serializer: S) -> Result { + serializer.serialize_str(&base64::engine::general_purpose::STANDARD.encode(bytes)) + } + pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result, D::Error> { + let text = String::deserialize(deserializer)?; + if text.len() > 352 * 1024 { + return Err(serde::de::Error::custom("message_too_large")); + } + base64::engine::general_purpose::STANDARD + .decode(text) + .map_err(serde::de::Error::custom) + } +} diff --git a/src/messaging/worker.rs b/src/messaging/worker.rs new file mode 100644 index 000000000..5ad6126c4 --- /dev/null +++ b/src/messaging/worker.rs @@ -0,0 +1,233 @@ +//! Parent-owned durable worker mailbox, bound to the sealed logical session. +use super::{DeliveryState, runtime::MessagingRuntime, send::MailboxSender}; +use crate::session_worker::{ + frames::{WorkerControlQueue, WorkerFrameChannels}, + mailbox_binding::{WorkerMailboxBinding, WorkerMailboxFactory}, + protocol::{WorkerControlFrame, WorkerManifest, WorkerOutputFrame}, +}; +use anyhow::{Context, Result}; +use std::{collections::HashMap, sync::Arc}; +use tokio::sync::mpsc; +use tokio_util::sync::CancellationToken; + +pub(crate) struct WorkerMailboxes { + runtime: Arc, + owners: parking_lot::Mutex>>, +} +struct WorkerOwner { + cancel: CancellationToken, + pending: parking_lot::Mutex>, + execution: parking_lot::Mutex>, + task: parking_lot::Mutex>>, + scope: crate::messaging::mailbox::MailboxScope, + address: super::SessionAddr, +} +impl WorkerMailboxes { + pub(crate) fn for_config(config: &crate::config::Config) -> Result> { + static FACTORIES: std::sync::OnceLock>>> = + std::sync::OnceLock::new(); + let runtime = MessagingRuntime::for_config(config)?; + let mut factories = FACTORIES.get_or_init(Default::default).lock(); + Ok(factories + .entry(config.workspace_dir.clone()) + .or_insert_with(|| { + Arc::new(Self { + runtime, + owners: Default::default(), + }) + }) + .clone()) + } +} +impl WorkerMailboxFactory for WorkerMailboxes { + fn bind(&self, manifest: &WorkerManifest) -> Result { + let owner = manifest.owner_id.as_deref().context("worker message owner missing")?; + let address = self.runtime.address( + owner, + &manifest.session_scope_key, + manifest.agent_id.as_deref().unwrap_or("main"), + ); + let inbox = self.runtime.register(address.clone())?; + let scope = self.runtime.resolve_scope(&address)?; + let execution = self + .runtime + .store + .execution_guard(&scope, &address, manifest.run_id.clone())?; + let sender = self.runtime.bind( + address.clone(), + manifest + .ordinary_source + .as_ref() + .and_then(|source| source.input.as_ref()) + .or_else(|| { + manifest + .operator_source + .as_ref() + .and_then(|source| source.input.as_ref()) + }) + .map(|input| input.event_id.as_str()), + )?; + let auth = crate::session_worker::frame_auth::FrameAuth::parent(&manifest.run_id)?; + let (controls, receiver) = mpsc::channel(64); + let (outputs, mut output_rx) = mpsc::channel(64); + let cancel = CancellationToken::new(); + let owner = Arc::new(WorkerOwner { + cancel: cancel.clone(), + pending: Default::default(), + execution: parking_lot::Mutex::new(Some(execution)), + task: Default::default(), + scope: scope.clone(), + address: address.clone(), + }); + anyhow::ensure!( + self.owners + .lock() + .insert(manifest.run_id.clone(), owner.clone()) + .is_none(), + "worker mailbox already bound" + ); + let runtime = self.runtime.clone(); + let target = address.clone(); + let stop = cancel; + let actor_owner = owner.clone(); + let task = tokio::spawn(async move { + let _inbox = inbox; + let pending = &actor_owner.pending; + let mut interval = tokio::time::interval(std::time::Duration::from_millis(100)); + loop { + let result: Result<()> = tokio::select! { + () = stop.cancelled() => break, + frame = output_rx.recv() => { + match frame { + Some(WorkerOutputFrame::Message { envelope }) => { + // Only the target and data are wire input. Sender, chain, + // pin, sequence and authority are reconstructed here. + async { + let to = runtime.alias(sender.source(), &serde_json::to_value(&envelope.to)?)?; + let text = String::from_utf8(envelope.body.bytes)?; + sender.send_with_id(to, text, envelope.body.mime, envelope.id).await?; + Ok(()) + }.await + } + Some(WorkerOutputFrame::Ack { message_id, state: DeliveryState::Consumed }) => { + let delivery = pending.lock().remove(&message_id); + delivery.map_or_else(||Ok(()),|delivery|runtime.store.adopt(&delivery).and_then(|receipt|runtime.adopted(delivery.message().clone(),receipt)).map_err(Into::into)) + } + Some(WorkerOutputFrame::Ack { .. }) => Ok(()), + None => break, + _ => Err(anyhow::anyhow!("unregistered worker broker frame")), + } + } + _ = interval.tick() => { + async { + runtime.store.validate_scope(&scope, &target)?; + if pending.lock().len() < 64 { + if let Some(delivery) = runtime.store.deliver(&scope, &target)? { + let frame = WorkerControlFrame::Message { envelope: Box::new(delivery.message().clone()) }; + let id = delivery.message().id; + pending.lock().insert(id, delivery); + controls.send(frame).await.context("worker control closed")?; + } + } + Ok(()) + }.await + } + }; + if let Err(error) = result { + tracing::warn!(error=%crate::agent::diagnostics::error_class(&error), "worker mailbox stopped"); + break; + } + } + }); + *owner.task.lock() = Some(task); + Ok(WorkerMailboxBinding { + address, + frames: WorkerFrameChannels { + controls: WorkerControlQueue { + receiver, + auth: Some(auth), + owner, + }, + outputs, + }, + }) + } + fn release(&self, run: &str, joined: bool) { + if joined && let Some(owner) = self.owners.lock().remove(run) { + owner.cancel.cancel(); + let task = owner.task.lock().take(); + let runtime = self.runtime.clone(); + tokio::spawn(async move { + if let Some(task) = task { + let _ = task.await; + } + owner.pending.lock().clear(); + drop(owner.execution.lock().take()); + let _ = runtime.store.recover_delivery(&owner.scope, &owner.address); + runtime.wake(&owner.address); + }); + } + } +} + +pub(crate) struct WorkerSender { + pub(crate) address: super::SessionAddr, +} +#[async_trait::async_trait] +impl MailboxSender for WorkerSender { + fn source(&self) -> &super::SessionAddr { + &self.address + } + async fn send( + &self, + target: super::SessionAddr, + text: String, + mime: String, + ) -> super::mailbox::MailboxResult { + use super::{ + IdempotencyKey, MessageBody, MessageKind, PrxMessage, RecipientPin, + mailbox::{MailboxError, MailboxPublished, MailboxSendState}, + }; + super::mailbox::validate_body(&mime, text.as_bytes())?; + let id = uuid::Uuid::new_v4(); + let message = PrxMessage { + id, + idempotency: IdempotencyKey::parse(&id.to_string()).map_err(|_| MailboxError::InvalidMetadata)?, + stream_id: None, + seq: 0, + ts: 0, + from: self.address.clone(), + to: target, + to_pin: RecipientPin { + incarnation: uuid::Uuid::nil(), + generation: 0, + token: String::new(), + }, + in_reply_to: None, + hop_count: 0, + ancestry: Vec::new(), + kind: MessageKind::Data, + body: MessageBody { + mime, + bytes: text.into_bytes(), + }, + origin: None, + auth: None, + exec: None, + canonical_hash: None, + }; + crate::session_worker::stdout::frame(&WorkerOutputFrame::Message { + envelope: Box::new(message), + }) + .map_err(|_| MailboxError::Storage)?; + Ok(MailboxPublished { + row_id: 0, + message_id: id, + stream_id: uuid::Uuid::nil(), + seq: 0, + state: MailboxSendState::Pending, + ack_state: None, + error: None, + }) + } +} diff --git a/src/providers/catalog/resolver_tests.rs b/src/providers/catalog/resolver_tests.rs index ea98861b2..16be04d5f 100644 --- a/src/providers/catalog/resolver_tests.rs +++ b/src/providers/catalog/resolver_tests.rs @@ -580,6 +580,7 @@ fn agent_and_route_keys_are_bound_to_their_entries_provider() { config.agents.insert( "coder".to_string(), crate::config::DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), approval_wait_secs: 600, limits: crate::config::AgentLimits::default(), provider: "claude-code".to_string(), diff --git a/src/providers/credential_containment_tests.rs b/src/providers/credential_containment_tests.rs index 550eb6bbe..fb428628e 100644 --- a/src/providers/credential_containment_tests.rs +++ b/src/providers/credential_containment_tests.rs @@ -197,6 +197,7 @@ fn configured_providers_are_every_provider_the_operator_named() { config.agents = std::collections::HashMap::from([( "coder".to_string(), crate::config::DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), approval_wait_secs: 600, limits: crate::config::AgentLimits::default(), provider: "groq".to_string(), diff --git a/src/runtime/child_source/golden_effective_config.json b/src/runtime/child_source/golden_effective_config.json index 679b2f856..d5b4d71c2 100644 --- a/src/runtime/child_source/golden_effective_config.json +++ b/src/runtime/child_source/golden_effective_config.json @@ -1 +1 @@ -{"a2a":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"client_ca_path":null,"credentials":{},"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"remote_tree":{"max_connections":4,"max_scheduled":4,"max_sends":4,"max_spawned":16},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"tls_cert_path":null,"tls_key_path":null,"trusted_trust_domains":[]},"agent":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2},"agents":{},"api_key":null,"api_url":null,"auth":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"},"autonomy":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":500,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true},"browser":{"allowed_domains":[],"computer_use":{"api_key":null}},"channels_config":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null},"chat":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2},"compliance":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}},"composio":{"api_key":null,"entity_id":"default"},"cost":{"allow_override":false,"daily_limit_usd":10.0,"monthly_limit_usd":100.0,"prices":{"alpha/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0},"zeta/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0}},"warn_at_percent":80},"cron":{"max_run_history":50},"decision_engine":{"backend":{"circuit_breaker":{"cooldown_secs":60,"failure_threshold":5},"credential_ref":"","endpoint":"","kind":"auto","max_request_bytes":65536,"max_response_bytes":262144,"model":"","pinned_snapshot":"","remote_enabled":false,"timeout_ms":250},"candidates":5,"enabled":false,"latency_budget_ms":500,"max_candidates":12,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"token_ratio_limit":0.3499999940395355},"default_model":"anthropic/claude-sonnet-5","default_provider":"openrouter","default_temperature":0.7,"embedding_routes":[],"gateway":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":false,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60},"heartbeat":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."},"http_request":{"max_response_size":1000000,"timeout_secs":30},"identity":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"},"identity_bindings":[],"mcp":{"servers":{}},"mcp_server":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true},"media":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"},"memory":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7},"model_routes":[],"model_settings":{},"multimodal":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4},"nodes":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}},"observability":{"backend":"none","otel_endpoint":null,"otel_service_name":null},"plugins":{"enabled":false},"providers":{"ollama":{"num_ctx":null}},"proxy":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"zeroclaw","services":[]},"query_classification":{"rules":[]},"reliability":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2},"router":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]},"runtime":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null},"scheduler":{"claim_lease_secs":90,"max_tasks":64},"secrets":{"encrypt":true},"security":{"audit":{"log_path":"audit.log","max_size_mb":100}},"self_system":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24},"sessions_spawn":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null},"skill_rag":{"top_k":32},"skills":{"open_skills_dir":null,"openclaw_skills_dir":null},"skills_lifecycle":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]},"smart_group":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5},"storage":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}},"task_routing":{"default_intent":"simple","rules":[]},"tool_tiering":{"always_exclude":[],"always_include":[],"channel_exclude":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","git_operations","skills_manage","memory_reindex","document_sync","document_ingest"]},"tunnel":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null},"user_policies":[],"web_search":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15},"webhook":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null},"xin":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}} \ No newline at end of file +{"a2a":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trust_domain":"prx.local","trusted_trust_domains":[]},"agent":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"messaging":{"inbound":true},"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2},"agents":{},"api_key":null,"api_url":null,"auth":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"},"autonomy":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":500,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true},"browser":{"allowed_domains":[],"computer_use":{"api_key":null}},"channels_config":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null},"chat":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2},"compliance":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}},"composio":{"api_key":null,"entity_id":"default"},"cost":{"allow_override":false,"daily_limit_usd":10.0,"monthly_limit_usd":100.0,"prices":{"alpha/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0},"zeta/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0}},"warn_at_percent":80},"cron":{"max_run_history":50},"decision_engine":{"backend":{"circuit_breaker":{"cooldown_secs":60,"failure_threshold":5},"credential_ref":"","endpoint":"","kind":"auto","max_request_bytes":65536,"max_response_bytes":262144,"model":"","pinned_snapshot":"","remote_enabled":false,"timeout_ms":250},"candidates":5,"enabled":false,"latency_budget_ms":500,"max_candidates":12,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"token_ratio_limit":0.3499999940395355},"default_model":"anthropic/claude-sonnet-5","default_provider":"openrouter","default_temperature":0.7,"embedding_routes":[],"gateway":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":false,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60},"heartbeat":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."},"http_request":{"max_response_size":1000000,"timeout_secs":30},"identity":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"},"identity_bindings":[],"mcp":{"servers":{}},"mcp_server":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true},"media":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"},"memory":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7},"model_routes":[],"model_settings":{},"multimodal":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4},"nodes":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}},"observability":{"backend":"none","otel_endpoint":null,"otel_service_name":null},"plugins":{"enabled":false},"providers":{"ollama":{"num_ctx":null}},"proxy":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"zeroclaw","services":[]},"query_classification":{"rules":[]},"reliability":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2},"router":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]},"runtime":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null},"scheduler":{"claim_lease_secs":90,"max_tasks":64},"secrets":{"encrypt":true},"security":{"audit":{"log_path":"audit.log","max_size_mb":100}},"self_system":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24},"sessions_spawn":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null},"skill_rag":{"top_k":32},"skills":{"open_skills_dir":null,"openclaw_skills_dir":null},"skills_lifecycle":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]},"smart_group":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5},"storage":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}},"task_routing":{"default_intent":"simple","rules":[]},"tool_tiering":{"always_exclude":[],"always_include":[],"channel_exclude":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","git_operations","skills_manage","memory_reindex","document_sync","document_ingest"]},"tunnel":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null},"user_policies":[],"web_search":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15},"webhook":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null},"xin":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}} \ No newline at end of file diff --git a/src/runtime/child_source/tests.rs b/src/runtime/child_source/tests.rs index ddf9eb282..f9789e368 100644 --- a/src/runtime/child_source/tests.rs +++ b/src/runtime/child_source/tests.rs @@ -851,7 +851,7 @@ fn golden_constraints_and_effective_config_payloads() { let zeta = literal.find(r#""zeta/model":{"#).expect("test: zeta price"); assert!(alpha < zeta, "the literal holds the nested maps sorted"); // The seal is recomputed with `ring` over the literal and pinned. - const EFFECTIVE_CONFIG_SEAL: &str = "2d058900ab3ab268628d973f4e4f6336a4613ac0d93c52bbeb76c7a2d195081c"; + const EFFECTIVE_CONFIG_SEAL: &str = "a80a6369db57cbb88d19e79b426628f9b973373f96d16bf7c73e0a5649f8b5db"; assert_eq!( golden_state_fingerprint(&k_child, &[b"process-effective-config-v1", &expected]), EFFECTIVE_CONFIG_SEAL diff --git a/src/runtime/mode.rs b/src/runtime/mode.rs index 62daad557..dfc85ff48 100644 --- a/src/runtime/mode.rs +++ b/src/runtime/mode.rs @@ -512,6 +512,10 @@ pub async fn dispatch(command: Commands, config: Config) -> Result<()> { Ok(()) } + Commands::A2a { command } => { + println!("{}", openprx::messaging::a2a::cli::run(command, config).await?); + Ok(()) + } Commands::Memory { memory_command } => handle_memory_command(memory_command, &config).await, Commands::Evolution { diff --git a/src/runtime/operator_spawn.rs b/src/runtime/operator_spawn.rs index 92a132b8a..396da1e45 100644 --- a/src/runtime/operator_spawn.rs +++ b/src/runtime/operator_spawn.rs @@ -10,6 +10,9 @@ use std::sync::{ use tokio_util::sync::CancellationToken; pub(crate) struct OperatorSpawnSource { + message_event: Option, + message_permit: Option>, + message_input: Option, continuation: Option, proof: OwnedTurnSourceProof, generation: Arc, @@ -87,6 +90,9 @@ impl OperatorSpawnSource { "operator model source differs from pinned PMM selection" ); Ok(Self { + message_event: None, + message_permit: None, + message_input: None, continuation: None, catalog, resolved, @@ -120,6 +126,59 @@ impl OperatorSpawnSource { Ok(self) } + /// A mailbox wake authorizes exactly one existing receiver session. It + /// never authorizes a new spawn or an operator command in the message body. + pub(crate) async fn for_message( + mut self, + record: crate::memory::child_sessions::ChildSessionRecord, + input: &crate::messaging::runtime::MessageInput, + ) -> anyhow::Result { + let runtime = crate::messaging::runtime::MessagingRuntime::for_config(&self.generation.effective)?; + input.verify(&runtime)?; + let id = input + .receipt + .adopted_message_event_id + .ok_or_else(|| anyhow::anyhow!("mailbox adoption missing"))? + .to_string(); + let event = self + .fabric + .memory() + .find_owned_message_event(&record.workspace, &record.owner, &id) + .await? + .ok_or_else(|| anyhow::anyhow!("mailbox input is no longer live"))?; + anyhow::ensure!( + input.message.to.session == record.session_key + && input.message.to.owner == record.owner + && event.session_key.as_deref() == Some(record.session_key.as_str()) + && event.role == "user" + && event.source.as_str() == "prx_mailbox" + && event.content == input.text + && input.auto_start(), + "mailbox wake identity differs" + ); + self = self.for_continuation(record)?; + let runtime = crate::messaging::runtime::MessagingRuntime::for_config(&self.generation.effective)?; + let scope = runtime.resolve_scope(&input.message.to)?; + let root = input.message.to.agent.clone(); + runtime.store.validate_scope(&scope, &input.message.to)?; + self.message_permit = + crate::runtime::agent_admission::admit(&self.generation.effective, self.proof.owner_id(), &root)? + .map(Arc::new); + self.message_event = Some(id); + self.message_input = Some(input.clone()); + Ok(self) + } + + pub(crate) const fn is_message_continuation(&self) -> bool { + self.message_event.is_some() && self.continuation.is_some() + } + pub(crate) fn message_input(&self) -> Option { + self.message_input.clone() + } + pub(crate) fn message_permit(&self) -> Option> { + self.message_permit.clone() + } + pub(crate) async fn scope(self, work: F) -> F::Output { let _lifetime = OperatorLifetime(self.cancellation.clone()); OPERATOR_SPAWN.scope(Arc::new(self), work).await @@ -162,7 +221,10 @@ impl OperatorSpawnSource { scope.channel = Some(self.proof.policy_channel().to_owned()); scope.sender = Some(self.proof.policy_sender().to_owned()); scope.recipient = self.proof.memory_scope().chat_id.clone(); - scope.causation_event_id = self.proof.source_event_id().map(str::to_owned); + scope.causation_event_id = self + .message_event + .clone() + .or_else(|| self.proof.source_event_id().map(str::to_owned)); scope.config_generation_id = Some(self.generation.id.0); scope.config_source_revision = Some(self.generation.source_revision.fingerprint_sha256.clone()); Ok(()) @@ -208,15 +270,15 @@ pub(crate) fn claim(args: &serde_json::Value) -> anyhow::Result - args.get("session_key").and_then(serde_json::Value::as_str) == Some(record.session_key.as_str()) - && args.get("mode").and_then(serde_json::Value::as_str) == Some(record.mode.as_str()) - && args.get("agent").and_then(serde_json::Value::as_str).unwrap_or("main") == record.agent, - None => !["session_key", "mode", "agent"] + && source.continuation.as_ref().map_or_else( + || !["session_key", "mode", "agent"] .iter() .any(|key| args.get(key).is_some()), - }, + |record| args.get("session_key").and_then(serde_json::Value::as_str) + == Some(record.session_key.as_str()) + && args.get("mode").and_then(serde_json::Value::as_str) == Some(record.mode.as_str()) + && args.get("agent").and_then(serde_json::Value::as_str).unwrap_or("main") == record.agent + ), "operator spawn differs from captured command" ); anyhow::ensure!( diff --git a/src/runtime/tasks_cli.rs b/src/runtime/tasks_cli.rs index bf03ad00f..432a48044 100644 --- a/src/runtime/tasks_cli.rs +++ b/src/runtime/tasks_cli.rs @@ -601,6 +601,8 @@ const fn one() -> u32 { /// acknowledgements that rode along. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AssignmentPull { + #[serde(default)] + pub messages: Vec, pub assignments: Vec, #[serde(default)] pub acked: usize, @@ -662,12 +664,23 @@ pub async fn pull_chat_assignments( session_token: &str, ack: &[String], max: Option, +) -> Result { + pull_chat_inbox(endpoint, session_id, session_token, ack, max, None).await +} + +pub async fn pull_chat_inbox( + endpoint: &TasksEndpoint, + session_id: &str, + session_token: &str, + ack: &[String], + max: Option, + message_target: Option<&crate::messaging::SessionAddr>, ) -> Result { let client = client()?; let path = format!("/api/chat-sessions/{}/inbox/pull", urlencoding::encode(session_id)); let response = endpoint .session_request(&client, reqwest::Method::POST, &path, session_token) - .json(&serde_json::json!({ "ack": ack, "max": max })) + .json(&serde_json::json!({ "ack": ack, "max": max, "message_target": message_target })) .send() .await .map_err(|error| unreachable_hint(endpoint, &error))?; diff --git a/src/session_worker/frame_auth.rs b/src/session_worker/frame_auth.rs new file mode 100644 index 000000000..9ad0d037c --- /dev/null +++ b/src/session_worker/frame_auth.rs @@ -0,0 +1,98 @@ +//! Run-bound, ordered authentication for mailbox frames on inherited pipes. +use anyhow::{Context, Result, ensure}; +use base64::Engine as _; +use serde::{Deserialize, Serialize}; +use std::sync::{ + Arc, + atomic::{AtomicU64, Ordering}, +}; + +#[derive(Clone)] +pub struct FrameAuth { + key: Arc, + run: String, + send: Arc, + receive: Arc, + outgoing: &'static str, + incoming: &'static str, +} +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct SignedFrame { + kind: String, + run: String, + sequence: u64, + frame: serde_json::Value, + mac: String, +} +impl FrameAuth { + pub(crate) fn parent(run: &str) -> Result { + Ok(Self::new( + crate::session_worker::transport_key::TransportSecret::for_launch()?.hmac_key(), + run, + false, + )) + } + pub(crate) fn worker(key: ring::hmac::Key, run: &str) -> Self { + Self::new(key, run, true) + } + fn new(key: ring::hmac::Key, run: &str, worker: bool) -> Self { + Self { + key: Arc::new(key), + run: run.into(), + send: Arc::new(AtomicU64::new(0)), + receive: Arc::new(AtomicU64::new(0)), + outgoing: if worker { "worker" } else { "parent" }, + incoming: if worker { "parent" } else { "worker" }, + } + } + fn payload(&self, direction: &str, sequence: u64, value: &serde_json::Value) -> Result> { + Ok(serde_json::to_vec(&( + "prx-mailbox-frame-v1", + direction, + &self.run, + sequence, + value, + ))?) + } + pub(crate) fn sign(&self, value: &impl Serialize) -> Result { + let frame = serde_json::to_value(value)?; + let previous = self + .send + .try_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_add(1)) + .map_err(|_| anyhow::anyhow!("worker frame sequence exhausted"))?; + let sequence = previous + 1; + let mac = ring::hmac::sign(&self.key, &self.payload(self.outgoing, sequence, &frame)?); + Ok(serde_json::to_value(SignedFrame { + kind: "authenticated_mailbox".into(), + run: self.run.clone(), + sequence, + frame, + mac: base64::engine::general_purpose::STANDARD.encode(mac.as_ref()), + })?) + } + pub(crate) fn verify(&self, value: serde_json::Value) -> Result { + let signed: SignedFrame = + serde_json::from_value(value).context("worker mailbox frame authentication required")?; + ensure!( + signed.kind == "authenticated_mailbox" && signed.run == self.run, + "worker frame run mismatch" + ); + let previous = self.receive.load(Ordering::SeqCst); + ensure!( + previous.checked_add(1) == Some(signed.sequence), + "worker frame sequence mismatch" + ); + let mac = base64::engine::general_purpose::STANDARD.decode(&signed.mac)?; + ring::hmac::verify( + &self.key, + &self.payload(self.incoming, signed.sequence, &signed.frame)?, + &mac, + ) + .map_err(|_| anyhow::anyhow!("worker frame MAC mismatch"))?; + self.receive + .compare_exchange(previous, signed.sequence, Ordering::SeqCst, Ordering::SeqCst) + .map_err(|_| anyhow::anyhow!("concurrent worker frame reader"))?; + Ok(signed.frame) + } +} diff --git a/src/session_worker/frames.rs b/src/session_worker/frames.rs index a0f360348..38c82b22d 100644 --- a/src/session_worker/frames.rs +++ b/src/session_worker/frames.rs @@ -8,6 +8,7 @@ use tokio::sync::mpsc; /// Explicitly supplied by the dormant mailbox runtime; no factory installs it. pub struct WorkerControlQueue { pub receiver: mpsc::Receiver, + pub auth: Option, /// Drops after the receiver and all queued payloads. pub owner: std::sync::Arc, } @@ -49,6 +50,16 @@ pub async fn read_worker_frames( where R: AsyncRead + Unpin, { + read_worker_frames_authenticated(reader, frames, progress, limit, None).await +} + +pub(crate) async fn read_worker_frames_authenticated( + reader: R, + frames: Option>, + progress: Option>, + limit: u64, + auth: Option, +) -> Result> { use tokio::io::AsyncReadExt; let reader = ProgressReader { inner: reader, @@ -79,6 +90,10 @@ where } let value: serde_json::Value = serde_json::from_slice(&line).context("invalid worker stdout JSON line")?; if value.get("kind").is_some() { + let value = match &auth { + Some(auth) => auth.verify(value)?, + None => value, + }; let frame: WorkerOutputFrame = serde_json::from_value(value).context("invalid worker output frame")?; if let Some(frames) = &frames { frames.send(frame).await.context("worker frame receiver closed")?; diff --git a/src/session_worker/mailbox.rs b/src/session_worker/mailbox.rs index 5dbc638bd..5b037e9ee 100644 --- a/src/session_worker/mailbox.rs +++ b/src/session_worker/mailbox.rs @@ -66,7 +66,6 @@ impl WorkerMailboxSender { return Err(MailboxError::StaleRun); } if message.ancestry.len() != usize::from(message.hop_count) - || message.hop_count > 8 || message.ancestry.last().copied() != message.in_reply_to || message.ancestry.contains(&message.id) { @@ -147,7 +146,10 @@ pub fn user_text(message: &PrxMessage) -> MailboxResult { if matches!(message.body.mime.as_str(), "text/plain" | "text/markdown") && let Ok(text) = std::str::from_utf8(&message.body.bytes) { - return Ok(text.to_owned()); + return Ok(format!( + "[message from {}/{}]\n{text}", + message.from.session, message.from.agent + )); } use base64::Engine as _; Ok(format!( diff --git a/src/session_worker/mailbox_harness.rs b/src/session_worker/mailbox_harness.rs index 95bedd239..4915aa99a 100644 --- a/src/session_worker/mailbox_harness.rs +++ b/src/session_worker/mailbox_harness.rs @@ -55,11 +55,6 @@ impl Factory { record.child_session = Some(crate::chat::sessions::child::ChildSessionMetadata { addr: addr.clone(), provider: None, - recipe: Some(crate::chat::sessions::child::RelaunchRecipe { - addr: addr.clone(), - last_run: Some(manifest.run_id.clone()), - inherited_provenance: manifest.inherited_provenance.clone(), - }), mailbox_projection: std::collections::BTreeMap::new(), }); Ok(record.to_json()?) @@ -188,7 +183,11 @@ impl WorkerMailboxFactory for Factory { Ok(WorkerMailboxBinding { address: worker, frames: WorkerFrameChannels { - controls: WorkerControlQueue { receiver, owner: actor }, + controls: WorkerControlQueue { + auth: Some(crate::session_worker::frame_auth::FrameAuth::parent(&manifest.run_id)?), + receiver, + owner: actor, + }, outputs, }, }) @@ -266,7 +265,6 @@ pub async fn run(workspace: &Path, turns: usize) -> Result<()> { "prx-mailbox-harness".into(), [31; 32], Arc::new(SystemMailboxClock), - config.a2a.remote_tree.clone(), )?; let factory = Arc::new(Factory { memory: Arc::clone(&memory), diff --git a/src/session_worker/mod.rs b/src/session_worker/mod.rs index 8147afaa0..7b3511a7f 100644 --- a/src/session_worker/mod.rs +++ b/src/session_worker/mod.rs @@ -18,3 +18,5 @@ pub mod mailbox_binding; #[cfg(feature = "test-mock")] pub mod mailbox_harness; + +pub mod frame_auth; diff --git a/src/session_worker/runner/mod.rs b/src/session_worker/runner/mod.rs index f717c6338..6be37a621 100644 --- a/src/session_worker/runner/mod.rs +++ b/src/session_worker/runner/mod.rs @@ -68,9 +68,16 @@ async fn run_manifest( } else { (None, None) }; + let frame_auth = manifest + .session_addr + .as_ref() + .map(|_| super::frame_auth::FrameAuth::worker(transport.key.clone(), &manifest.run_id)); + if let Some(auth) = &frame_auth { + super::stdout::authenticate(auth.clone())?; + } let steer_rx = read_stdin_control_frames.then(|| { let (steer_tx, steer_rx) = tokio::sync::mpsc::channel::(STEER_CHANNEL_CAPACITY); - spawn_stdin_control_reader(steer_tx, mailbox_tx); + spawn_stdin_control_reader(steer_tx, mailbox_tx, frame_auth); steer_rx }); run_authenticated_manifest(manifest, steer_rx, mailbox_rx, explicit_config_dir, Some(transport)).await diff --git a/src/session_worker/runner/run.rs b/src/session_worker/runner/run.rs index 76072add8..989618e55 100644 --- a/src/session_worker/runner/run.rs +++ b/src/session_worker/runner/run.rs @@ -681,12 +681,16 @@ async fn run_owned_manifest( crate::tools::SessionsListTool::new(Arc::clone(&active_runs)) .with_shared_memory(Arc::clone(&session_memory), workspace_id.clone()), )); - full_tools.push(Box::new( - crate::tools::SessionsSendTool::with_security(Arc::clone(&active_runs), Arc::clone(&security)) - .with_shared_memory(Arc::clone(&session_memory)) - .with_source_fabric(session_fabric.clone()) - .with_event_recording(config.memory.event_recording_config()), - )); + let mut send_tool = crate::tools::SessionsSendTool::with_security(Arc::clone(&active_runs), Arc::clone(&security)) + .with_shared_memory(Arc::clone(&session_memory)) + .with_source_fabric(session_fabric.clone()) + .with_event_recording(config.memory.event_recording_config()); + if let Some(address) = &manifest.session_addr { + send_tool = send_tool.with_mailbox(Arc::new(crate::messaging::worker::WorkerSender { + address: address.clone(), + })); + } + full_tools.push(Box::new(send_tool)); full_tools.push(Box::new( crate::tools::SubagentsTool::with_security(Arc::clone(&active_runs), Arc::clone(&security)) .with_shared_memory(Arc::clone(&session_memory)) @@ -895,13 +899,10 @@ async fn run_owned_manifest( let mut initial_history: Vec = manifest .seed_history .iter() - .map(|turn| crate::providers::ChatMessage { - role: turn.role.clone(), - content: turn.content.clone(), - }) + .map(|turn| crate::agent::turn_contracts::stored_turn_message(turn.role.clone(), turn.content.clone())) .collect(); if !initial_history.is_empty() { - initial_history.push(crate::providers::ChatMessage::user(&manifest.task)); + initial_history.push(crate::agent::turn_contracts::inbound_user_message(&manifest.task)); } let observer = NoopObserver; diff --git a/src/session_worker/runner/steering.rs b/src/session_worker/runner/steering.rs index 153712cb9..63c45ae53 100644 --- a/src/session_worker/runner/steering.rs +++ b/src/session_worker/runner/steering.rs @@ -46,6 +46,7 @@ use tokio_util::sync::CancellationToken; pub(super) fn spawn_stdin_control_reader( steer_tx: tokio::sync::mpsc::Sender, mut mailbox: Option, + auth: Option, ) { const MAX_CONTROL_LINE: u64 = 2 * 1024 * 1024; std::thread::spawn(move || { @@ -67,7 +68,25 @@ pub(super) fn spawn_stdin_control_reader( continue; } // A malformed frame must never end the run: skip it and keep reading. - let Ok(frame) = serde_json::from_str::(line) else { + let decoded = serde_json::from_str::(line) + .and_then(|value| { + if value.get("kind").and_then(|v| v.as_str()) == Some("authenticated_mailbox") { + auth.as_ref() + .ok_or_else(|| { + serde_json::Error::io(std::io::Error::other("unexpected authenticated frame")) + }) + .and_then(|auth| { + auth.verify(value) + .map_err(|e| serde_json::Error::io(std::io::Error::other(e))) + }) + } else if value.get("kind").and_then(|v| v.as_str()) == Some("message") && auth.is_some() { + Err(serde_json::Error::io(std::io::Error::other("unsigned mailbox frame"))) + } else { + Ok(value) + } + }) + .and_then(serde_json::from_value::); + let Ok(frame) = decoded else { tracing::warn!("session-worker discarded an unparseable stdin control frame"); continue; }; @@ -161,16 +180,16 @@ where segment.await } }; - let (mut advanced, result) = finished; + let (advanced, result) = finished; if result.is_err() { return (advanced, result); } while let Some(message) = mailbox.as_mut().and_then(|inbox| inbox.try_next()) { - let text = match super::super::mailbox::user_text(&message) { + let _text = match super::super::mailbox::user_text(&message) { Ok(text) => text, Err(error) => return (advanced, Err(error.into())), }; - advanced.push(crate::agent::turn_contracts::inbound_user_message_owned(text)); + let ack = mailbox .as_ref() .ok_or(crate::messaging::mailbox::MailboxError::CorruptState) diff --git a/src/session_worker/stdout.rs b/src/session_worker/stdout.rs index d8607af9a..fc39a5b5e 100644 --- a/src/session_worker/stdout.rs +++ b/src/session_worker/stdout.rs @@ -7,7 +7,11 @@ fn write(value: &impl Serialize, terminal: bool) -> Result<()> { static TERMINAL: parking_lot::Mutex = parking_lot::Mutex::new(false); let mut finished = TERMINAL.lock(); ensure!(!*finished, "worker stdout terminal result already emitted"); - let json = serde_json::to_vec(value).context("serialize worker stdout line")?; + let json = if !terminal && let Some(auth) = FRAME_AUTH.get() { + serde_json::to_vec(&auth.sign(value)?)? + } else { + serde_json::to_vec(value).context("serialize worker stdout line")? + }; if terminal { *finished = true; } @@ -19,6 +23,12 @@ fn write(value: &impl Serialize, terminal: bool) -> Result<()> { pub(crate) fn terminal(result: &impl Serialize) -> Result<()> { write(result, true) } +static FRAME_AUTH: std::sync::OnceLock = std::sync::OnceLock::new(); +pub(crate) fn authenticate(auth: super::frame_auth::FrameAuth) -> Result<()> { + FRAME_AUTH + .set(auth) + .map_err(|_| anyhow::anyhow!("worker frame authentication already initialized")) +} pub fn frame(frame: &super::protocol::WorkerOutputFrame) -> Result<()> { write(frame, false) } diff --git a/src/tools/agents_list.rs b/src/tools/agents_list.rs index 9bb260497..67ddd1f52 100644 --- a/src/tools/agents_list.rs +++ b/src/tools/agents_list.rs @@ -106,6 +106,7 @@ mod tests { fn make_agent(provider: &str, model: &str) -> DelegateAgentConfig { DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), approval_wait_secs: 600, limits: crate::config::AgentLimits::default(), provider: provider.to_string(), @@ -160,6 +161,7 @@ mod tests { agents.insert( "super-agent".to_string(), DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), approval_wait_secs: 600, agentic: true, ..make_agent("openai", "gpt-4o") diff --git a/src/tools/capability/catalog.rs b/src/tools/capability/catalog.rs index e1e78b0b4..49e409654 100644 --- a/src/tools/capability/catalog.rs +++ b/src/tools/capability/catalog.rs @@ -1,2369 +1,4 @@ pub(crate) mod process_snapshot; -use super::fingerprint::tool_spec_fingerprint; -use crate::acl::approval_grant::RiskLevel; -use crate::capability::{CapabilityAvailability, CapabilityAvailabilityLevel}; -use crate::security::runtime_key::DecisionKey; -use crate::skills::SkillMetadata; -use crate::tools::capability::contract::{ - ApprovalRequirement, CapabilityId, CapabilityRef, CapabilityTarget, CatalogGeneration, OpId, SchemaFingerprint, - SideEffectClass, -}; -use crate::tools::execution::{ToolAdapterKind, ToolCatalog, ToolDescriptor, ToolEffect, ToolExecutionService}; -use crate::tools::mcp::McpCapabilitySpec; -use crate::tools::traits::{Tool, ToolCategory, ToolSpec}; -use serde_json::{Value, json}; -use sha2::{Digest, Sha256}; -use std::collections::{BTreeMap, BTreeSet}; -use std::sync::Arc; -#[cfg(test)] -use std::sync::OnceLock; - -/// Model exposure is explicit and never inferred from existence in config. -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) enum Exposure { - Direct, - Searchable, - Unavailable { reason: String }, -} - -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) enum ExecutionTarget { - Tool(String), - Skill { name: String, root: String }, - Node { id: String, root: String }, - Hook, -} - -#[derive(Debug, Clone)] -pub(crate) struct CapabilityEntry { - pub id: CapabilityId, - pub public_name: String, - pub root: String, - pub family: CapabilityTarget, - pub namespace: String, - pub summary: String, - pub aliases: Vec, - pub categories: Vec, - /// Lowercased ID, public name and aliases, frozen after all source - /// metadata is attached and before the entry is published. - pub exact_mention_terms: Vec, - pub effect: SideEffectClass, - pub risk: RiskLevel, - pub op_ids: Vec, - pub approval: ApprovalRequirement, - pub channel_eligible: bool, - pub schema: Arc, - /// Serialized size of the pinned schema, computed with the same JSON - /// encoder used by turn cost estimates. - pub schema_bytes: usize, - pub fingerprint: SchemaFingerprint, - pub generation: CatalogGeneration, - pub target: ExecutionTarget, - pub binding_digest: Option<[u8; 32]>, - pub skill_metadata: Option>, - pub exposure: Exposure, - pub availability: CapabilityAvailability, - pub process_worker_compatible: bool, -} - -impl CapabilityEntry { - /// A concrete read-only Skill uses this native loader. Keep registry target - /// representation inside the catalog; decision ranking only needs the fact. - pub(crate) fn loads_read_only_skill(&self, skill: &Self) -> bool { - self.effect == SideEffectClass::ReadOnly - && skill.effect == SideEffectClass::ReadOnly - && matches!((&self.target, &skill.target), - (ExecutionTarget::Tool(name), ExecutionTarget::Skill { root, .. }) if name == root) - } - - /// Native tools whose approval operation derives completely from the - /// proposed arguments. Collection records one exact call before review; - /// it never executes. MCP, plugin and skill names cannot opt into this path. - pub(crate) fn collects_exact_call(&self) -> bool { - self.root == self.public_name - && matches!(&self.target, ExecutionTarget::Tool(name) if name == &self.public_name) - && match self.public_name.as_str() { - "skills_manage" => self.family == CapabilityTarget::NativeTool, - "shell" => matches!(self.family, CapabilityTarget::Filesystem | CapabilityTarget::Shell), - "http_request" => self.family == CapabilityTarget::Web, - _ => false, - } - } - - /// Lifecycle argument collection can follow an unnamed metadata search. - /// Direct publication must not hide that root from discovery. This offers - /// metadata only; collection and execution retain their own approval gates. - pub(crate) fn supports_metadata_discovery(&self) -> bool { - matches!(self.exposure, Exposure::Searchable) - || (matches!(self.exposure, Exposure::Direct) - && self.public_name == "skills_manage" - && self.collects_exact_call()) - } - - /// The (lowercased) request names a grant-bound action of a collectable - /// tool. Other actions need no approval collection: the model may call them - /// in an ordinary turn, and collecting them would end in an error. - pub(crate) fn names_collectable_action(&self, folded_text: &str) -> bool { - self.collects_exact_call() - && (self.public_name != "skills_manage" - || crate::security::approval_operation::SKILLS_MANAGE_GRANT_BOUND_ACTIONS - .iter() - .any(|action| folded_text.contains(action))) - } - - /// Name understood by the execution policy. Synthetic Skill and Node - /// entries dispatch through their registered root and inherit that root's - /// read/write classification; public names remain available for search, - /// exclusion and exact binding. - pub(crate) fn policy_tool_name(&self) -> &str { - match &self.target { - ExecutionTarget::Skill { root, .. } | ExecutionTarget::Node { root, .. } => root, - ExecutionTarget::Tool(_) | ExecutionTarget::Hook => &self.public_name, - } - } - - /// Project the actual execution target into the domain's Plan policy. - /// Aliases/effect labels never substitute for the registered root. - pub(crate) fn plan_intercepted(&self) -> bool { - match &self.target { - ExecutionTarget::Tool(name) => crate::tools::capability::policy::plan_intercepts_tool(name), - ExecutionTarget::Skill { root, .. } | ExecutionTarget::Node { root, .. } => { - crate::tools::capability::policy::plan_intercepts_tool(root) - } - ExecutionTarget::Hook => true, - } - } -} - -/// Inputs outside the finalized executable registry. Callers take these as -/// read-only snapshots of the same runtime generation. -#[derive(Debug, Clone, Default)] -pub(crate) struct CatalogSources { - pub config_generation_id: String, - pub mcp_state_epoch: u64, - pub wasm_generation: u64, - pub skills_dir_epoch: u64, - pub mcp: Vec, - pub skills: Vec, - pub hooks: Vec, - pub nodes: Vec, - pub node_key: Option>, -} - -#[derive(Debug, Clone)] -pub(crate) struct HookSource { - pub event: String, - pub action: String, - pub effect: SideEffectClass, -} - -#[derive(Debug, Clone)] -pub(crate) struct NodeSource { - pub id: String, - pub availability: CapabilityAvailability, - pub binding_digest: [u8; 32], -} - -impl CatalogSources { - /// Snapshot auxiliary metadata without network probes, skill-body - /// hydration or decision-key access. The turn service pins the finalized - /// registry and installs its generation-local key before catalog build. - pub(crate) fn from_runtime_inputs( - config_generation_id: String, - config: &crate::config::Config, - mcp: Vec, - hooks: &crate::hooks::HookDiagnostics, - wasm_generation: u64, - ) -> Self { - let skills = crate::skills::catalog_skill_metadata(&config.workspace_dir, config); - let mut mcp_hasher = Sha256::new(); - let mut mcp_ordered: Vec<_> = mcp.iter().collect(); - mcp_ordered.sort_by(|left, right| (&left.server, &left.tool).cmp(&(&right.server, &right.tool))); - for item in mcp_ordered { - mcp_hasher.update(item.server.len().to_be_bytes()); - mcp_hasher.update(item.server.as_bytes()); - mcp_hasher.update(item.state_digest); - } - let mcp_digest = mcp_hasher.finalize(); - let mut mcp_epoch_bytes = [0_u8; 8]; - mcp_epoch_bytes.copy_from_slice(mcp_digest.get(..8).unwrap_or_default()); - let mut skill_hasher = Sha256::new(); - for skill in &skills { - skill_hasher.update(skill.name.len().to_be_bytes()); - skill_hasher.update(skill.name.as_bytes()); - skill_hasher.update(skill.frontmatter_sha); - skill_hasher.update(skill.location.to_string_lossy().as_bytes()); - } - let skill_digest = skill_hasher.finalize(); - let mut epoch_bytes = [0_u8; 8]; - epoch_bytes.copy_from_slice(skill_digest.get(..8).unwrap_or_default()); - let skills_dir_epoch = u64::from_be_bytes(epoch_bytes); - let hooks = hooks - .events - .iter() - .flat_map(|(event, count)| { - (0..*count).map(move |index| HookSource { - event: event.clone(), - action: format!( - "action_{index}_{}", - hex::encode(hooks.catalog_digest.unwrap_or_default().get(..8).unwrap_or_default()) - ), - effect: SideEffectClass::ProcessExec, - }) - }) - .collect(); - let nodes = config - .nodes - .nodes - .iter() - .map(|node| NodeSource { - id: node.id.clone(), - availability: CapabilityAvailability::configured("remote node configured"), - binding_digest: serde_json::to_vec(node) - .map(|bytes| Sha256::digest(bytes).into()) - .unwrap_or_default(), - }) - .collect(); - Self { - config_generation_id, - mcp_state_epoch: u64::from_be_bytes(mcp_epoch_bytes), - wasm_generation, - skills_dir_epoch, - mcp, - skills, - hooks, - nodes, - node_key: None, - } - } -} - -/// The entrypoint's publication boundary, applied after registry discovery. -#[derive(Clone, Default)] -pub(crate) struct SurfacePolicy { - pub allowed_tools: Option>, - pub excluded_names: BTreeSet, - pub direct_names: BTreeSet, - pub channel_allowed: bool, -} - -impl std::fmt::Debug for SurfacePolicy { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let mut value = f.debug_struct("SurfacePolicy"); - value - .field("excluded_names", &self.excluded_names) - .field("direct_names", &self.direct_names) - .field("channel_allowed", &self.channel_allowed); - // Preserve the established generation fingerprint for unrestricted surfaces. - if let Some(allowed) = &self.allowed_tools { - value.field("allowed_tools", allowed); - } - value.finish() - } -} - -impl SurfacePolicy { - pub(crate) fn permits(&self, name: &str, root: &str, target: &ExecutionTarget) -> bool { - self.allowed_tools.as_ref().is_none_or(|allowed| { - allowed.contains(name) - || matches!(target, ExecutionTarget::Skill { .. } | ExecutionTarget::Node { .. }) - && allowed.contains(root) - }) - } -} - -#[derive(Debug, thiserror::Error)] -pub(crate) enum CatalogError { - #[error("duplicate capability public name or id")] - Duplicate, - #[error("invalid capability identity")] - Identity, - #[error("capability schema is invalid")] - Schema, -} - -#[derive(Debug, thiserror::Error)] -pub(crate) enum StaleCapability { - #[error("capability generation or schema changed")] - Stale, - #[error("capability is unavailable")] - Unavailable, -} - -#[derive(Debug, thiserror::Error)] -#[error("catalog and execution registry differ")] -pub(crate) struct ParityError; - -#[derive(Debug, Clone)] -pub(crate) struct CapabilityCatalog { - entries: Vec, - by_id: BTreeMap, - by_name: BTreeMap, - binding_roots: BTreeSet, - generation: CatalogGeneration, - search_index: super::search::SearchIndex, -} - -pub(crate) struct CatalogView<'a> { - surface: Option<&'a SurfacePolicy>, - #[cfg(test)] - entries: OnceLock>, - generation: CatalogGeneration, - by_id: &'a BTreeMap, - pub(super) search_index: &'a super::search::SearchIndex, - pub(super) all_entries: &'a [CapabilityEntry], - families: [bool; CapabilityTarget::ALL.len()], - channel: bool, -} - -#[derive(Debug, Clone, Default)] -pub(crate) struct CatalogScope { - pub families: BTreeSet, - pub channel: bool, -} - -impl CapabilityCatalog { - pub(crate) fn build( - registry: &[Box], - sources: &CatalogSources, - surface: &SurfacePolicy, - ) -> Result { - let discovered_mcp: BTreeSet<_> = sources.mcp.iter().map(|item| item.spec.name.as_str()).collect(); - let descriptors = ToolCatalog::from_boxed_registry(registry); - let mut entries = Vec::new(); - let mut seen_names = BTreeSet::new(); - let mut seen_ids = BTreeSet::new(); - let mut raw_names = BTreeSet::new(); - for tool in registry { - for spec in tool.specs() { - if !raw_names.insert(spec.name.clone()) { - return Err(CatalogError::Duplicate); - } - } - } - for descriptor in descriptors.descriptors() { - if descriptor.adapter == ToolAdapterKind::McpAlias - && discovered_mcp.contains(descriptor.public_name.as_str()) - { - continue; - } - let family = family_for(descriptor); - let namespace = if descriptor.adapter == ToolAdapterKind::McpAlias { - "mcp".to_string() - } else { - "native".to_string() - }; - let effect = effect_for(descriptor); - let entry = entry_from_spec( - ToolSpec { - name: descriptor.public_name.clone(), - description: descriptor.description.clone(), - parameters: descriptor.parameters.clone(), - }, - descriptor.backend_name.clone(), - namespace, - family, - descriptor.categories.clone(), - effect, - descriptor.availability.clone(), - descriptor.process_worker_compatible, - ExecutionTarget::Tool(descriptor.public_name.clone()), - surface, - )?; - insert(entry, &mut entries, &mut seen_names, &mut seen_ids)?; - } - for discovered in &sources.mcp { - let mut entry = entry_from_spec( - discovered.spec.clone(), - "mcp_call".to_string(), - discovered.server.clone(), - CapabilityTarget::Mcp, - vec![ToolCategory::Automation], - SideEffectClass::Destructive, - CapabilityAvailability::ready("discovered allowed MCP backend"), - true, - ExecutionTarget::Tool(discovered.spec.name.clone()), - surface, - )?; - entry.aliases.push(discovered.tool.clone()); - entry.binding_digest = Some(discovered.state_digest); - let op = OpId::new(&crate::security::op_id::op_id( - "mcp_call", - "call", - &[&discovered.server, &discovered.tool], - )); - entry.op_ids = vec![op.clone()]; - entry.approval = ApprovalRequirement::Required { op_ids: vec![op] }; - insert(entry, &mut entries, &mut seen_names, &mut seen_ids)?; - } - for skill in &sources.skills { - let spec = crate::tools::skills::catalog_skill_read_spec(skill); - let mut entry = entry_from_spec( - spec, - "skill_read".to_string(), - "skill".to_string(), - CapabilityTarget::Skill, - vec![ToolCategory::System], - SideEffectClass::ReadOnly, - CapabilityAvailability::configured("installed skill metadata"), - true, - ExecutionTarget::Skill { - name: skill.name.clone(), - root: "skill_read".to_string(), - }, - surface, - )?; - entry.binding_digest = Some(crate::skills::catalog_skill_binding_digest(skill)); - entry.skill_metadata = Some(Arc::new(skill.clone())); - if entry.public_name != skill.name { - entry.aliases.push(skill.name.clone()); - } - insert(entry, &mut entries, &mut seen_names, &mut seen_ids)?; - } - for hook in &sources.hooks { - let name = format!("hook_{}_{}", hook.event, hook.action); - let mut entry = entry_from_spec( - ToolSpec { - name: name.clone(), - description: "Registered lifecycle observer".to_string(), - parameters: json!({"type":"object","properties":{}}), - }, - "hooks".to_string(), - "hook".to_string(), - CapabilityTarget::Hook, - vec![ToolCategory::Automation], - hook.effect, - CapabilityAvailability::configured("registered lifecycle hook"), - true, - ExecutionTarget::Hook, - surface, - )?; - entry.exposure = Exposure::Unavailable { - reason: "hooks run as observers".to_string(), - }; - insert(entry, &mut entries, &mut seen_names, &mut seen_ids)?; - } - for node in &sources.nodes { - if node.binding_digest == [0; 32] { - return Err(CatalogError::Schema); - } - let key = sources.node_key.as_ref().ok_or(CatalogError::Identity)?; - let id = CapabilityId::remote_node(key, &node.id).map_err(|_| CatalogError::Identity)?; - let name = id - .as_str() - .rsplit(':') - .next() - .ok_or(CatalogError::Identity)? - .to_string(); - let mut entry = entry_from_spec( - ToolSpec { - name, - description: "Configured remote node shell".to_string(), - parameters: json!({"type":"object","properties":{"node":{"const":node.id}}}), - }, - "nodes".to_string(), - "node".to_string(), - CapabilityTarget::Shell, - vec![ToolCategory::DevOps], - SideEffectClass::ProcessExec, - node.availability.clone(), - true, - ExecutionTarget::Node { - id: node.id.clone(), - root: "nodes".to_string(), - }, - surface, - )?; - entry.id = id; - entry.binding_digest = Some(node.binding_digest); - // Cancel includes a runtime task ID and cannot be represented by - // a fixed node-level approval scope here. - entry.op_ids = ["exec", "write"] - .into_iter() - .map(|action| OpId::new(&format!("nodes:{action}:{}", node.id))) - .collect(); - entry.approval = ApprovalRequirement::Required { - op_ids: entry.op_ids.clone(), - }; - insert(entry, &mut entries, &mut seen_names, &mut seen_ids)?; - } - entries.sort_by(|left, right| left.id.cmp(&right.id)); - let generation = generation_of(sources, surface, &entries); - Ok(Self::from_entries(entries, generation)) - } - - fn from_entries(mut entries: Vec, generation: CatalogGeneration) -> Self { - let mut by_id = BTreeMap::new(); - let mut by_name = BTreeMap::new(); - let mut binding_roots = BTreeSet::new(); - for (index, entry) in entries.iter_mut().enumerate() { - entry.generation = generation; - by_id.insert(entry.id.clone(), index); - by_name.insert(entry.public_name.clone(), index); - if entry.binding_digest.is_some() { - binding_roots.insert(entry.root.clone()); - } - } - let search_index = super::search::SearchIndex::build(&entries); - Self { - entries, - by_id, - by_name, - binding_roots, - generation, - search_index, - } - } - - pub(crate) const fn generation(&self) -> &CatalogGeneration { - &self.generation - } - - pub(crate) fn view(&self, scope: &CatalogScope) -> CatalogView<'_> { - CatalogView { - surface: None, - search_index: &self.search_index, - by_id: &self.by_id, - all_entries: &self.entries, - families: CapabilityTarget::ALL.map(|family| scope.families.is_empty() || scope.families.contains(&family)), - channel: scope.channel, - #[cfg(test)] - entries: OnceLock::new(), - generation: self.generation, - } - } - - /// Every pinned public name, for surface enumeration. Callers resolve each - /// name live before treating it as a candidate. - pub(crate) fn public_names(&self) -> impl Iterator + '_ { - self.by_name.keys().map(String::as_str) - } - - pub(crate) fn entry_for_public_name(&self, name: &str) -> Option<&CapabilityEntry> { - self.by_name.get(name).and_then(|index| self.entries.get(*index)) - } - - pub(crate) fn resolve<'a>( - &self, - refs: impl IntoIterator, - ) -> Result, StaleCapability> { - refs.into_iter() - .map(|reference| { - let entry = self - .by_id - .get(&reference.id) - .and_then(|index| self.entries.get(*index)) - .ok_or(StaleCapability::Stale)?; - if reference.generation != self.generation || reference.fingerprint != entry.fingerprint { - return Err(StaleCapability::Stale); - } - if matches!(entry.exposure, Exposure::Unavailable { .. }) { - return Err(StaleCapability::Unavailable); - } - Ok(entry) - }) - .collect() - } - - /// Check a child's actual executor against the immutable parent catalog. - /// Omitted parent capabilities are not part of the child executor; every - /// granted reference and its root/dispatch binding must remain exact. - pub(crate) fn check_child_parity( - &self, - exec: &ToolExecutionService, - scope: &super::child::VerifiedChildScope, - ) -> Result<(), ParityError> { - let (manifest, parent) = scope.gate_inputs(); - manifest.verify(parent).map_err(|_| ParityError)?; - if manifest.catalog_generation != self.generation { - return Err(ParityError); - } - // Full children inherit the complete level surface, including parent - // backends this child executor cannot serve. Every served reference - // still needs exact descriptor/binding parity; below Full the entire - // sealed subset must be executable as before. - if manifest.authority.level == crate::security::AutonomyLevel::Full { - self.check_published_parity(exec, &self.served_references(exec, &manifest.allowed)) - } else { - self.check_published_parity(exec, &manifest.allowed) - } - } - - /// Whether `exec` registers the backend that runs `entry`. A worker's - /// catalog is its parent's pinned one and can hold entries its own - /// executor never registers (interactive-only tools); such an entry is - /// unserved there, not a parity failure. A registered backend must still - /// match exactly ([`Self::check_published_parity`]). - pub(crate) fn served_by(exec: &ToolExecutionService, entry: &CapabilityEntry) -> bool { - match &entry.target { - ExecutionTarget::Tool(name) => exec.current_descriptor(name).is_some(), - ExecutionTarget::Skill { .. } | ExecutionTarget::Node { .. } => { - exec.current_descriptor(&entry.root).is_some() - } - ExecutionTarget::Hook => false, - } - } - - /// The references of `allowed` whose backend `exec` registers. - pub(crate) fn served_references( - &self, - exec: &ToolExecutionService, - allowed: &std::collections::BTreeSet, - ) -> std::collections::BTreeSet { - allowed - .iter() - .filter(|reference| { - self.by_id - .get(&reference.id) - .and_then(|index| self.entries.get(*index)) - .is_none_or(|entry| Self::served_by(exec, entry)) - }) - .cloned() - .collect() - } - - /// Verify an authenticated publication's exact references against the local - /// executor. Authority and visibility are enforced by the owning service. - pub(crate) fn check_published_parity( - &self, - exec: &ToolExecutionService, - allowed: &std::collections::BTreeSet, - ) -> Result<(), ParityError> { - for reference in allowed { - let entry = self - .by_id - .get(&reference.id) - .and_then(|index| self.entries.get(*index)) - .ok_or(ParityError)?; - if reference.generation != self.generation - || reference.fingerprint != entry.fingerprint - || matches!(entry.exposure, Exposure::Unavailable { .. }) - { - return Err(ParityError); - } - let current_binding = match &entry.target { - ExecutionTarget::Tool(name) => { - let (exact, binding) = exec - .current_descriptor_with_binding(name, entry.binding_digest.is_some()) - .ok_or(ParityError)?; - verify_child_descriptor(entry, &exact)?; - binding - } - ExecutionTarget::Skill { name, .. } | ExecutionTarget::Node { id: name, .. } => { - let root_entry = self.entry_for_public_name(&entry.root).ok_or(ParityError)?; - let root = exec.current_descriptor(&entry.root).ok_or(ParityError)?; - verify_child_descriptor(root_entry, &root)?; - let argument = if matches!(entry.target, ExecutionTarget::Skill { .. }) { - "name" - } else { - "node" - }; - if root.parameters.pointer(&format!("/properties/{argument}")).is_none() - || entry.schema.pointer(&format!("/properties/{argument}/const")) - != Some(&Value::String(name.clone())) - { - return Err(ParityError); - } - exec.current_binding_digest(&entry.root, name) - } - ExecutionTarget::Hook => return Err(ParityError), - }; - if let Some(expected) = entry.binding_digest { - if current_binding != Some(expected) { - return Err(ParityError); - } - } else if !matches!(entry.target, ExecutionTarget::Tool(_)) { - return Err(ParityError); - } - } - Ok(()) - } - - pub(crate) fn check_parity(&self, exec: &ToolExecutionService) -> Result<(), ParityError> { - let live = exec.current_specs_for_parity(); - let mut live_by_index = vec![None; self.entries.len()]; - let mut bindings = BTreeMap::new(); - for root in &self.binding_roots { - if !live - .iter() - .any(|item| item.backend_name == root.as_str() && item.spec.shared_binding_digest().is_snapshot()) - { - bindings.insert(root.as_str(), exec.current_binding_snapshot(root).ok_or(ParityError)?); - } - } - for descriptor in &live { - if !descriptor.configured { - continue; - } - let index = *self.by_name.get(descriptor.spec.name.as_str()).ok_or(ParityError)?; - let slot = live_by_index.get_mut(index).ok_or(ParityError)?; - if slot.replace(descriptor).is_some() { - return Err(ParityError); - } - let entry = self.entries.get(index).ok_or(ParityError)?; - if entry.root != descriptor.backend_name - || descriptor.spec.fingerprint() != entry.fingerprint - || entry.binding_digest.is_some() - && descriptor.spec.shared_binding_digest().or_else_live(|| { - bindings - .get(entry.root.as_str()) - .and_then(|snapshot| snapshot.get(descriptor.spec.name.as_str())) - .copied() - }) != entry.binding_digest - { - return Err(ParityError); - } - } - let live_for = |name: &str| { - self.by_name - .get(name) - .and_then(|index| live_by_index.get(*index)) - .copied() - .flatten() - .ok_or(ParityError) - }; - for entry in &self.entries { - if matches!(entry.exposure, Exposure::Unavailable { .. }) { - continue; - } - if let ExecutionTarget::Tool(name) = &entry.target { - let exact = live_for(name)?; - if exact.backend_name != entry.root || exact.spec.fingerprint() != entry.fingerprint { - return Err(ParityError); - } - } else { - let current = live_for(&entry.root)?; - if !current.configured { - return Err(ParityError); - } - // A synthetic target must bind the exact dispatch argument - // accepted by the root contract, not only its root name. - let binding = match &entry.target { - ExecutionTarget::Skill { name, .. } => ("name", name.as_str()), - ExecutionTarget::Node { id, .. } => ("node", id.as_str()), - ExecutionTarget::Hook | ExecutionTarget::Tool(_) => return Err(ParityError), - }; - if current - .spec - .parameters - .pointer(&format!("/properties/{}", binding.0)) - .is_none() - || entry.schema.pointer(&format!("/properties/{}/const", binding.0)) - != Some(&Value::String(binding.1.to_string())) - || current.spec.shared_named_binding(binding.1).or_else_live(|| { - bindings - .get(entry.root.as_str()) - .and_then(|snapshot| snapshot.get(binding.1)) - .copied() - }) != entry.binding_digest - { - return Err(ParityError); - } - } - } - Ok(()) - } -} - -fn verify_child_descriptor(entry: &CapabilityEntry, current: &ToolDescriptor) -> Result<(), ParityError> { - let backend_matches = entry.root == current.backend_name; - if entry.public_name != current.public_name - || !backend_matches - || current.availability.level < CapabilityAvailabilityLevel::Configured - || crate::tools::schema::SchemaCleanr::validate(¤t.parameters).is_err() - || tool_spec_fingerprint(¤t.public_name, ¤t.description, ¤t.parameters) != entry.fingerprint - { - return Err(ParityError); - } - Ok(()) -} - -impl<'a> CatalogView<'a> { - /// Narrow a view without copying entries, schemas, bindings or the search index. - pub(crate) const fn with_surface(&self, surface: &'a SurfacePolicy) -> Self { - Self { - surface: Some(surface), - #[cfg(test)] - entries: OnceLock::new(), - generation: self.generation, - by_id: self.by_id, - search_index: self.search_index, - all_entries: self.all_entries, - families: self.families, - channel: self.channel, - } - } - - pub(crate) fn directly_exposes(&self, entry: &CapabilityEntry) -> bool { - matches!(entry.exposure, Exposure::Direct) - || self - .surface - .is_some_and(|surface| surface.direct_names.contains(&entry.public_name)) - } - - pub(crate) fn surface_excludes(&self, entry: &CapabilityEntry) -> bool { - self.surface.is_some_and(|surface| { - !surface.permits(&entry.public_name, &entry.root, &entry.target) - || surface.excluded_names.contains(&entry.public_name) - || surface.excluded_names.contains(&entry.root) - }) - } - - /// Compatibility slice for inspection fixtures. Production decision paths - /// use the borrowing iterator instead of materializing this slice. - #[cfg(test)] - pub(crate) fn entries(&self) -> &[&'a CapabilityEntry] { - self.entries.get_or_init(|| self.iter_entries().collect()) - } - - pub(crate) fn iter_entries(&self) -> impl Iterator + '_ { - self.all_entries.iter().filter(|entry| self.entry_visible(entry)) - } - - fn entry_visible(&self, entry: &CapabilityEntry) -> bool { - self.families - .iter() - .zip(CapabilityTarget::ALL) - .any(|(allowed, family)| *allowed && family == entry.family) - && (!self.channel || entry.channel_eligible) - && !self.surface_excludes(entry) - && !matches!(entry.exposure, Exposure::Unavailable { .. }) - } - - pub(super) fn is_visible_index(&self, index: usize) -> bool { - self.all_entries - .get(index) - .is_some_and(|entry| self.entry_visible(entry)) - } - - /// Look up a catalog entry before view filtering. Gates need to report - /// configured exclusions before reporting availability or stale refs. - pub(crate) fn entry_any(&self, id: &CapabilityId) -> Option<&'a CapabilityEntry> { - self.by_id.get(id).and_then(|index| self.all_entries.get(*index)) - } - - pub(crate) fn contains(&self, id: &CapabilityId) -> bool { - self.by_id.get(id).is_some_and(|index| self.is_visible_index(*index)) - } - - pub(crate) const fn generation(&self) -> CatalogGeneration { - self.generation - } -} - -fn insert( - mut entry: CapabilityEntry, - entries: &mut Vec, - names: &mut BTreeSet, - ids: &mut BTreeSet, -) -> Result<(), CatalogError> { - if !names.insert(entry.public_name.clone()) || !ids.insert(entry.id.clone()) { - return Err(CatalogError::Duplicate); - } - entry.exact_mention_terms = std::iter::once(entry.id.as_str()) - .chain(std::iter::once(entry.public_name.as_str())) - .chain(entry.aliases.iter().map(String::as_str)) - .map(str::to_lowercase) - .collect(); - entries.push(entry); - Ok(()) -} - -// Native identities remain compatible with existing manifests while semantic -// families distinguish document/process work. Creation and authenticated -// process restoration must use this one canonical identity rule. -fn canonical_identity_family(family: CapabilityTarget, namespace: &str, name: &str) -> CapabilityTarget { - if namespace == "native" - && matches!( - (family, name), - (CapabilityTarget::Shell, "shell") | (CapabilityTarget::Document, "document_ingest" | "document_sync") - ) - { - CapabilityTarget::Filesystem - } else { - family - } -} - -fn entry_from_spec( - spec: ToolSpec, - root: String, - namespace: String, - family: CapabilityTarget, - categories: Vec, - effect: SideEffectClass, - availability: CapabilityAvailability, - process_worker_compatible: bool, - target: ExecutionTarget, - surface: &SurfacePolicy, -) -> Result { - crate::tools::schema::SchemaCleanr::validate(&spec.parameters).map_err(|_| CatalogError::Schema)?; - let identity_family = canonical_identity_family(family, &namespace, &spec.name); - let id = CapabilityId::new(identity_family, &namespace, &spec.name).map_err(|_| CatalogError::Identity)?; - let fingerprint = tool_spec_fingerprint(&spec.name, &spec.description, &spec.parameters); - let exposure = if !surface.permits(&spec.name, &root, &target) - || surface.excluded_names.contains(&spec.name) - || surface.excluded_names.contains(&root) - || availability.level < CapabilityAvailabilityLevel::Configured - { - Exposure::Unavailable { - reason: "not available on this surface".to_string(), - } - } else if surface.direct_names.contains(&spec.name) { - Exposure::Direct - } else { - Exposure::Searchable - }; - // Most tools derive the exact operation id from runtime arguments (path, - // destination, task id). Do not advertise a fabricated grant target. - let op_ids = Vec::new(); - let approval = if effect == SideEffectClass::ReadOnly { - ApprovalRequirement::None - } else { - ApprovalRequirement::Required { op_ids: Vec::new() } - }; - let schema_bytes = serde_json::to_vec(&spec.parameters).map_or(usize::MAX, |value| value.len()); - Ok(CapabilityEntry { - id, - public_name: spec.name, - root, - family, - namespace, - summary: summary(&spec.description), - aliases: Vec::new(), - categories, - exact_mention_terms: Vec::new(), - effect, - risk: risk_for_effect(effect), - op_ids, - approval, - channel_eligible: surface.channel_allowed, - schema: Arc::new(spec.parameters), - schema_bytes, - fingerprint, - generation: CatalogGeneration([0; 32]), - target, - binding_digest: None, - skill_metadata: None, - exposure, - availability, - process_worker_compatible, - }) -} - -pub(super) const fn risk_for_effect(effect: SideEffectClass) -> RiskLevel { - match effect { - SideEffectClass::ReadOnly => RiskLevel::Low, - SideEffectClass::LocalWrite | SideEffectClass::ExternalSend | SideEffectClass::CredentialOrConfig => { - RiskLevel::Medium - } - SideEffectClass::ProcessExec | SideEffectClass::Destructive => RiskLevel::High, - } -} - -fn summary(description: &str) -> String { - let redacted = crate::security::redaction::redact_secrets(description); - redacted - .chars() - .filter(|ch| !ch.is_control() && !matches!(ch, '\u{200b}'..='\u{200f}' | '\u{2060}' | '\u{feff}')) - .take(160) - .collect() -} - -/// Canonical identity of a registered descriptor, shared by publication and -/// execution observations. This identifies an observed call, not permission. -pub(crate) fn descriptor_identity(descriptor: &ToolDescriptor) -> Result { - let namespace = if descriptor.adapter == ToolAdapterKind::McpAlias { - "mcp" - } else { - "native" - }; - let family = canonical_identity_family(family_for(descriptor), namespace, &descriptor.public_name); - CapabilityId::new(family, namespace, &descriptor.public_name).map_err(|_| CatalogError::Identity) -} - -fn family_for(descriptor: &ToolDescriptor) -> CapabilityTarget { - match descriptor.adapter { - ToolAdapterKind::McpAlias => CapabilityTarget::Mcp, - ToolAdapterKind::WasmPlugin => CapabilityTarget::Wasm, - ToolAdapterKind::Skill => CapabilityTarget::Skill, - ToolAdapterKind::Native => { - if matches!( - descriptor.public_name.as_str(), - "document_search" | "document_ingest" | "document_sync" - ) { - CapabilityTarget::Document - } else if descriptor.public_name == "sessions_history" { - CapabilityTarget::Session - } else if descriptor.public_name == "shell" { - CapabilityTarget::Shell - } else if descriptor.categories.contains(&ToolCategory::FileSystem) { - CapabilityTarget::Filesystem - } else if descriptor.categories.contains(&ToolCategory::Memory) { - CapabilityTarget::Memory - } else if descriptor.categories.contains(&ToolCategory::WebBrowsing) { - CapabilityTarget::Web - } else if descriptor.categories.contains(&ToolCategory::Communication) { - CapabilityTarget::Im - } else { - CapabilityTarget::NativeTool - } - } - } -} - -fn effect_for(descriptor: &ToolDescriptor) -> SideEffectClass { - match descriptor.effect { - ToolEffect::Read => SideEffectClass::ReadOnly, - ToolEffect::Act => match descriptor.public_name.as_str() { - "shell" | "git_operations" => SideEffectClass::ProcessExec, - "message_send" | "http_request" | "prx_message" => SideEffectClass::ExternalSend, - "sessions_send" if descriptor.parameters.get("oneOf").is_some() => SideEffectClass::ExternalSend, - "config_reload" | "proxy_config" => SideEffectClass::CredentialOrConfig, - "nodes" | "mcp_call" | "skill_execute" => SideEffectClass::Destructive, - "delegate" | "sessions_spawn" => SideEffectClass::ProcessExec, - _ => SideEffectClass::LocalWrite, - }, - } -} - -fn generation_of(sources: &CatalogSources, surface: &SurfacePolicy, entries: &[CapabilityEntry]) -> CatalogGeneration { - let mut hasher = Sha256::new(); - for value in [ - sources.config_generation_id.as_bytes(), - &sources.mcp_state_epoch.to_be_bytes(), - &sources.wasm_generation.to_be_bytes(), - &sources.skills_dir_epoch.to_be_bytes(), - ] { - hasher.update(value.len().to_be_bytes()); - hasher.update(value); - } - for entry in entries { - for value in [ - entry.id.as_str().as_bytes(), - entry.family.as_str().as_bytes(), - entry.fingerprint.0.as_slice(), - entry.root.as_bytes(), - entry.public_name.as_bytes(), - ] { - hasher.update(value.len().to_be_bytes()); - hasher.update(value); - } - let policy = format!( - "{:?}{:?}{:?}{:?}{:?}{:?}{:?}{:?}{:?}", - entry.categories, - entry.effect, - entry.risk, - entry.op_ids, - entry.approval, - entry.exposure, - entry.availability, - entry.target, - entry.binding_digest - ); - hasher.update(policy.len().to_be_bytes()); - hasher.update(policy.as_bytes()); - } - let mut mcp_ordered: Vec<_> = sources.mcp.iter().collect(); - mcp_ordered.sort_by(|left, right| (&left.server, &left.tool).cmp(&(&right.server, &right.tool))); - for item in mcp_ordered { - hasher.update(item.server.len().to_be_bytes()); - hasher.update(item.server.as_bytes()); - hasher.update(item.state_digest); - } - let policy = format!("{surface:?}"); - hasher.update(policy.len().to_be_bytes()); - hasher.update(policy.as_bytes()); - CatalogGeneration(hasher.finalize().into()) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::tools::capability::search::CatalogSearch; - use crate::tools::traits::ToolResult; - use async_trait::async_trait; - use std::sync::atomic::{AtomicUsize, Ordering}; - - struct ProbeTool { - name: &'static str, - description: &'static str, - } - - #[async_trait] - impl Tool for ProbeTool { - fn name(&self) -> &str { - self.name - } - - fn description(&self) -> &str { - self.description - } - - fn parameters_schema(&self) -> Value { - json!({"type":"object","properties":{"query":{"type":"string"}}}) - } - - async fn execute(&self, _args: Value) -> anyhow::Result { - Ok(ToolResult { - success: true, - output: String::new(), - error: None, - }) - } - } - - struct DocumentCategoryProbe(&'static str); - #[async_trait] - impl Tool for DocumentCategoryProbe { - fn name(&self) -> &str { - self.0 - } - fn description(&self) -> &str { - "Native document index operation" - } - fn parameters_schema(&self) -> Value { - json!({"type":"object","properties":{}}) - } - fn categories(&self) -> &'static [ToolCategory] { - &[ToolCategory::Memory, ToolCategory::FileSystem] - } - async fn execute(&self, _: Value) -> anyhow::Result { - anyhow::bail!("metadata fixture never executes") - } - } - - #[test] - fn document_index_tools_keep_legacy_ids_without_entering_filesystem_discovery() { - let registry: Vec> = vec![ - Box::new(DocumentCategoryProbe("document_ingest")), - Box::new(DocumentCategoryProbe("document_sync")), - ]; - let catalog = - CapabilityCatalog::build(®istry, &CatalogSources::default(), &SurfacePolicy::default()).unwrap(); - for name in ["document_ingest", "document_sync"] { - let entry = catalog.entry_for_public_name(name).unwrap(); - assert_eq!(entry.family, CapabilityTarget::Document); - assert_eq!(entry.id.as_str(), format!("filesystem:native:{name}")); - } - let view = catalog.view(&CatalogScope { - families: BTreeSet::from([CapabilityTarget::Filesystem]), - ..CatalogScope::default() - }); - assert!(view.iter_entries().next().is_none()); - } - - fn registry() -> Vec> { - vec![ - Box::new(ProbeTool { - name: "prx_search", - description: "Search local evidence", - }), - Box::new(ProbeTool { - name: "prx_read", - description: "Read local evidence", - }), - ] - } - - // Public aliases need not export their backend identity as another capability. - struct AliasOnlyParityTool { - backend: &'static str, - state: Arc, - } - - #[async_trait] - impl Tool for AliasOnlyParityTool { - fn name(&self) -> &str { - self.backend - } - - fn description(&self) -> &str { - "PRX alias parity fixture" - } - - fn parameters_schema(&self) -> Value { - if self.state.load(Ordering::SeqCst) == 1 { - json!({"type":"object","properties":{"value":{"type":"string"}}}) - } else { - json!({"type":"object","properties":{}}) - } - } - - fn specs(&self) -> Vec { - if self.state.load(Ordering::SeqCst) == 2 { - return Vec::new(); - } - vec![ToolSpec { - name: "prx_exact_alias".into(), - description: self.description().into(), - parameters: self.parameters_schema(), - }] - } - - fn supports_name(&self, name: &str) -> bool { - name == "prx_exact_alias" && self.state.load(Ordering::SeqCst) != 2 - } - - fn availability(&self) -> CapabilityAvailability { - if self.state.load(Ordering::SeqCst) == 3 { - CapabilityAvailability { - level: CapabilityAvailabilityLevel::Declared, - reason: "PRX fixture is no longer configured".into(), - } - } else { - CapabilityAvailability::ready("PRX fixture configured") - } - } - - async fn execute(&self, _args: Value) -> anyhow::Result { - anyhow::bail!("parity fixture does not execute effects") - } - } - - #[test] - fn alias_only_tool_parity_preserves_exact_identity_and_live_contract() { - let state = Arc::new(AtomicUsize::new(0)); - let registry: Vec> = vec![Box::new(AliasOnlyParityTool { - backend: "prx_alias_backend", - state: Arc::clone(&state), - })]; - let catalog = - CapabilityCatalog::build(®istry, &CatalogSources::default(), &SurfacePolicy::default()).unwrap(); - let entry = catalog.entry_for_public_name("prx_exact_alias").unwrap(); - let reference = CapabilityRef { - id: entry.id.clone(), - generation: entry.generation, - fingerprint: entry.fingerprint, - }; - let allowed = BTreeSet::from([reference.clone()]); - let service = - ToolExecutionService::with_security_policy(registry, Arc::new(crate::security::SecurityPolicy::default())); - assert!(catalog.entry_for_public_name("prx_alias_backend").is_none()); - assert!(service.current_descriptor("prx_alias_backend").is_none()); - assert!(catalog.check_parity(&service).is_ok()); - assert!(catalog.check_published_parity(&service, &allowed).is_ok()); - - let wrong_backend = ToolExecutionService::with_security_policy( - vec![Box::new(AliasOnlyParityTool { - backend: "prx_other_backend", - state: Arc::clone(&state), - })], - Arc::new(crate::security::SecurityPolicy::default()), - ); - assert!(catalog.check_parity(&wrong_backend).is_err()); - assert!(catalog.check_published_parity(&wrong_backend, &allowed).is_err()); - let mut stale = reference.clone(); - stale.generation = CatalogGeneration([0; 32]); - assert_ne!(stale.generation, reference.generation); - assert!( - catalog - .check_published_parity(&service, &BTreeSet::from([stale])) - .is_err() - ); - let mut changed = reference; - changed.fingerprint = SchemaFingerprint([0; 32]); - assert_ne!(changed.fingerprint, entry.fingerprint); - assert!( - catalog - .check_published_parity(&service, &BTreeSet::from([changed])) - .is_err() - ); - // Schema drift, disappearance and loss of configured availability each - // independently invalidate the original immutable publication. - for mode in [1, 2, 3] { - state.store(mode, Ordering::SeqCst); - assert!(catalog.check_parity(&service).is_err()); - assert!(catalog.check_published_parity(&service, &allowed).is_err()); - } - } - - struct BlankReasonAvailabilityTool; - - #[async_trait] - impl Tool for BlankReasonAvailabilityTool { - fn name(&self) -> &str { - "prx_blank_reason" - } - - fn description(&self) -> &str { - "PRX availability compatibility fixture" - } - - fn parameters_schema(&self) -> Value { - json!({"type":"object","properties":{}}) - } - - fn availability(&self) -> CapabilityAvailability { - CapabilityAvailability { - level: CapabilityAvailabilityLevel::Declared, - reason: String::new(), - } - } - - async fn execute(&self, _args: Value) -> anyhow::Result { - Ok(ToolResult { - success: true, - output: String::new(), - error: None, - }) - } - } - - #[test] - fn parity_preserves_legacy_empty_availability_reason_promotion() { - let registry: Vec> = vec![Box::new(BlankReasonAvailabilityTool)]; - let catalog = - CapabilityCatalog::build(®istry, &CatalogSources::default(), &SurfacePolicy::default()).unwrap(); - let service = - ToolExecutionService::with_security_policy(registry, Arc::new(crate::security::SecurityPolicy::default())); - assert_eq!( - service - .current_descriptor("prx_blank_reason") - .unwrap() - .availability - .level, - CapabilityAvailabilityLevel::Ready - ); - assert!(catalog.check_parity(&service).is_ok()); - } - - struct BorrowedSpecTool { - spec: ToolSpec, - owned_calls: Arc, - } - - #[async_trait] - impl Tool for BorrowedSpecTool { - fn name(&self) -> &str { - &self.spec.name - } - - fn description(&self) -> &str { - &self.spec.description - } - - fn parameters_schema(&self) -> Value { - self.spec.parameters.clone() - } - - fn catalog_specs(&self) -> Vec { - self.owned_calls.fetch_add(1, Ordering::SeqCst); - vec![self.spec.clone()] - } - - fn immutable_catalog_specs(&self) -> Option<&[ToolSpec]> { - Some(std::slice::from_ref(&self.spec)) - } - - async fn execute(&self, _args: Value) -> anyhow::Result { - anyhow::bail!("borrowed-spec fixture must not execute") - } - } - - #[test] - fn parity_borrows_immutable_specs_without_rebuilding_owned_inventory() { - let owned_calls = Arc::new(AtomicUsize::new(0)); - let registry: Vec> = vec![Box::new(BorrowedSpecTool { - spec: ToolSpec { - name: "prx_borrowed".to_string(), - description: "PRX borrowed spec fixture".to_string(), - parameters: json!({"type":"object","properties":{}}), - }, - owned_calls: Arc::clone(&owned_calls), - })]; - let catalog = - CapabilityCatalog::build(®istry, &CatalogSources::default(), &SurfacePolicy::default()).unwrap(); - let service = - ToolExecutionService::with_security_policy(registry, Arc::new(crate::security::SecurityPolicy::default())); - let before = owned_calls.load(Ordering::SeqCst); - assert!(catalog.check_parity(&service).is_ok()); - assert_eq!(owned_calls.load(Ordering::SeqCst), before); - } - - #[test] - fn catalog_fingerprint_equals_compiled_tool_context_per_spec_sha() { - let tools = registry(); - let catalog = CapabilityCatalog::build(&tools, &CatalogSources::default(), &SurfacePolicy::default()).unwrap(); - let compiled = - crate::agent::turn_context::CompiledToolContext::new(true, tools.iter().map(|tool| tool.spec()).collect()); - for entry in catalog.view(&CatalogScope::default()).entries() { - let compiled_spec = compiled - .fingerprint() - .tools - .iter() - .find(|spec| spec.name == entry.public_name) - .unwrap(); - assert_eq!(hex::encode(entry.fingerprint.0), compiled_spec.sha256); - } - } - - /// The canonical ids that `required-tools` takes are the ones the catalog - /// builds: Shell retains its historical file-system ID, and a discovered MCP - /// tool is filed under its server with its alias as the public name. - #[test] - fn canonical_ids_of_the_shell_and_a_discovered_mcp_tool_are_the_documented_ones() { - use crate::skills::lifecycle::{Bundle, BundleEntry, validate_manifest_strict}; - let workspace = tempfile::tempdir().unwrap(); - let tools: Vec> = vec![Box::new(crate::tools::shell::ShellTool::new( - Arc::new(crate::runtime::NativeRuntime::new()), - workspace.path().to_path_buf(), - ))]; - let mut sources = CatalogSources::default(); - sources.mcp.push(McpCapabilitySpec { - server: "notes".into(), - tool: "search".into(), - state_digest: [0; 32], - spec: ToolSpec { - name: "mcp__notes__search".into(), - description: "search notes".into(), - parameters: json!({"type":"object","properties":{}}), - }, - }); - let catalog = CapabilityCatalog::build(&tools, &sources, &SurfacePolicy::default()).unwrap(); - let shell = catalog.entry_for_public_name("shell").unwrap().id.as_str().to_owned(); - let mcp = catalog - .entry_for_public_name("mcp__notes__search") - .unwrap() - .id - .as_str() - .to_owned(); - assert_eq!(shell, "filesystem:native:shell"); - let shell_entry = catalog.entry_for_public_name("shell").unwrap(); - assert!(shell_entry.categories.contains(&ToolCategory::FileSystem)); - assert_eq!(shell_entry.family, CapabilityTarget::Shell); - assert_eq!(shell_entry.effect, SideEffectClass::ProcessExec); - let filesystem = catalog.view(&CatalogScope { - families: BTreeSet::from([CapabilityTarget::Filesystem]), - ..CatalogScope::default() - }); - assert!(filesystem.iter_entries().all(|entry| entry.public_name != "shell")); - let mut legacy_entries = catalog.entries.clone(); - legacy_entries - .iter_mut() - .find(|entry| entry.public_name == "shell") - .unwrap() - .family = CapabilityTarget::Filesystem; - assert_ne!( - generation_of(&sources, &SurfacePolicy::default(), &legacy_entries), - *catalog.generation(), - "semantic family drift must invalidate approvals even with stable capability IDs" - ); - assert_eq!(mcp, "mcp:notes:mcp__notes__search"); - // Exactly these strings are accepted by the lifecycle manifest check. - let skill = format!("---\nname: ids\ndescription: ids\nrequired-tools: [{shell}, {mcp}]\n---\n\nBody.\n"); - let bundle = Bundle::from_entries(vec![BundleEntry { - path: std::path::PathBuf::from("SKILL.md"), - bytes: skill.into_bytes(), - executable: false, - }]) - .unwrap(); - let info = validate_manifest_strict(&bundle).unwrap(); - assert_eq!(info.required_tools, vec![shell, mcp]); - } - - /// Every id the real catalog builds, for the built-in tools and for both MCP - /// forms, passes the strict write-time shape check of `required-tools`. - #[test] - fn every_id_the_catalog_builds_passes_the_required_tools_shape_check() { - use crate::skills::lifecycle::{Bundle, BundleEntry, validate_manifest_strict}; - let workspace = tempfile::tempdir().unwrap(); - let runtime: Arc = Arc::new(crate::runtime::NativeRuntime::new()); - let security = Arc::new(crate::security::SecurityPolicy::default()); - let tools: Vec> = vec![ - Box::new(crate::tools::shell::ShellTool::new( - runtime, - workspace.path().to_path_buf(), - )), - Box::new(crate::tools::file_read::FileReadTool::new(security, false)), - ]; - let mut sources = CatalogSources::default(); - for server in ["notes", "my__srv"] { - sources.mcp.push(McpCapabilitySpec { - server: server.into(), - tool: "search".into(), - state_digest: [0; 32], - spec: ToolSpec { - name: format!("mcp__{server}__search"), - description: "search".into(), - parameters: json!({"type":"object","properties":{}}), - }, - }); - } - let catalog = CapabilityCatalog::build(&tools, &sources, &SurfacePolicy::default()).unwrap(); - // An alias that was not discovered is filed under the namespace `mcp`. - let alias = CapabilityId::new(CapabilityTarget::Mcp, "mcp", "mcp__late__search").unwrap(); - let mut ids: Vec = catalog - .view(&CatalogScope::default()) - .iter_entries() - .map(|entry| entry.id.as_str().to_owned()) - .collect(); - ids.push(alias.as_str().to_owned()); - assert!(ids.iter().any(|id| id == "filesystem:native:shell"), "{ids:?}"); - assert!(ids.iter().any(|id| id == "filesystem:native:file_read"), "{ids:?}"); - assert!(ids.iter().any(|id| id == "mcp:my__srv:mcp__my__srv__search"), "{ids:?}"); - for id in &ids { - let skill = format!("---\nname: ids\ndescription: ids\nrequired-tools: [{id}]\n---\n\nBody.\n"); - let bundle = Bundle::from_entries(vec![BundleEntry { - path: std::path::PathBuf::from("SKILL.md"), - bytes: skill.into_bytes(), - executable: false, - }]) - .unwrap(); - let info = validate_manifest_strict(&bundle).unwrap_or_else(|e| panic!("{id} must pass: {e}")); - assert_eq!(info.required_tools, vec![id.clone()]); - } - } - - #[test] - fn catalog_rejects_duplicate_public_names_before_execution_deduplicates() { - let tools: Vec> = vec![ - Box::new(ProbeTool { - name: "prx_search", - description: "first", - }), - Box::new(ProbeTool { - name: "prx_search", - description: "second", - }), - ]; - assert!(matches!( - CapabilityCatalog::build(&tools, &CatalogSources::default(), &SurfacePolicy::default()), - Err(CatalogError::Duplicate) - )); - } - - #[test] - fn exact_name_precedes_ranked_search_and_exclusions() { - let mut surface = SurfacePolicy::default(); - surface.excluded_names.insert("prx_read".to_string()); - let catalog = CapabilityCatalog::build(®istry(), &CatalogSources::default(), &surface).unwrap(); - let view = catalog.view(&CatalogScope::default()); - let hit = CatalogSearch::find(&view, "prx_search", &[], 5); - assert_eq!(hit.len(), 1); - assert_eq!(hit.first().unwrap().entry.public_name, "prx_search"); - assert!( - CatalogSearch::find(&view, "prx_read", &[], 5) - .iter() - .all(|hit| hit.entry.public_name != "prx_read") - ); - assert!(CatalogSearch::find(&view, "*", &[], 5).is_empty()); - } - - #[test] - fn unspaced_script_query_matches_substring_of_longer_summary() { - // Neutral code points exercise the same bigram branch as CJK without - // embedding non-English prose in source or test fixtures. - assert!(crate::tools::capability::search::character_is_unspaced_script( - char::from_u32(0x4e00).unwrap() - )); - let description: String = (0x0e01..=0x0e08).filter_map(char::from_u32).collect(); - let query: String = description.chars().skip(2).take(3).collect(); - let tools: Vec> = vec![Box::new(ProbeTool { - name: "prx_remote", - description: Box::leak(description.into_boxed_str()), - })]; - let catalog = CapabilityCatalog::build(&tools, &CatalogSources::default(), &SurfacePolicy::default()).unwrap(); - let view = catalog.view(&CatalogScope::default()); - let hits = CatalogSearch::find(&view, &query, &[], 5); - assert_eq!( - hits.first().map(|hit| hit.entry.public_name.as_str()), - Some("prx_remote") - ); - } - - #[test] - fn excluding_dispatch_roots_hides_synthetic_children() { - let temp = tempfile::tempdir().unwrap(); - let mut sources = CatalogSources::default(); - sources.node_key = Some(DecisionKey::load_or_create(temp.path()).unwrap()); - sources.skills.push(SkillMetadata { - name: "prx_skill".into(), - description: "Skill".into(), - location: temp.path().join("SKILL.md"), - frontmatter_sha: [1; 32], - }); - sources.nodes.push(NodeSource { - id: "prx_node".into(), - availability: CapabilityAvailability::configured("configured"), - binding_digest: [2; 32], - }); - sources.mcp.push(McpCapabilitySpec { - server: "prx_server".into(), - tool: "read".into(), - state_digest: [3; 32], - spec: ToolSpec { - name: "mcp__prx_server__read".into(), - description: "MCP".into(), - parameters: json!({"type":"object","properties":{}}), - }, - }); - let mut surface = SurfacePolicy::default(); - surface - .excluded_names - .extend(["skill_read", "nodes", "mcp_call"].map(str::to_string)); - let catalog = CapabilityCatalog::build(&[], &sources, &surface).unwrap(); - assert!(catalog.view(&CatalogScope::default()).entries().is_empty()); - for entry in &catalog.entries { - let reference = CapabilityRef { - id: entry.id.clone(), - fingerprint: entry.fingerprint, - generation: *catalog.generation(), - }; - assert!(matches!( - catalog.resolve(&[reference]), - Err(StaleCapability::Unavailable) - )); - } - } - - #[test] - fn changed_schema_invalidates_pinned_reference() { - let original = - CapabilityCatalog::build(®istry(), &CatalogSources::default(), &SurfacePolicy::default()).unwrap(); - let entry = original - .view(&CatalogScope::default()) - .entries() - .first() - .copied() - .unwrap(); - let reference = CapabilityRef { - id: entry.id.clone(), - fingerprint: entry.fingerprint, - generation: *original.generation(), - }; - let changed: Vec> = vec![Box::new(ProbeTool { - name: "prx_search", - description: "changed schema description", - })]; - let changed = - CapabilityCatalog::build(&changed, &CatalogSources::default(), &SurfacePolicy::default()).unwrap(); - assert!(matches!(changed.resolve(&[reference]), Err(StaleCapability::Stale))); - } - - #[test] - fn unchanged_mcp_schema_with_changed_destination_invalidates_generation() { - let mut sources = CatalogSources::default(); - sources.mcp.push(McpCapabilitySpec { - server: "prx_server".into(), - tool: "read".into(), - state_digest: [1; 32], - spec: ToolSpec { - name: "mcp__prx_server__read".into(), - description: "Read remote data".into(), - parameters: json!({"type":"object","properties":{}}), - }, - }); - let first = CapabilityCatalog::build(&[], &sources, &SurfacePolicy::default()).unwrap(); - let entry = *first.view(&CatalogScope::default()).entries().first().unwrap(); - let reference = CapabilityRef { - id: entry.id.clone(), - fingerprint: entry.fingerprint, - generation: *first.generation(), - }; - sources.mcp.first_mut().unwrap().state_digest = [2; 32]; - let changed = CapabilityCatalog::build(&[], &sources, &SurfacePolicy::default()).unwrap(); - assert_ne!(first.generation(), changed.generation()); - assert!(matches!(changed.resolve(&[reference]), Err(StaleCapability::Stale))); - } - - #[test] - fn node_uses_keyed_canonical_identity_and_requires_key() { - let mut sources = CatalogSources::default(); - sources.nodes.push(NodeSource { - id: "Box:1".into(), - availability: CapabilityAvailability::configured("configured"), - binding_digest: [3; 32], - }); - assert!(matches!( - CapabilityCatalog::build(&[], &sources, &SurfacePolicy::default()), - Err(CatalogError::Identity) - )); - let temp = tempfile::tempdir().unwrap(); - let key = DecisionKey::load_or_create(temp.path()).unwrap(); - let expected = CapabilityId::remote_node(&key, "Box:1").unwrap(); - sources.node_key = Some(key); - let catalog = CapabilityCatalog::build(&[], &sources, &SurfacePolicy::default()).unwrap(); - let entry = catalog.entries.first().unwrap(); - assert_eq!(entry.id, expected); - assert_ne!(entry.public_name, "Box:1"); - } - - #[test] - fn surface_policy_changes_invalidate_refs() { - let tools = registry(); - let first = CapabilityCatalog::build(&tools, &CatalogSources::default(), &SurfacePolicy::default()).unwrap(); - let entry = *first.view(&CatalogScope::default()).entries().first().unwrap(); - let reference = CapabilityRef { - id: entry.id.clone(), - fingerprint: entry.fingerprint, - generation: *first.generation(), - }; - let mut changed_surface = SurfacePolicy::default(); - changed_surface.channel_allowed = true; - let changed = CapabilityCatalog::build(&tools, &CatalogSources::default(), &changed_surface).unwrap(); - assert!(matches!(changed.resolve(&[reference]), Err(StaleCapability::Stale))); - } - - #[test] - fn high_risk_root_actions_are_never_local_write() { - for name in ["nodes", "mcp_call", "skill_execute", "sessions_spawn", "delegate"] { - let tools: Vec> = vec![Box::new(ProbeTool { - name, - description: "Act", - })]; - let catalog = - CapabilityCatalog::build(&tools, &CatalogSources::default(), &SurfacePolicy::default()).unwrap(); - let entry = catalog.entries.first().unwrap(); - assert!(entry.effect >= SideEffectClass::ProcessExec, "{name}"); - assert!(matches!(entry.approval, ApprovalRequirement::Required { .. }), "{name}"); - assert!(entry.op_ids.is_empty(), "{name} has call-scoped operations"); - } - } - - struct DynamicAliasTool(Arc); - - #[async_trait] - impl Tool for DynamicAliasTool { - fn name(&self) -> &str { - "mcp_call" - } - fn description(&self) -> &str { - "Dynamic tool" - } - fn parameters_schema(&self) -> Value { - json!({"type":"object","properties":{}}) - } - fn specs(&self) -> Vec { - vec![self.spec()] - } - fn catalog_specs(&self) -> Vec { - let mut specs = self.specs(); - if self.0.load(Ordering::SeqCst) != 0 { - specs.push(ToolSpec { - name: "prx_collision".into(), - description: "new alias".into(), - parameters: self.parameters_schema(), - }); - } - specs - } - fn spec_for_name(&self, name: &str) -> Option { - self.catalog_specs().into_iter().find(|spec| spec.name == name) - } - fn supports_name(&self, name: &str) -> bool { - self.spec_for_name(name).is_some() - } - async fn execute(&self, _args: Value) -> anyhow::Result { - Ok(ToolResult { - success: true, - output: String::new(), - error: None, - }) - } - } - - #[test] - fn late_alias_collision_does_not_take_native_startup_owner_and_fails_parity() { - let state = Arc::new(AtomicUsize::new(0)); - let registry: Vec> = vec![ - Box::new(DynamicAliasTool(Arc::clone(&state))), - Box::new(ProbeTool { - name: "prx_collision", - description: "native owner", - }), - ]; - let catalog = - CapabilityCatalog::build(®istry, &CatalogSources::default(), &SurfacePolicy::default()).unwrap(); - let service = - ToolExecutionService::with_security_policy(registry, Arc::new(crate::security::SecurityPolicy::default())); - assert_eq!( - service.current_descriptor("prx_collision").unwrap().backend_name, - "prx_collision" - ); - assert!(catalog.check_parity(&service).is_ok()); - state.store(1, Ordering::SeqCst); - assert_eq!( - service.current_descriptor("prx_collision").unwrap().backend_name, - "prx_collision" - ); - assert!(catalog.check_parity(&service).is_err()); - } - - struct MutableBindingTool(Arc, [u8; 32]); - - #[async_trait] - impl Tool for MutableBindingTool { - fn name(&self) -> &str { - "skill_read" - } - fn description(&self) -> &str { - "Read a selected skill" - } - fn parameters_schema(&self) -> Value { - json!({"type":"object","properties":{"name":{"type":"string"}},"required":["name"]}) - } - fn catalog_binding_snapshot(&self) -> BTreeMap { - if self.0.load(Ordering::SeqCst) == 0 { - BTreeMap::from([("prx_skill".into(), self.1)]) - } else { - BTreeMap::new() - } - } - async fn execute(&self, _args: Value) -> anyhow::Result { - Ok(ToolResult { - success: true, - output: String::new(), - error: None, - }) - } - } - - #[test] - fn synthetic_skill_parity_fails_when_exact_target_disappears() { - let temp = tempfile::tempdir().unwrap(); - let skill = SkillMetadata { - name: "prx_skill".into(), - description: "Read it".into(), - location: temp.path().join("SKILL.md"), - frontmatter_sha: [4; 32], - }; - let digest = crate::skills::catalog_skill_binding_digest(&skill); - let mut sources = CatalogSources::default(); - sources.skills.push(skill); - let state = Arc::new(AtomicUsize::new(0)); - let registry: Vec> = vec![Box::new(MutableBindingTool(Arc::clone(&state), digest))]; - let catalog = CapabilityCatalog::build(®istry, &sources, &SurfacePolicy::default()).unwrap(); - let service = - ToolExecutionService::with_security_policy(registry, Arc::new(crate::security::SecurityPolicy::default())); - assert!(catalog.check_parity(&service).is_ok()); - state.store(1, Ordering::SeqCst); - assert!(catalog.check_parity(&service).is_err()); - } - - #[test] - fn instruction_read_wire_alias_collision_is_refused_instead_of_merging_targets() { - let temp = tempfile::tempdir().unwrap(); - let skill = SkillMetadata { - name: "Deploy helper".into(), - description: "Read one skill".into(), - location: temp.path().join("first/SKILL.md"), - frontmatter_sha: [4; 32], - }; - let mut colliding = skill.clone(); - colliding.name = crate::tools::skills::catalog_skill_read_name(&skill.name); - colliding.location = temp.path().join("second/SKILL.md"); - let sources = CatalogSources { - skills: vec![skill, colliding], - ..Default::default() - }; - assert!(matches!( - CapabilityCatalog::build(&[], &sources, &SurfacePolicy::default()), - Err(CatalogError::Duplicate) - )); - } - - #[test] - fn native_identity_and_instruction_alias_survive_the_bound_process_snapshot() { - let skill = SkillMetadata { - name: "Deploy helper".into(), - description: "Read one skill".into(), - location: std::path::PathBuf::from("/prx-workspace/skills/deploy/SKILL.md"), - frontmatter_sha: [4; 32], - }; - let alias = crate::tools::skills::catalog_skill_read_name(&skill.name); - let sources = CatalogSources { - skills: vec![skill.clone()], - ..Default::default() - }; - let workspace = tempfile::tempdir().unwrap(); - let registry: Vec> = vec![ - Box::new(crate::tools::shell::ShellTool::new( - Arc::new(crate::runtime::NativeRuntime::new()), - workspace.path().to_path_buf(), - )), - Box::new(DocumentCategoryProbe("document_ingest")), - Box::new(DocumentCategoryProbe("document_sync")), - ]; - let catalog = CapabilityCatalog::build(®istry, &sources, &SurfacePolicy::default()).unwrap(); - let key = crate::security::runtime_key::test_support::ephemeral_key(); - let snapshot = catalog.bind_process(&key).unwrap(); - let restored = CapabilityCatalog::restore_process(&snapshot, &key, *catalog.generation()).unwrap(); - for (name, family) in [ - ("shell", CapabilityTarget::Shell), - ("document_ingest", CapabilityTarget::Document), - ("document_sync", CapabilityTarget::Document), - ] { - let entry = restored.entry_for_public_name(name).unwrap(); - let parent = catalog.entry_for_public_name(name).unwrap(); - assert_eq!(entry.family, family); - assert_eq!(entry.id.as_str(), format!("filesystem:native:{name}")); - assert_eq!(entry.id, parent.id); - assert_eq!(entry.fingerprint, parent.fingerprint); - assert_eq!(entry.generation, parent.generation); - } - assert!( - CapabilityCatalog::restore_process( - &snapshot, - &crate::security::runtime_key::test_support::ephemeral_key(), - *catalog.generation() - ) - .is_err(), - "identity compatibility cannot bypass catalog authentication" - ); - let entry = restored.entry_for_public_name(&alias).unwrap(); - assert_eq!(entry.skill_metadata.as_ref().unwrap().name, skill.name); - assert_eq!( - entry.binding_digest, - Some(crate::skills::catalog_skill_binding_digest(&skill)) - ); - assert_eq!( - entry.schema.pointer("/properties/name/const"), - Some(&json!("Deploy helper")) - ); - assert!( - matches!(&entry.target, ExecutionTarget::Skill { name, root } if name=="Deploy helper" && root=="skill_read") - ); - } - - struct CountingBindingTool { - calls: Arc, - bindings: BTreeMap, - } - - #[async_trait] - impl Tool for CountingBindingTool { - fn name(&self) -> &str { - "skill_read" - } - fn description(&self) -> &str { - "Read selected skill" - } - fn parameters_schema(&self) -> Value { - json!({"type":"object","properties":{"name":{"type":"string"}},"required":["name"]}) - } - fn catalog_binding_snapshot(&self) -> BTreeMap { - self.calls.fetch_add(1, Ordering::SeqCst); - self.bindings.clone() - } - async fn execute(&self, _args: Value) -> anyhow::Result { - Ok(ToolResult { - success: true, - output: String::new(), - error: None, - }) - } - } - - #[test] - fn parity_reads_one_binding_snapshot_for_many_skills() { - let temp = tempfile::tempdir().unwrap(); - let mut sources = CatalogSources::default(); - let mut bindings = BTreeMap::new(); - for index in 0..32 { - let skill = SkillMetadata { - name: format!("prx_skill_{index}"), - description: "Skill".into(), - location: temp.path().join(format!("skill_{index}/SKILL.md")), - frontmatter_sha: [index; 32], - }; - bindings.insert(skill.name.clone(), crate::skills::catalog_skill_binding_digest(&skill)); - sources.skills.push(skill); - } - let calls = Arc::new(AtomicUsize::new(0)); - let registry: Vec> = vec![Box::new(CountingBindingTool { - calls: Arc::clone(&calls), - bindings, - })]; - let catalog = CapabilityCatalog::build(®istry, &sources, &SurfacePolicy::default()).unwrap(); - let service = - ToolExecutionService::with_security_policy(registry, Arc::new(crate::security::SecurityPolicy::default())); - assert!(catalog.check_parity(&service).is_ok()); - assert_eq!(calls.load(Ordering::SeqCst), 1); - } - - struct MutableMcpDestinationTool(Arc); - - #[async_trait] - impl Tool for MutableMcpDestinationTool { - fn name(&self) -> &str { - "mcp_call" - } - fn description(&self) -> &str { - "MCP root" - } - fn parameters_schema(&self) -> Value { - json!({"type":"object","properties":{}}) - } - fn catalog_specs(&self) -> Vec { - vec![ - self.spec(), - ToolSpec { - name: "mcp__prx_server__read".into(), - description: "Read remote data".into(), - parameters: self.parameters_schema(), - }, - ] - } - fn catalog_binding_snapshot(&self) -> BTreeMap { - let byte = u8::try_from(self.0.load(Ordering::SeqCst)).unwrap_or_default() + 1; - BTreeMap::from([("mcp__prx_server__read".into(), [byte; 32])]) - } - fn supports_name(&self, name: &str) -> bool { - name == self.name() || name == "mcp__prx_server__read" - } - fn spec_for_name(&self, name: &str) -> Option { - self.catalog_specs().into_iter().find(|spec| spec.name == name) - } - async fn execute(&self, _args: Value) -> anyhow::Result { - Ok(ToolResult { - success: true, - output: String::new(), - error: None, - }) - } - } - - #[test] - fn same_schema_mcp_destination_change_fails_live_parity() { - let state = Arc::new(AtomicUsize::new(0)); - let mut sources = CatalogSources::default(); - sources.mcp.push(McpCapabilitySpec { - server: "prx_server".into(), - tool: "read".into(), - state_digest: [1; 32], - spec: ToolSpec { - name: "mcp__prx_server__read".into(), - description: "Read remote data".into(), - parameters: json!({"type":"object","properties":{}}), - }, - }); - let registry: Vec> = vec![Box::new(MutableMcpDestinationTool(Arc::clone(&state)))]; - let catalog = CapabilityCatalog::build(®istry, &sources, &SurfacePolicy::default()).unwrap(); - let service = - ToolExecutionService::with_security_policy(registry, Arc::new(crate::security::SecurityPolicy::default())); - assert!(catalog.check_parity(&service).is_ok()); - state.store(1, Ordering::SeqCst); - assert!(catalog.check_parity(&service).is_err()); - sources.mcp.first_mut().unwrap().state_digest = [2; 32]; - let rebuilt = CapabilityCatalog::build( - &[Box::new(MutableMcpDestinationTool(state))], - &sources, - &SurfacePolicy::default(), - ) - .unwrap(); - assert_ne!(catalog.generation(), rebuilt.generation()); - } - - #[test] - fn child_parity_rejects_same_schema_mcp_destination_change() { - use crate::tools::capability::child::{ - AuthorityEnvelope, CapabilityConstraints, ChildCapabilityManifest, VerifiedChildScope, - }; - - let state = Arc::new(AtomicUsize::new(0)); - let mut sources = CatalogSources::default(); - sources.mcp.push(McpCapabilitySpec { - server: "prx_server".into(), - tool: "read".into(), - state_digest: [1; 32], - spec: ToolSpec { - name: "mcp__prx_server__read".into(), - description: "Read remote data".into(), - parameters: json!({"type":"object","properties":{}}), - }, - }); - let registry: Vec> = vec![Box::new(MutableMcpDestinationTool(Arc::clone(&state)))]; - let catalog = CapabilityCatalog::build(®istry, &sources, &SurfacePolicy::default()).unwrap(); - let service = - ToolExecutionService::with_security_policy(registry, Arc::new(crate::security::SecurityPolicy::default())); - let child_reference = catalog - .entries - .iter() - .find(|entry| entry.public_name == "mcp__prx_server__read") - .map(|entry| CapabilityRef { - id: entry.id.clone(), - fingerprint: entry.fingerprint, - generation: entry.generation, - }) - .expect("MCP alias reference"); - let allowed: BTreeSet<_> = catalog - .entries - .iter() - .map(|entry| CapabilityRef { - id: entry.id.clone(), - fingerprint: entry.fingerprint, - generation: entry.generation, - }) - .collect(); - let workspace = tempfile::tempdir().unwrap(); - let key = DecisionKey::load_or_create(workspace.path()).unwrap(); - let parent = CapabilityConstraints { - parent_authority_id: crate::security::decision_id::DecisionId::parse( - "0192f0c4-0000-7000-8000-000000000007", - ) - .expect("test: id") - .into(), - allowed, - authority: AuthorityEnvelope { - owner: "prx_user".into(), - workspace: "prx_workspace".into(), - level: crate::security::AutonomyLevel::Supervised, - max_cost_cents: 100, - remaining_depth: 2, - delegation: None, - }, - catalog_generation: *catalog.generation(), - key, - }; - let manifest = ChildCapabilityManifest::derive_strict_subset(&parent, &[child_reference]).unwrap(); - let scope = VerifiedChildScope::new(manifest, &parent).unwrap(); - - assert!(catalog.check_child_parity(&service, &scope).is_ok()); - state.store(1, Ordering::SeqCst); - assert!(catalog.check_child_parity(&service, &scope).is_err()); - } - - struct MutableSchemaTool(Arc); - - #[async_trait] - impl Tool for MutableSchemaTool { - fn name(&self) -> &str { - "prx_mutable" - } - - fn description(&self) -> &str { - "Mutable schema test tool" - } - - fn parameters_schema(&self) -> Value { - json!({"type":"object","properties":{"version":{"const":self.0.load(Ordering::SeqCst)}}}) - } - - async fn execute(&self, _args: Value) -> anyhow::Result { - Ok(ToolResult { - success: true, - output: String::new(), - error: None, - }) - } - } - - #[test] - fn execution_descriptor_rechecks_the_current_schema_after_startup() { - let version = Arc::new(AtomicUsize::new(1)); - let service = ToolExecutionService::with_security_policy( - vec![Box::new(MutableSchemaTool(Arc::clone(&version)))], - Arc::new(crate::security::SecurityPolicy::default()), - ); - let initial = service.current_descriptor("prx_mutable").unwrap(); - assert_eq!(initial.parameters.pointer("/properties/version/const"), Some(&json!(1))); - version.store(2, Ordering::SeqCst); - let current = service.current_descriptor("prx_mutable").unwrap(); - assert_eq!(current.parameters.pointer("/properties/version/const"), Some(&json!(2))); - } - - #[test] - fn excluded_executable_schema_change_still_fails_reverse_parity() { - let version = Arc::new(AtomicUsize::new(1)); - let registry: Vec> = vec![Box::new(MutableSchemaTool(Arc::clone(&version)))]; - let mut surface = SurfacePolicy::default(); - surface.excluded_names.insert("prx_mutable".into()); - let catalog = CapabilityCatalog::build(®istry, &CatalogSources::default(), &surface).unwrap(); - let service = - ToolExecutionService::with_security_policy(registry, Arc::new(crate::security::SecurityPolicy::default())); - assert!(catalog.check_parity(&service).is_ok()); - version.store(2, Ordering::SeqCst); - assert!(catalog.check_parity(&service).is_err()); - } - - #[test] - fn scoped_view_construction_allocates_nothing_for_any_inventory_size() { - for size in [0, 1, 64, 256] { - let sources = CatalogSources { - mcp: (0..size) - .map(|index| McpCapabilitySpec { - server: "prx_server".into(), - tool: format!("read_{index}"), - state_digest: [0; 32], - spec: ToolSpec { - name: format!("mcp__prx_server__read_{index}"), - description: "PRX inventory fixture".into(), - parameters: json!({"type":"object","properties":{}}), - }, - }) - .collect(), - ..CatalogSources::default() - }; - let surface = SurfacePolicy { - allowed_tools: None, - channel_allowed: true, - ..SurfacePolicy::default() - }; - let catalog = CapabilityCatalog::build(&[], &sources, &surface).unwrap(); - for families in [BTreeSet::new(), BTreeSet::from([CapabilityTarget::Mcp])] { - let scope = CatalogScope { - families, - channel: true, - }; - let (view, allocations) = - crate::decision_engine::prediction::builtin::allocation_counter::count(|| catalog.view(&scope)); - assert_eq!(allocations, 0, "view allocations at inventory size {size}"); - assert_eq!(view.entries().len(), size); - } - } - } - - #[test] - fn borrowed_visibility_matches_cached_entries_and_all_search_paths() { - let sources = CatalogSources { - mcp: vec![McpCapabilitySpec { - server: "prx_server".into(), - tool: "read".into(), - state_digest: [0; 32], - spec: ToolSpec { - name: "mcp__prx_server__read".into(), - description: "Search local evidence".into(), - parameters: json!({"type":"object","properties":{}}), - }, - }], - ..CatalogSources::default() - }; - let surface = SurfacePolicy { - allowed_tools: None, - channel_allowed: true, - excluded_names: BTreeSet::from(["prx_search".into()]), - ..SurfacePolicy::default() - }; - let mut catalog = CapabilityCatalog::build(®istry(), &sources, &surface).unwrap(); - catalog - .entries - .iter_mut() - .find(|entry| entry.public_name == "prx_read") - .unwrap() - .channel_eligible = false; - let scopes = std::iter::once(BTreeSet::new()) - .chain(CapabilityTarget::ALL.map(|family| BTreeSet::from([family]))) - .chain(std::iter::once(BTreeSet::from([ - CapabilityTarget::NativeTool, - CapabilityTarget::Mcp, - ]))); - for families in scopes { - for channel in [false, true] { - let scope = CatalogScope { - families: families.clone(), - channel, - }; - let expected: Vec<_> = catalog - .entries - .iter() - .filter(|entry| { - (families.is_empty() || families.contains(&entry.family)) - && (!channel || entry.channel_eligible) - && !matches!(entry.exposure, Exposure::Unavailable { .. }) - }) - .map(|entry| &entry.id) - .collect(); - for cache_first in [false, true] { - let view = catalog.view(&scope); - assert_eq!(view.iter_entries().map(|entry| &entry.id).collect::>(), expected); - assert!( - view.entries.get().is_none(), - "borrowing iteration must not initialize compatibility cache" - ); - if cache_first { - assert_eq!( - view.entries().iter().map(|entry| &entry.id).collect::>(), - expected - ); - } - for entry in &catalog.entries { - let visible = expected.contains(&&entry.id); - assert_eq!(view.contains(&entry.id), visible); - assert!( - std::ptr::eq(view.entry_any(&entry.id).unwrap(), entry), - "unfiltered gate lookup" - ); - for query in std::iter::once(entry.public_name.as_str()) - .chain(std::iter::once(entry.id.as_str())) - .chain(entry.aliases.iter().map(String::as_str)) - { - for query_families in [Vec::new(), vec![entry.family], vec![CapabilityTarget::None]] { - let hits = CatalogSearch::find(&view, query, &query_families, 16); - let allowed = - visible && (query_families.is_empty() || query_families.contains(&entry.family)); - assert_eq!( - hits.iter().any(|hit| hit.entry.id == entry.id), - allowed, - "exact search visibility for {query}" - ); - assert!(hits.iter().all(|hit| expected.contains(&&hit.entry.id))); - } - } - } - let ranked = CatalogSearch::find(&view, "local evidence", &[], 16); - assert_eq!( - ranked.iter().map(|hit| &hit.entry.id).collect::>(), - expected.iter().copied().collect() - ); - assert_eq!( - view.entries.get().is_some(), - cache_first, - "search must not initialize compatibility cache" - ); - assert_eq!( - view.entries().iter().map(|entry| &entry.id).collect::>(), - expected - ); - assert_eq!(view.iter_entries().map(|entry| &entry.id).collect::>(), expected); - } - } - } - } - - #[test] - fn thousands_of_mcp_aliases_stay_bounded_and_hidden_metadata_never_matches() { - let mut sources = CatalogSources::default(); - sources.mcp = (0..4096) - .map(|index| McpCapabilitySpec { - server: "prx_server".to_string(), - tool: format!("tool_{index}"), - state_digest: [0; 32], - spec: ToolSpec { - name: format!("mcp__prx_server__tool_{index}"), - description: if index == 4095 { - "\u{200b}last tool\nsecret=PRX-FAKE-SENTINEL".to_string() - } else { - "searchable remote tool".to_string() - }, - parameters: json!({"type":"object","properties":{}}), - }, - }) - .collect(); - let mut surface = SurfacePolicy::default(); - surface.excluded_names.insert("mcp__prx_server__tool_4095".to_string()); - let catalog = CapabilityCatalog::build(&[], &sources, &surface).unwrap(); - let view = catalog.view(&CatalogScope::default()); - assert_eq!(view.entries().len(), 4095); - let hits = CatalogSearch::find(&view, "searchable remote tool", &[], 5); - assert_eq!(hits.len(), 5); - assert!( - hits.iter() - .all(|hit| hit.entry.public_name != "mcp__prx_server__tool_4095") - ); - assert!( - CatalogSearch::find(&view, "tool_4095", &[], 5) - .iter() - .all(|hit| hit.entry.public_name != "mcp__prx_server__tool_4095") - ); - assert!( - catalog - .entries - .iter() - .all(|entry| entry.summary.len() <= 160 * 4 && !entry.summary.contains('\n')) - ); - } -} +include!("catalog/section_1.rs"); +include!("catalog/section_2.rs"); diff --git a/src/tools/capability/catalog/section_1.rs b/src/tools/capability/catalog/section_1.rs new file mode 100644 index 000000000..d78e5bb1d --- /dev/null +++ b/src/tools/capability/catalog/section_1.rs @@ -0,0 +1,1081 @@ + + +use super::fingerprint::tool_spec_fingerprint; +use crate::acl::approval_grant::RiskLevel; +use crate::capability::{CapabilityAvailability, CapabilityAvailabilityLevel}; +use crate::security::runtime_key::DecisionKey; +use crate::skills::SkillMetadata; +use crate::tools::capability::contract::{ + ApprovalRequirement, CapabilityId, CapabilityRef, CapabilityTarget, CatalogGeneration, OpId, SchemaFingerprint, + SideEffectClass, +}; +use crate::tools::execution::{ToolAdapterKind, ToolCatalog, ToolDescriptor, ToolEffect, ToolExecutionService}; +use crate::tools::mcp::McpCapabilitySpec; +use crate::tools::traits::{Tool, ToolCategory, ToolSpec}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; +#[cfg(test)] +use std::sync::OnceLock; + +/// Model exposure is explicit and never inferred from existence in config. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) enum Exposure { + Direct, + Searchable, + Unavailable { reason: String }, +} + +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) enum ExecutionTarget { + Tool(String), + Skill { name: String, root: String }, + Node { id: String, root: String }, + Hook, +} + +#[derive(Debug, Clone)] +pub(crate) struct CapabilityEntry { + pub id: CapabilityId, + pub public_name: String, + pub root: String, + pub family: CapabilityTarget, + pub namespace: String, + pub summary: String, + pub aliases: Vec, + pub categories: Vec, + /// Lowercased ID, public name and aliases, frozen after all source + /// metadata is attached and before the entry is published. + pub exact_mention_terms: Vec, + pub effect: SideEffectClass, + pub risk: RiskLevel, + pub op_ids: Vec, + pub approval: ApprovalRequirement, + pub channel_eligible: bool, + pub schema: Arc, + /// Serialized size of the pinned schema, computed with the same JSON + /// encoder used by turn cost estimates. + pub schema_bytes: usize, + pub fingerprint: SchemaFingerprint, + pub generation: CatalogGeneration, + pub target: ExecutionTarget, + pub binding_digest: Option<[u8; 32]>, + pub skill_metadata: Option>, + pub exposure: Exposure, + pub availability: CapabilityAvailability, + pub process_worker_compatible: bool, +} + +impl CapabilityEntry { + /// A concrete read-only Skill uses this native loader. Keep registry target + /// representation inside the catalog; decision ranking only needs the fact. + pub(crate) fn loads_read_only_skill(&self, skill: &Self) -> bool { + self.effect == SideEffectClass::ReadOnly + && skill.effect == SideEffectClass::ReadOnly + && matches!((&self.target, &skill.target), + (ExecutionTarget::Tool(name), ExecutionTarget::Skill { root, .. }) if name == root) + } + + /// Native tools whose approval operation derives completely from the + /// proposed arguments. Collection records one exact call before review; + /// it never executes. MCP, plugin and skill names cannot opt into this path. + pub(crate) fn collects_exact_call(&self) -> bool { + self.root == self.public_name + && matches!(&self.target, ExecutionTarget::Tool(name) if name == &self.public_name) + && match self.public_name.as_str() { + "skills_manage" => self.family == CapabilityTarget::NativeTool, + "shell" => matches!(self.family, CapabilityTarget::Filesystem | CapabilityTarget::Shell), + "http_request" => self.family == CapabilityTarget::Web, + _ => false, + } + } + + /// Lifecycle argument collection can follow an unnamed metadata search. + /// Direct publication must not hide that root from discovery. This offers + /// metadata only; collection and execution retain their own approval gates. + pub(crate) fn supports_metadata_discovery(&self) -> bool { + matches!(self.exposure, Exposure::Searchable) + || (matches!(self.exposure, Exposure::Direct) + && self.public_name == "skills_manage" + && self.collects_exact_call()) + } + + /// The (lowercased) request names a grant-bound action of a collectable + /// tool. Other actions need no approval collection: the model may call them + /// in an ordinary turn, and collecting them would end in an error. + pub(crate) fn names_collectable_action(&self, folded_text: &str) -> bool { + self.collects_exact_call() + && (self.public_name != "skills_manage" + || crate::security::approval_operation::SKILLS_MANAGE_GRANT_BOUND_ACTIONS + .iter() + .any(|action| folded_text.contains(action))) + } + + /// Name understood by the execution policy. Synthetic Skill and Node + /// entries dispatch through their registered root and inherit that root's + /// read/write classification; public names remain available for search, + /// exclusion and exact binding. + pub(crate) fn policy_tool_name(&self) -> &str { + match &self.target { + ExecutionTarget::Skill { root, .. } | ExecutionTarget::Node { root, .. } => root, + ExecutionTarget::Tool(_) | ExecutionTarget::Hook => &self.public_name, + } + } + + /// Project the actual execution target into the domain's Plan policy. + /// Aliases/effect labels never substitute for the registered root. + pub(crate) fn plan_intercepted(&self) -> bool { + match &self.target { + ExecutionTarget::Tool(name) => crate::tools::capability::policy::plan_intercepts_tool(name), + ExecutionTarget::Skill { root, .. } | ExecutionTarget::Node { root, .. } => { + crate::tools::capability::policy::plan_intercepts_tool(root) + } + ExecutionTarget::Hook => true, + } + } +} + +/// Inputs outside the finalized executable registry. Callers take these as +/// read-only snapshots of the same runtime generation. +#[derive(Debug, Clone, Default)] +pub(crate) struct CatalogSources { + pub config_generation_id: String, + pub mcp_state_epoch: u64, + pub wasm_generation: u64, + pub skills_dir_epoch: u64, + pub mcp: Vec, + pub skills: Vec, + pub hooks: Vec, + pub nodes: Vec, + pub node_key: Option>, +} + +#[derive(Debug, Clone)] +pub(crate) struct HookSource { + pub event: String, + pub action: String, + pub effect: SideEffectClass, +} + +#[derive(Debug, Clone)] +pub(crate) struct NodeSource { + pub id: String, + pub availability: CapabilityAvailability, + pub binding_digest: [u8; 32], +} + +impl CatalogSources { + /// Snapshot auxiliary metadata without network probes, skill-body + /// hydration or decision-key access. The turn service pins the finalized + /// registry and installs its generation-local key before catalog build. + pub(crate) fn from_runtime_inputs( + config_generation_id: String, + config: &crate::config::Config, + mcp: Vec, + hooks: &crate::hooks::HookDiagnostics, + wasm_generation: u64, + ) -> Self { + let skills = crate::skills::catalog_skill_metadata(&config.workspace_dir, config); + let mut mcp_hasher = Sha256::new(); + let mut mcp_ordered: Vec<_> = mcp.iter().collect(); + mcp_ordered.sort_by(|left, right| (&left.server, &left.tool).cmp(&(&right.server, &right.tool))); + for item in mcp_ordered { + mcp_hasher.update(item.server.len().to_be_bytes()); + mcp_hasher.update(item.server.as_bytes()); + mcp_hasher.update(item.state_digest); + } + let mcp_digest = mcp_hasher.finalize(); + let mut mcp_epoch_bytes = [0_u8; 8]; + mcp_epoch_bytes.copy_from_slice(mcp_digest.get(..8).unwrap_or_default()); + let mut skill_hasher = Sha256::new(); + for skill in &skills { + skill_hasher.update(skill.name.len().to_be_bytes()); + skill_hasher.update(skill.name.as_bytes()); + skill_hasher.update(skill.frontmatter_sha); + skill_hasher.update(skill.location.to_string_lossy().as_bytes()); + } + let skill_digest = skill_hasher.finalize(); + let mut epoch_bytes = [0_u8; 8]; + epoch_bytes.copy_from_slice(skill_digest.get(..8).unwrap_or_default()); + let skills_dir_epoch = u64::from_be_bytes(epoch_bytes); + let hooks = hooks + .events + .iter() + .flat_map(|(event, count)| { + (0..*count).map(move |index| HookSource { + event: event.clone(), + action: format!( + "action_{index}_{}", + hex::encode(hooks.catalog_digest.unwrap_or_default().get(..8).unwrap_or_default()) + ), + effect: SideEffectClass::ProcessExec, + }) + }) + .collect(); + let nodes = config + .nodes + .nodes + .iter() + .map(|node| NodeSource { + id: node.id.clone(), + availability: CapabilityAvailability::configured("remote node configured"), + binding_digest: serde_json::to_vec(node) + .map(|bytes| Sha256::digest(bytes).into()) + .unwrap_or_default(), + }) + .collect(); + Self { + config_generation_id, + mcp_state_epoch: u64::from_be_bytes(mcp_epoch_bytes), + wasm_generation, + skills_dir_epoch, + mcp, + skills, + hooks, + nodes, + node_key: None, + } + } +} + +/// The entrypoint's publication boundary, applied after registry discovery. +#[derive(Clone, Default)] +pub(crate) struct SurfacePolicy { + pub allowed_tools: Option>, + pub excluded_names: BTreeSet, + pub direct_names: BTreeSet, + pub channel_allowed: bool, +} + +impl std::fmt::Debug for SurfacePolicy { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let mut value = f.debug_struct("SurfacePolicy"); + value + .field("excluded_names", &self.excluded_names) + .field("direct_names", &self.direct_names) + .field("channel_allowed", &self.channel_allowed); + // Preserve the established generation fingerprint for unrestricted surfaces. + if let Some(allowed) = &self.allowed_tools { + value.field("allowed_tools", allowed); + } + value.finish() + } +} + +impl SurfacePolicy { + pub(crate) fn permits(&self, name: &str, root: &str, target: &ExecutionTarget) -> bool { + self.allowed_tools.as_ref().is_none_or(|allowed| { + allowed.contains(name) + || matches!(target, ExecutionTarget::Skill { .. } | ExecutionTarget::Node { .. }) + && allowed.contains(root) + }) + } +} + +#[derive(Debug, thiserror::Error)] +pub(crate) enum CatalogError { + #[error("duplicate capability public name or id")] + Duplicate, + #[error("invalid capability identity")] + Identity, + #[error("capability schema is invalid")] + Schema, +} + +#[derive(Debug, thiserror::Error)] +pub(crate) enum StaleCapability { + #[error("capability generation or schema changed")] + Stale, + #[error("capability is unavailable")] + Unavailable, +} + +#[derive(Debug, thiserror::Error)] +#[error("catalog and execution registry differ")] +pub(crate) struct ParityError; + +#[derive(Debug, Clone)] +pub(crate) struct CapabilityCatalog { + entries: Vec, + by_id: BTreeMap, + by_name: BTreeMap, + binding_roots: BTreeSet, + generation: CatalogGeneration, + search_index: super::search::SearchIndex, +} + +pub(crate) struct CatalogView<'a> { + surface: Option<&'a SurfacePolicy>, + #[cfg(test)] + entries: OnceLock>, + generation: CatalogGeneration, + by_id: &'a BTreeMap, + pub(super) search_index: &'a super::search::SearchIndex, + pub(super) all_entries: &'a [CapabilityEntry], + families: [bool; CapabilityTarget::ALL.len()], + channel: bool, +} + +#[derive(Debug, Clone, Default)] +pub(crate) struct CatalogScope { + pub families: BTreeSet, + pub channel: bool, +} + +impl CapabilityCatalog { + pub(crate) fn build( + registry: &[Box], + sources: &CatalogSources, + surface: &SurfacePolicy, + ) -> Result { + let discovered_mcp: BTreeSet<_> = sources.mcp.iter().map(|item| item.spec.name.as_str()).collect(); + let descriptors = ToolCatalog::from_boxed_registry(registry); + let mut entries = Vec::new(); + let mut seen_names = BTreeSet::new(); + let mut seen_ids = BTreeSet::new(); + let mut raw_names = BTreeSet::new(); + for tool in registry { + for spec in tool.specs() { + if !raw_names.insert(spec.name.clone()) { + return Err(CatalogError::Duplicate); + } + } + } + for descriptor in descriptors.descriptors() { + if descriptor.adapter == ToolAdapterKind::McpAlias + && discovered_mcp.contains(descriptor.public_name.as_str()) + { + continue; + } + let family = family_for(descriptor); + let namespace = if descriptor.adapter == ToolAdapterKind::McpAlias { + "mcp".to_string() + } else { + "native".to_string() + }; + let effect = effect_for(descriptor); + let entry = entry_from_spec( + ToolSpec { + name: descriptor.public_name.clone(), + description: descriptor.description.clone(), + parameters: descriptor.parameters.clone(), + }, + descriptor.backend_name.clone(), + namespace, + family, + descriptor.categories.clone(), + effect, + descriptor.availability.clone(), + descriptor.process_worker_compatible, + ExecutionTarget::Tool(descriptor.public_name.clone()), + surface, + )?; + insert(entry, &mut entries, &mut seen_names, &mut seen_ids)?; + } + for discovered in &sources.mcp { + let mut entry = entry_from_spec( + discovered.spec.clone(), + "mcp_call".to_string(), + discovered.server.clone(), + CapabilityTarget::Mcp, + vec![ToolCategory::Automation], + SideEffectClass::Destructive, + CapabilityAvailability::ready("discovered allowed MCP backend"), + true, + ExecutionTarget::Tool(discovered.spec.name.clone()), + surface, + )?; + entry.aliases.push(discovered.tool.clone()); + entry.binding_digest = Some(discovered.state_digest); + let op = OpId::new(&crate::security::op_id::op_id( + "mcp_call", + "call", + &[&discovered.server, &discovered.tool], + )); + entry.op_ids = vec![op.clone()]; + entry.approval = ApprovalRequirement::Required { op_ids: vec![op] }; + insert(entry, &mut entries, &mut seen_names, &mut seen_ids)?; + } + for skill in &sources.skills { + let spec = crate::tools::skills::catalog_skill_read_spec(skill); + let mut entry = entry_from_spec( + spec, + "skill_read".to_string(), + "skill".to_string(), + CapabilityTarget::Skill, + vec![ToolCategory::System], + SideEffectClass::ReadOnly, + CapabilityAvailability::configured("installed skill metadata"), + true, + ExecutionTarget::Skill { + name: skill.name.clone(), + root: "skill_read".to_string(), + }, + surface, + )?; + entry.binding_digest = Some(crate::skills::catalog_skill_binding_digest(skill)); + entry.skill_metadata = Some(Arc::new(skill.clone())); + if entry.public_name != skill.name { + entry.aliases.push(skill.name.clone()); + } + insert(entry, &mut entries, &mut seen_names, &mut seen_ids)?; + } + for hook in &sources.hooks { + let name = format!("hook_{}_{}", hook.event, hook.action); + let mut entry = entry_from_spec( + ToolSpec { + name: name.clone(), + description: "Registered lifecycle observer".to_string(), + parameters: json!({"type":"object","properties":{}}), + }, + "hooks".to_string(), + "hook".to_string(), + CapabilityTarget::Hook, + vec![ToolCategory::Automation], + hook.effect, + CapabilityAvailability::configured("registered lifecycle hook"), + true, + ExecutionTarget::Hook, + surface, + )?; + entry.exposure = Exposure::Unavailable { + reason: "hooks run as observers".to_string(), + }; + insert(entry, &mut entries, &mut seen_names, &mut seen_ids)?; + } + for node in &sources.nodes { + if node.binding_digest == [0; 32] { + return Err(CatalogError::Schema); + } + let key = sources.node_key.as_ref().ok_or(CatalogError::Identity)?; + let id = CapabilityId::remote_node(key, &node.id).map_err(|_| CatalogError::Identity)?; + let name = id + .as_str() + .rsplit(':') + .next() + .ok_or(CatalogError::Identity)? + .to_string(); + let mut entry = entry_from_spec( + ToolSpec { + name, + description: "Configured remote node shell".to_string(), + parameters: json!({"type":"object","properties":{"node":{"const":node.id}}}), + }, + "nodes".to_string(), + "node".to_string(), + CapabilityTarget::Shell, + vec![ToolCategory::DevOps], + SideEffectClass::ProcessExec, + node.availability.clone(), + true, + ExecutionTarget::Node { + id: node.id.clone(), + root: "nodes".to_string(), + }, + surface, + )?; + entry.id = id; + entry.binding_digest = Some(node.binding_digest); + // Cancel includes a runtime task ID and cannot be represented by + // a fixed node-level approval scope here. + entry.op_ids = ["exec", "write"] + .into_iter() + .map(|action| OpId::new(&format!("nodes:{action}:{}", node.id))) + .collect(); + entry.approval = ApprovalRequirement::Required { + op_ids: entry.op_ids.clone(), + }; + insert(entry, &mut entries, &mut seen_names, &mut seen_ids)?; + } + entries.sort_by(|left, right| left.id.cmp(&right.id)); + let generation = generation_of(sources, surface, &entries); + Ok(Self::from_entries(entries, generation)) + } + + fn from_entries(mut entries: Vec, generation: CatalogGeneration) -> Self { + let mut by_id = BTreeMap::new(); + let mut by_name = BTreeMap::new(); + let mut binding_roots = BTreeSet::new(); + for (index, entry) in entries.iter_mut().enumerate() { + entry.generation = generation; + by_id.insert(entry.id.clone(), index); + by_name.insert(entry.public_name.clone(), index); + if entry.binding_digest.is_some() { + binding_roots.insert(entry.root.clone()); + } + } + let search_index = super::search::SearchIndex::build(&entries); + Self { + entries, + by_id, + by_name, + binding_roots, + generation, + search_index, + } + } + + pub(crate) const fn generation(&self) -> &CatalogGeneration { + &self.generation + } + + pub(crate) fn view(&self, scope: &CatalogScope) -> CatalogView<'_> { + CatalogView { + surface: None, + search_index: &self.search_index, + by_id: &self.by_id, + all_entries: &self.entries, + families: CapabilityTarget::ALL.map(|family| scope.families.is_empty() || scope.families.contains(&family)), + channel: scope.channel, + #[cfg(test)] + entries: OnceLock::new(), + generation: self.generation, + } + } + + /// Every pinned public name, for surface enumeration. Callers resolve each + /// name live before treating it as a candidate. + pub(crate) fn public_names(&self) -> impl Iterator + '_ { + self.by_name.keys().map(String::as_str) + } + + pub(crate) fn entry_for_public_name(&self, name: &str) -> Option<&CapabilityEntry> { + self.by_name.get(name).and_then(|index| self.entries.get(*index)) + } + + pub(crate) fn resolve<'a>( + &self, + refs: impl IntoIterator, + ) -> Result, StaleCapability> { + refs.into_iter() + .map(|reference| { + let entry = self + .by_id + .get(&reference.id) + .and_then(|index| self.entries.get(*index)) + .ok_or(StaleCapability::Stale)?; + if reference.generation != self.generation || reference.fingerprint != entry.fingerprint { + return Err(StaleCapability::Stale); + } + if matches!(entry.exposure, Exposure::Unavailable { .. }) { + return Err(StaleCapability::Unavailable); + } + Ok(entry) + }) + .collect() + } + + /// Check a child's actual executor against the immutable parent catalog. + /// Omitted parent capabilities are not part of the child executor; every + /// granted reference and its root/dispatch binding must remain exact. + pub(crate) fn check_child_parity( + &self, + exec: &ToolExecutionService, + scope: &super::child::VerifiedChildScope, + ) -> Result<(), ParityError> { + let (manifest, parent) = scope.gate_inputs(); + manifest.verify(parent).map_err(|_| ParityError)?; + if manifest.catalog_generation != self.generation { + return Err(ParityError); + } + // Full children inherit the complete level surface, including parent + // backends this child executor cannot serve. Every served reference + // still needs exact descriptor/binding parity; below Full the entire + // sealed subset must be executable as before. + if manifest.authority.level == crate::security::AutonomyLevel::Full { + self.check_published_parity(exec, &self.served_references(exec, &manifest.allowed)) + } else { + self.check_published_parity(exec, &manifest.allowed) + } + } + + /// Whether `exec` registers the backend that runs `entry`. A worker's + /// catalog is its parent's pinned one and can hold entries its own + /// executor never registers (interactive-only tools); such an entry is + /// unserved there, not a parity failure. A registered backend must still + /// match exactly ([`Self::check_published_parity`]). + pub(crate) fn served_by(exec: &ToolExecutionService, entry: &CapabilityEntry) -> bool { + match &entry.target { + ExecutionTarget::Tool(name) => exec.current_descriptor(name).is_some(), + ExecutionTarget::Skill { .. } | ExecutionTarget::Node { .. } => { + exec.current_descriptor(&entry.root).is_some() + } + ExecutionTarget::Hook => false, + } + } + + /// The references of `allowed` whose backend `exec` registers. + pub(crate) fn served_references( + &self, + exec: &ToolExecutionService, + allowed: &std::collections::BTreeSet, + ) -> std::collections::BTreeSet { + allowed + .iter() + .filter(|reference| { + self.by_id + .get(&reference.id) + .and_then(|index| self.entries.get(*index)) + .is_none_or(|entry| Self::served_by(exec, entry)) + }) + .cloned() + .collect() + } + + /// Verify an authenticated publication's exact references against the local + /// executor. Authority and visibility are enforced by the owning service. + pub(crate) fn check_published_parity( + &self, + exec: &ToolExecutionService, + allowed: &std::collections::BTreeSet, + ) -> Result<(), ParityError> { + for reference in allowed { + let entry = self + .by_id + .get(&reference.id) + .and_then(|index| self.entries.get(*index)) + .ok_or(ParityError)?; + if reference.generation != self.generation + || reference.fingerprint != entry.fingerprint + || matches!(entry.exposure, Exposure::Unavailable { .. }) + { + return Err(ParityError); + } + let current_binding = match &entry.target { + ExecutionTarget::Tool(name) => { + let (exact, binding) = exec + .current_descriptor_with_binding(name, entry.binding_digest.is_some()) + .ok_or(ParityError)?; + verify_child_descriptor(entry, &exact)?; + binding + } + ExecutionTarget::Skill { name, .. } | ExecutionTarget::Node { id: name, .. } => { + let root_entry = self.entry_for_public_name(&entry.root).ok_or(ParityError)?; + let root = exec.current_descriptor(&entry.root).ok_or(ParityError)?; + verify_child_descriptor(root_entry, &root)?; + let argument = if matches!(entry.target, ExecutionTarget::Skill { .. }) { + "name" + } else { + "node" + }; + if root.parameters.pointer(&format!("/properties/{argument}")).is_none() + || entry.schema.pointer(&format!("/properties/{argument}/const")) + != Some(&Value::String(name.clone())) + { + return Err(ParityError); + } + exec.current_binding_digest(&entry.root, name) + } + ExecutionTarget::Hook => return Err(ParityError), + }; + if let Some(expected) = entry.binding_digest { + if current_binding != Some(expected) { + return Err(ParityError); + } + } else if !matches!(entry.target, ExecutionTarget::Tool(_)) { + return Err(ParityError); + } + } + Ok(()) + } + + pub(crate) fn check_parity(&self, exec: &ToolExecutionService) -> Result<(), ParityError> { + let live = exec.current_specs_for_parity(); + let mut live_by_index = vec![None; self.entries.len()]; + let mut bindings = BTreeMap::new(); + for root in &self.binding_roots { + if !live + .iter() + .any(|item| item.backend_name == root.as_str() && item.spec.shared_binding_digest().is_snapshot()) + { + bindings.insert(root.as_str(), exec.current_binding_snapshot(root).ok_or(ParityError)?); + } + } + for descriptor in &live { + if !descriptor.configured { + continue; + } + let index = *self.by_name.get(descriptor.spec.name.as_str()).ok_or(ParityError)?; + let slot = live_by_index.get_mut(index).ok_or(ParityError)?; + if slot.replace(descriptor).is_some() { + return Err(ParityError); + } + let entry = self.entries.get(index).ok_or(ParityError)?; + if entry.root != descriptor.backend_name + || descriptor.spec.fingerprint() != entry.fingerprint + || entry.binding_digest.is_some() + && descriptor.spec.shared_binding_digest().or_else_live(|| { + bindings + .get(entry.root.as_str()) + .and_then(|snapshot| snapshot.get(descriptor.spec.name.as_str())) + .copied() + }) != entry.binding_digest + { + return Err(ParityError); + } + } + let live_for = |name: &str| { + self.by_name + .get(name) + .and_then(|index| live_by_index.get(*index)) + .copied() + .flatten() + .ok_or(ParityError) + }; + for entry in &self.entries { + if matches!(entry.exposure, Exposure::Unavailable { .. }) { + continue; + } + if let ExecutionTarget::Tool(name) = &entry.target { + let exact = live_for(name)?; + if exact.backend_name != entry.root || exact.spec.fingerprint() != entry.fingerprint { + return Err(ParityError); + } + } else { + let current = live_for(&entry.root)?; + if !current.configured { + return Err(ParityError); + } + // A synthetic target must bind the exact dispatch argument + // accepted by the root contract, not only its root name. + let binding = match &entry.target { + ExecutionTarget::Skill { name, .. } => ("name", name.as_str()), + ExecutionTarget::Node { id, .. } => ("node", id.as_str()), + ExecutionTarget::Hook | ExecutionTarget::Tool(_) => return Err(ParityError), + }; + if current + .spec + .parameters + .pointer(&format!("/properties/{}", binding.0)) + .is_none() + || entry.schema.pointer(&format!("/properties/{}/const", binding.0)) + != Some(&Value::String(binding.1.to_string())) + || current.spec.shared_named_binding(binding.1).or_else_live(|| { + bindings + .get(entry.root.as_str()) + .and_then(|snapshot| snapshot.get(binding.1)) + .copied() + }) != entry.binding_digest + { + return Err(ParityError); + } + } + } + Ok(()) + } +} + +fn verify_child_descriptor(entry: &CapabilityEntry, current: &ToolDescriptor) -> Result<(), ParityError> { + let backend_matches = entry.root == current.backend_name; + if entry.public_name != current.public_name + || !backend_matches + || current.availability.level < CapabilityAvailabilityLevel::Configured + || crate::tools::schema::SchemaCleanr::validate(¤t.parameters).is_err() + || tool_spec_fingerprint(¤t.public_name, ¤t.description, ¤t.parameters) != entry.fingerprint + { + return Err(ParityError); + } + Ok(()) +} + +impl<'a> CatalogView<'a> { + /// Narrow a view without copying entries, schemas, bindings or the search index. + pub(crate) const fn with_surface(&self, surface: &'a SurfacePolicy) -> Self { + Self { + surface: Some(surface), + #[cfg(test)] + entries: OnceLock::new(), + generation: self.generation, + by_id: self.by_id, + search_index: self.search_index, + all_entries: self.all_entries, + families: self.families, + channel: self.channel, + } + } + + pub(crate) fn directly_exposes(&self, entry: &CapabilityEntry) -> bool { + matches!(entry.exposure, Exposure::Direct) + || self + .surface + .is_some_and(|surface| surface.direct_names.contains(&entry.public_name)) + } + + pub(crate) fn surface_excludes(&self, entry: &CapabilityEntry) -> bool { + self.surface.is_some_and(|surface| { + !surface.permits(&entry.public_name, &entry.root, &entry.target) + || surface.excluded_names.contains(&entry.public_name) + || surface.excluded_names.contains(&entry.root) + }) + } + + /// Compatibility slice for inspection fixtures. Production decision paths + /// use the borrowing iterator instead of materializing this slice. + #[cfg(test)] + pub(crate) fn entries(&self) -> &[&'a CapabilityEntry] { + self.entries.get_or_init(|| self.iter_entries().collect()) + } + + pub(crate) fn iter_entries(&self) -> impl Iterator + '_ { + self.all_entries.iter().filter(|entry| self.entry_visible(entry)) + } + + fn entry_visible(&self, entry: &CapabilityEntry) -> bool { + self.families + .iter() + .zip(CapabilityTarget::ALL) + .any(|(allowed, family)| *allowed && family == entry.family) + && (!self.channel || entry.channel_eligible) + && !self.surface_excludes(entry) + && !matches!(entry.exposure, Exposure::Unavailable { .. }) + } + + pub(super) fn is_visible_index(&self, index: usize) -> bool { + self.all_entries + .get(index) + .is_some_and(|entry| self.entry_visible(entry)) + } + + /// Look up a catalog entry before view filtering. Gates need to report + /// configured exclusions before reporting availability or stale refs. + pub(crate) fn entry_any(&self, id: &CapabilityId) -> Option<&'a CapabilityEntry> { + self.by_id.get(id).and_then(|index| self.all_entries.get(*index)) + } + + pub(crate) fn contains(&self, id: &CapabilityId) -> bool { + self.by_id.get(id).is_some_and(|index| self.is_visible_index(*index)) + } + + pub(crate) const fn generation(&self) -> CatalogGeneration { + self.generation + } +} + +fn insert( + mut entry: CapabilityEntry, + entries: &mut Vec, + names: &mut BTreeSet, + ids: &mut BTreeSet, +) -> Result<(), CatalogError> { + if !names.insert(entry.public_name.clone()) || !ids.insert(entry.id.clone()) { + return Err(CatalogError::Duplicate); + } + entry.exact_mention_terms = std::iter::once(entry.id.as_str()) + .chain(std::iter::once(entry.public_name.as_str())) + .chain(entry.aliases.iter().map(String::as_str)) + .map(str::to_lowercase) + .collect(); + entries.push(entry); + Ok(()) +} + +// Native identities remain compatible with existing manifests while semantic +// families distinguish document/process work. Creation and authenticated +// process restoration must use this one canonical identity rule. +fn canonical_identity_family(family: CapabilityTarget, namespace: &str, name: &str) -> CapabilityTarget { + if namespace == "native" + && matches!( + (family, name), + (CapabilityTarget::Shell, "shell") | (CapabilityTarget::Document, "document_ingest" | "document_sync") + ) + { + CapabilityTarget::Filesystem + } else { + family + } +} + +fn entry_from_spec( + spec: ToolSpec, + root: String, + namespace: String, + family: CapabilityTarget, + categories: Vec, + effect: SideEffectClass, + availability: CapabilityAvailability, + process_worker_compatible: bool, + target: ExecutionTarget, + surface: &SurfacePolicy, +) -> Result { + crate::tools::schema::SchemaCleanr::validate(&spec.parameters).map_err(|_| CatalogError::Schema)?; + let identity_family = canonical_identity_family(family, &namespace, &spec.name); + let id = CapabilityId::new(identity_family, &namespace, &spec.name).map_err(|_| CatalogError::Identity)?; + let fingerprint = tool_spec_fingerprint(&spec.name, &spec.description, &spec.parameters); + let exposure = if !surface.permits(&spec.name, &root, &target) + || surface.excluded_names.contains(&spec.name) + || surface.excluded_names.contains(&root) + || availability.level < CapabilityAvailabilityLevel::Configured + { + Exposure::Unavailable { + reason: "not available on this surface".to_string(), + } + } else if surface.direct_names.contains(&spec.name) { + Exposure::Direct + } else { + Exposure::Searchable + }; + // Most tools derive the exact operation id from runtime arguments (path, + // destination, task id). Do not advertise a fabricated grant target. + let op_ids = Vec::new(); + let approval = if effect == SideEffectClass::ReadOnly { + ApprovalRequirement::None + } else { + ApprovalRequirement::Required { op_ids: Vec::new() } + }; + let schema_bytes = serde_json::to_vec(&spec.parameters).map_or(usize::MAX, |value| value.len()); + Ok(CapabilityEntry { + id, + public_name: spec.name, + root, + family, + namespace, + summary: summary(&spec.description), + aliases: Vec::new(), + categories, + exact_mention_terms: Vec::new(), + effect, + risk: risk_for_effect(effect), + op_ids, + approval, + channel_eligible: surface.channel_allowed, + schema: Arc::new(spec.parameters), + schema_bytes, + fingerprint, + generation: CatalogGeneration([0; 32]), + target, + binding_digest: None, + skill_metadata: None, + exposure, + availability, + process_worker_compatible, + }) +} + +pub(super) const fn risk_for_effect(effect: SideEffectClass) -> RiskLevel { + match effect { + SideEffectClass::ReadOnly => RiskLevel::Low, + SideEffectClass::LocalWrite | SideEffectClass::ExternalSend | SideEffectClass::CredentialOrConfig => { + RiskLevel::Medium + } + SideEffectClass::ProcessExec | SideEffectClass::Destructive => RiskLevel::High, + } +} + +fn summary(description: &str) -> String { + let redacted = crate::security::redaction::redact_secrets(description); + redacted + .chars() + .filter(|ch| !ch.is_control() && !matches!(ch, '\u{200b}'..='\u{200f}' | '\u{2060}' | '\u{feff}')) + .take(160) + .collect() +} + +/// Canonical identity of a registered descriptor, shared by publication and +/// execution observations. This identifies an observed call, not permission. +pub(crate) fn descriptor_identity(descriptor: &ToolDescriptor) -> Result { + let namespace = if descriptor.adapter == ToolAdapterKind::McpAlias { + "mcp" + } else { + "native" + }; + let family = canonical_identity_family(family_for(descriptor), namespace, &descriptor.public_name); + CapabilityId::new(family, namespace, &descriptor.public_name).map_err(|_| CatalogError::Identity) +} + +fn family_for(descriptor: &ToolDescriptor) -> CapabilityTarget { + match descriptor.adapter { + ToolAdapterKind::McpAlias => CapabilityTarget::Mcp, + ToolAdapterKind::WasmPlugin => CapabilityTarget::Wasm, + ToolAdapterKind::Skill => CapabilityTarget::Skill, + ToolAdapterKind::Native => { + if matches!( + descriptor.public_name.as_str(), + "document_search" | "document_ingest" | "document_sync" + ) { + CapabilityTarget::Document + } else if descriptor.public_name == "sessions_history" { + CapabilityTarget::Session + } else if descriptor.public_name == "shell" { + CapabilityTarget::Shell + } else if descriptor.categories.contains(&ToolCategory::FileSystem) { + CapabilityTarget::Filesystem + } else if descriptor.categories.contains(&ToolCategory::Memory) { + CapabilityTarget::Memory + } else if descriptor.categories.contains(&ToolCategory::WebBrowsing) { + CapabilityTarget::Web + } else if descriptor.categories.contains(&ToolCategory::Communication) { + CapabilityTarget::Im + } else { + CapabilityTarget::NativeTool + } + } + } +} + +fn effect_for(descriptor: &ToolDescriptor) -> SideEffectClass { + match descriptor.effect { + ToolEffect::Read => SideEffectClass::ReadOnly, + ToolEffect::Act => match descriptor.public_name.as_str() { + "shell" | "git_operations" => SideEffectClass::ProcessExec, + "message_send" | "http_request" => SideEffectClass::ExternalSend, + "sessions_send" if descriptor.parameters.get("oneOf").is_some() => SideEffectClass::ExternalSend, + "config_reload" | "proxy_config" => SideEffectClass::CredentialOrConfig, + "nodes" | "mcp_call" | "skill_execute" => SideEffectClass::Destructive, + "delegate" | "sessions_spawn" => SideEffectClass::ProcessExec, + _ => SideEffectClass::LocalWrite, + }, + } +} + +fn generation_of(sources: &CatalogSources, surface: &SurfacePolicy, entries: &[CapabilityEntry]) -> CatalogGeneration { + let mut hasher = Sha256::new(); + for value in [ + sources.config_generation_id.as_bytes(), + &sources.mcp_state_epoch.to_be_bytes(), + &sources.wasm_generation.to_be_bytes(), + &sources.skills_dir_epoch.to_be_bytes(), + ] { + hasher.update(value.len().to_be_bytes()); + hasher.update(value); + } + for entry in entries { + for value in [ + entry.id.as_str().as_bytes(), + entry.family.as_str().as_bytes(), + entry.fingerprint.0.as_slice(), + entry.root.as_bytes(), + entry.public_name.as_bytes(), + ] { + hasher.update(value.len().to_be_bytes()); + hasher.update(value); + } + let policy = format!( + "{:?}{:?}{:?}{:?}{:?}{:?}{:?}{:?}{:?}", + entry.categories, + entry.effect, + entry.risk, + entry.op_ids, + entry.approval, + entry.exposure, + entry.availability, + entry.target, + entry.binding_digest + ); + hasher.update(policy.len().to_be_bytes()); + hasher.update(policy.as_bytes()); + } + let mut mcp_ordered: Vec<_> = sources.mcp.iter().collect(); + mcp_ordered.sort_by(|left, right| (&left.server, &left.tool).cmp(&(&right.server, &right.tool))); + for item in mcp_ordered { + hasher.update(item.server.len().to_be_bytes()); + hasher.update(item.server.as_bytes()); + hasher.update(item.state_digest); + } + let policy = format!("{surface:?}"); + hasher.update(policy.len().to_be_bytes()); + hasher.update(policy.as_bytes()); + CatalogGeneration(hasher.finalize().into()) +} diff --git a/src/tools/capability/catalog/section_2.rs b/src/tools/capability/catalog/section_2.rs new file mode 100644 index 000000000..b48f16909 --- /dev/null +++ b/src/tools/capability/catalog/section_2.rs @@ -0,0 +1,1287 @@ +#[cfg(test)] +mod tests { + use super::*; + use crate::tools::capability::search::CatalogSearch; + use crate::tools::traits::ToolResult; + use async_trait::async_trait; + use std::sync::atomic::{AtomicUsize, Ordering}; + + struct ProbeTool { + name: &'static str, + description: &'static str, + } + + #[async_trait] + impl Tool for ProbeTool { + fn name(&self) -> &str { + self.name + } + + fn description(&self) -> &str { + self.description + } + + fn parameters_schema(&self) -> Value { + json!({"type":"object","properties":{"query":{"type":"string"}}}) + } + + async fn execute(&self, _args: Value) -> anyhow::Result { + Ok(ToolResult { + success: true, + output: String::new(), + error: None, + }) + } + } + + struct DocumentCategoryProbe(&'static str); + #[async_trait] + impl Tool for DocumentCategoryProbe { + fn name(&self) -> &str { + self.0 + } + fn description(&self) -> &str { + "Native document index operation" + } + fn parameters_schema(&self) -> Value { + json!({"type":"object","properties":{}}) + } + fn categories(&self) -> &'static [ToolCategory] { + &[ToolCategory::Memory, ToolCategory::FileSystem] + } + async fn execute(&self, _: Value) -> anyhow::Result { + anyhow::bail!("metadata fixture never executes") + } + } + + #[test] + fn document_index_tools_keep_legacy_ids_without_entering_filesystem_discovery() { + let registry: Vec> = vec![ + Box::new(DocumentCategoryProbe("document_ingest")), + Box::new(DocumentCategoryProbe("document_sync")), + ]; + let catalog = + CapabilityCatalog::build(®istry, &CatalogSources::default(), &SurfacePolicy::default()).unwrap(); + for name in ["document_ingest", "document_sync"] { + let entry = catalog.entry_for_public_name(name).unwrap(); + assert_eq!(entry.family, CapabilityTarget::Document); + assert_eq!(entry.id.as_str(), format!("filesystem:native:{name}")); + } + let view = catalog.view(&CatalogScope { + families: BTreeSet::from([CapabilityTarget::Filesystem]), + ..CatalogScope::default() + }); + assert!(view.iter_entries().next().is_none()); + } + + fn registry() -> Vec> { + vec![ + Box::new(ProbeTool { + name: "prx_search", + description: "Search local evidence", + }), + Box::new(ProbeTool { + name: "prx_read", + description: "Read local evidence", + }), + ] + } + + // Public aliases need not export their backend identity as another capability. + struct AliasOnlyParityTool { + backend: &'static str, + state: Arc, + } + + #[async_trait] + impl Tool for AliasOnlyParityTool { + fn name(&self) -> &str { + self.backend + } + + fn description(&self) -> &str { + "PRX alias parity fixture" + } + + fn parameters_schema(&self) -> Value { + if self.state.load(Ordering::SeqCst) == 1 { + json!({"type":"object","properties":{"value":{"type":"string"}}}) + } else { + json!({"type":"object","properties":{}}) + } + } + + fn specs(&self) -> Vec { + if self.state.load(Ordering::SeqCst) == 2 { + return Vec::new(); + } + vec![ToolSpec { + name: "prx_exact_alias".into(), + description: self.description().into(), + parameters: self.parameters_schema(), + }] + } + + fn supports_name(&self, name: &str) -> bool { + name == "prx_exact_alias" && self.state.load(Ordering::SeqCst) != 2 + } + + fn availability(&self) -> CapabilityAvailability { + if self.state.load(Ordering::SeqCst) == 3 { + CapabilityAvailability { + level: CapabilityAvailabilityLevel::Declared, + reason: "PRX fixture is no longer configured".into(), + } + } else { + CapabilityAvailability::ready("PRX fixture configured") + } + } + + async fn execute(&self, _args: Value) -> anyhow::Result { + anyhow::bail!("parity fixture does not execute effects") + } + } + + #[test] + fn alias_only_tool_parity_preserves_exact_identity_and_live_contract() { + let state = Arc::new(AtomicUsize::new(0)); + let registry: Vec> = vec![Box::new(AliasOnlyParityTool { + backend: "prx_alias_backend", + state: Arc::clone(&state), + })]; + let catalog = + CapabilityCatalog::build(®istry, &CatalogSources::default(), &SurfacePolicy::default()).unwrap(); + let entry = catalog.entry_for_public_name("prx_exact_alias").unwrap(); + let reference = CapabilityRef { + id: entry.id.clone(), + generation: entry.generation, + fingerprint: entry.fingerprint, + }; + let allowed = BTreeSet::from([reference.clone()]); + let service = + ToolExecutionService::with_security_policy(registry, Arc::new(crate::security::SecurityPolicy::default())); + assert!(catalog.entry_for_public_name("prx_alias_backend").is_none()); + assert!(service.current_descriptor("prx_alias_backend").is_none()); + assert!(catalog.check_parity(&service).is_ok()); + assert!(catalog.check_published_parity(&service, &allowed).is_ok()); + + let wrong_backend = ToolExecutionService::with_security_policy( + vec![Box::new(AliasOnlyParityTool { + backend: "prx_other_backend", + state: Arc::clone(&state), + })], + Arc::new(crate::security::SecurityPolicy::default()), + ); + assert!(catalog.check_parity(&wrong_backend).is_err()); + assert!(catalog.check_published_parity(&wrong_backend, &allowed).is_err()); + let mut stale = reference.clone(); + stale.generation = CatalogGeneration([0; 32]); + assert_ne!(stale.generation, reference.generation); + assert!( + catalog + .check_published_parity(&service, &BTreeSet::from([stale])) + .is_err() + ); + let mut changed = reference; + changed.fingerprint = SchemaFingerprint([0; 32]); + assert_ne!(changed.fingerprint, entry.fingerprint); + assert!( + catalog + .check_published_parity(&service, &BTreeSet::from([changed])) + .is_err() + ); + // Schema drift, disappearance and loss of configured availability each + // independently invalidate the original immutable publication. + for mode in [1, 2, 3] { + state.store(mode, Ordering::SeqCst); + assert!(catalog.check_parity(&service).is_err()); + assert!(catalog.check_published_parity(&service, &allowed).is_err()); + } + } + + struct BlankReasonAvailabilityTool; + + #[async_trait] + impl Tool for BlankReasonAvailabilityTool { + fn name(&self) -> &str { + "prx_blank_reason" + } + + fn description(&self) -> &str { + "PRX availability compatibility fixture" + } + + fn parameters_schema(&self) -> Value { + json!({"type":"object","properties":{}}) + } + + fn availability(&self) -> CapabilityAvailability { + CapabilityAvailability { + level: CapabilityAvailabilityLevel::Declared, + reason: String::new(), + } + } + + async fn execute(&self, _args: Value) -> anyhow::Result { + Ok(ToolResult { + success: true, + output: String::new(), + error: None, + }) + } + } + + #[test] + fn parity_preserves_legacy_empty_availability_reason_promotion() { + let registry: Vec> = vec![Box::new(BlankReasonAvailabilityTool)]; + let catalog = + CapabilityCatalog::build(®istry, &CatalogSources::default(), &SurfacePolicy::default()).unwrap(); + let service = + ToolExecutionService::with_security_policy(registry, Arc::new(crate::security::SecurityPolicy::default())); + assert_eq!( + service + .current_descriptor("prx_blank_reason") + .unwrap() + .availability + .level, + CapabilityAvailabilityLevel::Ready + ); + assert!(catalog.check_parity(&service).is_ok()); + } + + struct BorrowedSpecTool { + spec: ToolSpec, + owned_calls: Arc, + } + + #[async_trait] + impl Tool for BorrowedSpecTool { + fn name(&self) -> &str { + &self.spec.name + } + + fn description(&self) -> &str { + &self.spec.description + } + + fn parameters_schema(&self) -> Value { + self.spec.parameters.clone() + } + + fn catalog_specs(&self) -> Vec { + self.owned_calls.fetch_add(1, Ordering::SeqCst); + vec![self.spec.clone()] + } + + fn immutable_catalog_specs(&self) -> Option<&[ToolSpec]> { + Some(std::slice::from_ref(&self.spec)) + } + + async fn execute(&self, _args: Value) -> anyhow::Result { + anyhow::bail!("borrowed-spec fixture must not execute") + } + } + + #[test] + fn parity_borrows_immutable_specs_without_rebuilding_owned_inventory() { + let owned_calls = Arc::new(AtomicUsize::new(0)); + let registry: Vec> = vec![Box::new(BorrowedSpecTool { + spec: ToolSpec { + name: "prx_borrowed".to_string(), + description: "PRX borrowed spec fixture".to_string(), + parameters: json!({"type":"object","properties":{}}), + }, + owned_calls: Arc::clone(&owned_calls), + })]; + let catalog = + CapabilityCatalog::build(®istry, &CatalogSources::default(), &SurfacePolicy::default()).unwrap(); + let service = + ToolExecutionService::with_security_policy(registry, Arc::new(crate::security::SecurityPolicy::default())); + let before = owned_calls.load(Ordering::SeqCst); + assert!(catalog.check_parity(&service).is_ok()); + assert_eq!(owned_calls.load(Ordering::SeqCst), before); + } + + #[test] + fn catalog_fingerprint_equals_compiled_tool_context_per_spec_sha() { + let tools = registry(); + let catalog = CapabilityCatalog::build(&tools, &CatalogSources::default(), &SurfacePolicy::default()).unwrap(); + let compiled = + crate::agent::turn_context::CompiledToolContext::new(true, tools.iter().map(|tool| tool.spec()).collect()); + for entry in catalog.view(&CatalogScope::default()).entries() { + let compiled_spec = compiled + .fingerprint() + .tools + .iter() + .find(|spec| spec.name == entry.public_name) + .unwrap(); + assert_eq!(hex::encode(entry.fingerprint.0), compiled_spec.sha256); + } + } + + /// The canonical ids that `required-tools` takes are the ones the catalog + /// builds: Shell retains its historical file-system ID, and a discovered MCP + /// tool is filed under its server with its alias as the public name. + #[test] + fn canonical_ids_of_the_shell_and_a_discovered_mcp_tool_are_the_documented_ones() { + use crate::skills::lifecycle::{Bundle, BundleEntry, validate_manifest_strict}; + let workspace = tempfile::tempdir().unwrap(); + let tools: Vec> = vec![Box::new(crate::tools::shell::ShellTool::new( + Arc::new(crate::runtime::NativeRuntime::new()), + workspace.path().to_path_buf(), + ))]; + let mut sources = CatalogSources::default(); + sources.mcp.push(McpCapabilitySpec { + server: "notes".into(), + tool: "search".into(), + state_digest: [0; 32], + spec: ToolSpec { + name: "mcp__notes__search".into(), + description: "search notes".into(), + parameters: json!({"type":"object","properties":{}}), + }, + }); + let catalog = CapabilityCatalog::build(&tools, &sources, &SurfacePolicy::default()).unwrap(); + let shell = catalog.entry_for_public_name("shell").unwrap().id.as_str().to_owned(); + let mcp = catalog + .entry_for_public_name("mcp__notes__search") + .unwrap() + .id + .as_str() + .to_owned(); + assert_eq!(shell, "filesystem:native:shell"); + let shell_entry = catalog.entry_for_public_name("shell").unwrap(); + assert!(shell_entry.categories.contains(&ToolCategory::FileSystem)); + assert_eq!(shell_entry.family, CapabilityTarget::Shell); + assert_eq!(shell_entry.effect, SideEffectClass::ProcessExec); + let filesystem = catalog.view(&CatalogScope { + families: BTreeSet::from([CapabilityTarget::Filesystem]), + ..CatalogScope::default() + }); + assert!(filesystem.iter_entries().all(|entry| entry.public_name != "shell")); + let mut legacy_entries = catalog.entries.clone(); + legacy_entries + .iter_mut() + .find(|entry| entry.public_name == "shell") + .unwrap() + .family = CapabilityTarget::Filesystem; + assert_ne!( + generation_of(&sources, &SurfacePolicy::default(), &legacy_entries), + *catalog.generation(), + "semantic family drift must invalidate approvals even with stable capability IDs" + ); + assert_eq!(mcp, "mcp:notes:mcp__notes__search"); + // Exactly these strings are accepted by the lifecycle manifest check. + let skill = format!("---\nname: ids\ndescription: ids\nrequired-tools: [{shell}, {mcp}]\n---\n\nBody.\n"); + let bundle = Bundle::from_entries(vec![BundleEntry { + path: std::path::PathBuf::from("SKILL.md"), + bytes: skill.into_bytes(), + executable: false, + }]) + .unwrap(); + let info = validate_manifest_strict(&bundle).unwrap(); + assert_eq!(info.required_tools, vec![shell, mcp]); + } + + /// Every id the real catalog builds, for the built-in tools and for both MCP + /// forms, passes the strict write-time shape check of `required-tools`. + #[test] + fn every_id_the_catalog_builds_passes_the_required_tools_shape_check() { + use crate::skills::lifecycle::{Bundle, BundleEntry, validate_manifest_strict}; + let workspace = tempfile::tempdir().unwrap(); + let runtime: Arc = Arc::new(crate::runtime::NativeRuntime::new()); + let security = Arc::new(crate::security::SecurityPolicy::default()); + let tools: Vec> = vec![ + Box::new(crate::tools::shell::ShellTool::new( + runtime, + workspace.path().to_path_buf(), + )), + Box::new(crate::tools::file_read::FileReadTool::new(security, false)), + ]; + let mut sources = CatalogSources::default(); + for server in ["notes", "my__srv"] { + sources.mcp.push(McpCapabilitySpec { + server: server.into(), + tool: "search".into(), + state_digest: [0; 32], + spec: ToolSpec { + name: format!("mcp__{server}__search"), + description: "search".into(), + parameters: json!({"type":"object","properties":{}}), + }, + }); + } + let catalog = CapabilityCatalog::build(&tools, &sources, &SurfacePolicy::default()).unwrap(); + // An alias that was not discovered is filed under the namespace `mcp`. + let alias = CapabilityId::new(CapabilityTarget::Mcp, "mcp", "mcp__late__search").unwrap(); + let mut ids: Vec = catalog + .view(&CatalogScope::default()) + .iter_entries() + .map(|entry| entry.id.as_str().to_owned()) + .collect(); + ids.push(alias.as_str().to_owned()); + assert!(ids.iter().any(|id| id == "filesystem:native:shell"), "{ids:?}"); + assert!(ids.iter().any(|id| id == "filesystem:native:file_read"), "{ids:?}"); + assert!(ids.iter().any(|id| id == "mcp:my__srv:mcp__my__srv__search"), "{ids:?}"); + for id in &ids { + let skill = format!("---\nname: ids\ndescription: ids\nrequired-tools: [{id}]\n---\n\nBody.\n"); + let bundle = Bundle::from_entries(vec![BundleEntry { + path: std::path::PathBuf::from("SKILL.md"), + bytes: skill.into_bytes(), + executable: false, + }]) + .unwrap(); + let info = validate_manifest_strict(&bundle).unwrap_or_else(|e| panic!("{id} must pass: {e}")); + assert_eq!(info.required_tools, vec![id.clone()]); + } + } + + #[test] + fn catalog_rejects_duplicate_public_names_before_execution_deduplicates() { + let tools: Vec> = vec![ + Box::new(ProbeTool { + name: "prx_search", + description: "first", + }), + Box::new(ProbeTool { + name: "prx_search", + description: "second", + }), + ]; + assert!(matches!( + CapabilityCatalog::build(&tools, &CatalogSources::default(), &SurfacePolicy::default()), + Err(CatalogError::Duplicate) + )); + } + + #[test] + fn exact_name_precedes_ranked_search_and_exclusions() { + let mut surface = SurfacePolicy::default(); + surface.excluded_names.insert("prx_read".to_string()); + let catalog = CapabilityCatalog::build(®istry(), &CatalogSources::default(), &surface).unwrap(); + let view = catalog.view(&CatalogScope::default()); + let hit = CatalogSearch::find(&view, "prx_search", &[], 5); + assert_eq!(hit.len(), 1); + assert_eq!(hit.first().unwrap().entry.public_name, "prx_search"); + assert!( + CatalogSearch::find(&view, "prx_read", &[], 5) + .iter() + .all(|hit| hit.entry.public_name != "prx_read") + ); + assert!(CatalogSearch::find(&view, "*", &[], 5).is_empty()); + } + + #[test] + fn unspaced_script_query_matches_substring_of_longer_summary() { + // Neutral code points exercise the same bigram branch as CJK without + // embedding non-English prose in source or test fixtures. + assert!(crate::tools::capability::search::character_is_unspaced_script( + char::from_u32(0x4e00).unwrap() + )); + let description: String = (0x0e01..=0x0e08).filter_map(char::from_u32).collect(); + let query: String = description.chars().skip(2).take(3).collect(); + let tools: Vec> = vec![Box::new(ProbeTool { + name: "prx_remote", + description: Box::leak(description.into_boxed_str()), + })]; + let catalog = CapabilityCatalog::build(&tools, &CatalogSources::default(), &SurfacePolicy::default()).unwrap(); + let view = catalog.view(&CatalogScope::default()); + let hits = CatalogSearch::find(&view, &query, &[], 5); + assert_eq!( + hits.first().map(|hit| hit.entry.public_name.as_str()), + Some("prx_remote") + ); + } + + #[test] + fn excluding_dispatch_roots_hides_synthetic_children() { + let temp = tempfile::tempdir().unwrap(); + let mut sources = CatalogSources::default(); + sources.node_key = Some(DecisionKey::load_or_create(temp.path()).unwrap()); + sources.skills.push(SkillMetadata { + name: "prx_skill".into(), + description: "Skill".into(), + location: temp.path().join("SKILL.md"), + frontmatter_sha: [1; 32], + }); + sources.nodes.push(NodeSource { + id: "prx_node".into(), + availability: CapabilityAvailability::configured("configured"), + binding_digest: [2; 32], + }); + sources.mcp.push(McpCapabilitySpec { + server: "prx_server".into(), + tool: "read".into(), + state_digest: [3; 32], + spec: ToolSpec { + name: "mcp__prx_server__read".into(), + description: "MCP".into(), + parameters: json!({"type":"object","properties":{}}), + }, + }); + let mut surface = SurfacePolicy::default(); + surface + .excluded_names + .extend(["skill_read", "nodes", "mcp_call"].map(str::to_string)); + let catalog = CapabilityCatalog::build(&[], &sources, &surface).unwrap(); + assert!(catalog.view(&CatalogScope::default()).entries().is_empty()); + for entry in &catalog.entries { + let reference = CapabilityRef { + id: entry.id.clone(), + fingerprint: entry.fingerprint, + generation: *catalog.generation(), + }; + assert!(matches!( + catalog.resolve(&[reference]), + Err(StaleCapability::Unavailable) + )); + } + } + + #[test] + fn changed_schema_invalidates_pinned_reference() { + let original = + CapabilityCatalog::build(®istry(), &CatalogSources::default(), &SurfacePolicy::default()).unwrap(); + let entry = original + .view(&CatalogScope::default()) + .entries() + .first() + .copied() + .unwrap(); + let reference = CapabilityRef { + id: entry.id.clone(), + fingerprint: entry.fingerprint, + generation: *original.generation(), + }; + let changed: Vec> = vec![Box::new(ProbeTool { + name: "prx_search", + description: "changed schema description", + })]; + let changed = + CapabilityCatalog::build(&changed, &CatalogSources::default(), &SurfacePolicy::default()).unwrap(); + assert!(matches!(changed.resolve(&[reference]), Err(StaleCapability::Stale))); + } + + #[test] + fn unchanged_mcp_schema_with_changed_destination_invalidates_generation() { + let mut sources = CatalogSources::default(); + sources.mcp.push(McpCapabilitySpec { + server: "prx_server".into(), + tool: "read".into(), + state_digest: [1; 32], + spec: ToolSpec { + name: "mcp__prx_server__read".into(), + description: "Read remote data".into(), + parameters: json!({"type":"object","properties":{}}), + }, + }); + let first = CapabilityCatalog::build(&[], &sources, &SurfacePolicy::default()).unwrap(); + let entry = *first.view(&CatalogScope::default()).entries().first().unwrap(); + let reference = CapabilityRef { + id: entry.id.clone(), + fingerprint: entry.fingerprint, + generation: *first.generation(), + }; + sources.mcp.first_mut().unwrap().state_digest = [2; 32]; + let changed = CapabilityCatalog::build(&[], &sources, &SurfacePolicy::default()).unwrap(); + assert_ne!(first.generation(), changed.generation()); + assert!(matches!(changed.resolve(&[reference]), Err(StaleCapability::Stale))); + } + + #[test] + fn node_uses_keyed_canonical_identity_and_requires_key() { + let mut sources = CatalogSources::default(); + sources.nodes.push(NodeSource { + id: "Box:1".into(), + availability: CapabilityAvailability::configured("configured"), + binding_digest: [3; 32], + }); + assert!(matches!( + CapabilityCatalog::build(&[], &sources, &SurfacePolicy::default()), + Err(CatalogError::Identity) + )); + let temp = tempfile::tempdir().unwrap(); + let key = DecisionKey::load_or_create(temp.path()).unwrap(); + let expected = CapabilityId::remote_node(&key, "Box:1").unwrap(); + sources.node_key = Some(key); + let catalog = CapabilityCatalog::build(&[], &sources, &SurfacePolicy::default()).unwrap(); + let entry = catalog.entries.first().unwrap(); + assert_eq!(entry.id, expected); + assert_ne!(entry.public_name, "Box:1"); + } + + #[test] + fn surface_policy_changes_invalidate_refs() { + let tools = registry(); + let first = CapabilityCatalog::build(&tools, &CatalogSources::default(), &SurfacePolicy::default()).unwrap(); + let entry = *first.view(&CatalogScope::default()).entries().first().unwrap(); + let reference = CapabilityRef { + id: entry.id.clone(), + fingerprint: entry.fingerprint, + generation: *first.generation(), + }; + let mut changed_surface = SurfacePolicy::default(); + changed_surface.channel_allowed = true; + let changed = CapabilityCatalog::build(&tools, &CatalogSources::default(), &changed_surface).unwrap(); + assert!(matches!(changed.resolve(&[reference]), Err(StaleCapability::Stale))); + } + + #[test] + fn high_risk_root_actions_are_never_local_write() { + for name in ["nodes", "mcp_call", "skill_execute", "sessions_spawn", "delegate"] { + let tools: Vec> = vec![Box::new(ProbeTool { + name, + description: "Act", + })]; + let catalog = + CapabilityCatalog::build(&tools, &CatalogSources::default(), &SurfacePolicy::default()).unwrap(); + let entry = catalog.entries.first().unwrap(); + assert!(entry.effect >= SideEffectClass::ProcessExec, "{name}"); + assert!(matches!(entry.approval, ApprovalRequirement::Required { .. }), "{name}"); + assert!(entry.op_ids.is_empty(), "{name} has call-scoped operations"); + } + } + + struct DynamicAliasTool(Arc); + + #[async_trait] + impl Tool for DynamicAliasTool { + fn name(&self) -> &str { + "mcp_call" + } + fn description(&self) -> &str { + "Dynamic tool" + } + fn parameters_schema(&self) -> Value { + json!({"type":"object","properties":{}}) + } + fn specs(&self) -> Vec { + vec![self.spec()] + } + fn catalog_specs(&self) -> Vec { + let mut specs = self.specs(); + if self.0.load(Ordering::SeqCst) != 0 { + specs.push(ToolSpec { + name: "prx_collision".into(), + description: "new alias".into(), + parameters: self.parameters_schema(), + }); + } + specs + } + fn spec_for_name(&self, name: &str) -> Option { + self.catalog_specs().into_iter().find(|spec| spec.name == name) + } + fn supports_name(&self, name: &str) -> bool { + self.spec_for_name(name).is_some() + } + async fn execute(&self, _args: Value) -> anyhow::Result { + Ok(ToolResult { + success: true, + output: String::new(), + error: None, + }) + } + } + + #[test] + fn late_alias_collision_does_not_take_native_startup_owner_and_fails_parity() { + let state = Arc::new(AtomicUsize::new(0)); + let registry: Vec> = vec![ + Box::new(DynamicAliasTool(Arc::clone(&state))), + Box::new(ProbeTool { + name: "prx_collision", + description: "native owner", + }), + ]; + let catalog = + CapabilityCatalog::build(®istry, &CatalogSources::default(), &SurfacePolicy::default()).unwrap(); + let service = + ToolExecutionService::with_security_policy(registry, Arc::new(crate::security::SecurityPolicy::default())); + assert_eq!( + service.current_descriptor("prx_collision").unwrap().backend_name, + "prx_collision" + ); + assert!(catalog.check_parity(&service).is_ok()); + state.store(1, Ordering::SeqCst); + assert_eq!( + service.current_descriptor("prx_collision").unwrap().backend_name, + "prx_collision" + ); + assert!(catalog.check_parity(&service).is_err()); + } + + struct MutableBindingTool(Arc, [u8; 32]); + + #[async_trait] + impl Tool for MutableBindingTool { + fn name(&self) -> &str { + "skill_read" + } + fn description(&self) -> &str { + "Read a selected skill" + } + fn parameters_schema(&self) -> Value { + json!({"type":"object","properties":{"name":{"type":"string"}},"required":["name"]}) + } + fn catalog_binding_snapshot(&self) -> BTreeMap { + if self.0.load(Ordering::SeqCst) == 0 { + BTreeMap::from([("prx_skill".into(), self.1)]) + } else { + BTreeMap::new() + } + } + async fn execute(&self, _args: Value) -> anyhow::Result { + Ok(ToolResult { + success: true, + output: String::new(), + error: None, + }) + } + } + + #[test] + fn synthetic_skill_parity_fails_when_exact_target_disappears() { + let temp = tempfile::tempdir().unwrap(); + let skill = SkillMetadata { + name: "prx_skill".into(), + description: "Read it".into(), + location: temp.path().join("SKILL.md"), + frontmatter_sha: [4; 32], + }; + let digest = crate::skills::catalog_skill_binding_digest(&skill); + let mut sources = CatalogSources::default(); + sources.skills.push(skill); + let state = Arc::new(AtomicUsize::new(0)); + let registry: Vec> = vec![Box::new(MutableBindingTool(Arc::clone(&state), digest))]; + let catalog = CapabilityCatalog::build(®istry, &sources, &SurfacePolicy::default()).unwrap(); + let service = + ToolExecutionService::with_security_policy(registry, Arc::new(crate::security::SecurityPolicy::default())); + assert!(catalog.check_parity(&service).is_ok()); + state.store(1, Ordering::SeqCst); + assert!(catalog.check_parity(&service).is_err()); + } + + #[test] + fn instruction_read_wire_alias_collision_is_refused_instead_of_merging_targets() { + let temp = tempfile::tempdir().unwrap(); + let skill = SkillMetadata { + name: "Deploy helper".into(), + description: "Read one skill".into(), + location: temp.path().join("first/SKILL.md"), + frontmatter_sha: [4; 32], + }; + let mut colliding = skill.clone(); + colliding.name = crate::tools::skills::catalog_skill_read_name(&skill.name); + colliding.location = temp.path().join("second/SKILL.md"); + let sources = CatalogSources { + skills: vec![skill, colliding], + ..Default::default() + }; + assert!(matches!( + CapabilityCatalog::build(&[], &sources, &SurfacePolicy::default()), + Err(CatalogError::Duplicate) + )); + } + + #[test] + fn native_identity_and_instruction_alias_survive_the_bound_process_snapshot() { + let skill = SkillMetadata { + name: "Deploy helper".into(), + description: "Read one skill".into(), + location: std::path::PathBuf::from("/prx-workspace/skills/deploy/SKILL.md"), + frontmatter_sha: [4; 32], + }; + let alias = crate::tools::skills::catalog_skill_read_name(&skill.name); + let sources = CatalogSources { + skills: vec![skill.clone()], + ..Default::default() + }; + let workspace = tempfile::tempdir().unwrap(); + let registry: Vec> = vec![ + Box::new(crate::tools::shell::ShellTool::new( + Arc::new(crate::runtime::NativeRuntime::new()), + workspace.path().to_path_buf(), + )), + Box::new(DocumentCategoryProbe("document_ingest")), + Box::new(DocumentCategoryProbe("document_sync")), + ]; + let catalog = CapabilityCatalog::build(®istry, &sources, &SurfacePolicy::default()).unwrap(); + let key = crate::security::runtime_key::test_support::ephemeral_key(); + let snapshot = catalog.bind_process(&key).unwrap(); + let restored = CapabilityCatalog::restore_process(&snapshot, &key, *catalog.generation()).unwrap(); + for (name, family) in [ + ("shell", CapabilityTarget::Shell), + ("document_ingest", CapabilityTarget::Document), + ("document_sync", CapabilityTarget::Document), + ] { + let entry = restored.entry_for_public_name(name).unwrap(); + let parent = catalog.entry_for_public_name(name).unwrap(); + assert_eq!(entry.family, family); + assert_eq!(entry.id.as_str(), format!("filesystem:native:{name}")); + assert_eq!(entry.id, parent.id); + assert_eq!(entry.fingerprint, parent.fingerprint); + assert_eq!(entry.generation, parent.generation); + } + assert!( + CapabilityCatalog::restore_process( + &snapshot, + &crate::security::runtime_key::test_support::ephemeral_key(), + *catalog.generation() + ) + .is_err(), + "identity compatibility cannot bypass catalog authentication" + ); + let entry = restored.entry_for_public_name(&alias).unwrap(); + assert_eq!(entry.skill_metadata.as_ref().unwrap().name, skill.name); + assert_eq!( + entry.binding_digest, + Some(crate::skills::catalog_skill_binding_digest(&skill)) + ); + assert_eq!( + entry.schema.pointer("/properties/name/const"), + Some(&json!("Deploy helper")) + ); + assert!( + matches!(&entry.target, ExecutionTarget::Skill { name, root } if name=="Deploy helper" && root=="skill_read") + ); + } + + struct CountingBindingTool { + calls: Arc, + bindings: BTreeMap, + } + + #[async_trait] + impl Tool for CountingBindingTool { + fn name(&self) -> &str { + "skill_read" + } + fn description(&self) -> &str { + "Read selected skill" + } + fn parameters_schema(&self) -> Value { + json!({"type":"object","properties":{"name":{"type":"string"}},"required":["name"]}) + } + fn catalog_binding_snapshot(&self) -> BTreeMap { + self.calls.fetch_add(1, Ordering::SeqCst); + self.bindings.clone() + } + async fn execute(&self, _args: Value) -> anyhow::Result { + Ok(ToolResult { + success: true, + output: String::new(), + error: None, + }) + } + } + + #[test] + fn parity_reads_one_binding_snapshot_for_many_skills() { + let temp = tempfile::tempdir().unwrap(); + let mut sources = CatalogSources::default(); + let mut bindings = BTreeMap::new(); + for index in 0..32 { + let skill = SkillMetadata { + name: format!("prx_skill_{index}"), + description: "Skill".into(), + location: temp.path().join(format!("skill_{index}/SKILL.md")), + frontmatter_sha: [index; 32], + }; + bindings.insert(skill.name.clone(), crate::skills::catalog_skill_binding_digest(&skill)); + sources.skills.push(skill); + } + let calls = Arc::new(AtomicUsize::new(0)); + let registry: Vec> = vec![Box::new(CountingBindingTool { + calls: Arc::clone(&calls), + bindings, + })]; + let catalog = CapabilityCatalog::build(®istry, &sources, &SurfacePolicy::default()).unwrap(); + let service = + ToolExecutionService::with_security_policy(registry, Arc::new(crate::security::SecurityPolicy::default())); + assert!(catalog.check_parity(&service).is_ok()); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + struct MutableMcpDestinationTool(Arc); + + #[async_trait] + impl Tool for MutableMcpDestinationTool { + fn name(&self) -> &str { + "mcp_call" + } + fn description(&self) -> &str { + "MCP root" + } + fn parameters_schema(&self) -> Value { + json!({"type":"object","properties":{}}) + } + fn catalog_specs(&self) -> Vec { + vec![ + self.spec(), + ToolSpec { + name: "mcp__prx_server__read".into(), + description: "Read remote data".into(), + parameters: self.parameters_schema(), + }, + ] + } + fn catalog_binding_snapshot(&self) -> BTreeMap { + let byte = u8::try_from(self.0.load(Ordering::SeqCst)).unwrap_or_default() + 1; + BTreeMap::from([("mcp__prx_server__read".into(), [byte; 32])]) + } + fn supports_name(&self, name: &str) -> bool { + name == self.name() || name == "mcp__prx_server__read" + } + fn spec_for_name(&self, name: &str) -> Option { + self.catalog_specs().into_iter().find(|spec| spec.name == name) + } + async fn execute(&self, _args: Value) -> anyhow::Result { + Ok(ToolResult { + success: true, + output: String::new(), + error: None, + }) + } + } + + #[test] + fn same_schema_mcp_destination_change_fails_live_parity() { + let state = Arc::new(AtomicUsize::new(0)); + let mut sources = CatalogSources::default(); + sources.mcp.push(McpCapabilitySpec { + server: "prx_server".into(), + tool: "read".into(), + state_digest: [1; 32], + spec: ToolSpec { + name: "mcp__prx_server__read".into(), + description: "Read remote data".into(), + parameters: json!({"type":"object","properties":{}}), + }, + }); + let registry: Vec> = vec![Box::new(MutableMcpDestinationTool(Arc::clone(&state)))]; + let catalog = CapabilityCatalog::build(®istry, &sources, &SurfacePolicy::default()).unwrap(); + let service = + ToolExecutionService::with_security_policy(registry, Arc::new(crate::security::SecurityPolicy::default())); + assert!(catalog.check_parity(&service).is_ok()); + state.store(1, Ordering::SeqCst); + assert!(catalog.check_parity(&service).is_err()); + sources.mcp.first_mut().unwrap().state_digest = [2; 32]; + let rebuilt = CapabilityCatalog::build( + &[Box::new(MutableMcpDestinationTool(state))], + &sources, + &SurfacePolicy::default(), + ) + .unwrap(); + assert_ne!(catalog.generation(), rebuilt.generation()); + } + + #[test] + fn child_parity_rejects_same_schema_mcp_destination_change() { + use crate::tools::capability::child::{ + AuthorityEnvelope, CapabilityConstraints, ChildCapabilityManifest, VerifiedChildScope, + }; + + let state = Arc::new(AtomicUsize::new(0)); + let mut sources = CatalogSources::default(); + sources.mcp.push(McpCapabilitySpec { + server: "prx_server".into(), + tool: "read".into(), + state_digest: [1; 32], + spec: ToolSpec { + name: "mcp__prx_server__read".into(), + description: "Read remote data".into(), + parameters: json!({"type":"object","properties":{}}), + }, + }); + let registry: Vec> = vec![Box::new(MutableMcpDestinationTool(Arc::clone(&state)))]; + let catalog = CapabilityCatalog::build(®istry, &sources, &SurfacePolicy::default()).unwrap(); + let service = + ToolExecutionService::with_security_policy(registry, Arc::new(crate::security::SecurityPolicy::default())); + let child_reference = catalog + .entries + .iter() + .find(|entry| entry.public_name == "mcp__prx_server__read") + .map(|entry| CapabilityRef { + id: entry.id.clone(), + fingerprint: entry.fingerprint, + generation: entry.generation, + }) + .expect("MCP alias reference"); + let allowed: BTreeSet<_> = catalog + .entries + .iter() + .map(|entry| CapabilityRef { + id: entry.id.clone(), + fingerprint: entry.fingerprint, + generation: entry.generation, + }) + .collect(); + let workspace = tempfile::tempdir().unwrap(); + let key = DecisionKey::load_or_create(workspace.path()).unwrap(); + let parent = CapabilityConstraints { + parent_authority_id: crate::security::decision_id::DecisionId::parse( + "0192f0c4-0000-7000-8000-000000000007", + ) + .expect("test: id") + .into(), + allowed, + authority: AuthorityEnvelope { + owner: "prx_user".into(), + workspace: "prx_workspace".into(), + level: crate::security::AutonomyLevel::Supervised, + max_cost_cents: 100, + remaining_depth: 2, + delegation: None, + }, + catalog_generation: *catalog.generation(), + key, + }; + let manifest = ChildCapabilityManifest::derive_strict_subset(&parent, &[child_reference]).unwrap(); + let scope = VerifiedChildScope::new(manifest, &parent).unwrap(); + + assert!(catalog.check_child_parity(&service, &scope).is_ok()); + state.store(1, Ordering::SeqCst); + assert!(catalog.check_child_parity(&service, &scope).is_err()); + } + + struct MutableSchemaTool(Arc); + + #[async_trait] + impl Tool for MutableSchemaTool { + fn name(&self) -> &str { + "prx_mutable" + } + + fn description(&self) -> &str { + "Mutable schema test tool" + } + + fn parameters_schema(&self) -> Value { + json!({"type":"object","properties":{"version":{"const":self.0.load(Ordering::SeqCst)}}}) + } + + async fn execute(&self, _args: Value) -> anyhow::Result { + Ok(ToolResult { + success: true, + output: String::new(), + error: None, + }) + } + } + + #[test] + fn execution_descriptor_rechecks_the_current_schema_after_startup() { + let version = Arc::new(AtomicUsize::new(1)); + let service = ToolExecutionService::with_security_policy( + vec![Box::new(MutableSchemaTool(Arc::clone(&version)))], + Arc::new(crate::security::SecurityPolicy::default()), + ); + let initial = service.current_descriptor("prx_mutable").unwrap(); + assert_eq!(initial.parameters.pointer("/properties/version/const"), Some(&json!(1))); + version.store(2, Ordering::SeqCst); + let current = service.current_descriptor("prx_mutable").unwrap(); + assert_eq!(current.parameters.pointer("/properties/version/const"), Some(&json!(2))); + } + + #[test] + fn excluded_executable_schema_change_still_fails_reverse_parity() { + let version = Arc::new(AtomicUsize::new(1)); + let registry: Vec> = vec![Box::new(MutableSchemaTool(Arc::clone(&version)))]; + let mut surface = SurfacePolicy::default(); + surface.excluded_names.insert("prx_mutable".into()); + let catalog = CapabilityCatalog::build(®istry, &CatalogSources::default(), &surface).unwrap(); + let service = + ToolExecutionService::with_security_policy(registry, Arc::new(crate::security::SecurityPolicy::default())); + assert!(catalog.check_parity(&service).is_ok()); + version.store(2, Ordering::SeqCst); + assert!(catalog.check_parity(&service).is_err()); + } + + #[test] + fn scoped_view_construction_allocates_nothing_for_any_inventory_size() { + for size in [0, 1, 64, 256] { + let sources = CatalogSources { + mcp: (0..size) + .map(|index| McpCapabilitySpec { + server: "prx_server".into(), + tool: format!("read_{index}"), + state_digest: [0; 32], + spec: ToolSpec { + name: format!("mcp__prx_server__read_{index}"), + description: "PRX inventory fixture".into(), + parameters: json!({"type":"object","properties":{}}), + }, + }) + .collect(), + ..CatalogSources::default() + }; + let surface = SurfacePolicy { + allowed_tools: None, + channel_allowed: true, + ..SurfacePolicy::default() + }; + let catalog = CapabilityCatalog::build(&[], &sources, &surface).unwrap(); + for families in [BTreeSet::new(), BTreeSet::from([CapabilityTarget::Mcp])] { + let scope = CatalogScope { + families, + channel: true, + }; + let (view, allocations) = + crate::decision_engine::prediction::builtin::allocation_counter::count(|| catalog.view(&scope)); + assert_eq!(allocations, 0, "view allocations at inventory size {size}"); + assert_eq!(view.entries().len(), size); + } + } + } + + #[test] + fn borrowed_visibility_matches_cached_entries_and_all_search_paths() { + let sources = CatalogSources { + mcp: vec![McpCapabilitySpec { + server: "prx_server".into(), + tool: "read".into(), + state_digest: [0; 32], + spec: ToolSpec { + name: "mcp__prx_server__read".into(), + description: "Search local evidence".into(), + parameters: json!({"type":"object","properties":{}}), + }, + }], + ..CatalogSources::default() + }; + let surface = SurfacePolicy { + allowed_tools: None, + channel_allowed: true, + excluded_names: BTreeSet::from(["prx_search".into()]), + ..SurfacePolicy::default() + }; + let mut catalog = CapabilityCatalog::build(®istry(), &sources, &surface).unwrap(); + catalog + .entries + .iter_mut() + .find(|entry| entry.public_name == "prx_read") + .unwrap() + .channel_eligible = false; + let scopes = std::iter::once(BTreeSet::new()) + .chain(CapabilityTarget::ALL.map(|family| BTreeSet::from([family]))) + .chain(std::iter::once(BTreeSet::from([ + CapabilityTarget::NativeTool, + CapabilityTarget::Mcp, + ]))); + for families in scopes { + for channel in [false, true] { + let scope = CatalogScope { + families: families.clone(), + channel, + }; + let expected: Vec<_> = catalog + .entries + .iter() + .filter(|entry| { + (families.is_empty() || families.contains(&entry.family)) + && (!channel || entry.channel_eligible) + && !matches!(entry.exposure, Exposure::Unavailable { .. }) + }) + .map(|entry| &entry.id) + .collect(); + for cache_first in [false, true] { + let view = catalog.view(&scope); + assert_eq!(view.iter_entries().map(|entry| &entry.id).collect::>(), expected); + assert!( + view.entries.get().is_none(), + "borrowing iteration must not initialize compatibility cache" + ); + if cache_first { + assert_eq!( + view.entries().iter().map(|entry| &entry.id).collect::>(), + expected + ); + } + for entry in &catalog.entries { + let visible = expected.contains(&&entry.id); + assert_eq!(view.contains(&entry.id), visible); + assert!( + std::ptr::eq(view.entry_any(&entry.id).unwrap(), entry), + "unfiltered gate lookup" + ); + for query in std::iter::once(entry.public_name.as_str()) + .chain(std::iter::once(entry.id.as_str())) + .chain(entry.aliases.iter().map(String::as_str)) + { + for query_families in [Vec::new(), vec![entry.family], vec![CapabilityTarget::None]] { + let hits = CatalogSearch::find(&view, query, &query_families, 16); + let allowed = + visible && (query_families.is_empty() || query_families.contains(&entry.family)); + assert_eq!( + hits.iter().any(|hit| hit.entry.id == entry.id), + allowed, + "exact search visibility for {query}" + ); + assert!(hits.iter().all(|hit| expected.contains(&&hit.entry.id))); + } + } + } + let ranked = CatalogSearch::find(&view, "local evidence", &[], 16); + assert_eq!( + ranked.iter().map(|hit| &hit.entry.id).collect::>(), + expected.iter().copied().collect() + ); + assert_eq!( + view.entries.get().is_some(), + cache_first, + "search must not initialize compatibility cache" + ); + assert_eq!( + view.entries().iter().map(|entry| &entry.id).collect::>(), + expected + ); + assert_eq!(view.iter_entries().map(|entry| &entry.id).collect::>(), expected); + } + } + } + } + + #[test] + fn thousands_of_mcp_aliases_stay_bounded_and_hidden_metadata_never_matches() { + let mut sources = CatalogSources::default(); + sources.mcp = (0..4096) + .map(|index| McpCapabilitySpec { + server: "prx_server".to_string(), + tool: format!("tool_{index}"), + state_digest: [0; 32], + spec: ToolSpec { + name: format!("mcp__prx_server__tool_{index}"), + description: if index == 4095 { + "\u{200b}last tool\nsecret=PRX-FAKE-SENTINEL".to_string() + } else { + "searchable remote tool".to_string() + }, + parameters: json!({"type":"object","properties":{}}), + }, + }) + .collect(); + let mut surface = SurfacePolicy::default(); + surface.excluded_names.insert("mcp__prx_server__tool_4095".to_string()); + let catalog = CapabilityCatalog::build(&[], &sources, &surface).unwrap(); + let view = catalog.view(&CatalogScope::default()); + assert_eq!(view.entries().len(), 4095); + let hits = CatalogSearch::find(&view, "searchable remote tool", &[], 5); + assert_eq!(hits.len(), 5); + assert!( + hits.iter() + .all(|hit| hit.entry.public_name != "mcp__prx_server__tool_4095") + ); + assert!( + CatalogSearch::find(&view, "tool_4095", &[], 5) + .iter() + .all(|hit| hit.entry.public_name != "mcp__prx_server__tool_4095") + ); + assert!( + catalog + .entries + .iter() + .all(|entry| entry.summary.len() <= 160 * 4 && !entry.summary.contains('\n')) + ); + } +} diff --git a/src/tools/delegate.rs b/src/tools/delegate.rs index d13c17ee6..6fe95b674 100644 --- a/src/tools/delegate.rs +++ b/src/tools/delegate.rs @@ -1868,2141 +1868,7 @@ mod task_boundary_tests { #[allow(clippy::indexing_slicing)] #[cfg(test)] -pub(crate) mod tests { - use super::*; - use crate::memory::{MemoryPrincipal, SqliteMemory}; - use crate::providers::{ChatRequest, ChatResponse, ToolCall}; - use crate::security::{AutonomyLevel, SecurityPolicy}; - use std::sync::atomic::{AtomicUsize, Ordering}; - - /// Workspace for the delegate tests, unique per process run. - /// - /// The tool-execution ledger lives inside the workspace and is durable on - /// purpose, so the default `.` workspace would both write into the source - /// tree and let one run's records replay into the next. - fn test_workspace() -> std::path::PathBuf { - static WORKSPACE: std::sync::OnceLock = std::sync::OnceLock::new(); - WORKSPACE - .get_or_init(|| { - std::env::temp_dir().join(format!( - "prx-delegate-tests-{}-{}", - std::process::id(), - uuid::Uuid::now_v7() - )) - }) - .clone() - } - - fn test_security() -> Arc { - Arc::new(SecurityPolicy { - workspace_dir: test_workspace(), - ..SecurityPolicy::default() - }) - } - - fn sample_agents() -> HashMap { - let mut agents = HashMap::new(); - agents.insert( - "researcher".to_string(), - DelegateAgentConfig { - approval_wait_secs: 600, - limits: crate::config::AgentLimits::default(), - provider: "ollama".to_string(), - model: "llama3".to_string(), - system_prompt: Some("You are a research assistant.".to_string()), - api_key: None, - credential_ref: None, - temperature: Some(0.3), - max_depth: 3, - agentic: false, - allowed_tools: Vec::new(), - identity_dir: None, - memory_scope: None, - spawn_enabled: None, - enabled: true, - autonomy: None, - }, - ); - agents.insert( - "coder".to_string(), - DelegateAgentConfig { - approval_wait_secs: 600, - limits: crate::config::AgentLimits::default(), - provider: "openrouter".to_string(), - model: "anthropic/claude-sonnet-4-20250514".to_string(), - system_prompt: None, - api_key: Some("delegate-test-credential".to_string()), - credential_ref: None, - temperature: None, - max_depth: 2, - agentic: false, - allowed_tools: Vec::new(), - identity_dir: None, - memory_scope: None, - spawn_enabled: None, - enabled: true, - autonomy: None, - }, - ); - agents - } - - /// Counts its own executions, so a test can tell "the delegated sub-agent ran - /// the tool" from "the tool was refused and the refusal was handed back as - /// tool output". - #[derive(Default)] - struct EchoTool { - executions: Arc, - } - - #[async_trait] - impl Tool for EchoTool { - fn name(&self) -> &str { - "echo_tool" - } - - fn description(&self) -> &str { - "Echoes the `value` argument." - } - - fn parameters_schema(&self) -> serde_json::Value { - serde_json::json!({ - "type": "object", - "properties": { - "value": {"type": "string"} - }, - "required": ["value"] - }) - } - - async fn execute(&self, args: serde_json::Value) -> anyhow::Result { - self.executions.fetch_add(1, Ordering::SeqCst); - let value = args - .get("value") - .and_then(serde_json::Value::as_str) - .unwrap_or_default() - .to_string(); - Ok(ToolResult { - success: true, - output: format!("echo:{value}"), - error: None, - }) - } - } - - struct DynamicAliasTool; - - #[async_trait] - impl Tool for DynamicAliasTool { - fn name(&self) -> &str { - "dynamic_root" - } - - fn description(&self) -> &str { - "Dynamic alias fixture" - } - - fn parameters_schema(&self) -> serde_json::Value { - json!({"type": "object", "properties": {}}) - } - - fn specs(&self) -> Vec { - vec![super::super::traits::ToolSpec { - name: "dynamic_alias".to_string(), - description: self.description().to_string(), - parameters: self.parameters_schema(), - }] - } - - fn supports_name(&self, name: &str) -> bool { - matches!(name, "dynamic_root" | "dynamic_alias") - } - - async fn execute(&self, args: serde_json::Value) -> anyhow::Result { - self.execute_named("dynamic_root", args).await - } - - async fn execute_named(&self, name: &str, _args: serde_json::Value) -> anyhow::Result { - Ok(ToolResult { - success: self.supports_name(name), - output: name.to_string(), - error: None, - }) - } - } - - #[tokio::test] - async fn delegated_tool_reference_preserves_dynamic_alias_contract() { - let delegated = ToolArcRef::new(Arc::new(DynamicAliasTool)); - assert!(delegated.supports_name("dynamic_alias")); - assert_eq!(delegated.specs()[0].name, "dynamic_alias"); - let result = delegated.execute_named("dynamic_alias", json!({})).await.unwrap(); - assert!(result.success); - assert_eq!(result.output, "dynamic_alias"); - - let restricted = ToolArcRef::for_name(Arc::new(DynamicAliasTool), "dynamic_alias").unwrap(); - assert_eq!(restricted.name(), "dynamic_alias"); - assert_eq!(restricted.specs().len(), 1); - assert!(restricted.supports_name("dynamic_alias")); - assert!(!restricted.supports_name("dynamic_root")); - assert!(restricted.execute_named("dynamic_root", json!({})).await.is_err()); - } - - struct OneToolThenFinalProvider; - - #[async_trait] - impl Provider for OneToolThenFinalProvider { - async fn chat_with_system( - &self, - _system_prompt: Option<&str>, - _message: &str, - _model: &str, - _temperature: f64, - ) -> anyhow::Result { - Ok("unused".to_string()) - } - - async fn chat( - &self, - request: ChatRequest<'_>, - _model: &str, - _temperature: f64, - ) -> anyhow::Result { - let has_tool_message = request.messages.iter().any(|m| m.role == "tool"); - if has_tool_message { - Ok(ChatResponse { - text: Some("done".to_string()), - tool_calls: Vec::new(), - reasoning_content: None, - }) - } else { - Ok(ChatResponse { - text: None, - tool_calls: vec![ToolCall { - id: "call_1".to_string(), - name: "echo_tool".to_string(), - arguments: "{\"value\":\"ping\"}".to_string(), - }], - reasoning_content: None, - }) - } - } - } - - fn agentic_config(allowed_tools: Vec) -> DelegateAgentConfig { - DelegateAgentConfig { - approval_wait_secs: 600, - limits: crate::config::AgentLimits::default(), - provider: "openrouter".to_string(), - identity_dir: None, - memory_scope: None, - spawn_enabled: None, - enabled: true, - autonomy: None, - model: "model-test".to_string(), - system_prompt: Some("You are agentic.".to_string()), - api_key: Some("delegate-test-credential".to_string()), - credential_ref: None, - temperature: Some(0.2), - max_depth: 3, - agentic: true, - allowed_tools, - } - } - - fn router_model(provider: &str, model_id: &str, max_context: usize) -> crate::config::RouterModelConfig { - crate::config::RouterModelConfig { - provider: provider.to_string(), - model_id: model_id.to_string(), - cost_per_million_tokens: 1.0, - max_context, - reserved_output_tokens: None, - latency_ms: 1_000, - categories: vec!["code".to_string()], - elo_rating: 1_000.0, - } - } - - #[test] - fn name_and_schema() { - let tool = DelegateTool::new(sample_agents(), test_security()); - assert_eq!(tool.name(), "delegate"); - let schema = tool.parameters_schema(); - assert!(schema["properties"]["agent"].is_object()); - assert!(schema["properties"]["prompt"].is_object()); - assert!(schema["properties"]["context"].is_object()); - let required = schema["required"].as_array().unwrap(); - assert!(required.contains(&json!("agent"))); - assert!(required.contains(&json!("prompt"))); - assert_eq!(schema["additionalProperties"], json!(false)); - assert_eq!(schema["properties"]["agent"]["minLength"], json!(1)); - assert_eq!(schema["properties"]["prompt"]["minLength"], json!(1)); - } - - #[test] - fn description_not_empty() { - let tool = DelegateTool::new(sample_agents(), test_security()); - assert!(!tool.description().is_empty(), "expected a non-empty value"); - } - - #[test] - fn schema_lists_agent_names() { - let tool = DelegateTool::new(sample_agents(), test_security()); - let schema = tool.parameters_schema(); - let desc = schema["properties"]["agent"]["description"].as_str().unwrap(); - assert!(desc.contains("researcher") || desc.contains("coder")); - } - - #[tokio::test] - async fn missing_agent_param() { - let tool = DelegateTool::new(sample_agents(), test_security()); - let result = tool.execute(json!({"prompt": "test"})).await; - assert!(result.is_err()); - } - - #[tokio::test] - async fn missing_prompt_param() { - let tool = DelegateTool::new(sample_agents(), test_security()); - let result = tool.execute(json!({"agent": "researcher"})).await; - assert!(result.is_err()); - } - - async fn dispatch_configured_delegate(mut tool: DelegateTool, arguments: serde_json::Value) -> ToolResult { - let workspace = tempfile::tempdir().unwrap(); - let mut config = crate::config::Config::default(); - config.workspace_dir = workspace.path().to_owned(); - config.config_path = workspace.path().join("config.toml"); - config.autonomy.level = AutonomyLevel::Full; - config.agents = tool.agents.as_ref().clone(); - tool.security = Arc::new(SecurityPolicy::from_config(&config.autonomy, workspace.path())); - dispatch_admitted_delegate(config, tool, arguments).await - } - - #[tokio::test] - async fn unknown_agent_returns_error() { - let tool = DelegateTool::new(sample_agents(), test_security()); - let result = dispatch_configured_delegate(tool, json!({"agent":"nonexistent", "prompt":"test"})).await; - assert!(!result.success); - assert!(result.error.unwrap().contains("Unknown agent")); - } - - #[tokio::test] - async fn depth_limit_enforced() { - let tool = DelegateTool::with_depth(sample_agents(), test_security(), 3); - let result = dispatch_configured_delegate(tool, json!({"agent":"researcher", "prompt":"test"})).await; - assert!(!result.success); - assert!(result.error.unwrap().contains("depth limit")); - } - - #[tokio::test] - async fn depth_limit_per_agent() { - // coder has max_depth=2, so depth=2 should be blocked - let tool = DelegateTool::with_depth(sample_agents(), test_security(), 2); - let result = dispatch_configured_delegate(tool, json!({"agent":"coder", "prompt":"test"})).await; - assert!(!result.success); - assert!(result.error.unwrap().contains("depth limit")); - } - - #[test] - fn empty_agents_schema() { - let tool = DelegateTool::new(HashMap::new(), test_security()); - let schema = tool.parameters_schema(); - let desc = schema["properties"]["agent"]["description"].as_str().unwrap(); - assert!(desc.contains("none configured")); - } - - #[tokio::test] - async fn invalid_provider_returns_error() { - let mut agents = HashMap::new(); - agents.insert( - "broken".to_string(), - DelegateAgentConfig { - approval_wait_secs: 600, - limits: crate::config::AgentLimits::default(), - provider: "totally-invalid-provider".to_string(), - model: "model".to_string(), - system_prompt: None, - api_key: None, - credential_ref: None, - temperature: None, - max_depth: 3, - agentic: false, - allowed_tools: Vec::new(), - identity_dir: None, - memory_scope: None, - spawn_enabled: None, - enabled: true, - autonomy: None, - }, - ); - let tool = DelegateTool::new(agents, test_security()); - let result = dispatch_configured_delegate(tool, json!({"agent":"broken", "prompt":"test"})).await; - assert!(!result.success); - assert!(result.error.unwrap().contains("is not one PRX can construct")); - } - - #[tokio::test] - async fn blank_agent_rejected() { - let tool = DelegateTool::new(sample_agents(), test_security()); - let result = tool.execute(json!({"agent": " ", "prompt": "test"})).await.unwrap(); - assert!(!result.success); - assert!(result.error.unwrap().contains("must not be empty")); - } - - #[tokio::test] - async fn blank_prompt_rejected() { - let tool = DelegateTool::new(sample_agents(), test_security()); - let result = tool - .execute(json!({"agent": "researcher", "prompt": " \t "})) - .await - .unwrap(); - assert!(!result.success); - assert!(result.error.unwrap().contains("must not be empty")); - } - - #[tokio::test] - async fn whitespace_agent_name_trimmed_and_found() { - let tool = DelegateTool::new(single_agent("researcher", "mock", "test-model"), test_security()); - let result = dispatch_configured_delegate(tool, json!({"agent":" researcher ", "prompt":"test"})).await; - assert!(result.success, "trimmed agent must execute: {:?}", result.error); - assert!(result.output.contains("mock/test-model")); - } - - #[tokio::test] - async fn delegation_blocked_in_readonly_mode() { - let workspace = tempfile::tempdir().unwrap(); - let mut config = crate::config::Config::default(); - config.workspace_dir = workspace.path().to_owned(); - config.config_path = workspace.path().join("config.toml"); - config.autonomy.level = AutonomyLevel::ReadOnly; - config.agents = single_agent("researcher", "mock", "test-model"); - let readonly = Arc::new(SecurityPolicy::from_config(&config.autonomy, workspace.path())); - let tool = DelegateTool::new(config.agents.clone(), readonly); - let (result, executions, history) = - observe_delegate_dispatch(config, tool, json!({"agent":"researcher", "prompt":"test"}), None).await; - assert_eq!(executions, 0, "readonly execution must reject before entering delegate"); - assert!(result.is_none()); - assert!( - history.iter().any(|message| message.role == "user" - && message - .content - .starts_with(crate::agent::turn_contracts::TOOL_RESULTS_PREFIX) - && message - .content - .contains("tool 'delegate' is not permitted under the current execution policy")), - "the parent must receive the actual policy denial: {history:?}" - ); - } - - #[tokio::test] - async fn delegate_context_is_prepended_to_prompt() { - let (result, requests) = run_configured_delegate_fixture( - vec!["dynamic_alias".to_owned()], - vec![Arc::new(DynamicAliasTool)], - "dynamic_alias", - json!({}), - None, - false, - Some("some context data"), - ) - .await; - assert!(result.success, "{:?}", result.error); - assert_eq!(requests.len(), 2, "child must execute the tool and finish"); - let messages = requests[0]["messages"].as_array().unwrap(); - let user_message = messages - .iter() - .find(|message| message["role"] == "user") - .expect("the provider must receive the delegated user input"); - assert_eq!( - user_message["content"], - "[Context]\nsome context data\n\n[Task]\ndynamic_alias" - ); - } - - #[tokio::test] - async fn delegate_records_request_and_result_message_events() { - let tmp = tempfile::TempDir::new().unwrap(); - let memory: Arc = Arc::new(SqliteMemory::new(tmp.path()).unwrap()); - let mut agents = HashMap::new(); - agents.insert( - "tester".to_string(), - DelegateAgentConfig { - approval_wait_secs: 600, - limits: crate::config::AgentLimits::default(), - provider: "mock".to_string(), - model: "test-model".to_string(), - system_prompt: None, - api_key: None, - credential_ref: None, - temperature: None, - max_depth: 3, - agentic: false, - allowed_tools: Vec::new(), - identity_dir: None, - memory_scope: None, - spawn_enabled: None, - enabled: true, - autonomy: None, - }, - ); - let mut config = crate::config::Config::default(); - config.workspace_dir = tmp.path().to_owned(); - config.config_path = tmp.path().join("config.toml"); - config.autonomy.level = AutonomyLevel::Full; - config.agents = agents.clone(); - let security = Arc::new(SecurityPolicy::from_config(&config.autonomy, tmp.path())); - let tool = DelegateTool::new(agents, security).with_shared_memory(memory.clone()); - let channel = crate::channels::traits::ChannelMessage { - id: "prx-source-message".to_owned(), - sender: "prx_user".to_owned(), - reply_target: "prx_channel".to_owned(), - content: String::new(), - channel: "telegram".to_owned(), - timestamp: 0, - chat_kind: crate::channels::traits::ChatKind::Dm, - chat_title: None, - sender_display: None, - thread_ts: None, - mentioned_uuids: Vec::new(), - mentioned: false, - is_group_hint: false, - sender_is_bot: false, - }; - let result = dispatch_admitted_delegate_from( - config, - tool, - json!({"agent":"tester", "prompt":"delegate through fabric"}), - Some(channel), - ) - .await; - assert!(result.success); - - let events = memory - .list_message_events_since( - &MemoryPrincipal { - require_owner_match: false, - workspace_id: tmp.path().to_string_lossy().to_string(), - agent_id: Some("tester".to_string()), - persona_id: None, - session_key: None, - channel: Some("telegram".to_string()), - sender: Some("prx_user".to_string()), - owner_id: None, - legacy_session_key: None, - agent_partition: None, - }, - 0, - 100, - ) - .await - .unwrap(); - - let request_event = events - .iter() - .find(|event| event.role == "user" && event.source == "delegate") - .expect("delegate request event"); - let result_event = events - .iter() - .find(|event| event.role == "event" && event.content.contains("tester")) - .expect("delegate domain result event"); - assert_eq!(request_event.source, "delegate"); - assert_eq!(request_event.content, "delegate through fabric"); - assert_eq!(result_event.source, "delegate"); - assert_eq!(events.iter().filter(|event| event.role == "assistant").count(), 1); - assert_eq!( - events - .iter() - .filter(|event| event.event_type == "provider.final_outcome") - .count(), - 1 - ); - assert_eq!( - events - .iter() - .filter(|event| event.event_type == "turn.finalized") - .count(), - 1 - ); - - let parent_id = request_event - .causation_event_id - .as_deref() - .expect("delegate input must reference the actual parent source event"); - let parent_events = memory - .list_message_events_recent( - &MemoryPrincipal { - require_owner_match: false, - workspace_id: tmp.path().to_string_lossy().to_string(), - agent_id: None, - persona_id: None, - session_key: None, - channel: Some("telegram".to_owned()), - sender: Some("prx_user".to_owned()), - owner_id: None, - legacy_session_key: None, - agent_partition: None, - }, - 100, - ) - .await - .unwrap(); - let parent = parent_events - .iter() - .find(|event| event.event_id == parent_id) - .expect("the referenced source event must actually be durable"); - assert_eq!(parent.role, "user"); - assert_eq!(parent.content, "delegate delegate through fabric"); - assert_eq!(request_event.parent_run_id, parent.run_id); - assert_eq!(request_event.parent_session_key, parent.session_key); - - let task_events = memory - .list_memory_events_since( - &MemoryPrincipal { - require_owner_match: false, - workspace_id: tmp.path().to_string_lossy().to_string(), - agent_id: Some("tester".to_string()), - persona_id: None, - session_key: None, - channel: Some("telegram".to_string()), - sender: Some("prx_user".to_string()), - owner_id: None, - legacy_session_key: None, - agent_partition: None, - }, - 0, - 100, - ) - .await - .unwrap() - .into_iter() - .filter(|event| event.subject_table == "tasks") - .collect::>(); - let event_types = task_events - .iter() - .map(|event| event.event_type.as_str()) - .collect::>(); - assert!(event_types.contains(&"delegate.task.started")); - assert!(event_types.contains(&"delegate.task.completed")); - assert!(task_events.iter().all(|event| !event.subject_id.is_empty())); - assert!(task_events.iter().any(|event| { - event.payload_json.as_deref().is_some_and(|payload| { - serde_json::from_str::(payload) - .is_ok_and(|value| value["source_message_event_id"] == parent_id) - }) - })); - } - - #[test] - fn delegate_event_scope_is_derived_from_runtime_envelope() { - let scope = DelegateScope { - sender: "alice".to_string(), - channel: "telegram".to_string(), - chat_id: "chat-1".to_string(), - owner_id: Some("owner:/tmp/ws:telegram:alice".to_string()), - topic_id: Some("topic-a".to_string()), - task_id: Some("task-a".to_string()), - source_message_event_id: Some("msg-a".to_string()), - config_generation_id: Some(17), - config_source_revision: Some("revision-17".to_string()), - }; - let event_scope = delegate_event_scope("/tmp/ws", "run-delegate", "tester", Some(&scope)); - - assert_eq!(event_scope.source, "delegate"); - assert_eq!(event_scope.channel.as_deref(), Some("telegram")); - assert_eq!( - event_scope.session_key.as_deref(), - Some("delegate:telegram:chat-1:alice") - ); - assert_eq!(event_scope.run_id.as_deref(), Some("run-delegate")); - assert_eq!(event_scope.config_generation_id, Some(17)); - assert_eq!(event_scope.config_source_revision.as_deref(), Some("revision-17")); - assert_eq!(event_scope.agent_id.as_deref(), Some("tester")); - assert_eq!(event_scope.sender.as_deref(), Some("alice")); - assert_eq!(event_scope.recipient.as_deref(), Some("chat-1")); - assert_eq!(event_scope.owner_id.as_deref(), Some("owner:/tmp/ws:telegram:alice")); - assert_eq!( - event_scope.subject, - Some(crate::memory::MessageEventSubject::Task("run-delegate".into())) - ); - } - - /// Two delegates under one parent task write their own task identity, so a - /// sibling's live request and prior segment never reach the other child, - /// while the shared main-channel event stays visible to both. - #[tokio::test] - async fn delegates_under_one_parent_task_recall_only_their_own_task() { - use crate::agent::context_recall::{RECALL_CONTEXT_BUDGET, RecallScope, scoped_recall}; - use crate::memory::{MessageEventSource, MessageEventSubject, SqliteMemory}; - - let tmp = tempfile::TempDir::new().expect("test: temp dir"); - let ws = tmp.path().to_string_lossy().to_string(); - let memory: Arc = Arc::new(SqliteMemory::new(tmp.path()).expect("test: sqlite")); - let fabric = MemoryFabric::new(Arc::clone(&memory), ws.clone()); - let parent = DelegateScope { - sender: "alice".to_string(), - channel: "telegram".to_string(), - chat_id: "chat-1".to_string(), - owner_id: Some("owner-T".to_string()), - topic_id: None, - task_id: Some("task-T".to_string()), - source_message_event_id: None, - config_generation_id: Some(1), - config_source_revision: Some("rev-1".to_string()), - }; - let mut shared = delegate_event_scope(&ws, "run-main", "tester", Some(&parent)); - shared.source = MessageEventSource::Channel; - shared.subject = None; - fabric - .record_inbound_user_message(shared, "SHARED-MAIN-POSITIVE", None, None) - .await - .expect("test: shared record"); - - let mut lanes = Vec::new(); - for run in ["run-a", "run-b"] { - let scope = delegate_event_scope(&ws, run, "tester", Some(&parent)); - assert_eq!(scope.subject, Some(MessageEventSubject::Task(run.to_string()))); - assert_ne!(scope.subject, Some(MessageEventSubject::Task("task-T".to_string()))); - assert_eq!(scope.session_key.as_deref(), Some("delegate:telegram:chat-1:alice")); - let live = fabric - .record_inbound_user_message(scope.clone(), format!("SENTINEL-{run}"), None, None) - .await - .expect("test: live record"); - assert!(live.id > 0); - let mut prior = scope.clone(); - prior.run_id = Some(format!("child-segment:{run}:1")); - fabric - .record_inbound_user_message(prior, format!("OWN-PRIOR-{run}"), None, None) - .await - .expect("test: prior record"); - lanes.push((run, live)); - } - - for (run, live) in &lanes { - let mut env = RuntimeEnvelope::delegate(&ws, "delegate:telegram:chat-1:alice", *run) - .with_agent_id("tester") - .with_channel("telegram") - .with_sender("alice") - .with_owner_id("owner-T") - .with_owner_isolation(); - env.task_id = crate::runtime::turn_source::subject_task_id(live.subject.as_ref()).map(str::to_owned); - env.source_message_event_id = Some(live.event_id.clone()); - let config = crate::config::MemoryConfig { - min_relevance_score: 0.0, - ..Default::default() - }; - let scope = RecallScope::from_envelope(&env, &config, "private"); - let recalled = scoped_recall(memory.as_ref(), &scope, "delegate live request", RECALL_CONTEXT_BUDGET).await; - let preamble = recalled.preamble; - let (own, other) = if *run == "run-a" { - ("run-a", "run-b") - } else { - ("run-b", "run-a") - }; - assert!( - preamble.contains(&format!("OWN-PRIOR-{own}")), - "{run} lost its own prior segment: {preamble}" - ); - assert!( - preamble.contains("SHARED-MAIN-POSITIVE"), - "{run} lost the shared main event: {preamble}" - ); - assert!( - !preamble.contains(&format!("SENTINEL-{other}")), - "{run} recalled the sibling live request: {preamble}" - ); - assert!( - !preamble.contains(&format!("OWN-PRIOR-{other}")), - "{run} recalled the sibling prior segment: {preamble}" - ); - } - } - - #[tokio::test] - async fn delegate_task_input_preserves_inherited_remote_provenance() { - use crate::tools::sessions_spawn::{SPAWN_EXECUTION_CONTEXT, SpawnExecutionContext}; - struct InputProbe(tokio::sync::mpsc::UnboundedSender>); - #[async_trait] - impl Tool for InputProbe { - fn name(&self) -> &str { - "dynamic_alias" - } - fn description(&self) -> &str { - "Report inherited task input" - } - fn parameters_schema(&self) -> serde_json::Value { - json!({"type":"object","properties":{}}) - } - async fn execute(&self, _: serde_json::Value) -> anyhow::Result { - let input = - SPAWN_EXECUTION_CONTEXT.try_with(|context| context.task_input.inherited_provenance.clone())?; - self.0 - .send(input) - .map_err(|_| anyhow::anyhow!("task input probe receiver closed"))?; - Ok(ToolResult { - success: true, - output: "dynamic_alias".into(), - error: None, - }) - } - } - let provenance = crate::messaging::InheritedProvenance { - remote: crate::messaging::RemotePeerAttr { - issuer: "spiffe://prx".into(), - subject: "spiffe://prx/peer".into(), - message_id: uuid::Uuid::from_u128(42), - }, - chain: crate::messaging::CausalChain { - trigger: uuid::Uuid::from_u128(42), - root: uuid::Uuid::from_u128(42), - depth: 2, - ancestry: Vec::new(), - }, - }; - let mut parent = SpawnExecutionContext::seed_turn_context("prx-parent".into(), "prx-session".into()); - provenance.seal_into_task_input(&mut parent.task_input); - let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel(); - let (result, requests) = SPAWN_EXECUTION_CONTEXT - .scope( - parent, - run_configured_delegate_fixture( - vec!["dynamic_alias".into()], - vec![Arc::new(InputProbe(sender))], - "dynamic_alias", - json!({}), - None, - false, - None, - ), - ) - .await; - assert!(result.success, "{:?}", result.error); - assert_eq!( - requests.len(), - 2, - "real delegated child must execute its tool and finish" - ); - let actual = tokio::time::timeout(std::time::Duration::from_secs(5), receiver.recv()) - .await - .expect("delegated tool observes task input") - .expect("probe result"); - assert_eq!(actual.as_ref(), Some(&provenance)); - } - - #[test] - fn parse_delegate_scope_preserves_owner_topic_task_lineage() { - let scope = parse_delegate_scope(&json!({ - "_zc_scope_trusted": true, - "_zc_scope": { - "sender": "alice", - "channel": "telegram", - "chat_type": "direct", - "chat_id": "chat-1", - "owner_id": "owner:/tmp/ws:telegram:alice", - "topic_id": "topic-a", - "task_id": "task-a", - "source_message_event_id": "msg-a", - "config_generation_id": 17, - "config_source_revision": "revision-17" - } - })) - .expect("trusted scope should parse"); - - assert_eq!(scope.owner_id.as_deref(), Some("owner:/tmp/ws:telegram:alice")); - assert_eq!(scope.topic_id.as_deref(), Some("topic-a")); - assert_eq!(scope.task_id.as_deref(), Some("task-a")); - assert_eq!(scope.source_message_event_id.as_deref(), Some("msg-a")); - assert_eq!(scope.config_generation_id, Some(17)); - assert_eq!(scope.config_source_revision.as_deref(), Some("revision-17")); - } - - #[tokio::test] - async fn delegate_empty_context_omits_prefix() { - assert_empty_delegate_context().await; - } - - async fn assert_empty_delegate_context() { - let (result, requests) = run_configured_delegate_fixture( - vec!["dynamic_alias".to_owned()], - vec![Arc::new(DynamicAliasTool)], - "dynamic_alias", - json!({}), - None, - false, - Some(""), - ) - .await; - assert!(result.success, "{:?}", result.error); - assert_eq!( - requests.len(), - 2, - "child must execute the tool and finish: {}", - result.output - ); - let messages = requests[0]["messages"].as_array().unwrap(); - let user_message = messages - .iter() - .find(|message| message["role"] == "user") - .expect("the provider must receive the delegated user input"); - assert_eq!(user_message["content"], "dynamic_alias"); - } - - /// The endpoint stalls only after a real child decision request arrives. - /// This spends more wall time than the unchanged 500 ms decision budget. - #[tokio::test(start_paused = true)] - async fn delegate_empty_context_executes_child_after_wall_preemption() { - let fixture = DELEGATE_CHILD_RESPONSE.scope( - crate::agent::agent::native_decision_fixture::ChildResponseControl::WallStall( - std::time::Duration::from_millis(600), - ), - async { - #[cfg(unix)] - super::delegate_diagnostic::scope(assert_empty_delegate_context) - .await - .expect("owned preemption diagnostic"); - #[cfg(not(unix))] - assert_empty_delegate_context().await; - }, - ); - tokio::pin!(fixture); - let started = std::time::Instant::now(); - loop { - if futures::poll!(fixture.as_mut()).is_ready() { - break; - } - assert!( - started.elapsed() < std::time::Duration::from_secs(20), - "fixture wall hang guard" - ); - // Keep this task runnable while real socket/SQLite I/O completes; - // paused Tokio transport timers must not auto-advance on idle. - tokio::task::yield_now().await; - } - } - - /// Spending the child's logical decision time no longer refuses the - /// child: after R9 the engine is advisory only, its analysis is charged to - /// the turn and skipped when the budget is tight, and the request is never - /// refused because of it. The child executes its tool once and finishes. - #[tokio::test] - async fn delegate_child_logical_deadline_never_refuses_the_child() { - let clock = crate::runtime::logical_clock::ManualClock::new(); - let control = crate::agent::agent::native_decision_fixture::ChildResponseControl::AdvanceClock( - Arc::clone(&clock), - std::time::Duration::from_millis(600), - ); - let (result, requests) = crate::runtime::logical_clock::scope_local( - clock, - DELEGATE_CHILD_RESPONSE.scope( - control, - run_configured_delegate_fixture( - vec!["dynamic_alias".to_owned()], - vec![Arc::new(DynamicAliasTool)], - "dynamic_alias", - json!({}), - None, - false, - Some(""), - ), - ), - ) - .await; - assert!( - result.success, - "test: a spent logical deadline never refuses the child: {:?}", - result.error - ); - assert_eq!( - requests.len(), - 2, - "test: the child executes the tool, then finishes: {}", - result.output - ); - let tool_replies: Vec<&str> = requests - .iter() - .filter_map(|request| request["messages"].as_array()) - .flatten() - .filter(|message| message["role"] == "tool") - .filter_map(|message| message["content"].as_str()) - .collect(); - assert_eq!( - tool_replies, - ["dynamic_alias"], - "test: the allowed tool executes exactly once" - ); - assert!( - result.output.ends_with("\ndone"), - "test: the child returns its final reply: {}", - result.output - ); - } - - #[test] - fn delegate_depth_construction() { - let tool = DelegateTool::with_depth(sample_agents(), test_security(), 5); - assert_eq!(tool.depth, 5); - } - - #[tokio::test] - async fn delegate_no_agents_configured() { - let tool = DelegateTool::new(HashMap::new(), test_security()); - let result = dispatch_configured_delegate(tool, json!({"agent":"any", "prompt":"test"})).await; - assert!(!result.success); - assert!(result.error.unwrap().contains("none configured")); - } - - struct CapturedDelegate { - inner: DelegateTool, - result: Arc>>, - executions: Arc, - } - - #[async_trait] - impl Tool for CapturedDelegate { - fn name(&self) -> &str { - self.inner.name() - } - fn description(&self) -> &str { - self.inner.description() - } - fn parameters_schema(&self) -> serde_json::Value { - self.inner.parameters_schema() - } - fn tier(&self) -> ToolTier { - self.inner.tier() - } - fn categories(&self) -> &'static [ToolCategory] { - self.inner.categories() - } - async fn execute(&self, args: serde_json::Value) -> anyhow::Result { - #[cfg(unix)] - super::delegate_diagnostic::phase("captor-entered.json"); - self.executions.fetch_add(1, Ordering::SeqCst); - let make = || self.inner.execute(args); - #[cfg(unix)] - super::delegate_diagnostic::future_layout("delegate-trait-future-layout.json", &make); - match make().await { - Ok(result) => { - *self.result.lock() = Some(result.clone()); - Ok(result) - } - Err(error) => { - *self.result.lock() = Some(ToolResult { - success: false, - output: String::new(), - error: Some(error.to_string()), - }); - Err(error) - } - } - } - } - - struct DelegateParentProvider { - arguments: serde_json::Value, - } - - #[async_trait] - impl Provider for DelegateParentProvider { - async fn chat_with_system(&self, _: Option<&str>, _: &str, _: &str, _: f64) -> anyhow::Result { - anyhow::bail!("fixture must use the shared parent tool loop") - } - async fn chat(&self, request: ChatRequest<'_>, _: &str, _: f64) -> anyhow::Result { - let content = if request.messages.iter().any(|message| { - message.role == "tool" - || (message.role == "user" - && message - .content - .starts_with(crate::agent::turn_contracts::TOOL_RESULTS_PREFIX)) - }) { - "parent complete".to_owned() - } else { - format!( - "\n{}\n", - json!({ - "name":"delegate", "arguments":self.arguments - }) - ) - }; - Ok(ChatResponse { - text: Some(content), - tool_calls: Vec::new(), - reasoning_content: None, - }) - } - } - - struct NativeDelegateParentProvider { - arguments: serde_json::Value, - } - - #[async_trait] - impl Provider for NativeDelegateParentProvider { - fn capabilities(&self) -> crate::providers::traits::ProviderCapabilities { - crate::providers::traits::ProviderCapabilities { - native_tool_calling: true, - vision: false, - } - } - async fn chat_with_system(&self, _: Option<&str>, _: &str, _: &str, _: f64) -> anyhow::Result { - anyhow::bail!("fixture must use the shared parent tool loop") - } - async fn chat(&self, request: ChatRequest<'_>, _: &str, _: f64) -> anyhow::Result { - if request.messages.iter().any(|message| { - message.role == "tool" - || (message.role == "user" - && message - .content - .starts_with(crate::agent::turn_contracts::TOOL_RESULTS_PREFIX)) - }) { - return Ok(ChatResponse { - text: Some("parent complete".to_owned()), - tool_calls: Vec::new(), - reasoning_content: None, - }); - } - Ok(ChatResponse { - text: None, - tool_calls: vec![crate::providers::traits::ToolCall { - id: "prx-parent-delegate".to_owned(), - name: "delegate".to_owned(), - arguments: self.arguments.to_string(), - }], - reasoning_content: None, - }) - } - } - - struct DelegateFixtureServer(tokio::task::JoinHandle<()>); - impl Drop for DelegateFixtureServer { - fn drop(&mut self) { - self.0.abort(); - } - } - - tokio::task_local! { static CONFIGURED_DELEGATE_ENDPOINT: String; } - tokio::task_local! { - static DELEGATE_CHILD_RESPONSE: crate::agent::agent::native_decision_fixture::ChildResponseControl; - } - // Set by a test whose child reaches its tool through `capability_search` - // first (R28: a child that owns the discovery control keeps deferred - // tools behind search). - tokio::task_local! { static DELEGATE_CHILD_SEARCHES_FIRST: (); } - - async fn run_configured_delegate_fixture( - allowed_tools: Vec, - parent_tools: Vec>, - tool_name: &'static str, - arguments: serde_json::Value, - provider_error: Option<&'static str>, - custom_userinfo: bool, - context: Option<&str>, - ) -> (ToolResult, Vec) { - let retained = tempfile::tempdir().expect("private decision evidence"); - let driver = crate::agent::agent::native_decision_fixture::Driver::start_delegation("native_tool") - .await - .expect("owned compatible decision listener") - .retain_evidence_at(retained.path().to_path_buf()); - if let Ok(control) = DELEGATE_CHILD_RESPONSE.try_with(Clone::clone) { - driver.control_child_response(control); - } - let search_first = DELEGATE_CHILD_SEARCHES_FIRST.try_with(|()| ()).is_ok(); - let endpoint = driver.endpoint().to_owned(); - let clock = - crate::runtime::logical_clock::capture().unwrap_or_else(crate::runtime::logical_clock::ManualClock::new); - // These tests assert child tool behavior. Exclude OS preemption from - // admission while leaving production budgets and real I/O intact. - crate::runtime::logical_clock::scope_local( - clock, - driver.run_factory(move || async move { - observe_owned_delegate_workspace(move |workspace| async move { - CONFIGURED_DELEGATE_ENDPOINT - .scope( - endpoint, - boxed_delegate_observation(|| { - run_admitted_delegate_fixture( - workspace, - allowed_tools, - parent_tools, - tool_name, - arguments, - provider_error, - custom_userinfo, - context, - search_first, - ) - }), - ) - .await - }) - .await - }), - ) - .await - } - - async fn observe_owned_delegate_workspace(work: F) -> T - where - F: FnOnce(std::path::PathBuf) -> Fut, - Fut: std::future::Future, - { - use futures::FutureExt as _; - // The work future is dropped before CleanupScope drains its writers. - // Its temporary files must therefore belong to this enclosing owner. - let workspace = tempfile::tempdir().expect("delegate fixture workspace"); - #[cfg(unix)] - let workspace = super::delegate_diagnostic::workspace(workspace); - let cleanup = crate::runtime::turn_cleanup::CleanupScope::new(None, tokio_util::sync::CancellationToken::new()) - .expect("delegate fixture cleanup owner"); - let mut observed = None; - let drained = cleanup - .run(boxed_delegate_observation(|| async { - observed = Some( - std::panic::AssertUnwindSafe(boxed_delegate_observation(|| work(workspace.path().to_owned()))) - .catch_unwind() - .await, - ); - Ok(()) - })) - .await; - if drained.is_err() { - // An unconfirmed writer may still be using this directory. Keep - // that failure's files, but never leak a confirmed workspace. - #[cfg(unix)] - if let super::delegate_diagnostic::Workspace::Temporary(directory) = workspace { - let _retained = directory.keep(); - } - #[cfg(not(unix))] - let _retained = workspace.keep(); - tracing::warn!("delegate fixture workspace retained after unconfirmed cleanup"); - } - match observed { - Some(Err(panic)) => std::panic::resume_unwind(panic), - Some(Ok(value)) => { - drained.expect("delegate fixture writers drained"); - value - } - None => { - drained.expect("delegate fixture cleanup entered"); - panic!("delegate fixture did not run") - } - } - } - - #[tokio::test] - async fn a_panicking_delegate_fixture_keeps_its_workspace_until_owned_writers_drain() { - use futures::FutureExt as _; - let (finished, observed_writer) = tokio::sync::oneshot::channel(); - let result: Result<(), _> = - std::panic::AssertUnwindSafe(observe_owned_delegate_workspace(move |workspace| async move { - let owner = crate::runtime::turn_cleanup::current_tracker().expect("fixture cleanup owner"); - let cancellation = tokio_util::sync::CancellationToken::new(); - let ticket = owner.register(cancellation.clone()).expect("owned fixture writer"); - tokio::spawn(async move { - cancellation.cancelled().await; - let existed = workspace.is_dir(); - let written = tokio::fs::write(workspace.join("owned-drain-proof"), b"drained") - .await - .is_ok(); - finished - .send((workspace, existed, written)) - .expect("fixture writer observation"); - ticket.finish(written); - }); - panic!("controlled delegate fixture abort"); - })) - .catch_unwind() - .await; - assert!(result.is_err(), "the original fixture panic must escape"); - assert_eq!( - result - .as_ref() - .err() - .and_then(|panic| panic.downcast_ref::<&str>()) - .copied(), - Some("controlled delegate fixture abort"), - "cleanup must preserve the original panic rather than replace it" - ); - let (workspace, existed, written) = observed_writer.await.expect("owned writer completed"); - assert!(existed, "the real cleanup drain must retain the fixture workspace"); - assert!( - written, - "the owned writer must finish before temporary-directory cleanup" - ); - assert!(!workspace.exists(), "the confirmed fixture workspace must not leak"); - } - - #[tokio::test] - async fn an_unconfirmed_delegate_fixture_keeps_its_workspace() { - use futures::FutureExt as _; - let (finished, observed_workspace) = tokio::sync::oneshot::channel(); - let result: Result<(), _> = - std::panic::AssertUnwindSafe(observe_owned_delegate_workspace(move |workspace| async move { - let owner = crate::runtime::turn_cleanup::current_tracker().expect("fixture cleanup owner"); - let ticket = owner - .register(tokio_util::sync::CancellationToken::new()) - .expect("owned fixture writer"); - ticket.finish(false); - finished.send(workspace).expect("fixture workspace observation"); - })) - .catch_unwind() - .await; - assert!(result.is_err(), "unconfirmed cleanup must not be accepted"); - let workspace = observed_workspace.await.expect("fixture work completed"); - assert!(workspace.is_dir(), "unconfirmed writer files must be retained"); - } - - async fn run_admitted_delegate_fixture( - workspace: std::path::PathBuf, - allowed_tools: Vec, - parent_tools: Vec>, - tool_name: &'static str, - arguments: serde_json::Value, - provider_error: Option<&'static str>, - custom_userinfo: bool, - context: Option<&str>, - search_first: bool, - ) -> (ToolResult, Vec) { - let requests = Arc::new(parking_lot::Mutex::new(Vec::::new())); - let capture = Arc::clone(&requests); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let endpoint = format!("http://{}", listener.local_addr().unwrap()); - let handler = axum::routing::post(move |axum::Json(request): axum::Json| { - let capture = Arc::clone(&capture); - let arguments = arguments.clone(); - async move { - let results = request["messages"] - .as_array() - .unwrap() - .iter() - .filter(|message| message["role"] == "tool") - .count(); - capture.lock().push(request); - if let Some(error) = provider_error { - return (axum::http::StatusCode::BAD_REQUEST, axum::Json(json!({"error":error}))); - } - let completed = results > usize::from(search_first); - let message = if completed { - json!({"role":"assistant", "content":"done"}) - } else if search_first && results == 0 { - json!({"role":"assistant", "content":"", "tool_calls":[{ - "function":{"name":"capability_search", "arguments":{"query":tool_name, "limit":1}} - }]}) - } else if custom_userinfo { - json!({"role":"assistant", "content":null, "tool_calls":[{ - "id":"call_dynamic", "type":"function", - "function":{"name":tool_name, "arguments":arguments.to_string()} - }]}) - } else { - json!({"role":"assistant", "content":"", "tool_calls":[{ - "function":{"name":tool_name, "arguments":arguments} - }]}) - }; - let body = if custom_userinfo { - json!({"id":"fixture-response", "object":"chat.completion", "created":0, - "model":"prx-local-model", "choices":[{"index":0, "message":message, - "finish_reason":if completed { "stop" } else { "tool_calls" }}], - "usage":{"prompt_tokens":1, "completion_tokens":1, "total_tokens":2}}) - } else { - json!({"model":"prx-local-model", "message":message, - "done":true, "prompt_eval_count":1, "eval_count":1}) - }; - (axum::http::StatusCode::OK, axum::Json(body)) - } - }); - let app = axum::Router::new() - .route("/api/chat", handler.clone()) - .route("/v1/chat/completions", handler); - let mut server = DelegateFixtureServer(tokio::spawn(async move { - axum::serve(listener, app).await.unwrap(); - })); - let mut config = crate::config::Config::default(); - config.workspace_dir = workspace.clone(); - config.config_path = workspace.join("config.toml"); - config.api_url = Some(endpoint.clone()); - config.default_provider = Some("ollama".to_owned()); - config.default_model = Some("prx-local-model".to_owned()); - config.reliability.provider_retries = 0; - config.autonomy.level = AutonomyLevel::Full; - let mut agent = agentic_config(allowed_tools); - agent.provider = if custom_userinfo { - format!( - "custom:http://prx_user:DELEGATE-SECRET-pw@{}/v1", - endpoint.trim_start_matches("http://") - ) - } else { - "ollama".to_owned() - }; - agent.model = "prx-local-model".to_owned(); - if custom_userinfo { - config.providers.models.push( - serde_json::from_value(json!({ - "provider": agent.provider, - "model": agent.model, - "operations": ["chat"], - "native_tools": true, - })) - .expect("custom child fixture model descriptor"), - ); - } - if !custom_userinfo { - // The local Ollama fixture owns one root connection: key and URL - // must resolve together, not mix an agent key with a root URL. - config.api_key = agent.api_key.take(); - } - let fixture_price_key = if custom_userinfo { - format!("{}/{}", agent.provider, agent.model) - } else { - "prx-local-model".to_owned() - }; - config.agents.insert("tester".to_owned(), agent); - config.cost.prices.insert( - fixture_price_key, - crate::config::schema::ModelPricing { - input: 1.0, - output: 1.0, - cache_write: 1.0, - cache_read: 1.0, - }, - ); - let delegate = DelegateTool::new( - config.agents.clone(), - Arc::new(SecurityPolicy::from_config(&config.autonomy, &workspace)), - ) - .with_parent_tools(Arc::new(parent_tools.clone())); - let delegate = if let Some(hooks) = crate::tools::child_hooks::parent_hook_manager(&parent_tools) { - delegate.with_parent_hooks(hooks) - } else { - delegate - }; - use futures::FutureExt as _; - let mut arguments = json!({"agent":"tester", "prompt":tool_name}); - if let Some(context) = context { - arguments["context"] = json!(context); - } - let result = std::panic::AssertUnwindSafe(dispatch_admitted_delegate(config, delegate, arguments)) - .catch_unwind() - .await; - server.0.abort(); - let _ = (&mut server.0).await; - let requests = requests.lock().clone(); - match result { - Ok(result) => (result, requests), - Err(panic) => std::panic::resume_unwind(panic), - } - } - - pub(super) async fn dispatch_admitted_delegate( - config: crate::config::Config, - delegate: DelegateTool, - arguments: serde_json::Value, - ) -> ToolResult { - dispatch_admitted_delegate_from(config, delegate, arguments, None).await - } - - async fn dispatch_admitted_delegate_from( - config: crate::config::Config, - delegate: DelegateTool, - arguments: serde_json::Value, - channel: Option, - ) -> ToolResult { - let (result, executions, _) = observe_delegate_dispatch(config, delegate, arguments, channel).await; - assert_eq!(executions, 1, "the admitted delegate must execute exactly once"); - result.expect("delegate must actually execute") - } - - // Construct the large observer state in a separate synchronous frame. - // The enclosing async function still defers all work until first poll. - #[inline(never)] - fn boxed_delegate_observation(make_work: F) -> std::pin::Pin> - where - F: FnOnce() -> Fut, - Fut: std::future::Future, - { - Box::pin(make_work()) - } - - async fn observe_delegate_dispatch( - config: crate::config::Config, - delegate: DelegateTool, - arguments: serde_json::Value, - channel: Option, - ) -> (Option, usize, Vec) { - boxed_delegate_observation(move || async move { - let workspace = config.workspace_dir.clone(); - let memory = delegate.memory.clone(); - let parent_tools = delegate.parent_tools.as_ref().clone(); - let captured = Arc::new(parking_lot::Mutex::new(None)); - let executions = Arc::new(AtomicUsize::new(0)); - let mut tools: Vec> = parent_tools - .into_iter() - .filter(|tool| tool.name() != "delegate") - .map(|tool| Box::new(ToolArcRef::new(tool)) as Box) - .collect(); - tools.push(Box::new(CapturedDelegate { - inner: delegate, - result: Arc::clone(&captured), - executions: Arc::clone(&executions), - })); - let registry = crate::agent::test_admission::registry_with_search(tools); - let input = format!("delegate {}", arguments["prompt"].as_str().unwrap_or_default()); - let configured_endpoint = CONFIGURED_DELEGATE_ENDPOINT.try_with(Clone::clone).ok(); - let parent_provider: Box = if configured_endpoint.is_some() { - Box::new(NativeDelegateParentProvider { arguments }) - } else { - Box::new(DelegateParentProvider { arguments }) - }; - #[cfg(unix)] - let dispatch_audit = (configured_endpoint.is_some() && super::delegate_diagnostic::active()) - .then(|| Arc::new(super::delegate_diagnostic::DispatchAudit::default())); - #[cfg(unix)] - let audit_sink = dispatch_audit - .as_ref() - .map(|audit| Arc::clone(audit) as Arc); - #[cfg(not(unix))] - let audit_sink = None; - let admitted = if let Some(endpoint) = configured_endpoint.as_deref() { - assert!( - channel.is_none() && memory.is_none(), - "configured alias owns its CLI SQLite source" - ); - crate::agent::test_admission::AdmittedTurn::configured_delegation( - config, - &input, - Arc::clone(®istry), - endpoint, - parent_provider.as_ref(), - audit_sink, - ) - .await - } else { - match (channel, memory) { - (Some(mut message), Some(memory)) => { - message.content = input.clone(); - crate::agent::test_admission::AdmittedTurn::with_channel_memory( - config, - message, - Arc::clone(®istry), - memory, - ) - .await - } - (Some(_), None) => panic!("channel delegate fixture requires its observed memory"), - (None, Some(memory)) => { - crate::agent::test_admission::AdmittedTurn::with_memory( - config, - &input, - Arc::clone(®istry), - memory, - ) - .await - } - (None, None) => { - crate::agent::test_admission::AdmittedTurn::with_config(config, &input, Arc::clone(®istry)) - .await - } - } - }; - #[cfg(unix)] - if super::delegate_diagnostic::active() { - super::delegate_diagnostic::admission(admitted.decision().context, parent_provider.capabilities()); - } - if configured_endpoint.is_some() { - // Prediction-free opening (R9): the configured parent publishes - // the delegator with its sealed outgoing child manifest, and - // the model chooses the call. - let decision = admitted.decision(); - let published = decision - .service - .agent_execution_specs(decision.proof, decision.context) - .expect("configured parent publication"); - assert!( - published.specs.iter().any(|spec| spec.name == "delegate"), - "configured parent must publish the delegate tool: {:?}", - published.specs.iter().map(|spec| &spec.name).collect::>() - ); - assert!( - decision.context.runtime().outgoing_delegation.is_some(), - "configured parent must seal an outgoing child manifest" - ); - } - let mut history = vec![crate::providers::ChatMessage::user(input)]; - let hooks = HookManager::new(workspace); - let multimodal = crate::config::MultimodalConfig::default(); - let parent_cleanup = crate::runtime::turn_cleanup::current_tracker(); - let cleanup = crate::runtime::turn_cleanup::CleanupScope::new( - parent_cleanup.as_ref(), - tokio_util::sync::CancellationToken::new(), - ) - .expect("delegate fixture cleanup owner"); - let result = cleanup - .run(async { - Ok(tokio::time::timeout( - std::time::Duration::from_secs(20), - crate::agent::turn_engine::run_turn( - &mut history, - crate::agent::turn_request::TurnRequest { - advice: None, - channel_name: "agent", - scope: None, - mode: Default::default(), - silent: true, - expose_stay_silent: false, - multimodal: &multimodal, - schedule: crate::agent::turn_request::TurnSchedule { - read_only_tool_concurrency_window: 2, - priority_scheduling_enabled: false, - low_priority_tool_names: Vec::new(), - }, - compaction: Some(admitted.compaction()), - decision: admitted.decision(), - }, - crate::agent::turn_request::TurnServices { - provider: parent_provider.as_ref(), - provider_name: "ollama", - model: "prx-local-model", - temperature: 0.0, - tools_registry: registry, - observer: &NoopObserver, - hooks: &hooks, - approval: None, - approval_resolver: None, - runtime_adapter: Some(admitted.adapter()), - memory: admitted.memory_runtime(), - }, - crate::agent::turn_request::TurnDelivery { - cancellation: None, - on_delta: None, - on_tool_call: None, - }, - ), - ) - .await) - }) - .await; - #[cfg(unix)] - if super::delegate_diagnostic::active() { - let kind = match &result { - Err(_) => "cleanup_error", - Ok(Err(_)) => "timeout", - Ok(Ok(Err(_))) => "engine_error", - Ok(Ok(Ok(_))) => "engine_success", - }; - super::delegate_diagnostic::outcome( - kind, - executions.load(Ordering::SeqCst), - captured.lock().is_some(), - &admitted.decision().context.terminal_execution_trace(), - dispatch_audit.as_deref(), - ); - } - if configured_endpoint.is_some() { - let _ = admitted.decision().context.terminal_execution_trace(); - } - result - .expect("delegate fixture cleanup") - .expect("bounded local delegate fixture") - .expect("parent execution"); - let result = captured.lock().take(); - (result, executions.load(Ordering::SeqCst), history) - }) - .await - } - - /// Finding 96b: a delegate child emits its hook events through the - /// parent's live manager. Every delegate child runs under its ordinary - /// parent runtime (P2-R15), whose hooks are that manager. - #[tokio::test] - async fn a_delegate_child_shares_the_parents_hook_manager() { - let temp = tempfile::tempdir().unwrap(); - let hook_workspace = temp.path().join("hooks-ws"); - std::fs::create_dir_all(&hook_workspace).unwrap(); - let log = temp.path().join("llm-request.log"); - let hooks = json!({ - "timeout_ms": 60_000, - "hooks": {"llm_request": [{ - "command": "sh", - "args": ["-c", format!("echo hit >> '{}'", log.display())], - "stdin_json": false - }]} - }); - std::fs::write(hook_workspace.join("hooks.json"), hooks.to_string()).unwrap(); - let manager = Arc::new(HookManager::new(hook_workspace).allowing_workspace_hooks(temp.path().join("hooks"))); - let mut parent_tools: Vec> = vec![Arc::new(DynamicAliasTool)]; - parent_tools.extend(manager.control_tool_arcs(test_security())); - - let (result, _) = run_configured_delegate_fixture( - vec!["dynamic_alias".to_owned()], - parent_tools, - "dynamic_alias", - json!({}), - None, - false, - None, - ) - .await; - assert!(result.success, "{:?}", result.error); - assert!(manager.drain(std::time::Duration::from_secs(30)).await); - assert!( - manager.dispatch_stats().delivered >= 1, - "the child's events reach the parent's queue" - ); - let recorded = std::fs::read_to_string(&log).unwrap_or_default(); - assert!(recorded.contains("hit"), "the parent's hook recorded the child's event"); - } - - #[tokio::test] - async fn agentic_mode_accepts_and_executes_one_explicit_dynamic_alias() { - let work = || { - run_configured_delegate_fixture( - vec!["dynamic_alias".to_owned()], - vec![Arc::new(DynamicAliasTool)], - "dynamic_alias", - json!({}), - None, - false, - None, - ) - }; - #[cfg(unix)] - let (result, requests) = super::delegate_diagnostic::scope(work) - .await - .expect("complete private delegate diagnostic"); - #[cfg(not(unix))] - let (result, requests) = work().await; - assert!(result.success, "{:?}", result.error); - assert!(result.output.ends_with("\ndone")); - assert_eq!(requests.len(), 2, "child must call its tool and finish"); - assert!( - requests[1]["messages"] - .as_array() - .unwrap() - .iter() - .any(|message| message["role"] == "tool" && message["content"] == "dynamic_alias"), - "the alias must execute, not merely be offered" - ); - } - - /// INT-2B USERINFO-3, RED before: the agentic path logged the child's - /// provider label raw in its compaction-window debug line. After: a - /// `custom:` URL's `user:password@` is redacted. - #[tokio::test] - async fn agentic_mode_never_logs_provider_url_userinfo() { - // Log-capturing tests share per-callsite interest process-wide. - let _serial = crate::config::secret_paths::fixture::LOG_CALLSITE_LOCK.lock().await; - #[derive(Clone, Default)] - struct Sink(Arc>>); - impl std::io::Write for Sink { - fn write(&mut self, buf: &[u8]) -> std::io::Result { - self.0.lock().extend_from_slice(buf); - Ok(buf.len()) - } - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) - } - } - let sink = Sink::default(); - let subscriber = tracing_subscriber::fmt() - .with_ansi(false) - .with_max_level(tracing::Level::TRACE) - .with_writer({ - let sink = sink.clone(); - move || sink.clone() - }) - .finish(); - use tracing::instrument::WithSubscriber as _; - - let (result, requests) = run_configured_delegate_fixture( - vec!["dynamic_alias".to_owned()], - vec![Arc::new(DynamicAliasTool)], - "dynamic_alias", - json!({}), - None, - true, - None, - ) - .with_subscriber(crate::config::secret_paths::fixture::capture_dispatch(subscriber)) - .await; - assert!(result.success, "{:?}", result.error); - assert!(result.output.ends_with("\ndone")); - assert_eq!(requests.len(), 2, "custom provider must execute and finish"); - assert!( - requests[1]["messages"] - .as_array() - .unwrap() - .iter() - .any(|message| message["role"] == "tool" && message["content"] == "dynamic_alias") - ); - let logs = String::from_utf8_lossy(&sink.0.lock()).to_string(); - assert!( - logs.contains("delegate resolved child compaction window"), - "the sensitive logging callsite must actually execute: {logs}" - ); - assert!(logs.contains("custom:http://[redacted]@127.0.0.1:"), "{logs}"); - assert!(!logs.contains("DELEGATE-SECRET-pw"), "{logs}"); - } - - /// The `*`-inheriting child owns `capability_search`, so the inherited - /// deferred `echo_tool` stays behind search (R28): the child searches, - /// then calls the tool it found, then finishes. - #[tokio::test] - async fn agentic_mode_inherits_parent_tools_only_with_explicit_wildcard() { - let executions = Arc::new(AtomicUsize::new(0)); - let (result, requests) = DELEGATE_CHILD_SEARCHES_FIRST - .scope( - (), - run_configured_delegate_fixture( - vec!["*".to_owned()], - vec![ - Arc::new(EchoTool { - executions: Arc::clone(&executions), - }), - Arc::new(crate::tools::capability::search_tool::CapabilitySearchTool), - Arc::new(DelegateTool::new(HashMap::new(), test_security())), - ], - "echo_tool", - json!({"value":"fixture"}), - None, - false, - None, - ), - ) - .await; - assert!(result.success, "{:?}", result.error); - assert!(result.output.contains("(ollama/prx-local-model, agentic)")); - assert!(result.output.ends_with("\ndone")); - assert_eq!(requests.len(), 3, "search, call, finish"); - let offered = |request: &serde_json::Value| -> Vec { - request["tools"] - .as_array() - .map(|tools| { - tools - .iter() - .filter_map(|tool| tool["function"]["name"].as_str().map(str::to_owned)) - .collect() - }) - .unwrap_or_default() - }; - let first = offered(&requests[0]); - assert!(first.iter().any(|name| name == "capability_search"), "{first:?}"); - assert!( - first.iter().all(|name| name != "echo_tool"), - "the inherited deferred tool is not declared before search: {first:?}" - ); - assert_eq!( - executions.load(Ordering::SeqCst), - 1, - "the delegated tool must actually run, not be refused" - ); - } - - #[tokio::test] - async fn agentic_mode_rejects_wildcard_mixed_with_named_tools() { - let config = agentic_config(vec!["*".to_string(), "echo_tool".to_string()]); - let tool = DelegateTool::new(HashMap::new(), test_security()) - .with_parent_tools(Arc::new(vec![Arc::new(EchoTool::default())])); - let provider = OneToolThenFinalProvider; - - let result = tool - .boxed_delegate_loop( - "agentic", - &config, - "openrouter", - "model-test", - &provider, - "run", - 0.2, - None, - None, - ) - .await - .unwrap(); - - assert!(!result.result.success); - assert!( - result - .result - .error - .as_deref() - .unwrap_or("") - .contains("must use allowed_tools=['*'] exclusively") - ); - } - - #[tokio::test] - async fn execute_agentic_runs_tool_call_loop_with_filtered_tools() { - let executions = Arc::new(AtomicUsize::new(0)); - let (result, requests) = run_configured_delegate_fixture( - vec!["echo_tool".to_owned()], - vec![ - Arc::new(EchoTool { - executions: Arc::clone(&executions), - }), - Arc::new(DelegateTool::new(HashMap::new(), test_security())), - ], - "echo_tool", - json!({"value":"fixture"}), - None, - false, - None, - ) - .await; - assert!(result.success, "{:?}", result.error); - assert!(result.output.contains("(ollama/prx-local-model, agentic)")); - assert!(result.output.ends_with("\ndone")); - assert_eq!(requests.len(), 2); - assert_eq!( - executions.load(Ordering::SeqCst), - 1, - "the delegated tool must actually run, not be refused" - ); - } - - #[test] - fn delegate_inline_model_override_drives_child_compaction_resolution() { - let mut config = crate::config::Config::default(); - config.router.models = vec![ - router_model("openrouter", "config-model", 1_000_000), - router_model("openrouter", "inline-small", 200_000), - ]; - - let resolved = resolve_pinned_child_compaction(&config, "openrouter", "inline-small"); - - assert_eq!(resolved.config.max_context_tokens, 200_000); - assert_eq!(resolved.selected_model, "inline-small"); - assert_ne!(resolved.config.max_context_tokens, 1_000_000); - } - - #[test] - fn delegate_child_compaction_uses_the_pinned_generation_catalog_after_reload() { - let mut startup = crate::config::Config::default(); - startup.providers.models.push( - toml::from_str("provider = \"openrouter\"\nmodel = \"vendor/reload-model\"\ncontext_window = 200000\n") - .expect("test: startup declaration"), - ); - let mut reloaded = startup.clone(); - reloaded.providers.models.clear(); - reloaded.providers.models.push( - toml::from_str("provider = \"openrouter\"\nmodel = \"vendor/reload-model\"\ncontext_window = 64000\n") - .expect("test: reloaded declaration"), - ); - - let before = resolve_pinned_child_compaction(&startup, "openrouter", "vendor/reload-model"); - let after = resolve_pinned_child_compaction(&reloaded, "openrouter", "vendor/reload-model"); - - assert_eq!(before.config.max_context_tokens, 200_000); - assert_eq!(after.config.max_context_tokens, 64_000); - assert_eq!( - after.max_context_source, - crate::providers::context_window::ContextWindowSource::Catalog - ); - } - - #[tokio::test] - async fn execute_agentic_rejects_delegate_as_ineligible() { - let config = agentic_config(vec!["delegate".to_string()]); - let tool = DelegateTool::new(HashMap::new(), test_security()).with_parent_tools(Arc::new(vec![Arc::new( - DelegateTool::new(HashMap::new(), test_security()), - )])); - - let provider = OneToolThenFinalProvider; - let result = tool - .boxed_delegate_loop( - "agentic", - &config, - "openrouter", - "model-test", - &provider, - "run", - 0.2, - None, - None, - ) - .await - .unwrap(); - - assert!(!result.result.success); - assert!( - result - .result - .error - .as_deref() - .unwrap_or("") - .contains("unknown or ineligible tools: delegate") - ); - } - - #[tokio::test] - async fn execute_agentic_propagates_provider_errors() { - let executions = Arc::new(AtomicUsize::new(0)); - let (result, requests) = run_configured_delegate_fixture( - vec!["echo_tool".to_owned()], - vec![Arc::new(EchoTool { - executions: Arc::clone(&executions), - })], - "echo_tool", - json!({"value":"fixture"}), - Some("provider boom"), - false, - None, - ) - .await; - assert!(!result.success); - assert!(result.error.as_deref().unwrap_or("").contains("provider boom")); - assert_eq!(requests.len(), 1, "the admitted child must reach the failing provider"); - assert_eq!( - executions.load(Ordering::SeqCst), - 0, - "a provider failure must not execute the child tool" - ); - } - - fn single_agent(name: &str, provider: &str, model: &str) -> HashMap { - let mut agents = HashMap::new(); - agents.insert( - name.to_string(), - DelegateAgentConfig { - approval_wait_secs: 600, - limits: crate::config::AgentLimits::default(), - provider: provider.to_string(), - model: model.to_string(), - system_prompt: None, - api_key: None, - credential_ref: None, - temperature: None, - max_depth: 3, - agentic: false, - allowed_tools: Vec::new(), - identity_dir: None, - memory_scope: None, - spawn_enabled: None, - enabled: true, - autonomy: None, - }, - ); - agents - } - - #[test] - fn delegate_fallback_credential_is_scoped_to_its_provider() { - let mut child = single_agent("tester", "kimi-code", "k3") - .remove("tester") - .expect("test agent"); - let tool = DelegateTool::new(HashMap::new(), test_security()).with_root_connection(RootConnection { - provider: Some("custom:http://127.0.0.1:18083/v1".to_string()), - key: Some("root-key".to_string()), - api_url: None, - }); - - assert_eq!(tool.child_connection(&child, "kimi-code").api_key, None); - assert_eq!( - tool.child_connection(&child, "CUSTOM:http://127.0.0.1:18083/v1") - .api_key, - Some("root-key") - ); - - child.api_key = Some("child-key".to_string()); - assert_eq!(tool.child_connection(&child, "kimi-code").api_key, Some("child-key")); - } - - #[test] - fn schema_exposes_inline_model_and_provider() { - let tool = DelegateTool::new(sample_agents(), test_security()); - let schema = tool.parameters_schema(); - assert!(schema["properties"]["model"].is_object()); - assert!(schema["properties"]["provider"].is_object()); - // Inline overrides must remain optional for backward compatibility. - let required = schema["required"].as_array().unwrap(); - assert!(!required.contains(&json!("model"))); - assert!(!required.contains(&json!("provider"))); - } - - #[tokio::test] - async fn delegate_inline_model_overrides_agent_config() { - // Agent config model is "config-model"; inline override pins "pinned-model". - let workspace = tempfile::tempdir().unwrap(); - let mut config = crate::config::Config::default(); - config.workspace_dir = workspace.path().to_owned(); - config.config_path = workspace.path().join("config.toml"); - config.autonomy.level = AutonomyLevel::Full; - config.agents = single_agent("tester", "mock", "config-model"); - let tool = DelegateTool::new( - config.agents.clone(), - Arc::new(SecurityPolicy::from_config(&config.autonomy, workspace.path())), - ); - let result = dispatch_admitted_delegate( - config, - tool, - json!({"agent":"tester", "prompt":"hello", "model":"pinned-model"}), - ) - .await; - - assert!(result.success, "mock provider should succeed: {:?}", result.error); - // The formatted output records the effective (overridden) model. - assert!( - result.output.contains("pinned-model"), - "output should reflect inline model: {}", - result.output - ); - assert!( - !result.output.contains("config-model"), - "inline model must replace config model: {}", - result.output - ); - } - - #[tokio::test] - async fn delegate_inline_provider_overrides_agent_config() { - // Agent config provider is valid ("mock"); inline override forces an - // invalid provider so we can observe that the override path is taken - // (provider creation fails naming the override, not the config value). - let workspace = tempfile::tempdir().unwrap(); - let mut config = crate::config::Config::default(); - config.workspace_dir = workspace.path().to_owned(); - config.config_path = workspace.path().join("config.toml"); - config.autonomy.level = AutonomyLevel::Full; - config.agents = single_agent("tester", "mock", "m"); - let tool = DelegateTool::new( - config.agents.clone(), - Arc::new(SecurityPolicy::from_config(&config.autonomy, workspace.path())), - ); - let result = dispatch_admitted_delegate( - config, - tool, - json!({"agent":"tester", "prompt":"hello", "provider":"totally-invalid-provider"}), - ) - .await; - - assert!(!result.success); - let err = result.error.as_deref().unwrap_or(""); - assert!( - err.contains("totally-invalid-provider"), - "error should name the inline provider override: {err}" - ); - } - - #[tokio::test] - async fn delegate_without_inline_uses_agent_config() { - // No inline model/provider → backward-compatible: agent config wins. - let workspace = tempfile::tempdir().unwrap(); - let mut config = crate::config::Config::default(); - config.workspace_dir = workspace.path().to_owned(); - config.config_path = workspace.path().join("config.toml"); - config.autonomy.level = AutonomyLevel::Full; - config.agents = single_agent("tester", "mock", "config-model"); - let tool = DelegateTool::new( - config.agents.clone(), - Arc::new(SecurityPolicy::from_config(&config.autonomy, workspace.path())), - ); - let result = dispatch_admitted_delegate(config, tool, json!({"agent":"tester", "prompt":"hello"})).await; - - assert!(result.success, "mock provider should succeed: {:?}", result.error); - assert!( - result.output.contains("mock/config-model"), - "output should reflect agent config provider/model: {}", - result.output - ); - } -} +pub(crate) mod tests; /// C0-C: the model may name a provider per call, but only one the operator /// configured, and each provider receives only its own credential. Driven diff --git a/src/tools/delegate/credential_containment_tests.rs b/src/tools/delegate/credential_containment_tests.rs index ccc42a552..3285b8642 100644 --- a/src/tools/delegate/credential_containment_tests.rs +++ b/src/tools/delegate/credential_containment_tests.rs @@ -7,6 +7,7 @@ const ROOT_SENTINEL: &str = "C0-DELEGATE-ROOT-SENTINEL"; fn agent(provider: &str, api_key: Option<&str>) -> DelegateAgentConfig { DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), approval_wait_secs: 600, limits: crate::config::AgentLimits::default(), provider: provider.to_string(), diff --git a/src/tools/delegate/tests.rs b/src/tools/delegate/tests.rs new file mode 100644 index 000000000..449a2ba29 --- /dev/null +++ b/src/tools/delegate/tests.rs @@ -0,0 +1,4 @@ +#![cfg(test)] + +include!("tests/section_1.rs"); +include!("tests/section_2.rs"); diff --git a/src/tools/delegate/tests/section_1.rs b/src/tools/delegate/tests/section_1.rs new file mode 100644 index 000000000..7dcd1b64a --- /dev/null +++ b/src/tools/delegate/tests/section_1.rs @@ -0,0 +1,1717 @@ + use super::*; + use crate::memory::{MemoryPrincipal, SqliteMemory}; + use crate::providers::{ChatRequest, ChatResponse, ToolCall}; + use crate::security::{AutonomyLevel, SecurityPolicy}; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// Workspace for the delegate tests, unique per process run. + /// + /// The tool-execution ledger lives inside the workspace and is durable on + /// purpose, so the default `.` workspace would both write into the source + /// tree and let one run's records replay into the next. + fn test_workspace() -> std::path::PathBuf { + static WORKSPACE: std::sync::OnceLock = std::sync::OnceLock::new(); + WORKSPACE + .get_or_init(|| { + std::env::temp_dir().join(format!( + "prx-delegate-tests-{}-{}", + std::process::id(), + uuid::Uuid::now_v7() + )) + }) + .clone() + } + + fn test_security() -> Arc { + Arc::new(SecurityPolicy { + workspace_dir: test_workspace(), + ..SecurityPolicy::default() + }) + } + + fn sample_agents() -> HashMap { + let mut agents = HashMap::new(); + agents.insert( + "researcher".to_string(), + DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), + approval_wait_secs: 600, + limits: crate::config::AgentLimits::default(), + provider: "ollama".to_string(), + model: "llama3".to_string(), + system_prompt: Some("You are a research assistant.".to_string()), + api_key: None, + credential_ref: None, + temperature: Some(0.3), + max_depth: 3, + agentic: false, + allowed_tools: Vec::new(), + identity_dir: None, + memory_scope: None, + spawn_enabled: None, + enabled: true, + autonomy: None, + }, + ); + agents.insert( + "coder".to_string(), + DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), + approval_wait_secs: 600, + limits: crate::config::AgentLimits::default(), + provider: "openrouter".to_string(), + model: "anthropic/claude-sonnet-4-20250514".to_string(), + system_prompt: None, + api_key: Some("delegate-test-credential".to_string()), + credential_ref: None, + temperature: None, + max_depth: 2, + agentic: false, + allowed_tools: Vec::new(), + identity_dir: None, + memory_scope: None, + spawn_enabled: None, + enabled: true, + autonomy: None, + }, + ); + agents + } + + /// Counts its own executions, so a test can tell "the delegated sub-agent ran + /// the tool" from "the tool was refused and the refusal was handed back as + /// tool output". + #[derive(Default)] + struct EchoTool { + executions: Arc, + } + + #[async_trait] + impl Tool for EchoTool { + fn name(&self) -> &str { + "echo_tool" + } + + fn description(&self) -> &str { + "Echoes the `value` argument." + } + + fn parameters_schema(&self) -> serde_json::Value { + serde_json::json!({ + "type": "object", + "properties": { + "value": {"type": "string"} + }, + "required": ["value"] + }) + } + + async fn execute(&self, args: serde_json::Value) -> anyhow::Result { + self.executions.fetch_add(1, Ordering::SeqCst); + let value = args + .get("value") + .and_then(serde_json::Value::as_str) + .unwrap_or_default() + .to_string(); + Ok(ToolResult { + success: true, + output: format!("echo:{value}"), + error: None, + }) + } + } + + struct DynamicAliasTool; + + #[async_trait] + impl Tool for DynamicAliasTool { + fn name(&self) -> &str { + "dynamic_root" + } + + fn description(&self) -> &str { + "Dynamic alias fixture" + } + + fn parameters_schema(&self) -> serde_json::Value { + json!({"type": "object", "properties": {}}) + } + + fn specs(&self) -> Vec { + vec![super::super::traits::ToolSpec { + name: "dynamic_alias".to_string(), + description: self.description().to_string(), + parameters: self.parameters_schema(), + }] + } + + fn supports_name(&self, name: &str) -> bool { + matches!(name, "dynamic_root" | "dynamic_alias") + } + + async fn execute(&self, args: serde_json::Value) -> anyhow::Result { + self.execute_named("dynamic_root", args).await + } + + async fn execute_named(&self, name: &str, _args: serde_json::Value) -> anyhow::Result { + Ok(ToolResult { + success: self.supports_name(name), + output: name.to_string(), + error: None, + }) + } + } + + #[tokio::test] + async fn delegated_tool_reference_preserves_dynamic_alias_contract() { + let delegated = ToolArcRef::new(Arc::new(DynamicAliasTool)); + assert!(delegated.supports_name("dynamic_alias")); + assert_eq!(delegated.specs()[0].name, "dynamic_alias"); + let result = delegated.execute_named("dynamic_alias", json!({})).await.unwrap(); + assert!(result.success); + assert_eq!(result.output, "dynamic_alias"); + + let restricted = ToolArcRef::for_name(Arc::new(DynamicAliasTool), "dynamic_alias").unwrap(); + assert_eq!(restricted.name(), "dynamic_alias"); + assert_eq!(restricted.specs().len(), 1); + assert!(restricted.supports_name("dynamic_alias")); + assert!(!restricted.supports_name("dynamic_root")); + assert!(restricted.execute_named("dynamic_root", json!({})).await.is_err()); + } + + struct OneToolThenFinalProvider; + + #[async_trait] + impl Provider for OneToolThenFinalProvider { + async fn chat_with_system( + &self, + _system_prompt: Option<&str>, + _message: &str, + _model: &str, + _temperature: f64, + ) -> anyhow::Result { + Ok("unused".to_string()) + } + + async fn chat( + &self, + request: ChatRequest<'_>, + _model: &str, + _temperature: f64, + ) -> anyhow::Result { + let has_tool_message = request.messages.iter().any(|m| m.role == "tool"); + if has_tool_message { + Ok(ChatResponse { + text: Some("done".to_string()), + tool_calls: Vec::new(), + reasoning_content: None, + }) + } else { + Ok(ChatResponse { + text: None, + tool_calls: vec![ToolCall { + id: "call_1".to_string(), + name: "echo_tool".to_string(), + arguments: "{\"value\":\"ping\"}".to_string(), + }], + reasoning_content: None, + }) + } + } + } + + fn agentic_config(allowed_tools: Vec) -> DelegateAgentConfig { + DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), + approval_wait_secs: 600, + limits: crate::config::AgentLimits::default(), + provider: "openrouter".to_string(), + identity_dir: None, + memory_scope: None, + spawn_enabled: None, + enabled: true, + autonomy: None, + model: "model-test".to_string(), + system_prompt: Some("You are agentic.".to_string()), + api_key: Some("delegate-test-credential".to_string()), + credential_ref: None, + temperature: Some(0.2), + max_depth: 3, + agentic: true, + allowed_tools, + } + } + + fn router_model(provider: &str, model_id: &str, max_context: usize) -> crate::config::RouterModelConfig { + crate::config::RouterModelConfig { + provider: provider.to_string(), + model_id: model_id.to_string(), + cost_per_million_tokens: 1.0, + max_context, + reserved_output_tokens: None, + latency_ms: 1_000, + categories: vec!["code".to_string()], + elo_rating: 1_000.0, + } + } + + #[test] + fn name_and_schema() { + let tool = DelegateTool::new(sample_agents(), test_security()); + assert_eq!(tool.name(), "delegate"); + let schema = tool.parameters_schema(); + assert!(schema["properties"]["agent"].is_object()); + assert!(schema["properties"]["prompt"].is_object()); + assert!(schema["properties"]["context"].is_object()); + let required = schema["required"].as_array().unwrap(); + assert!(required.contains(&json!("agent"))); + assert!(required.contains(&json!("prompt"))); + assert_eq!(schema["additionalProperties"], json!(false)); + assert_eq!(schema["properties"]["agent"]["minLength"], json!(1)); + assert_eq!(schema["properties"]["prompt"]["minLength"], json!(1)); + } + + #[test] + fn description_not_empty() { + let tool = DelegateTool::new(sample_agents(), test_security()); + assert!(!tool.description().is_empty(), "expected a non-empty value"); + } + + #[test] + fn schema_lists_agent_names() { + let tool = DelegateTool::new(sample_agents(), test_security()); + let schema = tool.parameters_schema(); + let desc = schema["properties"]["agent"]["description"].as_str().unwrap(); + assert!(desc.contains("researcher") || desc.contains("coder")); + } + + #[tokio::test] + async fn missing_agent_param() { + let tool = DelegateTool::new(sample_agents(), test_security()); + let result = tool.execute(json!({"prompt": "test"})).await; + assert!(result.is_err()); + } + + #[tokio::test] + async fn missing_prompt_param() { + let tool = DelegateTool::new(sample_agents(), test_security()); + let result = tool.execute(json!({"agent": "researcher"})).await; + assert!(result.is_err()); + } + + async fn dispatch_configured_delegate(mut tool: DelegateTool, arguments: serde_json::Value) -> ToolResult { + let workspace = tempfile::tempdir().unwrap(); + let mut config = crate::config::Config::default(); + config.workspace_dir = workspace.path().to_owned(); + config.config_path = workspace.path().join("config.toml"); + config.autonomy.level = AutonomyLevel::Full; + config.agents = tool.agents.as_ref().clone(); + tool.security = Arc::new(SecurityPolicy::from_config(&config.autonomy, workspace.path())); + dispatch_admitted_delegate(config, tool, arguments).await + } + + #[tokio::test] + async fn unknown_agent_returns_error() { + let tool = DelegateTool::new(sample_agents(), test_security()); + let result = dispatch_configured_delegate(tool, json!({"agent":"nonexistent", "prompt":"test"})).await; + assert!(!result.success); + assert!(result.error.unwrap().contains("Unknown agent")); + } + + #[tokio::test] + async fn depth_limit_enforced() { + let tool = DelegateTool::with_depth(sample_agents(), test_security(), 3); + let result = dispatch_configured_delegate(tool, json!({"agent":"researcher", "prompt":"test"})).await; + assert!(!result.success); + assert!(result.error.unwrap().contains("depth limit")); + } + + #[tokio::test] + async fn depth_limit_per_agent() { + // coder has max_depth=2, so depth=2 should be blocked + let tool = DelegateTool::with_depth(sample_agents(), test_security(), 2); + let result = dispatch_configured_delegate(tool, json!({"agent":"coder", "prompt":"test"})).await; + assert!(!result.success); + assert!(result.error.unwrap().contains("depth limit")); + } + + #[test] + fn empty_agents_schema() { + let tool = DelegateTool::new(HashMap::new(), test_security()); + let schema = tool.parameters_schema(); + let desc = schema["properties"]["agent"]["description"].as_str().unwrap(); + assert!(desc.contains("none configured")); + } + + #[tokio::test] + async fn invalid_provider_returns_error() { + let mut agents = HashMap::new(); + agents.insert( + "broken".to_string(), + DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), + approval_wait_secs: 600, + limits: crate::config::AgentLimits::default(), + provider: "totally-invalid-provider".to_string(), + model: "model".to_string(), + system_prompt: None, + api_key: None, + credential_ref: None, + temperature: None, + max_depth: 3, + agentic: false, + allowed_tools: Vec::new(), + identity_dir: None, + memory_scope: None, + spawn_enabled: None, + enabled: true, + autonomy: None, + }, + ); + let tool = DelegateTool::new(agents, test_security()); + let result = dispatch_configured_delegate(tool, json!({"agent":"broken", "prompt":"test"})).await; + assert!(!result.success); + assert!(result.error.unwrap().contains("is not one PRX can construct")); + } + + #[tokio::test] + async fn blank_agent_rejected() { + let tool = DelegateTool::new(sample_agents(), test_security()); + let result = tool.execute(json!({"agent": " ", "prompt": "test"})).await.unwrap(); + assert!(!result.success); + assert!(result.error.unwrap().contains("must not be empty")); + } + + #[tokio::test] + async fn blank_prompt_rejected() { + let tool = DelegateTool::new(sample_agents(), test_security()); + let result = tool + .execute(json!({"agent": "researcher", "prompt": " \t "})) + .await + .unwrap(); + assert!(!result.success); + assert!(result.error.unwrap().contains("must not be empty")); + } + + #[tokio::test] + async fn whitespace_agent_name_trimmed_and_found() { + let tool = DelegateTool::new(single_agent("researcher", "mock", "test-model"), test_security()); + let result = dispatch_configured_delegate(tool, json!({"agent":" researcher ", "prompt":"test"})).await; + assert!(result.success, "trimmed agent must execute: {:?}", result.error); + assert!(result.output.contains("mock/test-model")); + } + + #[tokio::test] + async fn delegation_blocked_in_readonly_mode() { + let workspace = tempfile::tempdir().unwrap(); + let mut config = crate::config::Config::default(); + config.workspace_dir = workspace.path().to_owned(); + config.config_path = workspace.path().join("config.toml"); + config.autonomy.level = AutonomyLevel::ReadOnly; + config.agents = single_agent("researcher", "mock", "test-model"); + let readonly = Arc::new(SecurityPolicy::from_config(&config.autonomy, workspace.path())); + let tool = DelegateTool::new(config.agents.clone(), readonly); + let (result, executions, history) = + observe_delegate_dispatch(config, tool, json!({"agent":"researcher", "prompt":"test"}), None).await; + assert_eq!(executions, 0, "readonly execution must reject before entering delegate"); + assert!(result.is_none()); + assert!( + history.iter().any(|message| message.role == "user" + && message + .content + .starts_with(crate::agent::turn_contracts::TOOL_RESULTS_PREFIX) + && message + .content + .contains("tool 'delegate' is not permitted under the current execution policy")), + "the parent must receive the actual policy denial: {history:?}" + ); + } + + #[tokio::test] + async fn delegate_context_is_prepended_to_prompt() { + let (result, requests) = run_configured_delegate_fixture( + vec!["dynamic_alias".to_owned()], + vec![Arc::new(DynamicAliasTool)], + "dynamic_alias", + json!({}), + None, + false, + Some("some context data"), + ) + .await; + assert!(result.success, "{:?}", result.error); + assert_eq!(requests.len(), 2, "child must execute the tool and finish"); + let messages = requests[0]["messages"].as_array().unwrap(); + let user_message = messages + .iter() + .find(|message| message["role"] == "user") + .expect("the provider must receive the delegated user input"); + assert_eq!( + user_message["content"], + "[Context]\nsome context data\n\n[Task]\ndynamic_alias" + ); + } + + #[tokio::test] + async fn delegate_records_request_and_result_message_events() { + let tmp = tempfile::TempDir::new().unwrap(); + let memory: Arc = Arc::new(SqliteMemory::new(tmp.path()).unwrap()); + let mut agents = HashMap::new(); + agents.insert( + "tester".to_string(), + DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), + approval_wait_secs: 600, + limits: crate::config::AgentLimits::default(), + provider: "mock".to_string(), + model: "test-model".to_string(), + system_prompt: None, + api_key: None, + credential_ref: None, + temperature: None, + max_depth: 3, + agentic: false, + allowed_tools: Vec::new(), + identity_dir: None, + memory_scope: None, + spawn_enabled: None, + enabled: true, + autonomy: None, + }, + ); + let mut config = crate::config::Config::default(); + config.workspace_dir = tmp.path().to_owned(); + config.config_path = tmp.path().join("config.toml"); + config.autonomy.level = AutonomyLevel::Full; + config.agents = agents.clone(); + let security = Arc::new(SecurityPolicy::from_config(&config.autonomy, tmp.path())); + let tool = DelegateTool::new(agents, security).with_shared_memory(memory.clone()); + let channel = crate::channels::traits::ChannelMessage { + id: "prx-source-message".to_owned(), + sender: "prx_user".to_owned(), + reply_target: "prx_channel".to_owned(), + content: String::new(), + channel: "telegram".to_owned(), + timestamp: 0, + chat_kind: crate::channels::traits::ChatKind::Dm, + chat_title: None, + sender_display: None, + thread_ts: None, + mentioned_uuids: Vec::new(), + mentioned: false, + is_group_hint: false, + sender_is_bot: false, + }; + let result = dispatch_admitted_delegate_from( + config, + tool, + json!({"agent":"tester", "prompt":"delegate through fabric"}), + Some(channel), + ) + .await; + assert!(result.success); + + let events = memory + .list_message_events_since( + &MemoryPrincipal { + require_owner_match: false, + workspace_id: tmp.path().to_string_lossy().to_string(), + agent_id: Some("tester".to_string()), + persona_id: None, + session_key: None, + channel: Some("telegram".to_string()), + sender: Some("prx_user".to_string()), + owner_id: None, + legacy_session_key: None, + agent_partition: None, + }, + 0, + 100, + ) + .await + .unwrap(); + + let request_event = events + .iter() + .find(|event| event.role == "user" && event.source == "delegate") + .expect("delegate request event"); + let result_event = events + .iter() + .find(|event| event.role == "event" && event.content.contains("tester")) + .expect("delegate domain result event"); + assert_eq!(request_event.source, "delegate"); + assert_eq!(request_event.content, "delegate through fabric"); + assert_eq!(result_event.source, "delegate"); + assert_eq!(events.iter().filter(|event| event.role == "assistant").count(), 1); + assert_eq!( + events + .iter() + .filter(|event| event.event_type == "provider.final_outcome") + .count(), + 1 + ); + assert_eq!( + events + .iter() + .filter(|event| event.event_type == "turn.finalized") + .count(), + 1 + ); + + let parent_id = request_event + .causation_event_id + .as_deref() + .expect("delegate input must reference the actual parent source event"); + let parent_events = memory + .list_message_events_recent( + &MemoryPrincipal { + require_owner_match: false, + workspace_id: tmp.path().to_string_lossy().to_string(), + agent_id: None, + persona_id: None, + session_key: None, + channel: Some("telegram".to_owned()), + sender: Some("prx_user".to_owned()), + owner_id: None, + legacy_session_key: None, + agent_partition: None, + }, + 100, + ) + .await + .unwrap(); + let parent = parent_events + .iter() + .find(|event| event.event_id == parent_id) + .expect("the referenced source event must actually be durable"); + assert_eq!(parent.role, "user"); + assert_eq!(parent.content, "delegate delegate through fabric"); + assert_eq!(request_event.parent_run_id, parent.run_id); + assert_eq!(request_event.parent_session_key, parent.session_key); + + let task_events = memory + .list_memory_events_since( + &MemoryPrincipal { + require_owner_match: false, + workspace_id: tmp.path().to_string_lossy().to_string(), + agent_id: Some("tester".to_string()), + persona_id: None, + session_key: None, + channel: Some("telegram".to_string()), + sender: Some("prx_user".to_string()), + owner_id: None, + legacy_session_key: None, + agent_partition: None, + }, + 0, + 100, + ) + .await + .unwrap() + .into_iter() + .filter(|event| event.subject_table == "tasks") + .collect::>(); + let event_types = task_events + .iter() + .map(|event| event.event_type.as_str()) + .collect::>(); + assert!(event_types.contains(&"delegate.task.started")); + assert!(event_types.contains(&"delegate.task.completed")); + assert!(task_events.iter().all(|event| !event.subject_id.is_empty())); + assert!(task_events.iter().any(|event| { + event.payload_json.as_deref().is_some_and(|payload| { + serde_json::from_str::(payload) + .is_ok_and(|value| value["source_message_event_id"] == parent_id) + }) + })); + } + + #[test] + fn delegate_event_scope_is_derived_from_runtime_envelope() { + let scope = DelegateScope { + sender: "alice".to_string(), + channel: "telegram".to_string(), + chat_id: "chat-1".to_string(), + owner_id: Some("owner:/tmp/ws:telegram:alice".to_string()), + topic_id: Some("topic-a".to_string()), + task_id: Some("task-a".to_string()), + source_message_event_id: Some("msg-a".to_string()), + config_generation_id: Some(17), + config_source_revision: Some("revision-17".to_string()), + }; + let event_scope = delegate_event_scope("/tmp/ws", "run-delegate", "tester", Some(&scope)); + + assert_eq!(event_scope.source, "delegate"); + assert_eq!(event_scope.channel.as_deref(), Some("telegram")); + assert_eq!( + event_scope.session_key.as_deref(), + Some("delegate:telegram:chat-1:alice") + ); + assert_eq!(event_scope.run_id.as_deref(), Some("run-delegate")); + assert_eq!(event_scope.config_generation_id, Some(17)); + assert_eq!(event_scope.config_source_revision.as_deref(), Some("revision-17")); + assert_eq!(event_scope.agent_id.as_deref(), Some("tester")); + assert_eq!(event_scope.sender.as_deref(), Some("alice")); + assert_eq!(event_scope.recipient.as_deref(), Some("chat-1")); + assert_eq!(event_scope.owner_id.as_deref(), Some("owner:/tmp/ws:telegram:alice")); + assert_eq!( + event_scope.subject, + Some(crate::memory::MessageEventSubject::Task("run-delegate".into())) + ); + } + + /// Two delegates under one parent task write their own task identity, so a + /// sibling's live request and prior segment never reach the other child, + /// while the shared main-channel event stays visible to both. + #[tokio::test] + async fn delegates_under_one_parent_task_recall_only_their_own_task() { + use crate::agent::context_recall::{RECALL_CONTEXT_BUDGET, RecallScope, scoped_recall}; + use crate::memory::{MessageEventSource, MessageEventSubject, SqliteMemory}; + + let tmp = tempfile::TempDir::new().expect("test: temp dir"); + let ws = tmp.path().to_string_lossy().to_string(); + let memory: Arc = Arc::new(SqliteMemory::new(tmp.path()).expect("test: sqlite")); + let fabric = MemoryFabric::new(Arc::clone(&memory), ws.clone()); + let parent = DelegateScope { + sender: "alice".to_string(), + channel: "telegram".to_string(), + chat_id: "chat-1".to_string(), + owner_id: Some("owner-T".to_string()), + topic_id: None, + task_id: Some("task-T".to_string()), + source_message_event_id: None, + config_generation_id: Some(1), + config_source_revision: Some("rev-1".to_string()), + }; + let mut shared = delegate_event_scope(&ws, "run-main", "tester", Some(&parent)); + shared.source = MessageEventSource::Channel; + shared.subject = None; + fabric + .record_inbound_user_message(shared, "SHARED-MAIN-POSITIVE", None, None) + .await + .expect("test: shared record"); + + let mut lanes = Vec::new(); + for run in ["run-a", "run-b"] { + let scope = delegate_event_scope(&ws, run, "tester", Some(&parent)); + assert_eq!(scope.subject, Some(MessageEventSubject::Task(run.to_string()))); + assert_ne!(scope.subject, Some(MessageEventSubject::Task("task-T".to_string()))); + assert_eq!(scope.session_key.as_deref(), Some("delegate:telegram:chat-1:alice")); + let live = fabric + .record_inbound_user_message(scope.clone(), format!("SENTINEL-{run}"), None, None) + .await + .expect("test: live record"); + assert!(live.id > 0); + let mut prior = scope.clone(); + prior.run_id = Some(format!("child-segment:{run}:1")); + fabric + .record_inbound_user_message(prior, format!("OWN-PRIOR-{run}"), None, None) + .await + .expect("test: prior record"); + lanes.push((run, live)); + } + + for (run, live) in &lanes { + let mut env = RuntimeEnvelope::delegate(&ws, "delegate:telegram:chat-1:alice", *run) + .with_agent_id("tester") + .with_channel("telegram") + .with_sender("alice") + .with_owner_id("owner-T") + .with_owner_isolation(); + env.task_id = crate::runtime::turn_source::subject_task_id(live.subject.as_ref()).map(str::to_owned); + env.source_message_event_id = Some(live.event_id.clone()); + let config = crate::config::MemoryConfig { + min_relevance_score: 0.0, + ..Default::default() + }; + let scope = RecallScope::from_envelope(&env, &config, "private"); + let recalled = scoped_recall(memory.as_ref(), &scope, "delegate live request", RECALL_CONTEXT_BUDGET).await; + let preamble = recalled.preamble; + let (own, other) = if *run == "run-a" { + ("run-a", "run-b") + } else { + ("run-b", "run-a") + }; + assert!( + preamble.contains(&format!("OWN-PRIOR-{own}")), + "{run} lost its own prior segment: {preamble}" + ); + assert!( + preamble.contains("SHARED-MAIN-POSITIVE"), + "{run} lost the shared main event: {preamble}" + ); + assert!( + !preamble.contains(&format!("SENTINEL-{other}")), + "{run} recalled the sibling live request: {preamble}" + ); + assert!( + !preamble.contains(&format!("OWN-PRIOR-{other}")), + "{run} recalled the sibling prior segment: {preamble}" + ); + } + } + + #[tokio::test] + async fn delegate_task_input_preserves_inherited_remote_provenance() { + use crate::tools::sessions_spawn::{SPAWN_EXECUTION_CONTEXT, SpawnExecutionContext}; + struct InputProbe(tokio::sync::mpsc::UnboundedSender>); + #[async_trait] + impl Tool for InputProbe { + fn name(&self) -> &str { + "dynamic_alias" + } + fn description(&self) -> &str { + "Report inherited task input" + } + fn parameters_schema(&self) -> serde_json::Value { + json!({"type":"object","properties":{}}) + } + async fn execute(&self, _: serde_json::Value) -> anyhow::Result { + let input = + SPAWN_EXECUTION_CONTEXT.try_with(|context| context.task_input.inherited_provenance.clone())?; + self.0 + .send(input) + .map_err(|_| anyhow::anyhow!("task input probe receiver closed"))?; + Ok(ToolResult { + success: true, + output: "dynamic_alias".into(), + error: None, + }) + } + } + let provenance = crate::messaging::InheritedProvenance { + remote: crate::messaging::RemotePeerAttr { + issuer: "spiffe://prx".into(), + subject: "spiffe://prx/peer".into(), + message_id: uuid::Uuid::from_u128(42), + }, + chain: crate::messaging::CausalChain { + trigger: uuid::Uuid::from_u128(42), + root: uuid::Uuid::from_u128(42), + depth: 2, + ancestry: Vec::new(), + }, + }; + let mut parent = SpawnExecutionContext::seed_turn_context("prx-parent".into(), "prx-session".into()); + provenance.seal_into_task_input(&mut parent.task_input); + let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel(); + let (result, requests) = SPAWN_EXECUTION_CONTEXT + .scope( + parent, + run_configured_delegate_fixture( + vec!["dynamic_alias".into()], + vec![Arc::new(InputProbe(sender))], + "dynamic_alias", + json!({}), + None, + false, + None, + ), + ) + .await; + assert!(result.success, "{:?}", result.error); + assert_eq!( + requests.len(), + 2, + "real delegated child must execute its tool and finish" + ); + let actual = tokio::time::timeout(std::time::Duration::from_secs(5), receiver.recv()) + .await + .expect("delegated tool observes task input") + .expect("probe result"); + assert_eq!(actual.as_ref(), Some(&provenance)); + } + + #[test] + fn parse_delegate_scope_preserves_owner_topic_task_lineage() { + let scope = parse_delegate_scope(&json!({ + "_zc_scope_trusted": true, + "_zc_scope": { + "sender": "alice", + "channel": "telegram", + "chat_type": "direct", + "chat_id": "chat-1", + "owner_id": "owner:/tmp/ws:telegram:alice", + "topic_id": "topic-a", + "task_id": "task-a", + "source_message_event_id": "msg-a", + "config_generation_id": 17, + "config_source_revision": "revision-17" + } + })) + .expect("trusted scope should parse"); + + assert_eq!(scope.owner_id.as_deref(), Some("owner:/tmp/ws:telegram:alice")); + assert_eq!(scope.topic_id.as_deref(), Some("topic-a")); + assert_eq!(scope.task_id.as_deref(), Some("task-a")); + assert_eq!(scope.source_message_event_id.as_deref(), Some("msg-a")); + assert_eq!(scope.config_generation_id, Some(17)); + assert_eq!(scope.config_source_revision.as_deref(), Some("revision-17")); + } + + #[tokio::test] + async fn delegate_empty_context_omits_prefix() { + assert_empty_delegate_context().await; + } + + async fn assert_empty_delegate_context() { + let (result, requests) = run_configured_delegate_fixture( + vec!["dynamic_alias".to_owned()], + vec![Arc::new(DynamicAliasTool)], + "dynamic_alias", + json!({}), + None, + false, + Some(""), + ) + .await; + assert!(result.success, "{:?}", result.error); + assert_eq!( + requests.len(), + 2, + "child must execute the tool and finish: {}", + result.output + ); + let messages = requests[0]["messages"].as_array().unwrap(); + let user_message = messages + .iter() + .find(|message| message["role"] == "user") + .expect("the provider must receive the delegated user input"); + assert_eq!(user_message["content"], "dynamic_alias"); + } + + /// The endpoint stalls only after a real child decision request arrives. + /// This spends more wall time than the unchanged 500 ms decision budget. + #[tokio::test(start_paused = true)] + async fn delegate_empty_context_executes_child_after_wall_preemption() { + let fixture = DELEGATE_CHILD_RESPONSE.scope( + crate::agent::agent::native_decision_fixture::ChildResponseControl::WallStall( + std::time::Duration::from_millis(600), + ), + async { + #[cfg(unix)] + super::delegate_diagnostic::scope(assert_empty_delegate_context) + .await + .expect("owned preemption diagnostic"); + #[cfg(not(unix))] + assert_empty_delegate_context().await; + }, + ); + tokio::pin!(fixture); + let started = std::time::Instant::now(); + loop { + if futures::poll!(fixture.as_mut()).is_ready() { + break; + } + assert!( + started.elapsed() < std::time::Duration::from_secs(20), + "fixture wall hang guard" + ); + // Keep this task runnable while real socket/SQLite I/O completes; + // paused Tokio transport timers must not auto-advance on idle. + tokio::task::yield_now().await; + } + } + + /// Spending the child's logical decision time no longer refuses the + /// child: after R9 the engine is advisory only, its analysis is charged to + /// the turn and skipped when the budget is tight, and the request is never + /// refused because of it. The child executes its tool once and finishes. + #[tokio::test] + async fn delegate_child_logical_deadline_never_refuses_the_child() { + let clock = crate::runtime::logical_clock::ManualClock::new(); + let control = crate::agent::agent::native_decision_fixture::ChildResponseControl::AdvanceClock( + Arc::clone(&clock), + std::time::Duration::from_millis(600), + ); + let (result, requests) = crate::runtime::logical_clock::scope_local( + clock, + DELEGATE_CHILD_RESPONSE.scope( + control, + run_configured_delegate_fixture( + vec!["dynamic_alias".to_owned()], + vec![Arc::new(DynamicAliasTool)], + "dynamic_alias", + json!({}), + None, + false, + Some(""), + ), + ), + ) + .await; + assert!( + result.success, + "test: a spent logical deadline never refuses the child: {:?}", + result.error + ); + assert_eq!( + requests.len(), + 2, + "test: the child executes the tool, then finishes: {}", + result.output + ); + let tool_replies: Vec<&str> = requests + .iter() + .filter_map(|request| request["messages"].as_array()) + .flatten() + .filter(|message| message["role"] == "tool") + .filter_map(|message| message["content"].as_str()) + .collect(); + assert_eq!( + tool_replies, + ["dynamic_alias"], + "test: the allowed tool executes exactly once" + ); + assert!( + result.output.ends_with("\ndone"), + "test: the child returns its final reply: {}", + result.output + ); + } + + #[test] + fn delegate_depth_construction() { + let tool = DelegateTool::with_depth(sample_agents(), test_security(), 5); + assert_eq!(tool.depth, 5); + } + + #[tokio::test] + async fn delegate_no_agents_configured() { + let tool = DelegateTool::new(HashMap::new(), test_security()); + let result = dispatch_configured_delegate(tool, json!({"agent":"any", "prompt":"test"})).await; + assert!(!result.success); + assert!(result.error.unwrap().contains("none configured")); + } + + struct CapturedDelegate { + inner: DelegateTool, + result: Arc>>, + executions: Arc, + } + + #[async_trait] + impl Tool for CapturedDelegate { + fn name(&self) -> &str { + self.inner.name() + } + fn description(&self) -> &str { + self.inner.description() + } + fn parameters_schema(&self) -> serde_json::Value { + self.inner.parameters_schema() + } + fn tier(&self) -> ToolTier { + self.inner.tier() + } + fn categories(&self) -> &'static [ToolCategory] { + self.inner.categories() + } + async fn execute(&self, args: serde_json::Value) -> anyhow::Result { + #[cfg(unix)] + super::delegate_diagnostic::phase("captor-entered.json"); + self.executions.fetch_add(1, Ordering::SeqCst); + let make = || self.inner.execute(args); + #[cfg(unix)] + super::delegate_diagnostic::future_layout("delegate-trait-future-layout.json", &make); + match make().await { + Ok(result) => { + *self.result.lock() = Some(result.clone()); + Ok(result) + } + Err(error) => { + *self.result.lock() = Some(ToolResult { + success: false, + output: String::new(), + error: Some(error.to_string()), + }); + Err(error) + } + } + } + } + + struct DelegateParentProvider { + arguments: serde_json::Value, + } + + #[async_trait] + impl Provider for DelegateParentProvider { + async fn chat_with_system(&self, _: Option<&str>, _: &str, _: &str, _: f64) -> anyhow::Result { + anyhow::bail!("fixture must use the shared parent tool loop") + } + async fn chat(&self, request: ChatRequest<'_>, _: &str, _: f64) -> anyhow::Result { + let content = if request.messages.iter().any(|message| { + message.role == "tool" + || (message.role == "user" + && message + .content + .starts_with(crate::agent::turn_contracts::TOOL_RESULTS_PREFIX)) + }) { + "parent complete".to_owned() + } else { + format!( + "\n{}\n", + json!({ + "name":"delegate", "arguments":self.arguments + }) + ) + }; + Ok(ChatResponse { + text: Some(content), + tool_calls: Vec::new(), + reasoning_content: None, + }) + } + } + + struct NativeDelegateParentProvider { + arguments: serde_json::Value, + } + + #[async_trait] + impl Provider for NativeDelegateParentProvider { + fn capabilities(&self) -> crate::providers::traits::ProviderCapabilities { + crate::providers::traits::ProviderCapabilities { + native_tool_calling: true, + vision: false, + } + } + async fn chat_with_system(&self, _: Option<&str>, _: &str, _: &str, _: f64) -> anyhow::Result { + anyhow::bail!("fixture must use the shared parent tool loop") + } + async fn chat(&self, request: ChatRequest<'_>, _: &str, _: f64) -> anyhow::Result { + if request.messages.iter().any(|message| { + message.role == "tool" + || (message.role == "user" + && message + .content + .starts_with(crate::agent::turn_contracts::TOOL_RESULTS_PREFIX)) + }) { + return Ok(ChatResponse { + text: Some("parent complete".to_owned()), + tool_calls: Vec::new(), + reasoning_content: None, + }); + } + Ok(ChatResponse { + text: None, + tool_calls: vec![crate::providers::traits::ToolCall { + id: "prx-parent-delegate".to_owned(), + name: "delegate".to_owned(), + arguments: self.arguments.to_string(), + }], + reasoning_content: None, + }) + } + } + + struct DelegateFixtureServer(tokio::task::JoinHandle<()>); + impl Drop for DelegateFixtureServer { + fn drop(&mut self) { + self.0.abort(); + } + } + + tokio::task_local! { static CONFIGURED_DELEGATE_ENDPOINT: String; } + tokio::task_local! { + static DELEGATE_CHILD_RESPONSE: crate::agent::agent::native_decision_fixture::ChildResponseControl; + } + // Set by a test whose child reaches its tool through `capability_search` + // first (R28: a child that owns the discovery control keeps deferred + // tools behind search). + tokio::task_local! { static DELEGATE_CHILD_SEARCHES_FIRST: (); } + + async fn run_configured_delegate_fixture( + allowed_tools: Vec, + parent_tools: Vec>, + tool_name: &'static str, + arguments: serde_json::Value, + provider_error: Option<&'static str>, + custom_userinfo: bool, + context: Option<&str>, + ) -> (ToolResult, Vec) { + let retained = tempfile::tempdir().expect("private decision evidence"); + let driver = crate::agent::agent::native_decision_fixture::Driver::start_delegation("native_tool") + .await + .expect("owned compatible decision listener") + .retain_evidence_at(retained.path().to_path_buf()); + if let Ok(control) = DELEGATE_CHILD_RESPONSE.try_with(Clone::clone) { + driver.control_child_response(control); + } + let search_first = DELEGATE_CHILD_SEARCHES_FIRST.try_with(|()| ()).is_ok(); + let endpoint = driver.endpoint().to_owned(); + let clock = + crate::runtime::logical_clock::capture().unwrap_or_else(crate::runtime::logical_clock::ManualClock::new); + // These tests assert child tool behavior. Exclude OS preemption from + // admission while leaving production budgets and real I/O intact. + crate::runtime::logical_clock::scope_local( + clock, + driver.run_factory(move || async move { + observe_owned_delegate_workspace(move |workspace| async move { + CONFIGURED_DELEGATE_ENDPOINT + .scope( + endpoint, + boxed_delegate_observation(|| { + run_admitted_delegate_fixture( + workspace, + allowed_tools, + parent_tools, + tool_name, + arguments, + provider_error, + custom_userinfo, + context, + search_first, + ) + }), + ) + .await + }) + .await + }), + ) + .await + } + + async fn observe_owned_delegate_workspace(work: F) -> T + where + F: FnOnce(std::path::PathBuf) -> Fut, + Fut: std::future::Future, + { + use futures::FutureExt as _; + // The work future is dropped before CleanupScope drains its writers. + // Its temporary files must therefore belong to this enclosing owner. + let workspace = tempfile::tempdir().expect("delegate fixture workspace"); + #[cfg(unix)] + let workspace = super::delegate_diagnostic::workspace(workspace); + let cleanup = crate::runtime::turn_cleanup::CleanupScope::new(None, tokio_util::sync::CancellationToken::new()) + .expect("delegate fixture cleanup owner"); + let mut observed = None; + let drained = cleanup + .run(boxed_delegate_observation(|| async { + observed = Some( + std::panic::AssertUnwindSafe(boxed_delegate_observation(|| work(workspace.path().to_owned()))) + .catch_unwind() + .await, + ); + Ok(()) + })) + .await; + if drained.is_err() { + // An unconfirmed writer may still be using this directory. Keep + // that failure's files, but never leak a confirmed workspace. + #[cfg(unix)] + if let super::delegate_diagnostic::Workspace::Temporary(directory) = workspace { + let _retained = directory.keep(); + } + #[cfg(not(unix))] + let _retained = workspace.keep(); + tracing::warn!("delegate fixture workspace retained after unconfirmed cleanup"); + } + match observed { + Some(Err(panic)) => std::panic::resume_unwind(panic), + Some(Ok(value)) => { + drained.expect("delegate fixture writers drained"); + value + } + None => { + drained.expect("delegate fixture cleanup entered"); + panic!("delegate fixture did not run") + } + } + } + + #[tokio::test] + async fn a_panicking_delegate_fixture_keeps_its_workspace_until_owned_writers_drain() { + use futures::FutureExt as _; + let (finished, observed_writer) = tokio::sync::oneshot::channel(); + let result: Result<(), _> = + std::panic::AssertUnwindSafe(observe_owned_delegate_workspace(move |workspace| async move { + let owner = crate::runtime::turn_cleanup::current_tracker().expect("fixture cleanup owner"); + let cancellation = tokio_util::sync::CancellationToken::new(); + let ticket = owner.register(cancellation.clone()).expect("owned fixture writer"); + tokio::spawn(async move { + cancellation.cancelled().await; + let existed = workspace.is_dir(); + let written = tokio::fs::write(workspace.join("owned-drain-proof"), b"drained") + .await + .is_ok(); + finished + .send((workspace, existed, written)) + .expect("fixture writer observation"); + ticket.finish(written); + }); + panic!("controlled delegate fixture abort"); + })) + .catch_unwind() + .await; + assert!(result.is_err(), "the original fixture panic must escape"); + assert_eq!( + result + .as_ref() + .err() + .and_then(|panic| panic.downcast_ref::<&str>()) + .copied(), + Some("controlled delegate fixture abort"), + "cleanup must preserve the original panic rather than replace it" + ); + let (workspace, existed, written) = observed_writer.await.expect("owned writer completed"); + assert!(existed, "the real cleanup drain must retain the fixture workspace"); + assert!( + written, + "the owned writer must finish before temporary-directory cleanup" + ); + assert!(!workspace.exists(), "the confirmed fixture workspace must not leak"); + } + + #[tokio::test] + async fn an_unconfirmed_delegate_fixture_keeps_its_workspace() { + use futures::FutureExt as _; + let (finished, observed_workspace) = tokio::sync::oneshot::channel(); + let result: Result<(), _> = + std::panic::AssertUnwindSafe(observe_owned_delegate_workspace(move |workspace| async move { + let owner = crate::runtime::turn_cleanup::current_tracker().expect("fixture cleanup owner"); + let ticket = owner + .register(tokio_util::sync::CancellationToken::new()) + .expect("owned fixture writer"); + ticket.finish(false); + finished.send(workspace).expect("fixture workspace observation"); + })) + .catch_unwind() + .await; + assert!(result.is_err(), "unconfirmed cleanup must not be accepted"); + let workspace = observed_workspace.await.expect("fixture work completed"); + assert!(workspace.is_dir(), "unconfirmed writer files must be retained"); + } + + async fn run_admitted_delegate_fixture( + workspace: std::path::PathBuf, + allowed_tools: Vec, + parent_tools: Vec>, + tool_name: &'static str, + arguments: serde_json::Value, + provider_error: Option<&'static str>, + custom_userinfo: bool, + context: Option<&str>, + search_first: bool, + ) -> (ToolResult, Vec) { + let requests = Arc::new(parking_lot::Mutex::new(Vec::::new())); + let capture = Arc::clone(&requests); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://{}", listener.local_addr().unwrap()); + let handler = axum::routing::post(move |axum::Json(request): axum::Json| { + let capture = Arc::clone(&capture); + let arguments = arguments.clone(); + async move { + let results = request["messages"] + .as_array() + .unwrap() + .iter() + .filter(|message| message["role"] == "tool") + .count(); + capture.lock().push(request); + if let Some(error) = provider_error { + return (axum::http::StatusCode::BAD_REQUEST, axum::Json(json!({"error":error}))); + } + let completed = results > usize::from(search_first); + let message = if completed { + json!({"role":"assistant", "content":"done"}) + } else if search_first && results == 0 { + json!({"role":"assistant", "content":"", "tool_calls":[{ + "function":{"name":"capability_search", "arguments":{"query":tool_name, "limit":1}} + }]}) + } else if custom_userinfo { + json!({"role":"assistant", "content":null, "tool_calls":[{ + "id":"call_dynamic", "type":"function", + "function":{"name":tool_name, "arguments":arguments.to_string()} + }]}) + } else { + json!({"role":"assistant", "content":"", "tool_calls":[{ + "function":{"name":tool_name, "arguments":arguments} + }]}) + }; + let body = if custom_userinfo { + json!({"id":"fixture-response", "object":"chat.completion", "created":0, + "model":"prx-local-model", "choices":[{"index":0, "message":message, + "finish_reason":if completed { "stop" } else { "tool_calls" }}], + "usage":{"prompt_tokens":1, "completion_tokens":1, "total_tokens":2}}) + } else { + json!({"model":"prx-local-model", "message":message, + "done":true, "prompt_eval_count":1, "eval_count":1}) + }; + (axum::http::StatusCode::OK, axum::Json(body)) + } + }); + let app = axum::Router::new() + .route("/api/chat", handler.clone()) + .route("/v1/chat/completions", handler); + let mut server = DelegateFixtureServer(tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + })); + let mut config = crate::config::Config::default(); + config.workspace_dir = workspace.clone(); + config.config_path = workspace.join("config.toml"); + config.api_url = Some(endpoint.clone()); + config.default_provider = Some("ollama".to_owned()); + config.default_model = Some("prx-local-model".to_owned()); + config.reliability.provider_retries = 0; + config.autonomy.level = AutonomyLevel::Full; + let mut agent = agentic_config(allowed_tools); + agent.provider = if custom_userinfo { + format!( + "custom:http://prx_user:DELEGATE-SECRET-pw@{}/v1", + endpoint.trim_start_matches("http://") + ) + } else { + "ollama".to_owned() + }; + agent.model = "prx-local-model".to_owned(); + if custom_userinfo { + config.providers.models.push( + serde_json::from_value(json!({ + "provider": agent.provider, + "model": agent.model, + "operations": ["chat"], + "native_tools": true, + })) + .expect("custom child fixture model descriptor"), + ); + } + if !custom_userinfo { + // The local Ollama fixture owns one root connection: key and URL + // must resolve together, not mix an agent key with a root URL. + config.api_key = agent.api_key.take(); + } + let fixture_price_key = if custom_userinfo { + format!("{}/{}", agent.provider, agent.model) + } else { + "prx-local-model".to_owned() + }; + config.agents.insert("tester".to_owned(), agent); + config.cost.prices.insert( + fixture_price_key, + crate::config::schema::ModelPricing { + input: 1.0, + output: 1.0, + cache_write: 1.0, + cache_read: 1.0, + }, + ); + let delegate = DelegateTool::new( + config.agents.clone(), + Arc::new(SecurityPolicy::from_config(&config.autonomy, &workspace)), + ) + .with_parent_tools(Arc::new(parent_tools.clone())); + let delegate = if let Some(hooks) = crate::tools::child_hooks::parent_hook_manager(&parent_tools) { + delegate.with_parent_hooks(hooks) + } else { + delegate + }; + use futures::FutureExt as _; + let mut arguments = json!({"agent":"tester", "prompt":tool_name}); + if let Some(context) = context { + arguments["context"] = json!(context); + } + let result = std::panic::AssertUnwindSafe(dispatch_admitted_delegate(config, delegate, arguments)) + .catch_unwind() + .await; + server.0.abort(); + let _ = (&mut server.0).await; + let requests = requests.lock().clone(); + match result { + Ok(result) => (result, requests), + Err(panic) => std::panic::resume_unwind(panic), + } + } + + pub(super) async fn dispatch_admitted_delegate( + config: crate::config::Config, + delegate: DelegateTool, + arguments: serde_json::Value, + ) -> ToolResult { + dispatch_admitted_delegate_from(config, delegate, arguments, None).await + } + + async fn dispatch_admitted_delegate_from( + config: crate::config::Config, + delegate: DelegateTool, + arguments: serde_json::Value, + channel: Option, + ) -> ToolResult { + let (result, executions, _) = observe_delegate_dispatch(config, delegate, arguments, channel).await; + assert_eq!(executions, 1, "the admitted delegate must execute exactly once"); + result.expect("delegate must actually execute") + } + + // Construct the large observer state in a separate synchronous frame. + // The enclosing async function still defers all work until first poll. + #[inline(never)] + fn boxed_delegate_observation(make_work: F) -> std::pin::Pin> + where + F: FnOnce() -> Fut, + Fut: std::future::Future, + { + Box::pin(make_work()) + } + + async fn observe_delegate_dispatch( + config: crate::config::Config, + delegate: DelegateTool, + arguments: serde_json::Value, + channel: Option, + ) -> (Option, usize, Vec) { + boxed_delegate_observation(move || async move { + let workspace = config.workspace_dir.clone(); + let memory = delegate.memory.clone(); + let parent_tools = delegate.parent_tools.as_ref().clone(); + let captured = Arc::new(parking_lot::Mutex::new(None)); + let executions = Arc::new(AtomicUsize::new(0)); + let mut tools: Vec> = parent_tools + .into_iter() + .filter(|tool| tool.name() != "delegate") + .map(|tool| Box::new(ToolArcRef::new(tool)) as Box) + .collect(); + tools.push(Box::new(CapturedDelegate { + inner: delegate, + result: Arc::clone(&captured), + executions: Arc::clone(&executions), + })); + let registry = crate::agent::test_admission::registry_with_search(tools); + let input = format!("delegate {}", arguments["prompt"].as_str().unwrap_or_default()); + let configured_endpoint = CONFIGURED_DELEGATE_ENDPOINT.try_with(Clone::clone).ok(); + let parent_provider: Box = if configured_endpoint.is_some() { + Box::new(NativeDelegateParentProvider { arguments }) + } else { + Box::new(DelegateParentProvider { arguments }) + }; + #[cfg(unix)] + let dispatch_audit = (configured_endpoint.is_some() && super::delegate_diagnostic::active()) + .then(|| Arc::new(super::delegate_diagnostic::DispatchAudit::default())); + #[cfg(unix)] + let audit_sink = dispatch_audit + .as_ref() + .map(|audit| Arc::clone(audit) as Arc); + #[cfg(not(unix))] + let audit_sink = None; + let admitted = if let Some(endpoint) = configured_endpoint.as_deref() { + assert!( + channel.is_none() && memory.is_none(), + "configured alias owns its CLI SQLite source" + ); + crate::agent::test_admission::AdmittedTurn::configured_delegation( + config, + &input, + Arc::clone(®istry), + endpoint, + parent_provider.as_ref(), + audit_sink, + ) + .await + } else { + match (channel, memory) { + (Some(mut message), Some(memory)) => { + message.content = input.clone(); + crate::agent::test_admission::AdmittedTurn::with_channel_memory( + config, + message, + Arc::clone(®istry), + memory, + ) + .await + } + (Some(_), None) => panic!("channel delegate fixture requires its observed memory"), + (None, Some(memory)) => { + crate::agent::test_admission::AdmittedTurn::with_memory( + config, + &input, + Arc::clone(®istry), + memory, + ) + .await + } + (None, None) => { + crate::agent::test_admission::AdmittedTurn::with_config(config, &input, Arc::clone(®istry)) + .await + } + } + }; + #[cfg(unix)] + if super::delegate_diagnostic::active() { + super::delegate_diagnostic::admission(admitted.decision().context, parent_provider.capabilities()); + } + if configured_endpoint.is_some() { + // Prediction-free opening (R9): the configured parent publishes + // the delegator with its sealed outgoing child manifest, and + // the model chooses the call. + let decision = admitted.decision(); + let published = decision + .service + .agent_execution_specs(decision.proof, decision.context) + .expect("configured parent publication"); + assert!( + published.specs.iter().any(|spec| spec.name == "delegate"), + "configured parent must publish the delegate tool: {:?}", + published.specs.iter().map(|spec| &spec.name).collect::>() + ); + assert!( + decision.context.runtime().outgoing_delegation.is_some(), + "configured parent must seal an outgoing child manifest" + ); + } + let mut history = vec![crate::providers::ChatMessage::user(input)]; + let hooks = HookManager::new(workspace); + let multimodal = crate::config::MultimodalConfig::default(); + let parent_cleanup = crate::runtime::turn_cleanup::current_tracker(); + let cleanup = crate::runtime::turn_cleanup::CleanupScope::new( + parent_cleanup.as_ref(), + tokio_util::sync::CancellationToken::new(), + ) + .expect("delegate fixture cleanup owner"); + let result = cleanup + .run(async { + Ok(tokio::time::timeout( + std::time::Duration::from_secs(20), + crate::agent::turn_engine::run_turn( + &mut history, + crate::agent::turn_request::TurnRequest { + advice: None, + channel_name: "agent", + scope: None, + mode: Default::default(), + silent: true, + expose_stay_silent: false, + multimodal: &multimodal, + schedule: crate::agent::turn_request::TurnSchedule { + read_only_tool_concurrency_window: 2, + priority_scheduling_enabled: false, + low_priority_tool_names: Vec::new(), + }, + compaction: Some(admitted.compaction()), + decision: admitted.decision(), + }, + crate::agent::turn_request::TurnServices { + provider: parent_provider.as_ref(), + provider_name: "ollama", + model: "prx-local-model", + temperature: 0.0, + tools_registry: registry, + observer: &NoopObserver, + hooks: &hooks, + approval: None, + approval_resolver: None, + runtime_adapter: Some(admitted.adapter()), + memory: admitted.memory_runtime(), + }, + crate::agent::turn_request::TurnDelivery { + cancellation: None, + on_delta: None, + on_tool_call: None, + }, + ), + ) + .await) + }) + .await; + #[cfg(unix)] + if super::delegate_diagnostic::active() { + let kind = match &result { + Err(_) => "cleanup_error", + Ok(Err(_)) => "timeout", + Ok(Ok(Err(_))) => "engine_error", + Ok(Ok(Ok(_))) => "engine_success", + }; + super::delegate_diagnostic::outcome( + kind, + executions.load(Ordering::SeqCst), + captured.lock().is_some(), + &admitted.decision().context.terminal_execution_trace(), + dispatch_audit.as_deref(), + ); + } + if configured_endpoint.is_some() { + let _ = admitted.decision().context.terminal_execution_trace(); + } + result + .expect("delegate fixture cleanup") + .expect("bounded local delegate fixture") + .expect("parent execution"); + let result = captured.lock().take(); + (result, executions.load(Ordering::SeqCst), history) + }) + .await + } + + /// Finding 96b: a delegate child emits its hook events through the + /// parent's live manager. Every delegate child runs under its ordinary + /// parent runtime (P2-R15), whose hooks are that manager. + #[tokio::test] + async fn a_delegate_child_shares_the_parents_hook_manager() { + let temp = tempfile::tempdir().unwrap(); + let hook_workspace = temp.path().join("hooks-ws"); + std::fs::create_dir_all(&hook_workspace).unwrap(); + let log = temp.path().join("llm-request.log"); + let hooks = json!({ + "timeout_ms": 60_000, + "hooks": {"llm_request": [{ + "command": "sh", + "args": ["-c", format!("echo hit >> '{}'", log.display())], + "stdin_json": false + }]} + }); + std::fs::write(hook_workspace.join("hooks.json"), hooks.to_string()).unwrap(); + let manager = Arc::new(HookManager::new(hook_workspace).allowing_workspace_hooks(temp.path().join("hooks"))); + let mut parent_tools: Vec> = vec![Arc::new(DynamicAliasTool)]; + parent_tools.extend(manager.control_tool_arcs(test_security())); + + let (result, _) = run_configured_delegate_fixture( + vec!["dynamic_alias".to_owned()], + parent_tools, + "dynamic_alias", + json!({}), + None, + false, + None, + ) + .await; + assert!(result.success, "{:?}", result.error); + assert!(manager.drain(std::time::Duration::from_secs(30)).await); + assert!( + manager.dispatch_stats().delivered >= 1, + "the child's events reach the parent's queue" + ); + let recorded = std::fs::read_to_string(&log).unwrap_or_default(); + assert!(recorded.contains("hit"), "the parent's hook recorded the child's event"); + } + + #[tokio::test] + async fn agentic_mode_accepts_and_executes_one_explicit_dynamic_alias() { + let work = || { + run_configured_delegate_fixture( + vec!["dynamic_alias".to_owned()], + vec![Arc::new(DynamicAliasTool)], + "dynamic_alias", + json!({}), + None, + false, + None, + ) + }; + #[cfg(unix)] + let (result, requests) = super::delegate_diagnostic::scope(work) + .await + .expect("complete private delegate diagnostic"); + #[cfg(not(unix))] + let (result, requests) = work().await; + assert!(result.success, "{:?}", result.error); + assert!(result.output.ends_with("\ndone")); + assert_eq!(requests.len(), 2, "child must call its tool and finish"); + assert!( + requests[1]["messages"] + .as_array() + .unwrap() + .iter() + .any(|message| message["role"] == "tool" && message["content"] == "dynamic_alias"), + "the alias must execute, not merely be offered" + ); + } diff --git a/src/tools/delegate/tests/section_2.rs b/src/tools/delegate/tests/section_2.rs new file mode 100644 index 000000000..aea340666 --- /dev/null +++ b/src/tools/delegate/tests/section_2.rs @@ -0,0 +1,421 @@ + /// INT-2B USERINFO-3, RED before: the agentic path logged the child's + /// provider label raw in its compaction-window debug line. After: a + /// `custom:` URL's `user:password@` is redacted. + #[tokio::test] + async fn agentic_mode_never_logs_provider_url_userinfo() { + // Log-capturing tests share per-callsite interest process-wide. + let _serial = crate::config::secret_paths::fixture::LOG_CALLSITE_LOCK.lock().await; + #[derive(Clone, Default)] + struct Sink(Arc>>); + impl std::io::Write for Sink { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.lock().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let sink = Sink::default(); + let subscriber = tracing_subscriber::fmt() + .with_ansi(false) + .with_max_level(tracing::Level::TRACE) + .with_writer({ + let sink = sink.clone(); + move || sink.clone() + }) + .finish(); + use tracing::instrument::WithSubscriber as _; + + let (result, requests) = run_configured_delegate_fixture( + vec!["dynamic_alias".to_owned()], + vec![Arc::new(DynamicAliasTool)], + "dynamic_alias", + json!({}), + None, + true, + None, + ) + .with_subscriber(crate::config::secret_paths::fixture::capture_dispatch(subscriber)) + .await; + assert!(result.success, "{:?}", result.error); + assert!(result.output.ends_with("\ndone")); + assert_eq!(requests.len(), 2, "custom provider must execute and finish"); + assert!( + requests[1]["messages"] + .as_array() + .unwrap() + .iter() + .any(|message| message["role"] == "tool" && message["content"] == "dynamic_alias") + ); + let logs = String::from_utf8_lossy(&sink.0.lock()).to_string(); + assert!( + logs.contains("delegate resolved child compaction window"), + "the sensitive logging callsite must actually execute: {logs}" + ); + assert!(logs.contains("custom:http://[redacted]@127.0.0.1:"), "{logs}"); + assert!(!logs.contains("DELEGATE-SECRET-pw"), "{logs}"); + } + + /// The `*`-inheriting child owns `capability_search`, so the inherited + /// deferred `echo_tool` stays behind search (R28): the child searches, + /// then calls the tool it found, then finishes. + #[tokio::test] + async fn agentic_mode_inherits_parent_tools_only_with_explicit_wildcard() { + let executions = Arc::new(AtomicUsize::new(0)); + let (result, requests) = DELEGATE_CHILD_SEARCHES_FIRST + .scope( + (), + run_configured_delegate_fixture( + vec!["*".to_owned()], + vec![ + Arc::new(EchoTool { + executions: Arc::clone(&executions), + }), + Arc::new(crate::tools::capability::search_tool::CapabilitySearchTool), + Arc::new(DelegateTool::new(HashMap::new(), test_security())), + ], + "echo_tool", + json!({"value":"fixture"}), + None, + false, + None, + ), + ) + .await; + assert!(result.success, "{:?}", result.error); + assert!(result.output.contains("(ollama/prx-local-model, agentic)")); + assert!(result.output.ends_with("\ndone")); + assert_eq!(requests.len(), 3, "search, call, finish"); + let offered = |request: &serde_json::Value| -> Vec { + request["tools"] + .as_array() + .map(|tools| { + tools + .iter() + .filter_map(|tool| tool["function"]["name"].as_str().map(str::to_owned)) + .collect() + }) + .unwrap_or_default() + }; + let first = offered(&requests[0]); + assert!(first.iter().any(|name| name == "capability_search"), "{first:?}"); + assert!( + first.iter().all(|name| name != "echo_tool"), + "the inherited deferred tool is not declared before search: {first:?}" + ); + assert_eq!( + executions.load(Ordering::SeqCst), + 1, + "the delegated tool must actually run, not be refused" + ); + } + + #[tokio::test] + async fn agentic_mode_rejects_wildcard_mixed_with_named_tools() { + let config = agentic_config(vec!["*".to_string(), "echo_tool".to_string()]); + let tool = DelegateTool::new(HashMap::new(), test_security()) + .with_parent_tools(Arc::new(vec![Arc::new(EchoTool::default())])); + let provider = OneToolThenFinalProvider; + + let result = tool + .boxed_delegate_loop( + "agentic", + &config, + "openrouter", + "model-test", + &provider, + "run", + 0.2, + None, + None, + ) + .await + .unwrap(); + + assert!(!result.result.success); + assert!( + result + .result + .error + .as_deref() + .unwrap_or("") + .contains("must use allowed_tools=['*'] exclusively") + ); + } + + #[tokio::test] + async fn execute_agentic_runs_tool_call_loop_with_filtered_tools() { + let executions = Arc::new(AtomicUsize::new(0)); + let (result, requests) = run_configured_delegate_fixture( + vec!["echo_tool".to_owned()], + vec![ + Arc::new(EchoTool { + executions: Arc::clone(&executions), + }), + Arc::new(DelegateTool::new(HashMap::new(), test_security())), + ], + "echo_tool", + json!({"value":"fixture"}), + None, + false, + None, + ) + .await; + assert!(result.success, "{:?}", result.error); + assert!(result.output.contains("(ollama/prx-local-model, agentic)")); + assert!(result.output.ends_with("\ndone")); + assert_eq!(requests.len(), 2); + assert_eq!( + executions.load(Ordering::SeqCst), + 1, + "the delegated tool must actually run, not be refused" + ); + } + + #[test] + fn delegate_inline_model_override_drives_child_compaction_resolution() { + let mut config = crate::config::Config::default(); + config.router.models = vec![ + router_model("openrouter", "config-model", 1_000_000), + router_model("openrouter", "inline-small", 200_000), + ]; + + let resolved = resolve_pinned_child_compaction(&config, "openrouter", "inline-small"); + + assert_eq!(resolved.config.max_context_tokens, 200_000); + assert_eq!(resolved.selected_model, "inline-small"); + assert_ne!(resolved.config.max_context_tokens, 1_000_000); + } + + #[test] + fn delegate_child_compaction_uses_the_pinned_generation_catalog_after_reload() { + let mut startup = crate::config::Config::default(); + startup.providers.models.push( + toml::from_str("provider = \"openrouter\"\nmodel = \"vendor/reload-model\"\ncontext_window = 200000\n") + .expect("test: startup declaration"), + ); + let mut reloaded = startup.clone(); + reloaded.providers.models.clear(); + reloaded.providers.models.push( + toml::from_str("provider = \"openrouter\"\nmodel = \"vendor/reload-model\"\ncontext_window = 64000\n") + .expect("test: reloaded declaration"), + ); + + let before = resolve_pinned_child_compaction(&startup, "openrouter", "vendor/reload-model"); + let after = resolve_pinned_child_compaction(&reloaded, "openrouter", "vendor/reload-model"); + + assert_eq!(before.config.max_context_tokens, 200_000); + assert_eq!(after.config.max_context_tokens, 64_000); + assert_eq!( + after.max_context_source, + crate::providers::context_window::ContextWindowSource::Catalog + ); + } + + #[tokio::test] + async fn execute_agentic_rejects_delegate_as_ineligible() { + let config = agentic_config(vec!["delegate".to_string()]); + let tool = DelegateTool::new(HashMap::new(), test_security()).with_parent_tools(Arc::new(vec![Arc::new( + DelegateTool::new(HashMap::new(), test_security()), + )])); + + let provider = OneToolThenFinalProvider; + let result = tool + .boxed_delegate_loop( + "agentic", + &config, + "openrouter", + "model-test", + &provider, + "run", + 0.2, + None, + None, + ) + .await + .unwrap(); + + assert!(!result.result.success); + assert!( + result + .result + .error + .as_deref() + .unwrap_or("") + .contains("unknown or ineligible tools: delegate") + ); + } + + #[tokio::test] + async fn execute_agentic_propagates_provider_errors() { + let executions = Arc::new(AtomicUsize::new(0)); + let (result, requests) = run_configured_delegate_fixture( + vec!["echo_tool".to_owned()], + vec![Arc::new(EchoTool { + executions: Arc::clone(&executions), + })], + "echo_tool", + json!({"value":"fixture"}), + Some("provider boom"), + false, + None, + ) + .await; + assert!(!result.success); + assert!(result.error.as_deref().unwrap_or("").contains("provider boom")); + assert_eq!(requests.len(), 1, "the admitted child must reach the failing provider"); + assert_eq!( + executions.load(Ordering::SeqCst), + 0, + "a provider failure must not execute the child tool" + ); + } + + fn single_agent(name: &str, provider: &str, model: &str) -> HashMap { + let mut agents = HashMap::new(); + agents.insert( + name.to_string(), + DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), + approval_wait_secs: 600, + limits: crate::config::AgentLimits::default(), + provider: provider.to_string(), + model: model.to_string(), + system_prompt: None, + api_key: None, + credential_ref: None, + temperature: None, + max_depth: 3, + agentic: false, + allowed_tools: Vec::new(), + identity_dir: None, + memory_scope: None, + spawn_enabled: None, + enabled: true, + autonomy: None, + }, + ); + agents + } + + #[test] + fn delegate_fallback_credential_is_scoped_to_its_provider() { + let mut child = single_agent("tester", "kimi-code", "k3") + .remove("tester") + .expect("test agent"); + let tool = DelegateTool::new(HashMap::new(), test_security()).with_root_connection(RootConnection { + provider: Some("custom:http://127.0.0.1:18083/v1".to_string()), + key: Some("root-key".to_string()), + api_url: None, + }); + + assert_eq!(tool.child_connection(&child, "kimi-code").api_key, None); + assert_eq!( + tool.child_connection(&child, "CUSTOM:http://127.0.0.1:18083/v1") + .api_key, + Some("root-key") + ); + + child.api_key = Some("child-key".to_string()); + assert_eq!(tool.child_connection(&child, "kimi-code").api_key, Some("child-key")); + } + + #[test] + fn schema_exposes_inline_model_and_provider() { + let tool = DelegateTool::new(sample_agents(), test_security()); + let schema = tool.parameters_schema(); + assert!(schema["properties"]["model"].is_object()); + assert!(schema["properties"]["provider"].is_object()); + // Inline overrides must remain optional for backward compatibility. + let required = schema["required"].as_array().unwrap(); + assert!(!required.contains(&json!("model"))); + assert!(!required.contains(&json!("provider"))); + } + + #[tokio::test] + async fn delegate_inline_model_overrides_agent_config() { + // Agent config model is "config-model"; inline override pins "pinned-model". + let workspace = tempfile::tempdir().unwrap(); + let mut config = crate::config::Config::default(); + config.workspace_dir = workspace.path().to_owned(); + config.config_path = workspace.path().join("config.toml"); + config.autonomy.level = AutonomyLevel::Full; + config.agents = single_agent("tester", "mock", "config-model"); + let tool = DelegateTool::new( + config.agents.clone(), + Arc::new(SecurityPolicy::from_config(&config.autonomy, workspace.path())), + ); + let result = dispatch_admitted_delegate( + config, + tool, + json!({"agent":"tester", "prompt":"hello", "model":"pinned-model"}), + ) + .await; + + assert!(result.success, "mock provider should succeed: {:?}", result.error); + // The formatted output records the effective (overridden) model. + assert!( + result.output.contains("pinned-model"), + "output should reflect inline model: {}", + result.output + ); + assert!( + !result.output.contains("config-model"), + "inline model must replace config model: {}", + result.output + ); + } + + #[tokio::test] + async fn delegate_inline_provider_overrides_agent_config() { + // Agent config provider is valid ("mock"); inline override forces an + // invalid provider so we can observe that the override path is taken + // (provider creation fails naming the override, not the config value). + let workspace = tempfile::tempdir().unwrap(); + let mut config = crate::config::Config::default(); + config.workspace_dir = workspace.path().to_owned(); + config.config_path = workspace.path().join("config.toml"); + config.autonomy.level = AutonomyLevel::Full; + config.agents = single_agent("tester", "mock", "m"); + let tool = DelegateTool::new( + config.agents.clone(), + Arc::new(SecurityPolicy::from_config(&config.autonomy, workspace.path())), + ); + let result = dispatch_admitted_delegate( + config, + tool, + json!({"agent":"tester", "prompt":"hello", "provider":"totally-invalid-provider"}), + ) + .await; + + assert!(!result.success); + let err = result.error.as_deref().unwrap_or(""); + assert!( + err.contains("totally-invalid-provider"), + "error should name the inline provider override: {err}" + ); + } + + #[tokio::test] + async fn delegate_without_inline_uses_agent_config() { + // No inline model/provider → backward-compatible: agent config wins. + let workspace = tempfile::tempdir().unwrap(); + let mut config = crate::config::Config::default(); + config.workspace_dir = workspace.path().to_owned(); + config.config_path = workspace.path().join("config.toml"); + config.autonomy.level = AutonomyLevel::Full; + config.agents = single_agent("tester", "mock", "config-model"); + let tool = DelegateTool::new( + config.agents.clone(), + Arc::new(SecurityPolicy::from_config(&config.autonomy, workspace.path())), + ); + let result = dispatch_admitted_delegate(config, tool, json!({"agent":"tester", "prompt":"hello"})).await; + + assert!(result.success, "mock provider should succeed: {:?}", result.error); + assert!( + result.output.contains("mock/config-model"), + "output should reflect agent config provider/model: {}", + result.output + ); + } diff --git a/src/tools/mod.rs b/src/tools/mod.rs index 8dcdbdb30..733d3c5ac 100644 --- a/src/tools/mod.rs +++ b/src/tools/mod.rs @@ -64,7 +64,6 @@ pub mod message_send; pub mod nodes; pub mod prompt; pub mod proxy_config; -pub mod prx_message; pub mod pushover; pub mod schema; pub mod session_status; @@ -1202,6 +1201,7 @@ mod tests { let agents = HashMap::from([( "schema-audit".to_string(), DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), approval_wait_secs: 600, limits: crate::config::AgentLimits::default(), provider: "ollama".to_string(), @@ -1325,6 +1325,7 @@ mod tests { agents.insert( "researcher".to_string(), DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), approval_wait_secs: 600, limits: crate::config::AgentLimits::default(), provider: "ollama".to_string(), @@ -1409,6 +1410,7 @@ mod tests { let agents = HashMap::from([( "a".to_string(), DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), approval_wait_secs: 600, limits: crate::config::AgentLimits::default(), provider: "litellm".to_string(), diff --git a/src/tools/prx_message.rs b/src/tools/prx_message.rs deleted file mode 100644 index 993699104..000000000 --- a/src/tools/prx_message.rs +++ /dev/null @@ -1,59 +0,0 @@ -//! Dormant sender-only tool. No tool factory registers this constructor. -use super::traits::{Tool, ToolCategory, ToolResult}; -use crate::messaging::mailbox::MailboxError; -use crate::messaging::send::{MailboxSender, parse_target, send_result, target_schema}; -use async_trait::async_trait; -use serde_json::{Value, json}; -use std::sync::Arc; - -pub struct PrxMessageTool { - sender: Arc, -} -impl PrxMessageTool { - pub fn new(sender: Arc) -> Self { - Self { sender } - } -} -#[async_trait] -impl Tool for PrxMessageTool { - fn name(&self) -> &str { - "prx_message" - } - fn description(&self) -> &str { - "Send one Data message to a session mailbox." - } - fn categories(&self) -> &'static [ToolCategory] { - &[ToolCategory::Communication] - } - fn parameters_schema(&self) -> Value { - json!({"type":"object","additionalProperties":false,"properties":{"to":target_schema(),"text":{"type":"string","minLength":1,"maxLength":crate::messaging::MAX_BODY_BYTES},"mime":{"type":"string","enum":["text/plain","text/markdown"],"default":"text/plain"}},"required":["to","text"]}) - } - async fn execute(&self, args: Value) -> anyhow::Result { - let object = args.as_object().ok_or(MailboxError::InvalidMetadata)?; - if object.keys().any(|key| !matches!(key.as_str(), "to" | "text" | "mime")) { - return Err(MailboxError::InvalidMetadata.into()); - } - let target = parse_target( - object.get("to").ok_or(MailboxError::InvalidAddress)?, - self.sender.source(), - )?; - let text = object - .get("text") - .and_then(Value::as_str) - .filter(|text| !text.is_empty()) - .ok_or(MailboxError::InvalidMetadata)?; - let mime = match object.get("mime") { - None => "text/plain", - Some(Value::String(mime)) if matches!(mime.as_str(), "text/plain" | "text/markdown") => mime, - _ => return Err(MailboxError::InvalidMime.into()), - }; - let result = self.sender.send(target, text.to_owned(), mime.to_owned()).await; - let success = result.is_ok(); - let error = result.as_ref().err().map(ToString::to_string); - Ok(ToolResult { - success, - output: send_result(result).to_string(), - error, - }) - } -} diff --git a/src/tools/session_status.rs b/src/tools/session_status.rs index b02c0069d..b16e24882 100644 --- a/src/tools/session_status.rs +++ b/src/tools/session_status.rs @@ -194,6 +194,24 @@ impl Tool for SessionStatusTool { output.push_str(&delegation.join("\n")); } + if self.memory.as_ref().is_some_and(|memory| memory.name() == "sqlite") + && !self.workspace_id.is_empty() + && let Some(caller) = crate::tools::execution::current_child_call_context() + { + caller.verify_tool("session_status")?; + let owner = caller.context().envelope.resolved_owner_id(); + let session = caller.context().envelope.session_key.clone(); + let workspace = self.workspace_id.clone(); + let rows = crate::runtime::blocking::spawn_blocking(move || { + crate::memory::SqliteMemory::new(std::path::Path::new(&workspace))? + .mailbox_send_status(&workspace, &owner, &session) + }) + .await??; + if !rows.is_empty() { + output.push_str("\nMessage outbox: "); + output.push_str(&serde_json::to_string(&rows)?); + } + } Ok(ToolResult { success: true, output, diff --git a/src/tools/sessions_send.rs b/src/tools/sessions_send.rs index c1f8c0572..04072dc6e 100644 --- a/src/tools/sessions_send.rs +++ b/src/tools/sessions_send.rs @@ -17,6 +17,7 @@ use tokio::sync::RwLock; /// Tool that sends a message to a running sub-agent session to redirect it. pub struct SessionsSendTool { + messaging: Option>, mailbox: Option>, active_runs: Arc>>, security: Arc, @@ -32,6 +33,7 @@ impl SessionsSendTool { pub fn with_security(active_runs: Arc>>, security: Arc) -> Self { Self { + messaging: None, mailbox: None, active_runs, security, @@ -40,6 +42,10 @@ impl SessionsSendTool { event_recording: MemoryEventRecording::default(), } } + pub fn with_messaging(mut self, config: &crate::config::Config) -> Self { + self.messaging = Some(Arc::new(config.clone())); + self + } /// Opt-in only; activation owns registration of the address-based schema. pub fn with_mailbox(mut self, sender: Arc) -> Self { @@ -119,10 +125,10 @@ impl Tool for SessionsSendTool { } fn parameters_schema(&self) -> serde_json::Value { - if self.mailbox.is_some() { + if self.mailbox.is_some() || self.messaging.is_some() { return json!({"oneOf":[ {"type":"object","additionalProperties":false,"properties":{"run_id":{"type":"string","minLength":1},"message":{"type":"string","minLength":1}},"required":["run_id","message"]}, - {"type":"object","additionalProperties":false,"properties":{"to":crate::messaging::send::target_schema(),"message":{"type":"string","minLength":1}},"required":["to","message"]} + {"type":"object","additionalProperties":false,"properties":{"to":{"oneOf":[crate::messaging::send::target_schema(),{"type":"string","minLength":1}]},"message":{"type":"string","minLength":1}},"required":["to","message"]} ]}); } json!({ @@ -145,16 +151,28 @@ impl Tool for SessionsSendTool { async fn execute(&self, args: serde_json::Value) -> anyhow::Result { if args.get("to").is_some() { + if let Some(config) = &self.messaging { + let runtime = crate::messaging::runtime::MessagingRuntime::for_config(config)?; + return self.send_message(&runtime, &args).await; + } use crate::messaging::{ mailbox::MailboxError, send::{parse_target, send_result}, }; let sender = self.mailbox.as_ref().ok_or(MailboxError::Unauthorized)?; let object = args.as_object().ok_or(MailboxError::InvalidMetadata)?; - if object.keys().any(|key| !matches!(key.as_str(), "to" | "message")) { + if object + .keys() + .any(|key| !matches!(key.as_str(), "to" | "message") && !key.starts_with("_zc_")) + { return Err(MailboxError::InvalidMetadata.into()); } - let target = parse_target(args.get("to").ok_or(MailboxError::InvalidAddress)?, sender.source())?; + let value = args.get("to").ok_or(MailboxError::InvalidAddress)?; + let target = if let Some(alias) = value.as_str() { + crate::messaging::SessionAddr::new(&sender.source().instance, &sender.source().owner, alias, None) + } else { + parse_target(value, sender.source())? + }; let message = args .get("message") .and_then(serde_json::Value::as_str) @@ -283,6 +301,65 @@ impl Tool for SessionsSendTool { } } +impl SessionsSendTool { + async fn send_message( + &self, + runtime: &Arc, + args: &serde_json::Value, + ) -> anyhow::Result { + use crate::messaging::send::MailboxSender; + let caller = crate::tools::execution::current_child_call_context() + .ok_or(crate::messaging::mailbox::MailboxError::Unauthorized)?; + caller.verify_tool("sessions_send")?; + anyhow::ensure!(args.get("run_id").is_none(), "exactly one of run_id and to is required"); + let context = caller.context(); + let source = runtime.address( + &context.envelope.resolved_owner_id(), + &context.envelope.session_key, + context.envelope.agent_id.as_deref().unwrap_or("main"), + ); + let mut target = args + .get("to") + .cloned() + .ok_or(crate::messaging::mailbox::MailboxError::InvalidAddress)?; + if let Some(alias) = target.as_str() { + let runs = self.active_runs.read().await; + let run = alias + .strip_prefix('#') + .and_then(|index| index.parse::().ok()) + .map_or_else( + || { + runs.iter().find(|run| { + run.owner_id.as_deref() == Some(source.owner.as_str()) + && (run.id == alias || run.session_scope_key == alias) + }) + }, + |index| { + runs.iter() + .filter(|run| run.owner_id.as_deref() == Some(source.owner.as_str())) + .nth(index.checked_sub(1).unwrap_or(usize::MAX)) + }, + ); + if let Some(run) = run { + target = serde_json::json!({"session":run.session_scope_key,"agent":run.agent_partition.as_ref().map_or("main",|partition| match &partition.key {crate::memory::PartitionKey::Main=>"main",crate::memory::PartitionKey::Named{name,..}=>name.as_str()})}); + } + } + let target = runtime.alias(&source, &target)?; + let text = args + .get("message") + .and_then(serde_json::Value::as_str) + .filter(|text| !text.is_empty()) + .ok_or(crate::messaging::mailbox::MailboxError::InvalidMetadata)?; + let sender = runtime.bind(source, context.envelope.source_message_event_id.as_deref())?; + let result = sender.send(target, text.into(), "text/plain".into()).await; + Ok(ToolResult { + success: result.is_ok(), + error: result.as_ref().err().map(ToString::to_string), + output: crate::messaging::send::send_result(result).to_string(), + }) + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/tools/sessions_spawn/child_lifecycle.rs b/src/tools/sessions_spawn/child_lifecycle.rs index 90ea0456c..d9074cff9 100644 --- a/src/tools/sessions_spawn/child_lifecycle.rs +++ b/src/tools/sessions_spawn/child_lifecycle.rs @@ -61,6 +61,7 @@ pub(super) async fn pump_worker_control_frames( history: Arc>>, run_id: String, ) { + use tokio::io::AsyncWriteExt as _; let mut steer_open = true; let mut controls_open = controls.is_some(); while steer_open || controls_open { @@ -76,7 +77,19 @@ pub(super) async fn pump_worker_control_frames( let Some(frame) = frame else { continue; }; - if let Err(error) = crate::session_worker::frames::write_control_frame(&mut stdin, &frame).await { + let write = async { + if let Some(auth) = controls.as_ref().and_then(|q| q.auth.as_ref()) { + let value = auth.sign(&frame)?; + stdin.write_all(&serde_json::to_vec(&value)?).await?; + stdin.write_all(b"\n").await?; + stdin.flush().await?; + Ok::<(), anyhow::Error>(()) + } else { + crate::session_worker::frames::write_control_frame(&mut stdin, &frame).await + } + } + .await; + if let Err(error) = write { tracing::debug!(%run_id,"sub-agent control pipe closed: {error}"); return; } @@ -151,6 +164,10 @@ pub(super) async fn run_spawned_child_lifecycle( ) -> anyhow::Result { use tokio::io::AsyncWriteExt; + let frame_auth = steer + .as_ref() + .and_then(|pipe| pipe.frames.as_ref()) + .and_then(|frames| frames.controls.auth.clone()); let frame_outputs = steer .as_ref() .and_then(|pipe| pipe.frames.as_ref().map(|frames| frames.outputs.clone())); @@ -224,11 +241,12 @@ pub(super) async fn run_spawned_child_lifecycle( .take() .ok_or_else(|| anyhow::anyhow!("session-worker stderr pipe was not configured"))?; - let stdout_task = tokio::spawn(crate::session_worker::frames::read_worker_frames( + let stdout_task = tokio::spawn(crate::session_worker::frames::read_worker_frames_authenticated( stdout_stream, frame_outputs, progress.as_ref().map(Arc::clone), MAX_SUBPROCESS_OUTPUT, + frame_auth, )); let stderr_task = tokio::spawn(drain_worker_stream( stderr_stream, diff --git a/src/tools/sessions_spawn/continuation.rs b/src/tools/sessions_spawn/continuation.rs index 8594372f5..1a34d51ea 100644 --- a/src/tools/sessions_spawn/continuation.rs +++ b/src/tools/sessions_spawn/continuation.rs @@ -100,7 +100,16 @@ impl SessionsSpawnTool { )), "child_session_busy" ); - let history = store.history(&record)?; + let mut history = store.history(&record)?; + if let Some(input) = operator.as_ref().and_then(|source| source.message_input()) { + anyhow::ensure!( + history + .last() + .is_some_and(|turn| turn.role == "user" && turn.content == input.text), + "adopted input is not the pending child turn" + ); + history.pop(); + } let mut launch = args.clone(); let object = launch .as_object_mut() diff --git a/src/tools/sessions_spawn/events.rs b/src/tools/sessions_spawn/events.rs index 9a2c5363f..cd88d0a9a 100644 --- a/src/tools/sessions_spawn/events.rs +++ b/src/tools/sessions_spawn/events.rs @@ -84,7 +84,7 @@ pub(super) async fn record_spawn_request_event( .ok_or_else(|| anyhow::anyhow!("child parent session missing"))?; let mut runs = super::continuation::current().map_or_else(Vec::new, |seed| seed.record.runs); runs.push(run.to_owned()); - metadata["child_session_record"] = serde_json::to_value(crate::memory::child_sessions::ChildSessionRecord { + let record = serde_json::to_value(crate::memory::child_sessions::ChildSessionRecord { workspace: fabric.workspace_id().to_owned(), owner: scope .owner_id @@ -108,6 +108,10 @@ pub(super) async fn record_spawn_request_event( context_after: 0, context: Vec::new(), })?; + metadata + .as_object_mut() + .ok_or_else(|| anyhow::anyhow!("child metadata must be an object"))? + .insert("child_session_record".into(), record); let receipt = crate::runtime::child_source::record_child_input(fabric, scope, task, None, Some(metadata.to_string())).await?; delegation::append_task(&mut metadata, task)?; diff --git a/src/tools/sessions_spawn/spawn.rs b/src/tools/sessions_spawn/spawn.rs index 75bf8133a..a1685a3e6 100644 --- a/src/tools/sessions_spawn/spawn.rs +++ b/src/tools/sessions_spawn/spawn.rs @@ -155,6 +155,8 @@ impl SessionsSpawnTool { if let Some(source) = &operator_source { source.verify_live()?; } + let message_input = crate::runtime::operator_spawn::current().and_then(|source| source.message_input()); + let message_permit = operator_source.as_ref().and_then(|source| source.message_permit()); let caller = crate::tools::execution::current_child_call_context(); if let Some(caller) = &caller { caller.verify_tool("sessions_spawn")?; @@ -338,12 +340,19 @@ impl SessionsSpawnTool { // so it is a Medium-risk side effect (requires an approval grant under // supervised autonomy; denied outright under read-only) rather than Low. let approval_grant = ApprovalGrant::from_runtime_args(self.name(), args); - if let Err(error) = SideEffectGate::new(launch_security.as_ref()).authorize_resource_operation( - self.name(), - "sessions_spawn:spawn", - ResourceRiskLevel::Medium, - approval_grant.as_ref(), - ) { + if let Err(error) = if operator_source + .as_ref() + .is_some_and(|source| source.is_message_continuation()) + { + Ok(ResourceRiskLevel::Medium) + } else { + SideEffectGate::new(launch_security.as_ref()).authorize_resource_operation( + self.name(), + "sessions_spawn:spawn", + ResourceRiskLevel::Medium, + approval_grant.as_ref(), + ) + } { return Ok(SpawnOutcome::rejected(error)); } @@ -1029,7 +1038,18 @@ impl SessionsSpawnTool { } else { None }; - let process_worker_mailbox = self.worker_mailbox.clone(); + let process_worker_mailbox = if let Some(factory) = &self.worker_mailbox { + Some(factory.clone()) + } else if let Some(config) = self + .hint_config + .as_ref() + .filter(|config| config.memory.backend == "sqlite") + { + Some(crate::messaging::worker::WorkerMailboxes::for_config(config)? + as Arc) + } else { + None + }; let process_batch_id = batch_id.map(str::to_owned); #[cfg(test)] let test_worker_executable = self.test_worker_executable.clone(); @@ -1044,6 +1064,8 @@ impl SessionsSpawnTool { SPAWN_EXECUTION_CONTEXT.scope( process_execution_ctx, crate::agent::idle::scope_beat(Some(Arc::clone(&monitor_progress)), async move { + let _message_permit=message_permit; + let _message_input=message_input; async { tracing::info!(run_id = %rid, "Sub-agent process starting"); @@ -1686,6 +1708,8 @@ impl SessionsSpawnTool { let jh = crate::agent::channel_approval::spawn(crate::runtime::registry::scope_current( sub_agent_work_id, SPAWN_EXECUTION_CONTEXT.scope(task_execution_ctx, async move { + let _message_permit = message_permit; + let _message_input = message_input; tracing::info!(run_id = %rid, "Sub-agent task starting"); let provider_started_at = Utc::now(); let (run_on_delta, run_on_tool) = match run_event_streams { diff --git a/src/tools/sessions_spawn/task_mode.rs b/src/tools/sessions_spawn/task_mode.rs index ec543ccb0..bfd2d266c 100644 --- a/src/tools/sessions_spawn/task_mode.rs +++ b/src/tools/sessions_spawn/task_mode.rs @@ -232,13 +232,10 @@ pub(super) async fn run_sub_agent_task( .read() .await .iter() - .map(|entry| ChatMessage { - role: entry.role.clone(), - content: entry.content.clone(), - }) + .map(|entry| crate::agent::turn_contracts::stored_turn_message(entry.role.clone(), entry.content.clone())) .collect(); if !history.is_empty() { - history.push(ChatMessage::user(task)); + history.push(crate::agent::turn_contracts::inbound_user_message(task)); } // NeedsInput: deterministically restore a suspended run to `Running` before diff --git a/src/tools/sessions_spawn/tests/credential_containment.rs b/src/tools/sessions_spawn/tests/credential_containment.rs index 943963220..bd663cf7d 100644 --- a/src/tools/sessions_spawn/tests/credential_containment.rs +++ b/src/tools/sessions_spawn/tests/credential_containment.rs @@ -9,6 +9,7 @@ const SPAWN_ROOT_SENTINEL: &str = "C0-SPAWN-ROOT-SENTINEL"; fn containment_agent(provider: &str, api_key: Option<&str>) -> DelegateAgentConfig { DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), approval_wait_secs: 600, limits: crate::config::AgentLimits::default(), provider: provider.to_string(), diff --git a/src/tools/sessions_spawn/tests/mod.rs b/src/tools/sessions_spawn/tests/mod.rs index 69896dfba..6e2fa34cc 100644 --- a/src/tools/sessions_spawn/tests/mod.rs +++ b/src/tools/sessions_spawn/tests/mod.rs @@ -532,6 +532,7 @@ impl crate::providers::Provider for EchoSystemProvider { fn make_agent_config(identity_dir: Option) -> DelegateAgentConfig { DelegateAgentConfig { + messaging: crate::config::schema::AgentMessaging::default(), approval_wait_secs: 600, limits: crate::config::AgentLimits::default(), provider: "ollama".to_string(), diff --git a/tests/architecture_boundaries/config.rs b/tests/architecture_boundaries/config.rs index 83a49a2ca..3abb9d31f 100644 --- a/tests/architecture_boundaries/config.rs +++ b/tests/architecture_boundaries/config.rs @@ -87,7 +87,8 @@ fn daemon_owned_components_do_not_reload_process_config_from_disk() { #[test] fn gateway_and_channels_have_one_shared_config_owner() { - let gateway = fs::read_to_string(repository_root().join("src/gateway/mod.rs")).expect("read src/gateway/mod.rs"); + let gateway = fs::read_to_string(repository_root().join("src/gateway/implementation/section_1.rs")) + .expect("read src/gateway/mod.rs"); let app_state_start = gateway.find("pub struct AppState").expect("AppState"); let app_state = &gateway[app_state_start ..gateway[app_state_start..] @@ -142,7 +143,7 @@ fn every_config_reload_entrypoint_routes_through_generation_manager() { ), ("src/config/manage/transaction.rs", "manager.reload_from_disk(trigger)"), ( - "src/gateway/mod.rs", + "src/gateway/implementation/section_2.rs", "reload_from_disk(crate::config::ConfigReloadTrigger::PairingPersistence)", ), ] { diff --git a/tests/architecture_boundaries/helpers.rs b/tests/architecture_boundaries/helpers.rs index 65c4a7dd4..a0d469de7 100644 --- a/tests/architecture_boundaries/helpers.rs +++ b/tests/architecture_boundaries/helpers.rs @@ -39,6 +39,50 @@ pub(super) fn rust_source_files() -> Vec { } } }); + files.retain(|path| { + ![ + "src/config/secret_paths/tests/section_1.rs", + "src/config/secret_paths/tests/section_2.rs", + "src/config/generation/section_1.rs", + "src/config/generation/section_2.rs", + "src/chat/provider_turns/section_1.rs", + "src/chat/provider_turns/section_2.rs", + "src/gateway/api/sessions/section_1.rs", + "src/gateway/api/sessions/section_2.rs", + "src/gateway/api/sessions/section_3.rs", + "src/chat/tests/p3_directional_switch_tests/section_1.rs", + "src/chat/tests/p3_directional_switch_tests/section_2.rs", + "src/chat/tests/p3_directional_switch_tests/section_3.rs", + "src/main/section_1.rs", + "src/main/section_2.rs", + "src/main/section_3.rs", + "src/chat/run/event_pump.rs", + "src/chat/run/commands.rs", + "src/chat/run/provider_turn.rs", + "src/doctor/implementation/section_1.rs", + "src/doctor/implementation/section_2.rs", + "src/doctor/tests/section_1.rs", + "src/doctor/tests/section_2.rs", + "src/gateway/implementation/section_1.rs", + "src/gateway/implementation/section_2.rs", + "src/gateway/implementation/section_3.rs", + "src/gateway/api/sessions/tests/targeting/section_1.rs", + "src/gateway/api/sessions/tests/targeting/section_2.rs", + "src/chat/sessions/assignment/section_1.rs", + "src/chat/sessions/assignment/section_2.rs", + "src/memory/sqlite/events/section_1.rs", + "src/memory/sqlite/events/section_2.rs", + "src/memory/sqlite/events/section_3.rs", + "src/memory/sqlite/tests/mailbox/section_1.rs", + "src/memory/sqlite/tests/mailbox/section_2.rs", + "src/memory/sqlite/tests/mailbox/section_3.rs", + "src/tools/capability/catalog/section_1.rs", + "src/tools/capability/catalog/section_2.rs", + "src/tools/delegate/tests/section_1.rs", + "src/tools/delegate/tests/section_2.rs", + ] + .contains(&relative_path(path).as_str()) + }); files.sort(); files } @@ -53,7 +97,64 @@ pub(super) fn read_source(path: &Path) -> String { .find(|(planted_path, _)| *planted_path == relative) .map(|(_, text)| text.clone()) }); - planted.unwrap_or_else(|| fs::read_to_string(path).unwrap_or_else(|error| panic!("read {relative}: {error}"))) + let mut source = + planted.unwrap_or_else(|| fs::read_to_string(path).unwrap_or_else(|error| panic!("read {relative}: {error}"))); + for (owner, included) in [ + ("src/config/secret_paths/tests.rs", "tests/section_1.rs"), + ("src/config/secret_paths/tests.rs", "tests/section_2.rs"), + ("src/config/generation.rs", "generation/section_1.rs"), + ("src/config/generation.rs", "generation/section_2.rs"), + ("src/chat/provider_turns.rs", "provider_turns/section_1.rs"), + ("src/chat/provider_turns.rs", "provider_turns/section_2.rs"), + ("src/gateway/api/sessions.rs", "sessions/section_1.rs"), + ("src/gateway/api/sessions.rs", "sessions/section_2.rs"), + ("src/gateway/api/sessions.rs", "sessions/section_3.rs"), + ( + "src/chat/tests/p3_directional_switch_tests.rs", + "p3_directional_switch_tests/section_1.rs", + ), + ( + "src/chat/tests/p3_directional_switch_tests.rs", + "p3_directional_switch_tests/section_2.rs", + ), + ( + "src/chat/tests/p3_directional_switch_tests.rs", + "p3_directional_switch_tests/section_3.rs", + ), + ("src/main.rs", "main/section_1.rs"), + ("src/main.rs", "main/section_2.rs"), + ("src/main.rs", "main/section_3.rs"), + ("src/chat/run.rs", "run/event_pump.rs"), + ("src/chat/run.rs", "run/commands.rs"), + ("src/chat/run.rs", "run/provider_turn.rs"), + ("src/doctor/mod.rs", "implementation/section_1.rs"), + ("src/doctor/mod.rs", "implementation/section_2.rs"), + ("src/doctor/tests.rs", "tests/section_1.rs"), + ("src/doctor/tests.rs", "tests/section_2.rs"), + ("src/gateway/mod.rs", "implementation/section_1.rs"), + ("src/gateway/mod.rs", "implementation/section_2.rs"), + ("src/gateway/mod.rs", "implementation/section_3.rs"), + ("src/gateway/api/sessions/tests/targeting.rs", "targeting/section_1.rs"), + ("src/gateway/api/sessions/tests/targeting.rs", "targeting/section_2.rs"), + ("src/chat/sessions/assignment.rs", "assignment/section_1.rs"), + ("src/chat/sessions/assignment.rs", "assignment/section_2.rs"), + ("src/memory/sqlite/events.rs", "events/section_1.rs"), + ("src/memory/sqlite/events.rs", "events/section_2.rs"), + ("src/memory/sqlite/events.rs", "events/section_3.rs"), + ("src/memory/sqlite/tests/mailbox.rs", "mailbox/section_1.rs"), + ("src/memory/sqlite/tests/mailbox.rs", "mailbox/section_2.rs"), + ("src/memory/sqlite/tests/mailbox.rs", "mailbox/section_3.rs"), + ("src/tools/capability/catalog.rs", "catalog/section_1.rs"), + ("src/tools/capability/catalog.rs", "catalog/section_2.rs"), + ("src/tools/delegate/tests.rs", "tests/section_1.rs"), + ("src/tools/delegate/tests.rs", "tests/section_2.rs"), + ] { + if relative == owner { + let included_path = path.parent().expect("source directory").join(included); + source = source.replace(&format!("include!(\"{included}\")"), &read_source(&included_path)); + } + } + source } /// Every Rust file the repository owns: the crate sources and the integration @@ -62,6 +163,50 @@ pub(super) fn rust_source_and_test_files() -> Vec { let mut files = Vec::new(); collect_rust_files(&repository_root().join("src"), &mut files); collect_rust_files(&repository_root().join("tests"), &mut files); + files.retain(|path| { + ![ + "src/config/secret_paths/tests/section_1.rs", + "src/config/secret_paths/tests/section_2.rs", + "src/config/generation/section_1.rs", + "src/config/generation/section_2.rs", + "src/chat/provider_turns/section_1.rs", + "src/chat/provider_turns/section_2.rs", + "src/gateway/api/sessions/section_1.rs", + "src/gateway/api/sessions/section_2.rs", + "src/gateway/api/sessions/section_3.rs", + "src/chat/tests/p3_directional_switch_tests/section_1.rs", + "src/chat/tests/p3_directional_switch_tests/section_2.rs", + "src/chat/tests/p3_directional_switch_tests/section_3.rs", + "src/main/section_1.rs", + "src/main/section_2.rs", + "src/main/section_3.rs", + "src/chat/run/event_pump.rs", + "src/chat/run/commands.rs", + "src/chat/run/provider_turn.rs", + "src/doctor/implementation/section_1.rs", + "src/doctor/implementation/section_2.rs", + "src/doctor/tests/section_1.rs", + "src/doctor/tests/section_2.rs", + "src/gateway/implementation/section_1.rs", + "src/gateway/implementation/section_2.rs", + "src/gateway/implementation/section_3.rs", + "src/gateway/api/sessions/tests/targeting/section_1.rs", + "src/gateway/api/sessions/tests/targeting/section_2.rs", + "src/chat/sessions/assignment/section_1.rs", + "src/chat/sessions/assignment/section_2.rs", + "src/memory/sqlite/events/section_1.rs", + "src/memory/sqlite/events/section_2.rs", + "src/memory/sqlite/events/section_3.rs", + "src/memory/sqlite/tests/mailbox/section_1.rs", + "src/memory/sqlite/tests/mailbox/section_2.rs", + "src/memory/sqlite/tests/mailbox/section_3.rs", + "src/tools/capability/catalog/section_1.rs", + "src/tools/capability/catalog/section_2.rs", + "src/tools/delegate/tests/section_1.rs", + "src/tools/delegate/tests/section_2.rs", + ] + .contains(&relative_path(path).as_str()) + }); files.sort(); files } diff --git a/tests/architecture_boundaries/loop_contracts.rs b/tests/architecture_boundaries/loop_contracts.rs index 98f9db32b..77550c4e6 100644 --- a/tests/architecture_boundaries/loop_contracts.rs +++ b/tests/architecture_boundaries/loop_contracts.rs @@ -826,7 +826,8 @@ fn tool_arguments_are_schema_validated_on_the_production_execution_path() { #[test] fn the_gateway_webhook_turn_seeds_its_spawn_boundary() { let root = repository_root(); - let gateway = fs::read_to_string(root.join("src/gateway/mod.rs")).expect("read src/gateway/mod.rs"); + let gateway = + fs::read_to_string(root.join("src/gateway/implementation/section_2.rs")).expect("read src/gateway/mod.rs"); let production = strip_cfg_test_items(&gateway); let production = production.as_str(); diff --git a/tests/architecture_boundaries/loop_prompt.rs b/tests/architecture_boundaries/loop_prompt.rs index 066e09451..6de68bc8a 100644 --- a/tests/architecture_boundaries/loop_prompt.rs +++ b/tests/architecture_boundaries/loop_prompt.rs @@ -196,9 +196,9 @@ fn production_tool_loop_memory_is_wired_to_request_context_events() { for relative in [ "src/agent/entry.rs", "src/channels/turn.rs", - "src/chat/run.rs", - "src/gateway/api/sessions.rs", - "src/gateway/mod.rs", + "src/chat/run/provider_turn.rs", + "src/gateway/api/sessions/section_1.rs", + "src/gateway/implementation/section_2.rs", "src/session_worker/runner/run.rs", "src/tools/delegate.rs", "src/tools/sessions_spawn/task_mode.rs", diff --git a/tests/architecture_boundaries/memory.rs b/tests/architecture_boundaries/memory.rs index 3c008d840..13bb446da 100644 --- a/tests/architecture_boundaries/memory.rs +++ b/tests/architecture_boundaries/memory.rs @@ -55,11 +55,11 @@ const ALLOWED_BRAIN_DB_OPENS_OUTSIDE_SQLITE_REPOSITORY: &[&str] = &[ "src/memory/sqlite/ingress_recovery.rs::inspect_unsettled_ingress::let connection = Connection::open_with_flags(&canonical, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?;", // D-107 amendment: the doctor reads the cron and Xin stores read-only. "src/doctor/mod.rs::read_only_unowned_rows::let connection = rusqlite::Connection::open_with_flags(db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?;", - "src/doctor/mod.rs::doctor_names_shell_jobs_without_a_recorded_creator::rusqlite::Connection::open(&db_path)", + "src/doctor/tests.rs::doctor_names_shell_jobs_without_a_recorded_creator::rusqlite::Connection::open(&db_path)", "src/doctor/mod.rs::read_only_sqlite_session_count::let conn = rusqlite::Connection::open_with_flags(db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?;", // Test-only legacy rows intentionally bypass the new public write guard so // the migration and doctor can prove they repair pre-guard data. - "src/doctor/mod.rs::doctor_reports_legacy_fitness_counts_and_repair_command::let connection = rusqlite::Connection::open(config.workspace_dir.join(\"memory/brain.db\")).unwrap();", + "src/doctor/tests.rs::doctor_reports_legacy_fitness_counts_and_repair_command::let connection = rusqlite::Connection::open(config.workspace_dir.join(\"memory/brain.db\")).unwrap();", "src/fitness_cli.rs::migration_exports_then_removes_legacy_rows_and_projections::let connection = rusqlite::Connection::open(db_path).unwrap();", // Test-only, read-only (V02-R9): the handler refusal test must prove that a // refused `memory_store` left the victim row's `owner_id` unchanged and wrote @@ -260,7 +260,7 @@ fn brain_db_is_not_opened_outside_the_sqlite_repository() { } } let source = read_source(&path); - if !source.contains("brain.db") { + if !source.contains("brain.db") && relative != "src/doctor/mod.rs" { continue; } let lines = source.lines().collect::>(); diff --git a/tests/architecture_boundaries/panic_policy.rs b/tests/architecture_boundaries/panic_policy.rs index bf21da116..526f60444 100644 --- a/tests/architecture_boundaries/panic_policy.rs +++ b/tests/architecture_boundaries/panic_policy.rs @@ -273,7 +273,7 @@ const CATCH_UNWIND_FILES: &[&str] = &[ "src/providers/label_redaction_tests.rs", "src/runtime/decision_accounting/transport_tests.rs", "src/runtime/h2_entry/authority/tests.rs", - "src/tools/delegate.rs", + "src/tools/delegate/tests.rs", "src/tools/delegate_diagnostic.rs", "src/tools/sessions_spawn/tests/lineage.rs", "src/tools/sessions_spawn/tests/owned_child.rs", diff --git a/tests/architecture_boundaries/process.rs b/tests/architecture_boundaries/process.rs index 68527d8f2..95e041282 100644 --- a/tests/architecture_boundaries/process.rs +++ b/tests/architecture_boundaries/process.rs @@ -214,7 +214,7 @@ fn workspace_hooks_launch_through_the_shared_builder_behind_the_opt_in() { #[test] fn every_live_hook_manager_owner_drains_at_shutdown() { for path in [ - "src/gateway/mod.rs", + "src/gateway/implementation/section_2.rs", "src/channels/startup.rs", "src/chat/run.rs", "src/agent/entry.rs", diff --git a/tests/architecture_boundaries/scanner_probes.rs b/tests/architecture_boundaries/scanner_probes.rs index ff38fd426..d7fb6fd28 100644 --- a/tests/architecture_boundaries/scanner_probes.rs +++ b/tests/architecture_boundaries/scanner_probes.rs @@ -811,7 +811,7 @@ fn mutation_proof_compaction_producer_guard() { ), ("src/chat/run/entry.rs", " Some(producer),", " None,"), ( - "src/chat/run.rs", + "src/chat/run/provider_turn.rs", "compaction_config: Some(effective_compaction.config.clone())", "compaction_config: Some(config.agent.compaction.clone())", ), @@ -841,12 +841,12 @@ fn mutation_proof_compaction_producer_guard() { fn mutation_proof_gateway_registration_guard() { for (path, old, new) in [ ( - "src/gateway/mod.rs", + "src/gateway/implementation/section_2.rs", "run_gateway_inner(host, port, config, shared_config, shutdown, None).await", "Ok(())", ), ( - "src/gateway/mod.rs", + "src/gateway/implementation/section_2.rs", "let (channels_registry, spawn_tools_handle) = register_gateway_turn_tools(", "let (channels_registry, spawn_tools_handle) = unreviewed_gateway_turn_tools(", ), diff --git a/tests/architecture_boundaries/tool_tables.rs b/tests/architecture_boundaries/tool_tables.rs index e800fa3b7..fe5233235 100644 --- a/tests/architecture_boundaries/tool_tables.rs +++ b/tests/architecture_boundaries/tool_tables.rs @@ -357,9 +357,14 @@ pub(super) const ALLOWED_DIRECT_TOOL_INVOCATIONS: &[(&str, usize, &str)] = &[ 1, "operator-typed `/kill`; the human at the keyboard is the authority", ), + ( + "src/chat/child_focus.rs::execute_source", + 1, + "operator input in child focus; admitted by the same captured local operator source", + ), ( "src/chat/run.rs::run_internal", - 4, + 3, "operator-typed `/spawn`, `/steer` and `!command`; the human at the keyboard is the \ authority", ), diff --git a/tests/int_memory_delegate.rs b/tests/int_memory_delegate.rs index a3bcac049..666185c16 100644 --- a/tests/int_memory_delegate.rs +++ b/tests/int_memory_delegate.rs @@ -209,6 +209,7 @@ async fn int_das_01_delegate_inherits_parent_security_policy() { agents.insert( "researcher".to_string(), DelegateAgentConfig { + messaging: openprx::config::schema::AgentMessaging::default(), approval_wait_secs: 600, limits: openprx::config::AgentLimits::default(), provider: "test".to_string(), @@ -405,6 +406,7 @@ async fn int_das_02_delegate_respects_max_depth() { agents.insert( "deep-agent".to_string(), DelegateAgentConfig { + messaging: openprx::config::schema::AgentMessaging::default(), approval_wait_secs: 600, limits: openprx::config::AgentLimits::default(), provider: "test".to_string(), @@ -677,6 +679,7 @@ async fn admitted_delegate_under_depth_reports_unsupported_provider() -> anyhow: agents.insert( "prx_depth_agent".to_string(), DelegateAgentConfig { + messaging: openprx::config::schema::AgentMessaging::default(), approval_wait_secs: 600, limits: openprx::config::AgentLimits::default(), provider: "test".to_string(), From 43f4c459402191b019a69b6a3aa6c5c8eb3541a0 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 15:07:17 +0400 Subject: [PATCH 0003/1567] fix(messaging): drive gateway receivers and update cookie security patch --- src/gateway/implementation/section_2.rs | 18 ++++++ src/gateway/mailbox.rs | 78 +++++++++++++++++++++++++ src/gateway/mod.rs | 1 + 3 files changed, 97 insertions(+) create mode 100644 src/gateway/mailbox.rs diff --git a/src/gateway/implementation/section_2.rs b/src/gateway/implementation/section_2.rs index 4649e56ae..c23438945 100644 --- a/src/gateway/implementation/section_2.rs +++ b/src/gateway/implementation/section_2.rs @@ -1034,6 +1034,23 @@ async fn run_gateway_chat_with_multimodal( Some(owner_id) => runtime_envelope.with_owner_id(owner_id), None => runtime_envelope, }; + let mut runtime_envelope = runtime_envelope; + let messaging = if config_snapshot.memory.backend == "sqlite" { + Some(crate::messaging::runtime::MessagingRuntime::for_config(&config_snapshot)?) + } else { + None + }; + let _mailbox_gate = if let Some(runtime) = &messaging { + let address = runtime.address( + &runtime_envelope.resolved_owner_id(), + &runtime_envelope.session_key, + runtime_envelope.agent_id.as_deref().unwrap_or("main"), + ); + runtime_envelope.source_message_event_id = mailbox::causation(runtime, &runtime_envelope)?; + Some(crate::messaging::receiver::gate(&address).lock_owned().await) + } else { + None + }; *stage = TurnFailureClass::ReplayLookup; if fabric.records_recovery_terminal() { if let Some(key) = fabric_ctx.idempotency_key.as_deref() { @@ -1083,6 +1100,7 @@ async fn run_gateway_chat_with_multimodal( .record(message.to_owned(), fabric_ctx.idempotency_key.clone()) .await?; let runtime_envelope = source_receipt.envelope().clone(); + mailbox::register(state, fabric_ctx, &runtime_envelope)?; let base_scope = runtime_envelope.message_scope(); *stage = TurnFailureClass::SourceBinding; let gateway_proof = source_receipt.bind(&turn_runtime, fabric_ctx)?; diff --git a/src/gateway/mailbox.rs b/src/gateway/mailbox.rs new file mode 100644 index 000000000..0a19bda25 --- /dev/null +++ b/src/gateway/mailbox.rs @@ -0,0 +1,78 @@ +//! Mailbox wakeups retain the actual gateway receiver's ingress identity. +use super::{AppState, GatewayFabricContext, TurnFailureClass, run_gateway_chat_with_multimodal}; +use crate::messaging::runtime::{MessageInput, MessagingRuntime}; +use std::sync::Arc; + +tokio::task_local! { static INPUT: MessageInput; } + +pub(super) fn causation( + runtime: &MessagingRuntime, + envelope: &crate::runtime::envelope::RuntimeEnvelope, +) -> anyhow::Result> { + INPUT + .try_with(|input| { + input.verify(runtime)?; + anyhow::ensure!( + input.auto_start() + && input.message.to.owner == envelope.resolved_owner_id() + && input.message.to.session == envelope.session_key + && input.message.to.agent == envelope.agent_id.as_deref().unwrap_or("main"), + "mailbox input differs from gateway receiver" + ); + Ok(input.receipt.adopted_message_event_id.map(|id| id.to_string())) + }) + .unwrap_or(Ok(None)) +} + +pub(super) fn register( + state: &AppState, + context: &GatewayFabricContext, + envelope: &crate::runtime::envelope::RuntimeEnvelope, +) -> anyhow::Result<()> { + let config = state.config.load_full(); + if config.memory.backend != "sqlite" { + return Ok(()); + } + let runtime = MessagingRuntime::for_config(&config)?; + let address = runtime.address( + &envelope.resolved_owner_id(), + &envelope.session_key, + envelope.agent_id.as_deref().unwrap_or("main"), + ); + let state = state.clone(); + let context = context.clone(); + crate::messaging::receiver::register( + runtime, + address, + Arc::new(move |input| { + let state = state.clone(); + let mut context = context.clone(); + // A message starts a fresh ingress; it never replays an HTTP request key. + context.idempotency_key = None; + Box::pin(async move { + let config = state.config.load_full(); + let _permit = + crate::runtime::agent_admission::wait(&config, &input.message.to.owner, &input.message.to.agent) + .await?; + let text = input.text.clone(); + INPUT + .scope(input, async { + let mut stage = TurnFailureClass::TurnNotReady; + // Normal gateway admission owns history, policy, costs and + // cleanup. Message data never enters the HTTP approval parser. + run_gateway_chat_with_multimodal( + &state, + crate::providers::selection::default_provider(&config), + &text, + &context, + None, + &mut stage, + ) + .await + .map(|_| ()) + }) + .await + }) + }), + ) +} diff --git a/src/gateway/mod.rs b/src/gateway/mod.rs index ac88f63a4..00abbd419 100644 --- a/src/gateway/mod.rs +++ b/src/gateway/mod.rs @@ -29,6 +29,7 @@ mod compat; mod h2_control; mod jobs; mod live_frames; +mod mailbox; #[cfg(test)] mod platform_test_transport; mod run_approvals; From 54e7e8bb324c55a24c086b6853d7e25b5f021e73 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 16:13:51 +0400 Subject: [PATCH 0004/1567] feat(sessions): admit mailbox child turns independently of ended parents --- docs/tools.md | 9 + src/chat/binding.rs | 34 +- src/chat/binding/tests.rs | 2 +- src/chat/binding/tests/operator_accounting.rs | 6 +- src/chat/child_focus.rs | 19 +- src/chat/message_inbox.rs | 28 + src/chat/run.rs | 1 + src/config/schema/integrations.rs | 1 - src/gateway/api/sessions/mailbox.rs | 14 +- src/gateway/child_mailbox.rs | 175 + src/gateway/jobs.rs | 3 + src/gateway/live_frames.rs | 7 + src/gateway/mailbox.rs | 38 +- src/gateway/mod.rs | 1 + src/gateway/run_approvals.rs | 12 +- src/memory/sqlite/mailbox.rs | 3 + src/memory/sqlite/mailbox/local_runtime.rs | 63 +- src/memory/sqlite/mailbox/retry.rs | 7 +- src/messaging/a2a/peers.rs | 6 +- src/messaging/receiver.rs | 19 + src/messaging/runtime.rs | 109 +- src/messaging/runtime/turns.rs | 124 + src/messaging/worker.rs | 19 +- src/runtime/child_source.rs | 8 +- src/runtime/child_source/parent.rs | 29 +- src/runtime/child_source/publication.rs | 14 +- .../child_source/publication/operator.rs | 49 +- src/runtime/child_source/tests.rs | 2 +- src/runtime/decision_accounting.rs | 6 + src/runtime/mailbox_child.rs | 281 + src/runtime/mailbox_child/approvals.rs | 30 + src/runtime/mailbox_child/driver.rs | 146 + src/runtime/mailbox_child/publication.rs | 78 + src/runtime/mod.rs | 1 + src/runtime/operator_spawn.rs | 32 +- src/runtime/operator_spawn/mailbox.rs | 48 + src/runtime/operator_spawn/process.rs | 22 +- src/runtime/operator_spawn/task.rs | 21 +- src/runtime/operator_spawn/task/segments.rs | 5 +- src/runtime/turn_cleanup.rs | 35 + src/runtime/turn_context/opening.rs | 1 + src/runtime/turn_source.rs | 24 + src/session_worker/mailbox.rs | 4 +- src/tools/sessions_spawn/continuation.rs | 16 +- src/tools/sessions_spawn/message_lifetime.rs | 50 + src/tools/sessions_spawn/mod.rs | 1 + src/tools/sessions_spawn/spawn.rs | 58 +- src/tools/sessions_spawn/task_mode.rs | 4 + tests/architecture_boundaries/providers.rs | 2 + tests/architecture_boundaries/tool_tables.rs | 5 + tests/fixtures/config-schema.json | 6589 +---------------- 51 files changed, 1507 insertions(+), 6754 deletions(-) create mode 100644 src/gateway/child_mailbox.rs create mode 100644 src/messaging/runtime/turns.rs create mode 100644 src/runtime/mailbox_child.rs create mode 100644 src/runtime/mailbox_child/approvals.rs create mode 100644 src/runtime/mailbox_child/driver.rs create mode 100644 src/runtime/mailbox_child/publication.rs create mode 100644 src/runtime/operator_spawn/mailbox.rs create mode 100644 src/tools/sessions_spawn/message_lifetime.rs diff --git a/docs/tools.md b/docs/tools.md index 1d10e2e6f..c53a1d492 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -1980,6 +1980,15 @@ when attached. Incoming data appears as `[message from /]`. Messages never approve tools, execute slash commands, or publish into an rf chat. Local adoption is journaled with session provenance; peer adoption carries its TLS SPIFFE identity. Erasing the local copy cannot erase a remote copy. + +An idle child can receive a message after its parent's turn ends. Its next +turn uses the persisted child session and model, with its level capped by the +current agent and owner configuration. It gets no inherited approval grant or +local operator authority. Task approvals use the root session's live surface; +without one, calls that need approval are denied with `no_approval_surface`. +Process-child approvals remain denied with `no_resolver`. Message turns count +toward the receiving agent's limits and daily cost, and run one at a time per +child session. Process children continue in a new worker with public history seeded. Their tool approvals remain denied with `no_resolver`; task/delegate approvals use the owner's pending-approval surface. diff --git a/src/chat/binding.rs b/src/chat/binding.rs index 51885a04d..c8f7518ee 100644 --- a/src/chat/binding.rs +++ b/src/chat/binding.rs @@ -376,7 +376,6 @@ impl Drop for ChatAdmissionGuard { /// Private fields keep mailbox content and decoded tool arguments from minting /// an operator command or replacing the model after verification. pub(super) struct ChatOperatorSpawn { - mailbox: Option, child: Option, command: String, binding: ChatProviderBinding, @@ -406,7 +405,6 @@ impl ChatOperatorSpawn { ); binding.verify(generation, provider, provider_name, model_name)?; Ok(Self { - mailbox: None, child: None, command: message.content.clone(), binding: ChatProviderBinding { @@ -435,7 +433,6 @@ impl ChatOperatorSpawn { ); binding.verify(&binding.generation, &binding.provider, &record.provider, &record.model)?; Ok(Self { - mailbox: None, command: format!("Continue child session {}", record.session_key), provider: record.provider.clone(), model: record.model.clone(), @@ -445,34 +442,13 @@ impl ChatOperatorSpawn { }) } - pub(super) fn capture_message( - input: crate::messaging::runtime::MessageInput, - record: crate::memory::child_sessions::ChildSessionRecord, - binding: ChatProviderBinding, - ) -> anyhow::Result { - anyhow::ensure!( - input.auto_start() && input.message.to.session == record.session_key, - "mailbox wake target differs" - ); - binding.verify(&binding.generation, &binding.provider, &record.provider, &record.model)?; - Ok(Self { - command: format!("Continue child session {}", record.session_key), - task: input.text.clone(), - provider: record.provider.clone(), - model: record.model.clone(), - child: Some(record), - mailbox: Some(input), - binding, - }) - } - pub(super) async fn admit( self, memory: Arc, session: &str, security: Arc, publication: Arc, - ) -> anyhow::Result<(serde_json::Value, crate::runtime::operator_spawn::OperatorSpawnSource)> { + ) -> anyhow::Result<(serde_json::Value, crate::runtime::operator_spawn::ChildLaunchSource)> { let generation = &self.binding.generation; let run = uuid::Uuid::new_v4().to_string(); let workspace = generation.effective.workspace_dir.to_string_lossy(); @@ -514,7 +490,7 @@ impl ChatOperatorSpawn { ) }; let runtime = Arc::clone(publication.runtime_holder()); - let mut source = crate::runtime::operator_spawn::OperatorSpawnSource::new( + let mut source = crate::runtime::operator_spawn::ChildLaunchSource::new( binding.as_ref(), Arc::clone(generation), fabric, @@ -533,11 +509,7 @@ impl ChatOperatorSpawn { if record.agent != "main" { object.insert("agent".into(), record.agent.clone().into()); } - source = if let Some(input) = self.mailbox { - source.for_message(record, &input).await? - } else { - source.for_continuation(record)? - }; + source = source.for_continuation(record)?; } if let Some(guard) = admission_guard { guard.handoff(); diff --git a/src/chat/binding/tests.rs b/src/chat/binding/tests.rs index bddaafe94..9aaac26a1 100644 --- a/src/chat/binding/tests.rs +++ b/src/chat/binding/tests.rs @@ -29,7 +29,7 @@ pub(crate) async fn recorded_local_operator_spawn( publication: crate::runtime::turn_publication::TurnPublication, provider: Arc, task: &str, -) -> anyhow::Result<(serde_json::Value, crate::runtime::operator_spawn::OperatorSpawnSource)> { +) -> anyhow::Result<(serde_json::Value, crate::runtime::operator_spawn::ChildLaunchSource)> { let generation = Arc::clone(&publication.generation); let memory = Arc::clone(&publication.memory); let security = Arc::clone(&publication.security); diff --git a/src/chat/binding/tests/operator_accounting.rs b/src/chat/binding/tests/operator_accounting.rs index 40fdf8335..84fa3fa29 100644 --- a/src/chat/binding/tests/operator_accounting.rs +++ b/src/chat/binding/tests/operator_accounting.rs @@ -198,7 +198,7 @@ async fn run_operator_case(process: bool) -> anyhow::Result<()> { .scope(async { let claimed = crate::runtime::operator_spawn::claim(&args)?.context("actual operator source missing")?; - let binding = Arc::new(crate::runtime::child_source::ChildProviderBinding::build_operator( + let binding = Arc::new(crate::runtime::child_source::ChildProviderBinding::build_independent( &claimed, )?); let mut scope = crate::runtime::envelope::RuntimeEnvelope::sessions_spawn( @@ -331,7 +331,7 @@ async fn run_operator_case(process: bool) -> anyhow::Result<()> { // Test-only composition fragment. Not a frozen candidate or executed test. async fn restore_operator_process( - source: &std::sync::Arc, + source: &std::sync::Arc, scope: &crate::memory::MessageEventScope, receipt: Option>, task: &str, @@ -425,7 +425,7 @@ async fn restore_operator_process( } async fn process_segment( - claimed: &std::sync::Arc, + claimed: &std::sync::Arc, scope: &crate::memory::MessageEventScope, receipt: Option>, task: &str, diff --git a/src/chat/child_focus.rs b/src/chat/child_focus.rs index e6855682d..b21e13d4f 100644 --- a/src/chat/child_focus.rs +++ b/src/chat/child_focus.rs @@ -32,19 +32,10 @@ impl ChildFocusContext<'_> { record: ChildSessionRecord, input: crate::messaging::runtime::MessageInput, ) -> anyhow::Result { - let provider = self.provider(&record)?; - let binding = ChatProviderBinding::capture(self.generation, &provider, &record.provider, &record.model)? - .context("child provider missing")?; - let command = ChatOperatorSpawn::capture_message(input, record, binding)?; - let (args, source) = command - .admit( - Arc::clone(self.memory), - self.parent, - Arc::clone(self.security), - Arc::clone(self.service), - ) - .await?; - self.execute_source(source, args).await + crate::runtime::mailbox_child::MailboxChildSource::admit(self.service, record, input, None) + .await? + .continue_turn(self.tools) + .await } pub(super) async fn view( &self, @@ -202,7 +193,7 @@ impl ChildFocusContext<'_> { } async fn execute_source( &self, - source: crate::runtime::operator_spawn::OperatorSpawnSource, + source: crate::runtime::operator_spawn::ChildLaunchSource, args: serde_json::Value, ) -> anyhow::Result { let tool = self diff --git a/src/chat/message_inbox.rs b/src/chat/message_inbox.rs index 6a905c884..97cd15cbb 100644 --- a/src/chat/message_inbox.rs +++ b/src/chat/message_inbox.rs @@ -91,6 +91,7 @@ pub(super) fn cause(message: &ChannelMessage) -> Option<&str> { pub(super) async fn send_command( config: &crate::config::Config, + memory:&Arc, parent: &str, focused: Option<&str>, message: &ChannelMessage, @@ -119,6 +120,33 @@ pub(super) async fn send_command( { source.agent = agent; } + let level = if source_session == parent { + config.autonomy.level + } else { + let store = memory.child_session_store() + .ok_or_else(|| anyhow::anyhow!("child store unavailable"))?; + let record = store + .sessions(&runtime.workspace, &owner)? + .into_iter() + .find(|record| record.session_key == source_session && record.parent_session == parent) + .ok_or_else(|| anyhow::anyhow!("child_session_unknown"))?; + record.level.min( + crate::security::agent_level::named_child_level(config, Some(&record.agent), config.autonomy.level) + .unwrap_or(config.autonomy.level), + ) + }; + let policy = crate::security::SecurityPolicy { + autonomy: level, + ..crate::security::SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir) + }; + crate::security::SideEffectGate::new(&policy) + .authorize_resource_operation( + "sessions_send", + "sessions_send:message", + crate::security::policy::ResourceRiskLevel::Low, + None, + ) + .map_err(anyhow::Error::msg)?; let (target, text) = super::commands::msg::parse(&message.content, &source)?; let mut target = serde_json::Value::String(target.session); if let Some(seq) = target diff --git a/src/chat/run.rs b/src/chat/run.rs index 9b7f66ee9..457b275d5 100644 --- a/src/chat/run.rs +++ b/src/chat/run.rs @@ -904,6 +904,7 @@ async fn run_internal( { let result = super::message_inbox::send_command( &config, + &mem, &chat_session_key, attached_follow.as_ref().map(|id| id.as_str()), &msg, diff --git a/src/config/schema/integrations.rs b/src/config/schema/integrations.rs index 4e8f90abf..b33a9fb25 100644 --- a/src/config/schema/integrations.rs +++ b/src/config/schema/integrations.rs @@ -357,7 +357,6 @@ impl Default for RemoteTreeLimits { } } -/// Inbound key-possession method a peer must use. /// Explicit pinned identity and local recipient grant. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] diff --git a/src/gateway/api/sessions/mailbox.rs b/src/gateway/api/sessions/mailbox.rs index 73ece083b..a6b16530e 100644 --- a/src/gateway/api/sessions/mailbox.rs +++ b/src/gateway/api/sessions/mailbox.rs @@ -16,6 +16,7 @@ pub(super) fn register( return Ok(()); } let runtime = MessagingRuntime::for_config(&config)?; + crate::gateway::child_mailbox::register(state, &envelope)?; let address = runtime.address( &envelope.resolved_owner_id(), &envelope.session_key, @@ -71,7 +72,9 @@ async fn run( ) .await?; let cancellation = tokio_util::sync::CancellationToken::new(); - let ticket = turn_runtime.publication_slot.cleanup.register(cancellation)?; + let stop = cancellation.clone(); + let _message_turn = runtime.hold_turn(&input, Arc::new(move || stop.cancel()))?; + let ticket = turn_runtime.publication_slot.cleanup.register(cancellation.clone())?; let pending = ConsolePendingInput { state: state.clone(), runtime: turn_runtime.clone(), @@ -90,9 +93,12 @@ async fn run( guard, owner_authenticated: false, }; - run_console_message_job_work(turn_runtime, state, input.text.clone(), turns, source, target) - .await - .map_err(anyhow::Error::msg)?; + crate::gateway::jobs::scope_cancellation( + cancellation, + run_console_message_job_work(turn_runtime, state, input.text.clone(), turns, source, target), + ) + .await + .map_err(anyhow::Error::msg)?; drop(input); Ok(()) } diff --git a/src/gateway/child_mailbox.rs b/src/gateway/child_mailbox.rs new file mode 100644 index 000000000..8e97a1bb2 --- /dev/null +++ b/src/gateway/child_mailbox.rs @@ -0,0 +1,175 @@ +//! Backend-owned wake drivers for durable children, independent of parent turns. +use super::AppState; +use crate::memory::child_sessions::ChildSessionRecord; +use crate::messaging::runtime::{MessageInput, MessagingRuntime}; +use anyhow::{Context, Result}; +use std::sync::{Arc, OnceLock, Weak}; +static ROOTS: OnceLock>>> = + OnceLock::new(); +struct Registration { + root: crate::messaging::SessionAddr, + token: Arc<()>, +} +impl Drop for Registration { + fn drop(&mut self) { + if let Some(roots) = ROOTS.get() { + let mut roots = roots.lock(); + if roots + .get(&self.root) + .is_some_and(|entry| Weak::ptr_eq(entry, &Arc::downgrade(&self.token))) + { + roots.remove(&self.root); + } + } + } +} +fn busy(record: &ChildSessionRecord) -> bool { + record + .runs + .last() + .and_then(|run| crate::runtime::registry::resolve_address(run)) + .is_some() +} +pub(super) fn register(state: &AppState, envelope: &crate::runtime::envelope::RuntimeEnvelope) -> Result<()> { + let config = state.config.load_full(); + if config.memory.backend != "sqlite" { + return Ok(()); + } + let runtime = MessagingRuntime::for_config(&config)?; + let root = runtime.address( + &envelope.resolved_owner_id(), + &envelope.session_key, + envelope.agent_id.as_deref().unwrap_or("main"), + ); + let root_scope = runtime.store.session_scope(&runtime.workspace, &root, false)?; + let lifetime = Arc::new(()); + { + let mut roots = ROOTS.get_or_init(Default::default).lock(); + roots.retain(|_, root| root.strong_count() > 0); + if roots.get(&root).and_then(Weak::upgrade).is_some() { + return Ok(()); + } + roots.insert(root.clone(), Arc::downgrade(&lifetime)); + } + let state = state.clone(); + tokio::spawn(async move { + let _lifetime = Registration { + root: root.clone(), + token: lifetime, + }; + let mut interval = tokio::time::interval(std::time::Duration::from_millis(100)); + loop { + interval.tick().await; + if runtime.store.validate_scope(&root_scope, &root).is_err() { + break; + } + let Some(store) = state.mem.child_session_store() else { + break; + }; + let Ok(records) = store.sessions(&runtime.workspace, &root.owner) else { + break; + }; + for mut record in records + .into_iter() + .filter(|record| record.parent_session == root.session && !busy(record)) + { + record.context.clear(); + let address = runtime.address(&record.owner, &record.session_key, &record.agent); + let idle_state = state.clone(); + let idle_record = record.clone(); + let idle = Arc::new(move || { + idle_state + .mem + .child_session_store() + .and_then(|store| store.sessions(&idle_record.workspace, &idle_record.owner).ok()) + .is_some_and(|records| { + records + .iter() + .any(|record| record.session_key == idle_record.session_key && !busy(record)) + }) + }); + let state = state.clone(); + let result = crate::messaging::receiver::register_idle( + Arc::clone(&runtime), + address, + Arc::new(move |input| { + let state = state.clone(); + let record = record.clone(); + Box::pin(run(state, record, input)) + }), + idle, + ); + if let Err(error) = result { + tracing::warn!(error=%crate::agent::diagnostics::error_class(&error),"child mailbox registration refused"); + } + } + } + }); + Ok(()) +} +async fn run(state: AppState, record: ChildSessionRecord, input: MessageInput) -> Result<()> { + let turn = state.admit_turn_runtime()?; + let cleanup = Arc::clone(&turn.publication_slot.cleanup); + cleanup + .scope(async { + let publication = turn.publication_slot.publish(&turn, &state).await?; + let runtime = MessagingRuntime::for_config(&turn.config_generation.effective)?; + input.verify(&runtime)?; + let mut live = crate::runtime::mailbox_child::no_surface(); + if state.rf_streams.connected(&record.owner) + && let Some(store) = state.mem.sync_store() + { + let event = input + .receipt + .adopted_message_event_id + .context("adopted child event missing")? + .to_string(); + if let Some(scope) = store.live_scope(&record.owner, &event)? { + live = + crate::agent::live_frames::LiveTurnRef(Arc::new(super::run_approvals::RunApprovalResolver { + scope, + streams: Arc::clone(&state.rf_streams), + approvals: Arc::clone(&state.rf_approvals), + cancellation: tokio_util::sync::CancellationToken::new(), + wait_secs: turn + .config_generation + .effective + .agents + .get(&record.agent) + .map_or(turn.config_generation.effective.agent.approval_wait_secs, |agent| { + agent.approval_wait_secs + }), + })); + } + } + crate::runtime::mailbox_child::MailboxChildSource::admit( + publication, + record.clone(), + input.clone(), + Some(live), + ) + .await? + .continue_turn(turn.tools_registry.as_ref()) + .await?; + // Keep this inbox serial until the independently owned task/process + // settles. The next message cannot become a second concurrent turn. + let mut interval = tokio::time::interval(std::time::Duration::from_millis(100)); + loop { + interval.tick().await; + input.verify(&runtime)?; + let records = state + .mem + .child_session_store() + .context("child store unavailable")? + .sessions(&record.workspace, &record.owner)?; + let Some(current) = records.iter().find(|current| current.session_key == record.session_key) else { + break; + }; + if !busy(current) { + break; + } + } + Ok(()) + }) + .await +} diff --git a/src/gateway/jobs.rs b/src/gateway/jobs.rs index 09770b0f6..ba3ad12c6 100644 --- a/src/gateway/jobs.rs +++ b/src/gateway/jobs.rs @@ -48,6 +48,9 @@ tokio::task_local! { pub(super) fn current_cancellation() -> Option { JOB_CANCELLATION.try_with(Clone::clone).ok() } +pub(super) async fn scope_cancellation(cancellation: CancellationToken, work: F) -> F::Output { + JOB_CANCELLATION.scope(cancellation, work).await +} /// Register before terminal work begins; the receiver survives abortion of /// the work task because the independent job monitor owns the collection. diff --git a/src/gateway/live_frames.rs b/src/gateway/live_frames.rs index 65584b782..40ae448d4 100644 --- a/src/gateway/live_frames.rs +++ b/src/gateway/live_frames.rs @@ -83,6 +83,13 @@ impl StreamQueue { } } impl StreamHub { + pub(crate) fn connected(&self, owner: &str) -> bool { + self.state + .lock() + .connections + .get(owner) + .is_some_and(|queue| !queue.failed()) + } pub(crate) fn connect(&self, owner: &str) -> Arc { let queue = Arc::new(StreamQueue::default()); let mut state = self.state.lock(); diff --git a/src/gateway/mailbox.rs b/src/gateway/mailbox.rs index 0a19bda25..7dd18590b 100644 --- a/src/gateway/mailbox.rs +++ b/src/gateway/mailbox.rs @@ -34,6 +34,7 @@ pub(super) fn register( return Ok(()); } let runtime = MessagingRuntime::for_config(&config)?; + super::child_mailbox::register(state, envelope)?; let address = runtime.address( &envelope.resolved_owner_id(), &envelope.session_key, @@ -55,22 +56,29 @@ pub(super) fn register( crate::runtime::agent_admission::wait(&config, &input.message.to.owner, &input.message.to.agent) .await?; let text = input.text.clone(); + let runtime = MessagingRuntime::for_config(&config)?; + let cancellation = tokio_util::sync::CancellationToken::new(); + let stop = cancellation.clone(); + let _message_turn = runtime.hold_turn(&input, Arc::new(move || stop.cancel()))?; INPUT - .scope(input, async { - let mut stage = TurnFailureClass::TurnNotReady; - // Normal gateway admission owns history, policy, costs and - // cleanup. Message data never enters the HTTP approval parser. - run_gateway_chat_with_multimodal( - &state, - crate::providers::selection::default_provider(&config), - &text, - &context, - None, - &mut stage, - ) - .await - .map(|_| ()) - }) + .scope( + input, + super::jobs::scope_cancellation(cancellation, async { + let mut stage = TurnFailureClass::TurnNotReady; + // Normal gateway admission owns history, policy, costs and + // cleanup. Message data never enters the HTTP approval parser. + run_gateway_chat_with_multimodal( + &state, + crate::providers::selection::default_provider(&config), + &text, + &context, + None, + &mut stage, + ) + .await + .map(|_| ()) + }), + ) .await }) }), diff --git a/src/gateway/mod.rs b/src/gateway/mod.rs index 00abbd419..e1b1aaca6 100644 --- a/src/gateway/mod.rs +++ b/src/gateway/mod.rs @@ -25,6 +25,7 @@ mod agent_lifecycle; mod api; +mod child_mailbox; mod compat; mod h2_control; mod jobs; diff --git a/src/gateway/run_approvals.rs b/src/gateway/run_approvals.rs index ca6f42dbd..d13df4797 100644 --- a/src/gateway/run_approvals.rs +++ b/src/gateway/run_approvals.rs @@ -117,13 +117,15 @@ pub(crate) struct RunApprovalResolver { } impl Drop for RunApprovalResolver { fn drop(&mut self) { + self.cancellation.cancel(); let root = self.scope.get("run_id").and_then(Value::as_str); self.approvals.entries.lock().retain(|_, entry| { - if entry - .pending - .rf - .as_ref() - .is_some_and(|rf| Some(rf.root_run_id.as_str()) == root) + if entry.cancel.is_cancelled() + && entry + .pending + .rf + .as_ref() + .is_some_and(|rf| Some(rf.root_run_id.as_str()) == root) { entry.cancel.cancel(); false diff --git a/src/memory/sqlite/mailbox.rs b/src/memory/sqlite/mailbox.rs index d3f8f595e..b2d8d9afa 100644 --- a/src/memory/sqlite/mailbox.rs +++ b/src/memory/sqlite/mailbox.rs @@ -36,6 +36,9 @@ pub struct SqliteMailbox { } impl SqliteMailbox { + pub(crate) fn cache_drain_guard(&self, scope: uuid::Uuid) -> std::sync::Arc { + std::sync::Arc::new(self.memory.mailbox_runtime.cache_lease(scope)) + } pub(crate) fn register_drainer(&self, drainer: &Arc) { self.memory.mailbox_runtime.register_drainer(drainer); } diff --git a/src/memory/sqlite/mailbox/local_runtime.rs b/src/memory/sqlite/mailbox/local_runtime.rs index aa868deb0..3e7638346 100644 --- a/src/memory/sqlite/mailbox/local_runtime.rs +++ b/src/memory/sqlite/mailbox/local_runtime.rs @@ -6,6 +6,30 @@ use crate::messaging::{CausalChain, SessionAddr}; use rusqlite::{OptionalExtension, Transaction, TransactionBehavior, params}; impl SqliteMailbox { + pub(crate) fn partition( + &self, + scope: &crate::messaging::mailbox::MailboxScope, + ) -> crate::messaging::mailbox::MailboxResult { + let writer = self.memory.pool.write(); + let key:String=writer.query_row("SELECT agent_key FROM agent_scopes WHERE scope_id=?1 AND workspace_id=?2 AND owner_id=?3 AND incarnation=?4 AND generation=?5",params![scope.scope_id.to_string(),scope.workspace_id,scope.owner_id,scope.incarnation.to_string(),scope.generation],|row|row.get(0)).map_err(storage_error)?; + let key = if key == "m" { + crate::memory::PartitionKey::Main + } else { + crate::memory::PartitionKey::Named { + name: crate::config::agent_name::AgentName::parse( + key.strip_prefix("n:") + .ok_or(crate::messaging::mailbox::MailboxError::CorruptState)?, + ) + .map_err(|_| crate::messaging::mailbox::MailboxError::CorruptState)?, + incarnation: scope.incarnation, + } + }; + Ok(crate::memory::AgentPartition { + workspace_id: scope.workspace_id.clone(), + owner_id: scope.owner_id.clone(), + key, + }) + } pub(crate) fn hold_input( &self, scope: &MailboxScope, @@ -17,18 +41,51 @@ impl SqliteMailbox { self.memory.mailbox_runtime.cache_lease(scope.scope_id), )) } + pub(crate) fn with_live_scope( + &self, + scope: &MailboxScope, + target: &SessionAddr, + action: impl FnOnce() -> T, + ) -> MailboxResult { + let writer = self.memory.pool.write(); + pin::check_scope(&writer, scope, target, None, true)?; + Ok(action()) + } pub(crate) fn validate_input( &self, workspace: &str, target: &SessionAddr, event: uuid::Uuid, text: &str, + message: uuid::Uuid, + receipt: &crate::messaging::mailbox::MailboxReceipt, ) -> MailboxResult<()> { + self.with_input(workspace, target, event, text, message, receipt, || ()) + } + pub(crate) fn with_input( + &self, + workspace: &str, + target: &SessionAddr, + event: uuid::Uuid, + text: &str, + message: uuid::Uuid, + receipt: &crate::messaging::mailbox::MailboxReceipt, + action: impl FnOnce() -> T, + ) -> MailboxResult { let scope = self.session_scope(workspace, target, false)?; - self.validate_scope(&scope, target)?; let writer = self.memory.pool.write(); - let present:bool=writer.query_row("SELECT EXISTS(SELECT 1 FROM message_events WHERE event_id=?1 AND workspace_id=?2 AND owner_id=?3 AND session_key=?4 AND source='prx_mailbox' AND role='user' AND content=?5 AND ma_scope_id=?6)",params![event.to_string(),scope.workspace_id,target.owner,target.session,text,scope.scope_id.to_string()],|r|r.get(0)).map_err(storage_error)?; - if present { Ok(()) } else { Err(MailboxError::Fenced) } + pin::check_scope(&writer, &scope, target, None, true)?; + let raw:Option=writer.query_row("SELECT source_ref_json FROM message_events WHERE event_id=?1 AND workspace_id=?2 AND owner_id=?3 AND session_key=?4 AND source='prx_mailbox' AND role='user' AND content=?5 AND ma_scope_id=?6",params![event.to_string(),scope.workspace_id,target.owner,target.session,text,scope.scope_id.to_string()],|r|r.get(0)).optional().map_err(storage_error)?; + let reference: super::model::EventRef = super::model::decode(&raw.ok_or(MailboxError::Fenced)?)?; + if reference.message_id != message + || receipt.message_id != message + || reference.common.chain(message) != receipt.chain + || reference.scope != scope + || reference.agent != target.agent + { + return Err(MailboxError::IdentityImmutable); + } + Ok(action()) } pub fn has_pending(&self, scope: &MailboxScope, target: &SessionAddr) -> MailboxResult { diff --git a/src/memory/sqlite/mailbox/retry.rs b/src/memory/sqlite/mailbox/retry.rs index b1351950e..efed07004 100644 --- a/src/memory/sqlite/mailbox/retry.rs +++ b/src/memory/sqlite/mailbox/retry.rs @@ -101,11 +101,16 @@ impl SqliteMailbox { let writer = self.memory.pool.write(); let tx = Transaction::new_unchecked(&writer, TransactionBehavior::Immediate).map_err(storage_error)?; pin::check_scope(&tx, scope, source, None, true)?; - let (id,raw):(i64,String)=tx.query_row("SELECT id,envelope_meta FROM prx_mailbox_outbox WHERE message_id=?1 AND ma_scope_id=?2 AND state IN(0,1)",params![message.id.as_bytes().as_slice(),scope.scope_id.to_string()],|r|Ok((r.get(0)?,r.get(1)?))).map_err(storage_error)?; + let (id,raw,stream_id):(i64,String,i64)=tx.query_row("SELECT id,envelope_meta,stream_id FROM prx_mailbox_outbox WHERE message_id=?1 AND ma_scope_id=?2 AND state IN(0,1)",params![message.id.as_bytes().as_slice(),scope.scope_id.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?))).map_err(storage_error)?; let mut meta: OutboxMeta = decode(&raw)?; if !meta.to_pin.incarnation.is_nil() && (meta.to_pin.incarnation != pin.incarnation || meta.to_pin.generation != pin.generation) { + // Old payloads stay bound to their old incarnation. Future sends + // get a new wire stream instead of reusing the receiver's tombstone. + let mut stream = super::stream::load(&tx, stream_id)?; + super::stream::retire(&tx, &mut stream, self.clock.now())?; + tx.commit().map_err(storage_error)?; return Err(MailboxError::StaleIncarnation); } message.to_pin = pin; diff --git a/src/messaging/a2a/peers.rs b/src/messaging/a2a/peers.rs index 39e8c10e7..7ec582682 100644 --- a/src/messaging/a2a/peers.rs +++ b/src/messaging/a2a/peers.rs @@ -56,7 +56,11 @@ pub fn validate(config: &A2aConfig) -> Result<()> { let url = reqwest::Url::parse(&format!("https://{}", peer.address))?; ensure!( url.host_str().is_some() - && url.port().is_some() + && url.port_or_known_default().is_some() + && peer + .address + .rsplit_once(':') + .is_some_and(|(_, port)| port.parse::().is_ok_and(|port| port > 0)) && url.username().is_empty() && url.password().is_none() && url.path() == "/" diff --git a/src/messaging/receiver.rs b/src/messaging/receiver.rs index 69814433c..2ada99310 100644 --- a/src/messaging/receiver.rs +++ b/src/messaging/receiver.rs @@ -22,6 +22,14 @@ pub(crate) fn gate(address: &SessionAddr) -> Arc> { gate } pub(crate) fn register(runtime: Arc, address: SessionAddr, callback: Callback) -> anyhow::Result<()> { + register_idle(runtime, address, callback, Arc::new(|| true)) +} +pub(crate) fn register_idle( + runtime: Arc, + address: SessionAddr, + callback: Callback, + idle: Arc bool + Send + Sync>, +) -> anyhow::Result<()> { // Registration is idempotent for the currently running backend owner. let Some(mut inbox) = runtime.register_backend(address)? else { return Ok(()); @@ -30,12 +38,23 @@ pub(crate) fn register(runtime: Arc, address: SessionAddr, cal let mut interval = tokio::time::interval(std::time::Duration::from_millis(100)); loop { interval.tick().await; + if !inbox.live() { + break; + } + if !idle() { + continue; + } match inbox.poll() { Ok(inputs) => { for input in inputs { + let retained = input.clone(); if input.auto_start() && let Err(error) = callback(input).await { + if error.is::() { + let _ = runtime.requeue(retained); + continue; + } tracing::warn!(error=%crate::agent::diagnostics::error_class(&error),"session mailbox turn refused"); } } diff --git a/src/messaging/runtime.rs b/src/messaging/runtime.rs index 033dd69a7..7655bf16f 100644 --- a/src/messaging/runtime.rs +++ b/src/messaging/runtime.rs @@ -1,4 +1,5 @@ //! Runtime-owned sender identity, durable local delivery and inbox wakeups. +mod turns; use super::mailbox::{MailboxAuthority, MailboxError, MailboxPublished, MailboxReceipt, MailboxResult, MailboxScope}; use super::send::{MailboxDestination, MailboxResolver, MailboxSender}; use super::{PrxMessage, SessionAddr}; @@ -11,16 +12,19 @@ use std::{ sync::{Arc, OnceLock, Weak}, }; use tokio::sync::mpsc; +pub(crate) use turns::MessageTurnGuard; type RuntimeRegistry = Mutex>>; static RUNTIMES: OnceLock = OnceLock::new(); pub struct MessagingRuntime { + turns: Mutex>>, + caches: Mutex>>, pub(crate) store: SqliteMailbox, pub(crate) workspace: String, pub(crate) instance: String, config: RwLock>, - inboxes: Mutex)>>, + inboxes: Mutex)>>, ready: Mutex>>, } @@ -38,9 +42,14 @@ impl MessageInput { .receipt .adopted_message_event_id .ok_or(MailboxError::CorruptState)?; - runtime - .store - .validate_input(&runtime.workspace, &self.message.to, event, &self.text) + runtime.store.validate_input( + &runtime.workspace, + &self.message.to, + event, + &self.text, + self.message.id, + &self.receipt, + ) } pub const fn auto_start(&self) -> bool { @@ -49,6 +58,7 @@ impl MessageInput { } pub struct SessionInbox { + registration: uuid::Uuid, runtime: Arc, address: SessionAddr, scope: MailboxScope, @@ -59,7 +69,7 @@ impl Drop for SessionInbox { let mut inboxes = self.runtime.inboxes.lock(); if inboxes .get(&self.address) - .is_some_and(|(scope, _)| *scope == self.scope.scope_id) + .is_some_and(|(_, registration, _)| *registration == self.registration) { inboxes.remove(&self.address); } @@ -99,6 +109,8 @@ impl MessagingRuntime { Arc::new(super::mailbox::SystemMailboxClock), )?; let runtime = Arc::new(Self { + turns: Default::default(), + caches: Default::default(), store, workspace: path.to_string_lossy().into_owned(), instance, @@ -122,13 +134,15 @@ impl MessagingRuntime { pub fn register(self: &Arc, address: SessionAddr) -> MailboxResult { let scope = self.store.session_scope(&self.workspace, &address, true)?; let (sender, receiver) = mpsc::channel(1); + let registration = uuid::Uuid::new_v4(); match self.inboxes.lock().entry(address.clone()) { std::collections::hash_map::Entry::Vacant(entry) => { - entry.insert((scope.scope_id, sender)); + entry.insert((scope.scope_id, registration, sender)); } std::collections::hash_map::Entry::Occupied(_) => return Err(MailboxError::IdentityImmutable), } Ok(SessionInbox { + registration, runtime: Arc::clone(self), address, scope, @@ -173,32 +187,64 @@ impl MessagingRuntime { self.store.session_scope(&self.workspace, target, registered) } + pub(crate) fn ready_capacity(&self, target: &SessionAddr) -> bool { + self.ready.lock().get(target).is_none_or(|queue| queue.len() < 64) + } pub(crate) fn adopted(&self, message: PrxMessage, receipt: MailboxReceipt) -> MailboxResult<()> { let text = crate::session_worker::mailbox::user_text(&message)?; let target = message.to.clone(); - let mut ready = self.ready.lock(); - let queue = ready.entry(target.clone()).or_default(); - if queue.len() >= usize::try_from(super::mailbox::MAX_QUEUE).map_err(|_| MailboxError::CorruptState)? { - return Err(MailboxError::QueueFull); - } - let scope = self.store.session_scope(&self.workspace, &message.to, false)?; - let lease = self.store.hold_input(&scope, &message.to)?; - queue.push_back(MessageInput { + let scope = self.store.session_scope(&self.workspace, &target, false)?; + let lease = self.store.hold_input(&scope, &target)?; + let input = MessageInput { _lease: lease, scope: scope.scope_id, message, receipt, text, - }); - drop(ready); + }; + self.requeue_back(input)?; self.wake(&target); Ok(()) } + fn requeue_back(&self, input: MessageInput) -> MailboxResult<()> { + self.queue_input(input, false) + } + fn queue_input(&self, input: MessageInput, front: bool) -> MailboxResult<()> { + let target = input.message.to.clone(); + let event = input + .receipt + .adopted_message_event_id + .ok_or(MailboxError::CorruptState)?; + self.store.with_input( + &self.workspace, + &target, + event, + &input.text, + input.message.id, + &input.receipt, + || { + let mut ready = self.ready.lock(); + let queue = ready.entry(target.clone()).or_default(); + if queue.len() >= 64 { + return Err(MailboxError::QueueFull); + } + if front { + queue.push_front(input.clone()); + } else { + queue.push_back(input.clone()); + } + Ok(()) + }, + )? + } pub fn wake(&self, target: &SessionAddr) { - if let Some((_, sender)) = self.inboxes.lock().get(target) { + if let Some((_, _, sender)) = self.inboxes.lock().get(target) { let _ = sender.try_send(()); } } + pub(crate) fn requeue(&self, input: MessageInput) -> MailboxResult<()> { + self.queue_input(input, true) + } pub fn bind(self: &Arc, source: SessionAddr, event: Option<&str>) -> MailboxResult { let mut source = source; @@ -343,14 +389,24 @@ impl SessionInbox { self.runtime .store .execution_guard(&self.scope, &self.address, uuid::Uuid::new_v4().to_string())?; - let mut inputs: Vec<_> = self - .runtime - .ready - .lock() - .remove(&self.address) - .unwrap_or_default() - .into_iter() - .collect(); + let queued = { + let mut ready = self.runtime.ready.lock(); + let value = ready + .get_mut(&self.address) + .and_then(std::collections::VecDeque::pop_front); + if ready + .get(&self.address) + .is_some_and(std::collections::VecDeque::is_empty) + { + ready.remove(&self.address); + } + value + }; + if let Some(input) = queued { + drop(execution); + return Ok(vec![input]); + } + let mut inputs = Vec::new(); for _ in 0..1 { let Some(delivery) = self.runtime.store.deliver(&self.scope, &self.address)? else { break; @@ -373,11 +429,12 @@ impl SessionInbox { impl super::mailbox::MailboxCacheDrainer for MessagingRuntime { fn drain(&self, scope: uuid::Uuid) { + self.stop_scope(scope); self.ready.lock().retain(|_, inputs| { inputs.retain(|input| input.scope != scope); !inputs.is_empty() }); - self.inboxes.lock().retain(|_, (registered, sender)| { + self.inboxes.lock().retain(|_, (registered, _, sender)| { if *registered == scope { let _ = sender.try_send(()); false diff --git a/src/messaging/runtime/turns.rs b/src/messaging/runtime/turns.rs new file mode 100644 index 000000000..fb014bbb8 --- /dev/null +++ b/src/messaging/runtime/turns.rs @@ -0,0 +1,124 @@ +//! Erase stops active receivers and waits for their retained source caches. +use super::{MessageInput, MessagingRuntime}; +use std::sync::{Arc, Weak}; +pub(super) type Stop = Arc; +pub(super) type Cache = Arc, Vec) + Send + Sync>; +pub(super) struct Active { + pub stop: Stop, + pub done: tokio_util::sync::CancellationToken, +} +pub(super) struct Cached { + pub alive: Arc bool + Send + Sync>, + pub clear: Cache, +} +pub(crate) struct MessageTurnGuard { + runtime: Weak, + scope: uuid::Uuid, + id: uuid::Uuid, + done: tokio_util::sync::CancellationToken, +} +impl Drop for MessageTurnGuard { + fn drop(&mut self) { + self.done.cancel(); + if let Some(runtime) = self.runtime.upgrade() { + let mut active = runtime.turns.lock(); + if let Some(turns) = active.get_mut(&self.scope) { + turns.remove(&self.id); + if turns.is_empty() { + active.remove(&self.scope); + } + } + } + } +} +impl MessagingRuntime { + pub(crate) fn hold_turn( + self: &Arc, + input: &MessageInput, + stop: Stop, + ) -> super::MailboxResult { + let event = input + .receipt + .adopted_message_event_id + .ok_or(super::MailboxError::CorruptState)?; + self.store.with_input( + &self.workspace, + &input.message.to, + event, + &input.text, + input.message.id, + &input.receipt, + || self.insert_turn(input.scope, stop), + ) + } + pub(crate) fn hold_scope( + self: &Arc, + scope: &super::MailboxScope, + target: &crate::messaging::SessionAddr, + stop: Stop, + ) -> super::MailboxResult { + self.store + .with_live_scope(scope, target, || self.insert_turn(scope.scope_id, stop)) + } + fn insert_turn(self: &Arc, scope: uuid::Uuid, stop: Stop) -> MessageTurnGuard { + let id = uuid::Uuid::new_v4(); + let done = tokio_util::sync::CancellationToken::new(); + self.turns.lock().entry(scope).or_default().insert( + id, + Active { + stop, + done: done.clone(), + }, + ); + MessageTurnGuard { + runtime: Arc::downgrade(self), + scope, + id, + done, + } + } + pub(crate) fn register_cache( + &self, + input: &MessageInput, + key: String, + alive: Arc bool + Send + Sync>, + clear: Cache, + ) -> super::MailboxResult<()> { + let event = input + .receipt + .adopted_message_event_id + .ok_or(super::MailboxError::CorruptState)?; + self.store.with_input( + &self.workspace, + &input.message.to, + event, + &input.text, + input.message.id, + &input.receipt, + || { + let mut caches = self.caches.lock(); + caches.retain(|_, entries| { + entries.retain(|_, entry| (entry.alive)()); + !entries.is_empty() + }); + caches + .entry(input.scope) + .or_default() + .insert(key, Cached { alive, clear }); + }, + ) + } + pub(super) fn stop_scope(&self, scope: uuid::Uuid) { + let turns = self.turns.lock().remove(&scope).unwrap_or_default(); + let done: Vec<_> = turns.values().map(|active| active.done.clone()).collect(); + for active in turns.into_values() { + (active.stop)(); + } + let caches = self.caches.lock().remove(&scope).unwrap_or_default(); + for cached in caches.into_values() { + if (cached.alive)() { + (cached.clear)(self.store.cache_drain_guard(scope), done.clone()); + } + } + } +} diff --git a/src/messaging/worker.rs b/src/messaging/worker.rs index 5ad6126c4..2444afe0d 100644 --- a/src/messaging/worker.rs +++ b/src/messaging/worker.rs @@ -15,6 +15,7 @@ pub(crate) struct WorkerMailboxes { owners: parking_lot::Mutex>>, } struct WorkerOwner { + turn: parking_lot::Mutex>, cancel: CancellationToken, pending: parking_lot::Mutex>, execution: parking_lot::Mutex>, @@ -71,7 +72,21 @@ impl WorkerMailboxFactory for WorkerMailboxes { let (controls, receiver) = mpsc::channel(64); let (outputs, mut output_rx) = mpsc::channel(64); let cancel = CancellationToken::new(); + let run = manifest.run_id.clone(); + let handle = tokio::runtime::Handle::try_current()?; + let turn = self.runtime.hold_scope( + &scope, + &address, + Arc::new(move || { + if let Some(id) = crate::runtime::registry::resolve_address(&run) { + handle.spawn(async move { + let _ = crate::runtime::registry::kill(id, true).await; + }); + } + }), + )?; let owner = Arc::new(WorkerOwner { + turn: parking_lot::Mutex::new(Some(turn)), cancel: cancel.clone(), pending: Default::default(), execution: parking_lot::Mutex::new(Some(execution)), @@ -110,6 +125,7 @@ impl WorkerMailboxFactory for WorkerMailboxes { }.await } Some(WorkerOutputFrame::Ack { message_id, state: DeliveryState::Consumed }) => { + if !runtime.ready_capacity(&target) {continue;} let delivery = pending.lock().remove(&message_id); delivery.map_or_else(||Ok(()),|delivery|runtime.store.adopt(&delivery).and_then(|receipt|runtime.adopted(delivery.message().clone(),receipt)).map_err(Into::into)) } @@ -121,7 +137,7 @@ impl WorkerMailboxFactory for WorkerMailboxes { _ = interval.tick() => { async { runtime.store.validate_scope(&scope, &target)?; - if pending.lock().len() < 64 { + if pending.lock().len() < 64 && runtime.ready_capacity(&target) { if let Some(delivery) = runtime.store.deliver(&scope, &target)? { let frame = WorkerControlFrame::Message { envelope: Box::new(delivery.message().clone()) }; let id = delivery.message().id; @@ -163,6 +179,7 @@ impl WorkerMailboxFactory for WorkerMailboxes { } owner.pending.lock().clear(); drop(owner.execution.lock().take()); + drop(owner.turn.lock().take()); let _ = runtime.store.recover_delivery(&owner.scope, &owner.address); runtime.wake(&owner.address); }); diff --git a/src/runtime/child_source.rs b/src/runtime/child_source.rs index b677a25c0..7e20a31f0 100644 --- a/src/runtime/child_source.rs +++ b/src/runtime/child_source.rs @@ -438,7 +438,7 @@ impl std::fmt::Debug for ChildProviderBinding { impl ChildProviderBinding { /// Preserve the provider instance authenticated by the explicit operator /// ingress. This model binding alone does not grant child capabilities. - pub(crate) fn build_operator(source: &super::operator_spawn::OperatorSpawnSource) -> anyhow::Result { + pub(crate) fn build_independent(source: &super::operator_spawn::ChildLaunchSource) -> anyhow::Result { use super::turn_source::TurnSourceProof; source.verify_live()?; let binding = Self { @@ -449,16 +449,16 @@ impl ChildProviderBinding { resolved: source.resolved().clone(), route: source.route().cloned(), }; - binding.verify_operator_source(source)?; + binding.verify_independent_source(source)?; source.verify_live()?; Ok(binding) } /// Verify retained model provenance independently of the command lifetime. /// The task driver separately owns and checks its cancellation authority. - pub(crate) fn verify_operator_source( + pub(crate) fn verify_independent_source( &self, - source: &super::operator_spawn::OperatorSpawnSource, + source: &super::operator_spawn::ChildLaunchSource, ) -> anyhow::Result<()> { use super::turn_source::TurnSourceProof; anyhow::ensure!( diff --git a/src/runtime/child_source/parent.rs b/src/runtime/child_source/parent.rs index 1d736988e..074fce05f 100644 --- a/src/runtime/child_source/parent.rs +++ b/src/runtime/child_source/parent.rs @@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize}; #[derive(Clone)] pub(crate) struct ParentSource { + cost_root_agent: Option, owner_isolated: bool, workspace_id: String, owner_id: String, @@ -56,6 +57,8 @@ struct RecallScope { #[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] struct SourceFields { + #[serde(default, skip_serializing_if = "Option::is_none")] + cost_root_agent: Option, // Required signed provenance: old payloads must not default to unisolated. owner_isolated: bool, workspace_id: String, @@ -79,6 +82,7 @@ impl ParentSource { pub(crate) fn capture(proof: &dyn crate::runtime::turn_source::TurnSourceProof) -> Self { Self { owner_isolated: proof.owner_isolated(), + cost_root_agent: proof.cost_root_agent(), workspace_id: proof.workspace_id().to_owned(), owner_id: proof.owner_id().to_owned(), session_key: proof.session_key().to_owned(), @@ -95,6 +99,9 @@ impl ParentSource { memory_scope: proof.memory_scope().clone(), } } + pub(crate) fn cost_root_agent(&self) -> Option { + self.cost_root_agent.clone() + } pub(crate) const fn owner_isolated(&self) -> bool { self.owner_isolated } @@ -163,6 +170,7 @@ impl ParentSource { fn process_payload(&self) -> anyhow::Result { let fields = SourceFields { owner_isolated: self.owner_isolated, + cost_root_agent: self.cost_root_agent.clone(), workspace_id: self.workspace_id.clone(), owner_id: self.owner_id.clone(), session_key: self.session_key.clone(), @@ -234,9 +242,13 @@ impl ParentSource { let fields: SourceFields = serde_json::from_str(&snapshot.payload)?; anyhow::ensure!( fields.task_run_id.is_none() - && fields.surface == "interactive" - && fields.policy_channel == "terminal" - && fields.policy_sender == "local-user" + && ((fields.surface == "interactive" + && fields.policy_channel == "terminal" + && fields.policy_sender == "local-user") + || (fields.surface == "server" + && fields.policy_channel == "mailbox" + && fields.policy_sender == "session" + && fields.cost_root_agent.is_some())) && !fields.run_id.is_empty() && !fields.session_key.is_empty() && fields.run_id != worker.run_id @@ -244,7 +256,7 @@ impl ParentSource { && fields.owner_id == publication.owner() && worker.parent_run_id.as_deref() == Some(fields.run_id.as_str()) && worker.owner_id.as_deref() == Some(fields.owner_id.as_str()) - && worker.session_scope_key == fields.session_key + && worker.session_scope_key.starts_with("spawn:") && worker.scope_channel.as_deref() == Some(fields.policy_channel.as_str()) && worker.scope_sender.as_deref() == Some(fields.policy_sender.as_str()) && worker.scope_chat_type.as_deref() == Some(fields.policy_chat_type.as_str()) @@ -258,6 +270,7 @@ impl ParentSource { ); Ok(Self { owner_isolated: fields.owner_isolated, + cost_root_agent: fields.cost_root_agent, workspace_id: fields.workspace_id, owner_id: fields.owner_id, session_key: fields.session_key, @@ -270,7 +283,11 @@ impl ParentSource { policy_channel: fields.policy_channel, policy_sender: fields.policy_sender, policy_chat_type: fields.policy_chat_type, - surface: TurnSurfaceKind::Interactive, + surface: if fields.surface == "server" { + TurnSurfaceKind::Server + } else { + TurnSurfaceKind::Interactive + }, memory_scope: MemoryWriteContext { agent_partition: super::inherited_partition(fields.memory_scope.agent_partition.as_ref()), session_key: None, @@ -349,6 +366,7 @@ impl ParentSource { ); Ok(Self { owner_isolated: fields.owner_isolated, + cost_root_agent: fields.cost_root_agent, workspace_id: fields.workspace_id, owner_id: fields.owner_id, session_key: fields.session_key, @@ -407,6 +425,7 @@ mod tests { fn parent(owner_isolated: bool) -> ParentSource { ParentSource { + cost_root_agent: None, owner_isolated, workspace_id: "prx_workspace".to_owned(), owner_id: "prx_user".to_owned(), diff --git a/src/runtime/child_source/publication.rs b/src/runtime/child_source/publication.rs index 98fe7f554..6223a7bee 100644 --- a/src/runtime/child_source/publication.rs +++ b/src/runtime/child_source/publication.rs @@ -2,7 +2,7 @@ //! operator children, the ordinary process launch and the execution-policy //! proof carried into an issued child grant. mod operator; -pub(crate) use operator::OperatorChildPublication; +pub(crate) use operator::IndependentChildPublication; mod ordinary_process; pub(crate) use ordinary_process::OrdinaryProcessLaunch; @@ -132,6 +132,18 @@ impl PartialEq for OrdinaryChildPublication { impl Eq for OrdinaryChildPublication {} impl OrdinaryChildPublication { + pub(crate) fn watch_mailbox_children(&self) -> anyhow::Result<()> { + let agent = self.inner.source.memory_scope().agent_partition.as_ref().map_or_else( + || "main".to_owned(), + |partition| crate::cost::types::RootAgent::from_partition(partition).name, + ); + crate::runtime::mailbox_child::watch( + Arc::clone(&self.inner.service), + self.inner.source.owner_id().to_owned(), + self.inner.source.session_key().to_owned(), + agent, + ) + } pub(crate) fn parent_authority(&self) -> &crate::runtime::child_source::ParentAuthority { &self.inner.authority } diff --git a/src/runtime/child_source/publication/operator.rs b/src/runtime/child_source/publication/operator.rs index 8db20c330..a23e0aeb3 100644 --- a/src/runtime/child_source/publication/operator.rs +++ b/src/runtime/child_source/publication/operator.rs @@ -22,13 +22,13 @@ use std::sync::Arc; /// Frozen upper bound for an operator-launched child below Full (a Full task /// is not limited by it, R51). The child still needs its own source/lifetime /// admission and per-call policy/approval checks. -pub(crate) struct OperatorChildPublication { +pub(crate) struct IndependentChildPublication { service: Arc, source: crate::runtime::turn_source::OwnedTurnSourceProof, authority: crate::runtime::child_source::ParentAuthority, } -impl OperatorChildPublication { +impl IndependentChildPublication { /// The direct names an operator process child is sealed with (D5). pub(crate) fn chat_lineage_direct_tools(&self) -> Option> { self.service.chat_lineage_direct_tools() @@ -42,7 +42,7 @@ impl OperatorChildPublication { memory: &Arc, security: &Arc, ) -> anyhow::Result { - service.verify_operator_spawn_source(source, generation, memory, security)?; + service.verify_independent_child_source(source, generation, memory, security)?; // R26: the operator child is funded from the publication's runtime // holder, which pins the same generation and security policy. anyhow::ensure!( @@ -113,7 +113,7 @@ impl OperatorChildPublication { security: &Arc, ) -> anyhow::Result<()> { self.service - .verify_operator_spawn_source(source, generation, memory, security)?; + .verify_independent_child_source(source, generation, memory, security)?; anyhow::ensure!( source.owner_id() == self.source.owner_id() && source.session_key() == self.source.session_key() @@ -147,7 +147,7 @@ impl OperatorChildPublication { } } -impl OperatorChildPublication { +impl IndependentChildPublication { pub(crate) fn loop_runtime(&self) -> anyhow::Result<&PublicationLoopRuntime> { self.service .loop_runtime @@ -166,8 +166,10 @@ impl OperatorChildPublication { ); task.verify()?; let parent = &self.service; + let mailbox = task.mailbox_turn(); + let child_names: BTreeSet = registry.iter().map(|tool| tool.name().to_owned()).collect(); anyhow::ensure!( - Arc::ptr_eq(®istry, &parent.registry), + mailbox || Arc::ptr_eq(®istry, &parent.registry), "operator task registry differs from source" ); // Full operators start Full children; below Full a named agent @@ -178,6 +180,12 @@ impl OperatorChildPublication { parent.security.autonomy, ) .unwrap_or(parent.security.autonomy); + let level = if mailbox { parent.security.autonomy } else { level }; + let registry = if mailbox { + Arc::clone(&parent.registry) + } else { + registry + }; let security = if level == parent.security.autonomy { Arc::clone(&parent.security) } else { @@ -224,8 +232,16 @@ impl OperatorChildPublication { policy.excluded_names.insert(entry.public_name.clone()); } } + if mailbox { + names.retain(|name| child_names.contains(name)); + } policy.allowed_tools = Some(names); } + if mailbox { + policy + .excluded_names + .extend(["sessions_spawn".to_owned(), "delegate".to_owned()]); + } parent.catalog.check_parity(&execution)?; let policy_version = pinned_policy_version(&parent.generation.effective, &security, &policy, &parent.state_key)?; @@ -291,7 +307,7 @@ impl OperatorChildPublication { } } -impl OperatorChildPublication { +impl IndependentChildPublication { /// `level` is the centrally derived child level, including Full /// inheritance from the operator, sealed into the publication. pub(crate) fn bind_process_publication( @@ -331,7 +347,7 @@ impl OperatorChildPublication { } } -impl OperatorChildPublication { +impl IndependentChildPublication { pub(crate) fn bind_process_snapshots( &self, id: uuid::Uuid, @@ -360,7 +376,7 @@ impl OperatorChildPublication { impl TurnRuntimeService { /// Local operator commands retain the actual Interactive publication. /// This validates source provenance without inventing a model decision. - pub(crate) fn verify_operator_spawn_source( + pub(crate) fn verify_independent_child_source( &self, source: &dyn TurnSourceProof, generation: &Arc, @@ -368,17 +384,24 @@ impl TurnRuntimeService { security: &Arc, ) -> anyhow::Result<()> { anyhow::ensure!( - self.surface == TurnSurfaceKind::Interactive + ((self.surface == TurnSurfaceKind::Interactive + && source.policy_channel() == "terminal" + && source.policy_sender() == "local-user") + || (self.surface == TurnSurfaceKind::Server + && source.mailbox_child_source_id().is_some() + && source.policy_channel() == "mailbox" + && source.policy_sender() == "session")) && Arc::ptr_eq(&self.generation, generation) && Arc::ptr_eq(&self.memory, memory) && Arc::ptr_eq(&self.security, security) - && self.child_scope().is_none() - && source.policy_channel() == "terminal" - && source.policy_sender() == "local-user", + && self.child_scope().is_none(), "operator spawn differs from its actual runtime publication" ); crate::runtime::turn_context::validate_agent_turn_origin(&self.generation, self.surface, source)?; self.check_live_parity()?; + if source.mailbox_child_source_id().is_some() { + return Ok(()); + } let entry = self .catalog .entry_for_public_name("sessions_spawn") diff --git a/src/runtime/child_source/tests.rs b/src/runtime/child_source/tests.rs index f9789e368..955d0273e 100644 --- a/src/runtime/child_source/tests.rs +++ b/src/runtime/child_source/tests.rs @@ -398,7 +398,7 @@ async fn operator_task_cells( drift: &AtomicUsize, ) -> anyhow::Result<()> { let claimed = crate::runtime::operator_spawn::claim(&args)?.context("operator source not in scope")?; - let binding = Arc::new(super::ChildProviderBinding::build_operator(&claimed)?); + let binding = Arc::new(super::ChildProviderBinding::build_independent(&claimed)?); let mut scope = crate::runtime::envelope::RuntimeEnvelope::sessions_spawn( claimed.fabric().workspace_id(), "prx_operator_session", diff --git a/src/runtime/decision_accounting.rs b/src/runtime/decision_accounting.rs index fc5a3d5ec..ae34ce804 100644 --- a/src/runtime/decision_accounting.rs +++ b/src/runtime/decision_accounting.rs @@ -95,6 +95,12 @@ impl AccountingScope { self.root_agent = partition.map(crate::cost::types::RootAgent::from_partition); self } + pub(crate) fn with_cost_root_agent(mut self, receiver: Option) -> Self { + if receiver.is_some() { + self.root_agent = receiver; + } + self + } pub(crate) fn money_owner(&self) -> Arc { Arc::clone( diff --git a/src/runtime/mailbox_child.rs b/src/runtime/mailbox_child.rs new file mode 100644 index 000000000..79fb61960 --- /dev/null +++ b/src/runtime/mailbox_child.rs @@ -0,0 +1,281 @@ +//! Fresh child continuation authority from a verified, adopted mailbox input. +mod approvals; +mod driver; +mod publication; +pub(crate) use approvals::no_surface; +pub(crate) use driver::watch; +#[derive(Debug, thiserror::Error)] +#[error("child_session_busy")] +pub(crate) struct ChildBusy; +use crate::memory::child_sessions::ChildSessionRecord; +use crate::messaging::runtime::{MessageInput, MessagingRuntime}; +use crate::runtime::turn_source::TurnSourceProof; +use anyhow::{Context, Result, ensure}; +use std::sync::Arc; + +pub(crate) struct MailboxChildSource { + source: crate::runtime::operator_spawn::ChildLaunchSource, + args: serde_json::Value, +} +/// Only this module can construct the sealed mailbox source proof. +pub(crate) struct MailboxChildProof { + session_key: String, + id: uuid::Uuid, + record: ChildSessionRecord, + event: String, + input: String, + generation: Arc, + binding: crate::agent::entry::AgentModelBinding, + memory: crate::memory::principal::MemoryWriteContext, + principal: crate::memory::MemoryPrincipal, +} +impl MailboxChildSource { + pub(crate) async fn admit( + parent: &Arc, + record: ChildSessionRecord, + input: MessageInput, + live: Option, + ) -> Result { + let runtime = MessagingRuntime::for_config(&parent.generation.effective)?; + input.verify(&runtime)?; + let mailbox_scope = runtime.resolve_scope(&input.message.to)?; + let memory = Arc::clone(&parent.memory); + let stored = memory + .child_session_store() + .context("child storage unavailable")? + .sessions(&record.workspace, &record.owner)? + .into_iter() + .find(|candidate| candidate.session_key == record.session_key) + .context("child_session_unknown")?; + ensure!( + stored.parent_session == record.parent_session && stored.agent == record.agent, + "child receiver changed" + ); + let record = stored; + ensure!( + input.auto_start() + && input.message.to.owner == record.owner + && input.message.to.session == record.session_key + && input.message.to.agent == record.agent, + "mailbox receiver differs from persisted child" + ); + let pinned = &parent.generation.effective; + let mut current = if pinned.config_path.exists() { + let directory = pinned + .config_path + .parent() + .and_then(std::path::Path::to_str) + .context("receiver config directory unavailable")?; + crate::config::Config::load_existing_read_only_with_config_dir(Some(directory)).await? + } else { + pinned.as_ref().clone() + }; + current.workspace_dir = pinned.workspace_dir.clone(); + current.config_path = pinned.config_path.clone(); + let config = ¤t; + let root_agent = runtime + .store + .logical_agent(&record.workspace, &record.owner, &record.parent_session)? + .unwrap_or_else(|| "main".to_owned()); + let root_level = if root_agent == "main" { + config.autonomy.level + } else { + let root = config + .agents + .get(&root_agent) + .filter(|agent| agent.enabled) + .context("root agent unavailable")?; + crate::security::agent_level::agent_level(root.autonomy, config.autonomy.level) + }; + let now = crate::security::agent_level::named_child_level(config, Some(&record.agent), root_level) + .unwrap_or(root_level); + let level = record.level.min(now); + let publication = publication::fresh(parent, level, ¤t)?; + let catalog = &publication.provider_catalog; + let named = config.agents.get(&record.agent).filter(|agent| { + crate::providers::ProviderId::of(&agent.provider) == crate::providers::ProviderId::of(&record.provider) + }); + let credential = named.map_or_else( + || crate::providers::selection::credential_for(config, &record.provider), + |agent| { + agent.credential_ref.as_ref().map_or_else( + || { + if agent.api_key.as_ref().is_some_and(|key| !key.trim().is_empty()) { + crate::providers::credentials::CredentialRef::LegacyInline( + crate::providers::credentials::LegacySlot::Agent(record.agent.clone()), + ) + } else { + crate::providers::selection::credential_for(config, &record.provider) + } + }, + |id| crate::providers::credentials::CredentialRef::Profile { id: id.clone() }, + ) + }, + ); + let resolved = crate::providers::selection::check_with( + config, + catalog, + &record.provider, + &record.model, + credential, + &crate::providers::catalog::Requirement::chat(), + crate::providers::catalog::UnknownPolicy::Invocation, + )?; + let route = crate::providers::selection::route_target(catalog, &record.provider, &record.model)?.cloned(); + let provider = Arc::from(crate::providers::create_routed_provider_for( + &resolved, + catalog, + config, + &crate::providers::provider_runtime_options_from_config(config), + )?); + let event_id = input + .receipt + .adopted_message_event_id + .context("mailbox adoption missing")? + .to_string(); + let event = memory + .find_owned_message_event(&record.workspace, &record.owner, &event_id) + .await? + .context("mailbox adoption was erased")?; + ensure!( + event.content == input.text && event.role == "user" && event.source.as_str() == "prx_mailbox", + "adopted source differs" + ); + let scope = crate::memory::principal::MemoryWriteContext { + workspace_id: Some(record.workspace.clone()), + owner_id: Some(record.owner.clone()), + session_key: Some(record.session_key.clone()), + channel: Some("mailbox".into()), + chat_type: Some("private".into()), + chat_id: Some(record.parent_session.clone()), + sender_id: Some("session".into()), + raw_sender: Some("session".into()), + require_owner_match: true, + agent_partition: Some(runtime.store.partition(&mailbox_scope)?), + }; + let principal = crate::memory::MemoryPrincipal { + workspace_id: record.workspace.clone(), + owner_id: Some(record.owner.clone()), + session_key: Some(record.session_key.clone()), + agent_id: Some(record.agent.clone()), + persona_id: None, + channel: scope.channel.clone(), + sender: scope.raw_sender.clone(), + require_owner_match: true, + legacy_session_key: None, + agent_partition: scope.agent_partition.clone(), + }; + let proof = MailboxChildProof { + session_key: record.parent_session.clone(), + id: input.message.id, + record: record.clone(), + event: event_id, + input: input.text.clone(), + generation: Arc::clone(&publication.generation), + binding: crate::agent::entry::AgentModelBinding::from_resolved(&resolved, route.clone()), + memory: scope, + principal, + }; + let source = crate::runtime::operator_spawn::ChildLaunchSource::from_mailbox( + &proof, + publication, + provider, + resolved, + route, + record.clone(), + input.clone(), + live, + ) + .await?; + let mut args = serde_json::json!({"action":"continue", "session_key":record.session_key, + "task":input.text,"provider":record.provider,"model":record.model,"mode":record.mode}); + if record.agent != "main" { + args.as_object_mut() + .context("continuation arguments must be an object")? + .insert("agent".into(), record.agent.into()); + } + Ok(Self { source, args }) + } + pub(crate) async fn continue_turn(self, tools: &[Box]) -> Result { + let tool = tools + .iter() + .find(|tool| tool.supports_name("sessions_spawn")) + .context("child execution unavailable")?; + let result = self + .source + .scope(tool.execute_named("sessions_spawn", self.args)) + .await?; + ensure!( + result.success, + "{}", + result.error.as_deref().unwrap_or("mailbox child continuation refused") + ); + Ok(result.output) + } +} +impl TurnSourceProof for MailboxChildProof { + fn cost_root_agent(&self) -> Option { + Some(crate::cost::types::RootAgent { + owner_id: self.record.owner.clone(), + name: self.record.agent.clone(), + }) + } + fn mailbox_child_source_id(&self) -> Option { + Some(self.id) + } + fn owner_isolated(&self) -> bool { + true + } + fn source_memory_principal(&self) -> crate::memory::MemoryPrincipal { + self.principal.clone() + } + fn workspace_id(&self) -> &str { + &self.record.workspace + } + fn owner_id(&self) -> &str { + &self.record.owner + } + fn session_key(&self) -> &str { + &self.session_key + } + // Lineage identifies the durable root; authority is newly issued from id. + fn run_id(&self) -> &str { + &self.record.parent_run + } + fn routing_input(&self) -> &str { + &self.input + } + fn provider_name(&self) -> &str { + &self.record.provider + } + fn model_name(&self) -> &str { + &self.record.model + } + fn config_source_revision(&self) -> &str { + &self.generation.source_revision.fingerprint_sha256 + } + fn source_event_id(&self) -> Option<&str> { + Some(&self.event) + } + fn memory_scope(&self) -> &crate::memory::principal::MemoryWriteContext { + &self.memory + } + fn model_binding(&self) -> &crate::agent::entry::AgentModelBinding { + &self.binding + } + fn config_generation_id(&self) -> u64 { + self.generation.id.0 + } + fn surface(&self) -> crate::tools::capability::turn_state::TurnSurfaceKind { + crate::tools::capability::turn_state::TurnSurfaceKind::Server + } + fn policy_channel(&self) -> &str { + "mailbox" + } + fn policy_sender(&self) -> &str { + "session" + } + fn policy_chat_type(&self) -> &str { + "private" + } +} diff --git a/src/runtime/mailbox_child/approvals.rs b/src/runtime/mailbox_child/approvals.rs new file mode 100644 index 000000000..81353058c --- /dev/null +++ b/src/runtime/mailbox_child/approvals.rs @@ -0,0 +1,30 @@ +//! Explicit denial when the receiving root has no live approval adapter. +use crate::agent::live_frames::{LiveFrameSink, LiveTurn, LiveTurnRef}; +use crate::agent::turn_contracts::ToolLoopEvent; +use std::sync::Arc; +struct NoSurface; +impl LiveFrameSink for NoSurface { + fn emit(&self, _: &ToolLoopEvent) {} + fn thinking(&self) {} + fn awaiting_approval(&self, _: &str) {} + fn child_denial(&self, _: &str, _: &str) {} +} +#[async_trait::async_trait] +impl LiveTurn for NoSurface { + fn frames( + &self, + _: &crate::runtime::envelope::RuntimeEnvelope, + _: &std::collections::HashSet, + ) -> Arc { + Arc::new(Self) + } + async fn approve(&self, _: crate::tools::ToolApprovalRequest) -> crate::tools::ToolApprovalDecision { + crate::tools::ToolApprovalDecision::Denied { + cause: crate::tools::ApprovalDenialCause::NoApprovalSurface, + reason: crate::tools::execution::APPROVAL_DENIED_NO_APPROVAL_SURFACE.to_owned(), + } + } +} +pub(crate) fn no_surface() -> LiveTurnRef { + LiveTurnRef(Arc::new(NoSurface)) +} diff --git a/src/runtime/mailbox_child/driver.rs b/src/runtime/mailbox_child/driver.rs new file mode 100644 index 000000000..ff5f1393c --- /dev/null +++ b/src/runtime/mailbox_child/driver.rs @@ -0,0 +1,146 @@ +//! Agent/channel/scheduled backends retain a publication, never a parent turn. +use super::{ChildBusy, MailboxChildSource}; +use crate::memory::child_sessions::ChildSessionRecord; +use crate::runtime::turn_publication::TurnRuntimeService; +use anyhow::{Context, Result}; +use std::sync::{Arc, OnceLock, Weak}; +type Key = (String, String, String); +static ROOTS: OnceLock>>> = OnceLock::new(); +struct Host { + key: Key, + parent: parking_lot::RwLock>, +} +impl Drop for Host { + fn drop(&mut self) { + if let Some(roots) = ROOTS.get() { + roots.lock().remove(&self.key); + } + } +} +fn busy(record: &ChildSessionRecord) -> bool { + record + .runs + .last() + .and_then(|run| crate::runtime::registry::resolve_address(run)) + .is_some() +} +pub(crate) fn watch(parent: Arc, owner: String, root: String, agent: String) -> Result<()> { + use crate::tools::capability::turn_state::TurnSurfaceKind; + // Those live backends own their UI/rf approval adapters and current host. + if matches!( + parent.surface, + TurnSurfaceKind::Interactive | TurnSurfaceKind::Server | TurnSurfaceKind::Worker + ) { + return Ok(()); + } + if parent.generation.effective.memory.backend != "sqlite" { + return Ok(()); + } + let runtime = crate::messaging::runtime::MessagingRuntime::for_config(&parent.generation.effective)?; + let address = runtime.address(&owner, &root, &agent); + let scope = runtime.store.session_scope(&runtime.workspace, &address, false)?; + let key = (runtime.workspace.clone(), owner.clone(), root.clone()); + let host = { + let mut roots = ROOTS.get_or_init(Default::default).lock(); + roots.retain(|_, host| host.strong_count() > 0); + if let Some(host) = roots.get(&key).and_then(Weak::upgrade) { + *host.parent.write() = parent; + return Ok(()); + } + let host = Arc::new(Host { + key: key.clone(), + parent: parking_lot::RwLock::new(parent), + }); + roots.insert(key, Arc::downgrade(&host)); + host + }; + tokio::spawn(async move { + let mut interval = tokio::time::interval(std::time::Duration::from_millis(100)); + loop { + interval.tick().await; + if runtime.store.validate_scope(&scope, &address).is_err() { + break; + } + let parent = Arc::clone(&host.parent.read()); + let Some(store) = parent.memory.child_session_store() else { + break; + }; + let Ok(records) = store.sessions(&runtime.workspace, &owner) else { + break; + }; + for mut record in records + .into_iter() + .filter(|record| record.parent_session == root && !busy(record)) + { + record.context.clear(); + let address = runtime.address(&owner, &record.session_key, &record.agent); + let idle_host = Arc::clone(&host); + let idle_record = record.clone(); + let idle = Arc::new(move || { + idle_host + .parent + .read() + .memory + .child_session_store() + .and_then(|store| store.sessions(&idle_record.workspace, &idle_record.owner).ok()) + .is_some_and(|records| { + records + .iter() + .any(|record| record.session_key == idle_record.session_key && !busy(record)) + }) + }); + let host = Arc::clone(&host); + let result = crate::messaging::receiver::register_idle( + Arc::clone(&runtime), + address, + Arc::new(move |input| { + let parent = Arc::clone(&host.parent.read()); + let record = record.clone(); + Box::pin(async move { + if busy(&record) { + return Err(ChildBusy.into()); + } + let cleanup = Arc::new(crate::runtime::turn_cleanup::CleanupTracker::default()); + cleanup + .scope(async { + MailboxChildSource::admit( + &parent, + record.clone(), + input.clone(), + Some(super::no_surface()), + ) + .await? + .continue_turn(parent.registry.as_ref()) + .await?; + let mut interval = tokio::time::interval(std::time::Duration::from_millis(100)); + loop { + interval.tick().await; + let records = parent + .memory + .child_session_store() + .context("child store unavailable")? + .sessions(&record.workspace, &record.owner)?; + let Some(current) = + records.iter().find(|current| current.session_key == record.session_key) + else { + break; + }; + if !busy(current) { + break; + } + } + Ok(()) + }) + .await + }) + }), + idle, + ); + if let Err(error) = result { + tracing::warn!(error=%crate::agent::diagnostics::error_class(&error),"child receiver registration refused"); + } + } + } + }); + Ok(()) +} diff --git a/src/runtime/mailbox_child/publication.rs b/src/runtime/mailbox_child/publication.rs new file mode 100644 index 000000000..8a06945fc --- /dev/null +++ b/src/runtime/mailbox_child/publication.rs @@ -0,0 +1,78 @@ +//! A fresh capped publication; no ended turn context or approval grant is kept. +use crate::runtime::turn_publication::TurnRuntimeService; +use std::sync::Arc; +pub(super) fn fresh( + parent: &Arc, + level: crate::security::AutonomyLevel, + config: &crate::config::Config, +) -> anyhow::Result> { + use crate::decision_engine::prediction::factory::{DecisionBackendFactory, FactoryDeps}; + let generation = crate::config::ConfigGeneration::for_child(config)?; + let provider_catalog = crate::providers::selection::catalog_for(config); + let security = Arc::new(crate::security::SecurityPolicy { + autonomy: level, + ..crate::security::SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir) + }); + let mut policy = crate::runtime::turn_publication::surface_policy( + parent.surface, + &config.tool_tiering.at_level(level, security.evaluation_sandbox), + ); + policy + .direct_names + .extend(parent.publication_policy.direct_names.iter().cloned()); + policy + .excluded_names + .extend(parent.publication_policy.excluded_names.iter().cloned()); + if level != crate::security::AutonomyLevel::Full { + policy.allowed_tools = parent.publication_policy.allowed_tools.clone(); + } + let policy_version = crate::runtime::turn_publication::service::pinned_policy_version( + config, + &security, + &policy, + &parent.state_key, + )?; + let deps = || FactoryDeps { + catalog: &provider_catalog, + key: Some(Arc::clone(&parent.state_key)), + transports: &crate::decision_engine::prediction::compatible_http::HttpDecisionTransports, + config_generation: generation.id.0, + events: Arc::clone(&parent.events), + }; + Ok(Arc::new(TurnRuntimeService { + runtime: Arc::new(crate::runtime::turn_context::TurnRuntimeHolder::new( + Arc::new(crate::runtime::ingress_recovery::RecoveryScope::unrecorded( + Arc::clone(&parent.memory), + config.workspace_dir.clone(), + crate::tools::capability::turn_state::TurnSurfaceKind::Server, + )), + None, + config, + &security, + )), + advisory: crate::runtime::decision_advisory::DecisionAdvisory::for_publication(&generation.effective, deps())?, + memory_loader: parent.memory_loader.clone(), + loop_runtime: parent.loop_runtime.clone(), + publication_policy: policy, + chat_lineage: parent.chat_lineage, + ordinary_parent: None, + operator_task: None, + operator_process: None, + ordinary_task: None, + ordinary_process: None, + service_id: uuid::Uuid::new_v4(), + surface: crate::tools::capability::turn_state::TurnSurfaceKind::Server, + generation: Arc::clone(&generation), + catalog: Arc::clone(&parent.catalog), + provider_catalog: provider_catalog.clone(), + factory: DecisionBackendFactory::from_config(config, deps())?, + events: Arc::clone(&parent.events), + state_key: Arc::clone(&parent.state_key), + policy_version, + recordable: parent.recordable, + registry: Arc::clone(&parent.registry), + execution: Arc::clone(&parent.execution), + memory: Arc::clone(&parent.memory), + security, + })) +} diff --git a/src/runtime/mod.rs b/src/runtime/mod.rs index 572df87ad..8731eafa1 100644 --- a/src/runtime/mod.rs +++ b/src/runtime/mod.rs @@ -119,6 +119,7 @@ mod tests { } } +pub(crate) mod mailbox_child; pub(crate) mod operator_spawn; pub(crate) mod ingress_recovery; diff --git a/src/runtime/operator_spawn.rs b/src/runtime/operator_spawn.rs index 396da1e45..5ab232982 100644 --- a/src/runtime/operator_spawn.rs +++ b/src/runtime/operator_spawn.rs @@ -1,4 +1,5 @@ -//! Typed local-operator ingress, separate from model delegation authority. +//! Independent child lifetimes issued by operator or adopted-message ingress. +mod mailbox; pub(crate) mod process; pub(crate) mod task; @@ -9,7 +10,8 @@ use std::sync::{ }; use tokio_util::sync::CancellationToken; -pub(crate) struct OperatorSpawnSource { +pub(crate) struct ChildLaunchSource { + live_turn: Option, message_event: Option, message_permit: Option>, message_input: Option, @@ -22,7 +24,7 @@ pub(crate) struct OperatorSpawnSource { resolved: crate::providers::catalog::ResolvedModel, route: Option, security: Arc, - publication: crate::runtime::child_source::publication::OperatorChildPublication, + publication: crate::runtime::child_source::publication::IndependentChildPublication, task: String, claimed: AtomicBool, child_issued: AtomicBool, @@ -36,13 +38,13 @@ impl Drop for OperatorLifetime { } } -tokio::task_local! { static OPERATOR_SPAWN: Arc; } +tokio::task_local! { static OPERATOR_SPAWN: Arc; } -pub(crate) fn current() -> Option> { +pub(crate) fn current() -> Option> { OPERATOR_SPAWN.try_with(Arc::clone).ok() } -impl OperatorSpawnSource { +impl ChildLaunchSource { pub(crate) fn new( proof: &dyn TurnSourceProof, generation: Arc, @@ -65,7 +67,7 @@ impl OperatorSpawnSource { && !task.is_empty(), "operator source identity differs" ); - let publication = crate::runtime::child_source::publication::OperatorChildPublication::capture( + let publication = crate::runtime::child_source::publication::IndependentChildPublication::capture( publication, runtime, proof, @@ -90,6 +92,7 @@ impl OperatorSpawnSource { "operator model source differs from pinned PMM selection" ); Ok(Self { + live_turn: None, message_event: None, message_permit: None, message_input: None, @@ -162,7 +165,13 @@ impl OperatorSpawnSource { let root = input.message.to.agent.clone(); runtime.store.validate_scope(&scope, &input.message.to)?; self.message_permit = - crate::runtime::agent_admission::admit(&self.generation.effective, self.proof.owner_id(), &root)? + crate::runtime::agent_admission::admit(&self.generation.effective, self.proof.owner_id(), &root) + .map_err(|error| match error { + crate::runtime::agent_admission::AdmissionError::Busy => { + anyhow::Error::new(crate::runtime::mailbox_child::ChildBusy) + } + error => anyhow::Error::new(error), + })? .map(Arc::new); self.message_event = Some(id); self.message_input = Some(input.clone()); @@ -178,6 +187,9 @@ impl OperatorSpawnSource { pub(crate) fn message_permit(&self) -> Option> { self.message_permit.clone() } + pub(crate) fn live_turn(&self) -> Option { + self.live_turn.clone() + } pub(crate) async fn scope(self, work: F) -> F::Output { let _lifetime = OperatorLifetime(self.cancellation.clone()); @@ -221,6 +233,8 @@ impl OperatorSpawnSource { scope.channel = Some(self.proof.policy_channel().to_owned()); scope.sender = Some(self.proof.policy_sender().to_owned()); scope.recipient = self.proof.memory_scope().chat_id.clone(); + scope.agent_partition = + crate::runtime::child_source::inherited_partition(self.proof.memory_scope().agent_partition.as_ref()); scope.causation_event_id = self .message_event .clone() @@ -244,7 +258,7 @@ impl OperatorSpawnSource { } } -pub(crate) fn claim(args: &serde_json::Value) -> anyhow::Result>> { +pub(crate) fn claim(args: &serde_json::Value) -> anyhow::Result>> { let Some(source) = OPERATOR_SPAWN.try_with(Arc::clone).ok() else { return Ok(None); }; diff --git a/src/runtime/operator_spawn/mailbox.rs b/src/runtime/operator_spawn/mailbox.rs new file mode 100644 index 000000000..034812b3c --- /dev/null +++ b/src/runtime/operator_spawn/mailbox.rs @@ -0,0 +1,48 @@ +//! The mailbox source shares child lifecycle mechanics, never operator provenance. +use super::{Arc, AtomicBool, CancellationToken, ChildLaunchSource, OwnedTurnSourceProof}; +impl ChildLaunchSource { + pub(crate) async fn from_mailbox( + proof: &crate::runtime::mailbox_child::MailboxChildProof, + publication: Arc, + provider: Arc, + resolved: crate::providers::catalog::ResolvedModel, + route: Option, + record: crate::memory::child_sessions::ChildSessionRecord, + input: crate::messaging::runtime::MessageInput, + live_turn: Option, + ) -> anyhow::Result { + let generation = Arc::clone(&publication.generation); + let fabric = crate::memory::MemoryFabric::new(Arc::clone(&publication.memory), &record.workspace) + .with_event_recording(generation.effective.memory.event_recording_config()); + let security = Arc::clone(&publication.security); + let publication = crate::runtime::child_source::publication::IndependentChildPublication::capture( + Arc::clone(&publication), + Arc::clone(publication.runtime_holder()), + proof, + &generation, + &fabric.memory(), + &security, + )?; + let source = Self { + live_turn, + message_event: None, + message_permit: None, + message_input: None, + continuation: None, + proof: OwnedTurnSourceProof::capture(proof), + catalog: crate::providers::selection::catalog_for(&generation.effective), + generation, + fabric, + provider, + resolved, + route, + security, + publication, + task: input.text.clone(), + claimed: AtomicBool::new(false), + child_issued: AtomicBool::new(false), + cancellation: CancellationToken::new(), + }; + source.for_message(record, &input).await + } +} diff --git a/src/runtime/operator_spawn/process.rs b/src/runtime/operator_spawn/process.rs index 95f48f018..84a4348e5 100644 --- a/src/runtime/operator_spawn/process.rs +++ b/src/runtime/operator_spawn/process.rs @@ -112,14 +112,14 @@ impl VerifiedOperatorProcessPublication { } pub(crate) struct OperatorProcessLaunch { - source: std::sync::Arc, + source: std::sync::Arc, scope: crate::memory::MessageEventScope, receipt: Option>, config_generation: String, id: uuid::Uuid, } -impl super::OperatorSpawnSource { +impl super::ChildLaunchSource { pub(crate) fn capture_process( self: &std::sync::Arc, scope: &crate::memory::MessageEventScope, @@ -231,7 +231,7 @@ impl OperatorProcessLaunch { && worker.task == source.task.trim() && Some(worker.run_id.as_str()) == self.scope.run_id.as_deref() && worker.config_generation == self.config_generation - && worker.session_scope_key == source.proof.session_key() + && Some(worker.session_scope_key.as_str()) == self.scope.session_key.as_deref() && worker.owner_id == self.scope.owner_id && worker.parent_run_id == self.scope.parent_run_id && worker.agent_id == self.scope.agent_id @@ -281,12 +281,16 @@ impl OperatorProcessLaunch { }, self.scope.attempt_id.clone(), self.scope.lease_epoch, - crate::security::agent_level::named_child_level( - &source.generation.effective, - self.scope.agent_id.as_deref(), - source.security.autonomy, - ) - .unwrap_or(source.security.autonomy), + if source.is_message_continuation() { + source.security.autonomy + } else { + crate::security::agent_level::named_child_level( + &source.generation.effective, + self.scope.agent_id.as_deref(), + source.security.autonomy, + ) + .unwrap_or(source.security.autonomy) + }, )?; source.publication.verify( &source.proof, diff --git a/src/runtime/operator_spawn/task.rs b/src/runtime/operator_spawn/task.rs index 0bdb4acef..198454af4 100644 --- a/src/runtime/operator_spawn/task.rs +++ b/src/runtime/operator_spawn/task.rs @@ -1,7 +1,7 @@ //! Detached task lifetime issued only by a live explicit operator command. mod segments; -use super::{Arc, AtomicBool, CancellationToken, OperatorSpawnSource, Ordering, OwnedTurnSourceProof, TurnSourceProof}; +use super::{Arc, AtomicBool, CancellationToken, ChildLaunchSource, Ordering, OwnedTurnSourceProof, TurnSourceProof}; use crate::runtime::child_source::{ChildInputReceipt, ChildProviderBinding}; use anyhow::Context; @@ -11,7 +11,7 @@ pub(crate) struct OperatorTaskAuthority { source_event_id: Option, scope: crate::memory::MessageEventScope, sequence_claimed: AtomicBool, - source: Arc, + source: Arc, binding: Arc, run_id: String, input: String, @@ -32,7 +32,7 @@ impl Drop for OperatorTaskLifetime { } } -impl OperatorSpawnSource { +impl ChildLaunchSource { pub(crate) fn issue_task( self: &Arc, binding: Arc, @@ -42,7 +42,7 @@ impl OperatorSpawnSource { cancellation: &CancellationToken, ) -> anyhow::Result<(Arc, OperatorTaskLifetime)> { self.verify_live()?; - binding.verify_operator_source(self)?; + binding.verify_independent_source(self)?; anyhow::ensure!( self.claimed.load(Ordering::Acquire) && input == self.task.trim() @@ -140,6 +140,12 @@ impl OperatorSpawnSource { } impl OperatorTaskAuthority { + pub(crate) fn mailbox_turn(&self) -> bool { + self.source.is_message_continuation() + } + pub(crate) fn live_turn(&self) -> Option { + self.source.live_turn() + } pub(crate) const fn allowance( &self, ) -> &Arc { @@ -157,7 +163,7 @@ impl OperatorTaskAuthority { &self.source.fabric } - pub(crate) fn publication(&self) -> &crate::runtime::child_source::publication::OperatorChildPublication { + pub(crate) fn publication(&self) -> &crate::runtime::child_source::publication::IndependentChildPublication { &self.source.publication } @@ -169,7 +175,7 @@ impl OperatorTaskAuthority { anyhow::ensure!(!self.cancellation.is_cancelled(), "operator task authority is closed"); // The command may have returned. The independently owned task lifetime // remains subject to the original frozen publication and actual policy. - self.binding.verify_operator_source(&self.source)?; + self.binding.verify_independent_source(&self.source)?; self.source.publication.verify( &self.source.proof, &self.source.generation, @@ -232,6 +238,9 @@ impl OperatorTaskAuthority { } impl TurnSourceProof for OperatorTaskAuthority { + fn cost_root_agent(&self) -> Option { + self.source.proof.cost_root_agent() + } fn owner_isolated(&self) -> bool { self.source.proof.owner_isolated() } diff --git a/src/runtime/operator_spawn/task/segments.rs b/src/runtime/operator_spawn/task/segments.rs index b015acf3e..4e9a223dd 100644 --- a/src/runtime/operator_spawn/task/segments.rs +++ b/src/runtime/operator_spawn/task/segments.rs @@ -76,6 +76,8 @@ impl OperatorTaskSegments { envelope.task_id = Some(authority.run_id.clone()); envelope.source_message_event_id = proof.source_event_id().map(str::to_owned); envelope.parent_run_id = scope.parent_run_id; + envelope.parent_session_key = scope.parent_session_key; + envelope.agent_partition = scope.agent_partition; envelope.agent_id = scope.agent_id; envelope.persona_id = scope.persona_id; envelope.channel = scope.channel; @@ -85,8 +87,9 @@ impl OperatorTaskSegments { envelope.lease_epoch = scope.lease_epoch; envelope.config_generation_id = scope.config_generation_id; envelope.config_source_revision = scope.config_source_revision; - let execution = ToolExecutionContext::new(envelope, proof.policy_chat_type()) + let mut execution = ToolExecutionContext::new(envelope, proof.policy_chat_type()) .with_dispatch_origin(crate::tools::DispatchOrigin::ModelTurn); + execution.live_turn = authority.live_turn(); self.next = following; self.previous_input = next_previous; Ok((proof, execution)) diff --git a/src/runtime/turn_cleanup.rs b/src/runtime/turn_cleanup.rs index 1fdc4038b..f6b72569a 100644 --- a/src/runtime/turn_cleanup.rs +++ b/src/runtime/turn_cleanup.rs @@ -61,6 +61,41 @@ pub(crate) struct CleanupTicket { id: u64, finished: bool, } +/// Release a child publication after its last segment, including early exits. +pub(crate) struct ChildServiceRetirement { + service: Option>, + owner: Arc, + handle: tokio::runtime::Handle, +} +impl ChildServiceRetirement { + pub(crate) fn new(service: Arc) -> anyhow::Result { + Ok(Self { + service: Some(service), + owner: current_tracker().ok_or_else(|| anyhow::anyhow!("child cleanup owner missing"))?, + handle: tokio::runtime::Handle::try_current()?, + }) + } +} +impl Drop for ChildServiceRetirement { + fn drop(&mut self) { + let Some(service) = self.service.take() else { + return; + }; + match self.owner.retire(&service) { + Ok(ticket) => { + self.handle.spawn(async move { + let drained = service + .drain_writes(std::time::Instant::now() + std::time::Duration::from_secs(2)) + .await; + ticket.finish(drained); + }); + } + Err(error) => { + tracing::warn!(error=%crate::agent::diagnostics::error_class(&error),"child publication retirement refused") + } + } + } +} impl CleanupTracker { pub(crate) async fn scope(self: &Arc, work: F) -> F::Output { diff --git a/src/runtime/turn_context/opening.rs b/src/runtime/turn_context/opening.rs index ff2e88545..bb4891d58 100644 --- a/src/runtime/turn_context/opening.rs +++ b/src/runtime/turn_context/opening.rs @@ -371,6 +371,7 @@ fn accounting_scope( deadline, ) .with_root_agent(proof.memory_scope().agent_partition.as_ref()) + .with_cost_root_agent(proof.cost_root_agent()) .with_money(service.runtime.recursive_money(proof)), )) } diff --git a/src/runtime/turn_source.rs b/src/runtime/turn_source.rs index 77bf1ae52..b8a4c6a78 100644 --- a/src/runtime/turn_source.rs +++ b/src/runtime/turn_source.rs @@ -85,6 +85,7 @@ pub(crate) const fn subject_task_id(subject: Option<&crate::memory::MessageEvent } mod sealed { + impl Sealed for crate::runtime::mailbox_child::MailboxChildProof {} impl Sealed for super::OwnedTurnSourceProof {} impl Sealed for crate::runtime::operator_spawn::task::OperatorTaskAuthority {} pub trait Sealed {} @@ -96,6 +97,13 @@ mod sealed { } pub(crate) trait TurnSourceProof: sealed::Sealed + Send + Sync { + /// Opaque identity issued only after a durable mailbox-child readback. + fn mailbox_child_source_id(&self) -> Option { + None + } + fn cost_root_agent(&self) -> Option { + None + } fn h2_entry_origin(&self) -> Option<&std::sync::Arc> { None } @@ -240,6 +248,8 @@ impl TurnSourceProof for AgentTurnProof { /// from a durable child receipt and a runtime-issued parent grant. /// Neither fields nor deserialization can synthesize source authority. pub(crate) struct OwnedTurnSourceProof { + cost_root_agent: Option, + mailbox_child_source_id: Option, h2_origin: Option>, owner_isolated: bool, approval_review_adapter: Option, @@ -338,6 +348,8 @@ impl OwnedTurnSourceProof { let selection = authority.model_selection(); let generation = selection.generation; let proof = Self { + mailbox_child_source_id: None, + cost_root_agent: None, owner_isolated: parent.owner_isolated(), h2_origin: None, approval_review_adapter: None, @@ -393,6 +405,8 @@ impl OwnedTurnSourceProof { let selection = authority.model_selection(); let generation = selection.generation; let proof = Self { + mailbox_child_source_id: None, + cost_root_agent: parent.cost_root_agent(), owner_isolated: parent.owner_isolated(), h2_origin: None, approval_review_adapter: None, @@ -487,6 +501,8 @@ impl OwnedTurnSourceProof { } }; Ok(Self { + mailbox_child_source_id: None, + cost_root_agent: None, owner_isolated: actor.envelope.owner_isolated, h2_origin: None, approval_review_adapter: None, @@ -711,6 +727,8 @@ impl OwnedTurnSourceProof { pub(crate) fn capture(proof: &dyn TurnSourceProof) -> Self { Self { + mailbox_child_source_id: proof.mailbox_child_source_id(), + cost_root_agent: proof.cost_root_agent(), owner_isolated: proof.owner_isolated(), h2_origin: proof.h2_entry_origin().cloned(), approval_review_adapter: proof.approval_review_adapter(), @@ -748,6 +766,12 @@ impl OwnedTurnSourceProof { } impl TurnSourceProof for OwnedTurnSourceProof { + fn cost_root_agent(&self) -> Option { + self.cost_root_agent.clone() + } + fn mailbox_child_source_id(&self) -> Option { + self.mailbox_child_source_id + } fn h2_entry_origin(&self) -> Option<&std::sync::Arc> { self.h2_origin.as_ref() } diff --git a/src/session_worker/mailbox.rs b/src/session_worker/mailbox.rs index 5b037e9ee..b5e55a504 100644 --- a/src/session_worker/mailbox.rs +++ b/src/session_worker/mailbox.rs @@ -153,7 +153,9 @@ pub fn user_text(message: &PrxMessage) -> MailboxResult { } use base64::Engine as _; Ok(format!( - "[mailbox MIME {} base64]\n{}", + "[message from {}/{}]\n[mailbox MIME {} base64]\n{}", + message.from.session, + message.from.agent, serde_json::to_string(&message.body.mime).map_err(|_| MailboxError::InvalidMetadata)?, base64::engine::general_purpose::STANDARD.encode(&message.body.bytes) )) diff --git a/src/tools/sessions_spawn/continuation.rs b/src/tools/sessions_spawn/continuation.rs index 1a34d51ea..962f56ebe 100644 --- a/src/tools/sessions_spawn/continuation.rs +++ b/src/tools/sessions_spawn/continuation.rs @@ -87,6 +87,8 @@ impl SessionsSpawnTool { && (record.session_key == target || record.runs.iter().any(|run| run == target)) }) .context("child_session_unknown")?; + let address = crate::messaging::SessionAddr::new(fabric.workspace_id(), &owner, &record.session_key, None); + let _gate = crate::messaging::receiver::gate(&address).lock_owned().await; anyhow::ensure!( !self .active_runs @@ -98,17 +100,15 @@ impl SessionsSpawnTool { run.status, SubAgentStatus::Running | SubAgentStatus::AwaitingInput { .. } )), - "child_session_busy" + crate::runtime::mailbox_child::ChildBusy ); let mut history = store.history(&record)?; if let Some(input) = operator.as_ref().and_then(|source| source.message_input()) { - anyhow::ensure!( - history - .last() - .is_some_and(|turn| turn.role == "user" && turn.content == input.text), - "adopted input is not the pending child turn" - ); - history.pop(); + let position = history + .iter() + .rposition(|turn| turn.role == "user" && turn.content == input.text) + .context("adopted input is not the pending child turn")?; + history.remove(position); } let mut launch = args.clone(); let object = launch diff --git a/src/tools/sessions_spawn/message_lifetime.rs b/src/tools/sessions_spawn/message_lifetime.rs new file mode 100644 index 000000000..4b36d12b4 --- /dev/null +++ b/src/tools/sessions_spawn/message_lifetime.rs @@ -0,0 +1,50 @@ +//! Mailbox-triggered run ownership and erase-time transcript cache removal. +use super::{HistoryEntry, SubAgentRun, SubAgentStatus}; +use std::sync::Arc; +use tokio::sync::RwLock; +pub(super) fn retain( + config: &crate::config::Config, + input: Option<&crate::messaging::runtime::MessageInput>, + runs: &Arc>>, + stop: Arc, +) -> anyhow::Result> { + let Some(input) = input else { + return Ok(None); + }; + let runtime = crate::messaging::runtime::MessagingRuntime::for_config(config)?; + let weak = Arc::downgrade(runs); + let alive = weak.clone(); + let session = input.message.to.session.clone(); + let handle = tokio::runtime::Handle::try_current()?; + runtime.register_cache( + input, + format!("{:p}:{session}", Arc::as_ptr(runs)), + Arc::new(move || alive.strong_count() > 0), + Arc::new(move |lease, joined| { + if let Some(runs) = weak.upgrade() { + let session = session.clone(); + handle.spawn(async move { + let _lease = lease; + for completed in joined { + completed.cancelled().await; + } + let histories: Vec>>> = { + let mut runs = runs.write().await; + runs.iter_mut() + .filter(|run| run.session_scope_key == session) + .map(|run| { + run.task.clear(); + run.status = SubAgentStatus::Failed("history_erased".into()); + Arc::clone(&run.history) + }) + .collect() + }; + for history in histories { + history.write().await.clear(); + } + }); + } + }), + )?; + Ok(Some(runtime.hold_turn(input, stop)?)) +} diff --git a/src/tools/sessions_spawn/mod.rs b/src/tools/sessions_spawn/mod.rs index 5542493e9..8703c8ecf 100644 --- a/src/tools/sessions_spawn/mod.rs +++ b/src/tools/sessions_spawn/mod.rs @@ -28,6 +28,7 @@ mod events; mod failure; mod live_usage; mod memory_scope; +mod message_lifetime; mod monitor; mod owned_process; mod process_control; diff --git a/src/tools/sessions_spawn/spawn.rs b/src/tools/sessions_spawn/spawn.rs index a1685a3e6..9083118d1 100644 --- a/src/tools/sessions_spawn/spawn.rs +++ b/src/tools/sessions_spawn/spawn.rs @@ -231,6 +231,14 @@ impl SessionsSpawnTool { }, crate::runtime::child_source::publication::OrdinaryChildPublication::level, ); + let child_level = if operator_source + .as_ref() + .is_some_and(|source| source.is_message_continuation()) + { + launch_security.autonomy + } else { + child_level + }; let provider_options = &providers::provider_runtime_options_from_config(child_model_config); let spawn_config = &child_model_config.sessions_spawn; let agents = &child_model_config.agents; @@ -362,6 +370,21 @@ impl SessionsSpawnTool { // source keeps its authenticated session. let session_scope_key = super::continuation::current().map_or_else(|| spawn_session_key(&run_id), |seed| seed.record.session_key); + let _new_session_gate = if super::continuation::current().is_none() { + let owner = spawn_scope + .as_ref() + .and_then(|scope| scope.owner_id.as_deref()) + .context("child owner missing")?; + let address = crate::messaging::SessionAddr::new( + child_model_config.workspace_dir.to_string_lossy(), + owner, + &session_scope_key, + None, + ); + Some(crate::messaging::receiver::gate(&address).lock_owned().await) + } else { + None + }; // The registry imposes no global fan-out or nesting limit. A child's // sealed delegation grant independently bounds its depth. An operator sees every @@ -448,7 +471,10 @@ impl SessionsSpawnTool { // `None` (no trusted scope) falls back at announce time to the shared // active channel, preserving single-channel / legacy behaviour. let run_channel_name = spawn_scope.as_ref().map(|scope| scope.channel.clone()); - let operator_channel = if operator_source.is_some() { + let operator_channel = if operator_source + .as_ref() + .is_some_and(|source| !source.is_message_continuation()) + { let channel = self.resolve_announce_channel(run_channel_name.as_deref()).await; anyhow::ensure!( Some(channel.name()) == run_channel_name.as_deref(), @@ -487,6 +513,9 @@ impl SessionsSpawnTool { // with `announce: true` at the top level delivers one message per member // on top of the parent's summary. let announce_result = batch_id.is_none() + && !operator_source + .as_ref() + .is_some_and(|source| source.is_message_continuation()) && args .get("announce") .and_then(serde_json::Value::as_bool) @@ -803,6 +832,9 @@ impl SessionsSpawnTool { ) .await?; + if let Some(publication) = ordinary_publication { + publication.watch_mailbox_children()?; + } if mode == "process" { let process_parent_frames = caller.as_ref().and_then(|caller| { let context = caller.context(); @@ -858,6 +890,19 @@ impl SessionsSpawnTool { let history_arc: Arc>> = Arc::new(RwLock::new(super::continuation::seed_history())); let process_control = ProcessRunControl::new(); + let stop_control = Arc::clone(&process_control); + let runtime_handle = tokio::runtime::Handle::try_current()?; + let message_turn = super::message_lifetime::retain( + child_model_config, + message_input.as_ref(), + &self.active_runs, + Arc::new(move || { + let control = Arc::clone(&stop_control); + runtime_handle.spawn(async move { + let _ = control.request_termination("history_erased").await; + }); + }), + )?; // Process-mode steering: the sender lives in the registry exactly as // it does for task mode, so `sessions_send` / `sessions_spawn:steer` // reach an OS-process sub-agent through the same code path. The @@ -1066,6 +1111,7 @@ impl SessionsSpawnTool { crate::agent::idle::scope_beat(Some(Arc::clone(&monitor_progress)), async move { let _message_permit=message_permit; let _message_input=message_input; + let _message_turn=message_turn; async { tracing::info!(run_id = %rid, "Sub-agent process starting"); @@ -1420,7 +1466,7 @@ impl SessionsSpawnTool { let mut provider_name = resolved_provider_name; let mut model = resolved_model; let child_provider_binding = if let Some(source) = &operator_source { - let binding = Arc::new(crate::runtime::child_source::ChildProviderBinding::build_operator( + let binding = Arc::new(crate::runtime::child_source::ChildProviderBinding::build_independent( source, )?); provider_name = binding.provider_name().to_owned(); @@ -1567,6 +1613,13 @@ impl SessionsSpawnTool { // owns cleanup; parenting this to the caller would cancel valid work // when that caller returns. Register before publishing the active row. let task_control = TaskRunControl::new(); + let stop_token = task_control.cancellation().clone(); + let message_turn = super::message_lifetime::retain( + child_model_config, + message_input.as_ref(), + &self.active_runs, + Arc::new(move || stop_token.cancel()), + )?; if let Some(source) = &operator_source { let (authority, lifetime) = source.issue_task( Arc::clone( @@ -1710,6 +1763,7 @@ impl SessionsSpawnTool { SPAWN_EXECUTION_CONTEXT.scope(task_execution_ctx, async move { let _message_permit = message_permit; let _message_input = message_input; + let _message_turn = message_turn; tracing::info!(run_id = %rid, "Sub-agent task starting"); let provider_started_at = Utc::now(); let (run_on_delta, run_on_tool) = match run_event_streams { diff --git a/src/tools/sessions_spawn/task_mode.rs b/src/tools/sessions_spawn/task_mode.rs index bfd2d266c..36eda5c57 100644 --- a/src/tools/sessions_spawn/task_mode.rs +++ b/src/tools/sessions_spawn/task_mode.rs @@ -217,6 +217,10 @@ pub(super) async fn run_sub_agent_task( } else { None }; + let _service_retirement = child_service + .as_ref() + .map(|service| crate::runtime::turn_cleanup::ChildServiceRetirement::new(Arc::clone(service))) + .transpose()?; let ordinary_runtime = ordinary_authority .as_ref() .map(|authority| authority.publication().loop_runtime().cloned()) diff --git a/tests/architecture_boundaries/providers.rs b/tests/architecture_boundaries/providers.rs index 34f6f39f8..8bc382da8 100644 --- a/tests/architecture_boundaries/providers.rs +++ b/tests/architecture_boundaries/providers.rs @@ -410,6 +410,8 @@ pub(super) fn provider_construction_outside_the_provider_module_is_pinned() { "src/gateway/api/sessions/target.rs:target_provider:create_routed_provider_for", "src/gateway/mod.rs:build_gateway_provider_selection:create_routed_provider_for", "src/runtime/child_source.rs:from_selection:create_provider_for", + // Adopted child uses the persisted model and its current PMM-scoped credential. + "src/runtime/mailbox_child.rs:admit:create_routed_provider_for", // Proposal and judge calls share the resolved, credential-scoped factory. "src/runtime/evolution_model.rs:from_config:create_provider_for", "src/runtime/decision_accounting/auxiliary.rs:auxiliary_accounting:create_provider_for", diff --git a/tests/architecture_boundaries/tool_tables.rs b/tests/architecture_boundaries/tool_tables.rs index fe5233235..fda4cdb23 100644 --- a/tests/architecture_boundaries/tool_tables.rs +++ b/tests/architecture_boundaries/tool_tables.rs @@ -362,6 +362,11 @@ pub(super) const ALLOWED_DIRECT_TOOL_INVOCATIONS: &[(&str, usize, &str)] = &[ 1, "operator input in child focus; admitted by the same captured local operator source", ), + ( + "src/runtime/mailbox_child.rs::continue_turn", + 1, + "verified adopted-message continuation of an existing child; never a new spawn or operator grant", + ), ( "src/chat/run.rs::run_internal", 3, diff --git a/tests/fixtures/config-schema.json b/tests/fixtures/config-schema.json index be5c65061..863a60e00 100644 --- a/tests/fixtures/config-schema.json +++ b/tests/fixtures/config-schema.json @@ -1,6588 +1 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "title": "Config", - "description": "Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).", - "type": "object", - "properties": { - "a2a": { - "description": "Agent-to-Agent compatibility configuration (`[a2a]`).", - "$ref": "#/$defs/A2aConfig", - "default": { - "agent_id": "prx-default", - "allowed_peer_issuers": [], - "bind": "127.0.0.1:16832", - "card_jwks_uri": null, - "card_signing_key_path": null, - "card_ttl_seconds": 3600, - "client_ca_path": null, - "credentials": {}, - "discovery_advertised": false, - "handoff_nonce_ttl_seconds": 3600, - "messaging_enabled": false, - "peers": {}, - "remote_tree": { - "max_connections": 4, - "max_scheduled": 4, - "max_sends": 4, - "max_spawned": 16 - }, - "spiffe_id": "spiffe://prx-local/agent/prx-default", - "spiffe_strict_validation": false, - "spiffe_trust_bundle_pem": null, - "tls_cert_path": null, - "tls_key_path": null, - "trusted_trust_domains": [] - } - }, - "agent": { - "description": "Agent orchestration settings (`[agent]`).", - "$ref": "#/$defs/AgentConfig", - "default": { - "approval_wait_secs": 600, - "compact_context": false, - "compaction": { - "keep_recent_messages": 12, - "max_context_tokens": 128000, - "memory_flush": true, - "mode": "switch", - "os_paging": { - "eviction_threshold": 0.7, - "keep_recent_messages": 12, - "max_recalled_pages": 10, - "proactive_retrieval": true, - "retrieval_injection_role": "system" - }, - "reserve_tokens": 4096 - }, - "low_priority_tools": [ - "sessions_spawn", - "delegate" - ], - "priority_scheduling_enabled": false, - "read_only_tool_concurrency_window": 2 - } - }, - "agents": { - "description": "Delegate agent configurations for multi-agent workflows.", - "type": "object", - "additionalProperties": { - "$ref": "#/$defs/DelegateAgentConfig" - }, - "default": {} - }, - "api_key": { - "description": "API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.", - "type": [ - "string", - "null" - ], - "default": null - }, - "api_url": { - "description": "Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)", - "type": [ - "string", - "null" - ], - "default": null - }, - "auth": { - "description": "Auth profile and external credential import settings (`[auth]`).", - "$ref": "#/$defs/AuthConfig", - "default": { - "codex_auth_json_auto_import": false, - "codex_auth_json_path": "~/.codex/auth.json" - } - }, - "autonomy": { - "description": "Autonomy and security policy configuration (`[autonomy]`).", - "$ref": "#/$defs/AutonomyConfig", - "default": { - "acknowledge_unrestricted_profile": false, - "forbidden_paths": [ - "/etc", - "/root", - "/home", - "/usr", - "/bin", - "/sbin", - "/lib", - "/opt", - "/boot", - "/dev", - "/proc", - "/sys", - "/var", - "/tmp", - "~/.ssh", - "~/.gnupg", - "~/.aws", - "~/.config" - ], - "level": "full", - "max_cost_per_day_cents": 500, - "scopes": { - "assign_owners": [], - "default": "allow", - "rules": [] - }, - "workspace_only": true - } - }, - "browser": { - "description": "Browser automation configuration (`[browser]`).", - "$ref": "#/$defs/BrowserConfig", - "default": { - "allowed_domains": [], - "computer_use": { - "api_key": null - } - } - }, - "channels_config": { - "description": "Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).", - "$ref": "#/$defs/ChannelsConfig", - "default": { - "cli": true, - "dingtalk": null, - "discord": null, - "email": null, - "imessage": null, - "irc": null, - "lark": null, - "linq": null, - "mattermost": null, - "nextcloud_talk": null, - "qq": null, - "ramflux": null, - "signal": null, - "slack": null, - "telegram": null, - "wacli": null, - "webhook": null, - "whatsapp": null - } - }, - "chat": { - "description": "Interactive chat UI configuration (`[chat]`).", - "$ref": "#/$defs/ChatConfig", - "default": { - "daemon": { - "token": "", - "url": "" - }, - "max_concurrent_visible_turns": 2 - } - }, - "compliance": { - "description": "Operator-owned compliance controls (`[compliance]`).", - "$ref": "#/$defs/ComplianceConfig", - "default": { - "eu_ai_act": { - "classification": { - "assessed_at": null, - "owner": null, - "status": "unclassified" - }, - "declaration": { - "applicable_union_law": [], - "artifact_path": null, - "artifact_version": null, - "conformity_assessment_procedure": null, - "conformity_statement": null, - "harmonised_standards": [], - "issue_date": null, - "issue_place": null, - "notified_body_certificate": null, - "notified_body_identification_number": null, - "notified_body_name": null, - "personal_data_compliance_statement": null, - "processes_personal_data": false, - "provider_address": null, - "provider_name": null, - "signer_function": null, - "signer_name": null, - "signer_on_behalf_of": null, - "sole_responsibility_statement": null, - "standards_not_applicable_reason": null, - "system_name": null, - "system_reference": null, - "system_type": null - }, - "incident_store_path": null - }, - "interaction_notice": { - "applicability": "required", - "exception_owner": null, - "exception_reviewed_at": null, - "text": "You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.", - "version": "1" - } - } - }, - "composio": { - "description": "Composio managed OAuth tools integration (`[composio]`).", - "$ref": "#/$defs/ComposioConfig", - "default": { - "api_key": null, - "entity_id": "default" - } - }, - "cost": { - "description": "Cost tracking and budget enforcement configuration (`[cost]`).", - "$ref": "#/$defs/CostConfig", - "default": { - "allow_override": false, - "daily_limit_usd": 10.0, - "monthly_limit_usd": 100.0, - "prices": {}, - "warn_at_percent": 80 - } - }, - "cron": { - "description": "Cron job configuration (`[cron]`).", - "$ref": "#/$defs/CronConfig", - "default": { - "max_run_history": 50 - } - }, - "decision_engine": { - "description": "Optional advisory decision engine, disabled by default.", - "$ref": "#/$defs/DecisionEngineConfig", - "default": { - "candidates": 5, - "enabled": false, - "mode": "pre", - "observe_queue": 64, - "prompt_budget_tokens": 300, - "telemetry_cap": 1000, - "timeout_ms": 1500, - "latency_budget_ms": 500, - "max_candidates": 12, - "token_ratio_limit": 0.3499999940395355 - } - }, - "default_model": { - "description": "Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.", - "type": [ - "string", - "null" - ] - }, - "default_provider": { - "description": "Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.", - "type": [ - "string", - "null" - ] - }, - "default_temperature": { - "description": "Default model temperature (0.0–2.0). Default: `0.7`.", - "type": "number", - "format": "double", - "default": 0.7 - }, - "embedding_routes": { - "description": "Embedding routing rules — route `hint:` to specific provider+model combos.", - "type": "array", - "default": [], - "items": { - "$ref": "#/$defs/EmbeddingRouteConfig" - } - }, - "gateway": { - "description": "Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).", - "$ref": "#/$defs/GatewayConfig", - "default": { - "allow_public_bind": false, - "api_rate_limit_per_minute": 60, - "channel_webhook_dedup_ttl_secs": 86400, - "host": "127.0.0.1", - "idempotency_max_keys": 10000, - "idempotency_ttl_secs": 300, - "pair_rate_limit_per_minute": 10, - "paired_tokens": [], - "port": 16830, - "rate_limit_max_keys": 10000, - "require_pairing": true, - "targeted_agents": false, - "trust_forwarded_headers": false, - "webhook_rate_limit_per_minute": 60 - } - }, - "heartbeat": { - "description": "Heartbeat configuration for periodic health pings (`[heartbeat]`).", - "$ref": "#/$defs/HeartbeatConfig", - "default": { - "active_hours": [ - 8, - 23 - ], - "interval_minutes": 30, - "prompt": "Check HEARTBEAT.md and follow instructions." - } - }, - "http_request": { - "description": "HTTP request tool configuration (`[http_request]`).", - "$ref": "#/$defs/HttpRequestConfig", - "default": { - "max_response_size": 1000000, - "timeout_secs": 30 - } - }, - "identity": { - "description": "Identity format configuration: OpenClaw or AIEOS (`[identity]`).", - "$ref": "#/$defs/IdentityConfig", - "default": { - "aieos_inline": null, - "aieos_path": null, - "format": "openclaw" - } - }, - "identity_bindings": { - "description": "Static identity bindings loaded at startup (`[[identity_bindings]]`).", - "type": "array", - "default": [], - "items": { - "$ref": "#/$defs/IdentityBindingConfig" - } - }, - "mcp": { - "description": "Secrets encryption configuration (`[secrets]`).", - "$ref": "#/$defs/McpConfig", - "default": { - "servers": {} - } - }, - "mcp_server": { - "description": "MCP server compatibility configuration (`[mcp_server]`).", - "$ref": "#/$defs/McpServerRuntimeConfig", - "default": { - "allowed_origins": [ - "claude.ai", - "openai.com", - "localhost" - ], - "bind": "127.0.0.1:16831", - "exposed_tools": [ - "memory_search", - "memory_recall", - "memory_get", - "document_search", - "document_get_chunk", - "sessions_list", - "sessions_history" - ], - "jwt_algorithms": [ - "RS256" - ], - "jwt_audience": null, - "jwt_issuer": null, - "jwt_jwks": null, - "jwt_jwks_cache_ttl_secs": 300, - "jwt_jwks_uri": null, - "jwt_public_key_pem": null, - "rate_limit_rps": 10, - "require_auth": true - } - }, - "media": { - "description": "Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.", - "$ref": "#/$defs/MediaConfig", - "default": { - "audio_model": "whisper", - "audio_ollama_url": "http://localhost:11434", - "audio_provider": "none", - "max_audio_size_mb": 20, - "max_video_size_mb": 50, - "video_max_frames": 4, - "video_provider": "none" - } - }, - "memory": { - "description": "Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).", - "$ref": "#/$defs/MemoryConfig", - "default": { - "acl_enabled": false, - "archive_after_days": 7, - "auto_hydrate": true, - "auto_save": true, - "backend": "sqlite", - "conversation_retention_days": 3, - "daily_retention_days": 7, - "embedding_cache_size": 10000, - "embedding_dimensions": 384, - "embedding_model": "prx-local-hash-v1", - "embedding_provider": "local", - "events": { - "record_assistant_messages": true, - "record_tool_events": false, - "record_user_messages": true - }, - "keyword_weight": 0.3, - "legacy_conversation_turns_visible": true, - "lucid_budget": null, - "lucid_cmd": null, - "lucid_failure_cooldown_ms": 60000, - "lucid_local_hit_threshold": 3, - "lucid_recall_timeout_ms": 5000, - "lucid_store_timeout_ms": 3000, - "min_relevance_score": 0.4, - "purge_after_days": 30, - "semantic": { - "auto_promote_assistant_messages": false, - "auto_promote_user_messages": true, - "min_chars": 30 - }, - "sqlite_open_timeout_secs": null, - "sqlite_read_pool_size": null, - "vector_candidate_cap": 2000, - "vector_weight": 0.7 - } - }, - "model_routes": { - "description": "Model routing rules — route `hint:` to specific provider+model combos.", - "type": "array", - "default": [], - "items": { - "$ref": "#/$defs/ModelRouteConfig" - } - }, - "model_settings": { - "description": "Catalog model levels and explicit parameters, keyed by canonical release ID.", - "type": "object", - "additionalProperties": { - "$ref": "#/$defs/ModelSettings" - }, - "default": {} - }, - "multimodal": { - "description": "Multimodal (image) handling configuration (`[multimodal]`).", - "$ref": "#/$defs/MultimodalConfig", - "default": { - "allow_remote_fetch": false, - "max_image_size_mb": 5, - "max_images": 4 - } - }, - "nodes": { - "description": "Remote node proxy configuration (`[nodes]`).", - "$ref": "#/$defs/NodesConfig", - "default": { - "nodes": [], - "request_timeout_ms": 15000, - "retry_max": 2, - "server": { - "allowed_commands": [ - "echo" - ], - "bearer_token": "", - "blocked_commands": [], - "exec_timeout_ms": 15000, - "hmac_secret": null, - "listen_addr": "127.0.0.1:8787", - "max_concurrent_tasks": 8, - "max_output_bytes": 1048576, - "sandbox_root": ".", - "task_result_ttl_ms": 3600000, - "tls_cert": null, - "tls_key": null, - "tls_required": true - } - } - }, - "observability": { - "description": "Observability backend configuration (`[observability]`).", - "$ref": "#/$defs/ObservabilityConfig", - "default": { - "backend": "none", - "otel_endpoint": null, - "otel_service_name": null - } - }, - "plugins": { - "description": "WASM plugin runtime switch (`[plugins]`), off by default.", - "$ref": "#/$defs/PluginsConfig", - "default": { - "enabled": false - } - }, - "providers": { - "description": "Provider-specific runtime options (`[providers.]`).", - "$ref": "#/$defs/ProvidersConfig", - "default": { - "ollama": { - "num_ctx": null - } - } - }, - "proxy": { - "description": "Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).", - "$ref": "#/$defs/ProxyConfig", - "default": { - "all_proxy": null, - "http_proxy": null, - "https_proxy": null, - "no_proxy": [], - "scope": "zeroclaw", - "services": [] - } - }, - "query_classification": { - "description": "Automatic query classification — maps user messages to model hints.", - "$ref": "#/$defs/QueryClassificationConfig", - "default": { - "rules": [] - } - }, - "reliability": { - "description": "Reliability settings: retries, fallback providers, backoff (`[reliability]`).", - "$ref": "#/$defs/ReliabilityConfig", - "default": { - "acknowledge_single_provider_risk": false, - "api_keys": [], - "channel_initial_backoff_secs": 2, - "channel_max_backoff_secs": 60, - "circuit_breaker": { - "enabled": true, - "failure_threshold": 5, - "max_open_secs": 300, - "open_secs": 30 - }, - "fallback_providers": [], - "model_fallbacks": {}, - "provider_backoff_ms": 500, - "provider_retries": 2, - "scheduler_poll_secs": 15, - "scheduler_retries": 2 - } - }, - "router": { - "description": "Heuristic LLM router configuration (`[router]`).", - "$ref": "#/$defs/RouterConfig", - "default": { - "alpha": 0.0, - "beta": 0.5, - "delta": 0.10000000149011612, - "epsilon": 0.10000000149011612, - "gamma": 0.30000001192092896, - "knn_k": 7, - "knn_min_records": 10, - "models": [] - } - }, - "runtime": { - "description": "Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.", - "$ref": "#/$defs/RuntimeConfig", - "default": { - "codex_reasoning_effort": null, - "codex_stream_idle_timeout_secs": null, - "docker": { - "allowed_workspace_roots": [], - "cpu_limit": 1.0, - "image": "alpine:3.20", - "memory_limit_mb": 512, - "mount_workspace": true, - "network": "none", - "read_only_rootfs": true - }, - "idle_hang_secs": null, - "kind": "native", - "long_task_warn_secs": null, - "managed_cgroup_root": null, - "max_blocking_threads": null, - "reasoning_enabled": null, - "shell_env_allowlist": [], - "workdir": null - } - }, - "scheduler": { - "description": "Scheduler configuration for periodic task execution (`[scheduler]`).", - "$ref": "#/$defs/SchedulerConfig", - "default": { - "claim_lease_secs": 90, - "max_tasks": 64 - } - }, - "secrets": { - "$ref": "#/$defs/SecretsConfig", - "default": { - "encrypt": true - } - }, - "security": { - "description": "Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).", - "$ref": "#/$defs/SecurityConfig", - "default": { - "audit": { - "log_path": "audit.log", - "max_size_mb": 100 - } - } - }, - "self_system": { - "description": "Self-system experimental automation controls (`[self_system]`).", - "$ref": "#/$defs/SelfSystemConfig", - "default": { - "evolution_config_path": null, - "evolution_debug_raw": false, - "evolution_interval_hours": 24, - "evolution_judge_timeout_secs": 180, - "evolution_model_max_micro_usd": 0, - "evolution_model_max_tokens": 16384, - "fitness": { - "auto_run": true, - "max_backfill_days": 7, - "min_coverage": 0.6, - "min_samples": 5, - "retention_days": 180, - "run_at": "00:10", - "timezone": "UTC" - }, - "fitness_interval_hours": 24 - } - }, - "sessions_spawn": { - "description": "Session spawning configuration (`[sessions_spawn]`).", - "$ref": "#/$defs/SessionsSpawnConfig", - "default": { - "cleanup_on_complete": true, - "default_mode": "task", - "process_memory_strategy": "shared_fabric", - "worker_workspace_root": null - } - }, - "skill_rag": { - "description": "Dynamic skill retrieval settings (`[skill_rag]`).", - "$ref": "#/$defs/SkillRagConfig", - "default": { - "top_k": 32 - } - }, - "skills": { - "description": "Skills loading and community repository behavior (`[skills]`).", - "$ref": "#/$defs/SkillsConfig", - "default": { - "open_skills_dir": null, - "openclaw_skills_dir": null - } - }, - "skills_lifecycle": { - "description": "Skill lifecycle (`[skills_lifecycle]`), off by default.", - "$ref": "#/$defs/SkillsLifecycleConfig", - "default": { - "allow_executable_proposals": false, - "enabled": false, - "max_concurrent_evaluations": 1, - "max_edit_fraction": 0.2, - "max_edit_tokens": 300, - "max_proposals_per_cycle": 1, - "min_cases_floor": 3, - "mode": "draft_only", - "owner_scope": null, - "require_holdout": true, - "storage_dir": "self/skill-lifecycle", - "suites": [] - } - }, - "smart_group": { - "description": "Smart group-reply pre-gate configuration (`[smart_group]`).", - "$ref": "#/$defs/SmartGroupConfig", - "default": { - "classifier_max_context_messages": 3, - "classifier_model": "", - "classifier_provider": "", - "classifier_temperature": 0.0, - "classifier_timeout_secs": 5 - } - }, - "storage": { - "description": "Persistent storage provider configuration (`[storage]`).", - "$ref": "#/$defs/StorageConfig", - "default": { - "provider": { - "config": { - "connect_timeout_secs": null, - "db_url": null, - "pool_max_size": 32, - "provider": "", - "schema": "public", - "table": "memories" - } - } - } - }, - "task_routing": { - "description": "Task routing configuration — classifies work by intent before the main agent loop.", - "$ref": "#/$defs/TaskRoutingConfig", - "default": { - "default_intent": "simple", - "rules": [] - } - }, - "tool_tiering": { - "description": "Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).", - "$ref": "#/$defs/ToolTieringConfig", - "default": { - "always_exclude": [], - "always_include": [], - "channel_exclude": [ - "wasm_plugins_manage", - "wasm_plugin_reload", - "wasm_plugins_status", - "hooks_manage", - "hooks_status", - "proxy_config", - "config_reload", - "gateway", - "mcp_status", - "nodes", - "git_operations", - "skills_manage", - "memory_reindex", - "document_sync", - "document_ingest" - ] - } - }, - "tunnel": { - "description": "Tunnel configuration for exposing the gateway publicly (`[tunnel]`).", - "$ref": "#/$defs/TunnelConfig", - "default": { - "cloudflare": null, - "custom": null, - "ngrok": null, - "provider": "none", - "tailscale": null - } - }, - "user_policies": { - "description": "Static user policy records loaded at startup (`[[user_policies]]`).", - "type": "array", - "default": [], - "items": { - "$ref": "#/$defs/UserPolicyConfig" - } - }, - "web_search": { - "description": "Web search tool configuration (`[web_search]`).", - "$ref": "#/$defs/WebSearchConfig", - "default": { - "brave_api_key": null, - "fetch_max_chars": 50000, - "max_results": 15, - "provider": "duckduckgo", - "timeout_secs": 15 - } - }, - "webhook": { - "description": "Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).", - "$ref": "#/$defs/MemoryWebhookConfig", - "default": { - "bind": "0.0.0.0:16899", - "signing_secret": null, - "token": null - } - }, - "xin": { - "description": "Xin autonomous task engine configuration (`[xin]`).", - "$ref": "#/$defs/XinConfig", - "default": { - "adopt_legacy_tasks": false, - "interval_minutes": 5, - "stale_timeout_minutes": 60 - } - } - }, - "$defs": { - "A2aConfig": { - "type": "object", - "properties": { - "agent_id": { - "description": "Stable PRX agent identifier advertised to peers.", - "type": "string", - "default": "prx-default" - }, - "allowed_peer_issuers": { - "description": "Accepted external peer issuers.", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "bind": { - "description": "Advertised bind address.", - "type": "string", - "default": "127.0.0.1:16832" - }, - "card_jwks_uri": { - "description": "Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.", - "type": [ - "string", - "null" - ], - "default": null - }, - "card_signing_key_path": { - "description": "On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).", - "type": [ - "string", - "null" - ], - "default": null - }, - "card_ttl_seconds": { - "description": "Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.", - "type": "integer", - "format": "uint64", - "default": 3600, - "minimum": 0 - }, - "client_ca_path": { - "description": "Optional PEM CA(s) for inbound client-certificate verification.", - "type": [ - "string", - "null" - ], - "default": null - }, - "credentials": { - "description": "Outbound identities used by `[a2a.peers.*.credential]`.", - "type": "object", - "additionalProperties": { - "$ref": "#/$defs/A2aCredential" - }, - "default": {} - }, - "discovery_advertised": { - "description": "Whether to advertise into an external A2A registry.", - "type": "boolean", - "default": false - }, - "handoff_nonce_ttl_seconds": { - "description": "Replay window for future handoff delegation tokens.", - "type": "integer", - "format": "uint64", - "default": 3600, - "minimum": 0 - }, - "messaging_enabled": { - "description": "When true, A2A messaging routes are registered. FOUNDATION keeps this\nfalse; ACT-1 flips it.", - "type": "boolean", - "default": false - }, - "peers": { - "description": "Named peer grants. Empty until operators add `[a2a.peers.*]`.", - "type": "object", - "additionalProperties": { - "$ref": "#/$defs/A2aPeer" - }, - "default": {} - }, - "remote_tree": { - "description": "Remote causal-tree occupancy caps.", - "$ref": "#/$defs/RemoteTreeLimits", - "default": { - "max_connections": 4, - "max_scheduled": 4, - "max_sends": 4, - "max_spawned": 16 - } - }, - "spiffe_id": { - "description": "Local SPIFFE-style identifier placeholder.", - "type": "string", - "default": "spiffe://prx-local/agent/prx-default" - }, - "spiffe_strict_validation": { - "description": "When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.", - "type": "boolean", - "default": false - }, - "spiffe_trust_bundle_pem": { - "description": "Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).", - "type": [ - "string", - "null" - ], - "default": null - }, - "tls_cert_path": { - "description": "PEM server certificate for the dedicated A2A listener. Required for a\nnon-loopback bind. Relative to the config dir. Read at use.", - "type": [ - "string", - "null" - ], - "default": null - }, - "tls_key_path": { - "description": "PEM server key for the dedicated A2A listener. Required for a\nnon-loopback bind. File mode must be 0600 at use.", - "type": [ - "string", - "null" - ], - "default": null - }, - "trusted_trust_domains": { - "description": "Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).", - "type": "array", - "default": [], - "items": { - "type": "string" - } - } - } - }, - "A2aCredential": { - "description": "One `[a2a.credentials.]` outbound identity.", - "type": "object", - "properties": { - "client_cert_path": { - "description": "Optional client certificate for mTLS.", - "type": [ - "string", - "null" - ] - }, - "client_key_path": { - "description": "Optional client key for mTLS. Mode 0600 at use.", - "type": [ - "string", - "null" - ] - }, - "jwt_signing_key_path": { - "description": "Ed25519 signing key we use to self-issue peer JWTs.", - "type": [ - "string", - "null" - ] - } - } - }, - "A2aPeer": { - "description": "One `[a2a.peers.]` grant row.", - "type": "object", - "properties": { - "agents": { - "description": "Allowed agent names, or `[\"*\"]`.", - "type": "array", - "default": [ - "*" - ], - "items": { - "type": "string" - } - }, - "auth": { - "description": "Inbound key-possession method.", - "$ref": "#/$defs/A2aPeerAuth" - }, - "credential": { - "description": "Outbound identity name in `[a2a.credentials.*]`.", - "type": [ - "string", - "null" - ] - }, - "endpoint": { - "description": "Outbound POST URL.", - "type": "string" - }, - "issuer": { - "description": "JWT `iss` or SPIFFE trust-domain prefix.", - "type": "string" - }, - "jwt_public_key_path": { - "description": "Ed25519 public key PEM. Required when `auth = \"jwt\"`.", - "type": [ - "string", - "null" - ] - }, - "local_owner": { - "description": "Local owner this peer may message (`to.owner`).", - "type": "string" - }, - "peer_instance": { - "description": "Stamped onto `from.instance`.", - "type": "string" - }, - "remote_owner": { - "description": "Stamped onto `from.owner` at use. `None` means the subject.", - "type": [ - "string", - "null" - ] - }, - "sessions": { - "description": "Allowed session ids, or `[\"*\"]`.", - "type": "array", - "default": [ - "*" - ], - "items": { - "type": "string" - } - }, - "subject": { - "description": "JWT `sub` or SPIFFE SAN.", - "type": "string" - }, - "tls_ca_path": { - "description": "Outbound CA for this peer's server cert. Unset uses system roots.", - "type": [ - "string", - "null" - ] - }, - "tls_server_name": { - "description": "Outbound TLS server name. Optional when the SAN equals `subject`.", - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "subject", - "issuer", - "peer_instance", - "endpoint", - "local_owner", - "auth" - ] - }, - "A2aPeerAuth": { - "description": "Inbound key-possession method a peer must use.", - "type": "string", - "enum": [ - "jwt", - "mtls" - ] - }, - "AgentCompactionConfig": { - "description": "Agent context compaction configuration (`[agent.compaction]`).", - "type": "object", - "properties": { - "keep_recent_messages": { - "description": "Number of recent non-system messages to keep after compaction.", - "type": "integer", - "format": "uint", - "default": 12, - "minimum": 0 - }, - "max_context_tokens": { - "description": "Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.", - "type": "integer", - "format": "uint", - "default": 128000, - "minimum": 0 - }, - "memory_flush": { - "description": "Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.", - "type": "boolean", - "default": true - }, - "mode": { - "description": "Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).", - "$ref": "#/$defs/AgentCompactionMode", - "default": "switch" - }, - "os_paging": { - "description": "Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.", - "$ref": "#/$defs/OsPagingConfig", - "default": { - "eviction_threshold": 0.7, - "keep_recent_messages": 12, - "max_recalled_pages": 10, - "proactive_retrieval": true, - "retrieval_injection_role": "system" - } - }, - "reserve_tokens": { - "description": "Tokens reserved for the next model response.", - "type": "integer", - "format": "uint", - "default": 4096, - "minimum": 0 - } - } - }, - "AgentCompactionMode": { - "description": "Compaction mode for long conversation contexts.", - "oneOf": [ - { - "description": "Disable proactive compaction.", - "type": "string", - "const": "off" - }, - { - "description": "Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.", - "type": "string", - "const": "switch" - }, - { - "description": "Conservative compaction that prefers summary replacement.", - "type": "string", - "const": "safeguard" - }, - { - "description": "Aggressive truncation mode for tighter contexts.", - "type": "string", - "const": "aggressive" - } - ] - }, - "AgentConfig": { - "description": "Agent orchestration configuration (`[agent]` section).", - "type": "object", - "properties": { - "approval_wait_secs": { - "description": "rf approve-and-continue wait; Console approvals retain their own expiry.", - "type": "integer", - "format": "uint64", - "default": 600, - "maximum": 86400, - "minimum": 1 - }, - "compact_context": { - "description": "When true: bootstrap_max_chars=6000. Use for 13B or smaller models.", - "type": "boolean", - "default": false - }, - "compaction": { - "description": "Context compaction controls (`[agent.compaction]`).", - "$ref": "#/$defs/AgentCompactionConfig", - "default": { - "keep_recent_messages": 12, - "max_context_tokens": 128000, - "memory_flush": true, - "mode": "switch", - "os_paging": { - "eviction_threshold": 0.7, - "keep_recent_messages": 12, - "max_recalled_pages": 10, - "proactive_retrieval": true, - "retrieval_injection_role": "system" - }, - "reserve_tokens": 4096 - } - }, - "low_priority_tools": { - "description": "Tool names treated as low-priority when `priority_scheduling_enabled = true`.", - "type": "array", - "default": [ - "sessions_spawn", - "delegate" - ], - "items": { - "type": "string" - } - }, - "priority_scheduling_enabled": { - "description": "Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.", - "type": "boolean", - "default": false - }, - "read_only_tool_concurrency_window": { - "description": "Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.", - "type": "integer", - "format": "uint", - "default": 2, - "minimum": 0 - } - } - }, - "AgentLimits": { - "description": "Optional admission limits for rf-started turns of a named agent.", - "type": "object", - "properties": { - "max_concurrent_turns": { - "type": [ - "integer", - "null" - ], - "format": "uint32", - "minimum": 0 - }, - "max_cost_per_day_cents": { - "type": [ - "integer", - "null" - ], - "format": "uint64", - "minimum": 0 - } - }, - "additionalProperties": false - }, - "AuditConfig": { - "description": "Audit logging configuration", - "type": "object", - "properties": { - "log_path": { - "description": "Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).", - "type": "string", - "default": "audit.log" - }, - "max_size_mb": { - "description": "Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).", - "type": "integer", - "format": "uint32", - "default": 100, - "minimum": 0 - } - } - }, - "AuthConfig": { - "description": "Authentication and external credential import configuration (`[auth]` section).", - "type": "object", - "properties": { - "codex_auth_json_auto_import": { - "description": "Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.", - "type": "boolean", - "default": false - }, - "codex_auth_json_path": { - "description": "Source path for Codex CLI auth.json import.", - "type": "string", - "default": "~/.codex/auth.json" - } - } - }, - "AutonomyConfig": { - "type": "object", - "properties": { - "acknowledge_unrestricted_profile": { - "description": "Operator acknowledgement for an intentionally unrestricted profile.\nThis suppresses doctor noise only; it does not alter policy behavior.", - "type": "boolean", - "default": false - }, - "forbidden_paths": { - "description": "Explicit path denylist. Default includes system-critical paths.\n\nFails closed: omitting the key keeps the built-in list rather than\nemptying it, so a partial `[autonomy]` section never removes the\ndenylist.", - "type": "array", - "default": [ - "/etc", - "/root", - "/home", - "/usr", - "/bin", - "/sbin", - "/lib", - "/opt", - "/boot", - "/dev", - "/proc", - "/sys", - "/var", - "/tmp", - "~/.ssh", - "~/.gnupg", - "~/.aws", - "~/.config" - ], - "items": { - "type": "string" - } - }, - "level": { - "description": "Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).", - "$ref": "#/$defs/AutonomyLevel", - "default": "full" - }, - "max_cost_per_day_cents": { - "description": "Maximum cost per day in cents per policy. Default: `500`.", - "type": "integer", - "format": "uint32", - "default": 500, - "minimum": 0 - }, - "scopes": { - "description": "Scope-based tool access control: per-user/channel/chat-type allow/deny rules.", - "$ref": "#/$defs/ScopeConfig", - "default": { - "assign_owners": [], - "default": "allow", - "rules": [] - } - }, - "workspace_only": { - "description": "Restrict file writes and command paths to the workspace directory. Default: `true`.\n\nFails closed: a `[autonomy]` section that omits this key keeps the\nworkspace restriction on, so a partial section can never widen the\nfilesystem reach by accident.", - "type": "boolean", - "default": true - } - } - }, - "AutonomyLevel": { - "description": "How much autonomy the agent has", - "oneOf": [ - { - "description": "Read-only: can observe but not act", - "type": "string", - "const": "readonly" - }, - { - "description": "Supervised: acts but requires approval for risky operations", - "type": "string", - "const": "supervised" - }, - { - "description": "Full: autonomous execution within policy bounds", - "type": "string", - "const": "full" - } - ] - }, - "BackendSelection": { - "description": "Which decision backend runs: `auto` (the factory's order) or one kind.", - "type": "string" - }, - "BrowserComputerUseConfig": { - "description": "Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.", - "type": "object", - "properties": { - "api_key": { - "description": "Optional bearer token (retained only for config secret handling).", - "type": [ - "string", - "null" - ], - "default": null - } - } - }, - "BrowserConfig": { - "description": "Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.", - "type": "object", - "properties": { - "allowed_domains": { - "description": "Allowed domains for `web_fetch` (exact or subdomain match).", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "computer_use": { - "description": "Computer-use sidecar config (retained only for `api_key` secret handling).", - "$ref": "#/$defs/BrowserComputerUseConfig", - "default": { - "api_key": null - } - } - } - }, - "ChannelsConfig": { - "description": "Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.", - "type": "object", - "properties": { - "cli": { - "description": "Enable the CLI interactive channel. Default: `true`.", - "type": "boolean", - "default": true - }, - "dingtalk": { - "description": "DingTalk channel configuration.", - "anyOf": [ - { - "$ref": "#/$defs/DingTalkConfig" - }, - { - "type": "null" - } - ] - }, - "discord": { - "description": "Discord bot channel configuration.", - "anyOf": [ - { - "$ref": "#/$defs/DiscordConfig" - }, - { - "type": "null" - } - ] - }, - "email": { - "description": "Email channel configuration.", - "anyOf": [ - { - "$ref": "#/$defs/EmailConfig" - }, - { - "type": "null" - } - ] - }, - "imessage": { - "description": "iMessage channel configuration (macOS only).", - "anyOf": [ - { - "$ref": "#/$defs/IMessageConfig" - }, - { - "type": "null" - } - ] - }, - "irc": { - "description": "IRC channel configuration.", - "anyOf": [ - { - "$ref": "#/$defs/IrcConfig" - }, - { - "type": "null" - } - ] - }, - "lark": { - "description": "Lark/Feishu channel configuration.", - "anyOf": [ - { - "$ref": "#/$defs/LarkConfig" - }, - { - "type": "null" - } - ] - }, - "linq": { - "description": "Linq Partner API channel configuration.", - "anyOf": [ - { - "$ref": "#/$defs/LinqConfig" - }, - { - "type": "null" - } - ] - }, - "mattermost": { - "description": "Mattermost bot channel configuration.", - "anyOf": [ - { - "$ref": "#/$defs/MattermostConfig" - }, - { - "type": "null" - } - ] - }, - "nextcloud_talk": { - "description": "Nextcloud Talk bot channel configuration.", - "anyOf": [ - { - "$ref": "#/$defs/NextcloudTalkConfig" - }, - { - "type": "null" - } - ] - }, - "qq": { - "description": "QQ Official Bot channel configuration.", - "anyOf": [ - { - "$ref": "#/$defs/QQConfig" - }, - { - "type": "null" - } - ] - }, - "ramflux": { - "description": "Local ramflux agent-host bridge.", - "anyOf": [ - { - "$ref": "#/$defs/RamfluxConfig" - }, - { - "type": "null" - } - ], - "default": null - }, - "signal": { - "description": "Signal channel configuration.", - "anyOf": [ - { - "$ref": "#/$defs/SignalConfig" - }, - { - "type": "null" - } - ] - }, - "slack": { - "description": "Slack bot channel configuration.", - "anyOf": [ - { - "$ref": "#/$defs/SlackConfig" - }, - { - "type": "null" - } - ] - }, - "telegram": { - "description": "Telegram bot channel configuration.", - "anyOf": [ - { - "$ref": "#/$defs/TelegramConfig" - }, - { - "type": "null" - } - ] - }, - "wacli": { - "description": "wacli JSON-RPC daemon channel configuration.", - "anyOf": [ - { - "$ref": "#/$defs/WacliConfig" - }, - { - "type": "null" - } - ], - "default": null - }, - "webhook": { - "description": "Webhook channel configuration.", - "anyOf": [ - { - "$ref": "#/$defs/WebhookConfig" - }, - { - "type": "null" - } - ] - }, - "whatsapp": { - "description": "WhatsApp channel configuration (Cloud API or Web mode).", - "anyOf": [ - { - "$ref": "#/$defs/WhatsAppConfig" - }, - { - "type": "null" - } - ] - } - } - }, - "ChatConfig": { - "description": "Interactive chat configuration (`[chat]`).", - "type": "object", - "properties": { - "daemon": { - "description": "How this chat process reaches the daemon it borrows channels from.", - "$ref": "#/$defs/ChatDaemonConfig", - "default": { - "token": "", - "url": "" - } - }, - "max_concurrent_visible_turns": { - "description": "Maximum concurrent visible provider turns in the TUI Redux driver.", - "type": "integer", - "format": "uint", - "default": 2, - "minimum": 0 - } - } - }, - "ChatDaemonConfig": { - "description": "Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.", - "type": "object", - "properties": { - "token": { - "description": "Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.", - "type": "string", - "default": "" - }, - "url": { - "description": "Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.", - "type": "string", - "default": "" - } - } - }, - "CircuitBreakerConfig": { - "description": "The per-backend circuit breaker.", - "type": "object", - "properties": { - "cooldown_secs": { - "description": "Seconds the breaker stays open (1 to 3600).", - "type": "integer", - "format": "uint32", - "default": 60, - "minimum": 0 - }, - "failure_threshold": { - "description": "Consecutive failures before the breaker opens (1 to 100).", - "type": "integer", - "format": "uint32", - "default": 5, - "minimum": 0 - } - } - }, - "ClassificationRule": { - "description": "A single classification rule mapping message patterns to a model hint.", - "type": "object", - "properties": { - "hint": { - "description": "Must match a `[[model_routes]]` hint value.", - "type": "string" - }, - "keywords": { - "description": "Case-insensitive substring matches.", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "max_length": { - "description": "Only match if message length <= N chars.", - "type": [ - "integer", - "null" - ], - "format": "uint", - "default": null, - "minimum": 0 - }, - "min_length": { - "description": "Only match if message length >= N chars.", - "type": [ - "integer", - "null" - ], - "format": "uint", - "default": null, - "minimum": 0 - }, - "patterns": { - "description": "Case-sensitive literal matches (for \"```\", \"fn \", etc.).", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "priority": { - "description": "Higher priority rules are checked first.", - "type": "integer", - "format": "int32", - "default": 0 - } - }, - "required": [ - "hint" - ] - }, - "CloudflareTunnelConfig": { - "type": "object", - "properties": { - "token": { - "description": "Cloudflare Tunnel token (from Zero Trust dashboard)", - "type": "string" - } - }, - "required": [ - "token" - ] - }, - "ComplianceConfig": { - "type": "object", - "properties": { - "eu_ai_act": { - "$ref": "#/$defs/EuAiActComplianceConfig", - "default": { - "classification": { - "assessed_at": null, - "owner": null, - "status": "unclassified" - }, - "declaration": { - "applicable_union_law": [], - "artifact_path": null, - "artifact_version": null, - "conformity_assessment_procedure": null, - "conformity_statement": null, - "harmonised_standards": [], - "issue_date": null, - "issue_place": null, - "notified_body_certificate": null, - "notified_body_identification_number": null, - "notified_body_name": null, - "personal_data_compliance_statement": null, - "processes_personal_data": false, - "provider_address": null, - "provider_name": null, - "signer_function": null, - "signer_name": null, - "signer_on_behalf_of": null, - "sole_responsibility_statement": null, - "standards_not_applicable_reason": null, - "system_name": null, - "system_reference": null, - "system_type": null - }, - "incident_store_path": null - } - }, - "interaction_notice": { - "$ref": "#/$defs/InteractionNoticeConfig", - "default": { - "applicability": "required", - "exception_owner": null, - "exception_reviewed_at": null, - "text": "You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.", - "version": "1" - } - } - } - }, - "ComposioConfig": { - "description": "Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.", - "type": "object", - "properties": { - "api_key": { - "description": "Composio API key (stored encrypted when secrets.encrypt = true)", - "type": [ - "string", - "null" - ], - "default": null - }, - "entity_id": { - "description": "Default entity ID for multi-user setups", - "type": "string", - "default": "default" - } - } - }, - "CostConfig": { - "description": "Cost tracking and budget enforcement configuration (`[cost]` section).", - "type": "object", - "properties": { - "allow_override": { - "description": "Allow requests to exceed budget with --override flag (default: false)", - "type": "boolean", - "default": false - }, - "daily_limit_usd": { - "description": "Daily spending limit in USD (default: 10.00)", - "type": "number", - "format": "double", - "default": 10.0 - }, - "monthly_limit_usd": { - "description": "Monthly spending limit in USD (default: 100.00)", - "type": "number", - "format": "double", - "default": 100.0 - }, - "prices": { - "description": "Per-model pricing (USD per 1M tokens)", - "type": "object", - "additionalProperties": { - "$ref": "#/$defs/ModelPricing" - }, - "default": {} - }, - "warn_at_percent": { - "description": "Warn when spending reaches this percentage of limit (default: 80)", - "type": "integer", - "format": "uint8", - "default": 80, - "maximum": 255, - "minimum": 0 - } - } - }, - "CredentialRefSetting": { - "description": "Which credential a decision backend uses. A reference, never a secret.", - "type": "string" - }, - "CronConfig": { - "description": "Cron job configuration (`[cron]` section).", - "type": "object", - "properties": { - "max_run_history": { - "description": "Maximum number of historical cron run records to retain. Default: `50`.", - "type": "integer", - "format": "uint32", - "default": 50, - "minimum": 0 - } - } - }, - "CustomTunnelConfig": { - "type": "object", - "properties": { - "health_url": { - "description": "Optional URL to check tunnel health", - "type": [ - "string", - "null" - ] - }, - "start_command": { - "description": "Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"", - "type": "string" - }, - "url_pattern": { - "description": "Optional regex to extract public URL from command stdout", - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "start_command" - ] - }, - "DecisionBackendConfig": { - "description": "The decision backend (`[decision_engine.backend]`).", - "type": "object", - "properties": { - "circuit_breaker": { - "description": "The circuit breaker.", - "$ref": "#/$defs/CircuitBreakerConfig", - "default": { - "cooldown_secs": 60, - "failure_threshold": 5 - } - }, - "credential_ref": { - "description": "The credential reference: `\"\"`, `\"none\"` or `cred-`.", - "$ref": "#/$defs/CredentialRefSetting", - "default": "" - }, - "endpoint": { - "description": "The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.", - "type": "string", - "default": "" - }, - "kind": { - "description": "`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).", - "$ref": "#/$defs/BackendSelection", - "default": "auto" - }, - "max_request_bytes": { - "description": "Largest request body (4 KiB to 1 MiB).", - "type": "integer", - "format": "uint32", - "default": 65536, - "minimum": 0 - }, - "max_response_bytes": { - "description": "Largest response body (4 KiB to 1 MiB).", - "type": "integer", - "format": "uint32", - "default": 262144, - "minimum": 0 - }, - "model": { - "description": "The model the endpoint serves; one exact version for a hosted\nservice.", - "type": "string", - "default": "" - }, - "pinned_snapshot": { - "description": "The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.", - "type": "string" - }, - "remote_enabled": { - "description": "Whether decision state may leave this machine. Default `false`.", - "type": "boolean", - "default": false - }, - "timeout_ms": { - "description": "Transport timeout (10 ms up to the extra latency budget).", - "type": "integer", - "format": "uint32", - "default": 250, - "minimum": 0 - } - } - }, - "DecisionEngineConfig": { - "type": "object", - "properties": { - "backend": { - "anyOf": [ - { - "$ref": "#/$defs/DecisionBackendConfig" - }, - { - "type": "null" - } - ] - }, - "candidates": { - "type": "integer", - "format": "uint32", - "default": 5, - "minimum": 0 - }, - "enabled": { - "type": "boolean", - "default": false - }, - "mode": { - "$ref": "#/$defs/DecisionMode", - "default": "pre" - }, - "observe_queue": { - "type": "integer", - "format": "uint32", - "default": 64, - "minimum": 0 - }, - "prompt_budget_tokens": { - "type": "integer", - "format": "uint32", - "default": 300, - "minimum": 0 - }, - "telemetry_cap": { - "type": "integer", - "format": "uint32", - "default": 1000, - "minimum": 0 - }, - "timeout_ms": { - "type": "integer", - "format": "uint32", - "default": 1500, - "minimum": 0 - }, - "latency_budget_ms": { - "description": "The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.", - "type": "integer", - "format": "uint64", - "default": 500, - "minimum": 0 - }, - "token_ratio_limit": { - "description": "Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).", - "type": "number", - "format": "float", - "default": 0.3499999940395355 - }, - "max_candidates": { - "description": "The most candidates a turn considers (1 to 32).", - "type": "integer", - "format": "uint8", - "default": 12, - "maximum": 255, - "minimum": 0 - } - } - }, - "DecisionMode": { - "type": "string", - "enum": [ - "pre", - "post", - "both" - ] - }, - "DeclarationOfConformityConfig": { - "type": "object", - "properties": { - "applicable_union_law": { - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "artifact_path": { - "type": [ - "string", - "null" - ], - "default": null - }, - "artifact_version": { - "type": [ - "string", - "null" - ], - "default": null - }, - "conformity_assessment_procedure": { - "type": [ - "string", - "null" - ], - "default": null - }, - "conformity_statement": { - "type": [ - "string", - "null" - ], - "default": null - }, - "harmonised_standards": { - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "issue_date": { - "type": [ - "string", - "null" - ], - "default": null - }, - "issue_place": { - "type": [ - "string", - "null" - ], - "default": null - }, - "notified_body_certificate": { - "type": [ - "string", - "null" - ], - "default": null - }, - "notified_body_identification_number": { - "type": [ - "string", - "null" - ], - "default": null - }, - "notified_body_name": { - "type": [ - "string", - "null" - ], - "default": null - }, - "personal_data_compliance_statement": { - "type": [ - "string", - "null" - ], - "default": null - }, - "processes_personal_data": { - "type": "boolean", - "default": false - }, - "provider_address": { - "type": [ - "string", - "null" - ], - "default": null - }, - "provider_name": { - "type": [ - "string", - "null" - ], - "default": null - }, - "signer_function": { - "type": [ - "string", - "null" - ], - "default": null - }, - "signer_name": { - "type": [ - "string", - "null" - ], - "default": null - }, - "signer_on_behalf_of": { - "type": [ - "string", - "null" - ], - "default": null - }, - "sole_responsibility_statement": { - "type": [ - "string", - "null" - ], - "default": null - }, - "standards_not_applicable_reason": { - "type": [ - "string", - "null" - ], - "default": null - }, - "system_name": { - "type": [ - "string", - "null" - ], - "default": null - }, - "system_reference": { - "type": [ - "string", - "null" - ], - "default": null - }, - "system_type": { - "type": [ - "string", - "null" - ], - "default": null - } - } - }, - "DelegateAgentConfig": { - "description": "Configuration for a delegate sub-agent used by the `delegate` tool.", - "type": "object", - "properties": { - "agentic": { - "description": "Enable agentic sub-agent mode (multi-turn tool-call loop).", - "type": "boolean", - "default": false - }, - "allowed_tools": { - "description": "Allowlist of tool names available to the sub-agent in agentic mode.", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "api_key": { - "description": "Optional API key override", - "type": [ - "string", - "null" - ], - "default": null - }, - "approval_wait_secs": { - "description": "rf approve-and-continue wait; Console approvals retain their own expiry.", - "type": "integer", - "format": "uint64", - "default": 600, - "maximum": 86400, - "minimum": 1 - }, - "autonomy": { - "description": "The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.", - "anyOf": [ - { - "$ref": "#/$defs/AutonomyLevel" - }, - { - "type": "null" - } - ] - }, - "credential_ref": { - "description": "A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.", - "type": [ - "string", - "null" - ] - }, - "enabled": { - "description": "Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.", - "type": "boolean", - "default": true - }, - "identity_dir": { - "description": "Optional identity files directory relative to workspace root.", - "type": [ - "string", - "null" - ], - "default": null - }, - "limits": { - "$ref": "#/$defs/AgentLimits", - "default": { - "max_concurrent_turns": null, - "max_cost_per_day_cents": null - } - }, - "max_depth": { - "description": "Max recursion depth for nested delegation", - "type": "integer", - "format": "uint32", - "default": 8, - "minimum": 0 - }, - "memory_scope": { - "description": "Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".", - "type": [ - "string", - "null" - ], - "default": null - }, - "model": { - "description": "Model name", - "type": "string" - }, - "provider": { - "description": "Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")", - "type": "string" - }, - "spawn_enabled": { - "description": "Whether this agent is allowed to be targeted by sessions_spawn (default: true).", - "type": [ - "boolean", - "null" - ], - "default": null - }, - "system_prompt": { - "description": "Optional system prompt for the sub-agent", - "type": [ - "string", - "null" - ], - "default": null - }, - "temperature": { - "description": "Temperature override", - "type": [ - "number", - "null" - ], - "format": "double", - "default": null - } - }, - "required": [ - "provider", - "model" - ] - }, - "DingTalkConfig": { - "description": "DingTalk configuration for Stream Mode messaging", - "type": "object", - "properties": { - "allowed_users": { - "description": "Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "client_id": { - "description": "Client ID (AppKey) from DingTalk developer console", - "type": "string" - }, - "client_secret": { - "description": "Client Secret (AppSecret) from DingTalk developer console", - "type": "string" - }, - "mention_only": { - "description": "When true, only process group messages that mention the bot.", - "type": "boolean", - "default": false - } - }, - "required": [ - "client_id", - "client_secret" - ] - }, - "DiscordConfig": { - "description": "Discord bot channel configuration.", - "type": "object", - "properties": { - "allowed_users": { - "description": "Allowed Discord user IDs. Empty = deny all.", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "bot_token": { - "description": "Discord bot token (from Discord Developer Portal).", - "type": "string" - }, - "group_reply_mode": { - "description": "Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.", - "anyOf": [ - { - "$ref": "#/$defs/GroupReplyMode" - }, - { - "type": "null" - } - ], - "default": null - }, - "guild_id": { - "description": "Optional guild (server) ID to restrict the bot to a single guild.", - "type": [ - "string", - "null" - ] - }, - "listen_to_bots": { - "description": "When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.", - "type": "boolean", - "default": false - }, - "mention_only": { - "description": "When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.", - "type": "boolean", - "default": false - } - }, - "required": [ - "bot_token" - ] - }, - "DmPolicy": { - "description": "Policy for direct-message handling.", - "oneOf": [ - { - "description": "Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).", - "type": "string", - "const": "pairing" - }, - { - "description": "Accept only senders listed in `allowed_from`.", - "type": "string", - "const": "allowlist" - }, - { - "description": "Accept any direct sender.", - "type": "string", - "const": "open" - }, - { - "description": "Ignore direct messages.", - "type": "string", - "const": "disabled" - } - ] - }, - "DockerRuntimeConfig": { - "description": "Docker runtime configuration (`[runtime.docker]` section).", - "type": "object", - "properties": { - "allowed_workspace_roots": { - "description": "Optional workspace root allowlist for Docker mount validation.", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "cpu_limit": { - "description": "Optional CPU limit (`None` = no explicit limit).", - "type": [ - "number", - "null" - ], - "format": "double", - "default": 1.0 - }, - "image": { - "description": "Runtime image used to execute shell commands.", - "type": "string", - "default": "alpine:3.20" - }, - "memory_limit_mb": { - "description": "Optional memory limit in MB (`None` = no explicit limit).", - "type": [ - "integer", - "null" - ], - "format": "uint64", - "default": 512, - "minimum": 0 - }, - "mount_workspace": { - "description": "Mount configured workspace into `/workspace`.", - "type": "boolean", - "default": true - }, - "network": { - "description": "Docker network mode (`none`, `bridge`, etc.).", - "type": "string", - "default": "none" - }, - "read_only_rootfs": { - "description": "Mount root filesystem as read-only.", - "type": "boolean", - "default": true - } - } - }, - "EmailConfig": { - "description": "Email channel configuration", - "type": "object", - "properties": { - "allowed_senders": { - "description": "Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "from_address": { - "description": "From address for outgoing emails", - "type": "string" - }, - "idle_timeout_secs": { - "description": "IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes", - "type": "integer", - "format": "uint64", - "default": 1740, - "minimum": 0 - }, - "imap_folder": { - "description": "IMAP folder to poll (default: INBOX)", - "type": "string", - "default": "INBOX" - }, - "imap_host": { - "description": "IMAP server hostname", - "type": "string" - }, - "imap_port": { - "description": "IMAP server port (default: 993 for TLS)", - "type": "integer", - "format": "uint16", - "default": 993, - "maximum": 65535, - "minimum": 0 - }, - "password": { - "description": "Email password for authentication", - "type": "string" - }, - "smtp_host": { - "description": "SMTP server hostname", - "type": "string" - }, - "smtp_port": { - "description": "SMTP server port (default: 465 for TLS)", - "type": "integer", - "format": "uint16", - "default": 465, - "maximum": 65535, - "minimum": 0 - }, - "smtp_tls": { - "description": "Use TLS for SMTP (default: true)", - "type": "boolean", - "default": true - }, - "username": { - "description": "Email username for authentication", - "type": "string" - } - }, - "required": [ - "imap_host", - "smtp_host", - "username", - "password", - "from_address" - ] - }, - "EmbeddingRouteConfig": { - "description": "Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```", - "type": "object", - "properties": { - "api_key": { - "description": "Optional API key override for this route's provider", - "type": [ - "string", - "null" - ], - "default": null - }, - "credential_ref": { - "description": "A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.", - "type": [ - "string", - "null" - ] - }, - "dimensions": { - "description": "Optional embedding dimension override for this route", - "type": [ - "integer", - "null" - ], - "format": "uint", - "default": null, - "minimum": 0 - }, - "hint": { - "description": "Route hint name (e.g. \"semantic\", \"archive\", \"faq\")", - "type": "string" - }, - "model": { - "description": "Embedding model to use with that provider", - "type": "string" - }, - "provider": { - "description": "Embedding provider (`none`, `openai`, or `custom:`)", - "type": "string" - } - }, - "required": [ - "hint", - "provider", - "model" - ] - }, - "EuAiActClassificationConfig": { - "type": "object", - "properties": { - "assessed_at": { - "type": [ - "string", - "null" - ], - "default": null - }, - "owner": { - "type": [ - "string", - "null" - ], - "default": null - }, - "status": { - "$ref": "#/$defs/EuAiActRiskClassification", - "default": "unclassified" - } - } - }, - "EuAiActComplianceConfig": { - "type": "object", - "properties": { - "classification": { - "$ref": "#/$defs/EuAiActClassificationConfig", - "default": { - "assessed_at": null, - "owner": null, - "status": "unclassified" - } - }, - "declaration": { - "$ref": "#/$defs/DeclarationOfConformityConfig", - "default": { - "applicable_union_law": [], - "artifact_path": null, - "artifact_version": null, - "conformity_assessment_procedure": null, - "conformity_statement": null, - "harmonised_standards": [], - "issue_date": null, - "issue_place": null, - "notified_body_certificate": null, - "notified_body_identification_number": null, - "notified_body_name": null, - "personal_data_compliance_statement": null, - "processes_personal_data": false, - "provider_address": null, - "provider_name": null, - "signer_function": null, - "signer_name": null, - "signer_on_behalf_of": null, - "sole_responsibility_statement": null, - "standards_not_applicable_reason": null, - "system_name": null, - "system_reference": null, - "system_type": null - } - }, - "incident_store_path": { - "type": [ - "string", - "null" - ], - "default": null - } - } - }, - "EuAiActRiskClassification": { - "type": "string", - "enum": [ - "unclassified", - "high_risk", - "not_high_risk" - ] - }, - "FitnessConfig": { - "description": "Calendar schedule, evidence thresholds, and retention for fitness v2.", - "type": "object", - "properties": { - "auto_run": { - "description": "Run the daily fitness worker in daemon mode.", - "type": "boolean", - "default": true - }, - "max_backfill_days": { - "description": "Maximum number of closed days recovered after downtime.", - "type": "integer", - "format": "uint32", - "default": 7, - "minimum": 0 - }, - "min_coverage": { - "description": "Minimum available metric weight required to publish a final score.", - "type": "number", - "format": "double", - "default": 0.6 - }, - "min_samples": { - "description": "Minimum samples required before an evidence-derived subscore is usable.", - "type": "integer", - "format": "uint", - "default": 5, - "minimum": 0 - }, - "retention_days": { - "description": "Number of daily JSON reports retained on disk.", - "type": "integer", - "format": "uint32", - "default": 180, - "minimum": 0 - }, - "run_at": { - "description": "Local wall-clock time (`HH:MM`) at which the previous day is scored.", - "type": "string", - "default": "00:10" - }, - "timezone": { - "description": "IANA timezone used to define closed calendar days.", - "type": "string", - "default": "UTC" - } - } - }, - "GatewayConfig": { - "description": "Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.", - "type": "object", - "properties": { - "allow_public_bind": { - "description": "Allow binding to non-localhost without a tunnel (default: false)", - "type": "boolean", - "default": false - }, - "api_rate_limit_per_minute": { - "description": "Max `/api/*` requests per minute per authenticated token.", - "type": "integer", - "format": "uint32", - "default": 60, - "minimum": 0 - }, - "channel_webhook_dedup_ttl_secs": { - "description": "How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.", - "type": "integer", - "format": "uint64", - "default": 86400, - "minimum": 0 - }, - "host": { - "description": "Gateway host (default: 127.0.0.1)", - "type": "string", - "default": "127.0.0.1" - }, - "idempotency_max_keys": { - "description": "Maximum distinct idempotency keys retained in memory.", - "type": "integer", - "format": "uint", - "default": 10000, - "minimum": 0 - }, - "idempotency_ttl_secs": { - "description": "TTL for webhook idempotency keys.", - "type": "integer", - "format": "uint64", - "default": 300, - "minimum": 0 - }, - "pair_rate_limit_per_minute": { - "description": "Max `/pair` requests per minute per client key.", - "type": "integer", - "format": "uint32", - "default": 10, - "minimum": 0 - }, - "paired_tokens": { - "description": "Paired bearer tokens (managed automatically, not user-edited)", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "port": { - "description": "Gateway port (default: 16830)", - "type": "integer", - "format": "uint16", - "default": 16830, - "maximum": 65535, - "minimum": 0 - }, - "rate_limit_max_keys": { - "description": "Maximum distinct client keys tracked by gateway rate limiter maps.", - "type": "integer", - "format": "uint", - "default": 10000, - "minimum": 0 - }, - "require_pairing": { - "description": "Require pairing before accepting requests (default: true)", - "type": "boolean", - "default": true - }, - "targeted_agents": { - "description": "Rollout switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). While false, any otherwise-valid\nnamed target answers 409 `agent_disabled` and never runs as Main.", - "type": "boolean", - "default": false - }, - "trust_forwarded_headers": { - "description": "Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.", - "type": "boolean", - "default": false - }, - "webhook_rate_limit_per_minute": { - "description": "Max `/webhook` requests per minute per client key.", - "type": "integer", - "format": "uint32", - "default": 60, - "minimum": 0 - } - } - }, - "GroupPolicy": { - "description": "Policy for group-message handling.", - "oneOf": [ - { - "description": "Accept only groups listed in `group_allow_from`.", - "type": "string", - "const": "allowlist" - }, - { - "description": "Accept any group.", - "type": "string", - "const": "open" - }, - { - "description": "Ignore group messages.", - "type": "string", - "const": "disabled" - } - ] - }, - "GroupReplyMode": { - "description": "How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.", - "oneOf": [ - { - "description": "Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).", - "type": "string", - "const": "off" - }, - { - "description": "Reply only when the bot is @-mentioned (legacy `mention_only = true`).", - "type": "string", - "const": "mention-only" - }, - { - "description": "Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).", - "type": "string", - "const": "smart" - } - ] - }, - "HeartbeatConfig": { - "description": "Heartbeat configuration for periodic health pings (`[heartbeat]` section).", - "type": "object", - "properties": { - "active_hours": { - "description": "Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.", - "type": "array", - "default": [ - 8, - 23 - ], - "items": { - "type": "integer", - "format": "uint8", - "maximum": 255, - "minimum": 0 - } - }, - "interval_minutes": { - "description": "Interval in minutes between heartbeat pings. Default: `30`.", - "type": "integer", - "format": "uint32", - "default": 30, - "minimum": 0 - }, - "prompt": { - "description": "Prompt used by heartbeat worker when dispatching tasks.", - "type": "string", - "default": "Check HEARTBEAT.md and follow instructions." - } - } - }, - "HttpRequestConfig": { - "description": "HTTP request tool configuration (`[http_request]` section).", - "type": "object", - "properties": { - "max_response_size": { - "description": "Maximum response size in bytes (default: 1MB)", - "type": "integer", - "format": "uint", - "default": 1000000, - "minimum": 0 - }, - "timeout_secs": { - "description": "Request timeout in seconds (default: 30)", - "type": "integer", - "format": "uint64", - "default": 30, - "minimum": 0 - } - } - }, - "IMessageConfig": { - "description": "iMessage channel configuration (macOS only).", - "type": "object", - "properties": { - "allowed_contacts": { - "description": "Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.", - "type": "array", - "items": { - "type": "string" - } - }, - "mention_only": { - "description": "When true, only process group messages that mention the bot.", - "type": "boolean", - "default": false - } - }, - "required": [ - "allowed_contacts" - ] - }, - "IdentityBindingConfig": { - "description": "Startup identity binding entry (`[[identity_bindings]]`).", - "type": "object", - "properties": { - "channel": { - "type": "string" - }, - "channel_account": { - "type": "string" - }, - "display_name": { - "type": [ - "string", - "null" - ], - "default": null - }, - "user_id": { - "type": "string" - } - }, - "required": [ - "user_id", - "channel", - "channel_account" - ] - }, - "IdentityConfig": { - "description": "Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.", - "type": "object", - "properties": { - "aieos_inline": { - "description": "Inline AIEOS JSON (alternative to file path)", - "type": [ - "string", - "null" - ], - "default": null - }, - "aieos_path": { - "description": "Path to AIEOS JSON file (relative to workspace)", - "type": [ - "string", - "null" - ], - "default": null - }, - "format": { - "description": "Identity format: \"openclaw\" (default) or \"aieos\"", - "type": "string", - "default": "openclaw" - } - } - }, - "InteractionNoticeApplicability": { - "type": "string", - "enum": [ - "required", - "not_applicable" - ] - }, - "InteractionNoticeConfig": { - "type": "object", - "properties": { - "applicability": { - "$ref": "#/$defs/InteractionNoticeApplicability", - "default": "required" - }, - "exception_owner": { - "type": [ - "string", - "null" - ], - "default": null - }, - "exception_reviewed_at": { - "type": [ - "string", - "null" - ], - "default": null - }, - "text": { - "type": "string", - "default": "You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers." - }, - "version": { - "type": "string", - "default": "1" - } - } - }, - "IrcConfig": { - "description": "IRC channel configuration.", - "type": "object", - "properties": { - "allowed_users": { - "description": "Allowed nicknames (case-insensitive) or \"*\" for all", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "channels": { - "description": "Channels to join on connect", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "mention_only": { - "description": "When true, only process channel/group messages that mention the bot.", - "type": "boolean", - "default": false - }, - "nickname": { - "description": "Bot nickname", - "type": "string" - }, - "nickserv_password": { - "description": "NickServ IDENTIFY password", - "type": [ - "string", - "null" - ] - }, - "port": { - "description": "IRC server port (default: 6697 for TLS)", - "type": "integer", - "format": "uint16", - "default": 6697, - "maximum": 65535, - "minimum": 0 - }, - "sasl_password": { - "description": "SASL PLAIN password (IRCv3)", - "type": [ - "string", - "null" - ] - }, - "server": { - "description": "IRC server hostname", - "type": "string" - }, - "server_password": { - "description": "Server password (for bouncers like ZNC)", - "type": [ - "string", - "null" - ] - }, - "username": { - "description": "Username (defaults to nickname if not set)", - "type": [ - "string", - "null" - ] - }, - "verify_tls": { - "description": "Verify TLS certificate (default: true)", - "type": [ - "boolean", - "null" - ] - } - }, - "required": [ - "server", - "nickname" - ] - }, - "LarkConfig": { - "description": "Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.", - "type": "object", - "properties": { - "allowed_users": { - "description": "Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "app_id": { - "description": "App ID from Lark/Feishu developer console", - "type": "string" - }, - "app_secret": { - "description": "App Secret from Lark/Feishu developer console", - "type": "string" - }, - "encrypt_key": { - "description": "Encrypt key for webhook message decryption (optional)", - "type": [ - "string", - "null" - ], - "default": null - }, - "mention_only": { - "description": "When true, only process group messages that mention the bot.", - "type": "boolean", - "default": false - }, - "port": { - "description": "HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.", - "type": [ - "integer", - "null" - ], - "format": "uint16", - "default": null, - "maximum": 65535, - "minimum": 0 - }, - "receive_mode": { - "description": "Event receive mode: \"websocket\" (default) or \"webhook\"", - "$ref": "#/$defs/LarkReceiveMode", - "default": "websocket" - }, - "use_feishu": { - "description": "Whether to use the Feishu (Chinese) endpoint instead of Lark (International)", - "type": "boolean", - "default": false - }, - "verification_token": { - "description": "Verification token for webhook validation (optional)", - "type": [ - "string", - "null" - ], - "default": null - } - }, - "required": [ - "app_id", - "app_secret" - ] - }, - "LarkReceiveMode": { - "description": "How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.", - "type": "string", - "enum": [ - "websocket", - "webhook" - ] - }, - "LinqConfig": { - "type": "object", - "properties": { - "allowed_senders": { - "description": "Allowed sender handles (phone numbers) or \"*\" for all", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "api_token": { - "description": "Linq Partner API token (Bearer auth)", - "type": "string" - }, - "from_phone": { - "description": "Phone number to send from (E.164 format)", - "type": "string" - }, - "mention_only": { - "description": "When true, only process group messages that mention the bot.", - "type": "boolean", - "default": false - }, - "signing_secret": { - "description": "Webhook signing secret for signature verification", - "type": [ - "string", - "null" - ], - "default": null - } - }, - "required": [ - "api_token", - "from_phone" - ] - }, - "MattermostConfig": { - "description": "Mattermost bot channel configuration.", - "type": "object", - "properties": { - "allowed_users": { - "description": "Allowed Mattermost user IDs. Empty = deny all.", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "bot_token": { - "description": "Mattermost bot access token.", - "type": "string" - }, - "channel_id": { - "description": "Optional channel ID to restrict the bot to a single channel.", - "type": [ - "string", - "null" - ] - }, - "mention_only": { - "description": "When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.", - "type": [ - "boolean", - "null" - ], - "default": null - }, - "thread_replies": { - "description": "When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.", - "type": [ - "boolean", - "null" - ], - "default": null - }, - "url": { - "description": "Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).", - "type": "string" - } - }, - "required": [ - "url", - "bot_token" - ] - }, - "McpConfig": { - "type": "object", - "properties": { - "servers": { - "description": "Named MCP server definitions", - "type": "object", - "additionalProperties": { - "$ref": "#/$defs/McpServerConfig" - }, - "default": {} - }, - "workspace_servers": { - "description": "Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.", - "$ref": "#/$defs/WorkspaceMcpServers" - } - } - }, - "McpServerConfig": { - "type": "object", - "properties": { - "allow_tools": { - "description": "Optional allow-list of exposed tools (empty = all)", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "args": { - "description": "Command args for stdio mode", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "command": { - "description": "Command for stdio mode", - "type": [ - "string", - "null" - ], - "default": null - }, - "deny_tools": { - "description": "Optional deny-list of exposed tools", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "env": { - "description": "Environment variables for stdio mode", - "type": "object", - "additionalProperties": { - "type": "string" - }, - "default": {} - }, - "request_timeout_ms": { - "description": "Request timeout in milliseconds", - "type": "integer", - "format": "uint64", - "default": 30000, - "minimum": 0 - }, - "startup_timeout_ms": { - "description": "Startup timeout in milliseconds", - "type": "integer", - "format": "uint64", - "default": 10000, - "minimum": 0 - }, - "tool_name_prefix": { - "description": "Prefix used in tool naming and routing", - "type": "string", - "default": "mcp" - }, - "transport": { - "description": "Transport type: stdio or http", - "$ref": "#/$defs/McpTransport", - "default": "stdio" - }, - "url": { - "description": "URL for HTTP mode (streamable HTTP endpoint)", - "type": [ - "string", - "null" - ], - "default": null - }, - "working_dir": { - "description": "Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).", - "type": [ - "string", - "null" - ] - } - } - }, - "McpServerRuntimeConfig": { - "type": "object", - "properties": { - "allowed_origins": { - "description": "Allowed browser origins for future streamable HTTP clients.", - "type": "array", - "default": [ - "claude.ai", - "openai.com", - "localhost" - ], - "items": { - "type": "string" - } - }, - "bind": { - "description": "Advertised bind address. The gateway may still be started with a CLI port override.", - "type": "string", - "default": "127.0.0.1:16831" - }, - "exposed_tools": { - "description": "Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.", - "type": "array", - "default": [ - "memory_search", - "memory_recall", - "memory_get", - "document_search", - "document_get_chunk", - "sessions_list", - "sessions_history" - ], - "items": { - "type": "string" - } - }, - "jwt_algorithms": { - "description": "Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.", - "type": "array", - "default": [ - "RS256" - ], - "items": { - "type": "string" - } - }, - "jwt_audience": { - "description": "Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.", - "type": [ - "string", - "null" - ], - "default": null - }, - "jwt_issuer": { - "description": "Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.", - "type": [ - "string", - "null" - ], - "default": null - }, - "jwt_jwks": { - "description": "Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.", - "type": [ - "string", - "null" - ], - "default": null - }, - "jwt_jwks_cache_ttl_secs": { - "description": "Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.", - "type": "integer", - "format": "uint64", - "default": 300, - "minimum": 0 - }, - "jwt_jwks_uri": { - "description": "Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.", - "type": [ - "string", - "null" - ], - "default": null - }, - "jwt_public_key_pem": { - "description": "PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.", - "type": [ - "string", - "null" - ], - "default": null - }, - "rate_limit_rps": { - "description": "Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.", - "type": "integer", - "format": "uint32", - "default": 10, - "minimum": 0 - }, - "require_auth": { - "description": "Require an authenticated external identity for mutating calls.", - "type": "boolean", - "default": true - } - } - }, - "McpTransport": { - "type": "string", - "enum": [ - "stdio", - "http" - ] - }, - "MediaConfig": { - "description": "Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.", - "type": "object", - "properties": { - "audio_model": { - "description": "Audio model name (Ollama model or OpenAI model). Default: \"whisper\".", - "type": "string", - "default": "whisper" - }, - "audio_ollama_url": { - "description": "Ollama base URL for audio transcription. Default: \"http://localhost:11434\".", - "type": "string", - "default": "http://localhost:11434" - }, - "audio_provider": { - "description": "Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".", - "type": "string", - "default": "none" - }, - "max_audio_size_mb": { - "description": "Maximum audio attachment size in MiB. Default: 20.", - "type": "integer", - "format": "uint", - "default": 20, - "minimum": 0 - }, - "max_video_size_mb": { - "description": "Maximum video attachment size in MiB. Default: 50.", - "type": "integer", - "format": "uint", - "default": 50, - "minimum": 0 - }, - "video_max_frames": { - "description": "Maximum video frames to extract per video. Default: 4.", - "type": "integer", - "format": "uint", - "default": 4, - "minimum": 0 - }, - "video_provider": { - "description": "Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".", - "type": "string", - "default": "none" - } - } - }, - "MemoryConfig": { - "description": "Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.", - "type": "object", - "properties": { - "acl_enabled": { - "description": "Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.", - "type": "boolean", - "default": false - }, - "archive_after_days": { - "description": "Archive daily/session files older than this many days", - "type": "integer", - "format": "uint32", - "default": 7, - "minimum": 0 - }, - "auto_hydrate": { - "description": "Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing", - "type": "boolean", - "default": true - }, - "auto_save": { - "description": "Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.", - "type": "boolean", - "default": true - }, - "backend": { - "description": "\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).", - "type": "string", - "default": "sqlite" - }, - "conversation_retention_days": { - "description": "For sqlite backend: prune conversation rows older than this many days", - "type": "integer", - "format": "uint32", - "default": 3, - "minimum": 0 - }, - "daily_retention_days": { - "description": "For sqlite backend: prune daily rows older than this many days", - "type": "integer", - "format": "uint32", - "default": 7, - "minimum": 0 - }, - "embedding_cache_size": { - "description": "Max embedding cache entries before LRU eviction", - "type": "integer", - "format": "uint", - "default": 10000, - "minimum": 0 - }, - "embedding_dimensions": { - "description": "Embedding vector dimensions", - "type": "integer", - "format": "uint", - "default": 384, - "minimum": 0 - }, - "embedding_model": { - "description": "Embedding model name (e.g. \"text-embedding-3-small\")", - "type": "string", - "default": "prx-local-hash-v1" - }, - "embedding_provider": { - "description": "Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"", - "type": "string", - "default": "local" - }, - "events": { - "description": "Raw/quasi-raw message event recording controls (`[memory.events]`).", - "$ref": "#/$defs/MemoryEventsConfig", - "default": { - "record_assistant_messages": true, - "record_tool_events": false, - "record_user_messages": true - } - }, - "keyword_weight": { - "description": "Weight for keyword BM25 in hybrid search (0.0–1.0)", - "type": "number", - "format": "double", - "default": 0.3 - }, - "legacy_conversation_turns_visible": { - "description": "Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.", - "type": "boolean", - "default": true - }, - "lucid_budget": { - "description": "Token budget for lucid (replaces ZEROCLAW_LUCID_BUDGET / OPENPRX_LUCID_BUDGET)", - "type": [ - "integer", - "null" - ], - "format": "uint32", - "default": null, - "minimum": 0 - }, - "lucid_cmd": { - "description": "Path to lucid binary (replaces ZEROCLAW_LUCID_CMD / OPENPRX_LUCID_CMD)", - "type": [ - "string", - "null" - ], - "default": null - }, - "lucid_failure_cooldown_ms": { - "description": "Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)", - "type": "integer", - "format": "uint64", - "default": 60000, - "minimum": 0 - }, - "lucid_local_hit_threshold": { - "description": "Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)", - "type": "integer", - "format": "uint", - "default": 3, - "minimum": 0 - }, - "lucid_recall_timeout_ms": { - "description": "Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)", - "type": "integer", - "format": "uint64", - "default": 5000, - "minimum": 0 - }, - "lucid_store_timeout_ms": { - "description": "Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)", - "type": "integer", - "format": "uint64", - "default": 3000, - "minimum": 0 - }, - "min_relevance_score": { - "description": "Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4", - "type": "number", - "format": "double", - "default": 0.4 - }, - "purge_after_days": { - "description": "Purge archived files older than this many days", - "type": "integer", - "format": "uint32", - "default": 30, - "minimum": 0 - }, - "semantic": { - "description": "Semantic memory promotion controls (`[memory.semantic]`).", - "$ref": "#/$defs/MemorySemanticConfig", - "default": { - "auto_promote_assistant_messages": false, - "auto_promote_user_messages": true, - "min_chars": 30 - } - }, - "sqlite_open_timeout_secs": { - "description": "For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.", - "type": [ - "integer", - "null" - ], - "format": "uint64", - "default": null, - "minimum": 0 - }, - "sqlite_read_pool_size": { - "description": "For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.", - "type": [ - "integer", - "null" - ], - "format": "uint", - "default": null, - "minimum": 0 - }, - "vector_candidate_cap": { - "description": "How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.", - "type": "integer", - "format": "uint", - "default": 2000, - "minimum": 0 - }, - "vector_weight": { - "description": "Weight for vector similarity in hybrid search (0.0–1.0)", - "type": "number", - "format": "double", - "default": 0.7 - } - } - }, - "MemoryEventsConfig": { - "description": "Raw message event recording configuration (`[memory.events]`).", - "type": "object", - "properties": { - "record_assistant_messages": { - "description": "Record assistant replies.", - "type": "boolean", - "default": true - }, - "record_tool_events": { - "description": "Record tool/event payloads by default.", - "type": "boolean", - "default": false - }, - "record_user_messages": { - "description": "Record inbound/user messages.", - "type": "boolean", - "default": true - } - } - }, - "MemorySemanticConfig": { - "description": "Semantic memory promotion configuration (`[memory.semantic]`).", - "type": "object", - "properties": { - "auto_promote_assistant_messages": { - "description": "Auto-promote eligible assistant messages. Disabled by default to reduce noise.", - "type": "boolean", - "default": false - }, - "auto_promote_user_messages": { - "description": "Auto-promote eligible user messages into long-term semantic memories.", - "type": "boolean", - "default": true - }, - "min_chars": { - "description": "Minimum content length for semantic auto-promotion.", - "type": "integer", - "format": "uint", - "default": 30, - "minimum": 0 - } - } - }, - "MemoryWebhookConfig": { - "type": "object", - "properties": { - "bind": { - "description": "Socket address for the receiver (e.g. \"0.0.0.0:16899\").", - "type": "string", - "default": "0.0.0.0:16899" - }, - "signing_secret": { - "description": "Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.", - "type": [ - "string", - "null" - ], - "default": null - }, - "token": { - "description": "Required bearer token for incoming webhook events.", - "type": [ - "string", - "null" - ], - "default": null - } - } - }, - "ModelOperationSetting": { - "description": "The operations a `[[providers.models]]` entry may list.", - "type": "string", - "enum": [ - "chat", - "embedding", - "decision_endpoint", - "rerank", - "image_generation", - "audio_generation", - "video_generation" - ] - }, - "ModelPricing": { - "description": "Per-model pricing entry (USD per 1M tokens).", - "type": "object", - "properties": { - "cache_read": { - "description": "Cache read input price per 1M tokens.", - "type": "number", - "format": "double", - "default": 0.0 - }, - "cache_write": { - "description": "Cache write/creation input price per 1M tokens.", - "type": "number", - "format": "double", - "default": 0.0 - }, - "input": { - "description": "Input price per 1M tokens", - "type": "number", - "format": "double", - "default": 0.0 - }, - "output": { - "description": "Output price per 1M tokens", - "type": "number", - "format": "double", - "default": 0.0 - } - } - }, - "ModelRouteConfig": { - "description": "Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.", - "type": "object", - "properties": { - "api_key": { - "description": "Optional API key override for this route's provider", - "type": [ - "string", - "null" - ], - "default": null - }, - "context_window": { - "description": "Context window in tokens for this model; only honoured under `[model_settings]`.", - "type": [ - "integer", - "null" - ], - "format": "uint64", - "minimum": 1 - }, - "credential_ref": { - "description": "A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.", - "type": [ - "string", - "null" - ] - }, - "hint": { - "description": "Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")", - "type": "string" - }, - "level": { - "type": [ - "string", - "null" - ] - }, - "model": { - "description": "Model to use with that provider", - "type": "string" - }, - "provider": { - "description": "Provider to route to (must match a known provider name)", - "type": "string" - }, - "reserved_output_tokens": { - "description": "Reserved output tokens for this model; only honoured under `[model_settings]`.", - "type": [ - "integer", - "null" - ], - "format": "uint64", - "minimum": 1 - } - }, - "additionalProperties": true, - "required": [ - "hint", - "provider", - "model" - ] - }, - "ModelSettings": { - "description": "A model level plus explicit parameter overrides in `[model_settings.\"\"]`.", - "type": "object", - "properties": { - "context_window": { - "description": "Context window in tokens for this model; only honoured under `[model_settings]`.", - "type": [ - "integer", - "null" - ], - "format": "uint64", - "minimum": 1 - }, - "level": { - "type": [ - "string", - "null" - ] - }, - "reserved_output_tokens": { - "description": "Reserved output tokens for this model; only honoured under `[model_settings]`.", - "type": [ - "integer", - "null" - ], - "format": "uint64", - "minimum": 1 - } - }, - "additionalProperties": true - }, - "MultimodalConfig": { - "description": "Multimodal (image) handling configuration (`[multimodal]` section).", - "type": "object", - "properties": { - "allow_remote_fetch": { - "description": "Allow fetching remote image URLs (http/https). Disabled by default.", - "type": "boolean", - "default": false - }, - "max_image_size_mb": { - "description": "Maximum image payload size in MiB before base64 encoding.", - "type": "integer", - "format": "uint", - "default": 5, - "minimum": 0 - }, - "max_images": { - "description": "Maximum number of image attachments accepted per request.", - "type": "integer", - "format": "uint", - "default": 4, - "minimum": 0 - } - } - }, - "NextcloudTalkConfig": { - "description": "Nextcloud Talk bot configuration (webhook receive + OCS send API).", - "type": "object", - "properties": { - "allowed_users": { - "description": "Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "app_token": { - "description": "Bot app token used for OCS API bearer auth.", - "type": "string" - }, - "base_url": { - "description": "Nextcloud base URL (e.g. \"https://cloud.example.com\").", - "type": "string" - }, - "mention_only": { - "description": "When true, only process group messages that mention the bot.", - "type": "boolean", - "default": false - }, - "webhook_secret": { - "description": "Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).", - "type": [ - "string", - "null" - ], - "default": null - } - }, - "required": [ - "base_url", - "app_token" - ] - }, - "NgrokTunnelConfig": { - "type": "object", - "properties": { - "auth_token": { - "description": "ngrok auth token", - "type": "string" - }, - "domain": { - "description": "Optional custom domain", - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "auth_token" - ] - }, - "NodeServerConfig": { - "description": "Node daemon runtime config used by `prx-node`.", - "type": "object", - "properties": { - "allowed_commands": { - "description": "Command allowlist matched on first token.\n\nIn restricted mode this list is required unless explicitly set to `[\"*\"]`.", - "type": "array", - "default": [ - "echo" - ], - "items": { - "type": "string" - } - }, - "bearer_token": { - "description": "Required bearer token for /rpc.", - "type": "string", - "default": "" - }, - "blocked_commands": { - "description": "Command denylist matched on first token. Always enforced.", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "exec_timeout_ms": { - "description": "Default command timeout in milliseconds.", - "type": "integer", - "format": "uint64", - "default": 15000, - "minimum": 0 - }, - "hmac_secret": { - "description": "Optional HMAC signing secret.", - "type": [ - "string", - "null" - ], - "default": null - }, - "listen_addr": { - "description": "Listen address for node daemon.", - "type": "string", - "default": "127.0.0.1:8787" - }, - "max_concurrent_tasks": { - "description": "Maximum number of concurrent async command tasks.", - "type": "integer", - "format": "uint", - "default": 8, - "minimum": 0 - }, - "max_output_bytes": { - "description": "Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.", - "type": "integer", - "format": "uint", - "default": 1048576, - "minimum": 0 - }, - "sandbox_root": { - "description": "Sandbox root directory for read/write/cwd constraints.", - "type": "string", - "default": "." - }, - "task_result_ttl_ms": { - "description": "TTL for completed task results in milliseconds.", - "type": "integer", - "format": "uint64", - "default": 3600000, - "minimum": 0 - }, - "tls_cert": { - "description": "TLS certificate path (PEM).", - "type": [ - "string", - "null" - ], - "default": null - }, - "tls_key": { - "description": "TLS private key path (PEM).", - "type": [ - "string", - "null" - ], - "default": null - }, - "tls_required": { - "description": "Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.", - "type": "boolean", - "default": true - } - } - }, - "NodesConfig": { - "description": "Remote node proxy configuration for core-side RPC calls and node daemon defaults.", - "type": "object", - "properties": { - "nodes": { - "description": "Configured remote nodes.", - "type": "array", - "default": [], - "items": { - "$ref": "#/$defs/RemoteNodeConfig" - } - }, - "request_timeout_ms": { - "description": "Default request timeout for node RPC calls.", - "type": "integer", - "format": "uint64", - "default": 15000, - "minimum": 0 - }, - "retry_max": { - "description": "Default max retries for node RPC calls.", - "type": "integer", - "format": "uint8", - "default": 2, - "maximum": 255, - "minimum": 0 - }, - "server": { - "description": "Embedded node server defaults used by `prx-node`.", - "$ref": "#/$defs/NodeServerConfig", - "default": { - "allowed_commands": [ - "echo" - ], - "bearer_token": "", - "blocked_commands": [], - "exec_timeout_ms": 15000, - "hmac_secret": null, - "listen_addr": "127.0.0.1:8787", - "max_concurrent_tasks": 8, - "max_output_bytes": 1048576, - "sandbox_root": ".", - "task_result_ttl_ms": 3600000, - "tls_cert": null, - "tls_key": null, - "tls_required": true - } - } - } - }, - "ObservabilityConfig": { - "description": "Observability backend configuration (`[observability]` section).", - "type": "object", - "properties": { - "backend": { - "description": "\"none\" | \"log\" | \"prometheus\" | \"otel\"", - "type": "string", - "default": "none" - }, - "otel_endpoint": { - "description": "OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".", - "type": [ - "string", - "null" - ], - "default": null - }, - "otel_service_name": { - "description": "Service name reported to the OTel collector. Defaults to \"prx\".", - "type": [ - "string", - "null" - ], - "default": null - } - } - }, - "OllamaProviderConfig": { - "description": "Ollama-specific request options (`[providers.ollama]`).", - "type": "object", - "properties": { - "num_ctx": { - "description": "Explicit context window sent as Ollama `options.num_ctx`.", - "type": [ - "integer", - "null" - ], - "format": "uint", - "default": null, - "minimum": 0 - } - } - }, - "OsPagingConfig": { - "description": "Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.", - "type": "object", - "properties": { - "eviction_threshold": { - "description": "Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.", - "type": "number", - "format": "double", - "default": 0.7 - }, - "keep_recent_messages": { - "description": "Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).", - "type": "integer", - "format": "uint", - "default": 12, - "minimum": 0 - }, - "max_recalled_pages": { - "description": "Maximum number of evicted pages (document chunks) recalled per turn.", - "type": "integer", - "format": "uint", - "default": 10, - "minimum": 0 - }, - "proactive_retrieval": { - "description": "Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.", - "type": "boolean", - "default": true - }, - "retrieval_injection_role": { - "description": "Role under which recalled pages are injected.", - "$ref": "#/$defs/RetrievalInjectionRole", - "default": "system" - } - } - }, - "PluginsConfig": { - "description": "WASM plugin runtime configuration.", - "type": "object", - "properties": { - "enabled": { - "description": "Load WASM plugins from `/plugins`. Default: `false`.", - "type": "boolean", - "default": false - } - }, - "additionalProperties": false - }, - "ProviderModelConfig": { - "description": "One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.", - "type": "object", - "properties": { - "context_window": { - "description": "The model's context window in tokens.", - "type": [ - "integer", - "null" - ], - "format": "uint32", - "minimum": 0 - }, - "model": { - "description": "The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.", - "type": [ - "string", - "null" - ] - }, - "native_tools": { - "description": "Whether the model accepts native tool calls.", - "type": [ - "boolean", - "null" - ] - }, - "operations": { - "description": "The complete list of operations the model executes; every operation not\nlisted is unsupported.", - "type": [ - "array", - "null" - ], - "items": { - "$ref": "#/$defs/ModelOperationSetting" - } - }, - "provider": { - "description": "The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.", - "type": "string" - }, - "streaming": { - "description": "Whether the model streams responses.", - "type": [ - "boolean", - "null" - ] - }, - "structured_output": { - "description": "Whether the model honours a JSON-schema response format.", - "type": [ - "boolean", - "null" - ] - }, - "tool_call_dialect": { - "description": "The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.", - "anyOf": [ - { - "$ref": "#/$defs/ToolCallDialectSetting" - }, - { - "type": "null" - } - ] - }, - "tool_schema_dialect": { - "description": "The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.", - "anyOf": [ - { - "$ref": "#/$defs/ToolSchemaDialectSetting" - }, - { - "type": "null" - } - ] - }, - "vision_input": { - "description": "Whether the model accepts image input.", - "type": [ - "boolean", - "null" - ] - } - }, - "required": [ - "provider" - ] - }, - "ProviderToolDialectConfig": { - "description": "One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.", - "type": "object", - "properties": { - "model": { - "description": "The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.", - "type": [ - "string", - "null" - ] - }, - "provider": { - "description": "The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.", - "type": "string" - }, - "tool_call": { - "description": "The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.", - "anyOf": [ - { - "$ref": "#/$defs/ToolCallDialectSetting" - }, - { - "type": "null" - } - ] - }, - "tool_schema": { - "description": "The tool-schema dialect the endpoint accepts.", - "anyOf": [ - { - "$ref": "#/$defs/ToolSchemaDialectSetting" - }, - { - "type": "null" - } - ] - } - }, - "required": [ - "provider" - ] - }, - "ProvidersConfig": { - "description": "Provider-specific runtime configuration (`[providers]`).", - "type": "object", - "properties": { - "models": { - "description": "Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.", - "type": "array", - "items": { - "$ref": "#/$defs/ProviderModelConfig" - } - }, - "ollama": { - "description": "Ollama-specific request options (`[providers.ollama]`).", - "$ref": "#/$defs/OllamaProviderConfig", - "default": { - "num_ctx": null - } - }, - "tool_dialects": { - "description": "Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).", - "type": "array", - "items": { - "$ref": "#/$defs/ProviderToolDialectConfig" - } - } - } - }, - "ProxyConfig": { - "description": "Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).", - "type": "object", - "properties": { - "all_proxy": { - "description": "Fallback proxy URL for all schemes.", - "type": [ - "string", - "null" - ], - "default": null - }, - "http_proxy": { - "description": "Proxy URL for HTTP requests (supports http, https, socks5, socks5h).", - "type": [ - "string", - "null" - ], - "default": null - }, - "https_proxy": { - "description": "Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).", - "type": [ - "string", - "null" - ], - "default": null - }, - "no_proxy": { - "description": "No-proxy bypass list. Same format as NO_PROXY.", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "scope": { - "description": "Proxy application scope.", - "$ref": "#/$defs/ProxyScope", - "default": "zeroclaw" - }, - "services": { - "description": "Service selectors used when scope = \"services\".", - "type": "array", - "default": [], - "items": { - "type": "string" - } - } - } - }, - "ProxyScope": { - "description": "Proxy application scope — determines which outbound traffic uses the proxy.", - "oneOf": [ - { - "description": "Use system environment proxy variables only.", - "type": "string", - "const": "environment" - }, - { - "description": "Apply proxy to all OpenPRX-managed HTTP traffic (default).", - "type": "string", - "const": "zeroclaw" - }, - { - "description": "Apply proxy only to explicitly listed service selectors.", - "type": "string", - "const": "services" - } - ] - }, - "QQConfig": { - "description": "QQ Official Bot configuration (Tencent QQ Bot SDK)", - "type": "object", - "properties": { - "allowed_users": { - "description": "Allowed user IDs. Empty = deny all, \"*\" = allow all", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "app_id": { - "description": "App ID from QQ Bot developer console", - "type": "string" - }, - "app_secret": { - "description": "App Secret from QQ Bot developer console", - "type": "string" - }, - "mention_only": { - "description": "When true, only process group messages that mention the bot.", - "type": "boolean", - "default": false - } - }, - "required": [ - "app_id", - "app_secret" - ] - }, - "QueryClassificationConfig": { - "description": "Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.", - "type": "object", - "properties": { - "rules": { - "description": "Classification rules evaluated in priority order.", - "type": "array", - "default": [], - "items": { - "$ref": "#/$defs/ClassificationRule" - } - } - } - }, - "RamfluxAccountConfig": { - "description": "Persona for one ramflux AI account. Missing fields fall back to the global agent.", - "type": "object", - "properties": { - "cross_conversation_retrieval": { - "description": "Cross-conversation memory retrieval. Off unless the owner sets it.", - "type": "boolean", - "default": false - }, - "model": { - "type": [ - "string", - "null" - ], - "default": null - }, - "provider": { - "type": [ - "string", - "null" - ], - "default": null - }, - "scope_profile": { - "type": [ - "string", - "null" - ], - "default": null - }, - "system_prompt_file": { - "description": "Path to a system-prompt file. Relative paths are resolved from the workspace.", - "type": [ - "string", - "null" - ], - "default": null - } - }, - "additionalProperties": false - }, - "RamfluxAttachmentFetch": { - "description": "Per-turn caps for `attachment.fetch`.", - "type": "object", - "properties": { - "max_bytes": { - "type": "integer", - "format": "uint64", - "default": 5242880, - "minimum": 0 - }, - "max_per_turn": { - "type": "integer", - "format": "uint8", - "default": 4, - "maximum": 255, - "minimum": 0 - } - }, - "additionalProperties": false - }, - "RamfluxAuthorizationMode": { - "description": "How prx combines its own setting with `bridge.hello.authorization`.", - "oneOf": [ - { - "description": "Use the agent-host value. Until hello arrives, the effective mode is supervised.", - "type": "string", - "const": "follow_rf" - }, - { - "description": "Always supervised, even when the agent-host declares full.", - "type": "string", - "const": "supervised" - }, - { - "description": "Full only when the agent-host also declares full. Config alone never yields full.", - "type": "string", - "const": "full" - } - ] - }, - "RamfluxConfig": { - "description": "Local ramflux agent-host bridge (`[channels_config.ramflux]`).", - "type": "object", - "properties": { - "accounts": { - "type": "object", - "additionalProperties": { - "$ref": "#/$defs/RamfluxAccountConfig" - }, - "default": {} - }, - "allowed_block_types": { - "type": "array", - "default": [ - "Text", - "Markdown", - "Heading", - "KeyValue", - "Metric", - "List", - "TableFallback", - "Form", - "Input", - "Select", - "Progress", - "LogStream", - "Warning", - "Error", - "Success", - "Approval", - "ActionGroup", - "FilePreview", - "Fallback" - ], - "items": { - "type": "string" - } - }, - "attachment_fetch": { - "$ref": "#/$defs/RamfluxAttachmentFetch", - "default": { - "max_bytes": 5242880, - "max_per_turn": 4 - } - }, - "authorization_mode": { - "$ref": "#/$defs/RamfluxAuthorizationMode", - "default": "follow_rf" - }, - "encrypt_at_rest": { - "type": "boolean", - "default": true - }, - "max_in_flight_per_conversation": { - "type": "integer", - "format": "uint8", - "default": 1, - "maximum": 255, - "minimum": 0 - }, - "on_new_message": { - "$ref": "#/$defs/RamfluxOnNewMessage", - "default": "queue" - }, - "socket_path": { - "description": "Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.", - "type": [ - "string", - "null" - ], - "default": null - }, - "surface_limits": { - "$ref": "#/$defs/RamfluxSurfaceLimits", - "default": { - "max_actions": 16, - "max_blocks": 32, - "max_bytes": 65536 - } - }, - "turn_wall_clock_secs": { - "description": "Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.", - "type": "integer", - "format": "uint64", - "default": 120, - "minimum": 0 - } - }, - "additionalProperties": false - }, - "RamfluxOnNewMessage": { - "description": "What to do with a new inbound message while a turn for that conversation is running.", - "type": "string", - "enum": [ - "queue", - "interrupt" - ] - }, - "RamfluxSurfaceLimits": { - "description": "Limits for `reply.surface` blocks and actions.", - "type": "object", - "properties": { - "max_actions": { - "type": "integer", - "format": "uint32", - "default": 16, - "minimum": 0 - }, - "max_blocks": { - "type": "integer", - "format": "uint32", - "default": 32, - "minimum": 0 - }, - "max_bytes": { - "type": "integer", - "format": "uint32", - "default": 65536, - "minimum": 0 - } - }, - "additionalProperties": false - }, - "ReliabilityCircuitBreakerConfig": { - "description": "Process-local provider circuit policy (`[reliability.circuit_breaker]`).", - "type": "object", - "properties": { - "enabled": { - "description": "Enable protection for factory-built provider chains.", - "type": "boolean", - "default": true - }, - "failure_threshold": { - "description": "Consecutive transient failures that open a circuit (at least 1).", - "type": "integer", - "format": "uint32", - "default": 5, - "minimum": 0 - }, - "max_open_secs": { - "description": "Maximum doubled window, between open_secs and 3600 seconds.", - "type": "integer", - "format": "uint64", - "default": 300, - "minimum": 0 - }, - "open_secs": { - "description": "Initial open window in seconds (at least 1).", - "type": "integer", - "format": "uint64", - "default": 30, - "minimum": 0 - } - } - }, - "ReliabilityConfig": { - "description": "Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.", - "type": "object", - "properties": { - "acknowledge_single_provider_risk": { - "description": "Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.", - "type": "boolean", - "default": false - }, - "api_keys": { - "description": "Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "channel_initial_backoff_secs": { - "description": "Initial backoff for channel/daemon restarts.", - "type": "integer", - "format": "uint64", - "default": 2, - "minimum": 0 - }, - "channel_max_backoff_secs": { - "description": "Max backoff for channel/daemon restarts.", - "type": "integer", - "format": "uint64", - "default": 60, - "minimum": 0 - }, - "circuit_breaker": { - "description": "Per-provider consecutive failure protection.", - "$ref": "#/$defs/ReliabilityCircuitBreakerConfig", - "default": { - "enabled": true, - "failure_threshold": 5, - "max_open_secs": 300, - "open_secs": 30 - } - }, - "fallback_providers": { - "description": "Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "model_fallbacks": { - "description": "Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`", - "type": "object", - "additionalProperties": { - "type": "array", - "items": { - "type": "string" - } - }, - "default": {} - }, - "provider_backoff_ms": { - "description": "Base backoff (ms) for provider retry delay.", - "type": "integer", - "format": "uint64", - "default": 500, - "minimum": 0 - }, - "provider_retries": { - "description": "Retries per provider before failing over.", - "type": "integer", - "format": "uint32", - "default": 2, - "minimum": 0 - }, - "scheduler_poll_secs": { - "description": "Scheduler polling cadence in seconds.", - "type": "integer", - "format": "uint64", - "default": 15, - "minimum": 0 - }, - "scheduler_retries": { - "description": "Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.", - "type": "integer", - "format": "uint32", - "default": 2, - "minimum": 0 - } - } - }, - "RemoteNodeConfig": { - "description": "A remote node target for core-side node proxy calls.", - "type": "object", - "properties": { - "bearer_token": { - "description": "Bearer token for node RPC authentication.", - "type": "string" - }, - "endpoint": { - "description": "Base endpoint (e.g. \"http://127.0.0.1:8787\").", - "type": "string" - }, - "hmac_secret": { - "description": "Optional request signing key (HMAC-SHA256).", - "type": [ - "string", - "null" - ], - "default": null - }, - "id": { - "description": "Stable node ID used by the nodes tool.", - "type": "string" - }, - "retry_max": { - "description": "Optional per-node retry override.", - "type": [ - "integer", - "null" - ], - "format": "uint8", - "default": null, - "maximum": 255, - "minimum": 0 - }, - "timeout_ms": { - "description": "Optional per-node timeout override.", - "type": [ - "integer", - "null" - ], - "format": "uint64", - "default": null, - "minimum": 0 - } - }, - "required": [ - "id", - "endpoint", - "bearer_token" - ] - }, - "RemoteTreeLimits": { - "description": "Caps for one remote causal tree (`[a2a.remote_tree]`).", - "type": "object", - "properties": { - "max_connections": { - "description": "Live connection occupancy.", - "type": "integer", - "format": "uint32", - "default": 4, - "minimum": 0 - }, - "max_scheduled": { - "description": "Live scheduled occupancy.", - "type": "integer", - "format": "uint32", - "default": 4, - "minimum": 0 - }, - "max_sends": { - "description": "Cumulative outbound sends.", - "type": "integer", - "format": "uint32", - "default": 4, - "minimum": 0 - }, - "max_spawned": { - "description": "Cumulative spawned descendants.", - "type": "integer", - "format": "uint32", - "default": 16, - "minimum": 0 - } - } - }, - "RetrievalInjectionRole": { - "description": "Where recalled context pages are injected back into the request.", - "oneOf": [ - { - "description": "Inject recalled pages as a leading `system` message (not user-visible).", - "type": "string", - "const": "system" - }, - { - "description": "Inject recalled pages as a leading `user` message.", - "type": "string", - "const": "user" - } - ] - }, - "RouterConfig": { - "description": "Heuristic LLM router configuration (`[router]` section).", - "type": "object", - "properties": { - "alpha": { - "description": "Similarity score weight. Phase 1 keeps this at `0.0`.", - "type": "number", - "format": "float", - "default": 0.0 - }, - "beta": { - "description": "Capability score weight.", - "type": "number", - "format": "float", - "default": 0.5 - }, - "delta": { - "description": "Cost penalty coefficient.", - "type": "number", - "format": "float", - "default": 0.10000000149011612 - }, - "epsilon": { - "description": "Latency penalty coefficient.", - "type": "number", - "format": "float", - "default": 0.10000000149011612 - }, - "gamma": { - "description": "Elo score weight.", - "type": "number", - "format": "float", - "default": 0.30000001192092896 - }, - "knn_k": { - "description": "Number of nearest neighbors considered for voting. Default: `7`.", - "type": "integer", - "format": "uint", - "default": 7, - "minimum": 0 - }, - "knn_min_records": { - "description": "Minimum history records before KNN affects routing. Default: `10`.", - "type": "integer", - "format": "uint", - "default": 10, - "minimum": 0 - }, - "models": { - "description": "Candidate model registry.", - "type": "array", - "default": [], - "items": { - "$ref": "#/$defs/RouterModelConfig" - } - } - } - }, - "RouterModelConfig": { - "description": "Static router metadata for one model candidate.", - "type": "object", - "properties": { - "categories": { - "description": "Capability categories such as `conversation`, `code`, or `analysis`.", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "cost_per_million_tokens": { - "description": "USD cost per million tokens.", - "type": "number", - "format": "float", - "default": 0.0 - }, - "elo_rating": { - "description": "Initial Elo rating.", - "type": "number", - "format": "float", - "default": 1000.0 - }, - "latency_ms": { - "description": "Average latency in milliseconds.", - "type": "integer", - "format": "uint32", - "default": 2000, - "minimum": 0 - }, - "max_context": { - "description": "Maximum context window in tokens.", - "type": "integer", - "format": "uint", - "default": 1000000, - "minimum": 0 - }, - "model_id": { - "description": "Model identifier without provider prefix.", - "type": "string" - }, - "provider": { - "description": "Provider identifier.", - "type": "string" - }, - "reserved_output_tokens": { - "description": "Output tokens reserved for this model when planning input context.", - "type": [ - "integer", - "null" - ], - "format": "uint", - "minimum": 0 - } - }, - "required": [ - "model_id", - "provider" - ] - }, - "RuntimeConfig": { - "description": "Runtime adapter configuration (`[runtime]` section).", - "type": "object", - "properties": { - "codex_reasoning_effort": { - "description": "Codex reasoning effort (replaces ZEROCLAW_CODEX_REASONING_EFFORT)", - "type": [ - "string", - "null" - ], - "default": null - }, - "codex_stream_idle_timeout_secs": { - "description": "Codex stream idle timeout in seconds (replaces ZEROCLAW_CODEX_STREAM_IDLE_TIMEOUT_SECS)", - "type": [ - "integer", - "null" - ], - "format": "uint64", - "default": null, - "minimum": 0 - }, - "docker": { - "description": "Docker runtime settings (used when `kind = \"docker\"`).", - "$ref": "#/$defs/DockerRuntimeConfig", - "default": { - "allowed_workspace_roots": [], - "cpu_limit": 1.0, - "image": "alpine:3.20", - "memory_limit_mb": 512, - "mount_workspace": true, - "network": "none", - "read_only_rootfs": true - } - }, - "idle_hang_secs": { - "description": "Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.", - "type": [ - "integer", - "null" - ], - "format": "uint64", - "default": null, - "minimum": 0 - }, - "kind": { - "description": "Runtime kind (`native` | `docker`).", - "type": "string", - "default": "native" - }, - "long_task_warn_secs": { - "description": "Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.", - "type": [ - "integer", - "null" - ], - "format": "uint64", - "default": null, - "minimum": 0 - }, - "managed_cgroup_root": { - "description": "Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.", - "type": [ - "string", - "null" - ], - "default": null - }, - "max_blocking_threads": { - "description": "Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.", - "type": [ - "integer", - "null" - ], - "format": "uint", - "default": null, - "minimum": 0 - }, - "reasoning_enabled": { - "description": "Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported", - "type": [ - "boolean", - "null" - ], - "default": null - }, - "shell_env_allowlist": { - "description": "Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "workdir": { - "description": "Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.", - "type": [ - "string", - "null" - ], - "default": null - } - } - }, - "SchedulerConfig": { - "description": "Scheduler configuration for periodic task execution (`[scheduler]` section).", - "type": "object", - "properties": { - "claim_lease_secs": { - "description": "Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.", - "type": "integer", - "format": "uint64", - "default": 90, - "minimum": 0 - }, - "max_tasks": { - "description": "Maximum number of persisted scheduled tasks.", - "type": "integer", - "format": "uint", - "default": 64, - "minimum": 0 - } - } - }, - "ScopeConfig": { - "description": "Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```", - "type": "object", - "properties": { - "assign_owners": { - "description": "Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "default": { - "description": "Default action when no rule matches: \"allow\" (default) or \"deny\".", - "$ref": "#/$defs/ScopeDefault", - "default": "allow" - }, - "rules": { - "description": "Ordered list of scope rules evaluated top-to-bottom.", - "type": "array", - "default": [], - "items": { - "$ref": "#/$defs/ScopeRule" - } - } - } - }, - "ScopeDefault": { - "description": "What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.", - "oneOf": [ - { - "description": "Unmatched tool calls are allowed (the default).", - "type": "string", - "const": "allow" - }, - { - "description": "Unmatched tool calls are refused.", - "type": "string", - "const": "deny" - } - ] - }, - "ScopeRule": { - "description": "A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.", - "type": "object", - "properties": { - "assign_allow": { - "description": "Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "assign_deny": { - "description": "Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "channel": { - "description": "Match by channel name: \"signal\", \"telegram\", \"discord\", etc.", - "type": [ - "string", - "null" - ] - }, - "chat_type": { - "description": "Match by chat type: \"direct\", \"group\", or \"*\" for any type.", - "type": [ - "string", - "null" - ] - }, - "send_allow": { - "description": "Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "send_deny": { - "description": "Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "tools_allow": { - "description": "Tool whitelist: only these tools are allowed (empty = all tools permitted).", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "tools_deny": { - "description": "Tool blacklist: these tools are denied regardless of allow list.", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "user": { - "description": "Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.", - "type": [ - "string", - "null" - ] - } - } - }, - "SecretsConfig": { - "description": "Secrets encryption configuration (`[secrets]` section).", - "type": "object", - "properties": { - "encrypt": { - "description": "Enable encryption for API keys and tokens in config.toml", - "type": "boolean", - "default": true - } - } - }, - "SecurityConfig": { - "description": "Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.", - "type": "object", - "properties": { - "audit": { - "description": "Audit logging configuration", - "$ref": "#/$defs/AuditConfig", - "default": { - "log_path": "audit.log", - "max_size_mb": 100 - } - }, - "workspace_hooks": { - "description": "Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.", - "$ref": "#/$defs/WorkspaceHooks" - } - } - }, - "SelfSystemConfig": { - "description": "Self-system experimental automation config (`[self_system]`).", - "type": "object", - "properties": { - "evolution_config_path": { - "description": "Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG / ZEROCLAW_EVOLUTION_CONFIG)", - "type": [ - "string", - "null" - ], - "default": null - }, - "evolution_debug_raw": { - "description": "Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW / ZEROCLAW_EVOLUTION_DEBUG_RAW)", - "type": "boolean", - "default": false - }, - "evolution_interval_hours": { - "description": "Evolution scheduler interval in hours (daemon mode).", - "type": "integer", - "format": "uint32", - "default": 24, - "minimum": 0 - }, - "evolution_judge_timeout_secs": { - "description": "Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.", - "type": "integer", - "format": "uint64", - "default": 180, - "minimum": 0 - }, - "evolution_model_max_micro_usd": { - "description": "Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.", - "type": "integer", - "format": "uint64", - "default": 0, - "minimum": 0 - }, - "evolution_model_max_tokens": { - "description": "Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.", - "type": "integer", - "format": "uint64", - "default": 16384, - "minimum": 0 - }, - "fitness": { - "description": "Daily fitness snapshot policy.", - "$ref": "#/$defs/FitnessConfig", - "default": { - "auto_run": true, - "max_backfill_days": 7, - "min_coverage": 0.6, - "min_samples": 5, - "retention_days": 180, - "run_at": "00:10", - "timezone": "UTC" - } - }, - "fitness_interval_hours": { - "description": "Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.", - "type": "integer", - "format": "uint64", - "default": 24, - "minimum": 0 - } - } - }, - "SessionsSpawnConfig": { - "description": "Sessions spawn configuration (`[sessions_spawn]` section).", - "type": "object", - "properties": { - "cleanup_on_complete": { - "description": "Remove worker workspace directory after process-mode completion.", - "type": "boolean", - "default": true - }, - "default_mode": { - "description": "Default execution mode for sessions_spawn (`task` or `process`).", - "type": "string", - "default": "task" - }, - "process_memory_strategy": { - "description": "Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.", - "type": "string", - "default": "shared_fabric" - }, - "worker_workspace_root": { - "description": "Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.", - "type": [ - "string", - "null" - ], - "default": null - } - } - }, - "SignalConfig": { - "type": "object", - "properties": { - "account": { - "description": "E.164 phone number of the signal-cli account (e.g. \"+1234567890\").", - "type": "string" - }, - "allowed_from": { - "description": "Allowed sender phone numbers (E.164) or \"*\" for all.", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "cli_path": { - "description": "Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).", - "type": [ - "string", - "null" - ], - "default": null - }, - "daemon_http_port": { - "description": "Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.", - "type": [ - "integer", - "null" - ], - "format": "uint16", - "default": null, - "maximum": 65535, - "minimum": 0 - }, - "daemon_mode": { - "description": "Deprecated: ignored. Accepted for backward compatibility with older config files.", - "type": [ - "boolean", - "null" - ], - "default": null - }, - "data_dir": { - "description": "signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).", - "type": [ - "string", - "null" - ], - "default": null - }, - "dm_policy": { - "description": "Direct-message policy.", - "$ref": "#/$defs/DmPolicy", - "default": "allowlist" - }, - "group_allow_from": { - "description": "Allowlisted group IDs used when `group_policy = \"allowlist\"`.", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "group_id": { - "description": "Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group", - "type": [ - "string", - "null" - ], - "default": null - }, - "group_policy": { - "description": "Group-message policy.", - "$ref": "#/$defs/GroupPolicy", - "default": "allowlist" - }, - "http_url": { - "description": "Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.", - "type": "string", - "default": "http://localhost:8080" - }, - "ignore_attachments": { - "description": "Skip messages that are attachment-only (no text body).", - "type": "boolean", - "default": false - }, - "ignore_stories": { - "description": "Skip incoming story messages.", - "type": "boolean", - "default": false - }, - "mention_only": { - "description": "When true, only process group messages that mention the bot.", - "type": "boolean", - "default": false - }, - "mode": { - "description": "Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.", - "type": [ - "string", - "null" - ], - "default": null - }, - "startup_timeout_ms": { - "description": "Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.", - "type": "integer", - "format": "uint64", - "default": 30000, - "minimum": 0 - }, - "storm_protection": { - "description": "Signal ingress storm protection controls.", - "$ref": "#/$defs/SignalStormProtectionConfig", - "default": { - "abnormal_threshold": 10, - "abnormal_window_secs": 60, - "breaker_duration_secs": 300, - "dedupe_ttl_secs": 60, - "min_reply_interval_secs": 2 - } - } - }, - "required": [ - "account" - ] - }, - "SignalStormProtectionConfig": { - "type": "object", - "properties": { - "abnormal_threshold": { - "description": "Non-user event threshold within `abnormal_window_secs` before tripping the breaker.", - "type": "integer", - "format": "uint", - "default": 10, - "minimum": 0 - }, - "abnormal_window_secs": { - "description": "Sliding window in seconds for non-user event counting.", - "type": "integer", - "format": "uint64", - "default": 60, - "minimum": 0 - }, - "breaker_duration_secs": { - "description": "Circuit breaker duration in seconds after threshold is reached.", - "type": "integer", - "format": "uint64", - "default": 300, - "minimum": 0 - }, - "dedupe_ttl_secs": { - "description": "Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.", - "type": "integer", - "format": "uint64", - "default": 60, - "minimum": 0 - }, - "min_reply_interval_secs": { - "description": "Minimum interval in seconds between replies for the same `(channel + reply_target)`.", - "type": "integer", - "format": "uint64", - "default": 2, - "minimum": 0 - } - } - }, - "SkillRagConfig": { - "description": "Dynamic skill retrieval configuration (`[skill_rag]` section).", - "type": "object", - "properties": { - "top_k": { - "description": "How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).", - "type": "integer", - "format": "uint", - "default": 32, - "minimum": 0 - } - } - }, - "SkillSuiteRegistration": { - "description": "The frozen suite that governs one skill's proposals.", - "type": "object", - "properties": { - "skill_id": { - "description": "The skill the suite governs.", - "type": "string" - }, - "suite_digest": { - "description": "SHA-256 digest (64 lowercase hex digits) of the frozen suite.", - "type": "string" - } - }, - "additionalProperties": false, - "required": [ - "skill_id", - "suite_digest" - ] - }, - "SkillsConfig": { - "description": "Skills loading configuration (`[skills]` section).", - "type": "object", - "properties": { - "open_skills_dir": { - "description": "Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.", - "type": [ - "string", - "null" - ], - "default": null - }, - "openclaw_skills_dir": { - "description": "Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.", - "type": [ - "string", - "null" - ], - "default": null - } - } - }, - "SkillsLifecycleConfig": { - "description": "`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.", - "type": "object", - "properties": { - "allow_executable_proposals": { - "description": "Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.", - "type": "boolean", - "default": false - }, - "enabled": { - "description": "Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.", - "type": "boolean", - "default": false - }, - "max_concurrent_evaluations": { - "description": "Most evaluations running at once.", - "type": "integer", - "format": "uint32", - "default": 1, - "minimum": 0 - }, - "max_edit_fraction": { - "description": "Edit budget of a proposal as a fraction of the skill body, in (0, 1].", - "type": "number", - "format": "double", - "default": 0.2 - }, - "max_edit_tokens": { - "description": "Edit budget of a proposal, in tokens.", - "type": "integer", - "format": "uint64", - "default": 300, - "minimum": 0 - }, - "max_proposals_per_cycle": { - "description": "Most proposals one cycle may start.", - "type": "integer", - "format": "uint32", - "default": 1, - "minimum": 0 - }, - "min_cases_floor": { - "description": "Smallest `min_cases` a governing suite may declare. Below 3 is refused.", - "type": "integer", - "format": "uint32", - "default": 3, - "minimum": 0 - }, - "mode": { - "description": "`draft_only`, `shadow` or `auto`.", - "$ref": "#/$defs/SkillsLifecycleModeConfig", - "default": "draft_only" - }, - "owner_scope": { - "description": "The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.", - "type": [ - "string", - "null" - ], - "default": null - }, - "require_holdout": { - "description": "A governing suite must have a holdout split. `false` is refused.", - "type": "boolean", - "default": true - }, - "storage_dir": { - "description": "Store location under the workspace. Only the default is supported.", - "type": "string", - "default": "self/skill-lifecycle" - }, - "suites": { - "description": "The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.", - "type": "array", - "default": [], - "items": { - "$ref": "#/$defs/SkillSuiteRegistration" - } - } - }, - "additionalProperties": false - }, - "SkillsLifecycleModeConfig": { - "description": "What the lifecycle may do. Mirrors `LifecycleMode`.", - "oneOf": [ - { - "description": "Drafts and reviews only.", - "type": "string", - "const": "draft_only" - }, - { - "description": "Drafts plus evaluation and gating; never publishes.", - "type": "string", - "const": "shadow" - }, - { - "description": "Publishes an eligible proposal after every gate.", - "type": "string", - "const": "auto" - } - ] - }, - "SlackConfig": { - "description": "Slack bot channel configuration.", - "type": "object", - "properties": { - "allowed_users": { - "description": "Allowed Slack user IDs. Empty = deny all.", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "app_token": { - "description": "Slack app-level token for Socket Mode (xapp-...).", - "type": [ - "string", - "null" - ] - }, - "bot_token": { - "description": "Slack bot OAuth token (xoxb-...).", - "type": "string" - }, - "channel_id": { - "description": "Optional channel ID to restrict the bot to a single channel.", - "type": [ - "string", - "null" - ] - }, - "mention_only": { - "description": "When true, only process group messages that mention the bot.", - "type": "boolean", - "default": false - } - }, - "required": [ - "bot_token" - ] - }, - "SmartGroupConfig": { - "description": "Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).", - "type": "object", - "properties": { - "classifier_max_context_messages": { - "description": "How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.", - "type": "integer", - "format": "uint", - "default": 3, - "minimum": 0 - }, - "classifier_model": { - "description": "Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.", - "type": "string", - "default": "" - }, - "classifier_provider": { - "description": "Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.", - "type": "string", - "default": "" - }, - "classifier_temperature": { - "description": "Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).", - "type": "number", - "format": "double", - "default": 0.0 - }, - "classifier_timeout_secs": { - "description": "Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.", - "type": "integer", - "format": "uint64", - "default": 5, - "minimum": 0 - } - } - }, - "StorageConfig": { - "description": "Persistent storage configuration (`[storage]` section).", - "type": "object", - "properties": { - "provider": { - "description": "Storage provider settings (e.g. sqlite, postgres).", - "$ref": "#/$defs/StorageProviderSection", - "default": { - "config": { - "connect_timeout_secs": null, - "db_url": null, - "pool_max_size": 32, - "provider": "", - "schema": "public", - "table": "memories" - } - } - } - } - }, - "StorageProviderConfig": { - "description": "Storage provider backend configuration (e.g. postgres connection details).", - "type": "object", - "properties": { - "connect_timeout_secs": { - "description": "Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.", - "type": [ - "integer", - "null" - ], - "format": "uint64", - "default": null, - "minimum": 0 - }, - "db_url": { - "description": "Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.", - "type": [ - "string", - "null" - ], - "default": null - }, - "pool_max_size": { - "description": "Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.", - "type": "integer", - "format": "uint", - "default": 32, - "minimum": 0 - }, - "provider": { - "description": "Storage engine key (e.g. \"postgres\", \"sqlite\").", - "type": "string", - "default": "" - }, - "schema": { - "description": "Database schema for SQL backends.", - "type": "string", - "default": "public" - }, - "table": { - "description": "Table name for memory entries.", - "type": "string", - "default": "memories" - } - } - }, - "StorageProviderSection": { - "description": "Wrapper for the storage provider configuration section.", - "type": "object", - "properties": { - "config": { - "description": "Storage provider backend settings.", - "$ref": "#/$defs/StorageProviderConfig", - "default": { - "connect_timeout_secs": null, - "db_url": null, - "pool_max_size": 32, - "provider": "", - "schema": "public", - "table": "memories" - } - } - } - }, - "StreamMode": { - "description": "Streaming mode for channels that support progressive message updates.", - "oneOf": [ - { - "description": "No streaming -- send the complete response as a single message (default).", - "type": "string", - "const": "off" - }, - { - "description": "Update a draft message with every flush interval.", - "type": "string", - "const": "partial" - } - ] - }, - "TailscaleTunnelConfig": { - "type": "object", - "properties": { - "funnel": { - "description": "Use Tailscale Funnel (public internet) vs Serve (tailnet only)", - "type": "boolean", - "default": false - }, - "hostname": { - "description": "Optional hostname override", - "type": [ - "string", - "null" - ] - } - } - }, - "TaskRoutingConfig": { - "description": "Lightweight pre-LLM task routing.", - "type": "object", - "properties": { - "default_intent": { - "description": "Fallback intent when no rule matches.", - "$ref": "#/$defs/TaskRoutingIntentConfig", - "default": "simple" - }, - "rules": { - "description": "Rules evaluated in descending priority order.", - "type": "array", - "default": [], - "items": { - "$ref": "#/$defs/TaskRoutingRule" - } - } - } - }, - "TaskRoutingIntentConfig": { - "description": "Task-routing default and rule intent.", - "type": "string", - "enum": [ - "simple", - "delegate", - "stream" - ] - }, - "TaskRoutingRule": { - "description": "A single task-routing rule.", - "type": "object", - "properties": { - "intent": { - "description": "Route intent to apply when a keyword matches.", - "$ref": "#/$defs/TaskRoutingIntentConfig", - "default": "simple" - }, - "keywords": { - "description": "Case-insensitive substring matches.", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "model_hint": { - "description": "Optional model hint/raw model for non-delegated requests.", - "type": [ - "string", - "null" - ], - "default": null - }, - "priority": { - "description": "Higher priority rules are checked first.", - "type": "integer", - "format": "int32", - "default": 0 - }, - "sub_agent_model": { - "description": "Optional raw sub-agent model override for delegated tasks.", - "type": [ - "string", - "null" - ], - "default": null - } - } - }, - "TelegramConfig": { - "description": "Telegram bot channel configuration.", - "type": "object", - "properties": { - "allowed_users": { - "description": "Allowed Telegram user IDs or usernames. Empty = deny all.", - "type": "array", - "items": { - "type": "string" - } - }, - "bot_token": { - "description": "Telegram Bot API token (from @BotFather).", - "type": "string" - }, - "draft_update_interval_ms": { - "description": "Minimum interval (ms) between draft message edits to avoid rate limits.", - "type": "integer", - "format": "uint64", - "default": 1000, - "minimum": 0 - }, - "group_reply_mode": { - "description": "Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.", - "anyOf": [ - { - "$ref": "#/$defs/GroupReplyMode" - }, - { - "type": "null" - } - ], - "default": null - }, - "interrupt_on_new_message": { - "description": "When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.", - "type": "boolean", - "default": false - }, - "mention_only": { - "description": "When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.", - "type": "boolean", - "default": false - }, - "stream_mode": { - "description": "Streaming mode for progressive response delivery via message edits.", - "$ref": "#/$defs/StreamMode", - "default": "off" - } - }, - "required": [ - "bot_token", - "allowed_users" - ] - }, - "ToolCallDialectSetting": { - "description": "The tool-call grammars an operator may declare for an endpoint.", - "oneOf": [ - { - "description": "Only the native `tool_calls` array is a tool call (the default).", - "type": "string", - "const": "native" - }, - { - "description": "Additionally read `{json}` from the content,\nfor a tool name the request registered.", - "type": "string", - "const": "xml_function_tags" - } - ] - }, - "ToolSchemaDialectSetting": { - "description": "The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.", - "oneOf": [ - { - "description": "The published document, byte for byte (the default).", - "type": "string", - "const": "raw" - }, - { - "description": "The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.", - "type": "string", - "const": "no_root_combinators" - } - ] - }, - "ToolTieringConfig": { - "description": "Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.", - "type": "object", - "properties": { - "always_exclude": { - "description": "Tool names excluded from capability publication.", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "always_include": { - "description": "Tool names preferred for direct publication, subject to admission gates.", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "channel_exclude": { - "description": "Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefaults to [`DEFAULT_CHANNEL_EXCLUDED_TOOLS`]; set to `[]` to expose the\nfull operator surface on channels again.", - "type": "array", - "default": [ - "wasm_plugins_manage", - "wasm_plugin_reload", - "wasm_plugins_status", - "hooks_manage", - "hooks_status", - "proxy_config", - "config_reload", - "gateway", - "mcp_status", - "nodes", - "git_operations", - "skills_manage", - "memory_reindex", - "document_sync", - "document_ingest" - ], - "items": { - "type": "string" - } - } - } - }, - "TunnelConfig": { - "description": "Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.", - "type": "object", - "properties": { - "cloudflare": { - "description": "Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).", - "anyOf": [ - { - "$ref": "#/$defs/CloudflareTunnelConfig" - }, - { - "type": "null" - } - ], - "default": null - }, - "custom": { - "description": "Custom tunnel command configuration (used when `provider = \"custom\"`).", - "anyOf": [ - { - "$ref": "#/$defs/CustomTunnelConfig" - }, - { - "type": "null" - } - ], - "default": null - }, - "ngrok": { - "description": "ngrok tunnel configuration (used when `provider = \"ngrok\"`).", - "anyOf": [ - { - "$ref": "#/$defs/NgrokTunnelConfig" - }, - { - "type": "null" - } - ], - "default": null - }, - "provider": { - "description": "Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.", - "type": "string", - "default": "none" - }, - "tailscale": { - "description": "Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).", - "anyOf": [ - { - "$ref": "#/$defs/TailscaleTunnelConfig" - }, - { - "type": "null" - } - ], - "default": null - } - } - }, - "UserPolicyConfig": { - "description": "Startup user policy entry (`[[user_policies]]`).", - "type": "object", - "properties": { - "blocked_patterns": { - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "projects": { - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "role": { - "type": "string", - "default": "guest" - }, - "user_id": { - "type": "string" - }, - "visibility_ceiling": { - "type": "string", - "default": "private" - } - }, - "required": [ - "user_id" - ] - }, - "WacliConfig": { - "description": "wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```", - "type": "object", - "properties": { - "allow_unsigned_loopback": { - "description": "Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).", - "type": "boolean", - "default": false - }, - "allowed_from": { - "description": "Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.", - "type": "array", - "default": [ - "*" - ], - "items": { - "type": "string" - } - }, - "bot_jid": { - "description": "Bot's own JID, used for reply-to-bot mention detection.", - "type": [ - "string", - "null" - ], - "default": null - }, - "bot_lid": { - "description": "The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.", - "type": [ - "string", - "null" - ], - "default": null - }, - "bot_number": { - "description": "Bot's own phone number (digits), used for `@` mention detection.", - "type": [ - "string", - "null" - ], - "default": null - }, - "cli_path": { - "description": "Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.", - "type": [ - "string", - "null" - ], - "default": null - }, - "group_reply_mode": { - "description": "Smart group-reply mode. When `None`, derived from `mention_only`.", - "anyOf": [ - { - "$ref": "#/$defs/GroupReplyMode" - }, - { - "type": "null" - } - ], - "default": null - }, - "host": { - "description": "REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].", - "type": [ - "string", - "null" - ], - "writeOnly": true - }, - "mention_only": { - "description": "When true, only process group messages that mention the bot.", - "type": "boolean", - "default": false - }, - "outbound_media_workspace_only": { - "description": "Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.", - "type": "boolean", - "default": false - }, - "port": { - "description": "REMOVED: legacy JSON-RPC daemon port. See `host`.", - "type": [ - "integer", - "null" - ], - "format": "uint16", - "maximum": 65535, - "minimum": 0, - "writeOnly": true - }, - "self_chat_mode": { - "description": "Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.", - "type": "boolean", - "default": false - }, - "store_dir": { - "description": "wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.", - "type": [ - "string", - "null" - ], - "default": null - }, - "webhook_listen": { - "description": "Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").", - "type": "string", - "default": "127.0.0.1:16868" - }, - "webhook_path": { - "description": "HTTP path the webhook server serves (default: \"/wacli\").", - "type": "string", - "default": "/wacli" - }, - "webhook_secret": { - "description": "HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.", - "type": [ - "string", - "null" - ], - "default": null - } - } - }, - "WebSearchConfig": { - "description": "Web search tool configuration (`[web_search]` section).", - "type": "object", - "properties": { - "brave_api_key": { - "description": "Brave Search API key (required if provider is \"brave\")", - "type": [ - "string", - "null" - ], - "default": null - }, - "fetch_max_chars": { - "description": "Maximum characters returned by `web_fetch` (default 10000)", - "type": "integer", - "format": "uint", - "default": 50000, - "minimum": 0 - }, - "max_results": { - "description": "Maximum results per search (1-20)", - "type": "integer", - "format": "uint", - "default": 15, - "minimum": 0 - }, - "provider": { - "description": "Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)", - "type": "string", - "default": "duckduckgo" - }, - "timeout_secs": { - "description": "Request timeout in seconds", - "type": "integer", - "format": "uint64", - "default": 15, - "minimum": 0 - } - } - }, - "WebhookConfig": { - "description": "Webhook channel configuration.", - "type": "object", - "properties": { - "port": { - "description": "Port to listen on for incoming webhooks.", - "type": "integer", - "format": "uint16", - "maximum": 65535, - "minimum": 0 - }, - "secret": { - "description": "Optional shared secret for webhook signature verification.", - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "port" - ] - }, - "WhatsAppConfig": { - "description": "WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.", - "type": "object", - "properties": { - "access_token": { - "description": "Access token from Meta Business Suite (Cloud API mode)", - "type": [ - "string", - "null" - ], - "default": null - }, - "allowed_numbers": { - "description": "Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "app_secret": { - "description": "App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode", - "type": [ - "string", - "null" - ], - "default": null - }, - "dm_policy": { - "description": "Direct-message policy.", - "$ref": "#/$defs/DmPolicy", - "default": "allowlist" - }, - "group_allow_from": { - "description": "Allowlisted group IDs used when `group_policy = \"allowlist\"`.", - "type": "array", - "default": [], - "items": { - "type": "string" - } - }, - "group_policy": { - "description": "Group-message policy.", - "$ref": "#/$defs/GroupPolicy", - "default": "allowlist" - }, - "group_reply_mode": { - "description": "Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).", - "anyOf": [ - { - "$ref": "#/$defs/GroupReplyMode" - }, - { - "type": "null" - } - ], - "default": null - }, - "mention_only": { - "description": "When true, only process group messages that mention the bot.", - "type": "boolean", - "default": false - }, - "pair_code": { - "description": "Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one", - "type": [ - "string", - "null" - ], - "default": null - }, - "pair_phone": { - "description": "Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used", - "type": [ - "string", - "null" - ], - "default": null - }, - "phone_number_id": { - "description": "Phone number ID from Meta Business API (Cloud API mode)", - "type": [ - "string", - "null" - ], - "default": null - }, - "read_pool_size": { - "description": "Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.", - "type": [ - "integer", - "null" - ], - "format": "uint", - "default": null, - "minimum": 0 - }, - "session_path": { - "description": "Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs", - "type": [ - "string", - "null" - ], - "default": null - }, - "verify_token": { - "description": "Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode", - "type": [ - "string", - "null" - ], - "default": null - }, - "ws_url": { - "description": "WebSocket URL override (replaces WHATSAPP_WS_URL)", - "type": [ - "string", - "null" - ], - "default": null - } - } - }, - "WorkspaceHooks": { - "description": "Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).", - "oneOf": [ - { - "description": "They do not run (the default); `prx doctor` and `hooks_status` say so.", - "type": "string", - "const": "off" - }, - { - "description": "They run, in a cleared environment and a dedicated directory beside\n`config.toml`.", - "type": "string", - "const": "on" - } - ] - }, - "WorkspaceMcpServers": { - "description": "Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).", - "oneOf": [ - { - "description": "None: a workspace file may only narrow the servers defined in\n`config.toml`.", - "type": "string", - "const": "off" - }, - { - "description": "HTTP servers (still refused when they target a private address).", - "type": "string", - "const": "http_only" - }, - { - "description": "HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.", - "type": "string", - "const": "stdio" - } - ] - }, - "XinConfig": { - "description": "Configuration for the xin autonomous task engine (`[xin]`).", - "type": "object", - "properties": { - "adopt_legacy_tasks": { - "description": "Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).", - "type": "boolean", - "default": false - }, - "interval_minutes": { - "description": "Tick interval in minutes (minimum 1). Default: 5.", - "type": "integer", - "format": "uint32", - "default": 5, - "minimum": 0 - }, - "stale_timeout_minutes": { - "description": "Minutes after which a running task is marked stale. Default: 60.", - "type": "integer", - "format": "uint32", - "default": 60, - "minimum": 0 - } - } - } - } -} +{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Config","description":"Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).","type":"object","properties":{"a2a":{"description":"Agent-to-Agent compatibility configuration (`[a2a]`).","$ref":"#/$defs/A2aConfig","default":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trusted_trust_domains":[],"trust_domain":"prx.local"}},"agent":{"description":"Agent orchestration settings (`[agent]`).","$ref":"#/$defs/AgentConfig","default":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2,"messaging":{"inbound":true}}},"agents":{"description":"Delegate agent configurations for multi-agent workflows.","type":"object","additionalProperties":{"$ref":"#/$defs/DelegateAgentConfig"},"default":{}},"api_key":{"description":"API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.","type":["string","null"],"default":null},"api_url":{"description":"Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)","type":["string","null"],"default":null},"auth":{"description":"Auth profile and external credential import settings (`[auth]`).","$ref":"#/$defs/AuthConfig","default":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"}},"autonomy":{"description":"Autonomy and security policy configuration (`[autonomy]`).","$ref":"#/$defs/AutonomyConfig","default":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":500,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true}},"browser":{"description":"Browser automation configuration (`[browser]`).","$ref":"#/$defs/BrowserConfig","default":{"allowed_domains":[],"computer_use":{"api_key":null}}},"channels_config":{"description":"Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).","$ref":"#/$defs/ChannelsConfig","default":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null}},"chat":{"description":"Interactive chat UI configuration (`[chat]`).","$ref":"#/$defs/ChatConfig","default":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2}},"compliance":{"description":"Operator-owned compliance controls (`[compliance]`).","$ref":"#/$defs/ComplianceConfig","default":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}},"composio":{"description":"Composio managed OAuth tools integration (`[composio]`).","$ref":"#/$defs/ComposioConfig","default":{"api_key":null,"entity_id":"default"}},"cost":{"description":"Cost tracking and budget enforcement configuration (`[cost]`).","$ref":"#/$defs/CostConfig","default":{"allow_override":false,"daily_limit_usd":10.0,"monthly_limit_usd":100.0,"prices":{},"warn_at_percent":80}},"cron":{"description":"Cron job configuration (`[cron]`).","$ref":"#/$defs/CronConfig","default":{"max_run_history":50}},"decision_engine":{"description":"Optional advisory decision engine, disabled by default.","$ref":"#/$defs/DecisionEngineConfig","default":{"candidates":5,"enabled":false,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"latency_budget_ms":500,"max_candidates":12,"token_ratio_limit":0.3499999940395355}},"default_model":{"description":"Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.","type":["string","null"]},"default_provider":{"description":"Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.","type":["string","null"]},"default_temperature":{"description":"Default model temperature (0.0–2.0). Default: `0.7`.","type":"number","format":"double","default":0.7},"embedding_routes":{"description":"Embedding routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/EmbeddingRouteConfig"}},"gateway":{"description":"Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).","$ref":"#/$defs/GatewayConfig","default":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":false,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60}},"heartbeat":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]`).","$ref":"#/$defs/HeartbeatConfig","default":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."}},"http_request":{"description":"HTTP request tool configuration (`[http_request]`).","$ref":"#/$defs/HttpRequestConfig","default":{"max_response_size":1000000,"timeout_secs":30}},"identity":{"description":"Identity format configuration: OpenClaw or AIEOS (`[identity]`).","$ref":"#/$defs/IdentityConfig","default":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"}},"identity_bindings":{"description":"Static identity bindings loaded at startup (`[[identity_bindings]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/IdentityBindingConfig"}},"mcp":{"description":"Secrets encryption configuration (`[secrets]`).","$ref":"#/$defs/McpConfig","default":{"servers":{}}},"mcp_server":{"description":"MCP server compatibility configuration (`[mcp_server]`).","$ref":"#/$defs/McpServerRuntimeConfig","default":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true}},"media":{"description":"Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.","$ref":"#/$defs/MediaConfig","default":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"}},"memory":{"description":"Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).","$ref":"#/$defs/MemoryConfig","default":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7}},"model_routes":{"description":"Model routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/ModelRouteConfig"}},"model_settings":{"description":"Catalog model levels and explicit parameters, keyed by canonical release ID.","type":"object","additionalProperties":{"$ref":"#/$defs/ModelSettings"},"default":{}},"multimodal":{"description":"Multimodal (image) handling configuration (`[multimodal]`).","$ref":"#/$defs/MultimodalConfig","default":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4}},"nodes":{"description":"Remote node proxy configuration (`[nodes]`).","$ref":"#/$defs/NodesConfig","default":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}},"observability":{"description":"Observability backend configuration (`[observability]`).","$ref":"#/$defs/ObservabilityConfig","default":{"backend":"none","otel_endpoint":null,"otel_service_name":null}},"plugins":{"description":"WASM plugin runtime switch (`[plugins]`), off by default.","$ref":"#/$defs/PluginsConfig","default":{"enabled":false}},"providers":{"description":"Provider-specific runtime options (`[providers.]`).","$ref":"#/$defs/ProvidersConfig","default":{"ollama":{"num_ctx":null}}},"proxy":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).","$ref":"#/$defs/ProxyConfig","default":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"zeroclaw","services":[]}},"query_classification":{"description":"Automatic query classification — maps user messages to model hints.","$ref":"#/$defs/QueryClassificationConfig","default":{"rules":[]}},"reliability":{"description":"Reliability settings: retries, fallback providers, backoff (`[reliability]`).","$ref":"#/$defs/ReliabilityConfig","default":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2}},"router":{"description":"Heuristic LLM router configuration (`[router]`).","$ref":"#/$defs/RouterConfig","default":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]}},"runtime":{"description":"Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.","$ref":"#/$defs/RuntimeConfig","default":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null}},"scheduler":{"description":"Scheduler configuration for periodic task execution (`[scheduler]`).","$ref":"#/$defs/SchedulerConfig","default":{"claim_lease_secs":90,"max_tasks":64}},"secrets":{"$ref":"#/$defs/SecretsConfig","default":{"encrypt":true}},"security":{"description":"Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).","$ref":"#/$defs/SecurityConfig","default":{"audit":{"log_path":"audit.log","max_size_mb":100}}},"self_system":{"description":"Self-system experimental automation controls (`[self_system]`).","$ref":"#/$defs/SelfSystemConfig","default":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24}},"sessions_spawn":{"description":"Session spawning configuration (`[sessions_spawn]`).","$ref":"#/$defs/SessionsSpawnConfig","default":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null}},"skill_rag":{"description":"Dynamic skill retrieval settings (`[skill_rag]`).","$ref":"#/$defs/SkillRagConfig","default":{"top_k":32}},"skills":{"description":"Skills loading and community repository behavior (`[skills]`).","$ref":"#/$defs/SkillsConfig","default":{"open_skills_dir":null,"openclaw_skills_dir":null}},"skills_lifecycle":{"description":"Skill lifecycle (`[skills_lifecycle]`), off by default.","$ref":"#/$defs/SkillsLifecycleConfig","default":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]}},"smart_group":{"description":"Smart group-reply pre-gate configuration (`[smart_group]`).","$ref":"#/$defs/SmartGroupConfig","default":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5}},"storage":{"description":"Persistent storage provider configuration (`[storage]`).","$ref":"#/$defs/StorageConfig","default":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"task_routing":{"description":"Task routing configuration — classifies work by intent before the main agent loop.","$ref":"#/$defs/TaskRoutingConfig","default":{"default_intent":"simple","rules":[]}},"tool_tiering":{"description":"Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).","$ref":"#/$defs/ToolTieringConfig","default":{"always_exclude":[],"always_include":[],"channel_exclude":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","git_operations","skills_manage","memory_reindex","document_sync","document_ingest"]}},"tunnel":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]`).","$ref":"#/$defs/TunnelConfig","default":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null}},"user_policies":{"description":"Static user policy records loaded at startup (`[[user_policies]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/UserPolicyConfig"}},"web_search":{"description":"Web search tool configuration (`[web_search]`).","$ref":"#/$defs/WebSearchConfig","default":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15}},"webhook":{"description":"Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).","$ref":"#/$defs/MemoryWebhookConfig","default":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null}},"xin":{"description":"Xin autonomous task engine configuration (`[xin]`).","$ref":"#/$defs/XinConfig","default":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}}},"$defs":{"A2aConfig":{"type":"object","properties":{"agent_id":{"description":"Stable PRX agent identifier advertised to peers.","type":"string","default":"prx-default"},"allowed_peer_issuers":{"description":"Accepted external peer issuers.","type":"array","default":[],"items":{"type":"string"}},"bind":{"description":"Advertised bind address.","type":"string","default":"127.0.0.1:16832"},"card_jwks_uri":{"description":"Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.","type":["string","null"],"default":null},"card_signing_key_path":{"description":"On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).","type":["string","null"],"default":null},"card_ttl_seconds":{"description":"Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.","type":"integer","format":"uint64","default":3600,"minimum":0},"discovery_advertised":{"description":"Whether to advertise into an external A2A registry.","type":"boolean","default":false},"handoff_nonce_ttl_seconds":{"description":"Replay window for future handoff delegation tokens.","type":"integer","format":"uint64","default":3600,"minimum":0},"messaging_enabled":{"description":"Enable the dedicated pinned mTLS messaging listener.","type":"boolean","default":false},"peers":{"type":"object","additionalProperties":{"$ref":"#/$defs/A2aPeer"},"default":{}},"spiffe_id":{"description":"Local SPIFFE-style identifier placeholder.","type":"string","default":"spiffe://prx-local/agent/prx-default"},"spiffe_strict_validation":{"description":"When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.","type":"boolean","default":false},"spiffe_trust_bundle_pem":{"description":"Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).","type":["string","null"],"default":null},"trusted_trust_domains":{"description":"Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).","type":"array","default":[],"items":{"type":"string"}},"trust_domain":{"description":"SPIFFE trust domain for new instance identities.","type":"string","default":"prx.local"}}},"A2aPeer":{"description":"Explicit pinned identity and local recipient grant.","type":"object","properties":{"spiffe_id":{"type":"string"},"fingerprints":{"type":"array","items":{"type":"string"}},"address":{"type":"string"},"owner":{"type":"string"},"sessions":{"type":"array","default":["*"],"items":{"type":"string"}},"agents":{"type":"array","default":["*"],"items":{"type":"string"}}},"required":["spiffe_id","fingerprints","address","owner"],"additionalProperties":false},"AgentCompactionConfig":{"description":"Agent context compaction configuration (`[agent.compaction]`).","type":"object","properties":{"keep_recent_messages":{"description":"Number of recent non-system messages to keep after compaction.","type":"integer","format":"uint","default":12,"minimum":0},"max_context_tokens":{"description":"Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.","type":"integer","format":"uint","default":128000,"minimum":0},"memory_flush":{"description":"Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.","type":"boolean","default":true},"mode":{"description":"Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).","$ref":"#/$defs/AgentCompactionMode","default":"switch"},"os_paging":{"description":"Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.","$ref":"#/$defs/OsPagingConfig","default":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"}},"reserve_tokens":{"description":"Tokens reserved for the next model response.","type":"integer","format":"uint","default":4096,"minimum":0}}},"AgentCompactionMode":{"description":"Compaction mode for long conversation contexts.","oneOf":[{"description":"Disable proactive compaction.","type":"string","const":"off"},{"description":"Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.","type":"string","const":"switch"},{"description":"Conservative compaction that prefers summary replacement.","type":"string","const":"safeguard"},{"description":"Aggressive truncation mode for tighter contexts.","type":"string","const":"aggressive"}]},"AgentConfig":{"description":"Agent orchestration configuration (`[agent]` section).","type":"object","properties":{"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"compact_context":{"description":"When true: bootstrap_max_chars=6000. Use for 13B or smaller models.","type":"boolean","default":false},"compaction":{"description":"Context compaction controls (`[agent.compaction]`).","$ref":"#/$defs/AgentCompactionConfig","default":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096}},"low_priority_tools":{"description":"Tool names treated as low-priority when `priority_scheduling_enabled = true`.","type":"array","default":["sessions_spawn","delegate"],"items":{"type":"string"}},"priority_scheduling_enabled":{"description":"Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.","type":"boolean","default":false},"read_only_tool_concurrency_window":{"description":"Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.","type":"integer","format":"uint","default":2,"minimum":0},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}}},"AgentLimits":{"description":"Optional admission limits for rf-started turns of a named agent.","type":"object","properties":{"max_concurrent_turns":{"type":["integer","null"],"format":"uint32","minimum":0},"max_cost_per_day_cents":{"type":["integer","null"],"format":"uint64","minimum":0}},"additionalProperties":false},"AuditConfig":{"description":"Audit logging configuration","type":"object","properties":{"log_path":{"description":"Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).","type":"string","default":"audit.log"},"max_size_mb":{"description":"Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).","type":"integer","format":"uint32","default":100,"minimum":0}}},"AuthConfig":{"description":"Authentication and external credential import configuration (`[auth]` section).","type":"object","properties":{"codex_auth_json_auto_import":{"description":"Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.","type":"boolean","default":false},"codex_auth_json_path":{"description":"Source path for Codex CLI auth.json import.","type":"string","default":"~/.codex/auth.json"}}},"AutonomyConfig":{"type":"object","properties":{"acknowledge_unrestricted_profile":{"description":"Operator acknowledgement for an intentionally unrestricted profile.\nThis suppresses doctor noise only; it does not alter policy behavior.","type":"boolean","default":false},"forbidden_paths":{"description":"Explicit path denylist. Default includes system-critical paths.\n\nFails closed: omitting the key keeps the built-in list rather than\nemptying it, so a partial `[autonomy]` section never removes the\ndenylist.","type":"array","default":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"items":{"type":"string"}},"level":{"description":"Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).","$ref":"#/$defs/AutonomyLevel","default":"full"},"max_cost_per_day_cents":{"description":"Maximum cost per day in cents per policy. Default: `500`.","type":"integer","format":"uint32","default":500,"minimum":0},"scopes":{"description":"Scope-based tool access control: per-user/channel/chat-type allow/deny rules.","$ref":"#/$defs/ScopeConfig","default":{"assign_owners":[],"default":"allow","rules":[]}},"workspace_only":{"description":"Restrict file writes and command paths to the workspace directory. Default: `true`.\n\nFails closed: a `[autonomy]` section that omits this key keeps the\nworkspace restriction on, so a partial section can never widen the\nfilesystem reach by accident.","type":"boolean","default":true}}},"AutonomyLevel":{"description":"How much autonomy the agent has","oneOf":[{"description":"Read-only: can observe but not act","type":"string","const":"readonly"},{"description":"Supervised: acts but requires approval for risky operations","type":"string","const":"supervised"},{"description":"Full: autonomous execution within policy bounds","type":"string","const":"full"}]},"BackendSelection":{"description":"Which decision backend runs: `auto` (the factory's order) or one kind.","type":"string"},"BrowserComputerUseConfig":{"description":"Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.","type":"object","properties":{"api_key":{"description":"Optional bearer token (retained only for config secret handling).","type":["string","null"],"default":null}}},"BrowserConfig":{"description":"Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.","type":"object","properties":{"allowed_domains":{"description":"Allowed domains for `web_fetch` (exact or subdomain match).","type":"array","default":[],"items":{"type":"string"}},"computer_use":{"description":"Computer-use sidecar config (retained only for `api_key` secret handling).","$ref":"#/$defs/BrowserComputerUseConfig","default":{"api_key":null}}}},"ChannelsConfig":{"description":"Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.","type":"object","properties":{"cli":{"description":"Enable the CLI interactive channel. Default: `true`.","type":"boolean","default":true},"dingtalk":{"description":"DingTalk channel configuration.","anyOf":[{"$ref":"#/$defs/DingTalkConfig"},{"type":"null"}]},"discord":{"description":"Discord bot channel configuration.","anyOf":[{"$ref":"#/$defs/DiscordConfig"},{"type":"null"}]},"email":{"description":"Email channel configuration.","anyOf":[{"$ref":"#/$defs/EmailConfig"},{"type":"null"}]},"imessage":{"description":"iMessage channel configuration (macOS only).","anyOf":[{"$ref":"#/$defs/IMessageConfig"},{"type":"null"}]},"irc":{"description":"IRC channel configuration.","anyOf":[{"$ref":"#/$defs/IrcConfig"},{"type":"null"}]},"lark":{"description":"Lark/Feishu channel configuration.","anyOf":[{"$ref":"#/$defs/LarkConfig"},{"type":"null"}]},"linq":{"description":"Linq Partner API channel configuration.","anyOf":[{"$ref":"#/$defs/LinqConfig"},{"type":"null"}]},"mattermost":{"description":"Mattermost bot channel configuration.","anyOf":[{"$ref":"#/$defs/MattermostConfig"},{"type":"null"}]},"nextcloud_talk":{"description":"Nextcloud Talk bot channel configuration.","anyOf":[{"$ref":"#/$defs/NextcloudTalkConfig"},{"type":"null"}]},"qq":{"description":"QQ Official Bot channel configuration.","anyOf":[{"$ref":"#/$defs/QQConfig"},{"type":"null"}]},"ramflux":{"description":"Local ramflux agent-host bridge.","anyOf":[{"$ref":"#/$defs/RamfluxConfig"},{"type":"null"}],"default":null},"signal":{"description":"Signal channel configuration.","anyOf":[{"$ref":"#/$defs/SignalConfig"},{"type":"null"}]},"slack":{"description":"Slack bot channel configuration.","anyOf":[{"$ref":"#/$defs/SlackConfig"},{"type":"null"}]},"telegram":{"description":"Telegram bot channel configuration.","anyOf":[{"$ref":"#/$defs/TelegramConfig"},{"type":"null"}]},"wacli":{"description":"wacli JSON-RPC daemon channel configuration.","anyOf":[{"$ref":"#/$defs/WacliConfig"},{"type":"null"}],"default":null},"webhook":{"description":"Webhook channel configuration.","anyOf":[{"$ref":"#/$defs/WebhookConfig"},{"type":"null"}]},"whatsapp":{"description":"WhatsApp channel configuration (Cloud API or Web mode).","anyOf":[{"$ref":"#/$defs/WhatsAppConfig"},{"type":"null"}]}}},"ChatConfig":{"description":"Interactive chat configuration (`[chat]`).","type":"object","properties":{"daemon":{"description":"How this chat process reaches the daemon it borrows channels from.","$ref":"#/$defs/ChatDaemonConfig","default":{"token":"","url":""}},"max_concurrent_visible_turns":{"description":"Maximum concurrent visible provider turns in the TUI Redux driver.","type":"integer","format":"uint","default":2,"minimum":0}}},"ChatDaemonConfig":{"description":"Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.","type":"object","properties":{"token":{"description":"Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.","type":"string","default":""},"url":{"description":"Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.","type":"string","default":""}}},"CircuitBreakerConfig":{"description":"The per-backend circuit breaker.","type":"object","properties":{"cooldown_secs":{"description":"Seconds the breaker stays open (1 to 3600).","type":"integer","format":"uint32","default":60,"minimum":0},"failure_threshold":{"description":"Consecutive failures before the breaker opens (1 to 100).","type":"integer","format":"uint32","default":5,"minimum":0}}},"ClassificationRule":{"description":"A single classification rule mapping message patterns to a model hint.","type":"object","properties":{"hint":{"description":"Must match a `[[model_routes]]` hint value.","type":"string"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"max_length":{"description":"Only match if message length <= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"min_length":{"description":"Only match if message length >= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"patterns":{"description":"Case-sensitive literal matches (for \"```\", \"fn \", etc.).","type":"array","default":[],"items":{"type":"string"}},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0}},"required":["hint"]},"CloudflareTunnelConfig":{"type":"object","properties":{"token":{"description":"Cloudflare Tunnel token (from Zero Trust dashboard)","type":"string"}},"required":["token"]},"ComplianceConfig":{"type":"object","properties":{"eu_ai_act":{"$ref":"#/$defs/EuAiActComplianceConfig","default":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null}},"interaction_notice":{"$ref":"#/$defs/InteractionNoticeConfig","default":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}}},"ComposioConfig":{"description":"Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.","type":"object","properties":{"api_key":{"description":"Composio API key (stored encrypted when secrets.encrypt = true)","type":["string","null"],"default":null},"entity_id":{"description":"Default entity ID for multi-user setups","type":"string","default":"default"}}},"CostConfig":{"description":"Cost tracking and budget enforcement configuration (`[cost]` section).","type":"object","properties":{"allow_override":{"description":"Allow requests to exceed budget with --override flag (default: false)","type":"boolean","default":false},"daily_limit_usd":{"description":"Daily spending limit in USD (default: 10.00)","type":"number","format":"double","default":10.0},"monthly_limit_usd":{"description":"Monthly spending limit in USD (default: 100.00)","type":"number","format":"double","default":100.0},"prices":{"description":"Per-model pricing (USD per 1M tokens)","type":"object","additionalProperties":{"$ref":"#/$defs/ModelPricing"},"default":{}},"warn_at_percent":{"description":"Warn when spending reaches this percentage of limit (default: 80)","type":"integer","format":"uint8","default":80,"maximum":255,"minimum":0}}},"CredentialRefSetting":{"description":"Which credential a decision backend uses. A reference, never a secret.","type":"string"},"CronConfig":{"description":"Cron job configuration (`[cron]` section).","type":"object","properties":{"max_run_history":{"description":"Maximum number of historical cron run records to retain. Default: `50`.","type":"integer","format":"uint32","default":50,"minimum":0}}},"CustomTunnelConfig":{"type":"object","properties":{"health_url":{"description":"Optional URL to check tunnel health","type":["string","null"]},"start_command":{"description":"Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"","type":"string"},"url_pattern":{"description":"Optional regex to extract public URL from command stdout","type":["string","null"]}},"required":["start_command"]},"DecisionBackendConfig":{"description":"The decision backend (`[decision_engine.backend]`).","type":"object","properties":{"circuit_breaker":{"description":"The circuit breaker.","$ref":"#/$defs/CircuitBreakerConfig","default":{"cooldown_secs":60,"failure_threshold":5}},"credential_ref":{"description":"The credential reference: `\"\"`, `\"none\"` or `cred-`.","$ref":"#/$defs/CredentialRefSetting","default":""},"endpoint":{"description":"The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.","type":"string","default":""},"kind":{"description":"`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).","$ref":"#/$defs/BackendSelection","default":"auto"},"max_request_bytes":{"description":"Largest request body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":65536,"minimum":0},"max_response_bytes":{"description":"Largest response body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":262144,"minimum":0},"model":{"description":"The model the endpoint serves; one exact version for a hosted\nservice.","type":"string","default":""},"pinned_snapshot":{"description":"The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.","type":"string"},"remote_enabled":{"description":"Whether decision state may leave this machine. Default `false`.","type":"boolean","default":false},"timeout_ms":{"description":"Transport timeout (10 ms up to the extra latency budget).","type":"integer","format":"uint32","default":250,"minimum":0}}},"DecisionEngineConfig":{"type":"object","properties":{"backend":{"anyOf":[{"$ref":"#/$defs/DecisionBackendConfig"},{"type":"null"}]},"candidates":{"type":"integer","format":"uint32","default":5,"minimum":0},"enabled":{"type":"boolean","default":false},"mode":{"$ref":"#/$defs/DecisionMode","default":"pre"},"observe_queue":{"type":"integer","format":"uint32","default":64,"minimum":0},"prompt_budget_tokens":{"type":"integer","format":"uint32","default":300,"minimum":0},"telemetry_cap":{"type":"integer","format":"uint32","default":1000,"minimum":0},"timeout_ms":{"type":"integer","format":"uint32","default":1500,"minimum":0},"latency_budget_ms":{"description":"The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.","type":"integer","format":"uint64","default":500,"minimum":0},"token_ratio_limit":{"description":"Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).","type":"number","format":"float","default":0.3499999940395355},"max_candidates":{"description":"The most candidates a turn considers (1 to 32).","type":"integer","format":"uint8","default":12,"maximum":255,"minimum":0}}},"DecisionMode":{"type":"string","enum":["pre","post","both"]},"DeclarationOfConformityConfig":{"type":"object","properties":{"applicable_union_law":{"type":"array","default":[],"items":{"type":"string"}},"artifact_path":{"type":["string","null"],"default":null},"artifact_version":{"type":["string","null"],"default":null},"conformity_assessment_procedure":{"type":["string","null"],"default":null},"conformity_statement":{"type":["string","null"],"default":null},"harmonised_standards":{"type":"array","default":[],"items":{"type":"string"}},"issue_date":{"type":["string","null"],"default":null},"issue_place":{"type":["string","null"],"default":null},"notified_body_certificate":{"type":["string","null"],"default":null},"notified_body_identification_number":{"type":["string","null"],"default":null},"notified_body_name":{"type":["string","null"],"default":null},"personal_data_compliance_statement":{"type":["string","null"],"default":null},"processes_personal_data":{"type":"boolean","default":false},"provider_address":{"type":["string","null"],"default":null},"provider_name":{"type":["string","null"],"default":null},"signer_function":{"type":["string","null"],"default":null},"signer_name":{"type":["string","null"],"default":null},"signer_on_behalf_of":{"type":["string","null"],"default":null},"sole_responsibility_statement":{"type":["string","null"],"default":null},"standards_not_applicable_reason":{"type":["string","null"],"default":null},"system_name":{"type":["string","null"],"default":null},"system_reference":{"type":["string","null"],"default":null},"system_type":{"type":["string","null"],"default":null}}},"DelegateAgentConfig":{"description":"Configuration for a delegate sub-agent used by the `delegate` tool.","type":"object","properties":{"agentic":{"description":"Enable agentic sub-agent mode (multi-turn tool-call loop).","type":"boolean","default":false},"allowed_tools":{"description":"Allowlist of tool names available to the sub-agent in agentic mode.","type":"array","default":[],"items":{"type":"string"}},"api_key":{"description":"Optional API key override","type":["string","null"],"default":null},"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"autonomy":{"description":"The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.","anyOf":[{"$ref":"#/$defs/AutonomyLevel"},{"type":"null"}]},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"enabled":{"description":"Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.","type":"boolean","default":true},"identity_dir":{"description":"Optional identity files directory relative to workspace root.","type":["string","null"],"default":null},"limits":{"$ref":"#/$defs/AgentLimits","default":{"max_concurrent_turns":null,"max_cost_per_day_cents":null}},"max_depth":{"description":"Max recursion depth for nested delegation","type":"integer","format":"uint32","default":8,"minimum":0},"memory_scope":{"description":"Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".","type":["string","null"],"default":null},"model":{"description":"Model name","type":"string"},"provider":{"description":"Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")","type":"string"},"spawn_enabled":{"description":"Whether this agent is allowed to be targeted by sessions_spawn (default: true).","type":["boolean","null"],"default":null},"system_prompt":{"description":"Optional system prompt for the sub-agent","type":["string","null"],"default":null},"temperature":{"description":"Temperature override","type":["number","null"],"format":"double","default":null},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}},"required":["provider","model"]},"DingTalkConfig":{"description":"DingTalk configuration for Stream Mode messaging","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"client_id":{"description":"Client ID (AppKey) from DingTalk developer console","type":"string"},"client_secret":{"description":"Client Secret (AppSecret) from DingTalk developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["client_id","client_secret"]},"DiscordConfig":{"description":"Discord bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Discord user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Discord bot token (from Discord Developer Portal).","type":"string"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"guild_id":{"description":"Optional guild (server) ID to restrict the bot to a single guild.","type":["string","null"]},"listen_to_bots":{"description":"When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.","type":"boolean","default":false}},"required":["bot_token"]},"DmPolicy":{"description":"Policy for direct-message handling.","oneOf":[{"description":"Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).","type":"string","const":"pairing"},{"description":"Accept only senders listed in `allowed_from`.","type":"string","const":"allowlist"},{"description":"Accept any direct sender.","type":"string","const":"open"},{"description":"Ignore direct messages.","type":"string","const":"disabled"}]},"DockerRuntimeConfig":{"description":"Docker runtime configuration (`[runtime.docker]` section).","type":"object","properties":{"allowed_workspace_roots":{"description":"Optional workspace root allowlist for Docker mount validation.","type":"array","default":[],"items":{"type":"string"}},"cpu_limit":{"description":"Optional CPU limit (`None` = no explicit limit).","type":["number","null"],"format":"double","default":1.0},"image":{"description":"Runtime image used to execute shell commands.","type":"string","default":"alpine:3.20"},"memory_limit_mb":{"description":"Optional memory limit in MB (`None` = no explicit limit).","type":["integer","null"],"format":"uint64","default":512,"minimum":0},"mount_workspace":{"description":"Mount configured workspace into `/workspace`.","type":"boolean","default":true},"network":{"description":"Docker network mode (`none`, `bridge`, etc.).","type":"string","default":"none"},"read_only_rootfs":{"description":"Mount root filesystem as read-only.","type":"boolean","default":true}}},"EmailConfig":{"description":"Email channel configuration","type":"object","properties":{"allowed_senders":{"description":"Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)","type":"array","default":[],"items":{"type":"string"}},"from_address":{"description":"From address for outgoing emails","type":"string"},"idle_timeout_secs":{"description":"IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes","type":"integer","format":"uint64","default":1740,"minimum":0},"imap_folder":{"description":"IMAP folder to poll (default: INBOX)","type":"string","default":"INBOX"},"imap_host":{"description":"IMAP server hostname","type":"string"},"imap_port":{"description":"IMAP server port (default: 993 for TLS)","type":"integer","format":"uint16","default":993,"maximum":65535,"minimum":0},"password":{"description":"Email password for authentication","type":"string"},"smtp_host":{"description":"SMTP server hostname","type":"string"},"smtp_port":{"description":"SMTP server port (default: 465 for TLS)","type":"integer","format":"uint16","default":465,"maximum":65535,"minimum":0},"smtp_tls":{"description":"Use TLS for SMTP (default: true)","type":"boolean","default":true},"username":{"description":"Email username for authentication","type":"string"}},"required":["imap_host","smtp_host","username","password","from_address"]},"EmbeddingRouteConfig":{"description":"Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"dimensions":{"description":"Optional embedding dimension override for this route","type":["integer","null"],"format":"uint","default":null,"minimum":0},"hint":{"description":"Route hint name (e.g. \"semantic\", \"archive\", \"faq\")","type":"string"},"model":{"description":"Embedding model to use with that provider","type":"string"},"provider":{"description":"Embedding provider (`none`, `openai`, or `custom:`)","type":"string"}},"required":["hint","provider","model"]},"EuAiActClassificationConfig":{"type":"object","properties":{"assessed_at":{"type":["string","null"],"default":null},"owner":{"type":["string","null"],"default":null},"status":{"$ref":"#/$defs/EuAiActRiskClassification","default":"unclassified"}}},"EuAiActComplianceConfig":{"type":"object","properties":{"classification":{"$ref":"#/$defs/EuAiActClassificationConfig","default":{"assessed_at":null,"owner":null,"status":"unclassified"}},"declaration":{"$ref":"#/$defs/DeclarationOfConformityConfig","default":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null}},"incident_store_path":{"type":["string","null"],"default":null}}},"EuAiActRiskClassification":{"type":"string","enum":["unclassified","high_risk","not_high_risk"]},"FitnessConfig":{"description":"Calendar schedule, evidence thresholds, and retention for fitness v2.","type":"object","properties":{"auto_run":{"description":"Run the daily fitness worker in daemon mode.","type":"boolean","default":true},"max_backfill_days":{"description":"Maximum number of closed days recovered after downtime.","type":"integer","format":"uint32","default":7,"minimum":0},"min_coverage":{"description":"Minimum available metric weight required to publish a final score.","type":"number","format":"double","default":0.6},"min_samples":{"description":"Minimum samples required before an evidence-derived subscore is usable.","type":"integer","format":"uint","default":5,"minimum":0},"retention_days":{"description":"Number of daily JSON reports retained on disk.","type":"integer","format":"uint32","default":180,"minimum":0},"run_at":{"description":"Local wall-clock time (`HH:MM`) at which the previous day is scored.","type":"string","default":"00:10"},"timezone":{"description":"IANA timezone used to define closed calendar days.","type":"string","default":"UTC"}}},"GatewayConfig":{"description":"Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.","type":"object","properties":{"allow_public_bind":{"description":"Allow binding to non-localhost without a tunnel (default: false)","type":"boolean","default":false},"api_rate_limit_per_minute":{"description":"Max `/api/*` requests per minute per authenticated token.","type":"integer","format":"uint32","default":60,"minimum":0},"channel_webhook_dedup_ttl_secs":{"description":"How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.","type":"integer","format":"uint64","default":86400,"minimum":0},"host":{"description":"Gateway host (default: 127.0.0.1)","type":"string","default":"127.0.0.1"},"idempotency_max_keys":{"description":"Maximum distinct idempotency keys retained in memory.","type":"integer","format":"uint","default":10000,"minimum":0},"idempotency_ttl_secs":{"description":"TTL for webhook idempotency keys.","type":"integer","format":"uint64","default":300,"minimum":0},"pair_rate_limit_per_minute":{"description":"Max `/pair` requests per minute per client key.","type":"integer","format":"uint32","default":10,"minimum":0},"paired_tokens":{"description":"Paired bearer tokens (managed automatically, not user-edited)","type":"array","default":[],"items":{"type":"string"}},"port":{"description":"Gateway port (default: 16830)","type":"integer","format":"uint16","default":16830,"maximum":65535,"minimum":0},"rate_limit_max_keys":{"description":"Maximum distinct client keys tracked by gateway rate limiter maps.","type":"integer","format":"uint","default":10000,"minimum":0},"require_pairing":{"description":"Require pairing before accepting requests (default: true)","type":"boolean","default":true},"targeted_agents":{"description":"Rollout switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). While false, any otherwise-valid\nnamed target answers 409 `agent_disabled` and never runs as Main.","type":"boolean","default":false},"trust_forwarded_headers":{"description":"Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.","type":"boolean","default":false},"webhook_rate_limit_per_minute":{"description":"Max `/webhook` requests per minute per client key.","type":"integer","format":"uint32","default":60,"minimum":0}}},"GroupPolicy":{"description":"Policy for group-message handling.","oneOf":[{"description":"Accept only groups listed in `group_allow_from`.","type":"string","const":"allowlist"},{"description":"Accept any group.","type":"string","const":"open"},{"description":"Ignore group messages.","type":"string","const":"disabled"}]},"GroupReplyMode":{"description":"How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.","oneOf":[{"description":"Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).","type":"string","const":"off"},{"description":"Reply only when the bot is @-mentioned (legacy `mention_only = true`).","type":"string","const":"mention-only"},{"description":"Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).","type":"string","const":"smart"}]},"HeartbeatConfig":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]` section).","type":"object","properties":{"active_hours":{"description":"Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.","type":"array","default":[8,23],"items":{"type":"integer","format":"uint8","maximum":255,"minimum":0}},"interval_minutes":{"description":"Interval in minutes between heartbeat pings. Default: `30`.","type":"integer","format":"uint32","default":30,"minimum":0},"prompt":{"description":"Prompt used by heartbeat worker when dispatching tasks.","type":"string","default":"Check HEARTBEAT.md and follow instructions."}}},"HttpRequestConfig":{"description":"HTTP request tool configuration (`[http_request]` section).","type":"object","properties":{"max_response_size":{"description":"Maximum response size in bytes (default: 1MB)","type":"integer","format":"uint","default":1000000,"minimum":0},"timeout_secs":{"description":"Request timeout in seconds (default: 30)","type":"integer","format":"uint64","default":30,"minimum":0}}},"IMessageConfig":{"description":"iMessage channel configuration (macOS only).","type":"object","properties":{"allowed_contacts":{"description":"Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.","type":"array","items":{"type":"string"}},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["allowed_contacts"]},"IdentityBindingConfig":{"description":"Startup identity binding entry (`[[identity_bindings]]`).","type":"object","properties":{"channel":{"type":"string"},"channel_account":{"type":"string"},"display_name":{"type":["string","null"],"default":null},"user_id":{"type":"string"}},"required":["user_id","channel","channel_account"]},"IdentityConfig":{"description":"Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.","type":"object","properties":{"aieos_inline":{"description":"Inline AIEOS JSON (alternative to file path)","type":["string","null"],"default":null},"aieos_path":{"description":"Path to AIEOS JSON file (relative to workspace)","type":["string","null"],"default":null},"format":{"description":"Identity format: \"openclaw\" (default) or \"aieos\"","type":"string","default":"openclaw"}}},"InteractionNoticeApplicability":{"type":"string","enum":["required","not_applicable"]},"InteractionNoticeConfig":{"type":"object","properties":{"applicability":{"$ref":"#/$defs/InteractionNoticeApplicability","default":"required"},"exception_owner":{"type":["string","null"],"default":null},"exception_reviewed_at":{"type":["string","null"],"default":null},"text":{"type":"string","default":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers."},"version":{"type":"string","default":"1"}}},"IrcConfig":{"description":"IRC channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed nicknames (case-insensitive) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"channels":{"description":"Channels to join on connect","type":"array","default":[],"items":{"type":"string"}},"mention_only":{"description":"When true, only process channel/group messages that mention the bot.","type":"boolean","default":false},"nickname":{"description":"Bot nickname","type":"string"},"nickserv_password":{"description":"NickServ IDENTIFY password","type":["string","null"]},"port":{"description":"IRC server port (default: 6697 for TLS)","type":"integer","format":"uint16","default":6697,"maximum":65535,"minimum":0},"sasl_password":{"description":"SASL PLAIN password (IRCv3)","type":["string","null"]},"server":{"description":"IRC server hostname","type":"string"},"server_password":{"description":"Server password (for bouncers like ZNC)","type":["string","null"]},"username":{"description":"Username (defaults to nickname if not set)","type":["string","null"]},"verify_tls":{"description":"Verify TLS certificate (default: true)","type":["boolean","null"]}},"required":["server","nickname"]},"LarkConfig":{"description":"Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from Lark/Feishu developer console","type":"string"},"app_secret":{"description":"App Secret from Lark/Feishu developer console","type":"string"},"encrypt_key":{"description":"Encrypt key for webhook message decryption (optional)","type":["string","null"],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"port":{"description":"HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"receive_mode":{"description":"Event receive mode: \"websocket\" (default) or \"webhook\"","$ref":"#/$defs/LarkReceiveMode","default":"websocket"},"use_feishu":{"description":"Whether to use the Feishu (Chinese) endpoint instead of Lark (International)","type":"boolean","default":false},"verification_token":{"description":"Verification token for webhook validation (optional)","type":["string","null"],"default":null}},"required":["app_id","app_secret"]},"LarkReceiveMode":{"description":"How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.","type":"string","enum":["websocket","webhook"]},"LinqConfig":{"type":"object","properties":{"allowed_senders":{"description":"Allowed sender handles (phone numbers) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"api_token":{"description":"Linq Partner API token (Bearer auth)","type":"string"},"from_phone":{"description":"Phone number to send from (E.164 format)","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"signing_secret":{"description":"Webhook signing secret for signature verification","type":["string","null"],"default":null}},"required":["api_token","from_phone"]},"MattermostConfig":{"description":"Mattermost bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Mattermost user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Mattermost bot access token.","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.","type":["boolean","null"],"default":null},"thread_replies":{"description":"When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.","type":["boolean","null"],"default":null},"url":{"description":"Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).","type":"string"}},"required":["url","bot_token"]},"McpConfig":{"type":"object","properties":{"servers":{"description":"Named MCP server definitions","type":"object","additionalProperties":{"$ref":"#/$defs/McpServerConfig"},"default":{}},"workspace_servers":{"description":"Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.","$ref":"#/$defs/WorkspaceMcpServers"}}},"McpServerConfig":{"type":"object","properties":{"allow_tools":{"description":"Optional allow-list of exposed tools (empty = all)","type":"array","default":[],"items":{"type":"string"}},"args":{"description":"Command args for stdio mode","type":"array","default":[],"items":{"type":"string"}},"command":{"description":"Command for stdio mode","type":["string","null"],"default":null},"deny_tools":{"description":"Optional deny-list of exposed tools","type":"array","default":[],"items":{"type":"string"}},"env":{"description":"Environment variables for stdio mode","type":"object","additionalProperties":{"type":"string"},"default":{}},"request_timeout_ms":{"description":"Request timeout in milliseconds","type":"integer","format":"uint64","default":30000,"minimum":0},"startup_timeout_ms":{"description":"Startup timeout in milliseconds","type":"integer","format":"uint64","default":10000,"minimum":0},"tool_name_prefix":{"description":"Prefix used in tool naming and routing","type":"string","default":"mcp"},"transport":{"description":"Transport type: stdio or http","$ref":"#/$defs/McpTransport","default":"stdio"},"url":{"description":"URL for HTTP mode (streamable HTTP endpoint)","type":["string","null"],"default":null},"working_dir":{"description":"Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).","type":["string","null"]}}},"McpServerRuntimeConfig":{"type":"object","properties":{"allowed_origins":{"description":"Allowed browser origins for future streamable HTTP clients.","type":"array","default":["claude.ai","openai.com","localhost"],"items":{"type":"string"}},"bind":{"description":"Advertised bind address. The gateway may still be started with a CLI port override.","type":"string","default":"127.0.0.1:16831"},"exposed_tools":{"description":"Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.","type":"array","default":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"items":{"type":"string"}},"jwt_algorithms":{"description":"Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.","type":"array","default":["RS256"],"items":{"type":"string"}},"jwt_audience":{"description":"Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.","type":["string","null"],"default":null},"jwt_issuer":{"description":"Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.","type":["string","null"],"default":null},"jwt_jwks":{"description":"Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.","type":["string","null"],"default":null},"jwt_jwks_cache_ttl_secs":{"description":"Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.","type":"integer","format":"uint64","default":300,"minimum":0},"jwt_jwks_uri":{"description":"Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.","type":["string","null"],"default":null},"jwt_public_key_pem":{"description":"PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.","type":["string","null"],"default":null},"rate_limit_rps":{"description":"Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.","type":"integer","format":"uint32","default":10,"minimum":0},"require_auth":{"description":"Require an authenticated external identity for mutating calls.","type":"boolean","default":true}}},"McpTransport":{"type":"string","enum":["stdio","http"]},"MediaConfig":{"description":"Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.","type":"object","properties":{"audio_model":{"description":"Audio model name (Ollama model or OpenAI model). Default: \"whisper\".","type":"string","default":"whisper"},"audio_ollama_url":{"description":"Ollama base URL for audio transcription. Default: \"http://localhost:11434\".","type":"string","default":"http://localhost:11434"},"audio_provider":{"description":"Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".","type":"string","default":"none"},"max_audio_size_mb":{"description":"Maximum audio attachment size in MiB. Default: 20.","type":"integer","format":"uint","default":20,"minimum":0},"max_video_size_mb":{"description":"Maximum video attachment size in MiB. Default: 50.","type":"integer","format":"uint","default":50,"minimum":0},"video_max_frames":{"description":"Maximum video frames to extract per video. Default: 4.","type":"integer","format":"uint","default":4,"minimum":0},"video_provider":{"description":"Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".","type":"string","default":"none"}}},"MemoryConfig":{"description":"Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.","type":"object","properties":{"acl_enabled":{"description":"Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.","type":"boolean","default":false},"archive_after_days":{"description":"Archive daily/session files older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"auto_hydrate":{"description":"Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing","type":"boolean","default":true},"auto_save":{"description":"Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.","type":"boolean","default":true},"backend":{"description":"\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).","type":"string","default":"sqlite"},"conversation_retention_days":{"description":"For sqlite backend: prune conversation rows older than this many days","type":"integer","format":"uint32","default":3,"minimum":0},"daily_retention_days":{"description":"For sqlite backend: prune daily rows older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"embedding_cache_size":{"description":"Max embedding cache entries before LRU eviction","type":"integer","format":"uint","default":10000,"minimum":0},"embedding_dimensions":{"description":"Embedding vector dimensions","type":"integer","format":"uint","default":384,"minimum":0},"embedding_model":{"description":"Embedding model name (e.g. \"text-embedding-3-small\")","type":"string","default":"prx-local-hash-v1"},"embedding_provider":{"description":"Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"","type":"string","default":"local"},"events":{"description":"Raw/quasi-raw message event recording controls (`[memory.events]`).","$ref":"#/$defs/MemoryEventsConfig","default":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true}},"keyword_weight":{"description":"Weight for keyword BM25 in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.3},"legacy_conversation_turns_visible":{"description":"Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.","type":"boolean","default":true},"lucid_budget":{"description":"Token budget for lucid (replaces ZEROCLAW_LUCID_BUDGET / OPENPRX_LUCID_BUDGET)","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"lucid_cmd":{"description":"Path to lucid binary (replaces ZEROCLAW_LUCID_CMD / OPENPRX_LUCID_CMD)","type":["string","null"],"default":null},"lucid_failure_cooldown_ms":{"description":"Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)","type":"integer","format":"uint64","default":60000,"minimum":0},"lucid_local_hit_threshold":{"description":"Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)","type":"integer","format":"uint","default":3,"minimum":0},"lucid_recall_timeout_ms":{"description":"Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)","type":"integer","format":"uint64","default":5000,"minimum":0},"lucid_store_timeout_ms":{"description":"Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)","type":"integer","format":"uint64","default":3000,"minimum":0},"min_relevance_score":{"description":"Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4","type":"number","format":"double","default":0.4},"purge_after_days":{"description":"Purge archived files older than this many days","type":"integer","format":"uint32","default":30,"minimum":0},"semantic":{"description":"Semantic memory promotion controls (`[memory.semantic]`).","$ref":"#/$defs/MemorySemanticConfig","default":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30}},"sqlite_open_timeout_secs":{"description":"For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"sqlite_read_pool_size":{"description":"For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"vector_candidate_cap":{"description":"How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.","type":"integer","format":"uint","default":2000,"minimum":0},"vector_weight":{"description":"Weight for vector similarity in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.7}}},"MemoryEventsConfig":{"description":"Raw message event recording configuration (`[memory.events]`).","type":"object","properties":{"record_assistant_messages":{"description":"Record assistant replies.","type":"boolean","default":true},"record_tool_events":{"description":"Record tool/event payloads by default.","type":"boolean","default":false},"record_user_messages":{"description":"Record inbound/user messages.","type":"boolean","default":true}}},"MemorySemanticConfig":{"description":"Semantic memory promotion configuration (`[memory.semantic]`).","type":"object","properties":{"auto_promote_assistant_messages":{"description":"Auto-promote eligible assistant messages. Disabled by default to reduce noise.","type":"boolean","default":false},"auto_promote_user_messages":{"description":"Auto-promote eligible user messages into long-term semantic memories.","type":"boolean","default":true},"min_chars":{"description":"Minimum content length for semantic auto-promotion.","type":"integer","format":"uint","default":30,"minimum":0}}},"MemoryWebhookConfig":{"type":"object","properties":{"bind":{"description":"Socket address for the receiver (e.g. \"0.0.0.0:16899\").","type":"string","default":"0.0.0.0:16899"},"signing_secret":{"description":"Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.","type":["string","null"],"default":null},"token":{"description":"Required bearer token for incoming webhook events.","type":["string","null"],"default":null}}},"ModelOperationSetting":{"description":"The operations a `[[providers.models]]` entry may list.","type":"string","enum":["chat","embedding","decision_endpoint","rerank","image_generation","audio_generation","video_generation"]},"ModelPricing":{"description":"Per-model pricing entry (USD per 1M tokens).","type":"object","properties":{"cache_read":{"description":"Cache read input price per 1M tokens.","type":"number","format":"double","default":0.0},"cache_write":{"description":"Cache write/creation input price per 1M tokens.","type":"number","format":"double","default":0.0},"input":{"description":"Input price per 1M tokens","type":"number","format":"double","default":0.0},"output":{"description":"Output price per 1M tokens","type":"number","format":"double","default":0.0}}},"ModelRouteConfig":{"description":"Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"hint":{"description":"Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")","type":"string"},"level":{"type":["string","null"]},"model":{"description":"Model to use with that provider","type":"string"},"provider":{"description":"Provider to route to (must match a known provider name)","type":"string"},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true,"required":["hint","provider","model"]},"ModelSettings":{"description":"A model level plus explicit parameter overrides in `[model_settings.\"\"]`.","type":"object","properties":{"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"level":{"type":["string","null"]},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true},"MultimodalConfig":{"description":"Multimodal (image) handling configuration (`[multimodal]` section).","type":"object","properties":{"allow_remote_fetch":{"description":"Allow fetching remote image URLs (http/https). Disabled by default.","type":"boolean","default":false},"max_image_size_mb":{"description":"Maximum image payload size in MiB before base64 encoding.","type":"integer","format":"uint","default":5,"minimum":0},"max_images":{"description":"Maximum number of image attachments accepted per request.","type":"integer","format":"uint","default":4,"minimum":0}}},"NextcloudTalkConfig":{"description":"Nextcloud Talk bot configuration (webhook receive + OCS send API).","type":"object","properties":{"allowed_users":{"description":"Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Bot app token used for OCS API bearer auth.","type":"string"},"base_url":{"description":"Nextcloud base URL (e.g. \"https://cloud.example.com\").","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"webhook_secret":{"description":"Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).","type":["string","null"],"default":null}},"required":["base_url","app_token"]},"NgrokTunnelConfig":{"type":"object","properties":{"auth_token":{"description":"ngrok auth token","type":"string"},"domain":{"description":"Optional custom domain","type":["string","null"]}},"required":["auth_token"]},"NodeServerConfig":{"description":"Node daemon runtime config used by `prx-node`.","type":"object","properties":{"allowed_commands":{"description":"Command allowlist matched on first token.\n\nIn restricted mode this list is required unless explicitly set to `[\"*\"]`.","type":"array","default":["echo"],"items":{"type":"string"}},"bearer_token":{"description":"Required bearer token for /rpc.","type":"string","default":""},"blocked_commands":{"description":"Command denylist matched on first token. Always enforced.","type":"array","default":[],"items":{"type":"string"}},"exec_timeout_ms":{"description":"Default command timeout in milliseconds.","type":"integer","format":"uint64","default":15000,"minimum":0},"hmac_secret":{"description":"Optional HMAC signing secret.","type":["string","null"],"default":null},"listen_addr":{"description":"Listen address for node daemon.","type":"string","default":"127.0.0.1:8787"},"max_concurrent_tasks":{"description":"Maximum number of concurrent async command tasks.","type":"integer","format":"uint","default":8,"minimum":0},"max_output_bytes":{"description":"Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.","type":"integer","format":"uint","default":1048576,"minimum":0},"sandbox_root":{"description":"Sandbox root directory for read/write/cwd constraints.","type":"string","default":"."},"task_result_ttl_ms":{"description":"TTL for completed task results in milliseconds.","type":"integer","format":"uint64","default":3600000,"minimum":0},"tls_cert":{"description":"TLS certificate path (PEM).","type":["string","null"],"default":null},"tls_key":{"description":"TLS private key path (PEM).","type":["string","null"],"default":null},"tls_required":{"description":"Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.","type":"boolean","default":true}}},"NodesConfig":{"description":"Remote node proxy configuration for core-side RPC calls and node daemon defaults.","type":"object","properties":{"nodes":{"description":"Configured remote nodes.","type":"array","default":[],"items":{"$ref":"#/$defs/RemoteNodeConfig"}},"request_timeout_ms":{"description":"Default request timeout for node RPC calls.","type":"integer","format":"uint64","default":15000,"minimum":0},"retry_max":{"description":"Default max retries for node RPC calls.","type":"integer","format":"uint8","default":2,"maximum":255,"minimum":0},"server":{"description":"Embedded node server defaults used by `prx-node`.","$ref":"#/$defs/NodeServerConfig","default":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}}},"ObservabilityConfig":{"description":"Observability backend configuration (`[observability]` section).","type":"object","properties":{"backend":{"description":"\"none\" | \"log\" | \"prometheus\" | \"otel\"","type":"string","default":"none"},"otel_endpoint":{"description":"OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".","type":["string","null"],"default":null},"otel_service_name":{"description":"Service name reported to the OTel collector. Defaults to \"prx\".","type":["string","null"],"default":null}}},"OllamaProviderConfig":{"description":"Ollama-specific request options (`[providers.ollama]`).","type":"object","properties":{"num_ctx":{"description":"Explicit context window sent as Ollama `options.num_ctx`.","type":["integer","null"],"format":"uint","default":null,"minimum":0}}},"OsPagingConfig":{"description":"Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.","type":"object","properties":{"eviction_threshold":{"description":"Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.","type":"number","format":"double","default":0.7},"keep_recent_messages":{"description":"Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).","type":"integer","format":"uint","default":12,"minimum":0},"max_recalled_pages":{"description":"Maximum number of evicted pages (document chunks) recalled per turn.","type":"integer","format":"uint","default":10,"minimum":0},"proactive_retrieval":{"description":"Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.","type":"boolean","default":true},"retrieval_injection_role":{"description":"Role under which recalled pages are injected.","$ref":"#/$defs/RetrievalInjectionRole","default":"system"}}},"PluginsConfig":{"description":"WASM plugin runtime configuration.","type":"object","properties":{"enabled":{"description":"Load WASM plugins from `/plugins`. Default: `false`.","type":"boolean","default":false}},"additionalProperties":false},"ProviderModelConfig":{"description":"One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.","type":"object","properties":{"context_window":{"description":"The model's context window in tokens.","type":["integer","null"],"format":"uint32","minimum":0},"model":{"description":"The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.","type":["string","null"]},"native_tools":{"description":"Whether the model accepts native tool calls.","type":["boolean","null"]},"operations":{"description":"The complete list of operations the model executes; every operation not\nlisted is unsupported.","type":["array","null"],"items":{"$ref":"#/$defs/ModelOperationSetting"}},"provider":{"description":"The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.","type":"string"},"streaming":{"description":"Whether the model streams responses.","type":["boolean","null"]},"structured_output":{"description":"Whether the model honours a JSON-schema response format.","type":["boolean","null"]},"tool_call_dialect":{"description":"The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema_dialect":{"description":"The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]},"vision_input":{"description":"Whether the model accepts image input.","type":["boolean","null"]}},"required":["provider"]},"ProviderToolDialectConfig":{"description":"One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.","type":"object","properties":{"model":{"description":"The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.","type":["string","null"]},"provider":{"description":"The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.","type":"string"},"tool_call":{"description":"The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema":{"description":"The tool-schema dialect the endpoint accepts.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]}},"required":["provider"]},"ProvidersConfig":{"description":"Provider-specific runtime configuration (`[providers]`).","type":"object","properties":{"models":{"description":"Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.","type":"array","items":{"$ref":"#/$defs/ProviderModelConfig"}},"ollama":{"description":"Ollama-specific request options (`[providers.ollama]`).","$ref":"#/$defs/OllamaProviderConfig","default":{"num_ctx":null}},"tool_dialects":{"description":"Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).","type":"array","items":{"$ref":"#/$defs/ProviderToolDialectConfig"}}}},"ProxyConfig":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).","type":"object","properties":{"all_proxy":{"description":"Fallback proxy URL for all schemes.","type":["string","null"],"default":null},"http_proxy":{"description":"Proxy URL for HTTP requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"https_proxy":{"description":"Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"no_proxy":{"description":"No-proxy bypass list. Same format as NO_PROXY.","type":"array","default":[],"items":{"type":"string"}},"scope":{"description":"Proxy application scope.","$ref":"#/$defs/ProxyScope","default":"zeroclaw"},"services":{"description":"Service selectors used when scope = \"services\".","type":"array","default":[],"items":{"type":"string"}}}},"ProxyScope":{"description":"Proxy application scope — determines which outbound traffic uses the proxy.","oneOf":[{"description":"Use system environment proxy variables only.","type":"string","const":"environment"},{"description":"Apply proxy to all OpenPRX-managed HTTP traffic (default).","type":"string","const":"zeroclaw"},{"description":"Apply proxy only to explicitly listed service selectors.","type":"string","const":"services"}]},"QQConfig":{"description":"QQ Official Bot configuration (Tencent QQ Bot SDK)","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs. Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from QQ Bot developer console","type":"string"},"app_secret":{"description":"App Secret from QQ Bot developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["app_id","app_secret"]},"QueryClassificationConfig":{"description":"Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.","type":"object","properties":{"rules":{"description":"Classification rules evaluated in priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/ClassificationRule"}}}},"RamfluxAccountConfig":{"description":"Persona for one ramflux AI account. Missing fields fall back to the global agent.","type":"object","properties":{"cross_conversation_retrieval":{"description":"Cross-conversation memory retrieval. Off unless the owner sets it.","type":"boolean","default":false},"model":{"type":["string","null"],"default":null},"provider":{"type":["string","null"],"default":null},"scope_profile":{"type":["string","null"],"default":null},"system_prompt_file":{"description":"Path to a system-prompt file. Relative paths are resolved from the workspace.","type":["string","null"],"default":null}},"additionalProperties":false},"RamfluxAttachmentFetch":{"description":"Per-turn caps for `attachment.fetch`.","type":"object","properties":{"max_bytes":{"type":"integer","format":"uint64","default":5242880,"minimum":0},"max_per_turn":{"type":"integer","format":"uint8","default":4,"maximum":255,"minimum":0}},"additionalProperties":false},"RamfluxAuthorizationMode":{"description":"How prx combines its own setting with `bridge.hello.authorization`.","oneOf":[{"description":"Use the agent-host value. Until hello arrives, the effective mode is supervised.","type":"string","const":"follow_rf"},{"description":"Always supervised, even when the agent-host declares full.","type":"string","const":"supervised"},{"description":"Full only when the agent-host also declares full. Config alone never yields full.","type":"string","const":"full"}]},"RamfluxConfig":{"description":"Local ramflux agent-host bridge (`[channels_config.ramflux]`).","type":"object","properties":{"accounts":{"type":"object","additionalProperties":{"$ref":"#/$defs/RamfluxAccountConfig"},"default":{}},"allowed_block_types":{"type":"array","default":["Text","Markdown","Heading","KeyValue","Metric","List","TableFallback","Form","Input","Select","Progress","LogStream","Warning","Error","Success","Approval","ActionGroup","FilePreview","Fallback"],"items":{"type":"string"}},"attachment_fetch":{"$ref":"#/$defs/RamfluxAttachmentFetch","default":{"max_bytes":5242880,"max_per_turn":4}},"authorization_mode":{"$ref":"#/$defs/RamfluxAuthorizationMode","default":"follow_rf"},"encrypt_at_rest":{"type":"boolean","default":true},"max_in_flight_per_conversation":{"type":"integer","format":"uint8","default":1,"maximum":255,"minimum":0},"on_new_message":{"$ref":"#/$defs/RamfluxOnNewMessage","default":"queue"},"socket_path":{"description":"Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.","type":["string","null"],"default":null},"surface_limits":{"$ref":"#/$defs/RamfluxSurfaceLimits","default":{"max_actions":16,"max_blocks":32,"max_bytes":65536}},"turn_wall_clock_secs":{"description":"Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.","type":"integer","format":"uint64","default":120,"minimum":0}},"additionalProperties":false},"RamfluxOnNewMessage":{"description":"What to do with a new inbound message while a turn for that conversation is running.","type":"string","enum":["queue","interrupt"]},"RamfluxSurfaceLimits":{"description":"Limits for `reply.surface` blocks and actions.","type":"object","properties":{"max_actions":{"type":"integer","format":"uint32","default":16,"minimum":0},"max_blocks":{"type":"integer","format":"uint32","default":32,"minimum":0},"max_bytes":{"type":"integer","format":"uint32","default":65536,"minimum":0}},"additionalProperties":false},"ReliabilityCircuitBreakerConfig":{"description":"Process-local provider circuit policy (`[reliability.circuit_breaker]`).","type":"object","properties":{"enabled":{"description":"Enable protection for factory-built provider chains.","type":"boolean","default":true},"failure_threshold":{"description":"Consecutive transient failures that open a circuit (at least 1).","type":"integer","format":"uint32","default":5,"minimum":0},"max_open_secs":{"description":"Maximum doubled window, between open_secs and 3600 seconds.","type":"integer","format":"uint64","default":300,"minimum":0},"open_secs":{"description":"Initial open window in seconds (at least 1).","type":"integer","format":"uint64","default":30,"minimum":0}}},"ReliabilityConfig":{"description":"Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.","type":"object","properties":{"acknowledge_single_provider_risk":{"description":"Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.","type":"boolean","default":false},"api_keys":{"description":"Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.","type":"array","default":[],"items":{"type":"string"}},"channel_initial_backoff_secs":{"description":"Initial backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":2,"minimum":0},"channel_max_backoff_secs":{"description":"Max backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":60,"minimum":0},"circuit_breaker":{"description":"Per-provider consecutive failure protection.","$ref":"#/$defs/ReliabilityCircuitBreakerConfig","default":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30}},"fallback_providers":{"description":"Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).","type":"array","default":[],"items":{"type":"string"}},"model_fallbacks":{"description":"Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`","type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"default":{}},"provider_backoff_ms":{"description":"Base backoff (ms) for provider retry delay.","type":"integer","format":"uint64","default":500,"minimum":0},"provider_retries":{"description":"Retries per provider before failing over.","type":"integer","format":"uint32","default":2,"minimum":0},"scheduler_poll_secs":{"description":"Scheduler polling cadence in seconds.","type":"integer","format":"uint64","default":15,"minimum":0},"scheduler_retries":{"description":"Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.","type":"integer","format":"uint32","default":2,"minimum":0}}},"RemoteNodeConfig":{"description":"A remote node target for core-side node proxy calls.","type":"object","properties":{"bearer_token":{"description":"Bearer token for node RPC authentication.","type":"string"},"endpoint":{"description":"Base endpoint (e.g. \"http://127.0.0.1:8787\").","type":"string"},"hmac_secret":{"description":"Optional request signing key (HMAC-SHA256).","type":["string","null"],"default":null},"id":{"description":"Stable node ID used by the nodes tool.","type":"string"},"retry_max":{"description":"Optional per-node retry override.","type":["integer","null"],"format":"uint8","default":null,"maximum":255,"minimum":0},"timeout_ms":{"description":"Optional per-node timeout override.","type":["integer","null"],"format":"uint64","default":null,"minimum":0}},"required":["id","endpoint","bearer_token"]},"RetrievalInjectionRole":{"description":"Where recalled context pages are injected back into the request.","oneOf":[{"description":"Inject recalled pages as a leading `system` message (not user-visible).","type":"string","const":"system"},{"description":"Inject recalled pages as a leading `user` message.","type":"string","const":"user"}]},"RouterConfig":{"description":"Heuristic LLM router configuration (`[router]` section).","type":"object","properties":{"alpha":{"description":"Similarity score weight. Phase 1 keeps this at `0.0`.","type":"number","format":"float","default":0.0},"beta":{"description":"Capability score weight.","type":"number","format":"float","default":0.5},"delta":{"description":"Cost penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"epsilon":{"description":"Latency penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"gamma":{"description":"Elo score weight.","type":"number","format":"float","default":0.30000001192092896},"knn_k":{"description":"Number of nearest neighbors considered for voting. Default: `7`.","type":"integer","format":"uint","default":7,"minimum":0},"knn_min_records":{"description":"Minimum history records before KNN affects routing. Default: `10`.","type":"integer","format":"uint","default":10,"minimum":0},"models":{"description":"Candidate model registry.","type":"array","default":[],"items":{"$ref":"#/$defs/RouterModelConfig"}}}},"RouterModelConfig":{"description":"Static router metadata for one model candidate.","type":"object","properties":{"categories":{"description":"Capability categories such as `conversation`, `code`, or `analysis`.","type":"array","default":[],"items":{"type":"string"}},"cost_per_million_tokens":{"description":"USD cost per million tokens.","type":"number","format":"float","default":0.0},"elo_rating":{"description":"Initial Elo rating.","type":"number","format":"float","default":1000.0},"latency_ms":{"description":"Average latency in milliseconds.","type":"integer","format":"uint32","default":2000,"minimum":0},"max_context":{"description":"Maximum context window in tokens.","type":"integer","format":"uint","default":1000000,"minimum":0},"model_id":{"description":"Model identifier without provider prefix.","type":"string"},"provider":{"description":"Provider identifier.","type":"string"},"reserved_output_tokens":{"description":"Output tokens reserved for this model when planning input context.","type":["integer","null"],"format":"uint","minimum":0}},"required":["model_id","provider"]},"RuntimeConfig":{"description":"Runtime adapter configuration (`[runtime]` section).","type":"object","properties":{"codex_reasoning_effort":{"description":"Codex reasoning effort (replaces ZEROCLAW_CODEX_REASONING_EFFORT)","type":["string","null"],"default":null},"codex_stream_idle_timeout_secs":{"description":"Codex stream idle timeout in seconds (replaces ZEROCLAW_CODEX_STREAM_IDLE_TIMEOUT_SECS)","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"docker":{"description":"Docker runtime settings (used when `kind = \"docker\"`).","$ref":"#/$defs/DockerRuntimeConfig","default":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true}},"idle_hang_secs":{"description":"Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"kind":{"description":"Runtime kind (`native` | `docker`).","type":"string","default":"native"},"long_task_warn_secs":{"description":"Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"managed_cgroup_root":{"description":"Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.","type":["string","null"],"default":null},"max_blocking_threads":{"description":"Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"reasoning_enabled":{"description":"Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported","type":["boolean","null"],"default":null},"shell_env_allowlist":{"description":"Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.","type":"array","default":[],"items":{"type":"string"}},"workdir":{"description":"Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.","type":["string","null"],"default":null}}},"SchedulerConfig":{"description":"Scheduler configuration for periodic task execution (`[scheduler]` section).","type":"object","properties":{"claim_lease_secs":{"description":"Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.","type":"integer","format":"uint64","default":90,"minimum":0},"max_tasks":{"description":"Maximum number of persisted scheduled tasks.","type":"integer","format":"uint","default":64,"minimum":0}}},"ScopeConfig":{"description":"Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```","type":"object","properties":{"assign_owners":{"description":"Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.","type":"array","default":[],"items":{"type":"string"}},"default":{"description":"Default action when no rule matches: \"allow\" (default) or \"deny\".","$ref":"#/$defs/ScopeDefault","default":"allow"},"rules":{"description":"Ordered list of scope rules evaluated top-to-bottom.","type":"array","default":[],"items":{"$ref":"#/$defs/ScopeRule"}}}},"ScopeDefault":{"description":"What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.","oneOf":[{"description":"Unmatched tool calls are allowed (the default).","type":"string","const":"allow"},{"description":"Unmatched tool calls are refused.","type":"string","const":"deny"}]},"ScopeRule":{"description":"A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.","type":"object","properties":{"assign_allow":{"description":"Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".","type":"array","default":[],"items":{"type":"string"}},"assign_deny":{"description":"Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.","type":"array","default":[],"items":{"type":"string"}},"channel":{"description":"Match by channel name: \"signal\", \"telegram\", \"discord\", etc.","type":["string","null"]},"chat_type":{"description":"Match by chat type: \"direct\", \"group\", or \"*\" for any type.","type":["string","null"]},"send_allow":{"description":"Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.","type":"array","default":[],"items":{"type":"string"}},"send_deny":{"description":"Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.","type":"array","default":[],"items":{"type":"string"}},"tools_allow":{"description":"Tool whitelist: only these tools are allowed (empty = all tools permitted).","type":"array","default":[],"items":{"type":"string"}},"tools_deny":{"description":"Tool blacklist: these tools are denied regardless of allow list.","type":"array","default":[],"items":{"type":"string"}},"user":{"description":"Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.","type":["string","null"]}}},"SecretsConfig":{"description":"Secrets encryption configuration (`[secrets]` section).","type":"object","properties":{"encrypt":{"description":"Enable encryption for API keys and tokens in config.toml","type":"boolean","default":true}}},"SecurityConfig":{"description":"Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.","type":"object","properties":{"audit":{"description":"Audit logging configuration","$ref":"#/$defs/AuditConfig","default":{"log_path":"audit.log","max_size_mb":100}},"workspace_hooks":{"description":"Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.","$ref":"#/$defs/WorkspaceHooks"}}},"SelfSystemConfig":{"description":"Self-system experimental automation config (`[self_system]`).","type":"object","properties":{"evolution_config_path":{"description":"Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG / ZEROCLAW_EVOLUTION_CONFIG)","type":["string","null"],"default":null},"evolution_debug_raw":{"description":"Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW / ZEROCLAW_EVOLUTION_DEBUG_RAW)","type":"boolean","default":false},"evolution_interval_hours":{"description":"Evolution scheduler interval in hours (daemon mode).","type":"integer","format":"uint32","default":24,"minimum":0},"evolution_judge_timeout_secs":{"description":"Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.","type":"integer","format":"uint64","default":180,"minimum":0},"evolution_model_max_micro_usd":{"description":"Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.","type":"integer","format":"uint64","default":0,"minimum":0},"evolution_model_max_tokens":{"description":"Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.","type":"integer","format":"uint64","default":16384,"minimum":0},"fitness":{"description":"Daily fitness snapshot policy.","$ref":"#/$defs/FitnessConfig","default":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"}},"fitness_interval_hours":{"description":"Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.","type":"integer","format":"uint64","default":24,"minimum":0}}},"SessionsSpawnConfig":{"description":"Sessions spawn configuration (`[sessions_spawn]` section).","type":"object","properties":{"cleanup_on_complete":{"description":"Remove worker workspace directory after process-mode completion.","type":"boolean","default":true},"default_mode":{"description":"Default execution mode for sessions_spawn (`task` or `process`).","type":"string","default":"task"},"process_memory_strategy":{"description":"Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.","type":"string","default":"shared_fabric"},"worker_workspace_root":{"description":"Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.","type":["string","null"],"default":null}}},"SignalConfig":{"type":"object","properties":{"account":{"description":"E.164 phone number of the signal-cli account (e.g. \"+1234567890\").","type":"string"},"allowed_from":{"description":"Allowed sender phone numbers (E.164) or \"*\" for all.","type":"array","default":[],"items":{"type":"string"}},"cli_path":{"description":"Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).","type":["string","null"],"default":null},"daemon_http_port":{"description":"Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"daemon_mode":{"description":"Deprecated: ignored. Accepted for backward compatibility with older config files.","type":["boolean","null"],"default":null},"data_dir":{"description":"signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_id":{"description":"Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group","type":["string","null"],"default":null},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"http_url":{"description":"Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.","type":"string","default":"http://localhost:8080"},"ignore_attachments":{"description":"Skip messages that are attachment-only (no text body).","type":"boolean","default":false},"ignore_stories":{"description":"Skip incoming story messages.","type":"boolean","default":false},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"mode":{"description":"Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.","type":["string","null"],"default":null},"startup_timeout_ms":{"description":"Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.","type":"integer","format":"uint64","default":30000,"minimum":0},"storm_protection":{"description":"Signal ingress storm protection controls.","$ref":"#/$defs/SignalStormProtectionConfig","default":{"abnormal_threshold":10,"abnormal_window_secs":60,"breaker_duration_secs":300,"dedupe_ttl_secs":60,"min_reply_interval_secs":2}}},"required":["account"]},"SignalStormProtectionConfig":{"type":"object","properties":{"abnormal_threshold":{"description":"Non-user event threshold within `abnormal_window_secs` before tripping the breaker.","type":"integer","format":"uint","default":10,"minimum":0},"abnormal_window_secs":{"description":"Sliding window in seconds for non-user event counting.","type":"integer","format":"uint64","default":60,"minimum":0},"breaker_duration_secs":{"description":"Circuit breaker duration in seconds after threshold is reached.","type":"integer","format":"uint64","default":300,"minimum":0},"dedupe_ttl_secs":{"description":"Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.","type":"integer","format":"uint64","default":60,"minimum":0},"min_reply_interval_secs":{"description":"Minimum interval in seconds between replies for the same `(channel + reply_target)`.","type":"integer","format":"uint64","default":2,"minimum":0}}},"SkillRagConfig":{"description":"Dynamic skill retrieval configuration (`[skill_rag]` section).","type":"object","properties":{"top_k":{"description":"How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).","type":"integer","format":"uint","default":32,"minimum":0}}},"SkillSuiteRegistration":{"description":"The frozen suite that governs one skill's proposals.","type":"object","properties":{"skill_id":{"description":"The skill the suite governs.","type":"string"},"suite_digest":{"description":"SHA-256 digest (64 lowercase hex digits) of the frozen suite.","type":"string"}},"additionalProperties":false,"required":["skill_id","suite_digest"]},"SkillsConfig":{"description":"Skills loading configuration (`[skills]` section).","type":"object","properties":{"open_skills_dir":{"description":"Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.","type":["string","null"],"default":null},"openclaw_skills_dir":{"description":"Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.","type":["string","null"],"default":null}}},"SkillsLifecycleConfig":{"description":"`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.","type":"object","properties":{"allow_executable_proposals":{"description":"Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.","type":"boolean","default":false},"enabled":{"description":"Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.","type":"boolean","default":false},"max_concurrent_evaluations":{"description":"Most evaluations running at once.","type":"integer","format":"uint32","default":1,"minimum":0},"max_edit_fraction":{"description":"Edit budget of a proposal as a fraction of the skill body, in (0, 1].","type":"number","format":"double","default":0.2},"max_edit_tokens":{"description":"Edit budget of a proposal, in tokens.","type":"integer","format":"uint64","default":300,"minimum":0},"max_proposals_per_cycle":{"description":"Most proposals one cycle may start.","type":"integer","format":"uint32","default":1,"minimum":0},"min_cases_floor":{"description":"Smallest `min_cases` a governing suite may declare. Below 3 is refused.","type":"integer","format":"uint32","default":3,"minimum":0},"mode":{"description":"`draft_only`, `shadow` or `auto`.","$ref":"#/$defs/SkillsLifecycleModeConfig","default":"draft_only"},"owner_scope":{"description":"The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.","type":["string","null"],"default":null},"require_holdout":{"description":"A governing suite must have a holdout split. `false` is refused.","type":"boolean","default":true},"storage_dir":{"description":"Store location under the workspace. Only the default is supported.","type":"string","default":"self/skill-lifecycle"},"suites":{"description":"The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.","type":"array","default":[],"items":{"$ref":"#/$defs/SkillSuiteRegistration"}}},"additionalProperties":false},"SkillsLifecycleModeConfig":{"description":"What the lifecycle may do. Mirrors `LifecycleMode`.","oneOf":[{"description":"Drafts and reviews only.","type":"string","const":"draft_only"},{"description":"Drafts plus evaluation and gating; never publishes.","type":"string","const":"shadow"},{"description":"Publishes an eligible proposal after every gate.","type":"string","const":"auto"}]},"SlackConfig":{"description":"Slack bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Slack user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Slack app-level token for Socket Mode (xapp-...).","type":["string","null"]},"bot_token":{"description":"Slack bot OAuth token (xoxb-...).","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["bot_token"]},"SmartGroupConfig":{"description":"Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).","type":"object","properties":{"classifier_max_context_messages":{"description":"How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.","type":"integer","format":"uint","default":3,"minimum":0},"classifier_model":{"description":"Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.","type":"string","default":""},"classifier_provider":{"description":"Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.","type":"string","default":""},"classifier_temperature":{"description":"Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).","type":"number","format":"double","default":0.0},"classifier_timeout_secs":{"description":"Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.","type":"integer","format":"uint64","default":5,"minimum":0}}},"StorageConfig":{"description":"Persistent storage configuration (`[storage]` section).","type":"object","properties":{"provider":{"description":"Storage provider settings (e.g. sqlite, postgres).","$ref":"#/$defs/StorageProviderSection","default":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}}},"StorageProviderConfig":{"description":"Storage provider backend configuration (e.g. postgres connection details).","type":"object","properties":{"connect_timeout_secs":{"description":"Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"db_url":{"description":"Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.","type":["string","null"],"default":null},"pool_max_size":{"description":"Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.","type":"integer","format":"uint","default":32,"minimum":0},"provider":{"description":"Storage engine key (e.g. \"postgres\", \"sqlite\").","type":"string","default":""},"schema":{"description":"Database schema for SQL backends.","type":"string","default":"public"},"table":{"description":"Table name for memory entries.","type":"string","default":"memories"}}},"StorageProviderSection":{"description":"Wrapper for the storage provider configuration section.","type":"object","properties":{"config":{"description":"Storage provider backend settings.","$ref":"#/$defs/StorageProviderConfig","default":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"StreamMode":{"description":"Streaming mode for channels that support progressive message updates.","oneOf":[{"description":"No streaming -- send the complete response as a single message (default).","type":"string","const":"off"},{"description":"Update a draft message with every flush interval.","type":"string","const":"partial"}]},"TailscaleTunnelConfig":{"type":"object","properties":{"funnel":{"description":"Use Tailscale Funnel (public internet) vs Serve (tailnet only)","type":"boolean","default":false},"hostname":{"description":"Optional hostname override","type":["string","null"]}}},"TaskRoutingConfig":{"description":"Lightweight pre-LLM task routing.","type":"object","properties":{"default_intent":{"description":"Fallback intent when no rule matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"rules":{"description":"Rules evaluated in descending priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/TaskRoutingRule"}}}},"TaskRoutingIntentConfig":{"description":"Task-routing default and rule intent.","type":"string","enum":["simple","delegate","stream"]},"TaskRoutingRule":{"description":"A single task-routing rule.","type":"object","properties":{"intent":{"description":"Route intent to apply when a keyword matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"model_hint":{"description":"Optional model hint/raw model for non-delegated requests.","type":["string","null"],"default":null},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0},"sub_agent_model":{"description":"Optional raw sub-agent model override for delegated tasks.","type":["string","null"],"default":null}}},"TelegramConfig":{"description":"Telegram bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Telegram user IDs or usernames. Empty = deny all.","type":"array","items":{"type":"string"}},"bot_token":{"description":"Telegram Bot API token (from @BotFather).","type":"string"},"draft_update_interval_ms":{"description":"Minimum interval (ms) between draft message edits to avoid rate limits.","type":"integer","format":"uint64","default":1000,"minimum":0},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"interrupt_on_new_message":{"description":"When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.","type":"boolean","default":false},"stream_mode":{"description":"Streaming mode for progressive response delivery via message edits.","$ref":"#/$defs/StreamMode","default":"off"}},"required":["bot_token","allowed_users"]},"ToolCallDialectSetting":{"description":"The tool-call grammars an operator may declare for an endpoint.","oneOf":[{"description":"Only the native `tool_calls` array is a tool call (the default).","type":"string","const":"native"},{"description":"Additionally read `{json}` from the content,\nfor a tool name the request registered.","type":"string","const":"xml_function_tags"}]},"ToolSchemaDialectSetting":{"description":"The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.","oneOf":[{"description":"The published document, byte for byte (the default).","type":"string","const":"raw"},{"description":"The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.","type":"string","const":"no_root_combinators"}]},"ToolTieringConfig":{"description":"Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.","type":"object","properties":{"always_exclude":{"description":"Tool names excluded from capability publication.","type":"array","default":[],"items":{"type":"string"}},"always_include":{"description":"Tool names preferred for direct publication, subject to admission gates.","type":"array","default":[],"items":{"type":"string"}},"channel_exclude":{"description":"Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefaults to [`DEFAULT_CHANNEL_EXCLUDED_TOOLS`]; set to `[]` to expose the\nfull operator surface on channels again.","type":"array","default":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","git_operations","skills_manage","memory_reindex","document_sync","document_ingest"],"items":{"type":"string"}}}},"TunnelConfig":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.","type":"object","properties":{"cloudflare":{"description":"Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).","anyOf":[{"$ref":"#/$defs/CloudflareTunnelConfig"},{"type":"null"}],"default":null},"custom":{"description":"Custom tunnel command configuration (used when `provider = \"custom\"`).","anyOf":[{"$ref":"#/$defs/CustomTunnelConfig"},{"type":"null"}],"default":null},"ngrok":{"description":"ngrok tunnel configuration (used when `provider = \"ngrok\"`).","anyOf":[{"$ref":"#/$defs/NgrokTunnelConfig"},{"type":"null"}],"default":null},"provider":{"description":"Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.","type":"string","default":"none"},"tailscale":{"description":"Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).","anyOf":[{"$ref":"#/$defs/TailscaleTunnelConfig"},{"type":"null"}],"default":null}}},"UserPolicyConfig":{"description":"Startup user policy entry (`[[user_policies]]`).","type":"object","properties":{"blocked_patterns":{"type":"array","default":[],"items":{"type":"string"}},"projects":{"type":"array","default":[],"items":{"type":"string"}},"role":{"type":"string","default":"guest"},"user_id":{"type":"string"},"visibility_ceiling":{"type":"string","default":"private"}},"required":["user_id"]},"WacliConfig":{"description":"wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```","type":"object","properties":{"allow_unsigned_loopback":{"description":"Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).","type":"boolean","default":false},"allowed_from":{"description":"Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.","type":"array","default":["*"],"items":{"type":"string"}},"bot_jid":{"description":"Bot's own JID, used for reply-to-bot mention detection.","type":["string","null"],"default":null},"bot_lid":{"description":"The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.","type":["string","null"],"default":null},"bot_number":{"description":"Bot's own phone number (digits), used for `@` mention detection.","type":["string","null"],"default":null},"cli_path":{"description":"Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.","type":["string","null"],"default":null},"group_reply_mode":{"description":"Smart group-reply mode. When `None`, derived from `mention_only`.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"host":{"description":"REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].","type":["string","null"],"writeOnly":true},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"outbound_media_workspace_only":{"description":"Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.","type":"boolean","default":false},"port":{"description":"REMOVED: legacy JSON-RPC daemon port. See `host`.","type":["integer","null"],"format":"uint16","maximum":65535,"minimum":0,"writeOnly":true},"self_chat_mode":{"description":"Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.","type":"boolean","default":false},"store_dir":{"description":"wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.","type":["string","null"],"default":null},"webhook_listen":{"description":"Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").","type":"string","default":"127.0.0.1:16868"},"webhook_path":{"description":"HTTP path the webhook server serves (default: \"/wacli\").","type":"string","default":"/wacli"},"webhook_secret":{"description":"HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.","type":["string","null"],"default":null}}},"WebSearchConfig":{"description":"Web search tool configuration (`[web_search]` section).","type":"object","properties":{"brave_api_key":{"description":"Brave Search API key (required if provider is \"brave\")","type":["string","null"],"default":null},"fetch_max_chars":{"description":"Maximum characters returned by `web_fetch` (default 10000)","type":"integer","format":"uint","default":50000,"minimum":0},"max_results":{"description":"Maximum results per search (1-20)","type":"integer","format":"uint","default":15,"minimum":0},"provider":{"description":"Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)","type":"string","default":"duckduckgo"},"timeout_secs":{"description":"Request timeout in seconds","type":"integer","format":"uint64","default":15,"minimum":0}}},"WebhookConfig":{"description":"Webhook channel configuration.","type":"object","properties":{"port":{"description":"Port to listen on for incoming webhooks.","type":"integer","format":"uint16","maximum":65535,"minimum":0},"secret":{"description":"Optional shared secret for webhook signature verification.","type":["string","null"]}},"required":["port"]},"WhatsAppConfig":{"description":"WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.","type":"object","properties":{"access_token":{"description":"Access token from Meta Business Suite (Cloud API mode)","type":["string","null"],"default":null},"allowed_numbers":{"description":"Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"app_secret":{"description":"App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"pair_code":{"description":"Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one","type":["string","null"],"default":null},"pair_phone":{"description":"Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used","type":["string","null"],"default":null},"phone_number_id":{"description":"Phone number ID from Meta Business API (Cloud API mode)","type":["string","null"],"default":null},"read_pool_size":{"description":"Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"session_path":{"description":"Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs","type":["string","null"],"default":null},"verify_token":{"description":"Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode","type":["string","null"],"default":null},"ws_url":{"description":"WebSocket URL override (replaces WHATSAPP_WS_URL)","type":["string","null"],"default":null}}},"WorkspaceHooks":{"description":"Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).","oneOf":[{"description":"They do not run (the default); `prx doctor` and `hooks_status` say so.","type":"string","const":"off"},{"description":"They run, in a cleared environment and a dedicated directory beside\n`config.toml`.","type":"string","const":"on"}]},"WorkspaceMcpServers":{"description":"Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).","oneOf":[{"description":"None: a workspace file may only narrow the servers defined in\n`config.toml`.","type":"string","const":"off"},{"description":"HTTP servers (still refused when they target a private address).","type":"string","const":"http_only"},{"description":"HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.","type":"string","const":"stdio"}]},"XinConfig":{"description":"Configuration for the xin autonomous task engine (`[xin]`).","type":"object","properties":{"adopt_legacy_tasks":{"description":"Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).","type":"boolean","default":false},"interval_minutes":{"description":"Tick interval in minutes (minimum 1). Default: 5.","type":"integer","format":"uint32","default":5,"minimum":0},"stale_timeout_minutes":{"description":"Minutes after which a running task is marked stale. Default: 60.","type":"integer","format":"uint32","default":60,"minimum":0}}},"AgentMessaging":{"description":"Owner-controlled inbound session messaging (enabled unless explicitly off).","type":"object","properties":{"inbound":{"type":"boolean","default":true}}}}} From 7af93a5e9ab2c9f3acb3863fe57692caebfb9c9d Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 16:20:41 +0400 Subject: [PATCH 0005/1567] fix(a2a): serialize outbox dispatch across local processes --- src/chat/message_inbox.rs | 5 +++-- src/messaging/a2a/leader.rs | 37 +++++++++++++++++++++++++++++++++++ src/messaging/a2a/mod.rs | 1 + src/messaging/a2a/outbound.rs | 12 +++++++++++- src/messaging/runtime.rs | 2 +- 5 files changed, 53 insertions(+), 4 deletions(-) create mode 100644 src/messaging/a2a/leader.rs diff --git a/src/chat/message_inbox.rs b/src/chat/message_inbox.rs index 97cd15cbb..99000664e 100644 --- a/src/chat/message_inbox.rs +++ b/src/chat/message_inbox.rs @@ -91,7 +91,7 @@ pub(super) fn cause(message: &ChannelMessage) -> Option<&str> { pub(super) async fn send_command( config: &crate::config::Config, - memory:&Arc, + memory: &Arc, parent: &str, focused: Option<&str>, message: &ChannelMessage, @@ -123,7 +123,8 @@ pub(super) async fn send_command( let level = if source_session == parent { config.autonomy.level } else { - let store = memory.child_session_store() + let store = memory + .child_session_store() .ok_or_else(|| anyhow::anyhow!("child store unavailable"))?; let record = store .sessions(&runtime.workspace, &owner)? diff --git a/src/messaging/a2a/leader.rs b/src/messaging/a2a/leader.rs new file mode 100644 index 000000000..38d3612e4 --- /dev/null +++ b/src/messaging/a2a/leader.rs @@ -0,0 +1,37 @@ +//! A process lease prevents multiple local chat/daemon outbox dispatchers. +use anyhow::{Result, ensure}; +use std::{ + fs::{File, OpenOptions}, + path::Path, +}; +pub(super) fn open(workspace: &Path) -> Result { + let path = workspace.join("a2a").join("outbox.lock"); + let mut options = OpenOptions::new(); + options.read(true).write(true).create(true).truncate(false); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600).custom_flags(libc::O_NOFOLLOW); + } + let file = options.open(&path)?; + ensure!( + file.metadata()?.is_file() && !std::fs::symlink_metadata(&path)?.file_type().is_symlink(), + "invalid outbox lease file" + ); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + ensure!( + file.metadata()?.permissions().mode().trailing_zeros() >= 7, + "outbox lease permissions exceed 0600" + ); + } + Ok(file) +} +pub(super) fn claim(file: &File) -> Result { + match file.try_lock() { + Ok(()) => Ok(true), + Err(std::fs::TryLockError::WouldBlock) => Ok(false), + Err(std::fs::TryLockError::Error(error)) => Err(error.into()), + } +} diff --git a/src/messaging/a2a/mod.rs b/src/messaging/a2a/mod.rs index b1c841ff9..2b2b24721 100644 --- a/src/messaging/a2a/mod.rs +++ b/src/messaging/a2a/mod.rs @@ -3,6 +3,7 @@ pub mod cli; mod clients; mod connections; pub mod identity; +mod leader; mod listener; mod outbound; pub mod peers; diff --git a/src/messaging/a2a/outbound.rs b/src/messaging/a2a/outbound.rs index 08416ac75..9d78db1cd 100644 --- a/src/messaging/a2a/outbound.rs +++ b/src/messaging/a2a/outbound.rs @@ -97,12 +97,21 @@ impl RemoteTransport { result=request=>result, } } - pub(crate) fn start(self, runtime: Arc) { + pub(crate) fn start(self, runtime: Arc) -> anyhow::Result<()> { + let lease = super::leader::open(&self.trust.config.workspace_dir)?; + let mut leader = super::leader::claim(&lease)?; tokio::spawn(async move { let _monitor = self.clients.monitor(); let mut interval = tokio::time::interval(Duration::from_secs(1)); loop { interval.tick().await; + if !leader { + match super::leader::claim(&lease) { + Ok(true) => leader = true, + Ok(false) => continue, + Err(_) => break, + } + } let Ok(sources) = runtime.store.outbox_sources() else { continue; }; @@ -166,6 +175,7 @@ impl RemoteTransport { } } }); + Ok(()) } } fn retry_after(response: &reqwest::Response) -> Option { diff --git a/src/messaging/runtime.rs b/src/messaging/runtime.rs index 7655bf16f..d93739ddd 100644 --- a/src/messaging/runtime.rs +++ b/src/messaging/runtime.rs @@ -121,7 +121,7 @@ impl MessagingRuntime { let drainer: Arc = runtime.clone(); runtime.store.register_drainer(&drainer); if config.a2a.messaging_enabled { - super::a2a::RemoteTransport::new(config).start(runtime.clone()); + super::a2a::RemoteTransport::new(config).start(runtime.clone())?; } runtimes.insert(path, Arc::downgrade(&runtime)); Ok(runtime) From cf6c9bd74d3ddef5902ece3878cd237c878d3311 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 16:38:26 +0400 Subject: [PATCH 0006/1567] fix(messaging): preserve typed refusals across child process completion --- docs/rf-contract/capability-tokens.md | 14 ++-- src/agent/live_frames.rs | 7 +- src/agent/tool_scheduler.rs | 7 +- src/gateway/live_frames.rs | 20 +++++- src/runtime/mailbox_child/approvals.rs | 2 +- src/session_worker/denials.rs | 68 ++++++++++++++++--- .../protocol/operator_completion.rs | 7 +- .../protocol/ordinary_completion.rs | 7 +- src/tools/execution/refusal_record.rs | 7 +- src/tools/sessions_spawn/process_mode.rs | 8 +-- 10 files changed, 108 insertions(+), 39 deletions(-) diff --git a/docs/rf-contract/capability-tokens.md b/docs/rf-contract/capability-tokens.md index cc885d6dc..d5c88a62f 100644 --- a/docs/rf-contract/capability-tokens.md +++ b/docs/rf-contract/capability-tokens.md @@ -745,11 +745,15 @@ interception uses `plan_only`. Every denied/failed tool outcome commits a `tool. journal row before its live frame, including scheduler refusals before service entry. Rows retain the internal `reason` and the same mapped `cause` as the live frame. A refusal-storage failure ends the turn without an unrecorded frame. -No refusal cause contains paths or arguments. Process workers have no approval relay in this unit. Their -completion returns a bounded, content-free `denials:[{tool,cause}]` inventory -under the existing completion signature. Only after authentication does the -parent emit one frame per denial on the **parent run**: -`{tool,phase:"denied",cause:"no_resolver",child_run_id}` plus its stable ids. +No refusal cause contains paths or arguments. Process workers have no approval +relay in this unit. Their completion returns a bounded, content-free +`denials:[{tool,cause}]` inventory under the existing completion signature. +This includes pre-approval refusal and failure causes; approval requests still +end with `no_resolver`. Only after authentication does the parent emit one +`tool_status` per outcome on the **parent run**, with `child_run_id` and its +stable ids. Its phase is `failed` for `failed`/`indeterminate` causes, otherwise +`denied`; its cause uses the same typed mapping as an in-process child. +Worker refusal rows are committed before the signed observation is emitted. The inventory holds at most 256 denials with tool names at most 64 bytes; overflow fails completion explicitly. It carries no model text or arguments. diff --git a/src/agent/live_frames.rs b/src/agent/live_frames.rs index 4e371dd04..7b3874ce1 100644 --- a/src/agent/live_frames.rs +++ b/src/agent/live_frames.rs @@ -7,7 +7,12 @@ pub(crate) trait LiveFrameSink: Send + Sync { fn emit(&self, event: &ToolLoopEvent); fn thinking(&self); fn awaiting_approval(&self, tool: &str); - fn child_denial(&self, tool: &str, child_run_id: &str); + fn child_denial( + &self, + tool: &str, + child_run_id: &str, + cause: crate::security::approval_ledger::run_call::RfDenialCause, + ); } #[async_trait::async_trait] diff --git a/src/agent/tool_scheduler.rs b/src/agent/tool_scheduler.rs index 3429ad7c1..f17963c07 100644 --- a/src/agent/tool_scheduler.rs +++ b/src/agent/tool_scheduler.rs @@ -392,7 +392,12 @@ async fn emit_tool_outcome( call: &ParsedToolCall, mut event: ToolLoopEvent, ) -> Result<()> { - if adapter.tool_execution_context.live_turn.is_some() + // A worker returns only sealed observations, never an approval relay. + // Commit the same refusal before its observation can reach the parent. + let context = &adapter.tool_execution_context; + let worker = context.pending_approval_denied + && context.envelope.source == crate::runtime::envelope::RuntimeSource::SessionWorker; + if (context.live_turn.is_some() || worker) && let ToolLoopEvent::ToolFinished { tool_call_id, name, diff --git a/src/gateway/live_frames.rs b/src/gateway/live_frames.rs index 40ae448d4..c5e12dee3 100644 --- a/src/gateway/live_frames.rs +++ b/src/gateway/live_frames.rs @@ -205,8 +205,24 @@ impl LiveFrameSink for Producer { fn awaiting_approval(&self, tool: &str) { self.send(json!({"kind":"tool_status","tool":tool,"phase":"awaiting_approval"})); } - fn child_denial(&self, tool: &str, child_run_id: &str) { - self.send(json!({"kind":"tool_status","tool":tool,"phase":"denied","cause":"no_resolver","child_run_id":child_run_id})); + fn child_denial( + &self, + tool: &str, + child_run_id: &str, + cause: crate::security::approval_ledger::run_call::RfDenialCause, + ) { + use crate::security::approval_ledger::run_call::RfDenialCause; + use crate::tools::execution::ToolCallRefusalReason; + let phase = if matches!( + cause, + RfDenialCause::Refusal(ToolCallRefusalReason::Failed | ToolCallRefusalReason::Indeterminate) + ) { + "failed" + } else { + "denied" + }; + let cause = crate::security::approval_ledger::run_call::rf_denial_cause(cause); + self.send(json!({"kind":"tool_status","tool":tool,"phase":phase,"cause":cause,"child_run_id":child_run_id})); } fn emit(&self, event: &ToolLoopEvent) { use crate::agent::tool_evidence::ToolCallOutcome; diff --git a/src/runtime/mailbox_child/approvals.rs b/src/runtime/mailbox_child/approvals.rs index 81353058c..c4f18fad8 100644 --- a/src/runtime/mailbox_child/approvals.rs +++ b/src/runtime/mailbox_child/approvals.rs @@ -7,7 +7,7 @@ impl LiveFrameSink for NoSurface { fn emit(&self, _: &ToolLoopEvent) {} fn thinking(&self) {} fn awaiting_approval(&self, _: &str) {} - fn child_denial(&self, _: &str, _: &str) {} + fn child_denial(&self, _: &str, _: &str, _: crate::security::approval_ledger::run_call::RfDenialCause) {} } #[async_trait::async_trait] impl LiveTurn for NoSurface { diff --git a/src/session_worker/denials.rs b/src/session_worker/denials.rs index 6470130fa..89d0fe74c 100644 --- a/src/session_worker/denials.rs +++ b/src/session_worker/denials.rs @@ -9,7 +9,30 @@ const MAX_DENIALS: usize = 256; #[serde(deny_unknown_fields)] pub struct WorkerDenial { pub tool: String, - pub cause: crate::tools::ApprovalDenialCause, + pub cause: WorkerDenialCause, +} +/// Content-free outcomes only; this never carries an approval request or grant. +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +#[serde(untagged)] +pub enum WorkerDenialCause { + Approval(crate::tools::ApprovalDenialCause), + Refusal(crate::tools::execution::ToolCallRefusalReason), +} +impl WorkerDenial { + pub(crate) const fn valid(&self) -> bool { + self.tool.len() <= 64 + && matches!( + self.cause, + WorkerDenialCause::Approval(crate::tools::ApprovalDenialCause::NoResolver) + | WorkerDenialCause::Refusal(_) + ) + } + pub(crate) fn rf_cause(&self) -> crate::security::approval_ledger::run_call::RfDenialCause { + match self.cause { + WorkerDenialCause::Approval(cause) => cause.into(), + WorkerDenialCause::Refusal(cause) => cause.into(), + } + } } #[derive(Default)] pub(crate) struct DenialSink { @@ -29,25 +52,43 @@ impl LiveFrameSink for DenialSink { fn thinking(&self) {} // Process workers have no approval relay; only typed denials enter completion. fn awaiting_approval(&self, _tool: &str) {} - fn child_denial(&self, tool: &str, _child_run_id: &str) { - self.record(tool); + fn child_denial( + &self, + tool: &str, + _child_run_id: &str, + cause: crate::security::approval_ledger::run_call::RfDenialCause, + ) { + self.record(tool, cause); } fn emit(&self, event: &ToolLoopEvent) { + use crate::agent::tool_evidence::ToolCallOutcome; + use crate::tools::execution::ToolCallRefusalReason; if let ToolLoopEvent::ToolFinished { name, - outcome: - crate::agent::tool_evidence::ToolCallOutcome::Denied { - cause: Some(crate::tools::ApprovalDenialCause::NoResolver), - }, + outcome, + refusal_cause, .. } = event { - self.record(name); + let cause = match outcome { + ToolCallOutcome::Denied { + cause: Some(crate::tools::ApprovalDenialCause::NoResolver), + } => Some(crate::tools::ApprovalDenialCause::NoResolver.into()), + ToolCallOutcome::Refused => Some(refusal_cause.unwrap_or(ToolCallRefusalReason::PolicyDenied).into()), + ToolCallOutcome::PlanOnly => Some(ToolCallRefusalReason::PlanOnly.into()), + ToolCallOutcome::Error => Some(refusal_cause.unwrap_or(ToolCallRefusalReason::Failed).into()), + ToolCallOutcome::Unknown => Some(refusal_cause.unwrap_or(ToolCallRefusalReason::Indeterminate).into()), + _ => None, + }; + if let Some(cause) = cause { + self.record(name, cause); + } } } } + impl DenialSink { - fn record(&self, tool: &str) { + fn record(&self, tool: &str, cause: crate::security::approval_ledger::run_call::RfDenialCause) { let mut denials = self.denials.lock(); if denials.len() == MAX_DENIALS || tool.len() > 64 { self.overflow.store(true, Ordering::Relaxed); @@ -55,7 +96,14 @@ impl DenialSink { } denials.push(WorkerDenial { tool: tool.to_owned(), - cause: crate::tools::ApprovalDenialCause::NoResolver, + cause: match cause { + crate::security::approval_ledger::run_call::RfDenialCause::Approval(cause) => { + WorkerDenialCause::Approval(cause) + } + crate::security::approval_ledger::run_call::RfDenialCause::Refusal(cause) => { + WorkerDenialCause::Refusal(cause) + } + }, }); } } diff --git a/src/session_worker/protocol/operator_completion.rs b/src/session_worker/protocol/operator_completion.rs index 18f86098b..cea55c545 100644 --- a/src/session_worker/protocol/operator_completion.rs +++ b/src/session_worker/protocol/operator_completion.rs @@ -104,12 +104,7 @@ impl OperatorWorkerCompletionEvidence { pub(crate) fn signing_bytes(&self, result: &WorkerResult) -> anyhow::Result> { anyhow::ensure!( - result.denials.len() <= 256 - && result - .denials - .iter() - .all(|denial| denial.tool.len() <= 64 - && denial.cause == crate::tools::ApprovalDenialCause::NoResolver), + result.denials.len() <= 256 && result.denials.iter().all(super::super::denials::WorkerDenial::valid), "invalid worker denial inventory" ); Ok(serde_json::to_vec(&( diff --git a/src/session_worker/protocol/ordinary_completion.rs b/src/session_worker/protocol/ordinary_completion.rs index 597b3bd22..cf58554b5 100644 --- a/src/session_worker/protocol/ordinary_completion.rs +++ b/src/session_worker/protocol/ordinary_completion.rs @@ -98,12 +98,7 @@ impl OrdinaryWorkerCompletionEvidence { pub(crate) fn signing_bytes(&self, result: &WorkerResult) -> anyhow::Result> { anyhow::ensure!( - result.denials.len() <= 256 - && result - .denials - .iter() - .all(|denial| denial.tool.len() <= 64 - && denial.cause == crate::tools::ApprovalDenialCause::NoResolver), + result.denials.len() <= 256 && result.denials.iter().all(super::super::denials::WorkerDenial::valid), "invalid worker denial inventory" ); Ok(serde_json::to_vec(&( diff --git a/src/tools/execution/refusal_record.rs b/src/tools/execution/refusal_record.rs index 0d0a22a5e..e4da91ec2 100644 --- a/src/tools/execution/refusal_record.rs +++ b/src/tools/execution/refusal_record.rs @@ -120,7 +120,12 @@ impl ToolExecutionService { // rf records every denied/failed frame at the scheduler boundary, // including refusals that never enter this service. Keep one row per // outcome there; the operator notice above retains its original order. - if context.live_turn.is_some() { + // The worker's sealed refusal inventory uses that same scheduler + // boundary. Approval calls still stay denied with no_resolver. + if context.live_turn.is_some() + || (context.pending_approval_denied + && context.envelope.source == crate::runtime::envelope::RuntimeSource::SessionWorker) + { return; } let Some(memory) = self.idempotency_memory.as_ref() else { diff --git a/src/tools/sessions_spawn/process_mode.rs b/src/tools/sessions_spawn/process_mode.rs index 14801970b..07bef1ded 100644 --- a/src/tools/sessions_spawn/process_mode.rs +++ b/src/tools/sessions_spawn/process_mode.rs @@ -787,9 +787,7 @@ pub(super) async fn run_sub_agent_process( verified.confirm_reaped(run_id)?; if let Some(frames) = &parent_frames { for denial in &verified.result.denials { - if denial.cause == crate::tools::ApprovalDenialCause::NoResolver { - frames.child_denial(&denial.tool, run_id); - } + frames.child_denial(&denial.tool, run_id, denial.rf_cause()); } } Ok(ProcessWorkerOutcome::OrdinaryVerifiedFinished(verified)) @@ -807,9 +805,7 @@ pub(super) async fn run_sub_agent_process( verified.confirm_reaped(run_id)?; if let Some(frames) = &parent_frames { for denial in &verified.result.denials { - if denial.cause == crate::tools::ApprovalDenialCause::NoResolver { - frames.child_denial(&denial.tool, run_id); - } + frames.child_denial(&denial.tool, run_id, denial.rf_cause()); } } Ok(ProcessWorkerOutcome::OperatorVerifiedFinished(verified)) From c7328e5698400f1ac1fc68883172e6c60474057c Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 17:21:58 +0400 Subject: [PATCH 0007/1567] fix(messaging): close review gaps and restore turn startup --- docs/configuration.md | 19 +- src/config/schema/lifecycle.rs | 3 + src/gateway/api/sessions/section_1.rs | 16 +- src/gateway/child_mailbox.rs | 90 ++++----- src/gateway/child_mailbox/approvals.rs | 48 +++++ src/gateway/run_approvals.rs | 19 ++ src/memory/sqlite/mailbox/pin.rs | 58 ++++-- src/memory/sqlite/tests/mailbox/section_2.rs | 2 +- src/messaging/a2a/cli.rs | 24 ++- src/messaging/a2a/clients.rs | 12 +- src/messaging/a2a/dispatch.rs | 97 ++++++++++ src/messaging/a2a/identity.rs | 66 ++++--- src/messaging/a2a/identity/rotation.rs | 54 ++++++ src/messaging/a2a/listener.rs | 103 ++++++----- src/messaging/a2a/mod.rs | 2 + src/messaging/a2a/outbound.rs | 167 +++++++++-------- src/messaging/a2a/peers.rs | 19 +- src/messaging/a2a/tls.rs | 47 ++--- src/messaging/a2a/trust.rs | 145 +++++++++++++++ src/messaging/receiver.rs | 47 +++-- src/messaging/runtime.rs | 40 ++-- src/messaging/types.rs | 2 +- src/runtime/mailbox_child.rs | 181 +++++++++++-------- src/runtime/mailbox_child/driver.rs | 34 ++-- src/runtime/mailbox_child/publication.rs | 22 ++- src/tools/sessions_send.rs | 23 ++- 26 files changed, 938 insertions(+), 402 deletions(-) create mode 100644 src/gateway/child_mailbox/approvals.rs create mode 100644 src/messaging/a2a/dispatch.rs create mode 100644 src/messaging/a2a/identity/rotation.rs create mode 100644 src/messaging/a2a/trust.rs diff --git a/docs/configuration.md b/docs/configuration.md index e792fa1e2..ae7c4cfb4 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -3474,6 +3474,8 @@ minutes. See [the rf live-frame and approval contract](rf-contract/capability-to `[agent.messaging] inbound = true` controls Main. Each `[agents..messaging] inbound = true` controls that agent. Both default to true. Messages are user data; an approval-looking body grants no permission. +Addresses use the full SPIFFE ID in `instance` when initialized; duplicate +peer UUIDs across trust domains and the local UUID are refused. An idle receiver starts a turn at its own level and budget; a busy receiver queues it. After eight automatic hops, delivery continues without starting a turn. The chain bound stops loops between honest instances; peers can be revoked. @@ -3500,14 +3502,25 @@ on the other instance using the existing peer name, then run `prx a2a init UUID and SPIFFE ID. Remove the old pin with `a2a peer remove --fingerprint `. A peer accepts at most two fingerprints during overlap. Removal and rotation close connections and cancel outstanding client -requests; TLS sessions are never resumed. Certificates expire after five years. +requests; interrupted deliveries retry. Activation deletes retired key/cert +files and stale temporary files; the staged pair is kept until activation. +TLS sessions are never resumed. Certificates expire after five years. `a2a init` displays the local expiry; `a2a peer list` obtains each remote expiry through authenticated TLS and reports when a peer is unreachable or refused. The outbox persists retries for up to 24 hours, below the seven-day replay window. Authentication, authorization, malformed-chain and oversized-message -refusals are permanent. Network failures, 429 and server failures retry with -jitter and `Retry-After`. A receiver pin is refreshed before each attempt; +refusals are permanent. Network failures, client rotation/cancellation, 408, 429 and server failures retry with +jitter and `Retry-After`, independently for each peer. Malformed messages +return 400 `field_invalid`; 422 is reserved for chain cycles. Pin tokens are +opaque authenticated ciphertext and disclose no workspace path or owner. +A receiver pin is refreshed before each attempt; recipient incarnation changes fail rather than redirect old data. To roll back, disable messaging and restart the gateway; retain the outbox and identity files. There are no remote-tree permission caps. Queue/body storage bounds remain. + +Mailbox children derive their tool allowlist from current configuration. Console +roots receive child approval requests in their owner-scoped approval inbox and +review them through the root session endpoint; the wait remains four minutes. +An rf root uses its connected live surface and configured wait. Without a live +approval surface the call is denied with `no_approval_surface`. diff --git a/src/config/schema/lifecycle.rs b/src/config/schema/lifecycle.rs index 9d3f70e9b..dee5b73b6 100644 --- a/src/config/schema/lifecycle.rs +++ b/src/config/schema/lifecycle.rs @@ -860,6 +860,9 @@ impl Config { self.memory.validate()?; self.sessions_spawn.validate()?; self.a2a.validate()?; + if let Some(local) = crate::messaging::a2a::identity::optional(self)? { + crate::messaging::a2a::peers::validate_local(&self.a2a, &local)?; + } // Smart group-reply pre-gate numeric ranges. self.smart_group.validate()?; diff --git a/src/gateway/api/sessions/section_1.rs b/src/gateway/api/sessions/section_1.rs index a46138321..f14135da5 100644 --- a/src/gateway/api/sessions/section_1.rs +++ b/src/gateway/api/sessions/section_1.rs @@ -1512,6 +1512,9 @@ pub(super) async fn get_decision_approval( Path((session_id, decision_id)): Path<(String, String)>, axum::Extension(principal): axum::Extension, ) -> Response { + if let Some(view) = state.rf_approvals.root_view(&principal.owner_id, &session_id, &decision_id) { + return Json(view).into_response(); + } call_approval_action(state, session_id, decision_id, principal, None, false).await } @@ -1606,8 +1609,9 @@ pub(super) async fn get_session_approvals( rows.push(( event.id, ApprovalInboxItem { - session_id: item.subject().session_key.clone().unwrap_or_default(), - view: item.view(), + session_id: item.rf.as_ref().map(|root| root.root_session.clone()) + .or_else(|| item.subject().session_key.clone()).unwrap_or_default(), + view: { let mut view = item.view(); if let Some(root) = &item.rf { view.tool = Some(root.tool.clone()); } view }, }, )); } @@ -1677,6 +1681,14 @@ pub(super) async fn post_decision_approval( let Ok(request) = serde_json::from_value::(request) else { return json_error(StatusCode::UNPROCESSABLE_ENTITY, "invalid approval body"); }; + if state.rf_approvals.root_view(&principal.owner_id, &session_id, &decision_id).is_some() { + if !owner_authenticated { + return json_error(StatusCode::FORBIDDEN, "Paired owner approval is required"); + } + let decision = if request.approved { "approved" } else { "denied" }; + return crate::gateway::run_approvals::decide(&state, &principal.owner_id, &session_id, &decision_id, + serde_json::json!({"decision":decision})).await; + } call_approval_action( state, session_id, diff --git a/src/gateway/child_mailbox.rs b/src/gateway/child_mailbox.rs index 8e97a1bb2..653bf794e 100644 --- a/src/gateway/child_mailbox.rs +++ b/src/gateway/child_mailbox.rs @@ -1,4 +1,5 @@ //! Backend-owned wake drivers for durable children, independent of parent turns. +mod approvals; use super::AppState; use crate::memory::child_sessions::ChildSessionRecord; use crate::messaging::runtime::{MessageInput, MessagingRuntime}; @@ -51,6 +52,7 @@ pub(super) fn register(state: &AppState, envelope: &crate::runtime::envelope::Ru } roots.insert(root.clone(), Arc::downgrade(&lifetime)); } + let console = envelope.source == crate::runtime::envelope::RuntimeSource::Console; let state = state.clone(); tokio::spawn(async move { let _lifetime = Registration { @@ -60,13 +62,19 @@ pub(super) fn register(state: &AppState, envelope: &crate::runtime::envelope::Ru let mut interval = tokio::time::interval(std::time::Duration::from_millis(100)); loop { interval.tick().await; - if runtime.store.validate_scope(&root_scope, &root).is_err() { - break; - } - let Some(store) = state.mem.child_session_store() else { - break; - }; - let Ok(records) = store.sessions(&runtime.workspace, &root.owner) else { + let reader = Arc::clone(&runtime); + let scope = root_scope.clone(); + let address = root.clone(); + let memory = Arc::clone(&state.mem); + let Ok(Ok(Some(records))) = crate::runtime::blocking::spawn_blocking(move || { + if reader.store.validate_scope(&scope, &address).is_err() { + return Ok(None); + } + let store = memory.child_session_store().context("child store unavailable")?; + Ok::<_, anyhow::Error>(Some(store.sessions(&reader.workspace, &address.owner)?)) + }) + .await + else { break; }; for mut record in records @@ -95,7 +103,7 @@ pub(super) fn register(state: &AppState, envelope: &crate::runtime::envelope::Ru Arc::new(move |input| { let state = state.clone(); let record = record.clone(); - Box::pin(run(state, record, input)) + Box::pin(run(state, record, input, console)) }), idle, ); @@ -107,41 +115,29 @@ pub(super) fn register(state: &AppState, envelope: &crate::runtime::envelope::Ru }); Ok(()) } -async fn run(state: AppState, record: ChildSessionRecord, input: MessageInput) -> Result<()> { +async fn run(state: AppState, record: ChildSessionRecord, input: MessageInput, console: bool) -> Result<()> { let turn = state.admit_turn_runtime()?; let cleanup = Arc::clone(&turn.publication_slot.cleanup); cleanup .scope(async { let publication = turn.publication_slot.publish(&turn, &state).await?; - let runtime = MessagingRuntime::for_config(&turn.config_generation.effective)?; - input.verify(&runtime)?; - let mut live = crate::runtime::mailbox_child::no_surface(); - if state.rf_streams.connected(&record.owner) - && let Some(store) = state.mem.sync_store() - { - let event = input - .receipt - .adopted_message_event_id - .context("adopted child event missing")? - .to_string(); - if let Some(scope) = store.live_scope(&record.owner, &event)? { - live = - crate::agent::live_frames::LiveTurnRef(Arc::new(super::run_approvals::RunApprovalResolver { - scope, - streams: Arc::clone(&state.rf_streams), - approvals: Arc::clone(&state.rf_approvals), - cancellation: tokio_util::sync::CancellationToken::new(), - wait_secs: turn - .config_generation - .effective - .agents - .get(&record.agent) - .map_or(turn.config_generation.effective.agent.approval_wait_secs, |agent| { - agent.approval_wait_secs - }), - })); - } - } + let configured = Arc::clone(&turn.config_generation.effective); + let incoming = input.clone(); + let runtime = crate::runtime::blocking::spawn_blocking(move || { + let runtime = MessagingRuntime::for_config(&configured)?; + incoming.verify(&runtime)?; + Ok::<_, anyhow::Error>(runtime) + }) + .await??; + let wait_secs = turn + .config_generation + .effective + .agents + .get(&record.agent) + .map_or(turn.config_generation.effective.agent.approval_wait_secs, |agent| { + agent.approval_wait_secs + }); + let live = approvals::live(&state, &record, &input, console, wait_secs).await?; crate::runtime::mailbox_child::MailboxChildSource::admit( publication, record.clone(), @@ -156,12 +152,18 @@ async fn run(state: AppState, record: ChildSessionRecord, input: MessageInput) - let mut interval = tokio::time::interval(std::time::Duration::from_millis(100)); loop { interval.tick().await; - input.verify(&runtime)?; - let records = state - .mem - .child_session_store() - .context("child store unavailable")? - .sessions(&record.workspace, &record.owner)?; + let reader = Arc::clone(&runtime); + let incoming = input.clone(); + let memory = Arc::clone(&state.mem); + let receiver = record.clone(); + let records = crate::runtime::blocking::spawn_blocking(move || { + incoming.verify(&reader)?; + memory + .child_session_store() + .context("child store unavailable")? + .sessions(&receiver.workspace, &receiver.owner) + }) + .await??; let Some(current) = records.iter().find(|current| current.session_key == record.session_key) else { break; }; diff --git a/src/gateway/child_mailbox/approvals.rs b/src/gateway/child_mailbox/approvals.rs new file mode 100644 index 000000000..90c2b732d --- /dev/null +++ b/src/gateway/child_mailbox/approvals.rs @@ -0,0 +1,48 @@ +//! Root-owned approval surfaces, without retaining the ended parent's authority. +use crate::{ + gateway::AppState, + memory::child_sessions::ChildSessionRecord, + messaging::runtime::{MessageInput, MessagingRuntime}, +}; +use anyhow::{Context, Result}; +use std::sync::Arc; +pub(super) async fn live( + state: &AppState, + record: &ChildSessionRecord, + input: &MessageInput, + console: bool, + wait_secs: u64, +) -> Result { + let state_owned = state.clone(); + let record = record.clone(); + let input = input.clone(); + let scope = crate::runtime::blocking::spawn_blocking(move || { + let event = input.receipt.adopted_message_event_id.context("adopted child event missing")?.to_string(); + if let Some(store) = state_owned.mem.sync_store() + && let Some(scope) = store.live_scope(&record.owner, &event)? + { + // rf requires a connected surface. A generic gateway root has none. + return Ok(if state_owned.rf_streams.connected(&record.owner) { Some((scope, false)) } else { None }); + } + if !console { return Ok(None); } + // A registered Console root has its authenticated durable approval inbox + // and decision endpoints, independently of an rf WebSocket connection. + let config = state_owned.config.load_full(); + let runtime = MessagingRuntime::for_config(&config)?; + let agent = runtime.store.logical_agent(&record.workspace, &record.owner, &record.parent_session)?.unwrap_or_else(|| "main".into()); + let address = runtime.address(&record.owner, &record.parent_session, &agent); + let root = runtime.store.session_scope(&record.workspace, &address, false)?; + Ok::<_, anyhow::Error>(Some((serde_json::json!({"session":record.parent_session,"agent":agent,"incarnation":root.incarnation,"run_id":record.parent_run}), true))) + }).await??; + Ok( + scope.map_or_else(crate::runtime::mailbox_child::no_surface, |(scope, console)| { + crate::agent::live_frames::LiveTurnRef(Arc::new(crate::gateway::run_approvals::RunApprovalResolver { + scope, + streams: Arc::clone(&state.rf_streams), + approvals: Arc::clone(&state.rf_approvals), + cancellation: tokio_util::sync::CancellationToken::new(), + wait_secs: if console { 240 } else { wait_secs }, + })) + }), + ) +} diff --git a/src/gateway/run_approvals.rs b/src/gateway/run_approvals.rs index d13df4797..2ac55e09b 100644 --- a/src/gateway/run_approvals.rs +++ b/src/gateway/run_approvals.rs @@ -43,6 +43,25 @@ impl Decision { pub struct ApprovalHub { entries: Mutex>>, } +impl ApprovalHub { + pub(crate) fn root_view( + &self, + owner: &str, + session: &str, + id: &str, + ) -> Option { + let entries = self.entries.lock(); + let entry = entries.get(id)?; + let root = entry.pending.rf.as_ref()?; + if entry.pending.subject().owner_id != owner || root.root_session != session { + return None; + } + let mut view = entry.pending.view(); + view.tool = Some(root.tool.clone()); + Some(view) + } +} + struct Entry { ledger: ExecutionApprovalLedger, pending: PendingCall, diff --git a/src/memory/sqlite/mailbox/pin.rs b/src/memory/sqlite/mailbox/pin.rs index a0ad649f7..705637fe6 100644 --- a/src/memory/sqlite/mailbox/pin.rs +++ b/src/memory/sqlite/mailbox/pin.rs @@ -1,9 +1,11 @@ -//! Recipient pins are HMAC-bound to a scope snapshot, target and verified peer. +//! Opaque AEAD pins bind the scope, target and verified peer without disclosure. use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; -use hmac::{Hmac, Mac}; +use chacha20poly1305::{ + ChaCha20Poly1305, Nonce, + aead::{Aead, KeyInit, Payload}, +}; use rusqlite::{Connection, OptionalExtension, params}; use serde::{Deserialize, Serialize}; -use sha2::Sha256; use uuid::Uuid; use super::{ @@ -55,14 +57,25 @@ impl SqliteMailbox { expires_at: self.clock.now().checked_add(300).ok_or(MailboxError::InvalidMetadata)?, }; let payload = encode(&claims)?; - let mut mac = Hmac::::new_from_slice(self.secret.as_ref()).map_err(|_| MailboxError::InvalidPin)?; - mac.update(b"prx-mailbox-recipient-v1\0"); - mac.update(payload.as_bytes()); - let token = format!( - "{}.{}", - URL_SAFE_NO_PAD.encode(payload.as_bytes()), - hex::encode(mac.finalize().into_bytes()) - ); + let cipher = ChaCha20Poly1305::new_from_slice(self.secret.as_ref()).map_err(|_| MailboxError::InvalidPin)?; + use ring::rand::SecureRandom as _; + let mut nonce_bytes = [0_u8; 12]; + ring::rand::SystemRandom::new() + .fill(&mut nonce_bytes) + .map_err(|_| MailboxError::InvalidPin)?; + let nonce = Nonce::from(nonce_bytes); + let encrypted = cipher + .encrypt( + &nonce, + Payload { + msg: payload.as_bytes(), + aad: b"prx-mailbox-recipient-v2", + }, + ) + .map_err(|_| MailboxError::InvalidPin)?; + let mut opaque = nonce.to_vec(); + opaque.extend_from_slice(&encrypted); + let token = URL_SAFE_NO_PAD.encode(opaque); Ok(RecipientPin { incarnation: scope.incarnation, generation: scope.generation, @@ -74,13 +87,22 @@ impl SqliteMailbox { if message.to_pin.token.is_empty() { return Err(MailboxError::PinRequired); } - let (payload, signature) = message.to_pin.token.split_once('.').ok_or(MailboxError::InvalidPin)?; - let bytes = URL_SAFE_NO_PAD.decode(payload).map_err(|_| MailboxError::InvalidPin)?; - let signature = hex::decode(signature).map_err(|_| MailboxError::InvalidPin)?; - let mut mac = Hmac::::new_from_slice(self.secret.as_ref()).map_err(|_| MailboxError::InvalidPin)?; - mac.update(b"prx-mailbox-recipient-v1\0"); - mac.update(&bytes); - mac.verify_slice(&signature).map_err(|_| MailboxError::InvalidPin)?; + let opaque = URL_SAFE_NO_PAD + .decode(&message.to_pin.token) + .map_err(|_| MailboxError::InvalidPin)?; + let (nonce, encrypted) = opaque.split_at_checked(12).ok_or(MailboxError::InvalidPin)?; + let cipher = ChaCha20Poly1305::new_from_slice(self.secret.as_ref()).map_err(|_| MailboxError::InvalidPin)?; + let nonce: [u8; 12] = nonce.try_into().map_err(|_| MailboxError::InvalidPin)?; + let nonce = Nonce::from(nonce); + let bytes = cipher + .decrypt( + &nonce, + Payload { + msg: encrypted, + aad: b"prx-mailbox-recipient-v2", + }, + ) + .map_err(|_| MailboxError::InvalidPin)?; let json = std::str::from_utf8(&bytes).map_err(|_| MailboxError::InvalidPin)?; let claims: PinClaims = decode(json).map_err(|_| MailboxError::InvalidPin)?; if claims.target != message.to diff --git a/src/memory/sqlite/tests/mailbox/section_2.rs b/src/memory/sqlite/tests/mailbox/section_2.rs index 8efc2875a..dfb64c67f 100644 --- a/src/memory/sqlite/tests/mailbox/section_2.rs +++ b/src/memory/sqlite/tests/mailbox/section_2.rs @@ -137,7 +137,7 @@ async fn sessions_send_remote_addr_is_not_steer() { let tool = crate::tools::sessions_send::SessionsSendTool::new(Arc::new(tokio::sync::RwLock::new(Vec::new()))) .with_mailbox(f.sender_port(None)); assert!( - tool.parameters_schema().get("oneOf").is_some(), + tool.parameters_schema().get("type").and_then(serde_json::Value::as_str) == Some("object"), "sessions send remote addr is not steer: expected messaging contract changed" ); assert!( diff --git a/src/messaging/a2a/cli.rs b/src/messaging/a2a/cli.rs index 2a45982cc..2002516f7 100644 --- a/src/messaging/a2a/cli.rs +++ b/src/messaging/a2a/cli.rs @@ -45,11 +45,15 @@ pub async fn run(command: A2aCommand, mut config: crate::config::Config) -> Resu let original = config.clone(); match command { A2aCommand::Init { rotate, prepare_rotate } => { - let identity = if prepare_rotate { - super::identity::prepare_rotation(&config)? - } else { - super::identity::init(&config, rotate)? - }; + let selected = config.clone(); + let identity = crate::runtime::blocking::spawn_blocking(move || { + if prepare_rotate { + super::identity::prepare_rotation(&selected) + } else { + super::identity::init(&selected, rotate) + } + }) + .await??; Ok(format!( "{}\nfingerprint {}\nexpires {}", identity.spiffe_id, identity.fingerprint, identity.expires_at @@ -58,7 +62,8 @@ pub async fn run(command: A2aCommand, mut config: crate::config::Config) -> Resu A2aCommand::Peer { command: PeerCommand::List, } => { - let local = super::identity::load(&config)?; + let selected = config.clone(); + let local = crate::runtime::blocking::spawn_blocking(move || super::identity::load(&selected)).await??; let mut rows = vec![format!("local {} expires {}", local.spiffe_id, local.expires_at)]; let mut peers: Vec<_> = config.a2a.peers.iter().collect(); peers.sort_by_key(|(name, _)| *name); @@ -93,10 +98,13 @@ pub async fn run(command: A2aCommand, mut config: crate::config::Config) -> Resu agents, }, } => { - let local = super::identity::load(&config)?; + let selected = config.clone(); + let local = crate::runtime::blocking::spawn_blocking(move || super::identity::load(&selected)).await??; super::peers::instance(&spiffe)?; ensure!( - spiffe != local.spiffe_id && fingerprint != local.fingerprint, + super::peers::instance(&spiffe)? != local.instance_id + && spiffe != local.spiffe_id + && fingerprint != local.fingerprint, "local identity cannot be a peer" ); ensure!( diff --git a/src/messaging/a2a/clients.rs b/src/messaging/a2a/clients.rs index afa90c15b..ba969fbdd 100644 --- a/src/messaging/a2a/clients.rs +++ b/src/messaging/a2a/clients.rs @@ -1,8 +1,5 @@ //! One revocable HTTP client per pinned peer and local key generation. -use super::{ - identity, - tls::{self, Trust}, -}; +use super::tls::{self, Trust}; use crate::config::A2aPeer; use anyhow::Result; use parking_lot::Mutex; @@ -29,7 +26,7 @@ impl Clients { } } pub(crate) fn get(&self, peer: &A2aPeer) -> Result<(reqwest::Client, CancellationToken)> { - let local = identity::load(&self.trust.config)?; + let local = self.trust.identity()?; let mut entries = self.entries.lock(); if let Some(entry) = entries.get(&peer.spiffe_id) { if same(&entry.peer, peer) && entry.local_fingerprint == local.fingerprint { @@ -43,7 +40,7 @@ impl Clients { peer.spiffe_id.clone(), Entry { peer: peer.clone(), - local_fingerprint: local.fingerprint, + local_fingerprint: local.fingerprint.clone(), client: client.clone(), cancellation: cancellation.clone(), }, @@ -60,7 +57,8 @@ impl Clients { tokio::select! { ()=stop.cancelled()=>break, _=interval.tick()=> { - let config=cache.trust.current();let local=identity::load(&cache.trust.config); + let _ = cache.trust.refresh_async().await; + let config=cache.trust.current();let local=cache.trust.identity(); cache.states.lock().retain(|spiffe,_|config.as_ref().is_ok_and(|config|config.peers.values().any(|peer|&peer.spiffe_id==spiffe))); cache.entries.lock().retain(|spiffe,entry| { let current=config.as_ref().ok().and_then(|config|config.peers.values().find(|peer|&peer.spiffe_id==spiffe)); diff --git a/src/messaging/a2a/dispatch.rs b/src/messaging/a2a/dispatch.rs new file mode 100644 index 000000000..624020bbd --- /dev/null +++ b/src/messaging/a2a/dispatch.rs @@ -0,0 +1,97 @@ +//! Independently scheduled peers under the workspace process lease. +use super::outbound::RemoteTransport; +use crate::messaging::{ + PrxMessage, SessionAddr, + mailbox::{MailboxError, MailboxScope}, + runtime::MessagingRuntime, +}; +use anyhow::Result; +use std::{ + collections::{HashMap, HashSet}, + sync::Arc, + time::Duration, +}; +pub(super) struct Pending { + pub scope: MailboxScope, + pub source: SessionAddr, + pub message: PrxMessage, + pub attempts: u32, +} +fn ready(runtime: &MessagingRuntime, mut selected: HashSet) -> Result> { + let mut pending = Vec::new(); + for (scope, source) in runtime.store.outbox_sources()? { + for outbound in runtime.store.pending_outbox(&scope, &source)? { + let message = outbound.message(); + if message.to.instance == runtime.instance || !selected.insert(message.to.instance.clone()) { + continue; + } + let message = message.clone(); + let (attempts, created) = runtime.store.outbox_retry(&scope, &message)?; + if chrono::Utc::now().timestamp().saturating_sub(created) >= 86400 { + runtime.store.retry_outbox(&scope, &source, &message, None, "expired")?; + } else { + pending.push(Pending { + scope: scope.clone(), + source: source.clone(), + message, + attempts, + }); + } + } + } + Ok(pending) +} +pub(super) async fn run( + transport: Arc, + runtime: Arc, + lease: Arc, +) -> Result<()> { + let mut leader = false; + let mut peers = HashSet::new(); + let mut tasks = HashMap::new(); + let mut jobs = tokio::task::JoinSet::new(); + let mut interval = tokio::time::interval(Duration::from_secs(1)); + loop { + tokio::select! { + result = jobs.join_next_with_id(), if !jobs.is_empty() => { + match result { + Some(Ok((id, result))) => { + if let Some(peer) = tasks.remove(&id) { peers.remove(&peer); } + if let Err(error) = result { tracing::error!(error=%crate::agent::diagnostics::error_class(&error), "A2A peer dispatcher failed; retrying durable work"); } + } + Some(Err(error)) => { + if let Some(peer) = tasks.remove(&error.id()) { peers.remove(&peer); } + tracing::error!("A2A peer dispatcher exited; restarting from durable work"); + } + None => {} + } + } + _ = interval.tick() => { + if !leader { + let lease = Arc::clone(&lease); + match crate::runtime::blocking::spawn_blocking(move || super::leader::claim(&lease)).await? { + Ok(true) => leader = true, + Ok(false) => continue, + Err(error) => { tracing::error!(error=%crate::agent::diagnostics::error_class(&error), "A2A dispatcher lease failed; retrying"); continue; } + } + } + let store = Arc::clone(&runtime); + let busy = peers.clone(); + for pending in crate::runtime::blocking::spawn_blocking(move || ready(&store, busy)).await?? { + let peer = pending.message.to.instance.clone(); + if !peers.insert(peer.clone()) { continue; } + let transport = Arc::clone(&transport); + let runtime = Arc::clone(&runtime); + let task = jobs.spawn(async move { transport.deliver(runtime, pending).await }); + tasks.insert(task.id(), peer); + } + } + } + } +} +pub(super) fn permanent(error: &anyhow::Error) -> bool { + matches!( + error.downcast_ref::(), + Some(MailboxError::Unauthorized | MailboxError::StaleIncarnation) + ) +} diff --git a/src/messaging/a2a/identity.rs b/src/messaging/a2a/identity.rs index 96fe773b0..9309fc92b 100644 --- a/src/messaging/a2a/identity.rs +++ b/src/messaging/a2a/identity.rs @@ -1,4 +1,5 @@ //! Atomic, private, persisted Ed25519 instance identities. +mod rotation; use anyhow::{Context, Result, ensure}; use rustls::pki_types::{CertificateDer, PrivateKeyDer}; use serde::{Deserialize, Serialize}; @@ -122,7 +123,9 @@ fn load_named(config: &crate::config::Config, name: &str) -> Result { Ok(identity) } pub fn init(config: &crate::config::Config, rotate: bool) -> Result { - let dir = directory(config); + let dir = prepare_directory(config)?; + let _lease = rotation::lock(&dir)?; + rotation::cleanup(&dir)?; if dir.join("identity.toml").exists() && !rotate { return load(config); } @@ -149,11 +152,17 @@ pub fn init(config: &crate::config::Config, rotate: bool) -> Result { ); fs::rename(dir.join("pending.toml"), dir.join("identity.toml"))?; fs::File::open(&dir)?.sync_all()?; + rotation::cleanup(&dir)?; return load(config); } - generate(config, "identity.toml", old) + let identity = generate(config, "identity.toml", old)?; + rotation::cleanup(&dir)?; + Ok(identity) } pub fn prepare_rotation(config: &crate::config::Config) -> Result { + let dir = prepare_directory(config)?; + let _lease = rotation::lock(&dir)?; + rotation::cleanup(&dir)?; let current = load(config)?; if directory(config).join("pending.toml").exists() { return load_named(config, "pending.toml"); @@ -162,30 +171,6 @@ pub fn prepare_rotation(config: &crate::config::Config) -> Result { } fn generate(config: &crate::config::Config, name: &str, old: Option) -> Result { let dir = directory(config); - fs::create_dir_all(&config.workspace_dir)?; - let mut builder = fs::DirBuilder::new(); - #[cfg(unix)] - { - use std::os::unix::fs::DirBuilderExt; - builder.mode(0o700); - } - match builder.create(&dir) { - Ok(()) => {} - Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {} - Err(error) => return Err(error.into()), - } - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - ensure!( - fs::metadata(&dir)?.permissions().mode().trailing_zeros() >= 6, - "A2A directory permissions exceed 0700" - ); - } - ensure!( - !fs::symlink_metadata(&dir)?.file_type().is_symlink(), - "A2A directory cannot be a symlink" - ); let instance_id = old .as_ref() .map_or_else(uuid::Uuid::new_v4, |identity| identity.instance_id); @@ -226,3 +211,32 @@ fn generate(config: &crate::config::Config, name: &str, old: Option) - pub(crate) fn fingerprint(der: &[u8]) -> String { hex::encode(Sha256::digest(der)) } + +fn prepare_directory(config: &crate::config::Config) -> Result { + let dir = directory(config); + fs::create_dir_all(&config.workspace_dir)?; + let mut builder = fs::DirBuilder::new(); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + builder.mode(0o700); + } + match builder.create(&dir) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(error) => return Err(error.into()), + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + ensure!( + fs::metadata(&dir)?.permissions().mode().trailing_zeros() >= 6, + "A2A directory permissions exceed 0700" + ); + } + ensure!( + !fs::symlink_metadata(&dir)?.file_type().is_symlink(), + "A2A directory cannot be a symlink" + ); + Ok(dir) +} diff --git a/src/messaging/a2a/identity/rotation.rs b/src/messaging/a2a/identity/rotation.rs new file mode 100644 index 000000000..9f999822e --- /dev/null +++ b/src/messaging/a2a/identity/rotation.rs @@ -0,0 +1,54 @@ +//! Serialize activation and remove key generations no longer used locally. +use super::{Record, read}; +use anyhow::{Result, ensure}; +use std::{ + fs::{self, OpenOptions}, + path::Path, +}; +pub(super) fn lock(dir: &Path) -> Result { + let path = dir.join("identity.lock"); + let mut options = OpenOptions::new(); + options.read(true).write(true).create(true).truncate(false); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600).custom_flags(libc::O_NOFOLLOW); + } + let file = options.open(&path)?; + ensure!(file.metadata()?.is_file(), "invalid identity lease"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + ensure!( + file.metadata()?.permissions().mode().trailing_zeros() >= 7, + "identity lease permissions exceed 0600" + ); + } + file.lock()?; + Ok(file) +} +pub(super) fn cleanup(dir: &Path) -> Result<()> { + let mut keep = std::collections::HashSet::new(); + for name in ["identity.toml", "pending.toml"] { + let path = dir.join(name); + if path.try_exists()? { + let record: Record = toml::from_str(std::str::from_utf8(&read(&path, true)?)?)?; + keep.insert(record.generation); + } + } + for entry in fs::read_dir(dir)? { + let entry = entry?; + let name = entry.file_name(); + let name = name.to_string_lossy(); + let key = name.strip_suffix(".key.pem").or_else(|| name.strip_suffix(".der")); + let generation = key.and_then(|name| uuid::Uuid::parse_str(name).ok()); + let temporary = name + .strip_prefix('.') + .is_some_and(|name| uuid::Uuid::parse_str(name).is_ok()); + if temporary || generation.is_some_and(|id| !keep.contains(&id)) { + fs::remove_file(entry.path())?; + } + } + fs::File::open(dir)?.sync_all()?; + Ok(()) +} diff --git a/src/messaging/a2a/listener.rs b/src/messaging/a2a/listener.rs index 612df1c3f..e0a5a3132 100644 --- a/src/messaging/a2a/listener.rs +++ b/src/messaging/a2a/listener.rs @@ -8,7 +8,7 @@ use crate::messaging::{ mailbox::{MailboxAuthority, MailboxError}, runtime::MessagingRuntime, }; -use anyhow::{Context, Result}; +use anyhow::Result; use http_body_util::{BodyExt as _, Full, Limited}; use hyper::{ Request, Response, StatusCode, @@ -47,7 +47,7 @@ fn target_authority( anyhow::ensure!(peers::allows(peer, target, &runtime.instance), "peer_not_allowed"); runtime.resolve_scope(target)?; crate::messaging::mailbox::validate_address(&source)?; - source.instance = peers::instance(&peer.spiffe_id)?.to_string(); + source.instance.clone_from(&peer.spiffe_id); source.owner = peer.owner.clone(); Ok(MailboxAuthority::verified_peer( runtime.workspace.clone(), @@ -67,6 +67,33 @@ async fn request( rate: Arc, request: Request, ) -> Response { + let route = if request.method() == hyper::Method::POST { + match request.uri().path() { + "/a2a/v1/pins" => Some(true), + "/a2a/v1/messages" => Some(false), + _ => None, + } + } else { + None + }; + let bytes = match Limited::new(request.into_body(), 352 * 1024).collect().await { + Ok(body) => body.to_bytes(), + Err(_) => return refused(StatusCode::PAYLOAD_TOO_LARGE, "message_too_large"), + }; + crate::runtime::blocking::spawn_blocking(move || process(trust, cert, rate, route, bytes)) + .await + .unwrap_or_else(|_| refused(StatusCode::SERVICE_UNAVAILABLE, "mailbox_unavailable")) +} +fn process( + trust: Trust, + cert: rustls::pki_types::CertificateDer<'static>, + rate: Arc, + route: Option, + bytes: Bytes, +) -> Response { + if trust.refresh().is_err() { + return refused(StatusCode::UNAUTHORIZED, "peer_unauthenticated"); + } let Ok(effective) = trust.effective() else { return refused(StatusCode::UNAUTHORIZED, "peer_unauthenticated"); }; @@ -86,13 +113,8 @@ async fn request( .insert(hyper::header::RETRY_AFTER, hyper::header::HeaderValue::from_static("1")); return response; } - if request.method() != hyper::Method::POST || !matches!(request.uri().path(), "/a2a/v1/pins" | "/a2a/v1/messages") { + let Some(pins) = route else { return refused(StatusCode::NOT_FOUND, "not_found"); - } - let pins = request.uri().path() == "/a2a/v1/pins"; - let bytes = match Limited::new(request.into_body(), 352 * 1024).collect().await { - Ok(body) => body.to_bytes(), - Err(_) => return refused(StatusCode::PAYLOAD_TOO_LARGE, "message_too_large"), }; if pins { #[derive(serde::Deserialize)] @@ -101,14 +123,9 @@ async fn request( to: SessionAddr, } let Ok(input) = serde_json::from_slice::(&bytes) else { - return refused(StatusCode::FORBIDDEN, "peer_not_allowed"); + return refused(StatusCode::BAD_REQUEST, "field_invalid"); }; - let source = SessionAddr::new( - peers::instance(&peer.spiffe_id).map_or_else(|_| String::new(), |id| id.to_string()), - &peer.owner, - "peer", - None, - ); + let source = SessionAddr::new(peer.spiffe_id.clone(), &peer.owner, "peer", None); let Ok(authority) = target_authority(&runtime, &peer, &input.to, source) else { return refused(StatusCode::FORBIDDEN, "peer_not_allowed"); }; @@ -127,7 +144,7 @@ async fn request( } let mut message: PrxMessage = match serde_json::from_slice(&bytes) { Ok(message) => message, - Err(_) => return refused(StatusCode::UNPROCESSABLE_ENTITY, "chain_limit_reached"), + Err(_) => return refused(StatusCode::BAD_REQUEST, "field_invalid"), }; if message.body.bytes.len() > crate::messaging::MAX_BODY_BYTES { return refused(StatusCode::PAYLOAD_TOO_LARGE, "message_too_large"); @@ -154,13 +171,18 @@ async fn request( .insert(hyper::header::RETRY_AFTER, hyper::header::HeaderValue::from_static("1")); result } + Err(MailboxError::ChainDepth) => refused(StatusCode::UNPROCESSABLE_ENTITY, "chain_limit_reached"), Err( - MailboxError::ChainDepth - | MailboxError::UnknownParent + MailboxError::UnknownParent | MailboxError::InvalidMetadata | MailboxError::IdempotencyConflict - | MailboxError::IdReuse, - ) => refused(StatusCode::UNPROCESSABLE_ENTITY, "chain_limit_reached"), + | MailboxError::IdReuse + | MailboxError::InvalidAddress + | MailboxError::InvalidMime + | MailboxError::StreamIdRequired + | MailboxError::SeqConflict + | MailboxError::NaturalKeyCollision, + ) => refused(StatusCode::BAD_REQUEST, "field_invalid"), Err(_) => refused(StatusCode::FORBIDDEN, "peer_not_allowed"), } } @@ -168,21 +190,16 @@ pub async fn start(config: &crate::config::Config, shutdown: CancellationToken) if !config.a2a.messaging_enabled { return Ok(None); } - config.a2a.validate()?; - let identity = identity::load(config).context("run prx a2a init before enabling messaging")?; - anyhow::ensure!( - !config - .a2a - .peers - .values() - .any(|peer| peer.spiffe_id == identity.spiffe_id || peer.fingerprints.contains(&identity.fingerprint)), - "local identity cannot be its own peer" - ); - let trust = Trust { - config: Arc::new(config.clone()), - }; - let _ = tls::server(trust.clone())?; - let runtime = MessagingRuntime::for_config(config)?; + let configured = config.clone(); + let (trust, runtime) = crate::runtime::blocking::spawn_blocking(move || { + let trust = Trust::new(&configured); + trust.refresh()?; + let local = trust.identity()?; + peers::validate_local(&configured.a2a, &local)?; + let _ = tls::server(trust.clone())?; + Ok::<_, anyhow::Error>((trust, MessagingRuntime::for_config(&configured)?)) + }) + .await??; let listener = tokio::net::TcpListener::bind(&config.a2a.bind).await?; let total = Arc::new(tokio::sync::Semaphore::new(128)); let registry = Arc::new(super::connections::Connections::default()); @@ -195,7 +212,8 @@ pub async fn start(config: &crate::config::Config, shutdown: CancellationToken) () = shutdown.cancelled() => break, _ = connections.join_next(), if !connections.is_empty() => continue, _=refresh.tick()=> { - let config=trust.current();let local=identity::load(&trust.config); + let _ = trust.refresh_async().await; + let config=trust.current();let local=trust.identity(); registry.recheck(config.as_ref().ok(),local.as_ref().ok().map(|identity|identity.fingerprint.as_str())); continue; } @@ -218,10 +236,13 @@ pub async fn start(config: &crate::config::Config, shutdown: CancellationToken) let shutdown = shutdown.clone(); connections.spawn(async move { let _permit = permit; - let Ok(local) = identity::load(&trust.config) else { - return; - }; - let Ok(server) = tls::server(trust.clone()) else { + let builder = trust.clone(); + let Ok(Ok((server, local))) = crate::runtime::blocking::spawn_blocking(move || { + builder.refresh()?; + Ok::<_, anyhow::Error>((tls::server(builder.clone())?, builder.identity()?)) + }) + .await + else { return; }; let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(server)); @@ -241,7 +262,7 @@ pub async fn start(config: &crate::config::Config, shutdown: CancellationToken) return; }; let fingerprint = identity::fingerprint(cert.as_ref()); - let Some(permit) = registry.register(peer, fingerprint, local.fingerprint) else { + let Some(permit) = registry.register(peer, fingerprint, local.fingerprint.clone()) else { return; }; let cancellation = permit.cancellation(); diff --git a/src/messaging/a2a/mod.rs b/src/messaging/a2a/mod.rs index 2b2b24721..b2aaf9865 100644 --- a/src/messaging/a2a/mod.rs +++ b/src/messaging/a2a/mod.rs @@ -2,6 +2,7 @@ pub mod cli; mod clients; mod connections; +mod dispatch; pub mod identity; mod leader; mod listener; @@ -9,5 +10,6 @@ mod outbound; pub mod peers; mod resources; mod tls; +mod trust; pub use listener::start; pub(crate) use outbound::RemoteTransport; diff --git a/src/messaging/a2a/outbound.rs b/src/messaging/a2a/outbound.rs index 9d78db1cd..b9d3c4e63 100644 --- a/src/messaging/a2a/outbound.rs +++ b/src/messaging/a2a/outbound.rs @@ -1,12 +1,12 @@ //! Durable remote publication and receiver-pin refresh before every attempt. -use super::{peers, tls::Trust}; +use super::tls::Trust; use crate::messaging::{ DeliveryState, RecipientPin, SessionAddr, mailbox::{MailboxAuthority, MailboxError, MailboxResult}, runtime::MessagingRuntime, send::MailboxDestination, }; -use std::{collections::HashSet, sync::Arc, time::Duration}; +use std::{sync::Arc, time::Duration}; pub(crate) struct RemoteTransport { trust: Trust, @@ -14,9 +14,7 @@ pub(crate) struct RemoteTransport { } impl RemoteTransport { pub(crate) fn new(config: &crate::config::Config) -> Self { - let trust = Trust { - config: Arc::new(config.clone()), - }; + let trust = Trust::new(config); Self { clients: super::clients::Clients::new(trust.clone()), trust, @@ -27,9 +25,9 @@ impl RemoteTransport { config .peers .values() - .find(|peer| peers::instance(&peer.spiffe_id).is_ok_and(|id| id.to_string() == target.instance)) + .find(|peer| peer.spiffe_id == target.instance) .cloned() - .ok_or_else(|| anyhow::anyhow!("peer_not_allowed")) + .ok_or_else(|| MailboxError::Unauthorized.into()) } pub(crate) fn destination( &self, @@ -55,8 +53,11 @@ impl RemoteTransport { source: &SessionAddr, message: &mut crate::messaging::PrxMessage, ) -> anyhow::Result<(u16, Option)> { - let peer = self.peer(&message.to).map_err(|_| MailboxError::Unauthorized)?; - let (client, cancellation) = self.clients.get(&peer)?; + self.trust.refresh_async().await?; + let peer = self.peer(&message.to)?; + let clients = self.clients.clone(); + let selected = peer.clone(); + let (client, cancellation) = crate::runtime::blocking::spawn_blocking(move || clients.get(&selected)).await??; let request = async { let response = client .post(format!("https://{}/a2a/v1/pins", peer.address)) @@ -74,9 +75,16 @@ impl RemoteTransport { expires_at: i64, } let pin: Pin = serde_json::from_slice(&bounded_response(response).await?)?; - runtime - .store - .refresh_outbox_pin(scope, source, message, pin.pin, pin.expires_at)?; + let store = runtime.store.clone(); + let scope = scope.clone(); + let source = source.clone(); + let mut refreshed = message.clone(); + *message = crate::runtime::blocking::spawn_blocking(move || { + store.refresh_outbox_pin(&scope, &source, &mut refreshed, pin.pin, pin.expires_at)?; + Ok::<_, MailboxError>(refreshed) + }) + .await??; + self.trust.refresh_async().await?; // Re-read grants between the two requests; no cached bearer authority. let current = self.peer(&message.to)?; anyhow::ensure!( @@ -93,90 +101,81 @@ impl RemoteTransport { Ok((response.status().as_u16(), retry_after(&response))) }; tokio::select! { - ()=cancellation.cancelled()=>Err(MailboxError::Unauthorized.into()), + ()=cancellation.cancelled()=>Err(anyhow::anyhow!("peer client changed; retry delivery")), result=request=>result, } } pub(crate) fn start(self, runtime: Arc) -> anyhow::Result<()> { - let lease = super::leader::open(&self.trust.config.workspace_dir)?; - let mut leader = super::leader::claim(&lease)?; + let lease = Arc::new(super::leader::open(&self.trust.config.workspace_dir)?); + let transport = Arc::new(self); tokio::spawn(async move { - let _monitor = self.clients.monitor(); - let mut interval = tokio::time::interval(Duration::from_secs(1)); + let _monitor = transport.clients.monitor(); loop { - interval.tick().await; - if !leader { - match super::leader::claim(&lease) { - Ok(true) => leader = true, - Ok(false) => continue, - Err(_) => break, - } - } - let Ok(sources) = runtime.store.outbox_sources() else { - continue; - }; - let mut peers = HashSet::new(); - for (scope, source) in sources { - let Ok(pending) = runtime.store.pending_outbox(&scope, &source) else { - continue; - }; - for outbound in pending { - let mut message = outbound.message().clone(); - if message.to.instance == runtime.instance || !peers.insert(message.to.instance.clone()) { - continue; - } - let Ok((attempts, created)) = runtime.store.outbox_retry(&scope, &message) else { - continue; - }; - let now = chrono::Utc::now().timestamp(); - if now.saturating_sub(created) >= 86400 { - let _ = runtime.store.retry_outbox(&scope, &source, &message, None, "expired"); - continue; - } - let result = self.attempt(&runtime, &scope, &source, &mut message).await; - let (status, retry) = match result { - Ok(value) => value, - Err(error) - if error.downcast_ref::() == Some(&MailboxError::StaleIncarnation) - || error.downcast_ref::() == Some(&MailboxError::Unauthorized) => - { - (403, None) - } - Err(_) => (0, None), - }; - if let Ok(peer) = self.peer(&message.to) { - self.clients - .state(&peer, if status == 202 { "available" } else { "unavailable" }); - } - if status == 202 { - let _ = runtime - .store - .acknowledge(&scope, &message.to, message.id, DeliveryState::Accepted); - continue; - } - let permanent = - matches!(status, 401 | 403 | 413 | 422) || (400..500).contains(&status) && status != 429; - let delay = backoff(attempts).max(retry.unwrap_or(0)); - let next = if permanent { - None - } else { - Some(now.saturating_add(i64::try_from(delay).unwrap_or(300))) - }; - let error = match status { - 401 => "peer_unauthenticated", - 403 => "peer_not_allowed", - 413 => "message_too_large", - 422 => "chain_limit_reached", - 429 => "inbox_full", - _ => "peer_unavailable", - }; - let _ = runtime.store.retry_outbox(&scope, &source, &message, next, error); + let (transport, runtime, lease) = (Arc::clone(&transport), Arc::clone(&runtime), Arc::clone(&lease)); + let result = tokio::spawn(super::dispatch::run(transport, runtime, lease)).await; + match result { + Ok(Err(error)) => { + tracing::error!(error=%crate::agent::diagnostics::error_class(&error), "A2A outbox dispatcher exited; restarting") } + _ => tracing::error!("A2A outbox dispatcher exited; restarting"), } + tokio::time::sleep(Duration::from_secs(1)).await; } }); Ok(()) } + pub(super) async fn deliver( + &self, + runtime: Arc, + pending: super::dispatch::Pending, + ) -> anyhow::Result<()> { + let super::dispatch::Pending { + scope, + source, + mut message, + attempts, + } = pending; + let (status, retry) = match self.attempt(&runtime, &scope, &source, &mut message).await { + Ok(value) => value, + Err(error) if super::dispatch::permanent(&error) => (403, None), + Err(_) => (0, None), + }; + if let Ok(peer) = self.peer(&message.to) { + self.clients + .state(&peer, if status == 202 { "available" } else { "unavailable" }); + } + let store = runtime.store.clone(); + crate::runtime::blocking::spawn_blocking(move || { + if status == 202 { + store.acknowledge(&scope, &message.to, message.id, DeliveryState::Accepted)?; + } else { + let permanent = (400..500).contains(&status) && !matches!(status, 408 | 429); + let delay = backoff(attempts).max(retry.unwrap_or(0)); + let next = if permanent { + None + } else { + Some( + chrono::Utc::now() + .timestamp() + .saturating_add(i64::try_from(delay).unwrap_or(300)), + ) + }; + let error = match status { + 400 => "field_invalid", + 401 => "peer_unauthenticated", + 403 => "peer_not_allowed", + 413 => "message_too_large", + 422 => "chain_limit_reached", + 429 => "inbox_full", + _ => "peer_unavailable", + }; + store.retry_outbox(&scope, &source, &message, next, error)?; + } + Ok::<_, MailboxError>(()) + }) + .await??; + Ok(()) + } } fn retry_after(response: &reqwest::Response) -> Option { let value = response.headers().get(reqwest::header::RETRY_AFTER)?.to_str().ok()?; diff --git a/src/messaging/a2a/peers.rs b/src/messaging/a2a/peers.rs index 7ec582682..a39bf4d88 100644 --- a/src/messaging/a2a/peers.rs +++ b/src/messaging/a2a/peers.rs @@ -30,9 +30,13 @@ pub fn instance(spiffe: &str) -> Result { pub fn validate(config: &A2aConfig) -> Result<()> { let mut identities = HashSet::new(); let mut fingerprints = HashSet::new(); + let mut instances = HashSet::new(); instance(&format!("spiffe://{}/prx/{}", config.trust_domain, uuid::Uuid::nil()))?; for peer in config.peers.values() { - instance(&peer.spiffe_id)?; + ensure!( + instances.insert(instance(&peer.spiffe_id)?), + "duplicate peer instance UUID" + ); ensure!(identities.insert(&peer.spiffe_id), "duplicate peer SPIFFE ID"); ensure!(!peer.owner.trim().is_empty(), "peer owner is required"); ensure!( @@ -80,3 +84,16 @@ pub(crate) fn allows(peer: &A2aPeer, target: &crate::messaging::SessionAddr, loc .any(|value| value == "*" || value == &target.session) && peer.agents.iter().any(|value| value == "*" || value == &target.agent) } + +pub(crate) fn validate_local(config: &A2aConfig, local: &super::identity::Identity) -> Result<()> { + validate(config)?; + for peer in config.peers.values() { + ensure!( + instance(&peer.spiffe_id)? != local.instance_id + && peer.spiffe_id != local.spiffe_id + && !peer.fingerprints.contains(&local.fingerprint), + "local identity cannot be a peer" + ); + } + Ok(()) +} diff --git a/src/messaging/a2a/tls.rs b/src/messaging/a2a/tls.rs index 6de1fd01d..b7e835d0c 100644 --- a/src/messaging/a2a/tls.rs +++ b/src/messaging/a2a/tls.rs @@ -1,6 +1,6 @@ //! Pinned Ed25519 verification plus real TLS CertificateVerify signatures. use super::{identity, peers}; -use crate::config::{A2aConfig, A2aPeer, Config}; +use crate::config::{A2aPeer, Config}; use anyhow::{Result, ensure}; use rustls::{ DigitallySignedStruct, DistinguishedName, Error, SignatureScheme, @@ -10,30 +10,8 @@ use rustls::{ }; use std::sync::Arc; -#[derive(Clone)] -pub(crate) struct Trust { - pub config: Arc, -} -impl std::fmt::Debug for Trust { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("PinnedA2aTrust") - } -} +pub(crate) use super::trust::Trust; impl Trust { - pub(crate) fn effective(&self) -> Result { - // CLI edits revoke connections immediately, independently of runtime reload. - let merged = crate::config::files::read_merged_toml_with_gate(&self.config.config_path)?; - let mut config: Config = merged.try_into()?; - config.config_path.clone_from(&self.config.config_path); - config.workspace_dir.clone_from(&self.config.workspace_dir); - config.a2a.validate()?; - Ok(config) - } - pub(crate) fn current(&self) -> Result { - let config = self.effective()?.a2a; - ensure!(config.messaging_enabled, "A2A messaging disabled"); - Ok(config) - } pub(crate) fn resolve(&self, cert: &CertificateDer<'_>, now: UnixTime) -> Result { let config = self.effective()?.a2a; let fingerprint = identity::fingerprint(cert.as_ref()); @@ -186,19 +164,19 @@ impl ServerCertVerifier for ServerPin { } } pub(crate) fn server(trust: Trust) -> Result { - let identity = identity::load(&trust.config)?; + let identity = trust.identity()?; check_certificate(&identity.cert, &identity.spiffe_id, UnixTime::now())?; let mut config = rustls::ServerConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider())) .with_protocol_versions(&[&rustls::version::TLS13])? .with_client_cert_verifier(Arc::new(trust)) - .with_single_cert(vec![identity.cert], identity.key)?; + .with_single_cert(vec![identity.cert.clone()], identity.key.clone_key())?; config.session_storage = Arc::new(rustls::server::NoServerSessionStorage {}); config.send_tls13_tickets = 0; config.alpn_protocols = vec![b"http/1.1".to_vec()]; Ok(config) } pub(crate) fn client(trust: Trust, peer: &A2aPeer) -> Result { - let identity = identity::load(&trust.config)?; + let identity = trust.identity()?; let mut config = rustls::ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider())) .with_protocol_versions(&[&rustls::version::TLS13])? .dangerous() @@ -206,7 +184,7 @@ pub(crate) fn client(trust: Trust, peer: &A2aPeer) -> Result { trust, spiffe: peer.spiffe_id.clone(), })) - .with_client_auth_cert(vec![identity.cert], identity.key)?; + .with_client_auth_cert(vec![identity.cert.clone()], identity.key.clone_key())?; config.resumption = rustls::client::Resumption::disabled(); config.alpn_protocols = vec![b"http/1.1".to_vec()]; Ok(reqwest::Client::builder() @@ -222,13 +200,12 @@ pub(crate) fn client(trust: Trust, peer: &A2aPeer) -> Result { } pub(crate) async fn peer_expiry(config: &Config, peer: &A2aPeer) -> Result { - let trust = Trust { - config: Arc::new(config.clone()), - }; - let response = client(trust, peer)? - .head(format!("https://{}/a2a/v1/pins", peer.address)) - .send() - .await?; + let trust = Trust::new(config); + trust.refresh_async().await?; + let address = peer.address.clone(); + let peer = peer.clone(); + let client = crate::runtime::blocking::spawn_blocking(move || client(trust, &peer)).await??; + let response = client.head(format!("https://{address}/a2a/v1/pins")).send().await?; let certificate = response .extensions() .get::() diff --git a/src/messaging/a2a/trust.rs b/src/messaging/a2a/trust.rs new file mode 100644 index 000000000..e5c63461f --- /dev/null +++ b/src/messaging/a2a/trust.rs @@ -0,0 +1,145 @@ +//! File-generation cache; refresh runs only on the blocking pool. +use super::{identity, peers}; +use crate::config::{A2aConfig, Config}; +use anyhow::{Result, ensure}; +use std::{path::PathBuf, sync::Arc, time::SystemTime}; +#[derive(Clone)] +pub(crate) struct Trust { + pub config: Arc, + snapshot: Arc>>, +} +struct Snapshot { + config: Arc, + identity: Option>, + stamp: Vec, +} +#[derive(PartialEq, Eq)] +struct FileGeneration { + path: PathBuf, + length: u64, + modified: Option, + mode: u32, + #[cfg(unix)] + inode: u64, + #[cfg(unix)] + changed: (i64, i64), +} +impl std::fmt::Debug for Trust { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("PinnedA2aTrust") + } +} +impl Trust { + pub(crate) fn new(config: &Config) -> Self { + let config = Arc::new(config.clone()); + Self { + snapshot: Arc::new(parking_lot::RwLock::new(Ok(Snapshot { + config: Arc::clone(&config), + identity: None, + stamp: Vec::new(), + }))), + config, + } + } + fn stamp(&self) -> Result> { + let mut paths = vec![self.config.config_path.clone()]; + paths.extend(crate::config::files::list_config_fragment_paths( + &self.config.config_path, + )?); + let dir = self.config.workspace_dir.join("a2a"); + paths.push(dir.clone()); + for entry in std::fs::read_dir(&dir)? { + let entry = entry?; + let name = entry.file_name(); + let name = name.to_string_lossy(); + if name == "identity.toml" || name.ends_with(".key.pem") || name.ends_with(".der") { + paths.push(entry.path()); + } + } + paths.sort(); + paths + .into_iter() + .map(|path| { + let metadata = std::fs::symlink_metadata(&path)?; + ensure!(!metadata.file_type().is_symlink(), "A2A source cannot be a symlink"); + #[cfg(unix)] + let mode = { + use std::os::unix::fs::PermissionsExt; + metadata.permissions().mode() + }; + #[cfg(not(unix))] + let mode = 0; + Ok(FileGeneration { + path, + length: metadata.len(), + modified: metadata.modified().ok(), + mode, + #[cfg(unix)] + inode: { + use std::os::unix::fs::MetadataExt; + metadata.ino() + }, + #[cfg(unix)] + changed: { + use std::os::unix::fs::MetadataExt; + (metadata.ctime(), metadata.ctime_nsec()) + }, + }) + }) + .collect() + } + pub(crate) fn refresh(&self) -> Result<()> { + let result = (|| { + let stamp = self.stamp()?; + if self + .snapshot + .read() + .as_ref() + .is_ok_and(|snapshot| snapshot.stamp == stamp) + { + return Ok(()); + } + let merged = crate::config::files::read_merged_toml_with_gate(&self.config.config_path)?; + let mut config: Config = merged.try_into()?; + config.config_path.clone_from(&self.config.config_path); + config.workspace_dir.clone_from(&self.config.workspace_dir); + let identity = identity::load(&config)?; + peers::validate_local(&config.a2a, &identity)?; + ensure!(stamp == self.stamp()?, "A2A configuration changed during refresh"); + *self.snapshot.write() = Ok(Snapshot { + config: Arc::new(config), + identity: Some(Arc::new(identity)), + stamp, + }); + Ok(()) + })(); + if result.is_err() { + *self.snapshot.write() = Err(()); + } + result + } + pub(crate) async fn refresh_async(&self) -> Result<()> { + let trust = self.clone(); + crate::runtime::blocking::spawn_blocking(move || trust.refresh()).await? + } + pub(crate) fn effective(&self) -> Result { + self.snapshot + .read() + .as_ref() + .map(|snapshot| (*snapshot.config).clone()) + .map_err(|()| anyhow::anyhow!("A2A configuration unavailable")) + } + pub(crate) fn current(&self) -> Result { + let config = self.effective()?.a2a; + ensure!(config.messaging_enabled, "A2A messaging disabled"); + Ok(config) + } + pub(crate) fn identity(&self) -> Result> { + self.snapshot + .read() + .as_ref() + .ok() + .and_then(|snapshot| snapshot.identity.clone()) + .ok_or_else(|| anyhow::anyhow!("A2A identity unavailable")) + } +} diff --git a/src/messaging/receiver.rs b/src/messaging/receiver.rs index 2ada99310..cc8eadb4f 100644 --- a/src/messaging/receiver.rs +++ b/src/messaging/receiver.rs @@ -30,21 +30,44 @@ pub(crate) fn register_idle( callback: Callback, idle: Arc bool + Send + Sync>, ) -> anyhow::Result<()> { - // Registration is idempotent for the currently running backend owner. - let Some(mut inbox) = runtime.register_backend(address)? else { - return Ok(()); - }; + // Registration and each poll own their SQLite work on the blocking pool. tokio::spawn(async move { + let backend = Arc::clone(&runtime); + let Ok(result) = crate::runtime::blocking::spawn_blocking(move || backend.register_backend(address)).await + else { + return; + }; + let mut inbox = match result { + Ok(Some(inbox)) => inbox, + Ok(None) => return, + Err(error) => { + tracing::warn!(error=%crate::agent::diagnostics::error_class(&error), "session mailbox registration refused"); + return; + } + }; let mut interval = tokio::time::interval(std::time::Duration::from_millis(100)); loop { interval.tick().await; - if !inbox.live() { + let idle = Arc::clone(&idle); + let Ok((returned, result)) = crate::runtime::blocking::spawn_blocking(move || { + let result = if !inbox.live() { + None + } else if !idle() { + Some(Ok(Vec::new())) + } else { + Some(inbox.poll()) + }; + (inbox, result) + }) + .await + else { break; - } - if !idle() { - continue; - } - match inbox.poll() { + }; + inbox = returned; + let Some(result) = result else { + break; + }; + match result { Ok(inputs) => { for input in inputs { let retained = input.clone(); @@ -52,7 +75,9 @@ pub(crate) fn register_idle( && let Err(error) = callback(input).await { if error.is::() { - let _ = runtime.requeue(retained); + let runtime = Arc::clone(&runtime); + let _ = + crate::runtime::blocking::spawn_blocking(move || runtime.requeue(retained)).await; continue; } tracing::warn!(error=%crate::agent::diagnostics::error_class(&error),"session mailbox turn refused"); diff --git a/src/messaging/runtime.rs b/src/messaging/runtime.rs index d93739ddd..43041fd09 100644 --- a/src/messaging/runtime.rs +++ b/src/messaging/runtime.rs @@ -95,12 +95,10 @@ impl MessagingRuntime { &[b"prx-mailbox-pins-v1"], ); let instance = if config.a2a.messaging_enabled { - super::a2a::identity::load(config)?.instance_id.to_string() + super::a2a::identity::load(config)?.spiffe_id } else { - super::a2a::identity::optional(config)?.map_or_else( - || config.a2a.agent_id.clone(), - |identity| identity.instance_id.to_string(), - ) + super::a2a::identity::optional(config)? + .map_or_else(|| config.a2a.agent_id.clone(), |identity| identity.spiffe_id) }; let store = SqliteMailbox::new( memory, @@ -313,21 +311,25 @@ struct LocalResolver { #[async_trait] impl MailboxResolver for LocalResolver { async fn resolve(&self, target: &SessionAddr) -> MailboxResult { - if target.instance != self.runtime.instance { - return super::a2a::RemoteTransport::new(&self.runtime.config.read()).destination( - &self.runtime, - &self.source, - target, - ); - } - let authority = MailboxAuthority::local(self.runtime.workspace.clone(), self.source.clone(), target.clone())?; - let scope = self.runtime.resolve_scope(target)?; - let pin = self.runtime.store.recipient_pin(&authority, &scope, &target.session)?; - Ok(MailboxDestination { - authority, - pin, - pin_expires_at: chrono::Utc::now().timestamp() + 300, + let runtime = Arc::clone(&self.runtime); + let source = self.source.clone(); + let target = target.clone(); + crate::runtime::blocking::spawn_blocking(move || { + if target.instance != runtime.instance { + return super::a2a::RemoteTransport::new(&runtime.config.read()) + .destination(&runtime, &source, &target); + } + let authority = MailboxAuthority::local(runtime.workspace.clone(), source.clone(), target.clone())?; + let scope = runtime.resolve_scope(&target)?; + let pin = runtime.store.recipient_pin(&authority, &scope, &target.session)?; + Ok(MailboxDestination { + authority, + pin, + pin_expires_at: chrono::Utc::now().timestamp() + 300, + }) }) + .await + .map_err(|_| MailboxError::Storage)? } } diff --git a/src/messaging/types.rs b/src/messaging/types.rs index 8cb845698..36bdbfd8d 100644 --- a/src/messaging/types.rs +++ b/src/messaging/types.rs @@ -10,7 +10,7 @@ pub const MAX_BODY_BYTES: usize = 256 * 1024; /// Logical session address. No execution-run field. #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct SessionAddr { - /// Persisted `a2a.agent_id`. + /// Full SPIFFE ID when A2A identity exists; local-only agent id otherwise. pub instance: String, /// Authenticated owner, never channel-derived. pub owner: String, diff --git a/src/runtime/mailbox_child.rs b/src/runtime/mailbox_child.rs index 79fb61960..1ff29d9d0 100644 --- a/src/runtime/mailbox_child.rs +++ b/src/runtime/mailbox_child.rs @@ -36,47 +36,58 @@ impl MailboxChildSource { input: MessageInput, live: Option, ) -> Result { - let runtime = MessagingRuntime::for_config(&parent.generation.effective)?; - input.verify(&runtime)?; - let mailbox_scope = runtime.resolve_scope(&input.message.to)?; + let parent_copy = Arc::clone(parent); + let record_copy = record; + let input_copy = input.clone(); + let (runtime, mailbox_scope, record, root_agent) = crate::runtime::blocking::spawn_blocking(move || { + let parent = parent_copy; + let record = record_copy; + let input = input_copy; + let runtime = MessagingRuntime::for_config(&parent.generation.effective)?; + input.verify(&runtime)?; + let mailbox_scope = runtime.resolve_scope(&input.message.to)?; + let memory = Arc::clone(&parent.memory); + let stored = memory + .child_session_store() + .context("child storage unavailable")? + .sessions(&record.workspace, &record.owner)? + .into_iter() + .find(|candidate| candidate.session_key == record.session_key) + .context("child_session_unknown")?; + ensure!( + stored.parent_session == record.parent_session && stored.agent == record.agent, + "child receiver changed" + ); + let record = stored; + ensure!( + input.auto_start() + && input.message.to.owner == record.owner + && input.message.to.session == record.session_key + && input.message.to.agent == record.agent, + "mailbox receiver differs from persisted child" + ); + let root_agent = runtime + .store + .logical_agent(&record.workspace, &record.owner, &record.parent_session)? + .unwrap_or_else(|| "main".to_owned()); + Ok::<_, anyhow::Error>((runtime, mailbox_scope, record, root_agent)) + }) + .await??; let memory = Arc::clone(&parent.memory); - let stored = memory - .child_session_store() - .context("child storage unavailable")? - .sessions(&record.workspace, &record.owner)? - .into_iter() - .find(|candidate| candidate.session_key == record.session_key) - .context("child_session_unknown")?; - ensure!( - stored.parent_session == record.parent_session && stored.agent == record.agent, - "child receiver changed" - ); - let record = stored; - ensure!( - input.auto_start() - && input.message.to.owner == record.owner - && input.message.to.session == record.session_key - && input.message.to.agent == record.agent, - "mailbox receiver differs from persisted child" - ); - let pinned = &parent.generation.effective; - let mut current = if pinned.config_path.exists() { - let directory = pinned - .config_path - .parent() - .and_then(std::path::Path::to_str) - .context("receiver config directory unavailable")?; - crate::config::Config::load_existing_read_only_with_config_dir(Some(directory)).await? - } else { - pinned.as_ref().clone() - }; - current.workspace_dir = pinned.workspace_dir.clone(); - current.config_path = pinned.config_path.clone(); + let pinned = Arc::clone(&parent.generation.effective); + let mut current = crate::runtime::blocking::spawn_blocking(move || { + if pinned.config_path.try_exists()? { + crate::config::Config::load_from_path(&pinned.config_path, pinned.workspace_dir.clone()) + } else { + Ok(pinned.as_ref().clone()) + } + }) + .await??; + current + .workspace_dir + .clone_from(&parent.generation.effective.workspace_dir); + current.config_path.clone_from(&parent.generation.effective.config_path); let config = ¤t; - let root_agent = runtime - .store - .logical_agent(&record.workspace, &record.owner, &record.parent_session)? - .unwrap_or_else(|| "main".to_owned()); let root_level = if root_agent == "main" { config.autonomy.level } else { @@ -90,44 +101,60 @@ impl MailboxChildSource { let now = crate::security::agent_level::named_child_level(config, Some(&record.agent), root_level) .unwrap_or(root_level); let level = record.level.min(now); - let publication = publication::fresh(parent, level, ¤t)?; - let catalog = &publication.provider_catalog; - let named = config.agents.get(&record.agent).filter(|agent| { - crate::providers::ProviderId::of(&agent.provider) == crate::providers::ProviderId::of(&record.provider) - }); - let credential = named.map_or_else( - || crate::providers::selection::credential_for(config, &record.provider), - |agent| { - agent.credential_ref.as_ref().map_or_else( - || { - if agent.api_key.as_ref().is_some_and(|key| !key.trim().is_empty()) { - crate::providers::credentials::CredentialRef::LegacyInline( - crate::providers::credentials::LegacySlot::Agent(record.agent.clone()), - ) - } else { - crate::providers::selection::credential_for(config, &record.provider) - } - }, - |id| crate::providers::credentials::CredentialRef::Profile { id: id.clone() }, - ) - }, - ); - let resolved = crate::providers::selection::check_with( - config, - catalog, - &record.provider, - &record.model, - credential, - &crate::providers::catalog::Requirement::chat(), - crate::providers::catalog::UnknownPolicy::Invocation, - )?; - let route = crate::providers::selection::route_target(catalog, &record.provider, &record.model)?.cloned(); - let provider = Arc::from(crate::providers::create_routed_provider_for( - &resolved, - catalog, - config, - &crate::providers::provider_runtime_options_from_config(config), - )?); + let retained = Arc::clone(parent); + let configured = current.clone(); + let agent = record.agent.clone(); + let publication = + crate::runtime::blocking::spawn_blocking(move || publication::fresh(&retained, level, &configured, &agent)) + .await??; + let configured = current; + let selected = record.clone(); + let published = Arc::clone(&publication); + let (resolved, route, provider) = crate::runtime::blocking::spawn_blocking(move || { + let config = &configured; + let record = selected; + let publication = published; + let catalog = &publication.provider_catalog; + let named = config.agents.get(&record.agent).filter(|agent| { + crate::providers::ProviderId::of(&agent.provider) == crate::providers::ProviderId::of(&record.provider) + }); + let credential = named.map_or_else( + || crate::providers::selection::credential_for(config, &record.provider), + |agent| { + agent.credential_ref.as_ref().map_or_else( + || { + if agent.api_key.as_ref().is_some_and(|key| !key.trim().is_empty()) { + crate::providers::credentials::CredentialRef::LegacyInline( + crate::providers::credentials::LegacySlot::Agent(record.agent.clone()), + ) + } else { + crate::providers::selection::credential_for(config, &record.provider) + } + }, + |id| crate::providers::credentials::CredentialRef::Profile { id: id.clone() }, + ) + }, + ); + let resolved = crate::providers::selection::check_with( + config, + catalog, + &record.provider, + &record.model, + credential, + &crate::providers::catalog::Requirement::chat(), + crate::providers::catalog::UnknownPolicy::Invocation, + )?; + let route = crate::providers::selection::route_target(catalog, &record.provider, &record.model)?.cloned(); + let provider: Arc = + Arc::from(crate::providers::create_routed_provider_for( + &resolved, + catalog, + config, + &crate::providers::provider_runtime_options_from_config(config), + )?); + Ok::<_, anyhow::Error>((resolved, route, provider)) + }) + .await??; let event_id = input .receipt .adopted_message_event_id diff --git a/src/runtime/mailbox_child/driver.rs b/src/runtime/mailbox_child/driver.rs index ff5f1393c..3f2991cf0 100644 --- a/src/runtime/mailbox_child/driver.rs +++ b/src/runtime/mailbox_child/driver.rs @@ -58,14 +58,20 @@ pub(crate) fn watch(parent: Arc, owner: String, root: String let mut interval = tokio::time::interval(std::time::Duration::from_millis(100)); loop { interval.tick().await; - if runtime.store.validate_scope(&scope, &address).is_err() { - break; - } + let reader = Arc::clone(&runtime); + let captured_scope = scope.clone(); + let target = address.clone(); let parent = Arc::clone(&host.parent.read()); - let Some(store) = parent.memory.child_session_store() else { - break; - }; - let Ok(records) = store.sessions(&runtime.workspace, &owner) else { + let selected_owner = owner.clone(); + let Ok(Ok(Some(records))) = crate::runtime::blocking::spawn_blocking(move || { + if reader.store.validate_scope(&captured_scope, &target).is_err() { + return Ok(None); + } + let store = parent.memory.child_session_store().context("child store unavailable")?; + Ok::<_, anyhow::Error>(Some(store.sessions(&reader.workspace, &selected_owner)?)) + }) + .await + else { break; }; for mut record in records @@ -115,11 +121,15 @@ pub(crate) fn watch(parent: Arc, owner: String, root: String let mut interval = tokio::time::interval(std::time::Duration::from_millis(100)); loop { interval.tick().await; - let records = parent - .memory - .child_session_store() - .context("child store unavailable")? - .sessions(&record.workspace, &record.owner)?; + let memory = Arc::clone(&parent.memory); + let receiver = record.clone(); + let records = crate::runtime::blocking::spawn_blocking(move || { + memory + .child_session_store() + .context("child store unavailable")? + .sessions(&receiver.workspace, &receiver.owner) + }) + .await??; let Some(current) = records.iter().find(|current| current.session_key == record.session_key) else { diff --git a/src/runtime/mailbox_child/publication.rs b/src/runtime/mailbox_child/publication.rs index 8a06945fc..1e11e3431 100644 --- a/src/runtime/mailbox_child/publication.rs +++ b/src/runtime/mailbox_child/publication.rs @@ -5,6 +5,7 @@ pub(super) fn fresh( parent: &Arc, level: crate::security::AutonomyLevel, config: &crate::config::Config, + agent: &str, ) -> anyhow::Result> { use crate::decision_engine::prediction::factory::{DecisionBackendFactory, FactoryDeps}; let generation = crate::config::ConfigGeneration::for_child(config)?; @@ -17,14 +18,19 @@ pub(super) fn fresh( parent.surface, &config.tool_tiering.at_level(level, security.evaluation_sandbox), ); - policy - .direct_names - .extend(parent.publication_policy.direct_names.iter().cloned()); - policy - .excluded_names - .extend(parent.publication_policy.excluded_names.iter().cloned()); - if level != crate::security::AutonomyLevel::Full { - policy.allowed_tools = parent.publication_policy.allowed_tools.clone(); + if level != crate::security::AutonomyLevel::Full + && let Some(named) = config.agents.get(agent) + && !named.allowed_tools.is_empty() + && !named.allowed_tools.iter().any(|name| name.trim() == "*") + { + let mut allowed: std::collections::BTreeSet<_> = named + .allowed_tools + .iter() + .map(|name| name.trim().to_owned()) + .filter(|name| !name.is_empty()) + .collect(); + allowed.insert(crate::tools::TRANSCRIPT_HISTORY_LOOKUP_TOOL_NAME.to_owned()); + policy.allowed_tools = Some(allowed); } let policy_version = crate::runtime::turn_publication::service::pinned_policy_version( config, diff --git a/src/tools/sessions_send.rs b/src/tools/sessions_send.rs index 04072dc6e..b8a503e83 100644 --- a/src/tools/sessions_send.rs +++ b/src/tools/sessions_send.rs @@ -126,10 +126,10 @@ impl Tool for SessionsSendTool { fn parameters_schema(&self) -> serde_json::Value { if self.mailbox.is_some() || self.messaging.is_some() { - return json!({"oneOf":[ - {"type":"object","additionalProperties":false,"properties":{"run_id":{"type":"string","minLength":1},"message":{"type":"string","minLength":1}},"required":["run_id","message"]}, - {"type":"object","additionalProperties":false,"properties":{"to":{"oneOf":[crate::messaging::send::target_schema(),{"type":"string","minLength":1}]},"message":{"type":"string","minLength":1}},"required":["to","message"]} - ]}); + return json!({"type":"object","additionalProperties":false, + "properties":{"run_id":{"type":"string","minLength":1}, + "to":{"oneOf":[crate::messaging::send::target_schema(),{"type":"string","minLength":1}]}, + "message":{"type":"string","minLength":1}},"required":["message"]}); } json!({ "type": "object", @@ -149,7 +149,18 @@ impl Tool for SessionsSendTool { }) } + fn execution_parameters_schema(&self) -> Option> { + let mut schema = self.parameters_schema(); + if let Some(object) = schema.as_object_mut() { + object.insert("oneOf".into(), json!([{"required":["run_id"]},{"required":["to"]}])); + } + Some(Arc::new(schema)) + } + async fn execute(&self, args: serde_json::Value) -> anyhow::Result { + if args.get("to").is_some() == args.get("run_id").is_some() { + return Err(InvalidSendSelector.into()); + } if args.get("to").is_some() { if let Some(config) = &self.messaging { let runtime = crate::messaging::runtime::MessagingRuntime::for_config(config)?; @@ -639,3 +650,7 @@ mod tests { assert!(result.error.unwrap().contains("already completed")); } } + +#[derive(Debug, thiserror::Error)] +#[error("invalid_arguments: exactly one of run_id and to is required")] +struct InvalidSendSelector; From 27ce7daa1f8cc91dff280370ebe3b6b8e1b35a9b Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 17:56:55 +0400 Subject: [PATCH 0008/1567] fix(messaging): issue sender authority and diagnose mailbox refusals --- docs/configuration.md | 15 + src/memory/sqlite/mailbox/accept.rs | 10 +- src/memory/sqlite/mailbox/adopt.rs | 8 +- src/memory/sqlite/mailbox/deliver.rs | 8 +- src/memory/sqlite/mailbox/local_runtime.rs | 14 +- src/memory/sqlite/mailbox/model.rs | 6 +- src/memory/sqlite/mailbox/outbox.rs | 8 +- src/memory/sqlite/mailbox/pin.rs | 4 +- src/memory/sqlite/mailbox/publish.rs | 4 +- src/memory/sqlite/mailbox/sender.rs | 30 +- src/memory/sqlite/mailbox/stream.rs | 4 +- src/messaging/a2a/outbound.rs | 5 +- src/messaging/mailbox.rs | 16 +- src/messaging/mailbox/authorization.rs | 63 + src/messaging/runtime.rs | 8 +- src/session_worker/mailbox.rs | 4 +- src/session_worker/mailbox_parent.rs | 8 +- src/session_worker/runner/steering.rs | 6 +- src/tools/execution.rs | 4291 +---------------- src/tools/execution/section_1.rs | 1706 +++++++ src/tools/execution/section_2.rs | 1037 ++++ src/tools/execution/section_3.rs | 1549 ++++++ src/tools/sessions_send.rs | 11 +- tests/architecture_boundaries/helpers.rs | 9 + .../architecture_boundaries/loop_contracts.rs | 2 +- 25 files changed, 4499 insertions(+), 4327 deletions(-) create mode 100644 src/messaging/mailbox/authorization.rs create mode 100644 src/tools/execution/section_1.rs create mode 100644 src/tools/execution/section_2.rs create mode 100644 src/tools/execution/section_3.rs diff --git a/docs/configuration.md b/docs/configuration.md index ae7c4cfb4..fdadc6741 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -3524,3 +3524,18 @@ roots receive child approval requests in their owner-scoped approval inbox and review them through the root session endpoint; the wait remains four minutes. An rf root uses its connected live surface and configured wait. Without a live approval surface the call is denied with `no_approval_surface`. + +Mailbox authorization refusals keep the public `mailbox_unauthorized` error and +emit a typed, content-free `reason` at WARN. Reasons identify missing caller +receipts, owner/instance/agent mismatches, unknown receivers, disabled inbound +messaging, missing peers and scope-binding failures; no message, token or key +is logged. Local targets default to the authenticated sender's owner. Remote +targets use the full SPIFFE ID and the receiving instance's actual owner, as +explicitly authorized by that instance's peer grant. + +Fresh `prx init` starts with no paired bearer. A serialized empty +`gateway.paired_tokens = []` does not block pairing. `prx token issue --out ...` +explicitly installs a bearer and records its hash in this list; the gateway +then reports pairing ACTIVE and accepts that bearer instead of offering a new +one-time pairing code. Keep and use the issued file; do not remove valid +paired credentials just to request a second pairing. diff --git a/src/memory/sqlite/mailbox/accept.rs b/src/memory/sqlite/mailbox/accept.rs index e5c0f53de..14ace6d32 100644 --- a/src/memory/sqlite/mailbox/accept.rs +++ b/src/memory/sqlite/mailbox/accept.rs @@ -19,7 +19,9 @@ impl SqliteMailbox { pub fn accept(&self, authority: &MailboxAuthority, mut message: PrxMessage) -> MailboxResult { authority.authorize(&message)?; if message.to.instance != self.local_instance { - return Err(MailboxError::Unauthorized); + return Err(crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::LocalInstanceMismatch, + )); } // Identity/origin/auth are runtime-owned, never trusted from the wire. message.from = authority.source.clone(); @@ -127,7 +129,11 @@ impl SqliteMailbox { reserve_gaps(&tx, &stream, &message)?; receipt::derive_chain(&tx, &authority.workspace_id, &claims.scope.owner_id, &mut message)?; let remote = if authority.origin == MessageOrigin::RemotePeer { - let auth = authority.auth.as_ref().ok_or(MailboxError::Unauthorized)?; + let auth = authority.auth.as_ref().ok_or_else(|| { + crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::PeerAuthenticationMissing, + ) + })?; Some(RemotePeerAttr { issuer: auth.issuer.clone(), subject: auth.subject.clone(), diff --git a/src/memory/sqlite/mailbox/adopt.rs b/src/memory/sqlite/mailbox/adopt.rs index ce901fe8d..46a5bcb68 100644 --- a/src/memory/sqlite/mailbox/adopt.rs +++ b/src/memory/sqlite/mailbox/adopt.rs @@ -30,7 +30,9 @@ impl SqliteMailbox { return Err(MailboxError::ReceiptExpired); } if saved.scope != *scope { - return Err(MailboxError::Unauthorized); + return Err(crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::AdoptScopeMismatch, + )); } saved.matches(&tx, &scope.workspace_id, delivery.message())?; if saved.state == DeliveryState::Consumed { @@ -108,7 +110,9 @@ impl SqliteMailbox { }) .map_err(storage_error)?; if owner.as_deref() != Some(scope.owner_id.as_str()) { - return Err(MailboxError::Unauthorized); + return Err(crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::AdoptScopeMismatch, + )); } let event_id = Uuid::new_v4(); let reference = EventRef { diff --git a/src/memory/sqlite/mailbox/deliver.rs b/src/memory/sqlite/mailbox/deliver.rs index f8cd89c12..4eb9d28c6 100644 --- a/src/memory/sqlite/mailbox/deliver.rs +++ b/src/memory/sqlite/mailbox/deliver.rs @@ -62,7 +62,9 @@ impl SqliteMailbox { pub fn deliver(&self, scope: &MailboxScope, address: &SessionAddr) -> MailboxResult> { if address.instance != self.local_instance { - return Err(MailboxError::Unauthorized); + return Err(crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::DeliverScopeMismatch, + )); } let now = self.clock.now(); if now < 0 { @@ -278,7 +280,9 @@ impl SqliteMailbox { let tx = Transaction::new_unchecked(&writer, TransactionBehavior::Immediate).map_err(storage_error)?; check_scope(&tx, scope, address, None, true)?; if address.instance != self.local_instance { - return Err(MailboxError::Unauthorized); + return Err(crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::DeliverScopeMismatch, + )); } let runtime = std::sync::Arc::clone(&self.memory.mailbox_runtime); runtime.set_execution(address.clone(), scope.clone(), Some(run.clone())); diff --git a/src/memory/sqlite/mailbox/local_runtime.rs b/src/memory/sqlite/mailbox/local_runtime.rs index 3e7638346..01b081b16 100644 --- a/src/memory/sqlite/mailbox/local_runtime.rs +++ b/src/memory/sqlite/mailbox/local_runtime.rs @@ -102,7 +102,9 @@ impl SqliteMailbox { ) -> MailboxResult { crate::messaging::mailbox::validate_address(address)?; if address.instance != self.local_instance { - return Err(MailboxError::Unauthorized); + return Err(crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::LocalInstanceMismatch, + )); } let writer = self.memory.pool.write(); let tx = Transaction::new_unchecked(&writer, TransactionBehavior::Immediate).map_err(storage_error)?; @@ -116,18 +118,22 @@ impl SqliteMailbox { } let actual:Option=tx.query_row("SELECT CASE WHEN s.agent_key='m' THEN 'main' ELSE substr(s.agent_key,3) END FROM message_events e JOIN agent_scopes s ON s.scope_id=e.ma_scope_id WHERE e.workspace_id=?1 AND e.owner_id=?2 AND e.session_key=?3 ORDER BY e.id DESC LIMIT 1",params![workspace,address.owner,address.session],|r|r.get(0)).optional().map_err(storage_error)?; if actual.as_deref().is_some_and(|agent| agent != address.agent) { - return Err(MailboxError::Unauthorized); + return Err(crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::ReceiverAgentMismatch, + )); } let known:bool=tx.query_row("SELECT EXISTS(SELECT 1 FROM message_events WHERE workspace_id=?1 AND owner_id=?2 AND session_key=?3) OR EXISTS(SELECT 1 FROM sessions WHERE owner_id=?2 AND session_key=?3) OR EXISTS(SELECT 1 FROM child_sessions WHERE workspace_id=?1 AND owner_id=?2 AND session_id=?3)",params![workspace,address.owner,address.session],|r|r.get(0)).map_err(storage_error)?; if !known && !registered { - return Err(MailboxError::Unauthorized); + return Err(crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::ReceiverUnknown, + )); } let key = if address.agent == "main" { PartitionKey::Main } else { let agent = crate::config::agent_name::AgentName::parse(&address.agent) .map_err(|_| MailboxError::InvalidAddress)?; - let incarnation:String=tx.query_row("SELECT incarnation FROM agent_incarnations WHERE workspace_id=?1 AND owner_id=?2 AND agent_key=?3 AND state='active'",params![workspace,address.owner,format!("n:{}",address.agent)],|r|r.get(0)).optional().map_err(storage_error)?.ok_or(MailboxError::Unauthorized)?; + let incarnation:String=tx.query_row("SELECT incarnation FROM agent_incarnations WHERE workspace_id=?1 AND owner_id=?2 AND agent_key=?3 AND state='active'",params![workspace,address.owner,format!("n:{}",address.agent)],|r|r.get(0)).optional().map_err(storage_error)?.ok_or_else(|| crate::messaging::mailbox::unauthorized(crate::messaging::mailbox::UnauthorizedReason::ReceiverAgentInactive))?; PartitionKey::Named { name: agent, incarnation: uuid::Uuid::parse_str(&incarnation).map_err(|_| MailboxError::CorruptState)?, diff --git a/src/memory/sqlite/mailbox/model.rs b/src/memory/sqlite/mailbox/model.rs index f590cecb6..828825623 100644 --- a/src/memory/sqlite/mailbox/model.rs +++ b/src/memory/sqlite/mailbox/model.rs @@ -44,7 +44,11 @@ impl Common { in_reply_to: message.in_reply_to, hop_count: message.hop_count, ancestry: message.ancestry.clone(), - origin: message.origin.ok_or(MailboxError::Unauthorized)?, + origin: message.origin.ok_or_else(|| { + crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::MessageOriginMissing, + ) + })?, auth: message.auth.clone(), remote_peer, }) diff --git a/src/memory/sqlite/mailbox/outbox.rs b/src/memory/sqlite/mailbox/outbox.rs index 252d56926..4e81c2bc7 100644 --- a/src/memory/sqlite/mailbox/outbox.rs +++ b/src/memory/sqlite/mailbox/outbox.rs @@ -28,7 +28,9 @@ impl SqliteMailbox { let tx = Transaction::new_unchecked(&writer, TransactionBehavior::Immediate).map_err(storage_error)?; check_scope(&tx, scope, address, None, true)?; if address.instance != self.local_instance { - return Err(MailboxError::Unauthorized); + return Err(crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::OutboxScopeMismatch, + )); } let mut query=tx.prepare("SELECT o.id,o.stream_id,o.seq,o.idempotency_key,o.message_id,o.body_bytes,o.envelope_meta FROM prx_mailbox_outbox o WHERE o.stream_id IN(SELECT stream_id FROM prx_mailbox_seq WHERE sender_ma_scope_id=?1 AND from_addr=?2) AND o.state IN(0,1) AND o.ma_scope_id=?1 ORDER BY o.stream_id,o.seq").map_err(storage_error)?; let rows = query @@ -148,7 +150,9 @@ impl SqliteMailbox { let found=tx.query_row("SELECT o.id,o.stream_id,o.state,o.envelope_meta FROM prx_mailbox_parents p JOIN prx_mailbox_outbox o ON o.id=p.id WHERE p.workspace_id=?1 AND p.owner_id=?2 AND p.message_id=?3 AND o.ma_scope_id=?4",params![scope.workspace_id,scope.owner_id,message_id.as_bytes().as_slice(),scope.scope_id.to_string()],|r|Ok((r.get::<_,i64>(0)?,r.get::<_,i64>(1)?,r.get::<_,i64>(2)?,r.get::<_,String>(3)?))).optional().map_err(storage_error)?.ok_or(MailboxError::InvalidMetadata)?; let stream = stream::load(&tx, found.1)?; if stream.sender.as_ref() != Some(scope) || *peer != stream.to || stream.from.instance != self.local_instance { - return Err(MailboxError::Unauthorized); + return Err(crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::OutboxScopeMismatch, + )); } check_scope(&tx, scope, &stream.from, None, true)?; let mut meta: OutboxMeta = decode(&found.3)?; diff --git a/src/memory/sqlite/mailbox/pin.rs b/src/memory/sqlite/mailbox/pin.rs index 705637fe6..6f0752209 100644 --- a/src/memory/sqlite/mailbox/pin.rs +++ b/src/memory/sqlite/mailbox/pin.rs @@ -37,7 +37,9 @@ impl SqliteMailbox { canonical_session_key: &str, ) -> MailboxResult { if authority.destination.instance != self.local_instance || authority.workspace_id != scope.workspace_id { - return Err(MailboxError::Unauthorized); + return Err(crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::PinScopeMismatch, + )); } bounded(canonical_session_key, 512)?; let writer = self.memory.pool.write(); diff --git a/src/memory/sqlite/mailbox/publish.rs b/src/memory/sqlite/mailbox/publish.rs index 92a53a831..6658bfac1 100644 --- a/src/memory/sqlite/mailbox/publish.rs +++ b/src/memory/sqlite/mailbox/publish.rs @@ -76,7 +76,9 @@ impl SqliteMailbox { || authority.workspace_id != sender.workspace_id || authority.origin == MessageOrigin::RemotePeer { - return Err(MailboxError::Unauthorized); + return Err(crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::PublishScopeMismatch, + )); } message.from = authority.source.clone(); message.origin = Some(MessageOrigin::LocalModel); diff --git a/src/memory/sqlite/mailbox/sender.rs b/src/memory/sqlite/mailbox/sender.rs index 8b93753d2..d8249bf0f 100644 --- a/src/memory/sqlite/mailbox/sender.rs +++ b/src/memory/sqlite/mailbox/sender.rs @@ -31,8 +31,15 @@ impl SqliteMailboxSender { inherited: Option, ) -> MailboxResult { crate::messaging::mailbox::validate_address(&source)?; - if source.instance != store.local_instance || scope.owner_id != source.owner { - return Err(MailboxError::Unauthorized); + if source.instance != store.local_instance { + return Err(crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::LocalInstanceMismatch, + )); + } + if scope.owner_id != source.owner { + return Err(crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::SenderOwnerMismatch, + )); } store.validate_scope(&scope, &source)?; Ok(Self { @@ -79,11 +86,20 @@ impl SqliteMailboxSender { PendingSend { text, _lease: lease } }; let resolved = self.resolver.resolve(&target).await?; - if resolved.authority.source != self.source - || resolved.authority.workspace_id != self.scope.workspace_id - || resolved.authority.destination != target - { - return Err(MailboxError::Unauthorized); + if resolved.authority.source != self.source { + return Err(crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::SenderIdentityMismatch, + )); + } + if resolved.authority.workspace_id != self.scope.workspace_id { + return Err(crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::SenderWorkspaceMismatch, + )); + } + if resolved.authority.destination != target { + return Err(crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::DestinationMismatch, + )); } let mut message = PrxMessage { id, diff --git a/src/memory/sqlite/mailbox/stream.rs b/src/memory/sqlite/mailbox/stream.rs index 1480d6eb2..993a84515 100644 --- a/src/memory/sqlite/mailbox/stream.rs +++ b/src/memory/sqlite/mailbox/stream.rs @@ -150,7 +150,9 @@ impl SqliteMailbox { } let address = if role == Role::Sender { &stream.from } else { &stream.to }; if address.instance != self.local_instance || scope.owner_id != address.owner { - return Err(MailboxError::Unauthorized); + return Err(crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::StreamScopeMismatch, + )); } check_scope(conn, scope, address, None, true)?; let previous = if role == Role::Sender { diff --git a/src/messaging/a2a/outbound.rs b/src/messaging/a2a/outbound.rs index b9d3c4e63..0a65089f5 100644 --- a/src/messaging/a2a/outbound.rs +++ b/src/messaging/a2a/outbound.rs @@ -27,7 +27,10 @@ impl RemoteTransport { .values() .find(|peer| peer.spiffe_id == target.instance) .cloned() - .ok_or_else(|| MailboxError::Unauthorized.into()) + .ok_or_else(|| { + crate::messaging::mailbox::unauthorized(crate::messaging::mailbox::UnauthorizedReason::PeerAbsent) + .into() + }) } pub(crate) fn destination( &self, diff --git a/src/messaging/mailbox.rs b/src/messaging/mailbox.rs index bc2868d48..de4f83774 100644 --- a/src/messaging/mailbox.rs +++ b/src/messaging/mailbox.rs @@ -1,6 +1,9 @@ //! Dormant mailbox contracts. Authority is runtime input, never deserialized //! from a model/tool request. SQLite owns all durable mutations. +mod authorization; +pub(crate) use authorization::{UnauthorizedReason, unauthorized}; + use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use uuid::Uuid; @@ -129,8 +132,11 @@ impl MailboxAuthority { validate_address(&source)?; validate_address(&destination)?; bounded(&workspace_id, 4096)?; - if source.instance != destination.instance || source.owner != destination.owner { - return Err(MailboxError::Unauthorized); + if source.instance != destination.instance { + return Err(unauthorized(UnauthorizedReason::LocalInstanceMismatch)); + } + if source.owner != destination.owner { + return Err(unauthorized(UnauthorizedReason::LocalOwnerMismatch)); } Ok(Self { workspace_id, @@ -154,7 +160,7 @@ impl MailboxAuthority { validate_address(&source)?; validate_address(&destination)?; if auth.method != "mtls" { - return Err(MailboxError::Unauthorized); + return Err(unauthorized(UnauthorizedReason::PeerAuthenticationMethod)); } Ok(Self { workspace_id, @@ -173,7 +179,7 @@ impl MailboxAuthority { validate_address(&source)?; validate_address(&destination)?; if source.instance == destination.instance && source.owner != destination.owner { - return Err(MailboxError::Unauthorized); + return Err(unauthorized(UnauthorizedReason::LocalOwnerMismatch)); } Ok(Self { workspace_id, @@ -196,7 +202,7 @@ impl MailboxAuthority { pub(crate) fn authorize(&self, message: &PrxMessage) -> MailboxResult<()> { if message.to != self.destination { - return Err(MailboxError::Unauthorized); + return Err(unauthorized(UnauthorizedReason::DestinationMismatch)); } Ok(()) } diff --git a/src/messaging/mailbox/authorization.rs b/src/messaging/mailbox/authorization.rs new file mode 100644 index 000000000..54719bf75 --- /dev/null +++ b/src/messaging/mailbox/authorization.rs @@ -0,0 +1,63 @@ +//! Content-free diagnostics at the exact failing authorization boundary. +use super::MailboxError; +#[derive(Debug, Clone, Copy)] +pub(crate) enum UnauthorizedReason { + CallerMissing, + WorkerSenderUnavailable, + LocalInstanceMismatch, + LocalOwnerMismatch, + PeerAuthenticationMethod, + DestinationMismatch, + SenderOwnerMismatch, + SenderIdentityMismatch, + SenderWorkspaceMismatch, + ReceiverAgentMismatch, + ReceiverUnknown, + ReceiverAgentInactive, + InboundDisabledOrConfigInvalid, + PeerAbsent, + MessageOriginMissing, + PeerAuthenticationMissing, + PinScopeMismatch, + OutboxScopeMismatch, + PublishScopeMismatch, + StreamScopeMismatch, + AdoptScopeMismatch, + DeliverScopeMismatch, + WorkerScopeMismatch, + WorkerSenderMismatch, +} +impl UnauthorizedReason { + pub(crate) const fn as_str(self) -> &'static str { + match self { + Self::CallerMissing => "caller_missing", + Self::WorkerSenderUnavailable => "worker_sender_unavailable", + Self::LocalInstanceMismatch => "local_instance_mismatch", + Self::LocalOwnerMismatch => "local_owner_mismatch", + Self::PeerAuthenticationMethod => "peer_authentication_method", + Self::DestinationMismatch => "destination_mismatch", + Self::SenderOwnerMismatch => "sender_owner_mismatch", + Self::SenderIdentityMismatch => "sender_identity_mismatch", + Self::SenderWorkspaceMismatch => "sender_workspace_mismatch", + Self::ReceiverAgentMismatch => "receiver_agent_mismatch", + Self::ReceiverUnknown => "receiver_unknown", + Self::ReceiverAgentInactive => "receiver_agent_inactive", + Self::InboundDisabledOrConfigInvalid => "inbound_disabled_or_config_invalid", + Self::PeerAbsent => "peer_absent", + Self::MessageOriginMissing => "message_origin_missing", + Self::PeerAuthenticationMissing => "peer_authentication_missing", + Self::PinScopeMismatch => "pin_scope_mismatch", + Self::OutboxScopeMismatch => "outbox_scope_mismatch", + Self::PublishScopeMismatch => "publish_scope_mismatch", + Self::StreamScopeMismatch => "stream_scope_mismatch", + Self::AdoptScopeMismatch => "adopt_scope_mismatch", + Self::DeliverScopeMismatch => "deliver_scope_mismatch", + Self::WorkerScopeMismatch => "worker_scope_mismatch", + Self::WorkerSenderMismatch => "worker_sender_mismatch", + } + } +} +pub(crate) fn unauthorized(reason: UnauthorizedReason) -> MailboxError { + tracing::warn!(reason = reason.as_str(), "mailbox authorization refused"); + MailboxError::Unauthorized +} diff --git a/src/messaging/runtime.rs b/src/messaging/runtime.rs index 43041fd09..a392b8b83 100644 --- a/src/messaging/runtime.rs +++ b/src/messaging/runtime.rs @@ -179,7 +179,9 @@ impl MessagingRuntime { pub fn resolve_scope(&self, target: &SessionAddr) -> MailboxResult { if !self.inbound(target) { - return Err(MailboxError::Unauthorized); + return Err(crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::InboundDisabledOrConfigInvalid, + )); } let registered = self.inboxes.lock().contains_key(target); self.store.session_scope(&self.workspace, target, registered) @@ -285,7 +287,9 @@ impl MessagingRuntime { return Ok(address); } if address.owner != source.owner { - return Err(MailboxError::Unauthorized); + return Err(crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::LocalOwnerMismatch, + )); } if matches!(address.session.as_str(), "main" | "parent") { address.session = self diff --git a/src/session_worker/mailbox.rs b/src/session_worker/mailbox.rs index b5e55a504..3b7e99dc0 100644 --- a/src/session_worker/mailbox.rs +++ b/src/session_worker/mailbox.rs @@ -47,7 +47,9 @@ impl WorkerMailboxSender { /// Called only on the pipe owned by the authenticated spawning parent. pub fn enqueue(&mut self, message: PrxMessage) -> MailboxResult { if message.kind != MessageKind::Data || message.to != self.address { - return Err(MailboxError::Unauthorized); + return Err(crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::WorkerScopeMismatch, + )); } validate_address(&message.from)?; validate_body(&message.body.mime, &message.body.bytes)?; diff --git a/src/session_worker/mailbox_parent.rs b/src/session_worker/mailbox_parent.rs index ea13ffedc..13b1318f7 100644 --- a/src/session_worker/mailbox_parent.rs +++ b/src/session_worker/mailbox_parent.rs @@ -32,7 +32,9 @@ impl WorkerMailboxParent { inherited: Option, ) -> MailboxResult { if worker_scope.workspace_id != parent_scope.workspace_id { - return Err(MailboxError::Unauthorized); + return Err(crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::WorkerScopeMismatch, + )); } store.validate_scope(&parent_scope, &parent)?; let mut incoming = MailboxAuthority::local(worker_scope.workspace_id.clone(), worker.clone(), parent.clone())?; @@ -158,7 +160,9 @@ impl WorkerMailboxParent { Ok(None) } WorkerOutputFrame::BrokerCall { .. } | WorkerOutputFrame::BrokerCancel { .. } => { - Err(MailboxError::Unauthorized) + Err(crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::WorkerSenderMismatch, + )) } } } diff --git a/src/session_worker/runner/steering.rs b/src/session_worker/runner/steering.rs index 63c45ae53..91cb5c6f8 100644 --- a/src/session_worker/runner/steering.rs +++ b/src/session_worker/runner/steering.rs @@ -99,7 +99,11 @@ pub(super) fn spawn_stdin_control_reader( WorkerControlFrame::Message { envelope } => { let result = mailbox .as_mut() - .ok_or(crate::messaging::mailbox::MailboxError::Unauthorized) + .ok_or_else(|| { + crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::WorkerSenderUnavailable, + ) + }) .and_then(|inbox| inbox.enqueue(*envelope)); match result { Ok(ack) => { diff --git a/src/tools/execution.rs b/src/tools/execution.rs index e87572fe9..6d4ded31b 100644 --- a/src/tools/execution.rs +++ b/src/tools/execution.rs @@ -13,4294 +13,9 @@ pub use refusal_record::ToolCallRefusalReason; pub(crate) use refusal_record::ToolRefusalNotice; pub(crate) use refusal_record::record_rf_call_refusal; -use super::schema::ToolSchemaDialect; -use super::traits::{Tool, ToolCategory, ToolResult, ToolSpec, ToolTier, is_tool_cancelled_result}; -use crate::capability::CapabilityAvailability; -use crate::memory::{Memory, MessageEventInput}; -use crate::runtime::envelope::RuntimeEnvelope; -use crate::security::SecurityPolicy; -use crate::security::policy::{RUNTIME_APPROVAL_GRANT_ARG, RUNTIME_APPROVAL_GRANTED_ARG, ToolDecision}; -use async_trait::async_trait; -use parking_lot::Mutex; -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; -use std::collections::HashMap; -use std::future::Future; -use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering}; -use std::sync::{Arc, OnceLock, Weak}; -use std::time::Instant; -use tokio::sync::Mutex as AsyncMutex; -use tokio_util::sync::CancellationToken; -use uuid::Uuid; - -/// Coarse side-effect classification used by the common policy stage. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum ToolEffect { - Read, - Act, -} - -/// Adapter family selected for a public tool name. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum ToolAdapterKind { - Native, - McpAlias, - WasmPlugin, - Skill, -} - -/// Small raw execution port consumed by the application service. -/// -/// Backends expose descriptors and invocation only; policy, approval, execution -/// preparation, auditing, and typed outcomes remain service-owned. -#[async_trait] -pub trait ToolBackend: Send + Sync { - /// Read-only operation metadata; never an execution or approval permit. - async fn resolve_approval_operation( - &self, - _public_name: &str, - _arguments: &serde_json::Value, - ) -> anyhow::Result> { - Ok(None) - } - /// Read-only below-Full path precheck; see [`Tool::path_precheck`]. - async fn path_precheck( - &self, - _public_name: &str, - _arguments: &serde_json::Value, - ) -> Result<(), crate::security::PathRefusal> { - Ok(()) - } - /// Defaults closed for aliases, plugins and unaudited backends. - fn supports_owner_filesystem(&self) -> bool { - false - } - fn process_worker_compatible(&self) -> bool { - true - } - fn execution_parameters_schema(&self) -> Option> { - None - } - fn root_name(&self) -> &str; - fn specs(&self) -> Vec; - fn catalog_specs(&self) -> Vec { - self.specs() - } - fn immutable_catalog_specs(&self) -> Option<&[ToolSpec]> { - None - } - fn shared_catalog_snapshot(&self) -> Option { - None - } - fn catalog_binding_snapshot(&self) -> std::collections::BTreeMap { - std::collections::BTreeMap::new() - } - fn spec_for_name(&self, public_name: &str) -> Option { - self.specs().into_iter().find(|spec| spec.name == public_name) - } - fn supports_name(&self, public_name: &str) -> bool; - fn tier(&self) -> ToolTier; - fn categories(&self) -> Vec; - fn adapter_kind(&self, public_name: &str) -> ToolAdapterKind; - fn availability(&self) -> CapabilityAvailability { - CapabilityAvailability::ready(format!("executable backend '{}' is registered", self.root_name())) - } - - fn catalog_availability_is_configured(&self) -> bool { - let availability = self.availability(); - availability.level >= crate::capability::CapabilityAvailabilityLevel::Configured - || availability.reason.trim().is_empty() - } - - async fn invoke( - &self, - public_name: &str, - arguments: serde_json::Value, - cancellation: Option, - ) -> anyhow::Result; - - async fn invoke_observed( - &self, - public_name: &str, - arguments: serde_json::Value, - cancellation: Option, - ) -> anyhow::Result { - self.invoke(public_name, arguments, cancellation).await.map(Into::into) - } -} - -/// Compatibility adapter for the existing native and MCP [`Tool`] registry. -pub struct LegacyToolAdapter { - tool: Arc, -} - -/// Named adapter over a shared boxed registry. Chat Redux keeps this legacy -/// registry alive across provider turns, so migration must borrow it rather -/// than consume or duplicate stateful tool instances. -struct SharedRegistryToolAdapter { - registry: Arc>>, - root_name: String, -} - -impl SharedRegistryToolAdapter { - fn tool(&self) -> Option<&dyn Tool> { - self.registry - .iter() - .find(|tool| tool.name() == self.root_name) - .map(Box::as_ref) - } -} - -#[async_trait] -impl ToolBackend for SharedRegistryToolAdapter { - async fn invoke_observed( - &self, - public_name: &str, - arguments: serde_json::Value, - cancellation: Option, - ) -> anyhow::Result { - self.tool() - .ok_or_else(|| anyhow::anyhow!("shared tool is no longer registered"))? - .execute_named_observed(public_name, arguments, cancellation) - .await - } - - fn execution_parameters_schema(&self) -> Option> { - self.tool()?.execution_parameters_schema() - } - fn supports_owner_filesystem(&self) -> bool { - self.tool().is_some_and(Tool::supports_owner_filesystem) - } - fn process_worker_compatible(&self) -> bool { - self.tool().is_some_and(Tool::process_worker_compatible) - } - async fn resolve_approval_operation( - &self, - public_name: &str, - arguments: &serde_json::Value, - ) -> anyhow::Result> { - let tool = self - .tool() - .ok_or_else(|| anyhow::anyhow!("approval tool unavailable"))?; - anyhow::ensure!(public_name == tool.name(), "approval alias is unsupported"); - tool.resolve_approval_operation(arguments).await - } - async fn path_precheck( - &self, - public_name: &str, - arguments: &serde_json::Value, - ) -> Result<(), crate::security::PathRefusal> { - // The root precheck reads the root's arguments; an alias is checked - // by its backend at execute time. - match self.tool() { - Some(tool) if public_name == tool.name() => tool.path_precheck(arguments).await, - _ => Ok(()), - } - } - fn root_name(&self) -> &str { - &self.root_name - } - - fn specs(&self) -> Vec { - self.tool().map_or_else(Vec::new, Tool::specs) - } - - fn catalog_specs(&self) -> Vec { - self.tool().map_or_else(Vec::new, Tool::catalog_specs) - } - - fn immutable_catalog_specs(&self) -> Option<&[ToolSpec]> { - self.tool()?.immutable_catalog_specs() - } - - fn shared_catalog_snapshot(&self) -> Option { - self.tool()?.shared_catalog_snapshot() - } - - fn catalog_binding_snapshot(&self) -> std::collections::BTreeMap { - self.tool() - .map_or_else(std::collections::BTreeMap::new, Tool::catalog_binding_snapshot) - } - - fn spec_for_name(&self, public_name: &str) -> Option { - self.tool()?.spec_for_name(public_name) - } - - fn supports_name(&self, public_name: &str) -> bool { - self.tool().is_some_and(|tool| tool.supports_name(public_name)) - } - - fn tier(&self) -> ToolTier { - self.tool().map_or(ToolTier::Standard, Tool::tier) - } - - fn categories(&self) -> Vec { - self.tool().map_or_else(Vec::new, |tool| tool.categories().to_vec()) - } - - fn adapter_kind(&self, public_name: &str) -> ToolAdapterKind { - if self.root_name == "mcp_call" && public_name != self.root_name { - ToolAdapterKind::McpAlias - } else if self.root_name == "wasm_plugin_call" { - ToolAdapterKind::WasmPlugin - } else if self.root_name == "skill_execute" || self.root_name == "skill_read" && public_name != self.root_name { - ToolAdapterKind::Skill - } else { - ToolAdapterKind::Native - } - } - - fn availability(&self) -> CapabilityAvailability { - self.tool().map_or_else( - || CapabilityAvailability::declared(format!("tool '{}' is no longer registered", self.root_name)), - Tool::availability, - ) - } - - fn catalog_availability_is_configured(&self) -> bool { - self.tool().is_some_and(Tool::catalog_availability_is_configured) - } - - async fn invoke( - &self, - public_name: &str, - arguments: serde_json::Value, - cancellation: Option, - ) -> anyhow::Result { - let Some(tool) = self.tool() else { - anyhow::bail!("shared tool '{}' is no longer registered", self.root_name); - }; - tool.execute_named_with_cancellation(public_name, arguments, cancellation) - .await - } -} - -impl LegacyToolAdapter { - #[must_use] - pub fn new(tool: Arc) -> Self { - Self { tool } - } -} - -#[async_trait] -impl ToolBackend for LegacyToolAdapter { - async fn invoke_observed( - &self, - public_name: &str, - arguments: serde_json::Value, - cancellation: Option, - ) -> anyhow::Result { - self.tool - .as_ref() - .execute_named_observed(public_name, arguments, cancellation) - .await - } - - fn execution_parameters_schema(&self) -> Option> { - self.tool.execution_parameters_schema() - } - fn supports_owner_filesystem(&self) -> bool { - self.tool.supports_owner_filesystem() - } - fn process_worker_compatible(&self) -> bool { - self.tool.process_worker_compatible() - } - async fn resolve_approval_operation( - &self, - public_name: &str, - arguments: &serde_json::Value, - ) -> anyhow::Result> { - anyhow::ensure!(public_name == self.tool.name(), "approval alias is unsupported"); - self.tool.resolve_approval_operation(arguments).await - } - async fn path_precheck( - &self, - public_name: &str, - arguments: &serde_json::Value, - ) -> Result<(), crate::security::PathRefusal> { - if public_name == self.tool.name() { - self.tool.path_precheck(arguments).await - } else { - Ok(()) - } - } - fn root_name(&self) -> &str { - self.tool.name() - } - - fn specs(&self) -> Vec { - self.tool.specs() - } - - fn catalog_specs(&self) -> Vec { - self.tool.catalog_specs() - } - - fn immutable_catalog_specs(&self) -> Option<&[ToolSpec]> { - self.tool.immutable_catalog_specs() - } - - fn shared_catalog_snapshot(&self) -> Option { - self.tool.shared_catalog_snapshot() - } - - fn catalog_binding_snapshot(&self) -> std::collections::BTreeMap { - self.tool.catalog_binding_snapshot() - } - - fn spec_for_name(&self, public_name: &str) -> Option { - self.tool.spec_for_name(public_name) - } - - fn supports_name(&self, public_name: &str) -> bool { - self.tool.supports_name(public_name) - } - - fn tier(&self) -> ToolTier { - self.tool.tier() - } - - fn categories(&self) -> Vec { - self.tool.categories().to_vec() - } - - fn adapter_kind(&self, public_name: &str) -> ToolAdapterKind { - if self.tool.name() == "mcp_call" && public_name != self.tool.name() { - ToolAdapterKind::McpAlias - } else if self.tool.name() == "wasm_plugin_call" { - ToolAdapterKind::WasmPlugin - } else if self.tool.name() == "skill_execute" - || self.tool.name() == "skill_read" && public_name != self.tool.name() - { - ToolAdapterKind::Skill - } else { - ToolAdapterKind::Native - } - } - - fn availability(&self) -> CapabilityAvailability { - self.tool.availability() - } - - fn catalog_availability_is_configured(&self) -> bool { - self.tool.catalog_availability_is_configured() - } - - async fn invoke( - &self, - public_name: &str, - arguments: serde_json::Value, - cancellation: Option, - ) -> anyhow::Result { - self.tool - .execute_named_with_cancellation(public_name, arguments, cancellation) - .await - } -} - -/// Immutable public descriptor captured before policy evaluation. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct ToolDescriptor { - pub public_name: String, - pub backend_name: String, - pub description: String, - pub parameters: serde_json::Value, - /// Full private built-in contract; None means the public contract is complete. - #[serde( - default, - skip_serializing_if = "Option::is_none", - serialize_with = "crate::tools::schema::serialize_execution_parameters", - deserialize_with = "crate::tools::schema::deserialize_execution_parameters" - )] - pub execution_parameters: Option>, - pub tier: ToolTier, - pub categories: Vec, - pub effect: ToolEffect, - pub adapter: ToolAdapterKind, - #[serde(default = "process_worker_compatible_by_default")] - pub process_worker_compatible: bool, - /// Evidence-backed runtime availability. Registered executable tools are - /// `Ready`; `Healthy` is reserved for a positive runtime probe. - pub availability: CapabilityAvailability, -} - -impl ToolDescriptor { - fn with_execution_parameters(mut self, schema: Option>) -> Self { - // A dynamic alias owns its own schema, never its backend's root contract. - if self.public_name == self.backend_name { - self.execution_parameters = schema; - } - self - } -} - -const fn process_worker_compatible_by_default() -> bool { - true -} - -/// Fresh executable spec for one parity pass. The backend identity is borrowed -/// from the live registry; published dynamic specs share one captured live view. -/// Legacy dynamic backends retain their owned-inventory fallback. -pub(crate) struct CurrentToolSpec<'a> { - pub(crate) backend_name: &'a str, - pub(crate) spec: CurrentToolSpecValue<'a>, - pub(crate) configured: bool, -} - -pub(crate) enum CurrentToolSpecValue<'a> { - Legacy(std::borrow::Cow<'a, ToolSpec>), - Shared { - entry: Arc, - snapshot: super::SharedToolCatalogSnapshot, - }, -} - -impl std::ops::Deref for CurrentToolSpecValue<'_> { - type Target = ToolSpec; - fn deref(&self) -> &ToolSpec { - match self { - Self::Legacy(spec) => spec, - Self::Shared { entry, .. } => entry.spec(), - } - } -} - -/// A captured snapshot's missing binding is authoritative. Only legacy -/// backends may query a fresh binding map as fallback. -pub(crate) enum SharedBinding { - Legacy, - Snapshot(Option<[u8; 32]>), -} - -impl SharedBinding { - pub(crate) const fn is_snapshot(&self) -> bool { - matches!(self, Self::Snapshot(_)) - } - - pub(crate) fn or_else_live(self, fallback: impl FnOnce() -> Option<[u8; 32]>) -> Option<[u8; 32]> { - match self { - Self::Legacy => fallback(), - Self::Snapshot(binding) => binding, - } - } -} - -impl CurrentToolSpecValue<'_> { - pub(crate) fn fingerprint(&self) -> crate::tools::capability::contract::SchemaFingerprint { - match self { - Self::Shared { entry, .. } => crate::tools::capability::contract::SchemaFingerprint(entry.fingerprint()), - Self::Legacy(spec) => { - super::capability::fingerprint::tool_spec_fingerprint(&spec.name, &spec.description, &spec.parameters) - } - } - } - pub(crate) fn shared_named_binding(&self, name: &str) -> SharedBinding { - match self { - Self::Shared { snapshot, .. } => SharedBinding::Snapshot(snapshot.binding_digest(name)), - Self::Legacy(_) => SharedBinding::Legacy, - } - } - - pub(crate) fn shared_binding_digest(&self) -> SharedBinding { - match self { - Self::Shared { entry, .. } => SharedBinding::Snapshot(entry.binding_digest()), - Self::Legacy(_) => SharedBinding::Legacy, - } - } -} - -fn current_tool_spec<'a>(backend: &'a dyn ToolBackend, spec: std::borrow::Cow<'a, ToolSpec>) -> CurrentToolSpec<'a> { - // Match tool_descriptor's legacy empty-reason promotion. - let configured = backend.catalog_availability_is_configured() - && crate::tools::schema::SchemaCleanr::validate(&spec.parameters).is_ok(); - CurrentToolSpec { - backend_name: backend.root_name(), - spec: CurrentToolSpecValue::Legacy(spec), - configured, - } -} - -/// One normalized execution request. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct ToolExecutionCommand { - pub operation_id: String, - pub name: String, - pub arguments: serde_json::Value, - pub idempotency_key: Option, -} - -impl ToolExecutionCommand { - #[must_use] - pub fn new(name: impl Into, arguments: serde_json::Value) -> Self { - Self { - operation_id: Uuid::now_v7().to_string(), - name: name.into(), - arguments, - idempotency_key: None, - } - } - - #[must_use] - pub fn with_idempotency_key(mut self, key: impl Into) -> Self { - self.idempotency_key = Some(key.into()); - self - } - - #[must_use] - pub fn with_operation_id(mut self, operation_id: impl Into) -> Self { - self.operation_id = operation_id.into(); - self - } -} - -/// Who constructed this execution context. Model turns fail closed without a -/// surface; every other origin keeps today's no-surface admission. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum DispatchOrigin { - ModelTurn, - Operator, - Job, - #[default] - Internal, -} - -/// Authenticated runtime facade available to every execution stage. -#[derive(Debug, Clone, PartialEq, Eq, Default)] -struct H2ExecutionMetadata { - controlled_case: Option>, - origin: Option>, -} -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ToolExecutionContext { - pub(crate) live_turn: Option, - h2_metadata: Option>, - pub(crate) dispatch_origin: DispatchOrigin, - pub(crate) turn_surface: Option>, - pub(crate) approval_ledger: Option, - pub(crate) owner_filesystem: Option>, - pub(crate) capability_search: Option, - pub(crate) ordinary_child_publication: Option, - /// Incoming child authority of this turn. - pub(crate) child_scope: Option>, - /// Pinned child provenance; dispatch refuses either half without the other. - pub(crate) child_pin: Option>, - /// Live G6 tokens for the model turn's called tools; absent outside model turns. - pub(crate) call_budget: Option, - /// A call that needs approval ends denied before any ledger route or - /// durable pending decision exists. Set for targeted agent turns, which - /// have no resumable approval until MA-04. - pub(crate) pending_approval_denied: bool, - pub(crate) execution_trace: Option, - /// Admission-time pin for MCP schema-drift (gateway compat). Agent turns - /// leave this empty; H2 uses `verify_admitted_call` against the service catalog. - pub(crate) admitted_binding: Option, - pub(crate) execution_admission: Option, - pub envelope: RuntimeEnvelope, - pub chat_type: String, - pub chat_id: String, - pub semantic_turn_id: String, - /// Which rewrite of the published tool schemas the model behind this turn - /// was actually shown. - /// - /// Argument validation enforces *that* document, not the published one: a - /// provider whose API rejects `additionalProperties` / `minLength` / - /// `minimum` never showed those constraints to the model, so holding the - /// model to them rejects calls it had no way to get right. Defaults to - /// [`ToolSchemaDialect::Raw`] — the published document — which is correct - /// for OpenAI and for every non-model entry point. - pub schema_dialect: ToolSchemaDialect, -} - -impl ToolExecutionContext { - pub(crate) fn controlled_case(&self) -> Option<&Arc> { - self.h2_metadata - .as_ref() - .and_then(|metadata| metadata.controlled_case.as_ref()) - } - pub(crate) fn h2_origin(&self) -> Option<&Arc> { - self.h2_metadata.as_ref().and_then(|metadata| metadata.origin.as_ref()) - } - fn normalize_h2_metadata(&mut self) { - if self - .h2_metadata - .as_ref() - .is_some_and(|metadata| metadata.controlled_case.is_none() && metadata.origin.is_none()) - { - self.h2_metadata = None; - } - } - pub(crate) fn set_controlled_case(&mut self, case: Arc) { - self.h2_metadata.get_or_insert_with(Box::default).controlled_case = Some(case); - } - pub(crate) fn set_h2_origin(&mut self, origin: Option>) { - if self.h2_metadata.is_none() && origin.is_none() { - return; - } - self.h2_metadata.get_or_insert_with(Box::default).origin = origin; - self.normalize_h2_metadata(); - } - #[must_use] - pub fn new(envelope: RuntimeEnvelope, chat_type: impl Into) -> Self { - let chat_id = envelope.session_key.clone(); - let semantic_turn_id = envelope - .source_message_event_id - .clone() - .or_else(|| envelope.run_id.clone()) - .or_else(|| envelope.task_id.clone()) - .unwrap_or_else(|| envelope.session_key.clone()); - Self { - live_turn: None, - h2_metadata: None, - dispatch_origin: DispatchOrigin::Internal, - turn_surface: None, - approval_ledger: None, - owner_filesystem: None, - capability_search: None, - ordinary_child_publication: None, - child_scope: None, - child_pin: None, - call_budget: None, - pending_approval_denied: false, - admitted_binding: None, - execution_admission: None, - execution_trace: None, - envelope, - chat_type: chat_type.into(), - chat_id, - semantic_turn_id, - schema_dialect: ToolSchemaDialect::Raw, - } - } - - /// Carries the authenticated incoming child authority from a child source - /// proof. Child provenance without a verified scope and pin is refused here. - pub(crate) fn with_incoming_child( - mut self, - proof: &dyn crate::runtime::turn_source::TurnSourceProof, - ) -> anyhow::Result { - anyhow::ensure!( - proof.child_scope().is_some() && proof.child_pin().is_some(), - "child provenance requires a verified scope and pinned catalog" - ); - self.child_scope = proof.child_scope().cloned(); - self.child_pin = proof.child_pin().cloned(); - Ok(self) - } - - /// Stamp the caller kind. Model-turn constructors set [`DispatchOrigin::ModelTurn`]. - #[must_use] - pub(crate) const fn with_dispatch_origin(mut self, dispatch_origin: DispatchOrigin) -> Self { - self.dispatch_origin = dispatch_origin; - self - } - - /// Deny every call that would otherwise wait for approval. - #[must_use] - pub(crate) const fn with_pending_approval_denied(mut self) -> Self { - self.pending_approval_denied = true; - self - } - - pub(crate) fn with_approval_ledger( - mut self, - ledger: Option, - ) -> Self { - self.approval_ledger = ledger; - self - } - - /// Declare the schema rewrite the serving provider applied for this turn. - #[must_use] - pub const fn with_schema_dialect(mut self, schema_dialect: ToolSchemaDialect) -> Self { - self.schema_dialect = schema_dialect; - self - } - - #[must_use] - pub fn with_chat_id(mut self, chat_id: impl Into) -> Self { - self.chat_id = chat_id.into(); - self - } - - #[must_use] - pub fn with_semantic_turn_id(mut self, semantic_turn_id: impl Into) -> Self { - self.semantic_turn_id = semantic_turn_id.into(); - self - } - - pub(super) fn sender(&self) -> &str { - self.envelope.sender.as_deref().unwrap_or("unknown") - } - - pub(super) fn channel(&self) -> &str { - self.envelope.channel.as_deref().unwrap_or("unknown") - } - - /// Whether this turn was initiated by the **local machine operator** — the - /// human sitting at the PRX terminal UI — as opposed to a remote IM user, a - /// gateway/webhook client, the console web UI, cron, or a spawned worker. - /// - /// This is the authority behind the runtime-injected `_prx_scope_trusted` - /// marker that guards destructive `gateway` actions (`config.patch`, - /// `restart`). It answers *who asked*, which at the default - /// [`AutonomyLevel::Full`] is the only thing standing between a remote - /// WhatsApp/Telegram message and a daemon restart: `SecurityPolicy::decide` - /// returns `Allow` for every side-effecting tool at `Full`, so no approval - /// is ever requested and `SideEffectGate::authorize_resource_operation` - /// passes medium-risk operations unconditionally. The second gate only - /// bites at `Supervised`; this one is what bites at the default. - /// - /// **Why the whole tuple and not `envelope.source`.** Every agent tool loop - /// builds its envelope with [`RuntimeEnvelope::chat_terminal`] regardless of - /// origin (see `agent_tool_execution_context` in `src/agent/execution_policy.rs`), so - /// `source` is `Chat` even for a Telegram turn and carries no signal at all. - /// The discriminating fields are the scope strings, and they are checked as - /// a set so that no single one has to be trusted alone: - /// - /// | origin | channel | sender | chat_id | chat_type | - /// |---|---|---|---|---| - /// | local terminal UI | `terminal` | `user` | `terminal:user` | `private` | - /// | IM channel | adapter name | remote user id | reply target | inferred | - /// | gateway / webhook | `webhook` / adapter | client id | `gateway:…` | `gateway` | - /// | console web UI | `console` | `console-user` | session key | `private` | - /// - /// The gateway surface cannot forge this even in principle: its `chat_id` is - /// `GatewayFabricContext`'s `session_key`, which is always built with a - /// literal `gateway:` prefix (`src/gateway/mod.rs:149,159`), so it can never - /// equal `terminal:user`. - /// - /// **Fail-closed by construction.** The predicate is an allowlist of one - /// exact tuple; anything unrecognised — a new runtime source, a renamed - /// channel, a missing envelope field (`sender()`/`channel()` fall back to - /// `"unknown"`) — lands on `false`, i.e. denied. It is never derived from - /// caller input: the two production sites that produce this tuple hardcode - /// every field (`src/chat/dispatcher.rs:2072-2090` and `src/chat/mod.rs:7142`). - #[must_use] - pub fn is_local_operator(&self) -> bool { - self.envelope.source == crate::runtime::envelope::RuntimeSource::Chat - && self.channel() == LOCAL_OPERATOR_CHANNEL - && self.sender() == LOCAL_OPERATOR_SENDER - && self.chat_id == LOCAL_OPERATOR_CHAT_ID - && self.chat_type == LOCAL_OPERATOR_CHAT_TYPE - } - - /// Whether the root principal of this call is the local operator: the - /// terminal UI turn itself, any child of a terminal turn at any depth - /// (children keep the root's `terminal` channel), a scheduled run the - /// local operator created (the local CLI tuple), or a scheduled run with - /// no recorded creator. Remote principals (IM channels, the console, the - /// gateway and rf), their children and their jobs answer `false`, as does - /// any owner-isolated scope. Runtime-authored; never caller input. - #[must_use] - pub fn is_local_root(&self) -> bool { - if self.envelope.owner_isolated { - return false; - } - self.is_local_operator() - || self.channel() == LOCAL_OPERATOR_CHANNEL - || (self.envelope.source == crate::runtime::envelope::RuntimeSource::Chat - && self.channel() == LOCAL_CLI_CHANNEL - && self.sender() == LOCAL_CLI_SENDER - && self.chat_id == LOCAL_CLI_CHAT_ID - && self.chat_type == LOCAL_OPERATOR_CHAT_TYPE) - || (self.dispatch_origin == DispatchOrigin::Job && self.chat_type == JOB_ORIGIN_UNKNOWN) - } -} - -/// The exact scope tuple the local terminal UI stamps on every turn it drives. -/// -/// Kept as constants next to [`ToolExecutionContext::is_local_operator`] so the -/// allowlist is one grep away from the sites that mint it. -const LOCAL_OPERATOR_CHANNEL: &str = "terminal"; -const LOCAL_OPERATOR_SENDER: &str = "user"; -const LOCAL_OPERATOR_CHAT_ID: &str = "terminal:user"; -const LOCAL_OPERATOR_CHAT_TYPE: &str = "private"; - -/// The exact scope tuple an operator-created cron or xin run of the internal agent engine stamps -/// on every tool call: `agent_tool_execution_context(None, "cli")` in -/// `src/agent/execution_policy.rs`. Cron agent jobs and xin tasks enter through the same -/// `run_with_runtime_envelope`, but carry this tuple only when their -/// [`JobOrigin`] is [`JobOrigin::LocalOperator`]; every other job runs under -/// [`JobOrigin::scheduled_tool_context`] instead. -const LOCAL_CLI_CHANNEL: &str = "cli"; -const LOCAL_CLI_SENDER: &str = "agent"; -const LOCAL_CLI_CHAT_ID: &str = "agent:local"; - -/// Whether the service-authored scope in `args` comes from a **local-process -/// operator surface**: the terminal UI or the local-operator CLI tuple (D-019 Q-5). -/// -/// This is wider than [`ToolExecutionContext::is_local_operator`] on purpose -/// and must never replace it: that predicate (`_prx_scope_trusted`) guards -/// destructive `gateway` actions and answers "is a human at this terminal", -/// while this one answers "is this turn the operator's own process rather -/// than a network surface" — the question the workspace-wide sub-agent run -/// view is gated on. Every network surface (gateway, webhook, Web Console, -/// MCP, IM channels) and every sub-agent worker answers `false`. -/// -/// Fail-closed like its sibling: both tuples are compared field for field -/// against the values the runtime itself authored into `_zc_scope` -/// (`normalize_arguments`), an owner-isolated scope never qualifies, and an -/// untrusted or missing scope is `false`. No network surface can mint either -/// tuple: gateway chat ids carry a literal `gateway:` prefix, IM chat ids are -/// the adapter's reply target, and the console's are session keys. -#[must_use] -pub fn scope_is_local_process_operator(args: &serde_json::Value) -> bool { - let trusted = args - .get("_zc_scope_trusted") - .and_then(serde_json::Value::as_bool) - .unwrap_or(false); - if !trusted || scope_requires_owner_match(args) { - return false; - } - if args - .get("_prx_scope_trusted") - .and_then(serde_json::Value::as_bool) - .unwrap_or(false) - { - return true; - } - let Some(scope) = args.get("_zc_scope").and_then(serde_json::Value::as_object) else { - return false; - }; - let field = |key: &str| scope.get(key).and_then(serde_json::Value::as_str); - field("runtime_source") == Some(crate::runtime::envelope::RuntimeSource::Chat.as_str()) - && field("channel") == Some(LOCAL_CLI_CHANNEL) - && field("sender") == Some(LOCAL_CLI_SENDER) - && field("chat_id") == Some(LOCAL_CLI_CHAT_ID) - && field("chat_type") == Some(LOCAL_OPERATOR_CHAT_TYPE) -} - -/// Who created a persisted background job — a cron job, a xin task or a xin -/// goal — and therefore whose authority its agent runs execute under -/// (CRON-ORIGIN; D-016, D-019 Q-5, D-026). -/// -/// A scheduled agent run has no live caller: the turn that created the job -/// ended long before. Without a recorded origin every run used to execute with -/// the local-operator CLI tuple, so a job scheduled from a channel, webhook or the -/// Web Console ran with the local operator's authority: the workspace-wide run -/// view and the `MEMORY.md` mirror. The origin is captured from the creating -/// turn's service-authored scope, persisted with the job, and never changed by -/// a later update, so a job can never gain authority after it was created. -/// -/// Fail-closed: [`Self::LocalOperator`] is granted only when the creating turn -/// was itself the local-process operator -/// ([`scope_is_local_process_operator`]) or the job was written by a path that -/// only a local operator reaches (the `prx cron` / `prx xin` CLI, built-in and -/// `HEARTBEAT.md` system tasks). Anything else — a network surface, a -/// sub-agent, an untrusted scope, a row stored before origins existed, an -/// unreadable stored value — never runs with operator authority. -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case")] -pub enum JobOrigin { - /// Created by the local operator. Runs keep the local-operator CLI tuple and - /// with it the workspace-wide run view and the `MEMORY.md` mirror. - LocalOperator, - /// Created from a trusted, non-operator scope. Runs act as this principal. - Principal { - channel: String, - sender: String, - chat_type: String, - #[serde(default)] - owner_id: Option, - #[serde(default)] - owner_isolated: bool, - }, - /// No attributable creator: a row stored before origins were recorded, or - /// a job created without a trusted scope. Runs act as the job itself — its - /// stored owner, if any — never as the operator. - #[default] - Unattributed, -} - -/// Channel segment of the per-job owner an ownerless scheduled job acts as -/// (R-CRON F-4). No channel adapter is named this, so the derived owner can -/// never equal a real principal's. -const UNATTRIBUTED_OWNER_CHANNEL: &str = "unattributed-job"; - -/// The value an absent origin field resolves to in [`JobOrigin::Principal`]. -const JOB_ORIGIN_UNKNOWN: &str = "unknown"; - -impl JobOrigin { - /// The origin a set of tool arguments proves for a job it creates. - /// - /// Read only from the service-authored `_zc_scope` (guarded by - /// `_zc_scope_trusted`): a caller can neither claim the operator origin nor - /// shed its own. `owner_id` is the owner the creating tool resolved for the - /// job's lineage, so the origin and the job's `owner_id` column agree. - #[must_use] - pub fn from_trusted_args(args: &serde_json::Value, owner_id: Option<&str>) -> Self { - let trusted = args - .get("_zc_scope_trusted") - .and_then(serde_json::Value::as_bool) - .unwrap_or(false); - let Some(scope) = args - .get("_zc_scope") - .and_then(serde_json::Value::as_object) - .filter(|_| trusted) - else { - return Self::Unattributed; - }; - if scope_is_local_process_operator(args) { - return Self::LocalOperator; - } - let field = |key: &str| { - scope - .get(key) - .and_then(serde_json::Value::as_str) - .map(str::trim) - .filter(|value| !value.is_empty()) - .unwrap_or(JOB_ORIGIN_UNKNOWN) - .to_string() - }; - Self::Principal { - channel: field("channel"), - sender: field("sender"), - chat_type: field("chat_type"), - owner_id: owner_id - .map(str::trim) - .filter(|owner| !owner.is_empty()) - .map(str::to_string), - owner_isolated: scope_requires_owner_match(args), - } - } - - /// Decode a stored origin column. - /// - /// `None` (a row written before the column existed) and an unreadable - /// value both resolve to [`Self::Unattributed`]: an origin that cannot be - /// proven is never the operator's. - #[must_use] - pub fn from_stored(raw: Option<&str>) -> Self { - let Some(raw) = raw.map(str::trim).filter(|raw| !raw.is_empty()) else { - return Self::Unattributed; - }; - serde_json::from_str(raw).unwrap_or_else(|error| { - tracing::warn!(%error, "unreadable scheduled-job origin; running the job as unattributed"); - Self::Unattributed - }) - } - - /// The column value [`Self::from_stored`] reads back. - /// - /// # Errors - /// Only if serialization fails, which a plain enum of strings cannot do in - /// practice; the error is propagated rather than stored as a guess. - pub fn to_stored(&self) -> anyhow::Result { - serde_json::to_string(self).map_err(|error| anyhow::anyhow!("failed to encode job origin: {error}")) - } - - /// Whether runs of this job keep the local operator's authority. - #[must_use] - pub const fn is_local_operator(&self) -> bool { - matches!(self, Self::LocalOperator) - } - - /// Whether the creator was an owner-isolated origin (an external MCP - /// caller); its runs are then owner-isolated too. - #[must_use] - pub const fn is_owner_isolated(&self) -> bool { - matches!( - self, - Self::Principal { - owner_isolated: true, - .. - } - ) - } - - /// The owner a principal origin recorded, if any. - #[must_use] - pub fn owner_id(&self) -> Option<&str> { - match self { - Self::Principal { owner_id, .. } => owner_id.as_deref(), - Self::LocalOperator | Self::Unattributed => None, - } - } - - /// [`Self::scheduled_tool_context`] paired with the configured policy at - /// the run's `level` (see [`ScheduledToolScope::new`]); `None` for an - /// operator job, which keeps the operator's CLI context and policy. - #[must_use] - pub fn scheduled_tool_scope( - &self, - run_envelope: RuntimeEnvelope, - config: &crate::config::Config, - level: crate::security::AutonomyLevel, - ) -> Option { - self.scheduled_tool_context(run_envelope) - .map(|context| ScheduledToolScope::new(context, config, level)) - } - - /// The tool execution context a scheduled run of this job must use, or - /// `None` when it keeps the local operator's CLI context. - /// - /// `run_envelope` is the job's own run envelope (`RuntimeEnvelope::cron` / - /// `RuntimeEnvelope::xin`, carrying the job's stored owner). The result - /// keeps its `cron`/`xin` runtime source and its `cron:{id}` / `xin:{id}` - /// session key as the chat id, so neither operator predicate — - /// [`ToolExecutionContext::is_local_operator`] (source `Chat`, chat id - /// `terminal:user`) nor [`scope_is_local_process_operator`] (source `Chat`, - /// chat id `agent:local`) — can match it, whatever the recorded channel and - /// sender are. A principal origin additionally acts as its creator: its - /// channel, sender, chat type, owner and owner isolation. - /// - /// A job with no owner — neither recorded by its origin nor stored on the - /// row — acts as an owner of its own, derived from its run envelope's - /// `cron:{id}` / `xin:{id}` session key (R-CRON F-4), so ownerless jobs do - /// not share one memory, run-view and job-management bucket. - #[must_use] - pub fn scheduled_tool_context(&self, run_envelope: RuntimeEnvelope) -> Option { - let run_envelope = if run_envelope.owner_id.is_none() { - let owner_id = crate::memory::principal::OwnerPrincipal::new( - run_envelope.workspace_id.clone(), - UNATTRIBUTED_OWNER_CHANNEL, - run_envelope.session_key.clone(), - run_envelope.session_key.clone(), - vec![crate::memory::principal::Role::Anonymous], - ) - .owner_id; - run_envelope.with_owner_id(owner_id) - } else { - run_envelope - }; - match self { - Self::LocalOperator => None, - Self::Unattributed => Some( - ToolExecutionContext::new(run_envelope, JOB_ORIGIN_UNKNOWN).with_dispatch_origin(DispatchOrigin::Job), - ), - Self::Principal { - channel, - sender, - chat_type, - owner_id, - owner_isolated, - } => { - let mut envelope = run_envelope.with_channel(channel.as_str()).with_sender(sender.as_str()); - if let Some(owner_id) = owner_id { - envelope = envelope.with_owner_id(owner_id.as_str()); - } - if *owner_isolated { - envelope = envelope.with_owner_isolation(); - } - Some(ToolExecutionContext::new(envelope, chat_type.as_str()).with_dispatch_origin(DispatchOrigin::Job)) - } - } - } -} - -/// What a non-operator scheduled run's tool calls are decided with: the -/// creator's context and the policy that applies to it (CRON-ORIGIN, R-CRON -/// F-1). -#[derive(Clone)] -pub struct ScheduledToolScope { - pub context: ToolExecutionContext, - pub policy: Arc, -} - -impl ScheduledToolScope { - /// Pair `context` with the configured policy at the run's `level` - /// (`security::agent_level::scheduled_level`), so the creator's - /// `[autonomy.scopes]` rules — keyed on the channel, sender and chat type - /// the context carries — apply to the run exactly as they applied to the - /// creator's own turn. - /// - /// One difference is deliberate: a scheduled run is unattended, so nobody - /// can answer an approval prompt. Under `supervised` a call that would - /// ask is refused instead (the level is read as `read_only` for the - /// effect decision), never approved on the creator's behalf and never put - /// to whoever happens to hold the daemon's terminal. - /// - /// The policy comes from `build_security_policy`, the sanctioned - /// constructor, so the configured audit block is wired exactly as on every - /// other surface (BUG-D1-01). - #[must_use] - pub fn new( - context: ToolExecutionContext, - config: &crate::config::Config, - level: crate::security::policy::AutonomyLevel, - ) -> Self { - let mut policy = crate::runtime::bootstrap::build_security_policy(config); - // Freshly built and not yet shared, so this mutates in place. - Arc::make_mut(&mut policy).autonomy = if level == crate::security::policy::AutonomyLevel::Supervised { - crate::security::policy::AutonomyLevel::ReadOnly - } else { - level - }; - Self { context, policy } - } -} - -impl std::fmt::Debug for ScheduledToolScope { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - formatter - .debug_struct("ScheduledToolScope") - .field("context", &self.context) - .field("autonomy", &self.policy.autonomy) - .finish_non_exhaustive() - } -} - -/// An immutable caller receipt issued only at the execution-service dispatch -/// boundary. Copying an envelope or decoding tool arguments cannot construct it. -#[derive(Clone)] -pub(crate) struct ChildCallContext { - tool_name: &'static str, - context: ToolExecutionContext, -} - -impl ChildCallContext { - pub(crate) fn verify_tool(&self, tool_name: &str) -> anyhow::Result<()> { - anyhow::ensure!(self.tool_name == tool_name, "child caller belongs to a different tool"); - Ok(()) - } - - pub(crate) const fn context(&self) -> &ToolExecutionContext { - &self.context - } - - /// Re-scope this receipt onto a publication derived from the caller's own - /// authenticated parent. Besides the dispatch boundary, this is the only - /// constructor, and it refuses any object with a different parent. - pub(crate) fn with_ordinary_publication( - &self, - derived: crate::runtime::child_source::publication::OrdinaryChildPublication, - ) -> anyhow::Result { - derived.verify_derived_from(&self.context)?; - let mut context = self.context.clone(); - context.ordinary_child_publication = Some(derived); - Ok(Self { - tool_name: self.tool_name, - context, - }) - } -} - -tokio::task_local! { - // Installed only by the execution service after policy/preparation checks. - // JSON arguments cannot supply this in-process child caller identity. - static CHILD_CALL_CONTEXT: Option; -} - -pub(crate) fn current_child_call_context() -> Option { - CHILD_CALL_CONTEXT.try_with(Clone::clone).ok().flatten() -} - -/// Validate an installed receipt without cloning its execution context. Direct -/// operator/legacy callers have no receipt and retain their existing admission. -pub(crate) fn verify_current_child_call(tool_name: &str) -> anyhow::Result<()> { - CHILD_CALL_CONTEXT - .try_with(|caller| caller.as_ref().map_or(Ok(()), |caller| caller.verify_tool(tool_name))) - .unwrap_or(Ok(())) -} - -tokio::task_local! { - /// The non-operator tool scope of the scheduled run on this task, if any. - static SCHEDULED_JOB_TOOL_SCOPE: Option; -} - -/// Run `future` with `scope` as the tool context and policy of every unscoped -/// agent tool loop inside it (see [`scheduled_job_tool_scope`]). -/// -/// `None` leaves the loop on its historical CLI context and policy. Only the -/// scheduled entry (`run_with_runtime_envelope`) installs one, from the job's -/// [`JobOrigin`]. -pub async fn with_scheduled_job_tool_scope(scope: Option, future: F) -> F::Output { - SCHEDULED_JOB_TOOL_SCOPE.scope(scope, future).await -} - -/// The tool scope installed by [`with_scheduled_job_tool_scope`] for the -/// current task, if any. Task-locals do not cross `tokio::spawn`; sub-agents -/// spawned from a scheduled run take their scope from the service-authored -/// `_zc_scope` of the spawning call instead, which this context produced. -#[must_use] -pub fn scheduled_job_tool_scope() -> Option { - SCHEDULED_JOB_TOOL_SCOPE.try_with(Clone::clone).ok().flatten() -} - -/// Typed policy decision used independently of the legacy policy enum. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum ToolExecutionDecision { - Allow, - Ask, - Deny, -} - -/// Pure side-effect policy port. -pub trait EffectPolicy: Send + Sync { - fn autonomy_level(&self) -> crate::security::AutonomyLevel; - fn decide(&self, descriptor: &ToolDescriptor, context: &ToolExecutionContext) -> ToolExecutionDecision; - /// Bind a bridge-approved call to the policy's trusted runtime scope. - /// Policies without a grant issuer leave resource gates fail-closed. - fn approved_call_grant( - &self, - _command: &ToolExecutionCommand, - _context: &ToolExecutionContext, - ) -> Option { - None - } - /// The decision at the call's effective level, which a child scope may - /// set apart from the service's own level. - fn decide_at( - &self, - descriptor: &ToolDescriptor, - context: &ToolExecutionContext, - _level: crate::security::AutonomyLevel, - ) -> ToolExecutionDecision { - self.decide(descriptor, context) - } -} - -/// Adapter from the current authoritative [`SecurityPolicy`] decision point. -pub struct SecurityEffectPolicy { - policy: Arc, -} - -impl SecurityEffectPolicy { - #[must_use] - pub const fn new(policy: Arc) -> Self { - Self { policy } - } -} - -impl EffectPolicy for SecurityEffectPolicy { - fn approved_call_grant( - &self, - command: &ToolExecutionCommand, - context: &ToolExecutionContext, - ) -> Option { - let scope = - crate::agent::turn_contracts::ScopeContext::from_execution_context(&self.policy, context, &context.chat_id); - let grant = crate::agent::execution_policy::runtime_approval_grant_for_call( - &command.name, - &command.arguments, - Some(&scope), - )?; - serde_json::to_value(grant) - .inspect_err(|_| tracing::warn!("bridge approval grant encoding failed")) - .ok() - } - - fn autonomy_level(&self) -> crate::security::AutonomyLevel { - self.policy.autonomy - } - fn decide(&self, descriptor: &ToolDescriptor, context: &ToolExecutionContext) -> ToolExecutionDecision { - let policy_name = if descriptor.adapter == ToolAdapterKind::Skill { - &descriptor.backend_name - } else { - &descriptor.public_name - }; - decide_tool_execution( - self.policy.as_ref(), - policy_name, - context.sender(), - context.channel(), - &context.chat_type, - ) - } - - fn decide_at( - &self, - descriptor: &ToolDescriptor, - context: &ToolExecutionContext, - level: crate::security::AutonomyLevel, - ) -> ToolExecutionDecision { - if level == self.policy.autonomy { - return self.decide(descriptor, context); - } - let policy_name = if descriptor.adapter == ToolAdapterKind::Skill { - &descriptor.backend_name - } else { - &descriptor.public_name - }; - let at_level = SecurityPolicy { - autonomy: level, - ..self.policy.as_ref().clone() - }; - decide_tool_execution( - &at_level, - policy_name, - context.sender(), - context.channel(), - &context.chat_type, - ) - } -} - -/// Canonical autonomy/scope decision projection used by both the legacy Agent -/// loop and [`ToolExecutionService`]. Approval UI and execution are downstream; -/// neither entry point may reinterpret the policy result. -#[must_use] -pub fn decide_tool_execution( - policy: &SecurityPolicy, - tool_name: &str, - sender: &str, - channel: &str, - chat_type: &str, -) -> ToolExecutionDecision { - match policy.decide(tool_name, sender, channel, chat_type) { - ToolDecision::Allow => ToolExecutionDecision::Allow, - ToolDecision::Ask => ToolExecutionDecision::Ask, - ToolDecision::Deny => ToolExecutionDecision::Deny, - } -} - -/// Request passed to a UI, queue, signed-grant, or fail-closed approval adapter. -#[derive(Debug, Clone)] -pub struct ToolApprovalRequest { - pub command: ToolExecutionCommand, - pub descriptor: ToolDescriptor, - pub context: ToolExecutionContext, -} - -/// Approval result. Runtime-only grant material is never accepted from the -/// original command arguments; only this trusted adapter may supply it. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum ToolApprovalDecision { - Approved { - runtime_approval_granted: bool, - runtime_grant: Option, - }, - /// The call did not run. `cause` is the typed reason; `reason` is the - /// display text the operator and the model read. - Denied { - cause: ApprovalDenialCause, - reason: String, - }, - Cancelled { - reason: String, - }, -} - -/// Why an approval-gated call was denied. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum ApprovalDenialCause { - /// The operator answered no (`n`, `Esc`, `Enter` on deny, or any other - /// plain answer). - UserRejected, - /// Plain mode: EOF, or the prompt stopped waiting. - NoAnswer, - /// The TUI had no approval surface, or the action channel closed. - NoApprovalSurface, - /// Plain or one-shot mode without a terminal and no allowing override. - NoTerminal, - /// Plain mode: the terminal was busy or its reader failed to start. - PromptUnavailable, - /// Another approval was already pending. - ConcurrentPending, - /// A session switch failed the approval closed. - SessionSwitched, - /// No resolver, or approval is not available for this agent. - NoResolver, - /// The channel approval gate denied the call. - ChannelDenied, - /// The approval ledger failed; its own error text is the reason. - LedgerRefused, -} - -/// Display text of a user rejection. -pub const APPROVAL_DENIED_USER_REJECTED: &str = "User rejected tool approval"; -/// Display text when no approval answer was given. -pub const APPROVAL_DENIED_NO_ANSWER: &str = "No approval answer was given"; -/// Display text when no approval prompt could be shown. -pub const APPROVAL_DENIED_NO_APPROVAL_SURFACE: &str = "No approval prompt could be shown, so the call was refused"; -/// Display text when no terminal could ask for approval. -pub const APPROVAL_DENIED_NO_TERMINAL: &str = "No terminal was available to ask for approval"; -/// Display text when the approval prompt was unavailable. -pub const APPROVAL_DENIED_PROMPT_UNAVAILABLE: &str = "The approval prompt was unavailable"; -/// Display text when another approval was already waiting. -pub const APPROVAL_DENIED_CONCURRENT_PENDING: &str = - "Another tool approval was already waiting, so this call was refused; retry it after that approval is answered"; -/// Display text when the chat session was switched before approval. -pub const APPROVAL_DENIED_SESSION_SWITCHED: &str = "The chat session was switched before approval"; -/// Display text when no approval resolver is available. -pub const APPROVAL_DENIED_NO_RESOLVER: &str = "approval required but no approval resolver is available"; -/// Display text of a channel approval gate denial. -pub const APPROVAL_DENIED_CHANNEL: &str = "approval denied"; - -impl ApprovalDenialCause { - /// The stable snake_case name recorded in the approval row. - #[must_use] - pub const fn as_str(self) -> &'static str { - match self { - Self::UserRejected => "user_rejected", - Self::NoAnswer => "no_answer", - Self::NoApprovalSurface => "no_approval_surface", - Self::NoTerminal => "no_terminal", - Self::PromptUnavailable => "prompt_unavailable", - Self::ConcurrentPending => "concurrent_pending", - Self::SessionSwitched => "session_switched", - Self::NoResolver => "no_resolver", - Self::ChannelDenied => "channel_denied", - Self::LedgerRefused => "ledger_refused", - } - } - - /// The fixed display text of this cause. `LedgerRefused` has none: its - /// text is the ledger's own error, carried in `Denied.reason`. - #[must_use] - pub const fn fixed_reason(self) -> Option<&'static str> { - match self { - Self::UserRejected => Some(APPROVAL_DENIED_USER_REJECTED), - Self::NoAnswer => Some(APPROVAL_DENIED_NO_ANSWER), - Self::NoApprovalSurface => Some(APPROVAL_DENIED_NO_APPROVAL_SURFACE), - Self::NoTerminal => Some(APPROVAL_DENIED_NO_TERMINAL), - Self::PromptUnavailable => Some(APPROVAL_DENIED_PROMPT_UNAVAILABLE), - Self::ConcurrentPending => Some(APPROVAL_DENIED_CONCURRENT_PENDING), - Self::SessionSwitched => Some(APPROVAL_DENIED_SESSION_SWITCHED), - Self::NoResolver => Some(APPROVAL_DENIED_NO_RESOLVER), - Self::ChannelDenied => Some(APPROVAL_DENIED_CHANNEL), - Self::LedgerRefused => None, - } - } -} - -/// How one approval request was resolved. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum ApprovalVerdict { - Approved, - Denied, - Cancelled, -} - -impl ApprovalVerdict { - /// The stable snake_case name recorded in the approval row. - #[must_use] - pub const fn as_str(self) -> &'static str { - match self { - Self::Approved => "approved", - Self::Denied => "denied", - Self::Cancelled => "cancelled", - } - } -} - -/// The model-visible result of a call that was denied before it ran. -#[must_use] -pub fn approval_denied_model_content(reason: &str, tool: &str) -> String { - format!("Denied: {reason}. The {tool} call did not run and produced no output.") -} - -#[async_trait] -pub trait ApprovalStrategy: Send + Sync { - async fn resolve(&self, request: ToolApprovalRequest) -> ToolApprovalDecision; -} - -/// Safe default for contexts without an interactive or persisted resolver. -#[derive(Debug, Default)] -pub struct DenyApprovalStrategy; - -#[async_trait] -impl ApprovalStrategy for DenyApprovalStrategy { - async fn resolve(&self, _request: ToolApprovalRequest) -> ToolApprovalDecision { - ToolApprovalDecision::Denied { - cause: ApprovalDenialCause::NoResolver, - reason: APPROVAL_DENIED_NO_RESOLVER.to_string(), - } - } -} - -/// Prepared execution boundary returned by the preparation stage. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct ToolExecutionPermit { - pub strategy: String, -} - -#[async_trait] -pub trait ToolExecutionPreparation: Send + Sync { - async fn prepare( - &self, - descriptor: &ToolDescriptor, - command: &ToolExecutionCommand, - context: &ToolExecutionContext, - ) -> Result; -} - -/// Default preparation for native and MCP adapters. The service keeps readiness -/// as an explicit auditable stage without claiming that it provides isolation. -#[derive(Debug, Default)] -pub struct AdapterOwnedPreparation; - -#[async_trait] -impl ToolExecutionPreparation for AdapterOwnedPreparation { - async fn prepare( - &self, - _descriptor: &ToolDescriptor, - _command: &ToolExecutionCommand, - _context: &ToolExecutionContext, - ) -> Result { - Ok(ToolExecutionPermit { - strategy: "adapter_owned".to_string(), - }) - } -} - -/// Terminal service outcome classes. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum ToolExecutionStatus { - Succeeded, - Failed, - Denied, - ApprovalDenied, - AwaitingApproval, - PreparationDenied, - UnknownTool, - StaleCapability, - InvalidArguments, - Cancelled, - IdempotencyConflict, - Indeterminate, -} - -/// Stable typed outcome shared by entrypoint-specific model/UI projections. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ToolExecutionOutcome { - pub operation_id: String, - pub descriptor: Option, - pub decision: Option, - pub status: ToolExecutionStatus, - pub model_content: String, - pub result: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub process: Option>, - pub error: Option, - pub preparation: Option, - pub duration_ms: u64, - #[serde(default)] - pub replayed: bool, - /// The typed reason of an `ApprovalDenied` outcome; `None` for every - /// other status. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub approval_denial_cause: Option, - /// Typed pre-approval refusal, projected only by rf live frames. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub refusal_cause: Option, -} - -impl ToolExecutionOutcome { - const fn with_refusal_cause(mut self, cause: ToolCallRefusalReason) -> Self { - self.refusal_cause = Some(cause); - self - } - - #[must_use] - pub fn succeeded(&self) -> bool { - self.status == ToolExecutionStatus::Succeeded - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct ToolExecutionReservation { - operation_id: String, - #[serde(default, alias = "owner_token")] - reservation_id: String, - #[serde(default)] - attempt: u32, - capability: String, - input_sha256: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct ToolExecutionTerminalRecord { - reservation: ToolExecutionReservation, - outcome: ToolExecutionOutcome, -} - -fn tool_execution_lock( - workspace_id: &str, - session_key: &str, - semantic_turn_id: &str, - idempotency_key: &str, -) -> Arc> { - static LOCKS: OnceLock>>>> = OnceLock::new(); - let lock_key = format!("{workspace_id}\0{session_key}\0{semantic_turn_id}\0{idempotency_key}"); - let locks = LOCKS.get_or_init(|| Mutex::new(HashMap::new())); - let mut locks = locks.lock(); - if let Some(lock) = locks.get(&lock_key).and_then(Weak::upgrade) { - return lock; - } - locks.retain(|_, lock| lock.strong_count() > 0); - let lock = Arc::new(AsyncMutex::new(())); - locks.insert(lock_key, Arc::downgrade(&lock)); - lock -} - -/// Digest of one tool call's session, semantic turn and idempotency key: the -/// scope shared by its execution-ledger and approval-event keys. -fn tool_execution_scope_digest(context: &ToolExecutionContext, idempotency_key: &str) -> String { - let scope = format!( - "{}\0{}\0{}", - context.envelope.session_key, context.semantic_turn_id, idempotency_key - ); - format!("{:x}", Sha256::digest(scope.as_bytes())) -} - -fn tool_execution_ledger_keys(context: &ToolExecutionContext, idempotency_key: &str) -> (String, String) { - let digest = tool_execution_scope_digest(context, idempotency_key); - ( - format!("tool-execution:{digest}:reservation"), - format!("tool-execution:{digest}:terminal"), - ) -} - -fn tool_execution_reservation_key(base_key: &str, attempt: u32) -> String { - if attempt == 0 { - base_key.to_string() - } else { - format!("{base_key}:retry:{attempt}") - } -} - -fn tool_execution_abandonment_key(base_key: &str, attempt: u32) -> String { - format!("{}:abandoned", tool_execution_reservation_key(base_key, attempt)) -} - -/// Audit projection emitted exactly once for every service outcome, including -/// resolution, policy, approval, preparation, validation, and cancellation failures. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct ToolExecutionAuditRecord { - pub operation_id: String, - pub capability: String, - pub backend_name: Option, - pub adapter: Option, - pub effect: Option, - pub decision: Option, - pub status: ToolExecutionStatus, - pub preparation_strategy: Option, - pub input_sha256: String, - pub source: String, - pub workspace_id: String, - pub session_key: String, - pub run_id: Option, - pub parent_run_id: Option, - pub task_id: Option, - pub error: Option, - pub duration_ms: u64, -} - -/// Audit is mandatory but observational: sinks cannot rewrite the result or -/// fail a completed side effect. -pub trait ToolExecutionAuditSink: Send + Sync { - fn record(&self, record: ToolExecutionAuditRecord); -} - -/// Structured tracing sink used when no durable integration-event writer has -/// yet been supplied by the entrypoint. -#[derive(Debug, Default)] -pub struct TracingToolExecutionAudit; - -impl ToolExecutionAuditSink for TracingToolExecutionAudit { - fn record(&self, record: ToolExecutionAuditRecord) { - tracing::info!( - target: "tool_execution_audit", - operation_id = %record.operation_id, - capability = %record.capability, - backend = ?record.backend_name, - adapter = ?record.adapter, - effect = ?record.effect, - decision = ?record.decision, - status = ?record.status, - preparation = ?record.preparation_strategy, - source = %record.source, - workspace_id = %record.workspace_id, - session_key = %record.session_key, - run_id = ?record.run_id, - parent_run_id = ?record.parent_run_id, - task_id = ?record.task_id, - duration_ms = record.duration_ms, - error = ?record.error, - "tool execution audited" - ); - } -} - -struct ResolvedTool { - shared_binding_digest: SharedBinding, - backend: Arc, - descriptor: ToolDescriptor, -} - -struct ToolExecutionLease { - _guard: tokio::sync::OwnedMutexGuard<()>, - memory: Arc, - reservation: ToolExecutionReservation, - abandonment_key: String, - terminal_key: String, -} - -/// Immutable descriptor snapshot shared by discovery and execution. -/// -/// The catalog is assembled from the exact finalized backend registry received -/// by an entry point. It never infers executable readiness from configuration. -#[derive(Debug, Clone)] -pub struct ToolCatalog { - descriptors: Arc<[ToolDescriptor]>, -} - -impl ToolCatalog { - fn from_backends(backends: &[Arc]) -> Self { - let descriptors = backends - .iter() - .flat_map(|backend| { - backend.specs().into_iter().map(|spec| { - tool_descriptor( - backend.root_name(), - spec, - backend.tier(), - backend.categories(), - |public_name| backend.adapter_kind(public_name), - backend.availability(), - backend.process_worker_compatible(), - ) - .with_execution_parameters(backend.execution_parameters_schema()) - }) - }) - .collect(); - Self::from_descriptors(descriptors) - } - - /// Snapshot a legacy boxed registry for user-facing discovery. This uses - /// the same descriptor construction as [`ToolExecutionService`]. - #[must_use] - pub fn from_boxed_registry(registry: &[Box]) -> Self { - Self::from_tools(registry.iter().map(Box::as_ref)) - } - - /// Snapshot any selected set of legacy tools. Entry-point-specific tiering - /// may choose a subset, but descriptor and availability semantics remain - /// identical everywhere. - #[must_use] - pub fn from_tools<'a>(tools: impl IntoIterator) -> Self { - let descriptors = tools - .into_iter() - .flat_map(|tool| { - tool.specs().into_iter().map(|spec| { - let root_name = tool.name(); - tool_descriptor( - root_name, - spec, - tool.tier(), - tool.categories().to_vec(), - |public_name| { - if root_name == "mcp_call" && public_name != root_name { - ToolAdapterKind::McpAlias - } else if root_name == "wasm_plugin_call" { - ToolAdapterKind::WasmPlugin - } else if root_name == "skill_execute" { - ToolAdapterKind::Skill - } else { - ToolAdapterKind::Native - } - }, - tool.availability(), - tool.process_worker_compatible(), - ) - .with_execution_parameters(tool.execution_parameters_schema()) - }) - }) - .collect(); - Self::from_descriptors(descriptors) - } - - fn from_descriptors(descriptors: Vec) -> Self { - // Preserve registry/spec order so adopting the catalog does not reorder - // provider prompts. The first executable registration owns a duplicate - // public name, matching execution resolution's first-match semantics. - let mut unique = Vec::with_capacity(descriptors.len()); - for descriptor in descriptors { - if !unique - .iter() - .any(|registered: &ToolDescriptor| registered.public_name == descriptor.public_name) - { - unique.push(descriptor); - } - } - Self { - descriptors: unique.into(), - } - } - - #[must_use] - pub fn descriptors(&self) -> &[ToolDescriptor] { - &self.descriptors - } - - /// Provider-facing projection of the canonical descriptors. - #[must_use] - pub fn tool_specs(&self) -> Vec { - self.descriptors - .iter() - .filter(|descriptor| { - descriptor.availability.level >= crate::capability::CapabilityAvailabilityLevel::Configured - }) - .map(|descriptor| ToolSpec { - name: descriptor.public_name.clone(), - description: descriptor.description.clone(), - parameters: descriptor.parameters.clone(), - }) - .collect() - } - - #[must_use] - pub fn descriptor(&self, public_name: &str) -> Option<&ToolDescriptor> { - self.descriptors - .iter() - .find(|descriptor| descriptor.public_name == public_name) - } -} - -fn tool_descriptor( - backend_name: &str, - spec: ToolSpec, - tier: ToolTier, - categories: Vec, - adapter_kind: impl FnOnce(&str) -> ToolAdapterKind, - availability: CapabilityAvailability, - process_worker_compatible: bool, -) -> ToolDescriptor { - let adapter = adapter_kind(&spec.name); - let effect = if backend_name == "skill_read" || crate::security::policy::is_read_only_tool(&spec.name) { - ToolEffect::Read - } else { - ToolEffect::Act - }; - let adapter_label = match adapter { - ToolAdapterKind::Native => "native", - ToolAdapterKind::McpAlias => "MCP alias", - ToolAdapterKind::WasmPlugin => "WASM plugin", - ToolAdapterKind::Skill => "skill", - }; - let availability = match crate::tools::schema::SchemaCleanr::validate(&spec.parameters) { - Ok(()) => availability, - Err(error) => CapabilityAvailability::declared(format!( - "invalid schema for {adapter_label} tool '{}': {error}", - spec.name - )), - }; - ToolDescriptor { - public_name: spec.name, - backend_name: backend_name.to_string(), - description: spec.description, - parameters: spec.parameters, - execution_parameters: None, - tier, - categories, - effect, - adapter, - process_worker_compatible, - availability: if availability.reason.trim().is_empty() { - CapabilityAvailability::ready(format!( - "executable {adapter_label} backend '{backend_name}' is registered" - )) - } else { - availability - }, - } -} - -/// Mandatory application pipeline for native tools and MCP aliases. -#[derive(Clone)] -pub struct ToolExecutionService { - backends: Arc<[Arc]>, - catalog: ToolCatalog, - policy: Arc, - approval: Arc, - preparation: Arc, - audit: Arc, - idempotency_memory: Option>, - refusal_notice: Option>, - #[cfg(test)] - post_reservation_gate: Option>, -} - -#[cfg(test)] -struct TestPostReservationGate { - armed: AtomicBool, - entered: tokio::sync::Notify, - release: tokio::sync::Notify, -} - -impl ToolExecutionService { - /// The same service under another approval strategy. The backends, - /// catalog, effect policy, preparation, audit and idempotency ledger are - /// shared, so only the approval decision differs (a task child's turn runs - /// its published service under its run's approval strategy). - #[must_use] - pub(crate) fn with_approval(&self, approval: Arc) -> Self { - let mut service = self.clone(); - service.approval = approval; - service - } - - #[must_use] - pub fn new( - tools: Vec>, - policy: Arc, - approval: Arc, - preparation: Arc, - audit: Arc, - ) -> Self { - let backends = tools - .into_iter() - .map(|tool| Arc::new(LegacyToolAdapter::new(tool)) as Arc) - .collect(); - Self::from_backends(backends, policy, approval, preparation, audit) - } - - /// Assemble the service from raw execution ports. - #[must_use] - pub fn from_backends( - backends: Vec>, - policy: Arc, - approval: Arc, - preparation: Arc, - audit: Arc, - ) -> Self { - let catalog = ToolCatalog::from_backends(&backends); - Self { - backends: backends.into(), - catalog, - policy, - approval, - preparation, - audit, - idempotency_memory: None, - refusal_notice: None, - #[cfg(test)] - post_reservation_gate: None, - } - } - - /// Consume the current boxed registry without cloning tool state. - #[must_use] - pub fn from_boxed( - tools: Vec>, - policy: Arc, - approval: Arc, - preparation: Arc, - audit: Arc, - ) -> Self { - let tools = tools.into_iter().map(Arc::::from).collect(); - Self::new(tools, policy, approval, preparation, audit) - } - - /// Adapt a shared boxed registry without cloning or consuming stateful - /// tools. This is the compatibility assembly used by Chat Redux. - #[must_use] - pub fn from_shared_boxed_registry( - registry: Arc>>, - policy: Arc, - approval: Arc, - preparation: Arc, - audit: Arc, - ) -> Self { - let backends = registry - .iter() - .map(|tool| tool.name().to_string()) - .map(|root_name| { - Arc::new(SharedRegistryToolAdapter { - registry: Arc::clone(®istry), - root_name, - }) as Arc - }) - .collect(); - Self::from_backends(backends, policy, approval, preparation, audit) - } - - /// Fail-closed convenience assembly for non-interactive callers. - #[must_use] - pub fn with_security_policy(tools: Vec>, policy: Arc) -> Self { - Self::from_boxed( - tools, - Arc::new(SecurityEffectPolicy::new(policy)), - Arc::new(DenyApprovalStrategy), - Arc::new(AdapterOwnedPreparation), - Arc::new(TracingToolExecutionAudit), - ) - } - - /// Attach the durable MessageEvent ledger used to reserve and replay - /// idempotent tool executions. - /// - /// Callers resolve the ledger through `crate::memory::tool_execution_ledger`, - /// which already guarantees a ledger-capable backend. The check here stays as - /// a last line of defence: a backend without a durable event log would - /// otherwise record reservations that never survive a crash. - #[must_use] - pub fn with_idempotency_memory(mut self, memory: Arc) -> Self { - if crate::memory::serves_tool_execution_ledger(memory.name()) { - self.idempotency_memory = Some(memory); - } else { - tracing::warn!( - backend = memory.name(), - "tool execution idempotency is unavailable for this memory backend" - ); - } - self - } - - /// Show the operator each call refused before approval (plain stderr - /// line or TUI notice). - #[must_use] - pub(crate) fn with_refusal_notice(mut self, notice: Arc) -> Self { - self.refusal_notice = Some(notice); - self - } - - #[cfg(test)] - fn with_post_reservation_gate(mut self, gate: Arc) -> Self { - self.post_reservation_gate = Some(gate); - self - } - - fn resolve(&self, public_name: &str) -> Option { - // Always inspect the current exact spec. A startup descriptor can be - // stale after MCP, WASM or Skill discovery changes its schema, and a - // live MCP catalog can be larger than the provider-facing spec window. - let pinned_root = self - .catalog - .descriptor(public_name) - .map(|entry| entry.backend_name.as_str()); - let mut resolved = None; - for backend in self.backends.iter() { - if pinned_root.is_some_and(|root| root != backend.root_name()) { - continue; - } - if !backend.supports_name(public_name) { - continue; - } - let (spec, shared_binding_digest) = if let Some(snapshot) = backend.shared_catalog_snapshot() { - let Some(entry) = snapshot.entry(public_name) else { - continue; - }; - (entry.spec().clone(), SharedBinding::Snapshot(entry.binding_digest())) - } else { - let Some(spec) = backend.spec_for_name(public_name) else { - continue; - }; - (spec, SharedBinding::Legacy) - }; - let descriptor = tool_descriptor( - backend.root_name(), - spec, - backend.tier(), - backend.categories(), - |name| backend.adapter_kind(name), - backend.availability(), - backend.process_worker_compatible(), - ) - .with_execution_parameters(backend.execution_parameters_schema()); - if resolved.is_some() { - // A dynamic name with more than one live owner is ambiguous. - return None; - } - resolved = Some(ResolvedTool { - shared_binding_digest, - backend: Arc::clone(backend), - descriptor, - }); - } - resolved - } - - /// Descriptor for the exact capability the execution service can run now. - #[must_use] - pub fn current_descriptor(&self, public_name: &str) -> Option { - self.resolve(public_name).map(|resolved| resolved.descriptor) - } - - /// Snapshot taken when the service was built; schema drift compares this - /// to the live descriptor. - pub(crate) fn admitted_descriptor(&self, public_name: &str) -> Option<&ToolDescriptor> { - self.catalog.descriptor(public_name) - } - - pub(crate) fn current_descriptor_with_binding( - &self, - name: &str, - require_binding: bool, - ) -> Option<(ToolDescriptor, Option<[u8; 32]>)> { - let resolved = self.resolve(name)?; - let binding = resolved.shared_binding_digest.or_else_live(|| { - require_binding - .then(|| resolved.backend.catalog_binding_snapshot().get(name).copied()) - .flatten() - }); - Some((resolved.descriptor, binding)) - } - - pub(crate) fn current_binding_digest(&self, root: &str, name: &str) -> Option<[u8; 32]> { - let owner = self.catalog.descriptor(root)?.backend_name.as_str(); - let backend = self.backends.iter().find(|backend| backend.root_name() == owner)?; - backend.shared_catalog_snapshot().map_or_else( - || backend.catalog_binding_snapshot().get(name).copied(), - |snapshot| snapshot.binding_digest(name), - ) - } - - pub(crate) fn supports_owner_filesystem(&self, public_name: &str) -> bool { - self.resolve(public_name).is_some_and(|resolved| { - resolved.descriptor.adapter == ToolAdapterKind::Native - && resolved.descriptor.backend_name == public_name - && matches!(public_name, "file_read" | "file_write" | "file_edit") - && resolved.backend.supports_owner_filesystem() - }) - } - - /// Full live inventory. A collision with a pinned startup name is - /// reported by parity even if the service still routes to its first owner. - #[must_use] - pub fn current_descriptors(&self) -> Vec { - self.backends - .iter() - .flat_map(|backend| { - backend.catalog_specs().into_iter().map(|spec| { - tool_descriptor( - backend.root_name(), - spec, - backend.tier(), - backend.categories(), - |name| backend.adapter_kind(name), - backend.availability(), - backend.process_worker_compatible(), - ) - .with_execution_parameters(backend.execution_parameters_schema()) - }) - }) - .collect() - } - - /// Live inventory paired with each entry's dispatch binding, in one pass - /// over the backends. The binding is read the same way `resolve` reads it, - /// but each backend's snapshot and binding map are captured only once. - #[must_use] - pub(crate) fn live_descriptors_with_bindings(&self) -> Vec<(ToolDescriptor, Option<[u8; 32]>)> { - let mut out = Vec::new(); - for backend in self.backends.iter() { - let shared = backend.shared_catalog_snapshot(); - let mut legacy_bindings = None; - for spec in backend.catalog_specs() { - let binding = if let Some(snapshot) = &shared { - snapshot.entry(&spec.name).and_then(|entry| entry.binding_digest()) - } else { - legacy_bindings - .get_or_insert_with(|| backend.catalog_binding_snapshot()) - .get(&spec.name) - .copied() - }; - let descriptor = tool_descriptor( - backend.root_name(), - spec, - backend.tier(), - backend.categories(), - |name| backend.adapter_kind(name), - backend.availability(), - backend.process_worker_compatible(), - ) - .with_execution_parameters(backend.execution_parameters_schema()); - out.push((descriptor, binding)); - } - } - out - } - - /// Full fresh inventory for causal parity without building user-facing - /// descriptors. A malformed schema has the same Declared status as the - /// descriptor path and therefore cannot satisfy a pinned configured entry. - #[must_use] - pub(crate) fn current_specs_for_parity(&self) -> Vec> { - // Capture each dynamic publication once before allocating the flat view. - // Startup descriptors may contain only a dynamic backend's root. - let snapshots: Vec<_> = self - .backends - .iter() - .map(|backend| backend.shared_catalog_snapshot()) - .collect(); - let capacity = self.catalog.descriptors().len() - + snapshots - .iter() - .flatten() - .map(|snapshot| snapshot.entries().len()) - .sum::(); - let mut live = Vec::with_capacity(capacity); - for (backend, snapshot) in self.backends.iter().zip(snapshots) { - let backend = backend.as_ref(); - if let Some(snapshot) = snapshot { - let configured = backend.catalog_availability_is_configured(); - for entry in snapshot.entries() { - live.push(CurrentToolSpec { - backend_name: backend.root_name(), - configured: configured && entry.schema_valid(), - spec: CurrentToolSpecValue::Shared { - entry: Arc::clone(entry), - snapshot: snapshot.clone(), - }, - }); - } - } else if let Some(specs) = backend.immutable_catalog_specs() { - for spec in specs { - live.push(current_tool_spec(backend, std::borrow::Cow::Borrowed(spec))); - } - } else { - for spec in backend.catalog_specs() { - live.push(current_tool_spec(backend, std::borrow::Cow::Owned(spec))); - } - } - } - live - } - - #[must_use] - pub fn current_binding_snapshot(&self, root: &str) -> Option> { - let owner = self.catalog.descriptor(root)?.backend_name.as_str(); - Some( - self.backends - .iter() - .find(|backend| backend.root_name() == owner)? - .catalog_binding_snapshot(), - ) - } - - /// Return whether an exact public tool name can currently be resolved. - /// - /// This includes live dynamic aliases that were discovered after the - /// immutable startup catalog was captured. Turn-level exposure guards use - /// this distinction to reject a known-but-unexposed capability without - /// changing the existing error for a genuinely unknown tool name. - #[must_use] - pub fn supports_public_name(&self, public_name: &str) -> bool { - self.resolve(public_name).is_some() - } - - /// Return the normal execution-policy denial for a known capability that - /// was withheld from this turn. This performs no binding, approval, - /// preparation, reservation, or backend work. - #[must_use] - pub fn unexposed_policy_denial(&self, public_name: &str, context: &ToolExecutionContext) -> Option { - let descriptor = self.resolve(public_name)?.descriptor; - (self.policy.decide(&descriptor, context) == ToolExecutionDecision::Deny).then(|| { - format!( - "tool '{}' is not permitted under the current execution policy", - descriptor.public_name - ) - }) - } - - #[must_use] - pub fn descriptors(&self) -> Vec { - self.catalog.descriptors().to_vec() - } - - #[must_use] - pub const fn catalog(&self) -> &ToolCatalog { - &self.catalog - } - - async fn prepare_idempotent_execution( - &self, - command: &ToolExecutionCommand, - context: &ToolExecutionContext, - input_sha256: &str, - descriptor: &ToolDescriptor, - decision: ToolExecutionDecision, - preparation: &ToolExecutionPermit, - started: Instant, - ) -> Result, Box> { - let Some(idempotency_key) = command.idempotency_key.as_deref() else { - return Ok(None); - }; - let Some(memory) = self.idempotency_memory.as_ref() else { - if descriptor.effect == ToolEffect::Read { - return Ok(None); - } - return Err(Box::new(self.finish( - command, - context, - input_sha256.to_string(), - Some(descriptor.clone()), - Some(decision), - ToolExecutionStatus::Indeterminate, - "Error: durable tool idempotency ledger is unavailable; refusing side effect".to_string(), - None, - Some("durable tool idempotency ledger is unavailable".to_string()), - Some(preparation.clone()), - started, - ))); - }; - let lock = tool_execution_lock( - &context.envelope.workspace_id, - &context.envelope.session_key, - &context.semantic_turn_id, - idempotency_key, - ); - let guard = lock.lock_owned().await; - let (base_reservation_key, terminal_key) = tool_execution_ledger_keys(context, idempotency_key); - - match memory - .find_message_event_by_idempotency_key(&context.envelope.workspace_id, &terminal_key) - .await - { - Ok(Some(event)) => { - let terminal = event - .raw_payload_json - .as_deref() - .and_then(|payload| serde_json::from_str::(payload).ok()); - let Some(terminal) = terminal else { - return Err(Box::new(self.finish( - command, - context, - input_sha256.to_string(), - Some(descriptor.clone()), - Some(decision), - ToolExecutionStatus::Indeterminate, - "Error: persisted tool terminal record is unreadable; refusing replay".to_string(), - None, - Some("persisted tool terminal record is unreadable".to_string()), - Some(preparation.clone()), - started, - ))); - }; - if terminal.reservation.capability != command.name || terminal.reservation.input_sha256 != input_sha256 - { - return Err(Box::new(self.finish( - command, - context, - input_sha256.to_string(), - Some(descriptor.clone()), - Some(decision), - ToolExecutionStatus::IdempotencyConflict, - "Error: idempotency key was already used for a different tool command".to_string(), - None, - Some("idempotency key command fingerprint mismatch".to_string()), - Some(preparation.clone()), - started, - ))); - } - return Err(Box::new(self.replay_outcome( - command, - context, - input_sha256, - terminal.outcome, - ))); - } - Ok(None) => {} - Err(error) => { - return Err(Box::new(self.finish( - command, - context, - input_sha256.to_string(), - Some(descriptor.clone()), - Some(decision), - ToolExecutionStatus::Indeterminate, - format!("Error: unable to inspect tool idempotency ledger: {error}"), - None, - Some(error.to_string()), - Some(preparation.clone()), - started, - ))); - } - } - - let mut attempt = 0_u32; - loop { - let reservation_key = tool_execution_reservation_key(&base_reservation_key, attempt); - match memory - .find_message_event_by_idempotency_key(&context.envelope.workspace_id, &reservation_key) - .await - { - Ok(Some(event)) => { - let existing = event - .raw_payload_json - .as_deref() - .and_then(|payload| serde_json::from_str::(payload).ok()); - let Some(existing) = existing else { - return Err(Box::new( - self.finish( - command, - context, - input_sha256.to_string(), - Some(descriptor.clone()), - Some(decision), - ToolExecutionStatus::Indeterminate, - "Error: persisted tool reservation is unreadable; refusing duplicate side effect" - .to_string(), - None, - Some("persisted tool reservation is unreadable".to_string()), - Some(preparation.clone()), - started, - ), - )); - }; - if existing.capability != command.name || existing.input_sha256 != input_sha256 { - return Err(Box::new(self.finish( - command, - context, - input_sha256.to_string(), - Some(descriptor.clone()), - Some(decision), - ToolExecutionStatus::IdempotencyConflict, - "Error: idempotency key was already used for a different tool command".to_string(), - None, - Some("idempotency key command fingerprint mismatch".to_string()), - Some(preparation.clone()), - started, - ))); - } - let abandonment_key = tool_execution_abandonment_key(&base_reservation_key, attempt); - let abandoned = memory - .find_message_event_by_idempotency_key(&context.envelope.workspace_id, &abandonment_key) - .await - .map_err(|error| { - self.finish( - command, - context, - input_sha256.to_string(), - Some(descriptor.clone()), - Some(decision), - ToolExecutionStatus::Indeterminate, - format!("Error: unable to inspect tool idempotency abandonment: {error}"), - None, - Some(error.to_string()), - Some(preparation.clone()), - started, - ) - })?; - let Some(abandoned) = abandoned else { - return Err(Box::new(self.finish( - command, - context, - input_sha256.to_string(), - Some(descriptor.clone()), - Some(decision), - ToolExecutionStatus::Indeterminate, - "Error: tool execution was reserved without a terminal outcome; refusing duplicate side effect" - .to_string(), - None, - Some( - "tool execution was reserved without a terminal outcome; refusing duplicate side effect" - .to_string(), - ), - Some(preparation.clone()), - started, - ))); - }; - let abandoned = abandoned - .raw_payload_json - .as_deref() - .and_then(|payload| serde_json::from_str::(payload).ok()); - if abandoned.as_ref().is_none_or(|abandoned| { - abandoned.reservation_id != existing.reservation_id - || abandoned.attempt != existing.attempt - || abandoned.capability != existing.capability - || abandoned.input_sha256 != existing.input_sha256 - }) { - return Err(Box::new( - self.finish( - command, - context, - input_sha256.to_string(), - Some(descriptor.clone()), - Some(decision), - ToolExecutionStatus::Indeterminate, - "Error: persisted tool abandonment is unreadable or does not own the reservation" - .to_string(), - None, - Some("persisted tool abandonment does not match reservation owner".to_string()), - Some(preparation.clone()), - started, - ), - )); - } - attempt = attempt.checked_add(1).ok_or_else(|| { - self.finish( - command, - context, - input_sha256.to_string(), - Some(descriptor.clone()), - Some(decision), - ToolExecutionStatus::Indeterminate, - "Error: tool idempotency retry generation overflow".to_string(), - None, - Some("tool idempotency retry generation overflow".to_string()), - Some(preparation.clone()), - started, - ) - })?; - } - Ok(None) => { - let reservation = ToolExecutionReservation { - operation_id: command.operation_id.clone(), - reservation_id: Uuid::now_v7().to_string(), - attempt, - capability: command.name.clone(), - input_sha256: input_sha256.to_string(), - }; - let payload = serde_json::to_string(&reservation).map_err(|error| { - self.finish( - command, - context, - input_sha256.to_string(), - Some(descriptor.clone()), - Some(decision), - ToolExecutionStatus::Indeterminate, - format!("Error: unable to encode tool idempotency reservation: {error}"), - None, - Some(error.to_string()), - Some(preparation.clone()), - started, - ) - })?; - let event = memory - .append_message_event(tool_execution_event_input( - context, - &reservation_key, - "tool.execution.reserved", - format!( - "operation_id={} capability={} attempt={attempt}", - command.operation_id, command.name - ), - payload, - )) - .await - .map_err(|error| { - self.finish( - command, - context, - input_sha256.to_string(), - Some(descriptor.clone()), - Some(decision), - ToolExecutionStatus::Indeterminate, - format!("Error: unable to reserve idempotent tool execution: {error}"), - None, - Some(error.to_string()), - Some(preparation.clone()), - started, - ) - })?; - // The reservation is a durable write the turn owed, and it - // sits between `ToolStart` and the backend's first poll - // with nothing else to show for it. Recorded now that it - // has come back, so a turn whose ledger is merely slow is - // not read as a turn that went silent — and so the hang - // report, when one is warranted, names where the turn - // actually was. - crate::agent::idle::beat(crate::agent::idle::ProgressKind::DurableWrite); - let recorded = event - .raw_payload_json - .as_deref() - .and_then(|payload| serde_json::from_str::(payload).ok()); - if recorded - .as_ref() - .is_none_or(|recorded| recorded.reservation_id != reservation.reservation_id) - { - return Err(Box::new(self.finish( - command, - context, - input_sha256.to_string(), - Some(descriptor.clone()), - Some(decision), - ToolExecutionStatus::Indeterminate, - "Error: another runtime owns this idempotent tool execution".to_string(), - None, - Some("another runtime owns this idempotent tool execution".to_string()), - Some(preparation.clone()), - started, - ))); - } - return Ok(Some(ToolExecutionLease { - _guard: guard, - memory: Arc::clone(memory), - abandonment_key: tool_execution_abandonment_key(&base_reservation_key, attempt), - reservation, - terminal_key, - })); - } - Err(error) => { - return Err(Box::new(self.finish( - command, - context, - input_sha256.to_string(), - Some(descriptor.clone()), - Some(decision), - ToolExecutionStatus::Indeterminate, - format!("Error: unable to inspect tool idempotency reservation: {error}"), - None, - Some(error.to_string()), - Some(preparation.clone()), - started, - ))); - } - } - } - } - - async fn commit_idempotent_execution( - &self, - lease: Option<&ToolExecutionLease>, - context: &ToolExecutionContext, - outcome: &ToolExecutionOutcome, - ) { - let Some(lease) = lease else { - return; - }; - let terminal = ToolExecutionTerminalRecord { - reservation: lease.reservation.clone(), - outcome: outcome.clone(), - }; - let payload = match serde_json::to_value(&terminal) - .map(crate::agent::terminal::redact_persisted_json) - .and_then(|value| serde_json::to_string(&value)) - { - Ok(payload) => payload, - Err(error) => { - tracing::error!(error = %error, "failed to encode idempotent tool terminal outcome"); - return; - } - }; - let appended = lease - .memory - .append_message_event(tool_execution_event_input( - context, - &lease.terminal_key, - "tool.execution.finalized", - format!("operation_id={} status={:?}", outcome.operation_id, outcome.status), - payload, - )) - .await; - // Same reasoning as the reservation write above, at the other end of - // the call: this is the last thing the turn does before the loop can - // announce the result, and until now it was silent. - crate::agent::idle::beat(crate::agent::idle::ProgressKind::DurableWrite); - if let Err(error) = appended { - tracing::error!( - operation_id = %outcome.operation_id, - error = %error, - "tool side effect completed but terminal idempotency outcome was not persisted" - ); - } - } - - async fn abandon_idempotent_execution( - &self, - lease: Option<&ToolExecutionLease>, - context: &ToolExecutionContext, - ) -> Result<(), String> { - let Some(lease) = lease else { - return Ok(()); - }; - let payload = serde_json::to_string(&lease.reservation) - .map_err(|error| format!("unable to encode tool idempotency abandonment: {error}"))?; - let event = lease - .memory - .append_message_event(tool_execution_event_input( - context, - &lease.abandonment_key, - "tool.execution.abandoned", - format!( - "operation_id={} attempt={}", - lease.reservation.operation_id, lease.reservation.attempt - ), - payload, - )) - .await - .map_err(|error| format!("unable to abandon tool idempotency reservation: {error}"))?; - let recorded = event - .raw_payload_json - .as_deref() - .and_then(|payload| serde_json::from_str::(payload).ok()); - if recorded.as_ref().is_none_or(|recorded| { - recorded.reservation_id != lease.reservation.reservation_id - || recorded.attempt != lease.reservation.attempt - || recorded.capability != lease.reservation.capability - || recorded.input_sha256 != lease.reservation.input_sha256 - }) { - return Err("another runtime owns the tool idempotency abandonment".to_string()); - } - Ok(()) - } - - fn replay_outcome( - &self, - command: &ToolExecutionCommand, - context: &ToolExecutionContext, - input_sha256: &str, - mut outcome: ToolExecutionOutcome, - ) -> ToolExecutionOutcome { - outcome.operation_id = command.operation_id.clone(); - outcome.replayed = true; - self.audit.record(ToolExecutionAuditRecord { - operation_id: command.operation_id.clone(), - capability: command.name.clone(), - backend_name: outcome.descriptor.as_ref().map(|value| value.backend_name.clone()), - adapter: outcome.descriptor.as_ref().map(|value| value.adapter), - effect: outcome.descriptor.as_ref().map(|value| value.effect), - decision: outcome.decision, - status: outcome.status, - preparation_strategy: outcome.preparation.as_ref().map(|value| value.strategy.clone()), - input_sha256: input_sha256.to_string(), - source: context.envelope.source.as_str().to_string(), - workspace_id: context.envelope.workspace_id.clone(), - session_key: context.envelope.session_key.clone(), - run_id: context.envelope.run_id.clone(), - parent_run_id: context.envelope.parent_run_id.clone(), - task_id: context.envelope.task_id.clone(), - error: outcome.error.clone(), - duration_ms: 0, - }); - outcome - } - - /// Run the fixed descriptor -> effect -> policy -> approval -> preparation -> - /// execute -> audit pipeline and return a typed terminal outcome. - pub async fn execute( - &self, - command: ToolExecutionCommand, - context: ToolExecutionContext, - cancellation: Option, - ) -> ToolExecutionOutcome { - let pending = context.execution_trace.as_ref().map(|trace| { - let binding = context.admitted_binding.as_ref(); - // Decision-free model turns still observe the identity of the - // concrete registered tool. An unknown name remains unbound; - // identifying a call never grants dispatch or marks it selected. - let observed = self.current_descriptor(&command.name).and_then(|descriptor| { - context - .turn_surface - .as_ref() - .and_then(|surface| surface.observed_capability_id(&command.name)) - .map(str::to_owned) - .or_else(|| { - super::capability::catalog::descriptor_identity(&descriptor) - .ok() - .map(|id| id.as_str().to_owned()) - }) - }); - trace.begin( - &command.operation_id, - binding.map(|binding| binding.capability_id()).or(observed.as_deref()), - binding.is_some_and(|binding| binding.is_selected()), - ) - }); - // `execute_inner` owns the whole descriptor, policy, approval, - // preparation and backend pipeline. Its state machine is large enough - // that embedding it in each caller's async frame can exhaust a default - // tokio worker stack when a tool starts another agent loop. Keep the - // canonical pipeline on the heap so every caller carries only a pointer - // while it is pending. - let mut outcome = Box::pin(self.execute_inner(command, context, cancellation)).await; - if let Some(stage) = crate::runtime::experiment_stage::current() { - if let Err(error) = stage.account_output(outcome.model_content.len()) { - outcome.status = ToolExecutionStatus::Failed; - outcome.error = Some(error.to_string()); - outcome.model_content = error.to_string(); - } - } - if let Some(pending) = pending { - pending.finish_with_error(outcome.status, outcome.error.as_deref()); - } - outcome - } - - async fn execute_inner( - &self, - mut command: ToolExecutionCommand, - context: ToolExecutionContext, - cancellation: Option, - ) -> ToolExecutionOutcome { - let started = Instant::now(); - // Every production tool call passes through here, which makes this the - // one place that has to register for the runtime work registry to be - // complete. The call gets its own kill handle, derived from the turn - // token so turn-level cancellation still reaches it, but cancellable on - // its own so an operator can end one stuck call without taking the - // whole turn down with it. - let cancellation = Some( - cancellation - .as_ref() - .map_or_else(CancellationToken::new, CancellationToken::child_token), - ); - let work = crate::runtime::registry::register_tool_call( - &command.name, - context.envelope.task_id.as_deref(), - cancellation.clone(), - ); - // A tool call starting is progress for the turn's idle detector, and - // this is the one place every production tool call passes through. - crate::agent::idle::beat(crate::agent::idle::ProgressKind::ToolStart); - let input_sha256 = format!("{:x}", Sha256::digest(command.arguments.to_string().as_bytes())); - if let Err((status, error)) = admission::admit(self, &context, &command.name) { - return self - .finish( - &command, - &context, - input_sha256, - None, - None, - status, - format!("Error: {error}"), - None, - Some(error), - None, - started, - ) - .with_refusal_cause(if status == ToolExecutionStatus::StaleCapability { - ToolCallRefusalReason::StaleCapability - } else { - ToolCallRefusalReason::PolicyDenied - }); - } - let Some(resolved) = self.resolve(&command.name) else { - let available = self - .descriptors() - .into_iter() - .map(|descriptor| descriptor.public_name) - .collect::>(); - let error = format!( - "unknown tool '{}'; available tools: {}", - command.name, - available.join(", ") - ); - return self - .finish( - &command, - &context, - input_sha256, - None, - None, - ToolExecutionStatus::UnknownTool, - format!("Error: {error}"), - None, - Some(error), - None, - started, - ) - .with_refusal_cause(ToolCallRefusalReason::UnknownTool); - }; - if let Err((status, error)) = admission::recheck_resolved(&context, &command.name) { - return self - .finish( - &command, - &context, - input_sha256, - None, - None, - status, - format!("Error: {error}"), - None, - Some(error), - None, - started, - ) - .with_refusal_cause(ToolCallRefusalReason::PolicyDenied); - } - let descriptor = resolved.descriptor; - if let Some(stage) = crate::runtime::experiment_stage::current() { - if let Err(error) = stage.claim_tool(&descriptor.backend_name) { - let error = error.to_string(); - return self - .finish( - &command, - &context, - input_sha256, - None, - None, - ToolExecutionStatus::Failed, - error.clone(), - None, - Some(error), - None, - started, - ) - .with_refusal_cause(ToolCallRefusalReason::PolicyDenied); - } - } - - if let Some(binding) = &context.admitted_binding { - let verified = (context.execution_trace.as_ref().is_some_and(|trace| !trace.is_sealed())) - .then_some(binding) - .ok_or(super::capability::execution_binding::ToolExecutionError::StaleCapability) - .and_then(|binding| binding.verify_admitted_descriptor(self, &context.envelope, &descriptor)); - if let Err(error) = verified { - let error = error.to_string(); - return self - .finish( - &command, - &context, - input_sha256, - Some(descriptor), - None, - ToolExecutionStatus::StaleCapability, - format!("Error: {error}"), - None, - Some(error), - None, - started, - ) - .with_refusal_cause(ToolCallRefusalReason::StaleCapability); - } - } - // V02-R9 / OQ-21: an owner-isolated origin runs only tools that enforce - // per-owner isolation. Keyed on the envelope rather than a channel name, - // so every isolated origin inherits it, and decided before policy so no - // autonomy level can widen it. - let private_filesystem = context - .owner_filesystem - .as_ref() - .filter(|scope| { - (context.controlled_case().is_some() - || (context.envelope.owner_isolated - && context.envelope.source == crate::runtime::envelope::RuntimeSource::Console)) - && (if context.controlled_case().is_some() { - scope.matches(&context.envelope.workspace_id, &context.envelope.resolved_owner_id()) - } else { - context - .envelope - .owner_id - .as_deref() - .is_some_and(|owner| scope.matches(&context.envelope.workspace_id, owner)) - }) - && descriptor.adapter == ToolAdapterKind::Native - && descriptor.backend_name == descriptor.public_name - && matches!( - descriptor.public_name.as_str(), - "file_read" | "file_write" | "file_edit" - ) - && resolved.backend.supports_owner_filesystem() - }) - .cloned(); - if context.envelope.owner_isolated && !admits_owner_isolated_origin(&descriptor) && private_filesystem.is_none() - { - let error = owner_isolation_refusal(&descriptor.public_name); - return self - .finish( - &command, - &context, - input_sha256, - Some(descriptor), - None, - ToolExecutionStatus::Denied, - format!("Error: {error}"), - None, - Some(error), - None, - started, - ) - .with_refusal_cause(ToolCallRefusalReason::OwnerIsolation); - } - // Structural validation runs before approval on purpose: a call that - // cannot legally execute must never reach an approval prompt, a - // reservation, or a backend. This is the one production gate for the - // tool contract, and every entry point funnels through here — including - // the gateway MCP server, which ran outside it until 0.8.126. The - // contract enforced is the one the caller was shown: see - // `ToolExecutionContext::schema_dialect`. - let contract = enforce_command_contract(&mut command.arguments, &descriptor, context.schema_dialect); - if let Err(error) = contract { - return self - .finish( - &command, - &context, - input_sha256, - Some(descriptor), - None, - ToolExecutionStatus::InvalidArguments, - format!("Error: {error}"), - None, - Some(error), - None, - started, - ) - .with_refusal_cause(ToolCallRefusalReason::InvalidArguments); - } - - let h2_invocation = match async { - use crate::runtime::h2_entry::{EntryAction, EntryInvocation}; - let requested = command.name == "skills_manage" - && command - .arguments - .get("action") - .and_then(serde_json::Value::as_str) - .is_some_and(|name| name.starts_with("lifecycle_experiment_")); - if let Some(origin) = context.h2_origin() { - origin.ensure_live()?; - anyhow::ensure!( - origin.profile().permits_tool(&command.name), - "tool is outside the fixed controlled profile" - ); - if command.name == "skills_manage" { - EntryAction::parse( - command - .arguments - .get("action") - .and_then(serde_json::Value::as_str) - .unwrap_or_default(), - )?; - } - } - if !requested { - return Ok::<_, anyhow::Error>(None); - } - let origin = context - .h2_origin() - .cloned() - .ok_or_else(|| anyhow::anyhow!("experiment action has no actual controlled source"))?; - let admission = context - .execution_admission - .as_ref() - .ok_or_else(|| anyhow::anyhow!("experiment action has no admitted descriptor"))?; - let verified = self - .verify_admitted_call(&context.envelope, admission, &descriptor, &command) - .map_err(|_| anyhow::anyhow!("experiment action has no admitted descriptor"))?; - // The initial pending call still needs to be recorded first. Full - // autonomy requests no approval and no review (R51); the - // admitted-descriptor verification above still applies. - let full = context.child_scope.as_ref().map_or_else( - || self.policy.autonomy_level(), - |scope| scope.gate_inputs().0.authority.level, - ) == crate::security::AutonomyLevel::Full; - if !full && crate::security::approval_operation::requires_explicit_grant(&command.name, &command.arguments) - { - return Ok(None); - } - Ok(Some(EntryInvocation::from_verified(origin, &verified, full).await?)) - } - .await - { - Ok(invocation) => invocation, - Err(error) => { - let error = error.to_string(); - return self - .finish( - &command, - &context, - input_sha256, - Some(descriptor), - None, - ToolExecutionStatus::Denied, - format!("Error: {error}"), - None, - Some(error), - None, - started, - ) - .with_refusal_cause(ToolCallRefusalReason::PolicyDenied); - } - }; - - // A child runs at its sealed scope level: its parent's level, or a - // named agent's own configured level (verified against the seal). - // Without a child scope the call runs at the service's level. - let effective_level = context.child_scope.as_ref().map_or_else( - || self.policy.autonomy_level(), - |scope| scope.gate_inputs().0.authority.level, - ); - let full = effective_level == crate::security::AutonomyLevel::Full; - let decision = admission::child_autonomy( - &context, - &descriptor, - self.policy.decide_at(&descriptor, &context, effective_level), - effective_level, - ); - // Ordinary calls honor the execution policy, including Full's Allow. - // Only the verified controlled H2 ingress retains its durable exact - // grant protocol, and only below Full: Full has no permission limits - // (R51). Deny always remains Deny. - let decision = if decision != ToolExecutionDecision::Deny - && !full - && context.h2_origin().is_some() - && crate::security::approval_operation::requires_explicit_grant(&descriptor.public_name, &command.arguments) - { - ToolExecutionDecision::Ask - } else { - decision - }; - if decision == ToolExecutionDecision::Deny { - let error = format!( - "tool '{}' is not permitted under the current execution policy", - descriptor.public_name - ); - self.record_call_refusal( - &command, - &context, - &input_sha256, - refusal_record::ToolCallRefusalReason::PolicyDenied, - &error, - ) - .await; - return self - .finish( - &command, - &context, - input_sha256, - Some(descriptor), - Some(decision), - ToolExecutionStatus::Denied, - format!("Error: {error}"), - None, - Some(error), - None, - started, - ) - .with_refusal_cause(ToolCallRefusalReason::PolicyDenied); - } - // Below Full, a path the tool's own policy refuses never reaches an - // approval prompt or a reservation (the structural-validation intent - // above). The backend re-checks at execute time with the same - // function. A private owner filesystem has its own resolver. - if effective_level != crate::security::AutonomyLevel::Full && private_filesystem.is_none() { - if let Err(refusal) = resolved - .backend - .path_precheck(&descriptor.public_name, &command.arguments) - .await - { - // The audit error and the durable row stay payload-free; only - // the model-visible result and the operator notice name the path. - let reason = refusal_record::ToolCallRefusalReason::from(refusal.reason()); - self.record_call_refusal(&command, &context, &input_sha256, reason, refusal.message()) - .await; - let error = format!("call refused before approval: {}", reason.as_str()); - let model_content = format!( - "Error: {}. The {} call did not run.", - refusal.message(), - descriptor.public_name - ); - return self - .finish( - &command, - &context, - input_sha256, - Some(descriptor), - Some(decision), - ToolExecutionStatus::Denied, - model_content, - None, - Some(error), - None, - started, - ) - .with_refusal_cause(reason); - } - } - - let mut runtime_approval_granted = false; - let mut runtime_grant = None; - let approval_run = context.envelope.run_id.clone().unwrap_or_default(); - let approval_channel = context.envelope.channel.clone().unwrap_or_default(); - let channel_gate = - crate::agent::channel_approval::lookup_for_call(&approval_run, context.envelope.parent_run_id.as_deref()); - let prx_operator_ask = decision == ToolExecutionDecision::Ask; - let channel_policy_ask = - channel_gate.as_ref().is_some_and(|gate| gate.force_ask) && decision == ToolExecutionDecision::Allow; - let decision = if channel_policy_ask && channel_gate.as_ref().is_some_and(|gate| !gate.effective_full) { - ToolExecutionDecision::Ask - } else { - decision - }; - if channel_policy_ask && channel_gate.as_ref().is_some_and(|gate| gate.effective_full) { - runtime_approval_granted = true; - } - if decision == ToolExecutionDecision::Ask && context.pending_approval_denied { - let reason = "approval is not available for this agent".to_string(); - self.record_approval_resolution( - &command, - &context, - &input_sha256, - ApprovalVerdict::Denied, - Some(ApprovalDenialCause::NoResolver), - Some(&reason), - ) - .await; - let model_content = approval_denied_model_content(&reason, &descriptor.public_name); - let mut outcome = self.finish( - &command, - &context, - input_sha256, - Some(descriptor), - Some(decision), - ToolExecutionStatus::ApprovalDenied, - model_content, - None, - Some(reason), - None, - started, - ); - outcome.approval_denial_cause = Some(ApprovalDenialCause::NoResolver); - return outcome; - } - // A supervised bridge owns its approval UI even when PRX also asks. - // A bridge that does not force approval keeps the durable PRX route. - if decision == ToolExecutionDecision::Ask - && channel_gate - .as_ref() - .is_some_and(|gate| !prx_operator_ask || gate.force_ask) - { - let approval_resolution: std::pin::Pin< - Box< - dyn std::future::Future> - + Send - + '_, - >, - > = Box::pin(crate::agent::channel_approval::resolve_tool( - &approval_run, - &descriptor.public_name, - &command.arguments, - &approval_channel, - )); - let resolved = approval_resolution.await; - if !matches!( - resolved, - Some( - crate::agent::turn_contracts::ApprovalDecision::Grant - | crate::agent::turn_contracts::ApprovalDecision::GrantForSession - ) - ) { - let reason = APPROVAL_DENIED_CHANNEL.to_string(); - self.record_approval_resolution( - &command, - &context, - &input_sha256, - ApprovalVerdict::Denied, - Some(ApprovalDenialCause::ChannelDenied), - Some(&reason), - ) - .await; - let model_content = approval_denied_model_content(&reason, &descriptor.public_name); - let mut outcome = self.finish( - &command, - &context, - input_sha256, - Some(descriptor), - Some(decision), - ToolExecutionStatus::ApprovalDenied, - model_content, - None, - Some(reason), - None, - started, - ); - outcome.approval_denial_cause = Some(ApprovalDenialCause::ChannelDenied); - return outcome; - } - self.record_approval_resolution(&command, &context, &input_sha256, ApprovalVerdict::Approved, None, None) - .await; - runtime_approval_granted = true; - if prx_operator_ask { - runtime_grant = self.policy.approved_call_grant(&command, &context); - } - } else if decision == ToolExecutionDecision::Ask { - let (approval, ledger_route) = self - .resolve_ordinary_approval(ToolApprovalRequest { - command: command.clone(), - descriptor: descriptor.clone(), - context: context.clone(), - }) - .await; - match approval { - ToolApprovalDecision::Approved { - runtime_approval_granted: approved, - runtime_grant: grant, - } => { - self.record_approval_resolution( - &command, - &context, - &input_sha256, - ApprovalVerdict::Approved, - None, - None, - ) - .await; - runtime_approval_granted = approved; - runtime_grant = grant; - } - ToolApprovalDecision::Denied { cause, reason } => { - self.record_approval_resolution( - &command, - &context, - &input_sha256, - ApprovalVerdict::Denied, - Some(cause), - Some(&reason), - ) - .await; - let model_content = approval_denied_model_content(&reason, &descriptor.public_name); - let mut outcome = self.finish( - &command, - &context, - input_sha256, - Some(descriptor), - Some(decision), - ToolExecutionStatus::ApprovalDenied, - model_content, - None, - Some(reason), - None, - started, - ); - outcome.approval_denial_cause = Some(cause); - return outcome; - } - ToolApprovalDecision::Cancelled { reason } => { - // An approval-ledger route that is still awaiting a grant - // stays pending: it writes no resolution row. - if !ledger_route { - self.record_approval_resolution( - &command, - &context, - &input_sha256, - ApprovalVerdict::Cancelled, - None, - Some(&reason), - ) - .await; - } - return self.finish( - &command, - &context, - input_sha256, - Some(descriptor), - Some(decision), - if ledger_route { - ToolExecutionStatus::AwaitingApproval - } else { - ToolExecutionStatus::Cancelled - }, - format!("Error: {reason}"), - None, - Some(reason), - None, - started, - ); - } - } - } - - let preparation = match self.preparation.prepare(&descriptor, &command, &context).await { - Ok(permit) => permit, - Err(error) => { - return self.finish( - &command, - &context, - input_sha256, - Some(descriptor), - Some(decision), - ToolExecutionStatus::PreparationDenied, - format!("Error: preparation denied tool execution: {error}"), - None, - Some(error), - None, - started, - ); - } - }; - - let arguments = match normalize_arguments(&command.arguments, &context, runtime_approval_granted, runtime_grant) - { - Ok(arguments) => arguments, - Err(error) => { - return self.finish( - &command, - &context, - input_sha256, - Some(descriptor), - Some(decision), - ToolExecutionStatus::InvalidArguments, - format!("Error: {error}"), - None, - Some(error), - Some(preparation), - started, - ); - } - }; - if cancellation.as_ref().is_some_and(CancellationToken::is_cancelled) { - return self.finish( - &command, - &context, - input_sha256, - Some(descriptor), - Some(decision), - ToolExecutionStatus::Cancelled, - "Error: tool execution cancelled".to_string(), - None, - Some("tool execution cancelled before reservation".to_string()), - Some(preparation), - started, - ); - } - - let exact_call = context - .execution_trace - .as_ref() - .and_then(|trace| trace.begin_exact_call(&command, &context, &input_sha256)); - let idempotency_lease = match self - .prepare_idempotent_execution( - &command, - &context, - &input_sha256, - &descriptor, - decision, - &preparation, - started, - ) - .await - { - Ok(lease) => { - if let Some(observation) = &exact_call { - observation.reserved(lease.as_ref().map(|lease| lease.reservation.attempt)); - } - lease - } - Err(outcome) => { - if let Some(observation) = exact_call { - observation.refused(outcome.status, outcome.replayed); - } - return *outcome; - } - }; - #[cfg(test)] - if let Some(gate) = self - .post_reservation_gate - .as_ref() - .filter(|gate| gate.armed.swap(false, AtomicOrdering::AcqRel)) - { - gate.entered.notify_one(); - gate.release.notified().await; - } - - // A scheduled claim can expire while approval, preparation or the - // idempotency reservation awaits. Validate its live authority before - // constructing/polling the backend future. The guard may read SQLite, - // so it runs on the blocking pool, never inside the schema verifier. - if let Some(authority_guard) = context.envelope.authority_guard.clone() { - let validate = async { - crate::runtime::blocking::spawn_blocking(move || authority_guard.validate()) - .await - .is_ok_and(|result| result.unwrap_or(false)) - }; - let current = if let Some(token) = cancellation.as_ref() { - tokio::select! { - biased; - () = token.cancelled() => false, - current = validate => current, - } - } else { - validate.await - }; - if !current { - let cancelled = cancellation.as_ref().is_some_and(CancellationToken::is_cancelled); - let status = if cancelled { - ToolExecutionStatus::Cancelled - } else { - ToolExecutionStatus::StaleCapability - }; - let error = if cancelled { - "tool execution cancelled during runtime authority validation" - } else { - "runtime execution authority is expired or unavailable" - }; - let abandonment = self - .abandon_idempotent_execution(idempotency_lease.as_ref(), &context) - .await; - let (status, error) = match abandonment { - Ok(()) => (status, error.to_owned()), - Err(error) => (ToolExecutionStatus::Indeterminate, error), - }; - if let Some(observation) = exact_call { - observation.complete(status); - } - return self.finish( - &command, - &context, - input_sha256, - Some(descriptor), - Some(decision), - status, - format!("Error: {error}"), - None, - Some(error), - Some(preparation), - started, - ); - } - } - - // Approval, preparation, reservation and claim may have awaited while the - // live registry changed. Recheck before the backend future is polled. - if let Err((status, error)) = admission::admit_child(self, &context, &command.name, true) - .and_then(|()| admission::admit_called_tokens(self, &context, &command.name)) - .and_then(|()| admission::admit_called_spend(self, &context, &command.name)) - { - let abandonment = self - .abandon_idempotent_execution(idempotency_lease.as_ref(), &context) - .await; - let (status, error) = match abandonment { - Ok(()) => (status, error), - Err(error) => (ToolExecutionStatus::Indeterminate, error), - }; - if let Some(observation) = exact_call { - observation.complete(status); - } - return self.finish( - &command, - &context, - input_sha256, - Some(descriptor), - Some(decision), - status, - format!("Error: {error}"), - None, - Some(error), - Some(preparation), - started, - ); - } - if let Some(binding) = &context.admitted_binding { - let verified = (context.execution_trace.as_ref().is_some_and(|trace| !trace.is_sealed())) - .then_some(binding) - .ok_or(super::capability::execution_binding::ToolExecutionError::StaleCapability) - .and_then(|binding| binding.verify_admitted_descriptor(self, &context.envelope, &descriptor)); - if let Err(error) = verified { - let abandonment = self - .abandon_idempotent_execution(idempotency_lease.as_ref(), &context) - .await; - let (status, error) = match abandonment { - Ok(()) => (ToolExecutionStatus::StaleCapability, error.to_string()), - Err(error) => (ToolExecutionStatus::Indeterminate, error), - }; - if let Some(observation) = exact_call { - observation.complete(status); - } - return self.finish( - &command, - &context, - input_sha256, - Some(descriptor), - Some(decision), - status, - format!("Error: {error}"), - None, - Some(error), - Some(preparation), - started, - ); - } - } - // The resolved Arc is immutable for the in-flight call even if a - // dynamic catalog refresh changes future descriptor snapshots. - let backend = resolved.backend; - let child_tool_name = match command.name.as_str() { - "delegate" => Some("delegate"), - "sessions_spawn" => Some("sessions_spawn"), - _ => None, - }; - let child_call_context = child_tool_name.map(|tool_name| ChildCallContext { - tool_name, - context: context.clone(), - }); - // Scoped so any child process the tool spawns registers with this call - // as its parent, which is what makes a cascading kill possible. - let backend_cancellation = cancellation.clone(); - let backend_h2_invocation = h2_invocation.clone(); - let exact_call_ref = exact_call.as_ref(); - let public_name = command.name.as_str(); - let execution_parameters = descriptor.execution_parameters.clone(); - let schema_dialect = context.schema_dialect; - let live_frames = context - .live_turn - .as_ref() - .map(|live| live.0.frames(&context.envelope, &std::collections::HashSet::new())); - let operation_id = &command.operation_id; - let tool_future = crate::runtime::registry::scope_current( - work.id(), - CHILD_CALL_CONTEXT.scope( - child_call_context, - super::capability::search_tool::with_search_authority( - if command.name == "capability_search" { - context.capability_search.clone() - } else { - None - }, - super::capability::execution_binding::scope_dispatch_binding( - if backend.root_name() == "mcp_call" { - context.admitted_binding.as_ref() - } else { - None - }, - async move { - // Emit only at backend entry, after approval and all - // admission gates, without changing legacy event sinks. - if let Some(live) = live_frames { - live.emit(&crate::agent::turn_contracts::ToolLoopEvent::ToolStarted { - tool_call_id: operation_id.clone(), - name: public_name.to_owned(), - args: String::new(), - }); - } - if let Some(observation) = exact_call_ref { - observation.backend_started(); - } - super::owner_filesystem_dispatch::scope( - private_filesystem, - crate::tools::schema::with_execution_contract( - execution_parameters, - schema_dialect, - crate::runtime::h2_entry::scope_invocation( - backend_h2_invocation.map(|invocation| { - (invocation, backend_cancellation.clone().unwrap_or_default()) - }), - super::effective_autonomy::scope( - effective_level, - backend.invoke_observed(public_name, arguments, backend_cancellation), - ), - ), - ), - ) - .await - }, - ), - ), - ), - ); - let tool_future = async { - if let Some(invocation) = &h2_invocation { - invocation.ensure_live()?; - } - tool_future.await - }; - let mut cancelled_before_invoke = false; - let raw_result = if let (Some(token), Some(_)) = (cancellation.clone(), idempotency_lease.as_ref()) { - // The outer cancellation race owns only the ReservedNotStarted - // phase. The wrapper marks the handoff immediately before the - // backend's first poll. Once that boundary is crossed we retain - // ownership and drive the backend's cooperative cancellation to a - // terminal result instead of dropping an indeterminate side - // effect. - let backend_started = Arc::new(AtomicBool::new(false)); - tokio::pin!(tool_future); - let started_for_poll = Arc::clone(&backend_started); - let tracked_future = std::future::poll_fn(move |context| { - started_for_poll.store(true, AtomicOrdering::Release); - tool_future.as_mut().poll(context) - }); - tokio::pin!(tracked_future); - tokio::select! { - biased; - () = token.cancelled() => { - if backend_started.load(AtomicOrdering::Acquire) { - Some(tracked_future.as_mut().await) - } else { - cancelled_before_invoke = true; - None - } - }, - result = tracked_future.as_mut() => Some(result), - } - } else if let Some(token) = cancellation { - tokio::select! { - biased; - () = token.cancelled() => None, - result = tool_future => Some(result), - } - } else { - Some(tool_future.await) - }; - - let abandonment_error = if cancelled_before_invoke { - self.abandon_idempotent_execution(idempotency_lease.as_ref(), &context) - .await - .err() - } else { - None - }; - let (raw_result, process) = match raw_result { - Some(Ok(observed)) => (Some(Ok(observed.result)), observed.process), - Some(Err(error)) => (Some(Err(error)), None), - None => (None, None), - }; - let mut outcome = match (raw_result, abandonment_error) { - (None, Some(error)) => self.finish( - &command, - &context, - input_sha256, - Some(descriptor), - Some(decision), - ToolExecutionStatus::Indeterminate, - format!("Error: {error}"), - None, - Some(error), - Some(preparation), - started, - ), - (None, None) => self.finish( - &command, - &context, - input_sha256, - Some(descriptor), - Some(decision), - ToolExecutionStatus::Cancelled, - "Error: tool execution cancelled".to_string(), - None, - Some("tool execution cancelled".to_string()), - Some(preparation), - started, - ), - (Some(Ok(result)), _) - if is_tool_cancelled_result(&result) - || process - .as_ref() - .is_some_and(|process| process.termination == super::traits::ProcessTermination::Cancelled) => - { - self.finish( - &command, - &context, - input_sha256, - Some(descriptor), - Some(decision), - ToolExecutionStatus::Cancelled, - "Error: tool execution cancelled".to_string(), - Some(result), - Some("tool execution cancelled".to_string()), - Some(preparation), - started, - ) - } - (Some(Ok(result)), _) => { - let (status, model_content, error) = if result.success { - let model_content = match result.error.as_deref().filter(|error| !error.is_empty()) { - Some(diagnostics) => format!("Output:\n{}\n\nDiagnostics:\n{diagnostics}", result.output), - None => result.output.clone(), - }; - (ToolExecutionStatus::Succeeded, model_content, None) - } else { - let error = process - .as_ref() - .map(|process| { - process - .diagnostic - .clone() - .unwrap_or_else(|| result.error.clone().unwrap_or_else(|| process.summary())) - }) - .unwrap_or_else(|| result.error.clone().unwrap_or_else(|| result.output.clone())); - let hint = super::error_hints::recovery_hint(&command.name, &error); - let mut model_content = if hint.is_empty() { - format!("Error: {error}") - } else { - format!("Error: {error}\n{hint}") - }; - // `error` is a separate diagnostic channel, not a replacement - // for output produced before failure. Keep the Error prefix - // used by existing history consumers and avoid duplicating - // output when it was the fallback error above. - if result.error.is_some() && !result.output.is_empty() { - model_content.push_str(&format!("\n\nOutput:\n{}", result.output)); - } - (ToolExecutionStatus::Failed, model_content, Some(error)) - }; - self.finish( - &command, - &context, - input_sha256, - Some(descriptor), - Some(decision), - status, - model_content, - Some(result), - error, - Some(preparation), - started, - ) - } - (Some(Err(error)), _) => { - // The trace alone classifies the full source chain; the outcome and - // everything built from it keep the plain message. - if let Some(trace) = context.execution_trace.as_ref() { - trace.note_error_detail(&command.operation_id, format!("{error:#}")); - } - let status = if error - .downcast_ref::() - .is_some() - { - ToolExecutionStatus::InvalidArguments - } else { - ToolExecutionStatus::Failed - }; - let error = error.to_string(); - let hint = super::error_hints::recovery_hint(&command.name, &error); - let model_content = if hint.is_empty() { - format!("Error executing {}: {error}", command.name) - } else { - format!("Error executing {}: {error}\n{hint}", command.name) - }; - self.finish( - &command, - &context, - input_sha256, - Some(descriptor), - Some(decision), - status, - model_content, - None, - Some(error), - Some(preparation), - started, - ) - } - }; - outcome.process = process; - if let (Some(process), Some(result)) = (&outcome.process, &outcome.result) { - outcome.model_content = process.render(result); - if !result.success { - let hint = - super::error_hints::recovery_hint(&command.name, outcome.error.as_deref().unwrap_or_default()); - if !hint.is_empty() { - outcome.model_content.push('\n'); - outcome.model_content.push_str(&hint); - } - } - } - if let Some(observation) = exact_call { - observation.complete(outcome.status); - } - if !cancelled_before_invoke { - self.commit_idempotent_execution(idempotency_lease.as_ref(), &context, &outcome) - .await; - } - outcome - } - - #[allow(clippy::too_many_arguments)] - fn finish( - &self, - command: &ToolExecutionCommand, - context: &ToolExecutionContext, - input_sha256: String, - descriptor: Option, - decision: Option, - status: ToolExecutionStatus, - model_content: String, - result: Option, - error: Option, - preparation: Option, - started: Instant, - ) -> ToolExecutionOutcome { - // ... and a tool call producing its terminal outcome is progress too. - crate::agent::idle::beat(crate::agent::idle::ProgressKind::ToolEnd); - let duration_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX); - self.audit.record(ToolExecutionAuditRecord { - operation_id: command.operation_id.clone(), - capability: command.name.clone(), - backend_name: descriptor.as_ref().map(|value| value.backend_name.clone()), - adapter: descriptor.as_ref().map(|value| value.adapter), - effect: descriptor.as_ref().map(|value| value.effect), - decision, - status, - preparation_strategy: preparation.as_ref().map(|value| value.strategy.clone()), - input_sha256, - source: context.envelope.source.as_str().to_string(), - workspace_id: context.envelope.workspace_id.clone(), - session_key: context.envelope.session_key.clone(), - run_id: context.envelope.run_id.clone(), - parent_run_id: context.envelope.parent_run_id.clone(), - task_id: context.envelope.task_id.clone(), - error: error.clone(), - duration_ms, - }); - ToolExecutionOutcome { - operation_id: command.operation_id.clone(), - descriptor, - decision, - status, - model_content, - result, - process: None, - error, - preparation, - duration_ms, - replayed: false, - approval_denial_cause: None, - refusal_cause: None, - } - } -} - -fn tool_execution_event_input( - context: &ToolExecutionContext, - idempotency_key: &str, - event_type: &str, - content: String, - raw_payload_json: String, -) -> MessageEventInput { - MessageEventInput { - event_id: None, - idempotency_key: Some(idempotency_key.to_string()), - workspace_id: context.envelope.workspace_id.clone(), - owner_id: context.envelope.owner_id.clone(), - source: context.envelope.source.as_str().into(), - channel: context.envelope.channel.clone(), - session_key: Some(context.envelope.session_key.clone()), - agent_partition: context.envelope.agent_partition.clone(), - parent_session_key: context.envelope.parent_session_key.clone(), - run_id: context.envelope.run_id.clone(), - parent_run_id: context.envelope.parent_run_id.clone(), - agent_id: context.envelope.agent_id.clone(), - persona_id: context.envelope.persona_id.clone(), - sender: context.envelope.sender.clone(), - recipient: context.envelope.recipient.clone(), - role: "event".to_string(), - event_type: event_type.to_string(), - subject: None, - goal_id: None, - causation_event_id: context.envelope.source_message_event_id.clone(), - correlation_id: context.envelope.run_id.clone(), - attempt_id: context.envelope.attempt_id.clone(), - lease_epoch: context.envelope.lease_epoch, - config_generation_id: context.envelope.config_generation_id, - config_source_revision: context.envelope.config_source_revision.clone(), - content, - raw_payload_json: Some(raw_payload_json), - visibility: context.envelope.visibility.clone(), - } -} - -/// Tool-argument name prefixes reserved for the runtime. -/// -/// Every argument under one of these prefixes is *runtime-only*: it is written -/// by the runtime immediately before a tool executes and it carries trust — -/// the caller scope (`_zc_scope`, `_zc_scope_trusted`, `_prx_scope_trusted`), -/// the approval grant (`_zc_approval_granted`, `_zc_approval_grant`) and the -/// principal binding (`_zc_principal`). None of it may ever survive from an -/// externally supplied payload (model output, an MCP gateway HTTP body, a -/// third-party tool result) into tool execution, and none of it may leak back -/// out to a third-party MCP server. -/// -/// Stripping is by prefix on purpose. A per-key blocklist fails *open*: adding -/// a new `_zc_*` key and forgetting one of the injection sites silently accepts -/// a forged one. With a prefix the same mistake fails *closed* — the runtime -/// key simply goes missing, which surfaces immediately as a denied or -/// untrusted call instead of an authorization bypass. -pub const RUNTIME_ONLY_ARG_PREFIXES: [&str; 2] = ["_zc_", "_prx_"]; - -/// Tools that enforce per-owner isolation for an owner-isolated origin -/// (V02-R9 / OQ-21). -/// -/// An owner-isolated context — today an externally authenticated MCP caller — -/// may execute only these. Stateful tools rebuild their principal from the service-authored -/// `_zc_scope` and applies [`scope_requires_owner_match`] (or the run registry's -/// owner scope) to every row it reads or deletes. Every other tool is refused: -/// autonomy approval is not consulted at `AutonomyLevel::Full`, so the operator's -/// `mcp_server.exposed_tools` list would otherwise be the only boundary between -/// an external caller and a mutating tool that does not scope its effect by -/// owner. A tool joins this list only once it is owner-aware or reads no private -/// runtime state. Web search is stateless; its provider key and quota are shared. -/// -/// `session_status` and `sessions_send` are owner-aware for in-process turns -/// but the gateway does not register them, so they stay off the list until it -/// does: an exposed entry is then refused with 403 before any identity binding -/// is written, instead of passing this gate and answering 404 afterwards. -pub use crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS; - -/// Whether `name` is on [`OWNER_ISOLATION_AWARE_TOOLS`]. -#[must_use] -pub fn is_owner_isolation_aware_tool(name: &str) -> bool { - OWNER_ISOLATION_AWARE_TOOLS.contains(&name) -} - -/// Whether a resolved tool may run for an owner-isolated origin. -/// -/// The public name must be on the list **and** be served by the backend of the -/// same name, so a dynamic MCP, WASM or skill alias that happens to publish a -/// listed name from another backend is refused: it is not the audited tool. -#[must_use] -pub fn admits_owner_isolated_origin(descriptor: &ToolDescriptor) -> bool { - crate::tools::capability::policy::admits_owner_isolated_identity(&descriptor.public_name, &descriptor.backend_name) -} - -/// The refusal given to an owner-isolated caller for a tool that does not -/// enforce per-owner isolation. -#[must_use] -pub fn owner_isolation_refusal(tool_name: &str) -> String { - format!("tool '{tool_name}' is not available to an owner-isolated caller: it does not enforce per-owner isolation") -} - -/// Key inside the service-authored `_zc_scope` that marks the turn's origin as -/// owner-isolated (C03 / V02-R4). -/// -/// Written only when [`crate::runtime::envelope::RuntimeEnvelope::owner_isolated`] -/// is set, which today means an externally authenticated MCP caller. Tools that -/// rebuild a [`crate::memory::MemoryPrincipal`] from the scope read it back with -/// [`scope_requires_owner_match`]. -pub const SCOPE_OWNER_ISOLATED_KEY: &str = "owner_isolated"; - -/// The agent partition the runtime authored into a trusted `_zc_scope` (MA-01b3). -/// -/// Read only when `_zc_scope_trusted` is literally `true`, so a model-supplied -/// `_zc_scope` never yields a partition. A malformed value reads as `None`. -#[must_use] -pub(crate) fn trusted_scope_agent_partition(args: &serde_json::Value) -> Option { - let trusted = args - .get("_zc_scope_trusted") - .and_then(serde_json::Value::as_bool) - .unwrap_or(false); - if !trusted { - return None; - } - let raw = args.get("_zc_scope")?.get("agent_partition")?; - match serde_json::from_value(raw.clone()) { - Ok(partition) => Some(partition), - Err(error) => { - tracing::warn!(error = %error, "ignoring malformed trusted agent_partition in _zc_scope"); - None - } - } -} - -/// The agent partition a read made for this call must stay in (MA-01h). -/// -/// `Ok(None)` only when the call carries no trusted scope or its trusted scope -/// names no partition (a turn that runs under none, such as the terminal). A -/// trusted scope whose partition is present but unreadable is refused, never -/// read as unpartitioned. -/// -/// # Errors -/// -/// [`crate::memory::AgentPartitionUnreadable`] for an unreadable partition. -pub(crate) fn trusted_scope_read_partition( - args: &serde_json::Value, -) -> Result, crate::memory::AgentPartitionUnreadable> { - let trusted = args - .get("_zc_scope_trusted") - .and_then(serde_json::Value::as_bool) - .unwrap_or(false); - if !trusted { - return Ok(None); - } - let Some(raw) = args.get("_zc_scope").and_then(|scope| scope.get("agent_partition")) else { - return Ok(None); - }; - serde_json::from_value(raw.clone()).map(Some).map_err(|error| { - tracing::warn!( - error_category = ?error.classify(), - "refusing a read whose trusted agent_partition is malformed" - ); - crate::memory::AgentPartitionUnreadable - }) -} - -/// Who is creating scheduled work with this call, and at what level: the -/// call's level from the execution service's carrier (`None` off the service -/// path) and the agent from the trusted scope's partition. A trusted scope -/// without a partition is Main's; an untrusted one names nobody. -#[must_use] -pub(crate) fn creator_stamp_from_trusted_args(args: &serde_json::Value) -> crate::security::agent_level::CreatorStamp { - use crate::memory::PartitionKey; - use crate::security::agent_level::{CREATOR_MAIN, CreatorStamp, creator_agent_named}; - let trusted = args - .get("_zc_scope_trusted") - .and_then(serde_json::Value::as_bool) - .unwrap_or(false) - && args.get("_zc_scope").is_some_and(serde_json::Value::is_object); - let agent = trusted.then( - || match trusted_scope_agent_partition(args).map(|partition| partition.key) { - Some(PartitionKey::Named { name, incarnation }) => creator_agent_named(name.as_str(), &incarnation), - Some(PartitionKey::Main) | None => CREATOR_MAIN.to_owned(), - }, - ); - CreatorStamp { - level: super::effective_autonomy::current(), - agent, - } -} - -/// Read the owner-isolation marker back out of tool arguments. -/// -/// Honoured only when `_zc_scope_trusted` is set, and that whole block is -/// re-authored by [`normalize_arguments`] from the authenticated execution -/// context after [`strip_runtime_only_args`] has dropped everything the caller -/// supplied — so a caller can neither forge the marker nor clear it. -#[must_use] -pub fn scope_requires_owner_match(args: &serde_json::Value) -> bool { - args.get("_zc_scope_trusted") - .and_then(serde_json::Value::as_bool) - .unwrap_or(false) - && args - .get("_zc_scope") - .and_then(serde_json::Value::as_object) - .and_then(|scope| scope.get(SCOPE_OWNER_ISOLATED_KEY)) - .and_then(serde_json::Value::as_bool) - .unwrap_or(false) -} - -/// Whether `key` names a runtime-only tool argument (see -/// [`RUNTIME_ONLY_ARG_PREFIXES`]). -#[must_use] -pub fn is_runtime_only_arg(key: &str) -> bool { - RUNTIME_ONLY_ARG_PREFIXES.iter().any(|prefix| key.starts_with(prefix)) -} - -/// Single source of truth for scrubbing runtime-only arguments off a tool -/// argument object. -/// -/// Every site that injects trusted runtime state into tool arguments must call -/// this first, and every site that forwards arguments to an untrusted process -/// must call it last. -pub fn strip_runtime_only_args(root: &mut serde_json::Map) { - root.retain(|key, _| !is_runtime_only_arg(key)); -} - -/// Enforce a tool's published contract on caller-supplied arguments: validate -/// them, then make the document say what the contract means. -/// -/// The descriptor's full `execution_parameters` (or public `parameters` when -/// no private contract exists) is the truth source: native, -/// skill, MCP alias and WASM plugin tools all reach this gate. Migrated built-ins -/// keep their original conditional rules here while publishing a flat schema. -/// `dialect` replays the provider's keyword lowering on the full contract: -/// Gemini strips `additionalProperties` and bounds using the same -/// [`crate::tools::schema::SchemaCleanr`] strategy as publication. Runtime-only -/// keys are removed first because the runtime authors them after validation and -/// they are intentionally absent from public schemas. -/// -/// On success the arguments are normalized in place — see -/// [`crate::tools::schema::CompiledToolSchema::normalize_integral_numbers`]. -/// That is why this takes `&mut`: enforcement is not only a verdict. -pub(crate) fn enforce_command_contract( - arguments: &mut serde_json::Value, - descriptor: &ToolDescriptor, - dialect: ToolSchemaDialect, -) -> Result<(), String> { - let compiled = crate::tools::schema::compiled_tool_schema_for_dialect( - &descriptor.public_name, - dialect, - descriptor - .execution_parameters - .as_deref() - .unwrap_or(&descriptor.parameters), - ); - if !arguments.is_object() { - return Err("tool arguments must be a JSON object".to_string()); - } - let issues = - crate::tools::schema::with_public_arguments(arguments, |public| compiled.validate_tool_arguments(public)); - if !issues.is_empty() { - return Err(crate::tools::schema::describe_argument_validation_issues( - &descriptor.public_name, - &issues, - )); - } - // The contract holds, so the document is now made to say what the contract - // says it means: `integer` is a mathematical value in JSON Schema, and a - // model that answers `200.0` for one is correct — but every executor reads - // integers with `as_u64()` / `as_i64()`, which see `Float(200.0)` as absent - // and fall back to a default. Coercing here, against the published schema, - // is the one place that knows which fields were declared `integer`; doing - // it in each executor would be ~20 copies of a rule none of them can state. - compiled.normalize_integral_numbers(arguments); - Ok(()) -} - -fn normalize_arguments( - arguments: &serde_json::Value, - context: &ToolExecutionContext, - runtime_approval_granted: bool, - runtime_grant: Option, -) -> Result { - let mut arguments = arguments.clone(); - let root = arguments - .as_object_mut() - .ok_or_else(|| "tool arguments must be a JSON object".to_string())?; - - // Structural validation against `descriptor.parameters` already ran in - // `ToolExecutionService::execute`, before approval. Re-checking here would - // be a second, divergent rule set. - - // Single source of truth: drop every runtime-only key an external caller - // may have supplied before re-injecting the authoritative ones below. - strip_runtime_only_args(root); - - let mut scope = serde_json::json!({ - "sender": context.sender(), - "channel": context.channel(), - "chat_type": context.chat_type, - "chat_id": context.chat_id, - "workspace_id": context.envelope.workspace_id, - "session_key": context.envelope.session_key, - "runtime_source": context.envelope.source.as_str(), - }); - if let Some(scope) = scope.as_object_mut() { - insert_optional(scope, "owner_id", context.envelope.owner_id.as_deref()); - // C03: only written when the origin is owner-isolated, so every other - // turn's authored scope stays byte-identical to the pre-C03 one. - if context.envelope.owner_isolated { - scope.insert(SCOPE_OWNER_ISOLATED_KEY.to_string(), serde_json::Value::Bool(true)); - } - if let Some(partition) = &context.envelope.agent_partition { - scope.insert( - "agent_partition".to_string(), - serde_json::to_value(partition).map_err(|error| error.to_string())?, - ); - } - insert_optional(scope, "topic_id", context.envelope.topic_id.as_deref()); - insert_optional(scope, "task_id", context.envelope.task_id.as_deref()); - insert_optional(scope, "run_id", context.envelope.run_id.as_deref()); - insert_optional(scope, "parent_run_id", context.envelope.parent_run_id.as_deref()); - insert_optional( - scope, - "source_message_event_id", - context.envelope.source_message_event_id.as_deref(), - ); - if let Some(config_generation_id) = context.envelope.config_generation_id { - scope.insert( - "config_generation_id".to_string(), - serde_json::Value::Number(config_generation_id.into()), - ); - } - insert_optional( - scope, - "config_source_revision", - context.envelope.config_source_revision.as_deref(), - ); - } - root.insert("_zc_scope".to_string(), scope); - root.insert("_zc_scope_trusted".to_string(), serde_json::Value::Bool(true)); - // Local-operator origin marker (T18). Unlike `_zc_scope_trusted` — which - // asserts "the `_zc_scope` block above was written by the runtime", and is - // therefore always true here — this one asserts "*a human at this machine's - // terminal* drove this turn". It is the guard on destructive `gateway` - // actions. Authored here and only here: the caller-supplied value was - // already dropped by `strip_runtime_only_args` above, so whatever the model - // or an HTTP body asked for is irrelevant either way. - root.insert( - "_prx_scope_trusted".to_string(), - serde_json::Value::Bool(context.is_local_operator()), - ); - // Local-root marker: the call's root principal is the local operator - // (see `ToolExecutionContext::is_local_root`). At Full it admits the - // destructive `gateway` actions for the operator's children and jobs. - // Authored here and only here, after caller values were stripped. - root.insert( - "_prx_local_root".to_string(), - serde_json::Value::Bool(context.is_local_root()), - ); - root.insert( - RUNTIME_APPROVAL_GRANTED_ARG.to_string(), - serde_json::Value::Bool(runtime_approval_granted), - ); - if let Some(grant) = runtime_grant { - root.insert(RUNTIME_APPROVAL_GRANT_ARG.to_string(), grant); - } - Ok(arguments) -} - -fn insert_optional(map: &mut serde_json::Map, key: &str, value: Option<&str>) { - if let Some(value) = value { - map.insert(key.to_string(), serde_json::Value::String(value.to_string())); - } -} +include!("execution/section_1.rs"); +include!("execution/section_2.rs"); +include!("execution/section_3.rs"); #[cfg(test)] pub(crate) mod tests; diff --git a/src/tools/execution/section_1.rs b/src/tools/execution/section_1.rs new file mode 100644 index 000000000..f97836f29 --- /dev/null +++ b/src/tools/execution/section_1.rs @@ -0,0 +1,1706 @@ +use super::schema::ToolSchemaDialect; +use super::traits::{Tool, ToolCategory, ToolResult, ToolSpec, ToolTier, is_tool_cancelled_result}; +use crate::capability::CapabilityAvailability; +use crate::memory::{Memory, MessageEventInput}; +use crate::runtime::envelope::RuntimeEnvelope; +use crate::security::SecurityPolicy; +use crate::security::policy::{RUNTIME_APPROVAL_GRANT_ARG, RUNTIME_APPROVAL_GRANTED_ARG, ToolDecision}; +use async_trait::async_trait; +use parking_lot::Mutex; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::HashMap; +use std::future::Future; +use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering}; +use std::sync::{Arc, OnceLock, Weak}; +use std::time::Instant; +use tokio::sync::Mutex as AsyncMutex; +use tokio_util::sync::CancellationToken; +use uuid::Uuid; + +/// Coarse side-effect classification used by the common policy stage. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ToolEffect { + Read, + Act, +} + +/// Adapter family selected for a public tool name. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ToolAdapterKind { + Native, + McpAlias, + WasmPlugin, + Skill, +} + +/// Small raw execution port consumed by the application service. +/// +/// Backends expose descriptors and invocation only; policy, approval, execution +/// preparation, auditing, and typed outcomes remain service-owned. +#[async_trait] +pub trait ToolBackend: Send + Sync { + /// Read-only operation metadata; never an execution or approval permit. + async fn resolve_approval_operation( + &self, + _public_name: &str, + _arguments: &serde_json::Value, + ) -> anyhow::Result> { + Ok(None) + } + /// Read-only below-Full path precheck; see [`Tool::path_precheck`]. + async fn path_precheck( + &self, + _public_name: &str, + _arguments: &serde_json::Value, + ) -> Result<(), crate::security::PathRefusal> { + Ok(()) + } + /// Defaults closed for aliases, plugins and unaudited backends. + fn supports_owner_filesystem(&self) -> bool { + false + } + fn process_worker_compatible(&self) -> bool { + true + } + fn execution_parameters_schema(&self) -> Option> { + None + } + fn root_name(&self) -> &str; + fn specs(&self) -> Vec; + fn catalog_specs(&self) -> Vec { + self.specs() + } + fn immutable_catalog_specs(&self) -> Option<&[ToolSpec]> { + None + } + fn shared_catalog_snapshot(&self) -> Option { + None + } + fn catalog_binding_snapshot(&self) -> std::collections::BTreeMap { + std::collections::BTreeMap::new() + } + fn spec_for_name(&self, public_name: &str) -> Option { + self.specs().into_iter().find(|spec| spec.name == public_name) + } + fn supports_name(&self, public_name: &str) -> bool; + fn tier(&self) -> ToolTier; + fn categories(&self) -> Vec; + fn adapter_kind(&self, public_name: &str) -> ToolAdapterKind; + fn availability(&self) -> CapabilityAvailability { + CapabilityAvailability::ready(format!("executable backend '{}' is registered", self.root_name())) + } + + fn catalog_availability_is_configured(&self) -> bool { + let availability = self.availability(); + availability.level >= crate::capability::CapabilityAvailabilityLevel::Configured + || availability.reason.trim().is_empty() + } + + async fn invoke( + &self, + public_name: &str, + arguments: serde_json::Value, + cancellation: Option, + ) -> anyhow::Result; + + async fn invoke_observed( + &self, + public_name: &str, + arguments: serde_json::Value, + cancellation: Option, + ) -> anyhow::Result { + self.invoke(public_name, arguments, cancellation).await.map(Into::into) + } +} + +/// Compatibility adapter for the existing native and MCP [`Tool`] registry. +pub struct LegacyToolAdapter { + tool: Arc, +} + +/// Named adapter over a shared boxed registry. Chat Redux keeps this legacy +/// registry alive across provider turns, so migration must borrow it rather +/// than consume or duplicate stateful tool instances. +struct SharedRegistryToolAdapter { + registry: Arc>>, + root_name: String, +} + +impl SharedRegistryToolAdapter { + fn tool(&self) -> Option<&dyn Tool> { + self.registry + .iter() + .find(|tool| tool.name() == self.root_name) + .map(Box::as_ref) + } +} + +#[async_trait] +impl ToolBackend for SharedRegistryToolAdapter { + async fn invoke_observed( + &self, + public_name: &str, + arguments: serde_json::Value, + cancellation: Option, + ) -> anyhow::Result { + self.tool() + .ok_or_else(|| anyhow::anyhow!("shared tool is no longer registered"))? + .execute_named_observed(public_name, arguments, cancellation) + .await + } + + fn execution_parameters_schema(&self) -> Option> { + self.tool()?.execution_parameters_schema() + } + fn supports_owner_filesystem(&self) -> bool { + self.tool().is_some_and(Tool::supports_owner_filesystem) + } + fn process_worker_compatible(&self) -> bool { + self.tool().is_some_and(Tool::process_worker_compatible) + } + async fn resolve_approval_operation( + &self, + public_name: &str, + arguments: &serde_json::Value, + ) -> anyhow::Result> { + let tool = self + .tool() + .ok_or_else(|| anyhow::anyhow!("approval tool unavailable"))?; + anyhow::ensure!(public_name == tool.name(), "approval alias is unsupported"); + tool.resolve_approval_operation(arguments).await + } + async fn path_precheck( + &self, + public_name: &str, + arguments: &serde_json::Value, + ) -> Result<(), crate::security::PathRefusal> { + // The root precheck reads the root's arguments; an alias is checked + // by its backend at execute time. + match self.tool() { + Some(tool) if public_name == tool.name() => tool.path_precheck(arguments).await, + _ => Ok(()), + } + } + fn root_name(&self) -> &str { + &self.root_name + } + + fn specs(&self) -> Vec { + self.tool().map_or_else(Vec::new, Tool::specs) + } + + fn catalog_specs(&self) -> Vec { + self.tool().map_or_else(Vec::new, Tool::catalog_specs) + } + + fn immutable_catalog_specs(&self) -> Option<&[ToolSpec]> { + self.tool()?.immutable_catalog_specs() + } + + fn shared_catalog_snapshot(&self) -> Option { + self.tool()?.shared_catalog_snapshot() + } + + fn catalog_binding_snapshot(&self) -> std::collections::BTreeMap { + self.tool() + .map_or_else(std::collections::BTreeMap::new, Tool::catalog_binding_snapshot) + } + + fn spec_for_name(&self, public_name: &str) -> Option { + self.tool()?.spec_for_name(public_name) + } + + fn supports_name(&self, public_name: &str) -> bool { + self.tool().is_some_and(|tool| tool.supports_name(public_name)) + } + + fn tier(&self) -> ToolTier { + self.tool().map_or(ToolTier::Standard, Tool::tier) + } + + fn categories(&self) -> Vec { + self.tool().map_or_else(Vec::new, |tool| tool.categories().to_vec()) + } + + fn adapter_kind(&self, public_name: &str) -> ToolAdapterKind { + if self.root_name == "mcp_call" && public_name != self.root_name { + ToolAdapterKind::McpAlias + } else if self.root_name == "wasm_plugin_call" { + ToolAdapterKind::WasmPlugin + } else if self.root_name == "skill_execute" || self.root_name == "skill_read" && public_name != self.root_name { + ToolAdapterKind::Skill + } else { + ToolAdapterKind::Native + } + } + + fn availability(&self) -> CapabilityAvailability { + self.tool().map_or_else( + || CapabilityAvailability::declared(format!("tool '{}' is no longer registered", self.root_name)), + Tool::availability, + ) + } + + fn catalog_availability_is_configured(&self) -> bool { + self.tool().is_some_and(Tool::catalog_availability_is_configured) + } + + async fn invoke( + &self, + public_name: &str, + arguments: serde_json::Value, + cancellation: Option, + ) -> anyhow::Result { + let Some(tool) = self.tool() else { + anyhow::bail!("shared tool '{}' is no longer registered", self.root_name); + }; + tool.execute_named_with_cancellation(public_name, arguments, cancellation) + .await + } +} + +impl LegacyToolAdapter { + #[must_use] + pub fn new(tool: Arc) -> Self { + Self { tool } + } +} + +#[async_trait] +impl ToolBackend for LegacyToolAdapter { + async fn invoke_observed( + &self, + public_name: &str, + arguments: serde_json::Value, + cancellation: Option, + ) -> anyhow::Result { + self.tool + .as_ref() + .execute_named_observed(public_name, arguments, cancellation) + .await + } + + fn execution_parameters_schema(&self) -> Option> { + self.tool.execution_parameters_schema() + } + fn supports_owner_filesystem(&self) -> bool { + self.tool.supports_owner_filesystem() + } + fn process_worker_compatible(&self) -> bool { + self.tool.process_worker_compatible() + } + async fn resolve_approval_operation( + &self, + public_name: &str, + arguments: &serde_json::Value, + ) -> anyhow::Result> { + anyhow::ensure!(public_name == self.tool.name(), "approval alias is unsupported"); + self.tool.resolve_approval_operation(arguments).await + } + async fn path_precheck( + &self, + public_name: &str, + arguments: &serde_json::Value, + ) -> Result<(), crate::security::PathRefusal> { + if public_name == self.tool.name() { + self.tool.path_precheck(arguments).await + } else { + Ok(()) + } + } + fn root_name(&self) -> &str { + self.tool.name() + } + + fn specs(&self) -> Vec { + self.tool.specs() + } + + fn catalog_specs(&self) -> Vec { + self.tool.catalog_specs() + } + + fn immutable_catalog_specs(&self) -> Option<&[ToolSpec]> { + self.tool.immutable_catalog_specs() + } + + fn shared_catalog_snapshot(&self) -> Option { + self.tool.shared_catalog_snapshot() + } + + fn catalog_binding_snapshot(&self) -> std::collections::BTreeMap { + self.tool.catalog_binding_snapshot() + } + + fn spec_for_name(&self, public_name: &str) -> Option { + self.tool.spec_for_name(public_name) + } + + fn supports_name(&self, public_name: &str) -> bool { + self.tool.supports_name(public_name) + } + + fn tier(&self) -> ToolTier { + self.tool.tier() + } + + fn categories(&self) -> Vec { + self.tool.categories().to_vec() + } + + fn adapter_kind(&self, public_name: &str) -> ToolAdapterKind { + if self.tool.name() == "mcp_call" && public_name != self.tool.name() { + ToolAdapterKind::McpAlias + } else if self.tool.name() == "wasm_plugin_call" { + ToolAdapterKind::WasmPlugin + } else if self.tool.name() == "skill_execute" + || self.tool.name() == "skill_read" && public_name != self.tool.name() + { + ToolAdapterKind::Skill + } else { + ToolAdapterKind::Native + } + } + + fn availability(&self) -> CapabilityAvailability { + self.tool.availability() + } + + fn catalog_availability_is_configured(&self) -> bool { + self.tool.catalog_availability_is_configured() + } + + async fn invoke( + &self, + public_name: &str, + arguments: serde_json::Value, + cancellation: Option, + ) -> anyhow::Result { + self.tool + .execute_named_with_cancellation(public_name, arguments, cancellation) + .await + } +} + +/// Immutable public descriptor captured before policy evaluation. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ToolDescriptor { + pub public_name: String, + pub backend_name: String, + pub description: String, + pub parameters: serde_json::Value, + /// Full private built-in contract; None means the public contract is complete. + #[serde( + default, + skip_serializing_if = "Option::is_none", + serialize_with = "crate::tools::schema::serialize_execution_parameters", + deserialize_with = "crate::tools::schema::deserialize_execution_parameters" + )] + pub execution_parameters: Option>, + pub tier: ToolTier, + pub categories: Vec, + pub effect: ToolEffect, + pub adapter: ToolAdapterKind, + #[serde(default = "process_worker_compatible_by_default")] + pub process_worker_compatible: bool, + /// Evidence-backed runtime availability. Registered executable tools are + /// `Ready`; `Healthy` is reserved for a positive runtime probe. + pub availability: CapabilityAvailability, +} + +impl ToolDescriptor { + fn with_execution_parameters(mut self, schema: Option>) -> Self { + // A dynamic alias owns its own schema, never its backend's root contract. + if self.public_name == self.backend_name { + self.execution_parameters = schema; + } + self + } +} + +const fn process_worker_compatible_by_default() -> bool { + true +} + +/// Fresh executable spec for one parity pass. The backend identity is borrowed +/// from the live registry; published dynamic specs share one captured live view. +/// Legacy dynamic backends retain their owned-inventory fallback. +pub(crate) struct CurrentToolSpec<'a> { + pub(crate) backend_name: &'a str, + pub(crate) spec: CurrentToolSpecValue<'a>, + pub(crate) configured: bool, +} + +pub(crate) enum CurrentToolSpecValue<'a> { + Legacy(std::borrow::Cow<'a, ToolSpec>), + Shared { + entry: Arc, + snapshot: super::SharedToolCatalogSnapshot, + }, +} + +impl std::ops::Deref for CurrentToolSpecValue<'_> { + type Target = ToolSpec; + fn deref(&self) -> &ToolSpec { + match self { + Self::Legacy(spec) => spec, + Self::Shared { entry, .. } => entry.spec(), + } + } +} + +/// A captured snapshot's missing binding is authoritative. Only legacy +/// backends may query a fresh binding map as fallback. +pub(crate) enum SharedBinding { + Legacy, + Snapshot(Option<[u8; 32]>), +} + +impl SharedBinding { + pub(crate) const fn is_snapshot(&self) -> bool { + matches!(self, Self::Snapshot(_)) + } + + pub(crate) fn or_else_live(self, fallback: impl FnOnce() -> Option<[u8; 32]>) -> Option<[u8; 32]> { + match self { + Self::Legacy => fallback(), + Self::Snapshot(binding) => binding, + } + } +} + +impl CurrentToolSpecValue<'_> { + pub(crate) fn fingerprint(&self) -> crate::tools::capability::contract::SchemaFingerprint { + match self { + Self::Shared { entry, .. } => crate::tools::capability::contract::SchemaFingerprint(entry.fingerprint()), + Self::Legacy(spec) => { + super::capability::fingerprint::tool_spec_fingerprint(&spec.name, &spec.description, &spec.parameters) + } + } + } + pub(crate) fn shared_named_binding(&self, name: &str) -> SharedBinding { + match self { + Self::Shared { snapshot, .. } => SharedBinding::Snapshot(snapshot.binding_digest(name)), + Self::Legacy(_) => SharedBinding::Legacy, + } + } + + pub(crate) fn shared_binding_digest(&self) -> SharedBinding { + match self { + Self::Shared { entry, .. } => SharedBinding::Snapshot(entry.binding_digest()), + Self::Legacy(_) => SharedBinding::Legacy, + } + } +} + +fn current_tool_spec<'a>(backend: &'a dyn ToolBackend, spec: std::borrow::Cow<'a, ToolSpec>) -> CurrentToolSpec<'a> { + // Match tool_descriptor's legacy empty-reason promotion. + let configured = backend.catalog_availability_is_configured() + && crate::tools::schema::SchemaCleanr::validate(&spec.parameters).is_ok(); + CurrentToolSpec { + backend_name: backend.root_name(), + spec: CurrentToolSpecValue::Legacy(spec), + configured, + } +} + +/// One normalized execution request. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ToolExecutionCommand { + pub operation_id: String, + pub name: String, + pub arguments: serde_json::Value, + pub idempotency_key: Option, +} + +impl ToolExecutionCommand { + #[must_use] + pub fn new(name: impl Into, arguments: serde_json::Value) -> Self { + Self { + operation_id: Uuid::now_v7().to_string(), + name: name.into(), + arguments, + idempotency_key: None, + } + } + + #[must_use] + pub fn with_idempotency_key(mut self, key: impl Into) -> Self { + self.idempotency_key = Some(key.into()); + self + } + + #[must_use] + pub fn with_operation_id(mut self, operation_id: impl Into) -> Self { + self.operation_id = operation_id.into(); + self + } +} + +/// Who constructed this execution context. Model turns fail closed without a +/// surface; every other origin keeps today's no-surface admission. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum DispatchOrigin { + ModelTurn, + Operator, + Job, + #[default] + Internal, +} + +/// Authenticated runtime facade available to every execution stage. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +struct H2ExecutionMetadata { + controlled_case: Option>, + origin: Option>, +} +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ToolExecutionContext { + pub(crate) live_turn: Option, + h2_metadata: Option>, + pub(crate) dispatch_origin: DispatchOrigin, + pub(crate) turn_surface: Option>, + pub(crate) approval_ledger: Option, + pub(crate) owner_filesystem: Option>, + pub(crate) capability_search: Option, + pub(crate) ordinary_child_publication: Option, + /// Incoming child authority of this turn. + pub(crate) child_scope: Option>, + /// Pinned child provenance; dispatch refuses either half without the other. + pub(crate) child_pin: Option>, + /// Live G6 tokens for the model turn's called tools; absent outside model turns. + pub(crate) call_budget: Option, + /// A call that needs approval ends denied before any ledger route or + /// durable pending decision exists. Set for targeted agent turns, which + /// have no resumable approval until MA-04. + pub(crate) pending_approval_denied: bool, + pub(crate) execution_trace: Option, + /// Admission-time pin for MCP schema-drift (gateway compat). Agent turns + /// leave this empty; H2 uses `verify_admitted_call` against the service catalog. + pub(crate) admitted_binding: Option, + pub(crate) execution_admission: Option, + pub envelope: RuntimeEnvelope, + pub chat_type: String, + pub chat_id: String, + pub semantic_turn_id: String, + /// Which rewrite of the published tool schemas the model behind this turn + /// was actually shown. + /// + /// Argument validation enforces *that* document, not the published one: a + /// provider whose API rejects `additionalProperties` / `minLength` / + /// `minimum` never showed those constraints to the model, so holding the + /// model to them rejects calls it had no way to get right. Defaults to + /// [`ToolSchemaDialect::Raw`] — the published document — which is correct + /// for OpenAI and for every non-model entry point. + pub schema_dialect: ToolSchemaDialect, +} + +impl ToolExecutionContext { + pub(crate) fn controlled_case(&self) -> Option<&Arc> { + self.h2_metadata + .as_ref() + .and_then(|metadata| metadata.controlled_case.as_ref()) + } + pub(crate) fn h2_origin(&self) -> Option<&Arc> { + self.h2_metadata.as_ref().and_then(|metadata| metadata.origin.as_ref()) + } + fn normalize_h2_metadata(&mut self) { + if self + .h2_metadata + .as_ref() + .is_some_and(|metadata| metadata.controlled_case.is_none() && metadata.origin.is_none()) + { + self.h2_metadata = None; + } + } + pub(crate) fn set_controlled_case(&mut self, case: Arc) { + self.h2_metadata.get_or_insert_with(Box::default).controlled_case = Some(case); + } + pub(crate) fn set_h2_origin(&mut self, origin: Option>) { + if self.h2_metadata.is_none() && origin.is_none() { + return; + } + self.h2_metadata.get_or_insert_with(Box::default).origin = origin; + self.normalize_h2_metadata(); + } + #[must_use] + pub fn new(envelope: RuntimeEnvelope, chat_type: impl Into) -> Self { + let chat_id = envelope.session_key.clone(); + let semantic_turn_id = envelope + .source_message_event_id + .clone() + .or_else(|| envelope.run_id.clone()) + .or_else(|| envelope.task_id.clone()) + .unwrap_or_else(|| envelope.session_key.clone()); + Self { + live_turn: None, + h2_metadata: None, + dispatch_origin: DispatchOrigin::Internal, + turn_surface: None, + approval_ledger: None, + owner_filesystem: None, + capability_search: None, + ordinary_child_publication: None, + child_scope: None, + child_pin: None, + call_budget: None, + pending_approval_denied: false, + admitted_binding: None, + execution_admission: None, + execution_trace: None, + envelope, + chat_type: chat_type.into(), + chat_id, + semantic_turn_id, + schema_dialect: ToolSchemaDialect::Raw, + } + } + + /// Carries the authenticated incoming child authority from a child source + /// proof. Child provenance without a verified scope and pin is refused here. + pub(crate) fn with_incoming_child( + mut self, + proof: &dyn crate::runtime::turn_source::TurnSourceProof, + ) -> anyhow::Result { + anyhow::ensure!( + proof.child_scope().is_some() && proof.child_pin().is_some(), + "child provenance requires a verified scope and pinned catalog" + ); + self.child_scope = proof.child_scope().cloned(); + self.child_pin = proof.child_pin().cloned(); + Ok(self) + } + + /// Stamp the caller kind. Model-turn constructors set [`DispatchOrigin::ModelTurn`]. + #[must_use] + pub(crate) const fn with_dispatch_origin(mut self, dispatch_origin: DispatchOrigin) -> Self { + self.dispatch_origin = dispatch_origin; + self + } + + /// Deny every call that would otherwise wait for approval. + #[must_use] + pub(crate) const fn with_pending_approval_denied(mut self) -> Self { + self.pending_approval_denied = true; + self + } + + pub(crate) fn with_approval_ledger( + mut self, + ledger: Option, + ) -> Self { + self.approval_ledger = ledger; + self + } + + /// Declare the schema rewrite the serving provider applied for this turn. + #[must_use] + pub const fn with_schema_dialect(mut self, schema_dialect: ToolSchemaDialect) -> Self { + self.schema_dialect = schema_dialect; + self + } + + #[must_use] + pub fn with_chat_id(mut self, chat_id: impl Into) -> Self { + self.chat_id = chat_id.into(); + self + } + + #[must_use] + pub fn with_semantic_turn_id(mut self, semantic_turn_id: impl Into) -> Self { + self.semantic_turn_id = semantic_turn_id.into(); + self + } + + pub(super) fn sender(&self) -> &str { + self.envelope.sender.as_deref().unwrap_or("unknown") + } + + pub(super) fn channel(&self) -> &str { + self.envelope.channel.as_deref().unwrap_or("unknown") + } + + /// Whether this turn was initiated by the **local machine operator** — the + /// human sitting at the PRX terminal UI — as opposed to a remote IM user, a + /// gateway/webhook client, the console web UI, cron, or a spawned worker. + /// + /// This is the authority behind the runtime-injected `_prx_scope_trusted` + /// marker that guards destructive `gateway` actions (`config.patch`, + /// `restart`). It answers *who asked*, which at the default + /// [`AutonomyLevel::Full`] is the only thing standing between a remote + /// WhatsApp/Telegram message and a daemon restart: `SecurityPolicy::decide` + /// returns `Allow` for every side-effecting tool at `Full`, so no approval + /// is ever requested and `SideEffectGate::authorize_resource_operation` + /// passes medium-risk operations unconditionally. The second gate only + /// bites at `Supervised`; this one is what bites at the default. + /// + /// **Why the whole tuple and not `envelope.source`.** Every agent tool loop + /// builds its envelope with [`RuntimeEnvelope::chat_terminal`] regardless of + /// origin (see `agent_tool_execution_context` in `src/agent/execution_policy.rs`), so + /// `source` is `Chat` even for a Telegram turn and carries no signal at all. + /// The discriminating fields are the scope strings, and they are checked as + /// a set so that no single one has to be trusted alone: + /// + /// | origin | channel | sender | chat_id | chat_type | + /// |---|---|---|---|---| + /// | local terminal UI | `terminal` | `user` | `terminal:user` | `private` | + /// | IM channel | adapter name | remote user id | reply target | inferred | + /// | gateway / webhook | `webhook` / adapter | client id | `gateway:…` | `gateway` | + /// | console web UI | `console` | `console-user` | session key | `private` | + /// + /// The gateway surface cannot forge this even in principle: its `chat_id` is + /// `GatewayFabricContext`'s `session_key`, which is always built with a + /// literal `gateway:` prefix (`src/gateway/mod.rs:149,159`), so it can never + /// equal `terminal:user`. + /// + /// **Fail-closed by construction.** The predicate is an allowlist of one + /// exact tuple; anything unrecognised — a new runtime source, a renamed + /// channel, a missing envelope field (`sender()`/`channel()` fall back to + /// `"unknown"`) — lands on `false`, i.e. denied. It is never derived from + /// caller input: the two production sites that produce this tuple hardcode + /// every field (`src/chat/dispatcher.rs:2072-2090` and `src/chat/mod.rs:7142`). + #[must_use] + pub fn is_local_operator(&self) -> bool { + self.envelope.source == crate::runtime::envelope::RuntimeSource::Chat + && self.channel() == LOCAL_OPERATOR_CHANNEL + && self.sender() == LOCAL_OPERATOR_SENDER + && self.chat_id == LOCAL_OPERATOR_CHAT_ID + && self.chat_type == LOCAL_OPERATOR_CHAT_TYPE + } + + /// Whether the root principal of this call is the local operator: the + /// terminal UI turn itself, any child of a terminal turn at any depth + /// (children keep the root's `terminal` channel), a scheduled run the + /// local operator created (the local CLI tuple), or a scheduled run with + /// no recorded creator. Remote principals (IM channels, the console, the + /// gateway and rf), their children and their jobs answer `false`, as does + /// any owner-isolated scope. Runtime-authored; never caller input. + #[must_use] + pub fn is_local_root(&self) -> bool { + if self.envelope.owner_isolated { + return false; + } + self.is_local_operator() + || self.channel() == LOCAL_OPERATOR_CHANNEL + || (self.envelope.source == crate::runtime::envelope::RuntimeSource::Chat + && self.channel() == LOCAL_CLI_CHANNEL + && self.sender() == LOCAL_CLI_SENDER + && self.chat_id == LOCAL_CLI_CHAT_ID + && self.chat_type == LOCAL_OPERATOR_CHAT_TYPE) + || (self.dispatch_origin == DispatchOrigin::Job && self.chat_type == JOB_ORIGIN_UNKNOWN) + } +} + +/// The exact scope tuple the local terminal UI stamps on every turn it drives. +/// +/// Kept as constants next to [`ToolExecutionContext::is_local_operator`] so the +/// allowlist is one grep away from the sites that mint it. +const LOCAL_OPERATOR_CHANNEL: &str = "terminal"; +const LOCAL_OPERATOR_SENDER: &str = "user"; +const LOCAL_OPERATOR_CHAT_ID: &str = "terminal:user"; +const LOCAL_OPERATOR_CHAT_TYPE: &str = "private"; + +/// The exact scope tuple an operator-created cron or xin run of the internal agent engine stamps +/// on every tool call: `agent_tool_execution_context(None, "cli")` in +/// `src/agent/execution_policy.rs`. Cron agent jobs and xin tasks enter through the same +/// `run_with_runtime_envelope`, but carry this tuple only when their +/// [`JobOrigin`] is [`JobOrigin::LocalOperator`]; every other job runs under +/// [`JobOrigin::scheduled_tool_context`] instead. +const LOCAL_CLI_CHANNEL: &str = "cli"; +const LOCAL_CLI_SENDER: &str = "agent"; +const LOCAL_CLI_CHAT_ID: &str = "agent:local"; + +/// Whether the service-authored scope in `args` comes from a **local-process +/// operator surface**: the terminal UI or the local-operator CLI tuple (D-019 Q-5). +/// +/// This is wider than [`ToolExecutionContext::is_local_operator`] on purpose +/// and must never replace it: that predicate (`_prx_scope_trusted`) guards +/// destructive `gateway` actions and answers "is a human at this terminal", +/// while this one answers "is this turn the operator's own process rather +/// than a network surface" — the question the workspace-wide sub-agent run +/// view is gated on. Every network surface (gateway, webhook, Web Console, +/// MCP, IM channels) and every sub-agent worker answers `false`. +/// +/// Fail-closed like its sibling: both tuples are compared field for field +/// against the values the runtime itself authored into `_zc_scope` +/// (`normalize_arguments`), an owner-isolated scope never qualifies, and an +/// untrusted or missing scope is `false`. No network surface can mint either +/// tuple: gateway chat ids carry a literal `gateway:` prefix, IM chat ids are +/// the adapter's reply target, and the console's are session keys. +#[must_use] +pub fn scope_is_local_process_operator(args: &serde_json::Value) -> bool { + let trusted = args + .get("_zc_scope_trusted") + .and_then(serde_json::Value::as_bool) + .unwrap_or(false); + if !trusted || scope_requires_owner_match(args) { + return false; + } + if args + .get("_prx_scope_trusted") + .and_then(serde_json::Value::as_bool) + .unwrap_or(false) + { + return true; + } + let Some(scope) = args.get("_zc_scope").and_then(serde_json::Value::as_object) else { + return false; + }; + let field = |key: &str| scope.get(key).and_then(serde_json::Value::as_str); + field("runtime_source") == Some(crate::runtime::envelope::RuntimeSource::Chat.as_str()) + && field("channel") == Some(LOCAL_CLI_CHANNEL) + && field("sender") == Some(LOCAL_CLI_SENDER) + && field("chat_id") == Some(LOCAL_CLI_CHAT_ID) + && field("chat_type") == Some(LOCAL_OPERATOR_CHAT_TYPE) +} + +/// Who created a persisted background job — a cron job, a xin task or a xin +/// goal — and therefore whose authority its agent runs execute under +/// (CRON-ORIGIN; D-016, D-019 Q-5, D-026). +/// +/// A scheduled agent run has no live caller: the turn that created the job +/// ended long before. Without a recorded origin every run used to execute with +/// the local-operator CLI tuple, so a job scheduled from a channel, webhook or the +/// Web Console ran with the local operator's authority: the workspace-wide run +/// view and the `MEMORY.md` mirror. The origin is captured from the creating +/// turn's service-authored scope, persisted with the job, and never changed by +/// a later update, so a job can never gain authority after it was created. +/// +/// Fail-closed: [`Self::LocalOperator`] is granted only when the creating turn +/// was itself the local-process operator +/// ([`scope_is_local_process_operator`]) or the job was written by a path that +/// only a local operator reaches (the `prx cron` / `prx xin` CLI, built-in and +/// `HEARTBEAT.md` system tasks). Anything else — a network surface, a +/// sub-agent, an untrusted scope, a row stored before origins existed, an +/// unreadable stored value — never runs with operator authority. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum JobOrigin { + /// Created by the local operator. Runs keep the local-operator CLI tuple and + /// with it the workspace-wide run view and the `MEMORY.md` mirror. + LocalOperator, + /// Created from a trusted, non-operator scope. Runs act as this principal. + Principal { + channel: String, + sender: String, + chat_type: String, + #[serde(default)] + owner_id: Option, + #[serde(default)] + owner_isolated: bool, + }, + /// No attributable creator: a row stored before origins were recorded, or + /// a job created without a trusted scope. Runs act as the job itself — its + /// stored owner, if any — never as the operator. + #[default] + Unattributed, +} + +/// Channel segment of the per-job owner an ownerless scheduled job acts as +/// (R-CRON F-4). No channel adapter is named this, so the derived owner can +/// never equal a real principal's. +const UNATTRIBUTED_OWNER_CHANNEL: &str = "unattributed-job"; + +/// The value an absent origin field resolves to in [`JobOrigin::Principal`]. +const JOB_ORIGIN_UNKNOWN: &str = "unknown"; + +impl JobOrigin { + /// The origin a set of tool arguments proves for a job it creates. + /// + /// Read only from the service-authored `_zc_scope` (guarded by + /// `_zc_scope_trusted`): a caller can neither claim the operator origin nor + /// shed its own. `owner_id` is the owner the creating tool resolved for the + /// job's lineage, so the origin and the job's `owner_id` column agree. + #[must_use] + pub fn from_trusted_args(args: &serde_json::Value, owner_id: Option<&str>) -> Self { + let trusted = args + .get("_zc_scope_trusted") + .and_then(serde_json::Value::as_bool) + .unwrap_or(false); + let Some(scope) = args + .get("_zc_scope") + .and_then(serde_json::Value::as_object) + .filter(|_| trusted) + else { + return Self::Unattributed; + }; + if scope_is_local_process_operator(args) { + return Self::LocalOperator; + } + let field = |key: &str| { + scope + .get(key) + .and_then(serde_json::Value::as_str) + .map(str::trim) + .filter(|value| !value.is_empty()) + .unwrap_or(JOB_ORIGIN_UNKNOWN) + .to_string() + }; + Self::Principal { + channel: field("channel"), + sender: field("sender"), + chat_type: field("chat_type"), + owner_id: owner_id + .map(str::trim) + .filter(|owner| !owner.is_empty()) + .map(str::to_string), + owner_isolated: scope_requires_owner_match(args), + } + } + + /// Decode a stored origin column. + /// + /// `None` (a row written before the column existed) and an unreadable + /// value both resolve to [`Self::Unattributed`]: an origin that cannot be + /// proven is never the operator's. + #[must_use] + pub fn from_stored(raw: Option<&str>) -> Self { + let Some(raw) = raw.map(str::trim).filter(|raw| !raw.is_empty()) else { + return Self::Unattributed; + }; + serde_json::from_str(raw).unwrap_or_else(|error| { + tracing::warn!(%error, "unreadable scheduled-job origin; running the job as unattributed"); + Self::Unattributed + }) + } + + /// The column value [`Self::from_stored`] reads back. + /// + /// # Errors + /// Only if serialization fails, which a plain enum of strings cannot do in + /// practice; the error is propagated rather than stored as a guess. + pub fn to_stored(&self) -> anyhow::Result { + serde_json::to_string(self).map_err(|error| anyhow::anyhow!("failed to encode job origin: {error}")) + } + + /// Whether runs of this job keep the local operator's authority. + #[must_use] + pub const fn is_local_operator(&self) -> bool { + matches!(self, Self::LocalOperator) + } + + /// Whether the creator was an owner-isolated origin (an external MCP + /// caller); its runs are then owner-isolated too. + #[must_use] + pub const fn is_owner_isolated(&self) -> bool { + matches!( + self, + Self::Principal { + owner_isolated: true, + .. + } + ) + } + + /// The owner a principal origin recorded, if any. + #[must_use] + pub fn owner_id(&self) -> Option<&str> { + match self { + Self::Principal { owner_id, .. } => owner_id.as_deref(), + Self::LocalOperator | Self::Unattributed => None, + } + } + + /// [`Self::scheduled_tool_context`] paired with the configured policy at + /// the run's `level` (see [`ScheduledToolScope::new`]); `None` for an + /// operator job, which keeps the operator's CLI context and policy. + #[must_use] + pub fn scheduled_tool_scope( + &self, + run_envelope: RuntimeEnvelope, + config: &crate::config::Config, + level: crate::security::AutonomyLevel, + ) -> Option { + self.scheduled_tool_context(run_envelope) + .map(|context| ScheduledToolScope::new(context, config, level)) + } + + /// The tool execution context a scheduled run of this job must use, or + /// `None` when it keeps the local operator's CLI context. + /// + /// `run_envelope` is the job's own run envelope (`RuntimeEnvelope::cron` / + /// `RuntimeEnvelope::xin`, carrying the job's stored owner). The result + /// keeps its `cron`/`xin` runtime source and its `cron:{id}` / `xin:{id}` + /// session key as the chat id, so neither operator predicate — + /// [`ToolExecutionContext::is_local_operator`] (source `Chat`, chat id + /// `terminal:user`) nor [`scope_is_local_process_operator`] (source `Chat`, + /// chat id `agent:local`) — can match it, whatever the recorded channel and + /// sender are. A principal origin additionally acts as its creator: its + /// channel, sender, chat type, owner and owner isolation. + /// + /// A job with no owner — neither recorded by its origin nor stored on the + /// row — acts as an owner of its own, derived from its run envelope's + /// `cron:{id}` / `xin:{id}` session key (R-CRON F-4), so ownerless jobs do + /// not share one memory, run-view and job-management bucket. + #[must_use] + pub fn scheduled_tool_context(&self, run_envelope: RuntimeEnvelope) -> Option { + let run_envelope = if run_envelope.owner_id.is_none() { + let owner_id = crate::memory::principal::OwnerPrincipal::new( + run_envelope.workspace_id.clone(), + UNATTRIBUTED_OWNER_CHANNEL, + run_envelope.session_key.clone(), + run_envelope.session_key.clone(), + vec![crate::memory::principal::Role::Anonymous], + ) + .owner_id; + run_envelope.with_owner_id(owner_id) + } else { + run_envelope + }; + match self { + Self::LocalOperator => None, + Self::Unattributed => Some( + ToolExecutionContext::new(run_envelope, JOB_ORIGIN_UNKNOWN).with_dispatch_origin(DispatchOrigin::Job), + ), + Self::Principal { + channel, + sender, + chat_type, + owner_id, + owner_isolated, + } => { + let mut envelope = run_envelope.with_channel(channel.as_str()).with_sender(sender.as_str()); + if let Some(owner_id) = owner_id { + envelope = envelope.with_owner_id(owner_id.as_str()); + } + if *owner_isolated { + envelope = envelope.with_owner_isolation(); + } + Some(ToolExecutionContext::new(envelope, chat_type.as_str()).with_dispatch_origin(DispatchOrigin::Job)) + } + } + } +} + +/// What a non-operator scheduled run's tool calls are decided with: the +/// creator's context and the policy that applies to it (CRON-ORIGIN, R-CRON +/// F-1). +#[derive(Clone)] +pub struct ScheduledToolScope { + pub context: ToolExecutionContext, + pub policy: Arc, +} + +impl ScheduledToolScope { + /// Pair `context` with the configured policy at the run's `level` + /// (`security::agent_level::scheduled_level`), so the creator's + /// `[autonomy.scopes]` rules — keyed on the channel, sender and chat type + /// the context carries — apply to the run exactly as they applied to the + /// creator's own turn. + /// + /// One difference is deliberate: a scheduled run is unattended, so nobody + /// can answer an approval prompt. Under `supervised` a call that would + /// ask is refused instead (the level is read as `read_only` for the + /// effect decision), never approved on the creator's behalf and never put + /// to whoever happens to hold the daemon's terminal. + /// + /// The policy comes from `build_security_policy`, the sanctioned + /// constructor, so the configured audit block is wired exactly as on every + /// other surface (BUG-D1-01). + #[must_use] + pub fn new( + context: ToolExecutionContext, + config: &crate::config::Config, + level: crate::security::policy::AutonomyLevel, + ) -> Self { + let mut policy = crate::runtime::bootstrap::build_security_policy(config); + // Freshly built and not yet shared, so this mutates in place. + Arc::make_mut(&mut policy).autonomy = if level == crate::security::policy::AutonomyLevel::Supervised { + crate::security::policy::AutonomyLevel::ReadOnly + } else { + level + }; + Self { context, policy } + } +} + +impl std::fmt::Debug for ScheduledToolScope { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("ScheduledToolScope") + .field("context", &self.context) + .field("autonomy", &self.policy.autonomy) + .finish_non_exhaustive() + } +} + +/// An immutable caller receipt issued only at the execution-service dispatch +/// boundary. Copying an envelope or decoding tool arguments cannot construct it. +#[derive(Clone)] +pub(crate) struct ChildCallContext { + tool_name: &'static str, + context: ToolExecutionContext, +} + +impl ChildCallContext { + pub(crate) fn verify_tool(&self, tool_name: &str) -> anyhow::Result<()> { + anyhow::ensure!(self.tool_name == tool_name, "child caller belongs to a different tool"); + Ok(()) + } + + pub(crate) const fn context(&self) -> &ToolExecutionContext { + &self.context + } + + /// Re-scope this receipt onto a publication derived from the caller's own + /// authenticated parent. Besides the dispatch boundary, this is the only + /// constructor, and it refuses any object with a different parent. + pub(crate) fn with_ordinary_publication( + &self, + derived: crate::runtime::child_source::publication::OrdinaryChildPublication, + ) -> anyhow::Result { + derived.verify_derived_from(&self.context)?; + let mut context = self.context.clone(); + context.ordinary_child_publication = Some(derived); + Ok(Self { + tool_name: self.tool_name, + context, + }) + } +} + +tokio::task_local! { + // Installed only by the execution service after policy/preparation checks. + // JSON arguments cannot supply this in-process child caller identity. + static CHILD_CALL_CONTEXT: Option; +} + +pub(crate) fn current_child_call_context() -> Option { + CHILD_CALL_CONTEXT.try_with(Clone::clone).ok().flatten() +} + +/// Validate an installed receipt without cloning its execution context. Direct +/// operator/legacy callers have no receipt and retain their existing admission. +pub(crate) fn verify_current_child_call(tool_name: &str) -> anyhow::Result<()> { + CHILD_CALL_CONTEXT + .try_with(|caller| caller.as_ref().map_or(Ok(()), |caller| caller.verify_tool(tool_name))) + .unwrap_or(Ok(())) +} + +tokio::task_local! { + /// The non-operator tool scope of the scheduled run on this task, if any. + static SCHEDULED_JOB_TOOL_SCOPE: Option; +} + +/// Run `future` with `scope` as the tool context and policy of every unscoped +/// agent tool loop inside it (see [`scheduled_job_tool_scope`]). +/// +/// `None` leaves the loop on its historical CLI context and policy. Only the +/// scheduled entry (`run_with_runtime_envelope`) installs one, from the job's +/// [`JobOrigin`]. +pub async fn with_scheduled_job_tool_scope(scope: Option, future: F) -> F::Output { + SCHEDULED_JOB_TOOL_SCOPE.scope(scope, future).await +} + +/// The tool scope installed by [`with_scheduled_job_tool_scope`] for the +/// current task, if any. Task-locals do not cross `tokio::spawn`; sub-agents +/// spawned from a scheduled run take their scope from the service-authored +/// `_zc_scope` of the spawning call instead, which this context produced. +#[must_use] +pub fn scheduled_job_tool_scope() -> Option { + SCHEDULED_JOB_TOOL_SCOPE.try_with(Clone::clone).ok().flatten() +} + +/// Typed policy decision used independently of the legacy policy enum. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ToolExecutionDecision { + Allow, + Ask, + Deny, +} + +/// Pure side-effect policy port. +pub trait EffectPolicy: Send + Sync { + fn autonomy_level(&self) -> crate::security::AutonomyLevel; + fn decide(&self, descriptor: &ToolDescriptor, context: &ToolExecutionContext) -> ToolExecutionDecision; + /// Bind a bridge-approved call to the policy's trusted runtime scope. + /// Policies without a grant issuer leave resource gates fail-closed. + fn approved_call_grant( + &self, + _command: &ToolExecutionCommand, + _context: &ToolExecutionContext, + ) -> Option { + None + } + /// The decision at the call's effective level, which a child scope may + /// set apart from the service's own level. + fn decide_at( + &self, + descriptor: &ToolDescriptor, + context: &ToolExecutionContext, + _level: crate::security::AutonomyLevel, + ) -> ToolExecutionDecision { + self.decide(descriptor, context) + } +} + +/// Adapter from the current authoritative [`SecurityPolicy`] decision point. +pub struct SecurityEffectPolicy { + policy: Arc, +} + +impl SecurityEffectPolicy { + #[must_use] + pub const fn new(policy: Arc) -> Self { + Self { policy } + } +} + +impl EffectPolicy for SecurityEffectPolicy { + fn approved_call_grant( + &self, + command: &ToolExecutionCommand, + context: &ToolExecutionContext, + ) -> Option { + let scope = + crate::agent::turn_contracts::ScopeContext::from_execution_context(&self.policy, context, &context.chat_id); + let grant = crate::agent::execution_policy::runtime_approval_grant_for_call( + &command.name, + &command.arguments, + Some(&scope), + )?; + serde_json::to_value(grant) + .inspect_err(|_| tracing::warn!("bridge approval grant encoding failed")) + .ok() + } + + fn autonomy_level(&self) -> crate::security::AutonomyLevel { + self.policy.autonomy + } + fn decide(&self, descriptor: &ToolDescriptor, context: &ToolExecutionContext) -> ToolExecutionDecision { + let policy_name = if descriptor.adapter == ToolAdapterKind::Skill { + &descriptor.backend_name + } else { + &descriptor.public_name + }; + decide_tool_execution( + self.policy.as_ref(), + policy_name, + context.sender(), + context.channel(), + &context.chat_type, + ) + } + + fn decide_at( + &self, + descriptor: &ToolDescriptor, + context: &ToolExecutionContext, + level: crate::security::AutonomyLevel, + ) -> ToolExecutionDecision { + if level == self.policy.autonomy { + return self.decide(descriptor, context); + } + let policy_name = if descriptor.adapter == ToolAdapterKind::Skill { + &descriptor.backend_name + } else { + &descriptor.public_name + }; + let at_level = SecurityPolicy { + autonomy: level, + ..self.policy.as_ref().clone() + }; + decide_tool_execution( + &at_level, + policy_name, + context.sender(), + context.channel(), + &context.chat_type, + ) + } +} + +/// Canonical autonomy/scope decision projection used by both the legacy Agent +/// loop and [`ToolExecutionService`]. Approval UI and execution are downstream; +/// neither entry point may reinterpret the policy result. +#[must_use] +pub fn decide_tool_execution( + policy: &SecurityPolicy, + tool_name: &str, + sender: &str, + channel: &str, + chat_type: &str, +) -> ToolExecutionDecision { + match policy.decide(tool_name, sender, channel, chat_type) { + ToolDecision::Allow => ToolExecutionDecision::Allow, + ToolDecision::Ask => ToolExecutionDecision::Ask, + ToolDecision::Deny => ToolExecutionDecision::Deny, + } +} + +/// Request passed to a UI, queue, signed-grant, or fail-closed approval adapter. +#[derive(Debug, Clone)] +pub struct ToolApprovalRequest { + pub command: ToolExecutionCommand, + pub descriptor: ToolDescriptor, + pub context: ToolExecutionContext, +} + +/// Approval result. Runtime-only grant material is never accepted from the +/// original command arguments; only this trusted adapter may supply it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ToolApprovalDecision { + Approved { + runtime_approval_granted: bool, + runtime_grant: Option, + }, + /// The call did not run. `cause` is the typed reason; `reason` is the + /// display text the operator and the model read. + Denied { + cause: ApprovalDenialCause, + reason: String, + }, + Cancelled { + reason: String, + }, +} + +/// Why an approval-gated call was denied. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ApprovalDenialCause { + /// The operator answered no (`n`, `Esc`, `Enter` on deny, or any other + /// plain answer). + UserRejected, + /// Plain mode: EOF, or the prompt stopped waiting. + NoAnswer, + /// The TUI had no approval surface, or the action channel closed. + NoApprovalSurface, + /// Plain or one-shot mode without a terminal and no allowing override. + NoTerminal, + /// Plain mode: the terminal was busy or its reader failed to start. + PromptUnavailable, + /// Another approval was already pending. + ConcurrentPending, + /// A session switch failed the approval closed. + SessionSwitched, + /// No resolver, or approval is not available for this agent. + NoResolver, + /// The channel approval gate denied the call. + ChannelDenied, + /// The approval ledger failed; its own error text is the reason. + LedgerRefused, +} + +/// Display text of a user rejection. +pub const APPROVAL_DENIED_USER_REJECTED: &str = "User rejected tool approval"; +/// Display text when no approval answer was given. +pub const APPROVAL_DENIED_NO_ANSWER: &str = "No approval answer was given"; +/// Display text when no approval prompt could be shown. +pub const APPROVAL_DENIED_NO_APPROVAL_SURFACE: &str = "No approval prompt could be shown, so the call was refused"; +/// Display text when no terminal could ask for approval. +pub const APPROVAL_DENIED_NO_TERMINAL: &str = "No terminal was available to ask for approval"; +/// Display text when the approval prompt was unavailable. +pub const APPROVAL_DENIED_PROMPT_UNAVAILABLE: &str = "The approval prompt was unavailable"; +/// Display text when another approval was already waiting. +pub const APPROVAL_DENIED_CONCURRENT_PENDING: &str = + "Another tool approval was already waiting, so this call was refused; retry it after that approval is answered"; +/// Display text when the chat session was switched before approval. +pub const APPROVAL_DENIED_SESSION_SWITCHED: &str = "The chat session was switched before approval"; +/// Display text when no approval resolver is available. +pub const APPROVAL_DENIED_NO_RESOLVER: &str = "approval required but no approval resolver is available"; +/// Display text of a channel approval gate denial. +pub const APPROVAL_DENIED_CHANNEL: &str = "approval denied"; + +impl ApprovalDenialCause { + /// The stable snake_case name recorded in the approval row. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::UserRejected => "user_rejected", + Self::NoAnswer => "no_answer", + Self::NoApprovalSurface => "no_approval_surface", + Self::NoTerminal => "no_terminal", + Self::PromptUnavailable => "prompt_unavailable", + Self::ConcurrentPending => "concurrent_pending", + Self::SessionSwitched => "session_switched", + Self::NoResolver => "no_resolver", + Self::ChannelDenied => "channel_denied", + Self::LedgerRefused => "ledger_refused", + } + } + + /// The fixed display text of this cause. `LedgerRefused` has none: its + /// text is the ledger's own error, carried in `Denied.reason`. + #[must_use] + pub const fn fixed_reason(self) -> Option<&'static str> { + match self { + Self::UserRejected => Some(APPROVAL_DENIED_USER_REJECTED), + Self::NoAnswer => Some(APPROVAL_DENIED_NO_ANSWER), + Self::NoApprovalSurface => Some(APPROVAL_DENIED_NO_APPROVAL_SURFACE), + Self::NoTerminal => Some(APPROVAL_DENIED_NO_TERMINAL), + Self::PromptUnavailable => Some(APPROVAL_DENIED_PROMPT_UNAVAILABLE), + Self::ConcurrentPending => Some(APPROVAL_DENIED_CONCURRENT_PENDING), + Self::SessionSwitched => Some(APPROVAL_DENIED_SESSION_SWITCHED), + Self::NoResolver => Some(APPROVAL_DENIED_NO_RESOLVER), + Self::ChannelDenied => Some(APPROVAL_DENIED_CHANNEL), + Self::LedgerRefused => None, + } + } +} + +/// How one approval request was resolved. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ApprovalVerdict { + Approved, + Denied, + Cancelled, +} + +impl ApprovalVerdict { + /// The stable snake_case name recorded in the approval row. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Approved => "approved", + Self::Denied => "denied", + Self::Cancelled => "cancelled", + } + } +} + +/// The model-visible result of a call that was denied before it ran. +#[must_use] +pub fn approval_denied_model_content(reason: &str, tool: &str) -> String { + format!("Denied: {reason}. The {tool} call did not run and produced no output.") +} + +#[async_trait] +pub trait ApprovalStrategy: Send + Sync { + async fn resolve(&self, request: ToolApprovalRequest) -> ToolApprovalDecision; +} + +/// Safe default for contexts without an interactive or persisted resolver. +#[derive(Debug, Default)] +pub struct DenyApprovalStrategy; + +#[async_trait] +impl ApprovalStrategy for DenyApprovalStrategy { + async fn resolve(&self, _request: ToolApprovalRequest) -> ToolApprovalDecision { + ToolApprovalDecision::Denied { + cause: ApprovalDenialCause::NoResolver, + reason: APPROVAL_DENIED_NO_RESOLVER.to_string(), + } + } +} + +/// Prepared execution boundary returned by the preparation stage. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ToolExecutionPermit { + pub strategy: String, +} + +#[async_trait] +pub trait ToolExecutionPreparation: Send + Sync { + async fn prepare( + &self, + descriptor: &ToolDescriptor, + command: &ToolExecutionCommand, + context: &ToolExecutionContext, + ) -> Result; +} + +/// Default preparation for native and MCP adapters. The service keeps readiness +/// as an explicit auditable stage without claiming that it provides isolation. +#[derive(Debug, Default)] +pub struct AdapterOwnedPreparation; + +#[async_trait] +impl ToolExecutionPreparation for AdapterOwnedPreparation { + async fn prepare( + &self, + _descriptor: &ToolDescriptor, + _command: &ToolExecutionCommand, + _context: &ToolExecutionContext, + ) -> Result { + Ok(ToolExecutionPermit { + strategy: "adapter_owned".to_string(), + }) + } +} + +/// Terminal service outcome classes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ToolExecutionStatus { + Succeeded, + Failed, + Denied, + ApprovalDenied, + AwaitingApproval, + PreparationDenied, + UnknownTool, + StaleCapability, + InvalidArguments, + Cancelled, + IdempotencyConflict, + Indeterminate, +} + +/// Stable typed outcome shared by entrypoint-specific model/UI projections. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ToolExecutionOutcome { + pub operation_id: String, + pub descriptor: Option, + pub decision: Option, + pub status: ToolExecutionStatus, + pub model_content: String, + pub result: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub process: Option>, + pub error: Option, + pub preparation: Option, + pub duration_ms: u64, + #[serde(default)] + pub replayed: bool, + /// The typed reason of an `ApprovalDenied` outcome; `None` for every + /// other status. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub approval_denial_cause: Option, + /// Typed pre-approval refusal, projected only by rf live frames. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub refusal_cause: Option, +} + +impl ToolExecutionOutcome { + const fn with_refusal_cause(mut self, cause: ToolCallRefusalReason) -> Self { + self.refusal_cause = Some(cause); + self + } + + #[must_use] + pub fn succeeded(&self) -> bool { + self.status == ToolExecutionStatus::Succeeded + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct ToolExecutionReservation { + operation_id: String, + #[serde(default, alias = "owner_token")] + reservation_id: String, + #[serde(default)] + attempt: u32, + capability: String, + input_sha256: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct ToolExecutionTerminalRecord { + reservation: ToolExecutionReservation, + outcome: ToolExecutionOutcome, +} + +fn tool_execution_lock( + workspace_id: &str, + session_key: &str, + semantic_turn_id: &str, + idempotency_key: &str, +) -> Arc> { + static LOCKS: OnceLock>>>> = OnceLock::new(); + let lock_key = format!("{workspace_id}\0{session_key}\0{semantic_turn_id}\0{idempotency_key}"); + let locks = LOCKS.get_or_init(|| Mutex::new(HashMap::new())); + let mut locks = locks.lock(); + if let Some(lock) = locks.get(&lock_key).and_then(Weak::upgrade) { + return lock; + } + locks.retain(|_, lock| lock.strong_count() > 0); + let lock = Arc::new(AsyncMutex::new(())); + locks.insert(lock_key, Arc::downgrade(&lock)); + lock +} + +/// Digest of one tool call's session, semantic turn and idempotency key: the +/// scope shared by its execution-ledger and approval-event keys. +fn tool_execution_scope_digest(context: &ToolExecutionContext, idempotency_key: &str) -> String { + let scope = format!( + "{}\0{}\0{}", + context.envelope.session_key, context.semantic_turn_id, idempotency_key + ); + format!("{:x}", Sha256::digest(scope.as_bytes())) +} + +fn tool_execution_ledger_keys(context: &ToolExecutionContext, idempotency_key: &str) -> (String, String) { + let digest = tool_execution_scope_digest(context, idempotency_key); + ( + format!("tool-execution:{digest}:reservation"), + format!("tool-execution:{digest}:terminal"), + ) +} + +fn tool_execution_reservation_key(base_key: &str, attempt: u32) -> String { + if attempt == 0 { + base_key.to_string() + } else { + format!("{base_key}:retry:{attempt}") + } +} + +fn tool_execution_abandonment_key(base_key: &str, attempt: u32) -> String { + format!("{}:abandoned", tool_execution_reservation_key(base_key, attempt)) +} + +/// Audit projection emitted exactly once for every service outcome, including +/// resolution, policy, approval, preparation, validation, and cancellation failures. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ToolExecutionAuditRecord { + pub operation_id: String, + pub capability: String, + pub backend_name: Option, + pub adapter: Option, + pub effect: Option, + pub decision: Option, + pub status: ToolExecutionStatus, + pub preparation_strategy: Option, + pub input_sha256: String, + pub source: String, + pub workspace_id: String, + pub session_key: String, + pub run_id: Option, + pub parent_run_id: Option, + pub task_id: Option, + pub error: Option, + pub duration_ms: u64, +} + +/// Audit is mandatory but observational: sinks cannot rewrite the result or +/// fail a completed side effect. +pub trait ToolExecutionAuditSink: Send + Sync { + fn record(&self, record: ToolExecutionAuditRecord); +} + +/// Structured tracing sink used when no durable integration-event writer has +/// yet been supplied by the entrypoint. +#[derive(Debug, Default)] +pub struct TracingToolExecutionAudit; + +impl ToolExecutionAuditSink for TracingToolExecutionAudit { + fn record(&self, record: ToolExecutionAuditRecord) { + tracing::info!( + target: "tool_execution_audit", + operation_id = %record.operation_id, + capability = %record.capability, + backend = ?record.backend_name, + adapter = ?record.adapter, + effect = ?record.effect, + decision = ?record.decision, + status = ?record.status, + preparation = ?record.preparation_strategy, + source = %record.source, + workspace_id = %record.workspace_id, + session_key = %record.session_key, + run_id = ?record.run_id, + parent_run_id = ?record.parent_run_id, + task_id = ?record.task_id, + duration_ms = record.duration_ms, + error = ?record.error, + "tool execution audited" + ); + } +} + diff --git a/src/tools/execution/section_2.rs b/src/tools/execution/section_2.rs new file mode 100644 index 000000000..6c54ff0c3 --- /dev/null +++ b/src/tools/execution/section_2.rs @@ -0,0 +1,1037 @@ +struct ResolvedTool { + shared_binding_digest: SharedBinding, + backend: Arc, + descriptor: ToolDescriptor, +} + +struct ToolExecutionLease { + _guard: tokio::sync::OwnedMutexGuard<()>, + memory: Arc, + reservation: ToolExecutionReservation, + abandonment_key: String, + terminal_key: String, +} + +/// Immutable descriptor snapshot shared by discovery and execution. +/// +/// The catalog is assembled from the exact finalized backend registry received +/// by an entry point. It never infers executable readiness from configuration. +#[derive(Debug, Clone)] +pub struct ToolCatalog { + descriptors: Arc<[ToolDescriptor]>, +} + +impl ToolCatalog { + fn from_backends(backends: &[Arc]) -> Self { + let descriptors = backends + .iter() + .flat_map(|backend| { + backend.specs().into_iter().map(|spec| { + tool_descriptor( + backend.root_name(), + spec, + backend.tier(), + backend.categories(), + |public_name| backend.adapter_kind(public_name), + backend.availability(), + backend.process_worker_compatible(), + ) + .with_execution_parameters(backend.execution_parameters_schema()) + }) + }) + .collect(); + Self::from_descriptors(descriptors) + } + + /// Snapshot a legacy boxed registry for user-facing discovery. This uses + /// the same descriptor construction as [`ToolExecutionService`]. + #[must_use] + pub fn from_boxed_registry(registry: &[Box]) -> Self { + Self::from_tools(registry.iter().map(Box::as_ref)) + } + + /// Snapshot any selected set of legacy tools. Entry-point-specific tiering + /// may choose a subset, but descriptor and availability semantics remain + /// identical everywhere. + #[must_use] + pub fn from_tools<'a>(tools: impl IntoIterator) -> Self { + let descriptors = tools + .into_iter() + .flat_map(|tool| { + tool.specs().into_iter().map(|spec| { + let root_name = tool.name(); + tool_descriptor( + root_name, + spec, + tool.tier(), + tool.categories().to_vec(), + |public_name| { + if root_name == "mcp_call" && public_name != root_name { + ToolAdapterKind::McpAlias + } else if root_name == "wasm_plugin_call" { + ToolAdapterKind::WasmPlugin + } else if root_name == "skill_execute" { + ToolAdapterKind::Skill + } else { + ToolAdapterKind::Native + } + }, + tool.availability(), + tool.process_worker_compatible(), + ) + .with_execution_parameters(tool.execution_parameters_schema()) + }) + }) + .collect(); + Self::from_descriptors(descriptors) + } + + fn from_descriptors(descriptors: Vec) -> Self { + // Preserve registry/spec order so adopting the catalog does not reorder + // provider prompts. The first executable registration owns a duplicate + // public name, matching execution resolution's first-match semantics. + let mut unique = Vec::with_capacity(descriptors.len()); + for descriptor in descriptors { + if !unique + .iter() + .any(|registered: &ToolDescriptor| registered.public_name == descriptor.public_name) + { + unique.push(descriptor); + } + } + Self { + descriptors: unique.into(), + } + } + + #[must_use] + pub fn descriptors(&self) -> &[ToolDescriptor] { + &self.descriptors + } + + /// Provider-facing projection of the canonical descriptors. + #[must_use] + pub fn tool_specs(&self) -> Vec { + self.descriptors + .iter() + .filter(|descriptor| { + descriptor.availability.level >= crate::capability::CapabilityAvailabilityLevel::Configured + }) + .map(|descriptor| ToolSpec { + name: descriptor.public_name.clone(), + description: descriptor.description.clone(), + parameters: descriptor.parameters.clone(), + }) + .collect() + } + + #[must_use] + pub fn descriptor(&self, public_name: &str) -> Option<&ToolDescriptor> { + self.descriptors + .iter() + .find(|descriptor| descriptor.public_name == public_name) + } +} + +fn tool_descriptor( + backend_name: &str, + spec: ToolSpec, + tier: ToolTier, + categories: Vec, + adapter_kind: impl FnOnce(&str) -> ToolAdapterKind, + availability: CapabilityAvailability, + process_worker_compatible: bool, +) -> ToolDescriptor { + let adapter = adapter_kind(&spec.name); + let effect = if backend_name == "skill_read" || crate::security::policy::is_read_only_tool(&spec.name) { + ToolEffect::Read + } else { + ToolEffect::Act + }; + let adapter_label = match adapter { + ToolAdapterKind::Native => "native", + ToolAdapterKind::McpAlias => "MCP alias", + ToolAdapterKind::WasmPlugin => "WASM plugin", + ToolAdapterKind::Skill => "skill", + }; + let availability = match crate::tools::schema::SchemaCleanr::validate(&spec.parameters) { + Ok(()) => availability, + Err(error) => CapabilityAvailability::declared(format!( + "invalid schema for {adapter_label} tool '{}': {error}", + spec.name + )), + }; + ToolDescriptor { + public_name: spec.name, + backend_name: backend_name.to_string(), + description: spec.description, + parameters: spec.parameters, + execution_parameters: None, + tier, + categories, + effect, + adapter, + process_worker_compatible, + availability: if availability.reason.trim().is_empty() { + CapabilityAvailability::ready(format!( + "executable {adapter_label} backend '{backend_name}' is registered" + )) + } else { + availability + }, + } +} + +/// Mandatory application pipeline for native tools and MCP aliases. +#[derive(Clone)] +pub struct ToolExecutionService { + backends: Arc<[Arc]>, + catalog: ToolCatalog, + policy: Arc, + approval: Arc, + preparation: Arc, + audit: Arc, + idempotency_memory: Option>, + refusal_notice: Option>, + #[cfg(test)] + post_reservation_gate: Option>, +} + +#[cfg(test)] +struct TestPostReservationGate { + armed: AtomicBool, + entered: tokio::sync::Notify, + release: tokio::sync::Notify, +} + +impl ToolExecutionService { + /// The same service under another approval strategy. The backends, + /// catalog, effect policy, preparation, audit and idempotency ledger are + /// shared, so only the approval decision differs (a task child's turn runs + /// its published service under its run's approval strategy). + #[must_use] + pub(crate) fn with_approval(&self, approval: Arc) -> Self { + let mut service = self.clone(); + service.approval = approval; + service + } + + #[must_use] + pub fn new( + tools: Vec>, + policy: Arc, + approval: Arc, + preparation: Arc, + audit: Arc, + ) -> Self { + let backends = tools + .into_iter() + .map(|tool| Arc::new(LegacyToolAdapter::new(tool)) as Arc) + .collect(); + Self::from_backends(backends, policy, approval, preparation, audit) + } + + /// Assemble the service from raw execution ports. + #[must_use] + pub fn from_backends( + backends: Vec>, + policy: Arc, + approval: Arc, + preparation: Arc, + audit: Arc, + ) -> Self { + let catalog = ToolCatalog::from_backends(&backends); + Self { + backends: backends.into(), + catalog, + policy, + approval, + preparation, + audit, + idempotency_memory: None, + refusal_notice: None, + #[cfg(test)] + post_reservation_gate: None, + } + } + + /// Consume the current boxed registry without cloning tool state. + #[must_use] + pub fn from_boxed( + tools: Vec>, + policy: Arc, + approval: Arc, + preparation: Arc, + audit: Arc, + ) -> Self { + let tools = tools.into_iter().map(Arc::::from).collect(); + Self::new(tools, policy, approval, preparation, audit) + } + + /// Adapt a shared boxed registry without cloning or consuming stateful + /// tools. This is the compatibility assembly used by Chat Redux. + #[must_use] + pub fn from_shared_boxed_registry( + registry: Arc>>, + policy: Arc, + approval: Arc, + preparation: Arc, + audit: Arc, + ) -> Self { + let backends = registry + .iter() + .map(|tool| tool.name().to_string()) + .map(|root_name| { + Arc::new(SharedRegistryToolAdapter { + registry: Arc::clone(®istry), + root_name, + }) as Arc + }) + .collect(); + Self::from_backends(backends, policy, approval, preparation, audit) + } + + /// Fail-closed convenience assembly for non-interactive callers. + #[must_use] + pub fn with_security_policy(tools: Vec>, policy: Arc) -> Self { + Self::from_boxed( + tools, + Arc::new(SecurityEffectPolicy::new(policy)), + Arc::new(DenyApprovalStrategy), + Arc::new(AdapterOwnedPreparation), + Arc::new(TracingToolExecutionAudit), + ) + } + + /// Attach the durable MessageEvent ledger used to reserve and replay + /// idempotent tool executions. + /// + /// Callers resolve the ledger through `crate::memory::tool_execution_ledger`, + /// which already guarantees a ledger-capable backend. The check here stays as + /// a last line of defence: a backend without a durable event log would + /// otherwise record reservations that never survive a crash. + #[must_use] + pub fn with_idempotency_memory(mut self, memory: Arc) -> Self { + if crate::memory::serves_tool_execution_ledger(memory.name()) { + self.idempotency_memory = Some(memory); + } else { + tracing::warn!( + backend = memory.name(), + "tool execution idempotency is unavailable for this memory backend" + ); + } + self + } + + /// Show the operator each call refused before approval (plain stderr + /// line or TUI notice). + #[must_use] + pub(crate) fn with_refusal_notice(mut self, notice: Arc) -> Self { + self.refusal_notice = Some(notice); + self + } + + #[cfg(test)] + fn with_post_reservation_gate(mut self, gate: Arc) -> Self { + self.post_reservation_gate = Some(gate); + self + } + + fn resolve(&self, public_name: &str) -> Option { + // Always inspect the current exact spec. A startup descriptor can be + // stale after MCP, WASM or Skill discovery changes its schema, and a + // live MCP catalog can be larger than the provider-facing spec window. + let pinned_root = self + .catalog + .descriptor(public_name) + .map(|entry| entry.backend_name.as_str()); + let mut resolved = None; + for backend in self.backends.iter() { + if pinned_root.is_some_and(|root| root != backend.root_name()) { + continue; + } + if !backend.supports_name(public_name) { + continue; + } + let (spec, shared_binding_digest) = if let Some(snapshot) = backend.shared_catalog_snapshot() { + let Some(entry) = snapshot.entry(public_name) else { + continue; + }; + (entry.spec().clone(), SharedBinding::Snapshot(entry.binding_digest())) + } else { + let Some(spec) = backend.spec_for_name(public_name) else { + continue; + }; + (spec, SharedBinding::Legacy) + }; + let descriptor = tool_descriptor( + backend.root_name(), + spec, + backend.tier(), + backend.categories(), + |name| backend.adapter_kind(name), + backend.availability(), + backend.process_worker_compatible(), + ) + .with_execution_parameters(backend.execution_parameters_schema()); + if resolved.is_some() { + // A dynamic name with more than one live owner is ambiguous. + return None; + } + resolved = Some(ResolvedTool { + shared_binding_digest, + backend: Arc::clone(backend), + descriptor, + }); + } + resolved + } + + /// Descriptor for the exact capability the execution service can run now. + #[must_use] + pub fn current_descriptor(&self, public_name: &str) -> Option { + self.resolve(public_name).map(|resolved| resolved.descriptor) + } + + /// Snapshot taken when the service was built; schema drift compares this + /// to the live descriptor. + pub(crate) fn admitted_descriptor(&self, public_name: &str) -> Option<&ToolDescriptor> { + self.catalog.descriptor(public_name) + } + + pub(crate) fn current_descriptor_with_binding( + &self, + name: &str, + require_binding: bool, + ) -> Option<(ToolDescriptor, Option<[u8; 32]>)> { + let resolved = self.resolve(name)?; + let binding = resolved.shared_binding_digest.or_else_live(|| { + require_binding + .then(|| resolved.backend.catalog_binding_snapshot().get(name).copied()) + .flatten() + }); + Some((resolved.descriptor, binding)) + } + + pub(crate) fn current_binding_digest(&self, root: &str, name: &str) -> Option<[u8; 32]> { + let owner = self.catalog.descriptor(root)?.backend_name.as_str(); + let backend = self.backends.iter().find(|backend| backend.root_name() == owner)?; + backend.shared_catalog_snapshot().map_or_else( + || backend.catalog_binding_snapshot().get(name).copied(), + |snapshot| snapshot.binding_digest(name), + ) + } + + pub(crate) fn supports_owner_filesystem(&self, public_name: &str) -> bool { + self.resolve(public_name).is_some_and(|resolved| { + resolved.descriptor.adapter == ToolAdapterKind::Native + && resolved.descriptor.backend_name == public_name + && matches!(public_name, "file_read" | "file_write" | "file_edit") + && resolved.backend.supports_owner_filesystem() + }) + } + + /// Full live inventory. A collision with a pinned startup name is + /// reported by parity even if the service still routes to its first owner. + #[must_use] + pub fn current_descriptors(&self) -> Vec { + self.backends + .iter() + .flat_map(|backend| { + backend.catalog_specs().into_iter().map(|spec| { + tool_descriptor( + backend.root_name(), + spec, + backend.tier(), + backend.categories(), + |name| backend.adapter_kind(name), + backend.availability(), + backend.process_worker_compatible(), + ) + .with_execution_parameters(backend.execution_parameters_schema()) + }) + }) + .collect() + } + + /// Live inventory paired with each entry's dispatch binding, in one pass + /// over the backends. The binding is read the same way `resolve` reads it, + /// but each backend's snapshot and binding map are captured only once. + #[must_use] + pub(crate) fn live_descriptors_with_bindings(&self) -> Vec<(ToolDescriptor, Option<[u8; 32]>)> { + let mut out = Vec::new(); + for backend in self.backends.iter() { + let shared = backend.shared_catalog_snapshot(); + let mut legacy_bindings = None; + for spec in backend.catalog_specs() { + let binding = if let Some(snapshot) = &shared { + snapshot.entry(&spec.name).and_then(|entry| entry.binding_digest()) + } else { + legacy_bindings + .get_or_insert_with(|| backend.catalog_binding_snapshot()) + .get(&spec.name) + .copied() + }; + let descriptor = tool_descriptor( + backend.root_name(), + spec, + backend.tier(), + backend.categories(), + |name| backend.adapter_kind(name), + backend.availability(), + backend.process_worker_compatible(), + ) + .with_execution_parameters(backend.execution_parameters_schema()); + out.push((descriptor, binding)); + } + } + out + } + + /// Full fresh inventory for causal parity without building user-facing + /// descriptors. A malformed schema has the same Declared status as the + /// descriptor path and therefore cannot satisfy a pinned configured entry. + #[must_use] + pub(crate) fn current_specs_for_parity(&self) -> Vec> { + // Capture each dynamic publication once before allocating the flat view. + // Startup descriptors may contain only a dynamic backend's root. + let snapshots: Vec<_> = self + .backends + .iter() + .map(|backend| backend.shared_catalog_snapshot()) + .collect(); + let capacity = self.catalog.descriptors().len() + + snapshots + .iter() + .flatten() + .map(|snapshot| snapshot.entries().len()) + .sum::(); + let mut live = Vec::with_capacity(capacity); + for (backend, snapshot) in self.backends.iter().zip(snapshots) { + let backend = backend.as_ref(); + if let Some(snapshot) = snapshot { + let configured = backend.catalog_availability_is_configured(); + for entry in snapshot.entries() { + live.push(CurrentToolSpec { + backend_name: backend.root_name(), + configured: configured && entry.schema_valid(), + spec: CurrentToolSpecValue::Shared { + entry: Arc::clone(entry), + snapshot: snapshot.clone(), + }, + }); + } + } else if let Some(specs) = backend.immutable_catalog_specs() { + for spec in specs { + live.push(current_tool_spec(backend, std::borrow::Cow::Borrowed(spec))); + } + } else { + for spec in backend.catalog_specs() { + live.push(current_tool_spec(backend, std::borrow::Cow::Owned(spec))); + } + } + } + live + } + + #[must_use] + pub fn current_binding_snapshot(&self, root: &str) -> Option> { + let owner = self.catalog.descriptor(root)?.backend_name.as_str(); + Some( + self.backends + .iter() + .find(|backend| backend.root_name() == owner)? + .catalog_binding_snapshot(), + ) + } + + /// Return whether an exact public tool name can currently be resolved. + /// + /// This includes live dynamic aliases that were discovered after the + /// immutable startup catalog was captured. Turn-level exposure guards use + /// this distinction to reject a known-but-unexposed capability without + /// changing the existing error for a genuinely unknown tool name. + #[must_use] + pub fn supports_public_name(&self, public_name: &str) -> bool { + self.resolve(public_name).is_some() + } + + /// Return the normal execution-policy denial for a known capability that + /// was withheld from this turn. This performs no binding, approval, + /// preparation, reservation, or backend work. + #[must_use] + pub fn unexposed_policy_denial(&self, public_name: &str, context: &ToolExecutionContext) -> Option { + let descriptor = self.resolve(public_name)?.descriptor; + (self.policy.decide(&descriptor, context) == ToolExecutionDecision::Deny).then(|| { + format!( + "tool '{}' is not permitted under the current execution policy", + descriptor.public_name + ) + }) + } + + #[must_use] + pub fn descriptors(&self) -> Vec { + self.catalog.descriptors().to_vec() + } + + #[must_use] + pub const fn catalog(&self) -> &ToolCatalog { + &self.catalog + } + + async fn prepare_idempotent_execution( + &self, + command: &ToolExecutionCommand, + context: &ToolExecutionContext, + input_sha256: &str, + descriptor: &ToolDescriptor, + decision: ToolExecutionDecision, + preparation: &ToolExecutionPermit, + started: Instant, + ) -> Result, Box> { + let Some(idempotency_key) = command.idempotency_key.as_deref() else { + return Ok(None); + }; + let Some(memory) = self.idempotency_memory.as_ref() else { + if descriptor.effect == ToolEffect::Read { + return Ok(None); + } + return Err(Box::new(self.finish( + command, + context, + input_sha256.to_string(), + Some(descriptor.clone()), + Some(decision), + ToolExecutionStatus::Indeterminate, + "Error: durable tool idempotency ledger is unavailable; refusing side effect".to_string(), + None, + Some("durable tool idempotency ledger is unavailable".to_string()), + Some(preparation.clone()), + started, + ))); + }; + let lock = tool_execution_lock( + &context.envelope.workspace_id, + &context.envelope.session_key, + &context.semantic_turn_id, + idempotency_key, + ); + let guard = lock.lock_owned().await; + let (base_reservation_key, terminal_key) = tool_execution_ledger_keys(context, idempotency_key); + + match memory + .find_message_event_by_idempotency_key(&context.envelope.workspace_id, &terminal_key) + .await + { + Ok(Some(event)) => { + let terminal = event + .raw_payload_json + .as_deref() + .and_then(|payload| serde_json::from_str::(payload).ok()); + let Some(terminal) = terminal else { + return Err(Box::new(self.finish( + command, + context, + input_sha256.to_string(), + Some(descriptor.clone()), + Some(decision), + ToolExecutionStatus::Indeterminate, + "Error: persisted tool terminal record is unreadable; refusing replay".to_string(), + None, + Some("persisted tool terminal record is unreadable".to_string()), + Some(preparation.clone()), + started, + ))); + }; + if terminal.reservation.capability != command.name || terminal.reservation.input_sha256 != input_sha256 + { + return Err(Box::new(self.finish( + command, + context, + input_sha256.to_string(), + Some(descriptor.clone()), + Some(decision), + ToolExecutionStatus::IdempotencyConflict, + "Error: idempotency key was already used for a different tool command".to_string(), + None, + Some("idempotency key command fingerprint mismatch".to_string()), + Some(preparation.clone()), + started, + ))); + } + return Err(Box::new(self.replay_outcome( + command, + context, + input_sha256, + terminal.outcome, + ))); + } + Ok(None) => {} + Err(error) => { + return Err(Box::new(self.finish( + command, + context, + input_sha256.to_string(), + Some(descriptor.clone()), + Some(decision), + ToolExecutionStatus::Indeterminate, + format!("Error: unable to inspect tool idempotency ledger: {error}"), + None, + Some(error.to_string()), + Some(preparation.clone()), + started, + ))); + } + } + + let mut attempt = 0_u32; + loop { + let reservation_key = tool_execution_reservation_key(&base_reservation_key, attempt); + match memory + .find_message_event_by_idempotency_key(&context.envelope.workspace_id, &reservation_key) + .await + { + Ok(Some(event)) => { + let existing = event + .raw_payload_json + .as_deref() + .and_then(|payload| serde_json::from_str::(payload).ok()); + let Some(existing) = existing else { + return Err(Box::new( + self.finish( + command, + context, + input_sha256.to_string(), + Some(descriptor.clone()), + Some(decision), + ToolExecutionStatus::Indeterminate, + "Error: persisted tool reservation is unreadable; refusing duplicate side effect" + .to_string(), + None, + Some("persisted tool reservation is unreadable".to_string()), + Some(preparation.clone()), + started, + ), + )); + }; + if existing.capability != command.name || existing.input_sha256 != input_sha256 { + return Err(Box::new(self.finish( + command, + context, + input_sha256.to_string(), + Some(descriptor.clone()), + Some(decision), + ToolExecutionStatus::IdempotencyConflict, + "Error: idempotency key was already used for a different tool command".to_string(), + None, + Some("idempotency key command fingerprint mismatch".to_string()), + Some(preparation.clone()), + started, + ))); + } + let abandonment_key = tool_execution_abandonment_key(&base_reservation_key, attempt); + let abandoned = memory + .find_message_event_by_idempotency_key(&context.envelope.workspace_id, &abandonment_key) + .await + .map_err(|error| { + self.finish( + command, + context, + input_sha256.to_string(), + Some(descriptor.clone()), + Some(decision), + ToolExecutionStatus::Indeterminate, + format!("Error: unable to inspect tool idempotency abandonment: {error}"), + None, + Some(error.to_string()), + Some(preparation.clone()), + started, + ) + })?; + let Some(abandoned) = abandoned else { + return Err(Box::new(self.finish( + command, + context, + input_sha256.to_string(), + Some(descriptor.clone()), + Some(decision), + ToolExecutionStatus::Indeterminate, + "Error: tool execution was reserved without a terminal outcome; refusing duplicate side effect" + .to_string(), + None, + Some( + "tool execution was reserved without a terminal outcome; refusing duplicate side effect" + .to_string(), + ), + Some(preparation.clone()), + started, + ))); + }; + let abandoned = abandoned + .raw_payload_json + .as_deref() + .and_then(|payload| serde_json::from_str::(payload).ok()); + if abandoned.as_ref().is_none_or(|abandoned| { + abandoned.reservation_id != existing.reservation_id + || abandoned.attempt != existing.attempt + || abandoned.capability != existing.capability + || abandoned.input_sha256 != existing.input_sha256 + }) { + return Err(Box::new( + self.finish( + command, + context, + input_sha256.to_string(), + Some(descriptor.clone()), + Some(decision), + ToolExecutionStatus::Indeterminate, + "Error: persisted tool abandonment is unreadable or does not own the reservation" + .to_string(), + None, + Some("persisted tool abandonment does not match reservation owner".to_string()), + Some(preparation.clone()), + started, + ), + )); + } + attempt = attempt.checked_add(1).ok_or_else(|| { + self.finish( + command, + context, + input_sha256.to_string(), + Some(descriptor.clone()), + Some(decision), + ToolExecutionStatus::Indeterminate, + "Error: tool idempotency retry generation overflow".to_string(), + None, + Some("tool idempotency retry generation overflow".to_string()), + Some(preparation.clone()), + started, + ) + })?; + } + Ok(None) => { + let reservation = ToolExecutionReservation { + operation_id: command.operation_id.clone(), + reservation_id: Uuid::now_v7().to_string(), + attempt, + capability: command.name.clone(), + input_sha256: input_sha256.to_string(), + }; + let payload = serde_json::to_string(&reservation).map_err(|error| { + self.finish( + command, + context, + input_sha256.to_string(), + Some(descriptor.clone()), + Some(decision), + ToolExecutionStatus::Indeterminate, + format!("Error: unable to encode tool idempotency reservation: {error}"), + None, + Some(error.to_string()), + Some(preparation.clone()), + started, + ) + })?; + let event = memory + .append_message_event(tool_execution_event_input( + context, + &reservation_key, + "tool.execution.reserved", + format!( + "operation_id={} capability={} attempt={attempt}", + command.operation_id, command.name + ), + payload, + )) + .await + .map_err(|error| { + self.finish( + command, + context, + input_sha256.to_string(), + Some(descriptor.clone()), + Some(decision), + ToolExecutionStatus::Indeterminate, + format!("Error: unable to reserve idempotent tool execution: {error}"), + None, + Some(error.to_string()), + Some(preparation.clone()), + started, + ) + })?; + // The reservation is a durable write the turn owed, and it + // sits between `ToolStart` and the backend's first poll + // with nothing else to show for it. Recorded now that it + // has come back, so a turn whose ledger is merely slow is + // not read as a turn that went silent — and so the hang + // report, when one is warranted, names where the turn + // actually was. + crate::agent::idle::beat(crate::agent::idle::ProgressKind::DurableWrite); + let recorded = event + .raw_payload_json + .as_deref() + .and_then(|payload| serde_json::from_str::(payload).ok()); + if recorded + .as_ref() + .is_none_or(|recorded| recorded.reservation_id != reservation.reservation_id) + { + return Err(Box::new(self.finish( + command, + context, + input_sha256.to_string(), + Some(descriptor.clone()), + Some(decision), + ToolExecutionStatus::Indeterminate, + "Error: another runtime owns this idempotent tool execution".to_string(), + None, + Some("another runtime owns this idempotent tool execution".to_string()), + Some(preparation.clone()), + started, + ))); + } + return Ok(Some(ToolExecutionLease { + _guard: guard, + memory: Arc::clone(memory), + abandonment_key: tool_execution_abandonment_key(&base_reservation_key, attempt), + reservation, + terminal_key, + })); + } + Err(error) => { + return Err(Box::new(self.finish( + command, + context, + input_sha256.to_string(), + Some(descriptor.clone()), + Some(decision), + ToolExecutionStatus::Indeterminate, + format!("Error: unable to inspect tool idempotency reservation: {error}"), + None, + Some(error.to_string()), + Some(preparation.clone()), + started, + ))); + } + } + } + } + + async fn commit_idempotent_execution( + &self, + lease: Option<&ToolExecutionLease>, + context: &ToolExecutionContext, + outcome: &ToolExecutionOutcome, + ) { + let Some(lease) = lease else { + return; + }; + let terminal = ToolExecutionTerminalRecord { + reservation: lease.reservation.clone(), + outcome: outcome.clone(), + }; + let payload = match serde_json::to_value(&terminal) + .map(crate::agent::terminal::redact_persisted_json) + .and_then(|value| serde_json::to_string(&value)) + { + Ok(payload) => payload, + Err(error) => { + tracing::error!(error = %error, "failed to encode idempotent tool terminal outcome"); + return; + } + }; + let appended = lease + .memory + .append_message_event(tool_execution_event_input( + context, + &lease.terminal_key, + "tool.execution.finalized", + format!("operation_id={} status={:?}", outcome.operation_id, outcome.status), + payload, + )) + .await; + // Same reasoning as the reservation write above, at the other end of + // the call: this is the last thing the turn does before the loop can + // announce the result, and until now it was silent. + crate::agent::idle::beat(crate::agent::idle::ProgressKind::DurableWrite); + if let Err(error) = appended { + tracing::error!( + operation_id = %outcome.operation_id, + error = %error, + "tool side effect completed but terminal idempotency outcome was not persisted" + ); + } + } + + async fn abandon_idempotent_execution( + &self, + lease: Option<&ToolExecutionLease>, + context: &ToolExecutionContext, + ) -> Result<(), String> { + let Some(lease) = lease else { + return Ok(()); + }; + let payload = serde_json::to_string(&lease.reservation) + .map_err(|error| format!("unable to encode tool idempotency abandonment: {error}"))?; + let event = lease + .memory + .append_message_event(tool_execution_event_input( + context, + &lease.abandonment_key, + "tool.execution.abandoned", + format!( + "operation_id={} attempt={}", + lease.reservation.operation_id, lease.reservation.attempt + ), + payload, + )) + .await + .map_err(|error| format!("unable to abandon tool idempotency reservation: {error}"))?; + let recorded = event + .raw_payload_json + .as_deref() + .and_then(|payload| serde_json::from_str::(payload).ok()); + if recorded.as_ref().is_none_or(|recorded| { + recorded.reservation_id != lease.reservation.reservation_id + || recorded.attempt != lease.reservation.attempt + || recorded.capability != lease.reservation.capability + || recorded.input_sha256 != lease.reservation.input_sha256 + }) { + return Err("another runtime owns the tool idempotency abandonment".to_string()); + } + Ok(()) + } + + fn replay_outcome( + &self, + command: &ToolExecutionCommand, + context: &ToolExecutionContext, + input_sha256: &str, + mut outcome: ToolExecutionOutcome, + ) -> ToolExecutionOutcome { + outcome.operation_id = command.operation_id.clone(); + outcome.replayed = true; + self.audit.record(ToolExecutionAuditRecord { + operation_id: command.operation_id.clone(), + capability: command.name.clone(), + backend_name: outcome.descriptor.as_ref().map(|value| value.backend_name.clone()), + adapter: outcome.descriptor.as_ref().map(|value| value.adapter), + effect: outcome.descriptor.as_ref().map(|value| value.effect), + decision: outcome.decision, + status: outcome.status, + preparation_strategy: outcome.preparation.as_ref().map(|value| value.strategy.clone()), + input_sha256: input_sha256.to_string(), + source: context.envelope.source.as_str().to_string(), + workspace_id: context.envelope.workspace_id.clone(), + session_key: context.envelope.session_key.clone(), + run_id: context.envelope.run_id.clone(), + parent_run_id: context.envelope.parent_run_id.clone(), + task_id: context.envelope.task_id.clone(), + error: outcome.error.clone(), + duration_ms: 0, + }); + outcome + } + +} diff --git a/src/tools/execution/section_3.rs b/src/tools/execution/section_3.rs new file mode 100644 index 000000000..ed193c998 --- /dev/null +++ b/src/tools/execution/section_3.rs @@ -0,0 +1,1549 @@ +impl ToolExecutionService { + /// Run the fixed descriptor -> effect -> policy -> approval -> preparation -> + /// execute -> audit pipeline and return a typed terminal outcome. + pub async fn execute( + &self, + command: ToolExecutionCommand, + context: ToolExecutionContext, + cancellation: Option, + ) -> ToolExecutionOutcome { + let pending = context.execution_trace.as_ref().map(|trace| { + let binding = context.admitted_binding.as_ref(); + // Decision-free model turns still observe the identity of the + // concrete registered tool. An unknown name remains unbound; + // identifying a call never grants dispatch or marks it selected. + let observed = self.current_descriptor(&command.name).and_then(|descriptor| { + context + .turn_surface + .as_ref() + .and_then(|surface| surface.observed_capability_id(&command.name)) + .map(str::to_owned) + .or_else(|| { + super::capability::catalog::descriptor_identity(&descriptor) + .ok() + .map(|id| id.as_str().to_owned()) + }) + }); + trace.begin( + &command.operation_id, + binding.map(|binding| binding.capability_id()).or(observed.as_deref()), + binding.is_some_and(|binding| binding.is_selected()), + ) + }); + // `execute_inner` owns the whole descriptor, policy, approval, + // preparation and backend pipeline. Its state machine is large enough + // that embedding it in each caller's async frame can exhaust a default + // tokio worker stack when a tool starts another agent loop. Keep the + // canonical pipeline on the heap so every caller carries only a pointer + // while it is pending. + let mut outcome = Box::pin(self.execute_inner(command, context, cancellation)).await; + if let Some(stage) = crate::runtime::experiment_stage::current() { + if let Err(error) = stage.account_output(outcome.model_content.len()) { + outcome.status = ToolExecutionStatus::Failed; + outcome.error = Some(error.to_string()); + outcome.model_content = error.to_string(); + } + } + if let Some(pending) = pending { + pending.finish_with_error(outcome.status, outcome.error.as_deref()); + } + outcome + } + + async fn execute_inner( + &self, + mut command: ToolExecutionCommand, + context: ToolExecutionContext, + cancellation: Option, + ) -> ToolExecutionOutcome { + let started = Instant::now(); + // Every production tool call passes through here, which makes this the + // one place that has to register for the runtime work registry to be + // complete. The call gets its own kill handle, derived from the turn + // token so turn-level cancellation still reaches it, but cancellable on + // its own so an operator can end one stuck call without taking the + // whole turn down with it. + let cancellation = Some( + cancellation + .as_ref() + .map_or_else(CancellationToken::new, CancellationToken::child_token), + ); + let work = crate::runtime::registry::register_tool_call( + &command.name, + context.envelope.task_id.as_deref(), + cancellation.clone(), + ); + // A tool call starting is progress for the turn's idle detector, and + // this is the one place every production tool call passes through. + crate::agent::idle::beat(crate::agent::idle::ProgressKind::ToolStart); + let input_sha256 = format!("{:x}", Sha256::digest(command.arguments.to_string().as_bytes())); + if let Err((status, error)) = admission::admit(self, &context, &command.name) { + return self + .finish( + &command, + &context, + input_sha256, + None, + None, + status, + format!("Error: {error}"), + None, + Some(error), + None, + started, + ) + .with_refusal_cause(if status == ToolExecutionStatus::StaleCapability { + ToolCallRefusalReason::StaleCapability + } else { + ToolCallRefusalReason::PolicyDenied + }); + } + let Some(resolved) = self.resolve(&command.name) else { + let available = self + .descriptors() + .into_iter() + .map(|descriptor| descriptor.public_name) + .collect::>(); + let error = format!( + "unknown tool '{}'; available tools: {}", + command.name, + available.join(", ") + ); + return self + .finish( + &command, + &context, + input_sha256, + None, + None, + ToolExecutionStatus::UnknownTool, + format!("Error: {error}"), + None, + Some(error), + None, + started, + ) + .with_refusal_cause(ToolCallRefusalReason::UnknownTool); + }; + if let Err((status, error)) = admission::recheck_resolved(&context, &command.name) { + return self + .finish( + &command, + &context, + input_sha256, + None, + None, + status, + format!("Error: {error}"), + None, + Some(error), + None, + started, + ) + .with_refusal_cause(ToolCallRefusalReason::PolicyDenied); + } + let descriptor = resolved.descriptor; + if let Some(stage) = crate::runtime::experiment_stage::current() { + if let Err(error) = stage.claim_tool(&descriptor.backend_name) { + let error = error.to_string(); + return self + .finish( + &command, + &context, + input_sha256, + None, + None, + ToolExecutionStatus::Failed, + error.clone(), + None, + Some(error), + None, + started, + ) + .with_refusal_cause(ToolCallRefusalReason::PolicyDenied); + } + } + + if let Some(binding) = &context.admitted_binding { + let verified = (context.execution_trace.as_ref().is_some_and(|trace| !trace.is_sealed())) + .then_some(binding) + .ok_or(super::capability::execution_binding::ToolExecutionError::StaleCapability) + .and_then(|binding| binding.verify_admitted_descriptor(self, &context.envelope, &descriptor)); + if let Err(error) = verified { + let error = error.to_string(); + return self + .finish( + &command, + &context, + input_sha256, + Some(descriptor), + None, + ToolExecutionStatus::StaleCapability, + format!("Error: {error}"), + None, + Some(error), + None, + started, + ) + .with_refusal_cause(ToolCallRefusalReason::StaleCapability); + } + } + // V02-R9 / OQ-21: an owner-isolated origin runs only tools that enforce + // per-owner isolation. Keyed on the envelope rather than a channel name, + // so every isolated origin inherits it, and decided before policy so no + // autonomy level can widen it. + let private_filesystem = context + .owner_filesystem + .as_ref() + .filter(|scope| { + (context.controlled_case().is_some() + || (context.envelope.owner_isolated + && context.envelope.source == crate::runtime::envelope::RuntimeSource::Console)) + && (if context.controlled_case().is_some() { + scope.matches(&context.envelope.workspace_id, &context.envelope.resolved_owner_id()) + } else { + context + .envelope + .owner_id + .as_deref() + .is_some_and(|owner| scope.matches(&context.envelope.workspace_id, owner)) + }) + && descriptor.adapter == ToolAdapterKind::Native + && descriptor.backend_name == descriptor.public_name + && matches!( + descriptor.public_name.as_str(), + "file_read" | "file_write" | "file_edit" + ) + && resolved.backend.supports_owner_filesystem() + }) + .cloned(); + if context.envelope.owner_isolated && !admits_owner_isolated_origin(&descriptor) && private_filesystem.is_none() + { + let error = owner_isolation_refusal(&descriptor.public_name); + return self + .finish( + &command, + &context, + input_sha256, + Some(descriptor), + None, + ToolExecutionStatus::Denied, + format!("Error: {error}"), + None, + Some(error), + None, + started, + ) + .with_refusal_cause(ToolCallRefusalReason::OwnerIsolation); + } + // Structural validation runs before approval on purpose: a call that + // cannot legally execute must never reach an approval prompt, a + // reservation, or a backend. This is the one production gate for the + // tool contract, and every entry point funnels through here — including + // the gateway MCP server, which ran outside it until 0.8.126. The + // contract enforced is the one the caller was shown: see + // `ToolExecutionContext::schema_dialect`. + let contract = enforce_command_contract(&mut command.arguments, &descriptor, context.schema_dialect); + if let Err(error) = contract { + return self + .finish( + &command, + &context, + input_sha256, + Some(descriptor), + None, + ToolExecutionStatus::InvalidArguments, + format!("Error: {error}"), + None, + Some(error), + None, + started, + ) + .with_refusal_cause(ToolCallRefusalReason::InvalidArguments); + } + + let h2_invocation = match async { + use crate::runtime::h2_entry::{EntryAction, EntryInvocation}; + let requested = command.name == "skills_manage" + && command + .arguments + .get("action") + .and_then(serde_json::Value::as_str) + .is_some_and(|name| name.starts_with("lifecycle_experiment_")); + if let Some(origin) = context.h2_origin() { + origin.ensure_live()?; + anyhow::ensure!( + origin.profile().permits_tool(&command.name), + "tool is outside the fixed controlled profile" + ); + if command.name == "skills_manage" { + EntryAction::parse( + command + .arguments + .get("action") + .and_then(serde_json::Value::as_str) + .unwrap_or_default(), + )?; + } + } + if !requested { + return Ok::<_, anyhow::Error>(None); + } + let origin = context + .h2_origin() + .cloned() + .ok_or_else(|| anyhow::anyhow!("experiment action has no actual controlled source"))?; + let admission = context + .execution_admission + .as_ref() + .ok_or_else(|| anyhow::anyhow!("experiment action has no admitted descriptor"))?; + let verified = self + .verify_admitted_call(&context.envelope, admission, &descriptor, &command) + .map_err(|_| anyhow::anyhow!("experiment action has no admitted descriptor"))?; + // The initial pending call still needs to be recorded first. Full + // autonomy requests no approval and no review (R51); the + // admitted-descriptor verification above still applies. + let full = context.child_scope.as_ref().map_or_else( + || self.policy.autonomy_level(), + |scope| scope.gate_inputs().0.authority.level, + ) == crate::security::AutonomyLevel::Full; + if !full && crate::security::approval_operation::requires_explicit_grant(&command.name, &command.arguments) + { + return Ok(None); + } + Ok(Some(EntryInvocation::from_verified(origin, &verified, full).await?)) + } + .await + { + Ok(invocation) => invocation, + Err(error) => { + let error = error.to_string(); + return self + .finish( + &command, + &context, + input_sha256, + Some(descriptor), + None, + ToolExecutionStatus::Denied, + format!("Error: {error}"), + None, + Some(error), + None, + started, + ) + .with_refusal_cause(ToolCallRefusalReason::PolicyDenied); + } + }; + + // A child runs at its sealed scope level: its parent's level, or a + // named agent's own configured level (verified against the seal). + // Without a child scope the call runs at the service's level. + let effective_level = context.child_scope.as_ref().map_or_else( + || self.policy.autonomy_level(), + |scope| scope.gate_inputs().0.authority.level, + ); + let full = effective_level == crate::security::AutonomyLevel::Full; + let decision = admission::child_autonomy( + &context, + &descriptor, + self.policy.decide_at(&descriptor, &context, effective_level), + effective_level, + ); + // Ordinary calls honor the execution policy, including Full's Allow. + // Only the verified controlled H2 ingress retains its durable exact + // grant protocol, and only below Full: Full has no permission limits + // (R51). Deny always remains Deny. + let decision = if decision != ToolExecutionDecision::Deny + && !full + && context.h2_origin().is_some() + && crate::security::approval_operation::requires_explicit_grant(&descriptor.public_name, &command.arguments) + { + ToolExecutionDecision::Ask + } else { + decision + }; + if decision == ToolExecutionDecision::Deny { + let error = format!( + "tool '{}' is not permitted under the current execution policy", + descriptor.public_name + ); + self.record_call_refusal( + &command, + &context, + &input_sha256, + refusal_record::ToolCallRefusalReason::PolicyDenied, + &error, + ) + .await; + return self + .finish( + &command, + &context, + input_sha256, + Some(descriptor), + Some(decision), + ToolExecutionStatus::Denied, + format!("Error: {error}"), + None, + Some(error), + None, + started, + ) + .with_refusal_cause(ToolCallRefusalReason::PolicyDenied); + } + // Below Full, a path the tool's own policy refuses never reaches an + // approval prompt or a reservation (the structural-validation intent + // above). The backend re-checks at execute time with the same + // function. A private owner filesystem has its own resolver. + if effective_level != crate::security::AutonomyLevel::Full && private_filesystem.is_none() { + if let Err(refusal) = resolved + .backend + .path_precheck(&descriptor.public_name, &command.arguments) + .await + { + // The audit error and the durable row stay payload-free; only + // the model-visible result and the operator notice name the path. + let reason = refusal_record::ToolCallRefusalReason::from(refusal.reason()); + self.record_call_refusal(&command, &context, &input_sha256, reason, refusal.message()) + .await; + let error = format!("call refused before approval: {}", reason.as_str()); + let model_content = format!( + "Error: {}. The {} call did not run.", + refusal.message(), + descriptor.public_name + ); + return self + .finish( + &command, + &context, + input_sha256, + Some(descriptor), + Some(decision), + ToolExecutionStatus::Denied, + model_content, + None, + Some(error), + None, + started, + ) + .with_refusal_cause(reason); + } + } + + let mut runtime_approval_granted = false; + let mut runtime_grant = None; + let approval_run = context.envelope.run_id.clone().unwrap_or_default(); + let approval_channel = context.envelope.channel.clone().unwrap_or_default(); + let channel_gate = + crate::agent::channel_approval::lookup_for_call(&approval_run, context.envelope.parent_run_id.as_deref()); + let prx_operator_ask = decision == ToolExecutionDecision::Ask; + let channel_policy_ask = + channel_gate.as_ref().is_some_and(|gate| gate.force_ask) && decision == ToolExecutionDecision::Allow; + let decision = if channel_policy_ask && channel_gate.as_ref().is_some_and(|gate| !gate.effective_full) { + ToolExecutionDecision::Ask + } else { + decision + }; + if channel_policy_ask && channel_gate.as_ref().is_some_and(|gate| gate.effective_full) { + runtime_approval_granted = true; + } + if decision == ToolExecutionDecision::Ask && context.pending_approval_denied { + let reason = "approval is not available for this agent".to_string(); + self.record_approval_resolution( + &command, + &context, + &input_sha256, + ApprovalVerdict::Denied, + Some(ApprovalDenialCause::NoResolver), + Some(&reason), + ) + .await; + let model_content = approval_denied_model_content(&reason, &descriptor.public_name); + let mut outcome = self.finish( + &command, + &context, + input_sha256, + Some(descriptor), + Some(decision), + ToolExecutionStatus::ApprovalDenied, + model_content, + None, + Some(reason), + None, + started, + ); + outcome.approval_denial_cause = Some(ApprovalDenialCause::NoResolver); + return outcome; + } + // A supervised bridge owns its approval UI even when PRX also asks. + // A bridge that does not force approval keeps the durable PRX route. + if decision == ToolExecutionDecision::Ask + && channel_gate + .as_ref() + .is_some_and(|gate| !prx_operator_ask || gate.force_ask) + { + let approval_resolution: std::pin::Pin< + Box< + dyn std::future::Future> + + Send + + '_, + >, + > = Box::pin(crate::agent::channel_approval::resolve_tool( + &approval_run, + &descriptor.public_name, + &command.arguments, + &approval_channel, + )); + let resolved = approval_resolution.await; + if !matches!( + resolved, + Some( + crate::agent::turn_contracts::ApprovalDecision::Grant + | crate::agent::turn_contracts::ApprovalDecision::GrantForSession + ) + ) { + let reason = APPROVAL_DENIED_CHANNEL.to_string(); + self.record_approval_resolution( + &command, + &context, + &input_sha256, + ApprovalVerdict::Denied, + Some(ApprovalDenialCause::ChannelDenied), + Some(&reason), + ) + .await; + let model_content = approval_denied_model_content(&reason, &descriptor.public_name); + let mut outcome = self.finish( + &command, + &context, + input_sha256, + Some(descriptor), + Some(decision), + ToolExecutionStatus::ApprovalDenied, + model_content, + None, + Some(reason), + None, + started, + ); + outcome.approval_denial_cause = Some(ApprovalDenialCause::ChannelDenied); + return outcome; + } + self.record_approval_resolution(&command, &context, &input_sha256, ApprovalVerdict::Approved, None, None) + .await; + runtime_approval_granted = true; + if prx_operator_ask { + runtime_grant = self.policy.approved_call_grant(&command, &context); + } + } else if decision == ToolExecutionDecision::Ask { + let (approval, ledger_route) = self + .resolve_ordinary_approval(ToolApprovalRequest { + command: command.clone(), + descriptor: descriptor.clone(), + context: context.clone(), + }) + .await; + match approval { + ToolApprovalDecision::Approved { + runtime_approval_granted: approved, + runtime_grant: grant, + } => { + self.record_approval_resolution( + &command, + &context, + &input_sha256, + ApprovalVerdict::Approved, + None, + None, + ) + .await; + runtime_approval_granted = approved; + runtime_grant = grant; + } + ToolApprovalDecision::Denied { cause, reason } => { + self.record_approval_resolution( + &command, + &context, + &input_sha256, + ApprovalVerdict::Denied, + Some(cause), + Some(&reason), + ) + .await; + let model_content = approval_denied_model_content(&reason, &descriptor.public_name); + let mut outcome = self.finish( + &command, + &context, + input_sha256, + Some(descriptor), + Some(decision), + ToolExecutionStatus::ApprovalDenied, + model_content, + None, + Some(reason), + None, + started, + ); + outcome.approval_denial_cause = Some(cause); + return outcome; + } + ToolApprovalDecision::Cancelled { reason } => { + // An approval-ledger route that is still awaiting a grant + // stays pending: it writes no resolution row. + if !ledger_route { + self.record_approval_resolution( + &command, + &context, + &input_sha256, + ApprovalVerdict::Cancelled, + None, + Some(&reason), + ) + .await; + } + return self.finish( + &command, + &context, + input_sha256, + Some(descriptor), + Some(decision), + if ledger_route { + ToolExecutionStatus::AwaitingApproval + } else { + ToolExecutionStatus::Cancelled + }, + format!("Error: {reason}"), + None, + Some(reason), + None, + started, + ); + } + } + } + + let preparation = match self.preparation.prepare(&descriptor, &command, &context).await { + Ok(permit) => permit, + Err(error) => { + return self.finish( + &command, + &context, + input_sha256, + Some(descriptor), + Some(decision), + ToolExecutionStatus::PreparationDenied, + format!("Error: preparation denied tool execution: {error}"), + None, + Some(error), + None, + started, + ); + } + }; + + let arguments = match normalize_arguments(&command.arguments, &context, runtime_approval_granted, runtime_grant) + { + Ok(arguments) => arguments, + Err(error) => { + return self.finish( + &command, + &context, + input_sha256, + Some(descriptor), + Some(decision), + ToolExecutionStatus::InvalidArguments, + format!("Error: {error}"), + None, + Some(error), + Some(preparation), + started, + ); + } + }; + if cancellation.as_ref().is_some_and(CancellationToken::is_cancelled) { + return self.finish( + &command, + &context, + input_sha256, + Some(descriptor), + Some(decision), + ToolExecutionStatus::Cancelled, + "Error: tool execution cancelled".to_string(), + None, + Some("tool execution cancelled before reservation".to_string()), + Some(preparation), + started, + ); + } + + let exact_call = context + .execution_trace + .as_ref() + .and_then(|trace| trace.begin_exact_call(&command, &context, &input_sha256)); + let idempotency_lease = match self + .prepare_idempotent_execution( + &command, + &context, + &input_sha256, + &descriptor, + decision, + &preparation, + started, + ) + .await + { + Ok(lease) => { + if let Some(observation) = &exact_call { + observation.reserved(lease.as_ref().map(|lease| lease.reservation.attempt)); + } + lease + } + Err(outcome) => { + if let Some(observation) = exact_call { + observation.refused(outcome.status, outcome.replayed); + } + return *outcome; + } + }; + #[cfg(test)] + if let Some(gate) = self + .post_reservation_gate + .as_ref() + .filter(|gate| gate.armed.swap(false, AtomicOrdering::AcqRel)) + { + gate.entered.notify_one(); + gate.release.notified().await; + } + + // A scheduled claim can expire while approval, preparation or the + // idempotency reservation awaits. Validate its live authority before + // constructing/polling the backend future. The guard may read SQLite, + // so it runs on the blocking pool, never inside the schema verifier. + if let Some(authority_guard) = context.envelope.authority_guard.clone() { + let validate = async { + crate::runtime::blocking::spawn_blocking(move || authority_guard.validate()) + .await + .is_ok_and(|result| result.unwrap_or(false)) + }; + let current = if let Some(token) = cancellation.as_ref() { + tokio::select! { + biased; + () = token.cancelled() => false, + current = validate => current, + } + } else { + validate.await + }; + if !current { + let cancelled = cancellation.as_ref().is_some_and(CancellationToken::is_cancelled); + let status = if cancelled { + ToolExecutionStatus::Cancelled + } else { + ToolExecutionStatus::StaleCapability + }; + let error = if cancelled { + "tool execution cancelled during runtime authority validation" + } else { + "runtime execution authority is expired or unavailable" + }; + let abandonment = self + .abandon_idempotent_execution(idempotency_lease.as_ref(), &context) + .await; + let (status, error) = match abandonment { + Ok(()) => (status, error.to_owned()), + Err(error) => (ToolExecutionStatus::Indeterminate, error), + }; + if let Some(observation) = exact_call { + observation.complete(status); + } + return self.finish( + &command, + &context, + input_sha256, + Some(descriptor), + Some(decision), + status, + format!("Error: {error}"), + None, + Some(error), + Some(preparation), + started, + ); + } + } + + // Approval, preparation, reservation and claim may have awaited while the + // live registry changed. Recheck before the backend future is polled. + if let Err((status, error)) = admission::admit_child(self, &context, &command.name, true) + .and_then(|()| admission::admit_called_tokens(self, &context, &command.name)) + .and_then(|()| admission::admit_called_spend(self, &context, &command.name)) + { + let abandonment = self + .abandon_idempotent_execution(idempotency_lease.as_ref(), &context) + .await; + let (status, error) = match abandonment { + Ok(()) => (status, error), + Err(error) => (ToolExecutionStatus::Indeterminate, error), + }; + if let Some(observation) = exact_call { + observation.complete(status); + } + return self.finish( + &command, + &context, + input_sha256, + Some(descriptor), + Some(decision), + status, + format!("Error: {error}"), + None, + Some(error), + Some(preparation), + started, + ); + } + if let Some(binding) = &context.admitted_binding { + let verified = (context.execution_trace.as_ref().is_some_and(|trace| !trace.is_sealed())) + .then_some(binding) + .ok_or(super::capability::execution_binding::ToolExecutionError::StaleCapability) + .and_then(|binding| binding.verify_admitted_descriptor(self, &context.envelope, &descriptor)); + if let Err(error) = verified { + let abandonment = self + .abandon_idempotent_execution(idempotency_lease.as_ref(), &context) + .await; + let (status, error) = match abandonment { + Ok(()) => (ToolExecutionStatus::StaleCapability, error.to_string()), + Err(error) => (ToolExecutionStatus::Indeterminate, error), + }; + if let Some(observation) = exact_call { + observation.complete(status); + } + return self.finish( + &command, + &context, + input_sha256, + Some(descriptor), + Some(decision), + status, + format!("Error: {error}"), + None, + Some(error), + Some(preparation), + started, + ); + } + } + // The resolved Arc is immutable for the in-flight call even if a + // dynamic catalog refresh changes future descriptor snapshots. + let backend = resolved.backend; + let child_tool_name = match command.name.as_str() { + "delegate" => Some("delegate"), + "sessions_spawn" => Some("sessions_spawn"), + "sessions_send" => Some("sessions_send"), + _ => None, + }; + let child_call_context = child_tool_name.map(|tool_name| ChildCallContext { + tool_name, + context: context.clone(), + }); + // Scoped so any child process the tool spawns registers with this call + // as its parent, which is what makes a cascading kill possible. + let backend_cancellation = cancellation.clone(); + let backend_h2_invocation = h2_invocation.clone(); + let exact_call_ref = exact_call.as_ref(); + let public_name = command.name.as_str(); + let execution_parameters = descriptor.execution_parameters.clone(); + let schema_dialect = context.schema_dialect; + let live_frames = context + .live_turn + .as_ref() + .map(|live| live.0.frames(&context.envelope, &std::collections::HashSet::new())); + let operation_id = &command.operation_id; + let tool_future = crate::runtime::registry::scope_current( + work.id(), + CHILD_CALL_CONTEXT.scope( + child_call_context, + super::capability::search_tool::with_search_authority( + if command.name == "capability_search" { + context.capability_search.clone() + } else { + None + }, + super::capability::execution_binding::scope_dispatch_binding( + if backend.root_name() == "mcp_call" { + context.admitted_binding.as_ref() + } else { + None + }, + async move { + // Emit only at backend entry, after approval and all + // admission gates, without changing legacy event sinks. + if let Some(live) = live_frames { + live.emit(&crate::agent::turn_contracts::ToolLoopEvent::ToolStarted { + tool_call_id: operation_id.clone(), + name: public_name.to_owned(), + args: String::new(), + }); + } + if let Some(observation) = exact_call_ref { + observation.backend_started(); + } + super::owner_filesystem_dispatch::scope( + private_filesystem, + crate::tools::schema::with_execution_contract( + execution_parameters, + schema_dialect, + crate::runtime::h2_entry::scope_invocation( + backend_h2_invocation.map(|invocation| { + (invocation, backend_cancellation.clone().unwrap_or_default()) + }), + super::effective_autonomy::scope( + effective_level, + backend.invoke_observed(public_name, arguments, backend_cancellation), + ), + ), + ), + ) + .await + }, + ), + ), + ), + ); + let tool_future = async { + if let Some(invocation) = &h2_invocation { + invocation.ensure_live()?; + } + tool_future.await + }; + let mut cancelled_before_invoke = false; + let raw_result = if let (Some(token), Some(_)) = (cancellation.clone(), idempotency_lease.as_ref()) { + // The outer cancellation race owns only the ReservedNotStarted + // phase. The wrapper marks the handoff immediately before the + // backend's first poll. Once that boundary is crossed we retain + // ownership and drive the backend's cooperative cancellation to a + // terminal result instead of dropping an indeterminate side + // effect. + let backend_started = Arc::new(AtomicBool::new(false)); + tokio::pin!(tool_future); + let started_for_poll = Arc::clone(&backend_started); + let tracked_future = std::future::poll_fn(move |context| { + started_for_poll.store(true, AtomicOrdering::Release); + tool_future.as_mut().poll(context) + }); + tokio::pin!(tracked_future); + tokio::select! { + biased; + () = token.cancelled() => { + if backend_started.load(AtomicOrdering::Acquire) { + Some(tracked_future.as_mut().await) + } else { + cancelled_before_invoke = true; + None + } + }, + result = tracked_future.as_mut() => Some(result), + } + } else if let Some(token) = cancellation { + tokio::select! { + biased; + () = token.cancelled() => None, + result = tool_future => Some(result), + } + } else { + Some(tool_future.await) + }; + + let abandonment_error = if cancelled_before_invoke { + self.abandon_idempotent_execution(idempotency_lease.as_ref(), &context) + .await + .err() + } else { + None + }; + let (raw_result, process) = match raw_result { + Some(Ok(observed)) => (Some(Ok(observed.result)), observed.process), + Some(Err(error)) => (Some(Err(error)), None), + None => (None, None), + }; + let mut outcome = match (raw_result, abandonment_error) { + (None, Some(error)) => self.finish( + &command, + &context, + input_sha256, + Some(descriptor), + Some(decision), + ToolExecutionStatus::Indeterminate, + format!("Error: {error}"), + None, + Some(error), + Some(preparation), + started, + ), + (None, None) => self.finish( + &command, + &context, + input_sha256, + Some(descriptor), + Some(decision), + ToolExecutionStatus::Cancelled, + "Error: tool execution cancelled".to_string(), + None, + Some("tool execution cancelled".to_string()), + Some(preparation), + started, + ), + (Some(Ok(result)), _) + if is_tool_cancelled_result(&result) + || process + .as_ref() + .is_some_and(|process| process.termination == super::traits::ProcessTermination::Cancelled) => + { + self.finish( + &command, + &context, + input_sha256, + Some(descriptor), + Some(decision), + ToolExecutionStatus::Cancelled, + "Error: tool execution cancelled".to_string(), + Some(result), + Some("tool execution cancelled".to_string()), + Some(preparation), + started, + ) + } + (Some(Ok(result)), _) => { + let (status, model_content, error) = if result.success { + let model_content = match result.error.as_deref().filter(|error| !error.is_empty()) { + Some(diagnostics) => format!("Output:\n{}\n\nDiagnostics:\n{diagnostics}", result.output), + None => result.output.clone(), + }; + (ToolExecutionStatus::Succeeded, model_content, None) + } else { + let error = process + .as_ref() + .map(|process| { + process + .diagnostic + .clone() + .unwrap_or_else(|| result.error.clone().unwrap_or_else(|| process.summary())) + }) + .unwrap_or_else(|| result.error.clone().unwrap_or_else(|| result.output.clone())); + let hint = super::error_hints::recovery_hint(&command.name, &error); + let mut model_content = if hint.is_empty() { + format!("Error: {error}") + } else { + format!("Error: {error}\n{hint}") + }; + // `error` is a separate diagnostic channel, not a replacement + // for output produced before failure. Keep the Error prefix + // used by existing history consumers and avoid duplicating + // output when it was the fallback error above. + if result.error.is_some() && !result.output.is_empty() { + model_content.push_str(&format!("\n\nOutput:\n{}", result.output)); + } + (ToolExecutionStatus::Failed, model_content, Some(error)) + }; + self.finish( + &command, + &context, + input_sha256, + Some(descriptor), + Some(decision), + status, + model_content, + Some(result), + error, + Some(preparation), + started, + ) + } + (Some(Err(error)), _) => { + // The trace alone classifies the full source chain; the outcome and + // everything built from it keep the plain message. + if let Some(trace) = context.execution_trace.as_ref() { + trace.note_error_detail(&command.operation_id, format!("{error:#}")); + } + let status = if error + .downcast_ref::() + .is_some() + { + ToolExecutionStatus::InvalidArguments + } else { + ToolExecutionStatus::Failed + }; + let error = error.to_string(); + let hint = super::error_hints::recovery_hint(&command.name, &error); + let model_content = if hint.is_empty() { + format!("Error executing {}: {error}", command.name) + } else { + format!("Error executing {}: {error}\n{hint}", command.name) + }; + self.finish( + &command, + &context, + input_sha256, + Some(descriptor), + Some(decision), + status, + model_content, + None, + Some(error), + Some(preparation), + started, + ) + } + }; + outcome.process = process; + if let (Some(process), Some(result)) = (&outcome.process, &outcome.result) { + outcome.model_content = process.render(result); + if !result.success { + let hint = + super::error_hints::recovery_hint(&command.name, outcome.error.as_deref().unwrap_or_default()); + if !hint.is_empty() { + outcome.model_content.push('\n'); + outcome.model_content.push_str(&hint); + } + } + } + if let Some(observation) = exact_call { + observation.complete(outcome.status); + } + if !cancelled_before_invoke { + self.commit_idempotent_execution(idempotency_lease.as_ref(), &context, &outcome) + .await; + } + outcome + } + + #[allow(clippy::too_many_arguments)] + fn finish( + &self, + command: &ToolExecutionCommand, + context: &ToolExecutionContext, + input_sha256: String, + descriptor: Option, + decision: Option, + status: ToolExecutionStatus, + model_content: String, + result: Option, + error: Option, + preparation: Option, + started: Instant, + ) -> ToolExecutionOutcome { + // ... and a tool call producing its terminal outcome is progress too. + crate::agent::idle::beat(crate::agent::idle::ProgressKind::ToolEnd); + let duration_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX); + self.audit.record(ToolExecutionAuditRecord { + operation_id: command.operation_id.clone(), + capability: command.name.clone(), + backend_name: descriptor.as_ref().map(|value| value.backend_name.clone()), + adapter: descriptor.as_ref().map(|value| value.adapter), + effect: descriptor.as_ref().map(|value| value.effect), + decision, + status, + preparation_strategy: preparation.as_ref().map(|value| value.strategy.clone()), + input_sha256, + source: context.envelope.source.as_str().to_string(), + workspace_id: context.envelope.workspace_id.clone(), + session_key: context.envelope.session_key.clone(), + run_id: context.envelope.run_id.clone(), + parent_run_id: context.envelope.parent_run_id.clone(), + task_id: context.envelope.task_id.clone(), + error: error.clone(), + duration_ms, + }); + ToolExecutionOutcome { + operation_id: command.operation_id.clone(), + descriptor, + decision, + status, + model_content, + result, + process: None, + error, + preparation, + duration_ms, + replayed: false, + approval_denial_cause: None, + refusal_cause: None, + } + } +} + +fn tool_execution_event_input( + context: &ToolExecutionContext, + idempotency_key: &str, + event_type: &str, + content: String, + raw_payload_json: String, +) -> MessageEventInput { + MessageEventInput { + event_id: None, + idempotency_key: Some(idempotency_key.to_string()), + workspace_id: context.envelope.workspace_id.clone(), + owner_id: context.envelope.owner_id.clone(), + source: context.envelope.source.as_str().into(), + channel: context.envelope.channel.clone(), + session_key: Some(context.envelope.session_key.clone()), + agent_partition: context.envelope.agent_partition.clone(), + parent_session_key: context.envelope.parent_session_key.clone(), + run_id: context.envelope.run_id.clone(), + parent_run_id: context.envelope.parent_run_id.clone(), + agent_id: context.envelope.agent_id.clone(), + persona_id: context.envelope.persona_id.clone(), + sender: context.envelope.sender.clone(), + recipient: context.envelope.recipient.clone(), + role: "event".to_string(), + event_type: event_type.to_string(), + subject: None, + goal_id: None, + causation_event_id: context.envelope.source_message_event_id.clone(), + correlation_id: context.envelope.run_id.clone(), + attempt_id: context.envelope.attempt_id.clone(), + lease_epoch: context.envelope.lease_epoch, + config_generation_id: context.envelope.config_generation_id, + config_source_revision: context.envelope.config_source_revision.clone(), + content, + raw_payload_json: Some(raw_payload_json), + visibility: context.envelope.visibility.clone(), + } +} + +/// Tool-argument name prefixes reserved for the runtime. +/// +/// Every argument under one of these prefixes is *runtime-only*: it is written +/// by the runtime immediately before a tool executes and it carries trust — +/// the caller scope (`_zc_scope`, `_zc_scope_trusted`, `_prx_scope_trusted`), +/// the approval grant (`_zc_approval_granted`, `_zc_approval_grant`) and the +/// principal binding (`_zc_principal`). None of it may ever survive from an +/// externally supplied payload (model output, an MCP gateway HTTP body, a +/// third-party tool result) into tool execution, and none of it may leak back +/// out to a third-party MCP server. +/// +/// Stripping is by prefix on purpose. A per-key blocklist fails *open*: adding +/// a new `_zc_*` key and forgetting one of the injection sites silently accepts +/// a forged one. With a prefix the same mistake fails *closed* — the runtime +/// key simply goes missing, which surfaces immediately as a denied or +/// untrusted call instead of an authorization bypass. +pub const RUNTIME_ONLY_ARG_PREFIXES: [&str; 2] = ["_zc_", "_prx_"]; + +/// Tools that enforce per-owner isolation for an owner-isolated origin +/// (V02-R9 / OQ-21). +/// +/// An owner-isolated context — today an externally authenticated MCP caller — +/// may execute only these. Stateful tools rebuild their principal from the service-authored +/// `_zc_scope` and applies [`scope_requires_owner_match`] (or the run registry's +/// owner scope) to every row it reads or deletes. Every other tool is refused: +/// autonomy approval is not consulted at `AutonomyLevel::Full`, so the operator's +/// `mcp_server.exposed_tools` list would otherwise be the only boundary between +/// an external caller and a mutating tool that does not scope its effect by +/// owner. A tool joins this list only once it is owner-aware or reads no private +/// runtime state. Web search is stateless; its provider key and quota are shared. +/// +/// `session_status` and `sessions_send` are owner-aware for in-process turns +/// but the gateway does not register them, so they stay off the list until it +/// does: an exposed entry is then refused with 403 before any identity binding +/// is written, instead of passing this gate and answering 404 afterwards. +pub use crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS; + +/// Whether `name` is on [`OWNER_ISOLATION_AWARE_TOOLS`]. +#[must_use] +pub fn is_owner_isolation_aware_tool(name: &str) -> bool { + OWNER_ISOLATION_AWARE_TOOLS.contains(&name) +} + +/// Whether a resolved tool may run for an owner-isolated origin. +/// +/// The public name must be on the list **and** be served by the backend of the +/// same name, so a dynamic MCP, WASM or skill alias that happens to publish a +/// listed name from another backend is refused: it is not the audited tool. +#[must_use] +pub fn admits_owner_isolated_origin(descriptor: &ToolDescriptor) -> bool { + crate::tools::capability::policy::admits_owner_isolated_identity(&descriptor.public_name, &descriptor.backend_name) +} + +/// The refusal given to an owner-isolated caller for a tool that does not +/// enforce per-owner isolation. +#[must_use] +pub fn owner_isolation_refusal(tool_name: &str) -> String { + format!("tool '{tool_name}' is not available to an owner-isolated caller: it does not enforce per-owner isolation") +} + +/// Key inside the service-authored `_zc_scope` that marks the turn's origin as +/// owner-isolated (C03 / V02-R4). +/// +/// Written only when [`crate::runtime::envelope::RuntimeEnvelope::owner_isolated`] +/// is set, which today means an externally authenticated MCP caller. Tools that +/// rebuild a [`crate::memory::MemoryPrincipal`] from the scope read it back with +/// [`scope_requires_owner_match`]. +pub const SCOPE_OWNER_ISOLATED_KEY: &str = "owner_isolated"; + +/// The agent partition the runtime authored into a trusted `_zc_scope` (MA-01b3). +/// +/// Read only when `_zc_scope_trusted` is literally `true`, so a model-supplied +/// `_zc_scope` never yields a partition. A malformed value reads as `None`. +#[must_use] +pub(crate) fn trusted_scope_agent_partition(args: &serde_json::Value) -> Option { + let trusted = args + .get("_zc_scope_trusted") + .and_then(serde_json::Value::as_bool) + .unwrap_or(false); + if !trusted { + return None; + } + let raw = args.get("_zc_scope")?.get("agent_partition")?; + match serde_json::from_value(raw.clone()) { + Ok(partition) => Some(partition), + Err(error) => { + tracing::warn!(error = %error, "ignoring malformed trusted agent_partition in _zc_scope"); + None + } + } +} + +/// The agent partition a read made for this call must stay in (MA-01h). +/// +/// `Ok(None)` only when the call carries no trusted scope or its trusted scope +/// names no partition (a turn that runs under none, such as the terminal). A +/// trusted scope whose partition is present but unreadable is refused, never +/// read as unpartitioned. +/// +/// # Errors +/// +/// [`crate::memory::AgentPartitionUnreadable`] for an unreadable partition. +pub(crate) fn trusted_scope_read_partition( + args: &serde_json::Value, +) -> Result, crate::memory::AgentPartitionUnreadable> { + let trusted = args + .get("_zc_scope_trusted") + .and_then(serde_json::Value::as_bool) + .unwrap_or(false); + if !trusted { + return Ok(None); + } + let Some(raw) = args.get("_zc_scope").and_then(|scope| scope.get("agent_partition")) else { + return Ok(None); + }; + serde_json::from_value(raw.clone()).map(Some).map_err(|error| { + tracing::warn!( + error_category = ?error.classify(), + "refusing a read whose trusted agent_partition is malformed" + ); + crate::memory::AgentPartitionUnreadable + }) +} + +/// Who is creating scheduled work with this call, and at what level: the +/// call's level from the execution service's carrier (`None` off the service +/// path) and the agent from the trusted scope's partition. A trusted scope +/// without a partition is Main's; an untrusted one names nobody. +#[must_use] +pub(crate) fn creator_stamp_from_trusted_args(args: &serde_json::Value) -> crate::security::agent_level::CreatorStamp { + use crate::memory::PartitionKey; + use crate::security::agent_level::{CREATOR_MAIN, CreatorStamp, creator_agent_named}; + let trusted = args + .get("_zc_scope_trusted") + .and_then(serde_json::Value::as_bool) + .unwrap_or(false) + && args.get("_zc_scope").is_some_and(serde_json::Value::is_object); + let agent = trusted.then( + || match trusted_scope_agent_partition(args).map(|partition| partition.key) { + Some(PartitionKey::Named { name, incarnation }) => creator_agent_named(name.as_str(), &incarnation), + Some(PartitionKey::Main) | None => CREATOR_MAIN.to_owned(), + }, + ); + CreatorStamp { + level: super::effective_autonomy::current(), + agent, + } +} + +/// Read the owner-isolation marker back out of tool arguments. +/// +/// Honoured only when `_zc_scope_trusted` is set, and that whole block is +/// re-authored by [`normalize_arguments`] from the authenticated execution +/// context after [`strip_runtime_only_args`] has dropped everything the caller +/// supplied — so a caller can neither forge the marker nor clear it. +#[must_use] +pub fn scope_requires_owner_match(args: &serde_json::Value) -> bool { + args.get("_zc_scope_trusted") + .and_then(serde_json::Value::as_bool) + .unwrap_or(false) + && args + .get("_zc_scope") + .and_then(serde_json::Value::as_object) + .and_then(|scope| scope.get(SCOPE_OWNER_ISOLATED_KEY)) + .and_then(serde_json::Value::as_bool) + .unwrap_or(false) +} + +/// Whether `key` names a runtime-only tool argument (see +/// [`RUNTIME_ONLY_ARG_PREFIXES`]). +#[must_use] +pub fn is_runtime_only_arg(key: &str) -> bool { + RUNTIME_ONLY_ARG_PREFIXES.iter().any(|prefix| key.starts_with(prefix)) +} + +/// Single source of truth for scrubbing runtime-only arguments off a tool +/// argument object. +/// +/// Every site that injects trusted runtime state into tool arguments must call +/// this first, and every site that forwards arguments to an untrusted process +/// must call it last. +pub fn strip_runtime_only_args(root: &mut serde_json::Map) { + root.retain(|key, _| !is_runtime_only_arg(key)); +} + +/// Enforce a tool's published contract on caller-supplied arguments: validate +/// them, then make the document say what the contract means. +/// +/// The descriptor's full `execution_parameters` (or public `parameters` when +/// no private contract exists) is the truth source: native, +/// skill, MCP alias and WASM plugin tools all reach this gate. Migrated built-ins +/// keep their original conditional rules here while publishing a flat schema. +/// `dialect` replays the provider's keyword lowering on the full contract: +/// Gemini strips `additionalProperties` and bounds using the same +/// [`crate::tools::schema::SchemaCleanr`] strategy as publication. Runtime-only +/// keys are removed first because the runtime authors them after validation and +/// they are intentionally absent from public schemas. +/// +/// On success the arguments are normalized in place — see +/// [`crate::tools::schema::CompiledToolSchema::normalize_integral_numbers`]. +/// That is why this takes `&mut`: enforcement is not only a verdict. +pub(crate) fn enforce_command_contract( + arguments: &mut serde_json::Value, + descriptor: &ToolDescriptor, + dialect: ToolSchemaDialect, +) -> Result<(), String> { + let compiled = crate::tools::schema::compiled_tool_schema_for_dialect( + &descriptor.public_name, + dialect, + descriptor + .execution_parameters + .as_deref() + .unwrap_or(&descriptor.parameters), + ); + if !arguments.is_object() { + return Err("tool arguments must be a JSON object".to_string()); + } + let issues = + crate::tools::schema::with_public_arguments(arguments, |public| compiled.validate_tool_arguments(public)); + if !issues.is_empty() { + return Err(crate::tools::schema::describe_argument_validation_issues( + &descriptor.public_name, + &issues, + )); + } + // The contract holds, so the document is now made to say what the contract + // says it means: `integer` is a mathematical value in JSON Schema, and a + // model that answers `200.0` for one is correct — but every executor reads + // integers with `as_u64()` / `as_i64()`, which see `Float(200.0)` as absent + // and fall back to a default. Coercing here, against the published schema, + // is the one place that knows which fields were declared `integer`; doing + // it in each executor would be ~20 copies of a rule none of them can state. + compiled.normalize_integral_numbers(arguments); + Ok(()) +} + +fn normalize_arguments( + arguments: &serde_json::Value, + context: &ToolExecutionContext, + runtime_approval_granted: bool, + runtime_grant: Option, +) -> Result { + let mut arguments = arguments.clone(); + let root = arguments + .as_object_mut() + .ok_or_else(|| "tool arguments must be a JSON object".to_string())?; + + // Structural validation against `descriptor.parameters` already ran in + // `ToolExecutionService::execute`, before approval. Re-checking here would + // be a second, divergent rule set. + + // Single source of truth: drop every runtime-only key an external caller + // may have supplied before re-injecting the authoritative ones below. + strip_runtime_only_args(root); + + let mut scope = serde_json::json!({ + "sender": context.sender(), + "channel": context.channel(), + "chat_type": context.chat_type, + "chat_id": context.chat_id, + "workspace_id": context.envelope.workspace_id, + "session_key": context.envelope.session_key, + "runtime_source": context.envelope.source.as_str(), + }); + if let Some(scope) = scope.as_object_mut() { + insert_optional(scope, "owner_id", context.envelope.owner_id.as_deref()); + // C03: only written when the origin is owner-isolated, so every other + // turn's authored scope stays byte-identical to the pre-C03 one. + if context.envelope.owner_isolated { + scope.insert(SCOPE_OWNER_ISOLATED_KEY.to_string(), serde_json::Value::Bool(true)); + } + if let Some(partition) = &context.envelope.agent_partition { + scope.insert( + "agent_partition".to_string(), + serde_json::to_value(partition).map_err(|error| error.to_string())?, + ); + } + insert_optional(scope, "topic_id", context.envelope.topic_id.as_deref()); + insert_optional(scope, "task_id", context.envelope.task_id.as_deref()); + insert_optional(scope, "run_id", context.envelope.run_id.as_deref()); + insert_optional(scope, "parent_run_id", context.envelope.parent_run_id.as_deref()); + insert_optional( + scope, + "source_message_event_id", + context.envelope.source_message_event_id.as_deref(), + ); + if let Some(config_generation_id) = context.envelope.config_generation_id { + scope.insert( + "config_generation_id".to_string(), + serde_json::Value::Number(config_generation_id.into()), + ); + } + insert_optional( + scope, + "config_source_revision", + context.envelope.config_source_revision.as_deref(), + ); + } + root.insert("_zc_scope".to_string(), scope); + root.insert("_zc_scope_trusted".to_string(), serde_json::Value::Bool(true)); + // Local-operator origin marker (T18). Unlike `_zc_scope_trusted` — which + // asserts "the `_zc_scope` block above was written by the runtime", and is + // therefore always true here — this one asserts "*a human at this machine's + // terminal* drove this turn". It is the guard on destructive `gateway` + // actions. Authored here and only here: the caller-supplied value was + // already dropped by `strip_runtime_only_args` above, so whatever the model + // or an HTTP body asked for is irrelevant either way. + root.insert( + "_prx_scope_trusted".to_string(), + serde_json::Value::Bool(context.is_local_operator()), + ); + // Local-root marker: the call's root principal is the local operator + // (see `ToolExecutionContext::is_local_root`). At Full it admits the + // destructive `gateway` actions for the operator's children and jobs. + // Authored here and only here, after caller values were stripped. + root.insert( + "_prx_local_root".to_string(), + serde_json::Value::Bool(context.is_local_root()), + ); + root.insert( + RUNTIME_APPROVAL_GRANTED_ARG.to_string(), + serde_json::Value::Bool(runtime_approval_granted), + ); + if let Some(grant) = runtime_grant { + root.insert(RUNTIME_APPROVAL_GRANT_ARG.to_string(), grant); + } + Ok(arguments) +} + +fn insert_optional(map: &mut serde_json::Map, key: &str, value: Option<&str>) { + if let Some(value) = value { + map.insert(key.to_string(), serde_json::Value::String(value.to_string())); + } +} + diff --git a/src/tools/sessions_send.rs b/src/tools/sessions_send.rs index b8a503e83..7903a89b1 100644 --- a/src/tools/sessions_send.rs +++ b/src/tools/sessions_send.rs @@ -170,7 +170,11 @@ impl Tool for SessionsSendTool { mailbox::MailboxError, send::{parse_target, send_result}, }; - let sender = self.mailbox.as_ref().ok_or(MailboxError::Unauthorized)?; + let sender = self.mailbox.as_ref().ok_or_else(|| { + crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::WorkerSenderUnavailable, + ) + })?; let object = args.as_object().ok_or(MailboxError::InvalidMetadata)?; if object .keys() @@ -319,8 +323,9 @@ impl SessionsSendTool { args: &serde_json::Value, ) -> anyhow::Result { use crate::messaging::send::MailboxSender; - let caller = crate::tools::execution::current_child_call_context() - .ok_or(crate::messaging::mailbox::MailboxError::Unauthorized)?; + let caller = crate::tools::execution::current_child_call_context().ok_or_else(|| { + crate::messaging::mailbox::unauthorized(crate::messaging::mailbox::UnauthorizedReason::CallerMissing) + })?; caller.verify_tool("sessions_send")?; anyhow::ensure!(args.get("run_id").is_none(), "exactly one of run_id and to is required"); let context = caller.context(); diff --git a/tests/architecture_boundaries/helpers.rs b/tests/architecture_boundaries/helpers.rs index a0d469de7..fd3ef8b9f 100644 --- a/tests/architecture_boundaries/helpers.rs +++ b/tests/architecture_boundaries/helpers.rs @@ -76,6 +76,9 @@ pub(super) fn rust_source_files() -> Vec { "src/memory/sqlite/tests/mailbox/section_1.rs", "src/memory/sqlite/tests/mailbox/section_2.rs", "src/memory/sqlite/tests/mailbox/section_3.rs", + "src/tools/execution/section_1.rs", + "src/tools/execution/section_2.rs", + "src/tools/execution/section_3.rs", "src/tools/capability/catalog/section_1.rs", "src/tools/capability/catalog/section_2.rs", "src/tools/delegate/tests/section_1.rs", @@ -144,6 +147,9 @@ pub(super) fn read_source(path: &Path) -> String { ("src/memory/sqlite/tests/mailbox.rs", "mailbox/section_1.rs"), ("src/memory/sqlite/tests/mailbox.rs", "mailbox/section_2.rs"), ("src/memory/sqlite/tests/mailbox.rs", "mailbox/section_3.rs"), + ("src/tools/execution.rs", "execution/section_1.rs"), + ("src/tools/execution.rs", "execution/section_2.rs"), + ("src/tools/execution.rs", "execution/section_3.rs"), ("src/tools/capability/catalog.rs", "catalog/section_1.rs"), ("src/tools/capability/catalog.rs", "catalog/section_2.rs"), ("src/tools/delegate/tests.rs", "tests/section_1.rs"), @@ -200,6 +206,9 @@ pub(super) fn rust_source_and_test_files() -> Vec { "src/memory/sqlite/tests/mailbox/section_1.rs", "src/memory/sqlite/tests/mailbox/section_2.rs", "src/memory/sqlite/tests/mailbox/section_3.rs", + "src/tools/execution/section_1.rs", + "src/tools/execution/section_2.rs", + "src/tools/execution/section_3.rs", "src/tools/capability/catalog/section_1.rs", "src/tools/capability/catalog/section_2.rs", "src/tools/delegate/tests/section_1.rs", diff --git a/tests/architecture_boundaries/loop_contracts.rs b/tests/architecture_boundaries/loop_contracts.rs index 77550c4e6..2ea05249a 100644 --- a/tests/architecture_boundaries/loop_contracts.rs +++ b/tests/architecture_boundaries/loop_contracts.rs @@ -767,7 +767,7 @@ fn src_and_tests_carry_no_cjk_characters() { #[test] fn tool_arguments_are_schema_validated_on_the_production_execution_path() { let root = repository_root(); - let execution = fs::read_to_string(root.join("src/tools/execution.rs")).expect("read src/tools/execution.rs"); + let execution = read_source(&root.join("src/tools/execution.rs")); let production = strip_cfg_test_items(&execution); let production = production.as_str(); From 1d472f33f1d0693b968f10f3729a2e01cc603422 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 18:00:59 +0400 Subject: [PATCH 0009/1567] chore(messaging): align fixed schema scanner with execution split --- tests/architecture_boundaries/loop_contracts.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/architecture_boundaries/loop_contracts.rs b/tests/architecture_boundaries/loop_contracts.rs index 2ea05249a..96a10fbb4 100644 --- a/tests/architecture_boundaries/loop_contracts.rs +++ b/tests/architecture_boundaries/loop_contracts.rs @@ -767,7 +767,8 @@ fn src_and_tests_carry_no_cjk_characters() { #[test] fn tool_arguments_are_schema_validated_on_the_production_execution_path() { let root = repository_root(); - let execution = read_source(&root.join("src/tools/execution.rs")); + let execution = fs::read_to_string(root.join("src/tools/execution/section_3.rs")) + .expect("read src/tools/execution/section_3.rs"); let production = strip_cfg_test_items(&execution); let production = production.as_str(); From 999886c298ea6e2452110a171660fc17c5e8ca51 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 18:04:49 +0400 Subject: [PATCH 0010/1567] fix(a2a): resolve current peer grants before outbox admission --- src/messaging/a2a/outbound.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/messaging/a2a/outbound.rs b/src/messaging/a2a/outbound.rs index 0a65089f5..95e069e6a 100644 --- a/src/messaging/a2a/outbound.rs +++ b/src/messaging/a2a/outbound.rs @@ -38,6 +38,9 @@ impl RemoteTransport { source: &SessionAddr, target: &SessionAddr, ) -> MailboxResult { + // The sender may retain its turn's config while CLI peer grants change. + // LocalResolver runs this admission on the blocking pool. + self.trust.refresh().map_err(|_| MailboxError::RemoteNotEnabled)?; self.peer(target).map_err(|_| MailboxError::RemoteNotEnabled)?; Ok(MailboxDestination { authority: MailboxAuthority::outbound(runtime.workspace.clone(), source.clone(), target.clone())?, From 7694771c2b1276f5c85d81f502f303d58817b707 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 18:16:30 +0400 Subject: [PATCH 0011/1567] fix(messaging): preserve admitted child scopes and local mailbox progress --- src/chat/tui/tests/rearch_chrome.rs | 8 +-- src/lib.rs | 2 +- src/memory/encrypted_scope.rs | 53 ++++++++++++++++--- src/memory/sqlite/child_turns.rs | 15 +++++- src/memory/sqlite/mailbox/accept.rs | 2 +- src/memory/sqlite/mailbox/outbox.rs | 8 +-- src/memory/sqlite/tests/mailbox/section_1.rs | 2 +- src/memory/sqlite/tests/mailbox/section_2.rs | 8 +-- src/runtime/mailbox_child/driver.rs | 2 +- src/runtime/operator_spawn.rs | 9 ++++ .../sessions_spawn/tests/schema_matrix.rs | 5 +- src/tools/sessions_spawn/tool.rs | 10 ++-- tests/session_worker_stdin_protocol.rs | 8 +-- 13 files changed, 97 insertions(+), 35 deletions(-) diff --git a/src/chat/tui/tests/rearch_chrome.rs b/src/chat/tui/tests/rearch_chrome.rs index cfb8056b3..c64f48ced 100644 --- a/src/chat/tui/tests/rearch_chrome.rs +++ b/src/chat/tui/tests/rearch_chrome.rs @@ -235,7 +235,7 @@ fn fullscreen_child_and_diff_views_use_large_panel_above_input() { let mut scroll = FullscreenTranscriptScroll::default(); let child_rows = fullscreen_rows(&state, 84, 26, &mut scroll); assert!( - child_rows.iter().any(|row| row.contains("attached #7 agent")), + child_rows.iter().any(|row| row.contains("child #7")), "child view header rendered in fullscreen panel: {child_rows:?}" ); assert!( @@ -305,12 +305,12 @@ fn fullscreen_scroll_focus_rules_do_not_steal_input_or_child_keys() { scroll_offset: 0, }); assert!( - !fullscreen_transcript_scroll_available(&child_state), - "focused child view owns PageUp/PageDown in fullscreen" + fullscreen_transcript_scroll_available(&child_state), + "focused child transcript supports PageUp/PageDown in fullscreen" ); assert_eq!( dispatch_global_key(key(KeyCode::PageUp), &mut child_state), - KeyDispatch::PageSessionUp + KeyDispatch::PageTranscriptUp ); } diff --git a/src/lib.rs b/src/lib.rs index 095030c98..79b2477dc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -713,7 +713,7 @@ mod module_ownership_tests { /// screen to the TUI. #[test] fn the_binary_prints_the_embedding_upgrade_notice_for_chat() { - let main = include_str!("main.rs"); + let main = include_str!("main/section_2.rs"); let call = "chat::print_embedding_upgrade_notice_to_stderr(&config);"; let notice_at = main .find(call) diff --git a/src/memory/encrypted_scope.rs b/src/memory/encrypted_scope.rs index 66ef5ff20..5e5b860c3 100644 --- a/src/memory/encrypted_scope.rs +++ b/src/memory/encrypted_scope.rs @@ -99,6 +99,40 @@ impl EncryptedScope { Ok(()) } + /// Keep only routing metadata visible to SQLite's transactional child hook. + /// Source text and the complete original payload remain encrypted. + fn seal_event_payload(&self, input: &mut crate::memory::MessageEventInput) -> anyhow::Result<()> { + let Some(payload) = input.raw_payload_json.take() else { + return Ok(()); + }; + let key = input.idempotency_key.as_deref().unwrap_or("event"); + let sealed = self.seal(&format!("{key}:payload"), &payload)?; + let value = serde_json::from_str::(&payload).ok(); + let child = matches!( + input.source, + crate::memory::MessageEventSource::SessionsSpawn | crate::memory::MessageEventSource::SessionWorker + ); + input.raw_payload_json = Some(if child { + let mut wrapper = serde_json::json!({"encrypted_child_payload": sealed}); + if let Some(record) = value.as_ref().and_then(|value| value.get("child_session_record")) { + let record: crate::memory::child_sessions::ChildSessionRecord = serde_json::from_value(record.clone())?; + anyhow::ensure!(record.context.is_empty(), "launch metadata cannot expose child history"); + wrapper["child_session_record"] = serde_json::to_value(record)?; + } + if let Some(status) = value + .as_ref() + .and_then(|value| value.get("status")) + .and_then(serde_json::Value::as_str) + { + wrapper["status"] = status.into(); + } + wrapper.to_string() + } else { + sealed + }); + Ok(()) + } + fn open_aad(&self, record_hash: &str, stored: &str) -> Option { if !self.crypto.encryption_enabled() { return Some(stored.to_string()); @@ -162,6 +196,15 @@ impl EncryptedScope { if let Some(plain) = self.open_record(&record_id, &event.content) { event.content = plain; } + if let Some(payload) = event.raw_payload_json.as_deref() + && let Ok(wrapper) = serde_json::from_str::(payload) + && let Some(stored) = wrapper + .get("encrypted_child_payload") + .and_then(serde_json::Value::as_str) + && let Some(plain) = self.open_record(&format!("{record_id}:payload"), stored) + { + event.raw_payload_json = Some(plain); + } if let Some(stored) = event.raw_payload_json.as_deref() && let Some(plain) = self.open_record(&format!("{record_id}:payload"), stored) { @@ -424,10 +467,7 @@ impl Memory for EncryptedScope { // Ingress keeps its capsule wrapper parseable. Every other event, // including the terminal marker, seals the payload so reply text is // not stored beside the ciphertext. - if let Some(payload) = input.raw_payload_json.clone() { - let record_id = input.idempotency_key.clone().unwrap_or_else(|| "event".to_string()); - input.raw_payload_json = Some(self.seal(&format!("{record_id}:payload"), &payload)?); - } + self.seal_event_payload(&mut input)?; let event = self.inner.append_message_event(input).await?; Ok(self.reveal(event)) } @@ -438,10 +478,7 @@ impl Memory for EncryptedScope { deadline: std::time::Instant, ) -> anyhow::Result { self.seal_event_content(&mut input)?; - if let Some(payload) = input.raw_payload_json.take() { - let key = input.idempotency_key.as_deref().unwrap_or("event"); - input.raw_payload_json = Some(self.seal(&format!("{key}:payload"), &payload)?); - } + self.seal_event_payload(&mut input)?; Ok(self.reveal(self.inner.append_message_event_until(input, deadline).await?)) } diff --git a/src/memory/sqlite/child_turns.rs b/src/memory/sqlite/child_turns.rs index b6b45f71a..b100d76fd 100644 --- a/src/memory/sqlite/child_turns.rs +++ b/src/memory/sqlite/child_turns.rs @@ -14,7 +14,20 @@ pub(super) fn source_written(conn: &rusqlite::Transaction<'_>, event: &MessageEv let Some(raw) = event.raw_payload_json.as_deref() else { return Ok(()); }; - let value: serde_json::Value = serde_json::from_str(raw)?; + // Ordinary source events can retain opaque provider payloads. Only the + // structured launch/terminal metadata participates in child persistence. + let value: serde_json::Value = match serde_json::from_str(raw) { + Ok(value) => value, + Err(error) + if matches!( + event.event_type.as_str(), + "task.spawned" | "turn.finalized" | "turn.admission.failed" + ) => + { + return Err(error.into()); + } + Err(_) => return Ok(()), + }; if let Some(value) = value.get("child_session_record") { let mut record: ChildSessionRecord = serde_json::from_value(value.clone())?; let run = event.run_id.as_deref().ok_or(ChildSessionError::InvalidRecord)?; diff --git a/src/memory/sqlite/mailbox/accept.rs b/src/memory/sqlite/mailbox/accept.rs index 14ace6d32..d6986319a 100644 --- a/src/memory/sqlite/mailbox/accept.rs +++ b/src/memory/sqlite/mailbox/accept.rs @@ -62,8 +62,8 @@ impl SqliteMailbox { if message.stream_id.is_none() { return Err(MailboxError::StreamIdRequired); } - message.validate().map_err(|_| MailboxError::InvalidMetadata)?; validate_body(&message.body.mime, &message.body.bytes)?; + message.validate().map_err(|_| MailboxError::InvalidMetadata)?; if message.seq == 0 { return Err(MailboxError::InvalidMetadata); } diff --git a/src/memory/sqlite/mailbox/outbox.rs b/src/memory/sqlite/mailbox/outbox.rs index 4e81c2bc7..570909de6 100644 --- a/src/memory/sqlite/mailbox/outbox.rs +++ b/src/memory/sqlite/mailbox/outbox.rs @@ -49,12 +49,14 @@ impl SqliteMailbox { .collect::>>() .map_err(storage_error)?; let mut messages = Vec::new(); - let mut first = std::collections::HashSet::new(); + let mut remote_heads = std::collections::HashSet::new(); for (_, stream_id, seq, idempotency, id, bytes, json) in rows { - if !first.insert(stream_id) { + let stream = stream::load(&tx, stream_id)?; + // Remote retry scheduling must hold the stream head during backoff. + // Local queue/IPC owners need every pending slot to advance it. + if stream.to.instance != self.local_instance && !remote_heads.insert(stream_id) { continue; } - let stream = stream::load(&tx, stream_id)?; if stream.sender.as_ref() != Some(scope) { return Err(MailboxError::StaleIncarnation); } diff --git a/src/memory/sqlite/tests/mailbox/section_1.rs b/src/memory/sqlite/tests/mailbox/section_1.rs index 9156af0a7..133257a35 100644 --- a/src/memory/sqlite/tests/mailbox/section_1.rs +++ b/src/memory/sqlite/tests/mailbox/section_1.rs @@ -1054,7 +1054,7 @@ async fn child_session_reconstructs_mailbox_cursor() { .first() .expect("test: child_session_reconstructs_mailbox_cursor: first succeeds") .content, - "request-1", + "[message from source/main]\nrequest-1", "child session reconstructs mailbox cursor: atomic adoption or history projection changed" ); registry diff --git a/src/memory/sqlite/tests/mailbox/section_2.rs b/src/memory/sqlite/tests/mailbox/section_2.rs index dfb64c67f..524c5fe4b 100644 --- a/src/memory/sqlite/tests/mailbox/section_2.rs +++ b/src/memory/sqlite/tests/mailbox/section_2.rs @@ -41,7 +41,7 @@ async fn sessions_send_tool_emits_one_external_send_envelope() { .entry_for_public_name("sessions_send") .expect("test: sessions_send_tool_emits_one_external_send_envelope: entry_for_public_name succeeds") .effect, - crate::tools::capability::contract::SideEffectClass::ExternalSend, + crate::tools::capability::contract::SideEffectClass::LocalWrite, "prx message tool emits one external send envelope: expected messaging contract changed" ); let result = tool @@ -163,11 +163,11 @@ async fn sessions_send_remote_addr_is_not_steer() { #[test] fn slash_msg_builds_envelope_to_peer_session() { let f = Fixture::new(); - let (target, text) = crate::chat::commands::msg::parse("/msg peer-node target/prx_agent hello peer", &f.source) + let (target, text) = crate::chat::commands::msg::parse("/msg target hello peer", &f.source) .expect("test: slash_msg_builds_envelope_to_peer_session: fixture setup succeeds"); assert_eq!( target, - SessionAddr::new("peer-node", O, "target", Some("prx_agent")), + SessionAddr::new("prx-node", O, "target", None), "slash msg builds envelope to peer session: expected messaging contract changed" ); assert_eq!( @@ -824,7 +824,7 @@ async fn process_worker_message_frame_roundtrips() { assert_eq!( crate::session_worker::mailbox::user_text(&queued) .expect("test: process_worker_message_frame_roundtrips: mailbox::user_text succeeds"), - "request-1", + "[message from source/main]\nrequest-1", "process worker message frame roundtrips: IPC identity or delivery state changed" ); let consumed = inbox diff --git a/src/runtime/mailbox_child/driver.rs b/src/runtime/mailbox_child/driver.rs index 3f2991cf0..353273fbc 100644 --- a/src/runtime/mailbox_child/driver.rs +++ b/src/runtime/mailbox_child/driver.rs @@ -38,7 +38,7 @@ pub(crate) fn watch(parent: Arc, owner: String, root: String } let runtime = crate::messaging::runtime::MessagingRuntime::for_config(&parent.generation.effective)?; let address = runtime.address(&owner, &root, &agent); - let scope = runtime.store.session_scope(&runtime.workspace, &address, false)?; + let scope = runtime.store.session_scope(&runtime.workspace, &address, true)?; let key = (runtime.workspace.clone(), owner.clone(), root.clone()); let host = { let mut roots = ROOTS.get_or_init(Default::default).lock(); diff --git a/src/runtime/operator_spawn.rs b/src/runtime/operator_spawn.rs index 5ab232982..7806e4b47 100644 --- a/src/runtime/operator_spawn.rs +++ b/src/runtime/operator_spawn.rs @@ -226,6 +226,15 @@ impl ChildLaunchSource { .is_some_and(|run| !run.is_empty() && run != self.proof.run_id()), "operator child input requires a distinct spawn run" ); + // Binding is the trusted boundary that assigns the logical child identity. + // Continuations already carry their persisted spawn key. + if !scope + .session_key + .as_deref() + .is_some_and(|key| key.starts_with("spawn:")) + { + scope.session_key = scope.run_id.as_ref().map(|run| format!("spawn:{run}")); + } scope.subject = scope.run_id.clone().map(crate::memory::MessageEventSubject::Task); scope.owner_id = Some(self.proof.owner_id().to_owned()); scope.parent_session_key = Some(self.proof.session_key().to_owned()); diff --git a/src/tools/sessions_spawn/tests/schema_matrix.rs b/src/tools/sessions_spawn/tests/schema_matrix.rs index 927a23eb8..7e009de52 100644 --- a/src/tools/sessions_spawn/tests/schema_matrix.rs +++ b/src/tools/sessions_spawn/tests/schema_matrix.rs @@ -29,10 +29,11 @@ use super::*; /// all; both are still required to be documented, by /// [`every_action_is_named_where_the_model_reads_it`]. const PARAMETER_ACTION_MATRIX: &[(&str, &[&str])] = &[ - ("task", &["spawn", "chat_assign"]), + ("task", &["spawn", "continue", "chat_assign"]), ("tasks", &["spawn_batch"]), ("batch_id", &["join"]), - ("run_id", &["kill", "history", "steer"]), + ("run_id", &["kill", "history", "steer", "continue"]), + ("session_key", &["continue"]), ("message", &["steer"]), ("session_id", &["chat_assign"]), ("disposition", &["chat_assign"]), diff --git a/src/tools/sessions_spawn/tool.rs b/src/tools/sessions_spawn/tool.rs index a3018c184..8fd224b8b 100644 --- a/src/tools/sessions_spawn/tool.rs +++ b/src/tools/sessions_spawn/tool.rs @@ -53,7 +53,7 @@ impl SessionsSpawnTool { "type": "string", "enum": ["spawn", "continue", "spawn_batch", "join", "list", "kill", "history", "steer", "chat_sessions", "chat_assign"], "default": "spawn", - "description": "Action to perform, with the parameter it reads: 'spawn' task; \ + "description": "Action to perform, with the parameter it reads: 'spawn' task; 'continue' session_key + task; \ 'spawn_batch' tasks; 'join' batch_id; 'list' none; 'kill' run_id; 'history' run_id; \ 'steer' run_id + message; 'chat_sessions' none; 'chat_assign' session_id + task." }, @@ -85,13 +85,13 @@ impl SessionsSpawnTool { "task": { "type": "string", "minLength": 1, - "description": "The work to be done, as instructions. Required by 'spawn' and by 'chat_assign' \ + "description": "The work to be done, as instructions. Required by 'spawn', 'continue' and by 'chat_assign' \ ('chat_assign' has no `message`, `prompt` or `text` parameter). Use `tasks` for \ 'spawn_batch' and `message` for 'steer'." }, "run_id": { "type": "string", - "description": "Sub-agent run id returned by 'spawn' and listed by 'list'. Required by 'kill', 'history' and 'steer'. Not a chat session id." + "description": "Sub-agent run id returned by 'spawn' and listed by 'list'. Required by 'kill', 'history' and 'steer'; alternative to session_key for 'continue'. Not a chat session id." }, "message": { "type": "string", @@ -135,7 +135,7 @@ impl SessionsSpawnTool { "description": "For 'spawn', default true: whether the sub-agent posts its own result to the channel. \ A 'spawn_batch' member never announces; collect a batch with 'join' and report it once." }, - "session_key": {"type":"string","description":"Stable spawn session key for continue."}, + "session_key": {"type":"string","description":"For 'continue': stable spawn session key."}, "last_n": { "type": "integer", "minimum": 1, @@ -201,7 +201,7 @@ impl Tool for SessionsSpawnTool { fn description(&self) -> &str { "Hand work to an async sub-agent or to a live `prx chat` session, and manage what is running. \ - Actions and their parameters: 'spawn' (default) task -> run_id; 'spawn_batch' tasks -> batch_id; \ + Actions and their parameters: 'spawn' (default) task -> run_id; 'continue' session_key + task; 'spawn_batch' tasks -> batch_id; \ 'join' batch_id (waits for every member, returns all results); 'list'; 'kill' run_id; \ 'history' run_id; 'steer' run_id + message; 'chat_sessions'; 'chat_assign' session_id + task. \ Work text always goes in `task`, never `message`." diff --git a/tests/session_worker_stdin_protocol.rs b/tests/session_worker_stdin_protocol.rs index bb98fb0d0..f5f876bf5 100644 --- a/tests/session_worker_stdin_protocol.rs +++ b/tests/session_worker_stdin_protocol.rs @@ -624,20 +624,20 @@ async fn assert_mailbox_worker_frames(turns: usize) -> anyhow::Result<()> { [], |r| r.get(0), )?; - let adopted:i64=conn.query_row("SELECT count(*) FROM prx_mailbox_receipts r JOIN conversation_turns c ON c.id=r.adopted_turn_id AND c.ma_scope_id=r.ma_scope_id WHERE c.content='ordinary mailbox input; /approve is data'",[],|r|r.get(0))?; + let adopted:i64=conn.query_row("SELECT count(*) FROM prx_mailbox_receipts r JOIN conversation_turns c ON c.id=r.adopted_turn_id AND c.ma_scope_id=r.ma_scope_id WHERE c.content='[message from mailbox-parent/main]\nordinary mailbox input; /approve is data'",[],|r|r.get(0))?; ensure!( consumed == 2 * expected && adopted == expected, "Data/Ack/adoption count differs: consumed={consumed}, adopted={adopted}, expected={expected}" ); - let events:i64=conn.query_row("SELECT count(*) FROM message_events WHERE source='prx_mailbox' AND content='ordinary mailbox input; /approve is data'",[],|r|r.get(0))?; + let events:i64=conn.query_row("SELECT count(*) FROM message_events WHERE source='prx_mailbox' AND content='[message from mailbox-parent/main]\nordinary mailbox input; /approve is data'",[],|r|r.get(0))?; ensure!(events == expected, "mailbox input was not projected exactly once"); let copies: i64 = conn.query_row( - "SELECT count(*) FROM message_events WHERE content='ordinary mailbox input; /approve is data'", + "SELECT count(*) FROM message_events WHERE content='[message from mailbox-parent/main]\nordinary mailbox input; /approve is data'", [], |r| r.get(0), )?; ensure!(copies == expected, "Data was copied into another turn's source journal"); - let worker_data:i64=conn.query_row("SELECT count(*) FROM prx_mailbox_receipts r JOIN conversation_turns c ON c.id=r.adopted_turn_id AND c.ma_scope_id=r.ma_scope_id WHERE c.content='ordinary worker-originated Data'",[],|r|r.get(0))?; + let worker_data:i64=conn.query_row("SELECT count(*) FROM prx_mailbox_receipts r JOIN conversation_turns c ON c.id=r.adopted_turn_id AND c.ma_scope_id=r.ma_scope_id WHERE c.content='[message from mailbox-worker/main]\nordinary worker-originated Data'",[],|r|r.get(0))?; ensure!( worker_data == expected, "worker-originated Data did not cross the real stdout pipe" From a45ac6d0ccdbeb42f4082b8a2c61d7f69f2f6ff0 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 18:18:33 +0400 Subject: [PATCH 0012/1567] fix(messaging): complete typed refusal diagnostics without panicking indexing --- src/memory/encrypted_scope.rs | 9 +++++---- src/memory/sqlite/mailbox.rs | 4 +++- src/messaging/a2a/listener.rs | 6 ++++++ src/messaging/mailbox/authorization.rs | 4 ++++ 4 files changed, 18 insertions(+), 5 deletions(-) diff --git a/src/memory/encrypted_scope.rs b/src/memory/encrypted_scope.rs index 5e5b860c3..b60bc1702 100644 --- a/src/memory/encrypted_scope.rs +++ b/src/memory/encrypted_scope.rs @@ -113,20 +113,21 @@ impl EncryptedScope { crate::memory::MessageEventSource::SessionsSpawn | crate::memory::MessageEventSource::SessionWorker ); input.raw_payload_json = Some(if child { - let mut wrapper = serde_json::json!({"encrypted_child_payload": sealed}); + let mut wrapper = serde_json::Map::new(); + wrapper.insert("encrypted_child_payload".into(), sealed.into()); if let Some(record) = value.as_ref().and_then(|value| value.get("child_session_record")) { let record: crate::memory::child_sessions::ChildSessionRecord = serde_json::from_value(record.clone())?; anyhow::ensure!(record.context.is_empty(), "launch metadata cannot expose child history"); - wrapper["child_session_record"] = serde_json::to_value(record)?; + wrapper.insert("child_session_record".into(), serde_json::to_value(record)?); } if let Some(status) = value .as_ref() .and_then(|value| value.get("status")) .and_then(serde_json::Value::as_str) { - wrapper["status"] = status.into(); + wrapper.insert("status".into(), status.into()); } - wrapper.to_string() + serde_json::Value::Object(wrapper).to_string() } else { sealed }); diff --git a/src/memory/sqlite/mailbox.rs b/src/memory/sqlite/mailbox.rs index b2d8d9afa..933ce5026 100644 --- a/src/memory/sqlite/mailbox.rs +++ b/src/memory/sqlite/mailbox.rs @@ -49,7 +49,9 @@ impl SqliteMailbox { address: &crate::messaging::SessionAddr, ) -> MailboxResult<()> { if address.instance != self.local_instance { - return Err(MailboxError::Unauthorized); + return Err(crate::messaging::mailbox::unauthorized( + crate::messaging::mailbox::UnauthorizedReason::LocalInstanceMismatch, + )); } let writer = self.memory.pool.write(); pin::check_scope(&writer, scope, address, None, true) diff --git a/src/messaging/a2a/listener.rs b/src/messaging/a2a/listener.rs index e0a5a3132..6108ab318 100644 --- a/src/messaging/a2a/listener.rs +++ b/src/messaging/a2a/listener.rs @@ -36,6 +36,12 @@ fn response(status: StatusCode, value: serde_json::Value) -> Response { response } fn refused(status: StatusCode, code: &str) -> Response { + use crate::messaging::mailbox::{UnauthorizedReason, unauthorized}; + if status == StatusCode::UNAUTHORIZED { + unauthorized(UnauthorizedReason::RequestIdentityRejected); + } else if status == StatusCode::FORBIDDEN { + unauthorized(UnauthorizedReason::PeerGrantMismatch); + } response(status, serde_json::json!({"error":code})) } fn target_authority( diff --git a/src/messaging/mailbox/authorization.rs b/src/messaging/mailbox/authorization.rs index 54719bf75..78d5cf77b 100644 --- a/src/messaging/mailbox/authorization.rs +++ b/src/messaging/mailbox/authorization.rs @@ -3,6 +3,8 @@ use super::MailboxError; #[derive(Debug, Clone, Copy)] pub(crate) enum UnauthorizedReason { CallerMissing, + RequestIdentityRejected, + PeerGrantMismatch, WorkerSenderUnavailable, LocalInstanceMismatch, LocalOwnerMismatch, @@ -31,6 +33,8 @@ impl UnauthorizedReason { pub(crate) const fn as_str(self) -> &'static str { match self { Self::CallerMissing => "caller_missing", + Self::RequestIdentityRejected => "request_identity_rejected", + Self::PeerGrantMismatch => "peer_grant_mismatch", Self::WorkerSenderUnavailable => "worker_sender_unavailable", Self::LocalInstanceMismatch => "local_instance_mismatch", Self::LocalOwnerMismatch => "local_owner_mismatch", From 838f322007321f1014fea41fda0264958c44c400 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 18:21:58 +0400 Subject: [PATCH 0013/1567] fix(messaging): preserve encrypted child routing on terminal recovery --- src/memory/encrypted_scope.rs | 72 +++++++++++++++++++---------------- 1 file changed, 39 insertions(+), 33 deletions(-) diff --git a/src/memory/encrypted_scope.rs b/src/memory/encrypted_scope.rs index b60bc1702..518147dc4 100644 --- a/src/memory/encrypted_scope.rs +++ b/src/memory/encrypted_scope.rs @@ -102,38 +102,44 @@ impl EncryptedScope { /// Keep only routing metadata visible to SQLite's transactional child hook. /// Source text and the complete original payload remain encrypted. fn seal_event_payload(&self, input: &mut crate::memory::MessageEventInput) -> anyhow::Result<()> { - let Some(payload) = input.raw_payload_json.take() else { - return Ok(()); - }; - let key = input.idempotency_key.as_deref().unwrap_or("event"); - let sealed = self.seal(&format!("{key}:payload"), &payload)?; - let value = serde_json::from_str::(&payload).ok(); - let child = matches!( - input.source, - crate::memory::MessageEventSource::SessionsSpawn | crate::memory::MessageEventSource::SessionWorker - ); - input.raw_payload_json = Some(if child { - let mut wrapper = serde_json::Map::new(); - wrapper.insert("encrypted_child_payload".into(), sealed.into()); - if let Some(record) = value.as_ref().and_then(|value| value.get("child_session_record")) { - let record: crate::memory::child_sessions::ChildSessionRecord = serde_json::from_value(record.clone())?; - anyhow::ensure!(record.context.is_empty(), "launch metadata cannot expose child history"); - wrapper.insert("child_session_record".into(), serde_json::to_value(record)?); - } - if let Some(status) = value - .as_ref() - .and_then(|value| value.get("status")) - .and_then(serde_json::Value::as_str) - { - wrapper.insert("status".into(), status.into()); - } - serde_json::Value::Object(wrapper).to_string() - } else { - sealed - }); + if let Some(payload) = input.raw_payload_json.take() { + let key = input.idempotency_key.as_deref().unwrap_or("event"); + input.raw_payload_json = Some(self.seal_payload(input.source, key, &payload)?); + } Ok(()) } + fn seal_payload( + &self, + source: crate::memory::MessageEventSource, + key: &str, + payload: &str, + ) -> anyhow::Result { + let sealed = self.seal(&format!("{key}:payload"), payload)?; + if !matches!( + source, + crate::memory::MessageEventSource::SessionsSpawn | crate::memory::MessageEventSource::SessionWorker + ) { + return Ok(sealed); + } + let value = serde_json::from_str::(payload).ok(); + let mut wrapper = serde_json::Map::new(); + wrapper.insert("encrypted_child_payload".into(), sealed.into()); + if let Some(record) = value.as_ref().and_then(|value| value.get("child_session_record")) { + let record: crate::memory::child_sessions::ChildSessionRecord = serde_json::from_value(record.clone())?; + anyhow::ensure!(record.context.is_empty(), "launch metadata cannot expose child history"); + wrapper.insert("child_session_record".into(), serde_json::to_value(record)?); + } + if let Some(status) = value + .as_ref() + .and_then(|value| value.get("status")) + .and_then(serde_json::Value::as_str) + { + wrapper.insert("status".into(), status.into()); + } + Ok(serde_json::Value::Object(wrapper).to_string()) + } + fn open_aad(&self, record_hash: &str, stored: &str) -> Option { if !self.crypto.encryption_enabled() { return Some(stored.to_string()); @@ -492,7 +498,7 @@ impl Memory for EncryptedScope { let key = event.idempotency_key.as_deref().unwrap_or("event"); event.content = self.seal(key, &event.content)?; if let Some(payload) = event.raw_payload_json.take() { - event.raw_payload_json = Some(self.seal(&format!("{key}:payload"), &payload)?); + event.raw_payload_json = Some(self.seal_payload(event.source, key, &payload)?); } self.inner.project_console_message_until(&event, deadline).await } @@ -1027,7 +1033,7 @@ impl Memory for EncryptedScope { self.seal_event_content(&mut event)?; if let Some(payload) = event.raw_payload_json.take() { let key = event.idempotency_key.as_deref().unwrap_or("event"); - event.raw_payload_json = Some(self.seal(&format!("{key}:payload"), &payload)?); + event.raw_payload_json = Some(self.seal_payload(event.source, key, &payload)?); } } } @@ -1082,7 +1088,7 @@ impl Memory for EncryptedScope { .raw_payload_json .clone() .context("stored recovery payload missing")?, - _ => self.seal(&format!("{key}:payload"), &payload)?, + _ => self.seal_payload(event.source, key, &payload)?, }); } } @@ -1127,7 +1133,7 @@ impl Memory for EncryptedScope { .clone() .context("stored recovery payload missing")? } - _ => reveal.seal(&format!("{key}:payload"), &payload)?, + _ => reveal.seal_payload(final_input.source, key, &payload)?, }); } Ok(()) From f30fb6b5b2e213bd09cba29e65106c47c7784933 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 18:25:50 +0400 Subject: [PATCH 0014/1567] fix(memory): borrow child source when sealing routing metadata --- src/memory/encrypted_scope.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/memory/encrypted_scope.rs b/src/memory/encrypted_scope.rs index 518147dc4..12a3e443a 100644 --- a/src/memory/encrypted_scope.rs +++ b/src/memory/encrypted_scope.rs @@ -104,14 +104,14 @@ impl EncryptedScope { fn seal_event_payload(&self, input: &mut crate::memory::MessageEventInput) -> anyhow::Result<()> { if let Some(payload) = input.raw_payload_json.take() { let key = input.idempotency_key.as_deref().unwrap_or("event"); - input.raw_payload_json = Some(self.seal_payload(input.source, key, &payload)?); + input.raw_payload_json = Some(self.seal_payload(&input.source, key, &payload)?); } Ok(()) } fn seal_payload( &self, - source: crate::memory::MessageEventSource, + source: &crate::memory::MessageEventSource, key: &str, payload: &str, ) -> anyhow::Result { @@ -498,7 +498,7 @@ impl Memory for EncryptedScope { let key = event.idempotency_key.as_deref().unwrap_or("event"); event.content = self.seal(key, &event.content)?; if let Some(payload) = event.raw_payload_json.take() { - event.raw_payload_json = Some(self.seal_payload(event.source, key, &payload)?); + event.raw_payload_json = Some(self.seal_payload(&event.source, key, &payload)?); } self.inner.project_console_message_until(&event, deadline).await } @@ -1033,7 +1033,7 @@ impl Memory for EncryptedScope { self.seal_event_content(&mut event)?; if let Some(payload) = event.raw_payload_json.take() { let key = event.idempotency_key.as_deref().unwrap_or("event"); - event.raw_payload_json = Some(self.seal_payload(event.source, key, &payload)?); + event.raw_payload_json = Some(self.seal_payload(&event.source, key, &payload)?); } } } @@ -1088,7 +1088,7 @@ impl Memory for EncryptedScope { .raw_payload_json .clone() .context("stored recovery payload missing")?, - _ => self.seal_payload(event.source, key, &payload)?, + _ => self.seal_payload(&event.source, key, &payload)?, }); } } @@ -1133,7 +1133,7 @@ impl Memory for EncryptedScope { .clone() .context("stored recovery payload missing")? } - _ => reveal.seal_payload(final_input.source, key, &payload)?, + _ => reveal.seal_payload(&final_input.source, key, &payload)?, }); } Ok(()) From 00f75ae68a306ba62a978fff2275fc9177755625 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 18:29:22 +0400 Subject: [PATCH 0015/1567] chore(tui): retain focused child key dispatch assertion --- src/chat/tui/tests/rearch_chrome.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/chat/tui/tests/rearch_chrome.rs b/src/chat/tui/tests/rearch_chrome.rs index c64f48ced..f94e89017 100644 --- a/src/chat/tui/tests/rearch_chrome.rs +++ b/src/chat/tui/tests/rearch_chrome.rs @@ -310,7 +310,7 @@ fn fullscreen_scroll_focus_rules_do_not_steal_input_or_child_keys() { ); assert_eq!( dispatch_global_key(key(KeyCode::PageUp), &mut child_state), - KeyDispatch::PageTranscriptUp + KeyDispatch::PageSessionUp ); } From ecb7d8c80acc9dc0d80ab6eb56a8c1cb8f1a992d Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 18:32:45 +0400 Subject: [PATCH 0016/1567] fix(messaging): persist spawn observations without replaying child admission --- src/memory/sqlite/child_turns.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/memory/sqlite/child_turns.rs b/src/memory/sqlite/child_turns.rs index b100d76fd..ea3c1c8a6 100644 --- a/src/memory/sqlite/child_turns.rs +++ b/src/memory/sqlite/child_turns.rs @@ -28,7 +28,12 @@ pub(super) fn source_written(conn: &rusqlite::Transaction<'_>, event: &MessageEv } Err(_) => return Ok(()), }; - if let Some(value) = value.get("child_session_record") { + // task.spawned mirrors this metadata for observation; only the admitted + // user input creates/advances the durable logical child. + if event.role == "user" + && event.event_type == "message.created" + && let Some(value) = value.get("child_session_record") + { let mut record: ChildSessionRecord = serde_json::from_value(value.clone())?; let run = event.run_id.as_deref().ok_or(ChildSessionError::InvalidRecord)?; anyhow::ensure!( From 0afc5792b346ecf566702ddc93e6ec1b390e511b Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 18:56:16 +0400 Subject: [PATCH 0017/1567] fix(messaging): align existing schema fixtures and canonical worker workspace --- src/memory/sqlite/tests/mailbox/section_2.rs | 2 +- src/session_worker/mailbox_harness.rs | 5 ++-- .../goldens/published/sessions_spawn.json | 11 ++++++-- src/tools/schema/goldens/sessions_spawn.json | 28 +++++++++++++++++-- 4 files changed, 37 insertions(+), 9 deletions(-) diff --git a/src/memory/sqlite/tests/mailbox/section_2.rs b/src/memory/sqlite/tests/mailbox/section_2.rs index 524c5fe4b..6b5f4bcd5 100644 --- a/src/memory/sqlite/tests/mailbox/section_2.rs +++ b/src/memory/sqlite/tests/mailbox/section_2.rs @@ -175,7 +175,7 @@ fn slash_msg_builds_envelope_to_peer_session() { "slash msg builds envelope to peer session: expected messaging contract changed" ); assert!( - crate::chat::commands::msg::parse("/msg local target/ ", &f.source).is_err(), + crate::chat::commands::msg::parse("/msg target ", &f.source).is_err(), "slash msg builds envelope to peer session: expected messaging contract changed" ); } diff --git a/src/session_worker/mailbox_harness.rs b/src/session_worker/mailbox_harness.rs index 4915aa99a..98b82879d 100644 --- a/src/session_worker/mailbox_harness.rs +++ b/src/session_worker/mailbox_harness.rs @@ -246,12 +246,12 @@ pub async fn run(workspace: &Path, turns: usize) -> Result<()> { std::fs::create_dir_all(workspace)?; let workspace = std::fs::canonicalize(workspace)?; let config_dir = crate::config::process_config_dir().context("mailbox process fixture requires --config-dir")?; - let config = crate::config::Config::load_existing_read_only_with_config_dir(Some( + let mut config = crate::config::Config::load_existing_read_only_with_config_dir(Some( config_dir.to_str().context("mailbox config path must be UTF-8")?, )) .await?; ensure!( - config.workspace_dir == workspace, + std::fs::canonicalize(&config.workspace_dir)? == workspace, "mailbox fixture workspace differs from loaded config" ); ensure!( @@ -259,6 +259,7 @@ pub async fn run(workspace: &Path, turns: usize) -> Result<()> { && config.default_model.as_deref() == Some("prx-mailbox-model"), "mailbox fixture requires its scripted model" ); + config.workspace_dir.clone_from(&workspace); let memory = Arc::new(SqliteMemory::new(&workspace)?); let store = SqliteMailbox::new( memory.as_ref().clone(), diff --git a/src/tools/schema/goldens/published/sessions_spawn.json b/src/tools/schema/goldens/published/sessions_spawn.json index 4803bc4b0..bacdc7d5c 100644 --- a/src/tools/schema/goldens/published/sessions_spawn.json +++ b/src/tools/schema/goldens/published/sessions_spawn.json @@ -3,9 +3,10 @@ "properties": { "action": { "default": "spawn", - "description": "Action to perform, with the parameter it reads: 'spawn' task; 'spawn_batch' tasks; 'join' batch_id; 'list' none; 'kill' run_id; 'history' run_id; 'steer' run_id + message; 'chat_sessions' none; 'chat_assign' session_id + task. Defaults to 'spawn' when omitted.", + "description": "Action to perform, with the parameter it reads: 'spawn' task; 'continue' session_key + task; 'spawn_batch' tasks; 'join' batch_id; 'list' none; 'kill' run_id; 'history' run_id; 'steer' run_id + message; 'chat_sessions' none; 'chat_assign' session_id + task. Defaults to 'spawn' when omitted.", "enum": [ "spawn", + "continue", "spawn_batch", "join", "list", @@ -84,7 +85,7 @@ "type": "string" }, "run_id": { - "description": "Sub-agent run id returned by 'spawn' and listed by 'list'. Required by 'kill', 'history' and 'steer'. Not a chat session id.", + "description": "Sub-agent run id returned by 'spawn' and listed by 'list'. Required by 'kill', 'history' and 'steer'; alternative to session_key for 'continue'. Not a chat session id.", "minLength": 1, "type": "string" }, @@ -93,8 +94,12 @@ "minLength": 1, "type": "string" }, + "session_key": { + "description": "For 'continue': stable spawn session key.", + "type": "string" + }, "task": { - "description": "The work to be done, as instructions. Required by 'spawn' and by 'chat_assign' ('chat_assign' has no `message`, `prompt` or `text` parameter). Use `tasks` for 'spawn_batch' and `message` for 'steer'.", + "description": "The work to be done, as instructions. Required by 'spawn', 'continue' and by 'chat_assign' ('chat_assign' has no `message`, `prompt` or `text` parameter). Use `tasks` for 'spawn_batch' and `message` for 'steer'.", "minLength": 1, "type": "string" }, diff --git a/src/tools/schema/goldens/sessions_spawn.json b/src/tools/schema/goldens/sessions_spawn.json index 8388a3c0d..987d3b2d9 100644 --- a/src/tools/schema/goldens/sessions_spawn.json +++ b/src/tools/schema/goldens/sessions_spawn.json @@ -32,6 +32,23 @@ ] } }, + { + "if": { + "properties": { + "action": { + "const": "continue" + } + }, + "required": [ + "action" + ] + }, + "then": { + "required": [ + "task" + ] + } + }, { "if": { "properties": { @@ -123,9 +140,10 @@ "properties": { "action": { "default": "spawn", - "description": "Action to perform, with the parameter it reads: 'spawn' task; 'spawn_batch' tasks; 'join' batch_id; 'list' none; 'kill' run_id; 'history' run_id; 'steer' run_id + message; 'chat_sessions' none; 'chat_assign' session_id + task. Defaults to 'spawn' when omitted.", + "description": "Action to perform, with the parameter it reads: 'spawn' task; 'continue' session_key + task; 'spawn_batch' tasks; 'join' batch_id; 'list' none; 'kill' run_id; 'history' run_id; 'steer' run_id + message; 'chat_sessions' none; 'chat_assign' session_id + task. Defaults to 'spawn' when omitted.", "enum": [ "spawn", + "continue", "spawn_batch", "join", "list", @@ -204,7 +222,7 @@ "type": "string" }, "run_id": { - "description": "Sub-agent run id returned by 'spawn' and listed by 'list'. Required by 'kill', 'history' and 'steer'. Not a chat session id.", + "description": "Sub-agent run id returned by 'spawn' and listed by 'list'. Required by 'kill', 'history' and 'steer'; alternative to session_key for 'continue'. Not a chat session id.", "minLength": 1, "type": "string" }, @@ -213,8 +231,12 @@ "minLength": 1, "type": "string" }, + "session_key": { + "description": "For 'continue': stable spawn session key.", + "type": "string" + }, "task": { - "description": "The work to be done, as instructions. Required by 'spawn' and by 'chat_assign' ('chat_assign' has no `message`, `prompt` or `text` parameter). Use `tasks` for 'spawn_batch' and `message` for 'steer'.", + "description": "The work to be done, as instructions. Required by 'spawn', 'continue' and by 'chat_assign' ('chat_assign' has no `message`, `prompt` or `text` parameter). Use `tasks` for 'spawn_batch' and `message` for 'steer'.", "minLength": 1, "type": "string" }, From f6536928f6f021d1db18d789279f5925bb6d2fc3 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 18:58:14 +0400 Subject: [PATCH 0018/1567] fix(messaging): describe logical recipients separately from live run steering --- src/tools/sessions_send.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/tools/sessions_send.rs b/src/tools/sessions_send.rs index 7903a89b1..c2b046847 100644 --- a/src/tools/sessions_send.rs +++ b/src/tools/sessions_send.rs @@ -118,6 +118,13 @@ impl Tool for SessionsSendTool { } fn description(&self) -> &str { + if self.mailbox.is_some() || self.messaging.is_some() { + return "Send an ordinary message using 'to' to a logical session, including an idle child. \ + Use its exact session_key (retain the spawn: prefix), or 'parent' from a child. \ + An object target is {session, instance?, owner?, agent?}; local defaults use the caller's instance/owner and main agent. \ + A remote target needs the full pinned SPIFFE instance ID and receiving owner's session. \ + Use 'run_id' only to steer a currently running execution. Supply exactly one of 'to' or 'run_id', plus 'message'."; + } "Send a message to a running sub-agent session to redirect or update its instructions. \ Use this for cross-session communication: inject new context, pivot the task, \ or provide additional information to a running sub-agent. \ @@ -127,8 +134,8 @@ impl Tool for SessionsSendTool { fn parameters_schema(&self) -> serde_json::Value { if self.mailbox.is_some() || self.messaging.is_some() { return json!({"type":"object","additionalProperties":false, - "properties":{"run_id":{"type":"string","minLength":1}, - "to":{"oneOf":[crate::messaging::send::target_schema(),{"type":"string","minLength":1}]}, + "properties":{"run_id":{"type":"string","minLength":1,"description":"Live execution ID for steering only; omit when sending an ordinary message with to."}, + "to":{"description":"Exact logical session_key (including spawn:), parent alias, or address object. Remote instance is a full pinned SPIFFE ID; owner/session belong to the receiver.","oneOf":[crate::messaging::send::target_schema(),{"type":"string","minLength":1}]}, "message":{"type":"string","minLength":1}},"required":["message"]}); } json!({ From fec85df017540111f8db90ba606347ce5c52afaa Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 19:10:51 +0400 Subject: [PATCH 0019/1567] fix(messaging): retain admitted run identity for mailbox child continuations --- src/tools/sessions_spawn/spawn.rs | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/src/tools/sessions_spawn/spawn.rs b/src/tools/sessions_spawn/spawn.rs index 9083118d1..b2c8f218c 100644 --- a/src/tools/sessions_spawn/spawn.rs +++ b/src/tools/sessions_spawn/spawn.rs @@ -1513,15 +1513,11 @@ impl SessionsSpawnTool { .approval_resolver_factory .as_ref() .map(|factory| factory.resolver_for(&run_id)); - // NeedsInput: when (and only when) an approval resolver is attached, hand - // the loop the run registry + id so it can deterministically restore - // `AwaitingInput` -> `Running` on cancel-and-resume (steer). `None` - // elsewhere — without a resolver no run can ever suspend. - let (restore_active_runs, restore_run_id) = if run_approval_resolver.is_some() { - (Some(self.active_runs.clone()), Some(run_id.clone())) - } else { - (None, None) - }; + // Only approval suspension needs the optional restoration registry. + // Every task still carries its admitted run identity, including mailbox + // continuations without an approval surface. + let restore_active_runs = run_approval_resolver.as_ref().map(|_| self.active_runs.clone()); + let restore_run_id = Some(run_id.clone()); let task_owned = task.to_string(); let identity_workspace = child_model_config.workspace_dir.clone(); let security = Arc::clone(launch_security); From f029b39122613a7c95715d9cbed4cec7d0b7898a Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 20:24:47 +0400 Subject: [PATCH 0020/1567] fix(messaging): align terminal mailbox identity and expose setup failures --- docs/configuration.md | 8 ++ docs/tools.md | 7 ++ src/chat/chat_events.rs | 5 +- src/chat/run/startup.rs | 10 ++- src/chat/session_switch.rs | 2 +- .../tests/regfix_approval_switch_tests.rs | 2 +- src/config/generation/section_1.rs | 7 +- src/memory/sqlite/mailbox/local_runtime.rs | 2 +- src/messaging/a2a/cli.rs | 53 +++++++++---- src/messaging/a2a/outbound.rs | 77 +++++++++++++++---- 10 files changed, 139 insertions(+), 34 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index fdadc6741..46f8caff8 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -3539,3 +3539,11 @@ explicitly installs a bearer and records its hash in this list; the gateway then reports pairing ACTIVE and accepts that bearer instead of offering a new one-time pairing code. Keep and use the issued file; do not remove valid paired credentials just to request a second pairing. + +For mTLS messaging, run `prx a2a init`, then `prx a2a bind 127.0.0.1:16832`. +Initialization prints the terminal-chat owner alongside the public SPIFFE identity +and fingerprint. `prx a2a peer add` requires an explicit `--owner`: this is the +**local receiving owner** whose sessions this peer may message. Use the local +owner on each instance, even when the instances have different default owners. +Restart running daemons and chats after A2A setup or listener/identity changes. +Peer grants and revocations are also rechecked during live delivery. diff --git a/docs/tools.md b/docs/tools.md index c53a1d492..62c89c0c0 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -1995,3 +1995,10 @@ the owner's pending-approval surface. `session_status` includes the caller session's last 64 outbox states, including `expired` and permanent refusals, without message bodies or recipient tokens. + +Terminal chats use the durable mailbox session key `chat:terminal:local-user:`. +The startup banner prints the complete session key and owner. Child focus accepts +follow-up text after completion and starts another turn in the same child session. +`/msg #1 ` addresses that child's logical session, including after completion. +If a process child reports `configuration_changed`, restart its parent chat before +retrying; a newer disk configuration cannot execute under the parent's old seal. diff --git a/src/chat/chat_events.rs b/src/chat/chat_events.rs index a642cbe16..cbbc040f8 100644 --- a/src/chat/chat_events.rs +++ b/src/chat/chat_events.rs @@ -50,7 +50,10 @@ impl ReduxMode { /// if the key is not in `chat:{id}` form it is returned unchanged (the canonical /// derivation then keys on the whole string, still stable). pub(super) fn chat_session_id_from_key(chat_session_key: &str) -> &str { - chat_session_key.strip_prefix("chat:").unwrap_or(chat_session_key) + chat_session_key + .strip_prefix("chat:terminal:local-user:") + .or_else(|| chat_session_key.strip_prefix("chat:")) + .unwrap_or(chat_session_key) } /// Build a chat message-event write scope on the stable durable-canonical diff --git a/src/chat/run/startup.rs b/src/chat/run/startup.rs index 62c08b9b9..bb52b2a00 100644 --- a/src/chat/run/startup.rs +++ b/src/chat/run/startup.rs @@ -299,7 +299,7 @@ pub(super) fn initial_conversation( // run_id. The session identity is carried by `chat_session_key`, never by // run_id, and turns deliberately set no parent_run_id (that field is reserved // for the spawn execution lineage, not for relating turns within a session). - let chat_session_key = format!("chat:{}", chat_session.id); + let chat_session_key = crate::runtime::envelope::RuntimeEnvelope::chat_canonical_session_key(&chat_session.id); let fabric_turn_seq: u64 = 0; // ── Build banner text ──────────────────────────────────────── @@ -315,7 +315,13 @@ pub(super) fn initial_conversation( // The previous multi-line "PRX Chat — ... \n Type /help for commands" // hint has moved to the persistent footer instead. `chat_session` is no // longer queried for the banner but stays in scope for downstream use. - let banner = startup_banner(provider_name, model_name); + let envelope = crate::chat::chat_runtime_envelope(&config.workspace_dir.to_string_lossy(), &chat_session_key); + let banner = format!( + "{}\nMailbox session={} owner={} agent=main", + startup_banner(provider_name, model_name), + chat_session_key, + envelope.resolved_owner_id() + ); // ── Conversation history ───────────────────────────────────── let leading_system_prompt = leading_system_prompt_for_session(config, model_name, skills, native_tools); diff --git a/src/chat/session_switch.rs b/src/chat/session_switch.rs index 55c32f3fa..8cad610c4 100644 --- a/src/chat/session_switch.rs +++ b/src/chat/session_switch.rs @@ -348,7 +348,7 @@ pub(super) async fn apply_chat_session_switch( *ctx.attached_follow = None; *ctx.attached_follow_seq = None; - *ctx.chat_session_key = format!("chat:{}", loaded.id); + *ctx.chat_session_key = crate::runtime::envelope::RuntimeEnvelope::chat_canonical_session_key(&loaded.id); *ctx.fabric_turn_seq = loaded .turns .iter() diff --git a/src/chat/tests/regfix_approval_switch_tests.rs b/src/chat/tests/regfix_approval_switch_tests.rs index 78db61838..8c69eb6a4 100644 --- a/src/chat/tests/regfix_approval_switch_tests.rs +++ b/src/chat/tests/regfix_approval_switch_tests.rs @@ -167,7 +167,7 @@ async fn session_switch_fail_closes_pending_approvals_and_resets_mirror() { "loaded-session", "the reader adopted the loaded session" ); - assert_eq!(chat_session_key, "chat:loaded-session"); + assert_eq!(chat_session_key, "chat:terminal:local-user:loaded-session"); assert_eq!(fabric_turn_seq, 1); assert!(announced_started_sessions.is_empty()); assert!(last_sessions_summary.is_empty(), "expected an empty value"); diff --git a/src/config/generation/section_1.rs b/src/config/generation/section_1.rs index bcedd623e..5411c9409 100644 --- a/src/config/generation/section_1.rs +++ b/src/config/generation/section_1.rs @@ -118,6 +118,11 @@ pub struct ConfigGeneration { #[error("worker working root differs from signed parent configuration")] pub(crate) struct ProcessWorkingRootMismatch; +/// A worker must not execute a newer disk configuration under an older parent seal. +#[derive(Debug, thiserror::Error)] +#[error("configuration_changed: process configuration changed since this chat started; restart the parent chat and retry the process child")] +pub(crate) struct ProcessConfigurationChanged; + /// Metadata, a working root override and a keyed effective snapshot digest. /// Credential values and other configuration overrides are not transported. #[derive(Debug, Clone, Serialize, Deserialize)] @@ -266,7 +271,7 @@ impl ConfigGeneration { } anyhow::ensure!( ConfigSourceRevision::from_config(&config)? == binding.source_revision, - "process configuration source differs from parent generation" + ProcessConfigurationChanged ); anyhow::ensure!( key.verify_hmac( diff --git a/src/memory/sqlite/mailbox/local_runtime.rs b/src/memory/sqlite/mailbox/local_runtime.rs index 01b081b16..f396f68c9 100644 --- a/src/memory/sqlite/mailbox/local_runtime.rs +++ b/src/memory/sqlite/mailbox/local_runtime.rs @@ -122,7 +122,7 @@ impl SqliteMailbox { crate::messaging::mailbox::UnauthorizedReason::ReceiverAgentMismatch, )); } - let known:bool=tx.query_row("SELECT EXISTS(SELECT 1 FROM message_events WHERE workspace_id=?1 AND owner_id=?2 AND session_key=?3) OR EXISTS(SELECT 1 FROM sessions WHERE owner_id=?2 AND session_key=?3) OR EXISTS(SELECT 1 FROM child_sessions WHERE workspace_id=?1 AND owner_id=?2 AND session_id=?3)",params![workspace,address.owner,address.session],|r|r.get(0)).map_err(storage_error)?; + let known:bool=tx.query_row("SELECT EXISTS(SELECT 1 FROM message_events WHERE workspace_id=?1 AND owner_id=?2 AND session_key=?3) OR EXISTS(SELECT 1 FROM sessions WHERE owner_id=?2 AND session_key=?3) OR EXISTS(SELECT 1 FROM child_sessions WHERE workspace_id=?1 AND owner_id=?2 AND session_id=?3) OR EXISTS(SELECT 1 FROM agent_scopes WHERE workspace_id=?1 AND owner_id=?2 AND session_key=?3 AND agent_key=?4)",params![workspace,address.owner,address.session,crate::messaging::mailbox::agent_key(&address.agent)?],|r|r.get(0)).map_err(storage_error)?; if !known && !registered { return Err(crate::messaging::mailbox::unauthorized( crate::messaging::mailbox::UnauthorizedReason::ReceiverUnknown, diff --git a/src/messaging/a2a/cli.rs b/src/messaging/a2a/cli.rs index 2002516f7..ed5be31cf 100644 --- a/src/messaging/a2a/cli.rs +++ b/src/messaging/a2a/cli.rs @@ -12,6 +12,8 @@ pub enum A2aCommand { #[arg(long, conflicts_with = "rotate")] prepare_rotate: bool, }, + /// Enable mTLS messaging at this address; restart running daemons and chats. + Bind { address: std::net::SocketAddr }, Peer { #[command(subcommand)] command: PeerCommand, @@ -28,7 +30,7 @@ pub enum PeerCommand { #[arg(long)] address: String, #[arg(long)] - owner: Option, + owner: String, #[arg(long = "session", default_value = "*")] sessions: Vec, #[arg(long = "agent", default_value = "*")] @@ -55,16 +57,32 @@ pub async fn run(command: A2aCommand, mut config: crate::config::Config) -> Resu }) .await??; Ok(format!( - "{}\nfingerprint {}\nexpires {}", - identity.spiffe_id, identity.fingerprint, identity.expires_at + "{}\nfingerprint {}\nexpires {}\nowner {}\nRestart running daemons and chats after A2A configuration or identity changes.", + identity.spiffe_id, + identity.fingerprint, + identity.expires_at, + local_owner(&config) )) } + A2aCommand::Bind { address } => { + ensure!(address.port() != 0, "A2A bind requires a nonzero port"); + config.a2a.bind = address.to_string(); + config.a2a.messaging_enabled = true; + config.a2a.validate()?; + persist(original, config).await?; + Ok("A2A messaging enabled; restart running daemons and chats to apply the listener configuration.".into()) + } A2aCommand::Peer { command: PeerCommand::List, } => { let selected = config.clone(); let local = crate::runtime::blocking::spawn_blocking(move || super::identity::load(&selected)).await??; - let mut rows = vec![format!("local {} expires {}", local.spiffe_id, local.expires_at)]; + let mut rows = vec![format!( + "local {} owner={} expires {}", + local.spiffe_id, + local_owner(&config), + local.expires_at + )]; let mut peers: Vec<_> = config.a2a.peers.iter().collect(); peers.sort_by_key(|(name, _)| *name); for (name, peer) in peers { @@ -115,14 +133,6 @@ pub async fn run(command: A2aCommand, mut config: crate::config::Config) -> Resu .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_')), "invalid peer name" ); - let owner = owner.unwrap_or_else(|| { - crate::runtime::envelope::RuntimeEnvelope::chat_canonical( - config.workspace_dir.to_string_lossy().into_owned(), - "peer-management", - crate::memory::MemoryVisibility::Workspace, - ) - .resolved_owner_id() - }); let mut fingerprints = vec![fingerprint.clone()]; if let Some(old) = config.a2a.peers.get(&name) { ensure!( @@ -134,6 +144,7 @@ pub async fn run(command: A2aCommand, mut config: crate::config::Config) -> Resu fingerprints.push(fingerprint); } } + let bound_owner = owner.clone(); config.a2a.peers.insert( name, crate::config::A2aPeer { @@ -147,7 +158,9 @@ pub async fn run(command: A2aCommand, mut config: crate::config::Config) -> Resu ); config.a2a.validate()?; persist(original, config).await?; - Ok("Peer grant saved; both instances must pin each other.".into()) + Ok(format!( + "Peer grant saved, bound owner={bound_owner}; both instances must pin each other. Restart running daemons and chats after setup." + )) } A2aCommand::Peer { command: PeerCommand::Remove { name, fingerprint }, @@ -167,7 +180,10 @@ pub async fn run(command: A2aCommand, mut config: crate::config::Config) -> Resu } config.a2a.validate()?; persist(original, config).await?; - Ok("Peer grant removed; live connections will close.".into()) + Ok( + "Peer grant removed; live connections will close. Restart running daemons and chats after setup." + .into(), + ) } } } @@ -180,3 +196,12 @@ async fn persist(before: crate::config::Config, after: crate::config::Config) -> service.apply(plan, ConfigActor::Cli, revision.as_deref()).await?; Ok(()) } + +fn local_owner(config: &crate::config::Config) -> String { + crate::runtime::envelope::RuntimeEnvelope::chat_canonical( + config.workspace_dir.to_string_lossy().into_owned(), + "peer-management", + crate::memory::MemoryVisibility::Workspace, + ) + .resolved_owner_id() +} diff --git a/src/messaging/a2a/outbound.rs b/src/messaging/a2a/outbound.rs index 95e069e6a..e634dd0a5 100644 --- a/src/messaging/a2a/outbound.rs +++ b/src/messaging/a2a/outbound.rs @@ -97,7 +97,7 @@ impl RemoteTransport { current.spiffe_id == peer.spiffe_id && current.fingerprints == peer.fingerprints && current.address == peer.address, - "peer changed" + AttemptInterrupted ); let response = client .post(format!("https://{}/a2a/v1/messages", peer.address)) @@ -107,7 +107,7 @@ impl RemoteTransport { Ok((response.status().as_u16(), retry_after(&response))) }; tokio::select! { - ()=cancellation.cancelled()=>Err(anyhow::anyhow!("peer client changed; retry delivery")), + ()=cancellation.cancelled()=>Err(AttemptInterrupted.into()), result=request=>result, } } @@ -143,9 +143,27 @@ impl RemoteTransport { } = pending; let (status, retry) = match self.attempt(&runtime, &scope, &source, &mut message).await { Ok(value) => value, - Err(error) if super::dispatch::permanent(&error) => (403, None), - Err(_) => (0, None), + Err(error) => { + tracing::warn!( + reason = attempt_reason(&error), + attempt = attempts.saturating_add(1), + "A2A outbound attempt failed" + ); + if super::dispatch::permanent(&error) { + (403, None) + } else { + (0, None) + } + } }; + if status != 202 && status != 0 { + tracing::warn!( + reason = status_reason(status), + status, + attempt = attempts.saturating_add(1), + "A2A outbound attempt refused" + ); + } if let Ok(peer) = self.peer(&message.to) { self.clients .state(&peer, if status == 202 { "available" } else { "unavailable" }); @@ -166,15 +184,7 @@ impl RemoteTransport { .saturating_add(i64::try_from(delay).unwrap_or(300)), ) }; - let error = match status { - 400 => "field_invalid", - 401 => "peer_unauthenticated", - 403 => "peer_not_allowed", - 413 => "message_too_large", - 422 => "chain_limit_reached", - 429 => "inbox_full", - _ => "peer_unavailable", - }; + let error = status_reason(status); store.retry_outbox(&scope, &source, &message, next, error)?; } Ok::<_, MailboxError>(()) @@ -206,3 +216,44 @@ fn backoff(attempts: u32) -> u64 { let ceiling = 1_u64.checked_shl(attempts.min(9)).unwrap_or(300).min(300); rand::random_range(0..=ceiling) } + +#[derive(Debug, thiserror::Error)] +#[error("peer configuration changed during delivery")] +struct AttemptInterrupted; +fn attempt_reason(error: &anyhow::Error) -> &'static str { + if error.is::() { + return "peer_configuration_changed"; + } + if let Some(error) = error.downcast_ref::() { + return if error.is_timeout() { + "peer_timeout" + } else if error.is_connect() { + "peer_connect_failed" + } else { + "peer_request_failed" + }; + } + if let Some(error) = error.downcast_ref::() { + return match error { + MailboxError::Unauthorized => "peer_not_allowed", + MailboxError::StaleIncarnation => "stale_incarnation", + _ => "mailbox_attempt_failed", + }; + } + if error.is::() { + return "peer_response_invalid"; + } + "peer_attempt_failed" +} +fn status_reason(status: u16) -> &'static str { + match status { + 400 => "field_invalid", + 401 => "peer_unauthenticated", + 403 => "peer_not_allowed", + 408 => "peer_timeout", + 413 => "message_too_large", + 422 => "chain_limit_reached", + 429 => "inbox_full", + _ => "peer_unavailable", + } +} From 36c350c47c501e1a35c3f4953c43d3fe18c12d13 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 20:27:30 +0400 Subject: [PATCH 0021/1567] fix(chat): poll durable peer inbox on the existing session tick --- src/chat/run/event_pump.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/chat/run/event_pump.rs b/src/chat/run/event_pump.rs index 8122e0e24..f0e37e7fb 100644 --- a/src/chat/run/event_pump.rs +++ b/src/chat/run/event_pump.rs @@ -526,6 +526,11 @@ loop { continue; } _ = sessions_tick.tick() => { + // A dedicated mTLS listener may run in another process. Its durable + // mailbox writes cannot signal this process's in-memory inbox. + if config.a2a.messaging_enabled && let Some(inbox) = message_inbox.as_mut() { + inbox.wake(); + } // 1) Summary reflow: surface each newly-finished session once, // carrying its `#N` + status (plan §v1b). No auto-focus. let finished = chat_sessions.poll_finished(&mut reported_sessions).await; From 30957b26a0ba5d9b915f7c64a51dd361446ec8f1 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 20:38:01 +0400 Subject: [PATCH 0022/1567] fix(a2a): make static delivery status classification const --- src/messaging/a2a/outbound.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/messaging/a2a/outbound.rs b/src/messaging/a2a/outbound.rs index e634dd0a5..54ecf4d6d 100644 --- a/src/messaging/a2a/outbound.rs +++ b/src/messaging/a2a/outbound.rs @@ -245,7 +245,7 @@ fn attempt_reason(error: &anyhow::Error) -> &'static str { } "peer_attempt_failed" } -fn status_reason(status: u16) -> &'static str { +const fn status_reason(status: u16) -> &'static str { match status { 400 => "field_invalid", 401 => "peer_unauthenticated", From 95bd19a62442485656c6c0bfc7d359e91e2200d1 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 21:59:49 +0400 Subject: [PATCH 0023/1567] fix(messaging): bind peer routing to owner grants and preserve terminal controls --- docs/configuration.md | 13 +- docs/tools.md | 16 +- src/chat/child_focus.rs | 17 +- src/chat/sessions/focus.rs | 13 +- src/chat/state/reduce_input.rs | 6 +- src/config/manage/autonomy.rs | 15 + src/config/manage/mod.rs | 1 + src/gateway/api/agent_erasure.rs | 99 +- src/gateway/api/mod.rs | 6 + src/main/section_1.rs | 7 + src/memory/sqlite/mailbox/outbox.rs | 15 + src/memory/sqlite/mailbox/sender.rs | 10 +- src/messaging/a2a/cli.rs | 1 + src/messaging/a2a/dispatch.rs | 8 +- src/messaging/a2a/listener.rs | 29 +- src/messaging/a2a/outbound.rs | 31 +- src/messaging/a2a/outbound/recipient.rs | 148 ++ src/messaging/mailbox.rs | 8 + src/messaging/runtime.rs | 15 +- src/runtime/manage_cli.rs | 2591 +--------------------- src/runtime/manage_cli/section_1.rs | 959 ++++++++ src/runtime/manage_cli/section_2.rs | 1637 ++++++++++++++ src/runtime/mode.rs | 1 + src/tools/sessions_send.rs | 4 +- tests/architecture_boundaries/config.rs | 8 +- tests/architecture_boundaries/helpers.rs | 2 + 26 files changed, 3011 insertions(+), 2649 deletions(-) create mode 100644 src/config/manage/autonomy.rs create mode 100644 src/messaging/a2a/outbound/recipient.rs create mode 100644 src/runtime/manage_cli/section_1.rs create mode 100644 src/runtime/manage_cli/section_2.rs diff --git a/docs/configuration.md b/docs/configuration.md index 46f8caff8..bd53bccc8 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -3530,8 +3530,9 @@ emit a typed, content-free `reason` at WARN. Reasons identify missing caller receipts, owner/instance/agent mismatches, unknown receivers, disabled inbound messaging, missing peers and scope-binding failures; no message, token or key is logged. Local targets default to the authenticated sender's owner. Remote -targets use the full SPIFFE ID and the receiving instance's actual owner, as -explicitly authorized by that instance's peer grant. +targets use the full SPIFFE ID and session; the receiving owner is learned +from its authenticated pins response. Typed routing refusals include +`peer_unknown`, `peer_not_allowed`, `owner_mismatch`, and `remote_not_enabled`. Fresh `prx init` starts with no paired bearer. A serialized empty `gateway.paired_tokens = []` does not block pairing. `prx token issue --out ...` @@ -3547,3 +3548,11 @@ and fingerprint. `prx a2a peer add` requires an explicit `--owner`: this is the owner on each instance, even when the instances have different default owners. Restart running daemons and chats after A2A setup or listener/identity changes. Peer grants and revocations are also rechecked during live delivery. + +`prx config autonomy supervised --yes` selects Supervised through the shared +configuration transaction; `readonly` and `full` are also accepted. An increase +prints the revision required by `--confirm-high-risk`. Restart running sessions +to apply it. `prx config agents new NAME --provider kimi-code --model k3 --yes` +creates a named role; apply the printed high-risk revision if required. +For a peer, `--owner` is the LOCAL owner allowed to send to and receive from that +peer; the remote destination owner is learned from the receiver's pins response. diff --git a/docs/tools.md b/docs/tools.md index 62c89c0c0..b40e9cb46 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -1973,7 +1973,8 @@ the existing explicit steering behavior. Targets include `main`, `parent`, `#N`, a child run ID, a stable `spawn:` session key, or another session key of the same owner. Structured `to` accepts `instance`, `owner`, `session`, `agent`; absent instance/owner default to the admitted caller. For a paired remote -instance, specify its persisted UUID and receiving owner explicitly. +instance, specify its full pinned SPIFFE ID and session; omit owner, which +the receiver supplies through its authenticated pins response. In interactive chat, `/msg ` uses the focused child's identity when attached. Incoming data appears as `[message from /]`. @@ -2002,3 +2003,16 @@ follow-up text after completion and starts another turn in the same child sessio `/msg #1 ` addresses that child's logical session, including after completion. If a process child reports `configuration_changed`, restart its parent chat before retrying; a newer disk configuration cannot execute under the parent's old seal. + +Remote `sessions_send` targets supply `instance`, `session`, and optionally `agent`. +Omit `owner`: the authenticated receiver's `/a2a/v1/pins` response supplies it. +A queued result always contains a durable message UUID; an assistant's text alone +is not a delivery receipt. Unknown peers, absent owner grants, foreign owners, and +disabled remote messaging return typed refusals before a write. + +A paired local operator erases a terminal chat or child through +`DELETE /api/terminal/sessions/{url-encoded-session-key}/agents/{agent}/history`. +First GET the same URL for its incarnation, then send that UUID in `If-Match` +and a fresh `Idempotency-Key`. The receiver derives the terminal owner from its +workspace; callers cannot supply a different owner. The Console erase route +remains `DELETE /api/sessions/{id}/agents/{agent}/history`. diff --git a/src/chat/child_focus.rs b/src/chat/child_focus.rs index b21e13d4f..6c29e2f47 100644 --- a/src/chat/child_focus.rs +++ b/src/chat/child_focus.rs @@ -333,7 +333,7 @@ impl ChildFocus { &record.model, &ctx.generation.effective.agent.compaction, None, - "manual", + crate::agent::compaction::MANUAL_COMPACT_TRIGGER, ) .await? { @@ -346,12 +346,25 @@ impl ChildFocus { timestamp: chrono::Utc::now(), }) .collect(); + } else { + return Ok(Some("Child context has no older complete turn to compact.".into())); } } _ => {} } + let count = turns.len(); store.replace_context(&record, &turns)?; - return Ok(Some("Child session updated.".into())); + if let Some(run) = ctx.sessions.child_run(&record.session_key).await { + *run.history.write().await = turns + .iter() + .map(|turn| crate::tools::sessions_spawn::HistoryEntry { + role: turn.role.clone(), + content: turn.content.clone(), + timestamp: turn.timestamp, + }) + .collect(); + } + return Ok(Some(format!("Child session updated: {count} context messages."))); } let mut session = super::session::ChatSession::new(&record.provider, &record.model); session.id = record.session_key.clone(); diff --git a/src/chat/sessions/focus.rs b/src/chat/sessions/focus.rs index 53b698fd2..888d0692d 100644 --- a/src/chat/sessions/focus.rs +++ b/src/chat/sessions/focus.rs @@ -376,7 +376,8 @@ pub enum EscAction { /// prompts before falling through to this resolver. /// 1. Switcher open → close the switcher. /// 2. Approval focus → deny the pending tool. -/// 3. Generating → interrupt the active turn. +/// 3. Child focus → detach or clear its input, preserving the parent turn. +/// 4. Main generating → interrupt the active turn. /// 4. Input non-empty → clear input (muscle memory preserved). /// 5. Input empty + session focused → detach. /// 6. Input empty + transcript focused → close transcript. @@ -393,6 +394,14 @@ pub const fn resolve_esc(input_empty: bool, focus: FocusTarget, switcher_open: b if matches!(focus, FocusTarget::Worker { .. }) && input_empty { return EscAction::CloseWorker; } + // Leaving a child must not cancel an unrelated parent mailbox turn. + if matches!(focus, FocusTarget::Session { .. }) { + return if input_empty { + EscAction::RequestDetach + } else { + EscAction::ClearInput + }; + } if generating { return EscAction::CancelGenerating; } @@ -764,7 +773,7 @@ mod tests { fn resolve_esc_generating_interrupts_before_input_or_focus_cleanup() { assert_eq!( resolve_esc(false, FocusTarget::Session { seq: 1 }, false, true), - EscAction::CancelGenerating + EscAction::ClearInput ); assert_eq!( resolve_esc(true, FocusTarget::Diff, false, true), diff --git a/src/chat/state/reduce_input.rs b/src/chat/state/reduce_input.rs index f0fdc5d55..f9feae7aa 100644 --- a/src/chat/state/reduce_input.rs +++ b/src/chat/state/reduce_input.rs @@ -67,7 +67,11 @@ impl ChatState { }; } - if key.code == KeyCode::Esc && key.modifiers == KeyModifiers::NONE && self.control.generating { + if key.code == KeyCode::Esc + && key.modifiers == KeyModifiers::NONE + && self.control.generating + && !matches!(self.ui.focus, crate::chat::sessions::FocusTarget::Session { .. }) + { return self.reduce_cancel_requested(); } diff --git a/src/config/manage/autonomy.rs b/src/config/manage/autonomy.rs new file mode 100644 index 000000000..5dc3a5f5e --- /dev/null +++ b/src/config/manage/autonomy.rs @@ -0,0 +1,15 @@ +//! Typed autonomy selection for the local management CLI. +use super::{ConfigActor, ManageError, ManagedPlan, ManagementService}; + +impl ManagementService { + /// Plan a level change under the ordinary revision and high-risk guards. + pub async fn plan_autonomy( + &self, + level: crate::security::AutonomyLevel, + actor: ConfigActor, + ) -> Result { + let mut candidate = (*self.config()).clone(); + candidate.autonomy.level = level; + self.plan_candidate(candidate, self.revision(), actor).await + } +} diff --git a/src/config/manage/mod.rs b/src/config/manage/mod.rs index 54eaafdd9..861f90719 100644 --- a/src/config/manage/mod.rs +++ b/src/config/manage/mod.rs @@ -17,6 +17,7 @@ //! - [`render`]: the one text rendering of a plan; //! - [`migrate`]: the legacy-configuration report and migration (PMM-H). +mod autonomy; pub(crate) mod boundary; pub mod credentials; pub mod history; diff --git a/src/gateway/api/agent_erasure.rs b/src/gateway/api/agent_erasure.rs index c025ed107..80d734a68 100644 --- a/src/gateway/api/agent_erasure.rs +++ b/src/gateway/api/agent_erasure.rs @@ -88,6 +88,65 @@ pub(super) async fn delete_history( headers: HeaderMap, uri: Uri, body: Bytes, +) -> Response { + history(state, (session, agent), principal, headers, uri, body, false).await +} + +/// Read the exact incarnation needed by the paired terminal erase operation. +pub(super) async fn get_terminal_history( + State(state): State, + Path((session, agent)): Path<(String, String)>, + headers: HeaderMap, +) -> Response { + if !super::owner_authenticated(&state, &headers) { + return coded_error( + StatusCode::UNAUTHORIZED, + "auth_failed", + "a paired owner bearer is required", + ); + } + let config = state.config.load_full(); + match crate::runtime::blocking::spawn_blocking(move || { + let owner = + crate::chat::chat_runtime_envelope(&config.workspace_dir.to_string_lossy(), &session).resolved_owner_id(); + let runtime = crate::messaging::runtime::MessagingRuntime::for_config(&config)?; + let target = runtime.address(&owner, &session, &agent); + runtime.resolve_scope(&target).map_err(anyhow::Error::from) + }) + .await + { + Ok(Ok(scope)) => { + Json(serde_json::json!({"incarnation":scope.incarnation,"generation":scope.generation})).into_response() + } + _ => coded_error( + StatusCode::NOT_FOUND, + "session_unknown", + "no terminal session of this installation has this key", + ), + } +} + +/// Paired local operators may erase their terminal sessions without rebinding +/// them to the Console owner or trusting an owner supplied in request JSON. +pub(super) async fn delete_terminal_history( + State(state): State, + Path(path): Path<(String, String)>, + Extension(principal): Extension, + headers: HeaderMap, + uri: Uri, + body: Bytes, +) -> Response { + history(state, path, principal, headers, uri, body, true).await +} + +async fn history( + state: AppState, + (session, agent): (String, String), + mut principal: ApiPrincipal, + headers: HeaderMap, + uri: Uri, + body: Bytes, + terminal: bool, ) -> Response { if !super::owner_authenticated(&state, &headers) { return coded_error( @@ -107,19 +166,43 @@ pub(super) async fn delete_history( Ok(name) if name.is_main() || !name.is_reserved() => name, _ => return coded_error(StatusCode::BAD_REQUEST, "agent_invalid", "invalid agent name"), }; - // Ownership is checked before idempotency or incarnation disclosure. - match state.mem.conversation_session_owner(&session).await { - Ok(Some(row)) - if row.channel == crate::memory::CALLER_KEYED_SESSION_CHANNEL - && row.owner_id.as_deref() == Some(principal.owner_id.as_str()) => {} - Ok(_) => { + // The terminal owner is derived exclusively from this installation's workspace. + if terminal { + let config = state.config.load_full(); + let owner = + crate::chat::chat_runtime_envelope(&config.workspace_dir.to_string_lossy(), &session).resolved_owner_id(); + let target_session = session.clone(); + let target_agent = agent.clone(); + let selected_owner = owner.clone(); + let known = crate::runtime::blocking::spawn_blocking(move || { + let runtime = crate::messaging::runtime::MessagingRuntime::for_config(&config)?; + let target = runtime.address(&selected_owner, &target_session, &target_agent); + runtime.resolve_scope(&target).map_err(anyhow::Error::from) + }) + .await; + if !matches!(known, Ok(Ok(_))) { return coded_error( StatusCode::NOT_FOUND, "session_unknown", - "no caller-keyed session of this owner has this id", + "no terminal session of this installation has this key", ); } - Err(error) => return failure(&error, false), + principal.owner_id = owner; + } else { + // Ownership is checked before idempotency or incarnation disclosure. + match state.mem.conversation_session_owner(&session).await { + Ok(Some(row)) + if row.channel == crate::memory::CALLER_KEYED_SESSION_CHANNEL + && row.owner_id.as_deref() == Some(principal.owner_id.as_str()) => {} + Ok(_) => { + return coded_error( + StatusCode::NOT_FOUND, + "session_unknown", + "no caller-keyed session of this owner has this id", + ); + } + Err(error) => return failure(&error, false), + } } let key = match idempotency_key(&headers) { Ok(key) => key, diff --git a/src/gateway/api/mod.rs b/src/gateway/api/mod.rs index bc1daed87..bde505649 100644 --- a/src/gateway/api/mod.rs +++ b/src/gateway/api/mod.rs @@ -309,6 +309,12 @@ pub fn router(state: AppState) -> Router { delete(agent_erasure::delete_history) .fallback(|| async { capabilities::method_not_allowed_allowing("DELETE") }), ) + .route( + "/terminal/sessions/{id}/agents/{name}/history", + get(agent_erasure::get_terminal_history) + .delete(agent_erasure::delete_terminal_history) + .fallback(|| async { capabilities::method_not_allowed_allowing("GET, DELETE") }), + ) .route( "/sessions/{id}/runs/{run_id}/cancel", post(sessions::post_run_cancel).fallback(capabilities::method_not_allowed), diff --git a/src/main/section_1.rs b/src/main/section_1.rs index 86680d718..c6358cb61 100644 --- a/src/main/section_1.rs +++ b/src/main/section_1.rs @@ -954,6 +954,13 @@ enum TasksCommands { #[derive(Subcommand, Debug)] enum ConfigCommands { + /// Set the runtime autonomy level through a configuration transaction; restart running chats. + Autonomy { + #[arg(value_parser = ["readonly", "supervised", "full"])] + level: String, + #[command(flatten)] + apply: ApplyArgs, + }, /// Set the Brave Search credential from stdin without an argument or echo BraveKey { #[arg(long, required = true)] diff --git a/src/memory/sqlite/mailbox/outbox.rs b/src/memory/sqlite/mailbox/outbox.rs index 570909de6..e7abf48fe 100644 --- a/src/memory/sqlite/mailbox/outbox.rs +++ b/src/memory/sqlite/mailbox/outbox.rs @@ -23,6 +23,21 @@ impl MailboxOutbound { } impl SqliteMailbox { + /// Reuse only an owner-bound, non-erased route previously pinned online. + pub(crate) fn known_remote_target( + &self, + workspace: &str, + source: &SessionAddr, + target: &SessionAddr, + ) -> MailboxResult> { + let scope = self.session_scope(workspace, source, false)?; + let writer = self.memory.pool.write(); + check_scope(&writer, &scope, source, None, true)?; + let raw: Option = writer.query_row( + "SELECT s.to_addr FROM prx_mailbox_seq s JOIN prx_mailbox_outbox o ON o.stream_id=s.stream_id WHERE s.sender_ma_scope_id=?1 AND s.from_addr=?2 AND json_extract(s.to_addr,'$.instance')=?3 AND json_extract(s.to_addr,'$.session')=?4 AND json_extract(s.to_addr,'$.agent')=?5 AND o.state IN(0,1,2) AND json_extract(o.envelope_meta,'$.body_erased_at') IS NULL ORDER BY o.id DESC LIMIT 1", + params![scope.scope_id.to_string(), encode(source)?,target.instance,target.session,target.agent], |r| r.get(0)).optional().map_err(storage_error)?; + raw.map(|raw| decode(&raw)).transpose() + } pub fn pending_outbox(&self, scope: &MailboxScope, address: &SessionAddr) -> MailboxResult> { let writer = self.memory.pool.write(); let tx = Transaction::new_unchecked(&writer, TransactionBehavior::Immediate).map_err(storage_error)?; diff --git a/src/memory/sqlite/mailbox/sender.rs b/src/memory/sqlite/mailbox/sender.rs index d8249bf0f..6a9228d9e 100644 --- a/src/memory/sqlite/mailbox/sender.rs +++ b/src/memory/sqlite/mailbox/sender.rs @@ -96,7 +96,13 @@ impl SqliteMailboxSender { crate::messaging::mailbox::UnauthorizedReason::SenderWorkspaceMismatch, )); } - if resolved.authority.destination != target { + let destination = &resolved.authority.destination; + // Only a verified remote pin response may supply the receiving owner. + let remote_owner = target.instance != self.source.instance + && destination.instance == target.instance + && destination.session == target.session + && destination.agent == target.agent; + if destination != &target && !remote_owner { return Err(crate::messaging::mailbox::unauthorized( crate::messaging::mailbox::UnauthorizedReason::DestinationMismatch, )); @@ -108,7 +114,7 @@ impl SqliteMailboxSender { seq: 0, ts: self.store.clock.now(), from: self.source.clone(), - to: target, + to: resolved.authority.destination.clone(), to_pin: resolved.pin, in_reply_to: None, hop_count: 0, diff --git a/src/messaging/a2a/cli.rs b/src/messaging/a2a/cli.rs index ed5be31cf..98bc5edf3 100644 --- a/src/messaging/a2a/cli.rs +++ b/src/messaging/a2a/cli.rs @@ -29,6 +29,7 @@ pub enum PeerCommand { fingerprint: String, #[arg(long)] address: String, + /// Local owner allowed to send to this peer and receive from it; destination owner is learned from its pins route. #[arg(long)] owner: String, #[arg(long = "session", default_value = "*")] diff --git a/src/messaging/a2a/dispatch.rs b/src/messaging/a2a/dispatch.rs index 624020bbd..5139f4d80 100644 --- a/src/messaging/a2a/dispatch.rs +++ b/src/messaging/a2a/dispatch.rs @@ -92,6 +92,12 @@ pub(super) async fn run( pub(super) fn permanent(error: &anyhow::Error) -> bool { matches!( error.downcast_ref::(), - Some(MailboxError::Unauthorized | MailboxError::StaleIncarnation) + Some( + MailboxError::Unauthorized + | MailboxError::StaleIncarnation + | MailboxError::PeerNotAllowed + | MailboxError::PeerUnknown + | MailboxError::OwnerMismatch + ) ) } diff --git a/src/messaging/a2a/listener.rs b/src/messaging/a2a/listener.rs index 6108ab318..80d863a14 100644 --- a/src/messaging/a2a/listener.rs +++ b/src/messaging/a2a/listener.rs @@ -126,24 +126,43 @@ fn process( #[derive(serde::Deserialize)] #[serde(deny_unknown_fields)] struct PinRequest { - to: SessionAddr, + to: PinTarget, + } + #[derive(serde::Deserialize)] + #[serde(deny_unknown_fields)] + struct PinTarget { + instance: String, + session: String, + #[serde(default)] + owner: Option, + #[serde(default = "main_agent")] + agent: String, + } + fn main_agent() -> String { + "main".into() } let Ok(input) = serde_json::from_slice::(&bytes) else { return refused(StatusCode::BAD_REQUEST, "field_invalid"); }; + let target = SessionAddr::new( + input.to.instance, + input.to.owner.unwrap_or_else(|| peer.owner.clone()), + input.to.session, + Some(&input.to.agent), + ); let source = SessionAddr::new(peer.spiffe_id.clone(), &peer.owner, "peer", None); - let Ok(authority) = target_authority(&runtime, &peer, &input.to, source) else { + let Ok(authority) = target_authority(&runtime, &peer, &target, source) else { return refused(StatusCode::FORBIDDEN, "peer_not_allowed"); }; let result = runtime - .resolve_scope(&input.to) - .and_then(|scope| runtime.store.recipient_pin(&authority, &scope, &input.to.session)); + .resolve_scope(&target) + .and_then(|scope| runtime.store.recipient_pin(&authority, &scope, &target.session)); return result.map_or_else( |_| refused(StatusCode::FORBIDDEN, "peer_not_allowed"), |pin| { response( StatusCode::OK, - serde_json::json!({"pin":pin,"expires_at":chrono::Utc::now().timestamp()+300}), + serde_json::json!({"to":target,"pin":pin,"expires_at":chrono::Utc::now().timestamp()+300}), ) }, ); diff --git a/src/messaging/a2a/outbound.rs b/src/messaging/a2a/outbound.rs index 54ecf4d6d..c30e009bf 100644 --- a/src/messaging/a2a/outbound.rs +++ b/src/messaging/a2a/outbound.rs @@ -1,11 +1,7 @@ //! Durable remote publication and receiver-pin refresh before every attempt. +mod recipient; use super::tls::Trust; -use crate::messaging::{ - DeliveryState, RecipientPin, SessionAddr, - mailbox::{MailboxAuthority, MailboxError, MailboxResult}, - runtime::MessagingRuntime, - send::MailboxDestination, -}; +use crate::messaging::{DeliveryState, RecipientPin, SessionAddr, mailbox::MailboxError, runtime::MessagingRuntime}; use std::{sync::Arc, time::Duration}; pub(crate) struct RemoteTransport { @@ -32,26 +28,6 @@ impl RemoteTransport { .into() }) } - pub(crate) fn destination( - &self, - runtime: &MessagingRuntime, - source: &SessionAddr, - target: &SessionAddr, - ) -> MailboxResult { - // The sender may retain its turn's config while CLI peer grants change. - // LocalResolver runs this admission on the blocking pool. - self.trust.refresh().map_err(|_| MailboxError::RemoteNotEnabled)?; - self.peer(target).map_err(|_| MailboxError::RemoteNotEnabled)?; - Ok(MailboxDestination { - authority: MailboxAuthority::outbound(runtime.workspace.clone(), source.clone(), target.clone())?, - pin: RecipientPin { - incarnation: uuid::Uuid::nil(), - generation: 1, - token: "pending-peer-pin".into(), - }, - pin_expires_at: chrono::Utc::now().timestamp() + 86400, - }) - } async fn attempt( &self, runtime: &MessagingRuntime, @@ -61,6 +37,7 @@ impl RemoteTransport { ) -> anyhow::Result<(u16, Option)> { self.trust.refresh_async().await?; let peer = self.peer(&message.to)?; + anyhow::ensure!(peer.owner == source.owner, MailboxError::PeerNotAllowed); let clients = self.clients.clone(); let selected = peer.clone(); let (client, cancellation) = crate::runtime::blocking::spawn_blocking(move || clients.get(&selected)).await??; @@ -77,10 +54,12 @@ impl RemoteTransport { } #[derive(serde::Deserialize)] struct Pin { + to: SessionAddr, pin: RecipientPin, expires_at: i64, } let pin: Pin = serde_json::from_slice(&bounded_response(response).await?)?; + anyhow::ensure!(pin.to == message.to, MailboxError::OwnerMismatch); let store = runtime.store.clone(); let scope = scope.clone(); let source = source.clone(); diff --git a/src/messaging/a2a/outbound/recipient.rs b/src/messaging/a2a/outbound/recipient.rs new file mode 100644 index 000000000..237a48f92 --- /dev/null +++ b/src/messaging/a2a/outbound/recipient.rs @@ -0,0 +1,148 @@ +//! Resolve receiving owners through the authenticated pin route, never tool JSON. +use super::{RemoteTransport, bounded_response}; +use crate::messaging::{ + RecipientPin, SessionAddr, + mailbox::{MailboxAuthority, MailboxError, MailboxResult}, + runtime::MessagingRuntime, + send::MailboxDestination, +}; + +#[derive(serde::Deserialize)] +struct PinResponse { + to: SessionAddr, + pin: RecipientPin, + expires_at: i64, +} +impl RemoteTransport { + pub(crate) async fn destination( + &self, + runtime: &MessagingRuntime, + source: &SessionAddr, + target: &SessionAddr, + ) -> MailboxResult { + self.resolve_destination(runtime, source, target) + .await + .inspect_err(|error| { + let reason = match error { + MailboxError::PeerUnknown => "peer_unknown", + MailboxError::PeerNotAllowed => "peer_not_allowed", + MailboxError::OwnerMismatch => "owner_mismatch", + MailboxError::RemoteNotEnabled => "remote_not_enabled", + MailboxError::PeerUnavailable => "peer_unavailable", + _ => "peer_resolution_failed", + }; + tracing::warn!(reason, "A2A recipient resolution refused"); + }) + } + async fn resolve_destination( + &self, + runtime: &MessagingRuntime, + source: &SessionAddr, + target: &SessionAddr, + ) -> MailboxResult { + self.trust + .refresh_async() + .await + .map_err(|_| MailboxError::RemoteNotEnabled)?; + if !self + .trust + .effective() + .map_err(|_| MailboxError::RemoteNotEnabled)? + .a2a + .messaging_enabled + { + return Err(MailboxError::RemoteNotEnabled); + } + let peer = self.peer(target).map_err(|_| MailboxError::PeerUnknown)?; + if peer.owner != source.owner { + return Err(MailboxError::PeerNotAllowed); + } + // The public address defaults to the local owner. The remote owner is + // learned only from the receiver authenticated by our current peer pin. + if target.owner != source.owner { + return Err(MailboxError::OwnerMismatch); + } + let clients = self.clients.clone(); + let selected = peer.clone(); + let (client, cancellation) = crate::runtime::blocking::spawn_blocking(move || clients.get(&selected)) + .await + .map_err(|_| MailboxError::Storage)? + .map_err(|_| MailboxError::PeerNotAllowed)?; + let request = client + .post(format!("https://{}/a2a/v1/pins", peer.address)) + .json(&serde_json::json!({"to":{"instance":target.instance,"session":target.session,"agent":target.agent}})) + .send(); + let response = tokio::select! { + () = cancellation.cancelled() => return Err(MailboxError::PeerUnavailable), + response = request => response, + }; + let pin = match response { + Ok(response) => { + if response.status().as_u16() != 200 { + return Err(MailboxError::PeerNotAllowed); + } + serde_json::from_slice::( + &bounded_response(response) + .await + .map_err(|_| MailboxError::PeerUnavailable)?, + ) + .map_err(|_| MailboxError::InvalidPin)? + } + Err(error) if offline(&error) => { + let store = runtime.store.clone(); + let (source, target) = (source.clone(), target.clone()); + let workspace = runtime.workspace.clone(); + let to = crate::runtime::blocking::spawn_blocking(move || { + store.known_remote_target(&workspace, &source, &target) + }) + .await + .map_err(|_| MailboxError::Storage)?? + .ok_or(MailboxError::PeerUnavailable)?; + PinResponse { + to, + pin: RecipientPin { + incarnation: uuid::Uuid::nil(), + generation: 1, + token: "pending-peer-pin".into(), + }, + expires_at: chrono::Utc::now().timestamp() + 86400, + } + } + Err(_) => return Err(MailboxError::PeerNotAllowed), + }; + if pin.to.instance != target.instance || pin.to.session != target.session || pin.to.agent != target.agent { + return Err(MailboxError::InvalidPin); + } + crate::messaging::mailbox::validate_address(&pin.to)?; + self.trust + .refresh_async() + .await + .map_err(|_| MailboxError::RemoteNotEnabled)?; + let current = self.peer(target).map_err(|_| MailboxError::PeerUnknown)?; + if current != peer { + return Err(MailboxError::PeerNotAllowed); + } + Ok(MailboxDestination { + authority: MailboxAuthority::outbound(runtime.workspace.clone(), source.clone(), pin.to)?, + pin: pin.pin, + pin_expires_at: pin.expires_at, + }) + } +} +fn offline(error: &reqwest::Error) -> bool { + use std::error::Error as _; + let mut cause = error.source(); + while let Some(error) = cause { + if let Some(error) = error.downcast_ref::() { + return matches!( + error.kind(), + std::io::ErrorKind::ConnectionRefused + | std::io::ErrorKind::TimedOut + | std::io::ErrorKind::NetworkUnreachable + | std::io::ErrorKind::HostUnreachable + ); + } + cause = error.source(); + } + error.is_timeout() +} diff --git a/src/messaging/mailbox.rs b/src/messaging/mailbox.rs index de4f83774..39f2184c2 100644 --- a/src/messaging/mailbox.rs +++ b/src/messaging/mailbox.rs @@ -22,6 +22,14 @@ pub const MAX_BYTES: i64 = 64 * 1024 * 1024; /// Stable refusals, shared by store, IPC and dormant send adapters. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum MailboxError { + #[error("peer_unknown")] + PeerUnknown, + #[error("peer_not_allowed")] + PeerNotAllowed, + #[error("owner_mismatch")] + OwnerMismatch, + #[error("peer_unavailable")] + PeerUnavailable, #[error("remote_not_enabled")] RemoteNotEnabled, #[error("invalid_address")] diff --git a/src/messaging/runtime.rs b/src/messaging/runtime.rs index a392b8b83..c91502e38 100644 --- a/src/messaging/runtime.rs +++ b/src/messaging/runtime.rs @@ -287,9 +287,8 @@ impl MessagingRuntime { return Ok(address); } if address.owner != source.owner { - return Err(crate::messaging::mailbox::unauthorized( - crate::messaging::mailbox::UnauthorizedReason::LocalOwnerMismatch, - )); + crate::messaging::mailbox::unauthorized(crate::messaging::mailbox::UnauthorizedReason::LocalOwnerMismatch); + return Err(MailboxError::OwnerMismatch); } if matches!(address.session.as_str(), "main" | "parent") { address.session = self @@ -318,11 +317,13 @@ impl MailboxResolver for LocalResolver { let runtime = Arc::clone(&self.runtime); let source = self.source.clone(); let target = target.clone(); + if target.instance != runtime.instance { + let config = runtime.config.read().clone(); + return super::a2a::RemoteTransport::new(&config) + .destination(&runtime, &source, &target) + .await; + } crate::runtime::blocking::spawn_blocking(move || { - if target.instance != runtime.instance { - return super::a2a::RemoteTransport::new(&runtime.config.read()) - .destination(&runtime, &source, &target); - } let authority = MailboxAuthority::local(runtime.workspace.clone(), source.clone(), target.clone())?; let scope = runtime.resolve_scope(&target)?; let pin = runtime.store.recipient_pin(&authority, &scope, &target.session)?; diff --git a/src/runtime/manage_cli.rs b/src/runtime/manage_cli.rs index 1173fed39..da0c4877d 100644 --- a/src/runtime/manage_cli.rs +++ b/src/runtime/manage_cli.rs @@ -1,2588 +1,3 @@ -//! `prx providers`, `prx models`, `prx routes`, the management part of -//! `prx config` (PMM-E) and `prx decision-engine config` (P2-R8). -//! -//! Every command calls the library's management service -//! (`config::manage::ManagementService`) in-process: the same candidate -//! building, the same validation and the same plan renderer the Gateway uses, -//! so an equal change prints the same plan and the same refusal on every -//! surface. A mutating command prints its plan and writes nothing unless -//! `--yes` is given; a high-risk plan also needs `--confirm-high-risk -//! `, naming the revision the plan reported (D-049 B). -//! -//! The CLI writes the files through the configuration transaction (revision -//! guard, history record, validation of the load); a running PRX picks the -//! change up through its configuration watcher. -//! -//! A credential never comes from an argument: `credential set` reads it from -//! a hidden prompt, standard input (`--from-stdin`) or an environment -//! variable (`--from-env VAR`), and nothing prints it. - -use anyhow::{Context, Result, bail}; -use openprx::config::manage::service::{self as manage, ProviderEntry}; -use openprx::config::manage::{ - ConfigActor, ConfigTransactionError, ManageError, ManagedChange, ManagedPlan, ManagementService, RecordStatus, - RollbackRequest, RootCredential, SelectionOperation, render_plan, -}; -use openprx::config::{self, Config}; -use openprx::providers; -use std::io::{Read, Write}; - -use crate::{ - AgentsCommands, ApplyArgs, ConfigCommands, CredentialCommands, DefaultCommands, HistoryCommands, ModelCommands, - ModelDeclarationArgs, OperationArg, ProvidersCommands, RoutesCommands, -}; - -/// A management command, as the dispatcher hands it over. -pub(crate) enum ManageCommand { - Providers(Option), - Routes(RoutesCommands), - Models(ModelCommands), - Config(ConfigCommands), - DecisionEngine(openprx::decision_engine_cli::DecisionEngineConfigCommands), -} - -/// Where a command writes and reads: the process's streams in production, -/// buffers in tests. -pub(crate) struct Io<'a> { - pub(crate) out: &'a mut dyn Write, - pub(crate) stdin: &'a mut dyn Read, - /// Reads an environment variable (`--from-env`). - pub(crate) env: &'a dyn Fn(&str) -> Option, - /// Asks for a secret without echoing it. - pub(crate) prompt: &'a dyn Fn(&str) -> Result, -} - -/// Run `command` against the process's own streams and environment. -pub(crate) async fn run_process(command: ManageCommand, config: Config) -> Result<()> { - let mut stdout = std::io::stdout(); - let mut stdin = std::io::stdin(); - let env = |name: &str| std::env::var(name).ok(); - let prompt = |label: &str| crate::read_auth_input(label); - let mut io = Io { - out: &mut stdout, - stdin: &mut stdin, - env: &env, - prompt: &prompt, - }; - run(command, config, &mut io).await -} - -/// Run `command` with `io`. -pub(crate) async fn run(command: ManageCommand, config: Config, io: &mut Io<'_>) -> Result<()> { - match command { - ManageCommand::Providers(command) => { - run_providers(command.unwrap_or(ProvidersCommands::List), config, io).await - } - ManageCommand::Routes(command) => run_routes(command, config, io).await, - ManageCommand::Models(command) => run_models(command, config, io).await, - ManageCommand::Config(command) => run_config(command, config, io).await, - ManageCommand::DecisionEngine(command) => run_decision_engine(command, config, io).await, - } -} - -/// The CLI does not run the configuration's runtime: what it applies is -/// activated by a running PRX's watcher, so it is recorded deferred. -fn service(config: Config) -> ManagementService { - ManagementService::deferred(config::new_shared(config)) -} - -const fn operation(arg: OperationArg) -> SelectionOperation { - match arg { - OperationArg::Chat => SelectionOperation::Chat, - OperationArg::Embedding => SelectionOperation::Embedding, - } -} - -/// Plan `change`, print the plan, and apply it when `apply.yes`. -async fn change(service: &ManagementService, change: ManagedChange, apply: &ApplyArgs, io: &mut Io<'_>) -> Result<()> { - let plan = service - .plan(&change, ConfigActor::Cli) - .await - .map_err(|error| anyhow::anyhow!("{error}"))?; - finish(service, plan, apply, io).await -} - -/// Print `plan`, then apply it when `apply.yes`. -async fn finish(service: &ManagementService, plan: ManagedPlan, apply: &ApplyArgs, io: &mut Io<'_>) -> Result<()> { - write!(io.out, "{}", plan.text())?; - if plan.summary().is_empty() { - writeln!(io.out, "Nothing to change.")?; - return Ok(()); - } - let revision = plan.revision().unwrap_or("none").to_string(); - let high_risk = !plan.summary().risk_reasons.is_empty(); - if !apply.yes { - if high_risk { - writeln!( - io.out, - "Dry run: nothing was written. This change is high risk: apply it with --yes --confirm-high-risk \ - {revision}" - )?; - } else { - writeln!(io.out, "Dry run: nothing was written. Apply it with --yes")?; - } - return Ok(()); - } - match service - .apply(plan, ConfigActor::Cli, apply.confirm_high_risk.as_deref()) - .await - { - Ok(outcome) => print_applied(&outcome, io), - Err(error) => Err(refusal(error)), - } -} - -/// What an applied CLI change prints: written and validated, activation -/// deferred to the daemon (D-085 F-4). -fn print_applied(outcome: &openprx::config::manage::ConfigTransactionOutcome, io: &mut Io<'_>) -> Result<()> { - match &outcome.record_id { - Some(record) => writeln!( - io.out, - "Written and validated (history record {record}); activation deferred to the daemon: a running PRX \ - activates it through its configuration watcher, otherwise at its next start. This command cannot \ - confirm the activation; see `prx config status`. `prx config rollback {record}` undoes it." - )?, - None => writeln!( - io.out, - "The files already held this configuration; nothing was written." - )?, - } - if !outcome.report.restart_required.is_empty() { - writeln!( - io.out, - "Takes effect after a restart: {}", - outcome.report.restart_required.join(", ") - )?; - } - Ok(()) -} - -/// A refused CLI change as the error the command exits with; a needed -/// confirmation names the revision to confirm. -fn refusal(error: ManageError) -> anyhow::Error { - match error { - ManageError::Transaction(error @ ConfigTransactionError::ConfirmationRequired { .. }) => { - let revision = match &error { - ConfigTransactionError::ConfirmationRequired { revision, .. } => revision.clone().unwrap_or_default(), - _ => String::new(), - }; - anyhow::anyhow!( - "{}. Review the plan above and confirm with --yes --confirm-high-risk {revision}", - error.to_string().trim_end_matches('.') - ) - } - error => anyhow::anyhow!("{error}"), - } -} - -// ── prx decision-engine config (P2-R8) ────────────────────────────── - -/// `prx decision-engine config set `: one allowlisted key, -/// planned and applied like every management change. A refused key is one -/// typed error (exit ≠ 0). -async fn run_decision_engine( - command: openprx::decision_engine_cli::DecisionEngineConfigCommands, - config: Config, - io: &mut Io<'_>, -) -> Result<()> { - use openprx::config::manage::mutation::decision_engine::{CausalMutation, engine_setting}; - use openprx::decision_engine_cli::DecisionEngineConfigCommands; - let DecisionEngineConfigCommands::Set { key, value, apply } = command; - let setting = engine_setting(&key, &value)?; - let service = service(config); - let plan = service - .plan_causal(&[CausalMutation::SetEngine(setting)], ConfigActor::Cli) - .await - .map_err(|error| anyhow::anyhow!("{error}"))?; - let apply = ApplyArgs { - yes: apply.yes, - confirm_high_risk: apply.confirm_high_risk, - }; - finish(&service, plan, &apply, io).await -} - -// ── prx providers ───────────────────────────────────────────────────── - -async fn run_providers(command: ProvidersCommands, config: Config, io: &mut Io<'_>) -> Result<()> { - match command { - ProvidersCommands::List => { - print_catalog(&config, io.out)?; - print_configured(&config, io.out) - } - ProvidersCommands::Show { provider } => print_provider(&config, &provider, io.out), - // `--fallback` is required by clap: it is the only role today. - ProvidersCommands::Add { - provider, - fallback: _, - model, - apply, - } => { - let mutation = match model { - Some(model) => ManagedChange::AddProviderWithModel { provider, model }, - None => ManagedChange::AddProvider { provider }, - }; - change(&service(config), mutation, &apply, io).await - } - ProvidersCommands::Update { - provider, - api_url, - clear_api_url, - apply, - } => { - let api_url = if clear_api_url { None } else { api_url }; - change( - &service(config), - ManagedChange::SetProviderEndpoint { provider, api_url }, - &apply, - io, - ) - .await - } - ProvidersCommands::Remove { provider, apply } => { - change(&service(config), ManagedChange::RemoveProvider { provider }, &apply, io).await - } - ProvidersCommands::Test { provider, model, live } => { - let mode = if live { - providers::connection_test::ProbeMode::Live - } else { - providers::connection_test::ProbeMode::Local - }; - let report = - providers::connection_test::test_connection(&config, provider.as_deref(), model.as_deref(), mode).await; - writeln!(io.out, "{report}")?; - let live_failed = report.live.as_ref().is_some_and(|live| live.error.is_some()); - if !report.local.resolved || live_failed { - bail!("the connection test failed"); - } - Ok(()) - } - ProvidersCommands::Credential { credential_command } => run_credential(credential_command, config, io).await, - ProvidersCommands::Migrate { apply, write } => run_migrate(config, apply, &write, io).await, - } -} - -// ── prx providers migrate ───────────────────────────────────────────── - -/// `prx providers migrate`: the report (always), then with `--apply` the -/// plan, and with `--yes` the write (SP-PMM §2.7, PMM-H). -async fn run_migrate(config: Config, apply: bool, write: &ApplyArgs, io: &mut Io<'_>) -> Result<()> { - let service = service(config); - let report = service.migration_report().map_err(|error| anyhow::anyhow!("{error}"))?; - write!(io.out, "{}", report.text())?; - if !apply { - if write.yes { - bail!("--yes writes the migration only together with --apply; nothing was written"); - } - if report.nothing_to_apply() { - writeln!(io.out, "Nothing to migrate.")?; - } else { - writeln!(io.out, "Dry run: nothing was written. Plan the migration with --apply")?; - } - return Ok(()); - } - let Some((report, plan)) = service - .plan_migration() - .await - .map_err(|error| anyhow::anyhow!("{error}"))? - else { - writeln!(io.out, "Nothing to migrate.")?; - return Ok(()); - }; - write!(io.out, "{}", plan.text())?; - let references = report - .inline_keys - .iter() - .map(openprx::config::manage::migrate::InlineKey::reference_id) - .collect::>(); - if !references.is_empty() { - writeln!( - io.out, - "Credential references stored first (encrypted at rest when secrets.encrypt = true): {}", - references.join(", ") - )?; - } - if !write.yes { - let revision = plan.revision().unwrap_or("none"); - if plan.summary().risk_reasons.is_empty() { - writeln!(io.out, "Dry run: nothing was written. Apply it with --apply --yes")?; - } else { - writeln!( - io.out, - "Dry run: nothing was written. This change is high risk: apply it with --apply --yes \ - --confirm-high-risk {revision}" - )?; - } - return Ok(()); - } - let outcome = service - .apply_migration(&report, plan, ConfigActor::Cli, write.confirm_high_risk.as_deref()) - .await; - match outcome { - Ok(outcome) => { - print_applied(&outcome, io)?; - if outcome.record_id.is_some() && !references.is_empty() { - writeln!( - io.out, - "Undoing it brings the inline keys back: `prx config rollback --yes \ - --restore-credentials`." - )?; - } - Ok(()) - } - Err(error) => Err(refusal(error)), - } -} - -/// The catalog of providers this build supports (the listing `prx -/// providers` always printed). -fn print_catalog(config: &Config, out: &mut dyn Write) -> Result<()> { - let catalog = providers::list_providers(); - let current = providers::selection::default_provider(config) - .trim() - .to_ascii_lowercase(); - writeln!(out, "Supported providers ({} total):\n", catalog.len())?; - writeln!(out, " ID (use in config) DESCRIPTION")?; - writeln!(out, " ─────────────────── ───────────")?; - for entry in &catalog { - let is_active = entry.name.eq_ignore_ascii_case(¤t) - || entry.aliases.iter().any(|alias| alias.eq_ignore_ascii_case(¤t)); - let marker = if is_active { " (active)" } else { "" }; - let local_tag = if entry.local { " [local]" } else { "" }; - let aliases = if entry.aliases.is_empty() { - String::new() - } else { - format!(" (aliases: {})", entry.aliases.join(", ")) - }; - writeln!( - out, - " {:<19} {}{}{}{}", - entry.name, entry.display_name, local_tag, marker, aliases - )?; - } - writeln!(out, "\n custom: Any OpenAI-compatible endpoint")?; - writeln!(out, " anthropic-custom: Any Anthropic-compatible endpoint")?; - Ok(()) -} - -fn roles(entry: &ProviderEntry) -> String { - let mut roles = Vec::new(); - if entry.default { - roles.push("default"); - } - if entry.fallback { - roles.push("fallback"); - } - if roles.is_empty() { - "used".to_string() - } else { - roles.join(", ") - } -} - -fn print_configured(config: &Config, out: &mut dyn Write) -> Result<()> { - writeln!(out, "\nConfigured providers:")?; - for entry in manage::configured_providers(config) { - let used_by = if entry.used_by.is_empty() { - "nothing".to_string() - } else { - entry.used_by.join("; ") - }; - writeln!(out, " {} [{}] used by: {used_by}", entry.provider, roles(&entry))?; - } - Ok(()) -} - -fn print_provider(config: &Config, provider: &str, out: &mut dyn Write) -> Result<()> { - let entry = manage::provider_entry(config, provider); - let credentials = manage::provider_credentials(config, provider).map_err(|error| anyhow::anyhow!("{error}"))?; - writeln!(out, "Provider: {}", entry.provider)?; - writeln!(out, "Identity: {}", entry.identity)?; - writeln!(out, "Roles: {}", roles(&entry))?; - if let Some(endpoint) = &entry.endpoint { - writeln!(out, "Endpoint (api_url): {endpoint}")?; - } - writeln!(out, "Model declarations: {}", entry.declarations)?; - if entry.used_by.is_empty() { - writeln!(out, "Used by: nothing")?; - } else { - writeln!(out, "Used by:")?; - for name in &entry.used_by { - writeln!(out, " - {name}")?; - } - } - print_provider_credentials(&config, &credentials, out) -} - -fn print_provider_credentials( - config: &Config, - credentials: &manage::ProviderCredentials, - out: &mut dyn Write, -) -> Result<()> { - writeln!(out, "Credentials (never shown):")?; - let mut any = false; - if credentials.root_connection { - any = true; - writeln!( - out, - " - root connection (api_key / api_url / reliability.api_keys): set" - )?; - } - for slot in &credentials.inline_slots { - any = true; - writeln!(out, " - inline key at {slot}: set")?; - } - for profile in &credentials.store_profiles { - any = true; - writeln!(out, " - auth profile {profile}")?; - } - for reference in &credentials.references { - any = true; - let uses = manage::reference_use(config, &reference.id).map_err(|error| anyhow::anyhow!("{error}"))?; - writeln!( - out, - " - credential reference {} (updated {}): {uses}", - reference.id, - reference.updated_at.to_rfc3339(), - )?; - } - if !any { - writeln!(out, " none")?; - } - writeln!(out, "In use: {}", credentials.guidance)?; - Ok(()) -} - -// ── prx providers credential ────────────────────────────────────────── - -/// The reference id a `remove` argument names: `cred-` or ``. -fn reference_id(reference: &str) -> Result { - let reference = reference.trim(); - if reference.starts_with(openprx::config::manage::credentials::REFERENCE_PREFIX) { - Ok(reference.to_string()) - } else { - openprx::config::manage::credentials::CredentialReferences::id_for(reference) - .map_err(|error| anyhow::anyhow!("{error}")) - } -} - -/// Read a secret from standard input or from an environment variable, when -/// one of them is named (`None` otherwise). The trailing newline of piped -/// input is dropped; an empty secret is refused. Shared by `credential set` -/// and the `--from-stdin`/`--from-env` alternatives of the deprecated -/// argument flags (`init --api-key`, `go -k`, `auth paste-token --token`). -pub(crate) fn secret_from( - from_stdin: bool, - from_env: Option<&str>, - stdin: &mut dyn Read, - env: &dyn Fn(&str) -> Option, -) -> Result> { - let secret = if let Some(variable) = from_env { - env(variable).with_context(|| format!("environment variable {variable} is not set"))? - } else if from_stdin { - let mut text = String::new(); - stdin - .read_to_string(&mut text) - .context("failed to read the secret from standard input")?; - text - } else { - return Ok(None); - }; - let secret = secret.trim_end_matches(['\r', '\n']).to_string(); - if secret.trim().is_empty() { - bail!("the secret is empty; nothing was stored"); - } - Ok(Some(secret)) -} - -/// Read a credential from exactly one source; never from an argument. -fn read_secret(from_stdin: bool, from_env: Option<&str>, io: &mut Io<'_>) -> Result { - if let Some(secret) = secret_from(from_stdin, from_env, io.stdin, io.env)? { - return Ok(secret); - } - let secret = (io.prompt)("Credential (input hidden)")?; - if secret.trim().is_empty() { - bail!("the credential is empty; nothing was stored"); - } - Ok(secret) -} - -async fn run_credential(command: CredentialCommands, config: Config, io: &mut Io<'_>) -> Result<()> { - match command { - CredentialCommands::Set { - provider, - name, - from_stdin, - from_env, - } => { - let id = providers::ProviderId::of(&provider); - let name = match name { - Some(name) => name, - None => id.catalog_name().map(str::to_string).context( - "name the credential with --name (a provider without a catalog name has no default name)", - )?, - }; - let secret = read_secret(from_stdin, from_env.as_deref(), io)?; - let guidance = manage::provider_credentials(&config, &provider) - .map_err(|error| anyhow::anyhow!("{error}"))? - .guidance; - let status = service(config) - .set_credential(provider, name, secret, ConfigActor::Cli) - .await - .map_err(|error| anyhow::anyhow!("{error}"))?; - writeln!( - io.out, - "Stored credential reference {id} for provider {owner} (encrypted at rest when secrets.encrypt = \ - true). A model route, embedding route or agent of {owner} uses it once its configuration names \ - it: `credential_ref = \"{id}\"`; an enabled decision backend of {owner} can use it when configured \ - with that reference. In a running PRX a replaced value takes effect when the \ - configuration next changes (Gateway) or at the next restart (channels and daemon components); \ - restart to apply it now. The replacement is recorded in the configuration history and cannot be \ - rolled back (the previous value is not kept).\n{guidance}.", - id = status.id, - owner = status.owner, - )?; - Ok(()) - } - CredentialCommands::Remove { reference } => { - let id = reference_id(&reference)?; - let removed = service(config) - .remove_credential(&id) - .await - .map_err(|error| anyhow::anyhow!("{error}"))?; - if removed { - writeln!(io.out, "Removed credential reference {id}.")?; - } else { - writeln!(io.out, "Credential reference {id} does not exist; nothing was removed.")?; - } - Ok(()) - } - CredentialCommands::Status { - provider: Some(provider), - } => { - let entry = manage::provider_entry(&config, &provider); - let credentials = - manage::provider_credentials(&config, &provider).map_err(|error| anyhow::anyhow!("{error}"))?; - writeln!(io.out, "Provider: {}", entry.provider)?; - print_provider_credentials(&config, &credentials, io.out) - } - CredentialCommands::Status { provider: None } => { - let references = service(config.clone()) - .credentials() - .and_then(|references| references.list().map_err(ManageError::from)) - .map_err(|error| anyhow::anyhow!("{error}"))?; - if references.is_empty() { - writeln!(io.out, "No credential references.")?; - } - for reference in references { - let used = manage::reference_use(&config, &reference.id).map_err(|error| anyhow::anyhow!("{error}"))?; - writeln!( - io.out, - "{} provider {} updated {} {used}", - reference.id, - reference.owner, - reference.updated_at.to_rfc3339() - )?; - } - Ok(()) - } - } -} - -// ── prx routes ──────────────────────────────────────────────────────── - -async fn run_routes(command: RoutesCommands, config: Config, io: &mut Io<'_>) -> Result<()> { - match command { - RoutesCommands::List { operation: op } => { - let routes: Vec<(String, String, String)> = match operation(op) { - SelectionOperation::Chat => config - .model_routes - .iter() - .map(|route| (route.hint.clone(), route.provider.clone(), route.model.clone())) - .collect(), - SelectionOperation::Embedding => config - .embedding_routes - .iter() - .map(|route| (route.hint.clone(), route.provider.clone(), route.model.clone())) - .collect(), - }; - if routes.is_empty() { - writeln!(io.out, "No routes.")?; - } - for (hint, provider, model) in routes { - writeln!( - io.out, - "hint:{hint} {} {model}", - manage::redact_provider_text(&provider) - )?; - } - Ok(()) - } - RoutesCommands::Add { - hint, - provider, - model, - operation: op, - apply, - } => { - change( - &service(config), - ManagedChange::AddRoute { - operation: operation(op), - hint, - provider, - model, - }, - &apply, - io, - ) - .await - } - RoutesCommands::Update { - hint, - provider, - model, - operation: op, - apply, - } => { - change( - &service(config), - ManagedChange::UpdateRoute { - operation: operation(op), - hint, - provider, - model, - }, - &apply, - io, - ) - .await - } - RoutesCommands::Remove { - hint, - operation: op, - apply, - } => { - change( - &service(config), - ManagedChange::RemoveRoute { - operation: operation(op), - hint, - }, - &apply, - io, - ) - .await - } - } -} - -// ── prx models ──────────────────────────────────────────────────────── - -fn declaration(args: ModelDeclarationArgs) -> (config::schema::ProviderModelConfig, ApplyArgs) { - let ModelDeclarationArgs { - provider, - model, - operations, - native_tools, - vision_input, - streaming, - structured_output, - tool_schema_dialect, - tool_call_dialect, - context_window, - apply, - } = args; - ( - config::schema::ProviderModelConfig { - provider, - model, - operations, - native_tools, - vision_input, - streaming, - structured_output, - tool_schema_dialect, - tool_call_dialect, - context_window, - }, - apply, - ) -} - -async fn run_models(command: ModelCommands, config: Config, io: &mut Io<'_>) -> Result<()> { - match command { - ModelCommands::Catalog { - catalog_command: crate::CatalogCommands::Status, - } => { - let release = providers::catalog::ReleaseCatalog::embedded_ref()?; - writeln!( - io.out, - "{}", - serde_json::to_string_pretty(&serde_json::json!({ - "source": "embedded", "revision": release.revision, - "content_sha256": release.content_sha256(), "providers": release.providers.len(), - "models": release.models.len(), - "active": release.models.iter().filter(|row| row.lifecycle.status == providers::catalog::ModelLifecycleStatus::Active).count(), - "deprecated": release.models.iter().filter(|row| row.lifecycle.status == providers::catalog::ModelLifecycleStatus::Deprecated).count(), - "retired": release.models.iter().filter(|row| row.lifecycle.status == providers::catalog::ModelLifecycleStatus::Retired).count(), - "updates": "releases only" - }))? - )?; - Ok(()) - } - ModelCommands::MigrateRetired { apply } => { - for warning in openprx::config::manage::lifecycle::warnings(&config)? { - writeln!(io.out, "{warning}")?; - } - change(&service(config), ManagedChange::MigrateRetired, &apply, io).await - } - ModelCommands::Levels { model } => { - let release = providers::catalog::ReleaseCatalog::embedded_ref()?; - let row = release - .models - .iter() - .find(|row| row.id == model) - .ok_or_else(|| anyhow::anyhow!("use a canonical release catalog model ID"))?; - writeln!( - io.out, - "{}", - serde_json::to_string_pretty(&serde_json::json!({ - "model": row.id, "levels": row.levels, "parameters": row.parameters, - "default_level": row.default_level - }))? - )?; - Ok(()) - } - ModelCommands::Settings { - model, - level, - overrides, - apply, - } => { - if level.is_none() && overrides.is_empty() { - let release = providers::catalog::ReleaseCatalog::embedded_ref()?; - if release.models.iter().any(|row| row.id == model && row.is_listed()) - && let Some(settings) = config.model_settings.get(&model) - { - settings.validate(&model)?; - } - writeln!( - io.out, - "{}", - serde_json::to_string_pretty(&config.model_settings.get(&model))? - )?; - return Ok(()); - } - let settings = parse_model_settings(level, overrides)?; - change( - &service(config), - ManagedChange::SetModelSettings { model, settings }, - &apply, - io, - ) - .await - } - - ModelCommands::List { - provider, - operation: None, - executable: false, - } => openprx::providers::model_discovery::run_models_list(&config, provider.as_deref()), - ModelCommands::List { - provider, - operation, - executable, - } => { - let operation = operation - .as_deref() - .map(manage::parse_operation) - .transpose() - .map_err(|error| anyhow::anyhow!("{error}"))?; - let entries = manage::model_catalog( - &config, - &manage::ModelFilter { - provider, - operation, - executable, - }, - ); - if entries.is_empty() { - writeln!(io.out, "No models match.")?; - } - for entry in &entries { - print_model_line(entry, io.out)?; - } - Ok(()) - } - ModelCommands::Show { provider, model } => { - let entry = manage::model_entry(&config, &provider, &model).map_err(|error| anyhow::anyhow!("{error}"))?; - print_model(&entry, io.out) - } - ModelCommands::Refresh { provider, force } => openprx::runtime::blocking::spawn_blocking(move || { - openprx::providers::model_discovery::run_models_refresh(&config, provider.as_deref(), force) - }) - .await - .map_err(|error| anyhow::anyhow!("models refresh task failed: {error}"))?, - ModelCommands::Add(args) => { - let (declaration, apply) = declaration(args); - change(&service(config), ManagedChange::AddModel(declaration), &apply, io).await - } - ModelCommands::Update(args) => { - let (declaration, apply) = declaration(args); - change(&service(config), ManagedChange::UpdateModel(declaration), &apply, io).await - } - ModelCommands::Remove { provider, model, apply } => { - change( - &service(config), - ManagedChange::RemoveModel { provider, model }, - &apply, - io, - ) - .await - } - ModelCommands::Default { default_command } => match default_command { - DefaultCommands::Show => { - match providers::selection::default_status(&config) { - Ok((_, line)) => writeln!(io.out, "Chat: {line}")?, - Err(refusal) => writeln!(io.out, "Chat: refused: {refusal}")?, - } - writeln!( - io.out, - "Embedding: provider '{}' model '{}'", - manage::redact_provider_text(&config.memory.embedding_provider), - config.memory.embedding_model - )?; - Ok(()) - } - DefaultCommands::Set { - level, - overrides, - provider, - model, - operation: op, - keep_root_credential, - clear_root_credential, - apply, - } => { - let settings = if level.is_some() || !overrides.is_empty() { - Some(parse_model_settings(level, overrides)?) - } else { - None - }; - let root_credential = if keep_root_credential { - RootCredential::Keep - } else if clear_root_credential { - RootCredential::Clear - } else { - RootCredential::Refuse - }; - change( - &service(config), - ManagedChange::SetDefault { - settings, - operation: operation(op), - provider, - model, - root_credential, - }, - &apply, - io, - ) - .await - } - }, - } -} - -/// One model on one line: provider, model, the operations the evidence -/// proves, and the evidence's source. -fn print_model_line(entry: &manage::ModelEntry, out: &mut dyn Write) -> Result<()> { - let supported = entry - .operations - .iter() - .filter(|(_, support)| support.as_str() == "supported") - .map(|(operation, _)| operation.as_str()) - .collect::>(); - let supported = if supported.is_empty() { - "unverified".to_string() - } else { - supported.join(",") - }; - let warning = entry - .lifecycle_warning - .as_deref() - .map(|warning| format!(" [{warning}]")) - .unwrap_or_default(); - writeln!( - out, - "{} {} [{supported}] ({}){warning}", - entry.provider, entry.model, entry.source - )?; - Ok(()) -} - -fn print_model(entry: &manage::ModelEntry, out: &mut dyn Write) -> Result<()> { - writeln!(out, "Provider: {} ({})", entry.provider, entry.identity)?; - writeln!(out, "Model: {}", entry.model)?; - writeln!(out, "Evidence: {}", entry.source)?; - if let Some(warning) = &entry.lifecycle_warning { - writeln!(out, "Lifecycle: {warning}")?; - } - if let Some(fetched) = entry.fetched_at_unix { - writeln!(out, "Catalog fetched at (unix): {fetched}")?; - } - if let Some(window) = entry.context_window { - writeln!(out, "Context window: {window}")?; - } - writeln!(out, "Operations:")?; - for (operation, support) in &entry.operations { - writeln!(out, " {operation}: {support}")?; - } - writeln!(out, "Chat features:")?; - for (feature, support) in &entry.features { - writeln!(out, " {feature}: {support}")?; - } - Ok(()) -} - -// ── prx config (management part) ────────────────────────────────────── - -/// Read the file a raw write posts, and refuse text that does not parse -/// without echoing it (the parser's message quotes the offending line). -fn read_posted_file(path: &std::path::Path) -> Result<(String, config::secret_paths::SecretScan)> { - let contents = std::fs::read_to_string(path).with_context(|| format!("failed to read {}", path.display()))?; - let parsed = toml::from_str::(&contents) - .map_err(|error| anyhow::anyhow!("{}", config::manage::render::toml_error_location(&contents, &error)))?; - let scan = config::secret_paths::scan(&toml::Value::Table(parsed)); - Ok((contents, scan)) -} - -pub(crate) async fn run_config(command: ConfigCommands, config: Config, io: &mut Io<'_>) -> Result<()> { - match command { - ConfigCommands::BraveKey { from_stdin: _, apply } => { - let service = service(config); - let revision = service.revision().unwrap_or_else(|| "none".to_owned()); - if !apply.yes || apply.confirm_high_risk.is_none() { - writeln!( - io.out, - "Dry run: stdin was not read. Set web_search.brave_api_key with --from-stdin --yes --confirm-high-risk {revision}" - )?; - return Ok(()); - } - if apply.confirm_high_risk.as_deref() != Some(revision.as_str()) { - bail!("the configuration revision changed; rerun the dry run before supplying a credential"); - } - let mut value = String::new(); - (&mut *io.stdin) - .take(16_385) - .read_to_string(&mut value) - .context("failed to read the Brave credential")?; - if value.len() > 16_384 { - bail!("the Brave credential exceeds 16384 bytes; nothing was stored"); - } - let secret = openprx::config::manage::credentials::SecretString::new( - value.trim_end_matches(['\r', '\n']).to_owned(), - ); - let plan = service.plan_brave_credential(&secret, ConfigActor::Cli).await?; - finish(&service, plan, &apply, io).await - } - ConfigCommands::Plan { - file, - target, - allow_credential_clear, - } => { - let (contents, scan) = read_posted_file(&file)?; - let plan = service(config) - .plan_file(target, contents, allow_credential_clear, ConfigActor::Cli) - .await - .map_err(|error| anyhow::anyhow!("{}", scan.scrub(&error.to_string())))?; - write!(io.out, "{}", plan.text())?; - writeln!(io.out, "Revision: {}", plan.revision().unwrap_or("none"))?; - Ok(()) - } - ConfigCommands::Apply { - file, - target, - allow_credential_clear, - apply, - } => { - let (contents, scan) = read_posted_file(&file)?; - let service = service(config); - let plan = service - .plan_file(target, contents, allow_credential_clear, ConfigActor::Cli) - .await - .map_err(|error| anyhow::anyhow!("{}", scan.scrub(&error.to_string())))?; - finish(&service, plan, &apply, io) - .await - .map_err(|error| anyhow::anyhow!("{}", scan.scrub(&format!("{error:#}")))) - } - ConfigCommands::History { history_command } => { - run_history(history_command.unwrap_or(HistoryCommands::List), config, io).await - } - ConfigCommands::Rollback { - id, - last, - yes, - restore_credentials, - disable_encryption, - } => { - let service = service(config); - let history = service.transactions().history()?; - let record = if last { - history - .list()? - .into_iter() - .find(|record| { - record.is_restorable() - && matches!( - record.status, - RecordStatus::Activated - | RecordStatus::ActivationDeferred - | RecordStatus::Pending - | RecordStatus::NotRestored - ) - }) - .context("no recorded change to roll back")? - } else { - let id = id.context("name the history record to roll back, or pass --last")?; - history.get(id.trim())? - }; - writeln!( - io.out, - "Rolling back to before record {} ({}).", - record.id, - record.status.as_str() - )?; - writeln!(io.out, "The recorded change that is undone:")?; - write!(io.out, "{}", render_plan(&record.summary, &[]))?; - let revision = match service.revision() { - Some(revision) => revision, - None => config::files::current_config_revision(&service.config().config_path)?, - }; - let outcome = service - .transactions() - .rollback(RollbackRequest { - record_id: &record.id, - expected_revision: &revision, - confirm: yes, - restore_credentials, - disable_encryption, - }) - .await; - match outcome { - Ok(outcome) => { - writeln!( - io.out, - "Rolled back on disk (history record {}); activation deferred to the daemon.", - outcome - .record_id - .as_deref() - .unwrap_or("none: the files already held it") - )?; - Ok(()) - } - Err(ConfigTransactionError::ConfirmationRequired { - required: "confirm", .. - }) => { - writeln!(io.out, "Dry run: nothing was written. Roll back with --yes")?; - Ok(()) - } - Err(ConfigTransactionError::ConfirmationRequired { required, .. }) => bail!( - "the rollback needs --{}: {}", - required.replace('_', "-"), - "it restores a credential or setting the current configuration no longer holds; nothing was written" - ), - Err(error) => bail!("{error}"), - } - } - ConfigCommands::Status => { - let service = service(config); - let desired = service.config(); - writeln!(io.out, "Configuration: {}", desired.config_path.display())?; - let revision = if desired.config_path.exists() { - config::files::current_config_revision(&desired.config_path)? - } else { - "none (no configuration file)".to_string() - }; - writeln!(io.out, "Revision: {revision}")?; - match providers::selection::default_status(&desired) { - Ok((_, line)) => writeln!(io.out, "Default: {line}")?, - Err(refusal) => writeln!(io.out, "Default: refused: {refusal}")?, - } - let records = service.transactions().history()?.list()?; - let pending = records - .iter() - .filter(|record| matches!(record.status, RecordStatus::Pending | RecordStatus::NotRestored)) - .map(|record| record.id.as_str()) - .collect::>(); - writeln!(io.out, "History: {} records", records.len())?; - let deferred = records - .iter() - .filter(|record| record.status == RecordStatus::ActivationDeferred) - .map(|record| record.id.as_str()) - .collect::>(); - if !deferred.is_empty() { - writeln!( - io.out, - "Written by `prx`, activation deferred to the daemon (not confirmed here): {}", - deferred.join(", ") - )?; - } - let superseded = records - .iter() - .filter(|record| record.status == RecordStatus::Superseded) - .map(|record| record.id.as_str()) - .collect::>(); - if !superseded.is_empty() { - writeln!( - io.out, - "Written by `prx` and replaced by a later write before a running PRX settled them: {}", - superseded.join(", ") - )?; - } - if !pending.is_empty() { - writeln!( - io.out, - "Unfinished changes (the process stopped, or a restore failed): {}. Inspect with `prx config \ - history show `; `prx config rollback ` restores the configuration from before it.", - pending.join(", ") - )?; - } - Ok(()) - } - ConfigCommands::Agents { agents_command } => match agents_command { - AgentsCommands::New { - agent, - provider, - model, - apply, - } => { - let plan = - openprx::identity::roles::NewRolePlan::prepare(service(config), &agent, &provider, &model).await?; - writeln!(io.out, "{}", plan.text())?; - if !apply.yes { - writeln!( - io.out, - "Dry run: nothing was written. Apply with --yes; if required, use --confirm-high-risk {}", - plan.revision().unwrap_or("none") - )?; - return Ok(()); - } - let outcome = plan.apply(apply.confirm_high_risk.as_deref()).await?; - print_applied(&outcome, io) - } - AgentsCommands::List => { - let mut agents = config.agents.iter().collect::>(); - agents.sort_by(|left, right| left.0.cmp(right.0)); - if agents.is_empty() { - writeln!(io.out, "No delegate agents.")?; - } - for (name, agent) in agents { - writeln!( - io.out, - "{name} {} {}", - manage::redact_provider_text(&agent.provider), - agent.model - )?; - } - Ok(()) - } - AgentsCommands::Set { - agent, - provider, - model, - apply, - } => { - change( - &service(config), - ManagedChange::BindAgent { agent, provider, model }, - &apply, - io, - ) - .await - } - }, - ConfigCommands::Show { .. } | ConfigCommands::Schema | ConfigCommands::Split { .. } | ConfigCommands::Merge => { - bail!("BUG: `prx config show|schema|split|merge` is handled by the dispatcher") - } - } -} - -async fn run_history(command: HistoryCommands, config: Config, io: &mut Io<'_>) -> Result<()> { - let service = service(config); - match command { - HistoryCommands::List => { - let records = service.transactions().history()?.list()?; - if records.is_empty() { - writeln!(io.out, "No recorded changes.")?; - } - for record in records { - writeln!( - io.out, - "{} {} {:?} {:?} {} changes, risk {:?}", - record.id, - record.created_at.to_rfc3339(), - record.actor, - record.status, - record.summary.changes.len(), - record.summary.risk - )?; - } - } - HistoryCommands::Show { id } => { - let record = service.transactions().history()?.get(id.trim())?; - writeln!(io.out, "Record: {}", record.id)?; - writeln!(io.out, "Created: {}", record.created_at.to_rfc3339())?; - writeln!(io.out, "Actor: {:?}", record.actor)?; - writeln!(io.out, "Status: {:?}", record.status)?; - if let Some(restores) = &record.restores { - writeln!(io.out, "Restores: before record {restores}")?; - } - if let Some(reason) = &record.reason { - writeln!(io.out, "Reason: {reason}")?; - } - write!(io.out, "{}", render_plan(&record.summary, &[]))?; - } - HistoryCommands::Purge { yes } => { - if !yes { - bail!("purging removes every history record and cannot be undone; confirm with --yes"); - } - let removed = service.transactions().purge_history().await?; - writeln!(io.out, "Removed {removed} history records.")?; - } - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{Cli, Commands}; - use clap::{CommandFactory, Parser}; - use openprx::config::manage::ManagementService; - - /// A credential-shaped sentinel. Not a real secret. - const SECRET: &str = "pmme-cli-sentinel-value"; - - #[test] - fn deprecated_model_warning_is_visible_in_cli_and_json_surfaces() { - let entry = manage::ModelEntry { - provider: "openai".to_owned(), - identity: "openai".to_owned(), - model: "gpt-legacy".to_owned(), - operations: std::collections::BTreeMap::from([("chat".to_owned(), "supported".to_owned())]), - features: std::collections::BTreeMap::new(), - context_window: None, - source: "release catalog".to_owned(), - fetched_at_unix: None, - lifecycle_warning: Some("deprecated; use openai/gpt-current".to_owned()), - }; - let mut listed = Vec::new(); - print_model_line(&entry, &mut listed).expect("test: list line"); - let listed = String::from_utf8(listed).expect("test: utf8 list line"); - assert!(listed.contains("deprecated; use openai/gpt-current")); - let mut shown = Vec::new(); - print_model(&entry, &mut shown).expect("test: model detail"); - let shown = String::from_utf8(shown).expect("test: utf8 model detail"); - assert!(shown.contains("Lifecycle: deprecated; use openai/gpt-current")); - let gateway_json = serde_json::to_value(&entry).expect("test: gateway JSON"); - assert_eq!( - gateway_json - .get("lifecycle_warning") - .and_then(serde_json::Value::as_str), - Some("deprecated; use openai/gpt-current") - ); - } - - async fn fixture(edit: impl FnOnce(&mut Config)) -> (tempfile::TempDir, Config) { - let dir = tempfile::TempDir::new().expect("test: temp dir"); - let mut config = Config { - config_path: dir.path().join("config.toml"), - workspace_dir: dir.path().join("workspace"), - default_provider: Some("openai".into()), - default_model: Some("gpt-4o".into()), - ..Config::default() - }; - edit(&mut config); - config.save().await.expect("test: save"); - let loaded = reload(&dir).await; - (dir, loaded) - } - - /// What the next `prx` invocation loads. - async fn reload(dir: &tempfile::TempDir) -> Config { - Config::load_or_init_with_config_dir(dir.path().to_str()) - .await - .expect("test: load") - } - - fn manage_command(args: &[&str]) -> ManageCommand { - let cli = Cli::try_parse_from(std::iter::once("prx").chain(args.iter().copied())) - .unwrap_or_else(|error| panic!("test: parse {args:?}: {error}")); - match cli.command { - Commands::Providers { providers_command } => ManageCommand::Providers(providers_command), - Commands::Routes { routes_command } => ManageCommand::Routes(routes_command), - Commands::Models { model_command } => ManageCommand::Models(model_command.unwrap_or(ModelCommands::List { - provider: None, - operation: None, - executable: false, - })), - Commands::Config { config_command } => ManageCommand::Config(config_command), - Commands::DecisionEngine { - command: openprx::decision_engine_cli::DecisionEngineCommands::Config { command }, - .. - } => ManageCommand::DecisionEngine(command), - other => panic!("test: not a management command: {other:?}"), - } - } - - /// Run `prx ` against `config` with `stdin` and `env`; returns the - /// result and everything written to stdout. - async fn run_cli(args: &[&str], config: Config, stdin: &str, env: &[(&str, &str)]) -> (Result<()>, String) { - let mut out = Vec::new(); - let mut input = stdin.as_bytes(); - let lookup = |name: &str| { - env.iter() - .find(|(key, _)| *key == name) - .map(|(_, value)| (*value).to_string()) - }; - let prompt = |_: &str| -> Result { bail!("test: no terminal") }; - let result = { - let mut io = Io { - out: &mut out, - stdin: &mut input, - env: &lookup, - prompt: &prompt, - }; - Box::pin(run(manage_command(args), config, &mut io)).await - }; - (result, String::from_utf8(out).expect("test: utf-8")) - } - - fn stored(dir: &tempfile::TempDir) -> Vec { - std::fs::read(dir.path().join("config.toml")).expect("test: read config.toml") - } - - /// Standard input that records whether anything read it. - struct Watched<'a> { - bytes: &'a [u8], - read: &'a std::cell::Cell, - } - - impl std::io::Read for Watched<'_> { - fn read(&mut self, buf: &mut [u8]) -> std::io::Result { - self.read.set(true); - self.bytes.read(buf) - } - } - - #[tokio::test] - async fn brave_stdin_intake_waits_for_confirmation_and_never_echoes_the_value() { - let (dir, config) = fixture(|_| {}).await; - let original = stored(&dir); - let read = std::cell::Cell::new(false); - let mut stdin = Watched { - bytes: SECRET.as_bytes(), - read: &read, - }; - let mut out = Vec::new(); - let mut io = Io { - out: &mut out, - stdin: &mut stdin, - env: &|_| None, - prompt: &|_| bail!("no prompt"), - }; - run( - manage_command(&["config", "brave-key", "--from-stdin"]), - config.clone(), - &mut io, - ) - .await - .unwrap(); - assert!(!read.get()); - assert_eq!(stored(&dir), original); - let revision = service(config.clone()).revision().unwrap(); - let (result, output) = run_cli( - &[ - "config", - "brave-key", - "--from-stdin", - "--yes", - "--confirm-high-risk", - &revision, - ], - config, - &format!("{SECRET}\n"), - &[], - ) - .await; - result.unwrap(); - assert!(!output.contains(SECRET)); - assert!(!String::from_utf8(stored(&dir)).unwrap().contains(SECRET)); - assert_eq!(reload(&dir).await.web_search.brave_api_key.as_deref(), Some(SECRET)); - } - - #[tokio::test] - async fn fallback_model_flag_updates_the_default_chain_without_duplicate_provider_membership() { - let (dir, config) = fixture(|_| {}).await; - let revision = service(config.clone()).revision().unwrap(); - let original = stored(&dir); - let (result, plan) = run_cli( - &["providers", "add", "openai", "--fallback", "--model", "gpt-5.6"], - config.clone(), - "", - &[], - ) - .await; - result.unwrap(); - assert!(plan.contains("model_fallbacks")); - assert_eq!(stored(&dir), original); - let (result, _) = run_cli( - &[ - "providers", - "add", - "openai", - "--fallback", - "--model", - "gpt-5.6", - "--yes", - "--confirm-high-risk", - &revision, - ], - config, - "", - &[], - ) - .await; - result.unwrap(); - let config = reload(&dir).await; - assert_eq!( - config.reliability.model_fallbacks.get("gpt-4o").unwrap(), - &vec!["gpt-5.6".to_owned()] - ); - assert_eq!(config.reliability.fallback_providers, Vec::::new()); - } - - /// E-1 guard: `prx providers` with no subcommand still lists the - /// providers. - #[tokio::test] - async fn providers_without_a_subcommand_still_lists() { - let cli = Cli::try_parse_from(["prx", "providers"]).expect("test: parse"); - assert!(matches!( - cli.command, - Commands::Providers { - providers_command: None - } - )); - let (_dir, config) = fixture(|config| config.reliability.fallback_providers = vec!["openrouter".into()]).await; - let (result, out) = run_cli(&["providers"], config, "", &[]).await; - result.expect("test: list"); - assert!(out.starts_with("Supported providers ("), "{out}"); - assert!(out.contains(" custom: Any OpenAI-compatible endpoint"), "{out}"); - assert!( - out.contains("Configured providers:\n openai [default] used by: default model"), - "{out}" - ); - assert!( - out.contains(" openrouter [fallback] used by: fallback provider 'openrouter'"), - "{out}" - ); - } - - /// E-1 guard over the clap tree: no management command takes a secret as - /// an argument; `credential set` reads it from a prompt, stdin or an - /// environment variable. - #[test] - fn no_management_command_takes_a_secret_argument() { - fn walk(command: &clap::Command, path: &str, found: &mut Vec) { - for arg in command.get_arguments() { - let names = std::iter::once(arg.get_id().as_str().to_string()) - .chain(arg.get_long().map(str::to_string)) - .chain(arg.get_short().map(|short| short.to_string())) - .collect::>(); - for name in names { - let lowered = name.to_ascii_lowercase(); - if ["key", "token", "secret", "password"] - .iter() - .any(|word| lowered.contains(word)) - { - found.push(format!("{path} --{name}")); - } - } - } - for sub in command.get_subcommands() { - walk(sub, &format!("{path} {}", sub.get_name()), found); - } - } - let root = Cli::command(); - let mut found = Vec::new(); - for name in ["providers", "models", "routes", "config"] { - let command = root - .find_subcommand(name) - .unwrap_or_else(|| panic!("test: `prx {name}` exists")); - walk(command, &format!("prx {name}"), &mut found); - } - assert!(found.is_empty(), "secret-shaped arguments: {found:?}"); - - let set = root - .find_subcommand("providers") - .and_then(|providers| providers.find_subcommand("credential")) - .and_then(|credential| credential.find_subcommand("set")) - .expect("test: `prx providers credential set` exists"); - let longs = set.get_arguments().filter_map(clap::Arg::get_long).collect::>(); - assert!( - longs.contains(&"from-stdin") && longs.contains(&"from-env"), - "{longs:?}" - ); - let positionals = set - .get_arguments() - .filter(|arg| arg.is_positional()) - .map(|arg| arg.get_id().as_str().to_string()) - .collect::>(); - assert_eq!(positionals, ["provider"]); - } - - /// D-101 F-5 ruling: read-only management commands without a - /// configuration run on the defaults and write nothing. - #[tokio::test] - async fn read_only_commands_without_a_config_write_nothing() { - let dir = tempfile::TempDir::new().expect("test: temp dir"); - let config_dir = dir.path().join("not-yet"); - let config = Config::load_existing_or_defaults_read_only(config_dir.to_str()) - .await - .expect("test: defaults"); - for args in [ - &["providers", "list"][..], - &["providers", "migrate"][..], - &["config", "status"][..], - &["routes", "list"][..], - ] { - let (result, _) = run_cli(args, config.clone(), "", &[]).await; - result.unwrap_or_else(|error| panic!("test: {args:?}: {error}")); - assert!(!config_dir.exists(), "{args:?} created the configuration directory"); - } - } - - /// RED before PMMH-g (D-104 C-2): `models list/show`, `config agents - /// list`, `config plan` and `config schema` loaded through the - /// initializing loader (creating `config.toml` on a new machine, running - /// the legacy upgrade otherwise). Every command that only reads loads - /// read-only now; a writing command does not. - #[test] - fn every_command_that_only_reads_loads_read_only() { - let parse = |args: &[&str]| { - Cli::try_parse_from(std::iter::once("prx").chain(args.iter().copied())) - .unwrap_or_else(|error| panic!("test: parse {args:?}: {error}")) - }; - for args in [ - &["models", "list"][..], - &["models", "show", "openai", "gpt-4o"][..], - &["config", "agents", "list"][..], - &["config", "plan", "--file", "candidate.toml"][..], - &["config", "schema"][..], - &["config", "status"][..], - &["providers", "migrate", "--apply"][..], - &["routes", "list"][..], - ] { - assert!( - crate::read_only_management_command(&parse(args).command), - "{args:?} loads through the initializing loader" - ); - } - for args in [ - &["providers", "migrate", "--apply", "--yes"][..], - &["config", "apply", "--file", "candidate.toml", "--yes"][..], - &["routes", "add", "fast", "openai", "gpt-4o-mini"][..], - ] { - assert!( - !crate::read_only_management_command(&parse(args).command), - "{args:?} writes" - ); - } - } - - /// RED before PMMH-f (D-101 F-2): replacing a credential reference - /// recorded `activated`, and `config rollback --last` offered to undo it - /// although the previous value is not kept. The record is - /// `credential_replaced` now, `--last` skips it, and the output says the - /// new value takes effect after a reload. - #[tokio::test] - async fn a_replaced_credential_is_not_offered_for_rollback() { - let (dir, config) = fixture(|_| {}).await; - let (result, _) = run_cli( - &["providers", "credential", "set", "openai", "--from-stdin"], - config, - &format!("{SECRET}\n"), - &[], - ) - .await; - result.expect("test: create"); - let (result, out) = run_cli( - &["providers", "credential", "set", "openai", "--from-stdin"], - reload(&dir).await, - "pmmh-cli-rotated-sentinel\n", - &[], - ) - .await; - result.expect("test: replace"); - assert!( - out.contains("when the configuration next changes (Gateway) or at the next restart"), - "{out}" - ); - - let (result, out) = run_cli(&["config", "rollback", "--last"], reload(&dir).await, "", &[]).await; - let error = result.expect_err("test: nothing restorable to roll back"); - assert!( - error.to_string().contains("no recorded change to roll back"), - "{error} {out}" - ); - } - - /// SP-PMM H-1/H-2 through the CLI: `providers migrate` reports and - /// writes nothing; `--apply` shows the plan and the revision to confirm; - /// with `--yes --confirm-high-risk` it writes the migration; a second - /// run has nothing to migrate. No output carries the key. - #[tokio::test] - async fn providers_migrate_reports_plans_and_applies() { - let (dir, config) = fixture(|config| { - config.model_routes.push(openprx::config::ModelRouteConfig { - settings: Default::default(), - hint: "fast".into(), - provider: "openai".into(), - model: "gpt-4o-mini".into(), - api_key: Some(SECRET.into()), - credential_ref: None, - }); - }) - .await; - let before = std::fs::read(dir.path().join("config.toml")).expect("test: read"); - - let (result, out) = run_cli(&["providers", "migrate"], config, "", &[]).await; - result.expect("test: report"); - assert!(out.contains("model_routes[0].api_key"), "{out}"); - assert!(out.contains("Plan the migration with --apply"), "{out}"); - assert!(!out.contains(SECRET), "{out}"); - assert_eq!( - std::fs::read(dir.path().join("config.toml")).expect("test: read"), - before - ); - - let (result, out) = run_cli(&["providers", "migrate", "--apply"], reload(&dir).await, "", &[]).await; - result.expect("test: plan"); - assert!(!out.contains(SECRET), "{out}"); - let revision = out - .lines() - .find_map(|line| line.split("--confirm-high-risk ").nth(1)) - .map(|revision| revision.trim().to_string()) - .unwrap_or_else(|| panic!("test: the plan names the revision to confirm: {out}")); - assert_eq!( - std::fs::read(dir.path().join("config.toml")).expect("test: read"), - before - ); - - let (result, out) = run_cli( - &[ - "providers", - "migrate", - "--apply", - "--yes", - "--confirm-high-risk", - &revision, - ], - reload(&dir).await, - "", - &[], - ) - .await; - result.expect("test: apply"); - assert!(out.contains("Written and validated"), "{out}"); - assert!(out.contains("--restore-credentials"), "{out}"); - assert!(!out.contains(SECRET), "{out}"); - let migrated = reload(&dir).await; - let route = migrated.model_routes.first().expect("test: the route"); - assert!(route.api_key.is_none()); - assert!(route.credential_ref.is_some()); - assert_eq!( - migrated - .model_routes_with_references() - .first() - .and_then(|route| route.api_key.as_deref()), - Some(SECRET) - ); - - let (result, out) = run_cli(&["providers", "migrate", "--apply"], migrated, "", &[]).await; - result.expect("test: nothing left"); - assert!(out.ends_with("Nothing to migrate.\n"), "{out}"); - } - - #[tokio::test] - async fn a_credential_is_read_from_stdin_or_env_and_never_printed_or_stored_in_plaintext() { - let (dir, config) = fixture(|_| {}).await; - let (result, out) = run_cli( - &["providers", "credential", "set", "openai", "--from-stdin"], - config, - &format!("{SECRET}\n"), - &[], - ) - .await; - result.expect("test: set from stdin"); - assert!( - out.contains("Stored credential reference cred-openai for provider catalog:openai"), - "{out}" - ); - // D-085 F-5, PMM-H: the output says how a configuration uses the - // reference, and which key PRX sends when nothing names one. - assert!(out.contains("`credential_ref = \"cred-openai\"`"), "{out}"); - assert!( - out.contains("PRX sends 'openai' its own auth profile today") - && out.contains("prx auth paste-token --provider openai --from-stdin"), - "{out}" - ); - let (result, out) = run_cli( - &[ - "providers", - "credential", - "set", - "openai", - "--name", - "spare", - "--from-env", - "PMME_TEST_KEY", - ], - reload(&dir).await, - "", - &[("PMME_TEST_KEY", SECRET)], - ) - .await; - result.expect("test: set from env"); - assert!(out.contains("cred-spare"), "{out}"); - let store = std::fs::read_to_string(dir.path().join("auth-profiles.json")).expect("test: store"); - assert!(!store.contains(SECRET), "stored in plaintext"); - - let (result, out) = run_cli(&["providers", "credential", "status"], reload(&dir).await, "", &[]).await; - result.expect("test: status"); - assert!(out.contains("cred-openai provider catalog:openai"), "{out}"); - let (result, out) = run_cli(&["providers", "show", "openai"], reload(&dir).await, "", &[]).await; - result.expect("test: show"); - assert!(out.contains(" - credential reference cred-spare"), "{out}"); - assert!(out.contains("not referenced"), "{out}"); - assert!(out.contains("In use: PRX sends 'openai'"), "{out}"); - assert!(!out.contains(SECRET), "{out}"); - - // A missing environment variable and an empty input are refused. - let (result, _) = run_cli( - &["providers", "credential", "set", "openai", "--from-env", "PMME_UNSET"], - reload(&dir).await, - "", - &[], - ) - .await; - assert!( - result - .expect_err("test: unset") - .to_string() - .contains("PMME_UNSET is not set") - ); - let (result, _) = run_cli( - &["providers", "credential", "set", "openai", "--from-stdin"], - reload(&dir).await, - "\n", - &[], - ) - .await; - assert!(result.is_err()); - - let (result, out) = run_cli( - &["providers", "credential", "remove", "spare"], - reload(&dir).await, - "", - &[], - ) - .await; - result.expect("test: remove"); - assert_eq!(out, "Removed credential reference cred-spare.\n"); - } - - /// E-2 (shared with PMM-F-3): the CLI prints exactly the service's plan - /// text for the same change, and the same refusal; a dry run writes - /// nothing. - #[tokio::test] - async fn the_cli_prints_the_services_plan_and_refusal_text_byte_for_byte() { - let (dir, config) = fixture(|config| { - config.agents.insert( - "coder".into(), - serde_json::from_value(serde_json::json!({ "provider": "openai", "model": "gpt-4o" })) - .expect("test: agent"), - ); - }) - .await; - let before = stored(&dir); - let cases: Vec<(Vec<&str>, ManagedChange)> = vec![ - ( - vec!["routes", "add", "fast", "openai", "gpt-5.6"], - ManagedChange::AddRoute { - operation: SelectionOperation::Chat, - hint: "fast".into(), - provider: "openai".into(), - model: "gpt-5.6".into(), - }, - ), - ( - vec!["models", "default", "set", "openai", "gpt-5.6"], - ManagedChange::SetDefault { - settings: None, - operation: SelectionOperation::Chat, - provider: "openai".into(), - model: "gpt-5.6".into(), - root_credential: RootCredential::Refuse, - }, - ), - ( - vec!["providers", "add", "openrouter", "--fallback"], - ManagedChange::AddProvider { - provider: "openrouter".into(), - }, - ), - ( - vec!["config", "agents", "set", "coder", "openai", "gpt-5.6"], - ManagedChange::BindAgent { - agent: "coder".into(), - provider: "openai".into(), - model: "gpt-5.6".into(), - }, - ), - ( - vec![ - "models", - "add", - "--provider", - "openai", - "--model", - "gpt-5.6", - "--operations", - "chat", - "--native-tools", - "true", - ], - ManagedChange::AddModel(config::schema::ProviderModelConfig { - provider: "openai".into(), - model: Some("gpt-5.6".into()), - operations: Some(vec![config::schema::ModelOperationSetting::Chat]), - native_tools: Some(true), - vision_input: None, - streaming: None, - structured_output: None, - tool_schema_dialect: None, - tool_call_dialect: None, - context_window: None, - }), - ), - ]; - for (args, change) in cases { - let service = ManagementService::new(config::new_shared(config.clone())); - let expected = service - .plan(&change, ConfigActor::Cli) - .await - .unwrap_or_else(|error| panic!("test: service plan {args:?}: {error}")) - .text(); - let (result, out) = run_cli(&args, config.clone(), "", &[]).await; - result.unwrap_or_else(|error| panic!("test: cli {args:?}: {error}")); - assert!( - out.starts_with(&expected), - "{args:?}: CLI printed\n{out}\nservice rendered\n{expected}" - ); - assert_eq!( - &out[expected.len()..], - "Dry run: nothing was written. Apply it with --yes\n", - "{args:?}" - ); - assert_eq!(stored(&dir), before, "{args:?}: a dry run wrote"); - } - - // The same refusal. - let service = ManagementService::new(config::new_shared(config.clone())); - let expected = service - .plan( - &ManagedChange::RemoveProvider { - provider: "openai".into(), - }, - ConfigActor::Cli, - ) - .await - .expect_err("test: refused") - .to_string(); - let (result, out) = run_cli(&["providers", "remove", "openai", "--yes"], config, "", &[]).await; - assert_eq!(result.expect_err("test: refused").to_string(), expected); - assert!(out.is_empty(), "{out}"); - assert_eq!(stored(&dir), before); - } - - /// D-085 F-7: `providers add` names its role; without `--fallback` it - /// does not parse. F-6: `config apply --file` writes only with `--yes`. - #[tokio::test] - async fn adding_a_provider_names_its_role_and_a_file_apply_needs_yes() { - assert!(Cli::try_parse_from(["prx", "providers", "add", "anthropic"]).is_err()); - assert!(Cli::try_parse_from(["prx", "providers", "add", "anthropic", "--fallback"]).is_ok()); - - let (dir, config) = fixture(|_| {}).await; - let before = stored(&dir); - let posted = dir.path().join("posted.toml"); - let text = String::from_utf8(before.clone()).expect("test: utf-8").replacen( - "default_temperature = 0.7", - "default_temperature = 0.3", - 1, - ); - assert_ne!(text.as_bytes(), before.as_slice(), "test: the edit changes the file"); - std::fs::write(&posted, text).expect("test: write"); - let path = posted.to_str().expect("test: path"); - let (result, out) = run_cli(&["config", "apply", "--file", path], config.clone(), "", &[]).await; - result.expect("test: dry run"); - assert!( - out.ends_with("Dry run: nothing was written. Apply it with --yes\n"), - "{out}" - ); - assert_eq!( - stored(&dir), - before, - "RED before PMME-f: `config apply` wrote without --yes" - ); - let (result, out) = run_cli(&["config", "apply", "--file", path, "--yes"], config, "", &[]).await; - result.expect("test: apply"); - assert!(out.contains("Written and validated"), "{out}"); - assert_ne!(stored(&dir), before); - } - - #[tokio::test] - async fn raw_config_secret_removal_requires_the_clear_flag_on_plan_and_apply() { - for encrypt in [false, true] { - for target in ["config.toml", "tools.toml"] { - let (dir, mut config) = fixture(|config| { - config.secrets.encrypt = encrypt; - config.web_search.brave_api_key = Some(SECRET.into()); - }) - .await; - if target == "tools.toml" { - config::files::write_split_config(&config, false).await.unwrap(); - config = reload(&dir).await; - } - let target_path = if target == "config.toml" { - dir.path().join(target) - } else { - dir.path().join("config.d").join(target) - }; - let original = std::fs::read_to_string(&target_path).unwrap(); - let before: toml::Value = toml::from_str(&original).unwrap(); - let mut omitted = before.clone(); - omitted - .get_mut("web_search") - .unwrap() - .as_table_mut() - .unwrap() - .remove("brave_api_key"); - let file = dir.path().join("posted.toml"); - let path = file.to_str().unwrap(); - let mut empty = before.clone(); - *empty.get_mut("web_search").unwrap().get_mut("brave_api_key").unwrap() = - toml::Value::String(String::new()); - for posted in [&omitted, &empty] { - std::fs::write(&file, toml::to_string(posted).unwrap()).unwrap(); - for command in ["plan", "apply"] { - let mut args = vec!["config", command, "--file", path, "--target", target]; - if command == "apply" { - args.push("--yes"); - } - let (result, out) = run_cli(&args, config.clone(), "", &[]).await; - let error = result.unwrap_err().to_string(); - for expected in [ - "web_search.brave_api_key", - "PUT /api/config/secrets", - "--allow-credential-clear", - ] { - assert!(error.contains(expected), "{error}"); - } - assert!(!error.contains(SECRET), "{error}"); - assert!(!out.contains(SECRET), "{out}"); - assert_eq!(std::fs::read_to_string(&target_path).unwrap(), original); - assert_eq!(reload(&dir).await.web_search.brave_api_key.as_deref(), Some(SECRET)); - } - } - // Exact stored ciphertext/plaintext is preserved without a clear flag. - std::fs::write(&file, &original).unwrap(); - let (result, _) = run_cli( - &["config", "plan", "--file", path, "--target", target], - config.clone(), - "", - &[], - ) - .await; - result.unwrap(); - // Even explicit clear permission cannot turn a masked read into a write. - let mut masked = before.clone(); - *masked.get_mut("web_search").unwrap().get_mut("brave_api_key").unwrap() = - toml::Value::String("***".into()); - std::fs::write(&file, toml::to_string(&masked).unwrap()).unwrap(); - let (result, _) = run_cli( - &[ - "config", - "apply", - "--file", - path, - "--target", - target, - "--allow-credential-clear", - "--yes", - ], - config.clone(), - "", - &[], - ) - .await; - assert!(result.unwrap_err().to_string().contains("redaction mask")); - assert_eq!(std::fs::read_to_string(&target_path).unwrap(), original); - if encrypt { - *masked.get_mut("web_search").unwrap().get_mut("brave_api_key").unwrap() = - toml::Value::String("prx-new-plaintext-fixture".into()); - std::fs::write(&file, toml::to_string(&masked).unwrap()).unwrap(); - let (result, _) = run_cli( - &[ - "config", - "apply", - "--file", - path, - "--target", - target, - "--allow-credential-clear", - "--yes", - ], - config.clone(), - "", - &[], - ) - .await; - assert!(result.unwrap_err().to_string().contains("plaintext credentials")); - assert_eq!(std::fs::read_to_string(&target_path).unwrap(), original); - } - std::fs::write(&file, toml::to_string(&omitted).unwrap()).unwrap(); - let (result, out) = run_cli( - &[ - "config", - "plan", - "--file", - path, - "--target", - target, - "--allow-credential-clear", - ], - config.clone(), - "", - &[], - ) - .await; - result.unwrap(); - assert!(!out.contains(SECRET), "{out}"); - assert_eq!(std::fs::read_to_string(&target_path).unwrap(), original); - let revision = out - .lines() - .find_map(|line| line.strip_prefix("Revision: ")) - .unwrap() - .to_owned(); - let (result, _) = run_cli( - &[ - "config", - "apply", - "--file", - path, - "--target", - target, - "--allow-credential-clear", - "--yes", - ], - config.clone(), - "", - &[], - ) - .await; - assert!(result.unwrap_err().to_string().contains("confirm-high-risk")); - assert_eq!(std::fs::read_to_string(&target_path).unwrap(), original); - let (result, out) = run_cli( - &[ - "config", - "apply", - "--file", - path, - "--target", - target, - "--allow-credential-clear", - "--yes", - "--confirm-high-risk", - &revision, - ], - config, - "", - &[], - ) - .await; - result.unwrap(); - assert!(out.contains("Written and validated"), "{out}"); - assert!(!out.contains(SECRET), "{out}"); - assert!(reload(&dir).await.web_search.brave_api_key.is_none()); - } - } - } - - #[tokio::test] - async fn raw_secret_clear_permission_does_not_confirm_access_changes() { - let (dir, config) = fixture(|config| config.gateway.paired_tokens = vec![SECRET.into()]).await; - let before = stored(&dir); - let mut posted: toml::Value = toml::from_str(std::str::from_utf8(&before).unwrap()).unwrap(); - *posted.get_mut("gateway").unwrap().get_mut("paired_tokens").unwrap() = toml::Value::Array(Vec::new()); - let file = dir.path().join("posted.toml"); - std::fs::write(&file, toml::to_string(&posted).unwrap()).unwrap(); - let (result, out) = run_cli( - &[ - "config", - "apply", - "--file", - file.to_str().unwrap(), - "--allow-credential-clear", - "--yes", - ], - config, - "", - &[], - ) - .await; - assert!(result.unwrap_err().to_string().contains("confirm-high-risk")); - assert!(!out.contains(SECRET), "{out}"); - assert_eq!(stored(&dir), before); - } - - #[tokio::test] - async fn config_apply_names_the_shadowing_fragment_and_target_repairs_it() { - let (dir, config) = fixture(|_| {}).await; - let before = stored(&dir); - let fragments = dir.path().join("config.d"); - std::fs::create_dir_all(&fragments).unwrap(); - let fragment = fragments.join("tools.toml"); - let original_fragment = "[web_search]\nprovider = 'duckduckgo'\n"; - std::fs::write(&fragment, original_fragment).unwrap(); - let mut posted: toml::Value = toml::from_str(std::str::from_utf8(&before).unwrap()).unwrap(); - *posted.get_mut("web_search").unwrap().get_mut("provider").unwrap() = toml::Value::String("brave".into()); - let file = dir.path().join("posted.toml"); - std::fs::write(&file, toml::to_string(&posted).unwrap()).unwrap(); - let path = file.to_str().unwrap(); - for args in [ - vec!["config", "plan", "--file", path], - vec!["config", "apply", "--file", path, "--yes"], - ] { - let (result, out) = run_cli(&args, config.clone(), "", &[]).await; - let error = result.unwrap_err().to_string(); - assert!( - error.contains("web_search.provider is shadowed by config.d/tools.toml; use --target tools.toml"), - "{error}" - ); - assert!(!out.contains("no change"), "{out}"); - assert_eq!(stored(&dir), before); - assert_eq!(std::fs::read_to_string(&fragment).unwrap(), original_fragment); - } - // A valid unrelated edit must not hide a shadowed field or be partly applied. - *posted.get_mut("default_temperature").unwrap() = toml::Value::Float(0.4); - std::fs::write(&file, toml::to_string(&posted).unwrap()).unwrap(); - let (result, _) = run_cli(&["config", "apply", "--file", path, "--yes"], config.clone(), "", &[]).await; - assert!( - result - .unwrap_err() - .to_string() - .contains("shadowed by config.d/tools.toml") - ); - assert_eq!(stored(&dir), before); - assert_eq!(std::fs::read_to_string(&fragment).unwrap(), original_fragment); - // Posting an unchanged base is still legal even though the fragment wins. - std::fs::write(&file, &before).unwrap(); - let (result, _) = run_cli(&["config", "plan", "--file", path], config.clone(), "", &[]).await; - result.unwrap(); - // Follow the exact guidance: the target is a basename and other files stay intact. - std::fs::write(&file, "[web_search]\nprovider = 'brave'\n").unwrap(); - let (result, out) = run_cli( - &["config", "apply", "--file", path, "--target", "tools.toml", "--yes"], - config, - "", - &[], - ) - .await; - result.unwrap(); - assert!(out.contains("Written and validated"), "{out}"); - assert_eq!(stored(&dir), before); - assert_eq!(reload(&dir).await.web_search.provider, "brave"); - } - - #[tokio::test] - async fn stored_deleted_model_settings_can_be_inspected_without_selecting_them() { - let (dir, config) = fixture(|config| { - config.model_settings.insert( - "openai/prx-deleted-model".into(), - config::model_settings::ModelSettings { - level: Some("high".into()), - ..Default::default() - }, - ); - }) - .await; - let before = stored(&dir); - let (result, text) = run_cli(&["models", "settings", "openai/prx-deleted-model"], config, "", &[]).await; - result.unwrap(); - let settings: serde_json::Value = serde_json::from_str(&text).unwrap(); - assert_eq!(settings.get("level").and_then(serde_json::Value::as_str), Some("high")); - assert_eq!(stored(&dir), before); - } - - #[tokio::test] - async fn catalog_lifecycle_status_and_migration_use_the_cli_transaction() { - let (dir, config) = fixture(|config| { - config.default_provider = Some("openai".into()); - config.default_model = Some("gpt-4o".into()); - }) - .await; - let before = stored(&dir); - let (result, text) = run_cli(&["models", "catalog", "status"], config.clone(), "", &[]).await; - result.unwrap(); - let status: serde_json::Value = serde_json::from_str(&text).unwrap(); - let release = providers::catalog::ReleaseCatalog::embedded_ref().unwrap(); - assert_eq!( - status.get("revision").and_then(serde_json::Value::as_str), - Some(release.revision.as_str()) - ); - assert_eq!( - status.get("models").and_then(serde_json::Value::as_u64), - Some(u64::try_from(release.models.len()).unwrap()) - ); - assert_eq!( - status.get("content_sha256").and_then(serde_json::Value::as_str), - Some(release.content_sha256()) - ); - assert_eq!( - status.get("updates").and_then(serde_json::Value::as_str), - Some("releases only") - ); - let (result, text) = run_cli(&["models", "migrate-retired"], config.clone(), "", &[]).await; - result.unwrap(); - assert!(text.contains("gpt-5.6-sol"), "{text}"); - assert_eq!(stored(&dir), before); - let (result, text) = run_cli(&["models", "migrate-retired", "--yes"], config, "", &[]).await; - result.unwrap(); - assert!(text.contains("history record"), "{text}"); - assert_ne!(stored(&dir), before); - assert!(String::from_utf8(stored(&dir)).unwrap().contains("gpt-5.6-sol")); - } - - /// D-085 F-6: `prx models list --operation` and `prx models show` print - /// the service's model read model. - #[tokio::test] - async fn models_list_by_operation_and_show_use_the_service_read_model() { - let (_dir, config) = fixture(|config| { - config.providers.models.push( - toml::from_str( - "provider = \"openrouter\"\nmodel = \"jev-decision-test\"\noperations = [\"decision_endpoint\"]\n", - ) - .expect("test: declaration"), - ); - config.providers.models.push( - toml::from_str("provider = \"openai\"\nmodel = \"gpt-4o\"\noperations = [\"chat\"]\n") - .expect("test: declaration"), - ); - }) - .await; - let (result, out) = run_cli( - &["models", "list", "--operation", "chat", "--executable"], - config.clone(), - "", - &[], - ) - .await; - result.expect("test: list"); - assert!(out.contains("openai gpt-4o [chat] (operator declaration)"), "{out}"); - assert!( - out.contains("openai gpt-5.6 [chat] (embedded release catalog)"), - "the real CLI listing must include release-catalog models: {out}" - ); - assert!(!out.contains("jev-decision-test"), "{out}"); - let (result, out) = run_cli(&["models", "show", "openrouter", "jev-decision-test"], config, "", &[]).await; - result.expect("test: show"); - assert!(out.contains("Evidence: operator declaration\n"), "{out}"); - assert!(out.contains(" chat: unsupported"), "{out}"); - } - - /// RED before PMME-g (D-088 C-6): `routes list` and `config agents list` - /// redacted only credential-named query parameters, so `?sig=` came - /// back verbatim. - #[tokio::test] - async fn listings_redact_every_url_query_value() { - const PROVIDER: &str = "custom:https://llm.example/v1?sig=sentinel-listing-sig"; - let (_dir, config) = fixture(|config| { - config.model_routes = vec![config::ModelRouteConfig { - settings: Default::default(), - hint: "fast".into(), - provider: PROVIDER.into(), - model: "m".into(), - api_key: None, - credential_ref: None, - }]; - config.agents.insert( - "coder".into(), - serde_json::from_value(serde_json::json!({ "provider": PROVIDER, "model": "m" })).expect("test: agent"), - ); - }) - .await; - for args in [&["routes", "list"][..], &["config", "agents", "list"][..]] { - let (result, out) = run_cli(args, config.clone(), "", &[]).await; - result.expect("test: list"); - assert!( - out.contains("custom:https://llm.example/v1?sig=[redacted]"), - "{args:?}: {out}" - ); - assert!(!out.contains("sentinel-listing-sig"), "{args:?}: {out}"); - } - } - - /// E-3: `prx config rollback --last` restores the before-image. - #[tokio::test] - async fn rollback_last_restores_the_before_image() { - let (dir, config) = fixture(|_| {}).await; - let before = stored(&dir); - let (result, out) = run_cli( - &["routes", "add", "fast", "openai", "gpt-5.6", "--yes"], - config, - "", - &[], - ) - .await; - result.expect("test: apply"); - assert!(out.contains("Written and validated (history record "), "{out}"); - assert!(out.contains("activation deferred to the daemon"), "{out}"); - assert!(!out.contains("Applied"), "{out}"); - assert_ne!(stored(&dir), before); - - let (result, out) = run_cli(&["config", "history"], reload(&dir).await, "", &[]).await; - result.expect("test: history"); - assert_eq!(out.lines().count(), 1, "{out}"); - // RED before PMME-f (D-085 F-4): recorded `Activated`, although the - // CLI cannot confirm what a running daemon does with the change. - assert!(out.contains("Cli ActivationDeferred"), "{out}"); - - // Without --yes nothing is written. - let changed = stored(&dir); - let (result, out) = run_cli(&["config", "rollback", "--last"], reload(&dir).await, "", &[]).await; - result.expect("test: dry rollback"); - assert!(out.contains(" + model_routes[0].hint = \"fast\"\n"), "{out}"); - assert!( - out.ends_with("Dry run: nothing was written. Roll back with --yes\n"), - "{out}" - ); - assert_eq!(stored(&dir), changed); - - let (result, out) = run_cli(&["config", "rollback", "--last", "--yes"], reload(&dir).await, "", &[]).await; - result.expect("test: rollback"); - assert!(out.contains("Rolled back on disk (history record "), "{out}"); - assert_eq!(stored(&dir), before, "the before-image is restored byte for byte"); - - let (result, out) = run_cli(&["config", "status"], reload(&dir).await, "", &[]).await; - result.expect("test: status"); - assert!(out.contains("History: 2 records"), "{out}"); - assert!( - out.contains("activation deferred to the daemon (not confirmed here)"), - "{out}" - ); - } - - #[tokio::test] - async fn a_confirmed_history_rollback_retains_the_existing_retired_default() { - let (dir, config) = fixture(|config| { - config.default_provider = Some("openai".into()); - config.default_model = Some("gpt-4o".into()); - }) - .await; - let before = stored(&dir); - let (result, _) = run_cli( - &["models", "default", "set", "openai", "gpt-5.6", "--yes"], - config, - "", - &[], - ) - .await; - result.unwrap(); - assert_ne!(stored(&dir), before); - let (result, _) = run_cli(&["config", "rollback", "--last", "--yes"], reload(&dir).await, "", &[]).await; - result.unwrap(); - assert_eq!(stored(&dir), before); - let restored = reload(&dir).await; - assert_eq!(restored.default_model.as_deref(), Some("gpt-4o")); - assert!( - openprx::config::manage::lifecycle::warnings(&restored) - .unwrap() - .iter() - .any(|warning| warning.contains("retired")) - ); - } - - /// A high-risk change applies only with a confirmation naming the - /// revision the plan reported (D-049 B). - #[tokio::test] - async fn a_high_risk_change_needs_the_confirmed_revision() { - let (dir, config) = fixture(|_| {}).await; - let before = stored(&dir); - let args = [ - "providers", - "update", - "openai", - "--api-url", - "https://proxy.example/v1", - "--yes", - ]; - let (result, out) = run_cli(&args, config.clone(), "", &[]).await; - let error = result.expect_err("test: confirmation required").to_string(); - assert!( - out.contains("High risk because the change:\n - changes the provider endpoint at api_url"), - "{out}" - ); - let revision = error - .rsplit("--confirm-high-risk ") - .next() - .expect("test: the refusal names the revision") - .trim() - .to_string(); - assert!(!revision.is_empty(), "{error}"); - assert_eq!(stored(&dir), before); - - let mut wrong = args.to_vec(); - wrong.extend(["--confirm-high-risk", "0000"]); - let (result, _) = run_cli(&wrong, config.clone(), "", &[]).await; - assert!(result.is_err()); - assert_eq!(stored(&dir), before); - - let mut confirmed = args.to_vec(); - confirmed.extend(["--confirm-high-risk", revision.as_str()]); - let (result, out) = run_cli(&confirmed, config, "", &[]).await; - result.unwrap_or_else(|error| panic!("test: confirmed: {error}")); - assert!(out.contains("Written and validated (history record "), "{out}"); - assert!(out.contains("activation deferred to the daemon"), "{out}"); - assert!(!out.contains("Applied"), "{out}"); - assert!( - String::from_utf8_lossy(&stored(&dir)).contains("https://proxy.example/v1"), - "the endpoint is written" - ); - } - - /// `prx config plan --file` goes through the same transaction as the raw - /// editor: a plaintext key at an encrypted slot is refused, and neither - /// the refusal nor a parse error quotes the posted secret. - #[tokio::test] - async fn a_raw_file_plan_never_echoes_a_posted_secret() { - let (dir, config) = fixture(|_| {}).await; - let posted = dir.path().join("posted.toml"); - let mut text = String::from_utf8(stored(&dir)).expect("test: utf-8"); - text = text.replacen( - "default_model = \"gpt-4o\"", - &format!("api_key = \"{SECRET}\"\ndefault_model = \"gpt-4o\""), - 1, - ); - std::fs::write(&posted, &text).expect("test: write"); - let path = posted.to_str().expect("test: path"); - let (result, out) = run_cli(&["config", "plan", "--file", path], config.clone(), "", &[]).await; - let error = result.expect_err("test: plaintext refused").to_string(); - assert!(error.contains("api_key"), "the refusal names the path: {error}"); - assert!(!error.contains(SECRET) && !out.contains(SECRET), "{error}\n{out}"); - - std::fs::write(&posted, format!("api_key = \"{SECRET}\n")).expect("test: write"); - let (result, _) = run_cli(&["config", "plan", "--file", path], config, "", &[]).await; - let error = result.expect_err("test: malformed").to_string(); - assert!(error.starts_with("Invalid TOML content at line 1"), "{error}"); - assert!(!error.contains(SECRET), "{error}"); - } - #[tokio::test] - async fn cli_model_settings_plan_inspect_and_atomic_default_selection_use_pmm() { - let (dir, config) = fixture(|_| {}).await; - let before = stored(&dir); - let (result, out) = run_cli(&["models", "levels", "openai/gpt-5.6"], config.clone(), "", &[]).await; - result.unwrap(); - assert!(out.contains("xhigh")); - assert_eq!(stored(&dir), before); - let (result, out) = run_cli( - &["models", "settings", "openai/gpt-5.6", "--level", "high"], - config.clone(), - "", - &[], - ) - .await; - result.unwrap(); - assert!(out.contains("model_settings")); - assert_eq!(stored(&dir), before); - let (result, out) = run_cli( - &[ - "models", - "default", - "set", - "openai", - "gpt-5.6", - "--level", - "high", - "--set", - "reasoning_effort=low", - "--yes", - ], - config, - "", - &[], - ) - .await; - result.unwrap(); - assert!(out.contains("history record")); - let config = reload(&dir).await; - assert_eq!(config.default_model.as_deref(), Some("gpt-5.6")); - let settings = config.model_settings.get("openai/gpt-5.6").unwrap(); - assert_eq!(settings.level.as_deref(), Some("high")); - assert_eq!( - settings.overrides.get("reasoning_effort"), - Some(&serde_json::json!("low")) - ); - let committed = stored(&dir); - let (result, _) = run_cli( - &[ - "models", - "settings", - "openai/gpt-5.6", - "--set", - "max_output_tokens=0", - "--yes", - ], - config, - "", - &[], - ) - .await; - assert!(result.is_err()); - assert_eq!(stored(&dir), committed); - } -} - -fn parse_model_settings( - level: Option, - overrides: Vec, -) -> Result { - let mut settings = config::model_settings::ModelSettings { - level, - ..Default::default() - }; - for entry in overrides { - let (name, value) = entry - .split_once('=') - .ok_or_else(|| anyhow::anyhow!("use --set name=value"))?; - if providers::catalog::ModelParameter::parse(name).is_none() { - anyhow::bail!("unknown model parameter"); - } - let value = serde_json::from_str(value).unwrap_or_else(|_| serde_json::Value::String(value.to_owned())); - if settings.overrides.insert(name.to_owned(), value).is_some() { - anyhow::bail!("duplicate model parameter"); - } - } - Ok(settings) -} +//! Typed management CLI over the shared configuration transactions. +include!("manage_cli/section_1.rs"); +include!("manage_cli/section_2.rs"); diff --git a/src/runtime/manage_cli/section_1.rs b/src/runtime/manage_cli/section_1.rs new file mode 100644 index 000000000..cc0326336 --- /dev/null +++ b/src/runtime/manage_cli/section_1.rs @@ -0,0 +1,959 @@ +// `prx providers`, `prx models`, `prx routes`, the management part of +// `prx config` (PMM-E) and `prx decision-engine config` (P2-R8). +// +// Every command calls the library's management service +// (`config::manage::ManagementService`) in-process: the same candidate +// building, the same validation and the same plan renderer the Gateway uses, +// so an equal change prints the same plan and the same refusal on every +// surface. A mutating command prints its plan and writes nothing unless +// `--yes` is given; a high-risk plan also needs `--confirm-high-risk +// `, naming the revision the plan reported (D-049 B). +// +// The CLI writes the files through the configuration transaction (revision +// guard, history record, validation of the load); a running PRX picks the +// change up through its configuration watcher. +// +// A credential never comes from an argument: `credential set` reads it from +// a hidden prompt, standard input (`--from-stdin`) or an environment +// variable (`--from-env VAR`), and nothing prints it. + +use anyhow::{Context, Result, bail}; +use openprx::config::manage::service::{self as manage, ProviderEntry}; +use openprx::config::manage::{ + ConfigActor, ConfigTransactionError, ManageError, ManagedChange, ManagedPlan, ManagementService, RecordStatus, + RollbackRequest, RootCredential, SelectionOperation, render_plan, +}; +use openprx::config::{self, Config}; +use openprx::providers; +use std::io::{Read, Write}; + +use crate::{ + AgentsCommands, ApplyArgs, ConfigCommands, CredentialCommands, DefaultCommands, HistoryCommands, ModelCommands, + ModelDeclarationArgs, OperationArg, ProvidersCommands, RoutesCommands, +}; + +/// A management command, as the dispatcher hands it over. +pub(crate) enum ManageCommand { + Providers(Option), + Routes(RoutesCommands), + Models(ModelCommands), + Config(ConfigCommands), + DecisionEngine(openprx::decision_engine_cli::DecisionEngineConfigCommands), +} + +/// Where a command writes and reads: the process's streams in production, +/// buffers in tests. +pub(crate) struct Io<'a> { + pub(crate) out: &'a mut dyn Write, + pub(crate) stdin: &'a mut dyn Read, + /// Reads an environment variable (`--from-env`). + pub(crate) env: &'a dyn Fn(&str) -> Option, + /// Asks for a secret without echoing it. + pub(crate) prompt: &'a dyn Fn(&str) -> Result, +} + +/// Run `command` against the process's own streams and environment. +pub(crate) async fn run_process(command: ManageCommand, config: Config) -> Result<()> { + let mut stdout = std::io::stdout(); + let mut stdin = std::io::stdin(); + let env = |name: &str| std::env::var(name).ok(); + let prompt = |label: &str| crate::read_auth_input(label); + let mut io = Io { + out: &mut stdout, + stdin: &mut stdin, + env: &env, + prompt: &prompt, + }; + run(command, config, &mut io).await +} + +/// Run `command` with `io`. +pub(crate) async fn run(command: ManageCommand, config: Config, io: &mut Io<'_>) -> Result<()> { + match command { + ManageCommand::Providers(command) => { + run_providers(command.unwrap_or(ProvidersCommands::List), config, io).await + } + ManageCommand::Routes(command) => run_routes(command, config, io).await, + ManageCommand::Models(command) => run_models(command, config, io).await, + ManageCommand::Config(command) => run_config(command, config, io).await, + ManageCommand::DecisionEngine(command) => run_decision_engine(command, config, io).await, + } +} + +/// The CLI does not run the configuration's runtime: what it applies is +/// activated by a running PRX's watcher, so it is recorded deferred. +fn service(config: Config) -> ManagementService { + ManagementService::deferred(config::new_shared(config)) +} + +const fn operation(arg: OperationArg) -> SelectionOperation { + match arg { + OperationArg::Chat => SelectionOperation::Chat, + OperationArg::Embedding => SelectionOperation::Embedding, + } +} + +/// Plan `change`, print the plan, and apply it when `apply.yes`. +async fn change(service: &ManagementService, change: ManagedChange, apply: &ApplyArgs, io: &mut Io<'_>) -> Result<()> { + let plan = service + .plan(&change, ConfigActor::Cli) + .await + .map_err(|error| anyhow::anyhow!("{error}"))?; + finish(service, plan, apply, io).await +} + +/// Print `plan`, then apply it when `apply.yes`. +async fn finish(service: &ManagementService, plan: ManagedPlan, apply: &ApplyArgs, io: &mut Io<'_>) -> Result<()> { + write!(io.out, "{}", plan.text())?; + if plan.summary().is_empty() { + writeln!(io.out, "Nothing to change.")?; + return Ok(()); + } + let revision = plan.revision().unwrap_or("none").to_string(); + let high_risk = !plan.summary().risk_reasons.is_empty(); + if !apply.yes { + if high_risk { + writeln!( + io.out, + "Dry run: nothing was written. This change is high risk: apply it with --yes --confirm-high-risk \ + {revision}" + )?; + } else { + writeln!(io.out, "Dry run: nothing was written. Apply it with --yes")?; + } + return Ok(()); + } + match service + .apply(plan, ConfigActor::Cli, apply.confirm_high_risk.as_deref()) + .await + { + Ok(outcome) => print_applied(&outcome, io), + Err(error) => Err(refusal(error)), + } +} + +/// What an applied CLI change prints: written and validated, activation +/// deferred to the daemon (D-085 F-4). +fn print_applied(outcome: &openprx::config::manage::ConfigTransactionOutcome, io: &mut Io<'_>) -> Result<()> { + match &outcome.record_id { + Some(record) => writeln!( + io.out, + "Written and validated (history record {record}); activation deferred to the daemon: a running PRX \ + activates it through its configuration watcher, otherwise at its next start. This command cannot \ + confirm the activation; see `prx config status`. `prx config rollback {record}` undoes it." + )?, + None => writeln!( + io.out, + "The files already held this configuration; nothing was written." + )?, + } + if !outcome.report.restart_required.is_empty() { + writeln!( + io.out, + "Takes effect after a restart: {}", + outcome.report.restart_required.join(", ") + )?; + } + Ok(()) +} + +/// A refused CLI change as the error the command exits with; a needed +/// confirmation names the revision to confirm. +fn refusal(error: ManageError) -> anyhow::Error { + match error { + ManageError::Transaction(error @ ConfigTransactionError::ConfirmationRequired { .. }) => { + let revision = match &error { + ConfigTransactionError::ConfirmationRequired { revision, .. } => revision.clone().unwrap_or_default(), + _ => String::new(), + }; + anyhow::anyhow!( + "{}. Review the plan above and confirm with --yes --confirm-high-risk {revision}", + error.to_string().trim_end_matches('.') + ) + } + error => anyhow::anyhow!("{error}"), + } +} + +// ── prx decision-engine config (P2-R8) ────────────────────────────── + +/// `prx decision-engine config set `: one allowlisted key, +/// planned and applied like every management change. A refused key is one +/// typed error (exit ≠ 0). +async fn run_decision_engine( + command: openprx::decision_engine_cli::DecisionEngineConfigCommands, + config: Config, + io: &mut Io<'_>, +) -> Result<()> { + use openprx::config::manage::mutation::decision_engine::{CausalMutation, engine_setting}; + use openprx::decision_engine_cli::DecisionEngineConfigCommands; + let DecisionEngineConfigCommands::Set { key, value, apply } = command; + let setting = engine_setting(&key, &value)?; + let service = service(config); + let plan = service + .plan_causal(&[CausalMutation::SetEngine(setting)], ConfigActor::Cli) + .await + .map_err(|error| anyhow::anyhow!("{error}"))?; + let apply = ApplyArgs { + yes: apply.yes, + confirm_high_risk: apply.confirm_high_risk, + }; + finish(&service, plan, &apply, io).await +} + +// ── prx providers ───────────────────────────────────────────────────── + +async fn run_providers(command: ProvidersCommands, config: Config, io: &mut Io<'_>) -> Result<()> { + match command { + ProvidersCommands::List => { + print_catalog(&config, io.out)?; + print_configured(&config, io.out) + } + ProvidersCommands::Show { provider } => print_provider(&config, &provider, io.out), + // `--fallback` is required by clap: it is the only role today. + ProvidersCommands::Add { + provider, + fallback: _, + model, + apply, + } => { + let mutation = match model { + Some(model) => ManagedChange::AddProviderWithModel { provider, model }, + None => ManagedChange::AddProvider { provider }, + }; + change(&service(config), mutation, &apply, io).await + } + ProvidersCommands::Update { + provider, + api_url, + clear_api_url, + apply, + } => { + let api_url = if clear_api_url { None } else { api_url }; + change( + &service(config), + ManagedChange::SetProviderEndpoint { provider, api_url }, + &apply, + io, + ) + .await + } + ProvidersCommands::Remove { provider, apply } => { + change(&service(config), ManagedChange::RemoveProvider { provider }, &apply, io).await + } + ProvidersCommands::Test { provider, model, live } => { + let mode = if live { + providers::connection_test::ProbeMode::Live + } else { + providers::connection_test::ProbeMode::Local + }; + let report = + providers::connection_test::test_connection(&config, provider.as_deref(), model.as_deref(), mode).await; + writeln!(io.out, "{report}")?; + let live_failed = report.live.as_ref().is_some_and(|live| live.error.is_some()); + if !report.local.resolved || live_failed { + bail!("the connection test failed"); + } + Ok(()) + } + ProvidersCommands::Credential { credential_command } => run_credential(credential_command, config, io).await, + ProvidersCommands::Migrate { apply, write } => run_migrate(config, apply, &write, io).await, + } +} + +// ── prx providers migrate ───────────────────────────────────────────── + +/// `prx providers migrate`: the report (always), then with `--apply` the +/// plan, and with `--yes` the write (SP-PMM §2.7, PMM-H). +async fn run_migrate(config: Config, apply: bool, write: &ApplyArgs, io: &mut Io<'_>) -> Result<()> { + let service = service(config); + let report = service.migration_report().map_err(|error| anyhow::anyhow!("{error}"))?; + write!(io.out, "{}", report.text())?; + if !apply { + if write.yes { + bail!("--yes writes the migration only together with --apply; nothing was written"); + } + if report.nothing_to_apply() { + writeln!(io.out, "Nothing to migrate.")?; + } else { + writeln!(io.out, "Dry run: nothing was written. Plan the migration with --apply")?; + } + return Ok(()); + } + let Some((report, plan)) = service + .plan_migration() + .await + .map_err(|error| anyhow::anyhow!("{error}"))? + else { + writeln!(io.out, "Nothing to migrate.")?; + return Ok(()); + }; + write!(io.out, "{}", plan.text())?; + let references = report + .inline_keys + .iter() + .map(openprx::config::manage::migrate::InlineKey::reference_id) + .collect::>(); + if !references.is_empty() { + writeln!( + io.out, + "Credential references stored first (encrypted at rest when secrets.encrypt = true): {}", + references.join(", ") + )?; + } + if !write.yes { + let revision = plan.revision().unwrap_or("none"); + if plan.summary().risk_reasons.is_empty() { + writeln!(io.out, "Dry run: nothing was written. Apply it with --apply --yes")?; + } else { + writeln!( + io.out, + "Dry run: nothing was written. This change is high risk: apply it with --apply --yes \ + --confirm-high-risk {revision}" + )?; + } + return Ok(()); + } + let outcome = service + .apply_migration(&report, plan, ConfigActor::Cli, write.confirm_high_risk.as_deref()) + .await; + match outcome { + Ok(outcome) => { + print_applied(&outcome, io)?; + if outcome.record_id.is_some() && !references.is_empty() { + writeln!( + io.out, + "Undoing it brings the inline keys back: `prx config rollback --yes \ + --restore-credentials`." + )?; + } + Ok(()) + } + Err(error) => Err(refusal(error)), + } +} + +/// The catalog of providers this build supports (the listing `prx +/// providers` always printed). +fn print_catalog(config: &Config, out: &mut dyn Write) -> Result<()> { + let catalog = providers::list_providers(); + let current = providers::selection::default_provider(config) + .trim() + .to_ascii_lowercase(); + writeln!(out, "Supported providers ({} total):\n", catalog.len())?; + writeln!(out, " ID (use in config) DESCRIPTION")?; + writeln!(out, " ─────────────────── ───────────")?; + for entry in &catalog { + let is_active = entry.name.eq_ignore_ascii_case(¤t) + || entry.aliases.iter().any(|alias| alias.eq_ignore_ascii_case(¤t)); + let marker = if is_active { " (active)" } else { "" }; + let local_tag = if entry.local { " [local]" } else { "" }; + let aliases = if entry.aliases.is_empty() { + String::new() + } else { + format!(" (aliases: {})", entry.aliases.join(", ")) + }; + writeln!( + out, + " {:<19} {}{}{}{}", + entry.name, entry.display_name, local_tag, marker, aliases + )?; + } + writeln!(out, "\n custom: Any OpenAI-compatible endpoint")?; + writeln!(out, " anthropic-custom: Any Anthropic-compatible endpoint")?; + Ok(()) +} + +fn roles(entry: &ProviderEntry) -> String { + let mut roles = Vec::new(); + if entry.default { + roles.push("default"); + } + if entry.fallback { + roles.push("fallback"); + } + if roles.is_empty() { + "used".to_string() + } else { + roles.join(", ") + } +} + +fn print_configured(config: &Config, out: &mut dyn Write) -> Result<()> { + writeln!(out, "\nConfigured providers:")?; + for entry in manage::configured_providers(config) { + let used_by = if entry.used_by.is_empty() { + "nothing".to_string() + } else { + entry.used_by.join("; ") + }; + writeln!(out, " {} [{}] used by: {used_by}", entry.provider, roles(&entry))?; + } + Ok(()) +} + +fn print_provider(config: &Config, provider: &str, out: &mut dyn Write) -> Result<()> { + let entry = manage::provider_entry(config, provider); + let credentials = manage::provider_credentials(config, provider).map_err(|error| anyhow::anyhow!("{error}"))?; + writeln!(out, "Provider: {}", entry.provider)?; + writeln!(out, "Identity: {}", entry.identity)?; + writeln!(out, "Roles: {}", roles(&entry))?; + if let Some(endpoint) = &entry.endpoint { + writeln!(out, "Endpoint (api_url): {endpoint}")?; + } + writeln!(out, "Model declarations: {}", entry.declarations)?; + if entry.used_by.is_empty() { + writeln!(out, "Used by: nothing")?; + } else { + writeln!(out, "Used by:")?; + for name in &entry.used_by { + writeln!(out, " - {name}")?; + } + } + print_provider_credentials(&config, &credentials, out) +} + +fn print_provider_credentials( + config: &Config, + credentials: &manage::ProviderCredentials, + out: &mut dyn Write, +) -> Result<()> { + writeln!(out, "Credentials (never shown):")?; + let mut any = false; + if credentials.root_connection { + any = true; + writeln!( + out, + " - root connection (api_key / api_url / reliability.api_keys): set" + )?; + } + for slot in &credentials.inline_slots { + any = true; + writeln!(out, " - inline key at {slot}: set")?; + } + for profile in &credentials.store_profiles { + any = true; + writeln!(out, " - auth profile {profile}")?; + } + for reference in &credentials.references { + any = true; + let uses = manage::reference_use(config, &reference.id).map_err(|error| anyhow::anyhow!("{error}"))?; + writeln!( + out, + " - credential reference {} (updated {}): {uses}", + reference.id, + reference.updated_at.to_rfc3339(), + )?; + } + if !any { + writeln!(out, " none")?; + } + writeln!(out, "In use: {}", credentials.guidance)?; + Ok(()) +} + +// ── prx providers credential ────────────────────────────────────────── + +/// The reference id a `remove` argument names: `cred-` or ``. +fn reference_id(reference: &str) -> Result { + let reference = reference.trim(); + if reference.starts_with(openprx::config::manage::credentials::REFERENCE_PREFIX) { + Ok(reference.to_string()) + } else { + openprx::config::manage::credentials::CredentialReferences::id_for(reference) + .map_err(|error| anyhow::anyhow!("{error}")) + } +} + +/// Read a secret from standard input or from an environment variable, when +/// one of them is named (`None` otherwise). The trailing newline of piped +/// input is dropped; an empty secret is refused. Shared by `credential set` +/// and the `--from-stdin`/`--from-env` alternatives of the deprecated +/// argument flags (`init --api-key`, `go -k`, `auth paste-token --token`). +pub(crate) fn secret_from( + from_stdin: bool, + from_env: Option<&str>, + stdin: &mut dyn Read, + env: &dyn Fn(&str) -> Option, +) -> Result> { + let secret = if let Some(variable) = from_env { + env(variable).with_context(|| format!("environment variable {variable} is not set"))? + } else if from_stdin { + let mut text = String::new(); + stdin + .read_to_string(&mut text) + .context("failed to read the secret from standard input")?; + text + } else { + return Ok(None); + }; + let secret = secret.trim_end_matches(['\r', '\n']).to_string(); + if secret.trim().is_empty() { + bail!("the secret is empty; nothing was stored"); + } + Ok(Some(secret)) +} + +/// Read a credential from exactly one source; never from an argument. +fn read_secret(from_stdin: bool, from_env: Option<&str>, io: &mut Io<'_>) -> Result { + if let Some(secret) = secret_from(from_stdin, from_env, io.stdin, io.env)? { + return Ok(secret); + } + let secret = (io.prompt)("Credential (input hidden)")?; + if secret.trim().is_empty() { + bail!("the credential is empty; nothing was stored"); + } + Ok(secret) +} + +async fn run_credential(command: CredentialCommands, config: Config, io: &mut Io<'_>) -> Result<()> { + match command { + CredentialCommands::Set { + provider, + name, + from_stdin, + from_env, + } => { + let id = providers::ProviderId::of(&provider); + let name = match name { + Some(name) => name, + None => id.catalog_name().map(str::to_string).context( + "name the credential with --name (a provider without a catalog name has no default name)", + )?, + }; + let secret = read_secret(from_stdin, from_env.as_deref(), io)?; + let guidance = manage::provider_credentials(&config, &provider) + .map_err(|error| anyhow::anyhow!("{error}"))? + .guidance; + let status = service(config) + .set_credential(provider, name, secret, ConfigActor::Cli) + .await + .map_err(|error| anyhow::anyhow!("{error}"))?; + writeln!( + io.out, + "Stored credential reference {id} for provider {owner} (encrypted at rest when secrets.encrypt = \ + true). A model route, embedding route or agent of {owner} uses it once its configuration names \ + it: `credential_ref = \"{id}\"`; an enabled decision backend of {owner} can use it when configured \ + with that reference. In a running PRX a replaced value takes effect when the \ + configuration next changes (Gateway) or at the next restart (channels and daemon components); \ + restart to apply it now. The replacement is recorded in the configuration history and cannot be \ + rolled back (the previous value is not kept).\n{guidance}.", + id = status.id, + owner = status.owner, + )?; + Ok(()) + } + CredentialCommands::Remove { reference } => { + let id = reference_id(&reference)?; + let removed = service(config) + .remove_credential(&id) + .await + .map_err(|error| anyhow::anyhow!("{error}"))?; + if removed { + writeln!(io.out, "Removed credential reference {id}.")?; + } else { + writeln!(io.out, "Credential reference {id} does not exist; nothing was removed.")?; + } + Ok(()) + } + CredentialCommands::Status { + provider: Some(provider), + } => { + let entry = manage::provider_entry(&config, &provider); + let credentials = + manage::provider_credentials(&config, &provider).map_err(|error| anyhow::anyhow!("{error}"))?; + writeln!(io.out, "Provider: {}", entry.provider)?; + print_provider_credentials(&config, &credentials, io.out) + } + CredentialCommands::Status { provider: None } => { + let references = service(config.clone()) + .credentials() + .and_then(|references| references.list().map_err(ManageError::from)) + .map_err(|error| anyhow::anyhow!("{error}"))?; + if references.is_empty() { + writeln!(io.out, "No credential references.")?; + } + for reference in references { + let used = manage::reference_use(&config, &reference.id).map_err(|error| anyhow::anyhow!("{error}"))?; + writeln!( + io.out, + "{} provider {} updated {} {used}", + reference.id, + reference.owner, + reference.updated_at.to_rfc3339() + )?; + } + Ok(()) + } + } +} + +// ── prx routes ──────────────────────────────────────────────────────── + +async fn run_routes(command: RoutesCommands, config: Config, io: &mut Io<'_>) -> Result<()> { + match command { + RoutesCommands::List { operation: op } => { + let routes: Vec<(String, String, String)> = match operation(op) { + SelectionOperation::Chat => config + .model_routes + .iter() + .map(|route| (route.hint.clone(), route.provider.clone(), route.model.clone())) + .collect(), + SelectionOperation::Embedding => config + .embedding_routes + .iter() + .map(|route| (route.hint.clone(), route.provider.clone(), route.model.clone())) + .collect(), + }; + if routes.is_empty() { + writeln!(io.out, "No routes.")?; + } + for (hint, provider, model) in routes { + writeln!( + io.out, + "hint:{hint} {} {model}", + manage::redact_provider_text(&provider) + )?; + } + Ok(()) + } + RoutesCommands::Add { + hint, + provider, + model, + operation: op, + apply, + } => { + change( + &service(config), + ManagedChange::AddRoute { + operation: operation(op), + hint, + provider, + model, + }, + &apply, + io, + ) + .await + } + RoutesCommands::Update { + hint, + provider, + model, + operation: op, + apply, + } => { + change( + &service(config), + ManagedChange::UpdateRoute { + operation: operation(op), + hint, + provider, + model, + }, + &apply, + io, + ) + .await + } + RoutesCommands::Remove { + hint, + operation: op, + apply, + } => { + change( + &service(config), + ManagedChange::RemoveRoute { + operation: operation(op), + hint, + }, + &apply, + io, + ) + .await + } + } +} + +// ── prx models ──────────────────────────────────────────────────────── + +fn declaration(args: ModelDeclarationArgs) -> (config::schema::ProviderModelConfig, ApplyArgs) { + let ModelDeclarationArgs { + provider, + model, + operations, + native_tools, + vision_input, + streaming, + structured_output, + tool_schema_dialect, + tool_call_dialect, + context_window, + apply, + } = args; + ( + config::schema::ProviderModelConfig { + provider, + model, + operations, + native_tools, + vision_input, + streaming, + structured_output, + tool_schema_dialect, + tool_call_dialect, + context_window, + }, + apply, + ) +} + +async fn run_models(command: ModelCommands, config: Config, io: &mut Io<'_>) -> Result<()> { + match command { + ModelCommands::Catalog { + catalog_command: crate::CatalogCommands::Status, + } => { + let release = providers::catalog::ReleaseCatalog::embedded_ref()?; + writeln!( + io.out, + "{}", + serde_json::to_string_pretty(&serde_json::json!({ + "source": "embedded", "revision": release.revision, + "content_sha256": release.content_sha256(), "providers": release.providers.len(), + "models": release.models.len(), + "active": release.models.iter().filter(|row| row.lifecycle.status == providers::catalog::ModelLifecycleStatus::Active).count(), + "deprecated": release.models.iter().filter(|row| row.lifecycle.status == providers::catalog::ModelLifecycleStatus::Deprecated).count(), + "retired": release.models.iter().filter(|row| row.lifecycle.status == providers::catalog::ModelLifecycleStatus::Retired).count(), + "updates": "releases only" + }))? + )?; + Ok(()) + } + ModelCommands::MigrateRetired { apply } => { + for warning in openprx::config::manage::lifecycle::warnings(&config)? { + writeln!(io.out, "{warning}")?; + } + change(&service(config), ManagedChange::MigrateRetired, &apply, io).await + } + ModelCommands::Levels { model } => { + let release = providers::catalog::ReleaseCatalog::embedded_ref()?; + let row = release + .models + .iter() + .find(|row| row.id == model) + .ok_or_else(|| anyhow::anyhow!("use a canonical release catalog model ID"))?; + writeln!( + io.out, + "{}", + serde_json::to_string_pretty(&serde_json::json!({ + "model": row.id, "levels": row.levels, "parameters": row.parameters, + "default_level": row.default_level + }))? + )?; + Ok(()) + } + ModelCommands::Settings { + model, + level, + overrides, + apply, + } => { + if level.is_none() && overrides.is_empty() { + let release = providers::catalog::ReleaseCatalog::embedded_ref()?; + if release.models.iter().any(|row| row.id == model && row.is_listed()) + && let Some(settings) = config.model_settings.get(&model) + { + settings.validate(&model)?; + } + writeln!( + io.out, + "{}", + serde_json::to_string_pretty(&config.model_settings.get(&model))? + )?; + return Ok(()); + } + let settings = parse_model_settings(level, overrides)?; + change( + &service(config), + ManagedChange::SetModelSettings { model, settings }, + &apply, + io, + ) + .await + } + + ModelCommands::List { + provider, + operation: None, + executable: false, + } => openprx::providers::model_discovery::run_models_list(&config, provider.as_deref()), + ModelCommands::List { + provider, + operation, + executable, + } => { + let operation = operation + .as_deref() + .map(manage::parse_operation) + .transpose() + .map_err(|error| anyhow::anyhow!("{error}"))?; + let entries = manage::model_catalog( + &config, + &manage::ModelFilter { + provider, + operation, + executable, + }, + ); + if entries.is_empty() { + writeln!(io.out, "No models match.")?; + } + for entry in &entries { + print_model_line(entry, io.out)?; + } + Ok(()) + } + ModelCommands::Show { provider, model } => { + let entry = manage::model_entry(&config, &provider, &model).map_err(|error| anyhow::anyhow!("{error}"))?; + print_model(&entry, io.out) + } + ModelCommands::Refresh { provider, force } => openprx::runtime::blocking::spawn_blocking(move || { + openprx::providers::model_discovery::run_models_refresh(&config, provider.as_deref(), force) + }) + .await + .map_err(|error| anyhow::anyhow!("models refresh task failed: {error}"))?, + ModelCommands::Add(args) => { + let (declaration, apply) = declaration(args); + change(&service(config), ManagedChange::AddModel(declaration), &apply, io).await + } + ModelCommands::Update(args) => { + let (declaration, apply) = declaration(args); + change(&service(config), ManagedChange::UpdateModel(declaration), &apply, io).await + } + ModelCommands::Remove { provider, model, apply } => { + change( + &service(config), + ManagedChange::RemoveModel { provider, model }, + &apply, + io, + ) + .await + } + ModelCommands::Default { default_command } => match default_command { + DefaultCommands::Show => { + match providers::selection::default_status(&config) { + Ok((_, line)) => writeln!(io.out, "Chat: {line}")?, + Err(refusal) => writeln!(io.out, "Chat: refused: {refusal}")?, + } + writeln!( + io.out, + "Embedding: provider '{}' model '{}'", + manage::redact_provider_text(&config.memory.embedding_provider), + config.memory.embedding_model + )?; + Ok(()) + } + DefaultCommands::Set { + level, + overrides, + provider, + model, + operation: op, + keep_root_credential, + clear_root_credential, + apply, + } => { + let settings = if level.is_some() || !overrides.is_empty() { + Some(parse_model_settings(level, overrides)?) + } else { + None + }; + let root_credential = if keep_root_credential { + RootCredential::Keep + } else if clear_root_credential { + RootCredential::Clear + } else { + RootCredential::Refuse + }; + change( + &service(config), + ManagedChange::SetDefault { + settings, + operation: operation(op), + provider, + model, + root_credential, + }, + &apply, + io, + ) + .await + } + }, + } +} + +/// One model on one line: provider, model, the operations the evidence +/// proves, and the evidence's source. +fn print_model_line(entry: &manage::ModelEntry, out: &mut dyn Write) -> Result<()> { + let supported = entry + .operations + .iter() + .filter(|(_, support)| support.as_str() == "supported") + .map(|(operation, _)| operation.as_str()) + .collect::>(); + let supported = if supported.is_empty() { + "unverified".to_string() + } else { + supported.join(",") + }; + let warning = entry + .lifecycle_warning + .as_deref() + .map(|warning| format!(" [{warning}]")) + .unwrap_or_default(); + writeln!( + out, + "{} {} [{supported}] ({}){warning}", + entry.provider, entry.model, entry.source + )?; + Ok(()) +} + +fn print_model(entry: &manage::ModelEntry, out: &mut dyn Write) -> Result<()> { + writeln!(out, "Provider: {} ({})", entry.provider, entry.identity)?; + writeln!(out, "Model: {}", entry.model)?; + writeln!(out, "Evidence: {}", entry.source)?; + if let Some(warning) = &entry.lifecycle_warning { + writeln!(out, "Lifecycle: {warning}")?; + } + if let Some(fetched) = entry.fetched_at_unix { + writeln!(out, "Catalog fetched at (unix): {fetched}")?; + } + if let Some(window) = entry.context_window { + writeln!(out, "Context window: {window}")?; + } + writeln!(out, "Operations:")?; + for (operation, support) in &entry.operations { + writeln!(out, " {operation}: {support}")?; + } + writeln!(out, "Chat features:")?; + for (feature, support) in &entry.features { + writeln!(out, " {feature}: {support}")?; + } + Ok(()) +} + +// ── prx config (management part) ────────────────────────────────────── + +/// Read the file a raw write posts, and refuse text that does not parse +/// without echoing it (the parser's message quotes the offending line). +fn read_posted_file(path: &std::path::Path) -> Result<(String, config::secret_paths::SecretScan)> { + let contents = std::fs::read_to_string(path).with_context(|| format!("failed to read {}", path.display()))?; + let parsed = toml::from_str::(&contents) + .map_err(|error| anyhow::anyhow!("{}", config::manage::render::toml_error_location(&contents, &error)))?; + let scan = config::secret_paths::scan(&toml::Value::Table(parsed)); + Ok((contents, scan)) +} + diff --git a/src/runtime/manage_cli/section_2.rs b/src/runtime/manage_cli/section_2.rs new file mode 100644 index 000000000..912d443b6 --- /dev/null +++ b/src/runtime/manage_cli/section_2.rs @@ -0,0 +1,1637 @@ +pub(crate) async fn run_config(command: ConfigCommands, config: Config, io: &mut Io<'_>) -> Result<()> { + match command { + ConfigCommands::Autonomy { level, apply } => { + let level = serde_json::from_value(serde_json::Value::String(level))?; + let service = service(config); + let plan = service.plan_autonomy(level, ConfigActor::Cli).await?; + finish(&service, plan, &apply, io).await?; + writeln!(io.out, "Restart running chats and daemons to use the selected autonomy level.")?; + Ok(()) + } + ConfigCommands::BraveKey { from_stdin: _, apply } => { + let service = service(config); + let revision = service.revision().unwrap_or_else(|| "none".to_owned()); + if !apply.yes || apply.confirm_high_risk.is_none() { + writeln!( + io.out, + "Dry run: stdin was not read. Set web_search.brave_api_key with --from-stdin --yes --confirm-high-risk {revision}" + )?; + return Ok(()); + } + if apply.confirm_high_risk.as_deref() != Some(revision.as_str()) { + bail!("the configuration revision changed; rerun the dry run before supplying a credential"); + } + let mut value = String::new(); + (&mut *io.stdin) + .take(16_385) + .read_to_string(&mut value) + .context("failed to read the Brave credential")?; + if value.len() > 16_384 { + bail!("the Brave credential exceeds 16384 bytes; nothing was stored"); + } + let secret = openprx::config::manage::credentials::SecretString::new( + value.trim_end_matches(['\r', '\n']).to_owned(), + ); + let plan = service.plan_brave_credential(&secret, ConfigActor::Cli).await?; + finish(&service, plan, &apply, io).await + } + ConfigCommands::Plan { + file, + target, + allow_credential_clear, + } => { + let (contents, scan) = read_posted_file(&file)?; + let plan = service(config) + .plan_file(target, contents, allow_credential_clear, ConfigActor::Cli) + .await + .map_err(|error| anyhow::anyhow!("{}", scan.scrub(&error.to_string())))?; + write!(io.out, "{}", plan.text())?; + writeln!(io.out, "Revision: {}", plan.revision().unwrap_or("none"))?; + Ok(()) + } + ConfigCommands::Apply { + file, + target, + allow_credential_clear, + apply, + } => { + let (contents, scan) = read_posted_file(&file)?; + let service = service(config); + let plan = service + .plan_file(target, contents, allow_credential_clear, ConfigActor::Cli) + .await + .map_err(|error| anyhow::anyhow!("{}", scan.scrub(&error.to_string())))?; + finish(&service, plan, &apply, io) + .await + .map_err(|error| anyhow::anyhow!("{}", scan.scrub(&format!("{error:#}")))) + } + ConfigCommands::History { history_command } => { + run_history(history_command.unwrap_or(HistoryCommands::List), config, io).await + } + ConfigCommands::Rollback { + id, + last, + yes, + restore_credentials, + disable_encryption, + } => { + let service = service(config); + let history = service.transactions().history()?; + let record = if last { + history + .list()? + .into_iter() + .find(|record| { + record.is_restorable() + && matches!( + record.status, + RecordStatus::Activated + | RecordStatus::ActivationDeferred + | RecordStatus::Pending + | RecordStatus::NotRestored + ) + }) + .context("no recorded change to roll back")? + } else { + let id = id.context("name the history record to roll back, or pass --last")?; + history.get(id.trim())? + }; + writeln!( + io.out, + "Rolling back to before record {} ({}).", + record.id, + record.status.as_str() + )?; + writeln!(io.out, "The recorded change that is undone:")?; + write!(io.out, "{}", render_plan(&record.summary, &[]))?; + let revision = match service.revision() { + Some(revision) => revision, + None => config::files::current_config_revision(&service.config().config_path)?, + }; + let outcome = service + .transactions() + .rollback(RollbackRequest { + record_id: &record.id, + expected_revision: &revision, + confirm: yes, + restore_credentials, + disable_encryption, + }) + .await; + match outcome { + Ok(outcome) => { + writeln!( + io.out, + "Rolled back on disk (history record {}); activation deferred to the daemon.", + outcome + .record_id + .as_deref() + .unwrap_or("none: the files already held it") + )?; + Ok(()) + } + Err(ConfigTransactionError::ConfirmationRequired { + required: "confirm", .. + }) => { + writeln!(io.out, "Dry run: nothing was written. Roll back with --yes")?; + Ok(()) + } + Err(ConfigTransactionError::ConfirmationRequired { required, .. }) => bail!( + "the rollback needs --{}: {}", + required.replace('_', "-"), + "it restores a credential or setting the current configuration no longer holds; nothing was written" + ), + Err(error) => bail!("{error}"), + } + } + ConfigCommands::Status => { + let service = service(config); + let desired = service.config(); + writeln!(io.out, "Configuration: {}", desired.config_path.display())?; + let revision = if desired.config_path.exists() { + config::files::current_config_revision(&desired.config_path)? + } else { + "none (no configuration file)".to_string() + }; + writeln!(io.out, "Revision: {revision}")?; + match providers::selection::default_status(&desired) { + Ok((_, line)) => writeln!(io.out, "Default: {line}")?, + Err(refusal) => writeln!(io.out, "Default: refused: {refusal}")?, + } + let records = service.transactions().history()?.list()?; + let pending = records + .iter() + .filter(|record| matches!(record.status, RecordStatus::Pending | RecordStatus::NotRestored)) + .map(|record| record.id.as_str()) + .collect::>(); + writeln!(io.out, "History: {} records", records.len())?; + let deferred = records + .iter() + .filter(|record| record.status == RecordStatus::ActivationDeferred) + .map(|record| record.id.as_str()) + .collect::>(); + if !deferred.is_empty() { + writeln!( + io.out, + "Written by `prx`, activation deferred to the daemon (not confirmed here): {}", + deferred.join(", ") + )?; + } + let superseded = records + .iter() + .filter(|record| record.status == RecordStatus::Superseded) + .map(|record| record.id.as_str()) + .collect::>(); + if !superseded.is_empty() { + writeln!( + io.out, + "Written by `prx` and replaced by a later write before a running PRX settled them: {}", + superseded.join(", ") + )?; + } + if !pending.is_empty() { + writeln!( + io.out, + "Unfinished changes (the process stopped, or a restore failed): {}. Inspect with `prx config \ + history show `; `prx config rollback ` restores the configuration from before it.", + pending.join(", ") + )?; + } + Ok(()) + } + ConfigCommands::Agents { agents_command } => match agents_command { + AgentsCommands::New { + agent, + provider, + model, + apply, + } => { + let plan = + openprx::identity::roles::NewRolePlan::prepare(service(config), &agent, &provider, &model).await?; + writeln!(io.out, "{}", plan.text())?; + if !apply.yes { + writeln!( + io.out, + "Dry run: nothing was written. Apply with --yes; if required, use --confirm-high-risk {}", + plan.revision().unwrap_or("none") + )?; + return Ok(()); + } + let outcome = plan.apply(apply.confirm_high_risk.as_deref()).await?; + print_applied(&outcome, io) + } + AgentsCommands::List => { + let mut agents = config.agents.iter().collect::>(); + agents.sort_by(|left, right| left.0.cmp(right.0)); + if agents.is_empty() { + writeln!(io.out, "No delegate agents.")?; + } + for (name, agent) in agents { + writeln!( + io.out, + "{name} {} {}", + manage::redact_provider_text(&agent.provider), + agent.model + )?; + } + Ok(()) + } + AgentsCommands::Set { + agent, + provider, + model, + apply, + } => { + change( + &service(config), + ManagedChange::BindAgent { agent, provider, model }, + &apply, + io, + ) + .await + } + }, + ConfigCommands::Show { .. } | ConfigCommands::Schema | ConfigCommands::Split { .. } | ConfigCommands::Merge => { + bail!("BUG: `prx config show|schema|split|merge` is handled by the dispatcher") + } + } +} + +async fn run_history(command: HistoryCommands, config: Config, io: &mut Io<'_>) -> Result<()> { + let service = service(config); + match command { + HistoryCommands::List => { + let records = service.transactions().history()?.list()?; + if records.is_empty() { + writeln!(io.out, "No recorded changes.")?; + } + for record in records { + writeln!( + io.out, + "{} {} {:?} {:?} {} changes, risk {:?}", + record.id, + record.created_at.to_rfc3339(), + record.actor, + record.status, + record.summary.changes.len(), + record.summary.risk + )?; + } + } + HistoryCommands::Show { id } => { + let record = service.transactions().history()?.get(id.trim())?; + writeln!(io.out, "Record: {}", record.id)?; + writeln!(io.out, "Created: {}", record.created_at.to_rfc3339())?; + writeln!(io.out, "Actor: {:?}", record.actor)?; + writeln!(io.out, "Status: {:?}", record.status)?; + if let Some(restores) = &record.restores { + writeln!(io.out, "Restores: before record {restores}")?; + } + if let Some(reason) = &record.reason { + writeln!(io.out, "Reason: {reason}")?; + } + write!(io.out, "{}", render_plan(&record.summary, &[]))?; + } + HistoryCommands::Purge { yes } => { + if !yes { + bail!("purging removes every history record and cannot be undone; confirm with --yes"); + } + let removed = service.transactions().purge_history().await?; + writeln!(io.out, "Removed {removed} history records.")?; + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Cli, Commands}; + use clap::{CommandFactory, Parser}; + use openprx::config::manage::ManagementService; + + /// A credential-shaped sentinel. Not a real secret. + const SECRET: &str = "pmme-cli-sentinel-value"; + + #[test] + fn deprecated_model_warning_is_visible_in_cli_and_json_surfaces() { + let entry = manage::ModelEntry { + provider: "openai".to_owned(), + identity: "openai".to_owned(), + model: "gpt-legacy".to_owned(), + operations: std::collections::BTreeMap::from([("chat".to_owned(), "supported".to_owned())]), + features: std::collections::BTreeMap::new(), + context_window: None, + source: "release catalog".to_owned(), + fetched_at_unix: None, + lifecycle_warning: Some("deprecated; use openai/gpt-current".to_owned()), + }; + let mut listed = Vec::new(); + print_model_line(&entry, &mut listed).expect("test: list line"); + let listed = String::from_utf8(listed).expect("test: utf8 list line"); + assert!(listed.contains("deprecated; use openai/gpt-current")); + let mut shown = Vec::new(); + print_model(&entry, &mut shown).expect("test: model detail"); + let shown = String::from_utf8(shown).expect("test: utf8 model detail"); + assert!(shown.contains("Lifecycle: deprecated; use openai/gpt-current")); + let gateway_json = serde_json::to_value(&entry).expect("test: gateway JSON"); + assert_eq!( + gateway_json + .get("lifecycle_warning") + .and_then(serde_json::Value::as_str), + Some("deprecated; use openai/gpt-current") + ); + } + + async fn fixture(edit: impl FnOnce(&mut Config)) -> (tempfile::TempDir, Config) { + let dir = tempfile::TempDir::new().expect("test: temp dir"); + let mut config = Config { + config_path: dir.path().join("config.toml"), + workspace_dir: dir.path().join("workspace"), + default_provider: Some("openai".into()), + default_model: Some("gpt-4o".into()), + ..Config::default() + }; + edit(&mut config); + config.save().await.expect("test: save"); + let loaded = reload(&dir).await; + (dir, loaded) + } + + /// What the next `prx` invocation loads. + async fn reload(dir: &tempfile::TempDir) -> Config { + Config::load_or_init_with_config_dir(dir.path().to_str()) + .await + .expect("test: load") + } + + fn manage_command(args: &[&str]) -> ManageCommand { + let cli = Cli::try_parse_from(std::iter::once("prx").chain(args.iter().copied())) + .unwrap_or_else(|error| panic!("test: parse {args:?}: {error}")); + match cli.command { + Commands::Providers { providers_command } => ManageCommand::Providers(providers_command), + Commands::Routes { routes_command } => ManageCommand::Routes(routes_command), + Commands::Models { model_command } => ManageCommand::Models(model_command.unwrap_or(ModelCommands::List { + provider: None, + operation: None, + executable: false, + })), + Commands::Config { config_command } => ManageCommand::Config(config_command), + Commands::DecisionEngine { + command: openprx::decision_engine_cli::DecisionEngineCommands::Config { command }, + .. + } => ManageCommand::DecisionEngine(command), + other => panic!("test: not a management command: {other:?}"), + } + } + + /// Run `prx ` against `config` with `stdin` and `env`; returns the + /// result and everything written to stdout. + async fn run_cli(args: &[&str], config: Config, stdin: &str, env: &[(&str, &str)]) -> (Result<()>, String) { + let mut out = Vec::new(); + let mut input = stdin.as_bytes(); + let lookup = |name: &str| { + env.iter() + .find(|(key, _)| *key == name) + .map(|(_, value)| (*value).to_string()) + }; + let prompt = |_: &str| -> Result { bail!("test: no terminal") }; + let result = { + let mut io = Io { + out: &mut out, + stdin: &mut input, + env: &lookup, + prompt: &prompt, + }; + Box::pin(run(manage_command(args), config, &mut io)).await + }; + (result, String::from_utf8(out).expect("test: utf-8")) + } + + fn stored(dir: &tempfile::TempDir) -> Vec { + std::fs::read(dir.path().join("config.toml")).expect("test: read config.toml") + } + + /// Standard input that records whether anything read it. + struct Watched<'a> { + bytes: &'a [u8], + read: &'a std::cell::Cell, + } + + impl std::io::Read for Watched<'_> { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + self.read.set(true); + self.bytes.read(buf) + } + } + + #[tokio::test] + async fn brave_stdin_intake_waits_for_confirmation_and_never_echoes_the_value() { + let (dir, config) = fixture(|_| {}).await; + let original = stored(&dir); + let read = std::cell::Cell::new(false); + let mut stdin = Watched { + bytes: SECRET.as_bytes(), + read: &read, + }; + let mut out = Vec::new(); + let mut io = Io { + out: &mut out, + stdin: &mut stdin, + env: &|_| None, + prompt: &|_| bail!("no prompt"), + }; + run( + manage_command(&["config", "brave-key", "--from-stdin"]), + config.clone(), + &mut io, + ) + .await + .unwrap(); + assert!(!read.get()); + assert_eq!(stored(&dir), original); + let revision = service(config.clone()).revision().unwrap(); + let (result, output) = run_cli( + &[ + "config", + "brave-key", + "--from-stdin", + "--yes", + "--confirm-high-risk", + &revision, + ], + config, + &format!("{SECRET}\n"), + &[], + ) + .await; + result.unwrap(); + assert!(!output.contains(SECRET)); + assert!(!String::from_utf8(stored(&dir)).unwrap().contains(SECRET)); + assert_eq!(reload(&dir).await.web_search.brave_api_key.as_deref(), Some(SECRET)); + } + + #[tokio::test] + async fn fallback_model_flag_updates_the_default_chain_without_duplicate_provider_membership() { + let (dir, config) = fixture(|_| {}).await; + let revision = service(config.clone()).revision().unwrap(); + let original = stored(&dir); + let (result, plan) = run_cli( + &["providers", "add", "openai", "--fallback", "--model", "gpt-5.6"], + config.clone(), + "", + &[], + ) + .await; + result.unwrap(); + assert!(plan.contains("model_fallbacks")); + assert_eq!(stored(&dir), original); + let (result, _) = run_cli( + &[ + "providers", + "add", + "openai", + "--fallback", + "--model", + "gpt-5.6", + "--yes", + "--confirm-high-risk", + &revision, + ], + config, + "", + &[], + ) + .await; + result.unwrap(); + let config = reload(&dir).await; + assert_eq!( + config.reliability.model_fallbacks.get("gpt-4o").unwrap(), + &vec!["gpt-5.6".to_owned()] + ); + assert_eq!(config.reliability.fallback_providers, Vec::::new()); + } + + /// E-1 guard: `prx providers` with no subcommand still lists the + /// providers. + #[tokio::test] + async fn providers_without_a_subcommand_still_lists() { + let cli = Cli::try_parse_from(["prx", "providers"]).expect("test: parse"); + assert!(matches!( + cli.command, + Commands::Providers { + providers_command: None + } + )); + let (_dir, config) = fixture(|config| config.reliability.fallback_providers = vec!["openrouter".into()]).await; + let (result, out) = run_cli(&["providers"], config, "", &[]).await; + result.expect("test: list"); + assert!(out.starts_with("Supported providers ("), "{out}"); + assert!(out.contains(" custom: Any OpenAI-compatible endpoint"), "{out}"); + assert!( + out.contains("Configured providers:\n openai [default] used by: default model"), + "{out}" + ); + assert!( + out.contains(" openrouter [fallback] used by: fallback provider 'openrouter'"), + "{out}" + ); + } + + /// E-1 guard over the clap tree: no management command takes a secret as + /// an argument; `credential set` reads it from a prompt, stdin or an + /// environment variable. + #[test] + fn no_management_command_takes_a_secret_argument() { + fn walk(command: &clap::Command, path: &str, found: &mut Vec) { + for arg in command.get_arguments() { + let names = std::iter::once(arg.get_id().as_str().to_string()) + .chain(arg.get_long().map(str::to_string)) + .chain(arg.get_short().map(|short| short.to_string())) + .collect::>(); + for name in names { + let lowered = name.to_ascii_lowercase(); + if ["key", "token", "secret", "password"] + .iter() + .any(|word| lowered.contains(word)) + { + found.push(format!("{path} --{name}")); + } + } + } + for sub in command.get_subcommands() { + walk(sub, &format!("{path} {}", sub.get_name()), found); + } + } + let root = Cli::command(); + let mut found = Vec::new(); + for name in ["providers", "models", "routes", "config"] { + let command = root + .find_subcommand(name) + .unwrap_or_else(|| panic!("test: `prx {name}` exists")); + walk(command, &format!("prx {name}"), &mut found); + } + assert!(found.is_empty(), "secret-shaped arguments: {found:?}"); + + let set = root + .find_subcommand("providers") + .and_then(|providers| providers.find_subcommand("credential")) + .and_then(|credential| credential.find_subcommand("set")) + .expect("test: `prx providers credential set` exists"); + let longs = set.get_arguments().filter_map(clap::Arg::get_long).collect::>(); + assert!( + longs.contains(&"from-stdin") && longs.contains(&"from-env"), + "{longs:?}" + ); + let positionals = set + .get_arguments() + .filter(|arg| arg.is_positional()) + .map(|arg| arg.get_id().as_str().to_string()) + .collect::>(); + assert_eq!(positionals, ["provider"]); + } + + /// D-101 F-5 ruling: read-only management commands without a + /// configuration run on the defaults and write nothing. + #[tokio::test] + async fn read_only_commands_without_a_config_write_nothing() { + let dir = tempfile::TempDir::new().expect("test: temp dir"); + let config_dir = dir.path().join("not-yet"); + let config = Config::load_existing_or_defaults_read_only(config_dir.to_str()) + .await + .expect("test: defaults"); + for args in [ + &["providers", "list"][..], + &["providers", "migrate"][..], + &["config", "status"][..], + &["routes", "list"][..], + ] { + let (result, _) = run_cli(args, config.clone(), "", &[]).await; + result.unwrap_or_else(|error| panic!("test: {args:?}: {error}")); + assert!(!config_dir.exists(), "{args:?} created the configuration directory"); + } + } + + /// RED before PMMH-g (D-104 C-2): `models list/show`, `config agents + /// list`, `config plan` and `config schema` loaded through the + /// initializing loader (creating `config.toml` on a new machine, running + /// the legacy upgrade otherwise). Every command that only reads loads + /// read-only now; a writing command does not. + #[test] + fn every_command_that_only_reads_loads_read_only() { + let parse = |args: &[&str]| { + Cli::try_parse_from(std::iter::once("prx").chain(args.iter().copied())) + .unwrap_or_else(|error| panic!("test: parse {args:?}: {error}")) + }; + for args in [ + &["models", "list"][..], + &["models", "show", "openai", "gpt-4o"][..], + &["config", "agents", "list"][..], + &["config", "plan", "--file", "candidate.toml"][..], + &["config", "schema"][..], + &["config", "status"][..], + &["providers", "migrate", "--apply"][..], + &["routes", "list"][..], + ] { + assert!( + crate::read_only_management_command(&parse(args).command), + "{args:?} loads through the initializing loader" + ); + } + for args in [ + &["providers", "migrate", "--apply", "--yes"][..], + &["config", "apply", "--file", "candidate.toml", "--yes"][..], + &["routes", "add", "fast", "openai", "gpt-4o-mini"][..], + ] { + assert!( + !crate::read_only_management_command(&parse(args).command), + "{args:?} writes" + ); + } + } + + /// RED before PMMH-f (D-101 F-2): replacing a credential reference + /// recorded `activated`, and `config rollback --last` offered to undo it + /// although the previous value is not kept. The record is + /// `credential_replaced` now, `--last` skips it, and the output says the + /// new value takes effect after a reload. + #[tokio::test] + async fn a_replaced_credential_is_not_offered_for_rollback() { + let (dir, config) = fixture(|_| {}).await; + let (result, _) = run_cli( + &["providers", "credential", "set", "openai", "--from-stdin"], + config, + &format!("{SECRET}\n"), + &[], + ) + .await; + result.expect("test: create"); + let (result, out) = run_cli( + &["providers", "credential", "set", "openai", "--from-stdin"], + reload(&dir).await, + "pmmh-cli-rotated-sentinel\n", + &[], + ) + .await; + result.expect("test: replace"); + assert!( + out.contains("when the configuration next changes (Gateway) or at the next restart"), + "{out}" + ); + + let (result, out) = run_cli(&["config", "rollback", "--last"], reload(&dir).await, "", &[]).await; + let error = result.expect_err("test: nothing restorable to roll back"); + assert!( + error.to_string().contains("no recorded change to roll back"), + "{error} {out}" + ); + } + + /// SP-PMM H-1/H-2 through the CLI: `providers migrate` reports and + /// writes nothing; `--apply` shows the plan and the revision to confirm; + /// with `--yes --confirm-high-risk` it writes the migration; a second + /// run has nothing to migrate. No output carries the key. + #[tokio::test] + async fn providers_migrate_reports_plans_and_applies() { + let (dir, config) = fixture(|config| { + config.model_routes.push(openprx::config::ModelRouteConfig { + settings: Default::default(), + hint: "fast".into(), + provider: "openai".into(), + model: "gpt-4o-mini".into(), + api_key: Some(SECRET.into()), + credential_ref: None, + }); + }) + .await; + let before = std::fs::read(dir.path().join("config.toml")).expect("test: read"); + + let (result, out) = run_cli(&["providers", "migrate"], config, "", &[]).await; + result.expect("test: report"); + assert!(out.contains("model_routes[0].api_key"), "{out}"); + assert!(out.contains("Plan the migration with --apply"), "{out}"); + assert!(!out.contains(SECRET), "{out}"); + assert_eq!( + std::fs::read(dir.path().join("config.toml")).expect("test: read"), + before + ); + + let (result, out) = run_cli(&["providers", "migrate", "--apply"], reload(&dir).await, "", &[]).await; + result.expect("test: plan"); + assert!(!out.contains(SECRET), "{out}"); + let revision = out + .lines() + .find_map(|line| line.split("--confirm-high-risk ").nth(1)) + .map(|revision| revision.trim().to_string()) + .unwrap_or_else(|| panic!("test: the plan names the revision to confirm: {out}")); + assert_eq!( + std::fs::read(dir.path().join("config.toml")).expect("test: read"), + before + ); + + let (result, out) = run_cli( + &[ + "providers", + "migrate", + "--apply", + "--yes", + "--confirm-high-risk", + &revision, + ], + reload(&dir).await, + "", + &[], + ) + .await; + result.expect("test: apply"); + assert!(out.contains("Written and validated"), "{out}"); + assert!(out.contains("--restore-credentials"), "{out}"); + assert!(!out.contains(SECRET), "{out}"); + let migrated = reload(&dir).await; + let route = migrated.model_routes.first().expect("test: the route"); + assert!(route.api_key.is_none()); + assert!(route.credential_ref.is_some()); + assert_eq!( + migrated + .model_routes_with_references() + .first() + .and_then(|route| route.api_key.as_deref()), + Some(SECRET) + ); + + let (result, out) = run_cli(&["providers", "migrate", "--apply"], migrated, "", &[]).await; + result.expect("test: nothing left"); + assert!(out.ends_with("Nothing to migrate.\n"), "{out}"); + } + + #[tokio::test] + async fn a_credential_is_read_from_stdin_or_env_and_never_printed_or_stored_in_plaintext() { + let (dir, config) = fixture(|_| {}).await; + let (result, out) = run_cli( + &["providers", "credential", "set", "openai", "--from-stdin"], + config, + &format!("{SECRET}\n"), + &[], + ) + .await; + result.expect("test: set from stdin"); + assert!( + out.contains("Stored credential reference cred-openai for provider catalog:openai"), + "{out}" + ); + // D-085 F-5, PMM-H: the output says how a configuration uses the + // reference, and which key PRX sends when nothing names one. + assert!(out.contains("`credential_ref = \"cred-openai\"`"), "{out}"); + assert!( + out.contains("PRX sends 'openai' its own auth profile today") + && out.contains("prx auth paste-token --provider openai --from-stdin"), + "{out}" + ); + let (result, out) = run_cli( + &[ + "providers", + "credential", + "set", + "openai", + "--name", + "spare", + "--from-env", + "PMME_TEST_KEY", + ], + reload(&dir).await, + "", + &[("PMME_TEST_KEY", SECRET)], + ) + .await; + result.expect("test: set from env"); + assert!(out.contains("cred-spare"), "{out}"); + let store = std::fs::read_to_string(dir.path().join("auth-profiles.json")).expect("test: store"); + assert!(!store.contains(SECRET), "stored in plaintext"); + + let (result, out) = run_cli(&["providers", "credential", "status"], reload(&dir).await, "", &[]).await; + result.expect("test: status"); + assert!(out.contains("cred-openai provider catalog:openai"), "{out}"); + let (result, out) = run_cli(&["providers", "show", "openai"], reload(&dir).await, "", &[]).await; + result.expect("test: show"); + assert!(out.contains(" - credential reference cred-spare"), "{out}"); + assert!(out.contains("not referenced"), "{out}"); + assert!(out.contains("In use: PRX sends 'openai'"), "{out}"); + assert!(!out.contains(SECRET), "{out}"); + + // A missing environment variable and an empty input are refused. + let (result, _) = run_cli( + &["providers", "credential", "set", "openai", "--from-env", "PMME_UNSET"], + reload(&dir).await, + "", + &[], + ) + .await; + assert!( + result + .expect_err("test: unset") + .to_string() + .contains("PMME_UNSET is not set") + ); + let (result, _) = run_cli( + &["providers", "credential", "set", "openai", "--from-stdin"], + reload(&dir).await, + "\n", + &[], + ) + .await; + assert!(result.is_err()); + + let (result, out) = run_cli( + &["providers", "credential", "remove", "spare"], + reload(&dir).await, + "", + &[], + ) + .await; + result.expect("test: remove"); + assert_eq!(out, "Removed credential reference cred-spare.\n"); + } + + /// E-2 (shared with PMM-F-3): the CLI prints exactly the service's plan + /// text for the same change, and the same refusal; a dry run writes + /// nothing. + #[tokio::test] + async fn the_cli_prints_the_services_plan_and_refusal_text_byte_for_byte() { + let (dir, config) = fixture(|config| { + config.agents.insert( + "coder".into(), + serde_json::from_value(serde_json::json!({ "provider": "openai", "model": "gpt-4o" })) + .expect("test: agent"), + ); + }) + .await; + let before = stored(&dir); + let cases: Vec<(Vec<&str>, ManagedChange)> = vec![ + ( + vec!["routes", "add", "fast", "openai", "gpt-5.6"], + ManagedChange::AddRoute { + operation: SelectionOperation::Chat, + hint: "fast".into(), + provider: "openai".into(), + model: "gpt-5.6".into(), + }, + ), + ( + vec!["models", "default", "set", "openai", "gpt-5.6"], + ManagedChange::SetDefault { + settings: None, + operation: SelectionOperation::Chat, + provider: "openai".into(), + model: "gpt-5.6".into(), + root_credential: RootCredential::Refuse, + }, + ), + ( + vec!["providers", "add", "openrouter", "--fallback"], + ManagedChange::AddProvider { + provider: "openrouter".into(), + }, + ), + ( + vec!["config", "agents", "set", "coder", "openai", "gpt-5.6"], + ManagedChange::BindAgent { + agent: "coder".into(), + provider: "openai".into(), + model: "gpt-5.6".into(), + }, + ), + ( + vec![ + "models", + "add", + "--provider", + "openai", + "--model", + "gpt-5.6", + "--operations", + "chat", + "--native-tools", + "true", + ], + ManagedChange::AddModel(config::schema::ProviderModelConfig { + provider: "openai".into(), + model: Some("gpt-5.6".into()), + operations: Some(vec![config::schema::ModelOperationSetting::Chat]), + native_tools: Some(true), + vision_input: None, + streaming: None, + structured_output: None, + tool_schema_dialect: None, + tool_call_dialect: None, + context_window: None, + }), + ), + ]; + for (args, change) in cases { + let service = ManagementService::new(config::new_shared(config.clone())); + let expected = service + .plan(&change, ConfigActor::Cli) + .await + .unwrap_or_else(|error| panic!("test: service plan {args:?}: {error}")) + .text(); + let (result, out) = run_cli(&args, config.clone(), "", &[]).await; + result.unwrap_or_else(|error| panic!("test: cli {args:?}: {error}")); + assert!( + out.starts_with(&expected), + "{args:?}: CLI printed\n{out}\nservice rendered\n{expected}" + ); + assert_eq!( + &out[expected.len()..], + "Dry run: nothing was written. Apply it with --yes\n", + "{args:?}" + ); + assert_eq!(stored(&dir), before, "{args:?}: a dry run wrote"); + } + + // The same refusal. + let service = ManagementService::new(config::new_shared(config.clone())); + let expected = service + .plan( + &ManagedChange::RemoveProvider { + provider: "openai".into(), + }, + ConfigActor::Cli, + ) + .await + .expect_err("test: refused") + .to_string(); + let (result, out) = run_cli(&["providers", "remove", "openai", "--yes"], config, "", &[]).await; + assert_eq!(result.expect_err("test: refused").to_string(), expected); + assert!(out.is_empty(), "{out}"); + assert_eq!(stored(&dir), before); + } + + /// D-085 F-7: `providers add` names its role; without `--fallback` it + /// does not parse. F-6: `config apply --file` writes only with `--yes`. + #[tokio::test] + async fn adding_a_provider_names_its_role_and_a_file_apply_needs_yes() { + assert!(Cli::try_parse_from(["prx", "providers", "add", "anthropic"]).is_err()); + assert!(Cli::try_parse_from(["prx", "providers", "add", "anthropic", "--fallback"]).is_ok()); + + let (dir, config) = fixture(|_| {}).await; + let before = stored(&dir); + let posted = dir.path().join("posted.toml"); + let text = String::from_utf8(before.clone()).expect("test: utf-8").replacen( + "default_temperature = 0.7", + "default_temperature = 0.3", + 1, + ); + assert_ne!(text.as_bytes(), before.as_slice(), "test: the edit changes the file"); + std::fs::write(&posted, text).expect("test: write"); + let path = posted.to_str().expect("test: path"); + let (result, out) = run_cli(&["config", "apply", "--file", path], config.clone(), "", &[]).await; + result.expect("test: dry run"); + assert!( + out.ends_with("Dry run: nothing was written. Apply it with --yes\n"), + "{out}" + ); + assert_eq!( + stored(&dir), + before, + "RED before PMME-f: `config apply` wrote without --yes" + ); + let (result, out) = run_cli(&["config", "apply", "--file", path, "--yes"], config, "", &[]).await; + result.expect("test: apply"); + assert!(out.contains("Written and validated"), "{out}"); + assert_ne!(stored(&dir), before); + } + + #[tokio::test] + async fn raw_config_secret_removal_requires_the_clear_flag_on_plan_and_apply() { + for encrypt in [false, true] { + for target in ["config.toml", "tools.toml"] { + let (dir, mut config) = fixture(|config| { + config.secrets.encrypt = encrypt; + config.web_search.brave_api_key = Some(SECRET.into()); + }) + .await; + if target == "tools.toml" { + config::files::write_split_config(&config, false).await.unwrap(); + config = reload(&dir).await; + } + let target_path = if target == "config.toml" { + dir.path().join(target) + } else { + dir.path().join("config.d").join(target) + }; + let original = std::fs::read_to_string(&target_path).unwrap(); + let before: toml::Value = toml::from_str(&original).unwrap(); + let mut omitted = before.clone(); + omitted + .get_mut("web_search") + .unwrap() + .as_table_mut() + .unwrap() + .remove("brave_api_key"); + let file = dir.path().join("posted.toml"); + let path = file.to_str().unwrap(); + let mut empty = before.clone(); + *empty.get_mut("web_search").unwrap().get_mut("brave_api_key").unwrap() = + toml::Value::String(String::new()); + for posted in [&omitted, &empty] { + std::fs::write(&file, toml::to_string(posted).unwrap()).unwrap(); + for command in ["plan", "apply"] { + let mut args = vec!["config", command, "--file", path, "--target", target]; + if command == "apply" { + args.push("--yes"); + } + let (result, out) = run_cli(&args, config.clone(), "", &[]).await; + let error = result.unwrap_err().to_string(); + for expected in [ + "web_search.brave_api_key", + "PUT /api/config/secrets", + "--allow-credential-clear", + ] { + assert!(error.contains(expected), "{error}"); + } + assert!(!error.contains(SECRET), "{error}"); + assert!(!out.contains(SECRET), "{out}"); + assert_eq!(std::fs::read_to_string(&target_path).unwrap(), original); + assert_eq!(reload(&dir).await.web_search.brave_api_key.as_deref(), Some(SECRET)); + } + } + // Exact stored ciphertext/plaintext is preserved without a clear flag. + std::fs::write(&file, &original).unwrap(); + let (result, _) = run_cli( + &["config", "plan", "--file", path, "--target", target], + config.clone(), + "", + &[], + ) + .await; + result.unwrap(); + // Even explicit clear permission cannot turn a masked read into a write. + let mut masked = before.clone(); + *masked.get_mut("web_search").unwrap().get_mut("brave_api_key").unwrap() = + toml::Value::String("***".into()); + std::fs::write(&file, toml::to_string(&masked).unwrap()).unwrap(); + let (result, _) = run_cli( + &[ + "config", + "apply", + "--file", + path, + "--target", + target, + "--allow-credential-clear", + "--yes", + ], + config.clone(), + "", + &[], + ) + .await; + assert!(result.unwrap_err().to_string().contains("redaction mask")); + assert_eq!(std::fs::read_to_string(&target_path).unwrap(), original); + if encrypt { + *masked.get_mut("web_search").unwrap().get_mut("brave_api_key").unwrap() = + toml::Value::String("prx-new-plaintext-fixture".into()); + std::fs::write(&file, toml::to_string(&masked).unwrap()).unwrap(); + let (result, _) = run_cli( + &[ + "config", + "apply", + "--file", + path, + "--target", + target, + "--allow-credential-clear", + "--yes", + ], + config.clone(), + "", + &[], + ) + .await; + assert!(result.unwrap_err().to_string().contains("plaintext credentials")); + assert_eq!(std::fs::read_to_string(&target_path).unwrap(), original); + } + std::fs::write(&file, toml::to_string(&omitted).unwrap()).unwrap(); + let (result, out) = run_cli( + &[ + "config", + "plan", + "--file", + path, + "--target", + target, + "--allow-credential-clear", + ], + config.clone(), + "", + &[], + ) + .await; + result.unwrap(); + assert!(!out.contains(SECRET), "{out}"); + assert_eq!(std::fs::read_to_string(&target_path).unwrap(), original); + let revision = out + .lines() + .find_map(|line| line.strip_prefix("Revision: ")) + .unwrap() + .to_owned(); + let (result, _) = run_cli( + &[ + "config", + "apply", + "--file", + path, + "--target", + target, + "--allow-credential-clear", + "--yes", + ], + config.clone(), + "", + &[], + ) + .await; + assert!(result.unwrap_err().to_string().contains("confirm-high-risk")); + assert_eq!(std::fs::read_to_string(&target_path).unwrap(), original); + let (result, out) = run_cli( + &[ + "config", + "apply", + "--file", + path, + "--target", + target, + "--allow-credential-clear", + "--yes", + "--confirm-high-risk", + &revision, + ], + config, + "", + &[], + ) + .await; + result.unwrap(); + assert!(out.contains("Written and validated"), "{out}"); + assert!(!out.contains(SECRET), "{out}"); + assert!(reload(&dir).await.web_search.brave_api_key.is_none()); + } + } + } + + #[tokio::test] + async fn raw_secret_clear_permission_does_not_confirm_access_changes() { + let (dir, config) = fixture(|config| config.gateway.paired_tokens = vec![SECRET.into()]).await; + let before = stored(&dir); + let mut posted: toml::Value = toml::from_str(std::str::from_utf8(&before).unwrap()).unwrap(); + *posted.get_mut("gateway").unwrap().get_mut("paired_tokens").unwrap() = toml::Value::Array(Vec::new()); + let file = dir.path().join("posted.toml"); + std::fs::write(&file, toml::to_string(&posted).unwrap()).unwrap(); + let (result, out) = run_cli( + &[ + "config", + "apply", + "--file", + file.to_str().unwrap(), + "--allow-credential-clear", + "--yes", + ], + config, + "", + &[], + ) + .await; + assert!(result.unwrap_err().to_string().contains("confirm-high-risk")); + assert!(!out.contains(SECRET), "{out}"); + assert_eq!(stored(&dir), before); + } + + #[tokio::test] + async fn config_apply_names_the_shadowing_fragment_and_target_repairs_it() { + let (dir, config) = fixture(|_| {}).await; + let before = stored(&dir); + let fragments = dir.path().join("config.d"); + std::fs::create_dir_all(&fragments).unwrap(); + let fragment = fragments.join("tools.toml"); + let original_fragment = "[web_search]\nprovider = 'duckduckgo'\n"; + std::fs::write(&fragment, original_fragment).unwrap(); + let mut posted: toml::Value = toml::from_str(std::str::from_utf8(&before).unwrap()).unwrap(); + *posted.get_mut("web_search").unwrap().get_mut("provider").unwrap() = toml::Value::String("brave".into()); + let file = dir.path().join("posted.toml"); + std::fs::write(&file, toml::to_string(&posted).unwrap()).unwrap(); + let path = file.to_str().unwrap(); + for args in [ + vec!["config", "plan", "--file", path], + vec!["config", "apply", "--file", path, "--yes"], + ] { + let (result, out) = run_cli(&args, config.clone(), "", &[]).await; + let error = result.unwrap_err().to_string(); + assert!( + error.contains("web_search.provider is shadowed by config.d/tools.toml; use --target tools.toml"), + "{error}" + ); + assert!(!out.contains("no change"), "{out}"); + assert_eq!(stored(&dir), before); + assert_eq!(std::fs::read_to_string(&fragment).unwrap(), original_fragment); + } + // A valid unrelated edit must not hide a shadowed field or be partly applied. + *posted.get_mut("default_temperature").unwrap() = toml::Value::Float(0.4); + std::fs::write(&file, toml::to_string(&posted).unwrap()).unwrap(); + let (result, _) = run_cli(&["config", "apply", "--file", path, "--yes"], config.clone(), "", &[]).await; + assert!( + result + .unwrap_err() + .to_string() + .contains("shadowed by config.d/tools.toml") + ); + assert_eq!(stored(&dir), before); + assert_eq!(std::fs::read_to_string(&fragment).unwrap(), original_fragment); + // Posting an unchanged base is still legal even though the fragment wins. + std::fs::write(&file, &before).unwrap(); + let (result, _) = run_cli(&["config", "plan", "--file", path], config.clone(), "", &[]).await; + result.unwrap(); + // Follow the exact guidance: the target is a basename and other files stay intact. + std::fs::write(&file, "[web_search]\nprovider = 'brave'\n").unwrap(); + let (result, out) = run_cli( + &["config", "apply", "--file", path, "--target", "tools.toml", "--yes"], + config, + "", + &[], + ) + .await; + result.unwrap(); + assert!(out.contains("Written and validated"), "{out}"); + assert_eq!(stored(&dir), before); + assert_eq!(reload(&dir).await.web_search.provider, "brave"); + } + + #[tokio::test] + async fn stored_deleted_model_settings_can_be_inspected_without_selecting_them() { + let (dir, config) = fixture(|config| { + config.model_settings.insert( + "openai/prx-deleted-model".into(), + config::model_settings::ModelSettings { + level: Some("high".into()), + ..Default::default() + }, + ); + }) + .await; + let before = stored(&dir); + let (result, text) = run_cli(&["models", "settings", "openai/prx-deleted-model"], config, "", &[]).await; + result.unwrap(); + let settings: serde_json::Value = serde_json::from_str(&text).unwrap(); + assert_eq!(settings.get("level").and_then(serde_json::Value::as_str), Some("high")); + assert_eq!(stored(&dir), before); + } + + #[tokio::test] + async fn catalog_lifecycle_status_and_migration_use_the_cli_transaction() { + let (dir, config) = fixture(|config| { + config.default_provider = Some("openai".into()); + config.default_model = Some("gpt-4o".into()); + }) + .await; + let before = stored(&dir); + let (result, text) = run_cli(&["models", "catalog", "status"], config.clone(), "", &[]).await; + result.unwrap(); + let status: serde_json::Value = serde_json::from_str(&text).unwrap(); + let release = providers::catalog::ReleaseCatalog::embedded_ref().unwrap(); + assert_eq!( + status.get("revision").and_then(serde_json::Value::as_str), + Some(release.revision.as_str()) + ); + assert_eq!( + status.get("models").and_then(serde_json::Value::as_u64), + Some(u64::try_from(release.models.len()).unwrap()) + ); + assert_eq!( + status.get("content_sha256").and_then(serde_json::Value::as_str), + Some(release.content_sha256()) + ); + assert_eq!( + status.get("updates").and_then(serde_json::Value::as_str), + Some("releases only") + ); + let (result, text) = run_cli(&["models", "migrate-retired"], config.clone(), "", &[]).await; + result.unwrap(); + assert!(text.contains("gpt-5.6-sol"), "{text}"); + assert_eq!(stored(&dir), before); + let (result, text) = run_cli(&["models", "migrate-retired", "--yes"], config, "", &[]).await; + result.unwrap(); + assert!(text.contains("history record"), "{text}"); + assert_ne!(stored(&dir), before); + assert!(String::from_utf8(stored(&dir)).unwrap().contains("gpt-5.6-sol")); + } + + /// D-085 F-6: `prx models list --operation` and `prx models show` print + /// the service's model read model. + #[tokio::test] + async fn models_list_by_operation_and_show_use_the_service_read_model() { + let (_dir, config) = fixture(|config| { + config.providers.models.push( + toml::from_str( + "provider = \"openrouter\"\nmodel = \"jev-decision-test\"\noperations = [\"decision_endpoint\"]\n", + ) + .expect("test: declaration"), + ); + config.providers.models.push( + toml::from_str("provider = \"openai\"\nmodel = \"gpt-4o\"\noperations = [\"chat\"]\n") + .expect("test: declaration"), + ); + }) + .await; + let (result, out) = run_cli( + &["models", "list", "--operation", "chat", "--executable"], + config.clone(), + "", + &[], + ) + .await; + result.expect("test: list"); + assert!(out.contains("openai gpt-4o [chat] (operator declaration)"), "{out}"); + assert!( + out.contains("openai gpt-5.6 [chat] (embedded release catalog)"), + "the real CLI listing must include release-catalog models: {out}" + ); + assert!(!out.contains("jev-decision-test"), "{out}"); + let (result, out) = run_cli(&["models", "show", "openrouter", "jev-decision-test"], config, "", &[]).await; + result.expect("test: show"); + assert!(out.contains("Evidence: operator declaration\n"), "{out}"); + assert!(out.contains(" chat: unsupported"), "{out}"); + } + + /// RED before PMME-g (D-088 C-6): `routes list` and `config agents list` + /// redacted only credential-named query parameters, so `?sig=` came + /// back verbatim. + #[tokio::test] + async fn listings_redact_every_url_query_value() { + const PROVIDER: &str = "custom:https://llm.example/v1?sig=sentinel-listing-sig"; + let (_dir, config) = fixture(|config| { + config.model_routes = vec![config::ModelRouteConfig { + settings: Default::default(), + hint: "fast".into(), + provider: PROVIDER.into(), + model: "m".into(), + api_key: None, + credential_ref: None, + }]; + config.agents.insert( + "coder".into(), + serde_json::from_value(serde_json::json!({ "provider": PROVIDER, "model": "m" })).expect("test: agent"), + ); + }) + .await; + for args in [&["routes", "list"][..], &["config", "agents", "list"][..]] { + let (result, out) = run_cli(args, config.clone(), "", &[]).await; + result.expect("test: list"); + assert!( + out.contains("custom:https://llm.example/v1?sig=[redacted]"), + "{args:?}: {out}" + ); + assert!(!out.contains("sentinel-listing-sig"), "{args:?}: {out}"); + } + } + + /// E-3: `prx config rollback --last` restores the before-image. + #[tokio::test] + async fn rollback_last_restores_the_before_image() { + let (dir, config) = fixture(|_| {}).await; + let before = stored(&dir); + let (result, out) = run_cli( + &["routes", "add", "fast", "openai", "gpt-5.6", "--yes"], + config, + "", + &[], + ) + .await; + result.expect("test: apply"); + assert!(out.contains("Written and validated (history record "), "{out}"); + assert!(out.contains("activation deferred to the daemon"), "{out}"); + assert!(!out.contains("Applied"), "{out}"); + assert_ne!(stored(&dir), before); + + let (result, out) = run_cli(&["config", "history"], reload(&dir).await, "", &[]).await; + result.expect("test: history"); + assert_eq!(out.lines().count(), 1, "{out}"); + // RED before PMME-f (D-085 F-4): recorded `Activated`, although the + // CLI cannot confirm what a running daemon does with the change. + assert!(out.contains("Cli ActivationDeferred"), "{out}"); + + // Without --yes nothing is written. + let changed = stored(&dir); + let (result, out) = run_cli(&["config", "rollback", "--last"], reload(&dir).await, "", &[]).await; + result.expect("test: dry rollback"); + assert!(out.contains(" + model_routes[0].hint = \"fast\"\n"), "{out}"); + assert!( + out.ends_with("Dry run: nothing was written. Roll back with --yes\n"), + "{out}" + ); + assert_eq!(stored(&dir), changed); + + let (result, out) = run_cli(&["config", "rollback", "--last", "--yes"], reload(&dir).await, "", &[]).await; + result.expect("test: rollback"); + assert!(out.contains("Rolled back on disk (history record "), "{out}"); + assert_eq!(stored(&dir), before, "the before-image is restored byte for byte"); + + let (result, out) = run_cli(&["config", "status"], reload(&dir).await, "", &[]).await; + result.expect("test: status"); + assert!(out.contains("History: 2 records"), "{out}"); + assert!( + out.contains("activation deferred to the daemon (not confirmed here)"), + "{out}" + ); + } + + #[tokio::test] + async fn a_confirmed_history_rollback_retains_the_existing_retired_default() { + let (dir, config) = fixture(|config| { + config.default_provider = Some("openai".into()); + config.default_model = Some("gpt-4o".into()); + }) + .await; + let before = stored(&dir); + let (result, _) = run_cli( + &["models", "default", "set", "openai", "gpt-5.6", "--yes"], + config, + "", + &[], + ) + .await; + result.unwrap(); + assert_ne!(stored(&dir), before); + let (result, _) = run_cli(&["config", "rollback", "--last", "--yes"], reload(&dir).await, "", &[]).await; + result.unwrap(); + assert_eq!(stored(&dir), before); + let restored = reload(&dir).await; + assert_eq!(restored.default_model.as_deref(), Some("gpt-4o")); + assert!( + openprx::config::manage::lifecycle::warnings(&restored) + .unwrap() + .iter() + .any(|warning| warning.contains("retired")) + ); + } + + /// A high-risk change applies only with a confirmation naming the + /// revision the plan reported (D-049 B). + #[tokio::test] + async fn a_high_risk_change_needs_the_confirmed_revision() { + let (dir, config) = fixture(|_| {}).await; + let before = stored(&dir); + let args = [ + "providers", + "update", + "openai", + "--api-url", + "https://proxy.example/v1", + "--yes", + ]; + let (result, out) = run_cli(&args, config.clone(), "", &[]).await; + let error = result.expect_err("test: confirmation required").to_string(); + assert!( + out.contains("High risk because the change:\n - changes the provider endpoint at api_url"), + "{out}" + ); + let revision = error + .rsplit("--confirm-high-risk ") + .next() + .expect("test: the refusal names the revision") + .trim() + .to_string(); + assert!(!revision.is_empty(), "{error}"); + assert_eq!(stored(&dir), before); + + let mut wrong = args.to_vec(); + wrong.extend(["--confirm-high-risk", "0000"]); + let (result, _) = run_cli(&wrong, config.clone(), "", &[]).await; + assert!(result.is_err()); + assert_eq!(stored(&dir), before); + + let mut confirmed = args.to_vec(); + confirmed.extend(["--confirm-high-risk", revision.as_str()]); + let (result, out) = run_cli(&confirmed, config, "", &[]).await; + result.unwrap_or_else(|error| panic!("test: confirmed: {error}")); + assert!(out.contains("Written and validated (history record "), "{out}"); + assert!(out.contains("activation deferred to the daemon"), "{out}"); + assert!(!out.contains("Applied"), "{out}"); + assert!( + String::from_utf8_lossy(&stored(&dir)).contains("https://proxy.example/v1"), + "the endpoint is written" + ); + } + + /// `prx config plan --file` goes through the same transaction as the raw + /// editor: a plaintext key at an encrypted slot is refused, and neither + /// the refusal nor a parse error quotes the posted secret. + #[tokio::test] + async fn a_raw_file_plan_never_echoes_a_posted_secret() { + let (dir, config) = fixture(|_| {}).await; + let posted = dir.path().join("posted.toml"); + let mut text = String::from_utf8(stored(&dir)).expect("test: utf-8"); + text = text.replacen( + "default_model = \"gpt-4o\"", + &format!("api_key = \"{SECRET}\"\ndefault_model = \"gpt-4o\""), + 1, + ); + std::fs::write(&posted, &text).expect("test: write"); + let path = posted.to_str().expect("test: path"); + let (result, out) = run_cli(&["config", "plan", "--file", path], config.clone(), "", &[]).await; + let error = result.expect_err("test: plaintext refused").to_string(); + assert!(error.contains("api_key"), "the refusal names the path: {error}"); + assert!(!error.contains(SECRET) && !out.contains(SECRET), "{error}\n{out}"); + + std::fs::write(&posted, format!("api_key = \"{SECRET}\n")).expect("test: write"); + let (result, _) = run_cli(&["config", "plan", "--file", path], config, "", &[]).await; + let error = result.expect_err("test: malformed").to_string(); + assert!(error.starts_with("Invalid TOML content at line 1"), "{error}"); + assert!(!error.contains(SECRET), "{error}"); + } + #[tokio::test] + async fn cli_model_settings_plan_inspect_and_atomic_default_selection_use_pmm() { + let (dir, config) = fixture(|_| {}).await; + let before = stored(&dir); + let (result, out) = run_cli(&["models", "levels", "openai/gpt-5.6"], config.clone(), "", &[]).await; + result.unwrap(); + assert!(out.contains("xhigh")); + assert_eq!(stored(&dir), before); + let (result, out) = run_cli( + &["models", "settings", "openai/gpt-5.6", "--level", "high"], + config.clone(), + "", + &[], + ) + .await; + result.unwrap(); + assert!(out.contains("model_settings")); + assert_eq!(stored(&dir), before); + let (result, out) = run_cli( + &[ + "models", + "default", + "set", + "openai", + "gpt-5.6", + "--level", + "high", + "--set", + "reasoning_effort=low", + "--yes", + ], + config, + "", + &[], + ) + .await; + result.unwrap(); + assert!(out.contains("history record")); + let config = reload(&dir).await; + assert_eq!(config.default_model.as_deref(), Some("gpt-5.6")); + let settings = config.model_settings.get("openai/gpt-5.6").unwrap(); + assert_eq!(settings.level.as_deref(), Some("high")); + assert_eq!( + settings.overrides.get("reasoning_effort"), + Some(&serde_json::json!("low")) + ); + let committed = stored(&dir); + let (result, _) = run_cli( + &[ + "models", + "settings", + "openai/gpt-5.6", + "--set", + "max_output_tokens=0", + "--yes", + ], + config, + "", + &[], + ) + .await; + assert!(result.is_err()); + assert_eq!(stored(&dir), committed); + } +} + +fn parse_model_settings( + level: Option, + overrides: Vec, +) -> Result { + let mut settings = config::model_settings::ModelSettings { + level, + ..Default::default() + }; + for entry in overrides { + let (name, value) = entry + .split_once('=') + .ok_or_else(|| anyhow::anyhow!("use --set name=value"))?; + if providers::catalog::ModelParameter::parse(name).is_none() { + anyhow::bail!("unknown model parameter"); + } + let value = serde_json::from_str(value).unwrap_or_else(|_| serde_json::Value::String(value.to_owned())); + if settings.overrides.insert(name.to_owned(), value).is_some() { + anyhow::bail!("duplicate model parameter"); + } + } + Ok(settings) +} diff --git a/src/runtime/mode.rs b/src/runtime/mode.rs index dfc85ff48..b2d2e6500 100644 --- a/src/runtime/mode.rs +++ b/src/runtime/mode.rs @@ -672,6 +672,7 @@ pub async fn dispatch(command: Commands, config: Config) -> Result<()> { Ok(()) } management @ (ConfigCommands::Plan { .. } + | ConfigCommands::Autonomy { .. } | ConfigCommands::BraveKey { .. } | ConfigCommands::Apply { .. } | ConfigCommands::History { .. } diff --git a/src/tools/sessions_send.rs b/src/tools/sessions_send.rs index c2b046847..7970631af 100644 --- a/src/tools/sessions_send.rs +++ b/src/tools/sessions_send.rs @@ -122,7 +122,7 @@ impl Tool for SessionsSendTool { return "Send an ordinary message using 'to' to a logical session, including an idle child. \ Use its exact session_key (retain the spawn: prefix), or 'parent' from a child. \ An object target is {session, instance?, owner?, agent?}; local defaults use the caller's instance/owner and main agent. \ - A remote target needs the full pinned SPIFFE instance ID and receiving owner's session. \ + A remote target needs the full pinned SPIFFE instance ID and session; omit owner, which the receiver supplies through mTLS pins. \ Use 'run_id' only to steer a currently running execution. Supply exactly one of 'to' or 'run_id', plus 'message'."; } "Send a message to a running sub-agent session to redirect or update its instructions. \ @@ -135,7 +135,7 @@ impl Tool for SessionsSendTool { if self.mailbox.is_some() || self.messaging.is_some() { return json!({"type":"object","additionalProperties":false, "properties":{"run_id":{"type":"string","minLength":1,"description":"Live execution ID for steering only; omit when sending an ordinary message with to."}, - "to":{"description":"Exact logical session_key (including spawn:), parent alias, or address object. Remote instance is a full pinned SPIFFE ID; owner/session belong to the receiver.","oneOf":[crate::messaging::send::target_schema(),{"type":"string","minLength":1}]}, + "to":{"description":"Exact logical session_key (including spawn:), parent alias, or address object. Remote instance is a full pinned SPIFFE ID; omit owner for remote sends; it is learned through mTLS pins.","oneOf":[crate::messaging::send::target_schema(),{"type":"string","minLength":1}]}, "message":{"type":"string","minLength":1}},"required":["message"]}); } json!({ diff --git a/tests/architecture_boundaries/config.rs b/tests/architecture_boundaries/config.rs index 3abb9d31f..cf2011cdd 100644 --- a/tests/architecture_boundaries/config.rs +++ b/tests/architecture_boundaries/config.rs @@ -385,8 +385,12 @@ pub(super) fn config_writes_route_through_the_transaction_layer() { /// renders no plan of its own. #[test] fn the_management_cli_goes_through_the_management_service() { - let source = fs::read_to_string(repository_root().join("src/runtime/manage_cli.rs")) - .unwrap_or_else(|error| panic!("read src/runtime/manage_cli.rs: {error}")); + let source = [ + "src/runtime/manage_cli/section_1.rs", + "src/runtime/manage_cli/section_2.rs", + ] + .map(|path| fs::read_to_string(repository_root().join(path)).unwrap_or_else(|error| panic!("read {path}: {error}"))) + .join("\n"); let production = production_part(&source); // The CLI does not run the configuration's runtime, so it records what // it applies as deferred to the daemon (D-085 F-4). diff --git a/tests/architecture_boundaries/helpers.rs b/tests/architecture_boundaries/helpers.rs index fd3ef8b9f..becf50049 100644 --- a/tests/architecture_boundaries/helpers.rs +++ b/tests/architecture_boundaries/helpers.rs @@ -147,6 +147,8 @@ pub(super) fn read_source(path: &Path) -> String { ("src/memory/sqlite/tests/mailbox.rs", "mailbox/section_1.rs"), ("src/memory/sqlite/tests/mailbox.rs", "mailbox/section_2.rs"), ("src/memory/sqlite/tests/mailbox.rs", "mailbox/section_3.rs"), + ("src/runtime/manage_cli.rs", "manage_cli/section_1.rs"), + ("src/runtime/manage_cli.rs", "manage_cli/section_2.rs"), ("src/tools/execution.rs", "execution/section_1.rs"), ("src/tools/execution.rs", "execution/section_2.rs"), ("src/tools/execution.rs", "execution/section_3.rs"), From 4997fc5fb5e1bca47f801d2a911c9b10fcb4f6db Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 22:01:35 +0400 Subject: [PATCH 0024/1567] fix(chat): distinguish live daemon delivery from next-turn fallback --- src/chat/message_inbox.rs | 42 ++++++++++++++++++++++++++++++++++++++ src/chat/run/event_pump.rs | 7 +++---- 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/src/chat/message_inbox.rs b/src/chat/message_inbox.rs index 99000664e..e5f5dd38f 100644 --- a/src/chat/message_inbox.rs +++ b/src/chat/message_inbox.rs @@ -26,6 +26,48 @@ impl ChatInbox { pending: Default::default(), })) } + /// Other local processes notify through durable storage while the owning + /// gateway is live. Without it, a human turn is the next polling boundary. + pub(super) async fn wake_from_daemon(&mut self, config: &crate::config::Config) { + let Ok(path) = crate::runtime::host_bootstrap::runtime_path(config) else { + return; + }; + let port = crate::runtime::blocking::spawn_blocking(move || { + use std::io::Read as _; + const MAX_RUNTIME_BYTES: u64 = 4096; + let mut bytes = Vec::new(); + std::fs::File::open(path) + .ok()? + .take(MAX_RUNTIME_BYTES + 1) + .read_to_end(&mut bytes) + .ok()?; + if bytes.len() > MAX_RUNTIME_BYTES as usize { + return None; + } + let record: serde_json::Value = serde_json::from_slice(&bytes).ok()?; + let url = reqwest::Url::parse(record.get("api_base")?.as_str()?).ok()?; + if url.scheme() != "http" || url.host_str() != Some("127.0.0.1") { + return None; + } + url.port() + }) + .await + .ok() + .flatten(); + if let Some(port) = port + && matches!( + tokio::time::timeout( + std::time::Duration::from_millis(200), + tokio::net::TcpStream::connect((std::net::Ipv4Addr::LOCALHOST, port)) + ) + .await, + Ok(Ok(_)) + ) + { + self.wake(); + } + } + pub(super) const fn wake(&mut self) { self.wake = true; } diff --git a/src/chat/run/event_pump.rs b/src/chat/run/event_pump.rs index f0e37e7fb..75f5dba6a 100644 --- a/src/chat/run/event_pump.rs +++ b/src/chat/run/event_pump.rs @@ -526,10 +526,9 @@ loop { continue; } _ = sessions_tick.tick() => { - // A dedicated mTLS listener may run in another process. Its durable - // mailbox writes cannot signal this process's in-memory inbox. - if config.a2a.messaging_enabled && let Some(inbox) = message_inbox.as_mut() { - inbox.wake(); + // Local daemon delivery works independently of peer messaging. + if let Some(inbox) = message_inbox.as_mut() { + inbox.wake_from_daemon(&config).await; } // 1) Summary reflow: surface each newly-finished session once, // carrying its `#N` + status (plan §v1b). No auto-focus. From f797820dbc3b0b0abaf4f9edf9877729fdaf03dd Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 22:18:25 +0400 Subject: [PATCH 0025/1567] fix(messaging): retain idle notification slots across worker continuation --- src/messaging/worker.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/messaging/worker.rs b/src/messaging/worker.rs index 2444afe0d..557af2864 100644 --- a/src/messaging/worker.rs +++ b/src/messaging/worker.rs @@ -48,7 +48,10 @@ impl WorkerMailboxFactory for WorkerMailboxes { &manifest.session_scope_key, manifest.agent_id.as_deref().unwrap_or("main"), ); - let inbox = self.runtime.register(address.clone())?; + // An idle child's TUI or gateway may already own its notification slot. + // The worker polls the same durable mailbox under the execution guard; + // it must not replace that registration when continuing the child. + let inbox = self.runtime.register_backend(address.clone())?; let scope = self.runtime.resolve_scope(&address)?; let execution = self .runtime From b1ddae10f66231e6e607013622abf30b4cd83886 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 22:21:05 +0400 Subject: [PATCH 0026/1567] fix(chat): bind child compaction to its durable transcript scope --- src/chat/child_focus.rs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/chat/child_focus.rs b/src/chat/child_focus.rs index 6c29e2f47..48e85d9fc 100644 --- a/src/chat/child_focus.rs +++ b/src/chat/child_focus.rs @@ -315,6 +315,25 @@ impl ChildFocus { } "/compact" => { let provider = ctx.provider(&record)?; + let runtime = crate::messaging::runtime::MessagingRuntime::for_config(&ctx.generation.effective)?; + let address = runtime.address(&record.owner, &record.session_key, &record.agent); + let scope = runtime.resolve_scope(&address)?; + let mut envelope = crate::runtime::envelope::RuntimeEnvelope::sessions_spawn( + &record.workspace, + &record.session_key, + uuid::Uuid::new_v4().to_string(), + ); + envelope.owner_id = Some(record.owner.clone()); + envelope.owner_isolated = true; + envelope.agent_id = Some(record.agent.clone()); + envelope.agent_partition = Some(runtime.store.partition(&scope)?); + let audit = crate::agent::document_ingest::DocumentIngestRuntime::from_envelope( + Arc::clone(ctx.memory), + &envelope, + ) + .bound_to_newest_user_input() + .await? + .context("child compaction requires a durable transcript")?; let mut history: Vec<_> = turns .iter() .map(|turn| { @@ -332,7 +351,7 @@ impl ChildFocus { provider.as_ref(), &record.model, &ctx.generation.effective.agent.compaction, - None, + Some(&audit), crate::agent::compaction::MANUAL_COMPACT_TRIGGER, ) .await? From 9b7d9a7b6b3bdfe5ab90e393361563f750e66bdb Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 22:27:47 +0400 Subject: [PATCH 0027/1567] fix(messaging): confirm worker publication and validate inherited child scope --- src/memory/sqlite/mailbox/pin.rs | 5 ++- src/messaging/mailbox.rs | 6 ++- src/messaging/worker.rs | 60 +++++++++++++++++++-------- src/session_worker/protocol.rs | 5 +++ src/session_worker/runner/steering.rs | 9 +++- 5 files changed, 64 insertions(+), 21 deletions(-) diff --git a/src/memory/sqlite/mailbox/pin.rs b/src/memory/sqlite/mailbox/pin.rs index 6f0752209..35fe519b9 100644 --- a/src/memory/sqlite/mailbox/pin.rs +++ b/src/memory/sqlite/mailbox/pin.rs @@ -157,7 +157,10 @@ pub(in crate::memory::sqlite) fn check_scope( return Err(MailboxError::StaleIncarnation); } if live { - let latest:i64=conn.query_row("SELECT max(generation) FROM agent_scopes WHERE workspace_id=?1 AND owner_id=?2 AND agent_key=?3 AND incarnation=?4 AND session_key IS ?5",params![scope.workspace_id,scope.owner_id,key,scope.incarnation.to_string(),row.1],|r|r.get(0)).map_err(storage_error)?; + // A named child may inherit its parent's storage partition. The + // child identity was verified above; its generation belongs to the + // stored partition, not the presentation agent on its address. + let latest:i64=conn.query_row("SELECT max(generation) FROM agent_scopes WHERE workspace_id=?1 AND owner_id=?2 AND agent_key=?3 AND incarnation=?4 AND session_key IS ?5",params![scope.workspace_id,scope.owner_id,row.0,scope.incarnation.to_string(),row.1],|r|r.get(0)).map_err(storage_error)?; if row.2 != "active" || latest != scope.generation || row.3.as_deref() == Some("erased") { return Err(MailboxError::StaleIncarnation); } diff --git a/src/messaging/mailbox.rs b/src/messaging/mailbox.rs index 39f2184c2..1aad9ffe5 100644 --- a/src/messaging/mailbox.rs +++ b/src/messaging/mailbox.rs @@ -22,6 +22,8 @@ pub const MAX_BYTES: i64 = 64 * 1024 * 1024; /// Stable refusals, shared by store, IPC and dormant send adapters. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum MailboxError { + #[error("{0}")] + PublicationRefused(String), #[error("peer_unknown")] PeerUnknown, #[error("peer_not_allowed")] @@ -232,7 +234,7 @@ pub struct MailboxReceipt { /// Publishing returns status only. Payloads leave the store exclusively /// through scoped pending-outbox leases, never through a status replay. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct MailboxPublished { pub row_id: i64, pub message_id: Uuid, @@ -242,7 +244,7 @@ pub struct MailboxPublished { pub ack_state: Option, pub error: Option, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum MailboxSendState { Pending, Sent, diff --git a/src/messaging/worker.rs b/src/messaging/worker.rs index 557af2864..d651052d3 100644 --- a/src/messaging/worker.rs +++ b/src/messaging/worker.rs @@ -120,12 +120,18 @@ impl WorkerMailboxFactory for WorkerMailboxes { Some(WorkerOutputFrame::Message { envelope }) => { // Only the target and data are wire input. Sender, chain, // pin, sequence and authority are reconstructed here. - async { + let message_id = envelope.id; + let result = async { let to = runtime.alias(sender.source(), &serde_json::to_value(&envelope.to)?)?; let text = String::from_utf8(envelope.body.bytes)?; - sender.send_with_id(to, text, envelope.body.mime, envelope.id).await?; - Ok(()) - }.await + Ok::<_, anyhow::Error>(sender.send_with_id(to, text, envelope.body.mime, message_id).await?) + }.await.map_err(|error| { + // Resolver and store errors contain typed causes only. + error.downcast_ref::() + .map_or_else(|| "mailbox_storage_error".to_owned(), ToString::to_string) + }); + controls.send(WorkerControlFrame::MessageResult { message_id, result }) + .await.context("worker control closed") } Some(WorkerOutputFrame::Ack { message_id, state: DeliveryState::Consumed }) => { if !runtime.ready_capacity(&target) {continue;} @@ -193,6 +199,24 @@ impl WorkerMailboxFactory for WorkerMailboxes { pub(crate) struct WorkerSender { pub(crate) address: super::SessionAddr, } +type PublicationResult = Result; +type Publications = parking_lot::Mutex>>; +fn publications() -> &'static Publications { + static PENDING: std::sync::OnceLock = std::sync::OnceLock::new(); + PENDING.get_or_init(Default::default) +} +struct PendingPublication(uuid::Uuid); +impl Drop for PendingPublication { + fn drop(&mut self) { + publications().lock().remove(&self.0); + } +} +pub(crate) fn resolve_publication(id: uuid::Uuid, result: PublicationResult) { + let sender = publications().lock().remove(&id); + if let Some(sender) = sender { + let _ = sender.send(result); + } +} #[async_trait::async_trait] impl MailboxSender for WorkerSender { fn source(&self) -> &super::SessionAddr { @@ -204,12 +228,18 @@ impl MailboxSender for WorkerSender { text: String, mime: String, ) -> super::mailbox::MailboxResult { - use super::{ - IdempotencyKey, MessageBody, MessageKind, PrxMessage, RecipientPin, - mailbox::{MailboxError, MailboxPublished, MailboxSendState}, - }; + use super::{IdempotencyKey, MessageBody, MessageKind, PrxMessage, RecipientPin, mailbox::MailboxError}; super::mailbox::validate_body(&mime, text.as_bytes())?; let id = uuid::Uuid::new_v4(); + let (reply, received) = tokio::sync::oneshot::channel(); + { + let mut pending = publications().lock(); + if pending.len() >= 64 { + return Err(MailboxError::QueueFull); + } + pending.insert(id, reply); + } + let _pending = PendingPublication(id); let message = PrxMessage { id, idempotency: IdempotencyKey::parse(&id.to_string()).map_err(|_| MailboxError::InvalidMetadata)?, @@ -240,14 +270,10 @@ impl MailboxSender for WorkerSender { envelope: Box::new(message), }) .map_err(|_| MailboxError::Storage)?; - Ok(MailboxPublished { - row_id: 0, - message_id: id, - stream_id: uuid::Uuid::nil(), - seq: 0, - state: MailboxSendState::Pending, - ack_state: None, - error: None, - }) + tokio::time::timeout(std::time::Duration::from_secs(30), received) + .await + .map_err(|_| MailboxError::Storage)? + .map_err(|_| MailboxError::Storage)? + .map_err(MailboxError::PublicationRefused) } } diff --git a/src/session_worker/protocol.rs b/src/session_worker/protocol.rs index f6a562820..2a7486512 100644 --- a/src/session_worker/protocol.rs +++ b/src/session_worker/protocol.rs @@ -308,6 +308,11 @@ fn config_source_generation_once(config_dir: &Path) -> anyhow::Result { #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "kind", rename_all = "snake_case")] pub enum WorkerControlFrame { + /// Durable publication result from the parent-owned mailbox broker. + MessageResult { + message_id: uuid::Uuid, + result: Result, + }, /// Inject an operator message into the worker's running conversation. Steer { message: String }, /// Parent-to-worker Data envelope (MSG-5). Types only in FOUNDATION. diff --git a/src/session_worker/runner/steering.rs b/src/session_worker/runner/steering.rs index 91cb5c6f8..3a0286e10 100644 --- a/src/session_worker/runner/steering.rs +++ b/src/session_worker/runner/steering.rs @@ -79,7 +79,11 @@ pub(super) fn spawn_stdin_control_reader( auth.verify(value) .map_err(|e| serde_json::Error::io(std::io::Error::other(e))) }) - } else if value.get("kind").and_then(|v| v.as_str()) == Some("message") && auth.is_some() { + } else if matches!( + value.get("kind").and_then(|v| v.as_str()), + Some("message" | "message_result") + ) && auth.is_some() + { Err(serde_json::Error::io(std::io::Error::other("unsigned mailbox frame"))) } else { Ok(value) @@ -91,6 +95,9 @@ pub(super) fn spawn_stdin_control_reader( continue; }; match frame { + WorkerControlFrame::MessageResult { message_id, result } => { + crate::messaging::worker::resolve_publication(message_id, result); + } WorkerControlFrame::Steer { message } => { if steer_tx.blocking_send(message).is_err() { break; From da39dae498fc67abc1a71e9c53e4d2d01cea9be8 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 22:33:51 +0400 Subject: [PATCH 0028/1567] fix(messaging): refuse self cycles before parent lookup --- src/memory/sqlite/mailbox/receipt.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/memory/sqlite/mailbox/receipt.rs b/src/memory/sqlite/mailbox/receipt.rs index 6e92f0b4e..3b957243b 100644 --- a/src/memory/sqlite/mailbox/receipt.rs +++ b/src/memory/sqlite/mailbox/receipt.rs @@ -240,8 +240,11 @@ pub(super) fn derive_chain( message.ancestry.clear(); return Ok(()); }; + if parent == message.id { + return Err(MailboxError::ChainDepth); + } let (depth, mut ancestry) = parent_chain(conn, workspace, owner, parent)?; - if ancestry.contains(&message.id) || parent == message.id { + if ancestry.contains(&message.id) { return Err(MailboxError::ChainDepth); } ancestry.push(parent); From 55f35cac58459ee1f50a15bcb9fb090e7cbda2fe Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 22:36:46 +0400 Subject: [PATCH 0029/1567] fix(chat): retain ambiguous recent turns during child compaction --- src/chat/child_focus.rs | 47 +++++++++++++++++++++++++++++------------ 1 file changed, 34 insertions(+), 13 deletions(-) diff --git a/src/chat/child_focus.rs b/src/chat/child_focus.rs index 48e85d9fc..042b39a2f 100644 --- a/src/chat/child_focus.rs +++ b/src/chat/child_focus.rs @@ -344,18 +344,37 @@ impl ChildFocus { None, turns.iter().map(|turn| (turn.role.as_str(), turn.content.as_str())), ); - if let crate::agent::compaction::CompactionBuild::Patch(patch) = - crate::agent::compaction::build_configurable_compaction_patch_with_source_history( - &history, - &source, - provider.as_ref(), - &record.model, - &ctx.generation.effective.agent.compaction, - Some(&audit), - crate::agent::compaction::MANUAL_COMPACT_TRIGGER, - ) - .await? - { + let mut compaction = ctx.generation.effective.agent.compaction.clone(); + let mut built = None; + // Steering segments can have distinct run provenance. Keep + // more recent turns rather than invent an exact handoff for + // an ambiguous cold window. Every attempted patch still + // goes through the normal transcript provenance checks. + const MAX_CHILD_COMPACTION_BOUNDARIES: usize = 16; + for _ in 0..MAX_CHILD_COMPACTION_BOUNDARIES { + if let crate::agent::compaction::CompactionBuild::Patch(patch) = + crate::agent::compaction::build_configurable_compaction_patch_with_source_history( + &history, + &source, + provider.as_ref(), + &record.model, + &compaction, + Some(&audit), + crate::agent::compaction::MANUAL_COMPACT_TRIGGER, + ) + .await? + { + built = Some(patch); + break; + } + if compaction.mode != crate::config::AgentCompactionMode::Switch + || compaction.keep_recent_messages >= history.len() + { + break; + } + compaction.keep_recent_messages = compaction.keep_recent_messages.saturating_add(2); + } + if let Some(patch) = built { crate::agent::compaction::apply_compaction_patch_exact(&mut history, &patch)?; turns = history .into_iter() @@ -366,7 +385,9 @@ impl ChildFocus { }) .collect(); } else { - return Ok(Some("Child context has no older complete turn to compact.".into())); + return Ok(Some( + "Child compaction unavailable: no older complete window has exact durable transcript provenance. Context retained.".into(), + )); } } _ => {} From 430bc754f0f521524bd0f10ca747f4a8b1e0eb48 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 22:39:47 +0400 Subject: [PATCH 0030/1567] fix(messaging): bind mailbox process admission to the persisted config revision --- src/config/generation/section_1.rs | 9 +++++++++ src/runtime/mailbox_child/publication.rs | 2 +- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/config/generation/section_1.rs b/src/config/generation/section_1.rs index 5411c9409..1f34fb90f 100644 --- a/src/config/generation/section_1.rs +++ b/src/config/generation/section_1.rs @@ -179,6 +179,15 @@ impl ProcessGenerationBinding { } impl ConfigGeneration { + /// Bind a freshly loaded mailbox-child configuration to the disk revision + /// that a relaunched process worker must verify. Its effective snapshot is + /// still sealed independently by `bind_process`. + pub(crate) fn for_mailbox_child(config: &Config) -> anyhow::Result> { + let mut generation = Self::for_child(config)?.as_ref().clone(); + generation.source_revision = ConfigSourceRevision::from_config(config)?; + Ok(Arc::new(generation)) + } + /// Pin an ordinary child without startup globals or disk reloads. pub(crate) fn for_child(config: &Config) -> anyhow::Result> { let mut value = serde_json::to_value((&config.workspace_dir, &config.config_path, config))?; diff --git a/src/runtime/mailbox_child/publication.rs b/src/runtime/mailbox_child/publication.rs index 1e11e3431..332f89439 100644 --- a/src/runtime/mailbox_child/publication.rs +++ b/src/runtime/mailbox_child/publication.rs @@ -8,7 +8,7 @@ pub(super) fn fresh( agent: &str, ) -> anyhow::Result> { use crate::decision_engine::prediction::factory::{DecisionBackendFactory, FactoryDeps}; - let generation = crate::config::ConfigGeneration::for_child(config)?; + let generation = crate::config::ConfigGeneration::for_mailbox_child(config)?; let provider_catalog = crate::providers::selection::catalog_for(config); let security = Arc::new(crate::security::SecurityPolicy { autonomy: level, From c7ee0526109e03bda36de1160372347287797daa Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 22:46:22 +0400 Subject: [PATCH 0031/1567] fix(messaging): verify adopted mailbox input across process continuation --- src/chat/child_focus.rs | 4 +- src/memory/sqlite/mailbox/local_runtime.rs | 27 +++++++++ .../child_source/operator_process_input.rs | 59 ++++++++++++++++--- src/runtime/child_source/parent.rs | 19 +++++- 4 files changed, 100 insertions(+), 9 deletions(-) diff --git a/src/chat/child_focus.rs b/src/chat/child_focus.rs index 042b39a2f..d767604ae 100644 --- a/src/chat/child_focus.rs +++ b/src/chat/child_focus.rs @@ -325,7 +325,9 @@ impl ChildFocus { ); envelope.owner_id = Some(record.owner.clone()); envelope.owner_isolated = true; - envelope.agent_id = Some(record.agent.clone()); + // Unnamed child transcript rows carry no presentation + // agent id. The verified partition already confines reads. + envelope.agent_id = (record.agent != "main").then(|| record.agent.clone()); envelope.agent_partition = Some(runtime.store.partition(&scope)?); let audit = crate::agent::document_ingest::DocumentIngestRuntime::from_envelope( Arc::clone(ctx.memory), diff --git a/src/memory/sqlite/mailbox/local_runtime.rs b/src/memory/sqlite/mailbox/local_runtime.rs index f396f68c9..e167003a4 100644 --- a/src/memory/sqlite/mailbox/local_runtime.rs +++ b/src/memory/sqlite/mailbox/local_runtime.rs @@ -6,6 +6,33 @@ use crate::messaging::{CausalChain, SessionAddr}; use rusqlite::{OptionalExtension, Transaction, TransactionBehavior, params}; impl SqliteMailbox { + /// Recheck a sealed process launch against the still-live adopted input. + pub(crate) fn validate_adopted_input( + &self, + workspace: &str, + target: &SessionAddr, + event: uuid::Uuid, + text: &str, + message: uuid::Uuid, + ) -> MailboxResult<()> { + let scope = self.session_scope(workspace, target, false)?; + let receipt = { + let writer = self.memory.pool.write(); + let id: i64 = writer.query_row( + "SELECT id FROM prx_mailbox_receipts WHERE workspace_id=?1 AND owner_id=?2 AND ma_scope_id=?3 AND message_id=?4", + params![workspace,target.owner,scope.scope_id.to_string(),message.as_bytes().as_slice()], + |row|row.get(0), + ).map_err(storage_error)?; + super::receipt::load(&writer, id)?.result(&writer)? + }; + if receipt.state != crate::messaging::DeliveryState::Consumed + || receipt.adopted_message_event_id != Some(event) + || receipt.chain.depth >= 8 + { + return Err(MailboxError::InvalidMetadata); + } + self.validate_input(workspace, target, event, text, message, &receipt) + } pub(crate) fn partition( &self, scope: &crate::messaging::mailbox::MailboxScope, diff --git a/src/runtime/child_source/operator_process_input.rs b/src/runtime/child_source/operator_process_input.rs index 8e3d7c64d..36126387b 100644 --- a/src/runtime/child_source/operator_process_input.rs +++ b/src/runtime/child_source/operator_process_input.rs @@ -34,20 +34,65 @@ pub(crate) async fn restore_input( .find_owned_message_event(fabric.workspace_id(), parent_source.owner_id(), id) .await? .context("operator worker parent event is unavailable")?; + let mailbox = parent_source.mailbox_child_source_id(); + if let Some(message) = mailbox { + anyhow::ensure!( + event.source.as_str() == "prx_mailbox" + && event.session_key.as_deref() == Some(worker.session_scope_key.as_str()) + && event.content == parent_source.routing_input(), + "mailbox worker adopted input differs from signed source" + ); + let config = std::sync::Arc::clone(&snapshots.generation.effective); + let parent = parent_source.clone(); + let session = worker.session_scope_key.clone(); + let agent = worker.agent_id.clone().unwrap_or_else(|| "main".to_owned()); + let run = worker.run_id.clone(); + let adopted = uuid::Uuid::parse_str(id)?; + let memory = fabric.memory(); + crate::runtime::blocking::spawn_blocking(move || { + let runtime = crate::messaging::runtime::MessagingRuntime::for_config(&config)?; + let target = runtime.address(parent.owner_id(), &session, &agent); + runtime.store.validate_adopted_input( + parent.workspace_id(), + &target, + adopted, + parent.routing_input(), + message, + )?; + let child = memory + .child_session_store() + .context("mailbox child storage unavailable")? + .sessions(parent.workspace_id(), parent.owner_id())? + .into_iter() + .find(|child| child.session_key == session) + .context("mailbox child unavailable")?; + anyhow::ensure!( + child.parent_session == parent.session_key() + && child.parent_run == parent.run_id() + && child.runs.last() == Some(&run) + && child.mode == "process", + "mailbox worker differs from persisted child lineage" + ); + Ok::<_, anyhow::Error>(()) + }) + .await??; + } anyhow::ensure!( event.id > 0 && event.event_id == id && event.workspace_id == parent_source.workspace_id() && event.owner_id.as_deref() == Some(parent_source.owner_id()) - && event.run_id.as_deref() == Some(parent_source.run_id()) - && event.session_key.as_deref() == Some(parent_source.session_key()) + && (mailbox.is_some() + || (event.run_id.as_deref() == Some(parent_source.run_id()) + && event.session_key.as_deref() == Some(parent_source.session_key()))) && event.role == "user" && event.event_type == "message.created" - && crate::runtime::turn_source::recorded_input_matches( - parent_source.surface(), - &event, - parent_source.routing_input(), - ), + && (mailbox.is_some() + || crate::runtime::turn_source::recorded_input_matches( + parent_source.surface(), + &event, + parent_source.routing_input(), + )), "operator worker parent event differs from signed provenance" ); } diff --git a/src/runtime/child_source/parent.rs b/src/runtime/child_source/parent.rs index 074fce05f..a2a6b7014 100644 --- a/src/runtime/child_source/parent.rs +++ b/src/runtime/child_source/parent.rs @@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize}; #[derive(Clone)] pub(crate) struct ParentSource { + mailbox_child_source_id: Option, cost_root_agent: Option, owner_isolated: bool, workspace_id: String, @@ -57,6 +58,8 @@ struct RecallScope { #[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] struct SourceFields { + #[serde(default, skip_serializing_if = "Option::is_none")] + mailbox_child_source_id: Option, #[serde(default, skip_serializing_if = "Option::is_none")] cost_root_agent: Option, // Required signed provenance: old payloads must not default to unisolated. @@ -81,6 +84,7 @@ struct SourceFields { impl ParentSource { pub(crate) fn capture(proof: &dyn crate::runtime::turn_source::TurnSourceProof) -> Self { Self { + mailbox_child_source_id: proof.mailbox_child_source_id(), owner_isolated: proof.owner_isolated(), cost_root_agent: proof.cost_root_agent(), workspace_id: proof.workspace_id().to_owned(), @@ -102,6 +106,9 @@ impl ParentSource { pub(crate) fn cost_root_agent(&self) -> Option { self.cost_root_agent.clone() } + pub(crate) const fn mailbox_child_source_id(&self) -> Option { + self.mailbox_child_source_id + } pub(crate) const fn owner_isolated(&self) -> bool { self.owner_isolated } @@ -169,6 +176,7 @@ impl ParentSource { fn process_payload(&self) -> anyhow::Result { let fields = SourceFields { + mailbox_child_source_id: self.mailbox_child_source_id, owner_isolated: self.owner_isolated, cost_root_agent: self.cost_root_agent.clone(), workspace_id: self.workspace_id.clone(), @@ -244,10 +252,12 @@ impl ParentSource { fields.task_run_id.is_none() && ((fields.surface == "interactive" && fields.policy_channel == "terminal" - && fields.policy_sender == "local-user") + && fields.policy_sender == "local-user" + && fields.mailbox_child_source_id.is_none()) || (fields.surface == "server" && fields.policy_channel == "mailbox" && fields.policy_sender == "session" + && fields.mailbox_child_source_id.is_some() && fields.cost_root_agent.is_some())) && !fields.run_id.is_empty() && !fields.session_key.is_empty() @@ -269,6 +279,7 @@ impl ParentSource { "operator worker provenance differs from signed publication" ); Ok(Self { + mailbox_child_source_id: fields.mailbox_child_source_id, owner_isolated: fields.owner_isolated, cost_root_agent: fields.cost_root_agent, workspace_id: fields.workspace_id, @@ -331,6 +342,10 @@ impl ParentSource { "ordinary worker parent provenance signature is invalid" ); let fields: SourceFields = serde_json::from_str(&snapshot.payload)?; + anyhow::ensure!( + fields.mailbox_child_source_id.is_none(), + "mailbox source requires operator worker admission" + ); let surface = match fields.surface.as_str() { "interactive" => TurnSurfaceKind::Interactive, "agent_loop" => TurnSurfaceKind::AgentLoop, @@ -365,6 +380,7 @@ impl ParentSource { "ordinary worker parent provenance differs from verified scope" ); Ok(Self { + mailbox_child_source_id: None, owner_isolated: fields.owner_isolated, cost_root_agent: fields.cost_root_agent, workspace_id: fields.workspace_id, @@ -425,6 +441,7 @@ mod tests { fn parent(owner_isolated: bool) -> ParentSource { ParentSource { + mailbox_child_source_id: None, cost_root_agent: None, owner_isolated, workspace_id: "prx_workspace".to_owned(), From 95271d026a12d8d7bfd15e7fcadfbe99d0787a2c Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 22:57:30 +0400 Subject: [PATCH 0032/1567] fix(gateway): register named mailboxes and project continuation starts --- src/gateway/api/sessions/mailbox.rs | 11 ++++++++++- src/memory/sqlite/sync_projection.rs | 2 +- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/gateway/api/sessions/mailbox.rs b/src/gateway/api/sessions/mailbox.rs index a6b16530e..1eaddc20b 100644 --- a/src/gateway/api/sessions/mailbox.rs +++ b/src/gateway/api/sessions/mailbox.rs @@ -8,13 +8,22 @@ use std::sync::Arc; pub(super) fn register( state: &AppState, - envelope: RuntimeEnvelope, + mut envelope: RuntimeEnvelope, principal: super::super::ApiPrincipal, ) -> anyhow::Result<()> { let config = state.config.load_full(); if config.memory.backend != "sqlite" { return Ok(()); } + if let Some(crate::memory::AgentPartition { + key: crate::memory::PartitionKey::Named { name, .. }, + .. + }) = &envelope.agent_partition + { + // Registration precedes target prompt binding. Use the already + // admitted partition rather than defaulting the named root to Main. + envelope.agent_id = Some(name.as_str().to_owned()); + } let runtime = MessagingRuntime::for_config(&config)?; crate::gateway::child_mailbox::register(state, &envelope)?; let address = runtime.address( diff --git a/src/memory/sqlite/sync_projection.rs b/src/memory/sqlite/sync_projection.rs index 20e3226eb..2f0dc2740 100644 --- a/src/memory/sqlite/sync_projection.rs +++ b/src/memory/sqlite/sync_projection.rs @@ -117,7 +117,7 @@ pub(super) fn payload(conn: &Connection, h: &Header) -> anyhow::Result { source.source_ref = format!("event:{message}"); return payload(conn, &source); } - if h.kind == "child_session.upsert" { + if h.kind == "child_session.upsert" || (h.kind == "turn.started" && h.source_ref.starts_with("memory:")) { return super::sync_lifecycle::child_payload(conn, h); } if let Some(id) = h.source_ref.strip_prefix("approval-cancel:") { From a5ee1fe72a6b6344961ea2097a45027c5d7d3561 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 23:00:50 +0400 Subject: [PATCH 0033/1567] fix(chat): consider complete turn boundaries during child compaction --- src/chat/child_focus.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/chat/child_focus.rs b/src/chat/child_focus.rs index d767604ae..107b2584b 100644 --- a/src/chat/child_focus.rs +++ b/src/chat/child_focus.rs @@ -374,7 +374,7 @@ impl ChildFocus { { break; } - compaction.keep_recent_messages = compaction.keep_recent_messages.saturating_add(2); + compaction.keep_recent_messages = compaction.keep_recent_messages.saturating_add(1); } if let Some(patch) = built { crate::agent::compaction::apply_compaction_patch_exact(&mut history, &patch)?; From 2c0967767e7f09fd23713161ffd440f1420313ce Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 23:02:32 +0400 Subject: [PATCH 0034/1567] fix(messaging): accept service-authored worker call arguments --- src/tools/sessions_send.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/tools/sessions_send.rs b/src/tools/sessions_send.rs index 7970631af..eed69ffd1 100644 --- a/src/tools/sessions_send.rs +++ b/src/tools/sessions_send.rs @@ -183,10 +183,12 @@ impl Tool for SessionsSendTool { ) })?; let object = args.as_object().ok_or(MailboxError::InvalidMetadata)?; - if object - .keys() - .any(|key| !matches!(key.as_str(), "to" | "message") && !key.starts_with("_zc_")) - { + if object.keys().any(|key| { + !matches!(key.as_str(), "to" | "message") + && !crate::tools::execution::RUNTIME_ONLY_ARG_PREFIXES + .into_iter() + .any(|prefix| key.starts_with(prefix)) + }) { return Err(MailboxError::InvalidMetadata.into()); } let value = args.get("to").ok_or(MailboxError::InvalidAddress)?; From 39b974d56b983923a968e00565beace6e465eb19 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 23:20:02 +0400 Subject: [PATCH 0035/1567] fix(chat): retain one current projection per recovered child --- src/chat/sessions/runtime.rs | 16 ++++++++++--- src/tools/sessions_spawn/process_terminal.rs | 25 ++++++++++++++++++-- 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/src/chat/sessions/runtime.rs b/src/chat/sessions/runtime.rs index c54fb7d33..c7f7a60af 100644 --- a/src/chat/sessions/runtime.rs +++ b/src/chat/sessions/runtime.rs @@ -198,15 +198,25 @@ impl ChatSessionsHandle { .read() .await .iter() - .find(|run| run.id == target || run.session_scope_key == target) + .filter(|run| run.id == target || run.session_scope_key == target) + .max_by_key(|run| run.started_at) .cloned() } pub(crate) async fn restore_child(&self, run: SubAgentRun) { let mut runs = self.runs.write().await; - if !runs.iter().any(|old| old.session_scope_key == run.session_scope_key) { - runs.push(run); + if runs.iter().any(|old| { + old.session_scope_key == run.session_scope_key + && (old.started_at >= run.started_at + || matches!( + old.status, + SubAgentStatus::Running | SubAgentStatus::AwaitingInput { .. } + )) + }) { + return; } + runs.retain(|old| old.session_scope_key != run.session_scope_key); + runs.push(run); } /// Build a handle over the supplied single-source agent registry Arc, with a diff --git a/src/tools/sessions_spawn/process_terminal.rs b/src/tools/sessions_spawn/process_terminal.rs index 499a0bd74..3bcb36fe5 100644 --- a/src/tools/sessions_spawn/process_terminal.rs +++ b/src/tools/sessions_spawn/process_terminal.rs @@ -211,6 +211,26 @@ impl RecoveredProcessRun { }; let mut runs = active_runs.write().await; let existing_index = runs.iter().position(|run| run.id == run_id); + // Recovery scans historical turns too. A logical child has one live + // projection; an older continuation cannot replace or duplicate it. + if existing_index.is_none() + && runs.iter().any(|run| { + run.session_scope_key == session + && run.owner_id == source.owner_id + && (run.started_at >= started_at + || !run + .process_control + .as_ref() + .is_some_and(|control| control.recovery_only)) + }) + { + return Ok(false); + } + let existing_index = existing_index.or_else(|| { + runs.iter().position(|run| { + run.session_scope_key == session && run.owner_id == source.owner_id && run.started_at < started_at + }) + }); if let Some(index) = existing_index { let existing = runs.get(index).context("recovered worker registry index disappeared")?; let recovery_only = existing @@ -228,13 +248,14 @@ impl RecoveredProcessRun { anyhow::ensure!( recovery_only && existing.owner_id == source.owner_id - && existing.source_message_event_id.as_deref() == Some(source.event_id.as_str()), + && (existing.id != run_id + || existing.source_message_event_id.as_deref() == Some(source.event_id.as_str())), "recovered worker conflicts with registry ownership" ); // A later sweep cannot discard or change an already authenticated // settlement, including while upgrading to a completed journal. anyhow::ensure!( - existing.token_usage_records.iter().all(|known| usage.contains(known)), + existing.id != run_id || existing.token_usage_records.iter().all(|known| usage.contains(known)), "worker recovery would lose or change a confirmed settlement" ); } From 29d5c733ebf4aa62fab43e9048ee6ccc4c573856 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 23:24:30 +0400 Subject: [PATCH 0036/1567] fix(runtime): verify proxied supervised child capability contracts --- .../child_source/publication/operator.rs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/runtime/child_source/publication/operator.rs b/src/runtime/child_source/publication/operator.rs index a23e0aeb3..e436e3372 100644 --- a/src/runtime/child_source/publication/operator.rs +++ b/src/runtime/child_source/publication/operator.rs @@ -168,10 +168,6 @@ impl IndependentChildPublication { let parent = &self.service; let mailbox = task.mailbox_turn(); let child_names: BTreeSet = registry.iter().map(|tool| tool.name().to_owned()).collect(); - anyhow::ensure!( - mailbox || Arc::ptr_eq(®istry, &parent.registry), - "operator task registry differs from source" - ); // Full operators start Full children; below Full a named agent // retains its configured level. let level = crate::security::agent_level::named_child_level( @@ -211,6 +207,12 @@ impl IndependentChildPublication { ) .with_idempotency_memory(Arc::clone(&parent.memory)), ); + // Named children can carry allowlist/memory-isolation proxies. Their + // served contracts must match the frozen parent capabilities; Arc + // identity of the containing vector does not establish that parity. + let served = parent + .catalog + .served_references(&execution, &self.authority.constraints.allowed); let mut policy = parent.publication_policy.clone(); // The frozen capability set is a membership limit. Full has no // permission limits (R51/OV-4): a Full task publishes under the @@ -224,7 +226,7 @@ impl IndependentChildPublication { fingerprint: entry.fingerprint, generation: entry.generation, }; - if self.authority.constraints.allowed.contains(&reference) { + if served.contains(&reference) { names.insert(entry.public_name.clone()); } else { // Explicit exclusions also prevent root aliases from admitting @@ -242,7 +244,11 @@ impl IndependentChildPublication { .excluded_names .extend(["sessions_spawn".to_owned(), "delegate".to_owned()]); } - parent.catalog.check_parity(&execution)?; + if level == crate::security::AutonomyLevel::Full { + parent.catalog.check_parity(&execution)?; + } else { + parent.catalog.check_published_parity(&execution, &served)?; + } let policy_version = pinned_policy_version(&parent.generation.effective, &security, &policy, &parent.state_key)?; let factory = DecisionBackendFactory::from_config( From c8b0126c564b39eff4ede3497ab2d309250c2bd7 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 23:28:05 +0400 Subject: [PATCH 0037/1567] fix(runtime): route operator task approvals to its live resolver --- src/runtime/child_source/publication/operator.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/runtime/child_source/publication/operator.rs b/src/runtime/child_source/publication/operator.rs index e436e3372..0e1998e16 100644 --- a/src/runtime/child_source/publication/operator.rs +++ b/src/runtime/child_source/publication/operator.rs @@ -301,7 +301,10 @@ impl IndependentChildPublication { events: Arc::clone(&parent.events), state_key: Arc::clone(&parent.state_key), policy_version, - recordable: parent.recordable, + // This service owns an unrecorded child recovery scope, as an + // ordinary task does. Its run's live approval resolver must own + // Ask suspension, rather than the parent's deferred ledger adapter. + recordable: false, registry, execution, memory: Arc::clone(&parent.memory), From 0b7012ac5ab57b2f158aef55e7d0147f0112b26e Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 23:37:09 +0400 Subject: [PATCH 0038/1567] fix(runtime): retain current tools for supervised mailbox children --- src/runtime/child_source/publication/operator.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/runtime/child_source/publication/operator.rs b/src/runtime/child_source/publication/operator.rs index 0e1998e16..5d8c07686 100644 --- a/src/runtime/child_source/publication/operator.rs +++ b/src/runtime/child_source/publication/operator.rs @@ -167,7 +167,6 @@ impl IndependentChildPublication { task.verify()?; let parent = &self.service; let mailbox = task.mailbox_turn(); - let child_names: BTreeSet = registry.iter().map(|tool| tool.name().to_owned()).collect(); // Full operators start Full children; below Full a named agent // retains its configured level. let level = crate::security::agent_level::named_child_level( @@ -234,9 +233,9 @@ impl IndependentChildPublication { policy.excluded_names.insert(entry.public_name.clone()); } } - if mailbox { - names.retain(|name| child_names.contains(name)); - } + // Mailbox publication was rebuilt against today's agent config. + // The retained spawn tool's old registry is not another grant or + // restriction; served references above use the fresh publication. policy.allowed_tools = Some(names); } if mailbox { From 19a9a20d453464ab19d82c180212492a6467baeb Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 23:44:30 +0400 Subject: [PATCH 0039/1567] chore(runtime): trace child capability binding without payloads --- src/runtime/child_source/publication/operator.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/runtime/child_source/publication/operator.rs b/src/runtime/child_source/publication/operator.rs index 5d8c07686..04775aab3 100644 --- a/src/runtime/child_source/publication/operator.rs +++ b/src/runtime/child_source/publication/operator.rs @@ -68,6 +68,14 @@ impl IndependentChildPublication { generation: entry.generation, }) .collect(); + tracing::debug!( + mailbox = source.mailbox_child_source_id().is_some(), + level = ?security.autonomy, + shell_visible = service.catalog_view().iter_entries().any(|entry| entry.public_name == "shell"), + shell_allowed = allowed.iter().any(|reference| reference.id.as_str().ends_with(":shell")), + shell_registered = service.registry.iter().any(|tool| tool.supports_name("shell")), + "independent child capability source captured" + ); let remaining = runtime.workspace_remaining_micro_usd()?; let authority = crate::runtime::child_source::ParentAuthority::for_run( source.run_id(), @@ -212,6 +220,12 @@ impl IndependentChildPublication { let served = parent .catalog .served_references(&execution, &self.authority.constraints.allowed); + tracing::debug!( + mailbox, + shell_registered = registry.iter().any(|tool| tool.supports_name("shell")), + shell_served = served.iter().any(|reference| reference.id.as_str().ends_with(":shell")), + "independent child executor bound" + ); let mut policy = parent.publication_policy.clone(); // The frozen capability set is a membership limit. Full has no // permission limits (R51/OV-4): a Full task publishes under the From c5fb58d216f9df5844c38cb8ad1e10e9cb635ed0 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 23:44:50 +0400 Subject: [PATCH 0040/1567] chore(messaging): trace hashed receiver lookup context --- src/memory/sqlite/mailbox/local_runtime.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/memory/sqlite/mailbox/local_runtime.rs b/src/memory/sqlite/mailbox/local_runtime.rs index e167003a4..b00c6ec77 100644 --- a/src/memory/sqlite/mailbox/local_runtime.rs +++ b/src/memory/sqlite/mailbox/local_runtime.rs @@ -151,6 +151,13 @@ impl SqliteMailbox { } let known:bool=tx.query_row("SELECT EXISTS(SELECT 1 FROM message_events WHERE workspace_id=?1 AND owner_id=?2 AND session_key=?3) OR EXISTS(SELECT 1 FROM sessions WHERE owner_id=?2 AND session_key=?3) OR EXISTS(SELECT 1 FROM child_sessions WHERE workspace_id=?1 AND owner_id=?2 AND session_id=?3) OR EXISTS(SELECT 1 FROM agent_scopes WHERE workspace_id=?1 AND owner_id=?2 AND session_key=?3 AND agent_key=?4)",params![workspace,address.owner,address.session,crate::messaging::mailbox::agent_key(&address.agent)?],|r|r.get(0)).map_err(storage_error)?; if !known && !registered { + tracing::debug!( + workspace = %crate::agent::diagnostics::text_class(workspace), + owner = %crate::agent::diagnostics::text_class(&address.owner), + session = %crate::agent::diagnostics::text_class(&address.session), + agent = %crate::agent::diagnostics::text_class(&address.agent), + "mailbox receiver lookup missed" + ); return Err(crate::messaging::mailbox::unauthorized( crate::messaging::mailbox::UnauthorizedReason::ReceiverUnknown, )); From 030def27594bd85acbeb4a7f020e2dbcfc805868 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Mon, 23 Nov 2026 23:55:25 +0400 Subject: [PATCH 0041/1567] fix(runtime): bind live child approvals to their durable ledger --- src/runtime/child_turn.rs | 2 +- src/runtime/turn_context/call_approval.rs | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/runtime/child_turn.rs b/src/runtime/child_turn.rs index c71f3793a..46f0d7b3b 100644 --- a/src/runtime/child_turn.rs +++ b/src/runtime/child_turn.rs @@ -245,7 +245,7 @@ impl ChildSegmentTurn { let live = self.execution.live_turn.clone(); let mut context = self.execution.clone(); if live.is_some() { - context.approval_ledger = self.service.execution_approval_ledger(); + context.approval_ledger = self.service.live_approval_ledger(); } ToolLoopRuntimeAdapter { live_frames: live.map(|live| { diff --git a/src/runtime/turn_context/call_approval.rs b/src/runtime/turn_context/call_approval.rs index 499dc4460..85d94b19d 100644 --- a/src/runtime/turn_context/call_approval.rs +++ b/src/runtime/turn_context/call_approval.rs @@ -10,6 +10,14 @@ impl TurnRuntimeService { if !self.recordable { return None; } + self.live_approval_ledger() + } + + /// A live child approval adapter journals against that child's durable + /// source, independently of whether its recovery scope is recordable. + pub(crate) fn live_approval_ledger( + &self, + ) -> Option { let workspace = self.generation.effective.workspace_dir.to_str()?.to_owned(); Some(crate::security::approval_ledger::strategy::ExecutionApprovalLedger { memory: std::sync::Arc::clone(&self.memory), From 1971108d96c5d6a44636bc9a0dc88a390e2d5109 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Tue, 24 Nov 2026 00:05:35 +0400 Subject: [PATCH 0042/1567] fix(approvals): route mailbox descendants to the root surface --- src/memory/sqlite/sync_journal.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/memory/sqlite/sync_journal.rs b/src/memory/sqlite/sync_journal.rs index 8237317de..59fbbafb4 100644 --- a/src/memory/sqlite/sync_journal.rs +++ b/src/memory/sqlite/sync_journal.rs @@ -433,8 +433,12 @@ impl SyncStore for SqliteMemory { return Ok(None); }; anyhow::ensure!(h.owner == owner, crate::memory::sync::SyncError::InvalidSource); + // Descendant headers retain the root's agent and incarnation. Its + // approval surface belongs to that root even after its turn ended. + let session = h.root_session.as_ref().unwrap_or(&h.session); + let run = h.root_run_id.as_ref().or(h.run_id.as_ref()); Ok(Some( - serde_json::json!({"session":h.session,"agent":h.agent,"incarnation":h.incarnation,"run_id":h.run_id}), + serde_json::json!({"session":session,"agent":h.agent,"incarnation":h.incarnation,"run_id":run}), )) } From 1eb13debbe78b5bdb9d022b61659146d6d12e5d2 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Tue, 24 Nov 2026 00:13:24 +0400 Subject: [PATCH 0043/1567] fix(messaging): log typed pin transport failures --- src/messaging/a2a/outbound/recipient.rs | 32 ++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/src/messaging/a2a/outbound/recipient.rs b/src/messaging/a2a/outbound/recipient.rs index 237a48f92..f48c6f618 100644 --- a/src/messaging/a2a/outbound/recipient.rs +++ b/src/messaging/a2a/outbound/recipient.rs @@ -75,7 +75,11 @@ impl RemoteTransport { let response = tokio::select! { () = cancellation.cancelled() => return Err(MailboxError::PeerUnavailable), response = request => response, - }; + } + .inspect_err(|error| { + let (reason, os_code) = transport_reason(error); + tracing::warn!(reason, os_code, "A2A pin request failed"); + }); let pin = match response { Ok(response) => { if response.status().as_u16() != 200 { @@ -129,6 +133,32 @@ impl RemoteTransport { }) } } +fn transport_reason(error: &reqwest::Error) -> (&'static str, Option) { + use std::error::Error as _; + let mut cause = error.source(); + while let Some(error) = cause { + if let Some(error) = error.downcast_ref::() { + let reason = match error.kind() { + std::io::ErrorKind::ConnectionRefused => "peer_connection_refused", + std::io::ErrorKind::TimedOut => "peer_timeout", + std::io::ErrorKind::NetworkUnreachable => "peer_network_unreachable", + std::io::ErrorKind::HostUnreachable => "peer_host_unreachable", + std::io::ErrorKind::PermissionDenied => "peer_network_permission_denied", + _ => "peer_io_failed", + }; + return (reason, error.raw_os_error()); + } + cause = error.source(); + } + ( + if error.is_timeout() { + "peer_timeout" + } else { + "peer_request_failed" + }, + None, + ) +} fn offline(error: &reqwest::Error) -> bool { use std::error::Error as _; let mut cause = error.source(); From c58e64c8c086158e09eaa7329e942096a22b60ba Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Tue, 24 Nov 2026 00:50:15 +0400 Subject: [PATCH 0044/1567] fix(history): scope terminal writes and fence erased sessions --- docs/rf-contract/capability-tokens.md | 10 +- docs/tools.md | 7 + src/agent/entry.rs | 2514 +----------------- src/agent/entry/section_1.rs | 1374 ++++++++++ src/agent/entry/section_2.rs | 1139 ++++++++ src/chat/binding/tests.rs | 1 + src/chat/chat_events.rs | 13 +- src/chat/message_inbox.rs | 18 + src/chat/mod.rs | 1 + src/chat/run.rs | 5 + src/chat/run/event_pump.rs | 3 + src/chat/run/provider_turn.rs | 3 +- src/chat/session_switch.rs | 2 + src/memory/sqlite/agent_erasure.rs | 56 +- src/memory/sqlite/agent_migration.rs | 1 + src/memory/sqlite/history_retention.rs | 57 + src/memory/sqlite/mailbox/local_runtime.rs | 11 + src/memory/sqlite/mod.rs | 2 + src/memory/sqlite/recall.rs | 2103 +-------------- src/memory/sqlite/recall/section_1.rs | 1009 +++++++ src/memory/sqlite/recall/section_2.rs | 1095 ++++++++ src/memory/sqlite/terminal_epoch.rs | 92 + src/runtime/mode.rs | 33 +- tests/architecture_boundaries/helpers.rs | 12 + tests/architecture_boundaries/loop_prompt.rs | 4 +- tests/architecture_boundaries/memory.rs | 4 +- tests/architecture_boundaries/process.rs | 2 +- 27 files changed, 4928 insertions(+), 4643 deletions(-) create mode 100644 src/agent/entry/section_1.rs create mode 100644 src/agent/entry/section_2.rs create mode 100644 src/memory/sqlite/history_retention.rs create mode 100644 src/memory/sqlite/recall/section_1.rs create mode 100644 src/memory/sqlite/recall/section_2.rs create mode 100644 src/memory/sqlite/terminal_epoch.rs diff --git a/docs/rf-contract/capability-tokens.md b/docs/rf-contract/capability-tokens.md index d5c88a62f..dac1e00d5 100644 --- a/docs/rf-contract/capability-tokens.md +++ b/docs/rf-contract/capability-tokens.md @@ -577,12 +577,16 @@ Success is `200 {"status":"erased","scope":{"session","agent","incarnation"}, "erase_id","generation","remaining":0,"incarnation"}`. Generations start at 1 and advance only after verified erasure; replay returns the saved receipt. The old scope stays sealed. A new turn uses the replacement generation. -Erasure removes scoped transcripts, events, memories/documents and derived -copies, mailbox payloads and approvals. Main erasure preserves other sessions +Erasure removes scoped transcripts, events, saved snapshots, context pages, +mailbox payloads and approvals. Owner memories/documents are kept by default +and listed in `retained:{memories:[{id,key}],documents:[id]}`. Main erasure preserves other sessions and shared configuration. Context pages are selected by scope, never by text. Payload-free message keys remain deleted so an old message retry cannot restore its content. With `forget_writes`, the run families' writes are also -forgotten and the receipt adds `forgotten:{created,touched}`. +forgotten and the receipt adds `forgotten:{created,touched}`. This policy also +applies to the paired terminal history route. A running terminal chat is fenced +by its erased generation and restarts with a fresh conversation. Late writes +from its old generation are refused; erased snapshots are never restored. `503 history_pending` requires retry with the same key; it never certifies zero residue. `409 incarnation_mismatch` includes `current_incarnation`. diff --git a/docs/tools.md b/docs/tools.md index b40e9cb46..923209e19 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -2016,3 +2016,10 @@ First GET the same URL for its incarnation, then send that UUID in `If-Match` and a fresh `Idempotency-Key`. The receiver derives the terminal owner from its workspace; callers cannot supply a different owner. The Console erase route remains `DELETE /api/sessions/{id}/agents/{agent}/history`. + +By default, erase keeps owner memories and documents and lists their IDs in +`retained`. Send `{"forget_writes":true}` to remove those writes and their +derived copies too. Saved transcript snapshots and context pages are always +cleared. An open terminal chat discards the erased conversation and starts a +fresh chat; its previous cached history cannot be saved again. Rows written +before session scoping was introduced are outside this erase contract. diff --git a/src/agent/entry.rs b/src/agent/entry.rs index 5752f0f4f..a67e7d3cc 100644 --- a/src/agent/entry.rs +++ b/src/agent/entry.rs @@ -1,2512 +1,4 @@ #![allow(clippy::print_stdout, clippy::print_stderr)] - -use crate::agent::context_recall::{current_input_memory_key, increment_recalled_useful_counts}; -use crate::agent::document_ingest::DocumentIngestRuntime; -use crate::agent::runtime_prompt::build_runtime_system_prompt; -use crate::agent::turn_contracts::ChatMode; -use crate::agent::turn_engine::run_turn; -use crate::agent::turn_request::ToolLoopMemory; -use crate::approval::ApprovalManager; -use crate::config::Config; -use crate::hooks::HookEvent; -use crate::memory::{Memory, MemoryCategory, MemoryFabric, MessageEventScope}; -use crate::observability::ObserverEvent; -use crate::providers; -use crate::providers::{ChatMessage, Provider}; -use crate::runtime::envelope::{RuntimeEnvelope, RuntimeSource}; -use crate::tools::Tool; -use anyhow::Result; -use std::path::Path; -use std::sync::Arc; -use std::time::Instant; -use tokio_util::sync::CancellationToken; -use uuid::Uuid; - -// ── Internal single-shot engine ────────────────────────────────────────── -// Wires up all subsystems (observer, runtime, security, memory, tools, -// provider, hardware RAG) and runs one turn for cron, xin, skill evaluation -// and controlled cases. - -tokio::task_local! { - static QUIET_SINGLE_SHOT: bool; -} - -/// Internal evaluations return their answer to the caller without mixing it -/// into the operator command's machine-readable stdout. -pub(crate) async fn run_quiet( - config: Config, - message: String, - temperature: f64, - shutdown: tokio_util::sync::CancellationToken, -) -> anyhow::Result { - QUIET_SINGLE_SHOT - .scope( - true, - Box::pin(run_with_runtime_envelope( - config, - message, - None, - None, - temperature, - shutdown, - None, - None, - )), - ) - .await -} - -/// A controlled case carries its native filesystem capability explicitly -/// through bootstrap, never in Config or model input. -pub(crate) async fn run_quiet_controlled( - config: Config, - message: String, - temperature: f64, - shutdown: CancellationToken, - scope: Arc, -) -> anyhow::Result { - QUIET_SINGLE_SHOT - .scope( - true, - Box::pin(run_with_runtime_envelope( - crate::runtime::bootstrap::AgentRuntimeConfig::ControlledCase { - config: Box::new(config), - scope, - }, - message, - None, - None, - temperature, - shutdown, - None, - None, - )), - ) - .await -} - -/// Persist a live CLI or chat input under its per-run semantic identity. -pub(crate) async fn save_current_input( - fabric: &crate::memory::MemoryFabric, - run: &str, - session_key: &str, - input: &str, - event: Option<&str>, -) -> anyhow::Result<()> { - let key = current_input_memory_key(run); - fabric - .record_semantic_memory_from_event( - &key, - input, - MemoryCategory::Conversation, - Some(session_key), - event, - None, - None, - None, - ) - .await -} - -/// Build one CLI turn's memory handles from the turn's own, user-authored text. -/// -/// Every single-shot turn needs these handles (cron jobs, xin tasks, skill -/// evaluation and controlled cases all enter through -/// `run_with_runtime_envelope`). One builder keeps the routing pin from going -/// missing in a hand-copied chain. -/// -/// Routing is supplied separately by the source-bound decision context. -fn cli_turn_memory_runtime( - mem: &Arc, - workspace_dir: &Path, - runtime_envelope: &RuntimeEnvelope, - memory_fabric: &MemoryFabric, - fabric_scope: &MessageEventScope, - user_message_event_id: Option<&str>, -) -> ToolLoopMemory { - ToolLoopMemory::new( - mem, - workspace_dir, - Some( - DocumentIngestRuntime::from_envelope(mem.clone(), runtime_envelope) - .with_source_message_event_id(user_message_event_id.map(ToString::to_string)), - ), - ) - .with_event_fabric(memory_fabric.clone()) - .with_request_event_scope({ - let mut scope = fabric_scope.clone(); - scope.causation_event_id = user_message_event_id.map(ToString::to_string); - scope - }) -} - -/// Preserve the CLI actor and chat scope while applying the bootstrap's -/// configured security policy and workspace. Scheduled and externally scoped turns leave -/// this adapter absent so their creator-owned scope retains priority. -fn configured_cli_tool_adapter( - security: &Arc, - registry: &Arc>>, - approval: &Arc, - memory_runtime: &ToolLoopMemory, -) -> crate::agent::turn_contracts::ToolLoopRuntimeAdapter { - crate::agent::execution_policy::build_agent_tool_runtime_adapter( - crate::agent::execution_policy::AgentToolRuntimeInputs { - scope: None, - channel_name: "cli", - tools_registry: Arc::clone(registry), - approval: Some(Arc::clone(approval)), - approval_resolver: None, - cancellation: None, - ledger: memory_runtime.ledger.clone(), - unscoped_policy: Some(Arc::clone(security)), - }, - ) -} - -fn terminal_binding_snapshot( - binding: &parking_lot::Mutex>, -) -> Option { - binding.lock().clone() -} - -/// A CLI Agent turn whose origin was checked by this entrypoint after inbound -/// event recording was attempted. Fields stay private; the decision service -/// reads them but cannot manufacture an authenticated source from a public -/// `RuntimeEnvelope`. -pub(crate) struct AgentTurnProof { - workspace_id: Arc, - owner_id: Arc, - session_key: Arc, - run_id: Arc, - source_event_id: Option>, - routing_input: Arc, - memory_scope: crate::memory::principal::MemoryWriteContext, - retrieval_principal: crate::memory::MemoryPrincipal, - provider_name: Arc, - model_name: Arc, - model_binding: AgentModelBinding, - config_generation_id: u64, - config_source_revision: Arc, - scheduled: Option>, -} - -/// Cleanup ownership starts before CLI durable input persistence. This is -/// separate from the source proof: neither a pending write nor its key grants -/// permission to execute a model or tool. -struct CliPendingInput { - fabric: MemoryFabric, - generation: Arc, - envelope: RuntimeEnvelope, - expected_session_key: String, - scope: crate::memory::MessageEventScope, - choice: AgentModelChoice, - input: String, - key: String, - ticket: crate::runtime::turn_cleanup::CleanupTicket, -} - -struct CliAdmissionGuard { - proof: Option, - fabric: MemoryFabric, - config: Arc, - ticket: Option, - pending: Option<(bool, String)>, -} - -impl CliPendingInput { - async fn issue(&self, event: Option<&crate::memory::MessageEvent>) -> Result { - let run = self - .envelope - .run_id - .as_deref() - .ok_or_else(|| anyhow::anyhow!("CLI input run is missing"))?; - let proof = issue_cli_agent_turn_proof_for_session( - None, - &self.envelope, - &self.generation, - (run, &self.expected_session_key), - &self.input, - event, - &self.choice, - )?; - if let Some(event) = event.filter(|event| event.id > 0) { - let mut expected = self.scope.clone(); - for label in [&mut expected.sender, &mut expected.recipient].into_iter().flatten() { - if crate::providers::byo_dialect_of(label).is_some() { - *label = crate::providers::redact_endpoint_userinfo(label).into_owned(); - } - } - anyhow::ensure!( - event.idempotency_key.as_deref() == Some(self.key.as_str()) - && event.source == expected.source - && event.channel == expected.channel - && event.sender == expected.sender - && event.recipient == expected.recipient - && event.owner_id == expected.owner_id - && event.visibility == expected.visibility - && event.goal_id == expected.goal_id - && event.correlation_id == expected.correlation_id - && event.subject == expected.subject - && event.causation_event_id == expected.causation_event_id, - "CLI input receipt attribution differs from its issued scope" - ); - let stored = self - .fabric - .memory() - .find_owned_message_event( - &self.envelope.workspace_id, - &self.envelope.resolved_owner_id(), - &event.event_id, - ) - .await? - .ok_or_else(|| anyhow::anyhow!("CLI input receipt is not durable"))?; - anyhow::ensure!( - serde_json::to_value(stored)? == serde_json::to_value(event)?, - "CLI input receipt differs from its durable source" - ); - } - Ok(proof) - } - - async fn record(mut self) -> Result<(Option, CliAdmissionGuard)> { - self.fabric = self - .fabric - .with_ingress_recovery(&self.generation.effective, &self.ticket) - .await?; - let (sender, receiver) = tokio::sync::oneshot::channel(); - let experiment_stage = crate::runtime::experiment_stage::current(); - tokio::spawn(async move { - let operation = crate::runtime::experiment_stage::retain(experiment_stage, async { - let event = self - .fabric - .record_inbound_user_message_best_effort( - self.scope.clone(), - self.input.clone(), - Some(self.key.clone()), - "CLI", - ) - .await?; - let proof = self.issue(event.as_ref()).await?; - Ok::<_, anyhow::Error>((event, proof)) - }); - let result = tokio::time::timeout(std::time::Duration::from_secs(15), operation) - .await - .map_err(|_| anyhow::anyhow!("CLI input persistence timed out")) - .and_then(std::convert::identity); - let result = match result { - Ok((event, proof)) => Ok(( - event, - CliAdmissionGuard { - proof: Some(proof), - fabric: self.fabric, - config: Arc::clone(&self.generation.effective), - ticket: Some(self.ticket), - pending: None, - }, - )), - Err(_error) if self.fabric.ingress_already_accepted() => { - self.ticket.finish(true); - Err(crate::runtime::ingress_recovery::AlreadyAccepted.into()) - } - Err(error) => { - let recovery = async { - let event = self - .fabric - .memory() - .find_owned_message_event_by_idempotency_key( - &self.envelope.workspace_id, - &self.envelope.resolved_owner_id(), - &self.key, - ) - .await? - .ok_or_else(|| anyhow::anyhow!("CLI input commit is unconfirmed"))?; - self.issue(Some(&event)).await - }; - match tokio::time::timeout(std::time::Duration::from_secs(15), recovery).await { - Ok(Ok(proof)) => { - let mut guard = CliAdmissionGuard { - proof: Some(proof), - fabric: self.fabric, - config: Arc::clone(&self.generation.effective), - ticket: Some(self.ticket), - pending: None, - }; - let _ = tokio::time::timeout( - std::time::Duration::from_secs(15), - guard.finish_failure(sender.is_closed(), "CLI input admission failed"), - ) - .await; - } - _ => self.ticket.finish(false), - } - Err(error) - } - }; - let _ = sender.send(result); - }); - receiver - .await - .map_err(|_| anyhow::anyhow!("CLI input owner ended without a receipt"))? - } -} - -impl CliAdmissionGuard { - /// Transfer the same lifecycle ticket to a real terminal owner without - /// an await or an interval where cancellation has no cleanup owner. - fn into_terminal_ticket(mut self) -> Result { - anyhow::ensure!(self.pending.is_none(), "CLI admission failure is already pending"); - let ticket = self - .ticket - .take() - .ok_or_else(|| anyhow::anyhow!("CLI admission cleanup ticket missing"))?; - self.proof = None; - Ok(ticket) - } - - async fn finish_failure(&mut self, cancelled: bool, summary: &str) -> Result<()> { - anyhow::ensure!(self.pending.is_none(), "CLI admission failure is already pending"); - self.pending = Some((cancelled, crate::security::redaction::redact_secrets(summary))); - let (cancelled, summary) = self - .pending - .as_ref() - .ok_or_else(|| anyhow::anyhow!("CLI failure missing"))?; - let result = self - .proof - .as_ref() - .ok_or_else(|| anyhow::anyhow!("CLI source proof missing"))? - .record_cli_admission_failure(&self.fabric, &self.config, *cancelled, summary) - .await; - self.proof = None; - if let Some(ticket) = self.ticket.take() { - ticket.finish(result.is_ok()); - } - result - } -} - -impl Drop for CliAdmissionGuard { - fn drop(&mut self) { - let Some(proof) = self.proof.take() else { - return; - }; - let Some(ticket) = self.ticket.take() else { - return; - }; - let (cancelled, summary) = self - .pending - .take() - .unwrap_or_else(|| (true, "CLI input admission task was dropped".to_owned())); - let Ok(runtime) = tokio::runtime::Handle::try_current() else { - ticket.finish(false); - return; - }; - let fabric = self.fabric.clone(); - let config = Arc::clone(&self.config); - runtime.spawn(async move { - let result = tokio::time::timeout( - std::time::Duration::from_secs(15), - proof.record_cli_admission_failure(&fabric, &config, cancelled, &summary), - ) - .await; - ticket.finish(matches!(result, Ok(Ok(())))); - }); - } -} - -impl AgentTurnProof { - async fn record_cli_admission_failure( - &self, - fabric: &MemoryFabric, - config: &Config, - cancelled: bool, - summary: &str, - ) -> Result<()> { - anyhow::ensure!( - self.scheduled.is_none(), - "scheduled admission retains its own failure owner" - ); - anyhow::ensure!( - fabric.workspace_id() == self.workspace_id.as_ref() - && config.workspace_dir.to_string_lossy() == self.workspace_id.as_ref(), - "CLI admission failure workspace changed" - ); - let Some(event_id) = self.source_event_id.as_deref() else { - anyhow::ensure!( - !config.memory.should_record_user_message_event(), - "CLI admission has no durable input" - ); - return Ok(()); - }; - let input = fabric - .memory() - .find_owned_message_event(&self.workspace_id, &self.owner_id, event_id) - .await? - .ok_or_else(|| anyhow::anyhow!("CLI admission input is missing"))?; - anyhow::ensure!( - input.id > 0 - && input.event_id == event_id - && input.workspace_id == self.workspace_id.as_ref() - && input.owner_id.as_deref() == Some(self.owner_id.as_ref()) - && input.session_key.as_deref() == Some(self.session_key.as_ref()) - && input.run_id.as_deref() == Some(self.run_id.as_ref()) - && input.config_generation_id == Some(self.config_generation_id) - && input.config_source_revision.as_deref() == Some(self.config_source_revision.as_ref()) - && input.role == "user" - && input.event_type == "message.created" - && input.parent_run_id.is_none() - && input.parent_session_key.is_none() - && input.agent_id.is_none() - && input.persona_id.is_none() - && input.subject.is_none() - && input.attempt_id.is_none() - && input.lease_epoch.is_none() - && crate::runtime::turn_source::recorded_input_matches(self.surface(), &input, &self.routing_input), - "CLI admission input differs from its source proof" - ); - let mut envelope = RuntimeEnvelope::agent(self.workspace_id.to_string(), self.run_id.to_string()) - .with_source_message_event_id(event_id); - envelope.session_key = self.session_key.to_string(); - let mut scope = envelope.message_scope(); - scope.config_generation_id = Some(self.config_generation_id); - scope.config_source_revision = Some(self.config_source_revision.to_string()); - let summary = crate::security::redaction::redact_secrets(summary); - let payload = serde_json::json!({ - "run_id": self.run_id.as_ref(), "source_event_id": event_id, - "status": if cancelled { "cancelled" } else { "failed" }, "summary": summary, - }); - let expected_content = format!("turn.admission.failed {summary}"); - let event = crate::runtime::ingress_recovery::commit_admission_failure( - fabric, - scope.clone(), - &summary, - serde_json::to_string(&payload)?, - format!("turn:{}:admission-failed", self.run_id), - ) - .await?; - anyhow::ensure!( - event.content == expected_content - && event.idempotency_key.as_deref() == Some(format!("turn:{}:admission-failed", self.run_id).as_str()) - && event.id > 0 - && !event.event_id.is_empty() - && event.workspace_id == fabric.workspace_id() - && event.owner_id == scope.owner_id - && event.source == scope.source - && event.channel == scope.channel - && event.sender == scope.sender - && event.session_key == scope.session_key - && event.run_id == scope.run_id - && event.causation_event_id == scope.causation_event_id - && event.recipient == scope.recipient - && event.parent_run_id == scope.parent_run_id - && event.parent_session_key == scope.parent_session_key - && event.subject == scope.subject - && event.agent_id == scope.agent_id - && event.persona_id == scope.persona_id - && event.attempt_id == scope.attempt_id - && event.lease_epoch == scope.lease_epoch - && event.config_generation_id == scope.config_generation_id - && event.config_source_revision == scope.config_source_revision - && event.visibility == scope.visibility - && event.role == "event" - && event.event_type == "turn.admission.failed" - && event - .raw_payload_json - .as_deref() - .map(serde_json::from_str::) - .transpose()? - .as_ref() - == Some(&payload), - "CLI admission failure retry conflicts with source or status" - ); - let durable = fabric - .memory() - .find_owned_message_event(fabric.workspace_id(), self.owner_id.as_ref(), &event.event_id) - .await? - .ok_or_else(|| anyhow::anyhow!("admission failure receipt is not durable"))?; - anyhow::ensure!( - serde_json::to_value(durable)? == serde_json::to_value(&event)?, - "admission failure receipt differs from durable event" - ); - Ok(()) - } - - pub(crate) fn owner_isolated(&self) -> bool { - self.scheduled - .as_ref() - .map_or(self.retrieval_principal.require_owner_match, |source| { - source.envelope.owner_isolated - }) - } - - pub(crate) fn retrieval_principal(&self) -> crate::memory::MemoryPrincipal { - self.scheduled.as_ref().map_or_else( - || self.retrieval_principal.clone(), - |source| source.envelope.memory_principal(), - ) - } - - pub(crate) fn task_id(&self) -> Option<&str> { - self.scheduled - .as_ref() - .and_then(|source| source.envelope.task_id.as_deref()) - } - pub(crate) fn surface(&self) -> crate::tools::capability::turn_state::TurnSurfaceKind { - use crate::tools::capability::turn_state::TurnSurfaceKind; - match self.scheduled.as_ref().map(|source| source.envelope.source) { - Some(RuntimeSource::Cron) => TurnSurfaceKind::Cron, - Some(RuntimeSource::Xin) => TurnSurfaceKind::Xin, - _ => TurnSurfaceKind::AgentLoop, - } - } - pub(crate) fn policy_channel(&self) -> &str { - self.scheduled - .as_ref() - .and_then(|source| source.execution.envelope.channel.as_deref()) - .unwrap_or("cli") - } - pub(crate) fn policy_sender(&self) -> &str { - self.scheduled - .as_ref() - .and_then(|source| source.execution.envelope.sender.as_deref()) - .unwrap_or("local-user") - } - pub(crate) fn policy_chat_type(&self) -> &str { - self.scheduled - .as_ref() - .map_or("private", |source| source.execution.chat_type.as_str()) - } - pub(crate) fn workspace_id(&self) -> &str { - &self.workspace_id - } - - pub(crate) fn owner_id(&self) -> &str { - &self.owner_id - } - - pub(crate) fn session_key(&self) -> &str { - &self.session_key - } - - pub(crate) fn run_id(&self) -> &str { - &self.run_id - } - - pub(crate) fn source_event_id(&self) -> Option<&str> { - self.source_event_id.as_deref() - } - - pub(crate) fn routing_input(&self) -> &str { - &self.routing_input - } - - pub(crate) const fn memory_scope(&self) -> &crate::memory::principal::MemoryWriteContext { - &self.memory_scope - } - - pub(crate) fn provider_name(&self) -> &str { - &self.provider_name - } - - pub(crate) fn model_name(&self) -> &str { - &self.model_name - } - - pub(crate) const fn model_binding(&self) -> &AgentModelBinding { - &self.model_binding - } - - pub(crate) const fn config_generation_id(&self) -> u64 { - self.config_generation_id - } - - pub(crate) fn config_source_revision(&self) -> &str { - &self.config_source_revision - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] -enum AgentTurnOriginError { - #[error("the CLI Agent turn does not match its authenticated runtime origin ({0})")] - Mismatch(&'static str), -} - -/// Only this entrypoint may issue a CLI Agent origin. Scheduled overrides are -/// separate surfaces and cannot inherit the local operator's authority. -fn issue_cli_agent_turn_proof( - runtime_envelope_override: Option<&RuntimeEnvelope>, - envelope: &RuntimeEnvelope, - generation: &crate::config::ConfigGeneration, - expected_run_id: &str, - routing_input: &str, - recorded_event: Option<&crate::memory::MessageEvent>, - choice: &AgentModelChoice, -) -> Result { - issue_cli_agent_turn_proof_for_session( - runtime_envelope_override, - envelope, - generation, - (expected_run_id, &format!("agent:{expected_run_id}")), - routing_input, - recorded_event, - choice, - ) -} - -// The expected session is minted at the CLI entry, independently of the envelope -// being validated. Run IDs remain per-turn. -fn issue_cli_agent_turn_proof_for_session( - runtime_envelope_override: Option<&RuntimeEnvelope>, - envelope: &RuntimeEnvelope, - generation: &crate::config::ConfigGeneration, - (expected_run_id, expected_session_key): (&str, &str), - routing_input: &str, - recorded_event: Option<&crate::memory::MessageEvent>, - choice: &AgentModelChoice, -) -> Result { - let run_id = envelope - .run_id - .as_deref() - .ok_or(AgentTurnOriginError::Mismatch("missing_run_id"))?; - let workspace_id = generation.effective.workspace_dir.to_string_lossy(); - let owner_id = crate::memory::principal::OwnerPrincipal::new( - workspace_id.as_ref(), - "cli", - "local-user", - &envelope.session_key, - vec![crate::memory::principal::Role::Anonymous], - ) - .owner_id; - if runtime_envelope_override.is_some() - || envelope.source != RuntimeSource::Agent - || envelope.workspace_id != workspace_id - || envelope.channel.as_deref() != Some("cli") - || envelope.sender.as_deref() != Some("local-user") - || envelope.owner_id.is_some() - || envelope.owner_isolated - || envelope.legacy_session_key.is_some() - || envelope.topic_id.is_some() - || envelope.task_id.is_some() - || envelope.source_message_event_id.is_some() - || envelope.parent_run_id.is_some() - || envelope.attempt_id.is_some() - || envelope.lease_epoch.is_some() - || envelope.authority_guard.is_some() - || envelope.agent_id.is_some() - || envelope.persona_id.is_some() - || envelope - .recipient - .as_deref() - .is_some_and(|recipient| recipient != "cli:local-user") - || envelope.visibility != crate::memory::MemoryVisibility::Session - || run_id != expected_run_id - || envelope.session_key != expected_session_key - || envelope.config_generation_id != Some(generation.id.0) - || envelope.config_source_revision.as_deref() != Some(&generation.source_revision.fingerprint_sha256) - { - return Err(AgentTurnOriginError::Mismatch("envelope")); - } - if !choice.factory_credential_source_matches(&generation.effective) { - return Err(AgentTurnOriginError::Mismatch("credential_source")); - } - let recorded_event_id = match recorded_event { - Some(event) if event.id > 0 => { - if event.event_id.trim().is_empty() - || event.workspace_id != workspace_id - || event.owner_id.as_deref() != Some(owner_id.as_str()) - || event.source != crate::memory::MessageEventSource::Agent - || event.channel.as_deref() != Some("cli") - || event.sender.as_deref() != Some("local-user") - || event.session_key.as_deref() != Some(envelope.session_key.as_str()) - || event.parent_session_key.is_some() - || event.run_id.as_deref() != Some(run_id) - || event.parent_run_id.is_some() - || event.agent_id.is_some() - || event.persona_id.is_some() - || event.attempt_id.is_some() - || event.lease_epoch.is_some() - || event.role != "user" - || event.event_type != "message.created" - || event.config_generation_id != Some(generation.id.0) - || event.config_source_revision.as_deref() != Some(&generation.source_revision.fingerprint_sha256) - || event.content != routing_input - || event.visibility != crate::memory::MemoryVisibility::Session - { - return Err(AgentTurnOriginError::Mismatch("recorded_event")); - } - Some(event.event_id.as_str()) - } - Some(_) | None => None, - }; - Ok(AgentTurnProof { - workspace_id: Arc::from(workspace_id.as_ref()), - owner_id: Arc::from(owner_id), - session_key: Arc::from(envelope.session_key.as_str()), - run_id: Arc::from(run_id), - source_event_id: recorded_event_id.map(Arc::from), - routing_input: Arc::from(routing_input), - memory_scope: envelope.memory_write_context("private"), - retrieval_principal: envelope.memory_principal(), - provider_name: Arc::from(choice.provider_name.as_str()), - model_name: Arc::from(choice.model_name.as_str()), - model_binding: choice.model_binding.clone(), - config_generation_id: generation.id.0, - config_source_revision: Arc::from(generation.source_revision.fingerprint_sha256.as_str()), - scheduled: None, - }) -} - -#[cfg(test)] -pub(crate) fn test_cli_agent_turn_proof( - generation: &crate::config::ConfigGeneration, - provider_name: &str, - model_name: &str, -) -> AgentTurnProof { - test_cli_agent_turn_proof_with_input(generation, provider_name, model_name, "prx test routing input") -} - -#[cfg(test)] -pub(crate) fn test_cli_agent_turn_proof_with_input( - generation: &crate::config::ConfigGeneration, - provider_name: &str, - model_name: &str, - routing_input: &str, -) -> AgentTurnProof { - test_cli_agent_turn_proof_with_run(generation, provider_name, model_name, routing_input, "prx_test_run") -} - -#[cfg(test)] -pub(crate) fn test_cli_agent_turn_proof_with_run( - generation: &crate::config::ConfigGeneration, - provider_name: &str, - model_name: &str, - routing_input: &str, - run_id: &str, -) -> AgentTurnProof { - let envelope = RuntimeEnvelope::agent(generation.effective.workspace_dir.to_string_lossy(), run_id) - .with_config_generation(generation); - issue_cli_agent_turn_proof( - None, - &envelope, - generation, - run_id, - routing_input, - None, - &resolve_agent_model_choice(&generation.effective, Some(provider_name), Some(model_name), None) - .expect("test selected model"), - ) - .expect("test CLI Agent proof") -} - -#[cfg(test)] -pub(crate) async fn test_recorded_cli_agent_turn_proof( - generation: &crate::config::ConfigGeneration, - memory: Arc, -) -> AgentTurnProof { - test_recorded_cli_agent_turn_proof_with_input(generation, memory, "prx test routing input", "prx_test_run").await -} - -#[cfg(test)] -pub(crate) async fn test_recorded_cli_agent_turn_proof_with_input( - generation: &crate::config::ConfigGeneration, - memory: Arc, - input: &str, - run_id: &str, -) -> AgentTurnProof { - test_recorded_cli_agent_turn_proof_with_selection(generation, memory, input, run_id, ("ollama", "prx-local-model")) - .await -} - -#[cfg(test)] -pub(crate) async fn test_recorded_cli_agent_turn_proof_with_selection( - generation: &crate::config::ConfigGeneration, - memory: Arc, - input: &str, - run_id: &str, - selection: (&str, &str), -) -> AgentTurnProof { - let envelope = RuntimeEnvelope::agent(generation.effective.workspace_dir.to_string_lossy(), run_id) - .with_config_generation(generation); - let fabric = crate::memory::MemoryFabric::new(memory, generation.effective.workspace_dir.to_string_lossy()) - .with_event_recording(generation.effective.memory.event_recording_config()); - let event = fabric - .record_inbound_user_message(envelope.message_scope(), input, None, None) - .await - .expect("persisted inbound event"); - issue_cli_agent_turn_proof( - None, - &envelope, - generation, - run_id, - input, - Some(&event), - &resolve_agent_model_choice(&generation.effective, Some(selection.0), Some(selection.1), None) - .expect("test selected model"), - ) - .expect("recorded CLI Agent proof") -} - -#[cfg(test)] -pub(crate) async fn test_recovery_cli_agent_turn_proof_with_selection( - generation: &crate::config::ConfigGeneration, - memory: Arc, - input: &str, - run_id: &str, - selection: (&str, &str), -) -> AgentTurnProof { - let envelope = RuntimeEnvelope::agent(generation.effective.workspace_dir.to_string_lossy(), run_id) - .with_config_generation(generation); - let owner = Arc::new(crate::runtime::turn_cleanup::CleanupTracker::default()); - let ticket = owner - .register(tokio_util::sync::CancellationToken::new()) - .expect("test: ingress owner"); - let fabric = crate::memory::MemoryFabric::new(memory, generation.effective.workspace_dir.to_string_lossy()) - .with_event_recording(generation.effective.memory.event_recording_config()) - .with_ingress_recovery(&generation.effective, &ticket) - .await - .expect("test: recovery ingress fabric"); - let event = fabric - .record_inbound_user_message( - envelope.message_scope(), - input, - Some(format!("prx:terminal-fixture:{run_id}:input")), - None, - ) - .await - .expect("test: recovery input"); - let proof = issue_cli_agent_turn_proof( - None, - &envelope, - generation, - run_id, - input, - Some(&event), - &resolve_agent_model_choice(&generation.effective, Some(selection.0), Some(selection.1), None) - .expect("test: selected recovery model"), - ) - .expect("test: recovery CLI proof"); - drop(fabric); - ticket.finish(true); - owner - .drain(tokio::time::Instant::now() + std::time::Duration::from_secs(5)) - .await - .expect("test: ingress owner drained"); - proof -} - -#[cfg(test)] -mod agent_turn_origin_tests { - use super::*; - - fn inbound_event( - envelope: &RuntimeEnvelope, - generation: &crate::config::ConfigGeneration, - content: &str, - ) -> crate::memory::MessageEvent { - crate::memory::MessageEvent { - id: 1, - event_id: "recorded_event".to_string(), - idempotency_key: None, - workspace_id: envelope.workspace_id.clone(), - owner_id: Some(envelope.resolved_owner_id()), - source: crate::memory::MessageEventSource::Agent, - channel: Some("cli".to_string()), - session_key: Some(envelope.session_key.clone()), - parent_session_key: None, - run_id: envelope.run_id.clone(), - parent_run_id: None, - agent_id: None, - persona_id: None, - sender: Some("local-user".to_string()), - recipient: None, - role: "user".to_string(), - event_type: "message.created".to_string(), - subject: None, - goal_id: None, - causation_event_id: None, - correlation_id: None, - attempt_id: None, - lease_epoch: None, - config_generation_id: Some(generation.id.0), - config_source_revision: Some(generation.source_revision.fingerprint_sha256.clone()), - content: content.to_string(), - content_hash: None, - raw_payload_json: None, - visibility: envelope.visibility.clone(), - created_at: "2026-01-01T00:00:00Z".to_string(), - updated_at: "2026-01-01T00:00:00Z".to_string(), - } - } - - #[tokio::test] - async fn cli_proof_binds_pinned_generation_and_recorded_inbound_event() { - let workspace = tempfile::tempdir().expect("test workspace"); - let mut config = Config::default(); - config.workspace_dir = workspace.path().to_path_buf(); - let generation = crate::config::new_shared(config).pin(); - let envelope = - RuntimeEnvelope::agent(workspace.path().to_string_lossy(), "prx_run").with_config_generation(&generation); - let memory: Arc = - Arc::new(crate::memory::SqliteMemory::new(workspace.path()).expect("test message-event backend")); - let fabric = MemoryFabric::new(memory, workspace.path().to_string_lossy()) - .with_event_recording(generation.effective.memory.event_recording_config()); - let event = fabric - .record_inbound_user_message(envelope.message_scope(), "raw request", None, None) - .await - .expect("persisted inbound receipt"); - assert!(event.id > 0); - let proof = issue_cli_agent_turn_proof( - None, - &envelope, - &generation, - "prx_run", - "raw request", - Some(&event), - &resolve_agent_model_choice(&generation.effective, Some("ollama"), Some("prx-local-model"), None) - .expect("test selected model"), - ) - .expect("local CLI origin"); - assert_eq!(proof.workspace_id(), workspace.path().to_string_lossy()); - assert_eq!(proof.session_key(), "agent:prx_run"); - assert_eq!(proof.run_id(), "prx_run"); - assert!(!event.event_id.is_empty(), "expected a non-empty value"); - assert_eq!(proof.source_event_id(), Some(event.event_id.as_str())); - assert_eq!(proof.routing_input(), "raw request"); - assert_eq!(proof.provider_name(), "ollama"); - assert_eq!(proof.model_name(), "prx-local-model"); - assert_eq!(proof.config_generation_id(), generation.id.0); - let expected_scope = envelope.memory_write_context("private"); - assert_eq!(proof.memory_scope().workspace_id, expected_scope.workspace_id); - assert_eq!(proof.memory_scope().channel, expected_scope.channel); - assert_eq!(proof.memory_scope().chat_id, expected_scope.chat_id); - assert_eq!(proof.memory_scope().sender_id, expected_scope.sender_id); - assert_eq!(proof.memory_scope().raw_sender, expected_scope.raw_sender); - assert_eq!(proof.memory_scope().owner_id, expected_scope.owner_id); - assert_eq!( - proof.config_source_revision(), - generation.source_revision.fingerprint_sha256 - ); - assert_eq!( - proof.owner_id(), - crate::memory::principal::OwnerPrincipal::new( - workspace.path().to_string_lossy(), - "cli", - "local-user", - "agent:prx_run", - vec![crate::memory::principal::Role::Anonymous], - ) - .owner_id - ); - crate::runtime::turn_context::validate_agent_turn_origin( - &generation, - crate::tools::capability::turn_state::TurnSurfaceKind::AgentLoop, - &proof, - ) - .expect("service accepts the pinned Agent origin"); - assert!( - crate::runtime::turn_context::validate_agent_turn_origin( - &generation, - crate::tools::capability::turn_state::TurnSurfaceKind::Interactive, - &proof, - ) - .is_err() - ); - } - - #[tokio::test] - async fn repl_proof_and_admission_failure_bind_session_independently_of_run() { - let workspace = tempfile::tempdir().expect("test workspace"); - let mut config = Config::default(); - config.workspace_dir = workspace.path().to_path_buf(); - let generation = crate::config::new_shared(config).pin(); - let envelope = RuntimeEnvelope::agent(workspace.path().to_string_lossy(), "prx_session") - .with_run_id("prx_turn") - .with_config_generation(&generation); - let fabric = MemoryFabric::new( - Arc::new(crate::memory::SqliteMemory::new(workspace.path()).expect("actual source memory")), - workspace.path().to_string_lossy(), - ); - let event = fabric - .record_inbound_user_message(envelope.message_scope(), "raw", None, None) - .await - .expect("persist inbound receipt"); - let choice = resolve_agent_model_choice(&generation.effective, Some("ollama"), Some("prx-local-model"), None) - .expect("test selected model"); - let issue = |identity| { - issue_cli_agent_turn_proof_for_session(None, &envelope, &generation, identity, "raw", Some(&event), &choice) - }; - assert!(issue(("prx_turn", "agent:other_session")).is_err()); - assert!(issue(("other_turn", "agent:prx_session")).is_err()); - let proof = issue(("prx_turn", "agent:prx_session")).expect("REPL proof"); - assert_eq!(proof.session_key(), "agent:prx_session"); - proof - .record_cli_admission_failure(&fabric, &generation.effective, false, "test refusal") - .await - .expect("persist admission failure"); - let failure = fabric - .memory() - .find_message_event_by_idempotency_key(fabric.workspace_id(), "turn:prx_turn:admission-failed") - .await - .expect("failure lookup") - .expect("durable failure event"); - assert_eq!(failure.session_key.as_deref(), Some("agent:prx_session")); - assert_eq!(failure.owner_id, Some(envelope.resolved_owner_id())); - assert_eq!(failure.run_id.as_deref(), Some("prx_turn")); - } - - #[tokio::test] - async fn missing_or_synthetic_inbound_receipt_confers_no_source_event() { - let workspace = tempfile::tempdir().expect("test workspace"); - let mut config = Config::default(); - config.workspace_dir = workspace.path().to_path_buf(); - config.memory.events.record_user_messages = false; - let generation = crate::config::new_shared(config).pin(); - let envelope = - RuntimeEnvelope::agent(workspace.path().to_string_lossy(), "prx_run").with_config_generation(&generation); - let choice = resolve_agent_model_choice(&generation.effective, Some("ollama"), Some("prx-local-model"), None) - .expect("test selected model"); - let fabric = MemoryFabric::new( - Arc::new(crate::memory::NoneMemory::new()), - workspace.path().to_string_lossy(), - ) - .with_event_recording(generation.effective.memory.event_recording_config()); - let synthetic = fabric - .record_inbound_user_message(envelope.message_scope(), "raw", None, None) - .await - .expect("disabled user-event recording yields a synthetic receipt"); - assert_eq!(synthetic.id, 0); - assert!(!synthetic.event_id.is_empty(), "expected a non-empty value"); - let failing_fabric = MemoryFabric::new( - Arc::new(crate::memory::MarkdownMemory::new(workspace.path())), - workspace.path().to_string_lossy(), - ); - assert!( - failing_fabric - .record_inbound_user_message(envelope.message_scope(), "raw", None, None) - .await - .is_err(), - "an enabled record path must report a failed append" - ); - // P2-R22: an unrecorded turn is never refused, but a missing or - // synthetic receipt never attests a source event for it. - for receipt in [None, Some(&synthetic)] { - let proof = issue_cli_agent_turn_proof(None, &envelope, &generation, "prx_run", "raw", receipt, &choice) - .expect("an unrecorded CLI turn is not refused"); - assert_eq!( - proof.source_event_id(), - None, - "a missing or synthetic receipt confers no source event" - ); - } - let persisted = inbound_event(&envelope, &generation, "raw"); - let proof = issue_cli_agent_turn_proof( - None, - &envelope, - &generation, - "prx_run", - "raw", - Some(&persisted), - &choice, - ) - .expect("a persisted receipt issues the proof"); - assert_eq!(proof.source_event_id(), Some(persisted.event_id.as_str())); - let mut foreign = persisted; - foreign.run_id = Some("other_run".to_string()); - assert!( - issue_cli_agent_turn_proof(None, &envelope, &generation, "prx_run", "raw", Some(&foreign), &choice) - .is_err() - ); - foreign.run_id = Some("prx_run".to_string()); - foreign.parent_run_id = Some("nested_run".to_string()); - assert!( - issue_cli_agent_turn_proof(None, &envelope, &generation, "prx_run", "raw", Some(&foreign), &choice) - .is_err() - ); - } - - #[tokio::test] - async fn disabled_agent_does_not_claim_synthetic_inbound_lineage() { - let workspace = tempfile::tempdir().expect("test workspace"); - let mut config = Config::default(); - config.workspace_dir = workspace.path().to_path_buf(); - config.memory.events.record_user_messages = false; - let generation = crate::config::new_shared(config).pin(); - let envelope = - RuntimeEnvelope::agent(workspace.path().to_string_lossy(), "prx_run").with_config_generation(&generation); - let choice = resolve_agent_model_choice(&generation.effective, Some("ollama"), Some("prx-local-model"), None) - .expect("test selected model"); - let fabric = MemoryFabric::new( - Arc::new(crate::memory::NoneMemory::new()), - workspace.path().to_string_lossy(), - ) - .with_event_recording(generation.effective.memory.event_recording_config()); - let synthetic = fabric - .record_inbound_user_message(envelope.message_scope(), "raw", None, None) - .await - .expect("disabled user-event recording yields a synthetic receipt"); - assert_eq!(synthetic.id, 0); - for receipt in [None, Some(&synthetic)] { - let proof = issue_cli_agent_turn_proof(None, &envelope, &generation, "prx_run", "raw", receipt, &choice) - .expect("disabled plane may run builtin without a persisted inbound event"); - assert_eq!(proof.source_event_id(), None); - } - } - - #[tokio::test] - async fn selected_memory_read_rejects_a_different_cli_turn_with_the_same_query() { - let workspace = tempfile::tempdir().expect("test workspace"); - let mut config = Config::default(); - config.workspace_dir = workspace.path().to_path_buf(); - let generation = crate::config::new_shared(config).pin(); - let choice = resolve_agent_model_choice(&generation.effective, Some("ollama"), Some("prx-local-model"), None) - .expect("test selected model"); - let workspace_id = workspace.path().to_string_lossy(); - let envelope_a = RuntimeEnvelope::agent(workspace_id.as_ref(), "prx_run_a").with_config_generation(&generation); - let envelope_b = RuntimeEnvelope::agent(workspace_id.as_ref(), "prx_run_b").with_config_generation(&generation); - let fabric = MemoryFabric::new( - Arc::new(crate::memory::SqliteMemory::new(workspace.path()).expect("actual source memory")), - workspace_id.as_ref(), - ); - let inbound_a = fabric - .record_inbound_user_message(envelope_a.message_scope(), "same query", None, None) - .await - .expect("persist first ingress"); - let inbound_b = fabric - .record_inbound_user_message(envelope_b.message_scope(), "same query", None, None) - .await - .expect("persist second ingress"); - let proof_a = issue_cli_agent_turn_proof( - None, - &envelope_a, - &generation, - "prx_run_a", - "same query", - Some(&inbound_a), - &choice, - ) - .expect("first source proof"); - let proof_b = issue_cli_agent_turn_proof( - None, - &envelope_b, - &generation, - "prx_run_b", - "same query", - Some(&inbound_b), - &choice, - ) - .expect("second source proof"); - assert_eq!(proof_a.routing_input(), proof_b.routing_input()); - assert_eq!(proof_a.owner_id(), proof_b.owner_id()); - assert_ne!(proof_a.session_key(), proof_b.session_key()); - let mut trusted = crate::decision_engine::state::fixtures::trusted(); - trusted.surface = crate::tools::capability::turn_state::TurnSurfaceKind::AgentLoop; - trusted.channel = None; - trusted.workspace_id = Arc::from(proof_a.workspace_id()); - trusted.owner_id = Some(Arc::from(proof_a.owner_id())); - trusted.session_key = Some(Arc::from(proof_a.session_key())); - trusted.run_id = Some(Arc::from(proof_a.run_id())); - trusted.source_event_id = proof_a.source_event_id().map(Arc::from); - trusted.resolved_model = Arc::from("prx:model"); - trusted.policy_version = Arc::from("policy-v1"); - trusted.exclusions.clear(); - let verify = crate::runtime::turn_context::validate_agent_retrieval_provenance; - assert!(verify(&proof_a, &trusted, "prx:model", "policy-v1", &[]).is_ok()); - assert!(verify(&proof_b, &trusted, "prx:model", "policy-v1", &[]).is_err()); - trusted.owner_id = Some(Arc::from("prx_foreign_owner")); - assert!(verify(&proof_a, &trusted, "prx:model", "policy-v1", &[]).is_err()); - trusted.owner_id = Some(Arc::from(proof_a.owner_id())); - trusted.source_event_id = Some(Arc::from("foreign-event")); - assert!(verify(&proof_a, &trusted, "prx:model", "policy-v1", &[]).is_err()); - trusted.source_event_id = proof_a.source_event_id().map(Arc::from); - assert!(verify(&proof_a, &trusted, "foreign:model", "policy-v1", &[]).is_err()); - assert!(verify(&proof_a, &trusted, "prx:model", "foreign-policy", &[]).is_err()); - assert!(verify(&proof_a, &trusted, "prx:model", "policy-v1", &[Arc::from("blocked")]).is_err()); - } - - #[tokio::test] - async fn override_and_mismatched_generation_cannot_issue_cli_proof() { - let workspace = tempfile::tempdir().expect("test workspace"); - let mut config = Config::default(); - config.workspace_dir = workspace.path().to_path_buf(); - let generation = crate::config::new_shared(config).pin(); - let good = resolve_agent_turn_envelope(None, &workspace.path().to_string_lossy(), "prx_run") - .with_config_generation(&generation); - let interactive = RuntimeEnvelope::agent(workspace.path().to_string_lossy(), "prx_run") - .with_recipient("cli:local-user") - .with_config_generation(&generation); - let choice = resolve_agent_model_choice(&generation.effective, Some("ollama"), Some("prx-local-model"), None) - .expect("test selected model"); - let fabric = MemoryFabric::new( - Arc::new(crate::memory::SqliteMemory::new(workspace.path()).expect("actual source memory")), - workspace.path().to_string_lossy(), - ); - let inbound = fabric - .record_inbound_user_message(good.message_scope(), "raw", None, None) - .await - .expect("persist actual ingress"); - for envelope in [&good, &interactive] { - assert!( - issue_cli_agent_turn_proof(None, envelope, &generation, "prx_run", "raw", Some(&inbound), &choice) - .is_ok(), - "ordinary CLI envelope must retain Agent proof eligibility" - ); - } - let rejected = |envelope: &RuntimeEnvelope, override_envelope: Option<&RuntimeEnvelope>| { - assert!( - issue_cli_agent_turn_proof( - override_envelope, - envelope, - &generation, - "prx_run", - "raw", - Some(&inbound), - &resolve_agent_model_choice(&generation.effective, Some("ollama"), Some("prx-local-model"), None) - .expect("test selected model"), - ) - .is_err() - ); - }; - rejected(&good, Some(&good)); - let mut wrong_source = good.clone(); - wrong_source.source = RuntimeSource::Cron; - rejected(&wrong_source, None); - let mut wrong_id = good.clone(); - wrong_id.config_generation_id = Some(generation.id.0.saturating_add(1)); - rejected(&wrong_id, None); - let mut wrong_revision = good.clone(); - wrong_revision.config_source_revision = Some("stale".to_string()); - rejected(&wrong_revision, None); - let mut wrong_workspace = good.clone(); - wrong_workspace.workspace_id = "other_workspace".to_string(); - rejected(&wrong_workspace, None); - let mut wrong_run = good.clone(); - wrong_run.run_id = Some("other_run".to_string()); - wrong_run.session_key = "agent:other_run".to_string(); - rejected(&wrong_run, None); - let mut forged_event = good.clone(); - forged_event.source_message_event_id = Some("untrusted_event".to_string()); - rejected(&forged_event, None); - let mut forged_owner = good; - forged_owner.owner_id = Some("untrusted_owner".to_string()); - rejected(&forged_owner, None); - let mut nested = forged_owner; - nested.owner_id = None; - nested.parent_run_id = Some("parent_run".to_string()); - rejected(&nested, None); - nested.parent_run_id = None; - nested.task_id = Some("child_task".to_string()); - rejected(&nested, None); - nested.task_id = None; - nested.attempt_id = Some("child_attempt".to_string()); - rejected(&nested, None); - nested.attempt_id = None; - nested.recipient = Some("foreign:recipient".to_string()); - rejected(&nested, None); - } - - /// P2-R22 and controller ruling CR-CI-1: no spelling check exists at - /// proof issuance. A receipt-less CLI proof issues and binds the - /// PMM-trimmed model on the direct and the hint route. - #[test] - fn raw_model_spelling_issues_a_proof_bound_to_the_pmm_model_on_direct_and_hint_routes() { - let workspace = tempfile::tempdir().expect("test workspace"); - let mut config = Config::default(); - config.workspace_dir = workspace.path().to_path_buf(); - config.default_provider = Some("ollama".to_string()); - config.default_model = Some("prx-local-model ".to_string()); - let direct = resolve_agent_model_choice(&config, None, None, None).expect("PMM trims direct model"); - let direct_generation = crate::config::new_shared(config.clone()).pin(); - let direct_envelope = RuntimeEnvelope::agent(workspace.path().to_string_lossy(), "prx_run") - .with_config_generation(&direct_generation); - let proof = issue_cli_agent_turn_proof( - None, - &direct_envelope, - &direct_generation, - "prx_run", - "ping", - None, - &direct, - ) - .expect("the direct route issues a proof"); - assert_eq!(proof.model_binding().pinned_model(), "prx-local-model"); - assert_eq!(proof.source_event_id(), None); - - config.default_model = Some("prx-local-model".to_string()); - config.model_routes.push(crate::config::ModelRouteConfig { - settings: Default::default(), - hint: "fast".to_string(), - provider: "ollama".to_string(), - model: "prx-route-model ".to_string(), - api_key: None, - credential_ref: None, - }); - let hint = resolve_agent_model_choice(&config, None, Some("hint:fast"), None).expect("PMM trims route model"); - let hint_generation = crate::config::new_shared(config).pin(); - let hint_envelope = RuntimeEnvelope::agent(workspace.path().to_string_lossy(), "prx_run") - .with_config_generation(&hint_generation); - let proof = issue_cli_agent_turn_proof(None, &hint_envelope, &hint_generation, "prx_run", "ping", None, &hint) - .expect("the hint route issues a proof"); - assert_eq!(proof.model_binding().pinned_model(), "prx-route-model"); - } - - /// P2-R22 and controller ruling CR-CI-1: the OAuth placeholder root - /// issues a proof on the resolved provider and model. Whether the - /// placeholder becomes key material is decided at provider construction - /// (the OAuth context), not at the proof boundary. - #[test] - fn oauth_placeholder_root_issues_a_proof_on_the_resolved_provider_and_model() { - let workspace = tempfile::tempdir().expect("test workspace"); - let mut config = Config::default(); - config.workspace_dir = workspace.path().to_path_buf(); - config.default_provider = Some("qwen-code".to_string()); - config.default_model = Some("qwen3-coder-plus".to_string()); - config.api_key = Some("qwen-oauth".to_string()); - let choice = resolve_agent_model_choice(&config, None, None, None).expect("PMM root placeholder selection"); - let generation = crate::config::new_shared(config).pin(); - let envelope = - RuntimeEnvelope::agent(workspace.path().to_string_lossy(), "prx_run").with_config_generation(&generation); - let proof = issue_cli_agent_turn_proof(None, &envelope, &generation, "prx_run", "ping", None, &choice) - .expect("the placeholder root issues a proof"); - assert_eq!(proof.model_binding().pinned_model(), "qwen3-coder-plus"); - assert_eq!(proof.model_binding().pinned_model(), choice.binding().pinned_model()); - assert_eq!(proof.provider_name(), choice.provider_name()); - } -} - -/// The provider and model an agent entry runs on, resolved and owned. -/// -/// The internal agent engine (cron and xin agent jobs, skill evaluation) -/// resolves their selection with -/// [`resolve_agent_model_choice`] before anything is constructed: before the -/// runtime bootstrap (memory hygiene, snapshots, the database, plugins, -/// tools), so a refused selection leaves no trace (D-065 M-1). -#[derive(Clone)] -pub(crate) struct AgentModelChoice { - provider_name: String, - model_name: String, - model_binding: AgentModelBinding, - resolved: crate::providers::catalog::ResolvedModel, - catalog: crate::providers::catalog::CatalogView, -} - -impl AgentModelChoice { - pub(crate) const fn binding(&self) -> &AgentModelBinding { - &self.model_binding - } - - pub(crate) fn provider_name(&self) -> &str { - &self.provider_name - } - - pub(crate) fn model_name(&self) -> &str { - &self.model_name - } - - pub(crate) const fn catalog(&self) -> &crate::providers::catalog::CatalogView { - &self.catalog - } - - /// An injected provider may switch model IDs only within the connection - /// identity already owned by that instance and pinned configuration. - pub(crate) fn same_provider_connection(&self, other: &Self) -> bool { - self.model_binding.provider == other.model_binding.provider - && self.model_binding.provider_label == other.model_binding.provider_label - && self.model_binding.credential_ref == other.model_binding.credential_ref - && self.model_binding.credential_has_key == other.model_binding.credential_has_key - } - - pub(crate) fn resolved_selection(&self) -> (&str, &str) { - (&self.model_binding.provider_label, &self.model_binding.model) - } - - /// Re-resolve the selected source against the pinned configuration and - /// require the complete resolver release, including credential material, - /// to be unchanged. Provider construction consumes `self.resolved` - /// directly, so unrelated routes no longer affect this attestation. - pub(crate) fn factory_credential_source_matches(&self, config: &Config) -> bool { - if self.provider_name.trim() != self.provider_name { - return false; - } - let route = match providers::selection::route_target(&self.catalog, &self.provider_name, &self.model_name) { - Ok(route) => route.cloned(), - Err(_) => return false, - }; - if route != self.model_binding.route { - return false; - } - providers::selection::check_with( - config, - &self.catalog, - &self.provider_name, - &self.model_name, - self.resolved.credential().reference().clone(), - &providers::catalog::Requirement::chat(), - providers::catalog::UnknownPolicy::Invocation, - ) - .is_ok_and(|fresh| fresh == self.resolved) - } -} - -/// Identity selected before provider construction. It deliberately excludes -/// credential material: the provider factory must receive its own pinned -/// material, while the decision service can compare route and owner facts. -#[derive(Clone)] -pub(crate) struct AgentModelBinding { - provider: crate::providers::ProviderId, - provider_label: Arc, - model: Arc, - credential_ref: crate::providers::credentials::CredentialRef, - route: Option, - verification: crate::providers::catalog::Verification, - source: crate::providers::catalog::DescriptorSource, - dialects: crate::providers::catalog::Dialects, - credential_has_key: bool, -} - -impl AgentModelBinding { - /// Admit only the source spelling or the provider/model pinned at ingress. - pub(crate) fn admits_execution(&self, source: (&str, &str), execution: (&str, &str)) -> bool { - execution == source || execution == (self.provider_label.as_ref(), self.model.as_ref()) - } - - /// The model pinned at ingress, independent of any route spelling used to execute it. - pub(crate) fn pinned_model(&self) -> &str { - &self.model - } - - /// The provider pinned at ingress: the one a route spelling (`hint:`) - /// resolved to, which may differ from the provider the selection named. - pub(crate) fn pinned_provider_label(&self) -> &str { - &self.provider_label - } - - pub(crate) const fn credential_reference(&self) -> &crate::providers::credentials::CredentialRef { - &self.credential_ref - } - - pub(crate) fn from_resolved( - resolved: &crate::providers::catalog::ResolvedModel, - route: Option, - ) -> Self { - Self { - provider: resolved.provider().clone(), - provider_label: Arc::from(resolved.provider_label()), - model: Arc::from(resolved.model()), - credential_ref: resolved.credential().reference().clone(), - route, - verification: resolved.verification().clone(), - source: resolved.source(), - dialects: resolved.dialects(), - credential_has_key: resolved.credential().api_key().is_some(), - } - } - - pub(crate) fn matches_identity(&self, resolved: &crate::providers::catalog::ResolvedModel) -> bool { - self.provider == *resolved.provider() - && self.provider_label.as_ref() == resolved.provider_label() - && self.model.as_ref() == resolved.model() - && self.credential_ref == *resolved.credential().reference() - } - - pub(crate) fn matches(&self, resolved: &crate::providers::catalog::ResolvedModel) -> bool { - self.matches_identity(resolved) - && self.verification == *resolved.verification() - && self.source == resolved.source() - && self.dialects == resolved.dialects() - } - - pub(crate) const fn route(&self) -> Option<&crate::providers::catalog::RouteTarget> { - self.route.as_ref() - } -} - -/// Resolve the selection for an agent entry, check-only. -/// -/// This is the one resolution of the entry. An operator's invocation runs an -/// id-only model with a warning and refuses one the evidence rules out -/// (D-034). The chain the entry builds is routed, so every `[[model_routes]]` -/// destination is resolved when the routed provider is built, and a `hint:` -/// model is checked as the destination it names (D-035). -pub(crate) fn resolve_agent_model_choice( - config: &Config, - provider_override: Option<&str>, - model_override: Option<&str>, - creator_agent: Option<&str>, -) -> Result { - use crate::providers::credentials::{CredentialRef, LegacySlot}; - let named = creator_agent - .map(|name| config.agents.get(name).ok_or_else(|| anyhow::anyhow!("creator_gone"))) - .transpose()?; - let provider_name = named.map_or_else( - || provider_override.unwrap_or_else(|| providers::selection::default_provider(config)), - |agent| agent.provider.as_str(), - ); - let model_name = named.map_or_else( - || model_override.unwrap_or_else(|| providers::selection::default_model(config)), - |agent| agent.model.as_str(), - ); - let credential = named.map_or_else( - || providers::selection::credential_for(config, provider_name), - |agent| { - agent.credential_ref.as_ref().map_or_else( - || { - if agent.api_key.as_deref().is_some_and(|key| !key.trim().is_empty()) { - CredentialRef::LegacyInline(LegacySlot::Agent(creator_agent.unwrap_or_default().to_owned())) - } else { - providers::selection::credential_for(config, provider_name) - } - }, - |id| CredentialRef::Profile { id: id.clone() }, - ) - }, - ); - let catalog = providers::selection::catalog_for(config); - let route = providers::selection::route_target(&catalog, provider_name, model_name)?.cloned(); - let resolved = providers::selection::check_with( - config, - &catalog, - provider_name, - model_name, - credential, - &providers::catalog::Requirement::chat(), - providers::catalog::UnknownPolicy::Invocation, - ) - .map_err(|refusal| providers::selection::route_refusal(route.as_ref(), refusal))?; - Ok(AgentModelChoice { - provider_name: provider_name.to_string(), - model_name: model_name.to_string(), - model_binding: AgentModelBinding::from_resolved(&resolved, route), - resolved, - catalog, - }) -} - -/// The provider an agent entry runs on, and the only connection it may use. -/// -/// The root credential, base URL and rotation keys are released only when -/// the resolved selection is the provider identity they were configured for. -/// Anything else resolves its own credential (auth profile, or none for a -/// keyless `custom:` endpoint) or is refused at construction, before any -/// transport exists. -pub(crate) struct AgentProviderSelection<'a> { - pub(crate) provider_name: &'a str, - pub(crate) model_name: &'a str, - resolved: &'a crate::providers::catalog::ResolvedModel, - catalog: &'a crate::providers::catalog::CatalogView, -} - -/// Scope the connection for a resolved selection. Resolution already ran in -/// [`resolve_agent_model_choice`]; this does not resolve again. -pub(crate) fn agent_provider_selection(choice: &AgentModelChoice) -> AgentProviderSelection<'_> { - AgentProviderSelection { - provider_name: &choice.provider_name, - model_name: &choice.model_name, - resolved: &choice.resolved, - catalog: &choice.catalog, - } -} - -impl AgentProviderSelection<'_> { - /// Build the routed provider chain from the resolver-owned selection. - pub(crate) fn build_provider( - &self, - config: &Config, - options: &providers::ProviderRuntimeOptions, - ) -> Result> { - providers::create_routed_provider_for(self.resolved, self.catalog, config, options) - } -} - -/// P0-B: a provider override on the agent entry must give the override only its own -/// credential. Driven through the production seam, the real factory and a -/// loopback endpoint; every credential is a sentinel and the config directory -/// is a fresh temporary one with no auth profiles. -#[path = "turn_tests/entry_provider_selection.rs"] -mod agent_provider_selection_tests; - -/// Run the Agent entry with a caller-owned runtime envelope. This preserves -/// owner/topic/task/source lineage for scheduler-driven single-shot turns while -/// keeping the public CLI entrypoint's existing defaults. -/// -/// `scheduled_tool_scope` is the tool context and policy a cron job or xin -/// task runs under when its `JobOrigin` is not the local operator -/// (CRON-ORIGIN); `None` keeps the local-operator CLI context and policy. It -/// governs a single-shot turn only. -#[allow(clippy::too_many_lines)] -pub(crate) async fn run_with_runtime_envelope( - config_source: impl Into, - message: String, - provider_override: Option, - model_override: Option, - temperature: f64, - shutdown: CancellationToken, - runtime_envelope_override: Option, - scheduled_tool_scope: Option, -) -> Result { - let config_source = config_source.into(); - let config = config_source.effective(); - let named_job = super::automation::select(config, runtime_envelope_override.as_ref())?; - let mut runtime_envelope_override = runtime_envelope_override; - let mut scheduled_tool_scope = scheduled_tool_scope; - if let (Some(job), Some(envelope)) = (&named_job, runtime_envelope_override.as_mut()) { - envelope.agent_partition = Some(job.partition(envelope)); - if let Some(scope) = scheduled_tool_scope.as_mut() { - scope.context.envelope.agent_partition = envelope.agent_partition.clone(); - } - } - let mut scheduled_admission = super::scheduled_source::validate_current( - runtime_envelope_override.as_ref(), - scheduled_tool_scope.as_ref(), - &shutdown, - ) - .await?; - anyhow::ensure!( - runtime_envelope_override.is_none() || scheduled_admission.is_some(), - "agent runtime override requires an admitted scheduled source" - ); - if let (Some(job), Some(admission), Some(envelope)) = ( - &named_job, - scheduled_admission.as_mut(), - runtime_envelope_override.as_ref(), - ) { - admission.job_metadata = Some(job.metadata(envelope)); - } - // Validate scoped identity before bootstrap can initialize persistence. - // Scheduled sources retain their attempt/lease run id through terminal - // recording and child lineage instead of acquiring a second CLI run id. - let scoped_run_id = runtime_envelope_override - .as_ref() - .map(|envelope| { - anyhow::ensure!( - envelope.workspace_id == config.workspace_dir.to_string_lossy() - && !envelope.session_key.trim().is_empty(), - "scoped runtime workspace or session does not match this invocation" - ); - let run_id = envelope - .run_id - .as_deref() - .filter(|run_id| !run_id.trim().is_empty()) - .ok_or_else(|| anyhow::anyhow!("a scoped runtime run requires its source-owned run identity"))?; - Ok::<_, anyhow::Error>(run_id.to_owned()) - }) - .transpose()?; - // Manual scheduled tool calls inherit this owner in ordinary single-shot - // execution. Let the entry's existing shutdown branch close its own turn; - // cancellation of this child scope must not race and drop that branch. - let caller_cleanup = if scheduled_admission.is_none() { - let parent = crate::runtime::turn_cleanup::current_tracker(); - Some(crate::runtime::turn_cleanup::CleanupScope::new( - parent.as_ref(), - CancellationToken::new(), - )?) - } else { - None - }; - - // D-065 M-1: resolve before the bootstrap, so a refused selection runs - // no memory hygiene, snapshot, database, plugin or tool setup. - let temperature = named_job - .as_ref() - .and_then(|job| config.agents.get(job.name.as_str())) - .and_then(|agent| agent.temperature) - .unwrap_or(temperature); - let choice = resolve_agent_model_choice( - config, - provider_override.as_deref(), - model_override.as_deref(), - named_job.as_ref().map(|job| job.name.as_str()), - )?; - // ── Wire up subsystems via RuntimeBootstrap (D1 step 2) ────── - // The internal agent engine is always a full single-shot run with no - // memory-only early-exit (unlike chat's `--list-sessions`), so it always - // needs memory + tools. It uses the dedicated `AgentLoop` profile: identical - // core to `Interactive` (memory + tools, no router), with the published - // source-bound turn decision service. Bootstrap constructs subsystems in - // observer/security/memory/runtime/tools order. - let ctx = crate::runtime::bootstrap::RuntimeBootstrap::build_agent( - config_source, - runtime_envelope_override.as_ref(), - scheduled_tool_scope.as_ref(), - ) - .await?; - - let _agent_permit = if let (Some(job), Some(envelope)) = (&named_job, runtime_envelope_override.as_ref()) { - let memory = ctx - .memory - .as_ref() - .ok_or_else(|| anyhow::anyhow!("agent_backend_unsupported"))?; - job.validate(memory.as_ref(), envelope)?; - let result = - crate::runtime::agent_admission::wait(&ctx.config, &envelope.resolved_owner_id(), job.name.as_str()).await; - // Retirement while waiting must refuse before any provider access. - job.validate(memory.as_ref(), envelope)?; - match result { - Ok(permit) => permit, - Err(error) => { - super::scheduled_source::begin_decision()?; - let fabric = MemoryFabric::new(Arc::clone(memory), envelope.workspace_id.clone()) - .with_event_recording(ctx.config.memory.event_recording_config()); - let payload = serde_json::json!({"job_id":envelope.task_id,"job_version":job.version,"reason":error.to_string(),"retryable":false}); - fabric - .record_runtime_event_idempotent( - envelope.message_scope(), - "scheduled.skipped", - "scheduled run skipped", - Some(serde_json::to_string(&payload)?), - format!("{}:skipped", envelope.run_id.as_deref().unwrap_or_default()), - ) - .await?; - return Err(error.into()); - } - } - } else { - None - }; - - // Scheduled cleanup owns the published writer even if this entry future is - // dropped before a decision or terminal proposal is available. - if scheduled_admission.is_some() { - let cleanup = crate::runtime::turn_cleanup::current_tracker() - .ok_or_else(|| anyhow::anyhow!("scheduled cleanup owner is missing"))?; - if let Some(service) = &ctx.turn_service { - cleanup.retain_service(Arc::clone(service)); - } - } - - // Capture invocation state without constructing the large async work yet. - let work = CliWork { - ctx: &ctx, - choice: &choice, - message, - temperature, - shutdown: &shutdown, - runtime_envelope_override, - scheduled_tool_scope, - scoped_run_id, - scheduled_admission: &scheduled_admission, - }; - // The synchronous factory invokes this closure in its own frame before - // returning the boxed future. The actual engine work remains owned here. - let work = boxed_cli_work(move || async move { - let CliWork { - ctx, - choice, - message, - temperature, - shutdown, - runtime_envelope_override, - scheduled_tool_scope, - scoped_run_id, - scheduled_admission, - } = work; - // `build` took ownership of `config`; reclaim a shared `Arc` for the - // rest of this function. `Arc` deref-coerces to `&Config`, so all the - // `config.xxx` accesses below are unchanged. - let config = Arc::clone(&ctx.config); - - let observer = Arc::clone(&ctx.observer); - let hooks = Arc::clone(&ctx.hooks); - // security is consumed only by tool construction, which now happens inside the - // bootstrap; it is not re-bound here on purpose (no downstream use in `run`). - // The local runtime adapter is likewise built and consumed inside the - // bootstrap, so it is no longer constructed here. - - // ── Memory (the brain) ──────────────────────────────────────── - // The Interactive profile always builds memory, so it is Some here; take it - // explicitly without panicking (iron rules 1/6). - let mem: Arc = ctx - .memory - .clone() - .ok_or_else(|| anyhow::anyhow!("bootstrap did not build a memory backend for the agent CLI"))?; - let memory_fabric = MemoryFabric::new(mem.clone(), config.workspace_dir.to_string_lossy()) - .with_event_recording(config.memory.event_recording_config()); - // One cost outbox pass before the turn (one-shot entry; D§5.2). - crate::runtime::cost_recovery::warn_legacy_files_once(&config.workspace_dir); - crate::runtime::cost_recovery::CostOutboxProjector::run_once( - Arc::clone(&mem), - config.workspace_dir.clone(), - config.cost.clone(), - ) - .await; - // D8-3: run_id is per-turn (generated inside each turn branch as `turn_run_id`), - // no longer a single per-run id held here. - let mut fabric_turn_seq: u64 = 0; - - // ── Tools ──────────────────────────────────────────────────── - // The Interactive profile built the tool registry inside the bootstrap - // (security + runtime + memory all ready) using the identical - // `all_tools_with_runtime` call with the same arguments; take it explicitly. - let tools_registry: Arc>> = ctx - .tools - .clone() - .ok_or_else(|| anyhow::anyhow!("bootstrap did not build the tool registry for the agent CLI"))?; - - // ── Provider (resolved before the bootstrap) ───────────────── - let selection = agent_provider_selection(choice); - let provider_name = selection.provider_name; - let model_name = selection.model_name; - - let provider_runtime_options = providers::provider_runtime_options_from_config(&config); - - let provider: Box = selection.build_provider(&config, &provider_runtime_options)?; - let effective_compaction = crate::providers::context_window::resolve_effective_compaction_config_with_catalog( - &config.agent.compaction, - provider_name, - model_name, - crate::providers::context_window::ContextWindowSources::from_config(&config), - &config.model_routes, - choice.catalog(), - ); - crate::providers::context_window::trace_effective_compaction_resolution(&effective_compaction); - - observer.record_event(&ObserverEvent::AgentStart { - provider: provider_name.to_string(), - model: model_name.to_string(), - }); - hooks - .emit( - HookEvent::AgentStart, - serde_json::json!({ - "provider": provider_name, - "model": model_name, - }), - ) - .await; - - // ── Build system prompt from the canonical prompt context ── - let native_tools = provider - .capabilities_for(model_name, crate::providers::traits::ProviderRequestMode::NonStreaming) - .native_tool_calling; - - // ── Approval manager (supervised mode) ─────────────────────── - let approval_manager = Arc::new(ApprovalManager::new()); - - // ── Execute ────────────────────────────────────────────────── - let start = Instant::now(); - - let mut final_output = String::new(); - - { - let msg = message; - // ── Single-shot turn (D5/D9 step 2) ────────────────────────── - // Race the work against the external shutdown token so a root - // cancel aborts the in-flight turn instead of waiting it out. - fabric_turn_seq += 1; - // Keep the turn identity outside the raced future so a shutdown that - // drops it can still close the shared terminal boundary as Cancelled. - let turn_run_id = scoped_run_id.unwrap_or_else(|| Uuid::new_v4().to_string()); - let mut runtime_envelope = scheduled_admission.as_ref().map_or_else( - || { - resolve_agent_turn_envelope( - runtime_envelope_override.as_ref(), - memory_fabric.workspace_id(), - &turn_run_id, - ) - }, - |admission| admission.envelope().clone(), - ); - if runtime_envelope.config_source_revision.is_none() { - runtime_envelope = runtime_envelope.with_config_generation(&ctx.config_generation); - } - let mut fabric_scope = runtime_envelope - .message_scope() - .with_recipient(format!("{provider_name}/{model_name}")); - let cancel_turn_id = turn_run_id.clone(); - let cancel_scope = parking_lot::Mutex::new(runtime_envelope.message_scope()); - let turn_started_at = chrono::Utc::now(); - let terminal_binding = Arc::new(parking_lot::Mutex::new(None::)); - let admission_proof = std::sync::OnceLock::::new(); - let terminal_guard = std::sync::OnceLock::::new(); - let mut cli_admission_guard = None; - let mut scheduled_input_guard = None; - let retained_provider_trace = Arc::new(crate::agent::turn_contracts::RetainedProviderTrace::default()); - let single_shot = boxed_cli_single_shot(async { - let agent_user_event = if scheduled_admission.is_none() { - let owner = crate::runtime::turn_cleanup::current_tracker() - .ok_or_else(|| anyhow::anyhow!("CLI input cleanup owner missing"))?; - let (event, guard) = CliPendingInput { - fabric: memory_fabric.clone(), - generation: Arc::clone(&ctx.config_generation), - envelope: runtime_envelope.clone(), - expected_session_key: format!("agent:{turn_run_id}"), - scope: fabric_scope.clone(), - choice: choice.clone(), - input: msg.clone(), - key: format!("agent:{turn_run_id}:{fabric_turn_seq}:user"), - ticket: owner.register(shutdown.clone())?, - } - .record() - .await?; - cli_admission_guard = Some(guard); - event - } else { - let admission = scheduled_admission - .as_ref() - .ok_or_else(|| anyhow::anyhow!("scheduled admission source missing"))?; - let owner = crate::runtime::turn_cleanup::current_tracker() - .ok_or_else(|| anyhow::anyhow!("scheduled input cleanup owner missing"))?; - let (event, guard) = admission - .record_guarded( - memory_fabric.clone(), - Arc::clone(&ctx.config_generation), - ( - msg.clone(), - format!("agent:{turn_run_id}:{fabric_turn_seq}:user"), - choice.clone(), - ), - owner.register(shutdown.clone())?, - ) - .await?; - scheduled_input_guard = Some(guard); - event - }; - - let decision_turn = { - let service = ctx - .turn_service - .as_ref() - .ok_or_else(|| anyhow::anyhow!("agent decision service is missing"))?; - let proof = if let Some(admission) = &scheduled_admission { - let source = admission - .bind_input( - mem.as_ref(), - &ctx.config_generation, - &runtime_envelope, - (&msg, choice), - agent_user_event.as_ref(), - shutdown, - ) - .await?; - AgentTurnProof { - workspace_id: Arc::from(source.envelope.workspace_id.as_str()), - owner_id: Arc::from(source.envelope.resolved_owner_id()), - session_key: Arc::from(source.envelope.session_key.as_str()), - run_id: Arc::from(turn_run_id.as_str()), - source_event_id: source.envelope.source_message_event_id.as_deref().map(Arc::from), - routing_input: Arc::from(msg.as_str()), - memory_scope: source - .envelope - .memory_write_context(source.execution.chat_type.as_str()), - provider_name: Arc::from(choice.provider_name()), - model_name: Arc::from(choice.model_name()), - model_binding: choice.binding().clone(), - config_generation_id: ctx.config_generation.id.0, - config_source_revision: Arc::from( - ctx.config_generation.source_revision.fingerprint_sha256.as_str(), - ), - retrieval_principal: source.envelope.memory_principal(), - scheduled: Some(Box::new(source)), - } - } else { - issue_cli_agent_turn_proof( - None, - &runtime_envelope, - &ctx.config_generation, - &turn_run_id, - &msg, - agent_user_event.as_ref(), - choice, - )? - }; - if let Some(source) = proof.scheduled.as_ref() { - runtime_envelope = source.envelope.clone(); - } - // Admission owns the durable input identity. Carry it into - // ordinary completion and cancellation, not just tool calls. - runtime_envelope.source_message_event_id = proof.source_event_id.as_deref().map(str::to_owned); - fabric_scope = runtime_envelope - .message_scope() - .with_recipient(format!("{provider_name}/{model_name}")); - *cancel_scope.lock() = runtime_envelope.message_scope(); - let proof = admission_proof.get_or_init(|| proof); - if scheduled_admission.is_some() { - // Mark before polling decision work: a failed or interrupted - // admission can already have a durable decision identity. - super::scheduled_source::begin_decision()?; - } - let decision = service - .open_issued_turn_context( - proof, - crate::runtime::turn_context::AgentTurnKind::SingleShot, - shutdown, - ) - .await?; - let advice = service.advisory().analyze_turn(decision.runtime(), shutdown).await; - *terminal_binding.lock() = Some(service.terminal_binding(&decision)?); - let cleanup_ticket = if scheduled_admission.is_some() { - scheduled_input_guard - .take() - .ok_or_else(|| anyhow::anyhow!("scheduled input cleanup guard missing"))? - .into_terminal_ticket()? - } else { - cli_admission_guard - .take() - .ok_or_else(|| anyhow::anyhow!("CLI input cleanup guard missing"))? - .into_terminal_ticket()? - }; - let route_decision = crate::llm::route_decision::RouteDecision::single_candidate_for_context( - provider_name, - model_name.to_string(), - runtime_envelope.resolved_owner_id(), - runtime_envelope.session_key.clone(), - runtime_envelope.source_message_event_id.clone(), - None, - "agent_cli_single", - u32::try_from(msg.chars().count() / 4).unwrap_or(u32::MAX), - !tools_registry.is_empty(), - false, - ); - let guard = crate::runtime::turn_terminal::TurnTerminalGuard::new( - cleanup_ticket, - Arc::clone(service), - Arc::clone(&decision), - memory_fabric.clone(), - Arc::clone(&config), - runtime_envelope.clone(), - None, - )? - .with_provider_trace(Arc::clone(&retained_provider_trace), route_decision.clone()); - terminal_guard - .set(guard) - .map_err(|_| anyhow::anyhow!("agent terminal owner already exists"))?; - - (service, proof, decision, route_decision, advice) - }; - - let (decision_service, decision_proof, decision_context, route_decision, advice) = &decision_turn; - let decision_proof = *decision_proof; - let selected_skills = decision_service.agent_prompt_skills(decision_proof, decision_context)?; - let system_prompt = match &named_job { - Some(job) => job.prompt(&config)?, - None => build_runtime_system_prompt(&config, model_name, &selected_skills, native_tools), - }; - - // Auto-save user message to memory (skip short/trivial messages) - if config.memory.should_auto_promote_user_message(&msg) { - let _ = save_current_input( - &memory_fabric, - &turn_run_id, - &runtime_envelope.session_key, - &msg, - agent_user_event.as_ref().map(|event| event.event_id.as_str()), - ) - .await; - } - - // Inject memory context into user message. The routing input is - // pinned from `msg` here, ahead of the enrichment below. - let memory_runtime = cli_turn_memory_runtime( - &mem, - &config.workspace_dir, - &runtime_envelope, - &memory_fabric, - &fabric_scope, - agent_user_event.as_ref().map(|event| event.event_id.as_str()), - ); - let mem_context = crate::agent::context_recall::scoped_recall( - mem.as_ref(), - &crate::agent::context_recall::RecallScope::from_envelope( - &runtime_envelope, - &config.memory, - "private", - ), - &msg, - crate::agent::context_recall::RECALL_CONTEXT_BUDGET, - ) - .await; - let context = mem_context.preamble.clone(); - let enriched = if context.is_empty() { - msg.clone() - } else { - format!("{context}{msg}") - }; - - let mut history = vec![ - ChatMessage::system(&system_prompt), - crate::agent::turn_contracts::inbound_user_message(&enriched), - ]; - - // D8-4: seed a turn-root spawn context so a sub-agent spawned from this - // single-shot agent turn inherits parent_run_id = the per-turn run_id. - let turn_spawn_ctx = crate::tools::sessions_spawn::SpawnExecutionContext::seed_turn_context( - turn_run_id.clone(), - runtime_envelope.session_key.clone(), - ); - let provider_started_at = chrono::Utc::now(); - let runtime_adapter = Some({ - let mut adapter = - configured_cli_tool_adapter(&ctx.security, &tools_registry, &approval_manager, &memory_runtime); - { - let proof = decision_proof; - let mut envelope = runtime_envelope.clone(); - if let Some(event_id) = proof.source_event_id() { - envelope = envelope.with_source_message_event_id(event_id); - } - adapter.tool_execution_context = proof.scheduled.as_ref().map_or_else( - || cli_tool_execution_context(envelope), - |source| source.execution.clone(), - ); - } - if let Some(case) = &ctx.controlled_case { - case.apply(&mut adapter.tool_execution_context)?; - } - adapter.provider_trace = Some(Arc::clone(&retained_provider_trace)); - adapter - }); - let turn_result = crate::tools::execution::with_scheduled_job_tool_scope( - scheduled_tool_scope, - crate::tools::sessions_spawn::SPAWN_EXECUTION_CONTEXT.scope(turn_spawn_ctx, async { - Box::pin(run_turn( - &mut history, - crate::agent::turn_request::TurnRequest { - advice: advice.clone(), - channel_name: "cli", - scope: None, - mode: ChatMode::default(), - silent: false, - expose_stay_silent: false, - multimodal: &config.multimodal, - schedule: crate::agent::turn_request::TurnSchedule { - read_only_tool_concurrency_window: config.agent.read_only_tool_concurrency_window, - priority_scheduling_enabled: config.agent.priority_scheduling_enabled, - low_priority_tool_names: config.agent.low_priority_tools.clone(), - }, - compaction: Some(decision_context.main_compaction()), - decision: crate::agent::turn_request::TurnDecision { - service: decision_service, - context: decision_context, - runtime: decision_context.runtime(), - proof: decision_proof, - }, - }, - crate::agent::turn_request::TurnServices { - provider: provider.as_ref(), - provider_name, - model: model_name, - temperature, - tools_registry: Arc::clone(&tools_registry), - observer: observer.as_ref(), - hooks: &hooks, - approval: Some(Arc::clone(&approval_manager)), - approval_resolver: None, - runtime_adapter, - memory: memory_runtime, - }, - crate::agent::turn_request::TurnDelivery { - cancellation: None, - on_delta: None, - on_tool_call: None, - }, - )) - .await - .map(|(outcome, trace)| (outcome.into_text(), trace)) - }), - ) - .await; - let (response, turn_trace) = match turn_result { - Ok(result) => result, - Err(error) => { - let provider_outcome = if error.is::() { - // No provider attempt belongs to a refused send. The - // terminal guard retains any earlier observed rounds. - None - } else { - Some( - crate::llm::route_decision::ProviderExecutionOutcome::failed_for_decision( - &route_decision, - provider_started_at, - &error, - ), - ) - }; - if let Err(finalize_error) = crate::runtime::turn_terminal::commit_terminal( - terminal_guard.get(), - &memory_fabric, - crate::agent::terminal::TurnTerminalDraft { - binding: terminal_binding_snapshot(&terminal_binding), - terminal_id: turn_run_id.clone(), - scope: runtime_envelope.message_scope(), - status: crate::agent::terminal::TurnTerminalStatus::Failed, - history: None, - history_scope: None, - provider_outcome, - telemetry: crate::agent::terminal::TurnTerminalTelemetry { - summary: error.to_string(), - started_at: provider_started_at, - finished_at: chrono::Utc::now(), - }, - delivery_intent: crate::agent::terminal::TurnDeliveryIntent::ReturnToCaller, - }, - &config, - ) - .await - { - tracing::warn!(error = %crate::agent::diagnostics::error_class(&finalize_error), "Failed to commit failed single-shot agent terminal event"); - } - if !QUIET_SINGLE_SHOT.try_with(|quiet| *quiet).unwrap_or(false) - && let Some(refusal) = - error.downcast_ref::() - { - println!("{}", refusal.reply()); - } - return Err(error); - } - }; - { - let decision = decision_context; - anyhow::ensure!( - turn_trace.execution_trace.as_ref() == Some(&decision.terminal_execution_trace()), - "tool loop trace differs from the owning decision's execution facts" - ); - } - let provider_outcome = crate::agent::terminal::provider_outcome_from_trace( - &route_decision, - provider_started_at, - turn_trace, - ); - if let Err(error) = crate::runtime::turn_terminal::commit_terminal( - terminal_guard.get(), - &memory_fabric, - crate::agent::terminal::TurnTerminalDraft { - binding: terminal_binding_snapshot(&terminal_binding), - terminal_id: turn_run_id.clone(), - scope: runtime_envelope.message_scope(), - status: crate::agent::terminal::TurnTerminalStatus::Completed, - history: Some(crate::agent::terminal::TurnHistoryProjection { - assistant_content: response.clone(), - history_commit_len: history.len(), - }), - history_scope: Some( - fabric_scope - .clone() - .with_sender(format!("{provider_name}/{model_name}")) - .with_recipient("local-user"), - ), - provider_outcome: Some(provider_outcome), - telemetry: crate::agent::terminal::TurnTerminalTelemetry { - summary: "single-shot agent turn completed".to_string(), - started_at: provider_started_at, - finished_at: chrono::Utc::now(), - }, - delivery_intent: crate::agent::terminal::TurnDeliveryIntent::ReturnToCaller, - }, - &config, - ) - .await - { - return Err(error); - } - increment_recalled_useful_counts(mem.as_ref(), &mem_context.ids).await; - final_output = response.clone(); - if !QUIET_SINGLE_SHOT.try_with(|quiet| *quiet).unwrap_or(false) { - println!("{response}"); - } - observer.record_event(&ObserverEvent::TurnComplete); - hooks - .emit( - HookEvent::TurnComplete, - serde_json::json!({ - "mode": "single", - "response_chars": response.chars().count(), - }), - ) - .await; - Ok::<(), anyhow::Error>(()) - }); - let single_result = tokio::select! { - biased; - () = shutdown.cancelled() => { - if terminal_guard.get().is_none() - && terminal_binding_snapshot(&terminal_binding).is_some() - { - let cancelled_scope = cancel_scope.lock().clone(); - if let Err(error) = crate::agent::terminal::finalize_turn( - &memory_fabric, - crate::agent::terminal::TurnTerminalDraft { - binding: terminal_binding_snapshot(&terminal_binding), - terminal_id: cancel_turn_id, - scope: cancelled_scope, - status: crate::agent::terminal::TurnTerminalStatus::Cancelled, - history: None, - history_scope: None, - provider_outcome: None, - telemetry: crate::agent::terminal::TurnTerminalTelemetry { - summary: "single-shot agent cancelled by shutdown signal".to_string(), - started_at: turn_started_at, - finished_at: chrono::Utc::now(), - }, - delivery_intent: crate::agent::terminal::TurnDeliveryIntent::None, - }, - &config.cost, - &config.workspace_dir, - ).await { - tracing::warn!(error = %crate::agent::diagnostics::error_class(&error), "Failed to commit cancelled single-shot agent terminal event"); - } - } - Err(anyhow::anyhow!("agent single-shot run cancelled by shutdown signal")) - } - result = single_shot => result, - }; - if let (Err(error), Some(guard)) = (&single_result, terminal_guard.get()) { - guard.finish_failure(error, shutdown.is_cancelled()).await?; - } - if let Err(error) = &single_result - && let Some(mut guard) = cli_admission_guard.take() - { - guard - .finish_failure(shutdown.is_cancelled(), &error.to_string()) - .await - .map_err(|record_error| { - anyhow::anyhow!( - "CLI admission failed: {error}; failure persistence is unconfirmed: {record_error}" - ) - })?; - } - if single_result.is_err() - && let Some(mut guard) = scheduled_input_guard.take() - { - guard - .finish_failure(shutdown.is_cancelled()) - .await - .map_err(|_| anyhow::anyhow!("scheduled admission failure persistence is unconfirmed"))?; - } - single_result?; - } - - let duration = start.elapsed(); - observer.record_event(&ObserverEvent::AgentEnd { - provider: provider_name.to_string(), - model: model_name.to_string(), - duration, - tokens_used: None, - cost_usd: None, - }); - hooks - .emit( - HookEvent::AgentEnd, - serde_json::json!({ - "duration_ms": duration.as_millis(), - "tokens_used": serde_json::Value::Null, - }), - ) - .await; - - Ok::(final_output) - }); - let result = match caller_cleanup { - Some(cleanup) => cleanup.run(work).await, - None => work.await, - }; - if scheduled_admission.is_none() { - if let Some(service) = &ctx.turn_service { - service - .shutdown(Instant::now() + std::time::Duration::from_secs(2)) - .await; - } - } - // The process may exit right after this run: deliver the queued hook events first. - ctx.hooks.drain_for_shutdown().await; - result -} - -// This invocation state preserves all captures across the boxed work boundary. -struct CliWork<'a> { - ctx: &'a crate::runtime::bootstrap::AppContext, - choice: &'a AgentModelChoice, - message: String, - temperature: f64, - shutdown: &'a CancellationToken, - runtime_envelope_override: Option, - scheduled_tool_scope: Option, - scoped_run_id: Option, - scheduled_admission: &'a Option, -} - -// Invoke the small capture closure here so the large future is constructed -// outside the canonical entry poll frame, then preserve the existing heap seam. -#[inline(never)] -fn boxed_cli_work<'a, F, Fut>( - make_work: F, -) -> std::pin::Pin> + Send + 'a>> -where - F: FnOnce() -> Fut, - Fut: std::future::Future> + Send + 'a, -{ - Box::pin(make_work()) -} - -// Keep the single-turn poll state out of the enclosing CLI select frame. -// The synchronous boundary also keeps Box construction in its own stack frame. -#[inline(never)] -fn boxed_cli_single_shot<'a>( - work: impl std::future::Future> + Send + 'a, -) -> std::pin::Pin> + Send + 'a>> { - Box::pin(work) -} - -fn resolve_agent_turn_envelope( - override_envelope: Option<&RuntimeEnvelope>, - workspace_id: &str, - turn_run_id: &str, -) -> RuntimeEnvelope { - let mut envelope = override_envelope - .cloned() - .unwrap_or_else(|| RuntimeEnvelope::agent(workspace_id.to_string(), turn_run_id.to_string())); - if envelope.recipient.is_none() { - envelope = envelope.with_recipient("cli:local-user"); - } - envelope -} - -#[path = "turn_tests/entry.rs"] -mod tests; - -#[cfg(test)] -mod cli_admission_failure_tests { - use super::*; - - #[tokio::test] - async fn cancelled_admission_retries_without_model_terminal_or_secret() { - let dir = tempfile::tempdir().unwrap(); - let mut config = Config::default(); - config.workspace_dir = dir.path().to_path_buf(); - config.config_path = dir.path().join("config.toml"); - let generation = crate::config::new_shared(config.clone()).pin(); - let memory: Arc = Arc::new(crate::memory::SqliteMemory::new(dir.path()).unwrap()); - let proof = - test_recorded_cli_agent_turn_proof_with_input(&generation, memory.clone(), "prx input", "prx_run").await; - let fabric = MemoryFabric::new(memory.clone(), dir.path().to_string_lossy()); - let summary = format!("cancelled {}", crate::agent::terminal::persistence_probe::PROBE_SECRET); - for _ in 0..2 { - proof - .record_cli_admission_failure(&fabric, &config, true, &summary) - .await - .unwrap(); - } - assert!( - proof - .record_cli_admission_failure(&fabric, &config, false, &summary) - .await - .is_err() - ); - let event = memory - .find_message_event_by_idempotency_key(fabric.workspace_id(), "turn:prx_run:admission-failed") - .await - .unwrap() - .unwrap(); - assert!(event.id > 0); - assert_eq!(event.causation_event_id.as_deref(), proof.source_event_id.as_deref()); - assert!( - memory - .find_message_event_by_idempotency_key(fabric.workspace_id(), "turn:prx_run:final",) - .await - .unwrap() - .is_none() - ); - crate::agent::terminal::persistence_probe::assert_nothing_under_persists_the_probe_secret(dir.path()); - } -} - -pub(crate) fn cli_tool_execution_context(envelope: RuntimeEnvelope) -> crate::tools::ToolExecutionContext { - crate::tools::ToolExecutionContext::new(envelope, "private") - .with_dispatch_origin(crate::tools::DispatchOrigin::Operator) -} +//! Agent entry, model binding and CLI execution. +include!("entry/section_1.rs"); +include!("entry/section_2.rs"); diff --git a/src/agent/entry/section_1.rs b/src/agent/entry/section_1.rs new file mode 100644 index 000000000..936968e61 --- /dev/null +++ b/src/agent/entry/section_1.rs @@ -0,0 +1,1374 @@ + +use crate::agent::context_recall::{current_input_memory_key, increment_recalled_useful_counts}; +use crate::agent::document_ingest::DocumentIngestRuntime; +use crate::agent::runtime_prompt::build_runtime_system_prompt; +use crate::agent::turn_contracts::ChatMode; +use crate::agent::turn_engine::run_turn; +use crate::agent::turn_request::ToolLoopMemory; +use crate::approval::ApprovalManager; +use crate::config::Config; +use crate::hooks::HookEvent; +use crate::memory::{Memory, MemoryCategory, MemoryFabric, MessageEventScope}; +use crate::observability::ObserverEvent; +use crate::providers; +use crate::providers::{ChatMessage, Provider}; +use crate::runtime::envelope::{RuntimeEnvelope, RuntimeSource}; +use crate::tools::Tool; +use anyhow::Result; +use std::path::Path; +use std::sync::Arc; +use std::time::Instant; +use tokio_util::sync::CancellationToken; +use uuid::Uuid; + +// ── Internal single-shot engine ────────────────────────────────────────── +// Wires up all subsystems (observer, runtime, security, memory, tools, +// provider, hardware RAG) and runs one turn for cron, xin, skill evaluation +// and controlled cases. + +tokio::task_local! { + static QUIET_SINGLE_SHOT: bool; +} + +/// Internal evaluations return their answer to the caller without mixing it +/// into the operator command's machine-readable stdout. +pub(crate) async fn run_quiet( + config: Config, + message: String, + temperature: f64, + shutdown: tokio_util::sync::CancellationToken, +) -> anyhow::Result { + QUIET_SINGLE_SHOT + .scope( + true, + Box::pin(run_with_runtime_envelope( + config, + message, + None, + None, + temperature, + shutdown, + None, + None, + )), + ) + .await +} + +/// A controlled case carries its native filesystem capability explicitly +/// through bootstrap, never in Config or model input. +pub(crate) async fn run_quiet_controlled( + config: Config, + message: String, + temperature: f64, + shutdown: CancellationToken, + scope: Arc, +) -> anyhow::Result { + QUIET_SINGLE_SHOT + .scope( + true, + Box::pin(run_with_runtime_envelope( + crate::runtime::bootstrap::AgentRuntimeConfig::ControlledCase { + config: Box::new(config), + scope, + }, + message, + None, + None, + temperature, + shutdown, + None, + None, + )), + ) + .await +} + +/// Persist a live CLI or chat input under its per-run semantic identity. +pub(crate) async fn save_current_input( + fabric: &crate::memory::MemoryFabric, + run: &str, + session_key: &str, + input: &str, + event: Option<&str>, + partition: Option, +) -> anyhow::Result<()> { + let key = current_input_memory_key(run); + fabric + .record_semantic_memory_from_event( + &key, + input, + MemoryCategory::Conversation, + Some(session_key), + event, + None, + None, + partition, + ) + .await +} + +/// Build one CLI turn's memory handles from the turn's own, user-authored text. +/// +/// Every single-shot turn needs these handles (cron jobs, xin tasks, skill +/// evaluation and controlled cases all enter through +/// `run_with_runtime_envelope`). One builder keeps the routing pin from going +/// missing in a hand-copied chain. +/// +/// Routing is supplied separately by the source-bound decision context. +fn cli_turn_memory_runtime( + mem: &Arc, + workspace_dir: &Path, + runtime_envelope: &RuntimeEnvelope, + memory_fabric: &MemoryFabric, + fabric_scope: &MessageEventScope, + user_message_event_id: Option<&str>, +) -> ToolLoopMemory { + ToolLoopMemory::new( + mem, + workspace_dir, + Some( + DocumentIngestRuntime::from_envelope(mem.clone(), runtime_envelope) + .with_source_message_event_id(user_message_event_id.map(ToString::to_string)), + ), + ) + .with_event_fabric(memory_fabric.clone()) + .with_request_event_scope({ + let mut scope = fabric_scope.clone(); + scope.causation_event_id = user_message_event_id.map(ToString::to_string); + scope + }) +} + +/// Preserve the CLI actor and chat scope while applying the bootstrap's +/// configured security policy and workspace. Scheduled and externally scoped turns leave +/// this adapter absent so their creator-owned scope retains priority. +fn configured_cli_tool_adapter( + security: &Arc, + registry: &Arc>>, + approval: &Arc, + memory_runtime: &ToolLoopMemory, +) -> crate::agent::turn_contracts::ToolLoopRuntimeAdapter { + crate::agent::execution_policy::build_agent_tool_runtime_adapter( + crate::agent::execution_policy::AgentToolRuntimeInputs { + scope: None, + channel_name: "cli", + tools_registry: Arc::clone(registry), + approval: Some(Arc::clone(approval)), + approval_resolver: None, + cancellation: None, + ledger: memory_runtime.ledger.clone(), + unscoped_policy: Some(Arc::clone(security)), + }, + ) +} + +fn terminal_binding_snapshot( + binding: &parking_lot::Mutex>, +) -> Option { + binding.lock().clone() +} + +/// A CLI Agent turn whose origin was checked by this entrypoint after inbound +/// event recording was attempted. Fields stay private; the decision service +/// reads them but cannot manufacture an authenticated source from a public +/// `RuntimeEnvelope`. +pub(crate) struct AgentTurnProof { + workspace_id: Arc, + owner_id: Arc, + session_key: Arc, + run_id: Arc, + source_event_id: Option>, + routing_input: Arc, + memory_scope: crate::memory::principal::MemoryWriteContext, + retrieval_principal: crate::memory::MemoryPrincipal, + provider_name: Arc, + model_name: Arc, + model_binding: AgentModelBinding, + config_generation_id: u64, + config_source_revision: Arc, + scheduled: Option>, +} + +/// Cleanup ownership starts before CLI durable input persistence. This is +/// separate from the source proof: neither a pending write nor its key grants +/// permission to execute a model or tool. +struct CliPendingInput { + fabric: MemoryFabric, + generation: Arc, + envelope: RuntimeEnvelope, + expected_session_key: String, + scope: crate::memory::MessageEventScope, + choice: AgentModelChoice, + input: String, + key: String, + ticket: crate::runtime::turn_cleanup::CleanupTicket, +} + +struct CliAdmissionGuard { + proof: Option, + fabric: MemoryFabric, + config: Arc, + ticket: Option, + pending: Option<(bool, String)>, +} + +impl CliPendingInput { + async fn issue(&self, event: Option<&crate::memory::MessageEvent>) -> Result { + let run = self + .envelope + .run_id + .as_deref() + .ok_or_else(|| anyhow::anyhow!("CLI input run is missing"))?; + let proof = issue_cli_agent_turn_proof_for_session( + None, + &self.envelope, + &self.generation, + (run, &self.expected_session_key), + &self.input, + event, + &self.choice, + )?; + if let Some(event) = event.filter(|event| event.id > 0) { + let mut expected = self.scope.clone(); + for label in [&mut expected.sender, &mut expected.recipient].into_iter().flatten() { + if crate::providers::byo_dialect_of(label).is_some() { + *label = crate::providers::redact_endpoint_userinfo(label).into_owned(); + } + } + anyhow::ensure!( + event.idempotency_key.as_deref() == Some(self.key.as_str()) + && event.source == expected.source + && event.channel == expected.channel + && event.sender == expected.sender + && event.recipient == expected.recipient + && event.owner_id == expected.owner_id + && event.visibility == expected.visibility + && event.goal_id == expected.goal_id + && event.correlation_id == expected.correlation_id + && event.subject == expected.subject + && event.causation_event_id == expected.causation_event_id, + "CLI input receipt attribution differs from its issued scope" + ); + let stored = self + .fabric + .memory() + .find_owned_message_event( + &self.envelope.workspace_id, + &self.envelope.resolved_owner_id(), + &event.event_id, + ) + .await? + .ok_or_else(|| anyhow::anyhow!("CLI input receipt is not durable"))?; + anyhow::ensure!( + serde_json::to_value(stored)? == serde_json::to_value(event)?, + "CLI input receipt differs from its durable source" + ); + } + Ok(proof) + } + + async fn record(mut self) -> Result<(Option, CliAdmissionGuard)> { + self.fabric = self + .fabric + .with_ingress_recovery(&self.generation.effective, &self.ticket) + .await?; + let (sender, receiver) = tokio::sync::oneshot::channel(); + let experiment_stage = crate::runtime::experiment_stage::current(); + tokio::spawn(async move { + let operation = crate::runtime::experiment_stage::retain(experiment_stage, async { + let event = self + .fabric + .record_inbound_user_message_best_effort( + self.scope.clone(), + self.input.clone(), + Some(self.key.clone()), + "CLI", + ) + .await?; + let proof = self.issue(event.as_ref()).await?; + Ok::<_, anyhow::Error>((event, proof)) + }); + let result = tokio::time::timeout(std::time::Duration::from_secs(15), operation) + .await + .map_err(|_| anyhow::anyhow!("CLI input persistence timed out")) + .and_then(std::convert::identity); + let result = match result { + Ok((event, proof)) => Ok(( + event, + CliAdmissionGuard { + proof: Some(proof), + fabric: self.fabric, + config: Arc::clone(&self.generation.effective), + ticket: Some(self.ticket), + pending: None, + }, + )), + Err(_error) if self.fabric.ingress_already_accepted() => { + self.ticket.finish(true); + Err(crate::runtime::ingress_recovery::AlreadyAccepted.into()) + } + Err(error) => { + let recovery = async { + let event = self + .fabric + .memory() + .find_owned_message_event_by_idempotency_key( + &self.envelope.workspace_id, + &self.envelope.resolved_owner_id(), + &self.key, + ) + .await? + .ok_or_else(|| anyhow::anyhow!("CLI input commit is unconfirmed"))?; + self.issue(Some(&event)).await + }; + match tokio::time::timeout(std::time::Duration::from_secs(15), recovery).await { + Ok(Ok(proof)) => { + let mut guard = CliAdmissionGuard { + proof: Some(proof), + fabric: self.fabric, + config: Arc::clone(&self.generation.effective), + ticket: Some(self.ticket), + pending: None, + }; + let _ = tokio::time::timeout( + std::time::Duration::from_secs(15), + guard.finish_failure(sender.is_closed(), "CLI input admission failed"), + ) + .await; + } + _ => self.ticket.finish(false), + } + Err(error) + } + }; + let _ = sender.send(result); + }); + receiver + .await + .map_err(|_| anyhow::anyhow!("CLI input owner ended without a receipt"))? + } +} + +impl CliAdmissionGuard { + /// Transfer the same lifecycle ticket to a real terminal owner without + /// an await or an interval where cancellation has no cleanup owner. + fn into_terminal_ticket(mut self) -> Result { + anyhow::ensure!(self.pending.is_none(), "CLI admission failure is already pending"); + let ticket = self + .ticket + .take() + .ok_or_else(|| anyhow::anyhow!("CLI admission cleanup ticket missing"))?; + self.proof = None; + Ok(ticket) + } + + async fn finish_failure(&mut self, cancelled: bool, summary: &str) -> Result<()> { + anyhow::ensure!(self.pending.is_none(), "CLI admission failure is already pending"); + self.pending = Some((cancelled, crate::security::redaction::redact_secrets(summary))); + let (cancelled, summary) = self + .pending + .as_ref() + .ok_or_else(|| anyhow::anyhow!("CLI failure missing"))?; + let result = self + .proof + .as_ref() + .ok_or_else(|| anyhow::anyhow!("CLI source proof missing"))? + .record_cli_admission_failure(&self.fabric, &self.config, *cancelled, summary) + .await; + self.proof = None; + if let Some(ticket) = self.ticket.take() { + ticket.finish(result.is_ok()); + } + result + } +} + +impl Drop for CliAdmissionGuard { + fn drop(&mut self) { + let Some(proof) = self.proof.take() else { + return; + }; + let Some(ticket) = self.ticket.take() else { + return; + }; + let (cancelled, summary) = self + .pending + .take() + .unwrap_or_else(|| (true, "CLI input admission task was dropped".to_owned())); + let Ok(runtime) = tokio::runtime::Handle::try_current() else { + ticket.finish(false); + return; + }; + let fabric = self.fabric.clone(); + let config = Arc::clone(&self.config); + runtime.spawn(async move { + let result = tokio::time::timeout( + std::time::Duration::from_secs(15), + proof.record_cli_admission_failure(&fabric, &config, cancelled, &summary), + ) + .await; + ticket.finish(matches!(result, Ok(Ok(())))); + }); + } +} + +impl AgentTurnProof { + async fn record_cli_admission_failure( + &self, + fabric: &MemoryFabric, + config: &Config, + cancelled: bool, + summary: &str, + ) -> Result<()> { + anyhow::ensure!( + self.scheduled.is_none(), + "scheduled admission retains its own failure owner" + ); + anyhow::ensure!( + fabric.workspace_id() == self.workspace_id.as_ref() + && config.workspace_dir.to_string_lossy() == self.workspace_id.as_ref(), + "CLI admission failure workspace changed" + ); + let Some(event_id) = self.source_event_id.as_deref() else { + anyhow::ensure!( + !config.memory.should_record_user_message_event(), + "CLI admission has no durable input" + ); + return Ok(()); + }; + let input = fabric + .memory() + .find_owned_message_event(&self.workspace_id, &self.owner_id, event_id) + .await? + .ok_or_else(|| anyhow::anyhow!("CLI admission input is missing"))?; + anyhow::ensure!( + input.id > 0 + && input.event_id == event_id + && input.workspace_id == self.workspace_id.as_ref() + && input.owner_id.as_deref() == Some(self.owner_id.as_ref()) + && input.session_key.as_deref() == Some(self.session_key.as_ref()) + && input.run_id.as_deref() == Some(self.run_id.as_ref()) + && input.config_generation_id == Some(self.config_generation_id) + && input.config_source_revision.as_deref() == Some(self.config_source_revision.as_ref()) + && input.role == "user" + && input.event_type == "message.created" + && input.parent_run_id.is_none() + && input.parent_session_key.is_none() + && input.agent_id.is_none() + && input.persona_id.is_none() + && input.subject.is_none() + && input.attempt_id.is_none() + && input.lease_epoch.is_none() + && crate::runtime::turn_source::recorded_input_matches(self.surface(), &input, &self.routing_input), + "CLI admission input differs from its source proof" + ); + let mut envelope = RuntimeEnvelope::agent(self.workspace_id.to_string(), self.run_id.to_string()) + .with_source_message_event_id(event_id); + envelope.session_key = self.session_key.to_string(); + let mut scope = envelope.message_scope(); + scope.config_generation_id = Some(self.config_generation_id); + scope.config_source_revision = Some(self.config_source_revision.to_string()); + let summary = crate::security::redaction::redact_secrets(summary); + let payload = serde_json::json!({ + "run_id": self.run_id.as_ref(), "source_event_id": event_id, + "status": if cancelled { "cancelled" } else { "failed" }, "summary": summary, + }); + let expected_content = format!("turn.admission.failed {summary}"); + let event = crate::runtime::ingress_recovery::commit_admission_failure( + fabric, + scope.clone(), + &summary, + serde_json::to_string(&payload)?, + format!("turn:{}:admission-failed", self.run_id), + ) + .await?; + anyhow::ensure!( + event.content == expected_content + && event.idempotency_key.as_deref() == Some(format!("turn:{}:admission-failed", self.run_id).as_str()) + && event.id > 0 + && !event.event_id.is_empty() + && event.workspace_id == fabric.workspace_id() + && event.owner_id == scope.owner_id + && event.source == scope.source + && event.channel == scope.channel + && event.sender == scope.sender + && event.session_key == scope.session_key + && event.run_id == scope.run_id + && event.causation_event_id == scope.causation_event_id + && event.recipient == scope.recipient + && event.parent_run_id == scope.parent_run_id + && event.parent_session_key == scope.parent_session_key + && event.subject == scope.subject + && event.agent_id == scope.agent_id + && event.persona_id == scope.persona_id + && event.attempt_id == scope.attempt_id + && event.lease_epoch == scope.lease_epoch + && event.config_generation_id == scope.config_generation_id + && event.config_source_revision == scope.config_source_revision + && event.visibility == scope.visibility + && event.role == "event" + && event.event_type == "turn.admission.failed" + && event + .raw_payload_json + .as_deref() + .map(serde_json::from_str::) + .transpose()? + .as_ref() + == Some(&payload), + "CLI admission failure retry conflicts with source or status" + ); + let durable = fabric + .memory() + .find_owned_message_event(fabric.workspace_id(), self.owner_id.as_ref(), &event.event_id) + .await? + .ok_or_else(|| anyhow::anyhow!("admission failure receipt is not durable"))?; + anyhow::ensure!( + serde_json::to_value(durable)? == serde_json::to_value(&event)?, + "admission failure receipt differs from durable event" + ); + Ok(()) + } + + pub(crate) fn owner_isolated(&self) -> bool { + self.scheduled + .as_ref() + .map_or(self.retrieval_principal.require_owner_match, |source| { + source.envelope.owner_isolated + }) + } + + pub(crate) fn retrieval_principal(&self) -> crate::memory::MemoryPrincipal { + self.scheduled.as_ref().map_or_else( + || self.retrieval_principal.clone(), + |source| source.envelope.memory_principal(), + ) + } + + pub(crate) fn task_id(&self) -> Option<&str> { + self.scheduled + .as_ref() + .and_then(|source| source.envelope.task_id.as_deref()) + } + pub(crate) fn surface(&self) -> crate::tools::capability::turn_state::TurnSurfaceKind { + use crate::tools::capability::turn_state::TurnSurfaceKind; + match self.scheduled.as_ref().map(|source| source.envelope.source) { + Some(RuntimeSource::Cron) => TurnSurfaceKind::Cron, + Some(RuntimeSource::Xin) => TurnSurfaceKind::Xin, + _ => TurnSurfaceKind::AgentLoop, + } + } + pub(crate) fn policy_channel(&self) -> &str { + self.scheduled + .as_ref() + .and_then(|source| source.execution.envelope.channel.as_deref()) + .unwrap_or("cli") + } + pub(crate) fn policy_sender(&self) -> &str { + self.scheduled + .as_ref() + .and_then(|source| source.execution.envelope.sender.as_deref()) + .unwrap_or("local-user") + } + pub(crate) fn policy_chat_type(&self) -> &str { + self.scheduled + .as_ref() + .map_or("private", |source| source.execution.chat_type.as_str()) + } + pub(crate) fn workspace_id(&self) -> &str { + &self.workspace_id + } + + pub(crate) fn owner_id(&self) -> &str { + &self.owner_id + } + + pub(crate) fn session_key(&self) -> &str { + &self.session_key + } + + pub(crate) fn run_id(&self) -> &str { + &self.run_id + } + + pub(crate) fn source_event_id(&self) -> Option<&str> { + self.source_event_id.as_deref() + } + + pub(crate) fn routing_input(&self) -> &str { + &self.routing_input + } + + pub(crate) const fn memory_scope(&self) -> &crate::memory::principal::MemoryWriteContext { + &self.memory_scope + } + + pub(crate) fn provider_name(&self) -> &str { + &self.provider_name + } + + pub(crate) fn model_name(&self) -> &str { + &self.model_name + } + + pub(crate) const fn model_binding(&self) -> &AgentModelBinding { + &self.model_binding + } + + pub(crate) const fn config_generation_id(&self) -> u64 { + self.config_generation_id + } + + pub(crate) fn config_source_revision(&self) -> &str { + &self.config_source_revision + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +enum AgentTurnOriginError { + #[error("the CLI Agent turn does not match its authenticated runtime origin ({0})")] + Mismatch(&'static str), +} + +/// Only this entrypoint may issue a CLI Agent origin. Scheduled overrides are +/// separate surfaces and cannot inherit the local operator's authority. +fn issue_cli_agent_turn_proof( + runtime_envelope_override: Option<&RuntimeEnvelope>, + envelope: &RuntimeEnvelope, + generation: &crate::config::ConfigGeneration, + expected_run_id: &str, + routing_input: &str, + recorded_event: Option<&crate::memory::MessageEvent>, + choice: &AgentModelChoice, +) -> Result { + issue_cli_agent_turn_proof_for_session( + runtime_envelope_override, + envelope, + generation, + (expected_run_id, &format!("agent:{expected_run_id}")), + routing_input, + recorded_event, + choice, + ) +} + +// The expected session is minted at the CLI entry, independently of the envelope +// being validated. Run IDs remain per-turn. +fn issue_cli_agent_turn_proof_for_session( + runtime_envelope_override: Option<&RuntimeEnvelope>, + envelope: &RuntimeEnvelope, + generation: &crate::config::ConfigGeneration, + (expected_run_id, expected_session_key): (&str, &str), + routing_input: &str, + recorded_event: Option<&crate::memory::MessageEvent>, + choice: &AgentModelChoice, +) -> Result { + let run_id = envelope + .run_id + .as_deref() + .ok_or(AgentTurnOriginError::Mismatch("missing_run_id"))?; + let workspace_id = generation.effective.workspace_dir.to_string_lossy(); + let owner_id = crate::memory::principal::OwnerPrincipal::new( + workspace_id.as_ref(), + "cli", + "local-user", + &envelope.session_key, + vec![crate::memory::principal::Role::Anonymous], + ) + .owner_id; + if runtime_envelope_override.is_some() + || envelope.source != RuntimeSource::Agent + || envelope.workspace_id != workspace_id + || envelope.channel.as_deref() != Some("cli") + || envelope.sender.as_deref() != Some("local-user") + || envelope.owner_id.is_some() + || envelope.owner_isolated + || envelope.legacy_session_key.is_some() + || envelope.topic_id.is_some() + || envelope.task_id.is_some() + || envelope.source_message_event_id.is_some() + || envelope.parent_run_id.is_some() + || envelope.attempt_id.is_some() + || envelope.lease_epoch.is_some() + || envelope.authority_guard.is_some() + || envelope.agent_id.is_some() + || envelope.persona_id.is_some() + || envelope + .recipient + .as_deref() + .is_some_and(|recipient| recipient != "cli:local-user") + || envelope.visibility != crate::memory::MemoryVisibility::Session + || run_id != expected_run_id + || envelope.session_key != expected_session_key + || envelope.config_generation_id != Some(generation.id.0) + || envelope.config_source_revision.as_deref() != Some(&generation.source_revision.fingerprint_sha256) + { + return Err(AgentTurnOriginError::Mismatch("envelope")); + } + if !choice.factory_credential_source_matches(&generation.effective) { + return Err(AgentTurnOriginError::Mismatch("credential_source")); + } + let recorded_event_id = match recorded_event { + Some(event) if event.id > 0 => { + if event.event_id.trim().is_empty() + || event.workspace_id != workspace_id + || event.owner_id.as_deref() != Some(owner_id.as_str()) + || event.source != crate::memory::MessageEventSource::Agent + || event.channel.as_deref() != Some("cli") + || event.sender.as_deref() != Some("local-user") + || event.session_key.as_deref() != Some(envelope.session_key.as_str()) + || event.parent_session_key.is_some() + || event.run_id.as_deref() != Some(run_id) + || event.parent_run_id.is_some() + || event.agent_id.is_some() + || event.persona_id.is_some() + || event.attempt_id.is_some() + || event.lease_epoch.is_some() + || event.role != "user" + || event.event_type != "message.created" + || event.config_generation_id != Some(generation.id.0) + || event.config_source_revision.as_deref() != Some(&generation.source_revision.fingerprint_sha256) + || event.content != routing_input + || event.visibility != crate::memory::MemoryVisibility::Session + { + return Err(AgentTurnOriginError::Mismatch("recorded_event")); + } + Some(event.event_id.as_str()) + } + Some(_) | None => None, + }; + Ok(AgentTurnProof { + workspace_id: Arc::from(workspace_id.as_ref()), + owner_id: Arc::from(owner_id), + session_key: Arc::from(envelope.session_key.as_str()), + run_id: Arc::from(run_id), + source_event_id: recorded_event_id.map(Arc::from), + routing_input: Arc::from(routing_input), + memory_scope: envelope.memory_write_context("private"), + retrieval_principal: envelope.memory_principal(), + provider_name: Arc::from(choice.provider_name.as_str()), + model_name: Arc::from(choice.model_name.as_str()), + model_binding: choice.model_binding.clone(), + config_generation_id: generation.id.0, + config_source_revision: Arc::from(generation.source_revision.fingerprint_sha256.as_str()), + scheduled: None, + }) +} + +#[cfg(test)] +pub(crate) fn test_cli_agent_turn_proof( + generation: &crate::config::ConfigGeneration, + provider_name: &str, + model_name: &str, +) -> AgentTurnProof { + test_cli_agent_turn_proof_with_input(generation, provider_name, model_name, "prx test routing input") +} + +#[cfg(test)] +pub(crate) fn test_cli_agent_turn_proof_with_input( + generation: &crate::config::ConfigGeneration, + provider_name: &str, + model_name: &str, + routing_input: &str, +) -> AgentTurnProof { + test_cli_agent_turn_proof_with_run(generation, provider_name, model_name, routing_input, "prx_test_run") +} + +#[cfg(test)] +pub(crate) fn test_cli_agent_turn_proof_with_run( + generation: &crate::config::ConfigGeneration, + provider_name: &str, + model_name: &str, + routing_input: &str, + run_id: &str, +) -> AgentTurnProof { + let envelope = RuntimeEnvelope::agent(generation.effective.workspace_dir.to_string_lossy(), run_id) + .with_config_generation(generation); + issue_cli_agent_turn_proof( + None, + &envelope, + generation, + run_id, + routing_input, + None, + &resolve_agent_model_choice(&generation.effective, Some(provider_name), Some(model_name), None) + .expect("test selected model"), + ) + .expect("test CLI Agent proof") +} + +#[cfg(test)] +pub(crate) async fn test_recorded_cli_agent_turn_proof( + generation: &crate::config::ConfigGeneration, + memory: Arc, +) -> AgentTurnProof { + test_recorded_cli_agent_turn_proof_with_input(generation, memory, "prx test routing input", "prx_test_run").await +} + +#[cfg(test)] +pub(crate) async fn test_recorded_cli_agent_turn_proof_with_input( + generation: &crate::config::ConfigGeneration, + memory: Arc, + input: &str, + run_id: &str, +) -> AgentTurnProof { + test_recorded_cli_agent_turn_proof_with_selection(generation, memory, input, run_id, ("ollama", "prx-local-model")) + .await +} + +#[cfg(test)] +pub(crate) async fn test_recorded_cli_agent_turn_proof_with_selection( + generation: &crate::config::ConfigGeneration, + memory: Arc, + input: &str, + run_id: &str, + selection: (&str, &str), +) -> AgentTurnProof { + let envelope = RuntimeEnvelope::agent(generation.effective.workspace_dir.to_string_lossy(), run_id) + .with_config_generation(generation); + let fabric = crate::memory::MemoryFabric::new(memory, generation.effective.workspace_dir.to_string_lossy()) + .with_event_recording(generation.effective.memory.event_recording_config()); + let event = fabric + .record_inbound_user_message(envelope.message_scope(), input, None, None) + .await + .expect("persisted inbound event"); + issue_cli_agent_turn_proof( + None, + &envelope, + generation, + run_id, + input, + Some(&event), + &resolve_agent_model_choice(&generation.effective, Some(selection.0), Some(selection.1), None) + .expect("test selected model"), + ) + .expect("recorded CLI Agent proof") +} + +#[cfg(test)] +pub(crate) async fn test_recovery_cli_agent_turn_proof_with_selection( + generation: &crate::config::ConfigGeneration, + memory: Arc, + input: &str, + run_id: &str, + selection: (&str, &str), +) -> AgentTurnProof { + let envelope = RuntimeEnvelope::agent(generation.effective.workspace_dir.to_string_lossy(), run_id) + .with_config_generation(generation); + let owner = Arc::new(crate::runtime::turn_cleanup::CleanupTracker::default()); + let ticket = owner + .register(tokio_util::sync::CancellationToken::new()) + .expect("test: ingress owner"); + let fabric = crate::memory::MemoryFabric::new(memory, generation.effective.workspace_dir.to_string_lossy()) + .with_event_recording(generation.effective.memory.event_recording_config()) + .with_ingress_recovery(&generation.effective, &ticket) + .await + .expect("test: recovery ingress fabric"); + let event = fabric + .record_inbound_user_message( + envelope.message_scope(), + input, + Some(format!("prx:terminal-fixture:{run_id}:input")), + None, + ) + .await + .expect("test: recovery input"); + let proof = issue_cli_agent_turn_proof( + None, + &envelope, + generation, + run_id, + input, + Some(&event), + &resolve_agent_model_choice(&generation.effective, Some(selection.0), Some(selection.1), None) + .expect("test: selected recovery model"), + ) + .expect("test: recovery CLI proof"); + drop(fabric); + ticket.finish(true); + owner + .drain(tokio::time::Instant::now() + std::time::Duration::from_secs(5)) + .await + .expect("test: ingress owner drained"); + proof +} + +#[cfg(test)] +mod agent_turn_origin_tests { + use super::*; + + fn inbound_event( + envelope: &RuntimeEnvelope, + generation: &crate::config::ConfigGeneration, + content: &str, + ) -> crate::memory::MessageEvent { + crate::memory::MessageEvent { + id: 1, + event_id: "recorded_event".to_string(), + idempotency_key: None, + workspace_id: envelope.workspace_id.clone(), + owner_id: Some(envelope.resolved_owner_id()), + source: crate::memory::MessageEventSource::Agent, + channel: Some("cli".to_string()), + session_key: Some(envelope.session_key.clone()), + parent_session_key: None, + run_id: envelope.run_id.clone(), + parent_run_id: None, + agent_id: None, + persona_id: None, + sender: Some("local-user".to_string()), + recipient: None, + role: "user".to_string(), + event_type: "message.created".to_string(), + subject: None, + goal_id: None, + causation_event_id: None, + correlation_id: None, + attempt_id: None, + lease_epoch: None, + config_generation_id: Some(generation.id.0), + config_source_revision: Some(generation.source_revision.fingerprint_sha256.clone()), + content: content.to_string(), + content_hash: None, + raw_payload_json: None, + visibility: envelope.visibility.clone(), + created_at: "2026-01-01T00:00:00Z".to_string(), + updated_at: "2026-01-01T00:00:00Z".to_string(), + } + } + + #[tokio::test] + async fn cli_proof_binds_pinned_generation_and_recorded_inbound_event() { + let workspace = tempfile::tempdir().expect("test workspace"); + let mut config = Config::default(); + config.workspace_dir = workspace.path().to_path_buf(); + let generation = crate::config::new_shared(config).pin(); + let envelope = + RuntimeEnvelope::agent(workspace.path().to_string_lossy(), "prx_run").with_config_generation(&generation); + let memory: Arc = + Arc::new(crate::memory::SqliteMemory::new(workspace.path()).expect("test message-event backend")); + let fabric = MemoryFabric::new(memory, workspace.path().to_string_lossy()) + .with_event_recording(generation.effective.memory.event_recording_config()); + let event = fabric + .record_inbound_user_message(envelope.message_scope(), "raw request", None, None) + .await + .expect("persisted inbound receipt"); + assert!(event.id > 0); + let proof = issue_cli_agent_turn_proof( + None, + &envelope, + &generation, + "prx_run", + "raw request", + Some(&event), + &resolve_agent_model_choice(&generation.effective, Some("ollama"), Some("prx-local-model"), None) + .expect("test selected model"), + ) + .expect("local CLI origin"); + assert_eq!(proof.workspace_id(), workspace.path().to_string_lossy()); + assert_eq!(proof.session_key(), "agent:prx_run"); + assert_eq!(proof.run_id(), "prx_run"); + assert!(!event.event_id.is_empty(), "expected a non-empty value"); + assert_eq!(proof.source_event_id(), Some(event.event_id.as_str())); + assert_eq!(proof.routing_input(), "raw request"); + assert_eq!(proof.provider_name(), "ollama"); + assert_eq!(proof.model_name(), "prx-local-model"); + assert_eq!(proof.config_generation_id(), generation.id.0); + let expected_scope = envelope.memory_write_context("private"); + assert_eq!(proof.memory_scope().workspace_id, expected_scope.workspace_id); + assert_eq!(proof.memory_scope().channel, expected_scope.channel); + assert_eq!(proof.memory_scope().chat_id, expected_scope.chat_id); + assert_eq!(proof.memory_scope().sender_id, expected_scope.sender_id); + assert_eq!(proof.memory_scope().raw_sender, expected_scope.raw_sender); + assert_eq!(proof.memory_scope().owner_id, expected_scope.owner_id); + assert_eq!( + proof.config_source_revision(), + generation.source_revision.fingerprint_sha256 + ); + assert_eq!( + proof.owner_id(), + crate::memory::principal::OwnerPrincipal::new( + workspace.path().to_string_lossy(), + "cli", + "local-user", + "agent:prx_run", + vec![crate::memory::principal::Role::Anonymous], + ) + .owner_id + ); + crate::runtime::turn_context::validate_agent_turn_origin( + &generation, + crate::tools::capability::turn_state::TurnSurfaceKind::AgentLoop, + &proof, + ) + .expect("service accepts the pinned Agent origin"); + assert!( + crate::runtime::turn_context::validate_agent_turn_origin( + &generation, + crate::tools::capability::turn_state::TurnSurfaceKind::Interactive, + &proof, + ) + .is_err() + ); + } + + #[tokio::test] + async fn repl_proof_and_admission_failure_bind_session_independently_of_run() { + let workspace = tempfile::tempdir().expect("test workspace"); + let mut config = Config::default(); + config.workspace_dir = workspace.path().to_path_buf(); + let generation = crate::config::new_shared(config).pin(); + let envelope = RuntimeEnvelope::agent(workspace.path().to_string_lossy(), "prx_session") + .with_run_id("prx_turn") + .with_config_generation(&generation); + let fabric = MemoryFabric::new( + Arc::new(crate::memory::SqliteMemory::new(workspace.path()).expect("actual source memory")), + workspace.path().to_string_lossy(), + ); + let event = fabric + .record_inbound_user_message(envelope.message_scope(), "raw", None, None) + .await + .expect("persist inbound receipt"); + let choice = resolve_agent_model_choice(&generation.effective, Some("ollama"), Some("prx-local-model"), None) + .expect("test selected model"); + let issue = |identity| { + issue_cli_agent_turn_proof_for_session(None, &envelope, &generation, identity, "raw", Some(&event), &choice) + }; + assert!(issue(("prx_turn", "agent:other_session")).is_err()); + assert!(issue(("other_turn", "agent:prx_session")).is_err()); + let proof = issue(("prx_turn", "agent:prx_session")).expect("REPL proof"); + assert_eq!(proof.session_key(), "agent:prx_session"); + proof + .record_cli_admission_failure(&fabric, &generation.effective, false, "test refusal") + .await + .expect("persist admission failure"); + let failure = fabric + .memory() + .find_message_event_by_idempotency_key(fabric.workspace_id(), "turn:prx_turn:admission-failed") + .await + .expect("failure lookup") + .expect("durable failure event"); + assert_eq!(failure.session_key.as_deref(), Some("agent:prx_session")); + assert_eq!(failure.owner_id, Some(envelope.resolved_owner_id())); + assert_eq!(failure.run_id.as_deref(), Some("prx_turn")); + } + + #[tokio::test] + async fn missing_or_synthetic_inbound_receipt_confers_no_source_event() { + let workspace = tempfile::tempdir().expect("test workspace"); + let mut config = Config::default(); + config.workspace_dir = workspace.path().to_path_buf(); + config.memory.events.record_user_messages = false; + let generation = crate::config::new_shared(config).pin(); + let envelope = + RuntimeEnvelope::agent(workspace.path().to_string_lossy(), "prx_run").with_config_generation(&generation); + let choice = resolve_agent_model_choice(&generation.effective, Some("ollama"), Some("prx-local-model"), None) + .expect("test selected model"); + let fabric = MemoryFabric::new( + Arc::new(crate::memory::NoneMemory::new()), + workspace.path().to_string_lossy(), + ) + .with_event_recording(generation.effective.memory.event_recording_config()); + let synthetic = fabric + .record_inbound_user_message(envelope.message_scope(), "raw", None, None) + .await + .expect("disabled user-event recording yields a synthetic receipt"); + assert_eq!(synthetic.id, 0); + assert!(!synthetic.event_id.is_empty(), "expected a non-empty value"); + let failing_fabric = MemoryFabric::new( + Arc::new(crate::memory::MarkdownMemory::new(workspace.path())), + workspace.path().to_string_lossy(), + ); + assert!( + failing_fabric + .record_inbound_user_message(envelope.message_scope(), "raw", None, None) + .await + .is_err(), + "an enabled record path must report a failed append" + ); + // P2-R22: an unrecorded turn is never refused, but a missing or + // synthetic receipt never attests a source event for it. + for receipt in [None, Some(&synthetic)] { + let proof = issue_cli_agent_turn_proof(None, &envelope, &generation, "prx_run", "raw", receipt, &choice) + .expect("an unrecorded CLI turn is not refused"); + assert_eq!( + proof.source_event_id(), + None, + "a missing or synthetic receipt confers no source event" + ); + } + let persisted = inbound_event(&envelope, &generation, "raw"); + let proof = issue_cli_agent_turn_proof( + None, + &envelope, + &generation, + "prx_run", + "raw", + Some(&persisted), + &choice, + ) + .expect("a persisted receipt issues the proof"); + assert_eq!(proof.source_event_id(), Some(persisted.event_id.as_str())); + let mut foreign = persisted; + foreign.run_id = Some("other_run".to_string()); + assert!( + issue_cli_agent_turn_proof(None, &envelope, &generation, "prx_run", "raw", Some(&foreign), &choice) + .is_err() + ); + foreign.run_id = Some("prx_run".to_string()); + foreign.parent_run_id = Some("nested_run".to_string()); + assert!( + issue_cli_agent_turn_proof(None, &envelope, &generation, "prx_run", "raw", Some(&foreign), &choice) + .is_err() + ); + } + + #[tokio::test] + async fn disabled_agent_does_not_claim_synthetic_inbound_lineage() { + let workspace = tempfile::tempdir().expect("test workspace"); + let mut config = Config::default(); + config.workspace_dir = workspace.path().to_path_buf(); + config.memory.events.record_user_messages = false; + let generation = crate::config::new_shared(config).pin(); + let envelope = + RuntimeEnvelope::agent(workspace.path().to_string_lossy(), "prx_run").with_config_generation(&generation); + let choice = resolve_agent_model_choice(&generation.effective, Some("ollama"), Some("prx-local-model"), None) + .expect("test selected model"); + let fabric = MemoryFabric::new( + Arc::new(crate::memory::NoneMemory::new()), + workspace.path().to_string_lossy(), + ) + .with_event_recording(generation.effective.memory.event_recording_config()); + let synthetic = fabric + .record_inbound_user_message(envelope.message_scope(), "raw", None, None) + .await + .expect("disabled user-event recording yields a synthetic receipt"); + assert_eq!(synthetic.id, 0); + for receipt in [None, Some(&synthetic)] { + let proof = issue_cli_agent_turn_proof(None, &envelope, &generation, "prx_run", "raw", receipt, &choice) + .expect("disabled plane may run builtin without a persisted inbound event"); + assert_eq!(proof.source_event_id(), None); + } + } + + #[tokio::test] + async fn selected_memory_read_rejects_a_different_cli_turn_with_the_same_query() { + let workspace = tempfile::tempdir().expect("test workspace"); + let mut config = Config::default(); + config.workspace_dir = workspace.path().to_path_buf(); + let generation = crate::config::new_shared(config).pin(); + let choice = resolve_agent_model_choice(&generation.effective, Some("ollama"), Some("prx-local-model"), None) + .expect("test selected model"); + let workspace_id = workspace.path().to_string_lossy(); + let envelope_a = RuntimeEnvelope::agent(workspace_id.as_ref(), "prx_run_a").with_config_generation(&generation); + let envelope_b = RuntimeEnvelope::agent(workspace_id.as_ref(), "prx_run_b").with_config_generation(&generation); + let fabric = MemoryFabric::new( + Arc::new(crate::memory::SqliteMemory::new(workspace.path()).expect("actual source memory")), + workspace_id.as_ref(), + ); + let inbound_a = fabric + .record_inbound_user_message(envelope_a.message_scope(), "same query", None, None) + .await + .expect("persist first ingress"); + let inbound_b = fabric + .record_inbound_user_message(envelope_b.message_scope(), "same query", None, None) + .await + .expect("persist second ingress"); + let proof_a = issue_cli_agent_turn_proof( + None, + &envelope_a, + &generation, + "prx_run_a", + "same query", + Some(&inbound_a), + &choice, + ) + .expect("first source proof"); + let proof_b = issue_cli_agent_turn_proof( + None, + &envelope_b, + &generation, + "prx_run_b", + "same query", + Some(&inbound_b), + &choice, + ) + .expect("second source proof"); + assert_eq!(proof_a.routing_input(), proof_b.routing_input()); + assert_eq!(proof_a.owner_id(), proof_b.owner_id()); + assert_ne!(proof_a.session_key(), proof_b.session_key()); + let mut trusted = crate::decision_engine::state::fixtures::trusted(); + trusted.surface = crate::tools::capability::turn_state::TurnSurfaceKind::AgentLoop; + trusted.channel = None; + trusted.workspace_id = Arc::from(proof_a.workspace_id()); + trusted.owner_id = Some(Arc::from(proof_a.owner_id())); + trusted.session_key = Some(Arc::from(proof_a.session_key())); + trusted.run_id = Some(Arc::from(proof_a.run_id())); + trusted.source_event_id = proof_a.source_event_id().map(Arc::from); + trusted.resolved_model = Arc::from("prx:model"); + trusted.policy_version = Arc::from("policy-v1"); + trusted.exclusions.clear(); + let verify = crate::runtime::turn_context::validate_agent_retrieval_provenance; + assert!(verify(&proof_a, &trusted, "prx:model", "policy-v1", &[]).is_ok()); + assert!(verify(&proof_b, &trusted, "prx:model", "policy-v1", &[]).is_err()); + trusted.owner_id = Some(Arc::from("prx_foreign_owner")); + assert!(verify(&proof_a, &trusted, "prx:model", "policy-v1", &[]).is_err()); + trusted.owner_id = Some(Arc::from(proof_a.owner_id())); + trusted.source_event_id = Some(Arc::from("foreign-event")); + assert!(verify(&proof_a, &trusted, "prx:model", "policy-v1", &[]).is_err()); + trusted.source_event_id = proof_a.source_event_id().map(Arc::from); + assert!(verify(&proof_a, &trusted, "foreign:model", "policy-v1", &[]).is_err()); + assert!(verify(&proof_a, &trusted, "prx:model", "foreign-policy", &[]).is_err()); + assert!(verify(&proof_a, &trusted, "prx:model", "policy-v1", &[Arc::from("blocked")]).is_err()); + } + + #[tokio::test] + async fn override_and_mismatched_generation_cannot_issue_cli_proof() { + let workspace = tempfile::tempdir().expect("test workspace"); + let mut config = Config::default(); + config.workspace_dir = workspace.path().to_path_buf(); + let generation = crate::config::new_shared(config).pin(); + let good = resolve_agent_turn_envelope(None, &workspace.path().to_string_lossy(), "prx_run") + .with_config_generation(&generation); + let interactive = RuntimeEnvelope::agent(workspace.path().to_string_lossy(), "prx_run") + .with_recipient("cli:local-user") + .with_config_generation(&generation); + let choice = resolve_agent_model_choice(&generation.effective, Some("ollama"), Some("prx-local-model"), None) + .expect("test selected model"); + let fabric = MemoryFabric::new( + Arc::new(crate::memory::SqliteMemory::new(workspace.path()).expect("actual source memory")), + workspace.path().to_string_lossy(), + ); + let inbound = fabric + .record_inbound_user_message(good.message_scope(), "raw", None, None) + .await + .expect("persist actual ingress"); + for envelope in [&good, &interactive] { + assert!( + issue_cli_agent_turn_proof(None, envelope, &generation, "prx_run", "raw", Some(&inbound), &choice) + .is_ok(), + "ordinary CLI envelope must retain Agent proof eligibility" + ); + } + let rejected = |envelope: &RuntimeEnvelope, override_envelope: Option<&RuntimeEnvelope>| { + assert!( + issue_cli_agent_turn_proof( + override_envelope, + envelope, + &generation, + "prx_run", + "raw", + Some(&inbound), + &resolve_agent_model_choice(&generation.effective, Some("ollama"), Some("prx-local-model"), None) + .expect("test selected model"), + ) + .is_err() + ); + }; + rejected(&good, Some(&good)); + let mut wrong_source = good.clone(); + wrong_source.source = RuntimeSource::Cron; + rejected(&wrong_source, None); + let mut wrong_id = good.clone(); + wrong_id.config_generation_id = Some(generation.id.0.saturating_add(1)); + rejected(&wrong_id, None); + let mut wrong_revision = good.clone(); + wrong_revision.config_source_revision = Some("stale".to_string()); + rejected(&wrong_revision, None); + let mut wrong_workspace = good.clone(); + wrong_workspace.workspace_id = "other_workspace".to_string(); + rejected(&wrong_workspace, None); + let mut wrong_run = good.clone(); + wrong_run.run_id = Some("other_run".to_string()); + wrong_run.session_key = "agent:other_run".to_string(); + rejected(&wrong_run, None); + let mut forged_event = good.clone(); + forged_event.source_message_event_id = Some("untrusted_event".to_string()); + rejected(&forged_event, None); + let mut forged_owner = good; + forged_owner.owner_id = Some("untrusted_owner".to_string()); + rejected(&forged_owner, None); + let mut nested = forged_owner; + nested.owner_id = None; + nested.parent_run_id = Some("parent_run".to_string()); + rejected(&nested, None); + nested.parent_run_id = None; + nested.task_id = Some("child_task".to_string()); + rejected(&nested, None); + nested.task_id = None; + nested.attempt_id = Some("child_attempt".to_string()); + rejected(&nested, None); + nested.attempt_id = None; + nested.recipient = Some("foreign:recipient".to_string()); + rejected(&nested, None); + } + + /// P2-R22 and controller ruling CR-CI-1: no spelling check exists at + /// proof issuance. A receipt-less CLI proof issues and binds the + /// PMM-trimmed model on the direct and the hint route. + #[test] + fn raw_model_spelling_issues_a_proof_bound_to_the_pmm_model_on_direct_and_hint_routes() { + let workspace = tempfile::tempdir().expect("test workspace"); + let mut config = Config::default(); + config.workspace_dir = workspace.path().to_path_buf(); + config.default_provider = Some("ollama".to_string()); + config.default_model = Some("prx-local-model ".to_string()); + let direct = resolve_agent_model_choice(&config, None, None, None).expect("PMM trims direct model"); + let direct_generation = crate::config::new_shared(config.clone()).pin(); + let direct_envelope = RuntimeEnvelope::agent(workspace.path().to_string_lossy(), "prx_run") + .with_config_generation(&direct_generation); + let proof = issue_cli_agent_turn_proof( + None, + &direct_envelope, + &direct_generation, + "prx_run", + "ping", + None, + &direct, + ) + .expect("the direct route issues a proof"); + assert_eq!(proof.model_binding().pinned_model(), "prx-local-model"); + assert_eq!(proof.source_event_id(), None); + + config.default_model = Some("prx-local-model".to_string()); + config.model_routes.push(crate::config::ModelRouteConfig { + settings: Default::default(), + hint: "fast".to_string(), + provider: "ollama".to_string(), + model: "prx-route-model ".to_string(), + api_key: None, + credential_ref: None, + }); + let hint = resolve_agent_model_choice(&config, None, Some("hint:fast"), None).expect("PMM trims route model"); + let hint_generation = crate::config::new_shared(config).pin(); + let hint_envelope = RuntimeEnvelope::agent(workspace.path().to_string_lossy(), "prx_run") + .with_config_generation(&hint_generation); + let proof = issue_cli_agent_turn_proof(None, &hint_envelope, &hint_generation, "prx_run", "ping", None, &hint) + .expect("the hint route issues a proof"); + assert_eq!(proof.model_binding().pinned_model(), "prx-route-model"); + } + + /// P2-R22 and controller ruling CR-CI-1: the OAuth placeholder root + /// issues a proof on the resolved provider and model. Whether the + /// placeholder becomes key material is decided at provider construction + /// (the OAuth context), not at the proof boundary. + #[test] + fn oauth_placeholder_root_issues_a_proof_on_the_resolved_provider_and_model() { + let workspace = tempfile::tempdir().expect("test workspace"); + let mut config = Config::default(); + config.workspace_dir = workspace.path().to_path_buf(); + config.default_provider = Some("qwen-code".to_string()); + config.default_model = Some("qwen3-coder-plus".to_string()); + config.api_key = Some("qwen-oauth".to_string()); + let choice = resolve_agent_model_choice(&config, None, None, None).expect("PMM root placeholder selection"); + let generation = crate::config::new_shared(config).pin(); + let envelope = + RuntimeEnvelope::agent(workspace.path().to_string_lossy(), "prx_run").with_config_generation(&generation); + let proof = issue_cli_agent_turn_proof(None, &envelope, &generation, "prx_run", "ping", None, &choice) + .expect("the placeholder root issues a proof"); + assert_eq!(proof.model_binding().pinned_model(), "qwen3-coder-plus"); + assert_eq!(proof.model_binding().pinned_model(), choice.binding().pinned_model()); + assert_eq!(proof.provider_name(), choice.provider_name()); + } +} + diff --git a/src/agent/entry/section_2.rs b/src/agent/entry/section_2.rs new file mode 100644 index 000000000..fa2dad093 --- /dev/null +++ b/src/agent/entry/section_2.rs @@ -0,0 +1,1139 @@ +/// The provider and model an agent entry runs on, resolved and owned. +/// +/// The internal agent engine (cron and xin agent jobs, skill evaluation) +/// resolves their selection with +/// [`resolve_agent_model_choice`] before anything is constructed: before the +/// runtime bootstrap (memory hygiene, snapshots, the database, plugins, +/// tools), so a refused selection leaves no trace (D-065 M-1). +#[derive(Clone)] +pub(crate) struct AgentModelChoice { + provider_name: String, + model_name: String, + model_binding: AgentModelBinding, + resolved: crate::providers::catalog::ResolvedModel, + catalog: crate::providers::catalog::CatalogView, +} + +impl AgentModelChoice { + pub(crate) const fn binding(&self) -> &AgentModelBinding { + &self.model_binding + } + + pub(crate) fn provider_name(&self) -> &str { + &self.provider_name + } + + pub(crate) fn model_name(&self) -> &str { + &self.model_name + } + + pub(crate) const fn catalog(&self) -> &crate::providers::catalog::CatalogView { + &self.catalog + } + + /// An injected provider may switch model IDs only within the connection + /// identity already owned by that instance and pinned configuration. + pub(crate) fn same_provider_connection(&self, other: &Self) -> bool { + self.model_binding.provider == other.model_binding.provider + && self.model_binding.provider_label == other.model_binding.provider_label + && self.model_binding.credential_ref == other.model_binding.credential_ref + && self.model_binding.credential_has_key == other.model_binding.credential_has_key + } + + pub(crate) fn resolved_selection(&self) -> (&str, &str) { + (&self.model_binding.provider_label, &self.model_binding.model) + } + + /// Re-resolve the selected source against the pinned configuration and + /// require the complete resolver release, including credential material, + /// to be unchanged. Provider construction consumes `self.resolved` + /// directly, so unrelated routes no longer affect this attestation. + pub(crate) fn factory_credential_source_matches(&self, config: &Config) -> bool { + if self.provider_name.trim() != self.provider_name { + return false; + } + let route = match providers::selection::route_target(&self.catalog, &self.provider_name, &self.model_name) { + Ok(route) => route.cloned(), + Err(_) => return false, + }; + if route != self.model_binding.route { + return false; + } + providers::selection::check_with( + config, + &self.catalog, + &self.provider_name, + &self.model_name, + self.resolved.credential().reference().clone(), + &providers::catalog::Requirement::chat(), + providers::catalog::UnknownPolicy::Invocation, + ) + .is_ok_and(|fresh| fresh == self.resolved) + } +} + +/// Identity selected before provider construction. It deliberately excludes +/// credential material: the provider factory must receive its own pinned +/// material, while the decision service can compare route and owner facts. +#[derive(Clone)] +pub(crate) struct AgentModelBinding { + provider: crate::providers::ProviderId, + provider_label: Arc, + model: Arc, + credential_ref: crate::providers::credentials::CredentialRef, + route: Option, + verification: crate::providers::catalog::Verification, + source: crate::providers::catalog::DescriptorSource, + dialects: crate::providers::catalog::Dialects, + credential_has_key: bool, +} + +impl AgentModelBinding { + /// Admit only the source spelling or the provider/model pinned at ingress. + pub(crate) fn admits_execution(&self, source: (&str, &str), execution: (&str, &str)) -> bool { + execution == source || execution == (self.provider_label.as_ref(), self.model.as_ref()) + } + + /// The model pinned at ingress, independent of any route spelling used to execute it. + pub(crate) fn pinned_model(&self) -> &str { + &self.model + } + + /// The provider pinned at ingress: the one a route spelling (`hint:`) + /// resolved to, which may differ from the provider the selection named. + pub(crate) fn pinned_provider_label(&self) -> &str { + &self.provider_label + } + + pub(crate) const fn credential_reference(&self) -> &crate::providers::credentials::CredentialRef { + &self.credential_ref + } + + pub(crate) fn from_resolved( + resolved: &crate::providers::catalog::ResolvedModel, + route: Option, + ) -> Self { + Self { + provider: resolved.provider().clone(), + provider_label: Arc::from(resolved.provider_label()), + model: Arc::from(resolved.model()), + credential_ref: resolved.credential().reference().clone(), + route, + verification: resolved.verification().clone(), + source: resolved.source(), + dialects: resolved.dialects(), + credential_has_key: resolved.credential().api_key().is_some(), + } + } + + pub(crate) fn matches_identity(&self, resolved: &crate::providers::catalog::ResolvedModel) -> bool { + self.provider == *resolved.provider() + && self.provider_label.as_ref() == resolved.provider_label() + && self.model.as_ref() == resolved.model() + && self.credential_ref == *resolved.credential().reference() + } + + pub(crate) fn matches(&self, resolved: &crate::providers::catalog::ResolvedModel) -> bool { + self.matches_identity(resolved) + && self.verification == *resolved.verification() + && self.source == resolved.source() + && self.dialects == resolved.dialects() + } + + pub(crate) const fn route(&self) -> Option<&crate::providers::catalog::RouteTarget> { + self.route.as_ref() + } +} + +/// Resolve the selection for an agent entry, check-only. +/// +/// This is the one resolution of the entry. An operator's invocation runs an +/// id-only model with a warning and refuses one the evidence rules out +/// (D-034). The chain the entry builds is routed, so every `[[model_routes]]` +/// destination is resolved when the routed provider is built, and a `hint:` +/// model is checked as the destination it names (D-035). +pub(crate) fn resolve_agent_model_choice( + config: &Config, + provider_override: Option<&str>, + model_override: Option<&str>, + creator_agent: Option<&str>, +) -> Result { + use crate::providers::credentials::{CredentialRef, LegacySlot}; + let named = creator_agent + .map(|name| config.agents.get(name).ok_or_else(|| anyhow::anyhow!("creator_gone"))) + .transpose()?; + let provider_name = named.map_or_else( + || provider_override.unwrap_or_else(|| providers::selection::default_provider(config)), + |agent| agent.provider.as_str(), + ); + let model_name = named.map_or_else( + || model_override.unwrap_or_else(|| providers::selection::default_model(config)), + |agent| agent.model.as_str(), + ); + let credential = named.map_or_else( + || providers::selection::credential_for(config, provider_name), + |agent| { + agent.credential_ref.as_ref().map_or_else( + || { + if agent.api_key.as_deref().is_some_and(|key| !key.trim().is_empty()) { + CredentialRef::LegacyInline(LegacySlot::Agent(creator_agent.unwrap_or_default().to_owned())) + } else { + providers::selection::credential_for(config, provider_name) + } + }, + |id| CredentialRef::Profile { id: id.clone() }, + ) + }, + ); + let catalog = providers::selection::catalog_for(config); + let route = providers::selection::route_target(&catalog, provider_name, model_name)?.cloned(); + let resolved = providers::selection::check_with( + config, + &catalog, + provider_name, + model_name, + credential, + &providers::catalog::Requirement::chat(), + providers::catalog::UnknownPolicy::Invocation, + ) + .map_err(|refusal| providers::selection::route_refusal(route.as_ref(), refusal))?; + Ok(AgentModelChoice { + provider_name: provider_name.to_string(), + model_name: model_name.to_string(), + model_binding: AgentModelBinding::from_resolved(&resolved, route), + resolved, + catalog, + }) +} + +/// The provider an agent entry runs on, and the only connection it may use. +/// +/// The root credential, base URL and rotation keys are released only when +/// the resolved selection is the provider identity they were configured for. +/// Anything else resolves its own credential (auth profile, or none for a +/// keyless `custom:` endpoint) or is refused at construction, before any +/// transport exists. +pub(crate) struct AgentProviderSelection<'a> { + pub(crate) provider_name: &'a str, + pub(crate) model_name: &'a str, + resolved: &'a crate::providers::catalog::ResolvedModel, + catalog: &'a crate::providers::catalog::CatalogView, +} + +/// Scope the connection for a resolved selection. Resolution already ran in +/// [`resolve_agent_model_choice`]; this does not resolve again. +pub(crate) fn agent_provider_selection(choice: &AgentModelChoice) -> AgentProviderSelection<'_> { + AgentProviderSelection { + provider_name: &choice.provider_name, + model_name: &choice.model_name, + resolved: &choice.resolved, + catalog: &choice.catalog, + } +} + +impl AgentProviderSelection<'_> { + /// Build the routed provider chain from the resolver-owned selection. + pub(crate) fn build_provider( + &self, + config: &Config, + options: &providers::ProviderRuntimeOptions, + ) -> Result> { + providers::create_routed_provider_for(self.resolved, self.catalog, config, options) + } +} + +/// P0-B: a provider override on the agent entry must give the override only its own +/// credential. Driven through the production seam, the real factory and a +/// loopback endpoint; every credential is a sentinel and the config directory +/// is a fresh temporary one with no auth profiles. +#[path = "../turn_tests/entry_provider_selection.rs"] +mod agent_provider_selection_tests; + +/// Run the Agent entry with a caller-owned runtime envelope. This preserves +/// owner/topic/task/source lineage for scheduler-driven single-shot turns while +/// keeping the public CLI entrypoint's existing defaults. +/// +/// `scheduled_tool_scope` is the tool context and policy a cron job or xin +/// task runs under when its `JobOrigin` is not the local operator +/// (CRON-ORIGIN); `None` keeps the local-operator CLI context and policy. It +/// governs a single-shot turn only. +#[allow(clippy::too_many_lines)] +pub(crate) async fn run_with_runtime_envelope( + config_source: impl Into, + message: String, + provider_override: Option, + model_override: Option, + temperature: f64, + shutdown: CancellationToken, + runtime_envelope_override: Option, + scheduled_tool_scope: Option, +) -> Result { + let config_source = config_source.into(); + let config = config_source.effective(); + let named_job = super::automation::select(config, runtime_envelope_override.as_ref())?; + let mut runtime_envelope_override = runtime_envelope_override; + let mut scheduled_tool_scope = scheduled_tool_scope; + if let (Some(job), Some(envelope)) = (&named_job, runtime_envelope_override.as_mut()) { + envelope.agent_partition = Some(job.partition(envelope)); + if let Some(scope) = scheduled_tool_scope.as_mut() { + scope.context.envelope.agent_partition = envelope.agent_partition.clone(); + } + } + let mut scheduled_admission = super::scheduled_source::validate_current( + runtime_envelope_override.as_ref(), + scheduled_tool_scope.as_ref(), + &shutdown, + ) + .await?; + anyhow::ensure!( + runtime_envelope_override.is_none() || scheduled_admission.is_some(), + "agent runtime override requires an admitted scheduled source" + ); + if let (Some(job), Some(admission), Some(envelope)) = ( + &named_job, + scheduled_admission.as_mut(), + runtime_envelope_override.as_ref(), + ) { + admission.job_metadata = Some(job.metadata(envelope)); + } + // Validate scoped identity before bootstrap can initialize persistence. + // Scheduled sources retain their attempt/lease run id through terminal + // recording and child lineage instead of acquiring a second CLI run id. + let scoped_run_id = runtime_envelope_override + .as_ref() + .map(|envelope| { + anyhow::ensure!( + envelope.workspace_id == config.workspace_dir.to_string_lossy() + && !envelope.session_key.trim().is_empty(), + "scoped runtime workspace or session does not match this invocation" + ); + let run_id = envelope + .run_id + .as_deref() + .filter(|run_id| !run_id.trim().is_empty()) + .ok_or_else(|| anyhow::anyhow!("a scoped runtime run requires its source-owned run identity"))?; + Ok::<_, anyhow::Error>(run_id.to_owned()) + }) + .transpose()?; + // Manual scheduled tool calls inherit this owner in ordinary single-shot + // execution. Let the entry's existing shutdown branch close its own turn; + // cancellation of this child scope must not race and drop that branch. + let caller_cleanup = if scheduled_admission.is_none() { + let parent = crate::runtime::turn_cleanup::current_tracker(); + Some(crate::runtime::turn_cleanup::CleanupScope::new( + parent.as_ref(), + CancellationToken::new(), + )?) + } else { + None + }; + + // D-065 M-1: resolve before the bootstrap, so a refused selection runs + // no memory hygiene, snapshot, database, plugin or tool setup. + let temperature = named_job + .as_ref() + .and_then(|job| config.agents.get(job.name.as_str())) + .and_then(|agent| agent.temperature) + .unwrap_or(temperature); + let choice = resolve_agent_model_choice( + config, + provider_override.as_deref(), + model_override.as_deref(), + named_job.as_ref().map(|job| job.name.as_str()), + )?; + // ── Wire up subsystems via RuntimeBootstrap (D1 step 2) ────── + // The internal agent engine is always a full single-shot run with no + // memory-only early-exit (unlike chat's `--list-sessions`), so it always + // needs memory + tools. It uses the dedicated `AgentLoop` profile: identical + // core to `Interactive` (memory + tools, no router), with the published + // source-bound turn decision service. Bootstrap constructs subsystems in + // observer/security/memory/runtime/tools order. + let ctx = crate::runtime::bootstrap::RuntimeBootstrap::build_agent( + config_source, + runtime_envelope_override.as_ref(), + scheduled_tool_scope.as_ref(), + ) + .await?; + + let _agent_permit = if let (Some(job), Some(envelope)) = (&named_job, runtime_envelope_override.as_ref()) { + let memory = ctx + .memory + .as_ref() + .ok_or_else(|| anyhow::anyhow!("agent_backend_unsupported"))?; + job.validate(memory.as_ref(), envelope)?; + let result = + crate::runtime::agent_admission::wait(&ctx.config, &envelope.resolved_owner_id(), job.name.as_str()).await; + // Retirement while waiting must refuse before any provider access. + job.validate(memory.as_ref(), envelope)?; + match result { + Ok(permit) => permit, + Err(error) => { + super::scheduled_source::begin_decision()?; + let fabric = MemoryFabric::new(Arc::clone(memory), envelope.workspace_id.clone()) + .with_event_recording(ctx.config.memory.event_recording_config()); + let payload = serde_json::json!({"job_id":envelope.task_id,"job_version":job.version,"reason":error.to_string(),"retryable":false}); + fabric + .record_runtime_event_idempotent( + envelope.message_scope(), + "scheduled.skipped", + "scheduled run skipped", + Some(serde_json::to_string(&payload)?), + format!("{}:skipped", envelope.run_id.as_deref().unwrap_or_default()), + ) + .await?; + return Err(error.into()); + } + } + } else { + None + }; + + // Scheduled cleanup owns the published writer even if this entry future is + // dropped before a decision or terminal proposal is available. + if scheduled_admission.is_some() { + let cleanup = crate::runtime::turn_cleanup::current_tracker() + .ok_or_else(|| anyhow::anyhow!("scheduled cleanup owner is missing"))?; + if let Some(service) = &ctx.turn_service { + cleanup.retain_service(Arc::clone(service)); + } + } + + // Capture invocation state without constructing the large async work yet. + let work = CliWork { + ctx: &ctx, + choice: &choice, + message, + temperature, + shutdown: &shutdown, + runtime_envelope_override, + scheduled_tool_scope, + scoped_run_id, + scheduled_admission: &scheduled_admission, + }; + // The synchronous factory invokes this closure in its own frame before + // returning the boxed future. The actual engine work remains owned here. + let work = boxed_cli_work(move || async move { + let CliWork { + ctx, + choice, + message, + temperature, + shutdown, + runtime_envelope_override, + scheduled_tool_scope, + scoped_run_id, + scheduled_admission, + } = work; + // `build` took ownership of `config`; reclaim a shared `Arc` for the + // rest of this function. `Arc` deref-coerces to `&Config`, so all the + // `config.xxx` accesses below are unchanged. + let config = Arc::clone(&ctx.config); + + let observer = Arc::clone(&ctx.observer); + let hooks = Arc::clone(&ctx.hooks); + // security is consumed only by tool construction, which now happens inside the + // bootstrap; it is not re-bound here on purpose (no downstream use in `run`). + // The local runtime adapter is likewise built and consumed inside the + // bootstrap, so it is no longer constructed here. + + // ── Memory (the brain) ──────────────────────────────────────── + // The Interactive profile always builds memory, so it is Some here; take it + // explicitly without panicking (iron rules 1/6). + let mem: Arc = ctx + .memory + .clone() + .ok_or_else(|| anyhow::anyhow!("bootstrap did not build a memory backend for the agent CLI"))?; + let memory_fabric = MemoryFabric::new(mem.clone(), config.workspace_dir.to_string_lossy()) + .with_event_recording(config.memory.event_recording_config()); + // One cost outbox pass before the turn (one-shot entry; D§5.2). + crate::runtime::cost_recovery::warn_legacy_files_once(&config.workspace_dir); + crate::runtime::cost_recovery::CostOutboxProjector::run_once( + Arc::clone(&mem), + config.workspace_dir.clone(), + config.cost.clone(), + ) + .await; + // D8-3: run_id is per-turn (generated inside each turn branch as `turn_run_id`), + // no longer a single per-run id held here. + let mut fabric_turn_seq: u64 = 0; + + // ── Tools ──────────────────────────────────────────────────── + // The Interactive profile built the tool registry inside the bootstrap + // (security + runtime + memory all ready) using the identical + // `all_tools_with_runtime` call with the same arguments; take it explicitly. + let tools_registry: Arc>> = ctx + .tools + .clone() + .ok_or_else(|| anyhow::anyhow!("bootstrap did not build the tool registry for the agent CLI"))?; + + // ── Provider (resolved before the bootstrap) ───────────────── + let selection = agent_provider_selection(choice); + let provider_name = selection.provider_name; + let model_name = selection.model_name; + + let provider_runtime_options = providers::provider_runtime_options_from_config(&config); + + let provider: Box = selection.build_provider(&config, &provider_runtime_options)?; + let effective_compaction = crate::providers::context_window::resolve_effective_compaction_config_with_catalog( + &config.agent.compaction, + provider_name, + model_name, + crate::providers::context_window::ContextWindowSources::from_config(&config), + &config.model_routes, + choice.catalog(), + ); + crate::providers::context_window::trace_effective_compaction_resolution(&effective_compaction); + + observer.record_event(&ObserverEvent::AgentStart { + provider: provider_name.to_string(), + model: model_name.to_string(), + }); + hooks + .emit( + HookEvent::AgentStart, + serde_json::json!({ + "provider": provider_name, + "model": model_name, + }), + ) + .await; + + // ── Build system prompt from the canonical prompt context ── + let native_tools = provider + .capabilities_for(model_name, crate::providers::traits::ProviderRequestMode::NonStreaming) + .native_tool_calling; + + // ── Approval manager (supervised mode) ─────────────────────── + let approval_manager = Arc::new(ApprovalManager::new()); + + // ── Execute ────────────────────────────────────────────────── + let start = Instant::now(); + + let mut final_output = String::new(); + + { + let msg = message; + // ── Single-shot turn (D5/D9 step 2) ────────────────────────── + // Race the work against the external shutdown token so a root + // cancel aborts the in-flight turn instead of waiting it out. + fabric_turn_seq += 1; + // Keep the turn identity outside the raced future so a shutdown that + // drops it can still close the shared terminal boundary as Cancelled. + let turn_run_id = scoped_run_id.unwrap_or_else(|| Uuid::new_v4().to_string()); + let mut runtime_envelope = scheduled_admission.as_ref().map_or_else( + || { + resolve_agent_turn_envelope( + runtime_envelope_override.as_ref(), + memory_fabric.workspace_id(), + &turn_run_id, + ) + }, + |admission| admission.envelope().clone(), + ); + if runtime_envelope.config_source_revision.is_none() { + runtime_envelope = runtime_envelope.with_config_generation(&ctx.config_generation); + } + let mut fabric_scope = runtime_envelope + .message_scope() + .with_recipient(format!("{provider_name}/{model_name}")); + let cancel_turn_id = turn_run_id.clone(); + let cancel_scope = parking_lot::Mutex::new(runtime_envelope.message_scope()); + let turn_started_at = chrono::Utc::now(); + let terminal_binding = Arc::new(parking_lot::Mutex::new(None::)); + let admission_proof = std::sync::OnceLock::::new(); + let terminal_guard = std::sync::OnceLock::::new(); + let mut cli_admission_guard = None; + let mut scheduled_input_guard = None; + let retained_provider_trace = Arc::new(crate::agent::turn_contracts::RetainedProviderTrace::default()); + let single_shot = boxed_cli_single_shot(async { + let agent_user_event = if scheduled_admission.is_none() { + let owner = crate::runtime::turn_cleanup::current_tracker() + .ok_or_else(|| anyhow::anyhow!("CLI input cleanup owner missing"))?; + let (event, guard) = CliPendingInput { + fabric: memory_fabric.clone(), + generation: Arc::clone(&ctx.config_generation), + envelope: runtime_envelope.clone(), + expected_session_key: format!("agent:{turn_run_id}"), + scope: fabric_scope.clone(), + choice: choice.clone(), + input: msg.clone(), + key: format!("agent:{turn_run_id}:{fabric_turn_seq}:user"), + ticket: owner.register(shutdown.clone())?, + } + .record() + .await?; + cli_admission_guard = Some(guard); + event + } else { + let admission = scheduled_admission + .as_ref() + .ok_or_else(|| anyhow::anyhow!("scheduled admission source missing"))?; + let owner = crate::runtime::turn_cleanup::current_tracker() + .ok_or_else(|| anyhow::anyhow!("scheduled input cleanup owner missing"))?; + let (event, guard) = admission + .record_guarded( + memory_fabric.clone(), + Arc::clone(&ctx.config_generation), + ( + msg.clone(), + format!("agent:{turn_run_id}:{fabric_turn_seq}:user"), + choice.clone(), + ), + owner.register(shutdown.clone())?, + ) + .await?; + scheduled_input_guard = Some(guard); + event + }; + + let decision_turn = { + let service = ctx + .turn_service + .as_ref() + .ok_or_else(|| anyhow::anyhow!("agent decision service is missing"))?; + let proof = if let Some(admission) = &scheduled_admission { + let source = admission + .bind_input( + mem.as_ref(), + &ctx.config_generation, + &runtime_envelope, + (&msg, choice), + agent_user_event.as_ref(), + shutdown, + ) + .await?; + AgentTurnProof { + workspace_id: Arc::from(source.envelope.workspace_id.as_str()), + owner_id: Arc::from(source.envelope.resolved_owner_id()), + session_key: Arc::from(source.envelope.session_key.as_str()), + run_id: Arc::from(turn_run_id.as_str()), + source_event_id: source.envelope.source_message_event_id.as_deref().map(Arc::from), + routing_input: Arc::from(msg.as_str()), + memory_scope: source + .envelope + .memory_write_context(source.execution.chat_type.as_str()), + provider_name: Arc::from(choice.provider_name()), + model_name: Arc::from(choice.model_name()), + model_binding: choice.binding().clone(), + config_generation_id: ctx.config_generation.id.0, + config_source_revision: Arc::from( + ctx.config_generation.source_revision.fingerprint_sha256.as_str(), + ), + retrieval_principal: source.envelope.memory_principal(), + scheduled: Some(Box::new(source)), + } + } else { + issue_cli_agent_turn_proof( + None, + &runtime_envelope, + &ctx.config_generation, + &turn_run_id, + &msg, + agent_user_event.as_ref(), + choice, + )? + }; + if let Some(source) = proof.scheduled.as_ref() { + runtime_envelope = source.envelope.clone(); + } + // Admission owns the durable input identity. Carry it into + // ordinary completion and cancellation, not just tool calls. + runtime_envelope.source_message_event_id = proof.source_event_id.as_deref().map(str::to_owned); + fabric_scope = runtime_envelope + .message_scope() + .with_recipient(format!("{provider_name}/{model_name}")); + *cancel_scope.lock() = runtime_envelope.message_scope(); + let proof = admission_proof.get_or_init(|| proof); + if scheduled_admission.is_some() { + // Mark before polling decision work: a failed or interrupted + // admission can already have a durable decision identity. + super::scheduled_source::begin_decision()?; + } + let decision = service + .open_issued_turn_context( + proof, + crate::runtime::turn_context::AgentTurnKind::SingleShot, + shutdown, + ) + .await?; + let advice = service.advisory().analyze_turn(decision.runtime(), shutdown).await; + *terminal_binding.lock() = Some(service.terminal_binding(&decision)?); + let cleanup_ticket = if scheduled_admission.is_some() { + scheduled_input_guard + .take() + .ok_or_else(|| anyhow::anyhow!("scheduled input cleanup guard missing"))? + .into_terminal_ticket()? + } else { + cli_admission_guard + .take() + .ok_or_else(|| anyhow::anyhow!("CLI input cleanup guard missing"))? + .into_terminal_ticket()? + }; + let route_decision = crate::llm::route_decision::RouteDecision::single_candidate_for_context( + provider_name, + model_name.to_string(), + runtime_envelope.resolved_owner_id(), + runtime_envelope.session_key.clone(), + runtime_envelope.source_message_event_id.clone(), + None, + "agent_cli_single", + u32::try_from(msg.chars().count() / 4).unwrap_or(u32::MAX), + !tools_registry.is_empty(), + false, + ); + let guard = crate::runtime::turn_terminal::TurnTerminalGuard::new( + cleanup_ticket, + Arc::clone(service), + Arc::clone(&decision), + memory_fabric.clone(), + Arc::clone(&config), + runtime_envelope.clone(), + None, + )? + .with_provider_trace(Arc::clone(&retained_provider_trace), route_decision.clone()); + terminal_guard + .set(guard) + .map_err(|_| anyhow::anyhow!("agent terminal owner already exists"))?; + + (service, proof, decision, route_decision, advice) + }; + + let (decision_service, decision_proof, decision_context, route_decision, advice) = &decision_turn; + let decision_proof = *decision_proof; + let selected_skills = decision_service.agent_prompt_skills(decision_proof, decision_context)?; + let system_prompt = match &named_job { + Some(job) => job.prompt(&config)?, + None => build_runtime_system_prompt(&config, model_name, &selected_skills, native_tools), + }; + + // Auto-save user message to memory (skip short/trivial messages) + if config.memory.should_auto_promote_user_message(&msg) { + let _ = save_current_input( + &memory_fabric, + &turn_run_id, + &runtime_envelope.session_key, + &msg, + agent_user_event.as_ref().map(|event| event.event_id.as_str()), + runtime_envelope.agent_partition.clone(), + ) + .await; + } + + // Inject memory context into user message. The routing input is + // pinned from `msg` here, ahead of the enrichment below. + let memory_runtime = cli_turn_memory_runtime( + &mem, + &config.workspace_dir, + &runtime_envelope, + &memory_fabric, + &fabric_scope, + agent_user_event.as_ref().map(|event| event.event_id.as_str()), + ); + let mem_context = crate::agent::context_recall::scoped_recall( + mem.as_ref(), + &crate::agent::context_recall::RecallScope::from_envelope( + &runtime_envelope, + &config.memory, + "private", + ), + &msg, + crate::agent::context_recall::RECALL_CONTEXT_BUDGET, + ) + .await; + let context = mem_context.preamble.clone(); + let enriched = if context.is_empty() { + msg.clone() + } else { + format!("{context}{msg}") + }; + + let mut history = vec![ + ChatMessage::system(&system_prompt), + crate::agent::turn_contracts::inbound_user_message(&enriched), + ]; + + // D8-4: seed a turn-root spawn context so a sub-agent spawned from this + // single-shot agent turn inherits parent_run_id = the per-turn run_id. + let turn_spawn_ctx = crate::tools::sessions_spawn::SpawnExecutionContext::seed_turn_context( + turn_run_id.clone(), + runtime_envelope.session_key.clone(), + ); + let provider_started_at = chrono::Utc::now(); + let runtime_adapter = Some({ + let mut adapter = + configured_cli_tool_adapter(&ctx.security, &tools_registry, &approval_manager, &memory_runtime); + { + let proof = decision_proof; + let mut envelope = runtime_envelope.clone(); + if let Some(event_id) = proof.source_event_id() { + envelope = envelope.with_source_message_event_id(event_id); + } + adapter.tool_execution_context = proof.scheduled.as_ref().map_or_else( + || cli_tool_execution_context(envelope), + |source| source.execution.clone(), + ); + } + if let Some(case) = &ctx.controlled_case { + case.apply(&mut adapter.tool_execution_context)?; + } + adapter.provider_trace = Some(Arc::clone(&retained_provider_trace)); + adapter + }); + let turn_result = crate::tools::execution::with_scheduled_job_tool_scope( + scheduled_tool_scope, + crate::tools::sessions_spawn::SPAWN_EXECUTION_CONTEXT.scope(turn_spawn_ctx, async { + Box::pin(run_turn( + &mut history, + crate::agent::turn_request::TurnRequest { + advice: advice.clone(), + channel_name: "cli", + scope: None, + mode: ChatMode::default(), + silent: false, + expose_stay_silent: false, + multimodal: &config.multimodal, + schedule: crate::agent::turn_request::TurnSchedule { + read_only_tool_concurrency_window: config.agent.read_only_tool_concurrency_window, + priority_scheduling_enabled: config.agent.priority_scheduling_enabled, + low_priority_tool_names: config.agent.low_priority_tools.clone(), + }, + compaction: Some(decision_context.main_compaction()), + decision: crate::agent::turn_request::TurnDecision { + service: decision_service, + context: decision_context, + runtime: decision_context.runtime(), + proof: decision_proof, + }, + }, + crate::agent::turn_request::TurnServices { + provider: provider.as_ref(), + provider_name, + model: model_name, + temperature, + tools_registry: Arc::clone(&tools_registry), + observer: observer.as_ref(), + hooks: &hooks, + approval: Some(Arc::clone(&approval_manager)), + approval_resolver: None, + runtime_adapter, + memory: memory_runtime, + }, + crate::agent::turn_request::TurnDelivery { + cancellation: None, + on_delta: None, + on_tool_call: None, + }, + )) + .await + .map(|(outcome, trace)| (outcome.into_text(), trace)) + }), + ) + .await; + let (response, turn_trace) = match turn_result { + Ok(result) => result, + Err(error) => { + let provider_outcome = if error.is::() { + // No provider attempt belongs to a refused send. The + // terminal guard retains any earlier observed rounds. + None + } else { + Some( + crate::llm::route_decision::ProviderExecutionOutcome::failed_for_decision( + &route_decision, + provider_started_at, + &error, + ), + ) + }; + if let Err(finalize_error) = crate::runtime::turn_terminal::commit_terminal( + terminal_guard.get(), + &memory_fabric, + crate::agent::terminal::TurnTerminalDraft { + binding: terminal_binding_snapshot(&terminal_binding), + terminal_id: turn_run_id.clone(), + scope: runtime_envelope.message_scope(), + status: crate::agent::terminal::TurnTerminalStatus::Failed, + history: None, + history_scope: None, + provider_outcome, + telemetry: crate::agent::terminal::TurnTerminalTelemetry { + summary: error.to_string(), + started_at: provider_started_at, + finished_at: chrono::Utc::now(), + }, + delivery_intent: crate::agent::terminal::TurnDeliveryIntent::ReturnToCaller, + }, + &config, + ) + .await + { + tracing::warn!(error = %crate::agent::diagnostics::error_class(&finalize_error), "Failed to commit failed single-shot agent terminal event"); + } + if !QUIET_SINGLE_SHOT.try_with(|quiet| *quiet).unwrap_or(false) + && let Some(refusal) = + error.downcast_ref::() + { + println!("{}", refusal.reply()); + } + return Err(error); + } + }; + { + let decision = decision_context; + anyhow::ensure!( + turn_trace.execution_trace.as_ref() == Some(&decision.terminal_execution_trace()), + "tool loop trace differs from the owning decision's execution facts" + ); + } + let provider_outcome = crate::agent::terminal::provider_outcome_from_trace( + &route_decision, + provider_started_at, + turn_trace, + ); + if let Err(error) = crate::runtime::turn_terminal::commit_terminal( + terminal_guard.get(), + &memory_fabric, + crate::agent::terminal::TurnTerminalDraft { + binding: terminal_binding_snapshot(&terminal_binding), + terminal_id: turn_run_id.clone(), + scope: runtime_envelope.message_scope(), + status: crate::agent::terminal::TurnTerminalStatus::Completed, + history: Some(crate::agent::terminal::TurnHistoryProjection { + assistant_content: response.clone(), + history_commit_len: history.len(), + }), + history_scope: Some( + fabric_scope + .clone() + .with_sender(format!("{provider_name}/{model_name}")) + .with_recipient("local-user"), + ), + provider_outcome: Some(provider_outcome), + telemetry: crate::agent::terminal::TurnTerminalTelemetry { + summary: "single-shot agent turn completed".to_string(), + started_at: provider_started_at, + finished_at: chrono::Utc::now(), + }, + delivery_intent: crate::agent::terminal::TurnDeliveryIntent::ReturnToCaller, + }, + &config, + ) + .await + { + return Err(error); + } + increment_recalled_useful_counts(mem.as_ref(), &mem_context.ids).await; + final_output = response.clone(); + if !QUIET_SINGLE_SHOT.try_with(|quiet| *quiet).unwrap_or(false) { + println!("{response}"); + } + observer.record_event(&ObserverEvent::TurnComplete); + hooks + .emit( + HookEvent::TurnComplete, + serde_json::json!({ + "mode": "single", + "response_chars": response.chars().count(), + }), + ) + .await; + Ok::<(), anyhow::Error>(()) + }); + let single_result = tokio::select! { + biased; + () = shutdown.cancelled() => { + if terminal_guard.get().is_none() + && terminal_binding_snapshot(&terminal_binding).is_some() + { + let cancelled_scope = cancel_scope.lock().clone(); + if let Err(error) = crate::agent::terminal::finalize_turn( + &memory_fabric, + crate::agent::terminal::TurnTerminalDraft { + binding: terminal_binding_snapshot(&terminal_binding), + terminal_id: cancel_turn_id, + scope: cancelled_scope, + status: crate::agent::terminal::TurnTerminalStatus::Cancelled, + history: None, + history_scope: None, + provider_outcome: None, + telemetry: crate::agent::terminal::TurnTerminalTelemetry { + summary: "single-shot agent cancelled by shutdown signal".to_string(), + started_at: turn_started_at, + finished_at: chrono::Utc::now(), + }, + delivery_intent: crate::agent::terminal::TurnDeliveryIntent::None, + }, + &config.cost, + &config.workspace_dir, + ).await { + tracing::warn!(error = %crate::agent::diagnostics::error_class(&error), "Failed to commit cancelled single-shot agent terminal event"); + } + } + Err(anyhow::anyhow!("agent single-shot run cancelled by shutdown signal")) + } + result = single_shot => result, + }; + if let (Err(error), Some(guard)) = (&single_result, terminal_guard.get()) { + guard.finish_failure(error, shutdown.is_cancelled()).await?; + } + if let Err(error) = &single_result + && let Some(mut guard) = cli_admission_guard.take() + { + guard + .finish_failure(shutdown.is_cancelled(), &error.to_string()) + .await + .map_err(|record_error| { + anyhow::anyhow!( + "CLI admission failed: {error}; failure persistence is unconfirmed: {record_error}" + ) + })?; + } + if single_result.is_err() + && let Some(mut guard) = scheduled_input_guard.take() + { + guard + .finish_failure(shutdown.is_cancelled()) + .await + .map_err(|_| anyhow::anyhow!("scheduled admission failure persistence is unconfirmed"))?; + } + single_result?; + } + + let duration = start.elapsed(); + observer.record_event(&ObserverEvent::AgentEnd { + provider: provider_name.to_string(), + model: model_name.to_string(), + duration, + tokens_used: None, + cost_usd: None, + }); + hooks + .emit( + HookEvent::AgentEnd, + serde_json::json!({ + "duration_ms": duration.as_millis(), + "tokens_used": serde_json::Value::Null, + }), + ) + .await; + + Ok::(final_output) + }); + let result = match caller_cleanup { + Some(cleanup) => cleanup.run(work).await, + None => work.await, + }; + if scheduled_admission.is_none() { + if let Some(service) = &ctx.turn_service { + service + .shutdown(Instant::now() + std::time::Duration::from_secs(2)) + .await; + } + } + // The process may exit right after this run: deliver the queued hook events first. + ctx.hooks.drain_for_shutdown().await; + result +} + +// This invocation state preserves all captures across the boxed work boundary. +struct CliWork<'a> { + ctx: &'a crate::runtime::bootstrap::AppContext, + choice: &'a AgentModelChoice, + message: String, + temperature: f64, + shutdown: &'a CancellationToken, + runtime_envelope_override: Option, + scheduled_tool_scope: Option, + scoped_run_id: Option, + scheduled_admission: &'a Option, +} + +// Invoke the small capture closure here so the large future is constructed +// outside the canonical entry poll frame, then preserve the existing heap seam. +#[inline(never)] +fn boxed_cli_work<'a, F, Fut>( + make_work: F, +) -> std::pin::Pin> + Send + 'a>> +where + F: FnOnce() -> Fut, + Fut: std::future::Future> + Send + 'a, +{ + Box::pin(make_work()) +} + +// Keep the single-turn poll state out of the enclosing CLI select frame. +// The synchronous boundary also keeps Box construction in its own stack frame. +#[inline(never)] +fn boxed_cli_single_shot<'a>( + work: impl std::future::Future> + Send + 'a, +) -> std::pin::Pin> + Send + 'a>> { + Box::pin(work) +} + +fn resolve_agent_turn_envelope( + override_envelope: Option<&RuntimeEnvelope>, + workspace_id: &str, + turn_run_id: &str, +) -> RuntimeEnvelope { + let mut envelope = override_envelope + .cloned() + .unwrap_or_else(|| RuntimeEnvelope::agent(workspace_id.to_string(), turn_run_id.to_string())); + if envelope.recipient.is_none() { + envelope = envelope.with_recipient("cli:local-user"); + } + envelope +} + +#[path = "../turn_tests/entry.rs"] +mod tests; + +#[cfg(test)] +mod cli_admission_failure_tests { + use super::*; + + #[tokio::test] + async fn cancelled_admission_retries_without_model_terminal_or_secret() { + let dir = tempfile::tempdir().unwrap(); + let mut config = Config::default(); + config.workspace_dir = dir.path().to_path_buf(); + config.config_path = dir.path().join("config.toml"); + let generation = crate::config::new_shared(config.clone()).pin(); + let memory: Arc = Arc::new(crate::memory::SqliteMemory::new(dir.path()).unwrap()); + let proof = + test_recorded_cli_agent_turn_proof_with_input(&generation, memory.clone(), "prx input", "prx_run").await; + let fabric = MemoryFabric::new(memory.clone(), dir.path().to_string_lossy()); + let summary = format!("cancelled {}", crate::agent::terminal::persistence_probe::PROBE_SECRET); + for _ in 0..2 { + proof + .record_cli_admission_failure(&fabric, &config, true, &summary) + .await + .unwrap(); + } + assert!( + proof + .record_cli_admission_failure(&fabric, &config, false, &summary) + .await + .is_err() + ); + let event = memory + .find_message_event_by_idempotency_key(fabric.workspace_id(), "turn:prx_run:admission-failed") + .await + .unwrap() + .unwrap(); + assert!(event.id > 0); + assert_eq!(event.causation_event_id.as_deref(), proof.source_event_id.as_deref()); + assert!( + memory + .find_message_event_by_idempotency_key(fabric.workspace_id(), "turn:prx_run:final",) + .await + .unwrap() + .is_none() + ); + crate::agent::terminal::persistence_probe::assert_nothing_under_persists_the_probe_secret(dir.path()); + } +} + +pub(crate) fn cli_tool_execution_context(envelope: RuntimeEnvelope) -> crate::tools::ToolExecutionContext { + crate::tools::ToolExecutionContext::new(envelope, "private") + .with_dispatch_origin(crate::tools::DispatchOrigin::Operator) +} diff --git a/src/chat/binding/tests.rs b/src/chat/binding/tests.rs index 9aaac26a1..a93fbf687 100644 --- a/src/chat/binding/tests.rs +++ b/src/chat/binding/tests.rs @@ -280,6 +280,7 @@ async fn chat_production_save_excludes_live_input_without_useful_feedback() { &binding.envelope().session_key, "prx input", binding.envelope().source_message_event_id.as_deref(), + None, ) .await .unwrap(); diff --git a/src/chat/chat_events.rs b/src/chat/chat_events.rs index cbbc040f8..33eee3c2c 100644 --- a/src/chat/chat_events.rs +++ b/src/chat/chat_events.rs @@ -73,7 +73,7 @@ pub(super) fn chat_message_event_scope( model_name: &str, ) -> MessageEventScope { let chat_session_id = chat_session_id_from_key(chat_session_key); - RuntimeEnvelope::chat_canonical(workspace_id, chat_session_id, MemoryVisibility::Workspace) + chat_runtime_envelope(workspace_id, chat_session_id) .with_recipient(format!("{provider_name}/{model_name}")) .with_run_id(chat_run_id.to_string()) .message_scope() @@ -84,8 +84,15 @@ pub(super) fn chat_message_event_scope( /// for read-merge so the read principal unions canonical + legacy history. pub(crate) fn chat_runtime_envelope(workspace_id: &str, chat_session_key: &str) -> RuntimeEnvelope { let chat_session_id = chat_session_id_from_key(chat_session_key); - RuntimeEnvelope::chat_canonical(workspace_id.to_string(), chat_session_id, MemoryVisibility::Workspace) - .with_recipient("terminal:user") + let envelope = + RuntimeEnvelope::chat_canonical(workspace_id.to_string(), chat_session_id, MemoryVisibility::Workspace) + .with_recipient("terminal:user"); + let partition = crate::memory::AgentPartition { + workspace_id: workspace_id.into(), + owner_id: envelope.resolved_owner_id(), + key: crate::memory::PartitionKey::Main, + }; + envelope.with_agent_partition(partition) } #[cfg(test)] diff --git a/src/chat/message_inbox.rs b/src/chat/message_inbox.rs index e5f5dd38f..946a399bd 100644 --- a/src/chat/message_inbox.rs +++ b/src/chat/message_inbox.rs @@ -3,6 +3,24 @@ use crate::channels::traits::ChannelMessage; use crate::messaging::runtime::{MessageInput, MessagingRuntime, SessionInbox}; use std::sync::Arc; +#[derive(Debug, thiserror::Error)] +#[error("terminal_session_erased: cached history discarded; starting a new chat")] +pub struct SessionErased; + +pub(super) async fn pin_epoch(config: &crate::config::Config, session: &str) -> anyhow::Result<()> { + if config.memory.backend != "sqlite" { + return Ok(()); + } + let config = config.clone(); + let session = session.to_owned(); + crate::runtime::blocking::spawn_blocking(move || { + let runtime = MessagingRuntime::for_config(&config)?; + let owner = super::chat_runtime_envelope(&runtime.workspace, &session).resolved_owner_id(); + runtime.store.pin_terminal_epoch(&runtime.workspace, &owner, &session) + }) + .await? +} + pub(super) struct ChatInbox { pub(super) runtime: Arc, inbox: SessionInbox, diff --git a/src/chat/mod.rs b/src/chat/mod.rs index 06fd6a3c9..925640355 100644 --- a/src/chat/mod.rs +++ b/src/chat/mod.rs @@ -91,6 +91,7 @@ mod file_mention; mod input_queue; mod line_approval; mod message_inbox; +pub use message_inbox::SessionErased; mod model_commands; mod output; mod plain_queue; diff --git a/src/chat/run.rs b/src/chat/run.rs index 457b275d5..9349cb4c6 100644 --- a/src/chat/run.rs +++ b/src/chat/run.rs @@ -363,6 +363,7 @@ async fn run_internal( &skills, native_tools, ); + super::message_inbox::pin_epoch(&config, &chat_session_key).await?; #[cfg(feature = "terminal-tui")] let (initial_saved_session_entries, chat_mirror) = @@ -843,6 +844,7 @@ async fn run_internal( // outer loop: it only `break`s with a real input message (or `None` on // shutdown). On a tick we poll the registry and surface results via the // dispatcher (single source, reaches both render paths), then keep waiting. + let mut session_erased = false; 'chat: while let Some(input) = include!("run/event_pump.rs") { turn_signal.ensure_history_commits_healthy()?; let provider_queue_task_id = input.turn_task_id; @@ -1070,6 +1072,9 @@ async fn run_internal( // The dispatcher is drained now: a save that failed during exit, // including one only seen while draining, has latched by this point, and // `/exit` or EOF must not report success over it. + if session_erased { + return Err(super::message_inbox::SessionErased.into()); + } exit_summaries?; turn_signal.ensure_history_commits_healthy()?; finished?; diff --git a/src/chat/run/event_pump.rs b/src/chat/run/event_pump.rs index 75f5dba6a..79350a419 100644 --- a/src/chat/run/event_pump.rs +++ b/src/chat/run/event_pump.rs @@ -7,6 +7,9 @@ loop { } else {true} }); inbox.drain(); + history.clear(); + session_erased = true; + break None; } if message_inbox.as_ref().is_some_and(|inbox|inbox.session()!=chat_session_key) { diff --git a/src/chat/run/provider_turn.rs b/src/chat/run/provider_turn.rs index 3edd86da4..3a1969c0a 100644 --- a/src/chat/run/provider_turn.rs +++ b/src/chat/run/provider_turn.rs @@ -118,7 +118,8 @@ let _ = crate::agent::entry::save_current_input(&memory_fabric, admitted_binding.envelope().run_id.as_deref().context("chat turn run id missing")?, &admitted_binding.envelope().session_key, - &safe_user_input, chat_user_event.as_ref().map(|event| event.event_id.as_str())).await; + &safe_user_input, chat_user_event.as_ref().map(|event| event.event_id.as_str()), + admitted_binding.envelope().agent_partition.clone()).await; } // Inject memory context diff --git a/src/chat/session_switch.rs b/src/chat/session_switch.rs index 8cad610c4..8cc504e90 100644 --- a/src/chat/session_switch.rs +++ b/src/chat/session_switch.rs @@ -307,6 +307,8 @@ pub(super) async fn apply_chat_session_switch( persist: bool, ) -> Result<()> { bind_session_to_runtime_provider_model(&mut loaded_session, ctx.provider_name, ctx.model_name); + let key = crate::runtime::envelope::RuntimeEnvelope::chat_canonical_session_key(&loaded_session.id); + super::message_inbox::pin_epoch(ctx.config, &key).await?; // The reducer history and the provider view open with the same system // prompt from the acknowledged load on. let leading_system_prompt = diff --git a/src/memory/sqlite/agent_erasure.rs b/src/memory/sqlite/agent_erasure.rs index 2802a5f27..4def7d599 100644 --- a/src/memory/sqlite/agent_erasure.rs +++ b/src/memory/sqlite/agent_erasure.rs @@ -261,6 +261,7 @@ fn erase_rows( counts: &mut BTreeMap, erase_id: Option<&str>, keep_message_keys: bool, + preserve_memories: bool, ) -> anyhow::Result<()> { check_manifest(conn)?; let tables = stamped_tables(conn)?; @@ -279,7 +280,7 @@ fn erase_rows( // Defer links while every member of the scoped family is removed. conn.execute_batch("PRAGMA defer_foreign_keys=ON")?; for (table, columns) in &tables { - let condition = erase_predicate(table, columns); + let condition = erase_condition(table, columns, preserve_memories); let amount: i64 = conn.query_row(&format!("SELECT count(*) FROM \"{table}\""), [], |row| row.get(0))?; *counts.entry(table.clone()).or_default() = u64::try_from(amount)?; if let Some(erase_id) = erase_id { @@ -307,7 +308,8 @@ fn erase_rows( } let ids = { let mut query = conn.prepare(&format!( - "SELECT {id_column} FROM {table} WHERE ma_scope_id IN(SELECT value FROM json_each(?1))" + "SELECT {id_column} FROM {table} WHERE {}", + erase_condition(table, &["ma_scope_id".into()], preserve_memories) ))?; query .query_map([scopes], |row| row.get::<_, String>(0))? @@ -335,7 +337,10 @@ fn erase_rows( )?; } else { conn.execute( - &format!("DELETE FROM \"{table}\" WHERE {}", erase_predicate(table, columns)), + &format!( + "DELETE FROM \"{table}\" WHERE {}", + erase_condition(table, columns, preserve_memories) + ), [scopes], )?; } @@ -372,7 +377,16 @@ fn erase_rows( Ok(()) } -fn verify(conn: &Connection, scopes: &str, keep_message_keys: bool) -> anyhow::Result<()> { +fn erase_condition(table: &str, columns: &[String], preserve_memories: bool) -> String { + let condition = erase_predicate(table, columns); + if preserve_memories { + format!("({condition}) AND NOT ({})", super::history_retention::kept(table)) + } else { + condition + } +} + +fn verify(conn: &Connection, scopes: &str, keep_message_keys: bool, preserve_memories: bool) -> anyhow::Result<()> { check_manifest(conn)?; for (table, columns) in stamped_tables(conn)? { let payload = if table == "rf_message_attempts" && keep_message_keys { @@ -383,7 +397,7 @@ fn verify(conn: &Connection, scopes: &str, keep_message_keys: bool) -> anyhow::R let remaining: i64 = conn.query_row( &format!( "SELECT count(*) FROM \"{table}\" WHERE ({}){payload}", - erase_predicate(&table, &columns) + erase_condition(&table, &columns, preserve_memories) ), [scopes], |row| row.get(0), @@ -490,13 +504,22 @@ pub(super) fn finish_history(memory: &SqliteMemory, work: &EraseWork) -> anyhow: forgotten.documents_touched += found.documents_touched; } } - erase_rows(&tx, &scopes, &mut counts, Some(&work.erase_id), !work.purge).context(ErasureStep::EraseRows)?; + erase_rows( + &tx, + &scopes, + &mut counts, + Some(&work.erase_id), + !work.purge, + !work.purge && !work.forget_writes, + ) + .context(ErasureStep::EraseRows)?; // Session previews are shared by agents; derive them again from survivors. tx.execute("UPDATE sessions SET last_message_preview=COALESCE((SELECT substr(c.content,1,200) FROM conversation_turns c WHERE c.session_key=sessions.session_key AND c.deleted_at IS NULL ORDER BY c.id DESC LIMIT 1),''), message_count=(SELECT count(*) FROM conversation_turns c WHERE c.session_key=sessions.session_key AND c.deleted_at IS NULL) WHERE session_key IN(SELECT session_key FROM agent_scopes WHERE scope_id IN(SELECT value FROM json_each(?1)))",[&scopes])?; - verify(&tx, &scopes, !work.purge).context(ErasureStep::VerifyCoverage)?; + verify(&tx, &scopes, !work.purge, !work.purge && !work.forget_writes) + .context(ErasureStep::VerifyCoverage)?; tx.execute( "UPDATE agent_erase_work SET main_erased=1,counts=?2,forgotten=?3 WHERE erase_id=?1", params![ @@ -514,7 +537,7 @@ pub(super) fn finish_history(memory: &SqliteMemory, work: &EraseWork) -> anyhow: .context(ErasureStep::TruncateWal)?; let conn = memory.pool.write(); let tx = begin_immediate(&conn)?; - verify(&tx, &scopes, !work.purge).context(ErasureStep::VerifyCoverage)?; + verify(&tx, &scopes, !work.purge, !work.purge && !work.forget_writes).context(ErasureStep::VerifyCoverage)?; let existing: Option = tx.query_row( "SELECT receipt FROM agent_erase_work WHERE erase_id=?1", [&work.erase_id], @@ -530,6 +553,12 @@ pub(super) fn finish_history(memory: &SqliteMemory, work: &EraseWork) -> anyhow: )?; let mut receipt = serde_json::json!({"status":"erased","scope":{"session":work.session,"agent":work.agent,"incarnation":work.incarnation}, "erase_id":work.erase_id,"generation":work.generation,"remaining":0,"incarnation":work.incarnation}); + if !work.forget_writes && !work.purge { + receipt + .as_object_mut() + .context("erase receipt must be an object")? + .insert("retained".into(), super::history_retention::list(&tx, &scopes)?); + } if work.forget_writes { let counts: crate::memory::RfForgetCounts = serde_json::from_str(&forgotten)?; receipt.as_object_mut().context("erase receipt must be an object")?.insert("forgotten".to_owned(),serde_json::json!({"created":counts.memories_created+counts.documents_created,"touched":counts.memories_touched+counts.documents_touched})); @@ -627,8 +656,15 @@ fn erase_side_stores(memory: &SqliteMemory, work: &EraseWork, scopes: &str) -> a serde_json::from_str::>(&old)? } else { let mut counts = BTreeMap::new(); - erase_rows(&tx, scopes, &mut counts, None, !work.purge)?; - verify(&tx, scopes, !work.purge)?; + erase_rows( + &tx, + scopes, + &mut counts, + None, + !work.purge, + !work.purge && !work.forget_writes, + )?; + verify(&tx, scopes, !work.purge, !work.purge && !work.forget_writes)?; tx.execute( "INSERT INTO agent_erase_side_progress VALUES(?1,?2)", params![work.erase_id, serde_json::to_string(&counts)?], diff --git a/src/memory/sqlite/agent_migration.rs b/src/memory/sqlite/agent_migration.rs index a84044c81..e68cf8d58 100644 --- a/src/memory/sqlite/agent_migration.rs +++ b/src/memory/sqlite/agent_migration.rs @@ -209,6 +209,7 @@ pub(super) fn resolve_input_scope( workspace_id: &str, owner_id: Option<&str>, ) -> anyhow::Result> { + super::terminal_epoch::check(tx, workspace_id, owner_id, session_key)?; let Some(partition) = partition else { return Ok(None); }; diff --git a/src/memory/sqlite/history_retention.rs b/src/memory/sqlite/history_retention.rs new file mode 100644 index 000000000..801b06f75 --- /dev/null +++ b/src/memory/sqlite/history_retention.rs @@ -0,0 +1,57 @@ +//! Owner memory survives a plain history erase; snapshots and paging do not. +use rusqlite::{Connection, params}; +const MAX_RETAINED: usize = 20_000; + +const MEMORIES: &str = + "SELECT key FROM memories WHERE ma_scope_id IN(SELECT value FROM json_each(?1)) AND key NOT GLOB 'chat_session:*'"; +const MEMORY_IDS: &str = + "SELECT id FROM memories WHERE ma_scope_id IN(SELECT value FROM json_each(?1)) AND key NOT GLOB 'chat_session:*'"; +const DOCUMENTS: &str = "SELECT document_id FROM documents WHERE ma_scope_id IN(SELECT value FROM json_each(?1)) AND source_kind<>'context_page'"; +const TOPICS: &str = "SELECT topic_id FROM memories WHERE ma_scope_id IN(SELECT value FROM json_each(?1)) AND key NOT GLOB 'chat_session:*' UNION SELECT topic_id FROM documents WHERE ma_scope_id IN(SELECT value FROM json_each(?1)) AND source_kind<>'context_page'"; + +pub(super) fn kept(table: &str) -> String { + match table { + "memories" => "key NOT GLOB 'chat_session:*'".into(), + "documents" => "source_kind<>'context_page'".into(), + "document_chunks" => format!("document_id IN({DOCUMENTS})"), + "memory_trash" => format!("memory_key IN({MEMORIES})"), + "memory_drafts" => format!("key IN({MEMORIES})"), + "memory_links" => format!("memory_key IN({MEMORIES}) OR document_id IN({DOCUMENTS})"), + "memory_events" => format!( + "(subject_table='memories' AND (subject_id IN({MEMORIES}) OR subject_id IN({MEMORY_IDS}))) OR (subject_table='documents' AND subject_id IN({DOCUMENTS}))" + ), + "topics" => format!("id IN({TOPICS})"), + "topic_participants" => format!("topic_id IN({TOPICS})"), + "topic_aliases" => format!("from_topic_id IN({TOPICS}) OR to_topic_id IN({TOPICS})"), + // Derived vectors and the content-free attribution log remain owned by + // the retained memories. Deleting snapshots/pages evicts their vectors. + "embedding_cache" => format!("EXISTS({MEMORIES}) OR EXISTS({DOCUMENTS})"), + "memory_write_log" => "1".into(), + _ => "0".into(), + } +} + +pub(super) fn list(conn: &Connection, scopes: &str) -> anyhow::Result { + let mut memories = conn.prepare(&format!( + "SELECT id,key FROM memories WHERE ma_scope_id IN(SELECT value FROM json_each(?1)) AND ({}) ORDER BY id LIMIT 20001", + kept("memories") + ))?; + let memories = memories + .query_map(params![scopes], |row| { + Ok(serde_json::json!({"id":row.get::<_,String>(0)?,"key":row.get::<_,String>(1)?})) + })? + .collect::>>()?; + anyhow::ensure!( + memories.len() <= MAX_RETAINED, + crate::memory::RfForgetRefused::FamilyTooLarge + ); + let mut documents = conn.prepare(&format!("SELECT document_id FROM documents WHERE ma_scope_id IN(SELECT value FROM json_each(?1)) AND ({}) ORDER BY document_id LIMIT 20001", kept("documents")))?; + let documents = documents + .query_map(params![scopes], |row| row.get::<_, String>(0))? + .collect::>>()?; + anyhow::ensure!( + documents.len() <= MAX_RETAINED, + crate::memory::RfForgetRefused::FamilyTooLarge + ); + Ok(serde_json::json!({"memories":memories,"documents":documents})) +} diff --git a/src/memory/sqlite/mailbox/local_runtime.rs b/src/memory/sqlite/mailbox/local_runtime.rs index b00c6ec77..b4cf4551d 100644 --- a/src/memory/sqlite/mailbox/local_runtime.rs +++ b/src/memory/sqlite/mailbox/local_runtime.rs @@ -6,6 +6,17 @@ use crate::messaging::{CausalChain, SessionAddr}; use rusqlite::{OptionalExtension, Transaction, TransactionBehavior, params}; impl SqliteMailbox { + pub(crate) fn pin_terminal_epoch(&self, workspace: &str, owner: &str, session: &str) -> anyhow::Result<()> { + super::super::terminal_epoch::pin( + &self.memory, + &crate::memory::AgentPartition { + workspace_id: workspace.to_owned(), + owner_id: owner.to_owned(), + key: crate::memory::PartitionKey::Main, + }, + session, + ) + } /// Recheck a sealed process launch against the still-live adopted input. pub(crate) fn validate_adopted_input( &self, diff --git a/src/memory/sqlite/mod.rs b/src/memory/sqlite/mod.rs index 0801f7a7e..49c1e14ce 100644 --- a/src/memory/sqlite/mod.rs +++ b/src/memory/sqlite/mod.rs @@ -47,10 +47,12 @@ pub(crate) use recovery_outbox::{ #[cfg(test)] pub(crate) use recovery_terminal::crash_before_commit; pub(crate) use recovery_terminal::map_after_prefix; +mod history_retention; mod router_history; mod router_learning; mod rows; mod schema; +pub(crate) mod terminal_epoch; use super::embeddings::EmbeddingProvider; use super::principal::{ChatType, MemoryWriteContext, Principal, Role, Visibility, resolve_principal}; diff --git a/src/memory/sqlite/recall.rs b/src/memory/sqlite/recall.rs index 1bb69395f..0a744ee5e 100644 --- a/src/memory/sqlite/recall.rs +++ b/src/memory/sqlite/recall.rs @@ -1,2100 +1,3 @@ -//! Store, recall, forget, FTS5/vector search, owner guards and reindex. - -use super::vector; -use crate::memory::filter::{MemorySafetyFilter, SourceMetadata, safety_rejection_message}; -use crate::memory::principal::{ChatType, MemoryWriteContext, Principal, classify_memory, log_access, post_filter}; -use crate::memory::topic::{delete_orphan_topic, resolve_topic}; -use crate::memory::traits::{ - DecisionMemoryHit, Memory, MemoryCategory, MemoryEntry, MemoryReadMode, MemoryStoreMetadata, - validate_memory_write_target, -}; -use crate::runtime::sqlite_pool::begin_immediate; -use crate::self_system::evolution::record::Actor; -use anyhow::Context; -use chrono::{Local, Utc}; -use rusqlite::{Connection, OptionalExtension, params, params_from_iter, types::Value}; -use std::fmt::Write as _; -use std::path::Path; -use uuid::Uuid; - -use super::{SQLITE_DIALECT, SqliteMemory, sqlite_owner_read_principal, sqlite_read_principal}; - -/// Default ceiling on the embedded memories `vector_search` will score, used -/// when no configuration is supplied. -/// -/// Cosine similarity cannot use an index, so the scan is bounded by insertion -/// order. Operators override this with `[memory] vector_candidate_cap`. -pub(super) const VECTOR_CANDIDATE_CAP: usize = 2_000; - -pub(super) struct PreparedEmbedding { - pub(super) bytes: Vec, - pub(super) hash: String, -} - -enum WriteOutcome { - Done, - Retry, -} - -/// Candidate count for one vector recall. -/// -/// The configured cap is authoritative — it is the number an operator tunes — -/// and is only ever raised to `limit`, because scoring fewer candidates than -/// the caller asked for results would return a short list for no reason. -/// Before 0.8.126 this was `max(limit * 50, 2000)` with no way to change it, -/// so a store larger than the cap lost recall with nothing to turn. -pub(super) const fn vector_candidate_cap(limit: usize, configured: usize) -> usize { - if limit > configured { limit } else { configured } -} - -pub(super) struct VectorCandidateQuery { - pub(super) sql: String, - pub(super) params: Vec>, - candidate_cap: usize, -} - -pub(super) fn vector_candidate_query( - provider: &str, - model: &str, - dimensions: usize, - limit: usize, - category: Option<&str>, - session_id: Option<&str>, - configured_candidate_cap: usize, -) -> VectorCandidateQuery { - let mut sql = "SELECT id, embedding FROM memories - WHERE embedding IS NOT NULL - AND embedding_provider = ?1 - AND embedding_model = ?2 - AND embedding_dimensions = ?3" - .to_string(); - let mut params: Vec> = vec![ - Box::new(provider.to_string()), - Box::new(model.to_string()), - Box::new(i64::try_from(dimensions).unwrap_or(i64::MAX)), - ]; - let mut idx = 4; - - if let Some(category) = category { - let _ = write!(sql, " AND category = ?{idx}"); - params.push(Box::new(category.to_string())); - idx += 1; - } - if let Some(session_id) = session_id { - let _ = write!(sql, " AND session_id = ?{idx}"); - params.push(Box::new(session_id.to_string())); - idx += 1; - } - let candidate_cap = vector_candidate_cap(limit, configured_candidate_cap); - let _ = write!(sql, " ORDER BY update_seq DESC, rowid DESC LIMIT ?{idx}"); - params.push(Box::new(i64::try_from(candidate_cap).unwrap_or(i64::MAX))); - - VectorCandidateQuery { - sql, - params, - candidate_cap, - } -} - -/// One process says "your memory store has outgrown the candidate cap" once. -/// -/// This is a warning, not a debug line: past this point vector recall is -/// silently incomplete — an old-but-relevant memory is never scored — and the -/// only fix is an operator raising `[memory] vector_candidate_cap`. Emitting it -/// per recall would bury the turn logs, so it is latched per process. -static VECTOR_CANDIDATE_CAP_WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - -/// `memories.ma_scope_id` qualified by the `m` alias of the FTS joins. -const MEMORY_ALIAS_SCOPE_COLUMN: &str = "m.ma_scope_id"; - -/// MA-01h: the partition conjunct on a `memories` column with bare `?` -/// markers, for statements whose scope predicate binds positionally. -fn memory_partition_conjunct(column: &str, partition: Option<&crate::memory::AgentPartition>) -> (String, Vec) { - let (sql, values) = super::events::partition_conjunct(column, partition, || "?".to_string()); - (sql, values.into_iter().map(Value::from).collect()) -} - -/// The ids among `ids` whose `memories` row lies in `partition`. -fn partition_visible_memory_ids( - conn: &Connection, - ids: &[&str], - partition: &crate::memory::AgentPartition, -) -> anyhow::Result> { - if ids.is_empty() { - return Ok(std::collections::HashSet::new()); - } - let (partition_sql, partition_values) = memory_partition_conjunct(super::events::MA_SCOPE_COLUMN, Some(partition)); - let placeholders = vec!["?"; ids.len()].join(","); - let sql = format!("SELECT id FROM memories WHERE id IN ({placeholders}){partition_sql}"); - let mut values = ids.iter().map(|id| Value::from((*id).to_string())).collect::>(); - values.extend(partition_values); - let mut stmt = conn.prepare(&sql)?; - let rows = stmt.query_map(params_from_iter(values), |row| row.get::<_, String>(0))?; - Ok(rows.collect::>()?) -} - -/// Keep only the entries whose row lies in `partition`; `None` keeps all. -fn retain_partition_entries( - conn: &Connection, - entries: Vec, - partition: Option<&crate::memory::AgentPartition>, -) -> anyhow::Result> { - let Some(partition) = partition else { - return Ok(entries); - }; - let ids = entries.iter().map(|entry| entry.id.as_str()).collect::>(); - let visible = partition_visible_memory_ids(conn, &ids, partition)?; - Ok(entries - .into_iter() - .filter(|entry| visible.contains(&entry.id)) - .collect()) -} - -impl SqliteMemory { - pub(super) fn open_rehearsal_reader(db_path: &Path, deadline: std::time::Instant) -> anyhow::Result { - anyhow::ensure!(std::time::Instant::now() < deadline, "rehearsal count deadline expired"); - // macOS may expose a trusted temporary parent through `/var` -> - // `/private/var`. Resolve the parent while refusing a symlink at the - // database leaf; a replaced regular file remains a separate threat. - let parent = db_path - .parent() - .ok_or_else(|| anyhow::anyhow!("missing decision database parent"))?; - let file_name = db_path - .file_name() - .ok_or_else(|| anyhow::anyhow!("missing decision database name"))?; - let read_path = parent.canonicalize()?.join(file_name); - anyhow::ensure!(std::time::Instant::now() < deadline, "rehearsal count deadline expired"); - let mut conn = Connection::open_with_flags( - read_path, - rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NOFOLLOW, - )?; - conn.busy_timeout(std::time::Duration::from_millis(25))?; - conn.progress_handler(1_000, Some(move || std::time::Instant::now() >= deadline))?; - Ok(conn) - } - - /// Inspect one key namespace through a byte-for-byte read-only connection. - /// This is used by migration dry-runs that must not initialize or mutate - /// the configured database. - pub async fn read_key_prefix_read_only( - workspace_dir: &Path, - prefix: &str, - ) -> anyhow::Result> { - let db_path = workspace_dir.join("memory/brain.db"); - if !db_path.exists() { - return Ok(Vec::new()); - } - let prefix = prefix.to_string(); - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { - let connection = Connection::open_with_flags(&db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY) - .with_context(|| format!("failed to open {} read-only", db_path.display()))?; - let escaped = prefix.replace('\\', "\\\\").replace('%', "\\%").replace('_', "\\_"); - let pattern = format!("{escaped}%"); - let mut statement = - connection.prepare("SELECT key, content FROM memories WHERE key LIKE ?1 ESCAPE '\\'")?; - let rows = statement.query_map([pattern], |row| { - Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) - })?; - rows.collect::, _>>().map_err(Into::into) - }) - .await? - } - - /// Delete an exact key namespace in one transaction. SQLite FTS triggers - /// remove the corresponding search rows in the same commit. - pub async fn delete_key_prefix_transactional(&self, prefix: &str) -> anyhow::Result { - let pool = self.pool.clone(); - let escaped = prefix.replace('\\', "\\\\").replace('%', "\\%").replace('_', "\\_"); - let pattern = format!("{escaped}%"); - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result { - let conn = pool.write(); - let tx = begin_immediate(&conn)?; - let affected = tx.execute("DELETE FROM memories WHERE key LIKE ?1 ESCAPE '\\'", params![pattern])?; - tx.commit()?; - Ok(affected) - }) - .await? - } - - pub(super) async fn store_internal( - &self, - key: &str, - content: &str, - category: MemoryCategory, - session_id: Option<&str>, - context: Option<&MemoryWriteContext>, - metadata: Option, - ) -> anyhow::Result<()> { - validate_memory_write_target(key, session_id)?; - // V02-R9: an owner-isolated write is confined to the caller's own keys. - // `Some(owner)` only for an isolated context; a blank owner id refuses - // here, before anything is written. - crate::memory::owner_predicate::isolated_store_owner(context)?; - self.check_memory_safety(content, context).await?; - self.write_checked(key, content, category, session_id, context, metadata) - .await - } - - /// The session-snapshot write (`Memory::store_session_snapshot` and - /// `Memory::store_session_snapshot_with_metadata`). The snapshot is the - /// owner's transcript, not recall memory, so the memory content filter - /// does not run. Target validation and the checked write stay. - pub(super) async fn store_session_snapshot_impl( - &self, - key: &str, - content: &str, - session_id: Option<&str>, - metadata: Option, - ) -> anyhow::Result<()> { - validate_memory_write_target(key, session_id)?; - self.write_checked(key, content, MemoryCategory::Conversation, session_id, None, metadata) - .await - } - - /// The write after the target and safety checks passed. - async fn write_checked( - &self, - key: &str, - content: &str, - category: MemoryCategory, - session_id: Option<&str>, - context: Option<&MemoryWriteContext>, - metadata: Option, - ) -> anyhow::Result<()> { - let isolated_owner = crate::memory::owner_predicate::isolated_store_owner(context)?; - let partition = context.and_then(|ctx| ctx.agent_partition.clone()); - let session_key = context.and_then(|ctx| ctx.session_key.clone()); - let needs_embedding = matches!(&category, MemoryCategory::Core | MemoryCategory::Custom(_)); - for attempt in 0..2_u8 { - let salt_scope = self - .salt_scope_for_write( - partition.as_ref(), - session_key.as_deref(), - context.and_then(|ctx| ctx.workspace_id.as_deref()), - context - .and_then(|ctx| ctx.owner_id.as_deref()) - .or(isolated_owner.as_deref()), - ) - .await?; - let prepared = if needs_embedding { - self.embed_without_cache(content, salt_scope.as_deref()).await? - } else { - None - }; - let embedding_bytes = prepared.as_ref().map(|item| item.bytes.clone()); - let embedding_provider = prepared.as_ref().map(|_| self.embedding_provider_name()); - let embedding_model = prepared.as_ref().map(|_| self.embedding_model_name()); - let embedding_dimensions = prepared.as_ref().map(|_| self.embedding_dimensions_i64()); - let cache_hash = prepared.as_ref().map(|item| item.hash.clone()); - - let pool = self.pool.clone(); - let key = key.to_string(); - let content = content.to_string(); - let sid = session_id.map(String::from); - let write_ctx = context.cloned(); - let mut metadata = metadata.clone().unwrap_or_default(); - if let Some(owner) = isolated_owner.as_ref() { - metadata.owner_id = Some(owner.clone()); - } - let owner_guard = crate::memory::owner_predicate::store_conflict_guard( - SQLITE_DIALECT, - "memories", - isolated_owner.is_some(), - ); - let expected_salt = salt_scope.clone(); - let cache_now = Local::now().to_rfc3339(); - let provider_name = self.embedding_provider_name(); - let model_name = self.embedding_model_name(); - let dimensions = self.embedding_dimensions_i64(); - let cache_max = i64::try_from(self.cache_max).unwrap_or(i64::MAX); - let cache_bytes = embedding_bytes.clone(); - let isolated_owner = isolated_owner.clone(); - let category = category.clone(); - let provenance = self.write_provenance.clone(); - - let outcome = crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result { - let conn = pool.write(); - let tx = begin_immediate(&conn)?; - let existed = match provenance.as_deref() { - Some(_) => super::write_log::target_exists(&tx, super::write_log::WriteTarget::Memory, &key)?, - None => false, - }; - let now = Local::now().to_rfc3339(); - let cat = Self::category_to_str(&category); - let id = Uuid::new_v4().to_string(); - let bound_scope = if let Some(ctx) = write_ctx.as_ref() { - super::agent_migration::resolve_input_scope( - &tx, - ctx.agent_partition.as_ref(), - ctx.session_key.as_deref(), - ctx.workspace_id.as_deref().unwrap_or(""), - ctx.owner_id.as_deref(), - )? - } else { - None - }; - if expected_salt.is_some() && bound_scope != expected_salt { - return Ok(WriteOutcome::Retry); - } - - let previous_topic_id: Option = tx - .query_row("SELECT topic_id FROM memories WHERE key = ?1", params![&key], |row| row.get(0)) - .optional()? - .flatten(); - - if let Some(ctx) = write_ctx { - if let Some(owner) = isolated_owner.as_deref() { - let stored_owner: Option> = tx - .query_row( - "SELECT owner_id FROM memories WHERE key = ?1", - params![&key], - |row| row.get(0), - ) - .optional()?; - if stored_owner.is_some_and(|stored| stored.as_deref() != Some(owner)) { - return Err(crate::memory::owner_predicate::OwnerScopedStoreRefusal::KeyNotAvailable { - key: key.clone(), - } - .into()); - } - } - let principal = sqlite_read_principal(&tx, &ctx); - let classified = classify_memory(&ctx, &content, &principal); - let topic_id = match resolve_topic(&tx, &content, &principal, bound_scope.as_deref()) { - Ok(topic_id) => topic_id, - Err(error) => { - tracing::warn!(error = %crate::agent::diagnostics::error_class(&error), "memory topic resolve failed"); - None - } - }; - let risk_json = serde_json::to_string(&classified.risk_signals)?; - let sender_id = if ctx.channel.is_some() && ctx.raw_sender.is_some() { - Some(principal.user_id) - } else { - None - }; - let explicit_sender_id = ctx.sender_id.or(sender_id); - let owner_id = metadata.owner_id.clone().or_else(|| explicit_sender_id.clone()); - let chat_type = ctx - .chat_type - .map(|raw| ChatType::from_str(&raw).as_str().to_string()); - let scope_guard = super::agent_migration::scope_conflict_guard("memories", !owner_guard.is_empty()); - let coalesce = super::agent_migration::scope_coalesce_set("memories"); - - let changed = tx.execute( - &format!("INSERT INTO memories ( - id, key, content, category, embedding, embedding_provider, - embedding_model, embedding_dimensions, created_at, updated_at, - session_id, workspace_id, owner_id, channel, chat_type, chat_id, - sender_id, raw_sender, topic_id, visibility, sensitivity, - risk_signals, policy_version, ma_scope_id - ) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, ?21, ?22, ?23, ?24) - ON CONFLICT(key) DO UPDATE SET - content = excluded.content, - category = excluded.category, - embedding = excluded.embedding, - embedding_provider = excluded.embedding_provider, - embedding_model = excluded.embedding_model, - embedding_dimensions = excluded.embedding_dimensions, - updated_at = excluded.updated_at, - session_id = excluded.session_id, - workspace_id = excluded.workspace_id, - owner_id = excluded.owner_id, - channel = excluded.channel, - chat_type = excluded.chat_type, - chat_id = excluded.chat_id, - sender_id = excluded.sender_id, - raw_sender = excluded.raw_sender, - topic_id = excluded.topic_id, - visibility = excluded.visibility, - sensitivity = excluded.sensitivity, - risk_signals = excluded.risk_signals, - policy_version = excluded.policy_version, - {coalesce}{owner_guard}{scope_guard}"), - params![ - id, - &key, - &content, - cat, - embedding_bytes, - embedding_provider, - embedding_model, - embedding_dimensions, - now, - now, - sid, - metadata.workspace_id.clone(), - owner_id, - ctx.channel, - chat_type, - ctx.chat_id, - explicit_sender_id, - ctx.raw_sender, - topic_id, - classified.visibility.as_str(), - classified.sensitivity.as_str(), - risk_json, - classified.policy_version, - bound_scope, - ], - )?; - if changed == 0 { - return Err(crate::memory::owner_predicate::OwnerScopedStoreRefusal::KeyNotAvailable { - key: key.clone(), - } - .into()); - } - if let Some(previous) = previous_topic_id.as_deref() - && Some(previous) != topic_id.as_deref() - { - delete_orphan_topic(&tx, previous)?; - } - } else { - let coalesce = super::agent_migration::scope_coalesce_set("memories"); - let scope_guard = super::agent_migration::scope_conflict_guard("memories", false); - let changed = tx.execute( - &format!( - "INSERT INTO memories ( - id, key, content, category, embedding, embedding_provider, - embedding_model, embedding_dimensions, created_at, updated_at, - session_id, workspace_id, owner_id, agent_id, persona_id, - source_event_id, source, channel, topic_id, ma_scope_id - ) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20) - ON CONFLICT(key) DO UPDATE SET - content = excluded.content, - category = excluded.category, - embedding = excluded.embedding, - embedding_provider = excluded.embedding_provider, - embedding_model = excluded.embedding_model, - embedding_dimensions = excluded.embedding_dimensions, - updated_at = excluded.updated_at, - session_id = excluded.session_id, - workspace_id = excluded.workspace_id, - owner_id = excluded.owner_id, - agent_id = excluded.agent_id, - persona_id = excluded.persona_id, - source_event_id = excluded.source_event_id, - source = excluded.source, - channel = excluded.channel, - topic_id = excluded.topic_id, - {coalesce}{scope_guard}" - ), - params![ - id, - &key, - &content, - cat, - embedding_bytes, - embedding_provider, - embedding_model, - embedding_dimensions, - now, - now, - sid, - metadata.workspace_id.clone(), - metadata.owner_id.clone(), - metadata.agent_id.clone(), - metadata.persona_id.clone(), - metadata.source_event_id.clone(), - metadata.source.clone(), - metadata.channel.clone(), - metadata.topic_id.clone(), - bound_scope, - ], - )?; - if changed == 0 { - return Err(crate::memory::owner_predicate::OwnerScopedStoreRefusal::KeyNotAvailable { - key: key.clone(), - } - .into()); - } - if let Some(previous) = previous_topic_id.as_deref() - && Some(previous) != metadata.topic_id.as_deref() - { - delete_orphan_topic(&tx, previous)?; - } - } - - if metadata.workspace_id.is_some() - || metadata.owner_id.is_some() - || metadata.agent_id.is_some() - || metadata.persona_id.is_some() - || metadata.source_event_id.is_some() - || metadata.source.is_some() - { - let metadata_owner_guard = if isolated_owner.is_some() { - " AND owner_id IS ?2" - } else { - "" - }; - let updated = tx.execute( - &format!( - "UPDATE memories - SET workspace_id = ?1, - owner_id = COALESCE(?2, owner_id), - agent_id = ?3, - persona_id = ?4, - source_event_id = ?5, - source = ?6, - updated_at = ?7 - WHERE key = ?8{metadata_owner_guard}" - ), - params![ - metadata.workspace_id, - metadata.owner_id, - metadata.agent_id, - metadata.persona_id, - metadata.source_event_id, - metadata.source, - Local::now().to_rfc3339(), - &key, - ], - )?; - if isolated_owner.is_some() && updated == 0 { - return Err(crate::memory::owner_predicate::OwnerScopedStoreRefusal::KeyNotAvailable { - key: key.clone(), - } - .into()); - } - } - if let (Some(hash), Some(bytes)) = (cache_hash, cache_bytes) { - Self::insert_embedding_cache( - &tx, - &hash, - &bytes, - &provider_name, - &model_name, - dimensions, - &cache_now, - bound_scope.as_deref(), - cache_max, - )?; - } - if let Some(provenance) = provenance.as_deref() { - super::write_log::record_memory_upsert(&tx, provenance, &key, existed)?; - } - tx.commit()?; - Ok(WriteOutcome::Done) - }) - .await??; - match outcome { - WriteOutcome::Done => break, - WriteOutcome::Retry if attempt == 0 => continue, - WriteOutcome::Retry => return Err(crate::memory::AgentScopeRefused.into()), - } - } - Ok(()) - } - - async fn check_memory_safety(&self, content: &str, context: Option<&MemoryWriteContext>) -> anyhow::Result<()> { - let source = SourceMetadata { - actor: Self::safety_actor_for_context(context), - historical_accuracy: None, - }; - let result = MemorySafetyFilter::default().check(content, &source).await; - if result.passed { - Ok(()) - } else { - anyhow::bail!("{}", safety_rejection_message(&result.issues)); - } - } - - const fn safety_actor_for_context(context: Option<&MemoryWriteContext>) -> Actor { - match context { - Some(ctx) if ctx.raw_sender.is_some() || ctx.sender_id.is_some() => Actor::User, - Some(_) => Actor::Agent, - None => Actor::Agent, - } - } - - /// Deterministic content hash for embedding cache. - /// Uses SHA-256 (truncated) instead of DefaultHasher, which is - /// explicitly documented as unstable across Rust versions. - pub(super) fn content_hash(text: &str) -> String { - use sha2::{Digest, Sha256}; - let hash = Sha256::digest(text.as_bytes()); - // First 16 bytes → 32 hex chars. 128-bit hash reduces collision risk - // to negligible levels (~2^-64 birthday bound vs ~2^-32 with 64-bit). - let mut hex = String::with_capacity(32); - for byte in hash.iter().take(16) { - use std::fmt::Write; - let _ = write!(hex, "{byte:02x}"); - } - hex - } - - /// SHA-256("ma:" + scope_id + NUL + text) as the partitioned cache key. - pub(super) fn scoped_content_hash(scope_id: Option<&str>, text: &str) -> String { - use sha2::{Digest, Sha256}; - let Some(scope_id) = scope_id else { - return Self::content_hash(text); - }; - let mut hasher = Sha256::new(); - hasher.update(b"ma:"); - hasher.update(scope_id.as_bytes()); - hasher.update([0u8]); - hasher.update(text.as_bytes()); - format!("{:x}", hasher.finalize()) - } - - pub(super) async fn salt_scope_for_write( - &self, - partition: Option<&crate::memory::AgentPartition>, - session_key: Option<&str>, - workspace_id: Option<&str>, - owner_id: Option<&str>, - ) -> anyhow::Result> { - let Some(partition) = partition.cloned() else { - return Ok(None); - }; - if partition.workspace_id != workspace_id.unwrap_or("") || owner_id != Some(partition.owner_id.as_str()) { - return Err(crate::memory::AgentScopeRefused.into()); - } - let session_key = session_key.map(str::to_owned); - let pool = self.pool.clone(); - crate::runtime::blocking::spawn_blocking(move || { - let conn = pool.write(); - super::agent_migration::lookup_or_mint_write_scope(&conn, &partition, session_key.as_deref()).map(Some) - }) - .await? - } - - pub(super) async fn embed_without_cache( - &self, - text: &str, - scope_id: Option<&str>, - ) -> anyhow::Result> { - if self.embedder.dimensions() == 0 { - return Ok(None); - } - let hash = Self::scoped_content_hash(scope_id, text); - let provider_name = self.embedding_provider_name(); - let model_name = self.embedding_model_name(); - let dimensions = self.embedding_dimensions_i64(); - let pool = self.pool.clone(); - let hash_c = hash.clone(); - let cached = crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result>> { - let conn = pool.write(); - Self::lookup_embedding_cache(&conn, &hash_c, &provider_name, &model_name, dimensions) - }) - .await??; - let embedding = if let Some(embedding) = cached { - embedding - } else { - self.embedder.embed_one(text).await? - }; - if embedding.len() != self.embedder.dimensions() { - anyhow::bail!( - "embedding dimension mismatch: provider={} model={} expected={} got={}", - self.embedding_provider_name(), - self.embedding_model_name(), - self.embedder.dimensions(), - embedding.len() - ); - } - Ok(Some(PreparedEmbedding { - bytes: vector::vec_to_bytes(&embedding), - hash, - })) - } - - fn lookup_embedding_cache( - conn: &Connection, - hash: &str, - provider: &str, - model: &str, - dimensions: i64, - ) -> anyhow::Result>> { - let mut stmt = conn.prepare( - "SELECT embedding FROM embedding_cache - WHERE content_hash = ?1 - AND provider = ?2 - AND model = ?3 - AND dimensions = ?4", - )?; - let blob: Option> = stmt - .query_row(params![hash, provider, model, dimensions], |row| row.get(0)) - .ok(); - let Some(bytes) = blob else { - return Ok(None); - }; - let embedding = vector::bytes_to_vec(&bytes); - if embedding.len() == usize::try_from(dimensions).unwrap_or(usize::MAX) { - Ok(Some(embedding)) - } else { - Ok(None) - } - } - - pub(super) fn insert_embedding_cache( - conn: &Connection, - hash: &str, - bytes: &[u8], - provider: &str, - model: &str, - dimensions: i64, - now: &str, - scope_id: Option<&str>, - cache_max: i64, - ) -> anyhow::Result<()> { - conn.execute( - "INSERT OR REPLACE INTO embedding_cache ( - content_hash, embedding, provider, model, dimensions, created_at, accessed_at, ma_scope_id - ) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", - params![hash, bytes, provider, model, dimensions, now, now, scope_id], - )?; - let count: i64 = conn.query_row("SELECT COUNT(*) FROM embedding_cache", [], |row| row.get(0))?; - if count > cache_max { - let to_delete = count - cache_max; - conn.execute( - "DELETE FROM embedding_cache WHERE content_hash IN ( - SELECT content_hash FROM embedding_cache - ORDER BY accessed_at ASC LIMIT ?1 - )", - params![to_delete], - )?; - } - Ok(()) - } - - pub(super) fn content_sha256_hex(text: &str) -> String { - use sha2::{Digest, Sha256}; - let hash = Sha256::digest(text.as_bytes()); - let mut hex = String::with_capacity(64); - for byte in hash { - let _ = write!(hex, "{byte:02x}"); - } - hex - } - - /// The owner id an owner-isolated delete is confined to, with blanks - /// treated as absent (the rule - /// [`crate::memory::owner_predicate::has_owner_id`] applies to reads). - /// - /// A non-isolated context never yields one, so the guard below renders - /// nothing for it and the historical statement is unchanged. - pub(super) fn forget_owner_anchor(context: &MemoryWriteContext) -> Option { - if !context.require_owner_match { - return None; - } - context - .owner_id - .as_deref() - .map(str::trim) - .filter(|owner| !owner.is_empty()) - .map(str::to_string) - } - - /// The guard appended to `forget_with_context`'s visibility scope - /// (R-B1d D-1). - /// - /// Delete-by-key was confined to the shared visibility predicate alone. - /// That predicate owner-qualifies every **non-public** arm for an isolated - /// caller, but `visibility = 'public'` stays shared by design — correct for - /// a read, wrong for a destructive operation, because it let an - /// owner-isolated caller remove a public row belonging to someone else. - /// This guard is therefore appended at the top level of the `WHERE` rather - /// than inside one arm: an owner-isolated caller deletes only rows whose - /// `owner_id` equals its authenticated owner id, whatever their visibility. - /// - /// The fragment comes from - /// [`crate::memory::owner_predicate::owner_match_suffix`] — the single - /// owner-isolation seam — so it renders the empty string for a - /// non-isolated caller (statement and bind list byte-identical), - /// `" AND FALSE"` for an isolated caller with no usable owner id (nothing - /// is deleted and the call reports that nothing was found), and - /// `" AND owner_id = ?N"` otherwise. A stored `NULL` `owner_id` compares to - /// `NULL`, so an unattributed row is not deletable by an isolated caller - /// either. `index` is the caller's next free placeholder, so the - /// one-marker-one-parameter accounting is preserved. - pub(super) fn forget_owner_guard( - context: &MemoryWriteContext, - index: usize, - ) -> crate::memory::owner_predicate::OwnerMatchPredicate { - crate::memory::owner_predicate::owner_match_suffix( - SQLITE_DIALECT, - index, - context.require_owner_match, - Self::forget_owner_anchor(context).is_some(), - ) - } - - pub(super) fn embedding_provider_name(&self) -> String { - self.embedder.name().to_string() - } - - pub(super) fn embedding_model_name(&self) -> String { - self.embedder.model().to_string() - } - - pub(super) fn embedding_dimensions_i64(&self) -> i64 { - i64::try_from(self.embedder.dimensions()).unwrap_or(i64::MAX) - } - - /// Get embedding from cache, or compute + cache it (unpartitioned hash). - pub(super) async fn get_or_compute_embedding(&self, text: &str) -> anyhow::Result>> { - self.embed_and_cache(text, None).await - } - - async fn embed_and_cache(&self, text: &str, scope_id: Option<&str>) -> anyhow::Result>> { - let Some(prepared) = self.embed_without_cache(text, scope_id).await? else { - return Ok(None); - }; - let embedding = vector::bytes_to_vec(&prepared.bytes); - let pool = self.pool.clone(); - let now = Local::now().to_rfc3339(); - let provider_name = self.embedding_provider_name(); - let model_name = self.embedding_model_name(); - let dimensions = self.embedding_dimensions_i64(); - let cache_max = i64::try_from(self.cache_max).unwrap_or(i64::MAX); - let scope = scope_id.map(str::to_owned); - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result<()> { - let conn = pool.write(); - Self::insert_embedding_cache( - &conn, - &prepared.hash, - &prepared.bytes, - &provider_name, - &model_name, - dimensions, - &now, - scope.as_deref(), - cache_max, - ) - }) - .await??; - Ok(Some(embedding)) - } - - /// FTS5 BM25 keyword search - fn fts5_search(conn: &Connection, query: &str, limit: usize) -> anyhow::Result> { - // Escape FTS5 special chars and build query - let fts_query: String = crate::memory::topic::build_safe_fts_query(query); - - if fts_query.is_empty() { - return Ok(Vec::new()); - } - - let sql = "SELECT m.id, bm25(memories_fts) as score - FROM memories_fts f - JOIN memories m ON m.rowid = f.rowid - WHERE memories_fts MATCH ?1 - ORDER BY score - LIMIT ?2"; - - let mut stmt = conn.prepare(sql)?; - #[allow(clippy::cast_possible_wrap)] - let limit_i64 = limit as i64; - - let rows = stmt.query_map(params![fts_query, limit_i64], |row| { - let id: String = row.get(0)?; - let score: f64 = row.get(1)?; - // BM25 returns negative scores (lower = better), negate for ranking - #[allow(clippy::cast_possible_truncation)] - Ok((id, (-score) as f32)) - })?; - - let mut results = Vec::new(); - for row in rows { - results.push(row?); - } - Ok(results) - } - - /// Vector similarity search: scan embeddings and compute cosine similarity. - /// - /// Optional `category` and `session_id` filters reduce full-table scans - /// when the caller already knows the scope of relevant memories. - /// - /// Cosine similarity has no index, so the candidate set is bounded before - /// scoring: without a bound this is O(N) over every embedded memory on a - /// path that runs once per turn. - /// - /// The bound orders by `update_seq`, not by `updated_at` and not by - /// `rowid`. - /// - /// `updated_at` is `Local::now().to_rfc3339()` — an RFC 3339 string carrying - /// the writer's UTC offset — and it is ordered lexicographically by SQLite. - /// Within one fixed offset that happens to match chronological order, but a - /// DST transition, a machine timezone change, or a store shared between - /// processes in different zones reorders whole blocks of rows, and any row - /// historically written with `Utc::now()` sorts in a third order again. The - /// rows dropped by `LIMIT` would then be the wrong ones. - /// - /// `rowid` cannot be reordered by a clock, but it does not move either: - /// every writer here upserts with `ON CONFLICT(key) DO UPDATE`, which - /// rewrites the content and the embedding of an existing key in place. A - /// long-lived key refreshed a second ago therefore kept its original - /// position, and in a store larger than the cap it stayed outside the - /// window — the memory whose embedding was *just* made relevant was the one - /// that could not be scored. - /// - /// `update_seq` is a per-store counter bumped by a trigger on every insert - /// and every update (see `init_schema`). It is an integer, so it has no - /// timezone, no offset and no DST; it is monotonic, so it cannot be - /// reordered by a clock; and it follows the row when the row is refreshed. - /// "Newest" here therefore means most recently *written*, created or - /// refreshed. `rowid` breaks ties so the window is deterministic on a store - /// whose sequence was backfilled by the migration. - /// - /// `candidate_cap` is the configured `[memory] vector_candidate_cap`. Hitting it is - /// a real recall regression — an old-but-relevant memory is never scored — - /// so it is reported once per process at `warn`, not at `debug`. - pub(super) fn vector_search( - conn: &Connection, - query_embedding: &[f32], - provider: &str, - model: &str, - dimensions: usize, - limit: usize, - category: Option<&str>, - session_id: Option<&str>, - candidate_cap: usize, - ) -> anyhow::Result> { - let VectorCandidateQuery { - sql, - params, - candidate_cap, - } = vector_candidate_query(provider, model, dimensions, limit, category, session_id, candidate_cap); - - let mut stmt = conn.prepare(&sql)?; - let params_ref: Vec<&dyn rusqlite::types::ToSql> = params.iter().map(AsRef::as_ref).collect(); - let rows = stmt.query_map(params_ref.as_slice(), |row| { - let id: String = row.get(0)?; - let blob: Vec = row.get(1)?; - Ok((id, blob)) - })?; - - let mut scored: Vec<(String, f32)> = Vec::new(); - let mut candidates = 0usize; - for row in rows { - let (id, blob) = row?; - candidates += 1; - let emb = vector::bytes_to_vec(&blob); - if emb.len() != dimensions { - tracing::debug!( - memory_id = %crate::agent::diagnostics::text_class(&id), - expected_dimensions = dimensions, - actual_dimensions = emb.len(), - "Skipping stale memory embedding with mismatched dimensions" - ); - continue; - } - let sim = vector::cosine_similarity(query_embedding, &emb); - if sim > 0.0 { - scored.push((id, sim)); - } - } - - if candidates >= candidate_cap && !VECTOR_CANDIDATE_CAP_WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) - { - tracing::warn!( - candidate_cap, - limit, - "Vector recall hit its candidate cap: older embedded memories are no longer scored and \ - cannot be recalled. Raise [memory] vector_candidate_cap to score more of the store." - ); - } - - scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal)); - scored.truncate(limit); - Ok(scored) - } - - /// Safe reindex: rebuild FTS5 + embeddings with rollback on failure - pub async fn reindex(&self) -> anyhow::Result { - // Step 1: Rebuild FTS5 - { - let pool = self.pool.clone(); - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result<()> { - let conn = pool.write(); - conn.execute_batch( - "INSERT INTO memories_fts(memories_fts) VALUES('rebuild'); - INSERT INTO document_chunks_fts(document_chunks_fts) VALUES('rebuild');", - )?; - Ok(()) - }) - .await??; - } - - // Step 2: Re-embed eligible memories that lack embeddings - if self.embedder.dimensions() == 0 { - return Ok(0); - } - - let provider_name = self.embedding_provider_name(); - let model_name = self.embedding_model_name(); - let dimensions = self.embedding_dimensions_i64(); - let pool = self.pool.clone(); - let entries: Vec<(String, String, Option)> = crate::runtime::blocking::spawn_blocking(move || { - let reader = pool.read()?; - let conn = reader.connection()?; - let mut stmt = conn.prepare( - "SELECT id, content, ma_scope_id - FROM memories - WHERE category NOT IN ('daily', 'conversation') - AND ( - embedding IS NULL - OR embedding_provider IS NULL - OR embedding_model IS NULL - OR embedding_dimensions IS NULL - OR embedding_provider != ?1 - OR embedding_model != ?2 - OR embedding_dimensions != ?3 - )", - )?; - let rows = stmt.query_map(params![provider_name, model_name, dimensions], |row| { - Ok(( - row.get::<_, String>(0)?, - row.get::<_, String>(1)?, - row.get::<_, Option>(2)?, - )) - })?; - Ok::<_, anyhow::Error>(rows.filter_map(std::result::Result::ok).collect()) - }) - .await??; - - let mut count = 0; - for (id, content, scope) in &entries { - if let Ok(Some(emb)) = self.embed_and_cache(content, scope.as_deref()).await { - let bytes = vector::vec_to_bytes(&emb); - let pool = self.pool.clone(); - let id = id.clone(); - let provider_name = self.embedding_provider_name(); - let model_name = self.embedding_model_name(); - let dimensions = self.embedding_dimensions_i64(); - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result<()> { - let conn = pool.write(); - conn.execute( - "UPDATE memories - SET embedding = ?1, - embedding_provider = ?2, - embedding_model = ?3, - embedding_dimensions = ?4 - WHERE id = ?5", - params![bytes, provider_name, model_name, dimensions, id], - )?; - Ok(()) - }) - .await??; - count += 1; - } - } - - let provider_name = self.embedding_provider_name(); - let model_name = self.embedding_model_name(); - let dimensions = self.embedding_dimensions_i64(); - let pool = self.pool.clone(); - let chunks: Vec<(String, String, Option)> = crate::runtime::blocking::spawn_blocking(move || { - let reader = pool.read()?; - let conn = reader.connection()?; - let mut stmt = conn.prepare( - "SELECT chunk_id, content, ma_scope_id - FROM document_chunks - WHERE embedding IS NULL - OR embedding_provider IS NULL - OR embedding_model IS NULL - OR embedding_dimensions IS NULL - OR embedding_provider != ?1 - OR embedding_model != ?2 - OR embedding_dimensions != ?3", - )?; - let rows = stmt.query_map(params![provider_name, model_name, dimensions], |row| { - Ok(( - row.get::<_, String>(0)?, - row.get::<_, String>(1)?, - row.get::<_, Option>(2)?, - )) - })?; - Ok::<_, anyhow::Error>(rows.filter_map(std::result::Result::ok).collect()) - }) - .await??; - - for (chunk_id, content, scope) in &chunks { - if let Ok(Some(emb)) = self.embed_and_cache(content, scope.as_deref()).await { - let bytes = vector::vec_to_bytes(&emb); - let pool = self.pool.clone(); - let chunk_id = chunk_id.clone(); - let provider_name = self.embedding_provider_name(); - let model_name = self.embedding_model_name(); - let dimensions = self.embedding_dimensions_i64(); - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result<()> { - let conn = pool.write(); - conn.execute( - "UPDATE document_chunks - SET embedding = ?1, - embedding_provider = ?2, - embedding_model = ?3, - embedding_dimensions = ?4 - WHERE chunk_id = ?5", - params![bytes, provider_name, model_name, dimensions, chunk_id], - )?; - Ok(()) - }) - .await??; - count += 1; - } - } - - Ok(count) - } - - pub(super) async fn mirror_operator_write_impl( - &self, - key: &str, - content: &str, - category: &MemoryCategory, - ) -> anyhow::Result<()> { - // With the memory ACL on the Markdown mirror is off altogether, as it - // always was. - if self.acl_enabled { - return Ok(()); - } - let db_path = self.db_path.clone(); - let key = key.to_string(); - let content = content.to_string(); - let category = category.clone(); - crate::runtime::blocking::spawn_blocking(move || { - Self::append_backup_entry(&db_path, &key, &content, &category); - }) - .await?; - Ok(()) - } - - /// Keep only the entries whose row lies in `partition` (MA-01h); `None` - /// keeps all. - async fn retain_in_partition( - &self, - entries: Vec, - partition: Option, - ) -> anyhow::Result> { - if partition.is_none() || entries.is_empty() { - return Ok(entries); - } - let pool = self.pool.clone(); - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { - let reader = pool.read()?; - let conn = reader.connection()?; - retain_partition_entries(&conn, entries, partition.as_ref()) - }) - .await? - } - - pub(super) async fn recall_impl( - &self, - query: &str, - limit: usize, - session_id: Option<&str>, - ) -> anyhow::Result> { - if query.trim().is_empty() { - return Ok(Vec::new()); - } - - // Compute query embedding (async, before blocking work) - let query_embedding = self.get_or_compute_embedding(query).await?; - - let pool = self.pool.clone(); - let query = query.to_string(); - let sid = session_id.map(String::from); - let vector_weight = self.vector_weight; - let keyword_weight = self.keyword_weight; - let embedding_provider = self.embedding_provider_name(); - let embedding_model = self.embedding_model_name(); - let embedding_dimensions = self.embedder.dimensions(); - let vector_candidate_cap = self.vector_candidate_cap; - - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { - let reader = pool.read()?; - let conn = reader.connection()?; - let session_ref = sid.as_deref(); - - // FTS5 BM25 keyword search - let keyword_results = match Self::fts5_search(&conn, &query, limit * 2) { - Ok(results) => results, - Err(e) => { - tracing::warn!(error = %crate::agent::diagnostics::error_class(&e), "FTS5 search failed (returning empty)"); - Vec::new() - } - }; - - // Vector similarity search (if embeddings available) - let vector_results = query_embedding.as_ref().map_or_else(Vec::new, |qe| { - match Self::vector_search( - &conn, - qe, - &embedding_provider, - &embedding_model, - embedding_dimensions, - limit * 2, - None, - session_ref, - vector_candidate_cap, - ) { - Ok(results) => results, - Err(e) => { - tracing::warn!(error = %crate::agent::diagnostics::error_class(&e), "Vector search failed (returning empty)"); - Vec::new() - } - } - }); - - // Hybrid merge - let merged = if vector_results.is_empty() { - keyword_results - .iter() - .map(|(id, score)| vector::ScoredResult { - id: id.clone(), - vector_score: None, - keyword_score: Some(*score), - final_score: *score, - }) - .collect::>() - } else { - vector::hybrid_merge(&vector_results, &keyword_results, vector_weight, keyword_weight, limit) - }; - - // Fetch full entries for merged results in a single query - // instead of N round-trips (N+1 pattern). - let mut results = Vec::new(); - if !merged.is_empty() { - let placeholders: String = (1..=merged.len()) - .map(|i| format!("?{i}")) - .collect::>() - .join(", "); - let sql = format!( - "SELECT id, key, content, category, created_at, session_id, useful_count \ - FROM memories WHERE id IN ({placeholders})" - ); - let mut stmt = conn.prepare(&sql)?; - let id_params: Vec> = merged - .iter() - .map(|s| Box::new(s.id.clone()) as Box) - .collect(); - let params_ref: Vec<&dyn rusqlite::types::ToSql> = id_params.iter().map(AsRef::as_ref).collect(); - let rows = stmt.query_map(params_ref.as_slice(), |row| { - Ok(( - row.get::<_, String>(0)?, - row.get::<_, String>(1)?, - row.get::<_, String>(2)?, - row.get::<_, String>(3)?, - row.get::<_, String>(4)?, - row.get::<_, Option>(5)?, - row.get::<_, Option>(6)?, - )) - })?; - - let mut entry_map = std::collections::HashMap::new(); - for row in rows { - let (id, key, content, cat, ts, sid, useful_count) = row?; - entry_map.insert(id, (key, content, cat, ts, sid, useful_count)); - } - - for scored in &merged { - if let Some((key, content, cat, ts, sid, useful_count)) = entry_map.remove(&scored.id) { - let entry = MemoryEntry { - origin: crate::memory::traits::MemoryEntryOrigin::Stored, - source_event_id: None, - id: scored.id.clone(), - key, - content, - category: Self::str_to_category(&cat), - timestamp: ts, - session_id: sid, - score: Some(f64::from(scored.final_score)), - tags: None, - access_count: None, - useful_count, - source: None, - source_confidence: None, - verification_status: None, - lifecycle_state: None, - compressed_from: None, - }; - if let Some(filter_sid) = session_ref { - if entry.session_id.as_deref() != Some(filter_sid) { - continue; - } - } - results.push(entry); - } - } - } - - // If hybrid returned nothing, fall back to LIKE search. - // Cap keyword count so we don't create too many SQL shapes, - // which helps prepared-statement cache efficiency. - if results.is_empty() { - const MAX_LIKE_KEYWORDS: usize = 8; - let keywords: Vec = query - .split_whitespace() - .take(MAX_LIKE_KEYWORDS) - .map(|w| format!("%{w}%")) - .collect(); - if !keywords.is_empty() { - let conditions: Vec = keywords - .iter() - .enumerate() - .map(|(i, _)| format!("(content LIKE ?{} OR key LIKE ?{})", i * 2 + 1, i * 2 + 2)) - .collect(); - let where_clause = conditions.join(" OR "); - let sql = format!( - "SELECT id, key, content, category, created_at, session_id, useful_count FROM memories - WHERE {where_clause} - ORDER BY updated_at DESC - LIMIT ?{}", - keywords.len() * 2 + 1 - ); - let mut stmt = conn.prepare(&sql)?; - let mut param_values: Vec> = Vec::new(); - for kw in &keywords { - param_values.push(Box::new(kw.clone())); - param_values.push(Box::new(kw.clone())); - } - #[allow(clippy::cast_possible_wrap)] - param_values.push(Box::new(limit as i64)); - let params_ref: Vec<&dyn rusqlite::types::ToSql> = param_values.iter().map(AsRef::as_ref).collect(); - let rows = stmt.query_map(params_ref.as_slice(), |row| { - Ok(MemoryEntry { - origin: crate::memory::traits::MemoryEntryOrigin::Stored, - source_event_id: None, - id: row.get(0)?, - key: row.get(1)?, - content: row.get(2)?, - category: Self::str_to_category(&row.get::<_, String>(3)?), - timestamp: row.get(4)?, - session_id: row.get(5)?, - score: Some(1.0), - tags: None, - access_count: None, - useful_count: row.get(6)?, - source: None, - source_confidence: None, - verification_status: None, - lifecycle_state: None, - compressed_from: None, - }) - })?; - for row in rows { - let entry = row?; - if let Some(sid) = session_ref { - if entry.session_id.as_deref() != Some(sid) { - continue; - } - } - results.push(entry); - } - } - } - - results.truncate(limit); - Ok(results) - }) - .await? - } - - pub(super) async fn recall_with_context_impl( - &self, - query: &str, - limit: usize, - session_id: Option<&str>, - context: Option<&MemoryWriteContext>, - ) -> anyhow::Result> { - let Some(context) = context.cloned() else { - return self.recall(query, limit, session_id).await; - }; - - let mut entries = self - .recall(query, limit.saturating_mul(3).max(limit), session_id) - .await?; - if entries.is_empty() { - return Ok(entries); - } - - let pool = self.pool.clone(); - let capped_limit = limit; - - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { - let reader = pool.read()?; - let conn = reader.connection()?; - let principal = sqlite_read_principal(&conn, &context); - // FIX-P1-06: the Anonymous `(channel, chat_id, raw_sender)` triple is - // now produced by `build_sql_scope` itself, so all roles share the - // single scope builder (no hardcoded branch). - let (scope_sql, scope_params) = principal.build_sql_scope(); - - let mut allowed_ids = std::collections::HashSet::new(); - if !entries.is_empty() { - let id_placeholders = (0..entries.len()).map(|_| "?").collect::>().join(","); - let (partition_sql, partition_params) = - memory_partition_conjunct(super::events::MA_SCOPE_COLUMN, context.agent_partition.as_ref()); - let sql = format!( - "SELECT id, source_event_id FROM memories WHERE id IN ({id_placeholders}) AND ({scope_sql}){partition_sql}" - ); - let mut params = entries - .iter() - .map(|entry| Value::from(entry.id.clone())) - .collect::>(); - params.extend(scope_params); - params.extend(partition_params); - let mut stmt = conn.prepare(&sql)?; - let rows = stmt.query_map(params_from_iter(params), |row| { - Ok((row.get::<_, String>(0)?, row.get::<_, Option>(1)?)) - })?; - for row in rows { - let (id, event) = row?; - for entry in &mut entries { - if entry.id == id { - entry.source_event_id = event.clone(); - } - } - allowed_ids.insert(id); - } - } - - let visible = entries - .into_iter() - .filter(|entry| allowed_ids.contains(&entry.id)) - .collect::>(); - let mut visible = post_filter(visible, &principal, |entry| entry.content.as_str()); - visible.truncate(capped_limit); - Ok(visible) - }) - .await? - } - - pub(super) async fn count_rehearsal_hits_impl( - &self, - query: &str, - limit: u8, - context: &MemoryWriteContext, - deadline: std::time::Instant, - ) -> anyhow::Result { - anyhow::ensure!( - query.len() <= 1_024 && (1..=16).contains(&limit), - "invalid rehearsal count bounds" - ); - anyhow::ensure!(std::time::Instant::now() < deadline, "rehearsal count deadline expired"); - let fts_query = crate::memory::topic::build_safe_fts_query(query); - if fts_query.is_empty() { - return Ok(0); - } - let db_path = self.db_path.clone(); - let context = context.clone(); - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result { - anyhow::ensure!(std::time::Instant::now() < deadline, "rehearsal count deadline expired"); - // A dedicated read-only connection cannot wait for a pooled reader - // after the decision deadline. SQLite itself interrupts slow FTS. - let conn = Self::open_rehearsal_reader(&db_path, deadline)?; - let principal = sqlite_read_principal(&conn, &context); - anyhow::ensure!(std::time::Instant::now() < deadline, "rehearsal count deadline expired"); - let (scope_sql, scope_params) = principal.build_sql_scope(); - let (partition_sql, partition_params) = - memory_partition_conjunct(MEMORY_ALIAS_SCOPE_COLUMN, context.agent_partition.as_ref()); - let sql = format!( - "SELECT m.content FROM memories_fts f JOIN memories m ON m.rowid = f.rowid \ - WHERE memories_fts MATCH ? AND ({scope_sql}){partition_sql} \ - AND length(CAST(m.content AS BLOB)) <= 4096 \ - ORDER BY bm25(memories_fts) LIMIT ?" - ); - let mut params = Vec::with_capacity(scope_params.len() + partition_params.len() + 2); - params.push(Value::from(fts_query)); - params.extend(scope_params); - params.extend(partition_params); - params.push(Value::from(i64::from(limit) * 3)); - let mut stmt = conn.prepare(&sql)?; - let rows = stmt.query_map(params_from_iter(params), |row| row.get::<_, String>(0))?; - let candidates = rows.collect::>>()?; - anyhow::ensure!(std::time::Instant::now() < deadline, "rehearsal count deadline expired"); - let visible = post_filter(candidates, &principal, String::as_str); - anyhow::ensure!(std::time::Instant::now() < deadline, "rehearsal count deadline expired"); - Ok(u32::try_from(visible.len().min(usize::from(limit)))?) - }) - .await? - } - - pub(super) async fn retrieve_decision_memory_impl( - &self, - query: &str, - limit: u8, - context: &MemoryWriteContext, - session_id: Option<&str>, - deadline: std::time::Instant, - ) -> anyhow::Result> { - anyhow::ensure!( - query.len() <= 1_024 && (1..=5).contains(&limit), - "invalid decision Memory bounds" - ); - anyhow::ensure!(std::time::Instant::now() < deadline, "decision Memory deadline expired"); - anyhow::ensure!( - session_id.is_none_or(|id| !id.is_empty() && id.len() <= 512), - "invalid decision Memory session" - ); - let fts_query = crate::memory::topic::build_safe_fts_query(query); - if fts_query.is_empty() { - return Ok(Vec::new()); - } - let session_id = session_id.map(str::to_owned); - let db_path = self.db_path.clone(); - let context = context.clone(); - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { - anyhow::ensure!(std::time::Instant::now() < deadline, "decision Memory deadline expired"); - let conn = Self::open_rehearsal_reader(&db_path, deadline)?; - let principal = sqlite_read_principal(&conn, &context); - let (scope_sql, scope_params) = principal.build_sql_scope(); - let (partition_sql, partition_params) = - memory_partition_conjunct(MEMORY_ALIAS_SCOPE_COLUMN, context.agent_partition.as_ref()); - let sql = format!( - "SELECT m.id, m.content, m.created_at, m.source_event_id, m.key, m.category, m.session_id FROM memories_fts f JOIN memories m ON m.rowid = f.rowid \ - WHERE memories_fts MATCH ? AND ({scope_sql}){partition_sql} \ - AND length(CAST(m.id AS BLOB)) <= 128 \ - AND length(CAST(m.content AS BLOB)) <= 4096 \ - AND length(CAST(m.created_at AS BLOB)) <= 64 \ - AND (m.source_event_id IS NULL OR length(CAST(m.source_event_id AS BLOB)) <= 128) \ - AND length(CAST(m.key AS BLOB)) <= 1024 AND length(CAST(m.category AS BLOB)) <= 128 \ - AND (m.session_id IS NULL OR length(CAST(m.session_id AS BLOB)) <= 512) \ - AND (? IS NULL OR m.session_id = ?) \ - ORDER BY bm25(memories_fts) LIMIT ?" - ); - let mut params = Vec::with_capacity(scope_params.len() + partition_params.len() + 4); - params.push(Value::from(fts_query)); - params.extend(scope_params); - params.extend(partition_params); - params.push(session_id.clone().map(Value::from).unwrap_or(Value::Null)); - params.push(session_id.map(Value::from).unwrap_or(Value::Null)); - params.push(Value::from(i64::from(limit) * 3)); - let mut stmt = conn.prepare(&sql)?; - let rows = stmt.query_map(params_from_iter(params), |row| { - Ok(DecisionMemoryHit { - id: row.get(0)?, - content: row.get(1)?, - created_at: row.get(2)?, - source_event_id: row.get(3)?, - key: row.get(4)?, category: Self::str_to_category(&row.get::<_, String>(5)?), - session_id: row.get(6)?, - }) - })?; - let candidates = rows.collect::>>()?; - anyhow::ensure!(std::time::Instant::now() < deadline, "decision Memory deadline expired"); - let mut visible = post_filter(candidates, &principal, |hit| hit.content.as_str()); - visible.truncate(usize::from(limit)); - anyhow::ensure!(std::time::Instant::now() < deadline, "decision Memory deadline expired"); - Ok(visible) - }) - .await? - } - - pub(super) async fn recall_with_context_mode_impl( - &self, - query: &str, - limit: usize, - session_id: Option<&str>, - context: Option<&MemoryWriteContext>, - mode: MemoryReadMode, - ) -> anyhow::Result> { - let context = context.cloned().unwrap_or_default(); - // C03 / V02-R5 defence in depth: an owner-isolated context is enforced - // whatever mode was requested. The tool already selects Enforce for an - // isolated caller; the backend must not be talked out of it by a - // caller, a config flag or a future call site. - let mode = if context.require_owner_match { - MemoryReadMode::Enforce - } else { - mode - }; - // MA-01h: the partition is not an ACL tier; Observe mode never reads - // past it. - let unrestricted = self.recall(query, limit, session_id).await?; - let unrestricted = self - .retain_in_partition(unrestricted, context.agent_partition.clone()) - .await?; - let scoped = self - .recall_with_context(query, limit, session_id, Some(&context)) - .await?; - let pool = self.pool.clone(); - let query_owned = query.to_string(); - let query_for_topics = query_owned.clone(); - let mut selected = match mode { - MemoryReadMode::Enforce => scoped.clone(), - MemoryReadMode::Observe => unrestricted.clone(), - }; - let mut selected_ids = selected - .iter() - .map(|entry| entry.id.clone()) - .collect::>(); - let topic_rows = - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result<(Vec, Principal)> { - let reader = pool.read()?; - let conn = reader.connection()?; - let principal = sqlite_read_principal(&conn, &context); - let topic_principal = match mode { - MemoryReadMode::Enforce => principal.clone(), - MemoryReadMode::Observe => sqlite_owner_read_principal(), - }; - let mut rows = Vec::new(); - for topic in crate::memory::topic::search_topics_fts(&conn, &query_for_topics, 3)? { - for entry in - crate::memory::topic::query_topic_context(&conn, &topic.id, &topic_principal, limit.max(1))? - { - rows.push(MemoryEntry { - origin: crate::memory::traits::MemoryEntryOrigin::Stored, - source_event_id: None, - id: entry.id, - key: entry.key, - content: entry.content, - category: MemoryCategory::Conversation, - timestamp: entry.created_at, - session_id: None, - score: Some(0.55), - tags: None, - access_count: None, - useful_count: None, - source: Some("topic_projection".to_string()), - source_confidence: None, - verification_status: None, - lifecycle_state: None, - compressed_from: None, - }); - } - } - let rows = retain_partition_entries(&conn, rows, context.agent_partition.as_ref())?; - Ok((rows, principal)) - }) - .await??; - for entry in topic_rows.0 { - if selected_ids.insert(entry.id.clone()) { - selected.push(entry); - } - } - selected.sort_by(|left, right| { - right - .score - .unwrap_or(0.0) - .partial_cmp(&left.score.unwrap_or(0.0)) - .unwrap_or(std::cmp::Ordering::Equal) - .then_with(|| left.key.cmp(&right.key)) - }); - selected.truncate(limit.max(1)); - - let would_deny = unrestricted - .iter() - .any(|entry| !scoped.iter().any(|allowed| allowed.id == entry.id)); - let pool = self.pool.clone(); - let principal = topic_rows.1; - let selected_empty = selected.is_empty(); - crate::runtime::blocking::spawn_blocking(move || { - let conn = pool.write(); - log_access( - &conn, - &principal, - "search", - Some(&query_owned), - None, - Some(match mode { - MemoryReadMode::Enforce => "acl_enforced", - MemoryReadMode::Observe => "observe_mode", - }), - if mode == MemoryReadMode::Observe && would_deny { - "would_deny" - } else if selected_empty { - "no_results" - } else { - "allowed" - }, - ); - }) - .await?; - Ok(selected) - } - - pub(super) async fn get_impl(&self, key: &str) -> anyhow::Result> { - let pool = self.pool.clone(); - let key = key.to_string(); - - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { - let reader = pool.read()?; - let conn = reader.connection()?; - let mut stmt = conn.prepare( - "SELECT id, key, content, category, created_at, session_id, useful_count FROM memories WHERE key = ?1", - )?; - - let mut rows = stmt.query_map(params![key], |row| { - Ok(MemoryEntry { - origin: crate::memory::traits::MemoryEntryOrigin::Stored, - source_event_id: None, - id: row.get(0)?, - key: row.get(1)?, - content: row.get(2)?, - category: Self::str_to_category(&row.get::<_, String>(3)?), - timestamp: row.get(4)?, - session_id: row.get(5)?, - score: None, - tags: None, - access_count: None, - useful_count: row.get(6)?, - source: None, - source_confidence: None, - verification_status: None, - lifecycle_state: None, - compressed_from: None, - }) - })?; - - match rows.next() { - Some(Ok(entry)) => Ok(Some(entry)), - _ => Ok(None), - } - }) - .await? - } - - pub(super) async fn get_with_context_impl( - &self, - key: &str, - context: Option<&MemoryWriteContext>, - ) -> anyhow::Result> { - let context = context.cloned().unwrap_or_default(); - let pool = self.pool.clone(); - let key = key.to_string(); - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { - let reader = pool.read()?; - let conn = reader.connection()?; - let principal = sqlite_read_principal(&conn, &context); - let (scope_sql, scope_params) = principal.build_sql_scope(); - let (partition_sql, partition_params) = - memory_partition_conjunct(super::events::MA_SCOPE_COLUMN, context.agent_partition.as_ref()); - let mut query_params = Vec::with_capacity(scope_params.len() + partition_params.len() + 1); - query_params.push(Value::from(key.clone())); - query_params.extend(scope_params); - query_params.extend(partition_params); - let sql = format!( - "SELECT id, key, content, category, created_at, session_id, useful_count - FROM memories WHERE key = ?1 AND ({scope_sql}){partition_sql} LIMIT 1" - ); - let entry = conn - .query_row(&sql, params_from_iter(query_params), |row| { - Ok(MemoryEntry { - origin: crate::memory::traits::MemoryEntryOrigin::Stored, - source_event_id: None, - id: row.get(0)?, - key: row.get(1)?, - content: row.get(2)?, - category: Self::str_to_category(&row.get::<_, String>(3)?), - timestamp: row.get(4)?, - session_id: row.get(5)?, - score: None, - tags: None, - access_count: None, - useful_count: row.get(6)?, - source: None, - source_confidence: None, - verification_status: None, - lifecycle_state: None, - compressed_from: None, - }) - }) - .optional()?; - let mut visible = post_filter(entry.into_iter().collect(), &principal, |entry| entry.content.as_str()); - Ok(visible.pop()) - }) - .await? - } - - pub(super) async fn get_with_context_mode_impl( - &self, - key: &str, - context: Option<&MemoryWriteContext>, - mode: MemoryReadMode, - ) -> anyhow::Result> { - let context = context.cloned().unwrap_or_default(); - // C03 / V02-R5: see `recall_with_context_mode` — isolation outranks the - // requested mode. - let mode = if context.require_owner_match { - MemoryReadMode::Enforce - } else { - mode - }; - let scoped = self.get_with_context(key, Some(&context)).await?; - let unrestricted = self.get(key).await?; - // MA-01h: as in `recall_with_context_mode`, Observe never reads past the partition. - let unrestricted = self - .retain_in_partition(unrestricted.into_iter().collect(), context.agent_partition.clone()) - .await? - .pop(); - let selected = match mode { - MemoryReadMode::Enforce => scoped.clone(), - MemoryReadMode::Observe => unrestricted.clone(), - }; - let would_deny = unrestricted.is_some() && scoped.is_none(); - let memory_id = selected.as_ref().map(|entry| entry.id.clone()); - let selected_is_some = selected.is_some(); - let key = key.to_string(); - let pool = self.pool.clone(); - crate::runtime::blocking::spawn_blocking(move || { - let conn = pool.write(); - let principal = sqlite_read_principal(&conn, &context); - log_access( - &conn, - &principal, - "get", - None, - memory_id.as_deref().or(Some(key.as_str())), - Some(match mode { - MemoryReadMode::Enforce => "acl_enforced", - MemoryReadMode::Observe => "observe_mode", - }), - if mode == MemoryReadMode::Observe && would_deny { - "would_deny" - } else if selected_is_some { - "allowed" - } else { - "denied" - }, - ); - }) - .await?; - Ok(selected) - } - - pub(super) async fn list_impl( - &self, - category: Option<&MemoryCategory>, - session_id: Option<&str>, - ) -> anyhow::Result> { - const DEFAULT_LIST_LIMIT: i64 = 1000; - - let pool = self.pool.clone(); - let category = category.cloned(); - let sid = session_id.map(String::from); - - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { - let reader = pool.read()?; - let conn = reader.connection()?; - let session_ref = sid.as_deref(); - let mut results = Vec::new(); - - let row_mapper = |row: &rusqlite::Row| -> rusqlite::Result { - Ok(MemoryEntry { - origin: crate::memory::traits::MemoryEntryOrigin::Stored, - source_event_id: None, - id: row.get(0)?, - key: row.get(1)?, - content: row.get(2)?, - category: Self::str_to_category(&row.get::<_, String>(3)?), - timestamp: row.get(4)?, - session_id: row.get(5)?, - score: None, - tags: None, - access_count: None, - useful_count: row.get(6)?, - source: None, - source_confidence: None, - verification_status: None, - lifecycle_state: None, - compressed_from: None, - }) - }; - - if let Some(ref cat) = category { - let cat_str = Self::category_to_str(cat); - let mut stmt = conn.prepare( - "SELECT id, key, content, category, created_at, session_id, useful_count FROM memories - WHERE category = ?1 ORDER BY updated_at DESC LIMIT ?2", - )?; - let rows = stmt.query_map(params![cat_str, DEFAULT_LIST_LIMIT], row_mapper)?; - for row in rows { - let entry = row?; - if let Some(sid) = session_ref { - if entry.session_id.as_deref() != Some(sid) { - continue; - } - } - results.push(entry); - } - } else { - let mut stmt = conn.prepare( - "SELECT id, key, content, category, created_at, session_id, useful_count FROM memories - ORDER BY updated_at DESC LIMIT ?1", - )?; - let rows = stmt.query_map(params![DEFAULT_LIST_LIMIT], row_mapper)?; - for row in rows { - let entry = row?; - if let Some(sid) = session_ref { - if entry.session_id.as_deref() != Some(sid) { - continue; - } - } - results.push(entry); - } - } - - Ok(results) - }) - .await? - } - - pub(super) async fn list_owner_ids_impl( - &self, - category: &MemoryCategory, - ) -> anyhow::Result>>> { - let pool = self.pool.clone(); - let category = Self::category_to_str(category); - crate::runtime::blocking::spawn_blocking( - move || -> anyhow::Result>>> { - let reader = pool.read()?; - let conn = reader.connection()?; - let mut stmt = conn.prepare("SELECT id, owner_id FROM memories WHERE category = ?1")?; - let owners = stmt - .query_map(params![category], |row| Ok((row.get(0)?, row.get(1)?)))? - .collect::>>>()?; - Ok(Some(owners)) - }, - ) - .await? - } - - pub(super) async fn forget_with_context_impl( - &self, - key: &str, - context: Option<&MemoryWriteContext>, - ) -> anyhow::Result { - let Some(context) = context.cloned() else { - return self.forget(key).await; - }; - - let pool = self.pool.clone(); - let key = key.to_string(); - - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result { - let conn = pool.write(); - let principal = sqlite_read_principal(&conn, &context); - // FIX-P1-06: unified scope builder for all roles (see recall_with_context). - let (scope_sql, scope_params) = principal.build_sql_scope(); - // R-B1d D-1: the delete guard. The fixed parameter is ?1 = key and - // the scope predicate occupies ?2..; the owner guard therefore - // binds at the next free index and its value is appended last, so - // the template order is preserved. - let owner_anchor = Self::forget_owner_anchor(&context); - let owner_guard = Self::forget_owner_guard(&context, scope_params.len() + 2); - // MA-01h: a partitioned caller deletes only a row of its own partition. - // The conjunct's bare markers follow every numbered one. - let (partition_sql, partition_params) = - memory_partition_conjunct(super::events::MA_SCOPE_COLUMN, context.agent_partition.as_ref()); - let mut query_params = Vec::with_capacity(scope_params.len() + partition_params.len() + 2); - query_params.push(Value::from(key.clone())); - query_params.extend(scope_params); - if let (true, Some(owner)) = (owner_guard.bound_owner, owner_anchor.as_deref()) { - query_params.push(Value::from(owner.to_string())); - } - query_params.extend(partition_params); - let owner_guard_sql = owner_guard.sql; - let query = format!( - "SELECT id FROM memories WHERE key = ?1 AND ({scope_sql}){owner_guard_sql}{partition_sql} LIMIT 1" - ); - let visible_id = conn - .query_row(&query, params_from_iter(query_params), |row| row.get::<_, String>(0)) - .optional()?; - - let Some(memory_id) = visible_id else { - log_access(&conn, &principal, "forget", Some(&key), None, None, "denied"); - return Ok(false); - }; - - let affected = conn.execute("DELETE FROM memories WHERE id = ?1", params![memory_id])?; - log_access( - &conn, - &principal, - "forget", - Some(&key), - Some(&memory_id), - None, - "allowed", - ); - Ok(affected > 0) - }) - .await? - } - - pub(super) async fn move_to_trash_impl( - &self, - key: &str, - reason: &str, - grace_days: u32, - ) -> anyhow::Result> { - let pool = self.pool.clone(); - let key = key.to_string(); - let reason = reason.to_string(); - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { - let conn = pool.write(); - let tx = begin_immediate(&conn)?; - // FIX-P1-11: snapshot the row's value before soft-deleting it. We DO NOT - // physically delete from `memories`; we record a trash row so it can be - // restored within the grace window. Parent stamp is read inside the - // writer transaction (review M3). - let row: Option<(String, String, Option)> = tx - .query_row( - "SELECT content, category, ma_scope_id FROM memories WHERE key = ?1", - params![key], - |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), - ) - .optional()?; - let Some((content, category, ma_scope_id)) = row else { - return Ok(None); - }; - // Idempotency: if an unrestored trash entry already exists for this key, - // return it rather than duplicating. - let existing: Option = tx - .query_row( - "SELECT trash_id FROM memory_trash WHERE memory_key = ?1 AND restored_at IS NULL LIMIT 1", - params![key], - |row| row.get(0), - ) - .optional()?; - if let Some(trash_id) = existing { - return Ok(Some(trash_id)); - } - let trash_id = format!("trash-{}", Uuid::now_v7()); - let now = Utc::now(); - let grace_until = now + chrono::Duration::days(i64::from(grace_days)); - tx.execute( - "INSERT INTO memory_trash ( - trash_id, memory_key, content, category, reason, trashed_at, grace_until, ma_scope_id - ) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", - params![ - trash_id, - key, - content, - category, - reason, - now.to_rfc3339(), - grace_until.to_rfc3339(), - ma_scope_id, - ], - )?; - tx.commit()?; - Ok(Some(trash_id)) - }) - .await? - } - - pub(super) async fn increment_useful_count_impl(&self, id: &str) -> anyhow::Result<()> { - let pool = self.pool.clone(); - let id = id.to_string(); - - crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result<()> { - let conn = pool.write(); - conn.execute( - "UPDATE memories - SET useful_count = COALESCE(useful_count, 0) + 1, - updated_at = ?1 - WHERE id = ?2", - params![Local::now().to_rfc3339(), id], - )?; - Ok(()) - }) - .await? - } -} +//! SQLite memory reads, writes and embedding search. +include!("recall/section_1.rs"); +include!("recall/section_2.rs"); diff --git a/src/memory/sqlite/recall/section_1.rs b/src/memory/sqlite/recall/section_1.rs new file mode 100644 index 000000000..c5e14f60f --- /dev/null +++ b/src/memory/sqlite/recall/section_1.rs @@ -0,0 +1,1009 @@ +// Store, recall, forget, FTS5/vector search, owner guards and reindex. + +use super::vector; +use crate::memory::filter::{MemorySafetyFilter, SourceMetadata, safety_rejection_message}; +use crate::memory::principal::{ChatType, MemoryWriteContext, Principal, classify_memory, log_access, post_filter}; +use crate::memory::topic::{delete_orphan_topic, resolve_topic}; +use crate::memory::traits::{ + DecisionMemoryHit, Memory, MemoryCategory, MemoryEntry, MemoryReadMode, MemoryStoreMetadata, + validate_memory_write_target, +}; +use crate::runtime::sqlite_pool::begin_immediate; +use crate::self_system::evolution::record::Actor; +use anyhow::Context; +use chrono::{Local, Utc}; +use rusqlite::{Connection, OptionalExtension, params, params_from_iter, types::Value}; +use std::fmt::Write as _; +use std::path::Path; +use uuid::Uuid; + +use super::{SQLITE_DIALECT, SqliteMemory, sqlite_owner_read_principal, sqlite_read_principal}; + +/// Default ceiling on the embedded memories `vector_search` will score, used +/// when no configuration is supplied. +/// +/// Cosine similarity cannot use an index, so the scan is bounded by insertion +/// order. Operators override this with `[memory] vector_candidate_cap`. +pub(super) const VECTOR_CANDIDATE_CAP: usize = 2_000; + +pub(super) struct PreparedEmbedding { + pub(super) bytes: Vec, + pub(super) hash: String, +} + +enum WriteOutcome { + Done, + Retry, +} + +/// Candidate count for one vector recall. +/// +/// The configured cap is authoritative — it is the number an operator tunes — +/// and is only ever raised to `limit`, because scoring fewer candidates than +/// the caller asked for results would return a short list for no reason. +/// Before 0.8.126 this was `max(limit * 50, 2000)` with no way to change it, +/// so a store larger than the cap lost recall with nothing to turn. +pub(super) const fn vector_candidate_cap(limit: usize, configured: usize) -> usize { + if limit > configured { limit } else { configured } +} + +pub(super) struct VectorCandidateQuery { + pub(super) sql: String, + pub(super) params: Vec>, + candidate_cap: usize, +} + +pub(super) fn vector_candidate_query( + provider: &str, + model: &str, + dimensions: usize, + limit: usize, + category: Option<&str>, + session_id: Option<&str>, + configured_candidate_cap: usize, +) -> VectorCandidateQuery { + let mut sql = "SELECT id, embedding FROM memories + WHERE embedding IS NOT NULL + AND embedding_provider = ?1 + AND embedding_model = ?2 + AND embedding_dimensions = ?3" + .to_string(); + let mut params: Vec> = vec![ + Box::new(provider.to_string()), + Box::new(model.to_string()), + Box::new(i64::try_from(dimensions).unwrap_or(i64::MAX)), + ]; + let mut idx = 4; + + if let Some(category) = category { + let _ = write!(sql, " AND category = ?{idx}"); + params.push(Box::new(category.to_string())); + idx += 1; + } + if let Some(session_id) = session_id { + let _ = write!(sql, " AND session_id = ?{idx}"); + params.push(Box::new(session_id.to_string())); + idx += 1; + } + let candidate_cap = vector_candidate_cap(limit, configured_candidate_cap); + let _ = write!(sql, " ORDER BY update_seq DESC, rowid DESC LIMIT ?{idx}"); + params.push(Box::new(i64::try_from(candidate_cap).unwrap_or(i64::MAX))); + + VectorCandidateQuery { + sql, + params, + candidate_cap, + } +} + +/// One process says "your memory store has outgrown the candidate cap" once. +/// +/// This is a warning, not a debug line: past this point vector recall is +/// silently incomplete — an old-but-relevant memory is never scored — and the +/// only fix is an operator raising `[memory] vector_candidate_cap`. Emitting it +/// per recall would bury the turn logs, so it is latched per process. +static VECTOR_CANDIDATE_CAP_WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// `memories.ma_scope_id` qualified by the `m` alias of the FTS joins. +const MEMORY_ALIAS_SCOPE_COLUMN: &str = "m.ma_scope_id"; + +/// MA-01h: the partition conjunct on a `memories` column with bare `?` +/// markers, for statements whose scope predicate binds positionally. +fn memory_partition_conjunct(column: &str, partition: Option<&crate::memory::AgentPartition>) -> (String, Vec) { + let (sql, values) = super::events::partition_conjunct(column, partition, || "?".to_string()); + (sql, values.into_iter().map(Value::from).collect()) +} + +/// The ids among `ids` whose `memories` row lies in `partition`. +fn partition_visible_memory_ids( + conn: &Connection, + ids: &[&str], + partition: &crate::memory::AgentPartition, +) -> anyhow::Result> { + if ids.is_empty() { + return Ok(std::collections::HashSet::new()); + } + let (partition_sql, partition_values) = memory_partition_conjunct(super::events::MA_SCOPE_COLUMN, Some(partition)); + let placeholders = vec!["?"; ids.len()].join(","); + let sql = format!("SELECT id FROM memories WHERE id IN ({placeholders}){partition_sql}"); + let mut values = ids.iter().map(|id| Value::from((*id).to_string())).collect::>(); + values.extend(partition_values); + let mut stmt = conn.prepare(&sql)?; + let rows = stmt.query_map(params_from_iter(values), |row| row.get::<_, String>(0))?; + Ok(rows.collect::>()?) +} + +/// Keep only the entries whose row lies in `partition`; `None` keeps all. +fn retain_partition_entries( + conn: &Connection, + entries: Vec, + partition: Option<&crate::memory::AgentPartition>, +) -> anyhow::Result> { + let Some(partition) = partition else { + return Ok(entries); + }; + let ids = entries.iter().map(|entry| entry.id.as_str()).collect::>(); + let visible = partition_visible_memory_ids(conn, &ids, partition)?; + Ok(entries + .into_iter() + .filter(|entry| visible.contains(&entry.id)) + .collect()) +} + +impl SqliteMemory { + pub(super) fn open_rehearsal_reader(db_path: &Path, deadline: std::time::Instant) -> anyhow::Result { + anyhow::ensure!(std::time::Instant::now() < deadline, "rehearsal count deadline expired"); + // macOS may expose a trusted temporary parent through `/var` -> + // `/private/var`. Resolve the parent while refusing a symlink at the + // database leaf; a replaced regular file remains a separate threat. + let parent = db_path + .parent() + .ok_or_else(|| anyhow::anyhow!("missing decision database parent"))?; + let file_name = db_path + .file_name() + .ok_or_else(|| anyhow::anyhow!("missing decision database name"))?; + let read_path = parent.canonicalize()?.join(file_name); + anyhow::ensure!(std::time::Instant::now() < deadline, "rehearsal count deadline expired"); + let mut conn = Connection::open_with_flags( + read_path, + rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NOFOLLOW, + )?; + conn.busy_timeout(std::time::Duration::from_millis(25))?; + conn.progress_handler(1_000, Some(move || std::time::Instant::now() >= deadline))?; + Ok(conn) + } + + /// Inspect one key namespace through a byte-for-byte read-only connection. + /// This is used by migration dry-runs that must not initialize or mutate + /// the configured database. + pub async fn read_key_prefix_read_only( + workspace_dir: &Path, + prefix: &str, + ) -> anyhow::Result> { + let db_path = workspace_dir.join("memory/brain.db"); + if !db_path.exists() { + return Ok(Vec::new()); + } + let prefix = prefix.to_string(); + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { + let connection = Connection::open_with_flags(&db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY) + .with_context(|| format!("failed to open {} read-only", db_path.display()))?; + let escaped = prefix.replace('\\', "\\\\").replace('%', "\\%").replace('_', "\\_"); + let pattern = format!("{escaped}%"); + let mut statement = + connection.prepare("SELECT key, content FROM memories WHERE key LIKE ?1 ESCAPE '\\'")?; + let rows = statement.query_map([pattern], |row| { + Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) + })?; + rows.collect::, _>>().map_err(Into::into) + }) + .await? + } + + /// Delete an exact key namespace in one transaction. SQLite FTS triggers + /// remove the corresponding search rows in the same commit. + pub async fn delete_key_prefix_transactional(&self, prefix: &str) -> anyhow::Result { + let pool = self.pool.clone(); + let escaped = prefix.replace('\\', "\\\\").replace('%', "\\%").replace('_', "\\_"); + let pattern = format!("{escaped}%"); + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result { + let conn = pool.write(); + let tx = begin_immediate(&conn)?; + let affected = tx.execute("DELETE FROM memories WHERE key LIKE ?1 ESCAPE '\\'", params![pattern])?; + tx.commit()?; + Ok(affected) + }) + .await? + } + + pub(super) async fn store_internal( + &self, + key: &str, + content: &str, + category: MemoryCategory, + session_id: Option<&str>, + context: Option<&MemoryWriteContext>, + metadata: Option, + ) -> anyhow::Result<()> { + validate_memory_write_target(key, session_id)?; + // V02-R9: an owner-isolated write is confined to the caller's own keys. + // `Some(owner)` only for an isolated context; a blank owner id refuses + // here, before anything is written. + crate::memory::owner_predicate::isolated_store_owner(context)?; + self.check_memory_safety(content, context).await?; + self.write_checked(key, content, category, session_id, context, metadata) + .await + } + + /// The session-snapshot write (`Memory::store_session_snapshot` and + /// `Memory::store_session_snapshot_with_metadata`). The snapshot is the + /// owner's transcript, not recall memory, so the memory content filter + /// does not run. Target validation and the checked write stay. + pub(super) async fn store_session_snapshot_impl( + &self, + key: &str, + content: &str, + session_id: Option<&str>, + metadata: Option, + ) -> anyhow::Result<()> { + validate_memory_write_target(key, session_id)?; + let context = super::terminal_epoch::snapshot_context(&self.db_path, key, session_id)?; + let linked = context.as_ref().and_then(|context| context.session_key.as_deref()).or(session_id); + self.write_checked(key, content, MemoryCategory::Conversation, linked, context.as_ref(), metadata) + .await + } + + /// The write after the target and safety checks passed. + async fn write_checked( + &self, + key: &str, + content: &str, + category: MemoryCategory, + session_id: Option<&str>, + context: Option<&MemoryWriteContext>, + metadata: Option, + ) -> anyhow::Result<()> { + let isolated_owner = crate::memory::owner_predicate::isolated_store_owner(context)?; + let partition = context.and_then(|ctx| ctx.agent_partition.clone()); + let session_key = context.and_then(|ctx| ctx.session_key.clone()); + let needs_embedding = matches!(&category, MemoryCategory::Core | MemoryCategory::Custom(_)); + for attempt in 0..2_u8 { + let salt_scope = self + .salt_scope_for_write( + partition.as_ref(), + session_key.as_deref(), + context.and_then(|ctx| ctx.workspace_id.as_deref()), + context + .and_then(|ctx| ctx.owner_id.as_deref()) + .or(isolated_owner.as_deref()), + ) + .await?; + let prepared = if needs_embedding { + self.embed_without_cache(content, salt_scope.as_deref()).await? + } else { + None + }; + let embedding_bytes = prepared.as_ref().map(|item| item.bytes.clone()); + let embedding_provider = prepared.as_ref().map(|_| self.embedding_provider_name()); + let embedding_model = prepared.as_ref().map(|_| self.embedding_model_name()); + let embedding_dimensions = prepared.as_ref().map(|_| self.embedding_dimensions_i64()); + let cache_hash = prepared.as_ref().map(|item| item.hash.clone()); + + let pool = self.pool.clone(); + let key = key.to_string(); + let content = content.to_string(); + let sid = session_id.map(String::from); + let write_ctx = context.cloned(); + let mut metadata = metadata.clone().unwrap_or_default(); + if let Some(owner) = isolated_owner.as_ref() { + metadata.owner_id = Some(owner.clone()); + } + let owner_guard = crate::memory::owner_predicate::store_conflict_guard( + SQLITE_DIALECT, + "memories", + isolated_owner.is_some(), + ); + let expected_salt = salt_scope.clone(); + let cache_now = Local::now().to_rfc3339(); + let provider_name = self.embedding_provider_name(); + let model_name = self.embedding_model_name(); + let dimensions = self.embedding_dimensions_i64(); + let cache_max = i64::try_from(self.cache_max).unwrap_or(i64::MAX); + let cache_bytes = embedding_bytes.clone(); + let isolated_owner = isolated_owner.clone(); + let category = category.clone(); + let provenance = self.write_provenance.clone(); + + let outcome = crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result { + let conn = pool.write(); + let tx = begin_immediate(&conn)?; + let existed = match provenance.as_deref() { + Some(_) => super::write_log::target_exists(&tx, super::write_log::WriteTarget::Memory, &key)?, + None => false, + }; + let now = Local::now().to_rfc3339(); + let cat = Self::category_to_str(&category); + let id = Uuid::new_v4().to_string(); + let bound_scope = if let Some(ctx) = write_ctx.as_ref() { + super::agent_migration::resolve_input_scope( + &tx, + ctx.agent_partition.as_ref(), + ctx.session_key.as_deref(), + ctx.workspace_id.as_deref().unwrap_or(""), + ctx.owner_id.as_deref(), + )? + } else { + None + }; + if expected_salt.is_some() && bound_scope != expected_salt { + return Ok(WriteOutcome::Retry); + } + + let previous_topic_id: Option = tx + .query_row("SELECT topic_id FROM memories WHERE key = ?1", params![&key], |row| row.get(0)) + .optional()? + .flatten(); + + if let Some(ctx) = write_ctx { + if let Some(owner) = isolated_owner.as_deref() { + let stored_owner: Option> = tx + .query_row( + "SELECT owner_id FROM memories WHERE key = ?1", + params![&key], + |row| row.get(0), + ) + .optional()?; + if stored_owner.is_some_and(|stored| stored.as_deref() != Some(owner)) { + return Err(crate::memory::owner_predicate::OwnerScopedStoreRefusal::KeyNotAvailable { + key: key.clone(), + } + .into()); + } + } + let principal = sqlite_read_principal(&tx, &ctx); + let classified = classify_memory(&ctx, &content, &principal); + let topic_id = match resolve_topic(&tx, &content, &principal, bound_scope.as_deref()) { + Ok(topic_id) => topic_id, + Err(error) => { + tracing::warn!(error = %crate::agent::diagnostics::error_class(&error), "memory topic resolve failed"); + None + } + }; + let risk_json = serde_json::to_string(&classified.risk_signals)?; + let sender_id = if ctx.channel.is_some() && ctx.raw_sender.is_some() { + Some(principal.user_id) + } else { + None + }; + let explicit_sender_id = ctx.sender_id.or(sender_id); + let owner_id = metadata.owner_id.clone().or_else(|| explicit_sender_id.clone()); + let chat_type = ctx + .chat_type + .map(|raw| ChatType::from_str(&raw).as_str().to_string()); + let scope_guard = super::agent_migration::scope_conflict_guard("memories", !owner_guard.is_empty()); + let coalesce = super::agent_migration::scope_coalesce_set("memories"); + + let changed = tx.execute( + &format!("INSERT INTO memories ( + id, key, content, category, embedding, embedding_provider, + embedding_model, embedding_dimensions, created_at, updated_at, + session_id, workspace_id, owner_id, channel, chat_type, chat_id, + sender_id, raw_sender, topic_id, visibility, sensitivity, + risk_signals, policy_version, ma_scope_id + ) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, ?21, ?22, ?23, ?24) + ON CONFLICT(key) DO UPDATE SET + content = excluded.content, + category = excluded.category, + embedding = excluded.embedding, + embedding_provider = excluded.embedding_provider, + embedding_model = excluded.embedding_model, + embedding_dimensions = excluded.embedding_dimensions, + updated_at = excluded.updated_at, + session_id = excluded.session_id, + workspace_id = excluded.workspace_id, + owner_id = excluded.owner_id, + channel = excluded.channel, + chat_type = excluded.chat_type, + chat_id = excluded.chat_id, + sender_id = excluded.sender_id, + raw_sender = excluded.raw_sender, + topic_id = excluded.topic_id, + visibility = excluded.visibility, + sensitivity = excluded.sensitivity, + risk_signals = excluded.risk_signals, + policy_version = excluded.policy_version, + {coalesce}{owner_guard}{scope_guard}"), + params![ + id, + &key, + &content, + cat, + embedding_bytes, + embedding_provider, + embedding_model, + embedding_dimensions, + now, + now, + sid, + metadata.workspace_id.clone(), + owner_id, + ctx.channel, + chat_type, + ctx.chat_id, + explicit_sender_id, + ctx.raw_sender, + topic_id, + classified.visibility.as_str(), + classified.sensitivity.as_str(), + risk_json, + classified.policy_version, + bound_scope, + ], + )?; + if changed == 0 { + return Err(crate::memory::owner_predicate::OwnerScopedStoreRefusal::KeyNotAvailable { + key: key.clone(), + } + .into()); + } + if let Some(previous) = previous_topic_id.as_deref() + && Some(previous) != topic_id.as_deref() + { + delete_orphan_topic(&tx, previous)?; + } + } else { + let coalesce = super::agent_migration::scope_coalesce_set("memories"); + let scope_guard = super::agent_migration::scope_conflict_guard("memories", false); + let changed = tx.execute( + &format!( + "INSERT INTO memories ( + id, key, content, category, embedding, embedding_provider, + embedding_model, embedding_dimensions, created_at, updated_at, + session_id, workspace_id, owner_id, agent_id, persona_id, + source_event_id, source, channel, topic_id, ma_scope_id + ) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20) + ON CONFLICT(key) DO UPDATE SET + content = excluded.content, + category = excluded.category, + embedding = excluded.embedding, + embedding_provider = excluded.embedding_provider, + embedding_model = excluded.embedding_model, + embedding_dimensions = excluded.embedding_dimensions, + updated_at = excluded.updated_at, + session_id = excluded.session_id, + workspace_id = excluded.workspace_id, + owner_id = excluded.owner_id, + agent_id = excluded.agent_id, + persona_id = excluded.persona_id, + source_event_id = excluded.source_event_id, + source = excluded.source, + channel = excluded.channel, + topic_id = excluded.topic_id, + {coalesce}{scope_guard}" + ), + params![ + id, + &key, + &content, + cat, + embedding_bytes, + embedding_provider, + embedding_model, + embedding_dimensions, + now, + now, + sid, + metadata.workspace_id.clone(), + metadata.owner_id.clone(), + metadata.agent_id.clone(), + metadata.persona_id.clone(), + metadata.source_event_id.clone(), + metadata.source.clone(), + metadata.channel.clone(), + metadata.topic_id.clone(), + bound_scope, + ], + )?; + if changed == 0 { + return Err(crate::memory::owner_predicate::OwnerScopedStoreRefusal::KeyNotAvailable { + key: key.clone(), + } + .into()); + } + if let Some(previous) = previous_topic_id.as_deref() + && Some(previous) != metadata.topic_id.as_deref() + { + delete_orphan_topic(&tx, previous)?; + } + } + + if metadata.workspace_id.is_some() + || metadata.owner_id.is_some() + || metadata.agent_id.is_some() + || metadata.persona_id.is_some() + || metadata.source_event_id.is_some() + || metadata.source.is_some() + { + let metadata_owner_guard = if isolated_owner.is_some() { + " AND owner_id IS ?2" + } else { + "" + }; + let updated = tx.execute( + &format!( + "UPDATE memories + SET workspace_id = ?1, + owner_id = COALESCE(?2, owner_id), + agent_id = ?3, + persona_id = ?4, + source_event_id = ?5, + source = ?6, + updated_at = ?7 + WHERE key = ?8{metadata_owner_guard}" + ), + params![ + metadata.workspace_id, + metadata.owner_id, + metadata.agent_id, + metadata.persona_id, + metadata.source_event_id, + metadata.source, + Local::now().to_rfc3339(), + &key, + ], + )?; + if isolated_owner.is_some() && updated == 0 { + return Err(crate::memory::owner_predicate::OwnerScopedStoreRefusal::KeyNotAvailable { + key: key.clone(), + } + .into()); + } + } + if let (Some(hash), Some(bytes)) = (cache_hash, cache_bytes) { + Self::insert_embedding_cache( + &tx, + &hash, + &bytes, + &provider_name, + &model_name, + dimensions, + &cache_now, + bound_scope.as_deref(), + cache_max, + )?; + } + if let Some(provenance) = provenance.as_deref() { + super::write_log::record_memory_upsert(&tx, provenance, &key, existed)?; + } + tx.commit()?; + Ok(WriteOutcome::Done) + }) + .await??; + match outcome { + WriteOutcome::Done => break, + WriteOutcome::Retry if attempt == 0 => continue, + WriteOutcome::Retry => return Err(crate::memory::AgentScopeRefused.into()), + } + } + Ok(()) + } + + async fn check_memory_safety(&self, content: &str, context: Option<&MemoryWriteContext>) -> anyhow::Result<()> { + let source = SourceMetadata { + actor: Self::safety_actor_for_context(context), + historical_accuracy: None, + }; + let result = MemorySafetyFilter::default().check(content, &source).await; + if result.passed { + Ok(()) + } else { + anyhow::bail!("{}", safety_rejection_message(&result.issues)); + } + } + + const fn safety_actor_for_context(context: Option<&MemoryWriteContext>) -> Actor { + match context { + Some(ctx) if ctx.raw_sender.is_some() || ctx.sender_id.is_some() => Actor::User, + Some(_) => Actor::Agent, + None => Actor::Agent, + } + } + + /// Deterministic content hash for embedding cache. + /// Uses SHA-256 (truncated) instead of DefaultHasher, which is + /// explicitly documented as unstable across Rust versions. + pub(super) fn content_hash(text: &str) -> String { + use sha2::{Digest, Sha256}; + let hash = Sha256::digest(text.as_bytes()); + // First 16 bytes → 32 hex chars. 128-bit hash reduces collision risk + // to negligible levels (~2^-64 birthday bound vs ~2^-32 with 64-bit). + let mut hex = String::with_capacity(32); + for byte in hash.iter().take(16) { + use std::fmt::Write; + let _ = write!(hex, "{byte:02x}"); + } + hex + } + + /// SHA-256("ma:" + scope_id + NUL + text) as the partitioned cache key. + pub(super) fn scoped_content_hash(scope_id: Option<&str>, text: &str) -> String { + use sha2::{Digest, Sha256}; + let Some(scope_id) = scope_id else { + return Self::content_hash(text); + }; + let mut hasher = Sha256::new(); + hasher.update(b"ma:"); + hasher.update(scope_id.as_bytes()); + hasher.update([0u8]); + hasher.update(text.as_bytes()); + format!("{:x}", hasher.finalize()) + } + + pub(super) async fn salt_scope_for_write( + &self, + partition: Option<&crate::memory::AgentPartition>, + session_key: Option<&str>, + workspace_id: Option<&str>, + owner_id: Option<&str>, + ) -> anyhow::Result> { + let Some(partition) = partition.cloned() else { + return Ok(None); + }; + if partition.workspace_id != workspace_id.unwrap_or("") || owner_id != Some(partition.owner_id.as_str()) { + return Err(crate::memory::AgentScopeRefused.into()); + } + let session_key = session_key.map(str::to_owned); + let pool = self.pool.clone(); + crate::runtime::blocking::spawn_blocking(move || { + let conn = pool.write(); + super::agent_migration::lookup_or_mint_write_scope(&conn, &partition, session_key.as_deref()).map(Some) + }) + .await? + } + + pub(super) async fn embed_without_cache( + &self, + text: &str, + scope_id: Option<&str>, + ) -> anyhow::Result> { + if self.embedder.dimensions() == 0 { + return Ok(None); + } + let hash = Self::scoped_content_hash(scope_id, text); + let provider_name = self.embedding_provider_name(); + let model_name = self.embedding_model_name(); + let dimensions = self.embedding_dimensions_i64(); + let pool = self.pool.clone(); + let hash_c = hash.clone(); + let cached = crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result>> { + let conn = pool.write(); + Self::lookup_embedding_cache(&conn, &hash_c, &provider_name, &model_name, dimensions) + }) + .await??; + let embedding = if let Some(embedding) = cached { + embedding + } else { + self.embedder.embed_one(text).await? + }; + if embedding.len() != self.embedder.dimensions() { + anyhow::bail!( + "embedding dimension mismatch: provider={} model={} expected={} got={}", + self.embedding_provider_name(), + self.embedding_model_name(), + self.embedder.dimensions(), + embedding.len() + ); + } + Ok(Some(PreparedEmbedding { + bytes: vector::vec_to_bytes(&embedding), + hash, + })) + } + + fn lookup_embedding_cache( + conn: &Connection, + hash: &str, + provider: &str, + model: &str, + dimensions: i64, + ) -> anyhow::Result>> { + let mut stmt = conn.prepare( + "SELECT embedding FROM embedding_cache + WHERE content_hash = ?1 + AND provider = ?2 + AND model = ?3 + AND dimensions = ?4", + )?; + let blob: Option> = stmt + .query_row(params![hash, provider, model, dimensions], |row| row.get(0)) + .ok(); + let Some(bytes) = blob else { + return Ok(None); + }; + let embedding = vector::bytes_to_vec(&bytes); + if embedding.len() == usize::try_from(dimensions).unwrap_or(usize::MAX) { + Ok(Some(embedding)) + } else { + Ok(None) + } + } + + pub(super) fn insert_embedding_cache( + conn: &Connection, + hash: &str, + bytes: &[u8], + provider: &str, + model: &str, + dimensions: i64, + now: &str, + scope_id: Option<&str>, + cache_max: i64, + ) -> anyhow::Result<()> { + conn.execute( + "INSERT OR REPLACE INTO embedding_cache ( + content_hash, embedding, provider, model, dimensions, created_at, accessed_at, ma_scope_id + ) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", + params![hash, bytes, provider, model, dimensions, now, now, scope_id], + )?; + let count: i64 = conn.query_row("SELECT COUNT(*) FROM embedding_cache", [], |row| row.get(0))?; + if count > cache_max { + let to_delete = count - cache_max; + conn.execute( + "DELETE FROM embedding_cache WHERE content_hash IN ( + SELECT content_hash FROM embedding_cache + ORDER BY accessed_at ASC LIMIT ?1 + )", + params![to_delete], + )?; + } + Ok(()) + } + + pub(super) fn content_sha256_hex(text: &str) -> String { + use sha2::{Digest, Sha256}; + let hash = Sha256::digest(text.as_bytes()); + let mut hex = String::with_capacity(64); + for byte in hash { + let _ = write!(hex, "{byte:02x}"); + } + hex + } + + /// The owner id an owner-isolated delete is confined to, with blanks + /// treated as absent (the rule + /// [`crate::memory::owner_predicate::has_owner_id`] applies to reads). + /// + /// A non-isolated context never yields one, so the guard below renders + /// nothing for it and the historical statement is unchanged. + pub(super) fn forget_owner_anchor(context: &MemoryWriteContext) -> Option { + if !context.require_owner_match { + return None; + } + context + .owner_id + .as_deref() + .map(str::trim) + .filter(|owner| !owner.is_empty()) + .map(str::to_string) + } + + /// The guard appended to `forget_with_context`'s visibility scope + /// (R-B1d D-1). + /// + /// Delete-by-key was confined to the shared visibility predicate alone. + /// That predicate owner-qualifies every **non-public** arm for an isolated + /// caller, but `visibility = 'public'` stays shared by design — correct for + /// a read, wrong for a destructive operation, because it let an + /// owner-isolated caller remove a public row belonging to someone else. + /// This guard is therefore appended at the top level of the `WHERE` rather + /// than inside one arm: an owner-isolated caller deletes only rows whose + /// `owner_id` equals its authenticated owner id, whatever their visibility. + /// + /// The fragment comes from + /// [`crate::memory::owner_predicate::owner_match_suffix`] — the single + /// owner-isolation seam — so it renders the empty string for a + /// non-isolated caller (statement and bind list byte-identical), + /// `" AND FALSE"` for an isolated caller with no usable owner id (nothing + /// is deleted and the call reports that nothing was found), and + /// `" AND owner_id = ?N"` otherwise. A stored `NULL` `owner_id` compares to + /// `NULL`, so an unattributed row is not deletable by an isolated caller + /// either. `index` is the caller's next free placeholder, so the + /// one-marker-one-parameter accounting is preserved. + pub(super) fn forget_owner_guard( + context: &MemoryWriteContext, + index: usize, + ) -> crate::memory::owner_predicate::OwnerMatchPredicate { + crate::memory::owner_predicate::owner_match_suffix( + SQLITE_DIALECT, + index, + context.require_owner_match, + Self::forget_owner_anchor(context).is_some(), + ) + } + + pub(super) fn embedding_provider_name(&self) -> String { + self.embedder.name().to_string() + } + + pub(super) fn embedding_model_name(&self) -> String { + self.embedder.model().to_string() + } + + pub(super) fn embedding_dimensions_i64(&self) -> i64 { + i64::try_from(self.embedder.dimensions()).unwrap_or(i64::MAX) + } + + /// Get embedding from cache, or compute + cache it (unpartitioned hash). + pub(super) async fn get_or_compute_embedding(&self, text: &str) -> anyhow::Result>> { + self.embed_and_cache(text, None).await + } + + async fn embed_and_cache(&self, text: &str, scope_id: Option<&str>) -> anyhow::Result>> { + let Some(prepared) = self.embed_without_cache(text, scope_id).await? else { + return Ok(None); + }; + let embedding = vector::bytes_to_vec(&prepared.bytes); + let pool = self.pool.clone(); + let now = Local::now().to_rfc3339(); + let provider_name = self.embedding_provider_name(); + let model_name = self.embedding_model_name(); + let dimensions = self.embedding_dimensions_i64(); + let cache_max = i64::try_from(self.cache_max).unwrap_or(i64::MAX); + let scope = scope_id.map(str::to_owned); + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result<()> { + let conn = pool.write(); + Self::insert_embedding_cache( + &conn, + &prepared.hash, + &prepared.bytes, + &provider_name, + &model_name, + dimensions, + &now, + scope.as_deref(), + cache_max, + ) + }) + .await??; + Ok(Some(embedding)) + } + + /// FTS5 BM25 keyword search + fn fts5_search(conn: &Connection, query: &str, limit: usize) -> anyhow::Result> { + // Escape FTS5 special chars and build query + let fts_query: String = crate::memory::topic::build_safe_fts_query(query); + + if fts_query.is_empty() { + return Ok(Vec::new()); + } + + let sql = "SELECT m.id, bm25(memories_fts) as score + FROM memories_fts f + JOIN memories m ON m.rowid = f.rowid + WHERE memories_fts MATCH ?1 + ORDER BY score + LIMIT ?2"; + + let mut stmt = conn.prepare(sql)?; + #[allow(clippy::cast_possible_wrap)] + let limit_i64 = limit as i64; + + let rows = stmt.query_map(params![fts_query, limit_i64], |row| { + let id: String = row.get(0)?; + let score: f64 = row.get(1)?; + // BM25 returns negative scores (lower = better), negate for ranking + #[allow(clippy::cast_possible_truncation)] + Ok((id, (-score) as f32)) + })?; + + let mut results = Vec::new(); + for row in rows { + results.push(row?); + } + Ok(results) + } + + /// Vector similarity search: scan embeddings and compute cosine similarity. + /// + /// Optional `category` and `session_id` filters reduce full-table scans + /// when the caller already knows the scope of relevant memories. + /// + /// Cosine similarity has no index, so the candidate set is bounded before + /// scoring: without a bound this is O(N) over every embedded memory on a + /// path that runs once per turn. + /// + /// The bound orders by `update_seq`, not by `updated_at` and not by + /// `rowid`. + /// + /// `updated_at` is `Local::now().to_rfc3339()` — an RFC 3339 string carrying + /// the writer's UTC offset — and it is ordered lexicographically by SQLite. + /// Within one fixed offset that happens to match chronological order, but a + /// DST transition, a machine timezone change, or a store shared between + /// processes in different zones reorders whole blocks of rows, and any row + /// historically written with `Utc::now()` sorts in a third order again. The + /// rows dropped by `LIMIT` would then be the wrong ones. + /// + /// `rowid` cannot be reordered by a clock, but it does not move either: + /// every writer here upserts with `ON CONFLICT(key) DO UPDATE`, which + /// rewrites the content and the embedding of an existing key in place. A + /// long-lived key refreshed a second ago therefore kept its original + /// position, and in a store larger than the cap it stayed outside the + /// window — the memory whose embedding was *just* made relevant was the one + /// that could not be scored. + /// + /// `update_seq` is a per-store counter bumped by a trigger on every insert + /// and every update (see `init_schema`). It is an integer, so it has no + /// timezone, no offset and no DST; it is monotonic, so it cannot be + /// reordered by a clock; and it follows the row when the row is refreshed. + /// "Newest" here therefore means most recently *written*, created or + /// refreshed. `rowid` breaks ties so the window is deterministic on a store + /// whose sequence was backfilled by the migration. + /// + /// `candidate_cap` is the configured `[memory] vector_candidate_cap`. Hitting it is + /// a real recall regression — an old-but-relevant memory is never scored — + /// so it is reported once per process at `warn`, not at `debug`. + pub(super) fn vector_search( + conn: &Connection, + query_embedding: &[f32], + provider: &str, + model: &str, + dimensions: usize, + limit: usize, + category: Option<&str>, + session_id: Option<&str>, + candidate_cap: usize, + ) -> anyhow::Result> { + let VectorCandidateQuery { + sql, + params, + candidate_cap, + } = vector_candidate_query(provider, model, dimensions, limit, category, session_id, candidate_cap); + + let mut stmt = conn.prepare(&sql)?; + let params_ref: Vec<&dyn rusqlite::types::ToSql> = params.iter().map(AsRef::as_ref).collect(); + let rows = stmt.query_map(params_ref.as_slice(), |row| { + let id: String = row.get(0)?; + let blob: Vec = row.get(1)?; + Ok((id, blob)) + })?; + + let mut scored: Vec<(String, f32)> = Vec::new(); + let mut candidates = 0usize; + for row in rows { + let (id, blob) = row?; + candidates += 1; + let emb = vector::bytes_to_vec(&blob); + if emb.len() != dimensions { + tracing::debug!( + memory_id = %crate::agent::diagnostics::text_class(&id), + expected_dimensions = dimensions, + actual_dimensions = emb.len(), + "Skipping stale memory embedding with mismatched dimensions" + ); + continue; + } + let sim = vector::cosine_similarity(query_embedding, &emb); + if sim > 0.0 { + scored.push((id, sim)); + } + } + + if candidates >= candidate_cap && !VECTOR_CANDIDATE_CAP_WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) + { + tracing::warn!( + candidate_cap, + limit, + "Vector recall hit its candidate cap: older embedded memories are no longer scored and \ + cannot be recalled. Raise [memory] vector_candidate_cap to score more of the store." + ); + } + + scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal)); + scored.truncate(limit); + Ok(scored) + } + +} diff --git a/src/memory/sqlite/recall/section_2.rs b/src/memory/sqlite/recall/section_2.rs new file mode 100644 index 000000000..759992646 --- /dev/null +++ b/src/memory/sqlite/recall/section_2.rs @@ -0,0 +1,1095 @@ +impl SqliteMemory { + /// Safe reindex: rebuild FTS5 + embeddings with rollback on failure + pub async fn reindex(&self) -> anyhow::Result { + // Step 1: Rebuild FTS5 + { + let pool = self.pool.clone(); + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result<()> { + let conn = pool.write(); + conn.execute_batch( + "INSERT INTO memories_fts(memories_fts) VALUES('rebuild'); + INSERT INTO document_chunks_fts(document_chunks_fts) VALUES('rebuild');", + )?; + Ok(()) + }) + .await??; + } + + // Step 2: Re-embed eligible memories that lack embeddings + if self.embedder.dimensions() == 0 { + return Ok(0); + } + + let provider_name = self.embedding_provider_name(); + let model_name = self.embedding_model_name(); + let dimensions = self.embedding_dimensions_i64(); + let pool = self.pool.clone(); + let entries: Vec<(String, String, Option)> = crate::runtime::blocking::spawn_blocking(move || { + let reader = pool.read()?; + let conn = reader.connection()?; + let mut stmt = conn.prepare( + "SELECT id, content, ma_scope_id + FROM memories + WHERE category NOT IN ('daily', 'conversation') + AND ( + embedding IS NULL + OR embedding_provider IS NULL + OR embedding_model IS NULL + OR embedding_dimensions IS NULL + OR embedding_provider != ?1 + OR embedding_model != ?2 + OR embedding_dimensions != ?3 + )", + )?; + let rows = stmt.query_map(params![provider_name, model_name, dimensions], |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, String>(1)?, + row.get::<_, Option>(2)?, + )) + })?; + Ok::<_, anyhow::Error>(rows.filter_map(std::result::Result::ok).collect()) + }) + .await??; + + let mut count = 0; + for (id, content, scope) in &entries { + if let Ok(Some(emb)) = self.embed_and_cache(content, scope.as_deref()).await { + let bytes = vector::vec_to_bytes(&emb); + let pool = self.pool.clone(); + let id = id.clone(); + let provider_name = self.embedding_provider_name(); + let model_name = self.embedding_model_name(); + let dimensions = self.embedding_dimensions_i64(); + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result<()> { + let conn = pool.write(); + conn.execute( + "UPDATE memories + SET embedding = ?1, + embedding_provider = ?2, + embedding_model = ?3, + embedding_dimensions = ?4 + WHERE id = ?5", + params![bytes, provider_name, model_name, dimensions, id], + )?; + Ok(()) + }) + .await??; + count += 1; + } + } + + let provider_name = self.embedding_provider_name(); + let model_name = self.embedding_model_name(); + let dimensions = self.embedding_dimensions_i64(); + let pool = self.pool.clone(); + let chunks: Vec<(String, String, Option)> = crate::runtime::blocking::spawn_blocking(move || { + let reader = pool.read()?; + let conn = reader.connection()?; + let mut stmt = conn.prepare( + "SELECT chunk_id, content, ma_scope_id + FROM document_chunks + WHERE embedding IS NULL + OR embedding_provider IS NULL + OR embedding_model IS NULL + OR embedding_dimensions IS NULL + OR embedding_provider != ?1 + OR embedding_model != ?2 + OR embedding_dimensions != ?3", + )?; + let rows = stmt.query_map(params![provider_name, model_name, dimensions], |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, String>(1)?, + row.get::<_, Option>(2)?, + )) + })?; + Ok::<_, anyhow::Error>(rows.filter_map(std::result::Result::ok).collect()) + }) + .await??; + + for (chunk_id, content, scope) in &chunks { + if let Ok(Some(emb)) = self.embed_and_cache(content, scope.as_deref()).await { + let bytes = vector::vec_to_bytes(&emb); + let pool = self.pool.clone(); + let chunk_id = chunk_id.clone(); + let provider_name = self.embedding_provider_name(); + let model_name = self.embedding_model_name(); + let dimensions = self.embedding_dimensions_i64(); + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result<()> { + let conn = pool.write(); + conn.execute( + "UPDATE document_chunks + SET embedding = ?1, + embedding_provider = ?2, + embedding_model = ?3, + embedding_dimensions = ?4 + WHERE chunk_id = ?5", + params![bytes, provider_name, model_name, dimensions, chunk_id], + )?; + Ok(()) + }) + .await??; + count += 1; + } + } + + Ok(count) + } + + pub(super) async fn mirror_operator_write_impl( + &self, + key: &str, + content: &str, + category: &MemoryCategory, + ) -> anyhow::Result<()> { + // With the memory ACL on the Markdown mirror is off altogether, as it + // always was. + if self.acl_enabled { + return Ok(()); + } + let db_path = self.db_path.clone(); + let key = key.to_string(); + let content = content.to_string(); + let category = category.clone(); + crate::runtime::blocking::spawn_blocking(move || { + Self::append_backup_entry(&db_path, &key, &content, &category); + }) + .await?; + Ok(()) + } + + /// Keep only the entries whose row lies in `partition` (MA-01h); `None` + /// keeps all. + async fn retain_in_partition( + &self, + entries: Vec, + partition: Option, + ) -> anyhow::Result> { + if partition.is_none() || entries.is_empty() { + return Ok(entries); + } + let pool = self.pool.clone(); + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { + let reader = pool.read()?; + let conn = reader.connection()?; + retain_partition_entries(&conn, entries, partition.as_ref()) + }) + .await? + } + + pub(super) async fn recall_impl( + &self, + query: &str, + limit: usize, + session_id: Option<&str>, + ) -> anyhow::Result> { + if query.trim().is_empty() { + return Ok(Vec::new()); + } + + // Compute query embedding (async, before blocking work) + let query_embedding = self.get_or_compute_embedding(query).await?; + + let pool = self.pool.clone(); + let query = query.to_string(); + let sid = session_id.map(String::from); + let vector_weight = self.vector_weight; + let keyword_weight = self.keyword_weight; + let embedding_provider = self.embedding_provider_name(); + let embedding_model = self.embedding_model_name(); + let embedding_dimensions = self.embedder.dimensions(); + let vector_candidate_cap = self.vector_candidate_cap; + + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { + let reader = pool.read()?; + let conn = reader.connection()?; + let session_ref = sid.as_deref(); + + // FTS5 BM25 keyword search + let keyword_results = match Self::fts5_search(&conn, &query, limit * 2) { + Ok(results) => results, + Err(e) => { + tracing::warn!(error = %crate::agent::diagnostics::error_class(&e), "FTS5 search failed (returning empty)"); + Vec::new() + } + }; + + // Vector similarity search (if embeddings available) + let vector_results = query_embedding.as_ref().map_or_else(Vec::new, |qe| { + match Self::vector_search( + &conn, + qe, + &embedding_provider, + &embedding_model, + embedding_dimensions, + limit * 2, + None, + session_ref, + vector_candidate_cap, + ) { + Ok(results) => results, + Err(e) => { + tracing::warn!(error = %crate::agent::diagnostics::error_class(&e), "Vector search failed (returning empty)"); + Vec::new() + } + } + }); + + // Hybrid merge + let merged = if vector_results.is_empty() { + keyword_results + .iter() + .map(|(id, score)| vector::ScoredResult { + id: id.clone(), + vector_score: None, + keyword_score: Some(*score), + final_score: *score, + }) + .collect::>() + } else { + vector::hybrid_merge(&vector_results, &keyword_results, vector_weight, keyword_weight, limit) + }; + + // Fetch full entries for merged results in a single query + // instead of N round-trips (N+1 pattern). + let mut results = Vec::new(); + if !merged.is_empty() { + let placeholders: String = (1..=merged.len()) + .map(|i| format!("?{i}")) + .collect::>() + .join(", "); + let sql = format!( + "SELECT id, key, content, category, created_at, session_id, useful_count \ + FROM memories WHERE id IN ({placeholders})" + ); + let mut stmt = conn.prepare(&sql)?; + let id_params: Vec> = merged + .iter() + .map(|s| Box::new(s.id.clone()) as Box) + .collect(); + let params_ref: Vec<&dyn rusqlite::types::ToSql> = id_params.iter().map(AsRef::as_ref).collect(); + let rows = stmt.query_map(params_ref.as_slice(), |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, String>(1)?, + row.get::<_, String>(2)?, + row.get::<_, String>(3)?, + row.get::<_, String>(4)?, + row.get::<_, Option>(5)?, + row.get::<_, Option>(6)?, + )) + })?; + + let mut entry_map = std::collections::HashMap::new(); + for row in rows { + let (id, key, content, cat, ts, sid, useful_count) = row?; + entry_map.insert(id, (key, content, cat, ts, sid, useful_count)); + } + + for scored in &merged { + if let Some((key, content, cat, ts, sid, useful_count)) = entry_map.remove(&scored.id) { + let entry = MemoryEntry { + origin: crate::memory::traits::MemoryEntryOrigin::Stored, + source_event_id: None, + id: scored.id.clone(), + key, + content, + category: Self::str_to_category(&cat), + timestamp: ts, + session_id: sid, + score: Some(f64::from(scored.final_score)), + tags: None, + access_count: None, + useful_count, + source: None, + source_confidence: None, + verification_status: None, + lifecycle_state: None, + compressed_from: None, + }; + if let Some(filter_sid) = session_ref { + if entry.session_id.as_deref() != Some(filter_sid) { + continue; + } + } + results.push(entry); + } + } + } + + // If hybrid returned nothing, fall back to LIKE search. + // Cap keyword count so we don't create too many SQL shapes, + // which helps prepared-statement cache efficiency. + if results.is_empty() { + const MAX_LIKE_KEYWORDS: usize = 8; + let keywords: Vec = query + .split_whitespace() + .take(MAX_LIKE_KEYWORDS) + .map(|w| format!("%{w}%")) + .collect(); + if !keywords.is_empty() { + let conditions: Vec = keywords + .iter() + .enumerate() + .map(|(i, _)| format!("(content LIKE ?{} OR key LIKE ?{})", i * 2 + 1, i * 2 + 2)) + .collect(); + let where_clause = conditions.join(" OR "); + let sql = format!( + "SELECT id, key, content, category, created_at, session_id, useful_count FROM memories + WHERE {where_clause} + ORDER BY updated_at DESC + LIMIT ?{}", + keywords.len() * 2 + 1 + ); + let mut stmt = conn.prepare(&sql)?; + let mut param_values: Vec> = Vec::new(); + for kw in &keywords { + param_values.push(Box::new(kw.clone())); + param_values.push(Box::new(kw.clone())); + } + #[allow(clippy::cast_possible_wrap)] + param_values.push(Box::new(limit as i64)); + let params_ref: Vec<&dyn rusqlite::types::ToSql> = param_values.iter().map(AsRef::as_ref).collect(); + let rows = stmt.query_map(params_ref.as_slice(), |row| { + Ok(MemoryEntry { + origin: crate::memory::traits::MemoryEntryOrigin::Stored, + source_event_id: None, + id: row.get(0)?, + key: row.get(1)?, + content: row.get(2)?, + category: Self::str_to_category(&row.get::<_, String>(3)?), + timestamp: row.get(4)?, + session_id: row.get(5)?, + score: Some(1.0), + tags: None, + access_count: None, + useful_count: row.get(6)?, + source: None, + source_confidence: None, + verification_status: None, + lifecycle_state: None, + compressed_from: None, + }) + })?; + for row in rows { + let entry = row?; + if let Some(sid) = session_ref { + if entry.session_id.as_deref() != Some(sid) { + continue; + } + } + results.push(entry); + } + } + } + + results.truncate(limit); + Ok(results) + }) + .await? + } + + pub(super) async fn recall_with_context_impl( + &self, + query: &str, + limit: usize, + session_id: Option<&str>, + context: Option<&MemoryWriteContext>, + ) -> anyhow::Result> { + let Some(context) = context.cloned() else { + return self.recall(query, limit, session_id).await; + }; + + let mut entries = self + .recall(query, limit.saturating_mul(3).max(limit), session_id) + .await?; + if entries.is_empty() { + return Ok(entries); + } + + let pool = self.pool.clone(); + let capped_limit = limit; + + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { + let reader = pool.read()?; + let conn = reader.connection()?; + let principal = sqlite_read_principal(&conn, &context); + // FIX-P1-06: the Anonymous `(channel, chat_id, raw_sender)` triple is + // now produced by `build_sql_scope` itself, so all roles share the + // single scope builder (no hardcoded branch). + let (scope_sql, scope_params) = principal.build_sql_scope(); + + let mut allowed_ids = std::collections::HashSet::new(); + if !entries.is_empty() { + let id_placeholders = (0..entries.len()).map(|_| "?").collect::>().join(","); + let (partition_sql, partition_params) = + memory_partition_conjunct(super::events::MA_SCOPE_COLUMN, context.agent_partition.as_ref()); + let sql = format!( + "SELECT id, source_event_id FROM memories WHERE id IN ({id_placeholders}) AND ({scope_sql}){partition_sql}" + ); + let mut params = entries + .iter() + .map(|entry| Value::from(entry.id.clone())) + .collect::>(); + params.extend(scope_params); + params.extend(partition_params); + let mut stmt = conn.prepare(&sql)?; + let rows = stmt.query_map(params_from_iter(params), |row| { + Ok((row.get::<_, String>(0)?, row.get::<_, Option>(1)?)) + })?; + for row in rows { + let (id, event) = row?; + for entry in &mut entries { + if entry.id == id { + entry.source_event_id = event.clone(); + } + } + allowed_ids.insert(id); + } + } + + let visible = entries + .into_iter() + .filter(|entry| allowed_ids.contains(&entry.id)) + .collect::>(); + let mut visible = post_filter(visible, &principal, |entry| entry.content.as_str()); + visible.truncate(capped_limit); + Ok(visible) + }) + .await? + } + + pub(super) async fn count_rehearsal_hits_impl( + &self, + query: &str, + limit: u8, + context: &MemoryWriteContext, + deadline: std::time::Instant, + ) -> anyhow::Result { + anyhow::ensure!( + query.len() <= 1_024 && (1..=16).contains(&limit), + "invalid rehearsal count bounds" + ); + anyhow::ensure!(std::time::Instant::now() < deadline, "rehearsal count deadline expired"); + let fts_query = crate::memory::topic::build_safe_fts_query(query); + if fts_query.is_empty() { + return Ok(0); + } + let db_path = self.db_path.clone(); + let context = context.clone(); + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result { + anyhow::ensure!(std::time::Instant::now() < deadline, "rehearsal count deadline expired"); + // A dedicated read-only connection cannot wait for a pooled reader + // after the decision deadline. SQLite itself interrupts slow FTS. + let conn = Self::open_rehearsal_reader(&db_path, deadline)?; + let principal = sqlite_read_principal(&conn, &context); + anyhow::ensure!(std::time::Instant::now() < deadline, "rehearsal count deadline expired"); + let (scope_sql, scope_params) = principal.build_sql_scope(); + let (partition_sql, partition_params) = + memory_partition_conjunct(MEMORY_ALIAS_SCOPE_COLUMN, context.agent_partition.as_ref()); + let sql = format!( + "SELECT m.content FROM memories_fts f JOIN memories m ON m.rowid = f.rowid \ + WHERE memories_fts MATCH ? AND ({scope_sql}){partition_sql} \ + AND length(CAST(m.content AS BLOB)) <= 4096 \ + ORDER BY bm25(memories_fts) LIMIT ?" + ); + let mut params = Vec::with_capacity(scope_params.len() + partition_params.len() + 2); + params.push(Value::from(fts_query)); + params.extend(scope_params); + params.extend(partition_params); + params.push(Value::from(i64::from(limit) * 3)); + let mut stmt = conn.prepare(&sql)?; + let rows = stmt.query_map(params_from_iter(params), |row| row.get::<_, String>(0))?; + let candidates = rows.collect::>>()?; + anyhow::ensure!(std::time::Instant::now() < deadline, "rehearsal count deadline expired"); + let visible = post_filter(candidates, &principal, String::as_str); + anyhow::ensure!(std::time::Instant::now() < deadline, "rehearsal count deadline expired"); + Ok(u32::try_from(visible.len().min(usize::from(limit)))?) + }) + .await? + } + + pub(super) async fn retrieve_decision_memory_impl( + &self, + query: &str, + limit: u8, + context: &MemoryWriteContext, + session_id: Option<&str>, + deadline: std::time::Instant, + ) -> anyhow::Result> { + anyhow::ensure!( + query.len() <= 1_024 && (1..=5).contains(&limit), + "invalid decision Memory bounds" + ); + anyhow::ensure!(std::time::Instant::now() < deadline, "decision Memory deadline expired"); + anyhow::ensure!( + session_id.is_none_or(|id| !id.is_empty() && id.len() <= 512), + "invalid decision Memory session" + ); + let fts_query = crate::memory::topic::build_safe_fts_query(query); + if fts_query.is_empty() { + return Ok(Vec::new()); + } + let session_id = session_id.map(str::to_owned); + let db_path = self.db_path.clone(); + let context = context.clone(); + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { + anyhow::ensure!(std::time::Instant::now() < deadline, "decision Memory deadline expired"); + let conn = Self::open_rehearsal_reader(&db_path, deadline)?; + let principal = sqlite_read_principal(&conn, &context); + let (scope_sql, scope_params) = principal.build_sql_scope(); + let (partition_sql, partition_params) = + memory_partition_conjunct(MEMORY_ALIAS_SCOPE_COLUMN, context.agent_partition.as_ref()); + let sql = format!( + "SELECT m.id, m.content, m.created_at, m.source_event_id, m.key, m.category, m.session_id FROM memories_fts f JOIN memories m ON m.rowid = f.rowid \ + WHERE memories_fts MATCH ? AND ({scope_sql}){partition_sql} \ + AND length(CAST(m.id AS BLOB)) <= 128 \ + AND length(CAST(m.content AS BLOB)) <= 4096 \ + AND length(CAST(m.created_at AS BLOB)) <= 64 \ + AND (m.source_event_id IS NULL OR length(CAST(m.source_event_id AS BLOB)) <= 128) \ + AND length(CAST(m.key AS BLOB)) <= 1024 AND length(CAST(m.category AS BLOB)) <= 128 \ + AND (m.session_id IS NULL OR length(CAST(m.session_id AS BLOB)) <= 512) \ + AND (? IS NULL OR m.session_id = ?) \ + ORDER BY bm25(memories_fts) LIMIT ?" + ); + let mut params = Vec::with_capacity(scope_params.len() + partition_params.len() + 4); + params.push(Value::from(fts_query)); + params.extend(scope_params); + params.extend(partition_params); + params.push(session_id.clone().map(Value::from).unwrap_or(Value::Null)); + params.push(session_id.map(Value::from).unwrap_or(Value::Null)); + params.push(Value::from(i64::from(limit) * 3)); + let mut stmt = conn.prepare(&sql)?; + let rows = stmt.query_map(params_from_iter(params), |row| { + Ok(DecisionMemoryHit { + id: row.get(0)?, + content: row.get(1)?, + created_at: row.get(2)?, + source_event_id: row.get(3)?, + key: row.get(4)?, category: Self::str_to_category(&row.get::<_, String>(5)?), + session_id: row.get(6)?, + }) + })?; + let candidates = rows.collect::>>()?; + anyhow::ensure!(std::time::Instant::now() < deadline, "decision Memory deadline expired"); + let mut visible = post_filter(candidates, &principal, |hit| hit.content.as_str()); + visible.truncate(usize::from(limit)); + anyhow::ensure!(std::time::Instant::now() < deadline, "decision Memory deadline expired"); + Ok(visible) + }) + .await? + } + + pub(super) async fn recall_with_context_mode_impl( + &self, + query: &str, + limit: usize, + session_id: Option<&str>, + context: Option<&MemoryWriteContext>, + mode: MemoryReadMode, + ) -> anyhow::Result> { + let context = context.cloned().unwrap_or_default(); + // C03 / V02-R5 defence in depth: an owner-isolated context is enforced + // whatever mode was requested. The tool already selects Enforce for an + // isolated caller; the backend must not be talked out of it by a + // caller, a config flag or a future call site. + let mode = if context.require_owner_match { + MemoryReadMode::Enforce + } else { + mode + }; + // MA-01h: the partition is not an ACL tier; Observe mode never reads + // past it. + let unrestricted = self.recall(query, limit, session_id).await?; + let unrestricted = self + .retain_in_partition(unrestricted, context.agent_partition.clone()) + .await?; + let scoped = self + .recall_with_context(query, limit, session_id, Some(&context)) + .await?; + let pool = self.pool.clone(); + let query_owned = query.to_string(); + let query_for_topics = query_owned.clone(); + let mut selected = match mode { + MemoryReadMode::Enforce => scoped.clone(), + MemoryReadMode::Observe => unrestricted.clone(), + }; + let mut selected_ids = selected + .iter() + .map(|entry| entry.id.clone()) + .collect::>(); + let topic_rows = + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result<(Vec, Principal)> { + let reader = pool.read()?; + let conn = reader.connection()?; + let principal = sqlite_read_principal(&conn, &context); + let topic_principal = match mode { + MemoryReadMode::Enforce => principal.clone(), + MemoryReadMode::Observe => sqlite_owner_read_principal(), + }; + let mut rows = Vec::new(); + for topic in crate::memory::topic::search_topics_fts(&conn, &query_for_topics, 3)? { + for entry in + crate::memory::topic::query_topic_context(&conn, &topic.id, &topic_principal, limit.max(1))? + { + rows.push(MemoryEntry { + origin: crate::memory::traits::MemoryEntryOrigin::Stored, + source_event_id: None, + id: entry.id, + key: entry.key, + content: entry.content, + category: MemoryCategory::Conversation, + timestamp: entry.created_at, + session_id: None, + score: Some(0.55), + tags: None, + access_count: None, + useful_count: None, + source: Some("topic_projection".to_string()), + source_confidence: None, + verification_status: None, + lifecycle_state: None, + compressed_from: None, + }); + } + } + let rows = retain_partition_entries(&conn, rows, context.agent_partition.as_ref())?; + Ok((rows, principal)) + }) + .await??; + for entry in topic_rows.0 { + if selected_ids.insert(entry.id.clone()) { + selected.push(entry); + } + } + selected.sort_by(|left, right| { + right + .score + .unwrap_or(0.0) + .partial_cmp(&left.score.unwrap_or(0.0)) + .unwrap_or(std::cmp::Ordering::Equal) + .then_with(|| left.key.cmp(&right.key)) + }); + selected.truncate(limit.max(1)); + + let would_deny = unrestricted + .iter() + .any(|entry| !scoped.iter().any(|allowed| allowed.id == entry.id)); + let pool = self.pool.clone(); + let principal = topic_rows.1; + let selected_empty = selected.is_empty(); + crate::runtime::blocking::spawn_blocking(move || { + let conn = pool.write(); + log_access( + &conn, + &principal, + "search", + Some(&query_owned), + None, + Some(match mode { + MemoryReadMode::Enforce => "acl_enforced", + MemoryReadMode::Observe => "observe_mode", + }), + if mode == MemoryReadMode::Observe && would_deny { + "would_deny" + } else if selected_empty { + "no_results" + } else { + "allowed" + }, + ); + }) + .await?; + Ok(selected) + } + + pub(super) async fn get_impl(&self, key: &str) -> anyhow::Result> { + let pool = self.pool.clone(); + let key = key.to_string(); + + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { + let reader = pool.read()?; + let conn = reader.connection()?; + let mut stmt = conn.prepare( + "SELECT id, key, content, category, created_at, session_id, useful_count FROM memories WHERE key = ?1", + )?; + + let mut rows = stmt.query_map(params![key], |row| { + Ok(MemoryEntry { + origin: crate::memory::traits::MemoryEntryOrigin::Stored, + source_event_id: None, + id: row.get(0)?, + key: row.get(1)?, + content: row.get(2)?, + category: Self::str_to_category(&row.get::<_, String>(3)?), + timestamp: row.get(4)?, + session_id: row.get(5)?, + score: None, + tags: None, + access_count: None, + useful_count: row.get(6)?, + source: None, + source_confidence: None, + verification_status: None, + lifecycle_state: None, + compressed_from: None, + }) + })?; + + match rows.next() { + Some(Ok(entry)) => Ok(Some(entry)), + _ => Ok(None), + } + }) + .await? + } + + pub(super) async fn get_with_context_impl( + &self, + key: &str, + context: Option<&MemoryWriteContext>, + ) -> anyhow::Result> { + let context = context.cloned().unwrap_or_default(); + let pool = self.pool.clone(); + let key = key.to_string(); + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { + let reader = pool.read()?; + let conn = reader.connection()?; + let principal = sqlite_read_principal(&conn, &context); + let (scope_sql, scope_params) = principal.build_sql_scope(); + let (partition_sql, partition_params) = + memory_partition_conjunct(super::events::MA_SCOPE_COLUMN, context.agent_partition.as_ref()); + let mut query_params = Vec::with_capacity(scope_params.len() + partition_params.len() + 1); + query_params.push(Value::from(key.clone())); + query_params.extend(scope_params); + query_params.extend(partition_params); + let sql = format!( + "SELECT id, key, content, category, created_at, session_id, useful_count + FROM memories WHERE key = ?1 AND ({scope_sql}){partition_sql} LIMIT 1" + ); + let entry = conn + .query_row(&sql, params_from_iter(query_params), |row| { + Ok(MemoryEntry { + origin: crate::memory::traits::MemoryEntryOrigin::Stored, + source_event_id: None, + id: row.get(0)?, + key: row.get(1)?, + content: row.get(2)?, + category: Self::str_to_category(&row.get::<_, String>(3)?), + timestamp: row.get(4)?, + session_id: row.get(5)?, + score: None, + tags: None, + access_count: None, + useful_count: row.get(6)?, + source: None, + source_confidence: None, + verification_status: None, + lifecycle_state: None, + compressed_from: None, + }) + }) + .optional()?; + let mut visible = post_filter(entry.into_iter().collect(), &principal, |entry| entry.content.as_str()); + Ok(visible.pop()) + }) + .await? + } + + pub(super) async fn get_with_context_mode_impl( + &self, + key: &str, + context: Option<&MemoryWriteContext>, + mode: MemoryReadMode, + ) -> anyhow::Result> { + let context = context.cloned().unwrap_or_default(); + // C03 / V02-R5: see `recall_with_context_mode` — isolation outranks the + // requested mode. + let mode = if context.require_owner_match { + MemoryReadMode::Enforce + } else { + mode + }; + let scoped = self.get_with_context(key, Some(&context)).await?; + let unrestricted = self.get(key).await?; + // MA-01h: as in `recall_with_context_mode`, Observe never reads past the partition. + let unrestricted = self + .retain_in_partition(unrestricted.into_iter().collect(), context.agent_partition.clone()) + .await? + .pop(); + let selected = match mode { + MemoryReadMode::Enforce => scoped.clone(), + MemoryReadMode::Observe => unrestricted.clone(), + }; + let would_deny = unrestricted.is_some() && scoped.is_none(); + let memory_id = selected.as_ref().map(|entry| entry.id.clone()); + let selected_is_some = selected.is_some(); + let key = key.to_string(); + let pool = self.pool.clone(); + crate::runtime::blocking::spawn_blocking(move || { + let conn = pool.write(); + let principal = sqlite_read_principal(&conn, &context); + log_access( + &conn, + &principal, + "get", + None, + memory_id.as_deref().or(Some(key.as_str())), + Some(match mode { + MemoryReadMode::Enforce => "acl_enforced", + MemoryReadMode::Observe => "observe_mode", + }), + if mode == MemoryReadMode::Observe && would_deny { + "would_deny" + } else if selected_is_some { + "allowed" + } else { + "denied" + }, + ); + }) + .await?; + Ok(selected) + } + + pub(super) async fn list_impl( + &self, + category: Option<&MemoryCategory>, + session_id: Option<&str>, + ) -> anyhow::Result> { + const DEFAULT_LIST_LIMIT: i64 = 1000; + + let pool = self.pool.clone(); + let category = category.cloned(); + let sid = session_id.map(String::from); + + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { + let reader = pool.read()?; + let conn = reader.connection()?; + let session_ref = sid.as_deref(); + let mut results = Vec::new(); + + let row_mapper = |row: &rusqlite::Row| -> rusqlite::Result { + Ok(MemoryEntry { + origin: crate::memory::traits::MemoryEntryOrigin::Stored, + source_event_id: None, + id: row.get(0)?, + key: row.get(1)?, + content: row.get(2)?, + category: Self::str_to_category(&row.get::<_, String>(3)?), + timestamp: row.get(4)?, + session_id: row.get(5)?, + score: None, + tags: None, + access_count: None, + useful_count: row.get(6)?, + source: None, + source_confidence: None, + verification_status: None, + lifecycle_state: None, + compressed_from: None, + }) + }; + + if let Some(ref cat) = category { + let cat_str = Self::category_to_str(cat); + let mut stmt = conn.prepare( + "SELECT id, key, content, category, created_at, session_id, useful_count FROM memories + WHERE category = ?1 ORDER BY updated_at DESC LIMIT ?2", + )?; + let rows = stmt.query_map(params![cat_str, DEFAULT_LIST_LIMIT], row_mapper)?; + for row in rows { + let entry = row?; + if let Some(sid) = session_ref { + if entry.session_id.as_deref() != Some(sid) { + continue; + } + } + results.push(entry); + } + } else { + let mut stmt = conn.prepare( + "SELECT id, key, content, category, created_at, session_id, useful_count FROM memories + ORDER BY updated_at DESC LIMIT ?1", + )?; + let rows = stmt.query_map(params![DEFAULT_LIST_LIMIT], row_mapper)?; + for row in rows { + let entry = row?; + if let Some(sid) = session_ref { + if entry.session_id.as_deref() != Some(sid) { + continue; + } + } + results.push(entry); + } + } + + Ok(results) + }) + .await? + } + + pub(super) async fn list_owner_ids_impl( + &self, + category: &MemoryCategory, + ) -> anyhow::Result>>> { + let pool = self.pool.clone(); + let category = Self::category_to_str(category); + crate::runtime::blocking::spawn_blocking( + move || -> anyhow::Result>>> { + let reader = pool.read()?; + let conn = reader.connection()?; + let mut stmt = conn.prepare("SELECT id, owner_id FROM memories WHERE category = ?1")?; + let owners = stmt + .query_map(params![category], |row| Ok((row.get(0)?, row.get(1)?)))? + .collect::>>>()?; + Ok(Some(owners)) + }, + ) + .await? + } + + pub(super) async fn forget_with_context_impl( + &self, + key: &str, + context: Option<&MemoryWriteContext>, + ) -> anyhow::Result { + let Some(context) = context.cloned() else { + return self.forget(key).await; + }; + + let pool = self.pool.clone(); + let key = key.to_string(); + + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result { + let conn = pool.write(); + let principal = sqlite_read_principal(&conn, &context); + // FIX-P1-06: unified scope builder for all roles (see recall_with_context). + let (scope_sql, scope_params) = principal.build_sql_scope(); + // R-B1d D-1: the delete guard. The fixed parameter is ?1 = key and + // the scope predicate occupies ?2..; the owner guard therefore + // binds at the next free index and its value is appended last, so + // the template order is preserved. + let owner_anchor = Self::forget_owner_anchor(&context); + let owner_guard = Self::forget_owner_guard(&context, scope_params.len() + 2); + // MA-01h: a partitioned caller deletes only a row of its own partition. + // The conjunct's bare markers follow every numbered one. + let (partition_sql, partition_params) = + memory_partition_conjunct(super::events::MA_SCOPE_COLUMN, context.agent_partition.as_ref()); + let mut query_params = Vec::with_capacity(scope_params.len() + partition_params.len() + 2); + query_params.push(Value::from(key.clone())); + query_params.extend(scope_params); + if let (true, Some(owner)) = (owner_guard.bound_owner, owner_anchor.as_deref()) { + query_params.push(Value::from(owner.to_string())); + } + query_params.extend(partition_params); + let owner_guard_sql = owner_guard.sql; + let query = format!( + "SELECT id FROM memories WHERE key = ?1 AND ({scope_sql}){owner_guard_sql}{partition_sql} LIMIT 1" + ); + let visible_id = conn + .query_row(&query, params_from_iter(query_params), |row| row.get::<_, String>(0)) + .optional()?; + + let Some(memory_id) = visible_id else { + log_access(&conn, &principal, "forget", Some(&key), None, None, "denied"); + return Ok(false); + }; + + let affected = conn.execute("DELETE FROM memories WHERE id = ?1", params![memory_id])?; + log_access( + &conn, + &principal, + "forget", + Some(&key), + Some(&memory_id), + None, + "allowed", + ); + Ok(affected > 0) + }) + .await? + } + + pub(super) async fn move_to_trash_impl( + &self, + key: &str, + reason: &str, + grace_days: u32, + ) -> anyhow::Result> { + let pool = self.pool.clone(); + let key = key.to_string(); + let reason = reason.to_string(); + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result> { + let conn = pool.write(); + let tx = begin_immediate(&conn)?; + // FIX-P1-11: snapshot the row's value before soft-deleting it. We DO NOT + // physically delete from `memories`; we record a trash row so it can be + // restored within the grace window. Parent stamp is read inside the + // writer transaction (review M3). + let row: Option<(String, String, Option)> = tx + .query_row( + "SELECT content, category, ma_scope_id FROM memories WHERE key = ?1", + params![key], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), + ) + .optional()?; + let Some((content, category, ma_scope_id)) = row else { + return Ok(None); + }; + // Idempotency: if an unrestored trash entry already exists for this key, + // return it rather than duplicating. + let existing: Option = tx + .query_row( + "SELECT trash_id FROM memory_trash WHERE memory_key = ?1 AND restored_at IS NULL LIMIT 1", + params![key], + |row| row.get(0), + ) + .optional()?; + if let Some(trash_id) = existing { + return Ok(Some(trash_id)); + } + let trash_id = format!("trash-{}", Uuid::now_v7()); + let now = Utc::now(); + let grace_until = now + chrono::Duration::days(i64::from(grace_days)); + tx.execute( + "INSERT INTO memory_trash ( + trash_id, memory_key, content, category, reason, trashed_at, grace_until, ma_scope_id + ) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", + params![ + trash_id, + key, + content, + category, + reason, + now.to_rfc3339(), + grace_until.to_rfc3339(), + ma_scope_id, + ], + )?; + tx.commit()?; + Ok(Some(trash_id)) + }) + .await? + } + + pub(super) async fn increment_useful_count_impl(&self, id: &str) -> anyhow::Result<()> { + let pool = self.pool.clone(); + let id = id.to_string(); + + crate::runtime::blocking::spawn_blocking(move || -> anyhow::Result<()> { + let conn = pool.write(); + conn.execute( + "UPDATE memories + SET useful_count = COALESCE(useful_count, 0) + 1, + updated_at = ?1 + WHERE id = ?2", + params![Local::now().to_rfc3339(), id], + )?; + Ok(()) + }) + .await? + } +} diff --git a/src/memory/sqlite/terminal_epoch.rs b/src/memory/sqlite/terminal_epoch.rs new file mode 100644 index 000000000..0da33392b --- /dev/null +++ b/src/memory/sqlite/terminal_epoch.rs @@ -0,0 +1,92 @@ +//! Process-local write epochs pinned by authenticated terminal sessions. +use super::{SqliteMemory, agent_migration}; +use crate::memory::{AgentPartition, AgentScopeRefused, PartitionKey, principal::MemoryWriteContext}; +use rusqlite::{Connection, params}; +use std::{collections::HashMap, path::Path, sync::OnceLock}; + +type Key = (String, String, String); +static EPOCHS: OnceLock>> = OnceLock::new(); +const MAX_EPOCHS: usize = 4096; + +pub(crate) fn pin(memory: &SqliteMemory, partition: &AgentPartition, session: &str) -> anyhow::Result<()> { + anyhow::ensure!(matches!(partition.key, PartitionKey::Main), AgentScopeRefused); + let writer = memory.pool.write(); + let scope = agent_migration::lookup_or_mint_write_scope(&writer, partition, Some(session))?; + let key = ( + partition.workspace_id.clone(), + partition.owner_id.clone(), + session.to_owned(), + ); + let mut epochs = EPOCHS.get_or_init(Default::default).lock(); + if let Some(pinned) = epochs.get(&key) { + anyhow::ensure!(pinned == &scope, AgentScopeRefused); + } else { + anyhow::ensure!(epochs.len() < MAX_EPOCHS, AgentScopeRefused); + epochs.insert(key, scope); + } + Ok(()) +} + +/// Called inside each writing transaction, before resolving a replacement scope. +pub(super) fn check( + conn: &Connection, + workspace: &str, + owner: Option<&str>, + session: Option<&str>, +) -> anyhow::Result<()> { + let (Some(epochs), Some(owner), Some(session)) = (EPOCHS.get(), owner, session) else { + return Ok(()); + }; + let scope = epochs + .lock() + .get(&(workspace.into(), owner.into(), session.into())) + .cloned(); + if let Some(scope) = scope { + let live: bool = conn.query_row( + "SELECT EXISTS(SELECT 1 FROM agent_scopes s WHERE s.scope_id=?1 AND s.workspace_id=?2 AND s.owner_id=?3 AND s.session_key=?4 AND NOT EXISTS(SELECT 1 FROM agent_erase_fences f WHERE f.scope_id=s.scope_id))", + params![scope,workspace,owner,session], |row|row.get(0))?; + anyhow::ensure!(live, AgentScopeRefused); + } + Ok(()) +} + +/// Snapshot keys are runtime-authored; authority comes only from the pinned map. +pub(super) fn snapshot_context( + path: &Path, + key: &str, + session: Option<&str>, +) -> anyhow::Result> { + let Some(id) = key.strip_prefix("chat_session:") else { + return Ok(None); + }; + let Some(workspace) = path.parent().and_then(Path::parent).and_then(Path::to_str) else { + return Ok(None); + }; + let canonical = format!("chat:terminal:local-user:{id}"); + let Some(epochs) = EPOCHS.get() else { + return Ok(None); + }; + let bound = epochs + .lock() + .keys() + .find(|(w, _, s)| w == workspace && s == &canonical) + .cloned(); + let Some((workspace, owner, session_key)) = bound else { + return Ok(None); + }; + anyhow::ensure!( + session.is_none_or(|session| session == id || session == session_key), + AgentScopeRefused + ); + Ok(Some(MemoryWriteContext { + workspace_id: Some(workspace.clone()), + owner_id: Some(owner.clone()), + session_key: Some(session_key), + agent_partition: Some(AgentPartition { + workspace_id: workspace, + owner_id: owner, + key: PartitionKey::Main, + }), + ..MemoryWriteContext::default() + })) +} diff --git a/src/runtime/mode.rs b/src/runtime/mode.rs index b2d2e6500..ce800d062 100644 --- a/src/runtime/mode.rs +++ b/src/runtime/mode.rs @@ -126,17 +126,28 @@ impl ModeRunner for ChatRunner { (None, None) => {} _ => anyhow::bail!("controlled H2 chat requires both explicit ceilings and authority lifetime"), } - chat::run( - me.config, - me.provider, - me.model, - me.temperature, - me.plain, - me.session.or_else(|| me.continue_last.then(|| "last".to_string())), - me.list_sessions, - shutdown, - ) - .await + let mut session = me.session.or_else(|| me.continue_last.then(|| "last".to_string())); + loop { + let result = chat::run( + me.config.clone(), + me.provider.clone(), + me.model.clone(), + me.temperature, + me.plain, + session.clone(), + me.list_sessions, + shutdown.child_token(), + ) + .await; + match result { + Err(error) if error.is::() && !shutdown.is_cancelled() => { + // The old chat drained before returning this marker. A new + // identity cannot inherit callbacks or cached erased text. + session = None; + } + result => return result, + } + } } } diff --git a/tests/architecture_boundaries/helpers.rs b/tests/architecture_boundaries/helpers.rs index becf50049..850668fbc 100644 --- a/tests/architecture_boundaries/helpers.rs +++ b/tests/architecture_boundaries/helpers.rs @@ -43,6 +43,10 @@ pub(super) fn rust_source_files() -> Vec { ![ "src/config/secret_paths/tests/section_1.rs", "src/config/secret_paths/tests/section_2.rs", + "src/agent/entry/section_1.rs", + "src/agent/entry/section_2.rs", + "src/memory/sqlite/recall/section_1.rs", + "src/memory/sqlite/recall/section_2.rs", "src/config/generation/section_1.rs", "src/config/generation/section_2.rs", "src/chat/provider_turns/section_1.rs", @@ -147,6 +151,10 @@ pub(super) fn read_source(path: &Path) -> String { ("src/memory/sqlite/tests/mailbox.rs", "mailbox/section_1.rs"), ("src/memory/sqlite/tests/mailbox.rs", "mailbox/section_2.rs"), ("src/memory/sqlite/tests/mailbox.rs", "mailbox/section_3.rs"), + ("src/memory/sqlite/recall.rs", "recall/section_1.rs"), + ("src/memory/sqlite/recall.rs", "recall/section_2.rs"), + ("src/agent/entry.rs", "entry/section_1.rs"), + ("src/agent/entry.rs", "entry/section_2.rs"), ("src/runtime/manage_cli.rs", "manage_cli/section_1.rs"), ("src/runtime/manage_cli.rs", "manage_cli/section_2.rs"), ("src/tools/execution.rs", "execution/section_1.rs"), @@ -175,6 +183,10 @@ pub(super) fn rust_source_and_test_files() -> Vec { ![ "src/config/secret_paths/tests/section_1.rs", "src/config/secret_paths/tests/section_2.rs", + "src/agent/entry/section_1.rs", + "src/agent/entry/section_2.rs", + "src/memory/sqlite/recall/section_1.rs", + "src/memory/sqlite/recall/section_2.rs", "src/config/generation/section_1.rs", "src/config/generation/section_2.rs", "src/chat/provider_turns/section_1.rs", diff --git a/tests/architecture_boundaries/loop_prompt.rs b/tests/architecture_boundaries/loop_prompt.rs index 6de68bc8a..430da4927 100644 --- a/tests/architecture_boundaries/loop_prompt.rs +++ b/tests/architecture_boundaries/loop_prompt.rs @@ -194,7 +194,7 @@ pub(super) fn outbound_middleware_has_one_production_owner() { #[test] fn production_tool_loop_memory_is_wired_to_request_context_events() { for relative in [ - "src/agent/entry.rs", + "src/agent/entry/section_2.rs", "src/channels/turn.rs", "src/chat/run/provider_turn.rs", "src/gateway/api/sessions/section_1.rs", @@ -242,7 +242,7 @@ pub(super) const REVIEWED_DECISION_HANDOFFS: &[(&str, usize, &str)] = &[ "crate::agent::turn_request::TurnDecision{service:&service,context:&decision,runtime:decision.runtime(),proof:source,}", ), ( - "src/agent/entry.rs", + "src/agent/entry/section_2.rs", 1, "crate::agent::turn_request::TurnDecision{service:decision_service,context:decision_context,runtime:decision_context.runtime(),proof:decision_proof,}", ), diff --git a/tests/architecture_boundaries/memory.rs b/tests/architecture_boundaries/memory.rs index 13bb446da..fe4ea0f50 100644 --- a/tests/architecture_boundaries/memory.rs +++ b/tests/architecture_boundaries/memory.rs @@ -171,6 +171,8 @@ const SQLITE_BACKEND_FILES: &[&str] = &[ /// Older child modules that were never part of the exemption for the /// repository root and stay scanned like any other file. const SQLITE_SEPARATE_MODULES: &[&str] = &[ + "history_retention.rs", + "terminal_epoch.rs", "agent_purge.rs", // R3d transactional branch copy; runs on the backend's pool, opens nothing. "branch_copy.rs", @@ -460,7 +462,7 @@ fn runtime_and_message_events_preserve_typed_config_generation_columns() { } } - for relative in ["src/agent/entry.rs", "src/chat/binding.rs"] { + for relative in ["src/agent/entry/section_1.rs", "src/chat/binding.rs"] { let source = fs::read_to_string(repository_root().join(relative)) .unwrap_or_else(|error| panic!("read {relative}: {error}")); assert!( diff --git a/tests/architecture_boundaries/process.rs b/tests/architecture_boundaries/process.rs index 95e041282..ba3f3b459 100644 --- a/tests/architecture_boundaries/process.rs +++ b/tests/architecture_boundaries/process.rs @@ -217,7 +217,7 @@ fn every_live_hook_manager_owner_drains_at_shutdown() { "src/gateway/implementation/section_2.rs", "src/channels/startup.rs", "src/chat/run.rs", - "src/agent/entry.rs", + "src/agent/entry/section_2.rs", "src/session_worker/runner/run.rs", ] { let source = From 4493d6a6bfa92f89b3ebdc803ddb3e83fe6f275e Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Tue, 24 Nov 2026 00:53:21 +0400 Subject: [PATCH 0045/1567] chore(architecture): preserve entry checks after source split --- tests/architecture_boundaries/loop_prompt.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/architecture_boundaries/loop_prompt.rs b/tests/architecture_boundaries/loop_prompt.rs index 430da4927..cdadb6b62 100644 --- a/tests/architecture_boundaries/loop_prompt.rs +++ b/tests/architecture_boundaries/loop_prompt.rs @@ -194,7 +194,7 @@ pub(super) fn outbound_middleware_has_one_production_owner() { #[test] fn production_tool_loop_memory_is_wired_to_request_context_events() { for relative in [ - "src/agent/entry/section_2.rs", + "src/agent/entry/section_1.rs", "src/channels/turn.rs", "src/chat/run/provider_turn.rs", "src/gateway/api/sessions/section_1.rs", @@ -242,7 +242,7 @@ pub(super) const REVIEWED_DECISION_HANDOFFS: &[(&str, usize, &str)] = &[ "crate::agent::turn_request::TurnDecision{service:&service,context:&decision,runtime:decision.runtime(),proof:source,}", ), ( - "src/agent/entry/section_2.rs", + "src/agent/entry.rs", 1, "crate::agent::turn_request::TurnDecision{service:decision_service,context:decision_context,runtime:decision_context.runtime(),proof:decision_proof,}", ), From 99e9cc2e3f48095837873cd78b4e5b477cbe0640 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Tue, 24 Nov 2026 01:06:02 +0400 Subject: [PATCH 0046/1567] fix(history): fence direct scope lookups and branch snapshots --- src/chat/run/commands.rs | 2 ++ src/memory/sqlite/agent_migration.rs | 1 + 2 files changed, 3 insertions(+) diff --git a/src/chat/run/commands.rs b/src/chat/run/commands.rs index 6df02e61d..28f44a97e 100644 --- a/src/chat/run/commands.rs +++ b/src/chat/run/commands.rs @@ -641,6 +641,8 @@ Retry with a compatible model: /provider {shown} ", // The branch's own transcript rows (handoff chain and // retained turns) commit in one transaction before the // branch session exists; any failure aborts the branch. + let branch_key = crate::runtime::envelope::RuntimeEnvelope::chat_canonical_session_key(&branch.id); + super::message_inbox::pin_epoch(&config, &branch_key).await?; if let Err(e) = super::branch_copy::copy_branch_transcript( mem.as_ref(), memory_fabric.workspace_id(), diff --git a/src/memory/sqlite/agent_migration.rs b/src/memory/sqlite/agent_migration.rs index e68cf8d58..29fa62462 100644 --- a/src/memory/sqlite/agent_migration.rs +++ b/src/memory/sqlite/agent_migration.rs @@ -135,6 +135,7 @@ pub(super) fn lookup_write_scope( partition: &AgentPartition, session_key: Option<&str>, ) -> anyhow::Result> { + super::terminal_epoch::check(conn, &partition.workspace_id, Some(&partition.owner_id), session_key)?; let session = require_session(session_key)?; let workspace = partition.workspace_id.as_str(); let owner = partition.owner_id.as_str(); From 7d22e5fdee8f4057dba109aa1e37592bf4173160 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Tue, 24 Nov 2026 01:14:21 +0400 Subject: [PATCH 0047/1567] fix(chat): bind the resolved owner on scoped tool events --- src/chat/chat_events.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/chat/chat_events.rs b/src/chat/chat_events.rs index 33eee3c2c..c0950053a 100644 --- a/src/chat/chat_events.rs +++ b/src/chat/chat_events.rs @@ -92,7 +92,9 @@ pub(crate) fn chat_runtime_envelope(workspace_id: &str, chat_session_key: &str) owner_id: envelope.resolved_owner_id(), key: crate::memory::PartitionKey::Main, }; - envelope.with_agent_partition(partition) + envelope + .with_owner_id(partition.owner_id.clone()) + .with_agent_partition(partition) } #[cfg(test)] From c5469a51474ba77f45655419e39eeb49d34d8a29 Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Tue, 24 Nov 2026 01:17:25 +0400 Subject: [PATCH 0048/1567] fix(history): stamp terminal metadata from its authenticated epoch --- src/memory/sqlite/agent_migration.rs | 2 ++ src/memory/sqlite/terminal_epoch.rs | 16 ++++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/src/memory/sqlite/agent_migration.rs b/src/memory/sqlite/agent_migration.rs index 29fa62462..2033bdbe2 100644 --- a/src/memory/sqlite/agent_migration.rs +++ b/src/memory/sqlite/agent_migration.rs @@ -211,6 +211,8 @@ pub(super) fn resolve_input_scope( owner_id: Option<&str>, ) -> anyhow::Result> { super::terminal_epoch::check(tx, workspace_id, owner_id, session_key)?; + let terminal_partition = super::terminal_epoch::partition(workspace_id, owner_id, session_key); + let partition = partition.or(terminal_partition.as_ref()); let Some(partition) = partition else { return Ok(None); }; diff --git a/src/memory/sqlite/terminal_epoch.rs b/src/memory/sqlite/terminal_epoch.rs index 0da33392b..e1fe25206 100644 --- a/src/memory/sqlite/terminal_epoch.rs +++ b/src/memory/sqlite/terminal_epoch.rs @@ -8,6 +8,22 @@ type Key = (String, String, String); static EPOCHS: OnceLock>> = OnceLock::new(); const MAX_EPOCHS: usize = 4096; +/// Runtime metadata writers can omit the partition; only a locally authenticated +/// terminal pin can supply it. A caller-provided session name alone grants nothing. +pub(super) fn partition(workspace: &str, owner: Option<&str>, session: Option<&str>) -> Option { + let (Some(epochs), Some(owner), Some(session)) = (EPOCHS.get(), owner, session) else { + return None; + }; + epochs + .lock() + .contains_key(&(workspace.into(), owner.into(), session.into())) + .then(|| AgentPartition { + workspace_id: workspace.into(), + owner_id: owner.into(), + key: PartitionKey::Main, + }) +} + pub(crate) fn pin(memory: &SqliteMemory, partition: &AgentPartition, session: &str) -> anyhow::Result<()> { anyhow::ensure!(matches!(partition.key, PartitionKey::Main), AgentScopeRefused); let writer = memory.pool.write(); From 715af41cd7d33385817a364b7fdb9a60568fed8d Mon Sep 17 00:00:00 2001 From: g1e2x87 Date: Tue, 24 Nov 2026 04:16:54 +0400 Subject: [PATCH 0049/1567] fix(chat): admit turns with the current selected model --- src/chat/run.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/chat/run.rs b/src/chat/run.rs index 9349cb4c6..c9a8e3eea 100644 --- a/src/chat/run.rs +++ b/src/chat/run.rs @@ -1026,6 +1026,7 @@ async fn run_internal( let () = include!("run/commands.rs"); + let model_name = current_model_owned.as_str(); include!("run/provider_turn.rs"); } From 0e6b539712dea90e2b95752207040093b1e0c8df Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:32:39 +0400 Subject: [PATCH 0050/1567] fix(gateway): answer /pair and /webhook 429 with a coded rate_limited body and Retry-After --- src/gateway/implementation/section_1.rs | 21 ++++++++++++ src/gateway/implementation/section_2.rs | 25 ++++++-------- src/gateway/implementation/section_3.rs | 44 ++++++++++--------------- src/webhook/mod.rs | 35 ++++++++++++++------ 4 files changed, 74 insertions(+), 51 deletions(-) diff --git a/src/gateway/implementation/section_1.rs b/src/gateway/implementation/section_1.rs index 147a36306..039aa4cfc 100644 --- a/src/gateway/implementation/section_1.rs +++ b/src/gateway/implementation/section_1.rs @@ -117,6 +117,27 @@ pub const MAX_BODY_SIZE: usize = 65_536; pub const MAX_API_BODY_SIZE: usize = (10 * 20 * 1024 * 1024) + (1024 * 1024); /// Sliding window used by gateway rate limiting. pub const RATE_LIMIT_WINDOW_SECS: u64 = 60; + +/// The coded `429 rate_limited` of the `/pair` and `/webhook` limits: the shared +/// `{"error":{"code","message","retry_after_ms"}}` body plus a `Retry-After` +/// header in whole seconds. +fn rate_limited_reply(message: &str, retry_after_secs: u64) -> axum::response::Response { + let mut response = ( + StatusCode::TOO_MANY_REQUESTS, + Json(serde_json::json!({ + "error": { + "code": "rate_limited", + "message": message, + "retry_after_ms": retry_after_secs.saturating_mul(1000), + } + })), + ) + .into_response(); + response + .headers_mut() + .insert(header::RETRY_AFTER, header::HeaderValue::from(retry_after_secs)); + response +} /// Fallback max distinct client keys tracked in gateway rate limiter. pub const RATE_LIMIT_MAX_KEYS_DEFAULT: usize = 10_000; /// Fallback max distinct idempotency keys retained in gateway memory. diff --git a/src/gateway/implementation/section_2.rs b/src/gateway/implementation/section_2.rs index c23438945..46237c804 100644 --- a/src/gateway/implementation/section_2.rs +++ b/src/gateway/implementation/section_2.rs @@ -756,15 +756,11 @@ async fn handle_pair( State(state): State, ConnectInfo(peer_addr): ConnectInfo, headers: HeaderMap, -) -> impl IntoResponse { +) -> axum::response::Response { let rate_key = client_key_from_request(Some(peer_addr), &headers, state.trust_forwarded_headers); if !state.rate_limiter.allow_pair(&rate_key) { tracing::warn!("/pair rate limit exceeded"); - let err = serde_json::json!({ - "error": "Too many pairing requests. Please retry later.", - "retry_after": RATE_LIMIT_WINDOW_SECS, - }); - return (StatusCode::TOO_MANY_REQUESTS, Json(err)); + return rate_limited_reply("Too many pairing requests. Please retry later.", RATE_LIMIT_WINDOW_SECS); } let code = headers @@ -773,7 +769,7 @@ async fn handle_pair( .unwrap_or(""); if let Err(error) = authorize_gateway_resource_mutation(&state, "gateway:pair", ResourceRiskLevel::Low) { - return error; + return error.into_response(); } match state.pairing.try_pair(code, &rate_key).await { @@ -787,7 +783,7 @@ async fn handle_pair( "token": token, "message": "Paired for this process, but failed to persist token to config.toml. Check config path and write permissions.", }); - return (StatusCode::OK, Json(body)); + return (StatusCode::OK, Json(body)).into_response(); } let body = serde_json::json!({ @@ -796,20 +792,19 @@ async fn handle_pair( "token": token, "message": "Save this token — use it as Authorization: Bearer " }); - (StatusCode::OK, Json(body)) + (StatusCode::OK, Json(body)).into_response() } Ok(None) => { tracing::warn!("🔐 Pairing attempt with invalid code"); let err = serde_json::json!({"error": "Invalid pairing code"}); - (StatusCode::FORBIDDEN, Json(err)) + (StatusCode::FORBIDDEN, Json(err)).into_response() } Err(lockout_secs) => { tracing::warn!("🔐 Pairing locked out — too many failed attempts ({lockout_secs}s remaining)"); - let err = serde_json::json!({ - "error": format!("Too many failed attempts. Try again in {lockout_secs}s."), - "retry_after": lockout_secs - }); - (StatusCode::TOO_MANY_REQUESTS, Json(err)) + rate_limited_reply( + &format!("Too many failed attempts. Try again in {lockout_secs}s."), + lockout_secs, + ) } } } diff --git a/src/gateway/implementation/section_3.rs b/src/gateway/implementation/section_3.rs index 7a171aec1..89ba6e60d 100644 --- a/src/gateway/implementation/section_3.rs +++ b/src/gateway/implementation/section_3.rs @@ -5,7 +5,7 @@ async fn handle_webhook( uri: axum::http::Uri, headers: HeaderMap, body: Bytes, -) -> impl IntoResponse { +) -> axum::response::Response { let async_mode = jobs::wants_async(uri.query(), &headers); let bearer_token = headers .get(header::AUTHORIZATION) @@ -27,11 +27,7 @@ async fn handle_webhook( let rate_key = client_key_from_request(Some(peer_addr), &headers, state.trust_forwarded_headers); if !state.rate_limiter.allow_webhook(&rate_key) { tracing::warn!("/webhook rate limit exceeded"); - let err = serde_json::json!({ - "error": "Too many webhook requests. Please retry later.", - "retry_after": RATE_LIMIT_WINDOW_SECS, - }); - return (StatusCode::TOO_MANY_REQUESTS, Json(err)); + return rate_limited_reply("Too many webhook requests. Please retry later.", RATE_LIMIT_WINDOW_SECS); } // ── Bearer token auth (pairing) ── @@ -41,7 +37,7 @@ async fn handle_webhook( let err = serde_json::json!({ "error": "Unauthorized — pair first via POST /pair, then send Authorization: Bearer " }); - return (StatusCode::UNAUTHORIZED, Json(err)); + return (StatusCode::UNAUTHORIZED, Json(err)).into_response(); } } @@ -53,7 +49,7 @@ async fn handle_webhook( _ => { tracing::warn!("Webhook: rejected request — invalid or missing X-Webhook-Token"); let err = serde_json::json!({"error": "Unauthorized — invalid or missing X-Webhook-Token header"}); - return (StatusCode::UNAUTHORIZED, Json(err)); + return (StatusCode::UNAUTHORIZED, Json(err)).into_response(); } } } @@ -65,7 +61,7 @@ async fn handle_webhook( _ => { tracing::warn!("Webhook: rejected request — invalid or missing X-Webhook-Signature"); let err = serde_json::json!({"error": "Unauthorized — invalid or missing X-Webhook-Signature header"}); - return (StatusCode::UNAUTHORIZED, Json(err)); + return (StatusCode::UNAUTHORIZED, Json(err)).into_response(); } } } @@ -106,15 +102,11 @@ async fn handle_webhook( }; if !state.rate_limiter.allow_webhook_credential(&credential_rate_key) { tracing::warn!("/webhook credential rate limit exceeded"); - let err = serde_json::json!({ - "error": "Too many webhook requests. Please retry later.", - "retry_after": RATE_LIMIT_WINDOW_SECS, - }); - return (StatusCode::TOO_MANY_REQUESTS, Json(err)); + return rate_limited_reply("Too many webhook requests. Please retry later.", RATE_LIMIT_WINDOW_SECS); } // Admission, before any idempotency claim is taken. if let Err(refusal) = state.admit_turn_runtime() { - return turn_not_ready_plain(refusal); + return turn_not_ready_plain(refusal).into_response(); } // ── Parse body ── @@ -125,7 +117,7 @@ async fn handle_webhook( let err = serde_json::json!({ "error": "Invalid JSON body. Expected: {\"message\": \"...\"}" }); - return (StatusCode::BAD_REQUEST, Json(err)); + return (StatusCode::BAD_REQUEST, Json(err)).into_response(); } }; @@ -134,7 +126,7 @@ async fn handle_webhook( Ok(key) => key, Err(message) => { let err = serde_json::json!({ "error": message }); - return (StatusCode::BAD_REQUEST, Json(err)); + return (StatusCode::BAD_REQUEST, Json(err)).into_response(); } }; let mut idempotency_digest = None; @@ -143,7 +135,7 @@ async fn handle_webhook( if let Err(error) = authorize_gateway_resource_mutation(&state, "gateway:webhook:idempotency", ResourceRiskLevel::Low) { - return error; + return error.into_response(); } let digest = webhook_idempotency_digest(&idempotency_scope, raw_key); let fingerprint = webhook_request_fingerprint(&body); @@ -158,17 +150,17 @@ async fn handle_webhook( "idempotent": true, "message": "A request with this idempotency key is still processing" }); - return (StatusCode::CONFLICT, Json(body)); + return (StatusCode::CONFLICT, Json(body)).into_response(); } IdempotencyClaimOutcome::Replay(replay) => { - return (StatusCode::OK, Json(replay.json_body())); + return (StatusCode::OK, Json(replay.json_body())).into_response(); } IdempotencyClaimOutcome::ReplayUnavailable { response_id, result_hash, } => { let body = replay_unavailable_body(response_id, &result_hash); - return (StatusCode::CONFLICT, Json(body)); + return (StatusCode::CONFLICT, Json(body)).into_response(); } IdempotencyClaimOutcome::RequestConflict => { let body = serde_json::json!({ @@ -176,7 +168,7 @@ async fn handle_webhook( "idempotent": true, "message": "This idempotency key was used with a different request body" }); - return (StatusCode::CONFLICT, Json(body)); + return (StatusCode::CONFLICT, Json(body)).into_response(); } IdempotencyClaimOutcome::RetryUnavailable => { let body = serde_json::json!({ @@ -184,14 +176,14 @@ async fn handle_webhook( "idempotent": true, "message": "This failed request is not eligible for retry" }); - return (StatusCode::CONFLICT, Json(body)); + return (StatusCode::CONFLICT, Json(body)).into_response(); } IdempotencyClaimOutcome::AtCapacity => { let body = serde_json::json!({ "error": "Idempotency capacity is temporarily exhausted", "retryable": true }); - return (StatusCode::SERVICE_UNAVAILABLE, Json(body)); + return (StatusCode::SERVICE_UNAVAILABLE, Json(body)).into_response(); } } } @@ -217,9 +209,9 @@ async fn handle_webhook( ); if async_mode { - return (StatusCode::ACCEPTED, Json(job.accepted_body())); + return (StatusCode::ACCEPTED, Json(job.accepted_body())).into_response(); } - job.wait().await.into_parts() + job.wait().await.into_parts().into_response() } /// Label for the registry row of a webhook job, so `prx tasks list` shows which diff --git a/src/webhook/mod.rs b/src/webhook/mod.rs index 639af7e49..fec07da48 100644 --- a/src/webhook/mod.rs +++ b/src/webhook/mod.rs @@ -9,8 +9,8 @@ use async_trait::async_trait; use axum::{ Json, Router, extract::State, - http::{HeaderMap, StatusCode, header::AUTHORIZATION}, - response::IntoResponse, + http::{HeaderMap, StatusCode, header::{AUTHORIZATION, RETRY_AFTER}}, + response::{IntoResponse, Response}, routing::post, }; use chrono::Utc; @@ -1150,20 +1150,35 @@ fn router(state: WebhookState) -> Router { .with_state(state) } +/// The coded `429 rate_limited` of the webhook limit, in the gateway's +/// `{"error":{"code","message","retry_after_ms"}}` shape, with `Retry-After` +/// in whole seconds. The sliding window does not compute the exact wait, so +/// both carry the window length: an upper bound. +fn rate_limited_reply() -> Response { + let mut response = ( + StatusCode::TOO_MANY_REQUESTS, + Json(serde_json::json!({ + "error": { + "code": "rate_limited", + "message": "Too many webhook requests. Please retry later.", + "retry_after_ms": WEBHOOK_RATE_LIMIT_WINDOW_SECS.saturating_mul(1000), + } + })), + ) + .into_response(); + response + .headers_mut() + .insert(RETRY_AFTER, axum::http::HeaderValue::from(WEBHOOK_RATE_LIMIT_WINDOW_SECS)); + response +} + async fn handle_webhook_event( State(state): State, headers: HeaderMap, body: axum::body::Bytes, ) -> impl IntoResponse { if !state.rate_limiter.allow().await { - return ( - StatusCode::TOO_MANY_REQUESTS, - Json(serde_json::json!({ - "error": "Too many webhook requests. Please retry later.", - "retry_after": WEBHOOK_RATE_LIMIT_WINDOW_SECS - })), - ) - .into_response(); + return rate_limited_reply(); } if !is_authorized(&headers, &state.token) { From bb06544ae57154807f2d9849931666c47d89f625 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:32:39 +0400 Subject: [PATCH 0051/1567] fix(gateway): list CLI-created cron jobs for the paired owner bearer --- src/gateway/api/cron_jobs.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/gateway/api/cron_jobs.rs b/src/gateway/api/cron_jobs.rs index 6c7a18fff..1a3d39060 100644 --- a/src/gateway/api/cron_jobs.rs +++ b/src/gateway/api/cron_jobs.rs @@ -312,8 +312,15 @@ fn event_view(event: &CronJobEvent) -> Value { }) } +/// Whether `owner` may see and manage `job`. A job stored under the owner id +/// is the owner's. A job the local operator created from the command line +/// carries no owner id and belongs to the install owner, so a paired bearer +/// sees it; a request with pairing off (`api:local`) does not. fn owns(job: &CronJob, owner: &str) -> bool { - job.owner_id.as_deref() == Some(owner) + match job.owner_id.as_deref() { + Some(job_owner) => job_owner == owner, + None => owner != super::LOCAL_OWNER_ID && job.origin == crate::cron::JobOrigin::LocalOperator, + } } fn visible_job(config: &crate::config::Config, owner: &str, id: &str) -> Result { From 72e320710bc648e0d66f97517d2edbeced806b01 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:32:39 +0400 Subject: [PATCH 0052/1567] docs(rf-contract): document coded 429 on /pair and /webhook and CLI cron jobs for the owner --- docs/rf-contract/capability-tokens.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/rf-contract/capability-tokens.md b/docs/rf-contract/capability-tokens.md index dac1e00d5..8e8178db6 100644 --- a/docs/rf-contract/capability-tokens.md +++ b/docs/rf-contract/capability-tokens.md @@ -30,7 +30,10 @@ These codes can answer any `/api` route, in the coded shape: - `429 rate_limited` `{"error":{"code","message","retry_after_ms"}}`: the shared API rate limit. The response also carries `Retry-After` in seconds. Both give the limiter window (60 s) as an upper bound: retry after at most - this long. Exception: `GET /api/skills/discover` reports an upstream limit + this long. `POST /pair` and `POST /webhook` (and the standalone webhook + listener) answer their own limits in the same coded shape with `Retry-After`; + a `/pair` lockout after failed codes reports the remaining lockout seconds. + Exception: `GET /api/skills/discover` reports an upstream limit in its own shape `{"code":"rate_limited","error":""}`. - `503 provider_not_ready` `{"error":{"code","message","reason"}}`: the default provider has no usable credential, so the daemon runs without a @@ -815,6 +818,10 @@ there is no PRX child-count cap; the agent's daily cost policy still applies. Owner-bearer inventory/control routes are: - `GET /api/cron/jobs?agent=` and the existing cron item/control routes. + A paired bearer is the install owner: jobs created from the command line + (`prx cron`) belong to it and are listed and controllable. They have a null + `creator_agent`; jobs created by a named agent keep theirs. A request with + pairing off does not see them. - `GET /api/xin/tasks?agent=` and `GET /api/xin/tasks/{id}`. - `GET /api/xin/goals?agent=` and `GET /api/xin/goals/{id}`. - `POST /api/xin/tasks/{id}/pause` and `/resume`; `DELETE /api/xin/tasks/{id}`. From b004c7ac037c5f955cca98be9a921137a3fae62e Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:28:18 +0400 Subject: [PATCH 0053/1567] fix(config): honour OPENPRX_WORKSPACE when OPENPRX_CONFIG_DIR is set --- docs/configuration.md | 5 +++++ src/config/schema/paths.rs | 16 ++++++++++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index bd53bccc8..e6b9dc512 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -291,6 +291,11 @@ the run's workspace is `/workspace`, even when that environment variable names a different directory. Omit `--config-dir` (and `OPENPRX_CONFIG_DIR`) when you intend to select the workspace through `OPENPRX_WORKSPACE`. +`OPENPRX_CONFIG_DIR` combines with `OPENPRX_WORKSPACE`: the configuration tree +comes from `OPENPRX_CONFIG_DIR` and the workspace from `OPENPRX_WORKSPACE`. +When `OPENPRX_WORKSPACE` is unset or empty, the workspace is +`$OPENPRX_CONFIG_DIR/workspace`. + On Unix, new workspace `state` directories are created with mode `0700` even under umask `0002`; workspace parents retain their normal umask permissions. Cost storage refuses an existing group- or world-writable state directory: diff --git a/src/config/schema/paths.rs b/src/config/schema/paths.rs index ba4019d7a..316fe4575 100644 --- a/src/config/schema/paths.rs +++ b/src/config/schema/paths.rs @@ -369,6 +369,17 @@ pub fn bootstrap_max_blocking_threads(explicit_config_dir: Option<&str>) -> Opti bootstrap.runtime.max_blocking_threads.filter(|value| *value > 0) } +/// The workspace for a config directory chosen by `OPENPRX_CONFIG_DIR`: a non-empty +/// `OPENPRX_WORKSPACE` is honoured, otherwise `/workspace`. +fn workspace_dir_for_config_dir(openprx_dir: &Path) -> Result { + match env_openprx("WORKSPACE") { + Ok(workspace) if !workspace.trim().is_empty() => { + std::path::absolute(workspace.trim()).context("resolve OPENPRX_WORKSPACE") + } + _ => Ok(openprx_dir.join("workspace")), + } +} + pub(super) async fn resolve_runtime_config_dirs( default_openprx_dir: &Path, default_workspace_dir: &Path, @@ -391,9 +402,10 @@ pub(super) async fn resolve_runtime_config_dirs( let custom_config_dir = custom_config_dir.trim(); if !custom_config_dir.is_empty() { let openprx_dir = std::path::absolute(custom_config_dir).context("resolve OPENPRX_CONFIG_DIR")?; + let workspace_dir = workspace_dir_for_config_dir(&openprx_dir)?; return Ok(( - openprx_dir.clone(), - openprx_dir.join("workspace"), + openprx_dir, + workspace_dir, ConfigResolutionSource::EnvConfigDir, )); } From b9968a8bf420d05332aed5e733b8c7e9a795f8de Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:28:18 +0400 Subject: [PATCH 0054/1567] fix(config): omit default-empty arrays when the config is written --- src/config/schema/lifecycle.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/src/config/schema/lifecycle.rs b/src/config/schema/lifecycle.rs index dee5b73b6..a1db739a0 100644 --- a/src/config/schema/lifecycle.rs +++ b/src/config/schema/lifecycle.rs @@ -954,6 +954,9 @@ impl Config { .context("Config path must have a parent directory")?; let store = crate::security::SecretStore::new(openprx_dir, self.secrets.encrypt); let mut value = toml::Value::try_from(self).context("Failed to convert config into TOML value")?; + let defaults = + toml::Value::try_from(Self::default()).context("Failed to convert default config into TOML value")?; + omit_default_empty_arrays(&mut value, &defaults); crate::config::secret_paths::encrypt_at_rest(&mut value, &store)?; Ok(value) } @@ -977,6 +980,32 @@ impl Config { } } +/// Remove every empty array that the default configuration also holds empty at +/// the same table path. +/// +/// An inline `model_routes = []` would make a later `[[model_routes]]` append +/// (a duplicate definition of the key) fail to parse. Omitting it loses +/// nothing, because the default of that key is the empty array. An empty array +/// whose default is non-empty is an explicit choice and is kept. +fn omit_default_empty_arrays(value: &mut toml::Value, defaults: &toml::Value) { + let (Some(table), Some(default_table)) = (value.as_table_mut(), defaults.as_table()) else { + return; + }; + table.retain(|key, entry| { + let default_entry = default_table.get(key); + let empty_by_default = default_entry + .and_then(toml::Value::as_array) + .is_some_and(Vec::is_empty); + if empty_by_default && entry.as_array().is_some_and(Vec::is_empty) { + return false; + } + if let Some(default_entry) = default_entry { + omit_default_empty_arrays(entry, default_entry); + } + true + }); +} + /// Whether the stored configuration writes `memory.embedding_provider` (or its /// migrated legacy spelling `[memory.embedding].provider`) at all. pub(super) fn memory_embedding_provider_present(config: &toml::Value) -> bool { From ffb6a4c122042743b56b07bfe1fd9c99c2760782 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:28:18 +0400 Subject: [PATCH 0055/1567] fix(doctor): report credentials stored through the credential store --- src/doctor/implementation/section_2.rs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/src/doctor/implementation/section_2.rs b/src/doctor/implementation/section_2.rs index d6f8ce201..17550d5d6 100644 --- a/src/doctor/implementation/section_2.rs +++ b/src/doctor/implementation/section_2.rs @@ -63,7 +63,23 @@ fn check_config_semantics(config: &Config, items: &mut Vec) { )); } AuthProfileCredentialStatus::Missing => { - items.push(DiagItem::warn(cat, "no api_key or active auth profile credential set")); + // A credential stored through `PUT /api/providers/{id}/credential` + // or `prx providers credential set` is a `cred-` reference in + // the same encrypted store. Presence only; no value is read out. + let references = crate::config::manage::service::provider_credentials(config, provider) + .map(|credentials| credentials.references) + .unwrap_or_else(|error| { + tracing::warn!(%error, "doctor could not read the stored credential references"); + Vec::new() + }); + if let Some(reference) = references.first() { + items.push(DiagItem::configured( + cat, + format!("stored credential present for \"{provider}\" ({})", reference.id), + )); + } else { + items.push(DiagItem::warn(cat, "no api_key or active auth profile credential set")); + } } } } else { From de0c0b260786011371dbe447f0075bddad26c7d9 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:28:18 +0400 Subject: [PATCH 0056/1567] feat(service): add --dry-run to service install --- src/lib.rs | 3 +++ src/service/mod.rs | 61 +++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 63 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 79b2477dc..c6d52b89c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -196,6 +196,9 @@ pub enum ServiceCommands { /// Accept non-interactive installation #[arg(long)] yes: bool, + /// Print the unit that would be installed and change nothing + #[arg(long)] + dry_run: bool, }, /// Start daemon service Start, diff --git a/src/service/mod.rs b/src/service/mod.rs index d36ec2d0d..0fb0de162 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -180,10 +180,14 @@ const fn windows_task_name() -> &'static str { pub async fn handle_command(command: &crate::ServiceCommands, config: &Config, init_system: InitSystem) -> Result<()> { match command { - crate::ServiceCommands::Install { user, .. } => { + crate::ServiceCommands::Install { user, dry_run, .. } => { if *user && cfg!(target_os = "linux") && init_system.resolve()? == InitSystem::Openrc { anyhow::bail!("service_user_unsupported: OpenRC installation requires a system service"); } + if *dry_run { + println!("{}", render_install_preview(config, init_system)?); + return Ok(()); + } install(config, init_system).await } crate::ServiceCommands::Start => start(config, init_system).await, @@ -194,6 +198,61 @@ pub async fn handle_command(command: &crate::ServiceCommands, config: &Config, i } } +/// The file that `service install` would write and its content, as text. +/// Reads the environment only: no directory is created, no file written and no +/// service manager is called. +fn render_install_preview(config: &Config, init_system: InitSystem) -> Result { + if cfg!(target_os = "macos") { + let file = macos_service_file()?; + let exe = std::env::current_exe().context("Failed to resolve current executable")?; + let config_dir = selected_config_dir(config)?; + let logs_dir = config_dir.join("logs"); + let service_path = inherited_service_path(&exe); + let plist = generate_launchd_plist( + &exe, + config_dir, + &logs_dir.join("daemon.stdout.log"), + &logs_dir.join("daemon.stderr.log"), + &service_path, + ); + Ok(format!("# Dry run: would write {}\n{plist}", file.display())) + } else if cfg!(target_os = "linux") { + match init_system.resolve()? { + InitSystem::Systemd => { + let file = linux_service_file(config)?; + let exe = std::env::current_exe().context("Failed to resolve current executable")?; + let service_path = inherited_service_path(&exe); + let unit = generate_systemd_unit(&exe, selected_config_dir(config)?, &service_path); + Ok(format!("# Dry run: would write {}\n{unit}", file.display())) + } + InitSystem::Openrc => { + let exe = resolve_openrc_executable()?; + let script = generate_openrc_script(&exe, Path::new("/etc/prx")); + Ok(format!("# Dry run: would write /etc/init.d/prx\n{script}")) + } + InitSystem::Auto => anyhow::bail!("InitSystem::Auto should be resolved before this point"), + } + } else if cfg!(target_os = "windows") { + let exe = std::env::current_exe().context("Failed to resolve current executable")?; + let config_dir = selected_config_dir(config)?; + let logs_dir = config_dir.join("logs"); + let wrapper = logs_dir.join("prx-daemon.cmd"); + let content = generate_windows_wrapper( + &exe, + config_dir, + &logs_dir.join("daemon.stdout.log"), + &logs_dir.join("daemon.stderr.log"), + ); + Ok(format!( + "# Dry run: would write {} and register scheduled task \"{}\"\n{content}", + wrapper.display(), + windows_task_name() + )) + } else { + anyhow::bail!("Service management is supported on macOS and Linux only"); + } +} + async fn install(config: &Config, init_system: InitSystem) -> Result<()> { if cfg!(target_os = "macos") { install_macos(config) From 21539cbc0df3a5ded9cbd24752e3512faf377e62 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:51:09 +0400 Subject: [PATCH 0057/1567] fix(config): scaffold init workspace where the runtime resolves it --- src/config/init.rs | 5 +++-- src/config/mod.rs | 2 +- src/config/schema/paths.rs | 29 ++++++++++++++++++++++++++ src/initialization/wizard.rs | 5 +++-- src/initialization/wizard/quick.rs | 3 ++- src/initialization/wizard/workspace.rs | 4 ++-- src/runtime/init_cli.rs | 5 ++++- 7 files changed, 44 insertions(+), 9 deletions(-) diff --git a/src/config/init.rs b/src/config/init.rs index 4446e57c2..642ab349b 100644 --- a/src/config/init.rs +++ b/src/config/init.rs @@ -65,7 +65,8 @@ impl Spec { } self.generate(target_dir, force).await?; if let Some(decision) = decision { - let config = super::Config::load_from_path(&target_dir.join("config.toml"), target_dir.join("workspace"))?; + let workspace_dir = super::init_workspace_dir(target_dir).await?; + let config = super::Config::load_from_path(&target_dir.join("config.toml"), workspace_dir)?; let plan = decision.apply(config).await?; print!("{plan}"); println!("Decision backend configured ({}).", decision.kind.as_str()); @@ -117,7 +118,7 @@ impl Spec { // defaults only: every value an operator wrote explicitly is carried over. // `--force` is a repair operation, not a reset. let main_toml = main_config_template(self); - let workspace_dir = target_dir.join("workspace"); + let workspace_dir = super::init_workspace_dir(target_dir).await?; let mut report = InitReport::default(); let mut preservation = None; let mut reset_reason = None; diff --git a/src/config/mod.rs b/src/config/mod.rs index b76dccb9d..86ee49ca8 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -40,7 +40,7 @@ pub use schema::{ StreamMode, TaskRoutingConfig, TaskRoutingIntentConfig, TaskRoutingRule, TelegramConfig, ToolTieringConfig, TunnelConfig, UserPolicyConfig, WacliConfig, WebSearchConfig, WebhookConfig, WhatsAppConfig, WorkdirError, WorkspaceHooks, WorkspaceMcpServers, apply_runtime_proxy_to_builder, bootstrap_max_blocking_threads, - build_runtime_proxy_client, build_runtime_proxy_client_with_timeouts, default_openprx_dir, expand_home, + build_runtime_proxy_client, build_runtime_proxy_client_with_timeouts, default_openprx_dir, expand_home, init_workspace_dir, platform_config_dir, process_config_dir, resolve_init_target_dir, runtime_proxy_config, runtime_proxy_generation, set_process_config_dir, user_home_dir, }; diff --git a/src/config/schema/paths.rs b/src/config/schema/paths.rs index 316fe4575..ae553c249 100644 --- a/src/config/schema/paths.rs +++ b/src/config/schema/paths.rs @@ -550,6 +550,35 @@ pub async fn resolve_init_target_dir( Ok(openprx_dir) } +/// The workspace `prx init` scaffolds for `target_dir`. +/// +/// It is the workspace a later run of the same process environment resolves +/// for that directory, so the scaffold and the runtime never disagree: +/// - the global `--config-dir` flag (published by the CLI before init runs) +/// names `target_dir`: `/workspace`, whatever +/// `OPENPRX_WORKSPACE` says; +/// - otherwise, when the environment (`OPENPRX_CONFIG_DIR`, `OPENPRX_WORKSPACE` +/// or the active-workspace marker) resolves to `target_dir`: the workspace +/// that resolution names; +/// - any other directory (for example `init --dir`): `/workspace`. +/// +/// # Errors +/// +/// When the default directories or the environment cannot be resolved. +pub async fn init_workspace_dir(target_dir: &Path) -> Result { + let flag_names_target = + process_config_dir().is_some_and(|published| init_targets_are_same_dir(&published, target_dir)); + if !flag_names_target { + let (default_openprx_dir, default_workspace_dir) = default_config_and_workspace_dirs()?; + let (openprx_dir, workspace_dir, _source) = + resolve_runtime_config_dirs(&default_openprx_dir, &default_workspace_dir, None).await?; + if init_targets_are_same_dir(&openprx_dir, target_dir) { + return Ok(workspace_dir); + } + } + Ok(target_dir.join("workspace")) +} + pub(super) fn config_dir_creation_error(path: &Path) -> String { format!( "Failed to create config directory: {}. If running as an OpenRC service, \ diff --git a/src/initialization/wizard.rs b/src/initialization/wizard.rs index f8b1e9ef4..6df126405 100644 --- a/src/initialization/wizard.rs +++ b/src/initialization/wizard.rs @@ -102,7 +102,7 @@ pub async fn run_wizard(config_dir: Option<&str>, spec: Spec, force: bool) -> Re println!(); print_step(1, 9, "Workspace Setup"); - let (workspace_dir, config_path) = setup_workspace(config_dir)?; + let (workspace_dir, config_path) = setup_workspace(config_dir).await?; let state_dir = config_path.parent().context("Config path has no parent")?; print_step(2, 9, "AI Provider & API Key"); @@ -236,7 +236,8 @@ pub async fn run_channels_repair_wizard(config_dir: Option<&str>) -> Result<(Con target.join("config.toml").is_file(), "Channel repair requires an existing configuration; run prx init first" ); - let mut config = Config::load_from_path(&target.join("config.toml"), target.join("workspace"))?; + let workspace_dir = crate::config::init_workspace_dir(&target).await?; + let mut config = Config::load_from_path(&target.join("config.toml"), workspace_dir)?; print_step(1, 1, "Channels (How You Talk to OpenPRX)"); config.channels_config = setup_channels()?; diff --git a/src/initialization/wizard/quick.rs b/src/initialization/wizard/quick.rs index f82878908..a67d26c4c 100644 --- a/src/initialization/wizard/quick.rs +++ b/src/initialization/wizard/quick.rs @@ -150,7 +150,8 @@ pub async fn run_quick_setup( println!(" prx auth login --provider xai --device-code"); println!("An xAI API key still works via --from-stdin or `api_key` in config.toml."); } - Config::load_from_path(&target.join("config.toml"), target.join("workspace")) + let workspace_dir = crate::config::init_workspace_dir(&target).await?; + Config::load_from_path(&target.join("config.toml"), workspace_dir) } #[cfg(test)] diff --git a/src/initialization/wizard/workspace.rs b/src/initialization/wizard/workspace.rs index f65d86152..235b41fc0 100644 --- a/src/initialization/wizard/workspace.rs +++ b/src/initialization/wizard/workspace.rs @@ -31,7 +31,7 @@ pub(super) async fn persist_workspace_selection_at(config_path: &Path, default_c // ── Step 1: Workspace ──────────────────────────────────────────── -pub(super) fn setup_workspace(config_dir: Option<&str>) -> Result<(PathBuf, PathBuf)> { +pub(super) async fn setup_workspace(config_dir: Option<&str>) -> Result<(PathBuf, PathBuf)> { let openprx_dir = if let Some(dir) = config_dir { PathBuf::from(dir) } else { @@ -53,7 +53,7 @@ pub(super) fn setup_workspace(config_dir: Option<&str>) -> Result<(PathBuf, Path } }; - let workspace_dir = openprx_dir.join("workspace"); + let workspace_dir = crate::config::init_workspace_dir(&openprx_dir).await?; let config_path = openprx_dir.join("config.toml"); println!( diff --git a/src/runtime/init_cli.rs b/src/runtime/init_cli.rs index 9ea041cf9..0f11332b4 100644 --- a/src/runtime/init_cli.rs +++ b/src/runtime/init_cli.rs @@ -156,7 +156,10 @@ pub(crate) async fn run(cli: &Cli) -> Result<()> { .await? } else { spec.generate(&target, *force).await?; - openprx::config::Config::load_or_init_with_config_dir(config_dir).await? + // Same resolution the runtime uses: the global flag, else the + // environment. Only `init --dir` names the directory itself. + let load_dir = if dir.is_some() { config_dir } else { cli.config_dir.as_deref() }; + openprx::config::Config::load_or_init_with_config_dir(load_dir).await? }; let config = if let Some(secret) = provider_secret { crate::runtime::host_bootstrap::store_provider_key(config, &secret).await? From fd485391922b7aec90cad74afba64505560872cd Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:51:09 +0400 Subject: [PATCH 0058/1567] fix(doctor): report stored credentials as used only when referenced --- src/doctor/implementation/section_2.rs | 101 +++++++++++++++++++------ 1 file changed, 77 insertions(+), 24 deletions(-) diff --git a/src/doctor/implementation/section_2.rs b/src/doctor/implementation/section_2.rs index 17550d5d6..8b0e77020 100644 --- a/src/doctor/implementation/section_2.rs +++ b/src/doctor/implementation/section_2.rs @@ -65,20 +65,31 @@ fn check_config_semantics(config: &Config, items: &mut Vec) { AuthProfileCredentialStatus::Missing => { // A credential stored through `PUT /api/providers/{id}/credential` // or `prx providers credential set` is a `cred-` reference in - // the same encrypted store. Presence only; no value is read out. - let references = crate::config::manage::service::provider_credentials(config, provider) - .map(|credentials| credentials.references) - .unwrap_or_else(|error| { - tracing::warn!(%error, "doctor could not read the stored credential references"); - Vec::new() - }); - if let Some(reference) = references.first() { - items.push(DiagItem::configured( - cat, - format!("stored credential present for \"{provider}\" ({})", reference.id), - )); - } else { - items.push(DiagItem::warn(cat, "no api_key or active auth profile credential set")); + // the same encrypted store. It is used only when the configuration + // references it (`credential_ref`), the same test `prx providers + // credential status` applies. Presence only; no value is read out. + match stored_credential_status(config, provider) { + StoredCredentialStatus::Referenced { id, users } => { + items.push(DiagItem::configured( + cat, + format!( + "stored credential {id} for \"{provider}\" is referenced by {}", + users.join(", ") + ), + )); + } + StoredCredentialStatus::Unreferenced { id } => { + items.push(DiagItem::warn( + cat, + format!( + "stored credential {id} exists for \"{provider}\" but is not referenced by any \ + model route, embedding route or agent (`credential_ref`), so it is not used" + ), + )); + } + StoredCredentialStatus::None => { + items.push(DiagItem::warn(cat, "no api_key or active auth profile credential set")); + } } } } @@ -229,18 +240,24 @@ fn check_config_semantics(config: &Config, items: &mut Vec) { ), )); } - if !availability.unavailable.is_empty() { + // A provider whose stored credential the configuration references is not + // missing one, whatever the availability summary (which looks at the root + // key and the environment) says; the credential line above names it. + let unavailable: Vec = availability + .unavailable + .iter() + .filter(|(name, _)| { + !matches!( + stored_credential_status(config, name), + StoredCredentialStatus::Referenced { .. } + ) + }) + .map(|(name, reason)| format!("{name}: {reason}")) + .collect(); + if !unavailable.is_empty() { items.push(DiagItem::warn( cat, - format!( - "unavailable providers: {}", - availability - .unavailable - .iter() - .map(|(name, reason)| format!("{name}: {reason}")) - .collect::>() - .join("; ") - ), + format!("unavailable providers: {}", unavailable.join("; ")), )); } @@ -390,6 +407,42 @@ enum AuthProfileCredentialStatus { Unreadable(String), } +/// What the credential store holds for a provider, by reference id only. +#[derive(Debug, Clone, PartialEq, Eq)] +enum StoredCredentialStatus { + /// A stored credential some part of the configuration references. + Referenced { id: String, users: Vec }, + /// A stored credential nothing references: it is never sent. + Unreferenced { id: String }, + /// No stored credential for the provider, or the store is unreadable. + None, +} + +fn stored_credential_status(config: &Config, provider: &str) -> StoredCredentialStatus { + let credentials = match crate::config::manage::service::provider_credentials(config, provider) { + Ok(credentials) => credentials, + Err(error) => { + tracing::warn!(%error, "doctor could not read the stored credential references"); + return StoredCredentialStatus::None; + } + }; + let mut unreferenced = None; + for reference in &credentials.references { + match credentials.reference_uses.get(&reference.id) { + Some(users) if !users.is_empty() => { + return StoredCredentialStatus::Referenced { + id: reference.id.clone(), + users: users.clone(), + }; + } + _ => { + unreferenced.get_or_insert_with(|| reference.id.clone()); + } + } + } + unreferenced.map_or(StoredCredentialStatus::None, |id| StoredCredentialStatus::Unreferenced { id }) +} + fn active_auth_profile_credential_status(config: &Config, provider: &str) -> AuthProfileCredentialStatus { let Some(openprx_dir) = config.config_path.parent() else { return AuthProfileCredentialStatus::Missing; From bd0b81f019880a43a0c60aafbdace05a30ccfe49 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:30:28 +0400 Subject: [PATCH 0059/1567] fix(chat): state the context handoff rule on every runtime entry surface --- src/agent/prompt.rs | 9 +++++++++ src/agent/runtime_prompt.rs | 6 +++--- src/agent/turn_tests/runtime_prompt.rs | 11 +++-------- 3 files changed, 15 insertions(+), 11 deletions(-) diff --git a/src/agent/prompt.rs b/src/agent/prompt.rs index eb17aa833..34eab2582 100644 --- a/src/agent/prompt.rs +++ b/src/agent/prompt.rs @@ -57,10 +57,15 @@ pub struct SystemPromptBuilder { } impl SystemPromptBuilder { + /// The default sections of every runtime entry surface (chat, gateway, + /// channels, workers, children). They include the context-handoff rule, so a + /// session whose earlier turns were moved out of its window can always + /// look them up again, whichever surface a turn enters through. pub fn with_defaults() -> Self { Self { sections: vec![ Box::new(TaskSection), + Box::new(ContextHandoffSection), Box::new(SafetySection), Box::new(OrchestrationSection), Box::new(SkillsSection), @@ -91,6 +96,9 @@ impl SystemPromptBuilder { /// tool-evidence rule (or the task section, or ends the prompt). #[must_use] pub fn with_context_handoff_rule(mut self) -> Self { + if self.sections.iter().any(|section| section.name() == "context_handoff") { + return self; + } let at = self .sections .iter() @@ -568,6 +576,7 @@ mod tests { .collect::>(), vec![ "task", + "context_handoff", "safety", "orchestration", "skills", diff --git a/src/agent/runtime_prompt.rs b/src/agent/runtime_prompt.rs index 712781d07..ea3069b01 100644 --- a/src/agent/runtime_prompt.rs +++ b/src/agent/runtime_prompt.rs @@ -71,10 +71,10 @@ pub(crate) fn build_chat_system_prompt( skills: &[crate::skills::Skill], native_tools: bool, ) -> String { + // The handoff rule is part of the shared defaults; only the tool-evidence + // rule is specific to the reducer-driven terminal chat. #[cfg(feature = "terminal-tui")] - let builder = crate::agent::prompt::SystemPromptBuilder::with_defaults() - .with_tool_evidence_rule() - .with_context_handoff_rule(); + let builder = crate::agent::prompt::SystemPromptBuilder::with_defaults().with_tool_evidence_rule(); #[cfg(not(feature = "terminal-tui"))] let builder = crate::agent::prompt::SystemPromptBuilder::with_defaults(); build_runtime_system_prompt_with(builder, config, model_name, skills, native_tools) diff --git a/src/agent/turn_tests/runtime_prompt.rs b/src/agent/turn_tests/runtime_prompt.rs index 6b8c3f477..2fffa6292 100644 --- a/src/agent/turn_tests/runtime_prompt.rs +++ b/src/agent/turn_tests/runtime_prompt.rs @@ -37,14 +37,9 @@ fn chat_prompt_states_the_handoff_rule_once() { let chat = build_chat_system_prompt(&config, "model", &[], true); let runtime = build_runtime_system_prompt(&config, "model", &[], true); - let expected = usize::from(cfg!(feature = "terminal-tui")); - assert_eq!( - chat.matches(rule).count(), - expected, - "the chat prompt states the rule once" - ); - assert!(!runtime.contains(rule), "a prompt outside chat does not state it"); - if expected == 1 { + assert_eq!(chat.matches(rule).count(), 1, "the chat prompt states the rule once"); + assert_eq!(runtime.matches(rule).count(), 1, "every runtime prompt states it once"); + if cfg!(feature = "terminal-tui") { let evidence = chat .find(crate::agent::tool_evidence::TOOL_EVIDENCE_PROMPT_RULE) .expect("the evidence rule"); From fcf77466c13986fd5b796e175011a04b1d6caf8a Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:30:28 +0400 Subject: [PATCH 0060/1567] fix(chat): read @file mentions at the turn's autonomy level --- src/chat/file_mention.rs | 6 +++++- src/chat/run/provider_turn.rs | 2 +- src/chat/tests/file_mention_tests.rs | 9 +++++---- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/src/chat/file_mention.rs b/src/chat/file_mention.rs index ceebd48b2..19638d16c 100644 --- a/src/chat/file_mention.rs +++ b/src/chat/file_mention.rs @@ -79,9 +79,13 @@ const fn is_file_mention_trailing_punctuation(ch: char) -> bool { matches!(ch, ',' | ';' | ':' | '!' | '?' | ')' | ']' | '}') } +/// Attach the files `user_input` mentions. The reads run at the turn's +/// effective `autonomy`: at Full the file tool resolves any path the OS lets +/// the process read, below Full the workspace confinement is unchanged. pub(super) async fn enrich_file_mentions_for_prompt( user_input: &str, tools_registry: &[Box], + autonomy: crate::security::AutonomyLevel, ) -> FileMentionEnrichment { let mentions = extract_file_mentions(user_input); if mentions.is_empty() { @@ -102,7 +106,7 @@ pub(super) async fn enrich_file_mentions_for_prompt( "path": mention.path.as_str(), "max_bytes": FILE_MENTION_MAX_BYTES, }); - match tool.execute_named("file_read", args).await { + match crate::tools::effective_autonomy::scope(autonomy, tool.execute_named("file_read", args)).await { Ok(result) if result.success => { let (content, truncated) = truncate_utf8_to_byte_cap(&result.output, FILE_MENTION_MAX_BYTES); let mut section = format!("### {}\nPath: {}\n\n{}", mention.token, mention.path, content); diff --git a/src/chat/run/provider_turn.rs b/src/chat/run/provider_turn.rs index 3a1969c0a..c5cd8a260 100644 --- a/src/chat/run/provider_turn.rs +++ b/src/chat/run/provider_turn.rs @@ -106,7 +106,7 @@ one_shot_binding = Some(Arc::clone(&admitted_binding)); } - let file_mention_enrichment = enrich_file_mentions_for_prompt(&user_input, tools_registry.as_ref()).await; + let file_mention_enrichment = enrich_file_mentions_for_prompt(&user_input, tools_registry.as_ref(), security.autonomy).await; if let Some(note) = file_mention_enrichment.visible_note.as_deref() { emit_chat_output(note); } diff --git a/src/chat/tests/file_mention_tests.rs b/src/chat/tests/file_mention_tests.rs index 045cf2a13..37faf80a9 100644 --- a/src/chat/tests/file_mention_tests.rs +++ b/src/chat/tests/file_mention_tests.rs @@ -97,7 +97,7 @@ async fn file_mention_success_uses_file_read_tool_and_preserves_original_text() std::fs::write(temp.path().join("note.txt"), "hello from mention").expect("write note"); let registry = file_read_registry(temp.path(), false); - let enriched = enrich_file_mentions_for_prompt("please inspect @note.txt", ®istry).await; + let enriched = enrich_file_mentions_for_prompt("please inspect @note.txt", ®istry, crate::security::AutonomyLevel::Supervised).await; assert!(enriched.prompt.starts_with("please inspect @note.txt")); assert!(enriched.prompt.contains("hello from mention")); @@ -121,6 +121,7 @@ async fn file_mention_security_negatives_are_soft_visible_and_generic() { let enriched = enrich_file_mentions_for_prompt( "check @../../etc/passwd @/etc/passwd @escape.txt @MEMORY.md @missing.txt", ®istry, + crate::security::AutonomyLevel::Supervised, ) .await; @@ -142,7 +143,7 @@ async fn file_mention_directory_is_rejected_softly() { std::fs::create_dir_all(temp.path().join("dir")).expect("create dir"); let registry = file_read_registry(temp.path(), false); - let enriched = enrich_file_mentions_for_prompt("inspect @dir", ®istry).await; + let enriched = enrich_file_mentions_for_prompt("inspect @dir", ®istry, crate::security::AutonomyLevel::Supervised).await; let note = enriched.visible_note.expect("visible directory note"); assert!(note.contains("@dir: unavailable")); @@ -203,7 +204,7 @@ async fn file_mention_caps_file_count_and_bytes() { max_bytes_seen: Arc::clone(&max_bytes_seen), })]; - let enriched = enrich_file_mentions_for_prompt("x @a @b @c @d @e @f", ®istry).await; + let enriched = enrich_file_mentions_for_prompt("x @a @b @c @d @e @f", ®istry, crate::security::AutonomyLevel::Supervised).await; assert_eq!(calls.load(Ordering::SeqCst), FILE_MENTION_MAX_FILES); assert_eq!( @@ -229,7 +230,7 @@ async fn file_mention_truncates_utf8_on_char_boundary() { std::fs::write(temp.path().join("big.txt"), "\u{20ac}".repeat(30_000)).expect("write big"); let registry = file_read_registry(temp.path(), false); - let enriched = enrich_file_mentions_for_prompt("read @big.txt", ®istry).await; + let enriched = enrich_file_mentions_for_prompt("read @big.txt", ®istry, crate::security::AutonomyLevel::Supervised).await; assert!(enriched.prompt.contains("[content truncated: 64 KiB limit]")); let attached_content = enriched From 4612f077b2cae736c0ad31dfe090399e41131383 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:30:28 +0400 Subject: [PATCH 0061/1567] fix(chat): record real token counts when a handoff is unavailable or failed --- src/chat/dispatcher.rs | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/src/chat/dispatcher.rs b/src/chat/dispatcher.rs index 469c4790f..37761e484 100644 --- a/src/chat/dispatcher.rs +++ b/src/chat/dispatcher.rs @@ -2181,6 +2181,24 @@ async fn send_context_degraded_notice( Ok(()) } +/// The budget the caller's lossy token-aware trim leaves behind, measured on a +/// copy so the degradation record carries real before and after counts even +/// though the caller owns the actual trim. +fn lossy_trim_budget( + history: &[crate::providers::traits::ChatMessage], + compaction_guard_history: &crate::agent::turn_history::CanonicalHistory, + config: &crate::config::AgentCompactionConfig, +) -> crate::agent::context_budget::ContextBudgetSnapshot { + let mut trimmed_view = history.to_vec(); + let mut projection_guard = compaction_guard_history.messages().to_vec(); + trim_redux_driver_context_budget_after_rollover(&mut trimmed_view, &mut projection_guard, config, None); + crate::agent::context_budget::plan_context_budget( + &trimmed_view, + config, + crate::agent::context_budget::PRE_TURN_FLUSH_THRESHOLD, + ) +} + async fn apply_redux_context_rollover( provider: &dyn Provider, history: &mut Vec, @@ -2235,12 +2253,13 @@ async fn apply_redux_context_rollover( config, crate::agent::context_budget::PRE_TURN_FLUSH_THRESHOLD, ); + let after_trim = lossy_trim_budget(history, compaction_guard_history, config); crate::agent::compaction::persist_context_switch_degradation( audit, trigger, "handoff_unavailable", budget.used_tokens, - budget.used_tokens, + after_trim.used_tokens, budget.available_input_tokens, ) .await; @@ -2268,12 +2287,13 @@ async fn apply_redux_context_rollover( config, crate::agent::context_budget::PRE_TURN_FLUSH_THRESHOLD, ); + let after_trim = lossy_trim_budget(history, compaction_guard_history, config); crate::agent::compaction::persist_context_switch_degradation( audit, trigger, "handoff_failed", budget.used_tokens, - budget.used_tokens, + after_trim.used_tokens, budget.available_input_tokens, ) .await; @@ -2306,12 +2326,13 @@ async fn apply_redux_context_rollover( config, crate::agent::context_budget::PRE_TURN_FLUSH_THRESHOLD, ); + let after_trim = lossy_trim_budget(history, compaction_guard_history, config); crate::agent::compaction::persist_context_switch_degradation( audit, trigger, "handoff_failed", budget.used_tokens, - budget.used_tokens, + after_trim.used_tokens, budget.available_input_tokens, ) .await; From 881ec23ced11143d007fd180f0ce7eb813bec85b Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:24:02 +0400 Subject: [PATCH 0062/1567] fix(tools): mask credential values behind a colon-qualified query name --- src/security/redaction.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/security/redaction.rs b/src/security/redaction.rs index a720854d5..bc2834976 100644 --- a/src/security/redaction.rs +++ b/src/security/redaction.rs @@ -217,11 +217,11 @@ fn looks_like_a_secret(value: &str) -> bool { && value.chars().any(|c| c.is_ascii_alphabetic()) } -/// A key's segments, lower-cased: split on `_`, `-`, `.` and camelCase +/// A key's segments, lower-cased: split on `_`, `-`, `.`, `:` and camelCase /// (`authToken` -> `auth`, `token`; `APIKey` -> `api`, `key`). fn key_segments(key: &str) -> Vec { let mut segments = Vec::new(); - for part in key.split(['_', '-', '.']).filter(|part| !part.is_empty()) { + for part in key.split(['_', '-', '.', ':']).filter(|part| !part.is_empty()) { let chars: Vec = part.chars().collect(); let mut current = String::new(); for (index, c) in chars.iter().enumerate() { From c0377458fb5bda7bdfbc7051470d788055ce8a68 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:35:56 +0400 Subject: [PATCH 0063/1567] fix(tools): accept a run id in join and name spawn_batch in the unknown-batch error --- src/tools/sessions_spawn/batch.rs | 41 ++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/src/tools/sessions_spawn/batch.rs b/src/tools/sessions_spawn/batch.rs index ceac08ab4..186197766 100644 --- a/src/tools/sessions_spawn/batch.rs +++ b/src/tools/sessions_spawn/batch.rs @@ -624,6 +624,21 @@ impl SessionsSpawnTool { batch_id: &str, owner_scope: &sessions_read_model::RunOwnerScope, ) -> anyhow::Result { + // A run id names exactly one batch; accept it where a batch id is expected. + let run_lookup = self.run_batch_lookup(batch_id, owner_scope).await; + let batch_id = match &run_lookup { + RunBatchLookup::InBatch(batch) => batch.as_str(), + RunBatchLookup::NoBatch => { + return Ok(ToolResult { + success: false, + output: String::new(), + error: Some(format!( + "'{batch_id}' is a run id, and that run belongs to no batch: join takes the batch_id returned by spawn_batch." + )), + }); + } + RunBatchLookup::NotARun => batch_id, + }; let caller = crate::tools::execution::current_child_call_context(); if let Some(caller) = &caller { caller.verify_tool("sessions_spawn")?; @@ -670,7 +685,8 @@ impl SessionsSpawnTool { success: false, output: String::new(), error: Some(format!( - "Unknown batch '{batch_id}': no sub-agent run in this session carries that batch id." + "Unknown batch '{batch_id}': no sub-agent run in this session carries that batch id. \ + join takes the batch_id returned by spawn_batch (a run id is accepted only while its run is still on file)." )), }); } @@ -683,6 +699,19 @@ impl SessionsSpawnTool { }) } + /// Whether `id` is the id of a run on file that this caller may see, and + /// the batch that run belongs to. + async fn run_batch_lookup(&self, id: &str, owner_scope: &sessions_read_model::RunOwnerScope) -> RunBatchLookup { + let runs = self.active_runs.read().await; + runs.iter() + .find(|run| run.id == id && owner_scope.admits(run.owner_id.as_deref(), run.agent_partition.as_ref())) + .map_or(RunBatchLookup::NotARun, |run| { + run.batch_id + .clone() + .map_or(RunBatchLookup::NoBatch, RunBatchLookup::InBatch) + }) + } + /// Who this batch launched. /// /// The roster is preferred over the registry because it is the only source @@ -725,3 +754,13 @@ impl SessionsSpawnTool { .collect() } } + +/// How the id given to `join` relates to the runs on file. +enum RunBatchLookup { + /// The id is a run id; this is the batch that run belongs to. + InBatch(String), + /// The id is a run id whose run is in no batch. + NoBatch, + /// The id is not a run id on file: treat it as a batch id. + NotARun, +} From 9911d13f6255f8368570d221525bfbe787541d7e Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:35:56 +0400 Subject: [PATCH 0064/1567] fix(tools): show a finished process child's stored result after restart recovery --- src/tools/sessions_spawn/process_terminal.rs | 27 ++++++++ .../process_terminal/operator.rs | 8 ++- .../process_terminal/ordinary.rs | 8 ++- .../process_terminal/stored_result.rs | 62 +++++++++++++++++++ 4 files changed, 103 insertions(+), 2 deletions(-) create mode 100644 src/tools/sessions_spawn/process_terminal/stored_result.rs diff --git a/src/tools/sessions_spawn/process_terminal.rs b/src/tools/sessions_spawn/process_terminal.rs index 3bcb36fe5..122550f8b 100644 --- a/src/tools/sessions_spawn/process_terminal.rs +++ b/src/tools/sessions_spawn/process_terminal.rs @@ -3,6 +3,7 @@ pub(super) mod operator; pub(super) mod ordinary; mod process_identity; pub(super) mod retained; +mod stored_result; use crate::agent::terminal::TurnTerminalStatus; use crate::memory::{MemoryFabric, MessageEvent, MessageEventSource, MessageEventSubject}; use crate::session_worker::protocol::WorkerResult; @@ -118,6 +119,9 @@ pub(super) enum RecoveredProcessOutcome { OperatorUnconfirmed(RecoveredWorkerUsage), OrdinaryComplete(ordinary::VerifiedOrdinaryWorkerCompletion), OrdinaryUnconfirmed(RecoveredWorkerUsage), + /// No signed journal, but the run's own result row exists: its outcome is + /// shown; cleanup and provider usage stay unconfirmed. + StoredResult(stored_result::StoredWorkerResult, RecoveredWorkerUsage), } impl RecoveredProcessRun { @@ -171,6 +175,29 @@ impl RecoveredProcessRun { Vec::new(), Some(ProcessRunControl::recovered_unconfirmed()), ), + RecoveredProcessOutcome::StoredResult(stored, recovered) => { + let status = if stored.success { + SubAgentStatus::Completed(stored.content.clone()) + } else { + SubAgentStatus::Failed(super::sub_agent_reported_failure(&stored.content)) + }; + let history = if stored.success { + vec![HistoryEntry { + role: "assistant".to_owned(), + content: stored.content, + timestamp: stored.finished_at, + }] + } else { + Vec::new() + }; + ( + status, + Some(stored.finished_at), + recovered.records, + history, + Some(ProcessRunControl::recovered_unconfirmed()), + ) + } RecoveredProcessOutcome::OperatorComplete(completion) => { let finished_at = completion .finished_at diff --git a/src/tools/sessions_spawn/process_terminal/operator.rs b/src/tools/sessions_spawn/process_terminal/operator.rs index 976bdd6c7..2d4465893 100644 --- a/src/tools/sessions_spawn/process_terminal/operator.rs +++ b/src/tools/sessions_spawn/process_terminal/operator.rs @@ -527,7 +527,13 @@ pub(super) async fn recover_restart_event( } let outcome = match launch.completion(fabric).await? { Some(completion) => RecoveredProcessOutcome::OperatorComplete(completion), - None => RecoveredProcessOutcome::OperatorUnconfirmed(launch.partial_usage(fabric).await?), + None => { + let usage = launch.partial_usage(fabric).await?; + match super::stored_result::read(fabric, owner, run).await? { + Some(stored) => RecoveredProcessOutcome::StoredResult(stored, usage), + None => RecoveredProcessOutcome::OperatorUnconfirmed(usage), + } + } }; let batch_id = None; Ok(Some(RecoveredProcessRun { diff --git a/src/tools/sessions_spawn/process_terminal/ordinary.rs b/src/tools/sessions_spawn/process_terminal/ordinary.rs index 8e483356b..d1e2946cb 100644 --- a/src/tools/sessions_spawn/process_terminal/ordinary.rs +++ b/src/tools/sessions_spawn/process_terminal/ordinary.rs @@ -508,7 +508,13 @@ pub(super) async fn recover_restart_event( } let outcome = match launch.completion(fabric).await? { Some(completion) => RecoveredProcessOutcome::OrdinaryComplete(completion), - None => RecoveredProcessOutcome::OrdinaryUnconfirmed(launch.partial_usage(fabric).await?), + None => { + let usage = launch.partial_usage(fabric).await?; + match super::stored_result::read(fabric, owner, run).await? { + Some(stored) => RecoveredProcessOutcome::StoredResult(stored, usage), + None => RecoveredProcessOutcome::OrdinaryUnconfirmed(usage), + } + } }; let batch_id = launch.batch_id().map(str::to_owned); let agent_partition = launch.agent_partition().cloned(); diff --git a/src/tools/sessions_spawn/process_terminal/stored_result.rs b/src/tools/sessions_spawn/process_terminal/stored_result.rs new file mode 100644 index 000000000..1fee89739 --- /dev/null +++ b/src/tools/sessions_spawn/process_terminal/stored_result.rs @@ -0,0 +1,62 @@ +//! The run's own stored result row, read first when recovery finds no signed +//! completion journal. +use crate::memory::MemoryFabric; +use anyhow::Context; + +/// What a finished process child recorded under its single result key. +pub(in crate::tools::sessions_spawn) struct StoredWorkerResult { + pub(in crate::tools::sessions_spawn) success: bool, + /// The reply on success, the failure text otherwise (already redacted). + pub(in crate::tools::sessions_spawn) content: String, + pub(in crate::tools::sessions_spawn) finished_at: chrono::DateTime, +} + +/// Read `worker::result`. `None` when no row exists, or when the row is +/// an owner-loss terminal, which records that no result was written. +pub(super) async fn read(fabric: &MemoryFabric, owner: &str, run: &str) -> anyhow::Result> { + let key = crate::session_worker::protocol::worker_result_key(run); + let Some(event) = fabric + .memory() + .find_owned_message_event_by_idempotency_key(fabric.workspace_id(), owner, &key) + .await? + else { + return Ok(None); + }; + anyhow::ensure!( + event.id > 0 + && event.workspace_id == fabric.workspace_id() + && event.owner_id.as_deref() == Some(owner) + && event.run_id.as_deref() == Some(run) + && event.role == "event" + && event.event_type == "worker.result.created" + && event.idempotency_key.as_deref() == Some(key.as_str()), + "stored worker result differs from its run" + ); + let payload: serde_json::Value = serde_json::from_str( + event + .raw_payload_json + .as_deref() + .context("stored worker result payload missing")?, + )?; + if payload.get("unconfirmed").and_then(serde_json::Value::as_bool) == Some(true) { + return Ok(None); + } + let success = payload + .get("success") + .and_then(serde_json::Value::as_bool) + .context("stored worker result success flag missing")?; + let content = if success { + event.content + } else { + payload + .get("error") + .and_then(serde_json::Value::as_str) + .map_or(event.content, str::to_owned) + }; + let finished_at = chrono::DateTime::parse_from_rfc3339(&event.created_at)?.with_timezone(&chrono::Utc); + Ok(Some(StoredWorkerResult { + success, + content, + finished_at, + })) +} From c5adea7bcf9bf66eabc872ca73de5c965b6747ac Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:57:21 +0400 Subject: [PATCH 0065/1567] fix(tools): resolve join batches and run ids from the durable batch journal --- src/tools/sessions_spawn/batch.rs | 99 ++++++++++++++--------- src/tools/sessions_spawn/batch_journal.rs | 55 +++++++++++++ 2 files changed, 115 insertions(+), 39 deletions(-) diff --git a/src/tools/sessions_spawn/batch.rs b/src/tools/sessions_spawn/batch.rs index 186197766..7b7570298 100644 --- a/src/tools/sessions_spawn/batch.rs +++ b/src/tools/sessions_spawn/batch.rs @@ -624,21 +624,6 @@ impl SessionsSpawnTool { batch_id: &str, owner_scope: &sessions_read_model::RunOwnerScope, ) -> anyhow::Result { - // A run id names exactly one batch; accept it where a batch id is expected. - let run_lookup = self.run_batch_lookup(batch_id, owner_scope).await; - let batch_id = match &run_lookup { - RunBatchLookup::InBatch(batch) => batch.as_str(), - RunBatchLookup::NoBatch => { - return Ok(ToolResult { - success: false, - output: String::new(), - error: Some(format!( - "'{batch_id}' is a run id, and that run belongs to no batch: join takes the batch_id returned by spawn_batch." - )), - }); - } - RunBatchLookup::NotARun => batch_id, - }; let caller = crate::tools::execution::current_child_call_context(); if let Some(caller) = &caller { caller.verify_tool("sessions_spawn")?; @@ -649,32 +634,64 @@ impl SessionsSpawnTool { if let (Some(publication), Some(caller)) = (publication, caller.as_ref()) { publication.verify_caller(caller.context())?; } - let recording_enabled = publication.map_or(self.event_recording.enabled, |publication| { - publication - .generation() - .effective - .memory - .event_recording_config() - .enabled - }); + // Durable batch state is read whether or not this tool instance + // launched the batch: a later process holds none of the launcher's + // memory. Nothing is written here, so recording being off only means + // there is nothing to find. let source_fabric = publication .map(|publication| publication.source_fabric()) .or_else(|| self.memory_fabric()); - let recorded = if recording_enabled { - if let Some(fabric) = source_fabric { - batch_journal::read( - &fabric, - std::path::Path::new(fabric.workspace_id()), - batch_id, - owner_scope, - ) - .await? - } else { - None + // A run id names exactly one batch; accept it where a batch id is + // expected. The registry row of a run restored by a later process + // carries no batch id, so the durable journal answers for it. + let run_lookup = self.run_batch_lookup(batch_id, owner_scope).await; + let (known_run, run_owner) = match &run_lookup { + RunBatchLookup::InBatch(..) => (true, None), + RunBatchLookup::NoBatch { owner } => (true, owner.clone()), + RunBatchLookup::NotARun => (false, None), + }; + let resolved: Option = match &run_lookup { + RunBatchLookup::InBatch(batch) => Some(batch.clone()), + RunBatchLookup::NoBatch { .. } | RunBatchLookup::NotARun => { + let owner = run_owner.or_else(|| match owner_scope { + sessions_read_model::RunOwnerScope::Owner(Some(owner)) => Some(owner.clone()), + _ => None, + }); + match (source_fabric.as_ref(), owner) { + (Some(fabric), Some(owner)) => { + batch_journal::batch_of_run(fabric, &owner, batch_id, owner_scope).await? + } + _ => None, + } } + }; + if resolved.is_none() && known_run { + return Ok(ToolResult { + success: false, + output: String::new(), + error: Some(format!( + "'{batch_id}' is a run id, and that run belongs to no batch: join takes the batch_id returned by spawn_batch." + )), + }); + } + let batch_id = resolved.as_deref().unwrap_or(batch_id); + let recorded = if let Some(fabric) = source_fabric.as_ref() { + batch_journal::read( + fabric, + std::path::Path::new(fabric.workspace_id()), + batch_id, + owner_scope, + ) + .await? } else { None }; + tracing::debug!( + publication = publication.is_some(), + fabric = source_fabric.is_some(), + journal_roster = recorded.is_some(), + "sessions_spawn join resolved batch membership" + ); let members = if let Some(roster) = recorded { roster.members } else { @@ -706,9 +723,12 @@ impl SessionsSpawnTool { runs.iter() .find(|run| run.id == id && owner_scope.admits(run.owner_id.as_deref(), run.agent_partition.as_ref())) .map_or(RunBatchLookup::NotARun, |run| { - run.batch_id - .clone() - .map_or(RunBatchLookup::NoBatch, RunBatchLookup::InBatch) + run.batch_id.clone().map_or_else( + || RunBatchLookup::NoBatch { + owner: run.owner_id.clone(), + }, + RunBatchLookup::InBatch, + ) }) } @@ -759,8 +779,9 @@ impl SessionsSpawnTool { enum RunBatchLookup { /// The id is a run id; this is the batch that run belongs to. InBatch(String), - /// The id is a run id whose run is in no batch. - NoBatch, + /// The id is a run id whose registry row names no batch, with the owner + /// of that row. + NoBatch { owner: Option }, /// The id is not a run id on file: treat it as a batch id. NotARun, } diff --git a/src/tools/sessions_spawn/batch_journal.rs b/src/tools/sessions_spawn/batch_journal.rs index b808dbada..7e0f13ad7 100644 --- a/src/tools/sessions_spawn/batch_journal.rs +++ b/src/tools/sessions_spawn/batch_journal.rs @@ -304,6 +304,61 @@ pub(super) async fn read( })) } +/// The batch whose durable plan names `run`, among the plans `owner` wrote, +/// or `None` when no visible batch holds it. A candidate is accepted only +/// after [`read`] has verified its seal and admitted it to `owners`. +pub(super) async fn batch_of_run( + fabric: &MemoryFabric, + owner: &str, + run: &str, + owners: &crate::tools::sessions_read_model::RunOwnerScope, +) -> anyhow::Result> { + const PAGE: usize = 128; + const MAX_PAGES: usize = 16; + let mut after = 0; + for _ in 0..MAX_PAGES { + let page = fabric + .memory() + .list_owned_message_events_by_type(fabric.workspace_id(), owner, "worker.batch.plan", after, PAGE) + .await?; + for event in &page { + after = after.max(event.id); + let Some(batch) = event + .idempotency_key + .as_deref() + .and_then(|key| key.strip_prefix("batch:")) + .and_then(|key| key.strip_suffix(":plan")) + else { + continue; + }; + // Cheap unauthenticated filter; the sealed read below decides. + let names_run = event + .raw_payload_json + .as_deref() + .and_then(|payload| serde_json::from_str::(payload).ok()) + .and_then(|payload| { + payload.pointer("/fields/members").and_then(serde_json::Value::as_array).map(|members| { + members + .iter() + .any(|member| member.get("run_id").and_then(serde_json::Value::as_str) == Some(run)) + }) + }) + .unwrap_or(false); + if !names_run { + continue; + } + let roster = read(fabric, std::path::Path::new(fabric.workspace_id()), batch, owners).await?; + if roster.is_some_and(|roster| roster.members.iter().any(|member| member.run_id == run)) { + return Ok(Some(batch.to_owned())); + } + } + if page.len() < PAGE { + break; + } + } + Ok(None) +} + fn verify( event: &crate::memory::MessageEvent, workspace: &str, From 92263f2f2b1fc0cc8052819b79affe64aa2886bc Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:05:21 +0400 Subject: [PATCH 0066/1567] fix(tools): keep the join run-id journal scan within the listing bounds and off the batch-id path --- src/tools/sessions_spawn/batch.rs | 149 +++++++++++++++------- src/tools/sessions_spawn/batch_journal.rs | 13 +- 2 files changed, 113 insertions(+), 49 deletions(-) diff --git a/src/tools/sessions_spawn/batch.rs b/src/tools/sessions_spawn/batch.rs index 7b7570298..98fe92f37 100644 --- a/src/tools/sessions_spawn/batch.rs +++ b/src/tools/sessions_spawn/batch.rs @@ -641,62 +641,54 @@ impl SessionsSpawnTool { let source_fabric = publication .map(|publication| publication.source_fabric()) .or_else(|| self.memory_fabric()); + let mut trace = JoinTrace { + publication: publication.is_some(), + fabric: source_fabric.is_some(), + journal_roster: false, + run_scan: false, + }; // A run id names exactly one batch; accept it where a batch id is // expected. The registry row of a run restored by a later process // carries no batch id, so the durable journal answers for it. let run_lookup = self.run_batch_lookup(batch_id, owner_scope).await; - let (known_run, run_owner) = match &run_lookup { - RunBatchLookup::InBatch(..) => (true, None), - RunBatchLookup::NoBatch { owner } => (true, owner.clone()), - RunBatchLookup::NotARun => (false, None), - }; - let resolved: Option = match &run_lookup { - RunBatchLookup::InBatch(batch) => Some(batch.clone()), - RunBatchLookup::NoBatch { .. } | RunBatchLookup::NotARun => { - let owner = run_owner.or_else(|| match owner_scope { - sessions_read_model::RunOwnerScope::Owner(Some(owner)) => Some(owner.clone()), - _ => None, - }); - match (source_fabric.as_ref(), owner) { - (Some(fabric), Some(owner)) => { - batch_journal::batch_of_run(fabric, &owner, batch_id, owner_scope).await? + let mut batch = batch_id.to_owned(); + match &run_lookup { + RunBatchLookup::InBatch(known) => batch.clone_from(known), + RunBatchLookup::NoBatch { owner } => { + trace.run_scan = true; + let resolved = Self::scan_batch_of_run(source_fabric.as_ref(), owner.clone(), batch_id, owner_scope).await?; + match resolved { + Some(found) => batch = found, + None => { + return Ok(ToolResult { + success: false, + output: String::new(), + error: Some(format!( + "'{batch_id}' is a run id, and that run belongs to no batch: join takes the batch_id returned by spawn_batch." + )), + }); } - _ => None, } } - }; - if resolved.is_none() && known_run { - return Ok(ToolResult { - success: false, - output: String::new(), - error: Some(format!( - "'{batch_id}' is a run id, and that run belongs to no batch: join takes the batch_id returned by spawn_batch." - )), - }); + RunBatchLookup::NotARun => {} } - let batch_id = resolved.as_deref().unwrap_or(batch_id); - let recorded = if let Some(fabric) = source_fabric.as_ref() { - batch_journal::read( - fabric, - std::path::Path::new(fabric.workspace_id()), - batch_id, - owner_scope, - ) - .await? - } else { - None - }; - tracing::debug!( - publication = publication.is_some(), - fabric = source_fabric.is_some(), - journal_roster = recorded.is_some(), - "sessions_spawn join resolved batch membership" - ); - let members = if let Some(roster) = recorded { - roster.members - } else { - self.batch_members(batch_id, owner_scope).await - }; + let mut members = self + .journal_or_registry_members(source_fabric.as_ref(), &batch, owner_scope, &mut trace) + .await?; + // Only an id that is no known batch is looked up as a run id, so a + // batch known here or in the journal never reaches the journal scan. + if members.is_empty() && matches!(run_lookup, RunBatchLookup::NotARun) { + trace.run_scan = true; + if let Some(found) = + Self::scan_batch_of_run(source_fabric.as_ref(), None, batch_id, owner_scope).await? + { + batch = found; + members = self + .journal_or_registry_members(source_fabric.as_ref(), &batch, owner_scope, &mut trace) + .await?; + } + } + let batch_id = batch.as_str(); if members.is_empty() { return Ok(ToolResult { success: false, @@ -708,6 +700,7 @@ impl SessionsSpawnTool { }); } + drop(trace); let settled = join_batch_members(&self.active_runs, &members).await; Ok(ToolResult { success: true, @@ -716,6 +709,46 @@ impl SessionsSpawnTool { }) } + /// The batch's members from the durable journal, else from this tool + /// instance's roster and registry. + async fn journal_or_registry_members( + &self, + fabric: Option<&crate::memory::MemoryFabric>, + batch: &str, + owner_scope: &sessions_read_model::RunOwnerScope, + trace: &mut JoinTrace, + ) -> anyhow::Result> { + let recorded = if let Some(fabric) = fabric { + batch_journal::read(fabric, std::path::Path::new(fabric.workspace_id()), batch, owner_scope).await? + } else { + None + }; + trace.journal_roster |= recorded.is_some(); + Ok(match recorded { + Some(roster) => roster.members, + None => self.batch_members(batch, owner_scope).await, + }) + } + + /// The batch a durable plan places `run` in. The owner is the registry + /// row's, else the one the caller's scope is confined to; with neither + /// there is nothing to list under. + async fn scan_batch_of_run( + fabric: Option<&crate::memory::MemoryFabric>, + row_owner: Option, + run: &str, + owner_scope: &sessions_read_model::RunOwnerScope, + ) -> anyhow::Result> { + let owner = row_owner.or_else(|| match owner_scope { + sessions_read_model::RunOwnerScope::Owner(Some(owner)) => Some(owner.clone()), + _ => None, + }); + match (fabric, owner) { + (Some(fabric), Some(owner)) => batch_journal::batch_of_run(fabric, &owner, run, owner_scope).await, + _ => Ok(None), + } + } + /// Whether `id` is the id of a run on file that this caller may see, and /// the batch that run belongs to. async fn run_batch_lookup(&self, id: &str, owner_scope: &sessions_read_model::RunOwnerScope) -> RunBatchLookup { @@ -785,3 +818,23 @@ enum RunBatchLookup { /// The id is not a run id on file: treat it as a batch id. NotARun, } + +/// What one join consulted, logged when the join ends on any path (no ids). +struct JoinTrace { + publication: bool, + fabric: bool, + journal_roster: bool, + run_scan: bool, +} + +impl Drop for JoinTrace { + fn drop(&mut self) { + tracing::debug!( + publication = self.publication, + fabric = self.fabric, + journal_roster = self.journal_roster, + run_scan = self.run_scan, + "sessions_spawn join resolved batch membership" + ); + } +} diff --git a/src/tools/sessions_spawn/batch_journal.rs b/src/tools/sessions_spawn/batch_journal.rs index 7e0f13ad7..d5a521498 100644 --- a/src/tools/sessions_spawn/batch_journal.rs +++ b/src/tools/sessions_spawn/batch_journal.rs @@ -244,6 +244,7 @@ pub(super) async fn read( .find_message_event_by_idempotency_key(fabric.workspace_id(), &lookup) .await? else { + tracing::debug!("batch journal: no plan row under the batch key"); return Ok(None); }; let parsed: Signed = serde_json::from_str(plan.raw_payload_json.as_deref().context("batch payload missing")?)?; @@ -255,6 +256,7 @@ pub(super) async fn read( )?; let plan_fields = verify(&plan, fabric.workspace_id(), batch, "plan", &key)?; if !owners.admits(plan.owner_id.as_deref(), plan_fields.ordinary_source.partition.as_ref()) { + tracing::debug!("batch journal: plan row exists but is not admitted to the caller scope"); return Ok(None); } @@ -313,8 +315,17 @@ pub(super) async fn batch_of_run( run: &str, owners: &crate::tools::sessions_read_model::RunOwnerScope, ) -> anyhow::Result> { - const PAGE: usize = 128; + // The listing accepts 1..=100 rows per page (`list_owned_message_events_by_type_impl` + // in the sqlite store, mirrored by the postgres store); it exports no constant. + const PAGE: usize = 100; const MAX_PAGES: usize = 16; + // The listing also requires a non-empty workspace, owner and type and a + // non-negative cursor: the workspace is the fabric's, the type is the + // constant below, the cursor starts at 0 and only grows, and an empty owner + // is refused here as "no batch" rather than as a listing error. + if owner.is_empty() { + return Ok(None); + } let mut after = 0; for _ in 0..MAX_PAGES { let page = fabric From b207427b207f55e96d3fdf71fd9af2628321beed Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:32:50 +0400 Subject: [PATCH 0067/1567] fix(memory): checked statfs type conversion with a typed error in SQLite ingress recovery --- src/memory/sqlite/ingress_recovery.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/memory/sqlite/ingress_recovery.rs b/src/memory/sqlite/ingress_recovery.rs index 2e1a41897..1b72cc544 100644 --- a/src/memory/sqlite/ingress_recovery.rs +++ b/src/memory/sqlite/ingress_recovery.rs @@ -922,13 +922,19 @@ mod local { }) } + /// The kernel reported a filesystem magic number that is not a valid + /// unsigned value, so it cannot match any admitted local filesystem. + #[derive(Debug, thiserror::Error)] + #[error("filesystem type reported by the kernel is out of range")] + struct FilesystemTypeOutOfRange; + /// Only known local filesystems are admitted. NFS/CIFS/FUSE and unknown /// types cannot supply this single-host lifetime proof. fn local_filesystem(file: &File) -> anyhow::Result<()> { #[cfg(any(target_os = "linux", target_os = "android"))] { let stat = rustix::fs::fstatfs(file)?; - let kind = stat.f_type as u64; + let kind = u64::try_from(stat.f_type).map_err(|_| FilesystemTypeOutOfRange)?; anyhow::ensure!( matches!( kind, From 4c56394e0a3e5f97df9424b565eb089e8a59b0fc Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:57:03 +0400 Subject: [PATCH 0068/1567] fix(memory): record message event ids on context pages and delete pages by event id --- docs/rf-contract/capability-tokens.md | 30 ++++--- src/agent/context_paging.rs | 16 +++- src/agent/mod.rs | 1 + src/agent/page_sources.rs | 89 +++++++++++++++++++ src/agent/turn_engine.rs | 19 ++-- src/agent/turn_history.rs | 117 +++++++++++++++++++++++-- src/agent/turn_request.rs | 13 +++ src/agent/turn_tests/context_recall.rs | 1 + src/gateway/api/sessions/section_1.rs | 9 +- src/gateway/api/sessions/section_3.rs | 1 + src/memory/encrypted_scope.rs | 1 + src/memory/postgres/events.rs | 1 + src/memory/postgres/memory_impl.rs | 1 + src/memory/sqlite/events/section_1.rs | 2 +- src/memory/sqlite/events/section_2.rs | 5 +- src/memory/sqlite/rf_delete.rs | 9 +- src/memory/sqlite/rf_forget.rs | 31 +++++-- src/memory/traits.rs | 4 + 18 files changed, 305 insertions(+), 45 deletions(-) create mode 100644 src/agent/page_sources.rs diff --git a/docs/rf-contract/capability-tokens.md b/docs/rf-contract/capability-tokens.md index 8e8178db6..c02432cc7 100644 --- a/docs/rf-contract/capability-tokens.md +++ b/docs/rf-contract/capability-tokens.md @@ -466,17 +466,25 @@ code). Only memories and documents are forgotten: other tool side effects **Context pages.** From the commit that advertises `message_forget_writes_v1`, every delete (with or without `forget_writes`) also deletes the agent's -OS-paging context-page documents of the session that hold a deleted row (a -page written during the deleted turn, or a page whose text holds the deleted -text). They are not counted in `forgotten`. - -How a page is matched today: by the input event of the turn in which the page -was written, or by the page text containing the first non-blank line of the -deleted message (at most 64 characters). The match is by text, not by message -id, so a very short message (for example `ok`) can remove other context pages -of the same agent and session. Context pages are recall copies; transcripts -and other sessions are never touched by this match. A client should tell the -user that deleting a short message may also drop older recall context. +OS-paging context-page documents of the session that hold a deleted row. They +are not counted in `forgotten`. + +How a page is matched: a context page records the event ids it was built from +(`message_event_ids`: the stored events of the paged messages; +`turn_event_ids`: the input event of the turn, when the page holds that turn's +own output). A delete removes a page when one of its `message_event_ids` is a +deleted event, or when the deleted message's input event is in its +`turn_event_ids`. The match is by message id, so deleting a short message (for +example `ok`) removes only the pages that hold that message. A page that holds +the deleted message is removed whole; the page's other messages stay in the +transcript and are paged again by a later eviction, and are not recallable in +the meantime. A reply delete does not remove a page that holds only the user +input. Context pages written before pages recorded ids carry no id arrays and +are still matched by their source event or by the text of the deleted message +(its first non-blank line, at most 64 characters); only those older pages can +be over-matched by a short message. Pages written by the terminal chat carry no +ids. Context pages are recall copies; transcripts and other sessions are never +touched by this match. **Replay.** A resend of a deleted message's key (`POST …/message` with that `client_message_id` for that agent) is `409 message_deleted`. The deleted mark diff --git a/src/agent/context_paging.rs b/src/agent/context_paging.rs index 5df038080..cf0871f4a 100644 --- a/src/agent/context_paging.rs +++ b/src/agent/context_paging.rs @@ -1,6 +1,7 @@ use crate::agent::compaction::COMPACTION_MAX_SUMMARY_CHARS; use crate::agent::context_budget::{estimate_history_tokens, plan_context_budget}; use crate::agent::document_ingest::DocumentIngestRuntime; +use crate::agent::page_sources::{MessageSources, PageEventIds}; #[cfg(test)] use crate::agent::history::drop_orphan_tool_results_at; use crate::agent::response_guard::strip_quoted_fabricated_tool_markers; @@ -67,7 +68,7 @@ pub(super) async fn apply_os_paging( config: &crate::config::AgentCompactionConfig, runtime: Option<&DocumentIngestRuntime>, ) -> Result { - let Some(eviction) = plan_os_paging(history, config, runtime).await? else { + let Some(eviction) = plan_os_paging(history, &[], config, runtime).await? else { return Ok(false); }; eviction.apply_to(history); @@ -101,8 +102,13 @@ impl OsPagingEviction { /// Plan an OS-paging eviction of `history` and write its page to the document /// store; the caller applies the returned eviction. `Ok(None)` when nothing is /// evicted (all failures are soft, as for [`apply_os_paging`]). +/// +/// `sources` is index-aligned with `history`; the evicted messages' event ids +/// are recorded in the page's metadata. A shorter slice records no ids for the +/// messages it does not cover. pub(super) async fn plan_os_paging( history: &[ChatMessage], + sources: &[MessageSources], config: &crate::config::AgentCompactionConfig, runtime: Option<&DocumentIngestRuntime>, ) -> Result> { @@ -157,6 +163,10 @@ pub(super) async fn plan_os_paging( } let transcript = build_page_transcript(to_evict); + let page_ids = PageEventIds::from_sources( + sources.get(start..evict_end).unwrap_or_default(), + runtime.source_message_event_id.as_deref(), + ); let token_count = estimate_history_tokens(to_evict); let evicted_message_count: usize = to_evict.len(); let timestamp = chrono::Utc::now().to_rfc3339(); @@ -170,6 +180,8 @@ pub(super) async fn plan_os_paging( hasher.update(session_key.as_bytes()); hasher.update(b"\0"); hasher.update(transcript.as_bytes()); + hasher.update(b"\0"); + hasher.update(page_ids.hash_bytes()); let digest = hex::encode(hasher.finalize()); let short = digest.get(..16).unwrap_or(&digest); let document_id = format!("context-page:{session_key}:{short}"); @@ -180,6 +192,8 @@ pub(super) async fn plan_os_paging( "evicted_at": timestamp, "message_count": to_evict.len(), "token_count": token_count, + "message_event_ids": page_ids.message_event_ids, + "turn_event_ids": page_ids.turn_event_ids, }) .to_string(); let input = DocumentIngestInput { diff --git a/src/agent/mod.rs b/src/agent/mod.rs index ee5a32b94..32e0eac87 100644 --- a/src/agent/mod.rs +++ b/src/agent/mod.rs @@ -18,6 +18,7 @@ pub(crate) mod history; pub mod idle; pub(crate) mod live_frames; pub mod memory_loader; +pub(crate) mod page_sources; pub mod prompt; pub(crate) mod prompt_cache_metrics; pub(crate) mod provider_round; diff --git a/src/agent/page_sources.rs b/src/agent/page_sources.rs new file mode 100644 index 000000000..69245ae38 --- /dev/null +++ b/src/agent/page_sources.rs @@ -0,0 +1,89 @@ +//! The message event ids a context page was built from. +//! +//! A canonical message may derive from stored `message_events` rows (a stored +//! turn, the request) or from this turn's own output, whose events are not yet +//! written. [`MessageSources`] records that per message; an OS-paging eviction +//! folds the sources of the evicted messages into the two arrays stored in the +//! page's `metadata_json`, so a message delete removes exactly the pages that +//! hold the deleted event (see `rf_forget::erase_context_pages`). + +use std::collections::BTreeSet; + +/// Where one canonical message came from, as event ids. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub(crate) struct MessageSources { + /// Stored `message_events.event_id` values the message derives from. + event_ids: Vec, + /// The message was appended by the running turn, whose events are written + /// after it (the turn's input event is the page's turn event). + turn_round: bool, +} + +impl MessageSources { + /// A stored turn (or the request) with its event id, when it has one. + pub(crate) fn stored(event_id: Option<&str>) -> Self { + Self { + event_ids: event_id.map(str::to_owned).into_iter().collect(), + turn_round: false, + } + } + + /// A message the running turn appended. + pub(crate) fn turn_round() -> Self { + Self { + event_ids: Vec::new(), + turn_round: true, + } + } + + /// The union of `sources`: a message derived from all of them. + pub(crate) fn union(sources: &[Self]) -> Self { + let event_ids: BTreeSet<&String> = sources.iter().flat_map(|source| &source.event_ids).collect(); + Self { + event_ids: event_ids.into_iter().cloned().collect(), + turn_round: sources.iter().any(|source| source.turn_round), + } + } +} + +/// The two id arrays a page records. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub(crate) struct PageEventIds { + /// Sorted, deduplicated union of the evicted messages' event ids. + pub(crate) message_event_ids: Vec, + /// The running turn's input event id when an evicted message is this + /// turn's own output, otherwise empty. + pub(crate) turn_event_ids: Vec, +} + +impl PageEventIds { + /// Fold the evicted messages' `sources` into the page arrays. + /// `turn_event_id` is the running turn's input event id, if it has one. + pub(crate) fn from_sources(sources: &[MessageSources], turn_event_id: Option<&str>) -> Self { + let union = MessageSources::union(sources); + Self { + message_event_ids: union.event_ids, + turn_event_ids: turn_event_id + .filter(|_| union.turn_round) + .map(str::to_owned) + .into_iter() + .collect(), + } + } + + /// Bytes mixed into the page's content-addressed id, so identical text + /// from different messages never shares a page. + pub(crate) fn hash_bytes(&self) -> Vec { + let mut bytes = Vec::new(); + for id in &self.message_event_ids { + bytes.extend_from_slice(id.as_bytes()); + bytes.push(b'\n'); + } + bytes.push(0); + for id in &self.turn_event_ids { + bytes.extend_from_slice(id.as_bytes()); + bytes.push(b'\n'); + } + bytes + } +} diff --git a/src/agent/turn_engine.rs b/src/agent/turn_engine.rs index bd900d2d1..c2bc2f28a 100644 --- a/src/agent/turn_engine.rs +++ b/src/agent/turn_engine.rs @@ -258,15 +258,6 @@ fn middleware_messages(history: &[ChatMessage], transformed: &serde_json::Value) /// durable compaction changed it: the turn's projection (recalled page, /// skill-metadata suppression, inbound middleware) over the canonical /// history. The per-provider preflight trims it again before the next request. -/// Whether this turn's history holds a context handoff: its canonical history -/// does (a per-request trim may have left the handoff out of the view), or the -/// provider view does (stored or rendered, both start with the marker). The -/// one test both the recovery-tool check and its publication use. -fn turn_holds_context_handoff(turn_history: &TurnHistory, view: &[ChatMessage]) -> bool { - crate::agent::compaction::holds_context_handoff(turn_history.canonical(view)) - || crate::agent::compaction::holds_context_handoff(view) -} - async fn rederive_provider_view( turn_history: &mut TurnHistory, history: &mut Vec, @@ -451,6 +442,7 @@ async fn run_turn_unguarded( tool_surface_reserve, canonical_history, caller_rollover, + history_event_ids, } = memory_runtime; // A session authority adopts this turn's durable compactions as patches // over its acknowledged history, so the turn must build them from that @@ -461,7 +453,8 @@ async fn run_turn_unguarded( ); // The canonical history every durable compaction of this turn is built // from; `history` is the provider view projected from it. - let mut turn_history = TurnHistory::new(history, canonical_history, caller_rollover); + let mut turn_history = + TurnHistory::new(history, canonical_history, caller_rollover).with_history_event_ids(history_event_ids); anyhow::ensure!( Arc::ptr_eq(turn_runtime, context.runtime()), "turn runtime context differs from the opened decision context" @@ -521,7 +514,7 @@ async fn run_turn_unguarded( // mode above the 0.85 threshold. if let Some(config) = compaction_config { let switch_needs_lookup = matches!(config.mode, crate::config::AgentCompactionMode::Switch) - && (turn_holds_context_handoff(&turn_history, history) + && (turn_history.holds_context_handoff(history) || plan_context_budget(history, config, PRE_TURN_FLUSH_THRESHOLD).over_warning); if switch_needs_lookup && !tools_registry @@ -549,7 +542,7 @@ async fn run_turn_unguarded( if plan_context_budget(history, config, config.os_paging.eviction_threshold).over_warning { let canonical = turn_history.canonical_mut(history); let before = history_before_change(&runtime_adapter, canonical); - match plan_os_paging(canonical.messages(), config, document_ingest.as_ref()).await { + match plan_os_paging(canonical.messages(), canonical.sources(), config, document_ingest.as_ref()).await { Ok(Some(eviction)) if canonical.apply_page_eviction(&eviction) => { crate::agent::idle::beat(crate::agent::idle::ProgressKind::Compaction); tracing::debug!("os-paging: pre-turn eviction applied"); @@ -905,7 +898,7 @@ async fn run_turn_unguarded( // handoff tells the model to call. let context_lookup_required = compaction_config .is_some_and(|config| matches!(config.mode, crate::config::AgentCompactionMode::Switch)) - && turn_holds_context_handoff(&turn_history, history); + && turn_history.holds_context_handoff(history); if context_lookup_required && !selected_tools .iter() diff --git a/src/agent/turn_history.rs b/src/agent/turn_history.rs index e9f21fa59..3b2fcfb84 100644 --- a/src/agent/turn_history.rs +++ b/src/agent/turn_history.rs @@ -28,6 +28,7 @@ use crate::agent::compaction::render_context_handoff_for_provider; use crate::agent::context_paging::inject_recalled_context; +use crate::agent::page_sources::MessageSources; use crate::agent::tool_evidence::{TurnToolEvidence, render_assistant_content}; use crate::agent::turn_contracts::{inbound_user_message, stored_turn_message}; use crate::providers::ChatMessage; @@ -96,6 +97,9 @@ pub(crate) struct CanonicalHistory { /// One evidence slot per message, index for index; only an acknowledged /// assistant message's slot can be filled. evidence: Vec>>, + /// One set of source event ids per message, index for index; an evicted + /// context page records the union over its messages. + sources: Vec, } impl PartialEq for CanonicalHistory { @@ -108,10 +112,12 @@ impl CanonicalHistory { fn with_origin(messages: Vec, origin: MessageOrigin) -> Self { let origins = vec![origin; messages.len()]; let evidence = vec![None; messages.len()]; + let sources = vec![MessageSources::default(); messages.len()]; Self { messages, origins, evidence, + sources, } } @@ -191,6 +197,7 @@ impl CanonicalHistory { .collect(); let mut origins = vec![MessageOrigin::Acknowledged; messages.len()]; let mut evidence = vec![None; messages.len()]; + let mut sources = vec![MessageSources::default(); messages.len()]; for (index, (role, content, turn_evidence)) in turns.into_iter().enumerate() { if !matches!(role, "user" | "assistant") { continue; @@ -203,11 +210,17 @@ impl CanonicalHistory { messages.push(stored_turn_message(role.to_owned(), content.to_owned())); origins.push(origin); evidence.push(turn_evidence.filter(|_| role == "assistant")); + sources.push(if origin == MessageOrigin::Request { + MessageSources::turn_round() + } else { + MessageSources::default() + }); } Self { messages, origins, evidence, + sources, } } @@ -217,6 +230,7 @@ impl CanonicalHistory { self.messages.push(inbound_user_message(request)); self.origins.push(MessageOrigin::Request); self.evidence.push(None); + self.sources.push(MessageSources::turn_round()); self } @@ -230,6 +244,34 @@ impl CanonicalHistory { Self::with_origin(messages.to_vec(), MessageOrigin::CallerSupplied) } + /// As [`Self::of_caller_without_session`], for a view the running turn + /// started with `started_len` messages and then appended to. `event_ids` + /// gives the stored event of each started message, index for index + /// (`None` for a message with no stored event); it is used only when it + /// covers exactly the started messages. The messages after them were + /// appended by the running turn. + pub(crate) fn of_caller_with_event_ids( + messages: &[ChatMessage], + started_len: usize, + event_ids: &[Option], + ) -> Self { + let mut canonical = Self::of_caller_without_session(messages); + let known = event_ids.len() == started_len; + for (index, slot) in canonical.sources.iter_mut().enumerate() { + if index >= started_len { + *slot = MessageSources::turn_round(); + } else if known { + *slot = MessageSources::stored(event_ids.get(index).and_then(Option::as_deref)); + } + } + canonical + } + + /// Per message, index for index, the event ids it derives from. + pub(crate) fn sources(&self) -> &[MessageSources] { + &self.sources + } + pub(crate) fn messages(&self) -> &[ChatMessage] { &self.messages } @@ -254,17 +296,27 @@ impl CanonicalHistory { self.origins .extend(std::iter::repeat_n(MessageOrigin::TurnRound, appended.len())); self.evidence.extend(std::iter::repeat_n(None, appended.len())); + self.sources + .extend(std::iter::repeat_n(MessageSources::turn_round(), appended.len())); } /// Replace `self[start..end]` with `replacement`, every new message of - /// `origin` and without evidence. `false` (and `self` unchanged) when the - /// range is not inside the history or the per-message lists disagree in - /// length. - fn splice(&mut self, start: usize, end: usize, replacement: &[ChatMessage], origin: MessageOrigin) -> bool { + /// `origin`, without evidence and with `sources`. `false` (and `self` + /// unchanged) when the range is not inside the history or the per-message + /// lists disagree in length. + fn splice( + &mut self, + start: usize, + end: usize, + replacement: &[ChatMessage], + origin: MessageOrigin, + sources: &MessageSources, + ) -> bool { if start > end || end > self.messages.len() || self.origins.len() != self.messages.len() || self.evidence.len() != self.messages.len() + || self.sources.len() != self.messages.len() { return false; } @@ -273,9 +325,17 @@ impl CanonicalHistory { .splice(start..end, std::iter::repeat_n(origin, replacement.len())); self.evidence .splice(start..end, std::iter::repeat_n(None, replacement.len())); + self.sources + .splice(start..end, std::iter::repeat_n(sources.clone(), replacement.len())); true } + /// The union of the sources of `self[start..end]`, which a replacement of + /// that range derives from. + fn range_sources(&self, start: usize, end: usize) -> MessageSources { + MessageSources::union(self.sources.get(start..end).unwrap_or_default()) + } + /// The guard of a patch that replaces `self[range_start..]`. pub(crate) fn guard_from(&self, range_start: usize) -> Option { crate::agent::compaction::compaction_patch_guard_for(&self.messages, range_start, self.messages.len()) @@ -317,7 +377,8 @@ impl CanonicalHistory { ) -> Result { self.check_patch(patch)?; let (start, end) = (patch.range_start(), patch.range_end()); - if !self.splice(start, end, &patch.replacement, MessageOrigin::Acknowledged) { + let derived = self.range_sources(start, end); + if !self.splice(start, end, &patch.replacement, MessageOrigin::Acknowledged, &derived) { return Err(crate::agent::turn_contracts::CompactionPatchError::RangeOutOfBounds { start, end, @@ -339,7 +400,13 @@ impl CanonicalHistory { patch: &crate::agent::turn_contracts::CompactionPatch, ) -> Result<(), crate::agent::turn_contracts::CompactionPatchError> { let notes = self.apply_patch(patch)?; - if !self.splice(notes.at, notes.at, ¬es.notes, MessageOrigin::RefreshAside) { + if !self.splice( + notes.at, + notes.at, + ¬es.notes, + MessageOrigin::RefreshAside, + &MessageSources::default(), + ) { return Err(crate::agent::turn_contracts::CompactionPatchError::RangeOutOfBounds { start: notes.at, end: notes.at, @@ -369,6 +436,7 @@ impl CanonicalHistory { if restored { self.origins.push(MessageOrigin::Request); self.evidence.push(None); + self.sources.push(MessageSources::turn_round()); } restored } @@ -382,6 +450,7 @@ impl CanonicalHistory { eviction.end, std::slice::from_ref(&eviction.breadcrumb), MessageOrigin::Acknowledged, + &MessageSources::default(), ) { return false; } @@ -394,6 +463,9 @@ impl CanonicalHistory { if behind < self.evidence.len() { self.evidence.remove(behind); } + if behind < self.sources.len() { + self.sources.remove(behind); + } } true } @@ -405,11 +477,13 @@ impl CanonicalHistory { let mut kept = Vec::with_capacity(self.messages.len()); let mut kept_origins = Vec::with_capacity(self.origins.len()); let mut kept_evidence = Vec::with_capacity(self.evidence.len()); - for ((message, origin), evidence) in self + let mut kept_sources = Vec::with_capacity(self.sources.len()); + for (((message, origin), evidence), sources) in self .messages .drain(..) .zip(self.origins.drain(..)) .zip(self.evidence.drain(..)) + .zip(self.sources.drain(..)) { if origin == MessageOrigin::RefreshAside { lifted.push((kept.len(), message)); @@ -417,11 +491,13 @@ impl CanonicalHistory { kept.push(message); kept_origins.push(origin); kept_evidence.push(evidence); + kept_sources.push(sources); } } self.messages = kept; self.origins = kept_origins; self.evidence = kept_evidence; + self.sources = kept_sources; lifted } @@ -643,6 +719,9 @@ pub(crate) struct TurnHistory { absorbed_view_len: usize, /// See [`Self::caller_rollover_current`]. caller_rollover_current: bool, + /// The stored event of each message of the view the turn started on, when + /// the caller knows them (see [`Self::with_history_event_ids`]). + history_event_ids: Vec>, projection: ProjectionInputs, #[cfg(feature = "wasm-plugins")] inbound_middleware_applied: bool, @@ -671,12 +750,33 @@ impl TurnHistory { caller_rollover_current: caller_rollover && canonical.is_some(), canonical, absorbed_view_len: view.len(), + history_event_ids: Vec::new(), projection, #[cfg(feature = "wasm-plugins")] inbound_middleware_applied: false, } } + /// Tell the turn the stored event of each message of the view it starts + /// on, index for index (`None` for a message with no stored event). They + /// apply only while the view still has that length when the canonical + /// history is first taken from it. + #[must_use] + pub(crate) fn with_history_event_ids(mut self, event_ids: Vec>) -> Self { + self.history_event_ids = event_ids; + self + } + + /// Whether this turn's history holds a context handoff: its canonical + /// history does (a per-request trim may have left the handoff out of the + /// view), or the provider view does (stored or rendered, both start with + /// the marker). The one test both the recovery-tool check and its + /// publication use. + pub(crate) fn holds_context_handoff(&self, view: &[ChatMessage]) -> bool { + crate::agent::compaction::holds_context_handoff(self.canonical(view)) + || crate::agent::compaction::holds_context_handoff(view) + } + /// Whether the caller's pre-turn rollover over the canonical history it /// supplied is still current: the turn has neither appended to `view` nor /// durably compacted that history since. While it is, no durable @@ -692,8 +792,9 @@ impl TurnHistory { fn catch_up(&mut self, view: &[ChatMessage]) -> &mut CanonicalHistory { let appended = view.get(self.absorbed_view_len..).unwrap_or_default(); let absorbed_any = !appended.is_empty(); + let (started_len, event_ids) = (self.absorbed_view_len, self.history_event_ids.as_slice()); let canonical = self.canonical.take().map_or_else( - || CanonicalHistory::of_caller_without_session(view), + || CanonicalHistory::of_caller_with_event_ids(view, started_len, event_ids), |mut canonical| { canonical.append_turn_messages(appended); canonical diff --git a/src/agent/turn_request.rs b/src/agent/turn_request.rs index d06a340fc..03367c9ed 100644 --- a/src/agent/turn_request.rs +++ b/src/agent/turn_request.rs @@ -156,6 +156,11 @@ pub(crate) struct ToolLoopMemory { /// Whether the caller compacted or trimmed the view before the turn, so /// the view already is a fitting projection of `canonical_history`. pub(super) caller_rollover: bool, + /// The stored event of each message of the turn's initial view, index for + /// index (`None` for a message with no stored event), for a caller whose + /// history carries no canonical history of its own (the console). Empty + /// when the caller knows none. + pub(super) history_event_ids: Vec>, } impl ToolLoopMemory { @@ -169,6 +174,7 @@ impl ToolLoopMemory { tool_surface_reserve: None, canonical_history: None, caller_rollover: false, + history_event_ids: Vec::new(), } } @@ -205,6 +211,13 @@ impl ToolLoopMemory { self } + /// Record the stored event of each message of the turn's initial view, + /// index for index, so an evicted context page names the events it holds. + pub(crate) fn with_history_event_ids(mut self, event_ids: Vec>) -> Self { + self.history_event_ids = event_ids; + self + } + pub(crate) fn with_event_fabric(mut self, event_fabric: MemoryFabric) -> Self { self.event_fabric = Some(event_fabric); self diff --git a/src/agent/turn_tests/context_recall.rs b/src/agent/turn_tests/context_recall.rs index d4459e3b2..51bf0bd04 100644 --- a/src/agent/turn_tests/context_recall.rs +++ b/src/agent/turn_tests/context_recall.rs @@ -974,6 +974,7 @@ fn quoted_turns_and_document_chunks_drop_fabricated_markers_too() { content: content.to_string(), timestamp: "2026-03-05T00:00:00Z".to_string(), message_id: None, + message_event_id: None, }; let turns = vec![ turn("assistant", "Cleaned up. [Used tools: shell, file_write]"), diff --git a/src/gateway/api/sessions/section_1.rs b/src/gateway/api/sessions/section_1.rs index f14135da5..55c2e0a8c 100644 --- a/src/gateway/api/sessions/section_1.rs +++ b/src/gateway/api/sessions/section_1.rs @@ -820,6 +820,12 @@ async fn run_console_runtime_turn( format!("{}{}", mem_context.preamble, visible_message) }; + // The stored event of each history message, index for index: none for the + // system prompt, each stored turn's event, then the request's own event. + let history_event_ids: Vec> = std::iter::once(None) + .chain(previous_turns.iter().map(|turn| turn.message_event_id.clone())) + .chain(std::iter::once(turn_envelope.source_message_event_id.clone())) + .collect(); let mut history = Vec::with_capacity(previous_turns.len() + 2); history.push(ChatMessage::system(system_prompt)); // stored console turns are neutralised like fresh input @@ -942,7 +948,8 @@ async fn run_console_runtime_turn( MemoryFabric::new(state.mem.clone(), turn_envelope.workspace_id.clone()) .with_event_recording(config_snapshot.memory.event_recording_config()), ) - .with_request_event_scope(turn_envelope.message_scope()), + .with_request_event_scope(turn_envelope.message_scope()) + .with_history_event_ids(history_event_ids), }, crate::agent::turn_request::TurnDelivery { cancellation: Some(decision.cancellation.clone()), diff --git a/src/gateway/api/sessions/section_3.rs b/src/gateway/api/sessions/section_3.rs index 51f291cb3..5c4736c8f 100644 --- a/src/gateway/api/sessions/section_3.rs +++ b/src/gateway/api/sessions/section_3.rs @@ -538,6 +538,7 @@ mod tests { content: "previous answer".to_string(), timestamp: "2026-05-27T00:00:00Z".to_string(), message_id: Some("previous-event".to_string()), + message_event_id: Some("previous-event".to_string()), }]; let (runtime, _, _, proof) = diff --git a/src/memory/encrypted_scope.rs b/src/memory/encrypted_scope.rs index 12a3e443a..15cae1adc 100644 --- a/src/memory/encrypted_scope.rs +++ b/src/memory/encrypted_scope.rs @@ -717,6 +717,7 @@ impl Memory for EncryptedScope { .get("message_id") .and_then(|item| item.as_str()) .map(str::to_string), + message_event_id: None, }); } for turns in out.values_mut() { diff --git a/src/memory/postgres/events.rs b/src/memory/postgres/events.rs index 9bda88ecf..bca5eec5c 100644 --- a/src/memory/postgres/events.rs +++ b/src/memory/postgres/events.rs @@ -96,6 +96,7 @@ impl PostgresMemory { content: row.get(3), timestamp: row.get(4), message_id: row.get(5), + message_event_id: None, }) .collect(); turns.reverse(); diff --git a/src/memory/postgres/memory_impl.rs b/src/memory/postgres/memory_impl.rs index 46c40bd1e..89c4865b7 100644 --- a/src/memory/postgres/memory_impl.rs +++ b/src/memory/postgres/memory_impl.rs @@ -1480,6 +1480,7 @@ impl Memory for PostgresMemory { content: row.get(3), timestamp: row.get(4), message_id: row.get(5), + message_event_id: None, }; histories.entry(turn.session_key.clone()).or_default().push(turn); } diff --git a/src/memory/sqlite/events/section_1.rs b/src/memory/sqlite/events/section_1.rs index 8814e3532..4523d981f 100644 --- a/src/memory/sqlite/events/section_1.rs +++ b/src/memory/sqlite/events/section_1.rs @@ -94,7 +94,7 @@ pub(crate) fn conversation_turns_select_sql( "\n AND deleted_at IS NULL" }; format!( - "SELECT id, session_key, role, content, timestamp, message_id, deleted_at IS NOT NULL + "SELECT id, session_key, role, content, timestamp, message_id, deleted_at IS NOT NULL, message_event_id FROM conversation_turns WHERE {session_fragment} AND ( diff --git a/src/memory/sqlite/events/section_2.rs b/src/memory/sqlite/events/section_2.rs index 3ecc6194b..83d97dffd 100644 --- a/src/memory/sqlite/events/section_2.rs +++ b/src/memory/sqlite/events/section_2.rs @@ -75,6 +75,7 @@ impl SqliteMemory { content: row.get(3)?, timestamp: row.get(4)?, message_id: row.get(5)?, + message_event_id: row.get(7)?, }, deleted: row.get(6)?, }) @@ -463,7 +464,7 @@ impl SqliteMemory { let reader = pool.read()?; let conn = reader.connection()?; let mut stmt = conn.prepare( - "SELECT id, session_key, role, content, timestamp, message_id + "SELECT id, session_key, role, content, timestamp, message_id, message_event_id FROM ( SELECT ct.id, @@ -472,6 +473,7 @@ impl SqliteMemory { ct.content, ct.timestamp, ct.message_id, + ct.message_event_id, ROW_NUMBER() OVER (PARTITION BY ct.session_key ORDER BY ct.id DESC) AS row_num FROM conversation_turns ct INNER JOIN ( @@ -501,6 +503,7 @@ impl SqliteMemory { content: row.get(3)?, timestamp: row.get(4)?, message_id: row.get(5)?, + message_event_id: row.get(6)?, }) }, )?; diff --git a/src/memory/sqlite/rf_delete.rs b/src/memory/sqlite/rf_delete.rs index 193863ccc..d71ca22df 100644 --- a/src/memory/sqlite/rf_delete.rs +++ b/src/memory/sqlite/rf_delete.rs @@ -492,7 +492,14 @@ fn erase(tx: &Connection, target: &Target<'_>, side: Side, attempt: &Attempt) -> .filter(|row| row.conversational && !row.content.is_empty()) .map(|row| row.content.as_str()) .collect::>(); - rf_forget::erase_context_pages(tx, target.session_key, attempt.partition(), &direct, &contents)?; + rf_forget::erase_context_pages( + tx, + target.session_key, + attempt.partition(), + &direct, + &attempt.input_event_id, + &contents, + )?; let mut ids = rows.into_iter().map(|row| row.event_id).collect::>(); let mut forgotten = tx.execute( "DELETE FROM memories WHERE source_event_id IN (SELECT value FROM json_each(?1))", diff --git a/src/memory/sqlite/rf_forget.rs b/src/memory/sqlite/rf_forget.rs index 3298267e6..ea2f11cf4 100644 --- a/src/memory/sqlite/rf_forget.rs +++ b/src/memory/sqlite/rf_forget.rs @@ -383,14 +383,20 @@ fn page_probe(content: &str) -> Option { } /// Delete the agent's OS-paging context pages of `session_key` that hold a -/// deleted row: a page ingested during a deleted turn (its source event is a -/// deleted event) or a page whose text holds a deleted row's text. Pages of -/// other agents stay. Not counted as forgotten. +/// deleted row. A page records the event ids it was built from in its +/// metadata: `message_event_ids` (stored events) and `turn_event_ids` (the +/// input event of the turn whose own output the page holds). It is deleted +/// whole when one of its `message_event_ids` is a deleted event (`event_ids`, +/// a JSON array) or `input_event_id` is among its `turn_event_ids`. A page +/// without a `message_event_ids` array (written before pages recorded ids) is +/// matched by its source event or by the text of a deleted row. Pages of other +/// agents stay. Not counted as forgotten. pub(super) fn erase_context_pages( tx: &Connection, session_key: &str, partition: Partition<'_>, event_ids: &str, + input_event_id: &str, contents: &[&str], ) -> anyhow::Result<()> { let probes = serde_json::to_string(&contents.iter().filter_map(|text| page_probe(text)).collect::>())?; @@ -403,10 +409,18 @@ pub(super) fn erase_context_pages( ON o.workspace_id = n.workspace_id AND o.owner_id = n.owner_id AND o.agent_key = n.agent_key AND o.incarnation = n.incarnation WHERE o.scope_id = d.ma_scope_id AND n.scope_id = ?2)) - AND (d.source_message_event_id IN (SELECT value FROM json_each(?4)) - OR (d.source_uri = ?1 AND EXISTS( - SELECT 1 FROM document_chunks c, json_each(?5) p - WHERE c.document_id = d.document_id AND instr(c.content, p.value) > 0)))", + AND d.source_uri = ?1 + AND (EXISTS(SELECT 1 FROM json_each(CASE WHEN json_valid(d.metadata_json) THEN d.metadata_json END, + '$.message_event_ids') m + WHERE m.value IN (SELECT value FROM json_each(?4))) + OR EXISTS(SELECT 1 FROM json_each(CASE WHEN json_valid(d.metadata_json) THEN d.metadata_json END, + '$.turn_event_ids') t + WHERE t.value = ?7) + OR ((CASE WHEN json_valid(d.metadata_json) + THEN json_type(d.metadata_json, '$.message_event_ids') END) IS NULL + AND (d.source_message_event_id IN (SELECT value FROM json_each(?4)) + OR EXISTS(SELECT 1 FROM document_chunks c, json_each(?5) p + WHERE c.document_id = d.document_id AND instr(c.content, p.value) > 0))))", )?; statement .query_map( @@ -416,7 +430,8 @@ pub(super) fn erase_context_pages( partition.main, event_ids, probes, - CONTEXT_PAGE_KIND + CONTEXT_PAGE_KIND, + input_event_id ], |row| row.get::<_, String>(0), )? diff --git a/src/memory/traits.rs b/src/memory/traits.rs index 9a39a97b2..316fa0f0b 100644 --- a/src/memory/traits.rs +++ b/src/memory/traits.rs @@ -302,6 +302,10 @@ pub struct ConversationTurn { pub content: String, pub timestamp: String, pub message_id: Option, + /// The `message_events.event_id` this turn was projected from, when the + /// turn was written through the event fabric. + #[serde(default)] + pub message_event_id: Option, } /// Visibility scope for message and memory fabric events. From 419047919ad58d91f4f254713dedf624ae7477c1 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:33:10 +0400 Subject: [PATCH 0069/1567] fix(tools): store the normalised child partition in the batch plan and roster so join admits Main callers --- src/runtime/child_source.rs | 2 +- src/tools/sessions_spawn/batch.rs | 9 ++++++--- src/tools/sessions_spawn/batch_journal.rs | 3 ++- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/runtime/child_source.rs b/src/runtime/child_source.rs index 7e20a31f0..16758cf23 100644 --- a/src/runtime/child_source.rs +++ b/src/runtime/child_source.rs @@ -54,7 +54,7 @@ impl std::error::Error for ChildPartitionUnresolved {} /// The root partition of a child issued by `caller`. The envelope's partition /// must agree with the partition sealed in the caller's parent publication. -fn caller_root_partition( +pub(crate) fn caller_root_partition( caller: &crate::tools::ToolExecutionContext, ) -> Result, ChildPartitionUnresolved> { let carried = inherited_partition(caller.envelope.agent_partition.as_ref()); diff --git a/src/tools/sessions_spawn/batch.rs b/src/tools/sessions_spawn/batch.rs index 98fe92f37..9cbaf0a14 100644 --- a/src/tools/sessions_spawn/batch.rs +++ b/src/tools/sessions_spawn/batch.rs @@ -485,6 +485,11 @@ impl SessionsSpawnTool { if let Some(caller) = &batch_caller { caller.verify_tool("sessions_spawn")?; } + // The child partition (Named or None), as every run row stores it. + let batch_partition = match &batch_caller { + Some(caller) => crate::runtime::child_source::caller_root_partition(caller.context())?, + None => None, + }; let batch_owner = batch_caller .as_ref() .map(|caller| caller.context().envelope.resolved_owner_id()) @@ -577,9 +582,7 @@ impl SessionsSpawnTool { rosters.push(BatchRoster { batch_id: batch_id.clone(), owner_id: batch_owner, - agent_partition: batch_caller - .as_ref() - .and_then(|caller| caller.context().envelope.agent_partition.clone()), + agent_partition: batch_partition, members: roster, }); } diff --git a/src/tools/sessions_spawn/batch_journal.rs b/src/tools/sessions_spawn/batch_journal.rs index d5a521498..0af4ddb26 100644 --- a/src/tools/sessions_spawn/batch_journal.rs +++ b/src/tools/sessions_spawn/batch_journal.rs @@ -129,7 +129,8 @@ impl PreparedBatch { } let fabric = publication.source_fabric(); let source = OrdinarySource { - partition: caller.envelope.agent_partition.clone(), + // The child partition (Named or None), as every run row stores it. + partition: crate::runtime::child_source::caller_root_partition(caller)?, // The batch parent is the run its members name (a child segment // spawns as its task run, CR-CI-3). parent_run: publication.spawn_run_id().to_owned(), From 28ecde10c411447bf34a104f4acf542ebf2edb62 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:54:01 +0400 Subject: [PATCH 0070/1567] docs(rf-contract): process children relay approvals to the root surface Replace the no-relay wording, extend the child-approval route to process children, and remove the TUI child-focus no_resolver branch. --- docs/rf-contract/capability-tokens.md | 44 +++++++++++++++++++-------- src/chat/child_focus.rs | 3 -- 2 files changed, 32 insertions(+), 15 deletions(-) diff --git a/docs/rf-contract/capability-tokens.md b/docs/rf-contract/capability-tokens.md index c02432cc7..fad2335d8 100644 --- a/docs/rf-contract/capability-tokens.md +++ b/docs/rf-contract/capability-tokens.md @@ -760,21 +760,41 @@ interception uses `plan_only`. Every denied/failed tool outcome commits a `tool. journal row before its live frame, including scheduler refusals before service entry. Rows retain the internal `reason` and the same mapped `cause` as the live frame. A refusal-storage failure ends the turn without an unrecorded frame. -No refusal cause contains paths or arguments. Process workers have no approval -relay in this unit. Their completion returns a bounded, content-free -`denials:[{tool,cause}]` inventory under the existing completion signature. -This includes pre-approval refusal and failure causes; approval requests still -end with `no_resolver`. Only after authentication does the parent emit one -`tool_status` per outcome on the **parent run**, with `child_run_id` and its -stable ids. Its phase is `failed` for `failed`/`indeterminate` causes, otherwise -`denied`; its cause uses the same typed mapping as an in-process child. -Worker refusal rows are committed before the signed observation is emitted. -The inventory holds at most 256 denials with tool names at most 64 bytes; -overflow fails completion explicitly. It carries no model text or arguments. +No refusal cause contains paths or arguments. A process worker below Full +relays its approval requests to the root session's approval surface, so a +process child's approval is answered the way a task child's is. The relay +travels only as authenticated mailbox frames of the worker pipe (`approval_request` +and `approval_withdraw` from the worker, `approval_decision` from the parent), +under the per-run frame MAC with strict sequence numbers. A signed `approval_relay` +manifest field turns it on, and only the parent sets it: for an authenticated +pipe, a child below Full, and a relay built from the spawning caller. The parent +re-checks every request against what it sealed (allowed tool, argument size +of at most 256 KiB, at most 8 outstanding requests per run, and that its own +policy still asks) and refuses a bad one with `ledger_refused` or +`concurrent_pending`. A decision is bound to the exact call by request id and +input digest, and an approval carries the same verified one-shot grant an +in-process child gets; the worker never creates a grant. Without the relay +(no authenticated pipe, or an operator-rooted child), approval requests still +end with `no_resolver`; a process turn woken by a message ends with +`no_approval_surface`, as a task child's does. While a relayed approval waits, +the child shows `tool_status{phase:"awaiting_approval"}` on the child run and +`approval.pending` carries the child `run_id`. The worker does not stream live +`started` or `succeeded` frames after an approval. The completion returns a +bounded, content-free `denials:[{tool,cause}]` inventory under the existing +completion signature. It carries pre-approval refusal and failure causes and +every approval denial cause, such as `owner_denied` and `expired`. Only after +authentication does the parent emit one `tool_status` per outcome on the +**parent run**, with `child_run_id` and its stable ids. Its phase is `failed` +for `failed`/`indeterminate` causes, otherwise `denied`; its cause uses the same +typed mapping as an in-process child. Worker refusal rows are committed before +the signed observation is emitted. The inventory holds at most 256 denials with +tool names at most 64 bytes; overflow fails completion explicitly. It carries no +model text or arguments. For an rf-keyed root session, `POST /api/sessions/{id}/approvals/{approval_id}` accepts exactly `{"decision":"approved"}` or `{"decision":"denied"}` under a -paired bearer. Child approvals use the root session id. Success is +paired bearer. Child approvals, of task and process children alike, use the root +session id. Success is `200 {approval_id,run_id,decision}`; the same decision is idempotent, another is `409 approval_decided`. Unknown ids return `404 approval_unknown`, mismatched owner/session or a run no longer live returns `409 approval_run_mismatch`, and diff --git a/src/chat/child_focus.rs b/src/chat/child_focus.rs index 107b2584b..7076f4aff 100644 --- a/src/chat/child_focus.rs +++ b/src/chat/child_focus.rs @@ -260,9 +260,6 @@ impl ChildFocus { .child_run(&record.session_key) .await .context("child is not running")?; - if record.mode == "process" { - return Ok(Some("Process-child approval is denied: no_resolver.".into())); - } let decision = if command == "/approve" { crate::agent::turn_contracts::ApprovalDecision::Grant } else { From 73e4165e1eaca795f8b2f7c2e0bce339b51bfbd7 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:54:01 +0400 Subject: [PATCH 0071/1567] feat(session-worker): relay process-child approvals to the root approval surface A worker below Full sends authenticated approval_request and approval_withdraw frames; the parent relays them through the approval chain a task child uses and answers with an authenticated approval_decision bound to the request id and input digest. The relay is switched on by a signed approval_relay manifest field that only the parent sets. --- src/agent/live_frames.rs | 3 + src/agent/tool_scheduler.rs | 7 +- src/chat/binding/tests/operator_accounting.rs | 1 + src/gateway/run_approvals.rs | 10 + src/messaging/worker.rs | 2 + src/session_worker/approval/client.rs | 103 ++++++++ src/session_worker/approval/demux.rs | 40 +++ src/session_worker/approval/mod.rs | 115 ++++++++ src/session_worker/approval/relay.rs | 250 ++++++++++++++++++ src/session_worker/approval/relay_context.rs | 173 ++++++++++++ src/session_worker/approval/waiters.rs | 91 +++++++ src/session_worker/denials.rs | 12 +- src/session_worker/frames.rs | 11 +- src/session_worker/mailbox_harness.rs | 2 + src/session_worker/mailbox_parent.rs | 5 +- src/session_worker/mod.rs | 1 + src/session_worker/protocol.rs | 16 ++ src/session_worker/runner/run.rs | 15 +- src/session_worker/runner/steering.rs | 22 +- src/session_worker/runner/tests/hybrid.rs | 4 + src/session_worker/runner/tests/mod.rs | 1 + .../runner/tests/spawn_context.rs | 2 + src/session_worker/stdout.rs | 4 + src/tools/execution/approval_route.rs | 26 ++ src/tools/execution/refusal_record.rs | 5 +- src/tools/sessions_spawn/process_mode.rs | 28 +- src/tools/sessions_spawn/spawn.rs | 13 + .../sessions_spawn/tests/process_manifest.rs | 1 + src/tools/sessions_spawn/worker_manifest.rs | 1 + 29 files changed, 938 insertions(+), 26 deletions(-) create mode 100644 src/session_worker/approval/client.rs create mode 100644 src/session_worker/approval/demux.rs create mode 100644 src/session_worker/approval/mod.rs create mode 100644 src/session_worker/approval/relay.rs create mode 100644 src/session_worker/approval/relay_context.rs create mode 100644 src/session_worker/approval/waiters.rs diff --git a/src/agent/live_frames.rs b/src/agent/live_frames.rs index 7b3874ce1..056117272 100644 --- a/src/agent/live_frames.rs +++ b/src/agent/live_frames.rs @@ -19,6 +19,9 @@ pub(crate) trait LiveFrameSink: Send + Sync { pub(crate) trait LiveTurn: Send + Sync { fn frames(&self, envelope: &RuntimeEnvelope, tools: &std::collections::HashSet) -> Arc; async fn approve(&self, request: crate::tools::ToolApprovalRequest) -> crate::tools::ToolApprovalDecision; + /// End every approval this surface still holds for `run_id` as cancelled. + /// A surface that keeps no per-run approval has nothing to close. + fn close_run(&self, _run_id: &str) {} } /// Runtime-owned hooks are inherited only through trusted child contexts. diff --git a/src/agent/tool_scheduler.rs b/src/agent/tool_scheduler.rs index f17963c07..6debb5af7 100644 --- a/src/agent/tool_scheduler.rs +++ b/src/agent/tool_scheduler.rs @@ -392,11 +392,10 @@ async fn emit_tool_outcome( call: &ParsedToolCall, mut event: ToolLoopEvent, ) -> Result<()> { - // A worker returns only sealed observations, never an approval relay. - // Commit the same refusal before its observation can reach the parent. + // A worker returns only sealed observations. Commit the same refusal before + // its observation can reach the parent. let context = &adapter.tool_execution_context; - let worker = context.pending_approval_denied - && context.envelope.source == crate::runtime::envelope::RuntimeSource::SessionWorker; + let worker = context.envelope.source == crate::runtime::envelope::RuntimeSource::SessionWorker; if (context.live_turn.is_some() || worker) && let ToolLoopEvent::ToolFinished { tool_call_id, diff --git a/src/chat/binding/tests/operator_accounting.rs b/src/chat/binding/tests/operator_accounting.rs index 84fa3fa29..6e8d30001 100644 --- a/src/chat/binding/tests/operator_accounting.rs +++ b/src/chat/binding/tests/operator_accounting.rs @@ -403,6 +403,7 @@ async fn restore_operator_process( inherited_provenance: None, session_addr: None, compaction_config: None, + approval_relay: false, }; // This exercises the real process-launch binding producer. The fixture // does not claim outer worker-channel authentication or an OS spawn. diff --git a/src/gateway/run_approvals.rs b/src/gateway/run_approvals.rs index 2ac55e09b..833f23e07 100644 --- a/src/gateway/run_approvals.rs +++ b/src/gateway/run_approvals.rs @@ -159,6 +159,16 @@ impl LiveTurn for RunApprovalResolver { fn frames(&self, envelope: &RuntimeEnvelope, tools: &HashSet) -> Arc { self.streams.producer(&self.scope, envelope, tools) } + fn close_run(&self, run_id: &str) { + // Cancelling an entry wakes its waiter task, which commits `cancelled` + // exactly as a root cancel does. The durable pending row closes with + // the run terminal. + for entry in self.approvals.entries.lock().values() { + if entry.pending.authority().run_id == run_id { + entry.cancel.cancel(); + } + } + } async fn approve(&self, request: ToolApprovalRequest) -> ToolApprovalDecision { match self.resolve(request).await { Ok(decision) => decision, diff --git a/src/messaging/worker.rs b/src/messaging/worker.rs index d651052d3..97a32a53d 100644 --- a/src/messaging/worker.rs +++ b/src/messaging/worker.rs @@ -73,6 +73,7 @@ impl WorkerMailboxFactory for WorkerMailboxes { )?; let auth = crate::session_worker::frame_auth::FrameAuth::parent(&manifest.run_id)?; let (controls, receiver) = mpsc::channel(64); + let control_sender = controls.clone(); let (outputs, mut output_rx) = mpsc::channel(64); let cancel = CancellationToken::new(); let run = manifest.run_id.clone(); @@ -174,6 +175,7 @@ impl WorkerMailboxFactory for WorkerMailboxes { owner, }, outputs, + control_sender, }, }) } diff --git a/src/session_worker/approval/client.rs b/src/session_worker/approval/client.rs new file mode 100644 index 000000000..231529d3f --- /dev/null +++ b/src/session_worker/approval/client.rs @@ -0,0 +1,103 @@ +//! Worker-side approval strategy: relay one request to the parent and wait. +use super::{ApprovalRequestPayload, WorkerApprovalOutcome, check_bounds, input_digest, waiters}; +use crate::session_worker::protocol::WorkerOutputFrame; +use crate::tools::{ApprovalDenialCause, ApprovalStrategy, ToolApprovalDecision, ToolApprovalRequest}; + +/// The approval strategy of a worker whose manifest enabled the relay. +/// +/// It owns no timer: the parent always answers, and the registry resolves every +/// waiter as cancelled when stdin ends. +#[derive(Debug, Default)] +pub(crate) struct WorkerApprovalClient; + +/// Sends `ApprovalWithdraw` when the waiting future is dropped before an +/// answer arrives (the segment was cancelled by steering or cancel). +struct WithdrawOnDrop { + request_id: u64, + armed: bool, +} + +impl Drop for WithdrawOnDrop { + fn drop(&mut self) { + if !self.armed { + return; + } + waiters::forget(self.request_id); + if let Err(error) = crate::session_worker::stdout::frame(&WorkerOutputFrame::ApprovalWithdraw { + request_id: self.request_id, + }) { + tracing::warn!( + error = %crate::agent::diagnostics::error_class(&error), + "session-worker could not withdraw an approval request" + ); + } + } +} + +fn cancelled(reason: &str) -> ToolApprovalDecision { + ToolApprovalDecision::Cancelled { + reason: reason.to_owned(), + } +} + +fn refused(reason: &str) -> ToolApprovalDecision { + ToolApprovalDecision::Denied { + cause: ApprovalDenialCause::LedgerRefused, + reason: format!("Approval request was refused ({reason}). Do not retry this call"), + } +} + +fn decision_from(outcome: WorkerApprovalOutcome) -> ToolApprovalDecision { + match outcome { + WorkerApprovalOutcome::Approved { grant } => ToolApprovalDecision::Approved { + runtime_approval_granted: true, + runtime_grant: grant, + }, + WorkerApprovalOutcome::Denied { cause, reason } => ToolApprovalDecision::Denied { cause, reason }, + WorkerApprovalOutcome::Cancelled { reason } => ToolApprovalDecision::Cancelled { reason }, + } +} + +#[async_trait::async_trait] +impl ApprovalStrategy for WorkerApprovalClient { + async fn resolve(&self, request: ToolApprovalRequest) -> ToolApprovalDecision { + let tool = request.descriptor.public_name.as_str(); + let call_id = request.command.operation_id.as_str(); + let arguments = &request.command.arguments; + if check_bounds(tool, call_id, arguments).is_err() { + return refused("ledger_refused: request exceeds the relay bounds"); + } + let input_sha256 = input_digest(arguments); + let Some((request_id, outcome)) = waiters::register(&input_sha256) else { + return cancelled("approval channel closed"); + }; + let mut guard = WithdrawOnDrop { + request_id, + armed: false, + }; + let frame = WorkerOutputFrame::ApprovalRequest(ApprovalRequestPayload { + request_id, + tool_call_id: call_id.to_owned(), + tool: tool.to_owned(), + arguments: arguments.clone(), + input_sha256, + }); + if let Err(error) = crate::session_worker::stdout::frame(&frame) { + waiters::forget(request_id); + tracing::warn!( + error = %crate::agent::diagnostics::error_class(&error), + "session-worker could not send an approval request" + ); + return ToolApprovalDecision::Denied { + cause: ApprovalDenialCause::NoApprovalSurface, + reason: crate::tools::execution::APPROVAL_DENIED_NO_APPROVAL_SURFACE.to_owned(), + }; + } + guard.armed = true; + // The wait is not worker silence: the parent holds the same pause. + let _pause = crate::agent::idle::pause_for_approval(); + let answer = outcome.await; + guard.armed = false; + answer.map_or_else(|_| cancelled("approval channel closed"), decision_from) + } +} diff --git a/src/session_worker/approval/demux.rs b/src/session_worker/approval/demux.rs new file mode 100644 index 000000000..5425b4eac --- /dev/null +++ b/src/session_worker/approval/demux.rs @@ -0,0 +1,40 @@ +//! Parent-side split of the worker's output frames. +//! +//! Approval frames go to the relay. Every other frame goes on, unchanged, to +//! the mailbox actor that was already reading them, and that actor still +//! rejects any frame it does not know. +use super::relay::ProcessApprovalRelay; +use crate::session_worker::frames::WorkerFrameChannels; +use crate::session_worker::protocol::WorkerOutputFrame; +use std::sync::Arc; +use tokio::sync::mpsc; + +/// Capacity of the forwarding queue, the same as the mailbox output queue. +const FORWARD_CAPACITY: usize = 64; + +/// Put the split in front of `frames.outputs`. The returned sender replaces the +/// original in the frames; the original moves into the forwarder. +/// +/// The forwarder never waits on the relay: a request is handed to a task of its +/// own, so a long approval does not hold up mailbox frames behind it. When the +/// pipe ends (the reader dropped its sender, whether the worker finished, was +/// killed or the read failed) every approval of the run ends as cancelled. +pub(crate) fn attach(relay: &Arc, frames: &mut WorkerFrameChannels) { + let (forward, mut incoming) = mpsc::channel::(FORWARD_CAPACITY); + let downstream = std::mem::replace(&mut frames.outputs, forward); + let relay = Arc::clone(relay); + tokio::spawn(async move { + while let Some(frame) = incoming.recv().await { + match frame { + WorkerOutputFrame::ApprovalRequest(payload) => relay.request(payload), + WorkerOutputFrame::ApprovalWithdraw { request_id } => relay.withdraw(request_id), + other => { + if downstream.send(other).await.is_err() { + break; + } + } + } + } + relay.cancel_all(); + }); +} diff --git a/src/session_worker/approval/mod.rs b/src/session_worker/approval/mod.rs new file mode 100644 index 000000000..2d19df477 --- /dev/null +++ b/src/session_worker/approval/mod.rs @@ -0,0 +1,115 @@ +//! Approval relay for process-mode children. +//! +//! A worker below Full cannot ask anyone itself. It sends an authenticated +//! `ApprovalRequest` frame; the parent carries it to the approval surface of +//! the root session and answers with an authenticated `ApprovalDecision`. The +//! worker never creates a grant: it only passes the parent's verified grant to +//! the policy gate that already checks it for an in-process child. +pub(crate) mod client; +pub(crate) mod demux; +pub(crate) mod relay; +pub(crate) mod relay_context; +pub(crate) mod waiters; + +use crate::tools::ApprovalDenialCause; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use sha2::{Digest, Sha256}; + +/// Longest public tool name a request may carry. +pub(crate) const MAX_TOOL_BYTES: usize = 64; +/// Longest tool call id a request may carry. +pub(crate) const MAX_CALL_ID_BYTES: usize = 256; +/// Largest serialized argument document a request may carry. +pub(crate) const MAX_ARGUMENT_BYTES: usize = 256 * 1024; +/// Most requests of one run that may wait at the same time. +pub(crate) const MAX_OUTSTANDING: usize = 8; + +/// A request that is outside the relay bounds, or that does not hash to the +/// digest it claims. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub(crate) enum ApprovalFrameError { + #[error("approval request tool name is empty or too long")] + Tool, + #[error("approval request call id is empty or too long")] + CallId, + #[error("approval request arguments exceed the relay limit")] + Arguments, + #[error("approval request digest does not match its arguments")] + Digest, +} + +/// Parent verdict on one relayed request. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum WorkerApprovalOutcome { + /// The grant is the parent's verified runtime grant, when the surface + /// issues one. The worker still verifies it at the policy gate. + Approved { grant: Option }, + Denied { + cause: ApprovalDenialCause, + reason: String, + }, + Cancelled { reason: String }, +} + +/// Worker-to-parent request. Only `tool`, `tool_call_id` and `arguments` are +/// taken from it; the parent rebuilds everything else from what it sealed. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct ApprovalRequestPayload { + /// Monotonic per run, starting at 1. + pub request_id: u64, + pub tool_call_id: String, + /// Public tool name. + pub tool: String, + pub arguments: Value, + pub input_sha256: String, +} + +/// Parent-to-worker answer, bound to one request by id and digest. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct ApprovalDecisionPayload { + pub request_id: u64, + pub input_sha256: String, + /// Ledger call id of the pending approval, when the surface keeps one. + pub approval_id: Option, + pub outcome: WorkerApprovalOutcome, +} + +/// Digest that binds a decision to the exact call: the same formula the tool +/// pipeline uses for `input_sha256`. +#[must_use] +pub(crate) fn input_digest(arguments: &Value) -> String { + format!("{:x}", Sha256::digest(arguments.to_string().as_bytes())) +} + +/// Check the size bounds of one request. +pub(crate) fn check_bounds(tool: &str, call_id: &str, arguments: &Value) -> Result<(), ApprovalFrameError> { + if tool.is_empty() || tool.len() > MAX_TOOL_BYTES { + return Err(ApprovalFrameError::Tool); + } + if call_id.is_empty() || call_id.len() > MAX_CALL_ID_BYTES { + return Err(ApprovalFrameError::CallId); + } + if arguments.to_string().len() > MAX_ARGUMENT_BYTES { + return Err(ApprovalFrameError::Arguments); + } + Ok(()) +} + +impl ApprovalRequestPayload { + /// Bounds, then the digest recomputed from the arguments actually received. + pub(crate) fn validate(&self) -> Result<(), ApprovalFrameError> { + check_bounds(&self.tool, &self.tool_call_id, &self.arguments)?; + if input_digest(&self.arguments) != self.input_sha256 { + return Err(ApprovalFrameError::Digest); + } + Ok(()) + } +} + +/// Frame kinds that must only ever travel inside an authenticated mailbox frame. +#[must_use] +pub(crate) fn is_approval_kind(kind: &str) -> bool { + matches!(kind, "approval_request" | "approval_withdraw" | "approval_decision") +} diff --git a/src/session_worker/approval/relay.rs b/src/session_worker/approval/relay.rs new file mode 100644 index 000000000..2ac39c7ec --- /dev/null +++ b/src/session_worker/approval/relay.rs @@ -0,0 +1,250 @@ +//! Parent side of the approval relay for one process worker run. +//! +//! Nothing from the worker is trusted except `tool`, `tool_call_id` and +//! `arguments`. Everything else comes from what the parent sealed at launch: +//! the child execution context, the approval strategy and the surfaces. +use super::{ + ApprovalDecisionPayload, ApprovalRequestPayload, MAX_OUTSTANDING, WorkerApprovalOutcome, +}; +use crate::agent::live_frames::LiveTurnRef; +use crate::session_worker::protocol::WorkerControlFrame; +use crate::tools::{ + ApprovalDenialCause, ToolApprovalDecision, ToolApprovalRequest, ToolDescriptor, ToolExecutionCommand, + ToolExecutionContext, ToolExecutionService, +}; +use parking_lot::Mutex; +use std::collections::HashMap; +use std::future::Future; +use std::sync::Arc; +use tokio::sync::mpsc; +use tokio::task::JoinSet; +use tokio_util::sync::CancellationToken; + +/// Everything the live relay needs, fixed at launch. +pub(crate) struct RelayParts { + pub(crate) run_id: String, + /// The sealed tool allowance; empty means the run inherits every tool. + pub(crate) allowed_tools: Vec, + pub(crate) execution: ToolExecutionContext, + pub(crate) service: Arc, + pub(crate) live_turn: Option, + pub(crate) controls: mpsc::Sender, + pub(crate) progress: Arc, + /// Ends every wait of the run: pipe end, kill or termination request. + pub(crate) cancel: CancellationToken, +} + +struct Outstanding { + cancel: CancellationToken, + withdrawn: bool, +} + +#[derive(Default)] +struct State { + last_id: u64, + outstanding: HashMap, +} + +enum Admission { + Accepted(ToolDescriptor, CancellationToken), + Refused(ApprovalDenialCause, &'static str), + /// A protocol violation; nothing is answered. + Dropped, +} + +pub(crate) struct ProcessApprovalRelay { + parts: RelayParts, + state: Mutex, + tasks: Mutex>, +} + +fn outcome_from(decision: ToolApprovalDecision) -> WorkerApprovalOutcome { + match decision { + ToolApprovalDecision::Approved { + runtime_approval_granted: true, + runtime_grant, + } => WorkerApprovalOutcome::Approved { grant: runtime_grant }, + ToolApprovalDecision::Approved { .. } => WorkerApprovalOutcome::Denied { + cause: ApprovalDenialCause::LedgerRefused, + reason: "Approval did not grant the call (ledger_refused). Do not retry this call".to_owned(), + }, + ToolApprovalDecision::Denied { cause, reason } => WorkerApprovalOutcome::Denied { cause, reason }, + ToolApprovalDecision::Cancelled { reason } => WorkerApprovalOutcome::Cancelled { reason }, + } +} + +fn refusal(cause: ApprovalDenialCause, why: &str) -> WorkerApprovalOutcome { + WorkerApprovalOutcome::Denied { + cause, + reason: cause.fixed_reason().map_or_else( + || format!("Approval request was refused ({why}). Do not retry this call"), + str::to_owned, + ), + } +} + +impl ProcessApprovalRelay { + pub(crate) fn new(parts: RelayParts) -> Arc { + Arc::new(Self { + parts, + state: Mutex::new(State::default()), + tasks: Mutex::new(JoinSet::new()), + }) + } + + fn spawn(&self, task: impl Future + Send + 'static) { + let mut tasks = self.tasks.lock(); + // Reap finished request tasks so the set stays bounded by the outstanding limit. + while tasks.try_join_next().is_some() {} + tasks.spawn(task); + } + + fn admit(&self, payload: &ApprovalRequestPayload) -> Admission { + let mut state = self.state.lock(); + if payload.request_id <= state.last_id { + return Admission::Dropped; + } + state.last_id = payload.request_id; + if payload.validate().is_err() { + return Admission::Refused(ApprovalDenialCause::LedgerRefused, "ledger_refused: invalid request"); + } + if state.outstanding.len() >= MAX_OUTSTANDING { + return Admission::Refused(ApprovalDenialCause::ConcurrentPending, "concurrent_pending"); + } + let allowed = &self.parts.allowed_tools; + if !allowed.is_empty() && !allowed.iter().any(|name| name == &payload.tool) { + return Admission::Refused(ApprovalDenialCause::LedgerRefused, "ledger_refused: tool not allowed"); + } + let service = &self.parts.service; + let Some(descriptor) = service.current_descriptor(&payload.tool) else { + return Admission::Refused(ApprovalDenialCause::LedgerRefused, "ledger_refused: unknown tool"); + }; + // The worker's own check is not evidence: only a call the parent's + // policy still holds for approval is relayed. + if !service.relayed_call_asks(&descriptor, &self.parts.execution) { + return Admission::Refused(ApprovalDenialCause::LedgerRefused, "ledger_refused: no approval required"); + } + let cancel = self.parts.cancel.child_token(); + state.outstanding.insert( + payload.request_id, + Outstanding { + cancel: cancel.clone(), + withdrawn: false, + }, + ); + Admission::Accepted(descriptor, cancel) + } + + /// One authenticated `ApprovalRequest` from the worker. + pub(crate) fn request(self: &Arc, payload: ApprovalRequestPayload) { + let request_id = payload.request_id; + let input_sha256 = payload.input_sha256.clone(); + match self.admit(&payload) { + Admission::Dropped => { + tracing::warn!("session-worker approval request out of sequence; dropped"); + } + Admission::Refused(cause, why) => { + let relay = Arc::clone(self); + self.spawn(async move { + relay + .send(request_id, input_sha256, refusal(cause, why)) + .await; + }); + } + Admission::Accepted(descriptor, cancel) => { + let relay = Arc::clone(self); + self.spawn(async move { relay.run(payload, descriptor, cancel).await }); + } + } + } + + async fn run(self: Arc, payload: ApprovalRequestPayload, descriptor: ToolDescriptor, cancel: CancellationToken) { + let ApprovalRequestPayload { + request_id, + tool_call_id, + tool, + arguments, + input_sha256, + } = payload; + let request = ToolApprovalRequest { + command: ToolExecutionCommand::new(tool, arguments).with_operation_id(tool_call_id), + descriptor, + context: self.parts.execution.clone(), + }; + // The run's beat is parented on its caller's: while this holds the + // pause, neither the child nor any waiting ancestor looks silent. + let outcome = crate::agent::idle::scope_beat(Some(Arc::clone(&self.parts.progress)), async { + let _pause = crate::agent::idle::pause_for_approval(); + tokio::select! { + biased; + () = cancel.cancelled() => WorkerApprovalOutcome::Cancelled { + reason: "approval cancelled".to_owned(), + }, + decision = self.parts.service.resolve_relayed_approval(request) => outcome_from(decision), + } + }) + .await; + let withdrawn = self + .state + .lock() + .outstanding + .remove(&request_id) + .is_some_and(|entry| entry.withdrawn); + if !withdrawn { + self.send(request_id, input_sha256, outcome).await; + } + } + + async fn send(&self, request_id: u64, input_sha256: String, outcome: WorkerApprovalOutcome) { + let frame = WorkerControlFrame::ApprovalDecision(ApprovalDecisionPayload { + request_id, + input_sha256, + approval_id: None, + outcome, + }); + if self.parts.controls.send(frame).await.is_err() { + tracing::debug!("session-worker control pipe closed before an approval decision"); + } + } + + /// The worker stopped waiting. A withdraw only happens when a whole segment + /// was cancelled, and pipe order puts it ahead of any request of the next + /// segment, so it closes the run's approvals, not one call. + pub(crate) fn withdraw(&self, request_id: u64) { + tracing::debug!(request_id, "session-worker withdrew its approval requests"); + for entry in self.state.lock().outstanding.values_mut() { + entry.withdrawn = true; + entry.cancel.cancel(); + } + self.close_run(); + } + + fn close_run(&self) { + if let Some(live) = &self.parts.live_turn { + live.0.close_run(&self.parts.run_id); + } + } + + /// The pipe ended, or the child is being cancelled or killed: every wait of + /// the run ends as cancelled. The durable rows close with the run terminal. + pub(crate) fn cancel_all(&self) { + self.parts.cancel.cancel(); + self.close_run(); + } + + /// Run `main`, ending every approval wait as soon as `termination` fires. + pub(crate) async fn guard(&self, termination: impl Future, main: F) -> F::Output { + tokio::pin!(main); + tokio::pin!(termination); + let mut watching = true; + loop { + tokio::select! { + output = &mut main => return output, + _reason = &mut termination, if watching => { + watching = false; + self.cancel_all(); + } + } + } + } +} diff --git a/src/session_worker/approval/relay_context.rs b/src/session_worker/approval/relay_context.rs new file mode 100644 index 000000000..f3c195140 --- /dev/null +++ b/src/session_worker/approval/relay_context.rs @@ -0,0 +1,173 @@ +//! Builds the parent-side relay from the spawning caller and seals it into the +//! worker manifest. +//! +//! The seed is built where the spawn call still holds its caller. It is armed +//! only against the finished manifest: the relay switch is set on the manifest +//! before the manifest HMAC is computed, and only when every condition holds, +//! so a worker can never turn the relay on by itself. +use super::relay::{ProcessApprovalRelay, RelayParts}; +use crate::agent::live_frames::LiveTurnRef; +use crate::runtime::child_source::{ChildInputReceipt, ChildProviderBinding}; +use crate::security::{AutonomyLevel, SecurityPolicy}; +use crate::session_worker::frames::WorkerFrameChannels; +use crate::session_worker::mailbox_binding::BoundWorkerMailbox; +use crate::session_worker::protocol::{WorkerControlFrame, WorkerManifest}; +use crate::tools::{ToolExecutionContext, ToolExecutionService}; +use anyhow::Context as _; +use std::sync::Arc; +use tokio::sync::mpsc; +use tokio_util::sync::CancellationToken; + +/// What the parent knows about the spawning caller, before the manifest exists. +pub(crate) struct ProcessRelaySeed { + execution: ToolExecutionContext, + service: Arc, + live_turn: Option, + level: AutonomyLevel, + cancel: CancellationToken, +} + +/// A seed checked against the sealed manifest, with the control queue it will +/// answer on. +pub(crate) struct ArmedRelay { + seed: ProcessRelaySeed, + controls: mpsc::Sender, + run_id: String, + allowed_tools: Vec, +} + +fn policy_at_level(policy: &Arc, level: AutonomyLevel) -> Arc { + if policy.autonomy == level { + Arc::clone(policy) + } else { + Arc::new(SecurityPolicy { + autonomy: level, + ..policy.as_ref().clone() + }) + } +} + +/// What the spawn call hands over to build the seed. +pub(crate) struct RelaySeedInputs<'a> { + pub(crate) caller: Option<&'a crate::tools::execution::ChildCallContext>, + pub(crate) binding: Option<&'a ChildProviderBinding>, + pub(crate) resolvers: Option<&'a crate::agent::turn_request::SpawnApprovalResolverFactory>, + pub(crate) scope: &'a crate::memory::MessageEventScope, + pub(crate) task: &'a str, + pub(crate) receipt: Option<&'a ChildInputReceipt>, + pub(crate) security: &'a Arc, + pub(crate) level: AutonomyLevel, + pub(crate) run_id: &'a str, +} + +impl RelaySeedInputs<'_> { + /// Build the seed of an ordinary process child below Full. `None` when there + /// is nothing to relay for: a Full child never asks, and an operator-rooted + /// child has no caller approval surface. + /// + /// The child context is rebuilt from the same inputs the launch capture + /// uses, so it carries the child run, its sealed scope and the caller's live + /// surface. The approval strategy is the one a task child gets: the run's + /// chat resolver, when the root has one, behind the caller's live surface. + pub(crate) fn seed(self) -> anyhow::Result> { + if self.level == AutonomyLevel::Full { + return Ok(None); + } + let (Some(caller), Some(binding)) = (self.caller, self.binding) else { + return Ok(None); + }; + let publication = caller + .context() + .ordinary_child_publication + .as_ref() + .context("approval relay parent publication missing")?; + let (_proof, mut execution) = + binding.ordinary_execution_source(&binding.provider(), caller, self.scope, self.task, self.receipt)?; + let live_turn = execution.live_turn.clone(); + // As an in-process child: the ledger only accompanies a live surface. + execution.approval_ledger = live_turn + .as_ref() + .and_then(|_| caller.context().approval_ledger.clone()); + let resolver = self.resolvers.map(|factory| factory.resolver_for(self.run_id)); + let manager = resolver + .as_ref() + .map(|_| Arc::new(crate::approval::ApprovalManager::new())); + let cancel = CancellationToken::new(); + let policy = policy_at_level(self.security, self.level); + let strategy = crate::agent::execution_policy::run_approval_strategy( + manager, + resolver, + "sessions_spawn", + Arc::clone(&policy), + Some(cancel.clone()), + ); + let service = Arc::new(ToolExecutionService::from_shared_boxed_registry( + publication.registry(), + Arc::new(crate::tools::SecurityEffectPolicy::new(policy)), + strategy, + Arc::new(crate::tools::AdapterOwnedPreparation), + Arc::new(crate::tools::TracingToolExecutionAudit), + )); + Ok(Some(ProcessRelaySeed { + execution, + service, + live_turn, + level: self.level, + cancel, + })) + } +} + +impl ProcessRelaySeed { + /// Seal the relay switch into `manifest`, which must still be unsigned. + /// Returns `None`, leaving the switch off, unless the pipe is authenticated + /// (a mailbox binding sealed the session address), the child is below Full, + /// and the rebuilt context names the same owner, session and run the + /// manifest does. + pub(crate) fn arm(self, binding: Option<&BoundWorkerMailbox>, manifest: &mut WorkerManifest) -> Option { + let controls = binding + .and_then(|binding| binding.frames.as_ref()) + .map(|frames| frames.control_sender.clone())?; + let envelope = &self.execution.envelope; + let same_child = manifest.session_addr.is_some() + && manifest.ordinary_source.is_some() + && self.level != AutonomyLevel::Full + && envelope.run_id.as_deref() == Some(manifest.run_id.as_str()) + && envelope.owner_id == manifest.owner_id + && envelope.session_key == manifest.session_scope_key; + if !same_child { + tracing::warn!("approval relay not armed: the child context differs from the sealed manifest"); + return None; + } + manifest.approval_relay = true; + Some(ArmedRelay { + seed: self, + controls, + run_id: manifest.run_id.clone(), + allowed_tools: manifest.allowed_tools.clone(), + }) + } +} + +impl ArmedRelay { + /// Start the relay on the worker's frames: approval frames go to it, every + /// other frame still reaches the mailbox actor. + pub(crate) fn attach( + self, + frames: &mut WorkerFrameChannels, + progress: Arc, + ) -> Arc { + let relay = ProcessApprovalRelay::new(RelayParts { + run_id: self.run_id, + allowed_tools: self.allowed_tools, + execution: self.seed.execution, + service: self.seed.service, + live_turn: self.seed.live_turn, + controls: self.controls, + progress, + cancel: self.seed.cancel, + }); + super::demux::attach(&relay, frames); + relay + } +} diff --git a/src/session_worker/approval/waiters.rs b/src/session_worker/approval/waiters.rs new file mode 100644 index 000000000..9bf7b88de --- /dev/null +++ b/src/session_worker/approval/waiters.rs @@ -0,0 +1,91 @@ +//! Worker-side registry of approvals that wait for a parent decision. +//! +//! One process-wide registry, in the same shape as the mailbox publication +//! waiters: the stdin reader thread resolves a waiter, the approval client +//! awaits it. A decision is accepted only for an outstanding request id whose +//! digest matches the request it answers. +use super::WorkerApprovalOutcome; +use parking_lot::Mutex; +use std::collections::HashMap; +use std::sync::LazyLock; +use tokio::sync::oneshot; + +struct Waiter { + input_sha256: String, + reply: oneshot::Sender, +} + +#[derive(Default)] +struct Registry { + last_id: u64, + closed: bool, + pending: HashMap, +} + +static REGISTRY: LazyLock> = LazyLock::new(Mutex::default); + +/// Why a decision did not reach a waiter. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Rejected { + /// No outstanding request has that id. + Unknown, + /// The digest differs from the request's. + DigestMismatch, +} + +/// Register a waiter for a new request and return its id. `None` once the +/// parent pipe has ended: nothing can answer any more. +pub(crate) fn register(input_sha256: &str) -> Option<(u64, oneshot::Receiver)> { + let mut registry = REGISTRY.lock(); + if registry.closed { + return None; + } + let request_id = registry.last_id.checked_add(1)?; + registry.last_id = request_id; + let (reply, outcome) = oneshot::channel(); + registry.pending.insert( + request_id, + Waiter { + input_sha256: input_sha256.to_owned(), + reply, + }, + ); + Some((request_id, outcome)) +} + +/// Deliver a verified decision. Anything but an outstanding id with a matching +/// digest is refused and leaves the waiter in place. +pub(crate) fn resolve(request_id: u64, input_sha256: &str, outcome: WorkerApprovalOutcome) -> Result<(), Rejected> { + let mut registry = REGISTRY.lock(); + let waiter = registry.pending.get(&request_id).ok_or(Rejected::Unknown)?; + if waiter.input_sha256 != input_sha256 { + return Err(Rejected::DigestMismatch); + } + if let Some(waiter) = registry.pending.remove(&request_id) { + // A closed receiver means the waiting future was dropped; its guard + // already withdrew the request. + let _ = waiter.reply.send(outcome); + } + Ok(()) +} + +/// Forget a request that nobody waits for any more. True when it was still +/// outstanding. +pub(crate) fn forget(request_id: u64) -> bool { + REGISTRY.lock().pending.remove(&request_id).is_some() +} + +/// End of input: the parent is gone or closed the pipe. Every waiter resolves +/// as cancelled, and later requests are refused at registration. +pub(crate) fn close_all() { + let drained: Vec = { + let mut registry = REGISTRY.lock(); + registry.closed = true; + registry.pending.drain().map(|(_, waiter)| waiter).collect() + }; + for waiter in drained { + let _ = waiter.reply.send(WorkerApprovalOutcome::Cancelled { + reason: "approval channel closed".to_owned(), + }); + } +} diff --git a/src/session_worker/denials.rs b/src/session_worker/denials.rs index 89d0fe74c..3b762f81f 100644 --- a/src/session_worker/denials.rs +++ b/src/session_worker/denials.rs @@ -21,11 +21,6 @@ pub enum WorkerDenialCause { impl WorkerDenial { pub(crate) const fn valid(&self) -> bool { self.tool.len() <= 64 - && matches!( - self.cause, - WorkerDenialCause::Approval(crate::tools::ApprovalDenialCause::NoResolver) - | WorkerDenialCause::Refusal(_) - ) } pub(crate) fn rf_cause(&self) -> crate::security::approval_ledger::run_call::RfDenialCause { match self.cause { @@ -50,7 +45,8 @@ impl DenialSink { } impl LiveFrameSink for DenialSink { fn thinking(&self) {} - // Process workers have no approval relay; only typed denials enter completion. + // The parent emits the live awaiting-approval status of a relayed request; + // only typed denials enter completion. fn awaiting_approval(&self, _tool: &str) {} fn child_denial( &self, @@ -71,9 +67,7 @@ impl LiveFrameSink for DenialSink { } = event { let cause = match outcome { - ToolCallOutcome::Denied { - cause: Some(crate::tools::ApprovalDenialCause::NoResolver), - } => Some(crate::tools::ApprovalDenialCause::NoResolver.into()), + ToolCallOutcome::Denied { cause: Some(cause) } => Some((*cause).into()), ToolCallOutcome::Refused => Some(refusal_cause.unwrap_or(ToolCallRefusalReason::PolicyDenied).into()), ToolCallOutcome::PlanOnly => Some(ToolCallRefusalReason::PlanOnly.into()), ToolCallOutcome::Error => Some(refusal_cause.unwrap_or(ToolCallRefusalReason::Failed).into()), diff --git a/src/session_worker/frames.rs b/src/session_worker/frames.rs index 38c82b22d..7087bbebc 100644 --- a/src/session_worker/frames.rs +++ b/src/session_worker/frames.rs @@ -16,6 +16,9 @@ pub struct WorkerControlQueue { pub struct WorkerFrameChannels { pub controls: WorkerControlQueue, pub outputs: mpsc::Sender, + /// A sender into the same queue as `controls.receiver`, for the parent + /// side of the approval relay. The control pump signs what it carries. + pub control_sender: mpsc::Sender, } pub async fn write_control_frame(writer: &mut W, frame: &WorkerControlFrame) -> Result<()> { @@ -89,7 +92,13 @@ pub(crate) async fn read_worker_frames_authenticated( continue; } let value: serde_json::Value = serde_json::from_slice(&line).context("invalid worker stdout JSON line")?; - if value.get("kind").is_some() { + if let Some(kind) = value.get("kind") { + // An approval frame is never valid outside an authenticated mailbox + // frame: without authentication it fails the read. + ensure!( + auth.is_some() || !kind.as_str().is_some_and(super::approval::is_approval_kind), + "unsigned approval frame refused" + ); let value = match &auth { Some(auth) => auth.verify(value)?, None => value, diff --git a/src/session_worker/mailbox_harness.rs b/src/session_worker/mailbox_harness.rs index 98b82879d..cc0a121a0 100644 --- a/src/session_worker/mailbox_harness.rs +++ b/src/session_worker/mailbox_harness.rs @@ -140,6 +140,7 @@ impl WorkerMailboxFactory for Factory { let frame = actor.lock().next_delivery()?.context("mailbox IPC delivery missing")?; let (controls, receiver) = mpsc::channel(64); controls.try_send(frame).context("queue initial mailbox Data")?; + let control_sender = controls.clone(); let (outputs, mut output_rx) = mpsc::channel(64); std::fs::write(&self.hold, b"wait for real delivery Ack")?; let hold = self.hold.clone(); @@ -189,6 +190,7 @@ impl WorkerMailboxFactory for Factory { owner: actor, }, outputs, + control_sender, }, }) } diff --git a/src/session_worker/mailbox_parent.rs b/src/session_worker/mailbox_parent.rs index 13b1318f7..8264f55e9 100644 --- a/src/session_worker/mailbox_parent.rs +++ b/src/session_worker/mailbox_parent.rs @@ -159,7 +159,10 @@ impl WorkerMailboxParent { } Ok(None) } - WorkerOutputFrame::BrokerCall { .. } | WorkerOutputFrame::BrokerCancel { .. } => { + WorkerOutputFrame::BrokerCall { .. } + | WorkerOutputFrame::BrokerCancel { .. } + | WorkerOutputFrame::ApprovalRequest(_) + | WorkerOutputFrame::ApprovalWithdraw { .. } => { Err(crate::messaging::mailbox::unauthorized( crate::messaging::mailbox::UnauthorizedReason::WorkerSenderMismatch, )) diff --git a/src/session_worker/mod.rs b/src/session_worker/mod.rs index 7b3511a7f..4d6132618 100644 --- a/src/session_worker/mod.rs +++ b/src/session_worker/mod.rs @@ -1,3 +1,4 @@ +pub(crate) mod approval; pub(crate) mod completion; pub(crate) mod denials; #[cfg(unix)] diff --git a/src/session_worker/protocol.rs b/src/session_worker/protocol.rs index 2a7486512..1af2d7cdf 100644 --- a/src/session_worker/protocol.rs +++ b/src/session_worker/protocol.rs @@ -238,6 +238,12 @@ pub struct WorkerManifest { pub inherited_provenance: Option, #[serde(default)] pub compaction_config: Option, + /// The parent relays this worker's approval requests to the root approval + /// surface. Sealed by the manifest HMAC, so a worker cannot turn it on; the + /// parent sets it only with an authenticated pipe, below Full and with a + /// relay built. + #[serde(default)] + pub approval_relay: bool, } impl WorkerManifest { @@ -323,6 +329,9 @@ pub enum WorkerControlFrame { BrokerResult { call_id: u64, outcome: BrokerOutcome }, /// Acknowledgement of `BrokerCancel`. BrokerCancelAck { call_id: u64 }, + /// Answer to a worker `ApprovalRequest`. Accepted only inside an + /// authenticated mailbox frame. + ApprovalDecision(super::approval::ApprovalDecisionPayload), } /// Worker-to-parent stdout frame. Line-delimited; the terminal `WorkerResult` @@ -350,6 +359,11 @@ pub enum WorkerOutputFrame { }, /// Cancel a pending broker call. BrokerCancel { call_id: u64 }, + /// Ask the parent to relay one approval to the root approval surface. + /// Accepted only inside an authenticated mailbox frame. + ApprovalRequest(super::approval::ApprovalRequestPayload), + /// The worker stopped waiting for its outstanding approvals. + ApprovalWithdraw { request_id: u64 }, } /// Issued capability kind on a broker call. @@ -470,6 +484,7 @@ mod tests { inherited_provenance: None, session_addr: None, compaction_config: Some(crate::config::AgentCompactionConfig::default()), + approval_relay: false, }; let json = serde_json::to_string(&manifest).expect("serialize manifest"); @@ -653,6 +668,7 @@ mod tests { inherited_provenance: None, session_addr: None, compaction_config: None, + approval_relay: false, }; let trigger = uuid::Uuid::from_u128(42); let provenance = crate::messaging::InheritedProvenance { diff --git a/src/session_worker/runner/run.rs b/src/session_worker/runner/run.rs index 989618e55..8c3056ae1 100644 --- a/src/session_worker/runner/run.rs +++ b/src/session_worker/runner/run.rs @@ -958,6 +958,10 @@ async fn run_owned_manifest( let raw_task = manifest.task.as_str(); let manifest_ref = &manifest; let config_ref = &config; + // The relay needs all three: the parent sealed it, the pipe is + // authenticated, and the stdin reader that carries decisions is running. + let approval_relay = + manifest.approval_relay && crate::session_worker::stdout::is_authenticated() && steer_rx.is_some(); let (history, loop_result) = run_segments_with_controls( initial_history, &mut steer_rx, @@ -1062,11 +1066,18 @@ async fn run_owned_manifest( let routing = admitted_turn.routing(); let advice = routing.service.advisory().analyze_turn(routing.runtime, &cancel).await; let adapter = child_turn.as_ref().map(|turn| { - let mut adapter = turn.adapter(); + // With the relay, an `Ask` goes to the parent's approval + // surface; the worker keeps no ledger and never issues a + // grant. Without it, approval stays denied (`no_resolver`). + let mut adapter = if approval_relay { + turn.adapter_with_approval(Arc::new(crate::session_worker::approval::client::WorkerApprovalClient)) + } else { + turn.adapter() + }; adapter.live_frames = Some(Arc::clone(&process_denials) as Arc); adapter.tool_execution_context.approval_ledger = None; - adapter.tool_execution_context.pending_approval_denied = true; + adapter.tool_execution_context.pending_approval_denied = !approval_relay; adapter }); let child_execution = adapter.as_ref().map(|adapter| adapter.tool_execution_context.clone()); diff --git a/src/session_worker/runner/steering.rs b/src/session_worker/runner/steering.rs index 3a0286e10..6ed01284e 100644 --- a/src/session_worker/runner/steering.rs +++ b/src/session_worker/runner/steering.rs @@ -79,10 +79,14 @@ pub(super) fn spawn_stdin_control_reader( auth.verify(value) .map_err(|e| serde_json::Error::io(std::io::Error::other(e))) }) - } else if matches!( + } else if (matches!( value.get("kind").and_then(|v| v.as_str()), Some("message" | "message_result") - ) && auth.is_some() + ) && auth.is_some()) + || value + .get("kind") + .and_then(|v| v.as_str()) + .is_some_and(crate::session_worker::approval::is_approval_kind) { Err(serde_json::Error::io(std::io::Error::other("unsigned mailbox frame"))) } else { @@ -126,8 +130,22 @@ pub(super) fn spawn_stdin_control_reader( WorkerControlFrame::BrokerResult { .. } | WorkerControlFrame::BrokerCancelAck { .. } => { tracing::warn!("session-worker discarded an unregistered broker control frame"); } + WorkerControlFrame::ApprovalDecision(decision) => { + // The frame is authenticated, but it is accepted only for + // an outstanding request and the digest of that request. + if let Err(rejected) = crate::session_worker::approval::waiters::resolve( + decision.request_id, + &decision.input_sha256, + decision.outcome, + ) { + tracing::warn!(?rejected, "session-worker dropped an approval decision"); + } + } } } + // Stdin ended (parent gone or pipe closed): nobody can answer an + // outstanding approval any more. + crate::session_worker::approval::waiters::close_all(); }); } diff --git a/src/session_worker/runner/tests/hybrid.rs b/src/session_worker/runner/tests/hybrid.rs index 798cb5300..5685afbde 100644 --- a/src/session_worker/runner/tests/hybrid.rs +++ b/src/session_worker/runner/tests/hybrid.rs @@ -100,6 +100,7 @@ async fn hybrid_worker_shared_context_reads_parent_fabric() { inherited_provenance: None, session_addr: None, compaction_config: None, + approval_relay: false, }; let context = load_worker_shared_context(&manifest, &Config::default(), &shared_memory).await; @@ -221,6 +222,7 @@ async fn process_mode_worker_prompt_carries_no_other_owners_spawn_text() { inherited_provenance: None, session_addr: None, compaction_config: None, + approval_relay: false, }; let context = load_worker_shared_context(&manifest, &Config::default(), &shared_memory).await; @@ -316,6 +318,7 @@ async fn hybrid_worker_result_creates_private_draft_and_parent_merge_request() { inherited_provenance: None, session_addr: None, compaction_config: None, + approval_relay: false, }; record_hybrid_worker_draft_if_needed( @@ -467,6 +470,7 @@ async fn hybrid_worker_draft_obeys_readonly_resource_gate() { inherited_provenance: None, session_addr: None, compaction_config: None, + approval_relay: false, }; let readonly = SecurityPolicy { autonomy: crate::security::policy::AutonomyLevel::ReadOnly, diff --git a/src/session_worker/runner/tests/mod.rs b/src/session_worker/runner/tests/mod.rs index d952e9212..63f5d2b75 100644 --- a/src/session_worker/runner/tests/mod.rs +++ b/src/session_worker/runner/tests/mod.rs @@ -65,5 +65,6 @@ pub(crate) fn base_manifest(workspace: &Path, capability: &str) -> WorkerManifes inherited_provenance: None, session_addr: None, compaction_config: None, + approval_relay: false, } } diff --git a/src/session_worker/runner/tests/spawn_context.rs b/src/session_worker/runner/tests/spawn_context.rs index 116b776da..b70cd3d21 100644 --- a/src/session_worker/runner/tests/spawn_context.rs +++ b/src/session_worker/runner/tests/spawn_context.rs @@ -58,6 +58,7 @@ async fn process_mode_restores_spawn_context_for_nested_runs() { inherited_provenance: None, session_addr: None, compaction_config: None, + approval_relay: false, }; let snapshot = with_manifest_spawn_context(&manifest, None, async { @@ -141,6 +142,7 @@ fn worker_event_scope_preserves_spawn_lineage_and_owner_isolation() { inherited_provenance: None, session_addr: None, compaction_config: None, + approval_relay: false, }; let scope = worker_message_event_scope(&manifest); diff --git a/src/session_worker/stdout.rs b/src/session_worker/stdout.rs index fc39a5b5e..a353d5250 100644 --- a/src/session_worker/stdout.rs +++ b/src/session_worker/stdout.rs @@ -32,3 +32,7 @@ pub(crate) fn authenticate(auth: super::frame_auth::FrameAuth) -> Result<()> { pub fn frame(frame: &super::protocol::WorkerOutputFrame) -> Result<()> { write(frame, false) } +/// True once the parent's frame authentication is installed for this worker. +pub(crate) fn is_authenticated() -> bool { + FRAME_AUTH.get().is_some() +} diff --git a/src/tools/execution/approval_route.rs b/src/tools/execution/approval_route.rs index 9b10fa6a0..08d9be89b 100644 --- a/src/tools/execution/approval_route.rs +++ b/src/tools/execution/approval_route.rs @@ -17,4 +17,30 @@ impl ToolExecutionService { } (self.approval.resolve(request).await, false) } + + /// Resolve an approval that a process worker relayed to its parent, along + /// the chain an in-process child's request takes. + pub(crate) async fn resolve_relayed_approval(&self, request: ToolApprovalRequest) -> ToolApprovalDecision { + self.resolve_ordinary_approval(request).await.0 + } + + /// Whether the parent's own policy, at the call's sealed level, still asks + /// for approval. A relayed request that would not ask is refused. + pub(crate) fn relayed_call_asks( + &self, + descriptor: &super::ToolDescriptor, + context: &super::ToolExecutionContext, + ) -> bool { + let level = context.child_scope.as_ref().map_or_else( + || self.policy.autonomy_level(), + |scope| scope.gate_inputs().0.authority.level, + ); + let decision = super::admission::child_autonomy( + context, + descriptor, + self.policy.decide_at(descriptor, context, level), + level, + ); + decision == super::ToolExecutionDecision::Ask + } } diff --git a/src/tools/execution/refusal_record.rs b/src/tools/execution/refusal_record.rs index e4da91ec2..65bf03a27 100644 --- a/src/tools/execution/refusal_record.rs +++ b/src/tools/execution/refusal_record.rs @@ -121,10 +121,9 @@ impl ToolExecutionService { // including refusals that never enter this service. Keep one row per // outcome there; the operator notice above retains its original order. // The worker's sealed refusal inventory uses that same scheduler - // boundary. Approval calls still stay denied with no_resolver. + // boundary. if context.live_turn.is_some() - || (context.pending_approval_denied - && context.envelope.source == crate::runtime::envelope::RuntimeSource::SessionWorker) + || context.envelope.source == crate::runtime::envelope::RuntimeSource::SessionWorker { return; } diff --git a/src/tools/sessions_spawn/process_mode.rs b/src/tools/sessions_spawn/process_mode.rs index 07bef1ded..149be0a6c 100644 --- a/src/tools/sessions_spawn/process_mode.rs +++ b/src/tools/sessions_spawn/process_mode.rs @@ -106,6 +106,7 @@ pub(super) async fn run_sub_agent_process( batch_id: Option<&str>, mailbox: Option<&Arc>, parent_frames: Option>, + approval_relay: Option, #[cfg(test)] test_worker_executable: Option<&TestWorkerExecutable>, ) -> anyhow::Result { if source_fabric.is_some_and(|fabric| fabric.memory().requires_scoped_execution()) { @@ -286,6 +287,10 @@ pub(super) async fn run_sub_agent_process( ) .map_err(refused_here)?; + // Sealed before the manifest HMAC below: the switch is on only for an + // authenticated pipe, below Full, with a relay built from the caller. + let approval_relay = + approval_relay.and_then(|relay| relay.arm(mailbox_binding.as_ref(), &mut manifest)); manifest.seed_history = history .read() .await @@ -511,13 +516,18 @@ pub(super) async fn run_sub_agent_process( std::fs::remove_file(&config_path) .with_context(|| format!("remove worker config `{}`", config_path.display()))?; } - run_spawned_child_lifecycle( + let mut frames = mailbox_binding.as_mut().and_then(|binding| binding.frames.take()); + let relay = match (approval_relay, frames.as_mut()) { + (Some(armed), Some(frames)) => Some(armed.attach(frames, Arc::clone(&progress))), + _ => None, + }; + let lifecycle = run_spawned_child_lifecycle( &mut child, &mut process_group, &payload, process_control, Some(WorkerSteerPipe { - frames: mailbox_binding.as_mut().and_then(|binding| binding.frames.take()), + frames, steer_rx, history, run_id: run_id.to_string(), @@ -527,8 +537,18 @@ pub(super) async fn run_sub_agent_process( false, #[cfg(test)] protocol, - ) - .await + ); + match relay { + Some(relay) => { + // A cancel or kill request ends every approval wait at once. + let phase = relay + .guard(process_control.termination_requested(), lifecycle) + .await; + relay.cancel_all(); + phase + } + None => lifecycle.await, + } } .await; // Confirm the leader's reap only on branches with actual cleanup evidence. diff --git a/src/tools/sessions_spawn/spawn.rs b/src/tools/sessions_spawn/spawn.rs index b2c8f218c..0484cb567 100644 --- a/src/tools/sessions_spawn/spawn.rs +++ b/src/tools/sessions_spawn/spawn.rs @@ -886,6 +886,18 @@ impl SessionsSpawnTool { )), None => process_source_launch, }; + let process_approval_relay = crate::session_worker::approval::relay_context::RelaySeedInputs { + caller: caller.as_ref(), + binding: ordinary_binding.as_deref(), + resolvers: self.approval_resolver_factory.as_ref(), + scope: &spawn_scope_for_event, + task, + receipt: source_receipt.as_deref(), + security: launch_security, + level: child_level, + run_id: &run_id, + } + .seed()?; let temperature = resolved_temperature; let history_arc: Arc>> = Arc::new(RwLock::new(super::continuation::seed_history())); @@ -1155,6 +1167,7 @@ impl SessionsSpawnTool { process_batch_id.as_deref(), process_worker_mailbox.as_ref(), process_parent_frames, + process_approval_relay, #[cfg(test)] test_worker_executable.as_ref(), ) diff --git a/src/tools/sessions_spawn/tests/process_manifest.rs b/src/tools/sessions_spawn/tests/process_manifest.rs index f3db8cd31..8e518d0d9 100644 --- a/src/tools/sessions_spawn/tests/process_manifest.rs +++ b/src/tools/sessions_spawn/tests/process_manifest.rs @@ -199,6 +199,7 @@ fn process_mode_task_arg_is_not_json_encoded() { inherited_provenance: None, session_addr: None, compaction_config: None, + approval_relay: false, }; let args = build_session_worker_cli_args(&manifest).unwrap(); diff --git a/src/tools/sessions_spawn/worker_manifest.rs b/src/tools/sessions_spawn/worker_manifest.rs index 5ff8807b8..ebc0646bc 100644 --- a/src/tools/sessions_spawn/worker_manifest.rs +++ b/src/tools/sessions_spawn/worker_manifest.rs @@ -183,6 +183,7 @@ pub(super) fn build_session_worker_manifest( .and_then(|context| context.task_input.inherited_provenance), session_addr: None, compaction_config: Some(compaction_config.clone()), + approval_relay: false, }; if let Some(launch) = source_launch { From 6dd00611b966d19fd0fa7eec653ae5fbe46c1b54 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:00:49 +0400 Subject: [PATCH 0072/1567] feat(session-worker): carry a cancelled approval in the completion inventory Add a cancelled cause to the rf denial mapping and the worker denial inventory, so a cancelled call of a process child reaches the parent run as tool_status phase cancelled, cause cancelled, with child_run_id. Document it and the non-recordable root case. --- docs/rf-contract/capability-tokens.md | 11 ++++++++--- src/gateway/live_frames.rs | 11 ++++------- src/security/approval_ledger/run_call.rs | 3 +++ src/session_worker/denials.rs | 13 +++++++++++++ src/tools/execution/refusal_record.rs | 1 + 5 files changed, 29 insertions(+), 10 deletions(-) diff --git a/docs/rf-contract/capability-tokens.md b/docs/rf-contract/capability-tokens.md index fad2335d8..bc98e26b0 100644 --- a/docs/rf-contract/capability-tokens.md +++ b/docs/rf-contract/capability-tokens.md @@ -779,14 +779,19 @@ end with `no_resolver`; a process turn woken by a message ends with `no_approval_surface`, as a task child's does. While a relayed approval waits, the child shows `tool_status{phase:"awaiting_approval"}` on the child run and `approval.pending` carries the child `run_id`. The worker does not stream live -`started` or `succeeded` frames after an approval. The completion returns a +`started` or `succeeded` frames after an approval. A root that is not recordable +has no relay ledger, so the approvals of its process children end with +`ledger_refused`. The completion returns a bounded, content-free `denials:[{tool,cause}]` inventory under the existing completion signature. It carries pre-approval refusal and failure causes and -every approval denial cause, such as `owner_denied` and `expired`. Only after +every approval denial cause, such as `owner_denied` and `expired`, and +`cancelled` for a cancelled approval. Only after authentication does the parent emit one `tool_status` per outcome on the **parent run**, with `child_run_id` and its stable ids. Its phase is `failed` for `failed`/`indeterminate` causes, otherwise `denied`; its cause uses the same -typed mapping as an in-process child. Worker refusal rows are committed before +typed mapping as an in-process child, except that a cancelled call has phase +`cancelled` and cause `cancelled`, as an in-process child's cancelled call does. +Worker refusal rows are committed before the signed observation is emitted. The inventory holds at most 256 denials with tool names at most 64 bytes; overflow fails completion explicitly. It carries no model text or arguments. diff --git a/src/gateway/live_frames.rs b/src/gateway/live_frames.rs index c5e12dee3..d7b531154 100644 --- a/src/gateway/live_frames.rs +++ b/src/gateway/live_frames.rs @@ -213,13 +213,10 @@ impl LiveFrameSink for Producer { ) { use crate::security::approval_ledger::run_call::RfDenialCause; use crate::tools::execution::ToolCallRefusalReason; - let phase = if matches!( - cause, - RfDenialCause::Refusal(ToolCallRefusalReason::Failed | ToolCallRefusalReason::Indeterminate) - ) { - "failed" - } else { - "denied" + let phase = match cause { + RfDenialCause::Refusal(ToolCallRefusalReason::Failed | ToolCallRefusalReason::Indeterminate) => "failed", + RfDenialCause::Cancelled => "cancelled", + RfDenialCause::Approval(_) | RfDenialCause::Refusal(_) => "denied", }; let cause = crate::security::approval_ledger::run_call::rf_denial_cause(cause); self.send(json!({"kind":"tool_status","tool":tool,"phase":phase,"cause":cause,"child_run_id":child_run_id})); diff --git a/src/security/approval_ledger/run_call.rs b/src/security/approval_ledger/run_call.rs index 88b6734c9..d7b99618e 100644 --- a/src/security/approval_ledger/run_call.rs +++ b/src/security/approval_ledger/run_call.rs @@ -124,6 +124,8 @@ pub(crate) struct PendingCallPage { pub(crate) enum RfDenialCause { Approval(crate::tools::ApprovalDenialCause), Refusal(crate::tools::execution::ToolCallRefusalReason), + /// The call ended because its approval or run was cancelled. + Cancelled, } impl From for RfDenialCause { @@ -145,6 +147,7 @@ pub(crate) fn rf_denial_cause(cause: impl Into) -> &'static str { RfDenialCause::Approval(crate::tools::ApprovalDenialCause::NoAnswer) => "expired", RfDenialCause::Approval(other) => other.as_str(), RfDenialCause::Refusal(reason) => reason.as_str(), + RfDenialCause::Cancelled => "cancelled", } } diff --git a/src/session_worker/denials.rs b/src/session_worker/denials.rs index 3b762f81f..803c77df7 100644 --- a/src/session_worker/denials.rs +++ b/src/session_worker/denials.rs @@ -17,6 +17,14 @@ pub struct WorkerDenial { pub enum WorkerDenialCause { Approval(crate::tools::ApprovalDenialCause), Refusal(crate::tools::execution::ToolCallRefusalReason), + /// Serializes as the string `cancelled`, which no other cause uses. + Cancelled(CancelledCause), +} +/// The single value of [`WorkerDenialCause::Cancelled`]. +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CancelledCause { + Cancelled, } impl WorkerDenial { pub(crate) const fn valid(&self) -> bool { @@ -26,6 +34,7 @@ impl WorkerDenial { match self.cause { WorkerDenialCause::Approval(cause) => cause.into(), WorkerDenialCause::Refusal(cause) => cause.into(), + WorkerDenialCause::Cancelled(CancelledCause::Cancelled) => crate::security::approval_ledger::run_call::RfDenialCause::Cancelled, } } } @@ -68,6 +77,7 @@ impl LiveFrameSink for DenialSink { { let cause = match outcome { ToolCallOutcome::Denied { cause: Some(cause) } => Some((*cause).into()), + ToolCallOutcome::Cancelled => Some(crate::security::approval_ledger::run_call::RfDenialCause::Cancelled), ToolCallOutcome::Refused => Some(refusal_cause.unwrap_or(ToolCallRefusalReason::PolicyDenied).into()), ToolCallOutcome::PlanOnly => Some(ToolCallRefusalReason::PlanOnly.into()), ToolCallOutcome::Error => Some(refusal_cause.unwrap_or(ToolCallRefusalReason::Failed).into()), @@ -97,6 +107,9 @@ impl DenialSink { crate::security::approval_ledger::run_call::RfDenialCause::Refusal(cause) => { WorkerDenialCause::Refusal(cause) } + crate::security::approval_ledger::run_call::RfDenialCause::Cancelled => { + WorkerDenialCause::Cancelled(CancelledCause::Cancelled) + } }, }); } diff --git a/src/tools/execution/refusal_record.rs b/src/tools/execution/refusal_record.rs index 65bf03a27..a227e75a0 100644 --- a/src/tools/execution/refusal_record.rs +++ b/src/tools/execution/refusal_record.rs @@ -172,6 +172,7 @@ pub(crate) async fn record_rf_call_refusal( let reason = match cause { crate::security::approval_ledger::run_call::RfDenialCause::Approval(cause) => cause.as_str(), crate::security::approval_ledger::run_call::RfDenialCause::Refusal(reason) => reason.as_str(), + crate::security::approval_ledger::run_call::RfDenialCause::Cancelled => "cancelled", }; append_refusal( memory, From 2e20e431d28d99f12ef18508e77282673265834a Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:59:11 +0400 Subject: [PATCH 0073/1567] docs: make the process-child approval statements consistent State that no_resolver occurs for a process child only where the relay is not armed, and replace the stale denied wording in the rf contract and tools guide. --- docs/rf-contract/capability-tokens.md | 13 ++++++++----- docs/tools.md | 9 +++++---- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/docs/rf-contract/capability-tokens.md b/docs/rf-contract/capability-tokens.md index bc98e26b0..d52b748d2 100644 --- a/docs/rf-contract/capability-tokens.md +++ b/docs/rf-contract/capability-tokens.md @@ -677,8 +677,8 @@ continuation has a fresh run ID; `turn.started`, `turn.appended`, and `child_session.upsert` keep that turn's run and the four ancestry links. Consumers must accept repeated running-to-succeeded cycles for one child session key. Terminal-chat child sessions remain outside this journal. -Process-child approvals remain denied with `no_resolver`; focused task-child -approvals resolve only that child's pending call. +A focused child's approval resolves only that child's pending call; a process +child's approval is relayed to the root surface (see the approvals section). Welcome is `{type:"welcome",epoch,head_seq}`; events replay in sequence before live delivery. The install epoch is 32 lowercase hex characters and survives @@ -773,9 +773,12 @@ of at most 256 KiB, at most 8 outstanding requests per run, and that its own policy still asks) and refuses a bad one with `ledger_refused` or `concurrent_pending`. A decision is bound to the exact call by request id and input digest, and an approval carries the same verified one-shot grant an -in-process child gets; the worker never creates a grant. Without the relay -(no authenticated pipe, or an operator-rooted child), approval requests still -end with `no_resolver`; a process turn woken by a message ends with +in-process child gets; the worker never creates a grant. `no_resolver` occurs +for a process child only where the relay is not armed (`approval_relay` false): +a backend without the authenticated mailbox pipe, or an operator-rooted child +that has no caller approval surface. With the relay armed, a root that has no +approval resolver at all gets the same outcome a task child would get in that +position. A process turn woken by a message ends with `no_approval_surface`, as a task child's does. While a relayed approval waits, the child shows `tool_status{phase:"awaiting_approval"}` on the child run and `approval.pending` carries the child `run_id`. The worker does not stream live diff --git a/docs/tools.md b/docs/tools.md index 923209e19..ab2a375f0 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -1963,7 +1963,7 @@ In `prx chat`, Enter in a focused child starts a turn or queues behind its current turn. `/now` puts input first; `/steer` explicitly interrupts the current turn. Session commands operate on the focused child's context, model, history, usage, and task-mode approvals. `/level` displays the inherited -level. Process-child approval calls remain denied with `no_resolver`. +level. A process child's approval calls are relayed to the root approval surface. ## Messages between sessions @@ -1987,12 +1987,13 @@ turn uses the persisted child session and model, with its level capped by the current agent and owner configuration. It gets no inherited approval grant or local operator authority. Task approvals use the root session's live surface; without one, calls that need approval are denied with `no_approval_surface`. -Process-child approvals remain denied with `no_resolver`. Message turns count +A process turn woken by a message ends with `no_approval_surface`, as a task child's does. Message turns count toward the receiving agent's limits and daily cost, and run one at a time per child session. Process children continue in a new worker with public history seeded. Their -tool approvals remain denied with `no_resolver`; task/delegate approvals use -the owner's pending-approval surface. +tool approvals are relayed to the root session's approval surface, like task +and delegate approvals; `no_resolver` remains only where the relay is not armed +(a backend without the authenticated mailbox pipe, or an operator-rooted child). `session_status` includes the caller session's last 64 outbox states, including `expired` and permanent refusals, without message bodies or recipient tokens. From 7c4be9a5feb6a278ff95af8283a44958db7e4d77 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:21:39 +0400 Subject: [PATCH 0074/1567] fix(session-worker): a cancelled process child ends with a cancelled terminal The worker commits its logical and segment terminals as cancelled when its loop was cancelled, and the parent completion verifiers accept a cancelled terminal only together with an unsuccessful result. --- src/session_worker/runner/run.rs | 17 +++++++++++++++-- .../sessions_spawn/process_terminal/operator.rs | 15 +++++++++------ .../sessions_spawn/process_terminal/ordinary.rs | 15 +++++++++------ 3 files changed, 33 insertions(+), 14 deletions(-) diff --git a/src/session_worker/runner/run.rs b/src/session_worker/runner/run.rs index 8c3056ae1..30fa2f912 100644 --- a/src/session_worker/runner/run.rs +++ b/src/session_worker/runner/run.rs @@ -53,6 +53,12 @@ pub(super) async fn run_validated_manifest( run_authenticated_manifest(manifest, steer_rx, None, explicit_config_dir, Some(transport)).await } +/// A segment ends as cancelled when its token fired or its loop was cancelled, +/// for example by a cancelled relayed approval. +fn loop_cancelled(error: &anyhow::Error, cancel: &CancellationToken) -> bool { + cancel.is_cancelled() || crate::agent::turn_contracts::is_tool_loop_cancelled(error) +} + pub(super) async fn run_authenticated_manifest( manifest: WorkerManifest, steer_rx: Option>, @@ -1159,7 +1165,10 @@ async fn run_owned_manifest( if let (Some(turn), Some(segments)) = (child_turn.as_ref(), child_segments.as_ref()) { let settlement = match &loop_result { Ok((outcome, trace)) => segments.completion.complete(turn, outcome, trace).await, - Err(error) => segments.completion.fail(turn, error, cancel.is_cancelled()).await, + Err(error) => segments + .completion + .fail(turn, error, loop_cancelled(error, &cancel)) + .await, }; if let Err(error) = settlement { return (segment_history, Err(error)); @@ -1222,7 +1231,11 @@ async fn run_owned_manifest( )), tokens_used: None, }, - crate::agent::terminal::TurnTerminalStatus::Failed, + if crate::agent::turn_contracts::is_tool_loop_cancelled(&error) { + crate::agent::terminal::TurnTerminalStatus::Cancelled + } else { + crate::agent::terminal::TurnTerminalStatus::Failed + }, ), }; diff --git a/src/tools/sessions_spawn/process_terminal/operator.rs b/src/tools/sessions_spawn/process_terminal/operator.rs index 2d4465893..9a7a3f18b 100644 --- a/src/tools/sessions_spawn/process_terminal/operator.rs +++ b/src/tools/sessions_spawn/process_terminal/operator.rs @@ -271,19 +271,22 @@ async fn verify_completion( .await?; verify_lineage(&event, lineage)?; let payload = terminal_payload(&event)?; - let expected_status = if result.success { - TurnTerminalStatus::Completed - } else { - TurnTerminalStatus::Failed - }; let status: TurnTerminalStatus = serde_json::from_value( payload .get("status") .cloned() .context("operator terminal status missing")?, )?; + // Success needs a Completed terminal. A Cancelled terminal is accepted + // only together with `!success`, and then every check below applies + // unchanged: no history, and the failure text as the telemetry summary. + let status_matches = if result.success { + status == TurnTerminalStatus::Completed + } else { + matches!(status, TurnTerminalStatus::Failed | TurnTerminalStatus::Cancelled) + }; anyhow::ensure!( - status == expected_status + status_matches && payload.get("terminal_id").and_then(serde_json::Value::as_str) == Some(lineage.run_id.as_str()) && ["decision_id", "provider_outcome", "usage_settlement", "cost_settlement"] .iter() diff --git a/src/tools/sessions_spawn/process_terminal/ordinary.rs b/src/tools/sessions_spawn/process_terminal/ordinary.rs index d1e2946cb..799d44038 100644 --- a/src/tools/sessions_spawn/process_terminal/ordinary.rs +++ b/src/tools/sessions_spawn/process_terminal/ordinary.rs @@ -243,19 +243,22 @@ async fn verify_completion( .await?; verify_lineage(&event, lineage)?; let payload = terminal_payload(&event)?; - let expected_status = if result.success { - TurnTerminalStatus::Completed - } else { - TurnTerminalStatus::Failed - }; let status: TurnTerminalStatus = serde_json::from_value( payload .get("status") .cloned() .context("ordinary terminal status missing")?, )?; + // Success needs a Completed terminal. A Cancelled terminal is accepted + // only together with `!success`, and then every check below applies + // unchanged: no history, and the failure text as the telemetry summary. + let status_matches = if result.success { + status == TurnTerminalStatus::Completed + } else { + matches!(status, TurnTerminalStatus::Failed | TurnTerminalStatus::Cancelled) + }; anyhow::ensure!( - status == expected_status + status_matches && payload.get("terminal_id").and_then(serde_json::Value::as_str) == Some(lineage.run_id.as_str()) && ["decision_id", "provider_outcome", "usage_settlement", "cost_settlement"] .iter() From 6284f8afb2c4c228693fb950eb1f6369c7056651 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:33:05 +0400 Subject: [PATCH 0075/1567] fix(gateway): keep resolver drop from cancelling the job token The rf approval resolver cancelled the token it was built with when its last Arc dropped. That token was the message job's turn token, so a successful turn lost its terminal commit and ended failed with 'runtime work cancelled', and failed turns were classed as cancelled. The resolver now owns a child of the run token; dropping it only ends its own approval waits. --- src/gateway/api/sessions/section_1.rs | 4 +++- src/gateway/run_approvals.rs | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/gateway/api/sessions/section_1.rs b/src/gateway/api/sessions/section_1.rs index 55c2e0a8c..fcdd7d772 100644 --- a/src/gateway/api/sessions/section_1.rs +++ b/src/gateway/api/sessions/section_1.rs @@ -769,7 +769,9 @@ async fn run_console_runtime_turn( scope, streams: std::sync::Arc::clone(&state.rf_streams), approvals: std::sync::Arc::clone(&state.rf_approvals), - cancellation: decision.cancellation.clone(), + // The resolver owns a child of the run token: run cancellation reaches its + // approval waits, while dropping it never cancels the run or the job. + cancellation: decision.cancellation.child_token(), wait_secs, }) as std::sync::Arc }); diff --git a/src/gateway/run_approvals.rs b/src/gateway/run_approvals.rs index 833f23e07..148d5ebe5 100644 --- a/src/gateway/run_approvals.rs +++ b/src/gateway/run_approvals.rs @@ -131,6 +131,8 @@ pub(crate) struct RunApprovalResolver { pub(crate) scope: Value, pub(crate) streams: Arc, pub(crate) approvals: Arc, + /// Owned by the resolver and cancelled on drop; it must never be a token + /// the run or job also holds (pass a child token of the run's token). pub(crate) cancellation: CancellationToken, pub(crate) wait_secs: u64, } From c7f881da129a61fcdd9664d0f35a832ef908478c Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:16:27 +0400 Subject: [PATCH 0076/1567] chore(hooks): rename the pre-push switches to the PRX_ prefix --- .githooks/pre-push | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/.githooks/pre-push b/.githooks/pre-push index f69e1cb59..875e9be3e 100755 --- a/.githooks/pre-push +++ b/.githooks/pre-push @@ -12,32 +12,32 @@ echo "==> pre-push: running rust quality gate..." exit 1 } -if [ "${ZEROCLAW_STRICT_LINT:-0}" = "1" ]; then - echo "==> pre-push: running strict clippy warnings gate (ZEROCLAW_STRICT_LINT=1)..." +if [ "${PRX_STRICT_LINT:-0}" = "1" ]; then + echo "==> pre-push: running strict clippy warnings gate (PRX_STRICT_LINT=1)..." ./scripts/ci/rust_quality_gate.sh --strict || { echo "FAIL: strict clippy warnings gate reported issues." exit 1 } fi -if [ "${ZEROCLAW_STRICT_DELTA_LINT:-0}" = "1" ]; then - echo "==> pre-push: running strict delta lint gate (ZEROCLAW_STRICT_DELTA_LINT=1)..." +if [ "${PRX_STRICT_DELTA_LINT:-0}" = "1" ]; then + echo "==> pre-push: running strict delta lint gate (PRX_STRICT_DELTA_LINT=1)..." ./scripts/ci/rust_strict_delta_gate.sh || { echo "FAIL: strict delta lint gate reported issues." exit 1 } fi -if [ "${ZEROCLAW_DOCS_LINT:-0}" = "1" ]; then - echo "==> pre-push: running docs quality gate (ZEROCLAW_DOCS_LINT=1)..." +if [ "${PRX_DOCS_LINT:-0}" = "1" ]; then + echo "==> pre-push: running docs quality gate (PRX_DOCS_LINT=1)..." ./scripts/ci/docs_quality_gate.sh || { echo "FAIL: docs quality gate reported issues." exit 1 } fi -if [ "${ZEROCLAW_DOCS_LINKS:-0}" = "1" ]; then - echo "==> pre-push: running docs links gate (ZEROCLAW_DOCS_LINKS=1)..." +if [ "${PRX_DOCS_LINKS:-0}" = "1" ]; then + echo "==> pre-push: running docs links gate (PRX_DOCS_LINKS=1)..." ./scripts/ci/docs_links_gate.sh || { echo "FAIL: docs links gate reported issues." exit 1 From d386d37200e680b0fae18188f9fe54e2847c03d0 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:16:27 +0400 Subject: [PATCH 0077/1567] docs(readme): drop the fork sentence from the introduction --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index bc4831da1..b8d0fcb98 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,6 @@ Self-hosted AI assistant framework built in Rust. Multi-channel, multi-provider, with built-in self-evolution. -Forked from [ZeroClaw](https://github.com/zeroclaw-labs/zeroclaw) and extended with production reliability, governance-aware AI, and a self-evolution system. - ## Highlights - **Broad LLM provider catalog** — Anthropic (Console API key), OpenAI, Google Gemini (API key), Ollama, AWS Bedrock, GLM, OpenAI Codex via Sign in with ChatGPT, local runtimes, and compatible endpoints. GitHub Copilot login is disabled. Provider requests send `User-Agent: prx/`. From 8d5c6f8a3064e480d774d4c772525f9bac05fa16 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:19:23 +0400 Subject: [PATCH 0078/1567] docs(readme): remove the related projects table --- README.md | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/README.md b/README.md index b8d0fcb98..f2229a094 100644 --- a/README.md +++ b/README.md @@ -145,16 +145,6 @@ cargo build --release --locked --bin prx - [Community](https://community.openprx.dev) — OpenPRX community forum - [OpenPRX](https://openprx.dev) — Project homepage -## Related Projects - -| Repository | Description | -|------------|-------------| -| [openprx/prx](https://github.com/openprx/prx) | AI assistant framework (this repo) | -| [openprx/prx-memory](https://github.com/openprx/prx-memory) | Standalone memory MCP server | -| [openprx/openpr](https://github.com/openprx/openpr) | Project management platform | -| [openprx/openpr-webhook](https://github.com/openprx/openpr-webhook) | Webhook receiver for OpenPR | -| [openprx/wacli](https://github.com/openprx/wacli) | WhatsApp CLI with JSON-RPC daemon | - ## Contact info@sylvode.org — general and partnership enquiries. Report security issues privately as described in [SECURITY.md](SECURITY.md). From 71c326c53b0f603c1066cfe14910f3c0cdcce519 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:23:24 +0400 Subject: [PATCH 0079/1567] refactor(config): rename the general proxy scope value to prx The default proxy scope is now spelled "prx" (ProxyScope::Prx). The previous value is no longer accepted: no alias, no migration. Golden effective config and its pinned fingerprint follow. --- src/config/generation/section_2.rs | 2 +- src/config/schema/proxy.rs | 12 ++++++------ src/config/schema/tests/proxy.rs | 6 +++--- .../child_source/golden_effective_config.json | 2 +- src/tools/http_request.rs | 2 +- src/tools/proxy_config.rs | 6 +++--- 6 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/config/generation/section_2.rs b/src/config/generation/section_2.rs index c2e10e1a0..1a9e636b0 100644 --- a/src/config/generation/section_2.rs +++ b/src/config/generation/section_2.rs @@ -32,7 +32,7 @@ mod tests { b"]", ] .concat(); - const FOR_CHILD_FINGERPRINT: &str = "82d04107528a017756b4311354691ae8cdae998870eb4902307c16e0b9e23df4"; + const FOR_CHILD_FINGERPRINT: &str = "205bb9dd92ff723b2353b3ee4bbf3d863c05c03a9befe49fe3506bfe4567f9c1"; assert_eq!(format!("{:x}", sha2::Sha256::digest(&preimage)), FOR_CHILD_FINGERPRINT); assert_eq!(generation.source_revision.fingerprint_sha256, FOR_CHILD_FINGERPRINT); assert_eq!(generation.id.0, 0); diff --git a/src/config/schema/proxy.rs b/src/config/schema/proxy.rs index 512e5164d..39074c5ba 100644 --- a/src/config/schema/proxy.rs +++ b/src/config/schema/proxy.rs @@ -66,7 +66,7 @@ pub enum ProxyScope { Environment, /// Apply proxy to all OpenPRX-managed HTTP traffic (default). #[default] - Zeroclaw, + Prx, /// Apply proxy only to explicitly listed service selectors. Services, } @@ -101,7 +101,7 @@ impl Default for ProxyConfig { https_proxy: None, all_proxy: None, no_proxy: Vec::new(), - scope: ProxyScope::Zeroclaw, + scope: ProxyScope::Prx, services: Vec::new(), } } @@ -175,7 +175,7 @@ impl ProxyConfig { /// `proxy.scope = "environment"`, and what the `proxy_config` tool /// answers when asked to set it. pub const ENVIRONMENT_SCOPE_INACTIVE: &str = "proxy.scope = \"environment\" is inactive: PRX never writes the \ - process environment, so the configured proxy URLs route no traffic. Migrate to proxy.scope = \"zeroclaw\" \ + process environment, so the configured proxy URLs route no traffic. Migrate to proxy.scope = \"prx\" \ (all PRX traffic; tool `proxy_config` scope 'prx') or to proxy.scope = \"services\" with a proxy.services \ list; to keep using inherited variables, start PRX with HTTP_PROXY/HTTPS_PROXY/ALL_PROXY/NO_PROXY already set"; @@ -185,7 +185,7 @@ impl ProxyConfig { pub const fn environment_scope_notice(&self) -> Option<&'static str> { match self.scope { ProxyScope::Environment => Some(Self::ENVIRONMENT_SCOPE_INACTIVE), - ProxyScope::Zeroclaw | ProxyScope::Services => None, + ProxyScope::Prx | ProxyScope::Services => None, } } @@ -193,7 +193,7 @@ impl ProxyConfig { /// the scope is `services` and `proxy.services` lists the key itself /// (trimmed and case-folded like every selector). A wildcard selector /// such as `tool.*`, a proxy that merely applies to everything (scope - /// `zeroclaw`) and one inherited from the environment are not an + /// `prx`) and one inherited from the environment are not an /// explicit selection. pub fn explicitly_selects_service(&self, service_key: &str) -> bool { if self.scope != ProxyScope::Services || !self.has_any_proxy_url() { @@ -236,7 +236,7 @@ impl ProxyConfig { match self.scope { ProxyScope::Environment => false, - ProxyScope::Zeroclaw => true, + ProxyScope::Prx => true, ProxyScope::Services => { let service_key = service_key.trim().to_ascii_lowercase(); if service_key.is_empty() { diff --git a/src/config/schema/tests/proxy.rs b/src/config/schema/tests/proxy.rs index e5d1ea488..33a0ac63f 100644 --- a/src/config/schema/tests/proxy.rs +++ b/src/config/schema/tests/proxy.rs @@ -116,7 +116,7 @@ fn proxy_with_scope(scope: ProxyScope, services: &[&str]) -> ProxyConfig { /// an explicit selection; a general or environment proxy is not. #[test] async fn only_a_services_selector_explicitly_selects_a_service() { - let general = proxy_with_scope(ProxyScope::Zeroclaw, &[]); + let general = proxy_with_scope(ProxyScope::Prx, &[]); assert!( general.should_apply_to_service("tool.http_request"), "a general proxy still applies to ordinary clients" @@ -185,13 +185,13 @@ async fn a_saved_environment_scope_loads_with_a_migration_notice() { ProxyConfig::ENVIRONMENT_SCOPE_INACTIVE, "the notice is the published migration text" ); - for needed in ["inactive", "zeroclaw", "services", "HTTP_PROXY"] { + for needed in ["inactive", "prx", "services", "HTTP_PROXY"] { assert!( notice.contains(needed), "the migration notice must mention `{needed}`: {notice}" ); } - for scope in [ProxyScope::Zeroclaw, ProxyScope::Services] { + for scope in [ProxyScope::Prx, ProxyScope::Services] { assert!( proxy_with_scope(scope, &["tool.*"]) .environment_scope_notice() diff --git a/src/runtime/child_source/golden_effective_config.json b/src/runtime/child_source/golden_effective_config.json index d5b4d71c2..19e5a18ef 100644 --- a/src/runtime/child_source/golden_effective_config.json +++ b/src/runtime/child_source/golden_effective_config.json @@ -1 +1 @@ -{"a2a":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trust_domain":"prx.local","trusted_trust_domains":[]},"agent":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"messaging":{"inbound":true},"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2},"agents":{},"api_key":null,"api_url":null,"auth":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"},"autonomy":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":500,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true},"browser":{"allowed_domains":[],"computer_use":{"api_key":null}},"channels_config":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null},"chat":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2},"compliance":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}},"composio":{"api_key":null,"entity_id":"default"},"cost":{"allow_override":false,"daily_limit_usd":10.0,"monthly_limit_usd":100.0,"prices":{"alpha/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0},"zeta/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0}},"warn_at_percent":80},"cron":{"max_run_history":50},"decision_engine":{"backend":{"circuit_breaker":{"cooldown_secs":60,"failure_threshold":5},"credential_ref":"","endpoint":"","kind":"auto","max_request_bytes":65536,"max_response_bytes":262144,"model":"","pinned_snapshot":"","remote_enabled":false,"timeout_ms":250},"candidates":5,"enabled":false,"latency_budget_ms":500,"max_candidates":12,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"token_ratio_limit":0.3499999940395355},"default_model":"anthropic/claude-sonnet-5","default_provider":"openrouter","default_temperature":0.7,"embedding_routes":[],"gateway":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":false,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60},"heartbeat":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."},"http_request":{"max_response_size":1000000,"timeout_secs":30},"identity":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"},"identity_bindings":[],"mcp":{"servers":{}},"mcp_server":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true},"media":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"},"memory":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7},"model_routes":[],"model_settings":{},"multimodal":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4},"nodes":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}},"observability":{"backend":"none","otel_endpoint":null,"otel_service_name":null},"plugins":{"enabled":false},"providers":{"ollama":{"num_ctx":null}},"proxy":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"zeroclaw","services":[]},"query_classification":{"rules":[]},"reliability":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2},"router":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]},"runtime":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null},"scheduler":{"claim_lease_secs":90,"max_tasks":64},"secrets":{"encrypt":true},"security":{"audit":{"log_path":"audit.log","max_size_mb":100}},"self_system":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24},"sessions_spawn":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null},"skill_rag":{"top_k":32},"skills":{"open_skills_dir":null,"openclaw_skills_dir":null},"skills_lifecycle":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]},"smart_group":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5},"storage":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}},"task_routing":{"default_intent":"simple","rules":[]},"tool_tiering":{"always_exclude":[],"always_include":[],"channel_exclude":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","git_operations","skills_manage","memory_reindex","document_sync","document_ingest"]},"tunnel":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null},"user_policies":[],"web_search":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15},"webhook":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null},"xin":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}} \ No newline at end of file +{"a2a":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trust_domain":"prx.local","trusted_trust_domains":[]},"agent":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"messaging":{"inbound":true},"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2},"agents":{},"api_key":null,"api_url":null,"auth":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"},"autonomy":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":500,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true},"browser":{"allowed_domains":[],"computer_use":{"api_key":null}},"channels_config":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null},"chat":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2},"compliance":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}},"composio":{"api_key":null,"entity_id":"default"},"cost":{"allow_override":false,"daily_limit_usd":10.0,"monthly_limit_usd":100.0,"prices":{"alpha/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0},"zeta/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0}},"warn_at_percent":80},"cron":{"max_run_history":50},"decision_engine":{"backend":{"circuit_breaker":{"cooldown_secs":60,"failure_threshold":5},"credential_ref":"","endpoint":"","kind":"auto","max_request_bytes":65536,"max_response_bytes":262144,"model":"","pinned_snapshot":"","remote_enabled":false,"timeout_ms":250},"candidates":5,"enabled":false,"latency_budget_ms":500,"max_candidates":12,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"token_ratio_limit":0.3499999940395355},"default_model":"anthropic/claude-sonnet-5","default_provider":"openrouter","default_temperature":0.7,"embedding_routes":[],"gateway":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":false,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60},"heartbeat":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."},"http_request":{"max_response_size":1000000,"timeout_secs":30},"identity":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"},"identity_bindings":[],"mcp":{"servers":{}},"mcp_server":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true},"media":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"},"memory":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7},"model_routes":[],"model_settings":{},"multimodal":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4},"nodes":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}},"observability":{"backend":"none","otel_endpoint":null,"otel_service_name":null},"plugins":{"enabled":false},"providers":{"ollama":{"num_ctx":null}},"proxy":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]},"query_classification":{"rules":[]},"reliability":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2},"router":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]},"runtime":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null},"scheduler":{"claim_lease_secs":90,"max_tasks":64},"secrets":{"encrypt":true},"security":{"audit":{"log_path":"audit.log","max_size_mb":100}},"self_system":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24},"sessions_spawn":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null},"skill_rag":{"top_k":32},"skills":{"open_skills_dir":null,"openclaw_skills_dir":null},"skills_lifecycle":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]},"smart_group":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5},"storage":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}},"task_routing":{"default_intent":"simple","rules":[]},"tool_tiering":{"always_exclude":[],"always_include":[],"channel_exclude":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","git_operations","skills_manage","memory_reindex","document_sync","document_ingest"]},"tunnel":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null},"user_policies":[],"web_search":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15},"webhook":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null},"xin":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}} \ No newline at end of file diff --git a/src/tools/http_request.rs b/src/tools/http_request.rs index cbddf0e35..f7b73444d 100644 --- a/src/tools/http_request.rs +++ b/src/tools/http_request.rs @@ -1268,7 +1268,7 @@ mod tests { let (target_listener, target_address) = loopback_listener().await; let (proxy_listener, proxy_address) = loopback_listener().await; let server = tokio::spawn(async move { serve_one_request(&target_listener, OK_RESPONSE).await }); - let general = proxy_config(crate::config::ProxyScope::Zeroclaw, &[], proxy_address); + let general = proxy_config(crate::config::ProxyScope::Prx, &[], proxy_address); assert!( general.should_apply_to_service(PROXY_SERVICE_KEY), "test setup: ordinary clients would use this proxy" diff --git a/src/tools/proxy_config.rs b/src/tools/proxy_config.rs index 36088d711..99effe806 100644 --- a/src/tools/proxy_config.rs +++ b/src/tools/proxy_config.rs @@ -96,7 +96,7 @@ impl ProxyConfigTool { fn parse_scope(raw: &str) -> Option { match raw.trim().to_ascii_lowercase().as_str() { "environment" | "env" => Some(ProxyScope::Environment), - "prx" | "internal" | "core" => Some(ProxyScope::Zeroclaw), + "prx" | "internal" | "core" => Some(ProxyScope::Prx), "services" | "service" => Some(ProxyScope::Services), _ => None, } @@ -448,7 +448,7 @@ impl Tool for ProxyConfigTool { } fn description(&self) -> &str { - "Manage ZeroClaw proxy settings (scope: prx | services): 'get' reads the effective settings, 'set' writes them, 'list_services' lists the routable service selectors; 'apply_env', 'clear_env' and scope 'environment' are refused (PRX never modifies the process environment)" + "Manage PRX proxy settings (scope: prx | services): 'get' reads the effective settings, 'set' writes them, 'list_services' lists the routable service selectors; 'apply_env', 'clear_env' and scope 'environment' are refused (PRX never modifies the process environment)" } fn parameters_schema(&self) -> serde_json::Value { @@ -849,7 +849,7 @@ mod tests { "scope '{scope}': the refusal is the typed error" ); assert!( - error.contains("nothing was changed") && error.contains("zeroclaw") && error.contains("services"), + error.contains("nothing was changed") && error.contains("prx") && error.contains("services"), "the refusal must carry the migration text, got {error}" ); } From 393aa343430061ac6a12440a478998c2fe550462 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:23:24 +0400 Subject: [PATCH 0080/1567] chore: drop legacy environment variable names from schema descriptions No code reads the removed names. Docs and the schema fixture follow. --- docs/configuration.md | 8 ++++---- docs/providers.md | 2 +- src/config/schema/agent.rs | 4 ++-- src/config/schema/memory.rs | 4 ++-- src/config/schema/runtime.rs | 4 ++-- src/service/mod.rs | 4 ++-- tests/fixtures/config-schema.json | 2 +- 7 files changed, 14 insertions(+), 14 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index e6b9dc512..927a92a7a 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -143,7 +143,7 @@ and the module-gate family are absorbed on load; they are not live switches. | `[http_request]` | `max_response_size = 1000000`; `timeout_secs = 30` | | `[multimodal]` | `max_images = 4`; `max_image_size_mb = 5`; `allow_remote_fetch = false` | | `[web_search]` | `provider = "duckduckgo"`; `brave_api_key` unset; `max_results = 15`; `timeout_secs = 15`; `fetch_max_chars = 50000` | -| `[proxy]` | `http_proxy`/`https_proxy`/`all_proxy` unset; `no_proxy = []`; `scope = "zeroclaw"`; `services = []` | +| `[proxy]` | `http_proxy`/`https_proxy`/`all_proxy` unset; `no_proxy = []`; `scope = "prx"`; `services = []` | | `[identity]` | `format = "openclaw"`; `aieos_path` unset; `aieos_inline` unset | | `[cost]` | `daily_limit_usd = 10.0`; `monthly_limit_usd = 100.0`; `warn_at_percent = 80`; `allow_override = false`; `prices = {}` (each price: `input`/`output`/`cache_write`/`cache_read = 0`) | | `[nodes]` | `request_timeout_ms = 15000`; `retry_max = 2`; `nodes = []`. A node: `id`, `endpoint`, `bearer_token` required; `hmac_secret` unset; `timeout_ms`/`retry_max` unset | @@ -2033,7 +2033,7 @@ again before downgrading. ### Outbound proxy (`[proxy]`) `[proxy]` routes PRX's outbound HTTP through `http_proxy`, `https_proxy` or -`all_proxy`. `scope = "zeroclaw"` (the default; `prx` in the agent +`all_proxy`. `scope = "prx"` (the default; the same word in the agent `proxy_config` tool) applies the proxy to all PRX-managed traffic; `scope = "services"` applies it only to the selectors in `proxy.services` (`provider.openai`, `tool.http_request`, `tool.*`, ...; the `proxy_config` @@ -2044,7 +2044,7 @@ cannot change `HTTP_PROXY` and its relatives safely, so: - `scope = "environment"` is inactive. A saved configuration that still has it loads, with one warning, and its proxy URLs route no traffic. Migrate - to `scope = "zeroclaw"` to proxy all PRX traffic, or to + to `scope = "prx"` to proxy all PRX traffic, or to `scope = "services"` with a `proxy.services` list. To rely on inherited variables instead, start PRX with `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY` and `NO_PROXY` already set and leave the `[proxy]` URLs empty. @@ -2057,7 +2057,7 @@ resolve the host once, refuse it when any address is private or local, and connect to exactly the checked address; `web_fetch` repeats this for every redirect hop and `http_request` does not follow redirects. A proxy resolves the host name itself, so through a proxy the checked address would not be -the one connected to. A general proxy (`scope = "zeroclaw"`) and proxy +the one connected to. A general proxy (`scope = "prx"`) and proxy variables inherited from the environment are therefore not used by these two tools: diff --git a/docs/providers.md b/docs/providers.md index 453a93f38..28495ed98 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -1127,7 +1127,7 @@ row with summed counters and the worst state. - Malformed/unexpected response payloads fail fast with `provider_response_parse_error`. - Stream idle timeout is controlled by - `ZEROCLAW_CODEX_STREAM_IDLE_TIMEOUT_SECS` (default 45 seconds, minimum 5). + `[runtime] codex_stream_idle_timeout_secs` (default 45 seconds, minimum 5). A Root connection with `api_url` or `reliability.api_keys` but no `api_key` keeps that owner-bound endpoint and rotation material, then performs the same diff --git a/src/config/schema/agent.rs b/src/config/schema/agent.rs index d040c38d2..c208ca169 100644 --- a/src/config/schema/agent.rs +++ b/src/config/schema/agent.rs @@ -241,11 +241,11 @@ pub struct SelfSystemConfig { #[serde(default = "default_self_system_evolution_interval_hours")] pub evolution_interval_hours: u32, - /// Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG / ZEROCLAW_EVOLUTION_CONFIG) + /// Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG) #[serde(default)] pub evolution_config_path: Option, - /// Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW / ZEROCLAW_EVOLUTION_DEBUG_RAW) + /// Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW) #[serde(default)] pub evolution_debug_raw: bool, diff --git a/src/config/schema/memory.rs b/src/config/schema/memory.rs index 3aabd81c3..1954372d2 100644 --- a/src/config/schema/memory.rs +++ b/src/config/schema/memory.rs @@ -194,11 +194,11 @@ pub struct MemoryConfig { pub sqlite_read_pool_size: Option, // ── Lucid memory backend options ───────────────────────────── - /// Path to lucid binary (replaces ZEROCLAW_LUCID_CMD / OPENPRX_LUCID_CMD) + /// Path to lucid binary (replaces OPENPRX_LUCID_CMD) #[serde(default)] pub lucid_cmd: Option, - /// Token budget for lucid (replaces ZEROCLAW_LUCID_BUDGET / OPENPRX_LUCID_BUDGET) + /// Token budget for lucid (replaces OPENPRX_LUCID_BUDGET) #[serde(default)] pub lucid_budget: Option, diff --git a/src/config/schema/runtime.rs b/src/config/schema/runtime.rs index 036f050c2..12bd886d1 100644 --- a/src/config/schema/runtime.rs +++ b/src/config/schema/runtime.rs @@ -36,11 +36,11 @@ pub struct RuntimeConfig { #[serde(default)] pub reasoning_enabled: Option, - /// Codex stream idle timeout in seconds (replaces ZEROCLAW_CODEX_STREAM_IDLE_TIMEOUT_SECS) + /// Codex stream idle timeout in seconds #[serde(default)] pub codex_stream_idle_timeout_secs: Option, - /// Codex reasoning effort (replaces ZEROCLAW_CODEX_REASONING_EFFORT) + /// Codex reasoning effort #[serde(default)] pub codex_reasoning_effort: Option, diff --git a/src/service/mod.rs b/src/service/mod.rs index 0fb0de162..a75c747c2 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -1644,8 +1644,8 @@ mod tests { assert!(script.contains("description=\"PRX daemon\"")); assert!(script.contains("command='/usr/local/bin/prx'")); assert!(script.contains("command_args=\"--config-dir '/etc/prx' daemon\"")); - assert!(!script.contains("env ZEROCLAW_CONFIG_DIR")); - assert!(!script.contains("env ZEROCLAW_WORKSPACE")); + assert!(!script.contains("env OPENPRX_CONFIG_DIR")); + assert!(!script.contains("env OPENPRX_WORKSPACE")); assert!(script.contains("command_background=\"yes\"")); assert!(script.contains("command_user=\"prx:prx\"")); assert!(script.contains("pidfile=\"/run/${RC_SVCNAME}.pid\"")); diff --git a/tests/fixtures/config-schema.json b/tests/fixtures/config-schema.json index 863a60e00..7300d84c3 100644 --- a/tests/fixtures/config-schema.json +++ b/tests/fixtures/config-schema.json @@ -1 +1 @@ -{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Config","description":"Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).","type":"object","properties":{"a2a":{"description":"Agent-to-Agent compatibility configuration (`[a2a]`).","$ref":"#/$defs/A2aConfig","default":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trusted_trust_domains":[],"trust_domain":"prx.local"}},"agent":{"description":"Agent orchestration settings (`[agent]`).","$ref":"#/$defs/AgentConfig","default":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2,"messaging":{"inbound":true}}},"agents":{"description":"Delegate agent configurations for multi-agent workflows.","type":"object","additionalProperties":{"$ref":"#/$defs/DelegateAgentConfig"},"default":{}},"api_key":{"description":"API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.","type":["string","null"],"default":null},"api_url":{"description":"Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)","type":["string","null"],"default":null},"auth":{"description":"Auth profile and external credential import settings (`[auth]`).","$ref":"#/$defs/AuthConfig","default":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"}},"autonomy":{"description":"Autonomy and security policy configuration (`[autonomy]`).","$ref":"#/$defs/AutonomyConfig","default":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":500,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true}},"browser":{"description":"Browser automation configuration (`[browser]`).","$ref":"#/$defs/BrowserConfig","default":{"allowed_domains":[],"computer_use":{"api_key":null}}},"channels_config":{"description":"Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).","$ref":"#/$defs/ChannelsConfig","default":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null}},"chat":{"description":"Interactive chat UI configuration (`[chat]`).","$ref":"#/$defs/ChatConfig","default":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2}},"compliance":{"description":"Operator-owned compliance controls (`[compliance]`).","$ref":"#/$defs/ComplianceConfig","default":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}},"composio":{"description":"Composio managed OAuth tools integration (`[composio]`).","$ref":"#/$defs/ComposioConfig","default":{"api_key":null,"entity_id":"default"}},"cost":{"description":"Cost tracking and budget enforcement configuration (`[cost]`).","$ref":"#/$defs/CostConfig","default":{"allow_override":false,"daily_limit_usd":10.0,"monthly_limit_usd":100.0,"prices":{},"warn_at_percent":80}},"cron":{"description":"Cron job configuration (`[cron]`).","$ref":"#/$defs/CronConfig","default":{"max_run_history":50}},"decision_engine":{"description":"Optional advisory decision engine, disabled by default.","$ref":"#/$defs/DecisionEngineConfig","default":{"candidates":5,"enabled":false,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"latency_budget_ms":500,"max_candidates":12,"token_ratio_limit":0.3499999940395355}},"default_model":{"description":"Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.","type":["string","null"]},"default_provider":{"description":"Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.","type":["string","null"]},"default_temperature":{"description":"Default model temperature (0.0–2.0). Default: `0.7`.","type":"number","format":"double","default":0.7},"embedding_routes":{"description":"Embedding routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/EmbeddingRouteConfig"}},"gateway":{"description":"Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).","$ref":"#/$defs/GatewayConfig","default":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":false,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60}},"heartbeat":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]`).","$ref":"#/$defs/HeartbeatConfig","default":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."}},"http_request":{"description":"HTTP request tool configuration (`[http_request]`).","$ref":"#/$defs/HttpRequestConfig","default":{"max_response_size":1000000,"timeout_secs":30}},"identity":{"description":"Identity format configuration: OpenClaw or AIEOS (`[identity]`).","$ref":"#/$defs/IdentityConfig","default":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"}},"identity_bindings":{"description":"Static identity bindings loaded at startup (`[[identity_bindings]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/IdentityBindingConfig"}},"mcp":{"description":"Secrets encryption configuration (`[secrets]`).","$ref":"#/$defs/McpConfig","default":{"servers":{}}},"mcp_server":{"description":"MCP server compatibility configuration (`[mcp_server]`).","$ref":"#/$defs/McpServerRuntimeConfig","default":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true}},"media":{"description":"Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.","$ref":"#/$defs/MediaConfig","default":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"}},"memory":{"description":"Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).","$ref":"#/$defs/MemoryConfig","default":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7}},"model_routes":{"description":"Model routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/ModelRouteConfig"}},"model_settings":{"description":"Catalog model levels and explicit parameters, keyed by canonical release ID.","type":"object","additionalProperties":{"$ref":"#/$defs/ModelSettings"},"default":{}},"multimodal":{"description":"Multimodal (image) handling configuration (`[multimodal]`).","$ref":"#/$defs/MultimodalConfig","default":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4}},"nodes":{"description":"Remote node proxy configuration (`[nodes]`).","$ref":"#/$defs/NodesConfig","default":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}},"observability":{"description":"Observability backend configuration (`[observability]`).","$ref":"#/$defs/ObservabilityConfig","default":{"backend":"none","otel_endpoint":null,"otel_service_name":null}},"plugins":{"description":"WASM plugin runtime switch (`[plugins]`), off by default.","$ref":"#/$defs/PluginsConfig","default":{"enabled":false}},"providers":{"description":"Provider-specific runtime options (`[providers.]`).","$ref":"#/$defs/ProvidersConfig","default":{"ollama":{"num_ctx":null}}},"proxy":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).","$ref":"#/$defs/ProxyConfig","default":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"zeroclaw","services":[]}},"query_classification":{"description":"Automatic query classification — maps user messages to model hints.","$ref":"#/$defs/QueryClassificationConfig","default":{"rules":[]}},"reliability":{"description":"Reliability settings: retries, fallback providers, backoff (`[reliability]`).","$ref":"#/$defs/ReliabilityConfig","default":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2}},"router":{"description":"Heuristic LLM router configuration (`[router]`).","$ref":"#/$defs/RouterConfig","default":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]}},"runtime":{"description":"Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.","$ref":"#/$defs/RuntimeConfig","default":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null}},"scheduler":{"description":"Scheduler configuration for periodic task execution (`[scheduler]`).","$ref":"#/$defs/SchedulerConfig","default":{"claim_lease_secs":90,"max_tasks":64}},"secrets":{"$ref":"#/$defs/SecretsConfig","default":{"encrypt":true}},"security":{"description":"Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).","$ref":"#/$defs/SecurityConfig","default":{"audit":{"log_path":"audit.log","max_size_mb":100}}},"self_system":{"description":"Self-system experimental automation controls (`[self_system]`).","$ref":"#/$defs/SelfSystemConfig","default":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24}},"sessions_spawn":{"description":"Session spawning configuration (`[sessions_spawn]`).","$ref":"#/$defs/SessionsSpawnConfig","default":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null}},"skill_rag":{"description":"Dynamic skill retrieval settings (`[skill_rag]`).","$ref":"#/$defs/SkillRagConfig","default":{"top_k":32}},"skills":{"description":"Skills loading and community repository behavior (`[skills]`).","$ref":"#/$defs/SkillsConfig","default":{"open_skills_dir":null,"openclaw_skills_dir":null}},"skills_lifecycle":{"description":"Skill lifecycle (`[skills_lifecycle]`), off by default.","$ref":"#/$defs/SkillsLifecycleConfig","default":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]}},"smart_group":{"description":"Smart group-reply pre-gate configuration (`[smart_group]`).","$ref":"#/$defs/SmartGroupConfig","default":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5}},"storage":{"description":"Persistent storage provider configuration (`[storage]`).","$ref":"#/$defs/StorageConfig","default":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"task_routing":{"description":"Task routing configuration — classifies work by intent before the main agent loop.","$ref":"#/$defs/TaskRoutingConfig","default":{"default_intent":"simple","rules":[]}},"tool_tiering":{"description":"Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).","$ref":"#/$defs/ToolTieringConfig","default":{"always_exclude":[],"always_include":[],"channel_exclude":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","git_operations","skills_manage","memory_reindex","document_sync","document_ingest"]}},"tunnel":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]`).","$ref":"#/$defs/TunnelConfig","default":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null}},"user_policies":{"description":"Static user policy records loaded at startup (`[[user_policies]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/UserPolicyConfig"}},"web_search":{"description":"Web search tool configuration (`[web_search]`).","$ref":"#/$defs/WebSearchConfig","default":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15}},"webhook":{"description":"Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).","$ref":"#/$defs/MemoryWebhookConfig","default":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null}},"xin":{"description":"Xin autonomous task engine configuration (`[xin]`).","$ref":"#/$defs/XinConfig","default":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}}},"$defs":{"A2aConfig":{"type":"object","properties":{"agent_id":{"description":"Stable PRX agent identifier advertised to peers.","type":"string","default":"prx-default"},"allowed_peer_issuers":{"description":"Accepted external peer issuers.","type":"array","default":[],"items":{"type":"string"}},"bind":{"description":"Advertised bind address.","type":"string","default":"127.0.0.1:16832"},"card_jwks_uri":{"description":"Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.","type":["string","null"],"default":null},"card_signing_key_path":{"description":"On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).","type":["string","null"],"default":null},"card_ttl_seconds":{"description":"Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.","type":"integer","format":"uint64","default":3600,"minimum":0},"discovery_advertised":{"description":"Whether to advertise into an external A2A registry.","type":"boolean","default":false},"handoff_nonce_ttl_seconds":{"description":"Replay window for future handoff delegation tokens.","type":"integer","format":"uint64","default":3600,"minimum":0},"messaging_enabled":{"description":"Enable the dedicated pinned mTLS messaging listener.","type":"boolean","default":false},"peers":{"type":"object","additionalProperties":{"$ref":"#/$defs/A2aPeer"},"default":{}},"spiffe_id":{"description":"Local SPIFFE-style identifier placeholder.","type":"string","default":"spiffe://prx-local/agent/prx-default"},"spiffe_strict_validation":{"description":"When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.","type":"boolean","default":false},"spiffe_trust_bundle_pem":{"description":"Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).","type":["string","null"],"default":null},"trusted_trust_domains":{"description":"Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).","type":"array","default":[],"items":{"type":"string"}},"trust_domain":{"description":"SPIFFE trust domain for new instance identities.","type":"string","default":"prx.local"}}},"A2aPeer":{"description":"Explicit pinned identity and local recipient grant.","type":"object","properties":{"spiffe_id":{"type":"string"},"fingerprints":{"type":"array","items":{"type":"string"}},"address":{"type":"string"},"owner":{"type":"string"},"sessions":{"type":"array","default":["*"],"items":{"type":"string"}},"agents":{"type":"array","default":["*"],"items":{"type":"string"}}},"required":["spiffe_id","fingerprints","address","owner"],"additionalProperties":false},"AgentCompactionConfig":{"description":"Agent context compaction configuration (`[agent.compaction]`).","type":"object","properties":{"keep_recent_messages":{"description":"Number of recent non-system messages to keep after compaction.","type":"integer","format":"uint","default":12,"minimum":0},"max_context_tokens":{"description":"Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.","type":"integer","format":"uint","default":128000,"minimum":0},"memory_flush":{"description":"Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.","type":"boolean","default":true},"mode":{"description":"Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).","$ref":"#/$defs/AgentCompactionMode","default":"switch"},"os_paging":{"description":"Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.","$ref":"#/$defs/OsPagingConfig","default":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"}},"reserve_tokens":{"description":"Tokens reserved for the next model response.","type":"integer","format":"uint","default":4096,"minimum":0}}},"AgentCompactionMode":{"description":"Compaction mode for long conversation contexts.","oneOf":[{"description":"Disable proactive compaction.","type":"string","const":"off"},{"description":"Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.","type":"string","const":"switch"},{"description":"Conservative compaction that prefers summary replacement.","type":"string","const":"safeguard"},{"description":"Aggressive truncation mode for tighter contexts.","type":"string","const":"aggressive"}]},"AgentConfig":{"description":"Agent orchestration configuration (`[agent]` section).","type":"object","properties":{"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"compact_context":{"description":"When true: bootstrap_max_chars=6000. Use for 13B or smaller models.","type":"boolean","default":false},"compaction":{"description":"Context compaction controls (`[agent.compaction]`).","$ref":"#/$defs/AgentCompactionConfig","default":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096}},"low_priority_tools":{"description":"Tool names treated as low-priority when `priority_scheduling_enabled = true`.","type":"array","default":["sessions_spawn","delegate"],"items":{"type":"string"}},"priority_scheduling_enabled":{"description":"Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.","type":"boolean","default":false},"read_only_tool_concurrency_window":{"description":"Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.","type":"integer","format":"uint","default":2,"minimum":0},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}}},"AgentLimits":{"description":"Optional admission limits for rf-started turns of a named agent.","type":"object","properties":{"max_concurrent_turns":{"type":["integer","null"],"format":"uint32","minimum":0},"max_cost_per_day_cents":{"type":["integer","null"],"format":"uint64","minimum":0}},"additionalProperties":false},"AuditConfig":{"description":"Audit logging configuration","type":"object","properties":{"log_path":{"description":"Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).","type":"string","default":"audit.log"},"max_size_mb":{"description":"Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).","type":"integer","format":"uint32","default":100,"minimum":0}}},"AuthConfig":{"description":"Authentication and external credential import configuration (`[auth]` section).","type":"object","properties":{"codex_auth_json_auto_import":{"description":"Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.","type":"boolean","default":false},"codex_auth_json_path":{"description":"Source path for Codex CLI auth.json import.","type":"string","default":"~/.codex/auth.json"}}},"AutonomyConfig":{"type":"object","properties":{"acknowledge_unrestricted_profile":{"description":"Operator acknowledgement for an intentionally unrestricted profile.\nThis suppresses doctor noise only; it does not alter policy behavior.","type":"boolean","default":false},"forbidden_paths":{"description":"Explicit path denylist. Default includes system-critical paths.\n\nFails closed: omitting the key keeps the built-in list rather than\nemptying it, so a partial `[autonomy]` section never removes the\ndenylist.","type":"array","default":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"items":{"type":"string"}},"level":{"description":"Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).","$ref":"#/$defs/AutonomyLevel","default":"full"},"max_cost_per_day_cents":{"description":"Maximum cost per day in cents per policy. Default: `500`.","type":"integer","format":"uint32","default":500,"minimum":0},"scopes":{"description":"Scope-based tool access control: per-user/channel/chat-type allow/deny rules.","$ref":"#/$defs/ScopeConfig","default":{"assign_owners":[],"default":"allow","rules":[]}},"workspace_only":{"description":"Restrict file writes and command paths to the workspace directory. Default: `true`.\n\nFails closed: a `[autonomy]` section that omits this key keeps the\nworkspace restriction on, so a partial section can never widen the\nfilesystem reach by accident.","type":"boolean","default":true}}},"AutonomyLevel":{"description":"How much autonomy the agent has","oneOf":[{"description":"Read-only: can observe but not act","type":"string","const":"readonly"},{"description":"Supervised: acts but requires approval for risky operations","type":"string","const":"supervised"},{"description":"Full: autonomous execution within policy bounds","type":"string","const":"full"}]},"BackendSelection":{"description":"Which decision backend runs: `auto` (the factory's order) or one kind.","type":"string"},"BrowserComputerUseConfig":{"description":"Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.","type":"object","properties":{"api_key":{"description":"Optional bearer token (retained only for config secret handling).","type":["string","null"],"default":null}}},"BrowserConfig":{"description":"Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.","type":"object","properties":{"allowed_domains":{"description":"Allowed domains for `web_fetch` (exact or subdomain match).","type":"array","default":[],"items":{"type":"string"}},"computer_use":{"description":"Computer-use sidecar config (retained only for `api_key` secret handling).","$ref":"#/$defs/BrowserComputerUseConfig","default":{"api_key":null}}}},"ChannelsConfig":{"description":"Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.","type":"object","properties":{"cli":{"description":"Enable the CLI interactive channel. Default: `true`.","type":"boolean","default":true},"dingtalk":{"description":"DingTalk channel configuration.","anyOf":[{"$ref":"#/$defs/DingTalkConfig"},{"type":"null"}]},"discord":{"description":"Discord bot channel configuration.","anyOf":[{"$ref":"#/$defs/DiscordConfig"},{"type":"null"}]},"email":{"description":"Email channel configuration.","anyOf":[{"$ref":"#/$defs/EmailConfig"},{"type":"null"}]},"imessage":{"description":"iMessage channel configuration (macOS only).","anyOf":[{"$ref":"#/$defs/IMessageConfig"},{"type":"null"}]},"irc":{"description":"IRC channel configuration.","anyOf":[{"$ref":"#/$defs/IrcConfig"},{"type":"null"}]},"lark":{"description":"Lark/Feishu channel configuration.","anyOf":[{"$ref":"#/$defs/LarkConfig"},{"type":"null"}]},"linq":{"description":"Linq Partner API channel configuration.","anyOf":[{"$ref":"#/$defs/LinqConfig"},{"type":"null"}]},"mattermost":{"description":"Mattermost bot channel configuration.","anyOf":[{"$ref":"#/$defs/MattermostConfig"},{"type":"null"}]},"nextcloud_talk":{"description":"Nextcloud Talk bot channel configuration.","anyOf":[{"$ref":"#/$defs/NextcloudTalkConfig"},{"type":"null"}]},"qq":{"description":"QQ Official Bot channel configuration.","anyOf":[{"$ref":"#/$defs/QQConfig"},{"type":"null"}]},"ramflux":{"description":"Local ramflux agent-host bridge.","anyOf":[{"$ref":"#/$defs/RamfluxConfig"},{"type":"null"}],"default":null},"signal":{"description":"Signal channel configuration.","anyOf":[{"$ref":"#/$defs/SignalConfig"},{"type":"null"}]},"slack":{"description":"Slack bot channel configuration.","anyOf":[{"$ref":"#/$defs/SlackConfig"},{"type":"null"}]},"telegram":{"description":"Telegram bot channel configuration.","anyOf":[{"$ref":"#/$defs/TelegramConfig"},{"type":"null"}]},"wacli":{"description":"wacli JSON-RPC daemon channel configuration.","anyOf":[{"$ref":"#/$defs/WacliConfig"},{"type":"null"}],"default":null},"webhook":{"description":"Webhook channel configuration.","anyOf":[{"$ref":"#/$defs/WebhookConfig"},{"type":"null"}]},"whatsapp":{"description":"WhatsApp channel configuration (Cloud API or Web mode).","anyOf":[{"$ref":"#/$defs/WhatsAppConfig"},{"type":"null"}]}}},"ChatConfig":{"description":"Interactive chat configuration (`[chat]`).","type":"object","properties":{"daemon":{"description":"How this chat process reaches the daemon it borrows channels from.","$ref":"#/$defs/ChatDaemonConfig","default":{"token":"","url":""}},"max_concurrent_visible_turns":{"description":"Maximum concurrent visible provider turns in the TUI Redux driver.","type":"integer","format":"uint","default":2,"minimum":0}}},"ChatDaemonConfig":{"description":"Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.","type":"object","properties":{"token":{"description":"Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.","type":"string","default":""},"url":{"description":"Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.","type":"string","default":""}}},"CircuitBreakerConfig":{"description":"The per-backend circuit breaker.","type":"object","properties":{"cooldown_secs":{"description":"Seconds the breaker stays open (1 to 3600).","type":"integer","format":"uint32","default":60,"minimum":0},"failure_threshold":{"description":"Consecutive failures before the breaker opens (1 to 100).","type":"integer","format":"uint32","default":5,"minimum":0}}},"ClassificationRule":{"description":"A single classification rule mapping message patterns to a model hint.","type":"object","properties":{"hint":{"description":"Must match a `[[model_routes]]` hint value.","type":"string"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"max_length":{"description":"Only match if message length <= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"min_length":{"description":"Only match if message length >= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"patterns":{"description":"Case-sensitive literal matches (for \"```\", \"fn \", etc.).","type":"array","default":[],"items":{"type":"string"}},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0}},"required":["hint"]},"CloudflareTunnelConfig":{"type":"object","properties":{"token":{"description":"Cloudflare Tunnel token (from Zero Trust dashboard)","type":"string"}},"required":["token"]},"ComplianceConfig":{"type":"object","properties":{"eu_ai_act":{"$ref":"#/$defs/EuAiActComplianceConfig","default":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null}},"interaction_notice":{"$ref":"#/$defs/InteractionNoticeConfig","default":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}}},"ComposioConfig":{"description":"Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.","type":"object","properties":{"api_key":{"description":"Composio API key (stored encrypted when secrets.encrypt = true)","type":["string","null"],"default":null},"entity_id":{"description":"Default entity ID for multi-user setups","type":"string","default":"default"}}},"CostConfig":{"description":"Cost tracking and budget enforcement configuration (`[cost]` section).","type":"object","properties":{"allow_override":{"description":"Allow requests to exceed budget with --override flag (default: false)","type":"boolean","default":false},"daily_limit_usd":{"description":"Daily spending limit in USD (default: 10.00)","type":"number","format":"double","default":10.0},"monthly_limit_usd":{"description":"Monthly spending limit in USD (default: 100.00)","type":"number","format":"double","default":100.0},"prices":{"description":"Per-model pricing (USD per 1M tokens)","type":"object","additionalProperties":{"$ref":"#/$defs/ModelPricing"},"default":{}},"warn_at_percent":{"description":"Warn when spending reaches this percentage of limit (default: 80)","type":"integer","format":"uint8","default":80,"maximum":255,"minimum":0}}},"CredentialRefSetting":{"description":"Which credential a decision backend uses. A reference, never a secret.","type":"string"},"CronConfig":{"description":"Cron job configuration (`[cron]` section).","type":"object","properties":{"max_run_history":{"description":"Maximum number of historical cron run records to retain. Default: `50`.","type":"integer","format":"uint32","default":50,"minimum":0}}},"CustomTunnelConfig":{"type":"object","properties":{"health_url":{"description":"Optional URL to check tunnel health","type":["string","null"]},"start_command":{"description":"Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"","type":"string"},"url_pattern":{"description":"Optional regex to extract public URL from command stdout","type":["string","null"]}},"required":["start_command"]},"DecisionBackendConfig":{"description":"The decision backend (`[decision_engine.backend]`).","type":"object","properties":{"circuit_breaker":{"description":"The circuit breaker.","$ref":"#/$defs/CircuitBreakerConfig","default":{"cooldown_secs":60,"failure_threshold":5}},"credential_ref":{"description":"The credential reference: `\"\"`, `\"none\"` or `cred-`.","$ref":"#/$defs/CredentialRefSetting","default":""},"endpoint":{"description":"The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.","type":"string","default":""},"kind":{"description":"`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).","$ref":"#/$defs/BackendSelection","default":"auto"},"max_request_bytes":{"description":"Largest request body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":65536,"minimum":0},"max_response_bytes":{"description":"Largest response body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":262144,"minimum":0},"model":{"description":"The model the endpoint serves; one exact version for a hosted\nservice.","type":"string","default":""},"pinned_snapshot":{"description":"The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.","type":"string"},"remote_enabled":{"description":"Whether decision state may leave this machine. Default `false`.","type":"boolean","default":false},"timeout_ms":{"description":"Transport timeout (10 ms up to the extra latency budget).","type":"integer","format":"uint32","default":250,"minimum":0}}},"DecisionEngineConfig":{"type":"object","properties":{"backend":{"anyOf":[{"$ref":"#/$defs/DecisionBackendConfig"},{"type":"null"}]},"candidates":{"type":"integer","format":"uint32","default":5,"minimum":0},"enabled":{"type":"boolean","default":false},"mode":{"$ref":"#/$defs/DecisionMode","default":"pre"},"observe_queue":{"type":"integer","format":"uint32","default":64,"minimum":0},"prompt_budget_tokens":{"type":"integer","format":"uint32","default":300,"minimum":0},"telemetry_cap":{"type":"integer","format":"uint32","default":1000,"minimum":0},"timeout_ms":{"type":"integer","format":"uint32","default":1500,"minimum":0},"latency_budget_ms":{"description":"The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.","type":"integer","format":"uint64","default":500,"minimum":0},"token_ratio_limit":{"description":"Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).","type":"number","format":"float","default":0.3499999940395355},"max_candidates":{"description":"The most candidates a turn considers (1 to 32).","type":"integer","format":"uint8","default":12,"maximum":255,"minimum":0}}},"DecisionMode":{"type":"string","enum":["pre","post","both"]},"DeclarationOfConformityConfig":{"type":"object","properties":{"applicable_union_law":{"type":"array","default":[],"items":{"type":"string"}},"artifact_path":{"type":["string","null"],"default":null},"artifact_version":{"type":["string","null"],"default":null},"conformity_assessment_procedure":{"type":["string","null"],"default":null},"conformity_statement":{"type":["string","null"],"default":null},"harmonised_standards":{"type":"array","default":[],"items":{"type":"string"}},"issue_date":{"type":["string","null"],"default":null},"issue_place":{"type":["string","null"],"default":null},"notified_body_certificate":{"type":["string","null"],"default":null},"notified_body_identification_number":{"type":["string","null"],"default":null},"notified_body_name":{"type":["string","null"],"default":null},"personal_data_compliance_statement":{"type":["string","null"],"default":null},"processes_personal_data":{"type":"boolean","default":false},"provider_address":{"type":["string","null"],"default":null},"provider_name":{"type":["string","null"],"default":null},"signer_function":{"type":["string","null"],"default":null},"signer_name":{"type":["string","null"],"default":null},"signer_on_behalf_of":{"type":["string","null"],"default":null},"sole_responsibility_statement":{"type":["string","null"],"default":null},"standards_not_applicable_reason":{"type":["string","null"],"default":null},"system_name":{"type":["string","null"],"default":null},"system_reference":{"type":["string","null"],"default":null},"system_type":{"type":["string","null"],"default":null}}},"DelegateAgentConfig":{"description":"Configuration for a delegate sub-agent used by the `delegate` tool.","type":"object","properties":{"agentic":{"description":"Enable agentic sub-agent mode (multi-turn tool-call loop).","type":"boolean","default":false},"allowed_tools":{"description":"Allowlist of tool names available to the sub-agent in agentic mode.","type":"array","default":[],"items":{"type":"string"}},"api_key":{"description":"Optional API key override","type":["string","null"],"default":null},"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"autonomy":{"description":"The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.","anyOf":[{"$ref":"#/$defs/AutonomyLevel"},{"type":"null"}]},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"enabled":{"description":"Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.","type":"boolean","default":true},"identity_dir":{"description":"Optional identity files directory relative to workspace root.","type":["string","null"],"default":null},"limits":{"$ref":"#/$defs/AgentLimits","default":{"max_concurrent_turns":null,"max_cost_per_day_cents":null}},"max_depth":{"description":"Max recursion depth for nested delegation","type":"integer","format":"uint32","default":8,"minimum":0},"memory_scope":{"description":"Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".","type":["string","null"],"default":null},"model":{"description":"Model name","type":"string"},"provider":{"description":"Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")","type":"string"},"spawn_enabled":{"description":"Whether this agent is allowed to be targeted by sessions_spawn (default: true).","type":["boolean","null"],"default":null},"system_prompt":{"description":"Optional system prompt for the sub-agent","type":["string","null"],"default":null},"temperature":{"description":"Temperature override","type":["number","null"],"format":"double","default":null},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}},"required":["provider","model"]},"DingTalkConfig":{"description":"DingTalk configuration for Stream Mode messaging","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"client_id":{"description":"Client ID (AppKey) from DingTalk developer console","type":"string"},"client_secret":{"description":"Client Secret (AppSecret) from DingTalk developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["client_id","client_secret"]},"DiscordConfig":{"description":"Discord bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Discord user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Discord bot token (from Discord Developer Portal).","type":"string"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"guild_id":{"description":"Optional guild (server) ID to restrict the bot to a single guild.","type":["string","null"]},"listen_to_bots":{"description":"When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.","type":"boolean","default":false}},"required":["bot_token"]},"DmPolicy":{"description":"Policy for direct-message handling.","oneOf":[{"description":"Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).","type":"string","const":"pairing"},{"description":"Accept only senders listed in `allowed_from`.","type":"string","const":"allowlist"},{"description":"Accept any direct sender.","type":"string","const":"open"},{"description":"Ignore direct messages.","type":"string","const":"disabled"}]},"DockerRuntimeConfig":{"description":"Docker runtime configuration (`[runtime.docker]` section).","type":"object","properties":{"allowed_workspace_roots":{"description":"Optional workspace root allowlist for Docker mount validation.","type":"array","default":[],"items":{"type":"string"}},"cpu_limit":{"description":"Optional CPU limit (`None` = no explicit limit).","type":["number","null"],"format":"double","default":1.0},"image":{"description":"Runtime image used to execute shell commands.","type":"string","default":"alpine:3.20"},"memory_limit_mb":{"description":"Optional memory limit in MB (`None` = no explicit limit).","type":["integer","null"],"format":"uint64","default":512,"minimum":0},"mount_workspace":{"description":"Mount configured workspace into `/workspace`.","type":"boolean","default":true},"network":{"description":"Docker network mode (`none`, `bridge`, etc.).","type":"string","default":"none"},"read_only_rootfs":{"description":"Mount root filesystem as read-only.","type":"boolean","default":true}}},"EmailConfig":{"description":"Email channel configuration","type":"object","properties":{"allowed_senders":{"description":"Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)","type":"array","default":[],"items":{"type":"string"}},"from_address":{"description":"From address for outgoing emails","type":"string"},"idle_timeout_secs":{"description":"IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes","type":"integer","format":"uint64","default":1740,"minimum":0},"imap_folder":{"description":"IMAP folder to poll (default: INBOX)","type":"string","default":"INBOX"},"imap_host":{"description":"IMAP server hostname","type":"string"},"imap_port":{"description":"IMAP server port (default: 993 for TLS)","type":"integer","format":"uint16","default":993,"maximum":65535,"minimum":0},"password":{"description":"Email password for authentication","type":"string"},"smtp_host":{"description":"SMTP server hostname","type":"string"},"smtp_port":{"description":"SMTP server port (default: 465 for TLS)","type":"integer","format":"uint16","default":465,"maximum":65535,"minimum":0},"smtp_tls":{"description":"Use TLS for SMTP (default: true)","type":"boolean","default":true},"username":{"description":"Email username for authentication","type":"string"}},"required":["imap_host","smtp_host","username","password","from_address"]},"EmbeddingRouteConfig":{"description":"Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"dimensions":{"description":"Optional embedding dimension override for this route","type":["integer","null"],"format":"uint","default":null,"minimum":0},"hint":{"description":"Route hint name (e.g. \"semantic\", \"archive\", \"faq\")","type":"string"},"model":{"description":"Embedding model to use with that provider","type":"string"},"provider":{"description":"Embedding provider (`none`, `openai`, or `custom:`)","type":"string"}},"required":["hint","provider","model"]},"EuAiActClassificationConfig":{"type":"object","properties":{"assessed_at":{"type":["string","null"],"default":null},"owner":{"type":["string","null"],"default":null},"status":{"$ref":"#/$defs/EuAiActRiskClassification","default":"unclassified"}}},"EuAiActComplianceConfig":{"type":"object","properties":{"classification":{"$ref":"#/$defs/EuAiActClassificationConfig","default":{"assessed_at":null,"owner":null,"status":"unclassified"}},"declaration":{"$ref":"#/$defs/DeclarationOfConformityConfig","default":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null}},"incident_store_path":{"type":["string","null"],"default":null}}},"EuAiActRiskClassification":{"type":"string","enum":["unclassified","high_risk","not_high_risk"]},"FitnessConfig":{"description":"Calendar schedule, evidence thresholds, and retention for fitness v2.","type":"object","properties":{"auto_run":{"description":"Run the daily fitness worker in daemon mode.","type":"boolean","default":true},"max_backfill_days":{"description":"Maximum number of closed days recovered after downtime.","type":"integer","format":"uint32","default":7,"minimum":0},"min_coverage":{"description":"Minimum available metric weight required to publish a final score.","type":"number","format":"double","default":0.6},"min_samples":{"description":"Minimum samples required before an evidence-derived subscore is usable.","type":"integer","format":"uint","default":5,"minimum":0},"retention_days":{"description":"Number of daily JSON reports retained on disk.","type":"integer","format":"uint32","default":180,"minimum":0},"run_at":{"description":"Local wall-clock time (`HH:MM`) at which the previous day is scored.","type":"string","default":"00:10"},"timezone":{"description":"IANA timezone used to define closed calendar days.","type":"string","default":"UTC"}}},"GatewayConfig":{"description":"Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.","type":"object","properties":{"allow_public_bind":{"description":"Allow binding to non-localhost without a tunnel (default: false)","type":"boolean","default":false},"api_rate_limit_per_minute":{"description":"Max `/api/*` requests per minute per authenticated token.","type":"integer","format":"uint32","default":60,"minimum":0},"channel_webhook_dedup_ttl_secs":{"description":"How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.","type":"integer","format":"uint64","default":86400,"minimum":0},"host":{"description":"Gateway host (default: 127.0.0.1)","type":"string","default":"127.0.0.1"},"idempotency_max_keys":{"description":"Maximum distinct idempotency keys retained in memory.","type":"integer","format":"uint","default":10000,"minimum":0},"idempotency_ttl_secs":{"description":"TTL for webhook idempotency keys.","type":"integer","format":"uint64","default":300,"minimum":0},"pair_rate_limit_per_minute":{"description":"Max `/pair` requests per minute per client key.","type":"integer","format":"uint32","default":10,"minimum":0},"paired_tokens":{"description":"Paired bearer tokens (managed automatically, not user-edited)","type":"array","default":[],"items":{"type":"string"}},"port":{"description":"Gateway port (default: 16830)","type":"integer","format":"uint16","default":16830,"maximum":65535,"minimum":0},"rate_limit_max_keys":{"description":"Maximum distinct client keys tracked by gateway rate limiter maps.","type":"integer","format":"uint","default":10000,"minimum":0},"require_pairing":{"description":"Require pairing before accepting requests (default: true)","type":"boolean","default":true},"targeted_agents":{"description":"Rollout switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). While false, any otherwise-valid\nnamed target answers 409 `agent_disabled` and never runs as Main.","type":"boolean","default":false},"trust_forwarded_headers":{"description":"Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.","type":"boolean","default":false},"webhook_rate_limit_per_minute":{"description":"Max `/webhook` requests per minute per client key.","type":"integer","format":"uint32","default":60,"minimum":0}}},"GroupPolicy":{"description":"Policy for group-message handling.","oneOf":[{"description":"Accept only groups listed in `group_allow_from`.","type":"string","const":"allowlist"},{"description":"Accept any group.","type":"string","const":"open"},{"description":"Ignore group messages.","type":"string","const":"disabled"}]},"GroupReplyMode":{"description":"How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.","oneOf":[{"description":"Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).","type":"string","const":"off"},{"description":"Reply only when the bot is @-mentioned (legacy `mention_only = true`).","type":"string","const":"mention-only"},{"description":"Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).","type":"string","const":"smart"}]},"HeartbeatConfig":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]` section).","type":"object","properties":{"active_hours":{"description":"Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.","type":"array","default":[8,23],"items":{"type":"integer","format":"uint8","maximum":255,"minimum":0}},"interval_minutes":{"description":"Interval in minutes between heartbeat pings. Default: `30`.","type":"integer","format":"uint32","default":30,"minimum":0},"prompt":{"description":"Prompt used by heartbeat worker when dispatching tasks.","type":"string","default":"Check HEARTBEAT.md and follow instructions."}}},"HttpRequestConfig":{"description":"HTTP request tool configuration (`[http_request]` section).","type":"object","properties":{"max_response_size":{"description":"Maximum response size in bytes (default: 1MB)","type":"integer","format":"uint","default":1000000,"minimum":0},"timeout_secs":{"description":"Request timeout in seconds (default: 30)","type":"integer","format":"uint64","default":30,"minimum":0}}},"IMessageConfig":{"description":"iMessage channel configuration (macOS only).","type":"object","properties":{"allowed_contacts":{"description":"Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.","type":"array","items":{"type":"string"}},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["allowed_contacts"]},"IdentityBindingConfig":{"description":"Startup identity binding entry (`[[identity_bindings]]`).","type":"object","properties":{"channel":{"type":"string"},"channel_account":{"type":"string"},"display_name":{"type":["string","null"],"default":null},"user_id":{"type":"string"}},"required":["user_id","channel","channel_account"]},"IdentityConfig":{"description":"Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.","type":"object","properties":{"aieos_inline":{"description":"Inline AIEOS JSON (alternative to file path)","type":["string","null"],"default":null},"aieos_path":{"description":"Path to AIEOS JSON file (relative to workspace)","type":["string","null"],"default":null},"format":{"description":"Identity format: \"openclaw\" (default) or \"aieos\"","type":"string","default":"openclaw"}}},"InteractionNoticeApplicability":{"type":"string","enum":["required","not_applicable"]},"InteractionNoticeConfig":{"type":"object","properties":{"applicability":{"$ref":"#/$defs/InteractionNoticeApplicability","default":"required"},"exception_owner":{"type":["string","null"],"default":null},"exception_reviewed_at":{"type":["string","null"],"default":null},"text":{"type":"string","default":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers."},"version":{"type":"string","default":"1"}}},"IrcConfig":{"description":"IRC channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed nicknames (case-insensitive) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"channels":{"description":"Channels to join on connect","type":"array","default":[],"items":{"type":"string"}},"mention_only":{"description":"When true, only process channel/group messages that mention the bot.","type":"boolean","default":false},"nickname":{"description":"Bot nickname","type":"string"},"nickserv_password":{"description":"NickServ IDENTIFY password","type":["string","null"]},"port":{"description":"IRC server port (default: 6697 for TLS)","type":"integer","format":"uint16","default":6697,"maximum":65535,"minimum":0},"sasl_password":{"description":"SASL PLAIN password (IRCv3)","type":["string","null"]},"server":{"description":"IRC server hostname","type":"string"},"server_password":{"description":"Server password (for bouncers like ZNC)","type":["string","null"]},"username":{"description":"Username (defaults to nickname if not set)","type":["string","null"]},"verify_tls":{"description":"Verify TLS certificate (default: true)","type":["boolean","null"]}},"required":["server","nickname"]},"LarkConfig":{"description":"Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from Lark/Feishu developer console","type":"string"},"app_secret":{"description":"App Secret from Lark/Feishu developer console","type":"string"},"encrypt_key":{"description":"Encrypt key for webhook message decryption (optional)","type":["string","null"],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"port":{"description":"HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"receive_mode":{"description":"Event receive mode: \"websocket\" (default) or \"webhook\"","$ref":"#/$defs/LarkReceiveMode","default":"websocket"},"use_feishu":{"description":"Whether to use the Feishu (Chinese) endpoint instead of Lark (International)","type":"boolean","default":false},"verification_token":{"description":"Verification token for webhook validation (optional)","type":["string","null"],"default":null}},"required":["app_id","app_secret"]},"LarkReceiveMode":{"description":"How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.","type":"string","enum":["websocket","webhook"]},"LinqConfig":{"type":"object","properties":{"allowed_senders":{"description":"Allowed sender handles (phone numbers) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"api_token":{"description":"Linq Partner API token (Bearer auth)","type":"string"},"from_phone":{"description":"Phone number to send from (E.164 format)","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"signing_secret":{"description":"Webhook signing secret for signature verification","type":["string","null"],"default":null}},"required":["api_token","from_phone"]},"MattermostConfig":{"description":"Mattermost bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Mattermost user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Mattermost bot access token.","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.","type":["boolean","null"],"default":null},"thread_replies":{"description":"When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.","type":["boolean","null"],"default":null},"url":{"description":"Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).","type":"string"}},"required":["url","bot_token"]},"McpConfig":{"type":"object","properties":{"servers":{"description":"Named MCP server definitions","type":"object","additionalProperties":{"$ref":"#/$defs/McpServerConfig"},"default":{}},"workspace_servers":{"description":"Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.","$ref":"#/$defs/WorkspaceMcpServers"}}},"McpServerConfig":{"type":"object","properties":{"allow_tools":{"description":"Optional allow-list of exposed tools (empty = all)","type":"array","default":[],"items":{"type":"string"}},"args":{"description":"Command args for stdio mode","type":"array","default":[],"items":{"type":"string"}},"command":{"description":"Command for stdio mode","type":["string","null"],"default":null},"deny_tools":{"description":"Optional deny-list of exposed tools","type":"array","default":[],"items":{"type":"string"}},"env":{"description":"Environment variables for stdio mode","type":"object","additionalProperties":{"type":"string"},"default":{}},"request_timeout_ms":{"description":"Request timeout in milliseconds","type":"integer","format":"uint64","default":30000,"minimum":0},"startup_timeout_ms":{"description":"Startup timeout in milliseconds","type":"integer","format":"uint64","default":10000,"minimum":0},"tool_name_prefix":{"description":"Prefix used in tool naming and routing","type":"string","default":"mcp"},"transport":{"description":"Transport type: stdio or http","$ref":"#/$defs/McpTransport","default":"stdio"},"url":{"description":"URL for HTTP mode (streamable HTTP endpoint)","type":["string","null"],"default":null},"working_dir":{"description":"Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).","type":["string","null"]}}},"McpServerRuntimeConfig":{"type":"object","properties":{"allowed_origins":{"description":"Allowed browser origins for future streamable HTTP clients.","type":"array","default":["claude.ai","openai.com","localhost"],"items":{"type":"string"}},"bind":{"description":"Advertised bind address. The gateway may still be started with a CLI port override.","type":"string","default":"127.0.0.1:16831"},"exposed_tools":{"description":"Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.","type":"array","default":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"items":{"type":"string"}},"jwt_algorithms":{"description":"Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.","type":"array","default":["RS256"],"items":{"type":"string"}},"jwt_audience":{"description":"Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.","type":["string","null"],"default":null},"jwt_issuer":{"description":"Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.","type":["string","null"],"default":null},"jwt_jwks":{"description":"Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.","type":["string","null"],"default":null},"jwt_jwks_cache_ttl_secs":{"description":"Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.","type":"integer","format":"uint64","default":300,"minimum":0},"jwt_jwks_uri":{"description":"Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.","type":["string","null"],"default":null},"jwt_public_key_pem":{"description":"PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.","type":["string","null"],"default":null},"rate_limit_rps":{"description":"Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.","type":"integer","format":"uint32","default":10,"minimum":0},"require_auth":{"description":"Require an authenticated external identity for mutating calls.","type":"boolean","default":true}}},"McpTransport":{"type":"string","enum":["stdio","http"]},"MediaConfig":{"description":"Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.","type":"object","properties":{"audio_model":{"description":"Audio model name (Ollama model or OpenAI model). Default: \"whisper\".","type":"string","default":"whisper"},"audio_ollama_url":{"description":"Ollama base URL for audio transcription. Default: \"http://localhost:11434\".","type":"string","default":"http://localhost:11434"},"audio_provider":{"description":"Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".","type":"string","default":"none"},"max_audio_size_mb":{"description":"Maximum audio attachment size in MiB. Default: 20.","type":"integer","format":"uint","default":20,"minimum":0},"max_video_size_mb":{"description":"Maximum video attachment size in MiB. Default: 50.","type":"integer","format":"uint","default":50,"minimum":0},"video_max_frames":{"description":"Maximum video frames to extract per video. Default: 4.","type":"integer","format":"uint","default":4,"minimum":0},"video_provider":{"description":"Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".","type":"string","default":"none"}}},"MemoryConfig":{"description":"Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.","type":"object","properties":{"acl_enabled":{"description":"Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.","type":"boolean","default":false},"archive_after_days":{"description":"Archive daily/session files older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"auto_hydrate":{"description":"Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing","type":"boolean","default":true},"auto_save":{"description":"Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.","type":"boolean","default":true},"backend":{"description":"\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).","type":"string","default":"sqlite"},"conversation_retention_days":{"description":"For sqlite backend: prune conversation rows older than this many days","type":"integer","format":"uint32","default":3,"minimum":0},"daily_retention_days":{"description":"For sqlite backend: prune daily rows older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"embedding_cache_size":{"description":"Max embedding cache entries before LRU eviction","type":"integer","format":"uint","default":10000,"minimum":0},"embedding_dimensions":{"description":"Embedding vector dimensions","type":"integer","format":"uint","default":384,"minimum":0},"embedding_model":{"description":"Embedding model name (e.g. \"text-embedding-3-small\")","type":"string","default":"prx-local-hash-v1"},"embedding_provider":{"description":"Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"","type":"string","default":"local"},"events":{"description":"Raw/quasi-raw message event recording controls (`[memory.events]`).","$ref":"#/$defs/MemoryEventsConfig","default":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true}},"keyword_weight":{"description":"Weight for keyword BM25 in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.3},"legacy_conversation_turns_visible":{"description":"Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.","type":"boolean","default":true},"lucid_budget":{"description":"Token budget for lucid (replaces ZEROCLAW_LUCID_BUDGET / OPENPRX_LUCID_BUDGET)","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"lucid_cmd":{"description":"Path to lucid binary (replaces ZEROCLAW_LUCID_CMD / OPENPRX_LUCID_CMD)","type":["string","null"],"default":null},"lucid_failure_cooldown_ms":{"description":"Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)","type":"integer","format":"uint64","default":60000,"minimum":0},"lucid_local_hit_threshold":{"description":"Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)","type":"integer","format":"uint","default":3,"minimum":0},"lucid_recall_timeout_ms":{"description":"Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)","type":"integer","format":"uint64","default":5000,"minimum":0},"lucid_store_timeout_ms":{"description":"Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)","type":"integer","format":"uint64","default":3000,"minimum":0},"min_relevance_score":{"description":"Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4","type":"number","format":"double","default":0.4},"purge_after_days":{"description":"Purge archived files older than this many days","type":"integer","format":"uint32","default":30,"minimum":0},"semantic":{"description":"Semantic memory promotion controls (`[memory.semantic]`).","$ref":"#/$defs/MemorySemanticConfig","default":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30}},"sqlite_open_timeout_secs":{"description":"For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"sqlite_read_pool_size":{"description":"For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"vector_candidate_cap":{"description":"How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.","type":"integer","format":"uint","default":2000,"minimum":0},"vector_weight":{"description":"Weight for vector similarity in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.7}}},"MemoryEventsConfig":{"description":"Raw message event recording configuration (`[memory.events]`).","type":"object","properties":{"record_assistant_messages":{"description":"Record assistant replies.","type":"boolean","default":true},"record_tool_events":{"description":"Record tool/event payloads by default.","type":"boolean","default":false},"record_user_messages":{"description":"Record inbound/user messages.","type":"boolean","default":true}}},"MemorySemanticConfig":{"description":"Semantic memory promotion configuration (`[memory.semantic]`).","type":"object","properties":{"auto_promote_assistant_messages":{"description":"Auto-promote eligible assistant messages. Disabled by default to reduce noise.","type":"boolean","default":false},"auto_promote_user_messages":{"description":"Auto-promote eligible user messages into long-term semantic memories.","type":"boolean","default":true},"min_chars":{"description":"Minimum content length for semantic auto-promotion.","type":"integer","format":"uint","default":30,"minimum":0}}},"MemoryWebhookConfig":{"type":"object","properties":{"bind":{"description":"Socket address for the receiver (e.g. \"0.0.0.0:16899\").","type":"string","default":"0.0.0.0:16899"},"signing_secret":{"description":"Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.","type":["string","null"],"default":null},"token":{"description":"Required bearer token for incoming webhook events.","type":["string","null"],"default":null}}},"ModelOperationSetting":{"description":"The operations a `[[providers.models]]` entry may list.","type":"string","enum":["chat","embedding","decision_endpoint","rerank","image_generation","audio_generation","video_generation"]},"ModelPricing":{"description":"Per-model pricing entry (USD per 1M tokens).","type":"object","properties":{"cache_read":{"description":"Cache read input price per 1M tokens.","type":"number","format":"double","default":0.0},"cache_write":{"description":"Cache write/creation input price per 1M tokens.","type":"number","format":"double","default":0.0},"input":{"description":"Input price per 1M tokens","type":"number","format":"double","default":0.0},"output":{"description":"Output price per 1M tokens","type":"number","format":"double","default":0.0}}},"ModelRouteConfig":{"description":"Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"hint":{"description":"Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")","type":"string"},"level":{"type":["string","null"]},"model":{"description":"Model to use with that provider","type":"string"},"provider":{"description":"Provider to route to (must match a known provider name)","type":"string"},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true,"required":["hint","provider","model"]},"ModelSettings":{"description":"A model level plus explicit parameter overrides in `[model_settings.\"\"]`.","type":"object","properties":{"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"level":{"type":["string","null"]},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true},"MultimodalConfig":{"description":"Multimodal (image) handling configuration (`[multimodal]` section).","type":"object","properties":{"allow_remote_fetch":{"description":"Allow fetching remote image URLs (http/https). Disabled by default.","type":"boolean","default":false},"max_image_size_mb":{"description":"Maximum image payload size in MiB before base64 encoding.","type":"integer","format":"uint","default":5,"minimum":0},"max_images":{"description":"Maximum number of image attachments accepted per request.","type":"integer","format":"uint","default":4,"minimum":0}}},"NextcloudTalkConfig":{"description":"Nextcloud Talk bot configuration (webhook receive + OCS send API).","type":"object","properties":{"allowed_users":{"description":"Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Bot app token used for OCS API bearer auth.","type":"string"},"base_url":{"description":"Nextcloud base URL (e.g. \"https://cloud.example.com\").","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"webhook_secret":{"description":"Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).","type":["string","null"],"default":null}},"required":["base_url","app_token"]},"NgrokTunnelConfig":{"type":"object","properties":{"auth_token":{"description":"ngrok auth token","type":"string"},"domain":{"description":"Optional custom domain","type":["string","null"]}},"required":["auth_token"]},"NodeServerConfig":{"description":"Node daemon runtime config used by `prx-node`.","type":"object","properties":{"allowed_commands":{"description":"Command allowlist matched on first token.\n\nIn restricted mode this list is required unless explicitly set to `[\"*\"]`.","type":"array","default":["echo"],"items":{"type":"string"}},"bearer_token":{"description":"Required bearer token for /rpc.","type":"string","default":""},"blocked_commands":{"description":"Command denylist matched on first token. Always enforced.","type":"array","default":[],"items":{"type":"string"}},"exec_timeout_ms":{"description":"Default command timeout in milliseconds.","type":"integer","format":"uint64","default":15000,"minimum":0},"hmac_secret":{"description":"Optional HMAC signing secret.","type":["string","null"],"default":null},"listen_addr":{"description":"Listen address for node daemon.","type":"string","default":"127.0.0.1:8787"},"max_concurrent_tasks":{"description":"Maximum number of concurrent async command tasks.","type":"integer","format":"uint","default":8,"minimum":0},"max_output_bytes":{"description":"Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.","type":"integer","format":"uint","default":1048576,"minimum":0},"sandbox_root":{"description":"Sandbox root directory for read/write/cwd constraints.","type":"string","default":"."},"task_result_ttl_ms":{"description":"TTL for completed task results in milliseconds.","type":"integer","format":"uint64","default":3600000,"minimum":0},"tls_cert":{"description":"TLS certificate path (PEM).","type":["string","null"],"default":null},"tls_key":{"description":"TLS private key path (PEM).","type":["string","null"],"default":null},"tls_required":{"description":"Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.","type":"boolean","default":true}}},"NodesConfig":{"description":"Remote node proxy configuration for core-side RPC calls and node daemon defaults.","type":"object","properties":{"nodes":{"description":"Configured remote nodes.","type":"array","default":[],"items":{"$ref":"#/$defs/RemoteNodeConfig"}},"request_timeout_ms":{"description":"Default request timeout for node RPC calls.","type":"integer","format":"uint64","default":15000,"minimum":0},"retry_max":{"description":"Default max retries for node RPC calls.","type":"integer","format":"uint8","default":2,"maximum":255,"minimum":0},"server":{"description":"Embedded node server defaults used by `prx-node`.","$ref":"#/$defs/NodeServerConfig","default":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}}},"ObservabilityConfig":{"description":"Observability backend configuration (`[observability]` section).","type":"object","properties":{"backend":{"description":"\"none\" | \"log\" | \"prometheus\" | \"otel\"","type":"string","default":"none"},"otel_endpoint":{"description":"OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".","type":["string","null"],"default":null},"otel_service_name":{"description":"Service name reported to the OTel collector. Defaults to \"prx\".","type":["string","null"],"default":null}}},"OllamaProviderConfig":{"description":"Ollama-specific request options (`[providers.ollama]`).","type":"object","properties":{"num_ctx":{"description":"Explicit context window sent as Ollama `options.num_ctx`.","type":["integer","null"],"format":"uint","default":null,"minimum":0}}},"OsPagingConfig":{"description":"Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.","type":"object","properties":{"eviction_threshold":{"description":"Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.","type":"number","format":"double","default":0.7},"keep_recent_messages":{"description":"Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).","type":"integer","format":"uint","default":12,"minimum":0},"max_recalled_pages":{"description":"Maximum number of evicted pages (document chunks) recalled per turn.","type":"integer","format":"uint","default":10,"minimum":0},"proactive_retrieval":{"description":"Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.","type":"boolean","default":true},"retrieval_injection_role":{"description":"Role under which recalled pages are injected.","$ref":"#/$defs/RetrievalInjectionRole","default":"system"}}},"PluginsConfig":{"description":"WASM plugin runtime configuration.","type":"object","properties":{"enabled":{"description":"Load WASM plugins from `/plugins`. Default: `false`.","type":"boolean","default":false}},"additionalProperties":false},"ProviderModelConfig":{"description":"One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.","type":"object","properties":{"context_window":{"description":"The model's context window in tokens.","type":["integer","null"],"format":"uint32","minimum":0},"model":{"description":"The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.","type":["string","null"]},"native_tools":{"description":"Whether the model accepts native tool calls.","type":["boolean","null"]},"operations":{"description":"The complete list of operations the model executes; every operation not\nlisted is unsupported.","type":["array","null"],"items":{"$ref":"#/$defs/ModelOperationSetting"}},"provider":{"description":"The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.","type":"string"},"streaming":{"description":"Whether the model streams responses.","type":["boolean","null"]},"structured_output":{"description":"Whether the model honours a JSON-schema response format.","type":["boolean","null"]},"tool_call_dialect":{"description":"The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema_dialect":{"description":"The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]},"vision_input":{"description":"Whether the model accepts image input.","type":["boolean","null"]}},"required":["provider"]},"ProviderToolDialectConfig":{"description":"One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.","type":"object","properties":{"model":{"description":"The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.","type":["string","null"]},"provider":{"description":"The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.","type":"string"},"tool_call":{"description":"The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema":{"description":"The tool-schema dialect the endpoint accepts.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]}},"required":["provider"]},"ProvidersConfig":{"description":"Provider-specific runtime configuration (`[providers]`).","type":"object","properties":{"models":{"description":"Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.","type":"array","items":{"$ref":"#/$defs/ProviderModelConfig"}},"ollama":{"description":"Ollama-specific request options (`[providers.ollama]`).","$ref":"#/$defs/OllamaProviderConfig","default":{"num_ctx":null}},"tool_dialects":{"description":"Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).","type":"array","items":{"$ref":"#/$defs/ProviderToolDialectConfig"}}}},"ProxyConfig":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).","type":"object","properties":{"all_proxy":{"description":"Fallback proxy URL for all schemes.","type":["string","null"],"default":null},"http_proxy":{"description":"Proxy URL for HTTP requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"https_proxy":{"description":"Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"no_proxy":{"description":"No-proxy bypass list. Same format as NO_PROXY.","type":"array","default":[],"items":{"type":"string"}},"scope":{"description":"Proxy application scope.","$ref":"#/$defs/ProxyScope","default":"zeroclaw"},"services":{"description":"Service selectors used when scope = \"services\".","type":"array","default":[],"items":{"type":"string"}}}},"ProxyScope":{"description":"Proxy application scope — determines which outbound traffic uses the proxy.","oneOf":[{"description":"Use system environment proxy variables only.","type":"string","const":"environment"},{"description":"Apply proxy to all OpenPRX-managed HTTP traffic (default).","type":"string","const":"zeroclaw"},{"description":"Apply proxy only to explicitly listed service selectors.","type":"string","const":"services"}]},"QQConfig":{"description":"QQ Official Bot configuration (Tencent QQ Bot SDK)","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs. Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from QQ Bot developer console","type":"string"},"app_secret":{"description":"App Secret from QQ Bot developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["app_id","app_secret"]},"QueryClassificationConfig":{"description":"Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.","type":"object","properties":{"rules":{"description":"Classification rules evaluated in priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/ClassificationRule"}}}},"RamfluxAccountConfig":{"description":"Persona for one ramflux AI account. Missing fields fall back to the global agent.","type":"object","properties":{"cross_conversation_retrieval":{"description":"Cross-conversation memory retrieval. Off unless the owner sets it.","type":"boolean","default":false},"model":{"type":["string","null"],"default":null},"provider":{"type":["string","null"],"default":null},"scope_profile":{"type":["string","null"],"default":null},"system_prompt_file":{"description":"Path to a system-prompt file. Relative paths are resolved from the workspace.","type":["string","null"],"default":null}},"additionalProperties":false},"RamfluxAttachmentFetch":{"description":"Per-turn caps for `attachment.fetch`.","type":"object","properties":{"max_bytes":{"type":"integer","format":"uint64","default":5242880,"minimum":0},"max_per_turn":{"type":"integer","format":"uint8","default":4,"maximum":255,"minimum":0}},"additionalProperties":false},"RamfluxAuthorizationMode":{"description":"How prx combines its own setting with `bridge.hello.authorization`.","oneOf":[{"description":"Use the agent-host value. Until hello arrives, the effective mode is supervised.","type":"string","const":"follow_rf"},{"description":"Always supervised, even when the agent-host declares full.","type":"string","const":"supervised"},{"description":"Full only when the agent-host also declares full. Config alone never yields full.","type":"string","const":"full"}]},"RamfluxConfig":{"description":"Local ramflux agent-host bridge (`[channels_config.ramflux]`).","type":"object","properties":{"accounts":{"type":"object","additionalProperties":{"$ref":"#/$defs/RamfluxAccountConfig"},"default":{}},"allowed_block_types":{"type":"array","default":["Text","Markdown","Heading","KeyValue","Metric","List","TableFallback","Form","Input","Select","Progress","LogStream","Warning","Error","Success","Approval","ActionGroup","FilePreview","Fallback"],"items":{"type":"string"}},"attachment_fetch":{"$ref":"#/$defs/RamfluxAttachmentFetch","default":{"max_bytes":5242880,"max_per_turn":4}},"authorization_mode":{"$ref":"#/$defs/RamfluxAuthorizationMode","default":"follow_rf"},"encrypt_at_rest":{"type":"boolean","default":true},"max_in_flight_per_conversation":{"type":"integer","format":"uint8","default":1,"maximum":255,"minimum":0},"on_new_message":{"$ref":"#/$defs/RamfluxOnNewMessage","default":"queue"},"socket_path":{"description":"Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.","type":["string","null"],"default":null},"surface_limits":{"$ref":"#/$defs/RamfluxSurfaceLimits","default":{"max_actions":16,"max_blocks":32,"max_bytes":65536}},"turn_wall_clock_secs":{"description":"Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.","type":"integer","format":"uint64","default":120,"minimum":0}},"additionalProperties":false},"RamfluxOnNewMessage":{"description":"What to do with a new inbound message while a turn for that conversation is running.","type":"string","enum":["queue","interrupt"]},"RamfluxSurfaceLimits":{"description":"Limits for `reply.surface` blocks and actions.","type":"object","properties":{"max_actions":{"type":"integer","format":"uint32","default":16,"minimum":0},"max_blocks":{"type":"integer","format":"uint32","default":32,"minimum":0},"max_bytes":{"type":"integer","format":"uint32","default":65536,"minimum":0}},"additionalProperties":false},"ReliabilityCircuitBreakerConfig":{"description":"Process-local provider circuit policy (`[reliability.circuit_breaker]`).","type":"object","properties":{"enabled":{"description":"Enable protection for factory-built provider chains.","type":"boolean","default":true},"failure_threshold":{"description":"Consecutive transient failures that open a circuit (at least 1).","type":"integer","format":"uint32","default":5,"minimum":0},"max_open_secs":{"description":"Maximum doubled window, between open_secs and 3600 seconds.","type":"integer","format":"uint64","default":300,"minimum":0},"open_secs":{"description":"Initial open window in seconds (at least 1).","type":"integer","format":"uint64","default":30,"minimum":0}}},"ReliabilityConfig":{"description":"Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.","type":"object","properties":{"acknowledge_single_provider_risk":{"description":"Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.","type":"boolean","default":false},"api_keys":{"description":"Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.","type":"array","default":[],"items":{"type":"string"}},"channel_initial_backoff_secs":{"description":"Initial backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":2,"minimum":0},"channel_max_backoff_secs":{"description":"Max backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":60,"minimum":0},"circuit_breaker":{"description":"Per-provider consecutive failure protection.","$ref":"#/$defs/ReliabilityCircuitBreakerConfig","default":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30}},"fallback_providers":{"description":"Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).","type":"array","default":[],"items":{"type":"string"}},"model_fallbacks":{"description":"Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`","type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"default":{}},"provider_backoff_ms":{"description":"Base backoff (ms) for provider retry delay.","type":"integer","format":"uint64","default":500,"minimum":0},"provider_retries":{"description":"Retries per provider before failing over.","type":"integer","format":"uint32","default":2,"minimum":0},"scheduler_poll_secs":{"description":"Scheduler polling cadence in seconds.","type":"integer","format":"uint64","default":15,"minimum":0},"scheduler_retries":{"description":"Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.","type":"integer","format":"uint32","default":2,"minimum":0}}},"RemoteNodeConfig":{"description":"A remote node target for core-side node proxy calls.","type":"object","properties":{"bearer_token":{"description":"Bearer token for node RPC authentication.","type":"string"},"endpoint":{"description":"Base endpoint (e.g. \"http://127.0.0.1:8787\").","type":"string"},"hmac_secret":{"description":"Optional request signing key (HMAC-SHA256).","type":["string","null"],"default":null},"id":{"description":"Stable node ID used by the nodes tool.","type":"string"},"retry_max":{"description":"Optional per-node retry override.","type":["integer","null"],"format":"uint8","default":null,"maximum":255,"minimum":0},"timeout_ms":{"description":"Optional per-node timeout override.","type":["integer","null"],"format":"uint64","default":null,"minimum":0}},"required":["id","endpoint","bearer_token"]},"RetrievalInjectionRole":{"description":"Where recalled context pages are injected back into the request.","oneOf":[{"description":"Inject recalled pages as a leading `system` message (not user-visible).","type":"string","const":"system"},{"description":"Inject recalled pages as a leading `user` message.","type":"string","const":"user"}]},"RouterConfig":{"description":"Heuristic LLM router configuration (`[router]` section).","type":"object","properties":{"alpha":{"description":"Similarity score weight. Phase 1 keeps this at `0.0`.","type":"number","format":"float","default":0.0},"beta":{"description":"Capability score weight.","type":"number","format":"float","default":0.5},"delta":{"description":"Cost penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"epsilon":{"description":"Latency penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"gamma":{"description":"Elo score weight.","type":"number","format":"float","default":0.30000001192092896},"knn_k":{"description":"Number of nearest neighbors considered for voting. Default: `7`.","type":"integer","format":"uint","default":7,"minimum":0},"knn_min_records":{"description":"Minimum history records before KNN affects routing. Default: `10`.","type":"integer","format":"uint","default":10,"minimum":0},"models":{"description":"Candidate model registry.","type":"array","default":[],"items":{"$ref":"#/$defs/RouterModelConfig"}}}},"RouterModelConfig":{"description":"Static router metadata for one model candidate.","type":"object","properties":{"categories":{"description":"Capability categories such as `conversation`, `code`, or `analysis`.","type":"array","default":[],"items":{"type":"string"}},"cost_per_million_tokens":{"description":"USD cost per million tokens.","type":"number","format":"float","default":0.0},"elo_rating":{"description":"Initial Elo rating.","type":"number","format":"float","default":1000.0},"latency_ms":{"description":"Average latency in milliseconds.","type":"integer","format":"uint32","default":2000,"minimum":0},"max_context":{"description":"Maximum context window in tokens.","type":"integer","format":"uint","default":1000000,"minimum":0},"model_id":{"description":"Model identifier without provider prefix.","type":"string"},"provider":{"description":"Provider identifier.","type":"string"},"reserved_output_tokens":{"description":"Output tokens reserved for this model when planning input context.","type":["integer","null"],"format":"uint","minimum":0}},"required":["model_id","provider"]},"RuntimeConfig":{"description":"Runtime adapter configuration (`[runtime]` section).","type":"object","properties":{"codex_reasoning_effort":{"description":"Codex reasoning effort (replaces ZEROCLAW_CODEX_REASONING_EFFORT)","type":["string","null"],"default":null},"codex_stream_idle_timeout_secs":{"description":"Codex stream idle timeout in seconds (replaces ZEROCLAW_CODEX_STREAM_IDLE_TIMEOUT_SECS)","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"docker":{"description":"Docker runtime settings (used when `kind = \"docker\"`).","$ref":"#/$defs/DockerRuntimeConfig","default":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true}},"idle_hang_secs":{"description":"Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"kind":{"description":"Runtime kind (`native` | `docker`).","type":"string","default":"native"},"long_task_warn_secs":{"description":"Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"managed_cgroup_root":{"description":"Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.","type":["string","null"],"default":null},"max_blocking_threads":{"description":"Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"reasoning_enabled":{"description":"Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported","type":["boolean","null"],"default":null},"shell_env_allowlist":{"description":"Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.","type":"array","default":[],"items":{"type":"string"}},"workdir":{"description":"Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.","type":["string","null"],"default":null}}},"SchedulerConfig":{"description":"Scheduler configuration for periodic task execution (`[scheduler]` section).","type":"object","properties":{"claim_lease_secs":{"description":"Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.","type":"integer","format":"uint64","default":90,"minimum":0},"max_tasks":{"description":"Maximum number of persisted scheduled tasks.","type":"integer","format":"uint","default":64,"minimum":0}}},"ScopeConfig":{"description":"Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```","type":"object","properties":{"assign_owners":{"description":"Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.","type":"array","default":[],"items":{"type":"string"}},"default":{"description":"Default action when no rule matches: \"allow\" (default) or \"deny\".","$ref":"#/$defs/ScopeDefault","default":"allow"},"rules":{"description":"Ordered list of scope rules evaluated top-to-bottom.","type":"array","default":[],"items":{"$ref":"#/$defs/ScopeRule"}}}},"ScopeDefault":{"description":"What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.","oneOf":[{"description":"Unmatched tool calls are allowed (the default).","type":"string","const":"allow"},{"description":"Unmatched tool calls are refused.","type":"string","const":"deny"}]},"ScopeRule":{"description":"A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.","type":"object","properties":{"assign_allow":{"description":"Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".","type":"array","default":[],"items":{"type":"string"}},"assign_deny":{"description":"Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.","type":"array","default":[],"items":{"type":"string"}},"channel":{"description":"Match by channel name: \"signal\", \"telegram\", \"discord\", etc.","type":["string","null"]},"chat_type":{"description":"Match by chat type: \"direct\", \"group\", or \"*\" for any type.","type":["string","null"]},"send_allow":{"description":"Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.","type":"array","default":[],"items":{"type":"string"}},"send_deny":{"description":"Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.","type":"array","default":[],"items":{"type":"string"}},"tools_allow":{"description":"Tool whitelist: only these tools are allowed (empty = all tools permitted).","type":"array","default":[],"items":{"type":"string"}},"tools_deny":{"description":"Tool blacklist: these tools are denied regardless of allow list.","type":"array","default":[],"items":{"type":"string"}},"user":{"description":"Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.","type":["string","null"]}}},"SecretsConfig":{"description":"Secrets encryption configuration (`[secrets]` section).","type":"object","properties":{"encrypt":{"description":"Enable encryption for API keys and tokens in config.toml","type":"boolean","default":true}}},"SecurityConfig":{"description":"Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.","type":"object","properties":{"audit":{"description":"Audit logging configuration","$ref":"#/$defs/AuditConfig","default":{"log_path":"audit.log","max_size_mb":100}},"workspace_hooks":{"description":"Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.","$ref":"#/$defs/WorkspaceHooks"}}},"SelfSystemConfig":{"description":"Self-system experimental automation config (`[self_system]`).","type":"object","properties":{"evolution_config_path":{"description":"Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG / ZEROCLAW_EVOLUTION_CONFIG)","type":["string","null"],"default":null},"evolution_debug_raw":{"description":"Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW / ZEROCLAW_EVOLUTION_DEBUG_RAW)","type":"boolean","default":false},"evolution_interval_hours":{"description":"Evolution scheduler interval in hours (daemon mode).","type":"integer","format":"uint32","default":24,"minimum":0},"evolution_judge_timeout_secs":{"description":"Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.","type":"integer","format":"uint64","default":180,"minimum":0},"evolution_model_max_micro_usd":{"description":"Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.","type":"integer","format":"uint64","default":0,"minimum":0},"evolution_model_max_tokens":{"description":"Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.","type":"integer","format":"uint64","default":16384,"minimum":0},"fitness":{"description":"Daily fitness snapshot policy.","$ref":"#/$defs/FitnessConfig","default":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"}},"fitness_interval_hours":{"description":"Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.","type":"integer","format":"uint64","default":24,"minimum":0}}},"SessionsSpawnConfig":{"description":"Sessions spawn configuration (`[sessions_spawn]` section).","type":"object","properties":{"cleanup_on_complete":{"description":"Remove worker workspace directory after process-mode completion.","type":"boolean","default":true},"default_mode":{"description":"Default execution mode for sessions_spawn (`task` or `process`).","type":"string","default":"task"},"process_memory_strategy":{"description":"Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.","type":"string","default":"shared_fabric"},"worker_workspace_root":{"description":"Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.","type":["string","null"],"default":null}}},"SignalConfig":{"type":"object","properties":{"account":{"description":"E.164 phone number of the signal-cli account (e.g. \"+1234567890\").","type":"string"},"allowed_from":{"description":"Allowed sender phone numbers (E.164) or \"*\" for all.","type":"array","default":[],"items":{"type":"string"}},"cli_path":{"description":"Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).","type":["string","null"],"default":null},"daemon_http_port":{"description":"Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"daemon_mode":{"description":"Deprecated: ignored. Accepted for backward compatibility with older config files.","type":["boolean","null"],"default":null},"data_dir":{"description":"signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_id":{"description":"Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group","type":["string","null"],"default":null},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"http_url":{"description":"Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.","type":"string","default":"http://localhost:8080"},"ignore_attachments":{"description":"Skip messages that are attachment-only (no text body).","type":"boolean","default":false},"ignore_stories":{"description":"Skip incoming story messages.","type":"boolean","default":false},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"mode":{"description":"Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.","type":["string","null"],"default":null},"startup_timeout_ms":{"description":"Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.","type":"integer","format":"uint64","default":30000,"minimum":0},"storm_protection":{"description":"Signal ingress storm protection controls.","$ref":"#/$defs/SignalStormProtectionConfig","default":{"abnormal_threshold":10,"abnormal_window_secs":60,"breaker_duration_secs":300,"dedupe_ttl_secs":60,"min_reply_interval_secs":2}}},"required":["account"]},"SignalStormProtectionConfig":{"type":"object","properties":{"abnormal_threshold":{"description":"Non-user event threshold within `abnormal_window_secs` before tripping the breaker.","type":"integer","format":"uint","default":10,"minimum":0},"abnormal_window_secs":{"description":"Sliding window in seconds for non-user event counting.","type":"integer","format":"uint64","default":60,"minimum":0},"breaker_duration_secs":{"description":"Circuit breaker duration in seconds after threshold is reached.","type":"integer","format":"uint64","default":300,"minimum":0},"dedupe_ttl_secs":{"description":"Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.","type":"integer","format":"uint64","default":60,"minimum":0},"min_reply_interval_secs":{"description":"Minimum interval in seconds between replies for the same `(channel + reply_target)`.","type":"integer","format":"uint64","default":2,"minimum":0}}},"SkillRagConfig":{"description":"Dynamic skill retrieval configuration (`[skill_rag]` section).","type":"object","properties":{"top_k":{"description":"How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).","type":"integer","format":"uint","default":32,"minimum":0}}},"SkillSuiteRegistration":{"description":"The frozen suite that governs one skill's proposals.","type":"object","properties":{"skill_id":{"description":"The skill the suite governs.","type":"string"},"suite_digest":{"description":"SHA-256 digest (64 lowercase hex digits) of the frozen suite.","type":"string"}},"additionalProperties":false,"required":["skill_id","suite_digest"]},"SkillsConfig":{"description":"Skills loading configuration (`[skills]` section).","type":"object","properties":{"open_skills_dir":{"description":"Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.","type":["string","null"],"default":null},"openclaw_skills_dir":{"description":"Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.","type":["string","null"],"default":null}}},"SkillsLifecycleConfig":{"description":"`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.","type":"object","properties":{"allow_executable_proposals":{"description":"Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.","type":"boolean","default":false},"enabled":{"description":"Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.","type":"boolean","default":false},"max_concurrent_evaluations":{"description":"Most evaluations running at once.","type":"integer","format":"uint32","default":1,"minimum":0},"max_edit_fraction":{"description":"Edit budget of a proposal as a fraction of the skill body, in (0, 1].","type":"number","format":"double","default":0.2},"max_edit_tokens":{"description":"Edit budget of a proposal, in tokens.","type":"integer","format":"uint64","default":300,"minimum":0},"max_proposals_per_cycle":{"description":"Most proposals one cycle may start.","type":"integer","format":"uint32","default":1,"minimum":0},"min_cases_floor":{"description":"Smallest `min_cases` a governing suite may declare. Below 3 is refused.","type":"integer","format":"uint32","default":3,"minimum":0},"mode":{"description":"`draft_only`, `shadow` or `auto`.","$ref":"#/$defs/SkillsLifecycleModeConfig","default":"draft_only"},"owner_scope":{"description":"The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.","type":["string","null"],"default":null},"require_holdout":{"description":"A governing suite must have a holdout split. `false` is refused.","type":"boolean","default":true},"storage_dir":{"description":"Store location under the workspace. Only the default is supported.","type":"string","default":"self/skill-lifecycle"},"suites":{"description":"The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.","type":"array","default":[],"items":{"$ref":"#/$defs/SkillSuiteRegistration"}}},"additionalProperties":false},"SkillsLifecycleModeConfig":{"description":"What the lifecycle may do. Mirrors `LifecycleMode`.","oneOf":[{"description":"Drafts and reviews only.","type":"string","const":"draft_only"},{"description":"Drafts plus evaluation and gating; never publishes.","type":"string","const":"shadow"},{"description":"Publishes an eligible proposal after every gate.","type":"string","const":"auto"}]},"SlackConfig":{"description":"Slack bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Slack user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Slack app-level token for Socket Mode (xapp-...).","type":["string","null"]},"bot_token":{"description":"Slack bot OAuth token (xoxb-...).","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["bot_token"]},"SmartGroupConfig":{"description":"Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).","type":"object","properties":{"classifier_max_context_messages":{"description":"How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.","type":"integer","format":"uint","default":3,"minimum":0},"classifier_model":{"description":"Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.","type":"string","default":""},"classifier_provider":{"description":"Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.","type":"string","default":""},"classifier_temperature":{"description":"Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).","type":"number","format":"double","default":0.0},"classifier_timeout_secs":{"description":"Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.","type":"integer","format":"uint64","default":5,"minimum":0}}},"StorageConfig":{"description":"Persistent storage configuration (`[storage]` section).","type":"object","properties":{"provider":{"description":"Storage provider settings (e.g. sqlite, postgres).","$ref":"#/$defs/StorageProviderSection","default":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}}},"StorageProviderConfig":{"description":"Storage provider backend configuration (e.g. postgres connection details).","type":"object","properties":{"connect_timeout_secs":{"description":"Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"db_url":{"description":"Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.","type":["string","null"],"default":null},"pool_max_size":{"description":"Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.","type":"integer","format":"uint","default":32,"minimum":0},"provider":{"description":"Storage engine key (e.g. \"postgres\", \"sqlite\").","type":"string","default":""},"schema":{"description":"Database schema for SQL backends.","type":"string","default":"public"},"table":{"description":"Table name for memory entries.","type":"string","default":"memories"}}},"StorageProviderSection":{"description":"Wrapper for the storage provider configuration section.","type":"object","properties":{"config":{"description":"Storage provider backend settings.","$ref":"#/$defs/StorageProviderConfig","default":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"StreamMode":{"description":"Streaming mode for channels that support progressive message updates.","oneOf":[{"description":"No streaming -- send the complete response as a single message (default).","type":"string","const":"off"},{"description":"Update a draft message with every flush interval.","type":"string","const":"partial"}]},"TailscaleTunnelConfig":{"type":"object","properties":{"funnel":{"description":"Use Tailscale Funnel (public internet) vs Serve (tailnet only)","type":"boolean","default":false},"hostname":{"description":"Optional hostname override","type":["string","null"]}}},"TaskRoutingConfig":{"description":"Lightweight pre-LLM task routing.","type":"object","properties":{"default_intent":{"description":"Fallback intent when no rule matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"rules":{"description":"Rules evaluated in descending priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/TaskRoutingRule"}}}},"TaskRoutingIntentConfig":{"description":"Task-routing default and rule intent.","type":"string","enum":["simple","delegate","stream"]},"TaskRoutingRule":{"description":"A single task-routing rule.","type":"object","properties":{"intent":{"description":"Route intent to apply when a keyword matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"model_hint":{"description":"Optional model hint/raw model for non-delegated requests.","type":["string","null"],"default":null},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0},"sub_agent_model":{"description":"Optional raw sub-agent model override for delegated tasks.","type":["string","null"],"default":null}}},"TelegramConfig":{"description":"Telegram bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Telegram user IDs or usernames. Empty = deny all.","type":"array","items":{"type":"string"}},"bot_token":{"description":"Telegram Bot API token (from @BotFather).","type":"string"},"draft_update_interval_ms":{"description":"Minimum interval (ms) between draft message edits to avoid rate limits.","type":"integer","format":"uint64","default":1000,"minimum":0},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"interrupt_on_new_message":{"description":"When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.","type":"boolean","default":false},"stream_mode":{"description":"Streaming mode for progressive response delivery via message edits.","$ref":"#/$defs/StreamMode","default":"off"}},"required":["bot_token","allowed_users"]},"ToolCallDialectSetting":{"description":"The tool-call grammars an operator may declare for an endpoint.","oneOf":[{"description":"Only the native `tool_calls` array is a tool call (the default).","type":"string","const":"native"},{"description":"Additionally read `{json}` from the content,\nfor a tool name the request registered.","type":"string","const":"xml_function_tags"}]},"ToolSchemaDialectSetting":{"description":"The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.","oneOf":[{"description":"The published document, byte for byte (the default).","type":"string","const":"raw"},{"description":"The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.","type":"string","const":"no_root_combinators"}]},"ToolTieringConfig":{"description":"Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.","type":"object","properties":{"always_exclude":{"description":"Tool names excluded from capability publication.","type":"array","default":[],"items":{"type":"string"}},"always_include":{"description":"Tool names preferred for direct publication, subject to admission gates.","type":"array","default":[],"items":{"type":"string"}},"channel_exclude":{"description":"Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefaults to [`DEFAULT_CHANNEL_EXCLUDED_TOOLS`]; set to `[]` to expose the\nfull operator surface on channels again.","type":"array","default":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","git_operations","skills_manage","memory_reindex","document_sync","document_ingest"],"items":{"type":"string"}}}},"TunnelConfig":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.","type":"object","properties":{"cloudflare":{"description":"Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).","anyOf":[{"$ref":"#/$defs/CloudflareTunnelConfig"},{"type":"null"}],"default":null},"custom":{"description":"Custom tunnel command configuration (used when `provider = \"custom\"`).","anyOf":[{"$ref":"#/$defs/CustomTunnelConfig"},{"type":"null"}],"default":null},"ngrok":{"description":"ngrok tunnel configuration (used when `provider = \"ngrok\"`).","anyOf":[{"$ref":"#/$defs/NgrokTunnelConfig"},{"type":"null"}],"default":null},"provider":{"description":"Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.","type":"string","default":"none"},"tailscale":{"description":"Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).","anyOf":[{"$ref":"#/$defs/TailscaleTunnelConfig"},{"type":"null"}],"default":null}}},"UserPolicyConfig":{"description":"Startup user policy entry (`[[user_policies]]`).","type":"object","properties":{"blocked_patterns":{"type":"array","default":[],"items":{"type":"string"}},"projects":{"type":"array","default":[],"items":{"type":"string"}},"role":{"type":"string","default":"guest"},"user_id":{"type":"string"},"visibility_ceiling":{"type":"string","default":"private"}},"required":["user_id"]},"WacliConfig":{"description":"wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```","type":"object","properties":{"allow_unsigned_loopback":{"description":"Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).","type":"boolean","default":false},"allowed_from":{"description":"Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.","type":"array","default":["*"],"items":{"type":"string"}},"bot_jid":{"description":"Bot's own JID, used for reply-to-bot mention detection.","type":["string","null"],"default":null},"bot_lid":{"description":"The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.","type":["string","null"],"default":null},"bot_number":{"description":"Bot's own phone number (digits), used for `@` mention detection.","type":["string","null"],"default":null},"cli_path":{"description":"Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.","type":["string","null"],"default":null},"group_reply_mode":{"description":"Smart group-reply mode. When `None`, derived from `mention_only`.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"host":{"description":"REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].","type":["string","null"],"writeOnly":true},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"outbound_media_workspace_only":{"description":"Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.","type":"boolean","default":false},"port":{"description":"REMOVED: legacy JSON-RPC daemon port. See `host`.","type":["integer","null"],"format":"uint16","maximum":65535,"minimum":0,"writeOnly":true},"self_chat_mode":{"description":"Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.","type":"boolean","default":false},"store_dir":{"description":"wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.","type":["string","null"],"default":null},"webhook_listen":{"description":"Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").","type":"string","default":"127.0.0.1:16868"},"webhook_path":{"description":"HTTP path the webhook server serves (default: \"/wacli\").","type":"string","default":"/wacli"},"webhook_secret":{"description":"HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.","type":["string","null"],"default":null}}},"WebSearchConfig":{"description":"Web search tool configuration (`[web_search]` section).","type":"object","properties":{"brave_api_key":{"description":"Brave Search API key (required if provider is \"brave\")","type":["string","null"],"default":null},"fetch_max_chars":{"description":"Maximum characters returned by `web_fetch` (default 10000)","type":"integer","format":"uint","default":50000,"minimum":0},"max_results":{"description":"Maximum results per search (1-20)","type":"integer","format":"uint","default":15,"minimum":0},"provider":{"description":"Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)","type":"string","default":"duckduckgo"},"timeout_secs":{"description":"Request timeout in seconds","type":"integer","format":"uint64","default":15,"minimum":0}}},"WebhookConfig":{"description":"Webhook channel configuration.","type":"object","properties":{"port":{"description":"Port to listen on for incoming webhooks.","type":"integer","format":"uint16","maximum":65535,"minimum":0},"secret":{"description":"Optional shared secret for webhook signature verification.","type":["string","null"]}},"required":["port"]},"WhatsAppConfig":{"description":"WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.","type":"object","properties":{"access_token":{"description":"Access token from Meta Business Suite (Cloud API mode)","type":["string","null"],"default":null},"allowed_numbers":{"description":"Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"app_secret":{"description":"App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"pair_code":{"description":"Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one","type":["string","null"],"default":null},"pair_phone":{"description":"Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used","type":["string","null"],"default":null},"phone_number_id":{"description":"Phone number ID from Meta Business API (Cloud API mode)","type":["string","null"],"default":null},"read_pool_size":{"description":"Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"session_path":{"description":"Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs","type":["string","null"],"default":null},"verify_token":{"description":"Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode","type":["string","null"],"default":null},"ws_url":{"description":"WebSocket URL override (replaces WHATSAPP_WS_URL)","type":["string","null"],"default":null}}},"WorkspaceHooks":{"description":"Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).","oneOf":[{"description":"They do not run (the default); `prx doctor` and `hooks_status` say so.","type":"string","const":"off"},{"description":"They run, in a cleared environment and a dedicated directory beside\n`config.toml`.","type":"string","const":"on"}]},"WorkspaceMcpServers":{"description":"Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).","oneOf":[{"description":"None: a workspace file may only narrow the servers defined in\n`config.toml`.","type":"string","const":"off"},{"description":"HTTP servers (still refused when they target a private address).","type":"string","const":"http_only"},{"description":"HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.","type":"string","const":"stdio"}]},"XinConfig":{"description":"Configuration for the xin autonomous task engine (`[xin]`).","type":"object","properties":{"adopt_legacy_tasks":{"description":"Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).","type":"boolean","default":false},"interval_minutes":{"description":"Tick interval in minutes (minimum 1). Default: 5.","type":"integer","format":"uint32","default":5,"minimum":0},"stale_timeout_minutes":{"description":"Minutes after which a running task is marked stale. Default: 60.","type":"integer","format":"uint32","default":60,"minimum":0}}},"AgentMessaging":{"description":"Owner-controlled inbound session messaging (enabled unless explicitly off).","type":"object","properties":{"inbound":{"type":"boolean","default":true}}}}} +{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Config","description":"Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).","type":"object","properties":{"a2a":{"description":"Agent-to-Agent compatibility configuration (`[a2a]`).","$ref":"#/$defs/A2aConfig","default":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trusted_trust_domains":[],"trust_domain":"prx.local"}},"agent":{"description":"Agent orchestration settings (`[agent]`).","$ref":"#/$defs/AgentConfig","default":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2,"messaging":{"inbound":true}}},"agents":{"description":"Delegate agent configurations for multi-agent workflows.","type":"object","additionalProperties":{"$ref":"#/$defs/DelegateAgentConfig"},"default":{}},"api_key":{"description":"API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.","type":["string","null"],"default":null},"api_url":{"description":"Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)","type":["string","null"],"default":null},"auth":{"description":"Auth profile and external credential import settings (`[auth]`).","$ref":"#/$defs/AuthConfig","default":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"}},"autonomy":{"description":"Autonomy and security policy configuration (`[autonomy]`).","$ref":"#/$defs/AutonomyConfig","default":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":500,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true}},"browser":{"description":"Browser automation configuration (`[browser]`).","$ref":"#/$defs/BrowserConfig","default":{"allowed_domains":[],"computer_use":{"api_key":null}}},"channels_config":{"description":"Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).","$ref":"#/$defs/ChannelsConfig","default":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null}},"chat":{"description":"Interactive chat UI configuration (`[chat]`).","$ref":"#/$defs/ChatConfig","default":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2}},"compliance":{"description":"Operator-owned compliance controls (`[compliance]`).","$ref":"#/$defs/ComplianceConfig","default":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}},"composio":{"description":"Composio managed OAuth tools integration (`[composio]`).","$ref":"#/$defs/ComposioConfig","default":{"api_key":null,"entity_id":"default"}},"cost":{"description":"Cost tracking and budget enforcement configuration (`[cost]`).","$ref":"#/$defs/CostConfig","default":{"allow_override":false,"daily_limit_usd":10.0,"monthly_limit_usd":100.0,"prices":{},"warn_at_percent":80}},"cron":{"description":"Cron job configuration (`[cron]`).","$ref":"#/$defs/CronConfig","default":{"max_run_history":50}},"decision_engine":{"description":"Optional advisory decision engine, disabled by default.","$ref":"#/$defs/DecisionEngineConfig","default":{"candidates":5,"enabled":false,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"latency_budget_ms":500,"max_candidates":12,"token_ratio_limit":0.3499999940395355}},"default_model":{"description":"Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.","type":["string","null"]},"default_provider":{"description":"Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.","type":["string","null"]},"default_temperature":{"description":"Default model temperature (0.0–2.0). Default: `0.7`.","type":"number","format":"double","default":0.7},"embedding_routes":{"description":"Embedding routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/EmbeddingRouteConfig"}},"gateway":{"description":"Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).","$ref":"#/$defs/GatewayConfig","default":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":false,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60}},"heartbeat":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]`).","$ref":"#/$defs/HeartbeatConfig","default":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."}},"http_request":{"description":"HTTP request tool configuration (`[http_request]`).","$ref":"#/$defs/HttpRequestConfig","default":{"max_response_size":1000000,"timeout_secs":30}},"identity":{"description":"Identity format configuration: OpenClaw or AIEOS (`[identity]`).","$ref":"#/$defs/IdentityConfig","default":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"}},"identity_bindings":{"description":"Static identity bindings loaded at startup (`[[identity_bindings]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/IdentityBindingConfig"}},"mcp":{"description":"Secrets encryption configuration (`[secrets]`).","$ref":"#/$defs/McpConfig","default":{"servers":{}}},"mcp_server":{"description":"MCP server compatibility configuration (`[mcp_server]`).","$ref":"#/$defs/McpServerRuntimeConfig","default":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true}},"media":{"description":"Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.","$ref":"#/$defs/MediaConfig","default":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"}},"memory":{"description":"Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).","$ref":"#/$defs/MemoryConfig","default":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7}},"model_routes":{"description":"Model routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/ModelRouteConfig"}},"model_settings":{"description":"Catalog model levels and explicit parameters, keyed by canonical release ID.","type":"object","additionalProperties":{"$ref":"#/$defs/ModelSettings"},"default":{}},"multimodal":{"description":"Multimodal (image) handling configuration (`[multimodal]`).","$ref":"#/$defs/MultimodalConfig","default":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4}},"nodes":{"description":"Remote node proxy configuration (`[nodes]`).","$ref":"#/$defs/NodesConfig","default":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}},"observability":{"description":"Observability backend configuration (`[observability]`).","$ref":"#/$defs/ObservabilityConfig","default":{"backend":"none","otel_endpoint":null,"otel_service_name":null}},"plugins":{"description":"WASM plugin runtime switch (`[plugins]`), off by default.","$ref":"#/$defs/PluginsConfig","default":{"enabled":false}},"providers":{"description":"Provider-specific runtime options (`[providers.]`).","$ref":"#/$defs/ProvidersConfig","default":{"ollama":{"num_ctx":null}}},"proxy":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).","$ref":"#/$defs/ProxyConfig","default":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]}},"query_classification":{"description":"Automatic query classification — maps user messages to model hints.","$ref":"#/$defs/QueryClassificationConfig","default":{"rules":[]}},"reliability":{"description":"Reliability settings: retries, fallback providers, backoff (`[reliability]`).","$ref":"#/$defs/ReliabilityConfig","default":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2}},"router":{"description":"Heuristic LLM router configuration (`[router]`).","$ref":"#/$defs/RouterConfig","default":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]}},"runtime":{"description":"Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.","$ref":"#/$defs/RuntimeConfig","default":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null}},"scheduler":{"description":"Scheduler configuration for periodic task execution (`[scheduler]`).","$ref":"#/$defs/SchedulerConfig","default":{"claim_lease_secs":90,"max_tasks":64}},"secrets":{"$ref":"#/$defs/SecretsConfig","default":{"encrypt":true}},"security":{"description":"Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).","$ref":"#/$defs/SecurityConfig","default":{"audit":{"log_path":"audit.log","max_size_mb":100}}},"self_system":{"description":"Self-system experimental automation controls (`[self_system]`).","$ref":"#/$defs/SelfSystemConfig","default":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24}},"sessions_spawn":{"description":"Session spawning configuration (`[sessions_spawn]`).","$ref":"#/$defs/SessionsSpawnConfig","default":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null}},"skill_rag":{"description":"Dynamic skill retrieval settings (`[skill_rag]`).","$ref":"#/$defs/SkillRagConfig","default":{"top_k":32}},"skills":{"description":"Skills loading and community repository behavior (`[skills]`).","$ref":"#/$defs/SkillsConfig","default":{"open_skills_dir":null,"openclaw_skills_dir":null}},"skills_lifecycle":{"description":"Skill lifecycle (`[skills_lifecycle]`), off by default.","$ref":"#/$defs/SkillsLifecycleConfig","default":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]}},"smart_group":{"description":"Smart group-reply pre-gate configuration (`[smart_group]`).","$ref":"#/$defs/SmartGroupConfig","default":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5}},"storage":{"description":"Persistent storage provider configuration (`[storage]`).","$ref":"#/$defs/StorageConfig","default":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"task_routing":{"description":"Task routing configuration — classifies work by intent before the main agent loop.","$ref":"#/$defs/TaskRoutingConfig","default":{"default_intent":"simple","rules":[]}},"tool_tiering":{"description":"Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).","$ref":"#/$defs/ToolTieringConfig","default":{"always_exclude":[],"always_include":[],"channel_exclude":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","git_operations","skills_manage","memory_reindex","document_sync","document_ingest"]}},"tunnel":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]`).","$ref":"#/$defs/TunnelConfig","default":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null}},"user_policies":{"description":"Static user policy records loaded at startup (`[[user_policies]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/UserPolicyConfig"}},"web_search":{"description":"Web search tool configuration (`[web_search]`).","$ref":"#/$defs/WebSearchConfig","default":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15}},"webhook":{"description":"Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).","$ref":"#/$defs/MemoryWebhookConfig","default":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null}},"xin":{"description":"Xin autonomous task engine configuration (`[xin]`).","$ref":"#/$defs/XinConfig","default":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}}},"$defs":{"A2aConfig":{"type":"object","properties":{"agent_id":{"description":"Stable PRX agent identifier advertised to peers.","type":"string","default":"prx-default"},"allowed_peer_issuers":{"description":"Accepted external peer issuers.","type":"array","default":[],"items":{"type":"string"}},"bind":{"description":"Advertised bind address.","type":"string","default":"127.0.0.1:16832"},"card_jwks_uri":{"description":"Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.","type":["string","null"],"default":null},"card_signing_key_path":{"description":"On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).","type":["string","null"],"default":null},"card_ttl_seconds":{"description":"Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.","type":"integer","format":"uint64","default":3600,"minimum":0},"discovery_advertised":{"description":"Whether to advertise into an external A2A registry.","type":"boolean","default":false},"handoff_nonce_ttl_seconds":{"description":"Replay window for future handoff delegation tokens.","type":"integer","format":"uint64","default":3600,"minimum":0},"messaging_enabled":{"description":"Enable the dedicated pinned mTLS messaging listener.","type":"boolean","default":false},"peers":{"type":"object","additionalProperties":{"$ref":"#/$defs/A2aPeer"},"default":{}},"spiffe_id":{"description":"Local SPIFFE-style identifier placeholder.","type":"string","default":"spiffe://prx-local/agent/prx-default"},"spiffe_strict_validation":{"description":"When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.","type":"boolean","default":false},"spiffe_trust_bundle_pem":{"description":"Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).","type":["string","null"],"default":null},"trusted_trust_domains":{"description":"Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).","type":"array","default":[],"items":{"type":"string"}},"trust_domain":{"description":"SPIFFE trust domain for new instance identities.","type":"string","default":"prx.local"}}},"A2aPeer":{"description":"Explicit pinned identity and local recipient grant.","type":"object","properties":{"spiffe_id":{"type":"string"},"fingerprints":{"type":"array","items":{"type":"string"}},"address":{"type":"string"},"owner":{"type":"string"},"sessions":{"type":"array","default":["*"],"items":{"type":"string"}},"agents":{"type":"array","default":["*"],"items":{"type":"string"}}},"required":["spiffe_id","fingerprints","address","owner"],"additionalProperties":false},"AgentCompactionConfig":{"description":"Agent context compaction configuration (`[agent.compaction]`).","type":"object","properties":{"keep_recent_messages":{"description":"Number of recent non-system messages to keep after compaction.","type":"integer","format":"uint","default":12,"minimum":0},"max_context_tokens":{"description":"Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.","type":"integer","format":"uint","default":128000,"minimum":0},"memory_flush":{"description":"Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.","type":"boolean","default":true},"mode":{"description":"Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).","$ref":"#/$defs/AgentCompactionMode","default":"switch"},"os_paging":{"description":"Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.","$ref":"#/$defs/OsPagingConfig","default":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"}},"reserve_tokens":{"description":"Tokens reserved for the next model response.","type":"integer","format":"uint","default":4096,"minimum":0}}},"AgentCompactionMode":{"description":"Compaction mode for long conversation contexts.","oneOf":[{"description":"Disable proactive compaction.","type":"string","const":"off"},{"description":"Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.","type":"string","const":"switch"},{"description":"Conservative compaction that prefers summary replacement.","type":"string","const":"safeguard"},{"description":"Aggressive truncation mode for tighter contexts.","type":"string","const":"aggressive"}]},"AgentConfig":{"description":"Agent orchestration configuration (`[agent]` section).","type":"object","properties":{"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"compact_context":{"description":"When true: bootstrap_max_chars=6000. Use for 13B or smaller models.","type":"boolean","default":false},"compaction":{"description":"Context compaction controls (`[agent.compaction]`).","$ref":"#/$defs/AgentCompactionConfig","default":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096}},"low_priority_tools":{"description":"Tool names treated as low-priority when `priority_scheduling_enabled = true`.","type":"array","default":["sessions_spawn","delegate"],"items":{"type":"string"}},"priority_scheduling_enabled":{"description":"Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.","type":"boolean","default":false},"read_only_tool_concurrency_window":{"description":"Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.","type":"integer","format":"uint","default":2,"minimum":0},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}}},"AgentLimits":{"description":"Optional admission limits for rf-started turns of a named agent.","type":"object","properties":{"max_concurrent_turns":{"type":["integer","null"],"format":"uint32","minimum":0},"max_cost_per_day_cents":{"type":["integer","null"],"format":"uint64","minimum":0}},"additionalProperties":false},"AuditConfig":{"description":"Audit logging configuration","type":"object","properties":{"log_path":{"description":"Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).","type":"string","default":"audit.log"},"max_size_mb":{"description":"Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).","type":"integer","format":"uint32","default":100,"minimum":0}}},"AuthConfig":{"description":"Authentication and external credential import configuration (`[auth]` section).","type":"object","properties":{"codex_auth_json_auto_import":{"description":"Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.","type":"boolean","default":false},"codex_auth_json_path":{"description":"Source path for Codex CLI auth.json import.","type":"string","default":"~/.codex/auth.json"}}},"AutonomyConfig":{"type":"object","properties":{"acknowledge_unrestricted_profile":{"description":"Operator acknowledgement for an intentionally unrestricted profile.\nThis suppresses doctor noise only; it does not alter policy behavior.","type":"boolean","default":false},"forbidden_paths":{"description":"Explicit path denylist. Default includes system-critical paths.\n\nFails closed: omitting the key keeps the built-in list rather than\nemptying it, so a partial `[autonomy]` section never removes the\ndenylist.","type":"array","default":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"items":{"type":"string"}},"level":{"description":"Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).","$ref":"#/$defs/AutonomyLevel","default":"full"},"max_cost_per_day_cents":{"description":"Maximum cost per day in cents per policy. Default: `500`.","type":"integer","format":"uint32","default":500,"minimum":0},"scopes":{"description":"Scope-based tool access control: per-user/channel/chat-type allow/deny rules.","$ref":"#/$defs/ScopeConfig","default":{"assign_owners":[],"default":"allow","rules":[]}},"workspace_only":{"description":"Restrict file writes and command paths to the workspace directory. Default: `true`.\n\nFails closed: a `[autonomy]` section that omits this key keeps the\nworkspace restriction on, so a partial section can never widen the\nfilesystem reach by accident.","type":"boolean","default":true}}},"AutonomyLevel":{"description":"How much autonomy the agent has","oneOf":[{"description":"Read-only: can observe but not act","type":"string","const":"readonly"},{"description":"Supervised: acts but requires approval for risky operations","type":"string","const":"supervised"},{"description":"Full: autonomous execution within policy bounds","type":"string","const":"full"}]},"BackendSelection":{"description":"Which decision backend runs: `auto` (the factory's order) or one kind.","type":"string"},"BrowserComputerUseConfig":{"description":"Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.","type":"object","properties":{"api_key":{"description":"Optional bearer token (retained only for config secret handling).","type":["string","null"],"default":null}}},"BrowserConfig":{"description":"Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.","type":"object","properties":{"allowed_domains":{"description":"Allowed domains for `web_fetch` (exact or subdomain match).","type":"array","default":[],"items":{"type":"string"}},"computer_use":{"description":"Computer-use sidecar config (retained only for `api_key` secret handling).","$ref":"#/$defs/BrowserComputerUseConfig","default":{"api_key":null}}}},"ChannelsConfig":{"description":"Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.","type":"object","properties":{"cli":{"description":"Enable the CLI interactive channel. Default: `true`.","type":"boolean","default":true},"dingtalk":{"description":"DingTalk channel configuration.","anyOf":[{"$ref":"#/$defs/DingTalkConfig"},{"type":"null"}]},"discord":{"description":"Discord bot channel configuration.","anyOf":[{"$ref":"#/$defs/DiscordConfig"},{"type":"null"}]},"email":{"description":"Email channel configuration.","anyOf":[{"$ref":"#/$defs/EmailConfig"},{"type":"null"}]},"imessage":{"description":"iMessage channel configuration (macOS only).","anyOf":[{"$ref":"#/$defs/IMessageConfig"},{"type":"null"}]},"irc":{"description":"IRC channel configuration.","anyOf":[{"$ref":"#/$defs/IrcConfig"},{"type":"null"}]},"lark":{"description":"Lark/Feishu channel configuration.","anyOf":[{"$ref":"#/$defs/LarkConfig"},{"type":"null"}]},"linq":{"description":"Linq Partner API channel configuration.","anyOf":[{"$ref":"#/$defs/LinqConfig"},{"type":"null"}]},"mattermost":{"description":"Mattermost bot channel configuration.","anyOf":[{"$ref":"#/$defs/MattermostConfig"},{"type":"null"}]},"nextcloud_talk":{"description":"Nextcloud Talk bot channel configuration.","anyOf":[{"$ref":"#/$defs/NextcloudTalkConfig"},{"type":"null"}]},"qq":{"description":"QQ Official Bot channel configuration.","anyOf":[{"$ref":"#/$defs/QQConfig"},{"type":"null"}]},"ramflux":{"description":"Local ramflux agent-host bridge.","anyOf":[{"$ref":"#/$defs/RamfluxConfig"},{"type":"null"}],"default":null},"signal":{"description":"Signal channel configuration.","anyOf":[{"$ref":"#/$defs/SignalConfig"},{"type":"null"}]},"slack":{"description":"Slack bot channel configuration.","anyOf":[{"$ref":"#/$defs/SlackConfig"},{"type":"null"}]},"telegram":{"description":"Telegram bot channel configuration.","anyOf":[{"$ref":"#/$defs/TelegramConfig"},{"type":"null"}]},"wacli":{"description":"wacli JSON-RPC daemon channel configuration.","anyOf":[{"$ref":"#/$defs/WacliConfig"},{"type":"null"}],"default":null},"webhook":{"description":"Webhook channel configuration.","anyOf":[{"$ref":"#/$defs/WebhookConfig"},{"type":"null"}]},"whatsapp":{"description":"WhatsApp channel configuration (Cloud API or Web mode).","anyOf":[{"$ref":"#/$defs/WhatsAppConfig"},{"type":"null"}]}}},"ChatConfig":{"description":"Interactive chat configuration (`[chat]`).","type":"object","properties":{"daemon":{"description":"How this chat process reaches the daemon it borrows channels from.","$ref":"#/$defs/ChatDaemonConfig","default":{"token":"","url":""}},"max_concurrent_visible_turns":{"description":"Maximum concurrent visible provider turns in the TUI Redux driver.","type":"integer","format":"uint","default":2,"minimum":0}}},"ChatDaemonConfig":{"description":"Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.","type":"object","properties":{"token":{"description":"Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.","type":"string","default":""},"url":{"description":"Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.","type":"string","default":""}}},"CircuitBreakerConfig":{"description":"The per-backend circuit breaker.","type":"object","properties":{"cooldown_secs":{"description":"Seconds the breaker stays open (1 to 3600).","type":"integer","format":"uint32","default":60,"minimum":0},"failure_threshold":{"description":"Consecutive failures before the breaker opens (1 to 100).","type":"integer","format":"uint32","default":5,"minimum":0}}},"ClassificationRule":{"description":"A single classification rule mapping message patterns to a model hint.","type":"object","properties":{"hint":{"description":"Must match a `[[model_routes]]` hint value.","type":"string"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"max_length":{"description":"Only match if message length <= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"min_length":{"description":"Only match if message length >= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"patterns":{"description":"Case-sensitive literal matches (for \"```\", \"fn \", etc.).","type":"array","default":[],"items":{"type":"string"}},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0}},"required":["hint"]},"CloudflareTunnelConfig":{"type":"object","properties":{"token":{"description":"Cloudflare Tunnel token (from Zero Trust dashboard)","type":"string"}},"required":["token"]},"ComplianceConfig":{"type":"object","properties":{"eu_ai_act":{"$ref":"#/$defs/EuAiActComplianceConfig","default":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null}},"interaction_notice":{"$ref":"#/$defs/InteractionNoticeConfig","default":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}}},"ComposioConfig":{"description":"Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.","type":"object","properties":{"api_key":{"description":"Composio API key (stored encrypted when secrets.encrypt = true)","type":["string","null"],"default":null},"entity_id":{"description":"Default entity ID for multi-user setups","type":"string","default":"default"}}},"CostConfig":{"description":"Cost tracking and budget enforcement configuration (`[cost]` section).","type":"object","properties":{"allow_override":{"description":"Allow requests to exceed budget with --override flag (default: false)","type":"boolean","default":false},"daily_limit_usd":{"description":"Daily spending limit in USD (default: 10.00)","type":"number","format":"double","default":10.0},"monthly_limit_usd":{"description":"Monthly spending limit in USD (default: 100.00)","type":"number","format":"double","default":100.0},"prices":{"description":"Per-model pricing (USD per 1M tokens)","type":"object","additionalProperties":{"$ref":"#/$defs/ModelPricing"},"default":{}},"warn_at_percent":{"description":"Warn when spending reaches this percentage of limit (default: 80)","type":"integer","format":"uint8","default":80,"maximum":255,"minimum":0}}},"CredentialRefSetting":{"description":"Which credential a decision backend uses. A reference, never a secret.","type":"string"},"CronConfig":{"description":"Cron job configuration (`[cron]` section).","type":"object","properties":{"max_run_history":{"description":"Maximum number of historical cron run records to retain. Default: `50`.","type":"integer","format":"uint32","default":50,"minimum":0}}},"CustomTunnelConfig":{"type":"object","properties":{"health_url":{"description":"Optional URL to check tunnel health","type":["string","null"]},"start_command":{"description":"Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"","type":"string"},"url_pattern":{"description":"Optional regex to extract public URL from command stdout","type":["string","null"]}},"required":["start_command"]},"DecisionBackendConfig":{"description":"The decision backend (`[decision_engine.backend]`).","type":"object","properties":{"circuit_breaker":{"description":"The circuit breaker.","$ref":"#/$defs/CircuitBreakerConfig","default":{"cooldown_secs":60,"failure_threshold":5}},"credential_ref":{"description":"The credential reference: `\"\"`, `\"none\"` or `cred-`.","$ref":"#/$defs/CredentialRefSetting","default":""},"endpoint":{"description":"The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.","type":"string","default":""},"kind":{"description":"`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).","$ref":"#/$defs/BackendSelection","default":"auto"},"max_request_bytes":{"description":"Largest request body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":65536,"minimum":0},"max_response_bytes":{"description":"Largest response body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":262144,"minimum":0},"model":{"description":"The model the endpoint serves; one exact version for a hosted\nservice.","type":"string","default":""},"pinned_snapshot":{"description":"The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.","type":"string"},"remote_enabled":{"description":"Whether decision state may leave this machine. Default `false`.","type":"boolean","default":false},"timeout_ms":{"description":"Transport timeout (10 ms up to the extra latency budget).","type":"integer","format":"uint32","default":250,"minimum":0}}},"DecisionEngineConfig":{"type":"object","properties":{"backend":{"anyOf":[{"$ref":"#/$defs/DecisionBackendConfig"},{"type":"null"}]},"candidates":{"type":"integer","format":"uint32","default":5,"minimum":0},"enabled":{"type":"boolean","default":false},"mode":{"$ref":"#/$defs/DecisionMode","default":"pre"},"observe_queue":{"type":"integer","format":"uint32","default":64,"minimum":0},"prompt_budget_tokens":{"type":"integer","format":"uint32","default":300,"minimum":0},"telemetry_cap":{"type":"integer","format":"uint32","default":1000,"minimum":0},"timeout_ms":{"type":"integer","format":"uint32","default":1500,"minimum":0},"latency_budget_ms":{"description":"The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.","type":"integer","format":"uint64","default":500,"minimum":0},"token_ratio_limit":{"description":"Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).","type":"number","format":"float","default":0.3499999940395355},"max_candidates":{"description":"The most candidates a turn considers (1 to 32).","type":"integer","format":"uint8","default":12,"maximum":255,"minimum":0}}},"DecisionMode":{"type":"string","enum":["pre","post","both"]},"DeclarationOfConformityConfig":{"type":"object","properties":{"applicable_union_law":{"type":"array","default":[],"items":{"type":"string"}},"artifact_path":{"type":["string","null"],"default":null},"artifact_version":{"type":["string","null"],"default":null},"conformity_assessment_procedure":{"type":["string","null"],"default":null},"conformity_statement":{"type":["string","null"],"default":null},"harmonised_standards":{"type":"array","default":[],"items":{"type":"string"}},"issue_date":{"type":["string","null"],"default":null},"issue_place":{"type":["string","null"],"default":null},"notified_body_certificate":{"type":["string","null"],"default":null},"notified_body_identification_number":{"type":["string","null"],"default":null},"notified_body_name":{"type":["string","null"],"default":null},"personal_data_compliance_statement":{"type":["string","null"],"default":null},"processes_personal_data":{"type":"boolean","default":false},"provider_address":{"type":["string","null"],"default":null},"provider_name":{"type":["string","null"],"default":null},"signer_function":{"type":["string","null"],"default":null},"signer_name":{"type":["string","null"],"default":null},"signer_on_behalf_of":{"type":["string","null"],"default":null},"sole_responsibility_statement":{"type":["string","null"],"default":null},"standards_not_applicable_reason":{"type":["string","null"],"default":null},"system_name":{"type":["string","null"],"default":null},"system_reference":{"type":["string","null"],"default":null},"system_type":{"type":["string","null"],"default":null}}},"DelegateAgentConfig":{"description":"Configuration for a delegate sub-agent used by the `delegate` tool.","type":"object","properties":{"agentic":{"description":"Enable agentic sub-agent mode (multi-turn tool-call loop).","type":"boolean","default":false},"allowed_tools":{"description":"Allowlist of tool names available to the sub-agent in agentic mode.","type":"array","default":[],"items":{"type":"string"}},"api_key":{"description":"Optional API key override","type":["string","null"],"default":null},"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"autonomy":{"description":"The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.","anyOf":[{"$ref":"#/$defs/AutonomyLevel"},{"type":"null"}]},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"enabled":{"description":"Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.","type":"boolean","default":true},"identity_dir":{"description":"Optional identity files directory relative to workspace root.","type":["string","null"],"default":null},"limits":{"$ref":"#/$defs/AgentLimits","default":{"max_concurrent_turns":null,"max_cost_per_day_cents":null}},"max_depth":{"description":"Max recursion depth for nested delegation","type":"integer","format":"uint32","default":8,"minimum":0},"memory_scope":{"description":"Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".","type":["string","null"],"default":null},"model":{"description":"Model name","type":"string"},"provider":{"description":"Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")","type":"string"},"spawn_enabled":{"description":"Whether this agent is allowed to be targeted by sessions_spawn (default: true).","type":["boolean","null"],"default":null},"system_prompt":{"description":"Optional system prompt for the sub-agent","type":["string","null"],"default":null},"temperature":{"description":"Temperature override","type":["number","null"],"format":"double","default":null},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}},"required":["provider","model"]},"DingTalkConfig":{"description":"DingTalk configuration for Stream Mode messaging","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"client_id":{"description":"Client ID (AppKey) from DingTalk developer console","type":"string"},"client_secret":{"description":"Client Secret (AppSecret) from DingTalk developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["client_id","client_secret"]},"DiscordConfig":{"description":"Discord bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Discord user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Discord bot token (from Discord Developer Portal).","type":"string"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"guild_id":{"description":"Optional guild (server) ID to restrict the bot to a single guild.","type":["string","null"]},"listen_to_bots":{"description":"When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.","type":"boolean","default":false}},"required":["bot_token"]},"DmPolicy":{"description":"Policy for direct-message handling.","oneOf":[{"description":"Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).","type":"string","const":"pairing"},{"description":"Accept only senders listed in `allowed_from`.","type":"string","const":"allowlist"},{"description":"Accept any direct sender.","type":"string","const":"open"},{"description":"Ignore direct messages.","type":"string","const":"disabled"}]},"DockerRuntimeConfig":{"description":"Docker runtime configuration (`[runtime.docker]` section).","type":"object","properties":{"allowed_workspace_roots":{"description":"Optional workspace root allowlist for Docker mount validation.","type":"array","default":[],"items":{"type":"string"}},"cpu_limit":{"description":"Optional CPU limit (`None` = no explicit limit).","type":["number","null"],"format":"double","default":1.0},"image":{"description":"Runtime image used to execute shell commands.","type":"string","default":"alpine:3.20"},"memory_limit_mb":{"description":"Optional memory limit in MB (`None` = no explicit limit).","type":["integer","null"],"format":"uint64","default":512,"minimum":0},"mount_workspace":{"description":"Mount configured workspace into `/workspace`.","type":"boolean","default":true},"network":{"description":"Docker network mode (`none`, `bridge`, etc.).","type":"string","default":"none"},"read_only_rootfs":{"description":"Mount root filesystem as read-only.","type":"boolean","default":true}}},"EmailConfig":{"description":"Email channel configuration","type":"object","properties":{"allowed_senders":{"description":"Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)","type":"array","default":[],"items":{"type":"string"}},"from_address":{"description":"From address for outgoing emails","type":"string"},"idle_timeout_secs":{"description":"IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes","type":"integer","format":"uint64","default":1740,"minimum":0},"imap_folder":{"description":"IMAP folder to poll (default: INBOX)","type":"string","default":"INBOX"},"imap_host":{"description":"IMAP server hostname","type":"string"},"imap_port":{"description":"IMAP server port (default: 993 for TLS)","type":"integer","format":"uint16","default":993,"maximum":65535,"minimum":0},"password":{"description":"Email password for authentication","type":"string"},"smtp_host":{"description":"SMTP server hostname","type":"string"},"smtp_port":{"description":"SMTP server port (default: 465 for TLS)","type":"integer","format":"uint16","default":465,"maximum":65535,"minimum":0},"smtp_tls":{"description":"Use TLS for SMTP (default: true)","type":"boolean","default":true},"username":{"description":"Email username for authentication","type":"string"}},"required":["imap_host","smtp_host","username","password","from_address"]},"EmbeddingRouteConfig":{"description":"Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"dimensions":{"description":"Optional embedding dimension override for this route","type":["integer","null"],"format":"uint","default":null,"minimum":0},"hint":{"description":"Route hint name (e.g. \"semantic\", \"archive\", \"faq\")","type":"string"},"model":{"description":"Embedding model to use with that provider","type":"string"},"provider":{"description":"Embedding provider (`none`, `openai`, or `custom:`)","type":"string"}},"required":["hint","provider","model"]},"EuAiActClassificationConfig":{"type":"object","properties":{"assessed_at":{"type":["string","null"],"default":null},"owner":{"type":["string","null"],"default":null},"status":{"$ref":"#/$defs/EuAiActRiskClassification","default":"unclassified"}}},"EuAiActComplianceConfig":{"type":"object","properties":{"classification":{"$ref":"#/$defs/EuAiActClassificationConfig","default":{"assessed_at":null,"owner":null,"status":"unclassified"}},"declaration":{"$ref":"#/$defs/DeclarationOfConformityConfig","default":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null}},"incident_store_path":{"type":["string","null"],"default":null}}},"EuAiActRiskClassification":{"type":"string","enum":["unclassified","high_risk","not_high_risk"]},"FitnessConfig":{"description":"Calendar schedule, evidence thresholds, and retention for fitness v2.","type":"object","properties":{"auto_run":{"description":"Run the daily fitness worker in daemon mode.","type":"boolean","default":true},"max_backfill_days":{"description":"Maximum number of closed days recovered after downtime.","type":"integer","format":"uint32","default":7,"minimum":0},"min_coverage":{"description":"Minimum available metric weight required to publish a final score.","type":"number","format":"double","default":0.6},"min_samples":{"description":"Minimum samples required before an evidence-derived subscore is usable.","type":"integer","format":"uint","default":5,"minimum":0},"retention_days":{"description":"Number of daily JSON reports retained on disk.","type":"integer","format":"uint32","default":180,"minimum":0},"run_at":{"description":"Local wall-clock time (`HH:MM`) at which the previous day is scored.","type":"string","default":"00:10"},"timezone":{"description":"IANA timezone used to define closed calendar days.","type":"string","default":"UTC"}}},"GatewayConfig":{"description":"Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.","type":"object","properties":{"allow_public_bind":{"description":"Allow binding to non-localhost without a tunnel (default: false)","type":"boolean","default":false},"api_rate_limit_per_minute":{"description":"Max `/api/*` requests per minute per authenticated token.","type":"integer","format":"uint32","default":60,"minimum":0},"channel_webhook_dedup_ttl_secs":{"description":"How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.","type":"integer","format":"uint64","default":86400,"minimum":0},"host":{"description":"Gateway host (default: 127.0.0.1)","type":"string","default":"127.0.0.1"},"idempotency_max_keys":{"description":"Maximum distinct idempotency keys retained in memory.","type":"integer","format":"uint","default":10000,"minimum":0},"idempotency_ttl_secs":{"description":"TTL for webhook idempotency keys.","type":"integer","format":"uint64","default":300,"minimum":0},"pair_rate_limit_per_minute":{"description":"Max `/pair` requests per minute per client key.","type":"integer","format":"uint32","default":10,"minimum":0},"paired_tokens":{"description":"Paired bearer tokens (managed automatically, not user-edited)","type":"array","default":[],"items":{"type":"string"}},"port":{"description":"Gateway port (default: 16830)","type":"integer","format":"uint16","default":16830,"maximum":65535,"minimum":0},"rate_limit_max_keys":{"description":"Maximum distinct client keys tracked by gateway rate limiter maps.","type":"integer","format":"uint","default":10000,"minimum":0},"require_pairing":{"description":"Require pairing before accepting requests (default: true)","type":"boolean","default":true},"targeted_agents":{"description":"Rollout switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). While false, any otherwise-valid\nnamed target answers 409 `agent_disabled` and never runs as Main.","type":"boolean","default":false},"trust_forwarded_headers":{"description":"Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.","type":"boolean","default":false},"webhook_rate_limit_per_minute":{"description":"Max `/webhook` requests per minute per client key.","type":"integer","format":"uint32","default":60,"minimum":0}}},"GroupPolicy":{"description":"Policy for group-message handling.","oneOf":[{"description":"Accept only groups listed in `group_allow_from`.","type":"string","const":"allowlist"},{"description":"Accept any group.","type":"string","const":"open"},{"description":"Ignore group messages.","type":"string","const":"disabled"}]},"GroupReplyMode":{"description":"How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.","oneOf":[{"description":"Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).","type":"string","const":"off"},{"description":"Reply only when the bot is @-mentioned (legacy `mention_only = true`).","type":"string","const":"mention-only"},{"description":"Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).","type":"string","const":"smart"}]},"HeartbeatConfig":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]` section).","type":"object","properties":{"active_hours":{"description":"Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.","type":"array","default":[8,23],"items":{"type":"integer","format":"uint8","maximum":255,"minimum":0}},"interval_minutes":{"description":"Interval in minutes between heartbeat pings. Default: `30`.","type":"integer","format":"uint32","default":30,"minimum":0},"prompt":{"description":"Prompt used by heartbeat worker when dispatching tasks.","type":"string","default":"Check HEARTBEAT.md and follow instructions."}}},"HttpRequestConfig":{"description":"HTTP request tool configuration (`[http_request]` section).","type":"object","properties":{"max_response_size":{"description":"Maximum response size in bytes (default: 1MB)","type":"integer","format":"uint","default":1000000,"minimum":0},"timeout_secs":{"description":"Request timeout in seconds (default: 30)","type":"integer","format":"uint64","default":30,"minimum":0}}},"IMessageConfig":{"description":"iMessage channel configuration (macOS only).","type":"object","properties":{"allowed_contacts":{"description":"Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.","type":"array","items":{"type":"string"}},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["allowed_contacts"]},"IdentityBindingConfig":{"description":"Startup identity binding entry (`[[identity_bindings]]`).","type":"object","properties":{"channel":{"type":"string"},"channel_account":{"type":"string"},"display_name":{"type":["string","null"],"default":null},"user_id":{"type":"string"}},"required":["user_id","channel","channel_account"]},"IdentityConfig":{"description":"Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.","type":"object","properties":{"aieos_inline":{"description":"Inline AIEOS JSON (alternative to file path)","type":["string","null"],"default":null},"aieos_path":{"description":"Path to AIEOS JSON file (relative to workspace)","type":["string","null"],"default":null},"format":{"description":"Identity format: \"openclaw\" (default) or \"aieos\"","type":"string","default":"openclaw"}}},"InteractionNoticeApplicability":{"type":"string","enum":["required","not_applicable"]},"InteractionNoticeConfig":{"type":"object","properties":{"applicability":{"$ref":"#/$defs/InteractionNoticeApplicability","default":"required"},"exception_owner":{"type":["string","null"],"default":null},"exception_reviewed_at":{"type":["string","null"],"default":null},"text":{"type":"string","default":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers."},"version":{"type":"string","default":"1"}}},"IrcConfig":{"description":"IRC channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed nicknames (case-insensitive) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"channels":{"description":"Channels to join on connect","type":"array","default":[],"items":{"type":"string"}},"mention_only":{"description":"When true, only process channel/group messages that mention the bot.","type":"boolean","default":false},"nickname":{"description":"Bot nickname","type":"string"},"nickserv_password":{"description":"NickServ IDENTIFY password","type":["string","null"]},"port":{"description":"IRC server port (default: 6697 for TLS)","type":"integer","format":"uint16","default":6697,"maximum":65535,"minimum":0},"sasl_password":{"description":"SASL PLAIN password (IRCv3)","type":["string","null"]},"server":{"description":"IRC server hostname","type":"string"},"server_password":{"description":"Server password (for bouncers like ZNC)","type":["string","null"]},"username":{"description":"Username (defaults to nickname if not set)","type":["string","null"]},"verify_tls":{"description":"Verify TLS certificate (default: true)","type":["boolean","null"]}},"required":["server","nickname"]},"LarkConfig":{"description":"Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from Lark/Feishu developer console","type":"string"},"app_secret":{"description":"App Secret from Lark/Feishu developer console","type":"string"},"encrypt_key":{"description":"Encrypt key for webhook message decryption (optional)","type":["string","null"],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"port":{"description":"HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"receive_mode":{"description":"Event receive mode: \"websocket\" (default) or \"webhook\"","$ref":"#/$defs/LarkReceiveMode","default":"websocket"},"use_feishu":{"description":"Whether to use the Feishu (Chinese) endpoint instead of Lark (International)","type":"boolean","default":false},"verification_token":{"description":"Verification token for webhook validation (optional)","type":["string","null"],"default":null}},"required":["app_id","app_secret"]},"LarkReceiveMode":{"description":"How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.","type":"string","enum":["websocket","webhook"]},"LinqConfig":{"type":"object","properties":{"allowed_senders":{"description":"Allowed sender handles (phone numbers) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"api_token":{"description":"Linq Partner API token (Bearer auth)","type":"string"},"from_phone":{"description":"Phone number to send from (E.164 format)","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"signing_secret":{"description":"Webhook signing secret for signature verification","type":["string","null"],"default":null}},"required":["api_token","from_phone"]},"MattermostConfig":{"description":"Mattermost bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Mattermost user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Mattermost bot access token.","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.","type":["boolean","null"],"default":null},"thread_replies":{"description":"When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.","type":["boolean","null"],"default":null},"url":{"description":"Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).","type":"string"}},"required":["url","bot_token"]},"McpConfig":{"type":"object","properties":{"servers":{"description":"Named MCP server definitions","type":"object","additionalProperties":{"$ref":"#/$defs/McpServerConfig"},"default":{}},"workspace_servers":{"description":"Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.","$ref":"#/$defs/WorkspaceMcpServers"}}},"McpServerConfig":{"type":"object","properties":{"allow_tools":{"description":"Optional allow-list of exposed tools (empty = all)","type":"array","default":[],"items":{"type":"string"}},"args":{"description":"Command args for stdio mode","type":"array","default":[],"items":{"type":"string"}},"command":{"description":"Command for stdio mode","type":["string","null"],"default":null},"deny_tools":{"description":"Optional deny-list of exposed tools","type":"array","default":[],"items":{"type":"string"}},"env":{"description":"Environment variables for stdio mode","type":"object","additionalProperties":{"type":"string"},"default":{}},"request_timeout_ms":{"description":"Request timeout in milliseconds","type":"integer","format":"uint64","default":30000,"minimum":0},"startup_timeout_ms":{"description":"Startup timeout in milliseconds","type":"integer","format":"uint64","default":10000,"minimum":0},"tool_name_prefix":{"description":"Prefix used in tool naming and routing","type":"string","default":"mcp"},"transport":{"description":"Transport type: stdio or http","$ref":"#/$defs/McpTransport","default":"stdio"},"url":{"description":"URL for HTTP mode (streamable HTTP endpoint)","type":["string","null"],"default":null},"working_dir":{"description":"Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).","type":["string","null"]}}},"McpServerRuntimeConfig":{"type":"object","properties":{"allowed_origins":{"description":"Allowed browser origins for future streamable HTTP clients.","type":"array","default":["claude.ai","openai.com","localhost"],"items":{"type":"string"}},"bind":{"description":"Advertised bind address. The gateway may still be started with a CLI port override.","type":"string","default":"127.0.0.1:16831"},"exposed_tools":{"description":"Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.","type":"array","default":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"items":{"type":"string"}},"jwt_algorithms":{"description":"Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.","type":"array","default":["RS256"],"items":{"type":"string"}},"jwt_audience":{"description":"Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.","type":["string","null"],"default":null},"jwt_issuer":{"description":"Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.","type":["string","null"],"default":null},"jwt_jwks":{"description":"Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.","type":["string","null"],"default":null},"jwt_jwks_cache_ttl_secs":{"description":"Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.","type":"integer","format":"uint64","default":300,"minimum":0},"jwt_jwks_uri":{"description":"Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.","type":["string","null"],"default":null},"jwt_public_key_pem":{"description":"PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.","type":["string","null"],"default":null},"rate_limit_rps":{"description":"Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.","type":"integer","format":"uint32","default":10,"minimum":0},"require_auth":{"description":"Require an authenticated external identity for mutating calls.","type":"boolean","default":true}}},"McpTransport":{"type":"string","enum":["stdio","http"]},"MediaConfig":{"description":"Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.","type":"object","properties":{"audio_model":{"description":"Audio model name (Ollama model or OpenAI model). Default: \"whisper\".","type":"string","default":"whisper"},"audio_ollama_url":{"description":"Ollama base URL for audio transcription. Default: \"http://localhost:11434\".","type":"string","default":"http://localhost:11434"},"audio_provider":{"description":"Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".","type":"string","default":"none"},"max_audio_size_mb":{"description":"Maximum audio attachment size in MiB. Default: 20.","type":"integer","format":"uint","default":20,"minimum":0},"max_video_size_mb":{"description":"Maximum video attachment size in MiB. Default: 50.","type":"integer","format":"uint","default":50,"minimum":0},"video_max_frames":{"description":"Maximum video frames to extract per video. Default: 4.","type":"integer","format":"uint","default":4,"minimum":0},"video_provider":{"description":"Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".","type":"string","default":"none"}}},"MemoryConfig":{"description":"Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.","type":"object","properties":{"acl_enabled":{"description":"Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.","type":"boolean","default":false},"archive_after_days":{"description":"Archive daily/session files older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"auto_hydrate":{"description":"Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing","type":"boolean","default":true},"auto_save":{"description":"Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.","type":"boolean","default":true},"backend":{"description":"\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).","type":"string","default":"sqlite"},"conversation_retention_days":{"description":"For sqlite backend: prune conversation rows older than this many days","type":"integer","format":"uint32","default":3,"minimum":0},"daily_retention_days":{"description":"For sqlite backend: prune daily rows older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"embedding_cache_size":{"description":"Max embedding cache entries before LRU eviction","type":"integer","format":"uint","default":10000,"minimum":0},"embedding_dimensions":{"description":"Embedding vector dimensions","type":"integer","format":"uint","default":384,"minimum":0},"embedding_model":{"description":"Embedding model name (e.g. \"text-embedding-3-small\")","type":"string","default":"prx-local-hash-v1"},"embedding_provider":{"description":"Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"","type":"string","default":"local"},"events":{"description":"Raw/quasi-raw message event recording controls (`[memory.events]`).","$ref":"#/$defs/MemoryEventsConfig","default":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true}},"keyword_weight":{"description":"Weight for keyword BM25 in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.3},"legacy_conversation_turns_visible":{"description":"Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.","type":"boolean","default":true},"lucid_budget":{"description":"Token budget for lucid (replaces OPENPRX_LUCID_BUDGET)","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"lucid_cmd":{"description":"Path to lucid binary (replaces OPENPRX_LUCID_CMD)","type":["string","null"],"default":null},"lucid_failure_cooldown_ms":{"description":"Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)","type":"integer","format":"uint64","default":60000,"minimum":0},"lucid_local_hit_threshold":{"description":"Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)","type":"integer","format":"uint","default":3,"minimum":0},"lucid_recall_timeout_ms":{"description":"Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)","type":"integer","format":"uint64","default":5000,"minimum":0},"lucid_store_timeout_ms":{"description":"Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)","type":"integer","format":"uint64","default":3000,"minimum":0},"min_relevance_score":{"description":"Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4","type":"number","format":"double","default":0.4},"purge_after_days":{"description":"Purge archived files older than this many days","type":"integer","format":"uint32","default":30,"minimum":0},"semantic":{"description":"Semantic memory promotion controls (`[memory.semantic]`).","$ref":"#/$defs/MemorySemanticConfig","default":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30}},"sqlite_open_timeout_secs":{"description":"For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"sqlite_read_pool_size":{"description":"For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"vector_candidate_cap":{"description":"How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.","type":"integer","format":"uint","default":2000,"minimum":0},"vector_weight":{"description":"Weight for vector similarity in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.7}}},"MemoryEventsConfig":{"description":"Raw message event recording configuration (`[memory.events]`).","type":"object","properties":{"record_assistant_messages":{"description":"Record assistant replies.","type":"boolean","default":true},"record_tool_events":{"description":"Record tool/event payloads by default.","type":"boolean","default":false},"record_user_messages":{"description":"Record inbound/user messages.","type":"boolean","default":true}}},"MemorySemanticConfig":{"description":"Semantic memory promotion configuration (`[memory.semantic]`).","type":"object","properties":{"auto_promote_assistant_messages":{"description":"Auto-promote eligible assistant messages. Disabled by default to reduce noise.","type":"boolean","default":false},"auto_promote_user_messages":{"description":"Auto-promote eligible user messages into long-term semantic memories.","type":"boolean","default":true},"min_chars":{"description":"Minimum content length for semantic auto-promotion.","type":"integer","format":"uint","default":30,"minimum":0}}},"MemoryWebhookConfig":{"type":"object","properties":{"bind":{"description":"Socket address for the receiver (e.g. \"0.0.0.0:16899\").","type":"string","default":"0.0.0.0:16899"},"signing_secret":{"description":"Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.","type":["string","null"],"default":null},"token":{"description":"Required bearer token for incoming webhook events.","type":["string","null"],"default":null}}},"ModelOperationSetting":{"description":"The operations a `[[providers.models]]` entry may list.","type":"string","enum":["chat","embedding","decision_endpoint","rerank","image_generation","audio_generation","video_generation"]},"ModelPricing":{"description":"Per-model pricing entry (USD per 1M tokens).","type":"object","properties":{"cache_read":{"description":"Cache read input price per 1M tokens.","type":"number","format":"double","default":0.0},"cache_write":{"description":"Cache write/creation input price per 1M tokens.","type":"number","format":"double","default":0.0},"input":{"description":"Input price per 1M tokens","type":"number","format":"double","default":0.0},"output":{"description":"Output price per 1M tokens","type":"number","format":"double","default":0.0}}},"ModelRouteConfig":{"description":"Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"hint":{"description":"Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")","type":"string"},"level":{"type":["string","null"]},"model":{"description":"Model to use with that provider","type":"string"},"provider":{"description":"Provider to route to (must match a known provider name)","type":"string"},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true,"required":["hint","provider","model"]},"ModelSettings":{"description":"A model level plus explicit parameter overrides in `[model_settings.\"\"]`.","type":"object","properties":{"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"level":{"type":["string","null"]},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true},"MultimodalConfig":{"description":"Multimodal (image) handling configuration (`[multimodal]` section).","type":"object","properties":{"allow_remote_fetch":{"description":"Allow fetching remote image URLs (http/https). Disabled by default.","type":"boolean","default":false},"max_image_size_mb":{"description":"Maximum image payload size in MiB before base64 encoding.","type":"integer","format":"uint","default":5,"minimum":0},"max_images":{"description":"Maximum number of image attachments accepted per request.","type":"integer","format":"uint","default":4,"minimum":0}}},"NextcloudTalkConfig":{"description":"Nextcloud Talk bot configuration (webhook receive + OCS send API).","type":"object","properties":{"allowed_users":{"description":"Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Bot app token used for OCS API bearer auth.","type":"string"},"base_url":{"description":"Nextcloud base URL (e.g. \"https://cloud.example.com\").","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"webhook_secret":{"description":"Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).","type":["string","null"],"default":null}},"required":["base_url","app_token"]},"NgrokTunnelConfig":{"type":"object","properties":{"auth_token":{"description":"ngrok auth token","type":"string"},"domain":{"description":"Optional custom domain","type":["string","null"]}},"required":["auth_token"]},"NodeServerConfig":{"description":"Node daemon runtime config used by `prx-node`.","type":"object","properties":{"allowed_commands":{"description":"Command allowlist matched on first token.\n\nIn restricted mode this list is required unless explicitly set to `[\"*\"]`.","type":"array","default":["echo"],"items":{"type":"string"}},"bearer_token":{"description":"Required bearer token for /rpc.","type":"string","default":""},"blocked_commands":{"description":"Command denylist matched on first token. Always enforced.","type":"array","default":[],"items":{"type":"string"}},"exec_timeout_ms":{"description":"Default command timeout in milliseconds.","type":"integer","format":"uint64","default":15000,"minimum":0},"hmac_secret":{"description":"Optional HMAC signing secret.","type":["string","null"],"default":null},"listen_addr":{"description":"Listen address for node daemon.","type":"string","default":"127.0.0.1:8787"},"max_concurrent_tasks":{"description":"Maximum number of concurrent async command tasks.","type":"integer","format":"uint","default":8,"minimum":0},"max_output_bytes":{"description":"Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.","type":"integer","format":"uint","default":1048576,"minimum":0},"sandbox_root":{"description":"Sandbox root directory for read/write/cwd constraints.","type":"string","default":"."},"task_result_ttl_ms":{"description":"TTL for completed task results in milliseconds.","type":"integer","format":"uint64","default":3600000,"minimum":0},"tls_cert":{"description":"TLS certificate path (PEM).","type":["string","null"],"default":null},"tls_key":{"description":"TLS private key path (PEM).","type":["string","null"],"default":null},"tls_required":{"description":"Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.","type":"boolean","default":true}}},"NodesConfig":{"description":"Remote node proxy configuration for core-side RPC calls and node daemon defaults.","type":"object","properties":{"nodes":{"description":"Configured remote nodes.","type":"array","default":[],"items":{"$ref":"#/$defs/RemoteNodeConfig"}},"request_timeout_ms":{"description":"Default request timeout for node RPC calls.","type":"integer","format":"uint64","default":15000,"minimum":0},"retry_max":{"description":"Default max retries for node RPC calls.","type":"integer","format":"uint8","default":2,"maximum":255,"minimum":0},"server":{"description":"Embedded node server defaults used by `prx-node`.","$ref":"#/$defs/NodeServerConfig","default":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}}},"ObservabilityConfig":{"description":"Observability backend configuration (`[observability]` section).","type":"object","properties":{"backend":{"description":"\"none\" | \"log\" | \"prometheus\" | \"otel\"","type":"string","default":"none"},"otel_endpoint":{"description":"OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".","type":["string","null"],"default":null},"otel_service_name":{"description":"Service name reported to the OTel collector. Defaults to \"prx\".","type":["string","null"],"default":null}}},"OllamaProviderConfig":{"description":"Ollama-specific request options (`[providers.ollama]`).","type":"object","properties":{"num_ctx":{"description":"Explicit context window sent as Ollama `options.num_ctx`.","type":["integer","null"],"format":"uint","default":null,"minimum":0}}},"OsPagingConfig":{"description":"Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.","type":"object","properties":{"eviction_threshold":{"description":"Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.","type":"number","format":"double","default":0.7},"keep_recent_messages":{"description":"Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).","type":"integer","format":"uint","default":12,"minimum":0},"max_recalled_pages":{"description":"Maximum number of evicted pages (document chunks) recalled per turn.","type":"integer","format":"uint","default":10,"minimum":0},"proactive_retrieval":{"description":"Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.","type":"boolean","default":true},"retrieval_injection_role":{"description":"Role under which recalled pages are injected.","$ref":"#/$defs/RetrievalInjectionRole","default":"system"}}},"PluginsConfig":{"description":"WASM plugin runtime configuration.","type":"object","properties":{"enabled":{"description":"Load WASM plugins from `/plugins`. Default: `false`.","type":"boolean","default":false}},"additionalProperties":false},"ProviderModelConfig":{"description":"One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.","type":"object","properties":{"context_window":{"description":"The model's context window in tokens.","type":["integer","null"],"format":"uint32","minimum":0},"model":{"description":"The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.","type":["string","null"]},"native_tools":{"description":"Whether the model accepts native tool calls.","type":["boolean","null"]},"operations":{"description":"The complete list of operations the model executes; every operation not\nlisted is unsupported.","type":["array","null"],"items":{"$ref":"#/$defs/ModelOperationSetting"}},"provider":{"description":"The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.","type":"string"},"streaming":{"description":"Whether the model streams responses.","type":["boolean","null"]},"structured_output":{"description":"Whether the model honours a JSON-schema response format.","type":["boolean","null"]},"tool_call_dialect":{"description":"The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema_dialect":{"description":"The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]},"vision_input":{"description":"Whether the model accepts image input.","type":["boolean","null"]}},"required":["provider"]},"ProviderToolDialectConfig":{"description":"One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.","type":"object","properties":{"model":{"description":"The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.","type":["string","null"]},"provider":{"description":"The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.","type":"string"},"tool_call":{"description":"The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema":{"description":"The tool-schema dialect the endpoint accepts.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]}},"required":["provider"]},"ProvidersConfig":{"description":"Provider-specific runtime configuration (`[providers]`).","type":"object","properties":{"models":{"description":"Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.","type":"array","items":{"$ref":"#/$defs/ProviderModelConfig"}},"ollama":{"description":"Ollama-specific request options (`[providers.ollama]`).","$ref":"#/$defs/OllamaProviderConfig","default":{"num_ctx":null}},"tool_dialects":{"description":"Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).","type":"array","items":{"$ref":"#/$defs/ProviderToolDialectConfig"}}}},"ProxyConfig":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).","type":"object","properties":{"all_proxy":{"description":"Fallback proxy URL for all schemes.","type":["string","null"],"default":null},"http_proxy":{"description":"Proxy URL for HTTP requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"https_proxy":{"description":"Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"no_proxy":{"description":"No-proxy bypass list. Same format as NO_PROXY.","type":"array","default":[],"items":{"type":"string"}},"scope":{"description":"Proxy application scope.","$ref":"#/$defs/ProxyScope","default":"prx"},"services":{"description":"Service selectors used when scope = \"services\".","type":"array","default":[],"items":{"type":"string"}}}},"ProxyScope":{"description":"Proxy application scope — determines which outbound traffic uses the proxy.","oneOf":[{"description":"Use system environment proxy variables only.","type":"string","const":"environment"},{"description":"Apply proxy to all OpenPRX-managed HTTP traffic (default).","type":"string","const":"prx"},{"description":"Apply proxy only to explicitly listed service selectors.","type":"string","const":"services"}]},"QQConfig":{"description":"QQ Official Bot configuration (Tencent QQ Bot SDK)","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs. Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from QQ Bot developer console","type":"string"},"app_secret":{"description":"App Secret from QQ Bot developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["app_id","app_secret"]},"QueryClassificationConfig":{"description":"Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.","type":"object","properties":{"rules":{"description":"Classification rules evaluated in priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/ClassificationRule"}}}},"RamfluxAccountConfig":{"description":"Persona for one ramflux AI account. Missing fields fall back to the global agent.","type":"object","properties":{"cross_conversation_retrieval":{"description":"Cross-conversation memory retrieval. Off unless the owner sets it.","type":"boolean","default":false},"model":{"type":["string","null"],"default":null},"provider":{"type":["string","null"],"default":null},"scope_profile":{"type":["string","null"],"default":null},"system_prompt_file":{"description":"Path to a system-prompt file. Relative paths are resolved from the workspace.","type":["string","null"],"default":null}},"additionalProperties":false},"RamfluxAttachmentFetch":{"description":"Per-turn caps for `attachment.fetch`.","type":"object","properties":{"max_bytes":{"type":"integer","format":"uint64","default":5242880,"minimum":0},"max_per_turn":{"type":"integer","format":"uint8","default":4,"maximum":255,"minimum":0}},"additionalProperties":false},"RamfluxAuthorizationMode":{"description":"How prx combines its own setting with `bridge.hello.authorization`.","oneOf":[{"description":"Use the agent-host value. Until hello arrives, the effective mode is supervised.","type":"string","const":"follow_rf"},{"description":"Always supervised, even when the agent-host declares full.","type":"string","const":"supervised"},{"description":"Full only when the agent-host also declares full. Config alone never yields full.","type":"string","const":"full"}]},"RamfluxConfig":{"description":"Local ramflux agent-host bridge (`[channels_config.ramflux]`).","type":"object","properties":{"accounts":{"type":"object","additionalProperties":{"$ref":"#/$defs/RamfluxAccountConfig"},"default":{}},"allowed_block_types":{"type":"array","default":["Text","Markdown","Heading","KeyValue","Metric","List","TableFallback","Form","Input","Select","Progress","LogStream","Warning","Error","Success","Approval","ActionGroup","FilePreview","Fallback"],"items":{"type":"string"}},"attachment_fetch":{"$ref":"#/$defs/RamfluxAttachmentFetch","default":{"max_bytes":5242880,"max_per_turn":4}},"authorization_mode":{"$ref":"#/$defs/RamfluxAuthorizationMode","default":"follow_rf"},"encrypt_at_rest":{"type":"boolean","default":true},"max_in_flight_per_conversation":{"type":"integer","format":"uint8","default":1,"maximum":255,"minimum":0},"on_new_message":{"$ref":"#/$defs/RamfluxOnNewMessage","default":"queue"},"socket_path":{"description":"Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.","type":["string","null"],"default":null},"surface_limits":{"$ref":"#/$defs/RamfluxSurfaceLimits","default":{"max_actions":16,"max_blocks":32,"max_bytes":65536}},"turn_wall_clock_secs":{"description":"Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.","type":"integer","format":"uint64","default":120,"minimum":0}},"additionalProperties":false},"RamfluxOnNewMessage":{"description":"What to do with a new inbound message while a turn for that conversation is running.","type":"string","enum":["queue","interrupt"]},"RamfluxSurfaceLimits":{"description":"Limits for `reply.surface` blocks and actions.","type":"object","properties":{"max_actions":{"type":"integer","format":"uint32","default":16,"minimum":0},"max_blocks":{"type":"integer","format":"uint32","default":32,"minimum":0},"max_bytes":{"type":"integer","format":"uint32","default":65536,"minimum":0}},"additionalProperties":false},"ReliabilityCircuitBreakerConfig":{"description":"Process-local provider circuit policy (`[reliability.circuit_breaker]`).","type":"object","properties":{"enabled":{"description":"Enable protection for factory-built provider chains.","type":"boolean","default":true},"failure_threshold":{"description":"Consecutive transient failures that open a circuit (at least 1).","type":"integer","format":"uint32","default":5,"minimum":0},"max_open_secs":{"description":"Maximum doubled window, between open_secs and 3600 seconds.","type":"integer","format":"uint64","default":300,"minimum":0},"open_secs":{"description":"Initial open window in seconds (at least 1).","type":"integer","format":"uint64","default":30,"minimum":0}}},"ReliabilityConfig":{"description":"Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.","type":"object","properties":{"acknowledge_single_provider_risk":{"description":"Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.","type":"boolean","default":false},"api_keys":{"description":"Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.","type":"array","default":[],"items":{"type":"string"}},"channel_initial_backoff_secs":{"description":"Initial backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":2,"minimum":0},"channel_max_backoff_secs":{"description":"Max backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":60,"minimum":0},"circuit_breaker":{"description":"Per-provider consecutive failure protection.","$ref":"#/$defs/ReliabilityCircuitBreakerConfig","default":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30}},"fallback_providers":{"description":"Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).","type":"array","default":[],"items":{"type":"string"}},"model_fallbacks":{"description":"Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`","type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"default":{}},"provider_backoff_ms":{"description":"Base backoff (ms) for provider retry delay.","type":"integer","format":"uint64","default":500,"minimum":0},"provider_retries":{"description":"Retries per provider before failing over.","type":"integer","format":"uint32","default":2,"minimum":0},"scheduler_poll_secs":{"description":"Scheduler polling cadence in seconds.","type":"integer","format":"uint64","default":15,"minimum":0},"scheduler_retries":{"description":"Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.","type":"integer","format":"uint32","default":2,"minimum":0}}},"RemoteNodeConfig":{"description":"A remote node target for core-side node proxy calls.","type":"object","properties":{"bearer_token":{"description":"Bearer token for node RPC authentication.","type":"string"},"endpoint":{"description":"Base endpoint (e.g. \"http://127.0.0.1:8787\").","type":"string"},"hmac_secret":{"description":"Optional request signing key (HMAC-SHA256).","type":["string","null"],"default":null},"id":{"description":"Stable node ID used by the nodes tool.","type":"string"},"retry_max":{"description":"Optional per-node retry override.","type":["integer","null"],"format":"uint8","default":null,"maximum":255,"minimum":0},"timeout_ms":{"description":"Optional per-node timeout override.","type":["integer","null"],"format":"uint64","default":null,"minimum":0}},"required":["id","endpoint","bearer_token"]},"RetrievalInjectionRole":{"description":"Where recalled context pages are injected back into the request.","oneOf":[{"description":"Inject recalled pages as a leading `system` message (not user-visible).","type":"string","const":"system"},{"description":"Inject recalled pages as a leading `user` message.","type":"string","const":"user"}]},"RouterConfig":{"description":"Heuristic LLM router configuration (`[router]` section).","type":"object","properties":{"alpha":{"description":"Similarity score weight. Phase 1 keeps this at `0.0`.","type":"number","format":"float","default":0.0},"beta":{"description":"Capability score weight.","type":"number","format":"float","default":0.5},"delta":{"description":"Cost penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"epsilon":{"description":"Latency penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"gamma":{"description":"Elo score weight.","type":"number","format":"float","default":0.30000001192092896},"knn_k":{"description":"Number of nearest neighbors considered for voting. Default: `7`.","type":"integer","format":"uint","default":7,"minimum":0},"knn_min_records":{"description":"Minimum history records before KNN affects routing. Default: `10`.","type":"integer","format":"uint","default":10,"minimum":0},"models":{"description":"Candidate model registry.","type":"array","default":[],"items":{"$ref":"#/$defs/RouterModelConfig"}}}},"RouterModelConfig":{"description":"Static router metadata for one model candidate.","type":"object","properties":{"categories":{"description":"Capability categories such as `conversation`, `code`, or `analysis`.","type":"array","default":[],"items":{"type":"string"}},"cost_per_million_tokens":{"description":"USD cost per million tokens.","type":"number","format":"float","default":0.0},"elo_rating":{"description":"Initial Elo rating.","type":"number","format":"float","default":1000.0},"latency_ms":{"description":"Average latency in milliseconds.","type":"integer","format":"uint32","default":2000,"minimum":0},"max_context":{"description":"Maximum context window in tokens.","type":"integer","format":"uint","default":1000000,"minimum":0},"model_id":{"description":"Model identifier without provider prefix.","type":"string"},"provider":{"description":"Provider identifier.","type":"string"},"reserved_output_tokens":{"description":"Output tokens reserved for this model when planning input context.","type":["integer","null"],"format":"uint","minimum":0}},"required":["model_id","provider"]},"RuntimeConfig":{"description":"Runtime adapter configuration (`[runtime]` section).","type":"object","properties":{"codex_reasoning_effort":{"description":"Codex reasoning effort","type":["string","null"],"default":null},"codex_stream_idle_timeout_secs":{"description":"Codex stream idle timeout in seconds","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"docker":{"description":"Docker runtime settings (used when `kind = \"docker\"`).","$ref":"#/$defs/DockerRuntimeConfig","default":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true}},"idle_hang_secs":{"description":"Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"kind":{"description":"Runtime kind (`native` | `docker`).","type":"string","default":"native"},"long_task_warn_secs":{"description":"Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"managed_cgroup_root":{"description":"Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.","type":["string","null"],"default":null},"max_blocking_threads":{"description":"Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"reasoning_enabled":{"description":"Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported","type":["boolean","null"],"default":null},"shell_env_allowlist":{"description":"Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.","type":"array","default":[],"items":{"type":"string"}},"workdir":{"description":"Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.","type":["string","null"],"default":null}}},"SchedulerConfig":{"description":"Scheduler configuration for periodic task execution (`[scheduler]` section).","type":"object","properties":{"claim_lease_secs":{"description":"Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.","type":"integer","format":"uint64","default":90,"minimum":0},"max_tasks":{"description":"Maximum number of persisted scheduled tasks.","type":"integer","format":"uint","default":64,"minimum":0}}},"ScopeConfig":{"description":"Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```","type":"object","properties":{"assign_owners":{"description":"Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.","type":"array","default":[],"items":{"type":"string"}},"default":{"description":"Default action when no rule matches: \"allow\" (default) or \"deny\".","$ref":"#/$defs/ScopeDefault","default":"allow"},"rules":{"description":"Ordered list of scope rules evaluated top-to-bottom.","type":"array","default":[],"items":{"$ref":"#/$defs/ScopeRule"}}}},"ScopeDefault":{"description":"What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.","oneOf":[{"description":"Unmatched tool calls are allowed (the default).","type":"string","const":"allow"},{"description":"Unmatched tool calls are refused.","type":"string","const":"deny"}]},"ScopeRule":{"description":"A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.","type":"object","properties":{"assign_allow":{"description":"Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".","type":"array","default":[],"items":{"type":"string"}},"assign_deny":{"description":"Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.","type":"array","default":[],"items":{"type":"string"}},"channel":{"description":"Match by channel name: \"signal\", \"telegram\", \"discord\", etc.","type":["string","null"]},"chat_type":{"description":"Match by chat type: \"direct\", \"group\", or \"*\" for any type.","type":["string","null"]},"send_allow":{"description":"Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.","type":"array","default":[],"items":{"type":"string"}},"send_deny":{"description":"Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.","type":"array","default":[],"items":{"type":"string"}},"tools_allow":{"description":"Tool whitelist: only these tools are allowed (empty = all tools permitted).","type":"array","default":[],"items":{"type":"string"}},"tools_deny":{"description":"Tool blacklist: these tools are denied regardless of allow list.","type":"array","default":[],"items":{"type":"string"}},"user":{"description":"Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.","type":["string","null"]}}},"SecretsConfig":{"description":"Secrets encryption configuration (`[secrets]` section).","type":"object","properties":{"encrypt":{"description":"Enable encryption for API keys and tokens in config.toml","type":"boolean","default":true}}},"SecurityConfig":{"description":"Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.","type":"object","properties":{"audit":{"description":"Audit logging configuration","$ref":"#/$defs/AuditConfig","default":{"log_path":"audit.log","max_size_mb":100}},"workspace_hooks":{"description":"Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.","$ref":"#/$defs/WorkspaceHooks"}}},"SelfSystemConfig":{"description":"Self-system experimental automation config (`[self_system]`).","type":"object","properties":{"evolution_config_path":{"description":"Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG)","type":["string","null"],"default":null},"evolution_debug_raw":{"description":"Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW)","type":"boolean","default":false},"evolution_interval_hours":{"description":"Evolution scheduler interval in hours (daemon mode).","type":"integer","format":"uint32","default":24,"minimum":0},"evolution_judge_timeout_secs":{"description":"Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.","type":"integer","format":"uint64","default":180,"minimum":0},"evolution_model_max_micro_usd":{"description":"Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.","type":"integer","format":"uint64","default":0,"minimum":0},"evolution_model_max_tokens":{"description":"Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.","type":"integer","format":"uint64","default":16384,"minimum":0},"fitness":{"description":"Daily fitness snapshot policy.","$ref":"#/$defs/FitnessConfig","default":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"}},"fitness_interval_hours":{"description":"Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.","type":"integer","format":"uint64","default":24,"minimum":0}}},"SessionsSpawnConfig":{"description":"Sessions spawn configuration (`[sessions_spawn]` section).","type":"object","properties":{"cleanup_on_complete":{"description":"Remove worker workspace directory after process-mode completion.","type":"boolean","default":true},"default_mode":{"description":"Default execution mode for sessions_spawn (`task` or `process`).","type":"string","default":"task"},"process_memory_strategy":{"description":"Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.","type":"string","default":"shared_fabric"},"worker_workspace_root":{"description":"Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.","type":["string","null"],"default":null}}},"SignalConfig":{"type":"object","properties":{"account":{"description":"E.164 phone number of the signal-cli account (e.g. \"+1234567890\").","type":"string"},"allowed_from":{"description":"Allowed sender phone numbers (E.164) or \"*\" for all.","type":"array","default":[],"items":{"type":"string"}},"cli_path":{"description":"Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).","type":["string","null"],"default":null},"daemon_http_port":{"description":"Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"daemon_mode":{"description":"Deprecated: ignored. Accepted for backward compatibility with older config files.","type":["boolean","null"],"default":null},"data_dir":{"description":"signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_id":{"description":"Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group","type":["string","null"],"default":null},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"http_url":{"description":"Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.","type":"string","default":"http://localhost:8080"},"ignore_attachments":{"description":"Skip messages that are attachment-only (no text body).","type":"boolean","default":false},"ignore_stories":{"description":"Skip incoming story messages.","type":"boolean","default":false},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"mode":{"description":"Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.","type":["string","null"],"default":null},"startup_timeout_ms":{"description":"Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.","type":"integer","format":"uint64","default":30000,"minimum":0},"storm_protection":{"description":"Signal ingress storm protection controls.","$ref":"#/$defs/SignalStormProtectionConfig","default":{"abnormal_threshold":10,"abnormal_window_secs":60,"breaker_duration_secs":300,"dedupe_ttl_secs":60,"min_reply_interval_secs":2}}},"required":["account"]},"SignalStormProtectionConfig":{"type":"object","properties":{"abnormal_threshold":{"description":"Non-user event threshold within `abnormal_window_secs` before tripping the breaker.","type":"integer","format":"uint","default":10,"minimum":0},"abnormal_window_secs":{"description":"Sliding window in seconds for non-user event counting.","type":"integer","format":"uint64","default":60,"minimum":0},"breaker_duration_secs":{"description":"Circuit breaker duration in seconds after threshold is reached.","type":"integer","format":"uint64","default":300,"minimum":0},"dedupe_ttl_secs":{"description":"Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.","type":"integer","format":"uint64","default":60,"minimum":0},"min_reply_interval_secs":{"description":"Minimum interval in seconds between replies for the same `(channel + reply_target)`.","type":"integer","format":"uint64","default":2,"minimum":0}}},"SkillRagConfig":{"description":"Dynamic skill retrieval configuration (`[skill_rag]` section).","type":"object","properties":{"top_k":{"description":"How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).","type":"integer","format":"uint","default":32,"minimum":0}}},"SkillSuiteRegistration":{"description":"The frozen suite that governs one skill's proposals.","type":"object","properties":{"skill_id":{"description":"The skill the suite governs.","type":"string"},"suite_digest":{"description":"SHA-256 digest (64 lowercase hex digits) of the frozen suite.","type":"string"}},"additionalProperties":false,"required":["skill_id","suite_digest"]},"SkillsConfig":{"description":"Skills loading configuration (`[skills]` section).","type":"object","properties":{"open_skills_dir":{"description":"Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.","type":["string","null"],"default":null},"openclaw_skills_dir":{"description":"Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.","type":["string","null"],"default":null}}},"SkillsLifecycleConfig":{"description":"`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.","type":"object","properties":{"allow_executable_proposals":{"description":"Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.","type":"boolean","default":false},"enabled":{"description":"Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.","type":"boolean","default":false},"max_concurrent_evaluations":{"description":"Most evaluations running at once.","type":"integer","format":"uint32","default":1,"minimum":0},"max_edit_fraction":{"description":"Edit budget of a proposal as a fraction of the skill body, in (0, 1].","type":"number","format":"double","default":0.2},"max_edit_tokens":{"description":"Edit budget of a proposal, in tokens.","type":"integer","format":"uint64","default":300,"minimum":0},"max_proposals_per_cycle":{"description":"Most proposals one cycle may start.","type":"integer","format":"uint32","default":1,"minimum":0},"min_cases_floor":{"description":"Smallest `min_cases` a governing suite may declare. Below 3 is refused.","type":"integer","format":"uint32","default":3,"minimum":0},"mode":{"description":"`draft_only`, `shadow` or `auto`.","$ref":"#/$defs/SkillsLifecycleModeConfig","default":"draft_only"},"owner_scope":{"description":"The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.","type":["string","null"],"default":null},"require_holdout":{"description":"A governing suite must have a holdout split. `false` is refused.","type":"boolean","default":true},"storage_dir":{"description":"Store location under the workspace. Only the default is supported.","type":"string","default":"self/skill-lifecycle"},"suites":{"description":"The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.","type":"array","default":[],"items":{"$ref":"#/$defs/SkillSuiteRegistration"}}},"additionalProperties":false},"SkillsLifecycleModeConfig":{"description":"What the lifecycle may do. Mirrors `LifecycleMode`.","oneOf":[{"description":"Drafts and reviews only.","type":"string","const":"draft_only"},{"description":"Drafts plus evaluation and gating; never publishes.","type":"string","const":"shadow"},{"description":"Publishes an eligible proposal after every gate.","type":"string","const":"auto"}]},"SlackConfig":{"description":"Slack bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Slack user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Slack app-level token for Socket Mode (xapp-...).","type":["string","null"]},"bot_token":{"description":"Slack bot OAuth token (xoxb-...).","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["bot_token"]},"SmartGroupConfig":{"description":"Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).","type":"object","properties":{"classifier_max_context_messages":{"description":"How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.","type":"integer","format":"uint","default":3,"minimum":0},"classifier_model":{"description":"Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.","type":"string","default":""},"classifier_provider":{"description":"Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.","type":"string","default":""},"classifier_temperature":{"description":"Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).","type":"number","format":"double","default":0.0},"classifier_timeout_secs":{"description":"Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.","type":"integer","format":"uint64","default":5,"minimum":0}}},"StorageConfig":{"description":"Persistent storage configuration (`[storage]` section).","type":"object","properties":{"provider":{"description":"Storage provider settings (e.g. sqlite, postgres).","$ref":"#/$defs/StorageProviderSection","default":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}}},"StorageProviderConfig":{"description":"Storage provider backend configuration (e.g. postgres connection details).","type":"object","properties":{"connect_timeout_secs":{"description":"Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"db_url":{"description":"Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.","type":["string","null"],"default":null},"pool_max_size":{"description":"Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.","type":"integer","format":"uint","default":32,"minimum":0},"provider":{"description":"Storage engine key (e.g. \"postgres\", \"sqlite\").","type":"string","default":""},"schema":{"description":"Database schema for SQL backends.","type":"string","default":"public"},"table":{"description":"Table name for memory entries.","type":"string","default":"memories"}}},"StorageProviderSection":{"description":"Wrapper for the storage provider configuration section.","type":"object","properties":{"config":{"description":"Storage provider backend settings.","$ref":"#/$defs/StorageProviderConfig","default":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"StreamMode":{"description":"Streaming mode for channels that support progressive message updates.","oneOf":[{"description":"No streaming -- send the complete response as a single message (default).","type":"string","const":"off"},{"description":"Update a draft message with every flush interval.","type":"string","const":"partial"}]},"TailscaleTunnelConfig":{"type":"object","properties":{"funnel":{"description":"Use Tailscale Funnel (public internet) vs Serve (tailnet only)","type":"boolean","default":false},"hostname":{"description":"Optional hostname override","type":["string","null"]}}},"TaskRoutingConfig":{"description":"Lightweight pre-LLM task routing.","type":"object","properties":{"default_intent":{"description":"Fallback intent when no rule matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"rules":{"description":"Rules evaluated in descending priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/TaskRoutingRule"}}}},"TaskRoutingIntentConfig":{"description":"Task-routing default and rule intent.","type":"string","enum":["simple","delegate","stream"]},"TaskRoutingRule":{"description":"A single task-routing rule.","type":"object","properties":{"intent":{"description":"Route intent to apply when a keyword matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"model_hint":{"description":"Optional model hint/raw model for non-delegated requests.","type":["string","null"],"default":null},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0},"sub_agent_model":{"description":"Optional raw sub-agent model override for delegated tasks.","type":["string","null"],"default":null}}},"TelegramConfig":{"description":"Telegram bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Telegram user IDs or usernames. Empty = deny all.","type":"array","items":{"type":"string"}},"bot_token":{"description":"Telegram Bot API token (from @BotFather).","type":"string"},"draft_update_interval_ms":{"description":"Minimum interval (ms) between draft message edits to avoid rate limits.","type":"integer","format":"uint64","default":1000,"minimum":0},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"interrupt_on_new_message":{"description":"When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.","type":"boolean","default":false},"stream_mode":{"description":"Streaming mode for progressive response delivery via message edits.","$ref":"#/$defs/StreamMode","default":"off"}},"required":["bot_token","allowed_users"]},"ToolCallDialectSetting":{"description":"The tool-call grammars an operator may declare for an endpoint.","oneOf":[{"description":"Only the native `tool_calls` array is a tool call (the default).","type":"string","const":"native"},{"description":"Additionally read `{json}` from the content,\nfor a tool name the request registered.","type":"string","const":"xml_function_tags"}]},"ToolSchemaDialectSetting":{"description":"The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.","oneOf":[{"description":"The published document, byte for byte (the default).","type":"string","const":"raw"},{"description":"The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.","type":"string","const":"no_root_combinators"}]},"ToolTieringConfig":{"description":"Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.","type":"object","properties":{"always_exclude":{"description":"Tool names excluded from capability publication.","type":"array","default":[],"items":{"type":"string"}},"always_include":{"description":"Tool names preferred for direct publication, subject to admission gates.","type":"array","default":[],"items":{"type":"string"}},"channel_exclude":{"description":"Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefaults to [`DEFAULT_CHANNEL_EXCLUDED_TOOLS`]; set to `[]` to expose the\nfull operator surface on channels again.","type":"array","default":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","git_operations","skills_manage","memory_reindex","document_sync","document_ingest"],"items":{"type":"string"}}}},"TunnelConfig":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.","type":"object","properties":{"cloudflare":{"description":"Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).","anyOf":[{"$ref":"#/$defs/CloudflareTunnelConfig"},{"type":"null"}],"default":null},"custom":{"description":"Custom tunnel command configuration (used when `provider = \"custom\"`).","anyOf":[{"$ref":"#/$defs/CustomTunnelConfig"},{"type":"null"}],"default":null},"ngrok":{"description":"ngrok tunnel configuration (used when `provider = \"ngrok\"`).","anyOf":[{"$ref":"#/$defs/NgrokTunnelConfig"},{"type":"null"}],"default":null},"provider":{"description":"Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.","type":"string","default":"none"},"tailscale":{"description":"Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).","anyOf":[{"$ref":"#/$defs/TailscaleTunnelConfig"},{"type":"null"}],"default":null}}},"UserPolicyConfig":{"description":"Startup user policy entry (`[[user_policies]]`).","type":"object","properties":{"blocked_patterns":{"type":"array","default":[],"items":{"type":"string"}},"projects":{"type":"array","default":[],"items":{"type":"string"}},"role":{"type":"string","default":"guest"},"user_id":{"type":"string"},"visibility_ceiling":{"type":"string","default":"private"}},"required":["user_id"]},"WacliConfig":{"description":"wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```","type":"object","properties":{"allow_unsigned_loopback":{"description":"Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).","type":"boolean","default":false},"allowed_from":{"description":"Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.","type":"array","default":["*"],"items":{"type":"string"}},"bot_jid":{"description":"Bot's own JID, used for reply-to-bot mention detection.","type":["string","null"],"default":null},"bot_lid":{"description":"The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.","type":["string","null"],"default":null},"bot_number":{"description":"Bot's own phone number (digits), used for `@` mention detection.","type":["string","null"],"default":null},"cli_path":{"description":"Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.","type":["string","null"],"default":null},"group_reply_mode":{"description":"Smart group-reply mode. When `None`, derived from `mention_only`.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"host":{"description":"REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].","type":["string","null"],"writeOnly":true},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"outbound_media_workspace_only":{"description":"Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.","type":"boolean","default":false},"port":{"description":"REMOVED: legacy JSON-RPC daemon port. See `host`.","type":["integer","null"],"format":"uint16","maximum":65535,"minimum":0,"writeOnly":true},"self_chat_mode":{"description":"Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.","type":"boolean","default":false},"store_dir":{"description":"wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.","type":["string","null"],"default":null},"webhook_listen":{"description":"Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").","type":"string","default":"127.0.0.1:16868"},"webhook_path":{"description":"HTTP path the webhook server serves (default: \"/wacli\").","type":"string","default":"/wacli"},"webhook_secret":{"description":"HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.","type":["string","null"],"default":null}}},"WebSearchConfig":{"description":"Web search tool configuration (`[web_search]` section).","type":"object","properties":{"brave_api_key":{"description":"Brave Search API key (required if provider is \"brave\")","type":["string","null"],"default":null},"fetch_max_chars":{"description":"Maximum characters returned by `web_fetch` (default 10000)","type":"integer","format":"uint","default":50000,"minimum":0},"max_results":{"description":"Maximum results per search (1-20)","type":"integer","format":"uint","default":15,"minimum":0},"provider":{"description":"Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)","type":"string","default":"duckduckgo"},"timeout_secs":{"description":"Request timeout in seconds","type":"integer","format":"uint64","default":15,"minimum":0}}},"WebhookConfig":{"description":"Webhook channel configuration.","type":"object","properties":{"port":{"description":"Port to listen on for incoming webhooks.","type":"integer","format":"uint16","maximum":65535,"minimum":0},"secret":{"description":"Optional shared secret for webhook signature verification.","type":["string","null"]}},"required":["port"]},"WhatsAppConfig":{"description":"WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.","type":"object","properties":{"access_token":{"description":"Access token from Meta Business Suite (Cloud API mode)","type":["string","null"],"default":null},"allowed_numbers":{"description":"Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"app_secret":{"description":"App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"pair_code":{"description":"Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one","type":["string","null"],"default":null},"pair_phone":{"description":"Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used","type":["string","null"],"default":null},"phone_number_id":{"description":"Phone number ID from Meta Business API (Cloud API mode)","type":["string","null"],"default":null},"read_pool_size":{"description":"Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"session_path":{"description":"Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs","type":["string","null"],"default":null},"verify_token":{"description":"Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode","type":["string","null"],"default":null},"ws_url":{"description":"WebSocket URL override (replaces WHATSAPP_WS_URL)","type":["string","null"],"default":null}}},"WorkspaceHooks":{"description":"Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).","oneOf":[{"description":"They do not run (the default); `prx doctor` and `hooks_status` say so.","type":"string","const":"off"},{"description":"They run, in a cleared environment and a dedicated directory beside\n`config.toml`.","type":"string","const":"on"}]},"WorkspaceMcpServers":{"description":"Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).","oneOf":[{"description":"None: a workspace file may only narrow the servers defined in\n`config.toml`.","type":"string","const":"off"},{"description":"HTTP servers (still refused when they target a private address).","type":"string","const":"http_only"},{"description":"HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.","type":"string","const":"stdio"}]},"XinConfig":{"description":"Configuration for the xin autonomous task engine (`[xin]`).","type":"object","properties":{"adopt_legacy_tasks":{"description":"Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).","type":"boolean","default":false},"interval_minutes":{"description":"Tick interval in minutes (minimum 1). Default: 5.","type":"integer","format":"uint32","default":5,"minimum":0},"stale_timeout_minutes":{"description":"Minutes after which a running task is marked stale. Default: 60.","type":"integer","format":"uint32","default":60,"minimum":0}}},"AgentMessaging":{"description":"Owner-controlled inbound session messaging (enabled unless explicitly off).","type":"object","properties":{"inbound":{"type":"boolean","default":true}}}}} From e2de4f823e8a072528a74378709000df79356bbc Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:23:24 +0400 Subject: [PATCH 0081/1567] chore: remove the legacy project name from comments and sample data --- .coderabbit.yaml | 2 +- Cargo.toml | 2 +- src/config/schema/tests/persistence.rs | 2 +- src/identity.rs | 4 ++-- src/security/mod.rs | 2 +- src/skills/mod.rs | 2 +- src/tools/composio.rs | 2 +- src/tools/message_send.rs | 4 ++-- src/util.rs | 2 +- tests/memory_comparison.rs | 2 +- 10 files changed, 12 insertions(+), 12 deletions(-) diff --git a/.coderabbit.yaml b/.coderabbit.yaml index 52cac8ef8..9108e655c 100644 --- a/.coderabbit.yaml +++ b/.coderabbit.yaml @@ -1,4 +1,4 @@ -# CodeRabbit configuration for ZeroClaw +# CodeRabbit configuration for PRX # Documentation: https://docs.coderabbit.ai/reference/configuration language: en-US diff --git a/Cargo.toml b/Cargo.toml index 10a7c881e..e7a2313f7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -208,7 +208,7 @@ rust-embed = "8.5" # OpenTelemetry — OTLP trace + metrics export. # Use the blocking HTTP exporter client to avoid Tokio-reactor panics in -# OpenTelemetry background batch threads when ZeroClaw emits spans/metrics from +# OpenTelemetry background batch threads when PRX emits spans/metrics from # non-Tokio contexts. opentelemetry = { version = "0.31", default-features = false, features = ["trace", "metrics"] } opentelemetry_sdk = { version = "0.31", default-features = false, features = ["trace", "metrics"] } diff --git a/src/config/schema/tests/persistence.rs b/src/config/schema/tests/persistence.rs index 656d6f73d..3fd3a962f 100644 --- a/src/config/schema/tests/persistence.rs +++ b/src/config/schema/tests/persistence.rs @@ -345,7 +345,7 @@ async fn config_split_and_reload_roundtrip_matches_original() { config.default_model = Some("roundtrip-model".into()); config.channels_config.telegram = Some(TelegramConfig { bot_token: "roundtrip-token".into(), - allowed_users: vec!["zeroclaw_user".into()], + allowed_users: vec!["prx_user".into()], stream_mode: StreamMode::default(), draft_update_interval_ms: default_draft_update_interval_ms(), interrupt_on_new_message: false, diff --git a/src/identity.rs b/src/identity.rs index a4c7e4fac..d7a6ffd0d 100644 --- a/src/identity.rs +++ b/src/identity.rs @@ -2,7 +2,7 @@ //! //! AIEOS (AI Entity Object Specification) is a standardization framework for //! portable AI identity. This module handles loading and converting AIEOS v1.1 -//! JSON to ZeroClaw's system prompt format. +//! JSON to PRX's system prompt format. pub mod delegated; pub mod roles; @@ -682,7 +682,7 @@ fn non_empty_list_at(value: &Value, path: &[&str]) -> Option> { /// Convert AIEOS identity to a system prompt string. /// /// Formats the AIEOS data into a structured markdown prompt compatible -/// with ZeroClaw's agent system. +/// with PRX's agent system. pub fn aieos_to_system_prompt(identity: &AieosIdentity) -> String { use std::fmt::Write; let mut prompt = String::new(); diff --git a/src/security/mod.rs b/src/security/mod.rs index 689aae1f1..f566c03e0 100644 --- a/src/security/mod.rs +++ b/src/security/mod.rs @@ -1,6 +1,6 @@ //! Security subsystem for policy enforcement and secret management. //! -//! This module provides the security infrastructure for ZeroClaw. The core type +//! This module provides the security infrastructure for PRX. The core type //! [`SecurityPolicy`] defines autonomy levels, workspace boundaries, and //! access-control rules that are enforced across the tool and runtime subsystems. //! [`PairingGuard`] implements device pairing for channel authentication, and diff --git a/src/skills/mod.rs b/src/skills/mod.rs index da7a3b012..e83905aab 100644 --- a/src/skills/mod.rs +++ b/src/skills/mod.rs @@ -1367,7 +1367,7 @@ pub fn init_skills_dir(workspace_dir: &Path) -> Result<()> { if !readme.exists() { std::fs::write( &readme, - "# ZeroClaw Skills\n\n\ + "# PRX Skills\n\n\ Each subdirectory is a skill. Create a `SKILL.toml` or `SKILL.md` file inside.\n\n\ ## SKILL.toml format\n\n\ ```toml\n\ diff --git a/src/tools/composio.rs b/src/tools/composio.rs index 1d7446438..5cce3d4f5 100644 --- a/src/tools/composio.rs +++ b/src/tools/composio.rs @@ -1,6 +1,6 @@ // Composio Tool Provider — optional managed tool surface with 1000+ OAuth integrations. // -// When enabled, ZeroClaw can execute actions on Gmail, Notion, GitHub, Slack, etc. +// When enabled, PRX can execute actions on Gmail, Notion, GitHub, Slack, etc. // through Composio's API without storing raw OAuth tokens locally. // // This is opt-in. Users who prefer sovereign/local-only mode skip this entirely. diff --git a/src/tools/message_send.rs b/src/tools/message_send.rs index f5e36a07a..de201bf4e 100644 --- a/src/tools/message_send.rs +++ b/src/tools/message_send.rs @@ -1428,7 +1428,7 @@ mod tests { .execute(json!({ "action": "send", "target": "+15551234567", - "message": "Hello from ZeroClaw!" + "message": "Hello from PRX!" })) .await .unwrap(); @@ -1436,7 +1436,7 @@ mod tests { assert!(result.success, "Expected success, got: {:?}", result.error); let msgs = sent.lock().await; assert_eq!(msgs.len(), 1); - assert_eq!(msgs[0], "Hello from ZeroClaw!"); + assert_eq!(msgs[0], "Hello from PRX!"); } #[tokio::test] diff --git a/src/util.rs b/src/util.rs index fa5c0d4b2..87bd79970 100644 --- a/src/util.rs +++ b/src/util.rs @@ -1,4 +1,4 @@ -//! Utility functions for `ZeroClaw`. +//! Utility functions for `PRX`. //! //! This module contains reusable helper functions used across the codebase. diff --git a/tests/memory_comparison.rs b/tests/memory_comparison.rs index fbe73ac5a..dd5679593 100644 --- a/tests/memory_comparison.rs +++ b/tests/memory_comparison.rs @@ -84,7 +84,7 @@ async fn compare_recall_quality() { ("lang_pref", "User prefers Rust over Python", MemoryCategory::Core), ("editor", "Uses VS Code with rust-analyzer", MemoryCategory::Core), ("tz", "Timezone is EST, works 9-5", MemoryCategory::Core), - ("proj1", "Working on ZeroClaw AI assistant", MemoryCategory::Daily), + ("proj1", "Working on PRX AI assistant", MemoryCategory::Daily), ( "proj2", "Previous project was a web scraper in Python", From ebb21ab40b3ae7f9360d6dd0cf5441ec83e3996a Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:23:24 +0400 Subject: [PATCH 0082/1567] docs: record the proxy scope rename in the changelog --- CHANGELOG.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index abb82e3ca..a2418f399 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -137,7 +137,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `http_request` tools resolve a host once, refuse it when any address is private or local, and connect to exactly the checked address (DNS rebinding); `web_fetch` does so for every redirect hop. Both now connect - directly: a general proxy (`proxy.scope = "zeroclaw"`) and inherited + directly: a general proxy (`proxy.scope = "prx"`) and inherited `HTTP_PROXY`/`HTTPS_PROXY`/`ALL_PROXY` are no longer used by them, because a proxy resolves the name itself. `http_request` uses the proxy only with `proxy.scope = "services"` and the exact key `tool.http_request` in @@ -147,7 +147,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - BREAKING (operators): PRX no longer writes the process environment. `proxy.scope = "environment"` is inactive: a saved configuration that has it still loads, with one warning, and its proxy URLs route no traffic. - Migrate to `proxy.scope = "zeroclaw"` (all PRX traffic) or to + Migrate to `proxy.scope = "prx"` (all PRX traffic) or to `proxy.scope = "services"` with `proxy.services`; to rely on inherited variables, start PRX with them set. The agent `proxy_config` tool refuses `set` with scope `environment`, `apply_env` and `clear_env`, and changes @@ -166,6 +166,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- BREAKING (operators): the general proxy scope value (`proxy.scope`) is now + `"prx"`; the previous value is no longer accepted and a configuration that + still has it fails to load. - BREAKING (operators): recursive delegation is on by default, so a child session equals the main session. Omitting `allow_delegation` on `sessions_spawn` gives a child that can spawn its own children, bounded only From 1b1d50062aec0f05a54266aa49c1a9869d0f355c Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:28:51 +0400 Subject: [PATCH 0083/1567] test: keep test targets compiling after signature changes --- src/agent/turn_tests/turn_history.rs | 2 +- tests/session_worker_stdin_protocol.rs | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/agent/turn_tests/turn_history.rs b/src/agent/turn_tests/turn_history.rs index c1ad6625d..685c9b0af 100644 --- a/src/agent/turn_tests/turn_history.rs +++ b/src/agent/turn_tests/turn_history.rs @@ -449,7 +449,7 @@ fn splice_eviction_and_lift_keep_evidence_aligned() { let mut broken = canonical_with_evidence(&evidence); broken.evidence.pop(); assert!( - !broken.splice(1, 2, &[ChatMessage::assistant("x")], MessageOrigin::Acknowledged), + !broken.splice(1, 2, &[ChatMessage::assistant("x")], MessageOrigin::Acknowledged, &MessageSources::turn_round()), "a splice over misaligned evidence is refused" ); assert_eq!( diff --git a/tests/session_worker_stdin_protocol.rs b/tests/session_worker_stdin_protocol.rs index f5f876bf5..4e2099bf5 100644 --- a/tests/session_worker_stdin_protocol.rs +++ b/tests/session_worker_stdin_protocol.rs @@ -73,6 +73,7 @@ fn manifest_for(config_dir: &Path, workspace_dir: &Path) -> WorkerManifest { route_credential: None, route_uses_root_connection: false, direct_uses_root_connection: false, + approval_relay: false, temperature: 0.7, temperature_override: None, config_dir: config_dir.to_path_buf(), From e9874519469379c1f2cbc56010214f2929939ac8 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:59:30 +0400 Subject: [PATCH 0084/1567] fix(messaging): refuse a send naming an unconfigured target agent instead of redirecting to the session's agent --- docs/tools.md | 7 +++++++ src/messaging/runtime.rs | 15 +++++++++++---- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/docs/tools.md b/docs/tools.md index ab2a375f0..5cbc341b0 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -2005,6 +2005,13 @@ follow-up text after completion and starts another turn in the same child sessio If a process child reports `configuration_changed`, restart its parent chat before retrying; a newer disk configuration cannot execute under the parent's old seal. +A local `sessions_send` target may name `agent`. Omitted or `main` addresses the +session's main agent as before. Any other name is the receiver the sender asked +for and is never replaced by the session's recorded agent: a name that is not a +configured, enabled agent that accepts inbound messages, or that does not match +the session's agent, is refused with `mailbox_unauthorized` before any outbox, +message or receipt row is written. + Remote `sessions_send` targets supply `instance`, `session`, and optionally `agent`. Omit `owner`: the authenticated receiver's `/a2a/v1/pins` response supplies it. A queued result always contains a durable message UUID; an assistant's text alone diff --git a/src/messaging/runtime.rs b/src/messaging/runtime.rs index c91502e38..06da272e9 100644 --- a/src/messaging/runtime.rs +++ b/src/messaging/runtime.rs @@ -290,16 +290,23 @@ impl MessagingRuntime { crate::messaging::mailbox::unauthorized(crate::messaging::mailbox::UnauthorizedReason::LocalOwnerMismatch); return Err(MailboxError::OwnerMismatch); } + // An explicit non-main agent is the sender's claim about the receiver. It is never + // replaced by the session's recorded agent: the store and the inbound check then + // refuse an unconfigured or mismatching agent instead of delivering to another one. + let explicit_agent = address.agent != "main" && target.get("agent").is_some(); if matches!(address.session.as_str(), "main" | "parent") { address.session = self .store .parent_session(&self.workspace, &source.owner, &source.session)? .unwrap_or_else(|| source.session.clone()); - address.agent = "main".into(); + if !explicit_agent { + address.agent = "main".into(); + } } - if let Some(agent) = self - .store - .logical_agent(&self.workspace, &source.owner, &address.session)? + if !explicit_agent + && let Some(agent) = self + .store + .logical_agent(&self.workspace, &source.owner, &address.session)? { address.agent = agent; } From 2073cb3a0a7ebec9980befba6e03377f658a9d28 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:49:39 +0400 Subject: [PATCH 0085/1567] fix(messaging): project an adopted mailbox message once, through its adoption row The woken turn's input stays in message_events but is no longer projected into conversation_turns, the snapshot or the model context. --- src/gateway/api/sessions/mailbox.rs | 22 +++++++++++++---- src/gateway/api/sessions/section_2.rs | 5 +++- src/memory/sqlite/events/section_2.rs | 4 ++++ src/memory/sqlite/mailbox_continuation.rs | 29 +++++++++++++++++++++++ src/memory/sqlite/mod.rs | 1 + src/memory/sqlite/sync_journal.rs | 8 ++----- src/memory/sqlite/sync_snapshot.rs | 11 ++++++--- 7 files changed, 65 insertions(+), 15 deletions(-) create mode 100644 src/memory/sqlite/mailbox_continuation.rs diff --git a/src/gateway/api/sessions/mailbox.rs b/src/gateway/api/sessions/mailbox.rs index 1eaddc20b..882cc534b 100644 --- a/src/gateway/api/sessions/mailbox.rs +++ b/src/gateway/api/sessions/mailbox.rs @@ -80,6 +80,22 @@ async fn run( &input.message.to.agent, ) .await?; + // The adoption row is the message's only history row. The woken turn's own + // input is not projected, and the request below carries the text once, so + // the adoption turn leaves the loaded history. A missing adoption row + // refuses the turn, as the child continuation does. + let adopted = envelope + .source_message_event_id + .clone() + .ok_or_else(|| anyhow::anyhow!("mailbox adoption row is missing"))?; + let principal_memory = envelope.memory_principal(); + let mut turns = state + .mem + .list_console_conversation_turns(&principal_memory, &input.message.to.session, MAX_PAGE_LIMIT, 0) + .await?; + let before = turns.len(); + turns.retain(|turn| turn.message_event_id.as_deref() != Some(adopted.as_str())); + anyhow::ensure!(turns.len() < before, "mailbox adoption row is missing from history"); let cancellation = tokio_util::sync::CancellationToken::new(); let stop = cancellation.clone(); let _message_turn = runtime.hold_turn(&input, Arc::new(move || stop.cancel()))?; @@ -90,13 +106,9 @@ async fn run( principal, envelope, ticket, + continuation: true, }; let (proof, guard) = pending.record(input.text.clone(), None).await?; - let principal = proof.envelope().memory_principal(); - let turns = state - .mem - .list_console_conversation_turns(&principal, &input.message.to.session, MAX_PAGE_LIMIT, 0) - .await?; let source = ConsoleTurnSource::Admitted { proof, guard, diff --git a/src/gateway/api/sessions/section_2.rs b/src/gateway/api/sessions/section_2.rs index 7a9bb7cad..4ef4f74ab 100644 --- a/src/gateway/api/sessions/section_2.rs +++ b/src/gateway/api/sessions/section_2.rs @@ -167,6 +167,8 @@ struct ConsolePendingInput { principal: super::ApiPrincipal, envelope: RuntimeEnvelope, ticket: crate::runtime::turn_cleanup::CleanupTicket, + /// Set only by the mailbox wake: the input anchors the run and is never a history row. + continuation: bool, } impl ConsolePendingInput { @@ -249,7 +251,7 @@ impl ConsolePendingInput { if recording.enabled && recording.record_user_messages { if console_recordable(&self.runtime.config_generation.effective, self.state.mem.as_ref()) { self.state.mem.project_console_message(&event).await?; - } else { + } else if !self.continuation { self.state .mem .append_conversation_turn( @@ -505,6 +507,7 @@ async fn submit_console_message( principal: api_principal, envelope: runtime_envelope, ticket, + continuation: false, }; let admission = rf.as_ref().map(|rf| rf.admission.clone()); let (proof, mut guard) = match pending.record(message.clone(), admission).await { diff --git a/src/memory/sqlite/events/section_2.rs b/src/memory/sqlite/events/section_2.rs index 83d97dffd..4a2ff6110 100644 --- a/src/memory/sqlite/events/section_2.rs +++ b/src/memory/sqlite/events/section_2.rs @@ -124,6 +124,10 @@ impl SqliteMemory { )?; anyhow::ensure!(serde_json::to_value(&durable)? == serde_json::to_value(&event)?, "console projection differs from its durable event"); + // A continuation input anchors the woken run; its adoption row is the history row. + if super::mailbox_continuation::is_continuation(&tx, &event)? { + return Ok(()); + } let existing: Vec<(String, Option, String, String, bool)> = { let mut stmt = tx.prepare("SELECT session_key, owner_id, role, content, deleted_at IS NOT NULL FROM conversation_turns WHERE message_event_id = ?1 OR message_id = ?1 LIMIT 2")?; diff --git a/src/memory/sqlite/mailbox_continuation.rs b/src/memory/sqlite/mailbox_continuation.rs new file mode 100644 index 000000000..6dc60e6c6 --- /dev/null +++ b/src/memory/sqlite/mailbox_continuation.rs @@ -0,0 +1,29 @@ +//! The one definition of a mailbox continuation input. +//! +//! A continuation input is a `user` row whose `causation_event_id` names a +//! `prx_mailbox` user row (the adoption row) of the same workspace, owner and +//! session. The adoption row is the message's only history row; the woken +//! turn's own input anchors the run but is never projected into history. +use rusqlite::{Connection, params}; + +/// SQL predicate over a `message_events` row aliased `e`: true when `e` is a +/// continuation input. Usable inside any query that exposes that alias. +pub(super) const CONTINUATION_PREDICATE_E: &str = "(e.role='user' AND EXISTS(SELECT 1 FROM message_events adopt \ + WHERE adopt.event_id=e.causation_event_id AND adopt.workspace_id=e.workspace_id \ + AND adopt.owner_id=e.owner_id AND adopt.session_key=e.session_key \ + AND adopt.source='prx_mailbox' AND adopt.role='user'))"; + +/// Whether `event` is a continuation of an adopted mailbox message. +pub(super) fn is_continuation(conn: &Connection, event: &crate::memory::MessageEvent) -> anyhow::Result { + Ok(conn.query_row( + "SELECT EXISTS(SELECT 1 FROM message_events WHERE event_id=?1 AND workspace_id=?2 AND owner_id=?3 \ + AND session_key=?4 AND source='prx_mailbox' AND role='user')", + params![ + event.causation_event_id, + event.workspace_id, + event.owner_id, + event.session_key + ], + |row| row.get(0), + )?) +} diff --git a/src/memory/sqlite/mod.rs b/src/memory/sqlite/mod.rs index 49c1e14ce..a506d8d9d 100644 --- a/src/memory/sqlite/mod.rs +++ b/src/memory/sqlite/mod.rs @@ -14,6 +14,7 @@ mod events; mod evolution; mod ingress_recovery; pub mod mailbox; +mod mailbox_continuation; mod mailbox_schema; mod memory_impl; mod mirror; diff --git a/src/memory/sqlite/sync_journal.rs b/src/memory/sqlite/sync_journal.rs index 59fbbafb4..4974f058f 100644 --- a/src/memory/sqlite/sync_journal.rs +++ b/src/memory/sqlite/sync_journal.rs @@ -285,7 +285,7 @@ pub(super) fn event_written(conn: &Connection, event: &crate::memory::MessageEve } if event.role == "user" && (h.parent_run_id.is_some() || event.source.as_str() == "prx_mailbox") - && !mailbox_continuation(conn, event)? + && !super::mailbox_continuation::is_continuation(conn, event)? { h.kind = "turn.appended".into(); h.event_id = format!("turn.appended:{}", h.source_ref); @@ -363,7 +363,7 @@ pub(super) fn admission( if h.run_id.is_some() { append(conn, &h)?; } - if mailbox_continuation(conn, event)? { + if super::mailbox_continuation::is_continuation(conn, event)? { return Ok(()); } h.kind = "turn.appended".into(); @@ -535,7 +535,3 @@ impl SyncStore for SqliteMemory { self.sync_runtime.shutdown.lock().clone() } } - -fn mailbox_continuation(conn: &Connection, event: &crate::memory::MessageEvent) -> anyhow::Result { - Ok(conn.query_row("SELECT EXISTS(SELECT 1 FROM message_events WHERE event_id=?1 AND workspace_id=?2 AND owner_id=?3 AND session_key=?4 AND source='prx_mailbox' AND role='user')",params![event.causation_event_id,event.workspace_id,event.owner_id,event.session_key],|row|row.get(0))?) -} diff --git a/src/memory/sqlite/sync_snapshot.rs b/src/memory/sqlite/sync_snapshot.rs index c24e0cdf0..4717928f7 100644 --- a/src/memory/sqlite/sync_snapshot.rs +++ b/src/memory/sqlite/sync_snapshot.rs @@ -131,8 +131,13 @@ fn inventory(conn: &Connection, id: &str, owner: &str, head: i64, water: i64) -> // Admission/terminal commits precede their transcript projections. The // cut must inventory the primary events, or it could advance past an // event that is absent from both snapshot and subsequent replay. - let mut q=conn.prepare("WITH candidates AS ( + let continuation_flag = format!( + "CASE WHEN {} THEN 1 ELSE 0 END", + super::mailbox_continuation::CONTINUATION_PREDICATE_E + ); + let mut q=conn.prepare(&format!("WITH candidates AS ( SELECT e.id,e.event_id,e.workspace_id,e.owner_id,e.run_id,e.role,e.event_type,e.idempotency_key, + {continuation_flag} AS continuation, CASE WHEN e.role='assistant' OR e.idempotency_key LIKE 'turn:%:assistant' THEN (SELECT f.event_id FROM message_events f WHERE f.owner_id=e.owner_id AND f.workspace_id=e.workspace_id AND f.run_id=e.run_id AND f.id<=?2 AND ( @@ -141,13 +146,13 @@ fn inventory(conn: &Connection, id: &str, owner: &str, head: i64, water: i64) -> ORDER BY f.id LIMIT 1) END AS final_marker FROM message_events e WHERE e.owner_id=?1 AND e.id<=?2) SELECT e.event_id,e.final_marker FROM candidates e WHERE - e.role='user' + (e.role='user' AND e.continuation=0) OR (e.event_type='message.deleted' AND ( EXISTS(SELECT 1 FROM rf_message_attempts a WHERE a.owner_id=e.owner_id AND a.message_event_id=e.event_id) OR EXISTS(SELECT 1 FROM conversation_turns c WHERE c.message_event_id=e.event_id AND c.role='user') OR EXISTS(SELECT 1 FROM sync_journal j WHERE j.owner_id=e.owner_id AND j.kind='turn.appended' AND j.source_ref='event:'||e.event_id AND j.seq<=?3))) OR e.final_marker IS NOT NULL - ORDER BY e.id")?; + ORDER BY e.id"))?; for row in q.query_map(params![owner, water, head], |r| { Ok((r.get::<_, String>(0)?, r.get::<_, Option>(1)?)) })? { From 46e829e5245238150a96802a7cea2b0f1babe778 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:31:42 +0400 Subject: [PATCH 0086/1567] fix(config): agent create, update and delete never need high-risk confirmation Agent management plans whose every change lies inside agents. are exempt from the confirm_high_risk gate. Any plan that reaches a path outside the subtree keeps the ordinary confirmation. --- docs/rf-contract/capability-tokens.md | 10 ++--- src/config/manage/agent_scope.rs | 53 +++++++++++++++++++++++++++ src/config/manage/mod.rs | 1 + src/config/manage/service.rs | 47 +++++++++++++++++------- src/config/manage/transaction.rs | 26 ++++++++++++- 5 files changed, 117 insertions(+), 20 deletions(-) create mode 100644 src/config/manage/agent_scope.rs diff --git a/docs/rf-contract/capability-tokens.md b/docs/rf-contract/capability-tokens.md index d52b748d2..2a9b1f628 100644 --- a/docs/rf-contract/capability-tokens.md +++ b/docs/rf-contract/capability-tokens.md @@ -159,7 +159,7 @@ without a level reads back Main's level, the one it runs at. |---|---|---| | `GET /api/agents` | | `200 {"revision","agents":[readback…]}`: every configured named agent, retired ones included, sorted by name; Main and names outside the grammar are not listed | | `GET /api/agents/{name}` | | `200` readback; `main` gives Main's | -| `PUT /api/agents/{name}` | `If-Match`; body `{"provider","model","autonomy","tools","enabled","prompt"?,"limits"?}`, a full replacement; `?confirm_high_risk=true` only after a `428` | `201` readback when created, `200` when replaced. The incarnation is created at the first `PUT`, whatever the switch or `enabled` say | +| `PUT /api/agents/{name}` | `If-Match`; body `{"provider","model","autonomy","tools","enabled","prompt"?,"limits"?}`, a full replacement; `?confirm_high_risk` is accepted and ignored (no `428`) | `201` readback when created, `200` when replaced. The incarnation is created at the first `PUT`, whatever the switch or `enabled` say | | `DELETE /api/agents/{name}` | `If-Match` | `200 {"name","status":"retired","revision"}`. The agent stays configured, disabled, and takes no turn; a repeated `DELETE` gives the same body with the current revision. The purge is `agent_memory_purge_v1` | | `GET /api/gateway/targeted-agents` | | `200 {"revision","configured","effective","restart_required"}` | | `PUT /api/gateway/targeted-agents` | `If-Match`; `{"enabled":bool}` | `200`, same shape; the switch takes effect at the next daemon restart, so `restart_required` is `true` until then | @@ -205,10 +205,10 @@ without a level reads back Main's level, the one it runs at. registry. - `422 not_applied`: the change was refused at activation and nothing stays written. -- `428 confirmation_required` `{"error":{"code","message","revision"}}`: a - high-risk change (for example a provider change on an agent that holds an - inline key); resend with `?confirm_high_risk=true` and `If-Match` equal to - `revision`. Nothing rf sends in normal use triggers it. +- No `428`: creating, replacing, retiring and purging an agent never require + high-risk confirmation, whatever the change touches inside `agents.`. + A `confirm_high_risk` query parameter on these routes is accepted and + ignored. A stale or missing `If-Match` is still `409` / the refusals above. - `500 storage_unavailable`: the configuration, the registry or a reload failed. diff --git a/src/config/manage/agent_scope.rs b/src/config/manage/agent_scope.rs new file mode 100644 index 000000000..e862f2bc3 --- /dev/null +++ b/src/config/manage/agent_scope.rs @@ -0,0 +1,53 @@ +//! The agent-management exemption from the high-risk confirmation. +//! +//! Creating, replacing, retiring and purging a named agent through the +//! management API never asks for `confirm_high_risk` (owner decision for the +//! rf integration). The exemption is only honoured for a plan whose every +//! change, every risk reason and every secret write or clear lies inside +//! `agents.`; a plan that reaches anything else keeps the ordinary +//! confirmation. + +use super::plan::{ConfigChangeSummary, RiskReason}; + +/// Whether `path` is `prefix` or lies below it (a key or an index). +fn under(path: &str, prefix: &str) -> bool { + path.strip_prefix(prefix) + .is_some_and(|rest| rest.is_empty() || rest.starts_with('.') || rest.starts_with('[')) +} + +/// The path a risk reason names; `None` for a reason that names none (the +/// reasons that concern the whole configuration). +fn reason_path(reason: &RiskReason) -> Option<&str> { + match reason { + RiskReason::CredentialChanged { path } + | RiskReason::EndpointChanged { path } + | RiskReason::CredentialReintroduced { path } + | RiskReason::PrivilegeWidened { path } + | RiskReason::CredentialRecipientChanged { path } + | RiskReason::ProcessEnvironmentChanged { path } + | RiskReason::CredentialOwnerChanged { path } + | RiskReason::AccessGrantChanged { path } + | RiskReason::RemoteDecisionEnabled { path } => Some(path), + RiskReason::EncryptionDisabled | RiskReason::BaselineUnavailable => None, + } +} + +/// Whether the whole change described by `summary` stays inside the +/// configuration of the agent `agent`. +pub(super) fn confines(summary: &ConfigChangeSummary, agent: &str) -> bool { + // A name that could be read as a longer path is never confined. + if agent.is_empty() || agent.contains(['.', '[', ']']) { + return false; + } + let prefix = format!("agents.{agent}"); + summary.changes.iter().all(|entry| under(&entry.path, &prefix)) + && summary + .risk_reasons + .iter() + .all(|reason| reason_path(reason).is_some_and(|path| under(path, &prefix))) + && summary + .secret_writes + .iter() + .chain(&summary.secret_clears) + .all(|path| under(path, &prefix)) +} diff --git a/src/config/manage/mod.rs b/src/config/manage/mod.rs index 861f90719..e9726ef23 100644 --- a/src/config/manage/mod.rs +++ b/src/config/manage/mod.rs @@ -17,6 +17,7 @@ //! - [`render`]: the one text rendering of a plan; //! - [`migrate`]: the legacy-configuration report and migration (PMM-H). +mod agent_scope; mod autonomy; pub(crate) mod boundary; pub mod credentials; diff --git a/src/config/manage/service.rs b/src/config/manage/service.rs index a7accd6fe..3ec054609 100644 --- a/src/config/manage/service.rs +++ b/src/config/manage/service.rs @@ -193,6 +193,9 @@ pub struct ManagedPlan { /// One sentence per selection the change makes that the evidence does /// not verify (accepted for the operator, D-034). warnings: Vec, + /// The agent whose own configuration is the whole change (agent + /// management); its plan needs no high-risk confirmation. + agent_subtree: Option, } impl std::fmt::Debug for ManagedPlan { @@ -300,7 +303,14 @@ impl ManagementService { let desired = self.shared.desired(); let candidate = candidate(&desired.config, change)?; let revision = ConfigTransactions::base_revision(&desired); - self.plan_candidate(candidate, revision, actor).await + let mut planned = self.plan_candidate(candidate, revision, actor).await?; + planned.agent_subtree = match change { + ManagedChange::PutAgent { agent, .. } + | ManagedChange::RetireAgent { agent } + | ManagedChange::PurgeAgent { agent } => Some(agent.clone()), + _ => None, + }; + Ok(planned) } /// Write-only Brave credential planning through the same slot validation, @@ -354,6 +364,7 @@ impl ManagementService { plan, revision, warnings, + agent_subtree: None, }) } @@ -373,6 +384,7 @@ impl ManagementService { plan, revision, warnings, + agent_subtree: None, }) } @@ -389,19 +401,25 @@ impl ManagementService { actor: ConfigActor, confirmed_revision: Option<&str>, ) -> Result { - let ManagedPlan { plan, revision, .. } = plan; - Ok(self - .transactions - .apply( - plan, - actor, - ApplyOptions { - expected_revision: revision.as_deref(), - confirm_high_risk: confirmed_revision.is_some(), - confirmed_revision, - }, - ) - .await?) + let ManagedPlan { + plan, + revision, + agent_subtree, + .. + } = plan; + let options = ApplyOptions { + expected_revision: revision.as_deref(), + confirm_high_risk: confirmed_revision.is_some(), + confirmed_revision, + }; + Ok(match agent_subtree.as_deref() { + Some(agent) => { + self.transactions + .apply_agent_subtree(plan, actor, options, agent) + .await? + } + None => self.transactions.apply(plan, actor, options).await?, + }) } /// Plan decision-plane `mutations` (CDP-14, `prx causal config`) over @@ -504,6 +522,7 @@ impl ManagementService { plan, revision, warnings: Vec::new(), + agent_subtree: None, }, ))) } diff --git a/src/config/manage/transaction.rs b/src/config/manage/transaction.rs index 3d2698e81..fafc97577 100644 --- a/src/config/manage/transaction.rs +++ b/src/config/manage/transaction.rs @@ -686,6 +686,29 @@ impl ConfigTransactions { plan: ConfigPlan, actor: ConfigActor, options: ApplyOptions<'_>, + ) -> Result { + self.apply_scoped(plan, actor, options, None).await + } + + /// [`apply`](Self::apply) for an agent-management change: a plan whose + /// every change lies inside `agents.` needs no confirmation + /// whatever its risk class; any other plan is held to the ordinary rule. + pub async fn apply_agent_subtree( + &self, + plan: ConfigPlan, + actor: ConfigActor, + options: ApplyOptions<'_>, + agent: &str, + ) -> Result { + self.apply_scoped(plan, actor, options, Some(agent)).await + } + + async fn apply_scoped( + &self, + plan: ConfigPlan, + actor: ConfigActor, + options: ApplyOptions<'_>, + agent: Option<&str>, ) -> Result { self.shared .ensure_runtime_writable() @@ -697,7 +720,8 @@ impl ConfigTransactions { // Every selection the change affects resolves before anything else // is asked of the caller: a refused model is refused, not confirmed. let warnings = check_plan_selections(&plan, actor).await?; - if plan.summary.risk == ConfigChangeRisk::High { + let confined = agent.is_some_and(|agent| super::agent_scope::confines(&plan.summary, agent)); + if plan.summary.risk == ConfigChangeRisk::High && !confined { if !options.confirm_high_risk { return Err(ConfigTransactionError::ConfirmationRequired { required: "confirm_high_risk", From 2cadab87f85f66f8849fde8f72faaae9cc3b632f Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:29:22 +0400 Subject: [PATCH 0087/1567] fix(sync): journal a child task once, not as spawn request and segment input --- src/memory/sqlite/mailbox_continuation.rs | 19 +++++++++++++++++++ src/memory/sqlite/sync_journal.rs | 1 + src/memory/sqlite/sync_snapshot.rs | 5 +++-- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/memory/sqlite/mailbox_continuation.rs b/src/memory/sqlite/mailbox_continuation.rs index 6dc60e6c6..cf18fcd76 100644 --- a/src/memory/sqlite/mailbox_continuation.rs +++ b/src/memory/sqlite/mailbox_continuation.rs @@ -27,3 +27,22 @@ pub(super) fn is_continuation(conn: &Connection, event: &crate::memory::MessageE |row| row.get(0), )?) } + +/// SQL predicate over a `message_events` row aliased `e`: true when `e` is a +/// child task segment input that restates the task already recorded by the +/// spawn request row (same session, role and content, and the spawn row's run +/// is the segment's `task_run_id`). History hides it the same way +/// (`child_turns::history`), so the journal and snapshot must not publish it. +pub(super) const TASK_ECHO_PREDICATE_E: &str = "(e.role='user' AND EXISTS(SELECT 1 FROM message_events p \ + WHERE p.workspace_id=e.workspace_id AND p.owner_id=e.owner_id AND p.id anyhow::Result { + Ok(conn.query_row( + &format!("SELECT EXISTS(SELECT 1 FROM message_events e WHERE e.event_id=?1 AND {TASK_ECHO_PREDICATE_E})"), + params![event_id], + |row| row.get(0), + )?) +} diff --git a/src/memory/sqlite/sync_journal.rs b/src/memory/sqlite/sync_journal.rs index 4974f058f..376cd8f12 100644 --- a/src/memory/sqlite/sync_journal.rs +++ b/src/memory/sqlite/sync_journal.rs @@ -286,6 +286,7 @@ pub(super) fn event_written(conn: &Connection, event: &crate::memory::MessageEve if event.role == "user" && (h.parent_run_id.is_some() || event.source.as_str() == "prx_mailbox") && !super::mailbox_continuation::is_continuation(conn, event)? + && !super::mailbox_continuation::is_task_echo(conn, &event.event_id)? { h.kind = "turn.appended".into(); h.event_id = format!("turn.appended:{}", h.source_ref); diff --git a/src/memory/sqlite/sync_snapshot.rs b/src/memory/sqlite/sync_snapshot.rs index 4717928f7..21420669d 100644 --- a/src/memory/sqlite/sync_snapshot.rs +++ b/src/memory/sqlite/sync_snapshot.rs @@ -132,8 +132,9 @@ fn inventory(conn: &Connection, id: &str, owner: &str, head: i64, water: i64) -> // cut must inventory the primary events, or it could advance past an // event that is absent from both snapshot and subsequent replay. let continuation_flag = format!( - "CASE WHEN {} THEN 1 ELSE 0 END", - super::mailbox_continuation::CONTINUATION_PREDICATE_E + "CASE WHEN {} OR {} THEN 1 ELSE 0 END", + super::mailbox_continuation::CONTINUATION_PREDICATE_E, + super::mailbox_continuation::TASK_ECHO_PREDICATE_E ); let mut q=conn.prepare(&format!("WITH candidates AS ( SELECT e.id,e.event_id,e.workspace_id,e.owner_id,e.run_id,e.role,e.event_type,e.idempotency_key, From b8fe493b0310bd994795eef1d42dac10fda6589c Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:31:25 +0400 Subject: [PATCH 0088/1567] fix(sessions): a cancelled process child is recorded as cancelled, not failed The worker already commits a cancelled terminal, but its result carried only success=false, so the parent wrote a task.failed event that the child session projection turned into a second child_session.upsert with status failed. The worker result now carries a cancelled flag, the parent records task.cancelled for it, and the read model treats task.cancelled like a terminated run. --- src/session_worker/protocol.rs | 5 +++ src/session_worker/runner/mod.rs | 3 ++ src/session_worker/runner/run.rs | 46 +++++++++++++---------- src/session_worker/runner/tests/hybrid.rs | 2 + src/session_worker/startup_failure.rs | 1 + src/tools/sessions_read_model.rs | 2 + src/tools/sessions_spawn/process_mode.rs | 1 + src/tools/sessions_spawn/spawn.rs | 14 ++++++- 8 files changed, 52 insertions(+), 22 deletions(-) diff --git a/src/session_worker/protocol.rs b/src/session_worker/protocol.rs index 1af2d7cdf..4c9be75a7 100644 --- a/src/session_worker/protocol.rs +++ b/src/session_worker/protocol.rs @@ -420,6 +420,10 @@ pub struct WorkerResult { pub error: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub tokens_used: Option, + /// The run ended because its work was cancelled, not because it failed. + /// `success` is still false; only the terminal classification differs. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub cancelled: bool, } #[cfg(test)] @@ -700,6 +704,7 @@ mod tests { output: String::new(), error: Some("timeout".into()), tokens_used: None, + cancelled: false, }; let json = serde_json::to_string(&result).expect("serialize result"); diff --git a/src/session_worker/runner/mod.rs b/src/session_worker/runner/mod.rs index 6be37a621..ddd233052 100644 --- a/src/session_worker/runner/mod.rs +++ b/src/session_worker/runner/mod.rs @@ -173,6 +173,7 @@ pub async fn run_from_stdin( output: String::new(), error: Some(format!("Invalid worker manifest JSON: {error:#}")), tokens_used: None, + cancelled: false, }; write_worker_result(&result)?; return Ok(()); @@ -200,6 +201,7 @@ pub async fn run_from_stdin( output: String::new(), error: Some(format!("{error:#}")), tokens_used: None, + cancelled: false, }; write_worker_result(&result)?; return Ok(()); @@ -219,6 +221,7 @@ pub async fn run_from_stdin( output: String::new(), error: Some(format!("{error:#}")), tokens_used: None, + cancelled: false, } } }; diff --git a/src/session_worker/runner/run.rs b/src/session_worker/runner/run.rs index 30fa2f912..a3d4ce3e2 100644 --- a/src/session_worker/runner/run.rs +++ b/src/session_worker/runner/run.rs @@ -1213,30 +1213,35 @@ async fn run_owned_manifest( }, error: None, tokens_used: tokens_used.has_any_tokens().then_some(tokens_used), + cancelled: false, }, crate::agent::terminal::TurnTerminalStatus::Completed, ) } - Err(error) => ( - WorkerResult { - denials: Vec::new(), - ordinary_completion: None, - operator_completion: None, - success: false, - output: String::new(), - error: Some(format!( - "worker execution in {} (memory {}): {error:#}", - manifest.workspace_dir.display(), - manifest.memory_db_path.display() - )), - tokens_used: None, - }, - if crate::agent::turn_contracts::is_tool_loop_cancelled(&error) { - crate::agent::terminal::TurnTerminalStatus::Cancelled - } else { - crate::agent::terminal::TurnTerminalStatus::Failed - }, - ), + Err(error) => { + let cancelled = crate::agent::turn_contracts::is_tool_loop_cancelled(&error); + ( + WorkerResult { + denials: Vec::new(), + ordinary_completion: None, + operator_completion: None, + success: false, + output: String::new(), + error: Some(format!( + "worker execution in {} (memory {}): {error:#}", + manifest.workspace_dir.display(), + manifest.memory_db_path.display() + )), + tokens_used: None, + cancelled, + }, + if cancelled { + crate::agent::terminal::TurnTerminalStatus::Cancelled + } else { + crate::agent::terminal::TurnTerminalStatus::Failed + }, + ) + } }; worker_result.denials = process_denials.take()?; @@ -1405,6 +1410,7 @@ async fn run_owned_manifest( crate::agent::terminal::redact_persisted_json(serde_json::json!({ "success": worker_result.success, "error": worker_result.error, + "cancelled": worker_result.cancelled, "owner_id": manifest.owner_id.as_deref(), "topic_id": manifest.topic_id.as_deref(), "parent_task_id": manifest.parent_task_id.as_deref(), diff --git a/src/session_worker/runner/tests/hybrid.rs b/src/session_worker/runner/tests/hybrid.rs index 5685afbde..a3331dfc9 100644 --- a/src/session_worker/runner/tests/hybrid.rs +++ b/src/session_worker/runner/tests/hybrid.rs @@ -262,6 +262,7 @@ async fn hybrid_worker_result_creates_private_draft_and_parent_merge_request() { output: "worker draft content".to_string(), error: None, tokens_used: None, + cancelled: false, }; let result_event = worker_fabric .record_worker_result(scope.clone(), result.output.clone(), None) @@ -418,6 +419,7 @@ async fn hybrid_worker_draft_obeys_readonly_resource_gate() { output: "worker draft content".to_string(), error: None, tokens_used: None, + cancelled: false, }; let manifest = WorkerManifest { seed_history: Vec::new(), diff --git a/src/session_worker/startup_failure.rs b/src/session_worker/startup_failure.rs index 778f6f7c3..79026f479 100644 --- a/src/session_worker/startup_failure.rs +++ b/src/session_worker/startup_failure.rs @@ -94,6 +94,7 @@ impl AuthenticatedStartupFailure { output: String::new(), error: Some(error), tokens_used: None, + cancelled: false, }; validate_failure(&result)?; let mut proof = StartupFailureProof { diff --git a/src/tools/sessions_read_model.rs b/src/tools/sessions_read_model.rs index 1eee71033..c93c3e6cc 100644 --- a/src/tools/sessions_read_model.rs +++ b/src/tools/sessions_read_model.rs @@ -566,6 +566,7 @@ fn is_task_lifecycle_event(event_type: &str) -> bool { || event_type == "task.completed" || event_type == "task.failed" || event_type == "task.killed" + || event_type == "task.cancelled" || event_type.ends_with(".task.started") || event_type.ends_with(".task.completed") || event_type.ends_with(".task.failed") @@ -578,6 +579,7 @@ fn status_from_event_type(event_type: &str) -> RecoveredTaskStatus { RecoveredTaskStatus::Completed } else if event_type == "task.failed" || event_type == "task.killed" + || event_type == "task.cancelled" || event_type.ends_with(".task.failed") || event_type.ends_with(".task.timeout") { diff --git a/src/tools/sessions_spawn/process_mode.rs b/src/tools/sessions_spawn/process_mode.rs index 149be0a6c..ccc25dfb0 100644 --- a/src/tools/sessions_spawn/process_mode.rs +++ b/src/tools/sessions_spawn/process_mode.rs @@ -62,6 +62,7 @@ impl WorkerUnverifiedFailure { output: String::new(), error: Some(format!("{}: {detail}", self.code())), tokens_used: None, + cancelled: false, }) } } diff --git a/src/tools/sessions_spawn/spawn.rs b/src/tools/sessions_spawn/spawn.rs index 0484cb567..36a80c520 100644 --- a/src/tools/sessions_spawn/spawn.rs +++ b/src/tools/sessions_spawn/spawn.rs @@ -1173,10 +1173,14 @@ impl SessionsSpawnTool { ) .await; + // The worker's own account that its work was cancelled; the run's + // status stays `Failed`, only the recorded task event differs. + let mut worker_cancelled = false; let (status, result_text, token_usage_records, finalization) = match worker_result { Ok(ProcessWorkerOutcome::OrdinaryVerifiedFinished(completion)) => { *monitor_ordinary_terminal.lock() = Some(completion.clone()); let result = completion.result; + worker_cancelled = result.cancelled; let (status, text) = if result.success { (SubAgentStatus::Completed(result.output.clone()), result.output) } else { @@ -1188,6 +1192,7 @@ impl SessionsSpawnTool { Ok(ProcessWorkerOutcome::OperatorVerifiedFinished(completion)) => { *monitor_operator_terminal.lock() = Some(completion.clone()); let result = completion.result; + worker_cancelled = result.cancelled; let (status, text) = if result.success { (SubAgentStatus::Completed(result.output.clone()), result.output) } else { @@ -1238,6 +1243,7 @@ impl SessionsSpawnTool { ) } Ok(ProcessWorkerOutcome::Finished(result)) => { + worker_cancelled = result.cancelled; let error = result.error.unwrap_or_else(|| "worker failed".to_string()); let msg = format!("Sub-agent error: {error}"); // `result.error` is a field of the JSON the @@ -1353,7 +1359,7 @@ impl SessionsSpawnTool { &result_text, &status, &process_lineage, - None, + worker_cancelled.then_some("task.cancelled"), Some(crate::session_worker::protocol::worker_result_key(&rid)), ) .await; @@ -1385,7 +1391,11 @@ impl SessionsSpawnTool { &result_text, &status, &process_lineage, - (finalization == ProcessFinalization::Terminated).then_some("task.killed"), + if finalization == ProcessFinalization::Terminated { + Some("task.killed") + } else { + worker_cancelled.then_some("task.cancelled") + }, Some(crate::session_worker::protocol::worker_result_key(&rid)), ) .await; From 8f4ddfa5a47615fca21008334947dabf2517f594 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:31:54 +0400 Subject: [PATCH 0089/1567] fix(messaging): wake adopted mailbox messages that a restart left unprocessed --- src/memory/sqlite/mailbox.rs | 1 + src/memory/sqlite/mailbox/deliver.rs | 62 +++++++++++--------- src/memory/sqlite/mailbox/recover.rs | 85 ++++++++++++++++++++++++++++ src/messaging/receiver.rs | 17 ++++++ src/messaging/runtime.rs | 32 +++++++++++ 5 files changed, 171 insertions(+), 26 deletions(-) create mode 100644 src/memory/sqlite/mailbox/recover.rs diff --git a/src/memory/sqlite/mailbox.rs b/src/memory/sqlite/mailbox.rs index 933ce5026..a11d648b5 100644 --- a/src/memory/sqlite/mailbox.rs +++ b/src/memory/sqlite/mailbox.rs @@ -11,6 +11,7 @@ mod outbox; pub(super) mod pin; mod publish; mod receipt; +mod recover; mod retry; mod stream; pub use outbox::MailboxOutbound; diff --git a/src/memory/sqlite/mailbox/deliver.rs b/src/memory/sqlite/mailbox/deliver.rs index 4eb9d28c6..b466ff2dd 100644 --- a/src/memory/sqlite/mailbox/deliver.rs +++ b/src/memory/sqlite/mailbox/deliver.rs @@ -164,32 +164,7 @@ impl SqliteMailbox { if pin.to_pin_token.is_empty() || pin.pin_expires_at < 0 { return Err(MailboxError::CorruptState); } - let message = PrxMessage { - id: saved.message_id, - idempotency: saved.idempotency.clone(), - stream_id: Some(stream.wire_id), - seq: saved.seq, - ts: saved.meta.wire_ts, - from: stream.from.clone(), - to: stream.to.clone(), - to_pin: RecipientPin { - incarnation: scope.incarnation, - generation: scope.generation, - token: pin.to_pin_token, - }, - in_reply_to: saved.meta.common.in_reply_to, - hop_count: saved.meta.common.hop_count, - ancestry: saved.meta.common.ancestry.clone(), - kind: MessageKind::Data, - body: MessageBody { - mime: body.0, - bytes: body.1, - }, - origin: Some(saved.meta.common.origin), - auth: saved.meta.common.auth.clone(), - exec: saved.meta.common.exec_run.clone().map(|run| ExecRef { run: Some(run) }), - canonical_hash: None, - }; + let message = wire_message(&saved, &stream, scope, body.0, body.1, pin.to_pin_token); if crate::messaging::request_digest(&message) != saved.meta.common.request_digest { return Err(MailboxError::IdentityImmutable); } @@ -253,6 +228,41 @@ impl SqliteMailbox { } } +/// Rebuild the wire message of a stored slot; delivery and restart recovery +/// share it so both verify the same request digest. +pub(super) fn wire_message( + saved: &receipt::Receipt, + stream: &stream::Stream, + scope: &MailboxScope, + mime: String, + bytes: Vec, + token: String, +) -> PrxMessage { + PrxMessage { + id: saved.message_id, + idempotency: saved.idempotency.clone(), + stream_id: Some(stream.wire_id), + seq: saved.seq, + ts: saved.meta.wire_ts, + from: stream.from.clone(), + to: stream.to.clone(), + to_pin: RecipientPin { + incarnation: scope.incarnation, + generation: scope.generation, + token, + }, + in_reply_to: saved.meta.common.in_reply_to, + hop_count: saved.meta.common.hop_count, + ancestry: saved.meta.common.ancestry.clone(), + kind: MessageKind::Data, + body: MessageBody { mime, bytes }, + origin: Some(saved.meta.common.origin), + auth: saved.meta.common.auth.clone(), + exec: saved.meta.common.exec_run.clone().map(|run| ExecRef { run: Some(run) }), + canonical_hash: None, + } +} + /// Kept by a live task/process owner until its model/cache/IPC has actually /// stopped. Dropping an old run cannot close a later run of the same address. #[must_use] diff --git a/src/memory/sqlite/mailbox/recover.rs b/src/memory/sqlite/mailbox/recover.rs new file mode 100644 index 000000000..8934d3d40 --- /dev/null +++ b/src/memory/sqlite/mailbox/recover.rs @@ -0,0 +1,85 @@ +//! Restart recovery: adopted messages whose waking turn never started. +use rusqlite::{Transaction, TransactionBehavior, params}; + +use super::{ + SqliteMailbox, + deliver::wire_message, + model::{DeliveryMeta, decode, encode}, + pin::check_scope, + receipt, storage_error, stream, +}; +use crate::messaging::mailbox::{MailboxError, MailboxReceipt, MailboxResult, MailboxScope}; +use crate::messaging::{DeliveryState, PrxMessage, SessionAddr}; + +/// A restart can only strand this many queued wakes (the ready queue cap). +const MAX_RECOVERED: i64 = 64; + +impl SqliteMailbox { + /// Adopted messages of `address` with no continuation input yet, oldest + /// first. The adoption commit and the wake are separate steps: a message + /// is "adopted, not woken" while no `message_events` row names its adoption + /// row as `causation_event_id`. The woken turn writes that row first, so a + /// turn that started (even if it never finished) is never replayed. + pub(crate) fn unwoken_adopted( + &self, + scope: &MailboxScope, + address: &SessionAddr, + ) -> MailboxResult> { + let writer = self.memory.pool.write(); + let tx = Transaction::new_unchecked(&writer, TransactionBehavior::Deferred).map_err(storage_error)?; + check_scope(&tx, scope, address, None, true)?; + let ids = { + let mut query = tx + .prepare( + "SELECT m.id FROM prx_mailbox_messages m \ + JOIN prx_mailbox_seq s ON s.stream_id=m.stream_id \ + WHERE m.ma_scope_id=?1 AND s.to_addr=?2 AND m.state=2 \ + ORDER BY m.id DESC LIMIT ?3", + ) + .map_err(storage_error)?; + query + .query_map(params![scope.scope_id.to_string(), encode(address)?, MAX_RECOVERED], |r| { + r.get::<_, i64>(0) + }) + .map_err(storage_error)? + .collect::>>() + .map_err(storage_error)? + }; + let mut found = Vec::new(); + for id in ids { + let saved = receipt::load(&tx, id)?; + let Some(event) = saved.meta.adopted_message_event_id else { + continue; + }; + if saved.state != DeliveryState::Consumed || saved.meta.body_erased_at.is_some() || saved.scope != *scope { + continue; + } + let woken: bool = tx + .query_row( + "SELECT EXISTS(SELECT 1 FROM message_events WHERE workspace_id=?1 AND causation_event_id=?2)", + params![scope.workspace_id, event.to_string()], + |r| r.get(0), + ) + .map_err(storage_error)?; + if woken { + continue; + } + let body: (String, Vec, String) = tx + .query_row( + "SELECT body_mime,body_bytes,delivery_meta FROM prx_mailbox_messages WHERE id=?1 AND ma_scope_id=?2", + params![id, scope.scope_id.to_string()], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), + ) + .map_err(storage_error)?; + let pin: DeliveryMeta = decode(&body.2)?; + let stream = stream::load(&tx, saved.stream_id)?; + let message = wire_message(&saved, &stream, scope, body.0, body.1, pin.to_pin_token); + if crate::messaging::request_digest(&message) != saved.meta.common.request_digest { + return Err(MailboxError::IdentityImmutable); + } + found.push((message, saved.result(&tx)?)); + } + found.reverse(); + Ok(found) + } +} diff --git a/src/messaging/receiver.rs b/src/messaging/receiver.rs index cc8eadb4f..31d25f174 100644 --- a/src/messaging/receiver.rs +++ b/src/messaging/receiver.rs @@ -45,6 +45,23 @@ pub(crate) fn register_idle( return; } }; + // Adopted but not yet woken before a restart: queue them for the first poll. + let Ok((returned, recovered)) = crate::runtime::blocking::spawn_blocking(move || { + let recovered = inbox.recover(); + (inbox, recovered) + }) + .await + else { + return; + }; + inbox = returned; + match recovered { + Ok(0) => {} + Ok(count) => tracing::info!(count, "session mailbox recovered adopted messages awaiting a wake"), + Err(error) => { + tracing::warn!(error=%crate::agent::diagnostics::error_class(&error), "session mailbox wake recovery failed"); + } + } let mut interval = tokio::time::interval(std::time::Duration::from_millis(100)); loop { interval.tick().await; diff --git a/src/messaging/runtime.rs b/src/messaging/runtime.rs index 06da272e9..b983e4402 100644 --- a/src/messaging/runtime.rs +++ b/src/messaging/runtime.rs @@ -397,6 +397,38 @@ impl SessionInbox { pub async fn notified(&mut self) { let _ = self.receiver.recv().await; } + /// Queue adopted messages whose waking turn never started, e.g. the + /// process stopped between the adoption commit and the wake. Run once, + /// right after registration and before the first poll. A message whose + /// continuation input exists is not returned by the store, so a turn that + /// started is never repeated. + pub(crate) fn recover(&self) -> MailboxResult { + let mut queued = 0; + for (message, receipt) in self.runtime.store.unwoken_adopted(&self.scope, &self.address)? { + let input = MessageInput { + _lease: self.runtime.store.hold_input(&self.scope, &self.address)?, + scope: self.scope.scope_id, + text: crate::session_worker::mailbox::user_text(&message)?, + message, + receipt, + }; + let pending = self + .runtime + .ready + .lock() + .get(&self.address) + .is_some_and(|queue| queue.iter().any(|held| held.message.id == input.message.id)); + if !input.auto_start() || pending { + continue; + } + match self.runtime.requeue_back(input) { + Ok(()) => queued += 1, + Err(MailboxError::QueueFull) => break, + Err(_) => {} + } + } + Ok(queued) + } pub fn poll(&mut self) -> MailboxResult> { self.runtime.store.validate_scope(&self.scope, &self.address)?; let execution = From a97a0579143f20c29aebbaf1b95d5d5a302c17b9 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:34:27 +0400 Subject: [PATCH 0090/1567] fix(gateway): decide message-woken turn approvals through the call approval path --- src/gateway/api/sessions/section_1.rs | 35 +++++++++++++++++++++------ src/gateway/run_approvals.rs | 28 +++++++++++++++++++++ 2 files changed, 55 insertions(+), 8 deletions(-) diff --git a/src/gateway/api/sessions/section_1.rs b/src/gateway/api/sessions/section_1.rs index fcdd7d772..0c5e0fe2f 100644 --- a/src/gateway/api/sessions/section_1.rs +++ b/src/gateway/api/sessions/section_1.rs @@ -1660,6 +1660,7 @@ pub(super) async fn post_decision_approval( Json(request): Json, ) -> Response { let owner_authenticated = super::owner_authenticated(&state, &headers); + let mut request = request; match rf_message::keyed_session(&state, &session_id).await { Some(true) => { if !owner_authenticated { @@ -1669,14 +1670,32 @@ pub(super) async fn post_decision_approval( "paired bearer required", ); } - return crate::gateway::run_approvals::decide( - &state, - &principal.owner_id, - &session_id, - &decision_id, - request, - ) - .await; + // A message-woken turn raises an ordinary call approval with no rf + // root; decide it through the ordinary call approval path. + let plain = crate::gateway::run_approvals::is_plain_call(&state, &decision_id).await; + if plain { + let approved = match request.get("decision").and_then(serde_json::Value::as_str) { + Some("approved") => true, + Some("denied") => false, + _ => { + return super::capabilities::coded_error( + StatusCode::BAD_REQUEST, + "field_invalid", + "decision must be approved or denied", + ); + } + }; + request = serde_json::json!({ "approved": approved }); + } else { + return crate::gateway::run_approvals::decide( + &state, + &principal.owner_id, + &session_id, + &decision_id, + request, + ) + .await; + } } None => { return super::capabilities::coded_error( diff --git a/src/gateway/run_approvals.rs b/src/gateway/run_approvals.rs index 148d5ebe5..6291478df 100644 --- a/src/gateway/run_approvals.rs +++ b/src/gateway/run_approvals.rs @@ -426,6 +426,34 @@ pub(crate) async fn decide( ), } } +/// True when `id` names a durable pending call that carries no rf run scope. +/// +/// A turn woken by a session-to-session message has no rf root, so its approval +/// is an ordinary call approval. The rf decide path cannot resolve it (it is +/// bound to an rf root session), the ordinary call approval path can. Any +/// lookup failure answers `false`, which keeps the rf path and its refusals. +pub(crate) async fn is_plain_call(state: &super::AppState, id: &str) -> bool { + if state.rf_approvals.entries.lock().contains_key(id) { + return false; + } + let Ok(authority) = RunCallAuthority::parse_call_id(id) else { + return false; + }; + let workspace = state.config.load_full().workspace_dir.to_string_lossy().into_owned(); + let Ok(Some(pending)) = state + .mem + .find_message_event_by_idempotency_key(&workspace, &authority.pending_key()) + .await + else { + return false; + }; + let raw: Value = pending + .raw_payload_json + .as_deref() + .and_then(|v| serde_json::from_str(v).ok()) + .unwrap_or_default(); + raw.get("record").is_some_and(Value::is_object) && raw.pointer("/record/rf").is_none_or(Value::is_null) +} async fn recorded( state: &super::AppState, owner: &str, From 53aa388cabd461b714e711a1be3b3d30d03f5291 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:01:35 +0400 Subject: [PATCH 0091/1567] fix(gateway): register receivers of sessions with unwoken adopted messages at startup --- src/gateway/api/mod.rs | 1 + src/gateway/api/sessions.rs | 1 + src/gateway/api/sessions/mailbox.rs | 89 +++++++++++++++++++++++++ src/gateway/implementation/section_2.rs | 1 + src/memory/sqlite/mailbox/recover.rs | 22 ++++++ 5 files changed, 114 insertions(+) diff --git a/src/gateway/api/mod.rs b/src/gateway/api/mod.rs index bde505649..7260a5fae 100644 --- a/src/gateway/api/mod.rs +++ b/src/gateway/api/mod.rs @@ -37,6 +37,7 @@ mod plugins; mod providers; mod runtime; mod sessions; +pub(super) use sessions::recover_startup as recover_mailbox_wakes; #[cfg(test)] pub(in crate::gateway) use sessions::post_session_message; #[cfg(test)] diff --git a/src/gateway/api/sessions.rs b/src/gateway/api/sessions.rs index 51bcb5226..2993cb279 100644 --- a/src/gateway/api/sessions.rs +++ b/src/gateway/api/sessions.rs @@ -1,4 +1,5 @@ mod mailbox; +pub(in crate::gateway) use mailbox::recover_startup; mod rf_delete; mod rf_message; mod rf_replay; diff --git a/src/gateway/api/sessions/mailbox.rs b/src/gateway/api/sessions/mailbox.rs index 882cc534b..bcdad7ec8 100644 --- a/src/gateway/api/sessions/mailbox.rs +++ b/src/gateway/api/sessions/mailbox.rs @@ -43,6 +43,95 @@ pub(super) fn register( }), ) } +/// Registers the receivers of owner sessions that hold adopted but unwoken +/// messages, so a restart wakes them without further input. Registration is +/// the existing path: its first poll queues the unwoken messages, and a later +/// submission to the same session finds the receiver registered and changes +/// nothing, so a message is never woken twice. A child session is reached +/// through its root, whose registration drives the children. +pub(in crate::gateway) async fn recover_startup(state: &AppState) { + let config = state.config.load_full(); + if config.memory.backend != "sqlite" { + return; + } + let Ok(runtime) = MessagingRuntime::for_config(&config) else { + return; + }; + let Ok(Ok(roots)) = crate::runtime::blocking::spawn_blocking(move || pending_roots(&runtime)).await else { + tracing::warn!("session mailbox startup wake scan failed"); + return; + }; + let workspace = config.workspace_dir.to_string_lossy().into_owned(); + for (owner, session, partition) in roots { + let Ok(Some(summary)) = state.mem.get_conversation_session(&session).await else { + continue; + }; + let envelope = super::console_runtime_envelope_for_workspace( + workspace.clone(), + &session, + &summary.channel, + &summary.sender, + ) + .with_owner_id(owner.clone()) + .with_owner_isolation() + .with_agent_partition(partition); + let principal = super::super::ApiPrincipal { owner_id: owner }; + match register(state, envelope, principal) { + Ok(()) => tracing::info!("session mailbox startup wake registered a receiver"), + Err(error) => { + tracing::warn!(error=%crate::agent::diagnostics::error_class(&error),"session mailbox startup wake refused"); + } + } + } +} + +/// Owner (`api:` ids only: the Console ingress) root sessions to register. +fn pending_roots( + runtime: &MessagingRuntime, +) -> crate::messaging::mailbox::MailboxResult> { + let workspace = &runtime.workspace; + let mut roots: Vec<(String, String, crate::memory::AgentPartition)> = Vec::new(); + for (owner, session, _) in runtime.store.unwoken_sessions(workspace)? { + if !owner.starts_with("api:") { + continue; + } + let mut root = session; + for _ in 0..8 { + match runtime.store.parent_session(workspace, &owner, &root)? { + Some(parent) => root = parent, + None => break, + } + } + if roots.iter().any(|(o, s, _)| *o == owner && *s == root) { + continue; + } + let agent = runtime + .store + .logical_agent(workspace, &owner, &root)? + .unwrap_or_else(|| "main".to_owned()); + let key = if agent == "main" { + crate::memory::PartitionKey::Main + } else { + let address = runtime.address(&owner, &root, &agent); + let scope = runtime.store.session_scope(workspace, &address, false)?; + let Ok(name) = crate::config::agent_name::AgentName::parse(&agent) else { + continue; + }; + crate::memory::PartitionKey::Named { + name, + incarnation: scope.incarnation, + } + }; + let partition = crate::memory::AgentPartition { + workspace_id: workspace.clone(), + owner_id: owner.clone(), + key, + }; + roots.push((owner, root, partition)); + } + Ok(roots) +} + async fn run( state: AppState, mut envelope: RuntimeEnvelope, diff --git a/src/gateway/implementation/section_2.rs b/src/gateway/implementation/section_2.rs index 46237c804..16c66d15e 100644 --- a/src/gateway/implementation/section_2.rs +++ b/src/gateway/implementation/section_2.rs @@ -573,6 +573,7 @@ async fn run_gateway_inner( .layer(RequestBodyLimitLayer::new(MAX_BODY_SIZE)); api::sync_startup::startup(&state, &shutdown).await?; + api::recover_mailbox_wakes(&state).await; let api_routes = api::router(state.clone()).layer(RequestBodyLimitLayer::new(MAX_API_BODY_SIZE)); // Build router with middleware diff --git a/src/memory/sqlite/mailbox/recover.rs b/src/memory/sqlite/mailbox/recover.rs index 8934d3d40..fbc13f2a3 100644 --- a/src/memory/sqlite/mailbox/recover.rs +++ b/src/memory/sqlite/mailbox/recover.rs @@ -15,6 +15,28 @@ use crate::messaging::{DeliveryState, PrxMessage, SessionAddr}; const MAX_RECOVERED: i64 = 64; impl SqliteMailbox { + /// Sessions `(owner, session, agent)` holding an adoption row that no + /// continuation input names, among the newest `MAX_RECOVERED` adoptions. + /// Startup uses it to find the sessions whose receiver must be registered. + pub(crate) fn unwoken_sessions(&self, workspace: &str) -> MailboxResult)>> { + let writer = self.memory.pool.write(); + let mut query = writer + .prepare( + "SELECT DISTINCT a.owner_id,a.session_key,a.agent_id FROM \ + (SELECT event_id,owner_id,session_key,agent_id FROM message_events \ + WHERE workspace_id=?1 AND source='prx_mailbox' AND role='user' \ + ORDER BY id DESC LIMIT ?2) a \ + WHERE NOT EXISTS(SELECT 1 FROM message_events c \ + WHERE c.workspace_id=?1 AND c.causation_event_id=a.event_id)", + ) + .map_err(storage_error)?; + query + .query_map(params![workspace, MAX_RECOVERED], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?))) + .map_err(storage_error)? + .collect::>>() + .map_err(storage_error) + } + /// Adopted messages of `address` with no continuation input yet, oldest /// first. The adoption commit and the wake are separate steps: a message /// is "adopted, not woken" while no `message_events` row names its adoption From 9fa0e73e8e267db75518730c81799a9a06a261dd Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:26:23 +0400 Subject: [PATCH 0092/1567] fix(approvals): stop listing reviewed call approvals as pending --- src/security/approval_ledger/run_call.rs | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/src/security/approval_ledger/run_call.rs b/src/security/approval_ledger/run_call.rs index d7b99618e..83b737838 100644 --- a/src/security/approval_ledger/run_call.rs +++ b/src/security/approval_ledger/run_call.rs @@ -792,21 +792,15 @@ impl ApprovalLedgerPort<'_> { { continue; } - if let Some(review) = self + // A reviewed call (approved or denied) is already decided: an approved one + // only awaits its single claim by the call, so it is not pending any more. + if self .memory .find_message_event_by_idempotency_key(self.workspace, &record.authority.review_key()) .await? + .is_some() { - let review: Signed = match self.decode(&review, b"call.review") { - Ok(review) => review, - Err(error) => { - tracing::warn!(event_id = %review.event_id, error = %error, "skipping corrupt call approval review event"); - continue; - } - }; - if !review.record.approved { - continue; - } + continue; } items.push(record); if items.len() == limit { From d77a0b0bc4f02e80495eb7f20cd5d6ebea2287a9 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:34:40 +0400 Subject: [PATCH 0093/1567] fix(gateway): refuse approval-gated calls in message-woken turns without an approval surface --- src/gateway/api/sessions/mailbox.rs | 21 ++++++++++++++++----- src/gateway/api/sessions/section_1.rs | 8 +++++++- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/src/gateway/api/sessions/mailbox.rs b/src/gateway/api/sessions/mailbox.rs index bcdad7ec8..f21603129 100644 --- a/src/gateway/api/sessions/mailbox.rs +++ b/src/gateway/api/sessions/mailbox.rs @@ -132,6 +132,13 @@ fn pending_roots( Ok(roots) } +tokio::task_local! { static WOKEN_TURN: (); } + +/// True only inside the turn this module drives for an adopted mailbox message. +pub(super) fn is_woken_turn() -> bool { + WOKEN_TURN.try_with(|()| ()).is_ok() +} + async fn run( state: AppState, mut envelope: RuntimeEnvelope, @@ -203,11 +210,15 @@ async fn run( guard, owner_authenticated: false, }; - crate::gateway::jobs::scope_cancellation( - cancellation, - run_console_message_job_work(turn_runtime, state, input.text.clone(), turns, source, target), - ) - .await + WOKEN_TURN + .scope( + (), + crate::gateway::jobs::scope_cancellation( + cancellation, + run_console_message_job_work(turn_runtime, state, input.text.clone(), turns, source, target), + ), + ) + .await .map_err(anyhow::Error::msg)?; drop(input); Ok(()) diff --git a/src/gateway/api/sessions/section_1.rs b/src/gateway/api/sessions/section_1.rs index 0c5e0fe2f..1bcd5c4c8 100644 --- a/src/gateway/api/sessions/section_1.rs +++ b/src/gateway/api/sessions/section_1.rs @@ -926,7 +926,13 @@ async fn run_console_runtime_turn( .with_dispatch_origin(crate::tools::DispatchOrigin::ModelTurn); context.live_turn = live .as_ref() - .map(|live| crate::agent::live_frames::LiveTurnRef(std::sync::Arc::clone(live))); + .map(|live| crate::agent::live_frames::LiveTurnRef(std::sync::Arc::clone(live))) + // A message-woken turn with no approval surface refuses a call + // that needs approval at once: no pending row nobody can act on. + .or_else(|| { + (target.is_none() && mailbox::is_woken_turn()) + .then(crate::runtime::mailbox_child::no_surface) + }); if target.is_some() && live.is_none() { // Until MA-04 a targeted call that needs approval ends // denied: no durable ledger route, no pending decision. From b811b1b38d3ae614b90e440e12ed99149e190911 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:32:02 +0400 Subject: [PATCH 0094/1567] fix(gateway): derive the isolation of a startup-recovered wake from current pairing The startup pass and the submission handler now share console_owner_isolated; the startup pass evaluates it on the current pairing state and fails closed. --- src/gateway/api/sessions/mailbox.rs | 47 +++++++++++++++++++++++++-- src/gateway/api/sessions/section_1.rs | 4 +-- src/gateway/api/sessions/section_2.rs | 9 ++--- src/gateway/api/sessions/target.rs | 14 ++++++++ 4 files changed, 65 insertions(+), 9 deletions(-) diff --git a/src/gateway/api/sessions/mailbox.rs b/src/gateway/api/sessions/mailbox.rs index f21603129..13b9ef4b0 100644 --- a/src/gateway/api/sessions/mailbox.rs +++ b/src/gateway/api/sessions/mailbox.rs @@ -1,7 +1,7 @@ //! Mailbox turns use the registered receiver's Console policy and provider. use super::{ AgentField, AppState, ConsolePendingInput, ConsoleTurnSource, MAX_PAGE_LIMIT, RuntimeEnvelope, TurnTarget, - prepare_target, resolve_target, run_console_message_job_work, + console_owner_isolated, prepare_target, resolve_target, run_console_message_job_work, }; use crate::messaging::runtime::{MessageInput, MessagingRuntime}; use std::sync::Arc; @@ -72,8 +72,14 @@ pub(in crate::gateway) async fn recover_startup(state: &AppState) { &summary.channel, &summary.sender, ) - .with_owner_id(owner.clone()) - .with_owner_isolation() + .with_owner_id(owner.clone()); + let isolated = startup_owner_isolated(state, &owner, &partition); + tracing::debug!(isolated, "session mailbox startup wake isolation decided"); + let envelope = if isolated { + envelope.with_owner_isolation() + } else { + envelope + } .with_agent_partition(partition); let principal = super::super::ApiPrincipal { owner_id: owner }; match register(state, envelope, principal) { @@ -85,6 +91,41 @@ pub(in crate::gateway) async fn recover_startup(state: &AppState) { } } +/// The isolation the owner's next submission to this session would get, +/// from the current pairing and config. It evaluates the submission's own +/// rule ([`console_owner_isolated`]) with an owner-authenticated flag that is +/// true only when pairing is required, a paired token remains and the owner is +/// the install owner. Any failure (target unresolved, runtime not admitted) +/// yields isolation. +fn startup_owner_isolated(state: &AppState, owner: &str, partition: &crate::memory::AgentPartition) -> bool { + let owner_authenticated = state.pairing.require_pairing() + && state.pairing.is_paired() + && state + .pairing + .install_owner() + .is_some_and(|install| install.as_str() == owner); + if !owner_authenticated { + return true; + } + let Ok(runtime) = state.admit_turn_runtime() else { + return true; + }; + let target_level = match &partition.key { + crate::memory::PartitionKey::Main => None, + crate::memory::PartitionKey::Named { name, .. } => { + match resolve_target(&runtime.config_generation.effective, &TurnTarget::Named(name.clone())) { + Ok(Some(plan)) => Some(plan.autonomy), + Ok(None) | Err(_) => return true, + } + } + }; + console_owner_isolated( + owner_authenticated, + target_level, + runtime.publication_slot.controlled.is_some(), + ) +} + /// Owner (`api:` ids only: the Console ingress) root sessions to register. fn pending_roots( runtime: &MessagingRuntime, diff --git a/src/gateway/api/sessions/section_1.rs b/src/gateway/api/sessions/section_1.rs index 1bcd5c4c8..30f18faac 100644 --- a/src/gateway/api/sessions/section_1.rs +++ b/src/gateway/api/sessions/section_1.rs @@ -36,8 +36,8 @@ pub(super) use rf_replay::{post_run_cancel, rf_job_cancel}; pub(super) use target::TARGET_EXCLUDED_TOOLS; use target::{ - AgentField, SelectedTurn, TargetError, TargetUnavailable, TargetedTurn, TurnTarget, prepare_target, - resolve_incarnation, resolve_target, + AgentField, SelectedTurn, TargetError, TargetUnavailable, TargetedTurn, TurnTarget, console_owner_isolated, + prepare_target, resolve_incarnation, resolve_target, }; #[derive(Serialize)] diff --git a/src/gateway/api/sessions/section_2.rs b/src/gateway/api/sessions/section_2.rs index 4ef4f74ab..b38f6d5ce 100644 --- a/src/gateway/api/sessions/section_2.rs +++ b/src/gateway/api/sessions/section_2.rs @@ -421,10 +421,11 @@ async fn submit_console_message( // turn's own level; any other caller (pairing off) stays owner-isolated. // A controlled H2 launch binds only isolated Gateway sources, so it keeps // isolation. - let full_target = target - .as_ref() - .is_some_and(|target| target.autonomy == crate::security::AutonomyLevel::Full); - let owner_isolated = (!owner_authenticated && !full_target) || turn_runtime.publication_slot.controlled.is_some(); + let owner_isolated = console_owner_isolated( + owner_authenticated, + target.as_ref().map(|target| target.autonomy), + turn_runtime.publication_slot.controlled.is_some(), + ); let run_id = rf .as_ref() .map_or_else(|| uuid::Uuid::new_v4().to_string(), |rf| rf.run_id.clone()); diff --git a/src/gateway/api/sessions/target.rs b/src/gateway/api/sessions/target.rs index 3f0008159..90927d207 100644 --- a/src/gateway/api/sessions/target.rs +++ b/src/gateway/api/sessions/target.rs @@ -167,6 +167,20 @@ fn allowlist_for(agent: &DelegateAgentConfig) -> Result, + controlled: bool, +) -> bool { + let full_target = target_level == Some(AutonomyLevel::Full); + (!owner_authenticated && !full_target) || controlled +} + /// A named target that passed resolution against one pinned config. #[derive(Clone)] pub(super) struct TargetPlan { From 4293ea7e048aadf7390d29be2f84e86004952e97 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:30:05 +0400 Subject: [PATCH 0095/1567] fix(sessions): parent a spawned run to its turn so a root cancel reaches it A sub-agent run was registered under the sessions_spawn tool call that launched it. That row is deregistered when the call returns, so the run dropped out of the lineage a cascading kill of the root walks, and a cancelled root left a process child running its tool to completion. The run is now parented to the nearest enclosing non-tool-call work item. --- src/runtime/registry.rs | 24 ++++++++++++++++++++++++ src/tools/sessions_spawn/spawn.rs | 11 +++++++---- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/src/runtime/registry.rs b/src/runtime/registry.rs index 67c3e7d5c..ceb167716 100644 --- a/src/runtime/registry.rs +++ b/src/runtime/registry.rs @@ -349,6 +349,30 @@ pub fn current_work_id() -> Option { CURRENT_WORK.try_with(|id| *id).ok() } +/// The nearest enclosing work item that is not a tool call. +/// +/// A run that outlives the tool call that launched it must not hang off that +/// call: the row is deregistered when the call returns, which cuts the run out +/// of the lineage a cascading kill of the turn walks. Parenting it to the +/// enclosing turn (or sub-agent) keeps the run reachable for as long as that +/// owner is registered. +#[must_use] +pub fn current_owner_work_id() -> Option { + let mut id = current_work_id()?; + loop { + let Some(slot) = REGISTRY.get(id.raw()) else { + return Some(id); + }; + if slot.kind != WorkKind::ToolCall { + return Some(id); + } + match slot.parent { + Some(parent) => id = WorkId(parent), + None => return Some(id), + } + } +} + /// RAII registration. Dropping it deregisters the work item. /// /// Deregistration lives in `Drop` rather than at a call site on purpose: a diff --git a/src/tools/sessions_spawn/spawn.rs b/src/tools/sessions_spawn/spawn.rs index 36a80c520..158034481 100644 --- a/src/tools/sessions_spawn/spawn.rs +++ b/src/tools/sessions_spawn/spawn.rs @@ -1046,7 +1046,10 @@ impl SessionsSpawnTool { // same owner to stop. A cascade additionally signals the worker's // process group through the child row `run_sub_agent_process` // registers underneath. - let sub_agent_parent = crate::runtime::registry::current_work_id(); + // Parented to the enclosing turn, not the launching tool call: that row + // is gone once the call returns, which would cut this run out of a + // cascading cancel of the root. + let sub_agent_parent = crate::runtime::registry::current_owner_work_id(); let sub_agent_label = process_agent_id .clone() .unwrap_or_else(|| "sub-agent (process)".to_string()); @@ -1755,9 +1758,9 @@ impl SessionsSpawnTool { } // Registry row for this run. Parent captured on the spawning task, which - // is the tool call that requested the spawn; a spawned task inherits no - // task-locals of its own. - let sub_agent_parent = crate::runtime::registry::current_work_id(); + // is the enclosing turn (not the launching tool call, which is gone once + // it returns); a spawned task inherits no task-locals of its own. + let sub_agent_parent = crate::runtime::registry::current_owner_work_id(); let sub_agent_label = agent_label_for_registry.unwrap_or_else(|| "sub-agent".to_string()); let mut sub_agent_work = crate::runtime::registry::register_sub_agent(&sub_agent_label, &rid, sub_agent_parent, batch_id, None); From b1f0e4f28aa5e1a4389d8cf5a984379de1f2230a Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:26:16 +0400 Subject: [PATCH 0096/1567] fix(sessions): record a requested stop of a process child as cancelled A kill that reaches a process-mode child through the registry or the kill action reaps the worker, and recovery then finds no completion record. The run was published as unconfirmed with no task event, so the child stayed running in the read model. When the stop was requested and recovery found no completion, the interrupted outcome is now converted to a terminated one that carries the recovered partial usage, and the parent records task.cancelled for it. --- src/tools/sessions_spawn/mod.rs | 1 + src/tools/sessions_spawn/owned_process.rs | 6 ++- src/tools/sessions_spawn/process_mode.rs | 16 +++++-- src/tools/sessions_spawn/requested_stop.rs | 53 ++++++++++++++++++++++ src/tools/sessions_spawn/spawn.rs | 12 ++--- 5 files changed, 76 insertions(+), 12 deletions(-) create mode 100644 src/tools/sessions_spawn/requested_stop.rs diff --git a/src/tools/sessions_spawn/mod.rs b/src/tools/sessions_spawn/mod.rs index 8703c8ecf..a1c22425c 100644 --- a/src/tools/sessions_spawn/mod.rs +++ b/src/tools/sessions_spawn/mod.rs @@ -34,6 +34,7 @@ mod owned_process; mod process_control; mod process_mode; mod provider; +mod requested_stop; mod scope; mod spawn; mod task_mode; diff --git a/src/tools/sessions_spawn/owned_process.rs b/src/tools/sessions_spawn/owned_process.rs index c2d4de1ae..3dd7be413 100644 --- a/src/tools/sessions_spawn/owned_process.rs +++ b/src/tools/sessions_spawn/owned_process.rs @@ -179,7 +179,11 @@ pub(super) enum ProcessWorkerOutcome { detail: String, usage: process_terminal::RecoveredWorkerUsage, }, - Terminated(String), + /// The stop was requested; `usage` is the partial provider usage recovered. + Terminated { + reason: String, + usage: Vec, + }, TerminationFailed(String), /// The worker's stdout reached EOF without a `WorkerResult` line. /// diff --git a/src/tools/sessions_spawn/process_mode.rs b/src/tools/sessions_spawn/process_mode.rs index ccc25dfb0..ef64a3184 100644 --- a/src/tools/sessions_spawn/process_mode.rs +++ b/src/tools/sessions_spawn/process_mode.rs @@ -313,7 +313,10 @@ pub(super) async fn run_sub_agent_process( if let Some(reason) = process_control.termination_reason() { cleanup_process_worker_workspace(run_id, &worker_workspace, keep_workspace); - return Ok(ProcessWorkerOutcome::Terminated(reason)); + return Ok(ProcessWorkerOutcome::Terminated { + reason, + usage: Vec::new(), + }); } #[cfg(not(test))] @@ -603,6 +606,7 @@ pub(super) async fn run_sub_agent_process( return Err(error); } }; + let stop = super::requested_stop::requested_stop_reason(process_control, worker_registration.kill_requested()); let (status, stdout, stderr) = match owned_phase { OwnedProcessPhase::Exited { status, stdout, stderr } => { worker_registration.mark_reaped(); @@ -650,7 +654,7 @@ pub(super) async fn run_sub_agent_process( ) .await; cleanup_process_worker_workspace(run_id, &worker_workspace, keep_workspace); - return recovered; + return super::requested_stop::settle_requested_stop(run_id, recovered, stop.as_deref()); } if let Some(generation) = &operator_generation { let recovered = recover_operator_interruption( @@ -664,10 +668,13 @@ pub(super) async fn run_sub_agent_process( ) .await; cleanup_process_worker_workspace(run_id, &worker_workspace, keep_workspace); - return recovered; + return super::requested_stop::settle_requested_stop(run_id, recovered, stop.as_deref()); } cleanup_process_worker_workspace(run_id, &worker_workspace, keep_workspace); - return Ok(ProcessWorkerOutcome::Terminated(reason)); + return Ok(ProcessWorkerOutcome::Terminated { + reason, + usage: Vec::new(), + }); } OwnedProcessPhase::TerminationFailed(error) => { tracing::warn!( @@ -842,6 +849,7 @@ pub(super) async fn run_sub_agent_process( } } .await; + let outcome = super::requested_stop::settle_requested_stop(run_id, outcome, stop.as_deref()); // The leader is confirmed reaped here, including decode/verification // failures. Unconfirmed cleanup branches above retain their workspace. cleanup_process_worker_workspace(run_id, &worker_workspace, keep_workspace); diff --git a/src/tools/sessions_spawn/requested_stop.rs b/src/tools/sessions_spawn/requested_stop.rs new file mode 100644 index 000000000..af0b434bc --- /dev/null +++ b/src/tools/sessions_spawn/requested_stop.rs @@ -0,0 +1,53 @@ +//! A run that was stopped on request ends as stopped, not as unconfirmed. +//! +//! When the stop was asked for (the tool `kill` action, or a registry kill of +//! the run or of its worker row) the worker group is killed and its leader +//! reaped, and the post-exit recovery has already looked for a signed +//! completion record. If it found none, no writer is left that could still +//! produce one, so the outcome is known: the run was stopped. Only the provider +//! usage that recovery found is partial. A stop nobody asked for (owner exit, a +//! crash) is not converted and stays unconfirmed. + +use super::{KILLED_BY_USER_REASON, ProcessRunControl, ProcessWorkerOutcome}; + +/// The reason to record when the run's stop was requested, if it was. +/// +/// The registry marks the worker row `kill_requested` before it signals the +/// group, while the control's termination reason is set only later by the +/// registry bridge, so the row flag covers a kill that has no reason yet. +pub(super) fn requested_stop_reason(control: &ProcessRunControl, worker_row_killed: bool) -> Option { + match control.termination_reason() { + Some(reason) if reason == KILLED_BY_USER_REASON => Some(reason), + Some(_) => None, + None => worker_row_killed.then(|| KILLED_BY_USER_REASON.to_owned()), + } +} + +/// Convert an unconfirmed ending into `Terminated` when the stop was requested. +/// Every other outcome passes through; a completion that recovery verified +/// after the reap is never replaced. +pub(super) fn settle_requested_stop( + run_id: &str, + outcome: anyhow::Result, + reason: Option<&str>, +) -> anyhow::Result { + let Some(reason) = reason else { + return outcome; + }; + let (usage, unfinished_segments) = match outcome { + Ok(ProcessWorkerOutcome::OrdinaryInterrupted { usage, .. }) + | Ok(ProcessWorkerOutcome::OperatorInterrupted { usage, .. }) => (usage.records, usage.unfinished_segments), + Ok(ProcessWorkerOutcome::ExitedWithoutResult(_)) => (Vec::new(), 0), + other => return other, + }; + tracing::info!( + run_id, + unfinished_segments, + usage_records = usage.len(), + "requested stop settled as terminated" + ); + Ok(ProcessWorkerOutcome::Terminated { + reason: reason.to_owned(), + usage, + }) +} diff --git a/src/tools/sessions_spawn/spawn.rs b/src/tools/sessions_spawn/spawn.rs index 158034481..02104c20f 100644 --- a/src/tools/sessions_spawn/spawn.rs +++ b/src/tools/sessions_spawn/spawn.rs @@ -1262,12 +1262,12 @@ impl SessionsSpawnTool { ProcessFinalization::Natural, ) } - Ok(ProcessWorkerOutcome::Terminated(reason)) => { + Ok(ProcessWorkerOutcome::Terminated { reason, usage }) => { let msg = format!("Sub-agent process terminated: {reason}"); ( SubAgentStatus::Failed(reason), msg, - Vec::new(), + usage, ProcessFinalization::Terminated, ) } @@ -1394,11 +1394,9 @@ impl SessionsSpawnTool { &result_text, &status, &process_lineage, - if finalization == ProcessFinalization::Terminated { - Some("task.killed") - } else { - worker_cancelled.then_some("task.cancelled") - }, + // A `Terminated` run is a requested stop: recorded as cancelled. + (finalization == ProcessFinalization::Terminated || worker_cancelled) + .then_some("task.cancelled"), Some(crate::session_worker::protocol::worker_result_key(&rid)), ) .await; From bfb45fd4dae1e1ad18f1babf8cedecf303dc591a Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:50:02 +0400 Subject: [PATCH 0097/1567] fix(runtime): kill the process groups of a session worker's shell commands with the worker --- src/runtime/descendant_groups.rs | 93 +++++++++++++++++++++++ src/runtime/mod.rs | 2 + src/runtime/registry.rs | 13 ++++ src/tools/sessions_spawn/owned_process.rs | 4 + src/tools/sessions_spawn/process_mode.rs | 7 +- 5 files changed, 117 insertions(+), 2 deletions(-) create mode 100644 src/runtime/descendant_groups.rs diff --git a/src/runtime/descendant_groups.rs b/src/runtime/descendant_groups.rs new file mode 100644 index 000000000..1a2e87bd5 --- /dev/null +++ b/src/runtime/descendant_groups.rs @@ -0,0 +1,93 @@ +//! Process groups of a worker's descendants that live outside the worker's own group. +//! +//! The shell tool starts every command in its own process group, so a `killpg` +//! of a session worker's group never reaches those commands: they are +//! reparented to init and keep running. The killer takes a snapshot of the +//! worker's process tree before it signals the worker (afterwards the parent +//! links are gone) and signals every group found in it. Nothing here depends on +//! the worker running code after `SIGKILL`. + +use std::collections::{HashMap, HashSet}; + +/// Group ids of all live descendants of `root_pid` that are not in `root_pgid` +/// and are neither init nor this process's own group. +#[cfg(unix)] +pub(crate) fn foreign_groups_of(root_pid: i32, root_pgid: i32) -> Vec { + // SAFETY: `getpgrp` takes no arguments, cannot fail and touches no memory. + #[allow(unsafe_code)] + let own_pgid = unsafe { libc::getpgrp() }; + let table = process_table(); + let mut seen: HashSet = HashSet::from([root_pid]); + let mut frontier = vec![root_pid]; + let mut groups: Vec = Vec::new(); + while let Some(parent) = frontier.pop() { + for (pid, (ppid, pgid)) in &table { + if *ppid == parent && seen.insert(*pid) { + frontier.push(*pid); + if *pgid > 1 && *pgid != root_pgid && *pgid != own_pgid && !groups.contains(pgid) { + groups.push(*pgid); + } + } + } + } + groups +} + +/// `SIGKILL` each group; errors (group already gone) are ignored. +#[cfg(unix)] +#[allow(unsafe_code)] +pub(crate) fn kill_groups(groups: &[i32]) { + for pgid in groups.iter().copied().filter(|pgid| *pgid > 1) { + // SAFETY: `pgid` is a positive group id read from the process table; + // `killpg` only delivers a signal and dereferences no pointer. + unsafe { libc::killpg(pgid, libc::SIGKILL) }; + } +} + +/// pid -> (ppid, pgid) for every visible process. +#[cfg(target_os = "linux")] +fn process_table() -> HashMap { + let mut table = HashMap::new(); + let Ok(entries) = std::fs::read_dir("/proc") else { + return table; + }; + for entry in entries.flatten() { + let Some(pid) = entry.file_name().to_str().and_then(|name| name.parse::().ok()) else { + continue; + }; + let Ok(stat) = std::fs::read_to_string(entry.path().join("stat")) else { + continue; + }; + // The command name is parenthesised and may contain spaces or parens; + // the fields after the last `)` are: state ppid pgrp ... + let Some((_, rest)) = stat.rsplit_once(')') else { + continue; + }; + let mut fields = rest.split_whitespace().skip(1); + let ppid = fields.next().and_then(|field| field.parse::().ok()); + let pgid = fields.next().and_then(|field| field.parse::().ok()); + if let (Some(ppid), Some(pgid)) = (ppid, pgid) { + table.insert(pid, (ppid, pgid)); + } + } + table +} + +/// pid -> (ppid, pgid) for every visible process, read through `ps`. +#[cfg(all(unix, not(target_os = "linux")))] +fn process_table() -> HashMap { + let mut table = HashMap::new(); + let Ok(output) = std::process::Command::new("ps") + .args(["-ax", "-o", "pid=,ppid=,pgid="]) + .output() + else { + return table; + }; + for line in String::from_utf8_lossy(&output.stdout).lines() { + let mut fields = line.split_whitespace().map(|field| field.parse::().ok()); + if let (Some(Some(pid)), Some(Some(ppid)), Some(Some(pgid))) = (fields.next(), fields.next(), fields.next()) { + table.insert(pid, (ppid, pgid)); + } + } + table +} diff --git a/src/runtime/mod.rs b/src/runtime/mod.rs index 8731eafa1..3ef021859 100644 --- a/src/runtime/mod.rs +++ b/src/runtime/mod.rs @@ -19,6 +19,8 @@ pub(crate) mod lesson_delivery; pub(crate) mod logical_clock; pub mod native; pub(crate) mod operator_notice; +#[cfg(unix)] +pub(crate) mod descendant_groups; pub mod registry; pub mod remote_tree; mod shell_cgroup; diff --git a/src/runtime/registry.rs b/src/runtime/registry.rs index ceb167716..0787d25c1 100644 --- a/src/runtime/registry.rs +++ b/src/runtime/registry.rs @@ -62,6 +62,10 @@ use tokio_util::sync::CancellationToken; /// unrelated tool calls almost never contend on the same lock. const SHARD_COUNT: usize = 16; +/// Label prefix of the process row of a `sessions_spawn` session worker; the +/// killer also ends the process groups of that worker's descendants. +pub const WORKER_PROCESS_LABEL_PREFIX: &str = "session-worker "; + /// How long [`kill`] waits for a target to actually disappear before reporting /// the request as merely *sent*. /// @@ -967,10 +971,19 @@ fn request_termination(slot: &Slot) -> bool { #[allow(unsafe_code)] fn kill_process_group(slot: &Slot) -> bool { if let Some(pgid) = slot.pgid.filter(|pgid| *pgid > 0) { + // A session worker's shell commands run in groups of their own that + // `killpg(pgid)` cannot reach, so snapshot them before the worker dies. + let foreign = match slot.pid.and_then(|pid| i32::try_from(pid).ok()) { + Some(pid) if slot.name.starts_with(WORKER_PROCESS_LABEL_PREFIX) => { + crate::runtime::descendant_groups::foreign_groups_of(pid, pgid) + } + _ => Vec::new(), + }; // SAFETY: `pgid` is the positive group id of a child spawned with // `process_group(0)`. `killpg` only delivers a signal; it dereferences // no pointer and the call cannot invalidate any Rust invariant. unsafe { libc::killpg(pgid, libc::SIGKILL) }; + crate::runtime::descendant_groups::kill_groups(&foreign); return true; } if let Some(pid) = slot.pid.and_then(|pid| i32::try_from(pid).ok()).filter(|pid| *pid > 0) { diff --git a/src/tools/sessions_spawn/owned_process.rs b/src/tools/sessions_spawn/owned_process.rs index 3dd7be413..ba659aa43 100644 --- a/src/tools/sessions_spawn/owned_process.rs +++ b/src/tools/sessions_spawn/owned_process.rs @@ -282,9 +282,13 @@ impl OwnedProcessGroup { } #[cfg(unix)] { + // The worker's shell commands run in groups of their own; snapshot + // them before the kill, which orphans them. + let foreign = crate::runtime::descendant_groups::foreign_groups_of(self.pgid, self.pgid); // SAFETY: `pgid` is captured from a child spawned with // `process_group(0)` and is never exposed outside its owner. let rc = unsafe { libc::killpg(self.pgid, libc::SIGKILL) }; + crate::runtime::descendant_groups::kill_groups(&foreign); if rc != 0 { let error = std::io::Error::last_os_error(); if error.raw_os_error() != Some(libc::ESRCH) { diff --git a/src/tools/sessions_spawn/process_mode.rs b/src/tools/sessions_spawn/process_mode.rs index ef64a3184..1b4115f38 100644 --- a/src/tools/sessions_spawn/process_mode.rs +++ b/src/tools/sessions_spawn/process_mode.rs @@ -417,8 +417,11 @@ pub(super) async fn run_sub_agent_process( .filter(|pid| *pid > 0); #[cfg(not(unix))] let worker_pgid: Option = None; - let mut worker_registration = - crate::runtime::registry::register_process(&format!("session-worker {run_id}"), child.id(), worker_pgid); + let mut worker_registration = crate::runtime::registry::register_process( + &format!("{}{run_id}", crate::runtime::registry::WORKER_PROCESS_LABEL_PREFIX), + child.id(), + worker_pgid, + ); #[cfg(test)] if let Some(control) = protocol { control.diagnostic.lock().registry_id = Some(worker_registration.id().raw()); From 0d79bde5095dbb746fa03d9d428a5c9e2a50ab3a Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:17:50 +0400 Subject: [PATCH 0098/1567] fix(sessions): settle a worker that exits on its own without a result as failed When no stop was requested and the worker leader is reaped with an empty stdout, post-exit recovery has already looked for a signed completion record and no writer remains. The parent now records task.failed (exit status or signal only), finalizes the run and releases its registry rows instead of leaving it unconfirmed. --- src/tools/sessions_spawn/mod.rs | 1 + src/tools/sessions_spawn/owned_process.rs | 6 +++ src/tools/sessions_spawn/process_mode.rs | 7 +++ src/tools/sessions_spawn/spawn.rs | 5 ++ src/tools/sessions_spawn/unrequested_exit.rs | 51 ++++++++++++++++++++ 5 files changed, 70 insertions(+) create mode 100644 src/tools/sessions_spawn/unrequested_exit.rs diff --git a/src/tools/sessions_spawn/mod.rs b/src/tools/sessions_spawn/mod.rs index a1c22425c..f2eea3692 100644 --- a/src/tools/sessions_spawn/mod.rs +++ b/src/tools/sessions_spawn/mod.rs @@ -35,6 +35,7 @@ mod process_control; mod process_mode; mod provider; mod requested_stop; +mod unrequested_exit; mod scope; mod spawn; mod task_mode; diff --git a/src/tools/sessions_spawn/owned_process.rs b/src/tools/sessions_spawn/owned_process.rs index ba659aa43..66218d228 100644 --- a/src/tools/sessions_spawn/owned_process.rs +++ b/src/tools/sessions_spawn/owned_process.rs @@ -185,6 +185,12 @@ pub(super) enum ProcessWorkerOutcome { usage: Vec, }, TerminationFailed(String), + /// The worker died on its own (no stop requested) and recovery found no + /// completion record; `usage` is the partial provider usage recovered. + ExitedUnrequested { + detail: String, + usage: Vec, + }, /// The worker's stdout reached EOF without a `WorkerResult` line. /// /// This is the process-mode half of "the run died where the parent cannot diff --git a/src/tools/sessions_spawn/process_mode.rs b/src/tools/sessions_spawn/process_mode.rs index 1b4115f38..f588f1b0e 100644 --- a/src/tools/sessions_spawn/process_mode.rs +++ b/src/tools/sessions_spawn/process_mode.rs @@ -730,6 +730,8 @@ pub(super) async fn run_sub_agent_process( } } } + // Empty stdout is the only case converted below, so note it before recovery. + let silent_exit = matches!(outcome, Ok(ProcessWorkerOutcome::ExitedWithoutResult(_))).then_some(status); let outcome = async { // A cleanup-confirmed worker can exit after journaling but before its // stdout result reaches the parent. Reuse its exact launch authority. @@ -853,6 +855,11 @@ pub(super) async fn run_sub_agent_process( } .await; let outcome = super::requested_stop::settle_requested_stop(run_id, outcome, stop.as_deref()); + // Read late: a stop requested while recovery ran must not be misread as a crash. + let unrequested = + stop.is_none() && process_control.termination_reason().is_none() && !worker_registration.kill_requested(); + let outcome = + super::unrequested_exit::settle_unrequested_exit(run_id, outcome, silent_exit.filter(|_| unrequested)); // The leader is confirmed reaped here, including decode/verification // failures. Unconfirmed cleanup branches above retain their workspace. cleanup_process_worker_workspace(run_id, &worker_workspace, keep_workspace); diff --git a/src/tools/sessions_spawn/spawn.rs b/src/tools/sessions_spawn/spawn.rs index 02104c20f..332a1a6b4 100644 --- a/src/tools/sessions_spawn/spawn.rs +++ b/src/tools/sessions_spawn/spawn.rs @@ -1298,6 +1298,11 @@ impl SessionsSpawnTool { ProcessFinalization::Natural, ) } + Ok(ProcessWorkerOutcome::ExitedUnrequested { detail, usage }) => { + let error = exited_without_result_reason(&detail); + (SubAgentStatus::Failed(error.clone()), format!("Sub-agent process error: {error}"), + usage, ProcessFinalization::Natural) + } Ok(ProcessWorkerOutcome::TerminationFailed(error)) => { let msg = format!("Sub-agent process termination failed: {error}"); ( diff --git a/src/tools/sessions_spawn/unrequested_exit.rs b/src/tools/sessions_spawn/unrequested_exit.rs new file mode 100644 index 000000000..defa84340 --- /dev/null +++ b/src/tools/sessions_spawn/unrequested_exit.rs @@ -0,0 +1,51 @@ +//! A worker that died on its own, with its owner alive, ends as failed. +//! +//! When nobody asked for a stop and the worker's leader has been reaped with +//! no result line on its pipes, post-exit recovery has already looked for a +//! signed completion record. Nothing is left that could still write one: the +//! only writer is the worker itself, it is reaped, and its output pipes are +//! drained. So the parent settles the run as failed instead of leaving it +//! unconfirmed (which clients show as `running` forever). An exit that follows +//! a requested stop, an owner exit or an owner loss is not converted here. + +use super::{ProcessWorkerOutcome, describe_worker_exit}; +use std::process::ExitStatus; + +/// Convert an interrupted ending into `ExitedUnrequested` when the worker +/// exited with an empty stdout (`silent_exit` is its status) and no stop was +/// requested. Every other outcome passes through, so a completion that +/// recovery verified after the reap is never replaced. +pub(super) fn settle_unrequested_exit( + run_id: &str, + outcome: anyhow::Result, + silent_exit: Option, +) -> anyhow::Result { + let Some(status) = silent_exit else { + return outcome; + }; + let (usage, unfinished_segments) = match outcome { + Ok(ProcessWorkerOutcome::OrdinaryInterrupted { usage, .. }) + | Ok(ProcessWorkerOutcome::OperatorInterrupted { usage, .. }) => (usage.records, usage.unfinished_segments), + other => return other, + }; + #[cfg(unix)] + let signal = { + use std::os::unix::process::ExitStatusExt as _; + status.signal() + }; + #[cfg(not(unix))] + let signal: Option = None; + tracing::info!( + run_id, + exit_code = status.code(), + signal, + unfinished_segments, + usage_records = usage.len(), + "unrequested worker exit settled as failed" + ); + Ok(ProcessWorkerOutcome::ExitedUnrequested { + // Status only: the worker's stderr is not copied into the record. + detail: describe_worker_exit(status, ""), + usage, + }) +} From d2f4d68e923c5095504707264d2f6a8aa681188a Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:20:52 +0400 Subject: [PATCH 0099/1567] fix(tools): refuse join from a non-launching session that cannot see the batch members' results --- src/tools/sessions_spawn/batch.rs | 37 ++++++++++++++++++++--- src/tools/sessions_spawn/batch_journal.rs | 1 + 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/src/tools/sessions_spawn/batch.rs b/src/tools/sessions_spawn/batch.rs index 9cbaf0a14..b8a462848 100644 --- a/src/tools/sessions_spawn/batch.rs +++ b/src/tools/sessions_spawn/batch.rs @@ -29,6 +29,10 @@ pub(super) struct BatchRoster { /// The owner the batch was launched for (OWNER-VIS): `join` answers a /// batch only to a caller whose run scope admits this owner. pub(super) owner_id: Option, + /// The session that launched the batch, when known. Only the durable plan + /// records it; `join` uses it to tell the spawning session from another + /// session of the same owner. + pub(super) parent_session: Option, pub(super) members: Vec, } @@ -583,6 +587,9 @@ impl SessionsSpawnTool { batch_id: batch_id.clone(), owner_id: batch_owner, agent_partition: batch_partition, + parent_session: batch_caller + .as_ref() + .map(|caller| caller.context().envelope.session_key.clone()), members: roster, }); } @@ -675,7 +682,7 @@ impl SessionsSpawnTool { } RunBatchLookup::NotARun => {} } - let mut members = self + let (mut members, mut launcher_session) = self .journal_or_registry_members(source_fabric.as_ref(), &batch, owner_scope, &mut trace) .await?; // Only an id that is no known batch is looked up as a run id, so a @@ -686,7 +693,7 @@ impl SessionsSpawnTool { Self::scan_batch_of_run(source_fabric.as_ref(), None, batch_id, owner_scope).await? { batch = found; - members = self + (members, launcher_session) = self .journal_or_registry_members(source_fabric.as_ref(), &batch, owner_scope, &mut trace) .await?; } @@ -704,6 +711,26 @@ impl SessionsSpawnTool { } drop(trace); + // The durable plan admits every session of the owner, but member + // results live only in the registry of the process that ran them. A + // session other than the launcher that cannot find a member's row + // would be handed a summary of `no_result` entries; refuse instead. + let caller_session = caller.as_ref().map(|caller| caller.context().envelope.session_key.as_str()); + if let (Some(launcher), Some(current)) = (launcher_session.as_deref(), caller_session) { + if launcher != current { + let runs = self.active_runs.read().await; + if members.iter().any(|member| !runs.iter().any(|run| run.id == member.run_id)) { + return Ok(ToolResult { + success: false, + output: String::new(), + error: Some(format!( + "Unknown batch '{batch_id}': no sub-agent run in this session carries that batch id. \ + join takes the batch_id returned by spawn_batch, from the session that launched it." + )), + }); + } + } + } let settled = join_batch_members(&self.active_runs, &members).await; Ok(ToolResult { success: true, @@ -720,7 +747,7 @@ impl SessionsSpawnTool { batch: &str, owner_scope: &sessions_read_model::RunOwnerScope, trace: &mut JoinTrace, - ) -> anyhow::Result> { + ) -> anyhow::Result<(Vec, Option)> { let recorded = if let Some(fabric) = fabric { batch_journal::read(fabric, std::path::Path::new(fabric.workspace_id()), batch, owner_scope).await? } else { @@ -728,8 +755,8 @@ impl SessionsSpawnTool { }; trace.journal_roster |= recorded.is_some(); Ok(match recorded { - Some(roster) => roster.members, - None => self.batch_members(batch, owner_scope).await, + Some(roster) => (roster.members, roster.parent_session), + None => (self.batch_members(batch, owner_scope).await, None), }) } diff --git a/src/tools/sessions_spawn/batch_journal.rs b/src/tools/sessions_spawn/batch_journal.rs index 0af4ddb26..85fa880ff 100644 --- a/src/tools/sessions_spawn/batch_journal.rs +++ b/src/tools/sessions_spawn/batch_journal.rs @@ -288,6 +288,7 @@ pub(super) async fn read( batch_id: batch.to_owned(), owner_id: Some(plan_fields.owner), agent_partition: plan_fields.ordinary_source.partition, + parent_session: Some(plan_fields.ordinary_source.parent_session), members: plan_fields .members .into_iter() From 6e13266f0ce4a75dc1d79a46eaea383f890007ee Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:45:53 +0400 Subject: [PATCH 0100/1567] refactor(sessions): split spawn.rs into process and task launch files Move the process-mode and task-mode launch bodies of execute_spawn_with_id into process_launch.rs and task_launch.rs. The values resolved before the mode split travel in a SpawnLaunch struct; function bodies are moved verbatim. The compaction producer scanner now anchors on the resolved window clone that stays in execute_spawn_with_id. --- src/tools/sessions_spawn/mod.rs | 2 + src/tools/sessions_spawn/process_launch.rs | 700 +++++++++++ src/tools/sessions_spawn/spawn.rs | 1258 ++----------------- src/tools/sessions_spawn/task_launch.rs | 560 +++++++++ tests/architecture_boundaries/compaction.rs | 2 +- 5 files changed, 1376 insertions(+), 1146 deletions(-) create mode 100644 src/tools/sessions_spawn/process_launch.rs create mode 100644 src/tools/sessions_spawn/task_launch.rs diff --git a/src/tools/sessions_spawn/mod.rs b/src/tools/sessions_spawn/mod.rs index f2eea3692..fc70ceb6d 100644 --- a/src/tools/sessions_spawn/mod.rs +++ b/src/tools/sessions_spawn/mod.rs @@ -37,7 +37,9 @@ mod provider; mod requested_stop; mod unrequested_exit; mod scope; +mod process_launch; mod spawn; +mod task_launch; mod task_mode; #[cfg(test)] pub(crate) use task_mode::configure_operator_child_approval; diff --git a/src/tools/sessions_spawn/process_launch.rs b/src/tools/sessions_spawn/process_launch.rs new file mode 100644 index 000000000..0b2f59b66 --- /dev/null +++ b/src/tools/sessions_spawn/process_launch.rs @@ -0,0 +1,700 @@ +//! Process-mode launch of one sub-agent run: worker setup, registry row, and the monitor task that +//! owns the OS child until it ends. + +use super::{ + SessionsSpawnTool, AnnounceOrigin, HistoryEntry, OutboundNotice, OwnerLossReason, ProcessFinalization, ProcessModeRunSeed, + ProcessRunControl, ProcessWorkerOutcome, SPAWN_EXECUTION_CONTEXT, STEER_CHANNEL_CAPACITY, SpawnExecutionContext, + SubAgentStatus, commit_process_terminal_state, deliver_or_withhold_notice, exited_without_result_reason, + format_announce_message, new_process_mode_run, process_terminal, record_owner_loss_terminal, + record_spawn_result_event_keyed, register_killable_process_run, resolve_worker_workspace_root, + run_sub_agent_process, spawn_started_text, sub_agent_reported_failure, watch_process_mode_monitor, +}; +use super::spawn::{SpawnLaunch, SpawnOutcome, policy_at_level}; +use anyhow::Context as _; +use std::sync::Arc; +use tokio::sync::RwLock; + +impl SessionsSpawnTool { + /// Launch the run as an OS-process worker once `execute_spawn_with_id` has resolved + /// the request, provider route and admitted source into a [`SpawnLaunch`]. + pub(super) async fn launch_process_run(&self, launch: SpawnLaunch<'_>) -> anyhow::Result { + let SpawnLaunch { + operator_source, + message_input, + message_permit, + caller, + child_delegation, + ordinary_publication, + child_model_config, + launch_security, + child_level, + spawn_config, + task, + process_memory_strategy, + spawn_scope, + parent_exec_ctx, + spawn_depth, + parent_run_id, + inherited_channel_exclusions, + run_id, + session_scope_key, + selected_agent, + recipient, + run_channel_name, + operator_channel, + announce_result, + memory_fabric, + process_memory_backend, + resolved_provider_name, + resolved_model, + child_requested_model, + selected_route_hint, + route_source_provider, + child_credential, + route_credential, + route_uses_root_connection, + direct_uses_root_connection, + temperature_override, + resolved_temperature, + ordinary_binding, + spawn_scope_for_event, + run_lineage, + allowed_tools, + process_config_source, + source_receipt, + batch_id, + process_compaction_config, + .. + } = launch; + let process_parent_frames = caller.as_ref().and_then(|caller| { + let context = caller.context(); + context + .live_turn + .as_ref() + .map(|live| live.0.frames(&context.envelope, &std::collections::HashSet::new())) + }); + let (process_config_dir, process_config_generation) = + process_config_source.ok_or_else(|| anyhow::anyhow!("process config source was not resolved"))?; + let process_provider_selection = if ordinary_publication.is_some() { + let (provider, model) = child_requested_model + .as_ref() + .context("process child selection missing")?; + Some(crate::session_worker::protocol::WorkerProviderSelection { + provider: provider.clone(), + model: model.clone(), + credential: child_credential.clone().context("process child credential missing")?, + }) + } else { + None + }; + let process_source_launch = ordinary_publication + .map(|publication| { + publication.capture_process_launch( + caller.as_ref().context("ordinary process caller missing")?, + ordinary_binding + .as_deref() + .context("ordinary process binding missing")?, + &spawn_scope_for_event, + task, + source_receipt.clone(), + process_provider_selection + .clone() + .context("ordinary process selection missing")?, + process_config_generation.clone(), + ) + }) + .transpose()? + .map(|launch| crate::runtime::operator_spawn::process::ProcessSourceLaunch::Ordinary(Box::new(launch))); + let process_source_launch = match &operator_source { + Some(source) => Some(crate::runtime::operator_spawn::process::ProcessSourceLaunch::Operator( + Box::new(source.capture_process( + &spawn_scope_for_event, + task, + source_receipt.clone(), + process_config_generation.clone(), + )?), + )), + None => process_source_launch, + }; + let process_approval_relay = crate::session_worker::approval::relay_context::RelaySeedInputs { + caller: caller.as_ref(), + binding: ordinary_binding.as_deref(), + resolvers: self.approval_resolver_factory.as_ref(), + scope: &spawn_scope_for_event, + task, + receipt: source_receipt.as_deref(), + security: launch_security, + level: child_level, + run_id: &run_id, + } + .seed()?; + let temperature = resolved_temperature; + let history_arc: Arc>> = + Arc::new(RwLock::new(super::continuation::seed_history())); + let process_control = ProcessRunControl::new(); + let stop_control = Arc::clone(&process_control); + let runtime_handle = tokio::runtime::Handle::try_current()?; + let message_turn = super::message_lifetime::retain( + child_model_config, + message_input.as_ref(), + &self.active_runs, + Arc::new(move || { + let control = Arc::clone(&stop_control); + runtime_handle.spawn(async move { + let _ = control.request_termination("history_erased").await; + }); + }), + )?; + // Process-mode steering: the sender lives in the registry exactly as + // it does for task mode, so `sessions_send` / `sessions_spawn:steer` + // reach an OS-process sub-agent through the same code path. The + // receiver is handed to the child owner, which forwards each message + // as a line-delimited control frame on the worker's stdin. + let (process_steer_tx, process_steer_rx) = tokio::sync::mpsc::channel::(STEER_CHANNEL_CAPACITY); + // Minted here, on the *spawning* task, so the run's beat is parented + // on the caller's: a parent legitimately blocked on a working child + // must not look silent to its own hang detector. A beat minted + // inside the spawned monitor would have no parent at all, because + // task-locals do not cross `tokio::spawn`. + let process_progress = crate::agent::idle::child_beat(); + + { + let mut runs = self.active_runs.write().await; + let mut run = new_process_mode_run(ProcessModeRunSeed { + id: run_id.clone(), + task: task.to_string(), + lineage: &run_lineage, + recipient: recipient.clone(), + channel_name: run_channel_name.clone(), + process_control: process_control.clone(), + history: history_arc.clone(), + steer_tx: process_steer_tx.clone(), + parent_run_id: parent_run_id.clone(), + session_scope_key: session_scope_key.clone(), + spawn_depth, + // Recursive delegation status is issued by no parent (P2-G4). + delegation: None, + progress: Arc::clone(&process_progress), + batch_id: batch_id.map(str::to_string), + }); + run.agent_partition = spawn_scope_for_event.agent_partition.clone(); + super::continuation::register(&mut runs, run)?; + } + + let model = resolved_model; + let provider_name = resolved_provider_name; + let route_hint = selected_route_hint; + let workspace_root = child_model_config.workspace_dir.clone(); + let worker_workspace_root = + resolve_worker_workspace_root(spawn_config.worker_workspace_root.as_deref(), &workspace_root); + let active_runs = self.active_runs.clone(); + // Resolve the announce channel from the *per-turn* channel name bound + // to this run (the launching message's scope), not the shared active + // channel — so a concurrently-processed message cannot mis-route this + // run's result. Falls back to the active channel when no scope name. + let channel = match &operator_channel { + Some(channel) => Arc::clone(channel), + None => self.resolve_announce_channel(run_channel_name.as_deref()).await, + }; + let keep_workspace = !spawn_config.cleanup_on_complete; + let process_agent_id = selected_agent.as_ref().map(|(name, _)| name.clone()); + let identity_dir = selected_agent.as_ref().and_then(|(_, cfg)| { + cfg.identity_dir + .as_deref() + .map(str::trim) + .filter(|value| !value.is_empty()) + .map(str::to_string) + }); + // Process workers need the same explicit agent contract as task-mode + // children. Without carrying this prompt into the signed manifest, + // a named agent's tool-use and completion instructions silently vanish + // at the OS-process boundary. + let process_system_prompt = selected_agent.as_ref().and_then(|(_, cfg)| { + cfg.system_prompt + .as_deref() + .map(str::trim) + .filter(|value| !value.is_empty()) + .map(str::to_string) + }); + let task_owned = task.to_string(); + let rid = run_id.clone(); + let process_scope = spawn_scope.clone(); + // Announcement gate inputs for the process-mode monitor. Same three + // values the task-mode branch below captures, handed to the same + // `deliver_or_withhold_notice`. + let process_announce_security = policy_at_level(launch_security, child_level); + let process_announce_origin = AnnounceOrigin::from_scope(spawn_scope.as_ref()); + let process_announce_history = history_arc.clone(); + // The worker's parent is the run its bound input names: the + // publication's spawn run, or the operator source run. A gateway + // Console turn seeds no spawn context, so `parent_run_id` alone is + // None there and the manifest would differ from its issued input. + let process_parent_run_id = spawn_scope_for_event + .parent_run_id + .clone() + .or_else(|| parent_run_id.clone()); + let process_session_scope_key = session_scope_key.clone(); + let process_spawn_depth = spawn_depth; + let process_channel_exclusions = inherited_channel_exclusions.clone(); + let process_event_recording = child_model_config.memory.event_recording_config(); + let process_execution_ctx = SpawnExecutionContext { + task_input: parent_exec_ctx + .as_ref() + .map(|context| context.task_input.clone()) + .unwrap_or_default(), + operator_authority: None, + ordinary_authority: None, + provider_binding: None, + terminal_usage: None, + input_receipt: source_receipt.clone(), + run_id: rid.clone(), + session_scope_key: session_scope_key.clone(), + spawn_depth, + owner_id: run_lineage.owner_id.clone(), + owner_isolated: run_lineage.owner_isolated, + topic_id: run_lineage.topic_id.clone(), + source_message_event_id: run_lineage.source_message_event_id.clone(), + // A spawn-run context (this run may itself spawn): its children + // compute spawn_depth + 1. + is_turn_root: false, + channel_excluded_tools: inherited_channel_exclusions.clone(), + }; + let process_memory_fabric = Some(memory_fabric.clone()); + let process_result_scope = spawn_scope_for_event.clone(); + let process_lineage = run_lineage.clone(); + let process_cost_config = child_model_config.cost.clone(); + let monitor_process_control = process_control.clone(); + + // Registry row for this run. The parent is captured *here*, on the + // spawning task, because a freshly spawned task inherits no + // task-locals. No abort handle is attached: this monitor is the sole + // owner responsible for signalling and reaping the OS child, so + // aborting it would strand the very process a kill is meant to end. + // The row's cooperative token is how a kill reaches it instead — + // see `bridge_registry_kill_to_process_control`, which asks that + // same owner to stop. A cascade additionally signals the worker's + // process group through the child row `run_sub_agent_process` + // registers underneath. + // Parented to the enclosing turn, not the launching tool call: that row + // is gone once the call returns, which would cut this run out of a + // cascading cancel of the root. + let sub_agent_parent = crate::runtime::registry::current_owner_work_id(); + let sub_agent_label = process_agent_id + .clone() + .unwrap_or_else(|| "sub-agent (process)".to_string()); + let mut sub_agent_work = + register_killable_process_run(&sub_agent_label, &rid, sub_agent_parent, batch_id, &process_control); + // Publish this run's steering channel on its registry row so the + // control plane can address it by run id from another entry point. + // Same sender, same bounded queue as `sessions_send` — only the + // lookup is new; see `registry::attach_steer_sender`. + crate::runtime::registry::attach_steer_sender(sub_agent_work.id(), process_steer_tx.clone()); + sub_agent_work.require_cleanup_acknowledgement(); + let process_work_id = sub_agent_work.id(); + let is_ordinary_process = process_source_launch + .as_ref() + .is_some_and(|launch| launch.is_ordinary()); + let ordinary_recovery = if is_ordinary_process { + Some(process_terminal::ordinary::OrdinaryProcessRecovery::new( + process_memory_fabric + .clone() + .context("ordinary recovery fabric missing")?, + workspace_root.clone(), + run_lineage + .owner_id + .clone() + .context("ordinary recovery owner missing")?, + run_id.clone(), + )?) + } else { + None + }; + let is_operator_process = process_source_launch + .as_ref() + .is_some_and(|launch| !launch.is_ordinary()); + let operator_recovery = if is_operator_process { + Some(process_terminal::operator::OperatorProcessRecovery::new( + process_memory_fabric + .clone() + .context("operator recovery fabric missing")?, + workspace_root.clone(), + run_lineage + .owner_id + .clone() + .context("operator recovery owner missing")?, + run_id.clone(), + )?) + } else { + None + }; + let process_worker_mailbox = if let Some(factory) = &self.worker_mailbox { + Some(factory.clone()) + } else if let Some(config) = self + .hint_config + .as_ref() + .filter(|config| config.memory.backend == "sqlite") + { + Some(crate::messaging::worker::WorkerMailboxes::for_config(config)? + as Arc) + } else { + None + }; + let process_batch_id = batch_id.map(str::to_owned); + #[cfg(test)] + let test_worker_executable = self.test_worker_executable.clone(); + let ordinary_terminal = Arc::new(parking_lot::Mutex::new(None)); + let monitor_ordinary_terminal = Arc::clone(&ordinary_terminal); + let operator_terminal = Arc::new(parking_lot::Mutex::new(None)); + let monitor_operator_terminal = Arc::clone(&operator_terminal); + let monitor_active_runs = active_runs.clone(); + let monitor_progress = Arc::clone(&process_progress); + let jh = crate::agent::channel_approval::spawn(crate::runtime::registry::scope_current( + process_work_id, + SPAWN_EXECUTION_CONTEXT.scope( + process_execution_ctx, + crate::agent::idle::scope_beat(Some(Arc::clone(&monitor_progress)), async move { + let _message_permit=message_permit; + let _message_input=message_input; + let _message_turn=message_turn; + async { + tracing::info!(run_id = %rid, "Sub-agent process starting"); + + let worker_result = run_sub_agent_process( + &rid, + &task_owned, + &provider_name, + &model, + route_hint.as_deref(), + route_source_provider.as_deref(), + route_credential.as_ref(), + route_uses_root_connection, + direct_uses_root_connection, + temperature, + temperature_override, + &workspace_root, + &worker_workspace_root, + identity_dir.as_deref(), + process_system_prompt.as_deref(), + &allowed_tools, + keep_workspace, + process_scope.as_ref(), + process_spawn_depth, + &process_session_scope_key, + process_parent_run_id.as_deref(), + process_agent_id.as_deref(), + &process_lineage, + &process_memory_strategy, + &process_memory_backend, + &process_config_dir, + &process_config_generation, + process_event_recording, + &process_compaction_config, + &process_channel_exclusions, + monitor_process_control.as_ref(), + process_steer_rx, + history_arc, + Arc::clone(&monitor_progress), + process_memory_fabric.as_ref(), + process_source_launch, + process_batch_id.as_deref(), + process_worker_mailbox.as_ref(), + process_parent_frames, + process_approval_relay, + #[cfg(test)] + test_worker_executable.as_ref(), + ) + .await; + + // The worker's own account that its work was cancelled; the run's + // status stays `Failed`, only the recorded task event differs. + let mut worker_cancelled = false; + let (status, result_text, token_usage_records, finalization) = match worker_result { + Ok(ProcessWorkerOutcome::OrdinaryVerifiedFinished(completion)) => { + *monitor_ordinary_terminal.lock() = Some(completion.clone()); + let result = completion.result; + worker_cancelled = result.cancelled; + let (status, text) = if result.success { + (SubAgentStatus::Completed(result.output.clone()), result.output) + } else { + let error = super::failure::llm_visible_error(&result.error.unwrap_or_else(|| "worker failed".to_owned())); + (SubAgentStatus::Failed(sub_agent_reported_failure(&error)), format!("Sub-agent error: {error}")) + }; + (status, text, completion.usage, ProcessFinalization::Natural) + } + Ok(ProcessWorkerOutcome::OperatorVerifiedFinished(completion)) => { + *monitor_operator_terminal.lock() = Some(completion.clone()); + let result = completion.result; + worker_cancelled = result.cancelled; + let (status, text) = if result.success { + (SubAgentStatus::Completed(result.output.clone()), result.output) + } else { + let error = super::failure::llm_visible_error(&result.error.unwrap_or_else(|| "worker failed".to_owned())); + (SubAgentStatus::Failed(sub_agent_reported_failure(&error)), format!("Sub-agent error: {error}")) + }; + (status, text, completion.usage, ProcessFinalization::Natural) + } + Ok(ProcessWorkerOutcome::VerifiedStartupFailure(result)) => { + let error = result.error.context("verified startup failure detail missing"); + let error = match error { + Ok(error) => error, + Err(error) => { + tracing::error!(run_id = %rid, error = %error, "verified startup result invalid"); + return; + } + }; + ( + SubAgentStatus::Failed(sub_agent_reported_failure(&error)), + format!("Sub-agent startup error: {error}"), + Vec::new(), + ProcessFinalization::Natural, + ) + } + Ok(ProcessWorkerOutcome::UnverifiedStartupFailure(_)) => { + tracing::error!(run_id = %rid, "unverified startup failure escaped process owner"); + return; + } + Ok(ProcessWorkerOutcome::Finished(result)) if result.success => { + let token_usage_records = result + .tokens_used + .as_ref() + .and_then(|usage| { + crate::llm::route_decision::MeteredTokenUsageRecord::from_parts( + &provider_name, + &model, + usage, + &process_cost_config, + ) + }) + .into_iter() + .collect::>(); + ( + SubAgentStatus::Completed(result.output.clone()), + result.output, + token_usage_records, + ProcessFinalization::Natural, + ) + } + Ok(ProcessWorkerOutcome::Finished(result)) => { + worker_cancelled = result.cancelled; + let error = result.error.unwrap_or_else(|| "worker failed".to_string()); + let msg = format!("Sub-agent error: {error}"); + // `result.error` is a field of the JSON the + // worker itself printed, so it is the run's + // account of the run — quarantined here so + // it cannot pass for a runtime wording in + // `termination_cause`. The announcement + // above still shows the raw account. + ( + SubAgentStatus::Failed(sub_agent_reported_failure(&error)), + msg, + Vec::new(), + ProcessFinalization::Natural, + ) + } + Ok(ProcessWorkerOutcome::Terminated { reason, usage }) => { + let msg = format!("Sub-agent process terminated: {reason}"); + ( + SubAgentStatus::Failed(reason), + msg, + usage, + ProcessFinalization::Terminated, + ) + } + Ok(ProcessWorkerOutcome::OrdinaryInterrupted { detail, usage }) => { + let error = format!("{}; cleanup and provider usage remain unconfirmed; {} visible segments lack a terminal", + exited_without_result_reason(&detail), usage.unfinished_segments); + (SubAgentStatus::Failed(error.clone()), format!("Sub-agent process error: {error}"), + usage.records, ProcessFinalization::Unconfirmed) + } + Ok(ProcessWorkerOutcome::OperatorInterrupted { detail, usage }) => { + let error = format!("{}; cleanup and provider usage remain unconfirmed; {} visible segments lack a terminal", + exited_without_result_reason(&detail), usage.unfinished_segments); + (SubAgentStatus::Failed(error.clone()), format!("Sub-agent process error: {error}"), + usage.records, ProcessFinalization::Unconfirmed) + } + Ok(ProcessWorkerOutcome::ExitedWithoutResult(detail)) => { + // MUTATION GUARD: folding this back into the + // generic parse-error path loses the only + // wording an operator can act on, and folding it + // into "keep waiting" would leave the run + // `Running` for as long as the process lives. + let error = exited_without_result_reason(&detail); + let msg = format!("Sub-agent process error: {error}"); + ( + SubAgentStatus::Failed(error), + msg, + Vec::new(), + ProcessFinalization::Natural, + ) + } + Ok(ProcessWorkerOutcome::ExitedUnrequested { detail, usage }) => { + let error = exited_without_result_reason(&detail); + (SubAgentStatus::Failed(error.clone()), format!("Sub-agent process error: {error}"), + usage, ProcessFinalization::Natural) + } + Ok(ProcessWorkerOutcome::TerminationFailed(error)) => { + let msg = format!("Sub-agent process termination failed: {error}"); + ( + SubAgentStatus::Failed(error), + msg, + Vec::new(), + ProcessFinalization::TerminationFailed, + ) + } + Err(error) => { + // Nothing was spawned for a refused launch, so its + // failure is final rather than left to recovery. + let launch_refused = + error.downcast_ref::().is_some(); + tracing::warn!( + run_id = %rid, + launch_refused, + error = %crate::agent::diagnostics::error_class(&error), + "sub-agent process ended with an error" + ); + let detail = super::failure::llm_visible_error(&format!("{error:#}")); + let msg = format!("Sub-agent process error: {detail}"); + ( + SubAgentStatus::Failed(detail), + msg, + Vec::new(), + if (is_ordinary_process || is_operator_process) && !launch_refused { + ProcessFinalization::Unconfirmed + } else { ProcessFinalization::Natural }, + ) + } + }; + + let announce = format_announce_message(&rid, &status, &result_text); + // An exiting owner waits only for finalization, so the run's + // durable terminal row is written before the commit publishes it. + let owner_exiting = monitor_process_control.termination_reason().as_deref() + == Some(OwnerLossReason::OwnerExited.code()); + if owner_exiting { + if matches!(finalization, ProcessFinalization::Terminated | ProcessFinalization::Unconfirmed) { + if let Some(fabric) = process_memory_fabric.as_ref() { + if let Err(error) = record_owner_loss_terminal( + fabric, + process_result_scope.clone(), + &rid, + OwnerLossReason::OwnerExited, + ) + .await + { + tracing::error!( + run_id = %rid, + error = %crate::agent::diagnostics::error_class(&error), + "owner-exit terminal row remains unconfirmed" + ); + } + } + } else if finalization == ProcessFinalization::Natural { + // Finished on its own within the bound: its real outcome. + record_spawn_result_event_keyed( + process_memory_fabric.as_ref(), + process_result_scope.clone(), + &result_text, + &status, + &process_lineage, + worker_cancelled.then_some("task.cancelled"), + Some(crate::session_worker::protocol::worker_result_key(&rid)), + ) + .await; + } + } + if let Err(error) = commit_process_terminal_state( + &active_runs, + &rid, + status.clone(), + token_usage_records, + monitor_process_control.as_ref(), + finalization, + None, + #[cfg(test)] + None, + ) + .await { + tracing::error!(run_id = %rid, error = %error, "process terminal registry commit remains unconfirmed"); + return; + } + if finalization == ProcessFinalization::Unconfirmed || owner_exiting { + return; + } + // One result row per run: the worker's own row, if it wrote one, + // already holds the run's key and this write adds nothing. + record_spawn_result_event_keyed( + process_memory_fabric.as_ref(), + process_result_scope, + &result_text, + &status, + &process_lineage, + // A `Terminated` run is a requested stop: recorded as cancelled. + (finalization == ProcessFinalization::Terminated || worker_cancelled) + .then_some("task.cancelled"), + Some(crate::session_worker::protocol::worker_result_key(&rid)), + ) + .await; + + if !announce_result { + tracing::debug!( + run_id = %rid, + "Sub-agent process result withheld from the channel (announce=false); \ + it is delivered to whoever joins this run's batch" + ); + } else if let Some(target) = recipient { + // Not a mirror of the task-mode block any more: + // the same function, so the gate this path gets + // is literally the gate the task-mode tests + // exercise. Driving a real process-mode + // announcement from a unit test is impossible + // (the worker re-execs `current_exe`, which under + // `cargo test` is the test binary), so sharing the + // implementation is what covers it. + deliver_or_withhold_notice( + &process_announce_security, + process_announce_origin.as_ref(), + channel.as_ref(), + &process_announce_history, + &rid, + &target, + &announce, + OutboundNotice::ProcessRunResult, + ) + .await; + } + + tracing::info!(run_id = %rid, "Sub-agent process finished"); + } + .await; + }), + ), + )); + + // Process-mode callers must never abort this monitor: it is the + // sole owner responsible for signalling and reaping the OS child. + // Awaiting the handle from a *separate* task does not abort it, and + // is the only way a cancellation of the monitor (runtime shutdown, + // a future registry abort) can still reach the tool-plane row. + watch_process_mode_monitor( + jh, + monitor_active_runs, + run_id.clone(), + process_control.clone(), + sub_agent_work, + ordinary_terminal, + ordinary_recovery, + operator_terminal, + operator_recovery, + ); + + return Ok(SpawnOutcome::started( + run_id.clone(), + spawn_started_text( + "Sub-agent spawned in process mode", + &run_id, + child_delegation, + announce_result, + ), + )); + } +} diff --git a/src/tools/sessions_spawn/spawn.rs b/src/tools/sessions_spawn/spawn.rs index 332a1a6b4..8fa518e9d 100644 --- a/src/tools/sessions_spawn/spawn.rs +++ b/src/tools/sessions_spawn/spawn.rs @@ -1,27 +1,18 @@ use super::delegation; use super::{ - AllowedToolProxy, AnnounceOrigin, HistoryEntry, MemoryScope, OutboundNotice, OwnerLossReason, ProcessFinalization, - ProcessModeRunSeed, ProcessRunControl, ProcessWorkerOutcome, SPAWN_EXECUTION_CONTEXT, STEER_CHANNEL_CAPACITY, - SessionsSpawnTool, SpawnExecutionContext, SpawnRecordCodes, SpawnScope, SubAgentRun, SubAgentStatus, - TaskRunControl, TerminationCause, boxed_spawn_field, commit_process_terminal_state, - current_spawn_execution_context, deliver_or_withhold_notice, exited_without_result_reason, format_announce_message, - new_process_mode_run, normalize_process_memory_strategy, parse_memory_scope, parse_spawn_scope, process_terminal, - record_owner_loss_terminal, record_spawn_request_event, record_spawn_result_event, record_spawn_result_event_keyed, - refresh_tools_for_explicit_allowlist, register_killable_process_run, resolve_tools_for_agent, - resolve_worker_workspace_root, run_sub_agent_process, run_sub_agent_task, running_run_count, spawn_event_scope, - spawn_lineage, spawn_session_key, spawn_started_text, sub_agent_reported_failure, task_failure_reason, - task_terminal, termination_cause, watch_process_mode_monitor, watch_task_mode_monitor, + SessionsSpawnTool, SpawnExecutionContext, SpawnLineage, SpawnRecordCodes, SpawnScope, boxed_spawn_field, + current_spawn_execution_context, normalize_process_memory_strategy, parse_spawn_scope, + record_spawn_request_event, refresh_tools_for_explicit_allowlist, running_run_count, spawn_event_scope, + spawn_lineage, spawn_session_key, }; +use crate::channels::traits::Channel; use crate::providers; use crate::runtime::child_source::publication::ChildDelegation; use crate::security::SideEffectGate; use crate::security::policy::{ApprovalGrant, ResourceRiskLevel}; use crate::tools::traits::{Tool, ToolResult}; use anyhow::Context as _; -use chrono::Utc; use std::sync::Arc; -use tokio::sync::RwLock; -use tokio_util::sync::CancellationToken; use uuid::Uuid; /// What one spawn attempt produced: the tool-visible result, plus the run id @@ -46,7 +37,7 @@ impl SpawnOutcome { } /// A run is registered and its driver task is live. - const fn started(run_id: String, output: String) -> Self { + pub(super) const fn started(run_id: String, output: String) -> Self { Self { result: ToolResult { success: true, @@ -74,6 +65,60 @@ pub(super) fn resolve_pinned_child_compaction( ) } +/// Everything `execute_spawn_with_id` resolved before the launch mode splits: the admitted source, +/// the pinned provider route, the run identity and its scope. Borrowed fields point into values the +/// caller keeps alive for the whole launch. +pub(super) struct SpawnLaunch<'a> { + pub(super) operator_source: &'a Option>, + pub(super) message_input: Option, + pub(super) message_permit: Option>, + pub(super) caller: &'a Option, + pub(super) child_delegation: Option, + pub(super) ordinary_publication: Option<&'a crate::runtime::child_source::publication::OrdinaryChildPublication>, + pub(super) child_model_config: &'a crate::config::Config, + pub(super) launch_security: &'a Arc, + pub(super) child_level: crate::security::AutonomyLevel, + pub(super) spawn_config: &'a crate::config::schema::SessionsSpawnConfig, + pub(super) task: &'a str, + pub(super) process_memory_strategy: String, + pub(super) spawn_scope: Option, + pub(super) parent_exec_ctx: Option, + pub(super) spawn_depth: usize, + pub(super) parent_run_id: Option, + pub(super) child_full: bool, + pub(super) inherited_channel_exclusions: Vec, + pub(super) run_id: String, + pub(super) session_scope_key: String, + pub(super) selected_agent: Option<(String, crate::config::DelegateAgentConfig)>, + pub(super) recipient: Option, + pub(super) run_channel_name: Option, + pub(super) operator_channel: Option>, + pub(super) announce_result: bool, + pub(super) memory_fabric: crate::memory::MemoryFabric, + pub(super) process_memory_backend: String, + pub(super) resolved_provider_name: String, + pub(super) resolved_model: String, + pub(super) child_requested_model: Option<(String, String)>, + pub(super) selected_route_hint: Option, + pub(super) route_source_provider: Option, + pub(super) child_credential: Option, + pub(super) route_credential: Option, + pub(super) route_uses_root_connection: bool, + pub(super) direct_uses_root_connection: bool, + pub(super) temperature_override: Option, + pub(super) resolved_temperature: f64, + pub(super) ordinary_binding: Option>, + pub(super) spawn_scope_for_event: crate::memory::fabric::MessageEventScope, + pub(super) run_lineage: SpawnLineage, + pub(super) allowed_tools: Vec, + pub(super) tools: Option>>>, + pub(super) process_config_source: Option<(std::path::PathBuf, String)>, + pub(super) source_receipt: Option>, + pub(super) batch_id: Option<&'a str>, + pub(super) process_compaction_config: crate::config::AgentCompactionConfig, + pub(super) parent_hooks: Option>, +} + impl SessionsSpawnTool { /// Launch exactly one sub-agent run and return as soon as it is registered /// and its driver task is running. @@ -835,1138 +880,61 @@ impl SessionsSpawnTool { if let Some(publication) = ordinary_publication { publication.watch_mailbox_children()?; } - if mode == "process" { - let process_parent_frames = caller.as_ref().and_then(|caller| { - let context = caller.context(); - context - .live_turn - .as_ref() - .map(|live| live.0.frames(&context.envelope, &std::collections::HashSet::new())) - }); - let (process_config_dir, process_config_generation) = - process_config_source.ok_or_else(|| anyhow::anyhow!("process config source was not resolved"))?; - let process_provider_selection = if ordinary_publication.is_some() { - let (provider, model) = child_requested_model - .as_ref() - .context("process child selection missing")?; - Some(crate::session_worker::protocol::WorkerProviderSelection { - provider: provider.clone(), - model: model.clone(), - credential: child_credential.clone().context("process child credential missing")?, - }) - } else { - None - }; - let process_source_launch = ordinary_publication - .map(|publication| { - publication.capture_process_launch( - caller.as_ref().context("ordinary process caller missing")?, - ordinary_binding - .as_deref() - .context("ordinary process binding missing")?, - &spawn_scope_for_event, - task, - source_receipt.clone(), - process_provider_selection - .clone() - .context("ordinary process selection missing")?, - process_config_generation.clone(), - ) - }) - .transpose()? - .map(|launch| crate::runtime::operator_spawn::process::ProcessSourceLaunch::Ordinary(Box::new(launch))); - let process_source_launch = match &operator_source { - Some(source) => Some(crate::runtime::operator_spawn::process::ProcessSourceLaunch::Operator( - Box::new(source.capture_process( - &spawn_scope_for_event, - task, - source_receipt.clone(), - process_config_generation.clone(), - )?), - )), - None => process_source_launch, - }; - let process_approval_relay = crate::session_worker::approval::relay_context::RelaySeedInputs { - caller: caller.as_ref(), - binding: ordinary_binding.as_deref(), - resolvers: self.approval_resolver_factory.as_ref(), - scope: &spawn_scope_for_event, - task, - receipt: source_receipt.as_deref(), - security: launch_security, - level: child_level, - run_id: &run_id, - } - .seed()?; - let temperature = resolved_temperature; - let history_arc: Arc>> = - Arc::new(RwLock::new(super::continuation::seed_history())); - let process_control = ProcessRunControl::new(); - let stop_control = Arc::clone(&process_control); - let runtime_handle = tokio::runtime::Handle::try_current()?; - let message_turn = super::message_lifetime::retain( - child_model_config, - message_input.as_ref(), - &self.active_runs, - Arc::new(move || { - let control = Arc::clone(&stop_control); - runtime_handle.spawn(async move { - let _ = control.request_termination("history_erased").await; - }); - }), - )?; - // Process-mode steering: the sender lives in the registry exactly as - // it does for task mode, so `sessions_send` / `sessions_spawn:steer` - // reach an OS-process sub-agent through the same code path. The - // receiver is handed to the child owner, which forwards each message - // as a line-delimited control frame on the worker's stdin. - let (process_steer_tx, process_steer_rx) = tokio::sync::mpsc::channel::(STEER_CHANNEL_CAPACITY); - // Minted here, on the *spawning* task, so the run's beat is parented - // on the caller's: a parent legitimately blocked on a working child - // must not look silent to its own hang detector. A beat minted - // inside the spawned monitor would have no parent at all, because - // task-locals do not cross `tokio::spawn`. - let process_progress = crate::agent::idle::child_beat(); - - { - let mut runs = self.active_runs.write().await; - let mut run = new_process_mode_run(ProcessModeRunSeed { - id: run_id.clone(), - task: task.to_string(), - lineage: &run_lineage, - recipient: recipient.clone(), - channel_name: run_channel_name.clone(), - process_control: process_control.clone(), - history: history_arc.clone(), - steer_tx: process_steer_tx.clone(), - parent_run_id: parent_run_id.clone(), - session_scope_key: session_scope_key.clone(), - spawn_depth, - // Recursive delegation status is issued by no parent (P2-G4). - delegation: None, - progress: Arc::clone(&process_progress), - batch_id: batch_id.map(str::to_string), - }); - run.agent_partition = spawn_scope_for_event.agent_partition.clone(); - super::continuation::register(&mut runs, run)?; - } - - let model = resolved_model; - let provider_name = resolved_provider_name; - let route_hint = selected_route_hint; - let workspace_root = child_model_config.workspace_dir.clone(); - let worker_workspace_root = - resolve_worker_workspace_root(spawn_config.worker_workspace_root.as_deref(), &workspace_root); - let active_runs = self.active_runs.clone(); - // Resolve the announce channel from the *per-turn* channel name bound - // to this run (the launching message's scope), not the shared active - // channel — so a concurrently-processed message cannot mis-route this - // run's result. Falls back to the active channel when no scope name. - let channel = match &operator_channel { - Some(channel) => Arc::clone(channel), - None => self.resolve_announce_channel(run_channel_name.as_deref()).await, - }; - let keep_workspace = !spawn_config.cleanup_on_complete; - let process_agent_id = selected_agent.as_ref().map(|(name, _)| name.clone()); - let identity_dir = selected_agent.as_ref().and_then(|(_, cfg)| { - cfg.identity_dir - .as_deref() - .map(str::trim) - .filter(|value| !value.is_empty()) - .map(str::to_string) - }); - // Process workers need the same explicit agent contract as task-mode - // children. Without carrying this prompt into the signed manifest, - // a named agent's tool-use and completion instructions silently vanish - // at the OS-process boundary. - let process_system_prompt = selected_agent.as_ref().and_then(|(_, cfg)| { - cfg.system_prompt - .as_deref() - .map(str::trim) - .filter(|value| !value.is_empty()) - .map(str::to_string) - }); - let task_owned = task.to_string(); - let rid = run_id.clone(); - let process_scope = spawn_scope.clone(); - // Announcement gate inputs for the process-mode monitor. Same three - // values the task-mode branch below captures, handed to the same - // `deliver_or_withhold_notice`. - let process_announce_security = policy_at_level(launch_security, child_level); - let process_announce_origin = AnnounceOrigin::from_scope(spawn_scope.as_ref()); - let process_announce_history = history_arc.clone(); - // The worker's parent is the run its bound input names: the - // publication's spawn run, or the operator source run. A gateway - // Console turn seeds no spawn context, so `parent_run_id` alone is - // None there and the manifest would differ from its issued input. - let process_parent_run_id = spawn_scope_for_event - .parent_run_id - .clone() - .or_else(|| parent_run_id.clone()); - let process_session_scope_key = session_scope_key.clone(); - let process_spawn_depth = spawn_depth; - let process_channel_exclusions = inherited_channel_exclusions.clone(); - let process_compaction_config = resolved_compaction.config.clone(); - let process_event_recording = child_model_config.memory.event_recording_config(); - let process_execution_ctx = SpawnExecutionContext { - task_input: parent_exec_ctx - .as_ref() - .map(|context| context.task_input.clone()) - .unwrap_or_default(), - operator_authority: None, - ordinary_authority: None, - provider_binding: None, - terminal_usage: None, - input_receipt: source_receipt.clone(), - run_id: rid.clone(), - session_scope_key: session_scope_key.clone(), - spawn_depth, - owner_id: run_lineage.owner_id.clone(), - owner_isolated: run_lineage.owner_isolated, - topic_id: run_lineage.topic_id.clone(), - source_message_event_id: run_lineage.source_message_event_id.clone(), - // A spawn-run context (this run may itself spawn): its children - // compute spawn_depth + 1. - is_turn_root: false, - channel_excluded_tools: inherited_channel_exclusions.clone(), - }; - let process_memory_fabric = Some(memory_fabric.clone()); - let process_result_scope = spawn_scope_for_event.clone(); - let process_lineage = run_lineage.clone(); - let process_cost_config = child_model_config.cost.clone(); - let monitor_process_control = process_control.clone(); - - // Registry row for this run. The parent is captured *here*, on the - // spawning task, because a freshly spawned task inherits no - // task-locals. No abort handle is attached: this monitor is the sole - // owner responsible for signalling and reaping the OS child, so - // aborting it would strand the very process a kill is meant to end. - // The row's cooperative token is how a kill reaches it instead — - // see `bridge_registry_kill_to_process_control`, which asks that - // same owner to stop. A cascade additionally signals the worker's - // process group through the child row `run_sub_agent_process` - // registers underneath. - // Parented to the enclosing turn, not the launching tool call: that row - // is gone once the call returns, which would cut this run out of a - // cascading cancel of the root. - let sub_agent_parent = crate::runtime::registry::current_owner_work_id(); - let sub_agent_label = process_agent_id - .clone() - .unwrap_or_else(|| "sub-agent (process)".to_string()); - let mut sub_agent_work = - register_killable_process_run(&sub_agent_label, &rid, sub_agent_parent, batch_id, &process_control); - // Publish this run's steering channel on its registry row so the - // control plane can address it by run id from another entry point. - // Same sender, same bounded queue as `sessions_send` — only the - // lookup is new; see `registry::attach_steer_sender`. - crate::runtime::registry::attach_steer_sender(sub_agent_work.id(), process_steer_tx.clone()); - sub_agent_work.require_cleanup_acknowledgement(); - let process_work_id = sub_agent_work.id(); - let is_ordinary_process = process_source_launch - .as_ref() - .is_some_and(|launch| launch.is_ordinary()); - let ordinary_recovery = if is_ordinary_process { - Some(process_terminal::ordinary::OrdinaryProcessRecovery::new( - process_memory_fabric - .clone() - .context("ordinary recovery fabric missing")?, - workspace_root.clone(), - run_lineage - .owner_id - .clone() - .context("ordinary recovery owner missing")?, - run_id.clone(), - )?) - } else { - None - }; - let is_operator_process = process_source_launch - .as_ref() - .is_some_and(|launch| !launch.is_ordinary()); - let operator_recovery = if is_operator_process { - Some(process_terminal::operator::OperatorProcessRecovery::new( - process_memory_fabric - .clone() - .context("operator recovery fabric missing")?, - workspace_root.clone(), - run_lineage - .owner_id - .clone() - .context("operator recovery owner missing")?, - run_id.clone(), - )?) - } else { - None - }; - let process_worker_mailbox = if let Some(factory) = &self.worker_mailbox { - Some(factory.clone()) - } else if let Some(config) = self - .hint_config - .as_ref() - .filter(|config| config.memory.backend == "sqlite") - { - Some(crate::messaging::worker::WorkerMailboxes::for_config(config)? - as Arc) - } else { - None - }; - let process_batch_id = batch_id.map(str::to_owned); - #[cfg(test)] - let test_worker_executable = self.test_worker_executable.clone(); - let ordinary_terminal = Arc::new(parking_lot::Mutex::new(None)); - let monitor_ordinary_terminal = Arc::clone(&ordinary_terminal); - let operator_terminal = Arc::new(parking_lot::Mutex::new(None)); - let monitor_operator_terminal = Arc::clone(&operator_terminal); - let monitor_active_runs = active_runs.clone(); - let monitor_progress = Arc::clone(&process_progress); - let jh = crate::agent::channel_approval::spawn(crate::runtime::registry::scope_current( - process_work_id, - SPAWN_EXECUTION_CONTEXT.scope( - process_execution_ctx, - crate::agent::idle::scope_beat(Some(Arc::clone(&monitor_progress)), async move { - let _message_permit=message_permit; - let _message_input=message_input; - let _message_turn=message_turn; - async { - tracing::info!(run_id = %rid, "Sub-agent process starting"); - - let worker_result = run_sub_agent_process( - &rid, - &task_owned, - &provider_name, - &model, - route_hint.as_deref(), - route_source_provider.as_deref(), - route_credential.as_ref(), - route_uses_root_connection, - direct_uses_root_connection, - temperature, - temperature_override, - &workspace_root, - &worker_workspace_root, - identity_dir.as_deref(), - process_system_prompt.as_deref(), - &allowed_tools, - keep_workspace, - process_scope.as_ref(), - process_spawn_depth, - &process_session_scope_key, - process_parent_run_id.as_deref(), - process_agent_id.as_deref(), - &process_lineage, - &process_memory_strategy, - &process_memory_backend, - &process_config_dir, - &process_config_generation, - process_event_recording, - &process_compaction_config, - &process_channel_exclusions, - monitor_process_control.as_ref(), - process_steer_rx, - history_arc, - Arc::clone(&monitor_progress), - process_memory_fabric.as_ref(), - process_source_launch, - process_batch_id.as_deref(), - process_worker_mailbox.as_ref(), - process_parent_frames, - process_approval_relay, - #[cfg(test)] - test_worker_executable.as_ref(), - ) - .await; - - // The worker's own account that its work was cancelled; the run's - // status stays `Failed`, only the recorded task event differs. - let mut worker_cancelled = false; - let (status, result_text, token_usage_records, finalization) = match worker_result { - Ok(ProcessWorkerOutcome::OrdinaryVerifiedFinished(completion)) => { - *monitor_ordinary_terminal.lock() = Some(completion.clone()); - let result = completion.result; - worker_cancelled = result.cancelled; - let (status, text) = if result.success { - (SubAgentStatus::Completed(result.output.clone()), result.output) - } else { - let error = super::failure::llm_visible_error(&result.error.unwrap_or_else(|| "worker failed".to_owned())); - (SubAgentStatus::Failed(sub_agent_reported_failure(&error)), format!("Sub-agent error: {error}")) - }; - (status, text, completion.usage, ProcessFinalization::Natural) - } - Ok(ProcessWorkerOutcome::OperatorVerifiedFinished(completion)) => { - *monitor_operator_terminal.lock() = Some(completion.clone()); - let result = completion.result; - worker_cancelled = result.cancelled; - let (status, text) = if result.success { - (SubAgentStatus::Completed(result.output.clone()), result.output) - } else { - let error = super::failure::llm_visible_error(&result.error.unwrap_or_else(|| "worker failed".to_owned())); - (SubAgentStatus::Failed(sub_agent_reported_failure(&error)), format!("Sub-agent error: {error}")) - }; - (status, text, completion.usage, ProcessFinalization::Natural) - } - Ok(ProcessWorkerOutcome::VerifiedStartupFailure(result)) => { - let error = result.error.context("verified startup failure detail missing"); - let error = match error { - Ok(error) => error, - Err(error) => { - tracing::error!(run_id = %rid, error = %error, "verified startup result invalid"); - return; - } - }; - ( - SubAgentStatus::Failed(sub_agent_reported_failure(&error)), - format!("Sub-agent startup error: {error}"), - Vec::new(), - ProcessFinalization::Natural, - ) - } - Ok(ProcessWorkerOutcome::UnverifiedStartupFailure(_)) => { - tracing::error!(run_id = %rid, "unverified startup failure escaped process owner"); - return; - } - Ok(ProcessWorkerOutcome::Finished(result)) if result.success => { - let token_usage_records = result - .tokens_used - .as_ref() - .and_then(|usage| { - crate::llm::route_decision::MeteredTokenUsageRecord::from_parts( - &provider_name, - &model, - usage, - &process_cost_config, - ) - }) - .into_iter() - .collect::>(); - ( - SubAgentStatus::Completed(result.output.clone()), - result.output, - token_usage_records, - ProcessFinalization::Natural, - ) - } - Ok(ProcessWorkerOutcome::Finished(result)) => { - worker_cancelled = result.cancelled; - let error = result.error.unwrap_or_else(|| "worker failed".to_string()); - let msg = format!("Sub-agent error: {error}"); - // `result.error` is a field of the JSON the - // worker itself printed, so it is the run's - // account of the run — quarantined here so - // it cannot pass for a runtime wording in - // `termination_cause`. The announcement - // above still shows the raw account. - ( - SubAgentStatus::Failed(sub_agent_reported_failure(&error)), - msg, - Vec::new(), - ProcessFinalization::Natural, - ) - } - Ok(ProcessWorkerOutcome::Terminated { reason, usage }) => { - let msg = format!("Sub-agent process terminated: {reason}"); - ( - SubAgentStatus::Failed(reason), - msg, - usage, - ProcessFinalization::Terminated, - ) - } - Ok(ProcessWorkerOutcome::OrdinaryInterrupted { detail, usage }) => { - let error = format!("{}; cleanup and provider usage remain unconfirmed; {} visible segments lack a terminal", - exited_without_result_reason(&detail), usage.unfinished_segments); - (SubAgentStatus::Failed(error.clone()), format!("Sub-agent process error: {error}"), - usage.records, ProcessFinalization::Unconfirmed) - } - Ok(ProcessWorkerOutcome::OperatorInterrupted { detail, usage }) => { - let error = format!("{}; cleanup and provider usage remain unconfirmed; {} visible segments lack a terminal", - exited_without_result_reason(&detail), usage.unfinished_segments); - (SubAgentStatus::Failed(error.clone()), format!("Sub-agent process error: {error}"), - usage.records, ProcessFinalization::Unconfirmed) - } - Ok(ProcessWorkerOutcome::ExitedWithoutResult(detail)) => { - // MUTATION GUARD: folding this back into the - // generic parse-error path loses the only - // wording an operator can act on, and folding it - // into "keep waiting" would leave the run - // `Running` for as long as the process lives. - let error = exited_without_result_reason(&detail); - let msg = format!("Sub-agent process error: {error}"); - ( - SubAgentStatus::Failed(error), - msg, - Vec::new(), - ProcessFinalization::Natural, - ) - } - Ok(ProcessWorkerOutcome::ExitedUnrequested { detail, usage }) => { - let error = exited_without_result_reason(&detail); - (SubAgentStatus::Failed(error.clone()), format!("Sub-agent process error: {error}"), - usage, ProcessFinalization::Natural) - } - Ok(ProcessWorkerOutcome::TerminationFailed(error)) => { - let msg = format!("Sub-agent process termination failed: {error}"); - ( - SubAgentStatus::Failed(error), - msg, - Vec::new(), - ProcessFinalization::TerminationFailed, - ) - } - Err(error) => { - // Nothing was spawned for a refused launch, so its - // failure is final rather than left to recovery. - let launch_refused = - error.downcast_ref::().is_some(); - tracing::warn!( - run_id = %rid, - launch_refused, - error = %crate::agent::diagnostics::error_class(&error), - "sub-agent process ended with an error" - ); - let detail = super::failure::llm_visible_error(&format!("{error:#}")); - let msg = format!("Sub-agent process error: {detail}"); - ( - SubAgentStatus::Failed(detail), - msg, - Vec::new(), - if (is_ordinary_process || is_operator_process) && !launch_refused { - ProcessFinalization::Unconfirmed - } else { ProcessFinalization::Natural }, - ) - } - }; - - let announce = format_announce_message(&rid, &status, &result_text); - // An exiting owner waits only for finalization, so the run's - // durable terminal row is written before the commit publishes it. - let owner_exiting = monitor_process_control.termination_reason().as_deref() - == Some(OwnerLossReason::OwnerExited.code()); - if owner_exiting { - if matches!(finalization, ProcessFinalization::Terminated | ProcessFinalization::Unconfirmed) { - if let Some(fabric) = process_memory_fabric.as_ref() { - if let Err(error) = record_owner_loss_terminal( - fabric, - process_result_scope.clone(), - &rid, - OwnerLossReason::OwnerExited, - ) - .await - { - tracing::error!( - run_id = %rid, - error = %crate::agent::diagnostics::error_class(&error), - "owner-exit terminal row remains unconfirmed" - ); - } - } - } else if finalization == ProcessFinalization::Natural { - // Finished on its own within the bound: its real outcome. - record_spawn_result_event_keyed( - process_memory_fabric.as_ref(), - process_result_scope.clone(), - &result_text, - &status, - &process_lineage, - worker_cancelled.then_some("task.cancelled"), - Some(crate::session_worker::protocol::worker_result_key(&rid)), - ) - .await; - } - } - if let Err(error) = commit_process_terminal_state( - &active_runs, - &rid, - status.clone(), - token_usage_records, - monitor_process_control.as_ref(), - finalization, - None, - #[cfg(test)] - None, - ) - .await { - tracing::error!(run_id = %rid, error = %error, "process terminal registry commit remains unconfirmed"); - return; - } - if finalization == ProcessFinalization::Unconfirmed || owner_exiting { - return; - } - // One result row per run: the worker's own row, if it wrote one, - // already holds the run's key and this write adds nothing. - record_spawn_result_event_keyed( - process_memory_fabric.as_ref(), - process_result_scope, - &result_text, - &status, - &process_lineage, - // A `Terminated` run is a requested stop: recorded as cancelled. - (finalization == ProcessFinalization::Terminated || worker_cancelled) - .then_some("task.cancelled"), - Some(crate::session_worker::protocol::worker_result_key(&rid)), - ) - .await; - - if !announce_result { - tracing::debug!( - run_id = %rid, - "Sub-agent process result withheld from the channel (announce=false); \ - it is delivered to whoever joins this run's batch" - ); - } else if let Some(target) = recipient { - // Not a mirror of the task-mode block any more: - // the same function, so the gate this path gets - // is literally the gate the task-mode tests - // exercise. Driving a real process-mode - // announcement from a unit test is impossible - // (the worker re-execs `current_exe`, which under - // `cargo test` is the test binary), so sharing the - // implementation is what covers it. - deliver_or_withhold_notice( - &process_announce_security, - process_announce_origin.as_ref(), - channel.as_ref(), - &process_announce_history, - &rid, - &target, - &announce, - OutboundNotice::ProcessRunResult, - ) - .await; - } - - tracing::info!(run_id = %rid, "Sub-agent process finished"); - } - .await; - }), - ), - )); - - // Process-mode callers must never abort this monitor: it is the - // sole owner responsible for signalling and reaping the OS child. - // Awaiting the handle from a *separate* task does not abort it, and - // is the only way a cancellation of the monitor (runtime shutdown, - // a future registry abort) can still reach the tool-plane row. - watch_process_mode_monitor( - jh, - monitor_active_runs, - run_id.clone(), - process_control.clone(), - sub_agent_work, - ordinary_terminal, - ordinary_recovery, - operator_terminal, - operator_recovery, - ); - - return Ok(SpawnOutcome::started( - run_id.clone(), - spawn_started_text( - "Sub-agent spawned in process mode", - &run_id, - child_delegation, - announce_result, - ), - )); - } - - // Create shared history and steer channel for this run - let history_arc: Arc>> = Arc::new(RwLock::new(super::continuation::seed_history())); - // Class B — bounded. Steering messages are produced by operators and by - // model tool calls, neither of which is rate-limited now that sub-agent - // concurrency is uncapped, while the consumer only polls between tool - // iterations. An unbounded queue therefore grows for the whole lifetime - // of a long-running sub-agent. - let (steer_tx, steer_rx) = tokio::sync::mpsc::channel::(STEER_CHANNEL_CAPACITY); - // Minted on the spawning task so the run's beat is parented on the - // caller's (see `crate::agent::idle::child_beat`). The sub-agent's own - // guarded turn parents *its* beat on this one, so every ProgressKind - // event it produces refreshes this row and the caller's window alike. - let task_progress = crate::agent::idle::child_beat(); - - // Clone everything the spawned task needs. - // Resolve the announce channel from the *per-turn* channel name bound to - // this run (the launching message's scope), not the shared active channel - // — so a concurrently-processed message cannot mis-route this run's - // result. Falls back to the active channel when no scope name is present. - let channel = match &operator_channel { - Some(channel) => Arc::clone(channel), - None => self.resolve_announce_channel(run_channel_name.as_deref()).await, - }; - let mut provider_name = resolved_provider_name; - let mut model = resolved_model; - let child_provider_binding = if let Some(source) = &operator_source { - let binding = Arc::new(crate::runtime::child_source::ChildProviderBinding::build_independent( - source, - )?); - provider_name = binding.provider_name().to_owned(); - model = binding.model().to_owned(); - Some(binding) - } else if let Some(binding) = ordinary_binding { - provider_name = binding.provider_name().to_owned(); - model = binding.model().to_owned(); - Some(binding) - } else { - None - }; - let temperature = resolved_temperature; - // An explicit hint always builds its exact selected chain, even when - // it names the gateway provider: the gateway may hold another route's - // credential. Direct models keep their existing provider plan. - if let Some(source) = &operator_source { - source.verify_live()?; - let binding = child_provider_binding - .as_ref() - .context("operator child model binding missing")?; - anyhow::ensure!( - Arc::ptr_eq(&binding.provider(), source.provider()), - "operator child provider differs from captured ingress" - ); - } - let provider = child_provider_binding - .as_ref() - .context("admitted sessions_spawn child model binding missing")? - .provider(); - let active_runs = self.active_runs.clone(); - let rid = run_id.clone(); - // Event bridge (v1.1a): if a chat-side sink is attached, create this - // session's middle channels + drainer up front (run_id is already - // minted, so the drainer is tagged with the correct id — no race). The - // background agent only ever `.send().await`s onto these; the drainer - // continuously empties them, so the agent never back-pressures. - let run_event_streams = self.event_sink.as_ref().map(|sink| sink.streams_for(&run_id)); - // NeedsInput (chat `/bg` only): mint this run's approval resolver so a - // supervised gate hit suspends awaiting an operator decision instead of - // auto-failing. `None` everywhere else (channels/gateway) preserves the - // historical auto-fail-on-gate semantics. - let run_approval_resolver = self - .approval_resolver_factory - .as_ref() - .map(|factory| factory.resolver_for(&run_id)); - // Only approval suspension needs the optional restoration registry. - // Every task still carries its admitted run identity, including mailbox - // continuations without an approval surface. - let restore_active_runs = run_approval_resolver.as_ref().map(|_| self.active_runs.clone()); - let restore_run_id = Some(run_id.clone()); - let task_owned = task.to_string(); - let identity_workspace = child_model_config.workspace_dir.clone(); - let security = Arc::clone(launch_security); - // Second handle, for the announcement gate: `security` above is moved - // into the sub-agent's own loop, and the announcement is authorized only - // once that loop has returned. - let announce_security = policy_at_level(launch_security, child_level); - // The launching turn's trusted identity, captured atomically with - // `recipient` / `run_channel_name` from the same scope snapshot. - let announce_origin = AnnounceOrigin::from_scope(spawn_scope.as_ref()); - // Same handle the run writes its transcript through, so a refused - // announcement is visible on the run itself and not only in the log. - let announce_history = history_arc.clone(); - let mut terminal_usage = None; - let mut task_execution_ctx = SpawnExecutionContext { - task_input: parent_exec_ctx - .as_ref() - .map(|context| context.task_input.clone()) - .unwrap_or_default(), - operator_authority: None, - ordinary_authority: None, - provider_binding: child_provider_binding, - terminal_usage: terminal_usage.clone(), - input_receipt: source_receipt, - run_id: rid.clone(), - session_scope_key: session_scope_key.clone(), - spawn_depth, - owner_id: run_lineage.owner_id.clone(), - owner_isolated: run_lineage.owner_isolated, - topic_id: run_lineage.topic_id.clone(), - source_message_event_id: run_lineage.source_message_event_id.clone(), - // A spawn-run context (this run may itself spawn): its children - // compute spawn_depth + 1. - is_turn_root: false, - channel_excluded_tools: inherited_channel_exclusions.clone(), - }; - let task_memory_fabric = memory_fabric.clone(); - let task_result_scope = spawn_scope_for_event.clone(); - let task_lineage = run_lineage.clone(); - let agent_label_for_registry = selected_agent.as_ref().map(|(name, _)| name.clone()); - let (system_prompt, filtered_tools) = if let Some((agent, cfg)) = selected_agent { - let identity_path = cfg - .identity_dir - .as_deref() - .map(str::trim) - .filter(|value| !value.is_empty()) - .map(|directory| identity_workspace.join(directory)); - let prompt = crate::identity::delegated::compose(identity_path.as_deref(), cfg.system_prompt.as_deref()); - let memory_scope = parse_memory_scope(cfg.memory_scope.as_deref())?; - let tools = tools.map(|registry| { - if ordinary_publication.is_some() { - // Keep the backend root identity and dynamic metadata for - // the sealed catalog. The child service enforces the exact - // manifest, agent allowance and inherited exclusions. - let memory_prefix = (memory_scope == MemoryScope::Isolated).then(|| agent.clone()); - return Arc::new( - registry - .iter() - .map(|tool| { - Box::new(AllowedToolProxy { - source: Arc::clone(®istry), - public_name: tool.name().to_owned(), - memory_prefix: memory_prefix.clone(), - }) as Box - }) - .collect(), - ); - } - resolve_tools_for_agent( - registry, - &agent, - memory_scope, - if child_full || cfg.allowed_tools.is_empty() { - None - } else { - Some(&cfg.allowed_tools) - }, - &inherited_channel_exclusions, - ) - }); - (prompt, tools) - } else { - (crate::identity::delegated::DEFAULT_PROMPT.to_owned(), tools) - }; - - // Register the run. - // - // A background run outlives its spawning turn. Its independent observer - // owns cleanup; parenting this to the caller would cancel valid work - // when that caller returns. Register before publishing the active row. - let task_control = TaskRunControl::new(); - let stop_token = task_control.cancellation().clone(); - let message_turn = super::message_lifetime::retain( + let process_compaction_config = resolved_compaction.config.clone(); + let launch = SpawnLaunch { + operator_source: &operator_source, + message_input, + message_permit, + caller: &caller, + child_delegation, + ordinary_publication, child_model_config, - message_input.as_ref(), - &self.active_runs, - Arc::new(move || stop_token.cancel()), - )?; - if let Some(source) = &operator_source { - let (authority, lifetime) = source.issue_task( - Arc::clone( - task_execution_ctx - .provider_binding - .as_ref() - .context("operator model binding missing")?, - ), - &task_result_scope, - task, - task_execution_ctx.input_receipt.as_deref(), - task_control.cancellation(), - )?; - task_control.retain_operator_lifetime(lifetime)?; - use crate::runtime::turn_source::TurnSourceProof; - let usage = Arc::new(crate::runtime::turn_terminal::TerminalUsageCollector::new_ordinary( - authority.workspace_id().to_owned(), - authority.owner_id().to_owned(), - rid.clone(), - authority.generation().effective.memory.event_recording_config(), - )); - terminal_usage = Some(Arc::clone(&usage)); - task_execution_ctx.terminal_usage = Some(usage); - task_execution_ctx.operator_authority = Some(authority); - } - if ordinary_publication.is_some() { - let binding = task_execution_ctx - .provider_binding - .as_ref() - .context("ordinary task provider binding missing")?; - let caller = caller.as_ref().context("ordinary task caller missing")?; - let (authority, lifetime) = binding.issue_ordinary_task( - caller, - &task_result_scope, - task, - task_execution_ctx.input_receipt.as_deref(), - task_control.cancellation(), - )?; - task_control.retain_ordinary_lifetime(lifetime)?; - use crate::runtime::turn_source::TurnSourceProof; - let (proof, _) = authority.source()?; - let usage = Arc::new(crate::runtime::turn_terminal::TerminalUsageCollector::new_ordinary( - proof.workspace_id().to_owned(), - proof.owner_id().to_owned(), - rid.clone(), - authority - .publication() - .generation() - .effective - .memory - .event_recording_config(), - )); - terminal_usage = Some(Arc::clone(&usage)); - task_execution_ctx.terminal_usage = Some(usage); - task_execution_ctx.ordinary_authority = Some(authority); - } - let logical_terminal = { - use crate::agent::terminal::logical::LogicalTaskTerminalRef; - match ( - task_execution_ctx.ordinary_authority.as_deref(), - task_execution_ctx.operator_authority.as_deref(), - ) { - (Some(authority), None) => LogicalTaskTerminalRef::ordinary(authority)?, - (None, Some(authority)) => LogicalTaskTerminalRef::operator(authority)?, - _ => anyhow::bail!("logical task completion requires one issued source authority"), - } + launch_security, + child_level, + spawn_config, + task, + process_memory_strategy, + spawn_scope, + parent_exec_ctx, + spawn_depth, + parent_run_id, + child_full, + inherited_channel_exclusions, + run_id, + session_scope_key, + selected_agent, + recipient, + run_channel_name, + operator_channel, + announce_result, + memory_fabric, + process_memory_backend, + resolved_provider_name, + resolved_model, + child_requested_model, + selected_route_hint, + route_source_provider, + child_credential, + route_credential, + route_uses_root_connection, + direct_uses_root_connection, + temperature_override, + resolved_temperature, + ordinary_binding, + spawn_scope_for_event, + run_lineage, + allowed_tools, + tools, + process_config_source, + source_receipt, + batch_id, + process_compaction_config, + parent_hooks, }; - let run_cleanup = Arc::new(crate::runtime::turn_cleanup::CleanupTracker::default()); - let run_cleanup_scope = - crate::runtime::turn_cleanup::CleanupScope::new(Some(&run_cleanup), CancellationToken::new())?; - - // Deliberately the *last* fallible-free step before the driver task is - // spawned, and never earlier: everything between this block and - // `tokio::spawn` below is infallible, so the presence of a row in - // `active_runs` implies a driver task that will publish a terminal status - // for it. Registering before the fallible preparation above (agent prompt - // and tool resolution) left a `Running` row behind on every early return — - // no abort handle, no driver task, no observer — and `join` polls such a - // row forever, with no wall-clock fallback in this runtime to break the - // tie. Keep any new fallible step above this block. - // - // `abort_handle` is filled in right after `tokio::spawn` returns. - { - let mut runs = self.active_runs.write().await; - super::continuation::register( - &mut runs, - SubAgentRun { - agent_partition: spawn_scope_for_event.agent_partition.clone(), - id: run_id.clone(), - task: task.to_string(), - owner_id: run_lineage.owner_id.clone(), - topic_id: run_lineage.topic_id.clone(), - source_message_event_id: run_lineage.source_message_event_id.clone(), - started_at: Utc::now(), - finished_at: None, - status: SubAgentStatus::Running, - recipient: recipient.clone(), - channel_name: run_channel_name.clone(), - abort_handle: None, - process_control: None, - task_control: Some(Arc::clone(&task_control)), - history: history_arc.clone(), - steer_tx: Some(steer_tx.clone()), - parent_run_id: parent_run_id.clone(), - session_scope_key: session_scope_key.clone(), - spawn_depth, - // Recursive delegation status is issued by no parent (P2-G4). - delegation: None, - token_usage_records: Vec::new(), - progress: Arc::clone(&task_progress), - batch_id: batch_id.map(str::to_string), - }, - )?; - } - - // Registry row for this run. Parent captured on the spawning task, which - // is the enclosing turn (not the launching tool call, which is gone once - // it returns); a spawned task inherits no task-locals of its own. - let sub_agent_parent = crate::runtime::registry::current_owner_work_id(); - let sub_agent_label = agent_label_for_registry.unwrap_or_else(|| "sub-agent".to_string()); - let mut sub_agent_work = - crate::runtime::registry::register_sub_agent(&sub_agent_label, &rid, sub_agent_parent, batch_id, None); - let sub_agent_work_id = sub_agent_work.id(); - sub_agent_work.require_cleanup_acknowledgement(); - // As in the process branch: the control plane resolves `run_id` through - // the process-wide work registry, so the run's existing steer sender is - // published there. `active_runs` stays the tool-plane source of truth. - crate::runtime::registry::attach_steer_sender(sub_agent_work_id, steer_tx.clone()); - - let terminal_journal = Arc::new(task_terminal::TaskTerminalJournal::new( - task_memory_fabric.clone(), - task_result_scope.clone(), - logical_terminal, - true, - terminal_usage, - )); - let driver_terminal_journal = Arc::clone(&terminal_journal); - // Spawn async task (fire-and-forget); capture handle to support kill - let jh = crate::agent::channel_approval::spawn(crate::runtime::registry::scope_current( - sub_agent_work_id, - SPAWN_EXECUTION_CONTEXT.scope(task_execution_ctx, async move { - let _message_permit = message_permit; - let _message_input = message_input; - let _message_turn = message_turn; - tracing::info!(run_id = %rid, "Sub-agent task starting"); - let provider_started_at = Utc::now(); - let (run_on_delta, run_on_tool) = match run_event_streams { - Some((delta_tx, tool_tx)) => (Some(delta_tx), Some(tool_tx)), - None => (None, None), - }; - // Construct the large child loop behind the existing allocation - // boundary before adding task-local temperature ownership. - let run_future = boxed_spawn_field(|| { - run_sub_agent_task( - &task_owned, - provider, - &provider_name, - &model, - temperature, - filtered_tools, - &system_prompt, - security, - steer_rx, - history_arc, - run_on_delta, - run_on_tool, - run_approval_resolver, - restore_active_runs, - restore_run_id, - Arc::clone(&task_progress), - parent_hooks, - ) - }); - let result = run_cleanup_scope - .run(crate::providers::model_settings::with_temperature( - temperature_override, - run_future, - )) - .await; - tracing::info!(run_id = %rid, success = result.is_ok(), "Sub-agent task finished"); - - let (status, result_text, terminal_status, history_projection, token_usage_records) = match result { - Ok(task_result) => ( - SubAgentStatus::Completed(task_result.output.clone()), - task_result.output.clone(), - crate::agent::terminal::TurnTerminalStatus::Completed, - Some(crate::agent::terminal::TurnHistoryProjection { - assistant_content: task_result.output, - history_commit_len: task_result.history_commit_len, - }), - task_result.segment_usage, - ), - Err(error) => { - // Persist the same runtime-classified reason used by the - // live registry. Recovery after commit must not lose the - // quarantine tag on provider/tool-authored failure text. - let reason = task_failure_reason(&error); - let terminal_status = if matches!(termination_cause(&reason), TerminationCause::Killed) { - crate::agent::terminal::TurnTerminalStatus::Cancelled - } else { - crate::agent::terminal::TurnTerminalStatus::Failed - }; - ( - SubAgentStatus::Failed(reason.clone()), - reason, - terminal_status, - None, - Vec::new(), - ) - } - }; - - let delivery_intent = recipient.as_ref().map_or_else( - || crate::agent::terminal::TurnDeliveryIntent::Deferred { - route: "sessions_registry".to_string(), - }, - |target| crate::agent::terminal::TurnDeliveryIntent::Reply { target: target.clone() }, - ); - match driver_terminal_journal - .commit(crate::agent::terminal::TurnTerminalDraft { - binding: None, - terminal_id: rid.clone(), - scope: task_result_scope.clone(), - status: terminal_status, - history: history_projection, - history_scope: None, - provider_outcome: None, - telemetry: crate::agent::terminal::TurnTerminalTelemetry { - summary: result_text.clone(), - started_at: provider_started_at, - finished_at: Utc::now(), - }, - delivery_intent, - }) - .await - { - Ok(_) => {} - Err(error) => { - tracing::error!(run_id = %rid, error = %error, "task terminal persistence remains unconfirmed"); - // The external observer retries this exact proposal. - // Do not publish a result or a substitute usage receipt. - return; - } - } - let announce = format_announce_message(&rid, &status, &result_text); - record_spawn_result_event( - Some(&task_memory_fabric), - task_result_scope, - &result_text, - &status, - &task_lineage, - None, - ) - .await; - - // Update run status - { - let mut runs = active_runs.write().await; - if let Some(run) = runs.iter_mut().find(|r| r.id == rid) { - run.finished_at = Some(Utc::now()); - run.status = status; - run.token_usage_records.extend(token_usage_records); - run.steer_tx = None; // drop sender — no more steering possible - } - } - - // Announce result back to channel if we have a recipient - if !announce_result { - tracing::debug!( - run_id = %rid, - "Sub-agent result withheld from the channel (announce=false); \ - it is delivered to whoever joins this run's batch" - ); - } else if let Some(target) = recipient { - // MUTATION GUARD: route this straight to `channel.send` and the - // model-supplied `recipient` on the spawn call reaches the - // channel with no authorization at all — the hole - // `message_send`'s own outbound gate closes on its side. - deliver_or_withhold_notice( - &announce_security, - announce_origin.as_ref(), - channel.as_ref(), - &announce_history, - &rid, - &target, - &announce, - OutboundNotice::RunResult, - ) - .await; - } else { - tracing::warn!( - run_id = %rid, - "Sub-agent completed but no recipient configured for announcement" - ); - } - }), - )); - - // Install the external owner before the first suspension after spawn. - let abort_handle = jh.abort_handle(); - task_control.attach(abort_handle.clone()); - crate::runtime::registry::attach_abort_handle(sub_agent_work_id, abort_handle.clone()); - watch_task_mode_monitor( - jh, - self.active_runs.clone(), - run_id.clone(), - Some(run_cleanup), - Some(task_control), - Some(sub_agent_work), - Some(terminal_journal), - ); - { - let mut runs = self.active_runs.write().await; - if let Some(run) = runs.iter_mut().find(|r| r.id == run_id) { - run.abort_handle = Some(abort_handle); - } + if mode == "process" { + return self.launch_process_run(launch).await; } - - Ok(SpawnOutcome::started( - run_id.clone(), - spawn_started_text("Sub-agent spawned", &run_id, child_delegation, announce_result), - )) + self.launch_task_run(launch).await } } @@ -1980,7 +948,7 @@ fn requested_agent_name(args: &serde_json::Value) -> Option<&str> { /// `policy` at the level of the run that sends an announcement: the gate /// applies the outbound scope at that run's level. -fn policy_at_level( +pub(super) fn policy_at_level( policy: &Arc, level: crate::security::AutonomyLevel, ) -> Arc { diff --git a/src/tools/sessions_spawn/task_launch.rs b/src/tools/sessions_spawn/task_launch.rs new file mode 100644 index 000000000..e8692a8c6 --- /dev/null +++ b/src/tools/sessions_spawn/task_launch.rs @@ -0,0 +1,560 @@ +//! Task-mode launch of one sub-agent run: in-process driver construction, registry row, and the driver +//! task that runs the child loop to its terminal state. + +use super::{ + SessionsSpawnTool, AllowedToolProxy, AnnounceOrigin, HistoryEntry, MemoryScope, OutboundNotice, SPAWN_EXECUTION_CONTEXT, + STEER_CHANNEL_CAPACITY, SpawnExecutionContext, SubAgentRun, SubAgentStatus, TaskRunControl, TerminationCause, + boxed_spawn_field, deliver_or_withhold_notice, format_announce_message, parse_memory_scope, + record_spawn_result_event, resolve_tools_for_agent, run_sub_agent_task, spawn_started_text, task_failure_reason, + task_terminal, termination_cause, watch_task_mode_monitor, +}; +use super::spawn::{SpawnLaunch, SpawnOutcome, policy_at_level}; +use crate::tools::traits::Tool; +use anyhow::Context as _; +use chrono::Utc; +use std::sync::Arc; +use tokio::sync::RwLock; +use tokio_util::sync::CancellationToken; + +impl SessionsSpawnTool { + /// Launch the run as an in-process task once `execute_spawn_with_id` has resolved + /// the request, provider route and admitted source into a [`SpawnLaunch`]. + pub(super) async fn launch_task_run(&self, launch: SpawnLaunch<'_>) -> anyhow::Result { + let SpawnLaunch { + operator_source, + message_input, + message_permit, + caller, + child_delegation, + ordinary_publication, + child_model_config, + launch_security, + child_level, + task, + spawn_scope, + parent_exec_ctx, + spawn_depth, + parent_run_id, + child_full, + inherited_channel_exclusions, + run_id, + session_scope_key, + selected_agent, + recipient, + run_channel_name, + operator_channel, + announce_result, + memory_fabric, + resolved_provider_name, + resolved_model, + temperature_override, + resolved_temperature, + ordinary_binding, + spawn_scope_for_event, + run_lineage, + tools, + source_receipt, + batch_id, + parent_hooks, + .. + } = launch; + // Create shared history and steer channel for this run + let history_arc: Arc>> = Arc::new(RwLock::new(super::continuation::seed_history())); + // Class B — bounded. Steering messages are produced by operators and by + // model tool calls, neither of which is rate-limited now that sub-agent + // concurrency is uncapped, while the consumer only polls between tool + // iterations. An unbounded queue therefore grows for the whole lifetime + // of a long-running sub-agent. + let (steer_tx, steer_rx) = tokio::sync::mpsc::channel::(STEER_CHANNEL_CAPACITY); + // Minted on the spawning task so the run's beat is parented on the + // caller's (see `crate::agent::idle::child_beat`). The sub-agent's own + // guarded turn parents *its* beat on this one, so every ProgressKind + // event it produces refreshes this row and the caller's window alike. + let task_progress = crate::agent::idle::child_beat(); + + // Clone everything the spawned task needs. + // Resolve the announce channel from the *per-turn* channel name bound to + // this run (the launching message's scope), not the shared active channel + // — so a concurrently-processed message cannot mis-route this run's + // result. Falls back to the active channel when no scope name is present. + let channel = match &operator_channel { + Some(channel) => Arc::clone(channel), + None => self.resolve_announce_channel(run_channel_name.as_deref()).await, + }; + let mut provider_name = resolved_provider_name; + let mut model = resolved_model; + let child_provider_binding = if let Some(source) = &operator_source { + let binding = Arc::new(crate::runtime::child_source::ChildProviderBinding::build_independent( + source, + )?); + provider_name = binding.provider_name().to_owned(); + model = binding.model().to_owned(); + Some(binding) + } else if let Some(binding) = ordinary_binding { + provider_name = binding.provider_name().to_owned(); + model = binding.model().to_owned(); + Some(binding) + } else { + None + }; + let temperature = resolved_temperature; + // An explicit hint always builds its exact selected chain, even when + // it names the gateway provider: the gateway may hold another route's + // credential. Direct models keep their existing provider plan. + if let Some(source) = &operator_source { + source.verify_live()?; + let binding = child_provider_binding + .as_ref() + .context("operator child model binding missing")?; + anyhow::ensure!( + Arc::ptr_eq(&binding.provider(), source.provider()), + "operator child provider differs from captured ingress" + ); + } + let provider = child_provider_binding + .as_ref() + .context("admitted sessions_spawn child model binding missing")? + .provider(); + let active_runs = self.active_runs.clone(); + let rid = run_id.clone(); + // Event bridge (v1.1a): if a chat-side sink is attached, create this + // session's middle channels + drainer up front (run_id is already + // minted, so the drainer is tagged with the correct id — no race). The + // background agent only ever `.send().await`s onto these; the drainer + // continuously empties them, so the agent never back-pressures. + let run_event_streams = self.event_sink.as_ref().map(|sink| sink.streams_for(&run_id)); + // NeedsInput (chat `/bg` only): mint this run's approval resolver so a + // supervised gate hit suspends awaiting an operator decision instead of + // auto-failing. `None` everywhere else (channels/gateway) preserves the + // historical auto-fail-on-gate semantics. + let run_approval_resolver = self + .approval_resolver_factory + .as_ref() + .map(|factory| factory.resolver_for(&run_id)); + // Only approval suspension needs the optional restoration registry. + // Every task still carries its admitted run identity, including mailbox + // continuations without an approval surface. + let restore_active_runs = run_approval_resolver.as_ref().map(|_| self.active_runs.clone()); + let restore_run_id = Some(run_id.clone()); + let task_owned = task.to_string(); + let identity_workspace = child_model_config.workspace_dir.clone(); + let security = Arc::clone(launch_security); + // Second handle, for the announcement gate: `security` above is moved + // into the sub-agent's own loop, and the announcement is authorized only + // once that loop has returned. + let announce_security = policy_at_level(launch_security, child_level); + // The launching turn's trusted identity, captured atomically with + // `recipient` / `run_channel_name` from the same scope snapshot. + let announce_origin = AnnounceOrigin::from_scope(spawn_scope.as_ref()); + // Same handle the run writes its transcript through, so a refused + // announcement is visible on the run itself and not only in the log. + let announce_history = history_arc.clone(); + let mut terminal_usage = None; + let mut task_execution_ctx = SpawnExecutionContext { + task_input: parent_exec_ctx + .as_ref() + .map(|context| context.task_input.clone()) + .unwrap_or_default(), + operator_authority: None, + ordinary_authority: None, + provider_binding: child_provider_binding, + terminal_usage: terminal_usage.clone(), + input_receipt: source_receipt, + run_id: rid.clone(), + session_scope_key: session_scope_key.clone(), + spawn_depth, + owner_id: run_lineage.owner_id.clone(), + owner_isolated: run_lineage.owner_isolated, + topic_id: run_lineage.topic_id.clone(), + source_message_event_id: run_lineage.source_message_event_id.clone(), + // A spawn-run context (this run may itself spawn): its children + // compute spawn_depth + 1. + is_turn_root: false, + channel_excluded_tools: inherited_channel_exclusions.clone(), + }; + let task_memory_fabric = memory_fabric.clone(); + let task_result_scope = spawn_scope_for_event.clone(); + let task_lineage = run_lineage.clone(); + let agent_label_for_registry = selected_agent.as_ref().map(|(name, _)| name.clone()); + let (system_prompt, filtered_tools) = if let Some((agent, cfg)) = selected_agent { + let identity_path = cfg + .identity_dir + .as_deref() + .map(str::trim) + .filter(|value| !value.is_empty()) + .map(|directory| identity_workspace.join(directory)); + let prompt = crate::identity::delegated::compose(identity_path.as_deref(), cfg.system_prompt.as_deref()); + let memory_scope = parse_memory_scope(cfg.memory_scope.as_deref())?; + let tools = tools.map(|registry| { + if ordinary_publication.is_some() { + // Keep the backend root identity and dynamic metadata for + // the sealed catalog. The child service enforces the exact + // manifest, agent allowance and inherited exclusions. + let memory_prefix = (memory_scope == MemoryScope::Isolated).then(|| agent.clone()); + return Arc::new( + registry + .iter() + .map(|tool| { + Box::new(AllowedToolProxy { + source: Arc::clone(®istry), + public_name: tool.name().to_owned(), + memory_prefix: memory_prefix.clone(), + }) as Box + }) + .collect(), + ); + } + resolve_tools_for_agent( + registry, + &agent, + memory_scope, + if child_full || cfg.allowed_tools.is_empty() { + None + } else { + Some(&cfg.allowed_tools) + }, + &inherited_channel_exclusions, + ) + }); + (prompt, tools) + } else { + (crate::identity::delegated::DEFAULT_PROMPT.to_owned(), tools) + }; + + // Register the run. + // + // A background run outlives its spawning turn. Its independent observer + // owns cleanup; parenting this to the caller would cancel valid work + // when that caller returns. Register before publishing the active row. + let task_control = TaskRunControl::new(); + let stop_token = task_control.cancellation().clone(); + let message_turn = super::message_lifetime::retain( + child_model_config, + message_input.as_ref(), + &self.active_runs, + Arc::new(move || stop_token.cancel()), + )?; + if let Some(source) = &operator_source { + let (authority, lifetime) = source.issue_task( + Arc::clone( + task_execution_ctx + .provider_binding + .as_ref() + .context("operator model binding missing")?, + ), + &task_result_scope, + task, + task_execution_ctx.input_receipt.as_deref(), + task_control.cancellation(), + )?; + task_control.retain_operator_lifetime(lifetime)?; + use crate::runtime::turn_source::TurnSourceProof; + let usage = Arc::new(crate::runtime::turn_terminal::TerminalUsageCollector::new_ordinary( + authority.workspace_id().to_owned(), + authority.owner_id().to_owned(), + rid.clone(), + authority.generation().effective.memory.event_recording_config(), + )); + terminal_usage = Some(Arc::clone(&usage)); + task_execution_ctx.terminal_usage = Some(usage); + task_execution_ctx.operator_authority = Some(authority); + } + if ordinary_publication.is_some() { + let binding = task_execution_ctx + .provider_binding + .as_ref() + .context("ordinary task provider binding missing")?; + let caller = caller.as_ref().context("ordinary task caller missing")?; + let (authority, lifetime) = binding.issue_ordinary_task( + caller, + &task_result_scope, + task, + task_execution_ctx.input_receipt.as_deref(), + task_control.cancellation(), + )?; + task_control.retain_ordinary_lifetime(lifetime)?; + use crate::runtime::turn_source::TurnSourceProof; + let (proof, _) = authority.source()?; + let usage = Arc::new(crate::runtime::turn_terminal::TerminalUsageCollector::new_ordinary( + proof.workspace_id().to_owned(), + proof.owner_id().to_owned(), + rid.clone(), + authority + .publication() + .generation() + .effective + .memory + .event_recording_config(), + )); + terminal_usage = Some(Arc::clone(&usage)); + task_execution_ctx.terminal_usage = Some(usage); + task_execution_ctx.ordinary_authority = Some(authority); + } + let logical_terminal = { + use crate::agent::terminal::logical::LogicalTaskTerminalRef; + match ( + task_execution_ctx.ordinary_authority.as_deref(), + task_execution_ctx.operator_authority.as_deref(), + ) { + (Some(authority), None) => LogicalTaskTerminalRef::ordinary(authority)?, + (None, Some(authority)) => LogicalTaskTerminalRef::operator(authority)?, + _ => anyhow::bail!("logical task completion requires one issued source authority"), + } + }; + let run_cleanup = Arc::new(crate::runtime::turn_cleanup::CleanupTracker::default()); + let run_cleanup_scope = + crate::runtime::turn_cleanup::CleanupScope::new(Some(&run_cleanup), CancellationToken::new())?; + + // Deliberately the *last* fallible-free step before the driver task is + // spawned, and never earlier: everything between this block and + // `tokio::spawn` below is infallible, so the presence of a row in + // `active_runs` implies a driver task that will publish a terminal status + // for it. Registering before the fallible preparation above (agent prompt + // and tool resolution) left a `Running` row behind on every early return — + // no abort handle, no driver task, no observer — and `join` polls such a + // row forever, with no wall-clock fallback in this runtime to break the + // tie. Keep any new fallible step above this block. + // + // `abort_handle` is filled in right after `tokio::spawn` returns. + { + let mut runs = self.active_runs.write().await; + super::continuation::register( + &mut runs, + SubAgentRun { + agent_partition: spawn_scope_for_event.agent_partition.clone(), + id: run_id.clone(), + task: task.to_string(), + owner_id: run_lineage.owner_id.clone(), + topic_id: run_lineage.topic_id.clone(), + source_message_event_id: run_lineage.source_message_event_id.clone(), + started_at: Utc::now(), + finished_at: None, + status: SubAgentStatus::Running, + recipient: recipient.clone(), + channel_name: run_channel_name.clone(), + abort_handle: None, + process_control: None, + task_control: Some(Arc::clone(&task_control)), + history: history_arc.clone(), + steer_tx: Some(steer_tx.clone()), + parent_run_id: parent_run_id.clone(), + session_scope_key: session_scope_key.clone(), + spawn_depth, + // Recursive delegation status is issued by no parent (P2-G4). + delegation: None, + token_usage_records: Vec::new(), + progress: Arc::clone(&task_progress), + batch_id: batch_id.map(str::to_string), + }, + )?; + } + + // Registry row for this run. Parent captured on the spawning task, which + // is the enclosing turn (not the launching tool call, which is gone once + // it returns); a spawned task inherits no task-locals of its own. + let sub_agent_parent = crate::runtime::registry::current_owner_work_id(); + let sub_agent_label = agent_label_for_registry.unwrap_or_else(|| "sub-agent".to_string()); + let mut sub_agent_work = + crate::runtime::registry::register_sub_agent(&sub_agent_label, &rid, sub_agent_parent, batch_id, None); + let sub_agent_work_id = sub_agent_work.id(); + sub_agent_work.require_cleanup_acknowledgement(); + // As in the process branch: the control plane resolves `run_id` through + // the process-wide work registry, so the run's existing steer sender is + // published there. `active_runs` stays the tool-plane source of truth. + crate::runtime::registry::attach_steer_sender(sub_agent_work_id, steer_tx.clone()); + + let terminal_journal = Arc::new(task_terminal::TaskTerminalJournal::new( + task_memory_fabric.clone(), + task_result_scope.clone(), + logical_terminal, + true, + terminal_usage, + )); + let driver_terminal_journal = Arc::clone(&terminal_journal); + // Spawn async task (fire-and-forget); capture handle to support kill + let jh = crate::agent::channel_approval::spawn(crate::runtime::registry::scope_current( + sub_agent_work_id, + SPAWN_EXECUTION_CONTEXT.scope(task_execution_ctx, async move { + let _message_permit = message_permit; + let _message_input = message_input; + let _message_turn = message_turn; + tracing::info!(run_id = %rid, "Sub-agent task starting"); + let provider_started_at = Utc::now(); + let (run_on_delta, run_on_tool) = match run_event_streams { + Some((delta_tx, tool_tx)) => (Some(delta_tx), Some(tool_tx)), + None => (None, None), + }; + // Construct the large child loop behind the existing allocation + // boundary before adding task-local temperature ownership. + let run_future = boxed_spawn_field(|| { + run_sub_agent_task( + &task_owned, + provider, + &provider_name, + &model, + temperature, + filtered_tools, + &system_prompt, + security, + steer_rx, + history_arc, + run_on_delta, + run_on_tool, + run_approval_resolver, + restore_active_runs, + restore_run_id, + Arc::clone(&task_progress), + parent_hooks, + ) + }); + let result = run_cleanup_scope + .run(crate::providers::model_settings::with_temperature( + temperature_override, + run_future, + )) + .await; + tracing::info!(run_id = %rid, success = result.is_ok(), "Sub-agent task finished"); + + let (status, result_text, terminal_status, history_projection, token_usage_records) = match result { + Ok(task_result) => ( + SubAgentStatus::Completed(task_result.output.clone()), + task_result.output.clone(), + crate::agent::terminal::TurnTerminalStatus::Completed, + Some(crate::agent::terminal::TurnHistoryProjection { + assistant_content: task_result.output, + history_commit_len: task_result.history_commit_len, + }), + task_result.segment_usage, + ), + Err(error) => { + // Persist the same runtime-classified reason used by the + // live registry. Recovery after commit must not lose the + // quarantine tag on provider/tool-authored failure text. + let reason = task_failure_reason(&error); + let terminal_status = if matches!(termination_cause(&reason), TerminationCause::Killed) { + crate::agent::terminal::TurnTerminalStatus::Cancelled + } else { + crate::agent::terminal::TurnTerminalStatus::Failed + }; + ( + SubAgentStatus::Failed(reason.clone()), + reason, + terminal_status, + None, + Vec::new(), + ) + } + }; + + let delivery_intent = recipient.as_ref().map_or_else( + || crate::agent::terminal::TurnDeliveryIntent::Deferred { + route: "sessions_registry".to_string(), + }, + |target| crate::agent::terminal::TurnDeliveryIntent::Reply { target: target.clone() }, + ); + match driver_terminal_journal + .commit(crate::agent::terminal::TurnTerminalDraft { + binding: None, + terminal_id: rid.clone(), + scope: task_result_scope.clone(), + status: terminal_status, + history: history_projection, + history_scope: None, + provider_outcome: None, + telemetry: crate::agent::terminal::TurnTerminalTelemetry { + summary: result_text.clone(), + started_at: provider_started_at, + finished_at: Utc::now(), + }, + delivery_intent, + }) + .await + { + Ok(_) => {} + Err(error) => { + tracing::error!(run_id = %rid, error = %error, "task terminal persistence remains unconfirmed"); + // The external observer retries this exact proposal. + // Do not publish a result or a substitute usage receipt. + return; + } + } + let announce = format_announce_message(&rid, &status, &result_text); + record_spawn_result_event( + Some(&task_memory_fabric), + task_result_scope, + &result_text, + &status, + &task_lineage, + None, + ) + .await; + + // Update run status + { + let mut runs = active_runs.write().await; + if let Some(run) = runs.iter_mut().find(|r| r.id == rid) { + run.finished_at = Some(Utc::now()); + run.status = status; + run.token_usage_records.extend(token_usage_records); + run.steer_tx = None; // drop sender — no more steering possible + } + } + + // Announce result back to channel if we have a recipient + if !announce_result { + tracing::debug!( + run_id = %rid, + "Sub-agent result withheld from the channel (announce=false); \ + it is delivered to whoever joins this run's batch" + ); + } else if let Some(target) = recipient { + // MUTATION GUARD: route this straight to `channel.send` and the + // model-supplied `recipient` on the spawn call reaches the + // channel with no authorization at all — the hole + // `message_send`'s own outbound gate closes on its side. + deliver_or_withhold_notice( + &announce_security, + announce_origin.as_ref(), + channel.as_ref(), + &announce_history, + &rid, + &target, + &announce, + OutboundNotice::RunResult, + ) + .await; + } else { + tracing::warn!( + run_id = %rid, + "Sub-agent completed but no recipient configured for announcement" + ); + } + }), + )); + + // Install the external owner before the first suspension after spawn. + let abort_handle = jh.abort_handle(); + task_control.attach(abort_handle.clone()); + crate::runtime::registry::attach_abort_handle(sub_agent_work_id, abort_handle.clone()); + watch_task_mode_monitor( + jh, + self.active_runs.clone(), + run_id.clone(), + Some(run_cleanup), + Some(task_control), + Some(sub_agent_work), + Some(terminal_journal), + ); + { + let mut runs = self.active_runs.write().await; + if let Some(run) = runs.iter_mut().find(|r| r.id == run_id) { + run.abort_handle = Some(abort_handle); + } + } + + Ok(SpawnOutcome::started( + run_id.clone(), + spawn_started_text("Sub-agent spawned", &run_id, child_delegation, announce_result), + )) + } +} diff --git a/tests/architecture_boundaries/compaction.rs b/tests/architecture_boundaries/compaction.rs index 71498bb87..5fb4e6e3d 100644 --- a/tests/architecture_boundaries/compaction.rs +++ b/tests/architecture_boundaries/compaction.rs @@ -356,7 +356,7 @@ const FORWARDED_COMPACTION_PRODUCERS: &[(&str, &str, &str, Option<&str>)] = &[ ( "src/tools/sessions_spawn/spawn.rs", "execute_spawn_with_id", - "&process_compaction_config", + "resolved_compaction.config.clone()", None, ), ]; From 7e090a8d44144aaaec687235f9bc5dba3d52ca47 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:55:01 +0400 Subject: [PATCH 0101/1567] fix(sync): read a child's mode from its session record so process children never project as task A child_session.upsert whose header run is a turn-level segment run found no task.spawned event and fell back to mode task. The mode now comes from the child session record, and the snapshot no longer picks a segment run as the child's latest event. --- src/memory/sqlite/sync_lifecycle.rs | 11 +++++++++++ src/memory/sqlite/sync_snapshot.rs | 2 +- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/memory/sqlite/sync_lifecycle.rs b/src/memory/sqlite/sync_lifecycle.rs index 69c00cb22..15b515272 100644 --- a/src/memory/sqlite/sync_lifecycle.rs +++ b/src/memory/sqlite/sync_lifecycle.rs @@ -55,6 +55,17 @@ pub(super) fn child_payload(conn: &Connection, h: &Header) -> anyhow::Result = conn + .query_row( + "SELECT json_extract(record,'$.mode') FROM child_sessions WHERE key=?1 AND owner_id=?2", + params![h.session, h.owner], + |r| r.get(0), + ) + .optional()? + .flatten(); + let mode = recorded_mode.or(mode); let (status, ended) = if let Some(id) = h.source_ref.strip_prefix("memory:") { let kind: Option = conn .query_row( diff --git a/src/memory/sqlite/sync_snapshot.rs b/src/memory/sqlite/sync_snapshot.rs index 21420669d..c34c63dab 100644 --- a/src/memory/sqlite/sync_snapshot.rs +++ b/src/memory/sqlite/sync_snapshot.rs @@ -80,7 +80,7 @@ fn inventory(conn: &Connection, id: &str, owner: &str, head: i64, water: i64) -> ), )?; } - let mut q=conn.prepare("SELECT e.event_id FROM message_events e WHERE e.owner_id=?1 AND e.parent_run_id IS NOT NULL AND e.id<=?2 AND e.id=(SELECT x.id FROM message_events x WHERE x.owner_id=e.owner_id AND x.session_key=e.session_key AND x.parent_run_id IS NOT NULL AND x.id<=?2 ORDER BY (x.event_type IN('turn.finalized','turn.admission.failed')) DESC,x.id DESC LIMIT 1) ORDER BY e.session_key")?; + let mut q=conn.prepare("SELECT e.event_id FROM message_events e WHERE e.owner_id=?1 AND e.parent_run_id IS NOT NULL AND e.id<=?2 AND COALESCE(e.run_id,'') NOT LIKE 'child-segment:%' AND COALESCE(e.run_id,'') NOT LIKE 'operator-worker-segment:%' AND e.id=(SELECT x.id FROM message_events x WHERE x.owner_id=e.owner_id AND x.session_key=e.session_key AND x.parent_run_id IS NOT NULL AND x.id<=?2 AND COALESCE(x.run_id,'') NOT LIKE 'child-segment:%' AND COALESCE(x.run_id,'') NOT LIKE 'operator-worker-segment:%' ORDER BY (x.event_type IN('turn.finalized','turn.admission.failed')) DESC,x.id DESC LIMIT 1) ORDER BY e.session_key")?; for source in q.query_map(params![owner, water], |r| r.get::<_, String>(0))? { let source = source?; if let Some(mut h) = super::sync_journal::event_header(conn, &source, "child_session.upsert")? { From d53f742d4be11f412998f4e60a638d7b09fb4cf9 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:55:51 +0400 Subject: [PATCH 0102/1567] fix(sync): project one terminal child_session.upsert per child run A child run ended three times for clients: the segment turn terminal (child-end with the segment run id), the run turn terminal (child-end) and the terminal task event (child). A segment terminal ends one turn, not the child session, so it no longer produces an upsert. Of the run's two remaining writers the first one written holds the slot; the other adds nothing. --- src/memory/sqlite/sync_journal.rs | 15 +++++++++++---- src/memory/sqlite/sync_lifecycle.rs | 27 ++++++++++++++++++++++++++- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/src/memory/sqlite/sync_journal.rs b/src/memory/sqlite/sync_journal.rs index 376cd8f12..fef914f21 100644 --- a/src/memory/sqlite/sync_journal.rs +++ b/src/memory/sqlite/sync_journal.rs @@ -327,10 +327,17 @@ pub(super) fn event_written(conn: &Connection, event: &crate::memory::MessageEve if let Some(run) = &event.run_id { super::sync_lifecycle::cancel_approvals(conn, &h, &event.workspace_id, run, status == "cancelled")?; } - if h.parent_run_id.is_some() { - h.kind = "child_session.upsert".into(); - h.event_id = format!("child-end:{}", event.event_id); - append(conn, &h)?; + // The end of the child session is its run's terminal. A segment's own + // terminal ends one turn only, and a run that already has a terminal + // upsert (from its `task.*` event) keeps that one. + if let Some(run) = h.run_id.clone().filter(|_| h.parent_run_id.is_some()) { + if !super::sync_lifecycle::is_segment_run(&run) + && !super::sync_lifecycle::terminal_upsert_exists(conn, &h.owner, &run)? + { + h.kind = "child_session.upsert".into(); + h.event_id = format!("child-end:{}", event.event_id); + append(conn, &h)?; + } } } Ok(()) diff --git a/src/memory/sqlite/sync_lifecycle.rs b/src/memory/sqlite/sync_lifecycle.rs index 15b515272..e2d02ea4f 100644 --- a/src/memory/sqlite/sync_lifecycle.rs +++ b/src/memory/sqlite/sync_lifecycle.rs @@ -34,7 +34,11 @@ pub(super) fn memory_written(conn: &Connection, event: &MemoryEvent) -> anyhow:: h.source_ref = format!("memory:{}", event.event_id); h.event_id = format!("child:{}", event.event_id); h.timestamp = event.created_at.clone(); - append(conn, &h)?; + // A child run ends once for clients: a terminal already projected from the + // run's own turn terminal keeps the slot. + if event.event_type == "task.spawned" || !terminal_upsert_exists(conn, &h.owner, run)? { + append(conn, &h)?; + } if event.event_type == "task.spawned" { h.kind = "turn.started".into(); h.event_id = format!("child-turn:{}", event.event_id); @@ -43,6 +47,27 @@ pub(super) fn memory_written(conn: &Connection, event: &MemoryEvent) -> anyhow:: Ok(()) } +/// Turn-level segment runs of a child (`child-segment:` for ordinary children, +/// `operator-worker-segment:` for operator ones). Their terminal is a fact about +/// one turn, never the end of the child session. +pub(super) fn is_segment_run(run: &str) -> bool { + run.starts_with("child-segment:") || run.starts_with("operator-worker-segment:") +} + +/// Whether the child run already has a terminal `child_session.upsert` in the +/// journal: one projected from its turn terminal (`child-end:`), or one from +/// its terminal `task.*` event (`child:`). The first one written is the +/// authoritative end of the run; later writers add nothing. +pub(super) fn terminal_upsert_exists(conn: &Connection, owner: &str, run: &str) -> anyhow::Result { + Ok(conn.query_row( + "SELECT EXISTS(SELECT 1 FROM sync_journal j WHERE j.owner_id=?1 AND j.run_id=?2 AND j.kind='child_session.upsert' + AND (j.event_id LIKE 'child-end:%' OR j.source_ref IN (SELECT 'memory:'||m.event_id FROM memory_events m + WHERE m.owner_id=?1 AND m.run_id=?2 AND m.event_type IN ('task.completed','task.failed','task.cancelled'))))", + params![owner, run], + |r| r.get(0), + )?) +} + pub(super) fn child_payload(conn: &Connection, h: &Header) -> anyhow::Result { let deleted:bool=conn.query_row("SELECT EXISTS(SELECT 1 FROM rf_message_attempts a WHERE a.owner_id=?1 AND a.run_id=?2 AND (a.deleted_at IS NOT NULL OR a.reply_deleted_at IS NOT NULL OR EXISTS(SELECT 1 FROM agent_erase_fences f WHERE f.scope_id=a.ma_scope_id)))",params![h.owner,h.root_run_id.as_ref().or(h.run_id.as_ref())],|r|r.get(0))?; if deleted { From aace69ff5b62e92f3b0841c41a05fa414794b8d3 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:56:40 +0400 Subject: [PATCH 0103/1567] fix(sync): close the unfinished turns of a child whose run was settled as cancelled or failed A process child that was killed or died left its own turn and its segment turns without a terminal journal entry, because the worker that would have written the marker was gone. When the terminal task event settles the run, each such turn now gets one turn.cancelled or turn.failed entry, with a fixed per-run id; a turn that already has its marker keeps it, and a marker projected later is dropped. --- src/memory/sqlite/sync_journal.rs | 12 +++++- src/memory/sqlite/sync_lifecycle.rs | 58 +++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) diff --git a/src/memory/sqlite/sync_journal.rs b/src/memory/sqlite/sync_journal.rs index fef914f21..01f94344a 100644 --- a/src/memory/sqlite/sync_journal.rs +++ b/src/memory/sqlite/sync_journal.rs @@ -308,7 +308,17 @@ pub(super) fn event_written(conn: &Connection, event: &crate::memory::MessageEve "cancelled" => Some("turn.cancelled"), _ => Some("turn.failed"), }; - if let Some(kind) = kind { + // A turn the parent already closed after its writer died keeps that + // terminal; the real marker adds none. + let closed: bool = match &h.run_id { + Some(run) => conn.query_row( + "SELECT EXISTS(SELECT 1 FROM sync_journal WHERE event_id=?1)", + [super::sync_lifecycle::open_terminal_id(run)], + |r| r.get(0), + )?, + None => false, + }; + if let Some(kind) = kind.filter(|_| !closed) { h.kind = kind.into(); h.event_id = format!("terminal:{}", event.event_id); append(conn, &h)?; diff --git a/src/memory/sqlite/sync_lifecycle.rs b/src/memory/sqlite/sync_lifecycle.rs index e2d02ea4f..e7487c61b 100644 --- a/src/memory/sqlite/sync_lifecycle.rs +++ b/src/memory/sqlite/sync_lifecycle.rs @@ -34,6 +34,14 @@ pub(super) fn memory_written(conn: &Connection, event: &MemoryEvent) -> anyhow:: h.source_ref = format!("memory:{}", event.event_id); h.event_id = format!("child:{}", event.event_id); h.timestamp = event.created_at.clone(); + if matches!(event.event_type.as_str(), "task.cancelled" | "task.failed") { + let kind = if event.event_type == "task.cancelled" { + "turn.cancelled" + } else { + "turn.failed" + }; + close_open_turns(conn, event, &source, kind)?; + } // A child run ends once for clients: a terminal already projected from the // run's own turn terminal keeps the slot. if event.event_type == "task.spawned" || !terminal_upsert_exists(conn, &h.owner, run)? { @@ -47,6 +55,56 @@ pub(super) fn memory_written(conn: &Connection, event: &MemoryEvent) -> anyhow:: Ok(()) } +/// The journal id of the terminal written for a turn that its own writer never +/// finished. A turn terminal projected later from the real marker is dropped +/// when this one exists. +pub(super) fn open_terminal_id(run: &str) -> String { + format!("terminal:open:{run}") +} + +/// A child whose run ended as cancelled or failed may leave its own turn and +/// its segment turns without a terminal: the worker that would have written +/// it was killed or died. The parent has settled the run, so each such turn +/// ends here, once, with the settlement's kind. A turn that already has its +/// marker keeps it, and the id is fixed per run so a replay adds nothing. +fn close_open_turns(conn: &Connection, event: &MemoryEvent, source: &str, kind: &str) -> anyhow::Result<()> { + let mut firsts = vec![source.to_owned()]; + let mut query = conn.prepare( + "SELECT e.event_id FROM message_events e + WHERE e.workspace_id=?1 AND e.owner_id=?2 + AND e.session_key=(SELECT s.session_key FROM message_events s WHERE s.event_id=?3) + AND (e.run_id LIKE 'child-segment:%' OR e.run_id LIKE 'operator-worker-segment:%') + AND e.id=(SELECT MIN(x.id) FROM message_events x WHERE x.workspace_id=e.workspace_id AND x.owner_id=e.owner_id AND x.run_id=e.run_id) + ORDER BY e.id", + )?; + for row in query.query_map(params![event.workspace_id, event.owner_id, source], |r| { + r.get::<_, String>(0) + })? { + firsts.push(row?); + } + for first in firsts { + let Some(mut h) = event_header(conn, &first, kind)? else { + continue; + }; + let Some(run) = h.run_id.clone() else { + continue; + }; + let finished: bool = conn.query_row( + "SELECT EXISTS(SELECT 1 FROM message_events WHERE workspace_id=?1 AND owner_id=?2 AND run_id=?3 + AND event_type IN ('turn.finalized','turn.admission.failed'))", + params![event.workspace_id, h.owner, run], + |r| r.get(0), + )?; + if finished { + continue; + } + h.event_id = open_terminal_id(&run); + h.timestamp = event.created_at.clone(); + append(conn, &h)?; + } + Ok(()) +} + /// Turn-level segment runs of a child (`child-segment:` for ordinary children, /// `operator-worker-segment:` for operator ones). Their terminal is a fact about /// one turn, never the end of the child session. From d634de8c2abd345d3c320f815475fae54224f049 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:57:14 +0400 Subject: [PATCH 0104/1567] fix(sync): do not project a root session's batch journal events as a child session The batch membership journal writes events under the root session with the root run as parent run. The snapshot and the live journal took them for a child session of the root itself, in mode task, that never reached a terminal status. An event whose parent session is its own session is not a child event. --- src/memory/sqlite/sync_journal.rs | 8 ++++++-- src/memory/sqlite/sync_snapshot.rs | 2 +- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/memory/sqlite/sync_journal.rs b/src/memory/sqlite/sync_journal.rs index 01f94344a..36b85e214 100644 --- a/src/memory/sqlite/sync_journal.rs +++ b/src/memory/sqlite/sync_journal.rs @@ -267,8 +267,12 @@ pub(super) fn event_written(conn: &Connection, event: &crate::memory::MessageEve append(conn, &h)?; } } + // An event of a session written on behalf of that same session (the batch + // membership journal of a root run) carries the run's parent link but is + // not a child session. + let own_session = event.parent_session_key.is_some() && event.parent_session_key == event.session_key; // Root user rows are appended by admit, after their attempt is inserted. - if h.parent_run_id.is_some() { + if h.parent_run_id.is_some() && !own_session { let first: bool = conn.query_row( "SELECT NOT EXISTS(SELECT 1 FROM sync_journal WHERE owner_id=?1 AND session=?2 AND kind='session.upsert')", params![h.owner, h.session], @@ -340,7 +344,7 @@ pub(super) fn event_written(conn: &Connection, event: &crate::memory::MessageEve // The end of the child session is its run's terminal. A segment's own // terminal ends one turn only, and a run that already has a terminal // upsert (from its `task.*` event) keeps that one. - if let Some(run) = h.run_id.clone().filter(|_| h.parent_run_id.is_some()) { + if let Some(run) = h.run_id.clone().filter(|_| h.parent_run_id.is_some() && !own_session) { if !super::sync_lifecycle::is_segment_run(&run) && !super::sync_lifecycle::terminal_upsert_exists(conn, &h.owner, &run)? { diff --git a/src/memory/sqlite/sync_snapshot.rs b/src/memory/sqlite/sync_snapshot.rs index c34c63dab..c376bf575 100644 --- a/src/memory/sqlite/sync_snapshot.rs +++ b/src/memory/sqlite/sync_snapshot.rs @@ -80,7 +80,7 @@ fn inventory(conn: &Connection, id: &str, owner: &str, head: i64, water: i64) -> ), )?; } - let mut q=conn.prepare("SELECT e.event_id FROM message_events e WHERE e.owner_id=?1 AND e.parent_run_id IS NOT NULL AND e.id<=?2 AND COALESCE(e.run_id,'') NOT LIKE 'child-segment:%' AND COALESCE(e.run_id,'') NOT LIKE 'operator-worker-segment:%' AND e.id=(SELECT x.id FROM message_events x WHERE x.owner_id=e.owner_id AND x.session_key=e.session_key AND x.parent_run_id IS NOT NULL AND x.id<=?2 AND COALESCE(x.run_id,'') NOT LIKE 'child-segment:%' AND COALESCE(x.run_id,'') NOT LIKE 'operator-worker-segment:%' ORDER BY (x.event_type IN('turn.finalized','turn.admission.failed')) DESC,x.id DESC LIMIT 1) ORDER BY e.session_key")?; + let mut q=conn.prepare("SELECT e.event_id FROM message_events e WHERE e.owner_id=?1 AND e.parent_run_id IS NOT NULL AND e.id<=?2 AND COALESCE(e.parent_session_key,'')<>e.session_key AND COALESCE(e.run_id,'') NOT LIKE 'child-segment:%' AND COALESCE(e.run_id,'') NOT LIKE 'operator-worker-segment:%' AND e.id=(SELECT x.id FROM message_events x WHERE x.owner_id=e.owner_id AND x.session_key=e.session_key AND x.parent_run_id IS NOT NULL AND x.id<=?2 AND COALESCE(x.parent_session_key,'')<>x.session_key AND COALESCE(x.run_id,'') NOT LIKE 'child-segment:%' AND COALESCE(x.run_id,'') NOT LIKE 'operator-worker-segment:%' ORDER BY (x.event_type IN('turn.finalized','turn.admission.failed')) DESC,x.id DESC LIMIT 1) ORDER BY e.session_key")?; for source in q.query_map(params![owner, water], |r| r.get::<_, String>(0))? { let source = source?; if let Some(mut h) = super::sync_journal::event_header(conn, &source, "child_session.upsert")? { From 5ae38259b9f246fdc66ed02d0e20a2da31e3a7c8 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:57:55 +0400 Subject: [PATCH 0105/1567] fix(sessions): a process child whose owner went away ends failed for clients When the owner of a process child exits, or a later start finds a leftover whose owner is gone, only an unconfirmed result row was written, so clients showed the child running forever. The writer of that row now also records task.failed naming the owner-loss cause. A result row the worker wrote first wins, and then nothing is added. --- src/tools/sessions_spawn/events.rs | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/src/tools/sessions_spawn/events.rs b/src/tools/sessions_spawn/events.rs index cd88d0a9a..8987e28cd 100644 --- a/src/tools/sessions_spawn/events.rs +++ b/src/tools/sessions_spawn/events.rs @@ -148,6 +148,7 @@ pub(super) async fn record_owner_loss_terminal( ) -> anyhow::Result { let key = crate::session_worker::protocol::worker_result_key(run_id); let code = reason.code(); + let task_scope = scope.clone(); let payload = json!({ "success": false, "error": code, @@ -169,7 +170,31 @@ pub(super) async fn record_owner_loss_terminal( || (event.idempotency_key.as_deref() == Some(key.as_str()) && event.run_id.as_deref() == Some(run_id)), "process worker result row differs from its run" ); - Ok(event.id > 0 && event.raw_payload_json.as_deref() == Some(payload.as_str())) + let created = event.id > 0 && event.raw_payload_json.as_deref() == Some(payload.as_str()); + if created { + // Nobody requested this stop and no writer is left: the child ended + // failed, and clients read that from the task event. Only the writer + // of the run's single result row records it, so a result the worker + // wrote first (and the turn terminal it came with) stays the outcome. + let message = format!( + "Sub-agent process ended without a result: its owner went away ({code}); cleanup and provider usage remain unconfirmed" + ); + let task_payload = json!({ + "success": false, + "error": message, + "result_preview": message, + "owner_id": task_scope.owner_id, + "reason": code, + }) + .to_string(); + if let Err(error) = fabric + .record_task_event(task_scope, run_id.to_owned(), "task.failed", Some(task_payload)) + .await + { + tracing::warn!("failed to record owner-loss task.failed event: {error}"); + } + } + Ok(created) } pub(super) async fn record_spawn_result_event( From 68ff9adb3fea1b48ca41f87b5db774879d003518 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:58:36 +0400 Subject: [PATCH 0106/1567] fix(sessions): a run restored from a stored cancelled result reads as cancelled Restart recovery restored every unsuccessful stored result as a failure the sub-agent reported about itself. A stored result that carries the cancelled flag now restores as the stopped run it was, the same value the run had before the restart. The parent's own result row for a requested stop carries the flag too. --- src/tools/sessions_spawn/events.rs | 27 +++++++++++-------- src/tools/sessions_spawn/process_terminal.rs | 4 +++ .../process_terminal/stored_result.rs | 5 ++++ 3 files changed, 25 insertions(+), 11 deletions(-) diff --git a/src/tools/sessions_spawn/events.rs b/src/tools/sessions_spawn/events.rs index 8987e28cd..5c123db85 100644 --- a/src/tools/sessions_spawn/events.rs +++ b/src/tools/sessions_spawn/events.rs @@ -237,17 +237,22 @@ pub(super) async fn record_spawn_result_event_keyed( // The result and task records carry the sub-agent's reply or error text: // redacted like the terminal commit (D-053). let content = crate::agent::terminal::redact_persisted_text(result_text); - let payload = Some( - crate::agent::terminal::redact_persisted_json(json!({ - "success": success, - "error": error, - "owner_id": lineage.owner_id, - "topic_id": lineage.topic_id, - "parent_task_id": lineage.parent_task_id, - "source_message_event_id": lineage.source_message_event_id - })) - .to_string(), - ); + let mut result_payload = json!({ + "success": success, + "error": error, + "owner_id": lineage.owner_id, + "topic_id": lineage.topic_id, + "parent_task_id": lineage.parent_task_id, + "source_message_event_id": lineage.source_message_event_id + }); + // The same flag the worker's own result row carries, so a restart reads + // either writer's row as cancelled. + if terminal_event_type == Some("task.cancelled") { + if let Some(object) = result_payload.as_object_mut() { + object.insert("cancelled".to_owned(), json!(true)); + } + } + let payload = Some(crate::agent::terminal::redact_persisted_json(result_payload).to_string()); let recorded = match result_key { Some(key) => { fabric diff --git a/src/tools/sessions_spawn/process_terminal.rs b/src/tools/sessions_spawn/process_terminal.rs index 122550f8b..a87311bdb 100644 --- a/src/tools/sessions_spawn/process_terminal.rs +++ b/src/tools/sessions_spawn/process_terminal.rs @@ -178,6 +178,10 @@ impl RecoveredProcessRun { RecoveredProcessOutcome::StoredResult(stored, recovered) => { let status = if stored.success { SubAgentStatus::Completed(stored.content.clone()) + } else if stored.cancelled { + // `SubAgentStatus` has no cancelled value: a stopped run + // reads as the operator kill it was, as before the restart. + SubAgentStatus::Failed(super::KILLED_BY_USER_REASON.to_owned()) } else { SubAgentStatus::Failed(super::sub_agent_reported_failure(&stored.content)) }; diff --git a/src/tools/sessions_spawn/process_terminal/stored_result.rs b/src/tools/sessions_spawn/process_terminal/stored_result.rs index 1fee89739..125039b48 100644 --- a/src/tools/sessions_spawn/process_terminal/stored_result.rs +++ b/src/tools/sessions_spawn/process_terminal/stored_result.rs @@ -6,6 +6,9 @@ use anyhow::Context; /// What a finished process child recorded under its single result key. pub(in crate::tools::sessions_spawn) struct StoredWorkerResult { pub(in crate::tools::sessions_spawn) success: bool, + /// The run ended because its work was cancelled (a requested stop or the + /// worker's own cancelled result), not because it failed. + pub(in crate::tools::sessions_spawn) cancelled: bool, /// The reply on success, the failure text otherwise (already redacted). pub(in crate::tools::sessions_spawn) content: String, pub(in crate::tools::sessions_spawn) finished_at: chrono::DateTime, @@ -45,6 +48,7 @@ pub(super) async fn read(fabric: &MemoryFabric, owner: &str, run: &str) -> anyho .get("success") .and_then(serde_json::Value::as_bool) .context("stored worker result success flag missing")?; + let cancelled = payload.get("cancelled").and_then(serde_json::Value::as_bool) == Some(true); let content = if success { event.content } else { @@ -56,6 +60,7 @@ pub(super) async fn read(fabric: &MemoryFabric, owner: &str, run: &str) -> anyho let finished_at = chrono::DateTime::parse_from_rfc3339(&event.created_at)?.with_timezone(&chrono::Utc); Ok(Some(StoredWorkerResult { success, + cancelled, content, finished_at, })) From 6b0e7a94af96c36271b688da34b486545048672a Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:58:36 +0400 Subject: [PATCH 0107/1567] docs(rf-contract): state the single terminal child_session.upsert and its mode --- docs/rf-contract/capability-tokens.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/rf-contract/capability-tokens.md b/docs/rf-contract/capability-tokens.md index 2a9b1f628..5a3cbcb8a 100644 --- a/docs/rf-contract/capability-tokens.md +++ b/docs/rf-contract/capability-tokens.md @@ -677,6 +677,14 @@ continuation has a fresh run ID; `turn.started`, `turn.appended`, and `child_session.upsert` keep that turn's run and the four ancestry links. Consumers must accept repeated running-to-succeeded cycles for one child session key. Terminal-chat child sessions remain outside this journal. +A child run ends with exactly one terminal `child_session.upsert` (`succeeded`, +`failed` or `cancelled`) whose `mode` is the child's own mode (`task` or +`process`); the first of the run's turn terminal and terminal task event holds +that slot, and a segment turn's terminal never produces one. Every upsert and +the snapshot row of a child carry the same mode. A child that was killed, died, +or lost its owner (gateway exit or restart) ends `cancelled` for a requested +stop and `failed` otherwise, and its unfinished turns get one `turn.cancelled` +or `turn.failed` each. A root session never appears as a `child_session` row. A focused child's approval resolves only that child's pending call; a process child's approval is relayed to the root surface (see the approvals section). From 3851fe6fc81034953e9bf4d7ac165b7beb16a4ca Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:29:21 +0400 Subject: [PATCH 0108/1567] feat(gateway): let a message-woken turn wait for the receiver owner's approval A turn woken by a session message is its own approval root in the receiving session. Build the root explicitly in the mailbox receiver, resolve it from the sync journal as a third root kind, and cancel approvals left open by a dead process at startup without replaying the message. --- docs/rf-contract/capability-tokens.md | 9 ++- docs/tools.md | 9 ++- src/gateway/api/sessions/mailbox.rs | 40 +++++++++++-- src/gateway/api/sessions/section_1.rs | 24 +++++--- src/gateway/api/sync_startup.rs | 10 ++++ src/gateway/child_mailbox/approvals.rs | 1 + src/gateway/run_approvals.rs | 8 +++ src/memory/sqlite/mod.rs | 1 + src/memory/sqlite/sync_journal.rs | 11 ++++ src/memory/sqlite/sync_woken.rs | 81 ++++++++++++++++++++++++++ src/memory/sync.rs | 2 + 11 files changed, 180 insertions(+), 16 deletions(-) create mode 100644 src/memory/sqlite/sync_woken.rs diff --git a/docs/rf-contract/capability-tokens.md b/docs/rf-contract/capability-tokens.md index 5a3cbcb8a..1dc0e8c52 100644 --- a/docs/rf-contract/capability-tokens.md +++ b/docs/rf-contract/capability-tokens.md @@ -787,7 +787,14 @@ a backend without the authenticated mailbox pipe, or an operator-rooted child that has no caller approval surface. With the relay armed, a root that has no approval resolver at all gets the same outcome a task child would get in that position. A process turn woken by a message ends with -`no_approval_surface`, as a task child's does. While a relayed approval waits, +`no_approval_surface`, as a task child's does. An in-process turn woken by a +message is its own root in the receiving session `T`: `approval.pending` and +`approval.decided` carry `session=T` and the woken `run_id` (no +`client_message_id`), and only the owner of `T` decides through +`POST /sessions//approvals/`. A decision under another session id is +refused with `approval_run_mismatch`. The woken run's transcript and terminal +reach the stream as well. After a restart the pending approval is reported as +`cancelled` and the message is not run again. While a relayed approval waits, the child shows `tool_status{phase:"awaiting_approval"}` on the child run and `approval.pending` carries the child `run_id`. The worker does not stream live `started` or `succeeded` frames after an approval. A root that is not recordable diff --git a/docs/tools.md b/docs/tools.md index 5cbc341b0..b47a10532 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -1987,7 +1987,14 @@ turn uses the persisted child session and model, with its level capped by the current agent and owner configuration. It gets no inherited approval grant or local operator authority. Task approvals use the root session's live surface; without one, calls that need approval are denied with `no_approval_surface`. -A process turn woken by a message ends with `no_approval_surface`, as a task child's does. Message turns count +A process turn woken by a message ends with `no_approval_surface`, as a task child's does. +A turn woken by a message in an in-process session is its own approval root, owned by the +receiving session: a call that needs approval waits for the owner of that session, bounded +by the receiving agent's `approval_wait_secs`, and an approval resumes the same call in the +same run. The sender never decides it, and a decision posted under another session id is +refused. A denial or the timeout refuses the call. The woken run holds its agent's slot while +it waits, so later messages queue behind it. A restart cancels the approval and does not run +the message again. Message turns count toward the receiving agent's limits and daily cost, and run one at a time per child session. Process children continue in a new worker with public history seeded. Their diff --git a/src/gateway/api/sessions/mailbox.rs b/src/gateway/api/sessions/mailbox.rs index 13b9ef4b0..334a68925 100644 --- a/src/gateway/api/sessions/mailbox.rs +++ b/src/gateway/api/sessions/mailbox.rs @@ -173,11 +173,37 @@ fn pending_roots( Ok(roots) } -tokio::task_local! { static WOKEN_TURN: (); } +tokio::task_local! { + /// The woken run's own approval root, `{session, agent, incarnation, run_id}`. + static WOKEN_TURN: serde_json::Value; +} + +/// The approval root of the turn this module drives for an adopted mailbox +/// message, `None` outside such a turn. The woken run is its own root, scoped +/// to the receiving session: built here from the receiver address and the new +/// run id, never from the adopted event (which inherits an earlier run id). +pub(super) fn woken_scope() -> Option { + WOKEN_TURN.try_with(Clone::clone).ok() +} -/// True only inside the turn this module drives for an adopted mailbox message. -pub(super) fn is_woken_turn() -> bool { - WOKEN_TURN.try_with(|()| ()).is_ok() +/// The explicit approval root of a woken run owned by the receiver session. +async fn receiver_root( + runtime: &Arc, + input: &MessageInput, + run_id: &str, +) -> anyhow::Result { + let address = input.message.to.clone(); + let store = Arc::clone(runtime); + let scope = crate::runtime::blocking::spawn_blocking(move || { + store.store.session_scope(&store.workspace, &address, false) + }) + .await??; + Ok(serde_json::json!({ + "session": input.message.to.session, + "agent": input.message.to.agent, + "incarnation": scope.incarnation.to_string(), + "run_id": run_id, + })) } async fn run( @@ -206,7 +232,9 @@ async fn run( } else { (parent, None) }; - envelope.run_id = Some(uuid::Uuid::new_v4().to_string()); + let run_id = uuid::Uuid::new_v4().to_string(); + let root = receiver_root(&runtime, &input, &run_id).await?; + envelope.run_id = Some(run_id); envelope.source_message_event_id = input.receipt.adopted_message_event_id.map(|id| id.to_string()); envelope = envelope.with_config_generation(&turn_runtime.config_generation); // Only the verified adopted event supplies causation. Content never enters @@ -253,7 +281,7 @@ async fn run( }; WOKEN_TURN .scope( - (), + root, crate::gateway::jobs::scope_cancellation( cancellation, run_console_message_job_work(turn_runtime, state, input.text.clone(), turns, source, target), diff --git a/src/gateway/api/sessions/section_1.rs b/src/gateway/api/sessions/section_1.rs index 30f18faac..5bb6bb469 100644 --- a/src/gateway/api/sessions/section_1.rs +++ b/src/gateway/api/sessions/section_1.rs @@ -752,13 +752,20 @@ async fn run_console_runtime_turn( // decision slot publishes its tool policy with. config_snapshot.autonomy.level = target.autonomy; } - let live_scope = - if let (Some(store), Some(source)) = (state.mem.sync_store(), turn_envelope.source_message_event_id.clone()) { - let owner = turn_envelope.resolved_owner_id(); - crate::runtime::blocking::spawn_blocking(move || store.live_scope(&owner, &source)).await?? - } else { - None - }; + // A message-woken run is its own root, owned by the receiving session and + // built explicitly by the mailbox receiver. Every other turn resolves its + // root from the stored source event. + let woken_root = mailbox::woken_scope(); + let woken = woken_root.is_some(); + let live_scope = if let Some(root) = woken_root { + Some(root) + } else if let (Some(store), Some(source)) = (state.mem.sync_store(), turn_envelope.source_message_event_id.clone()) + { + let owner = turn_envelope.resolved_owner_id(); + crate::runtime::blocking::spawn_blocking(move || store.live_scope(&owner, &source)).await?? + } else { + None + }; let live = live_scope.map(|scope| { let wait_secs = target .and_then(|target| config_snapshot.agents.get(target.name.as_str())) @@ -773,6 +780,7 @@ async fn run_console_runtime_turn( // approval waits, while dropping it never cancels the run or the job. cancellation: decision.cancellation.child_token(), wait_secs, + woken, }) as std::sync::Arc }); let live_frames = live.as_ref().map(|live| { @@ -930,7 +938,7 @@ async fn run_console_runtime_turn( // A message-woken turn with no approval surface refuses a call // that needs approval at once: no pending row nobody can act on. .or_else(|| { - (target.is_none() && mailbox::is_woken_turn()) + (target.is_none() && mailbox::woken_scope().is_some()) .then(crate::runtime::mailbox_child::no_surface) }); if target.is_some() && live.is_none() { diff --git a/src/gateway/api/sync_startup.rs b/src/gateway/api/sync_startup.rs index 473204ce1..fb7b76ef6 100644 --- a/src/gateway/api/sync_startup.rs +++ b/src/gateway/api/sync_startup.rs @@ -63,6 +63,16 @@ async fn startup_inner(state: &AppState, shutdown: &CancellationToken) -> anyhow } } } + // A message-woken run that died with the previous process is never replayed: + // close the approvals it left open before any wake or request is served. A + // failure leaves them listed but undecidable (no live waiter holds them). + let sync = Arc::clone(&store); + if !matches!( + crate::runtime::blocking::spawn_blocking(move || sync.cancel_orphaned_woken_approvals()).await, + Ok(Ok(_)) + ) { + tracing::warn!("startup sweep of message-woken approvals failed"); + } let sync = Arc::clone(&store); crate::runtime::blocking::spawn_blocking(move || sync.refresh_config(&config, &revision)).await??; let sync = Arc::clone(&store); diff --git a/src/gateway/child_mailbox/approvals.rs b/src/gateway/child_mailbox/approvals.rs index 90c2b732d..dd606697e 100644 --- a/src/gateway/child_mailbox/approvals.rs +++ b/src/gateway/child_mailbox/approvals.rs @@ -42,6 +42,7 @@ pub(super) async fn live( approvals: Arc::clone(&state.rf_approvals), cancellation: tokio_util::sync::CancellationToken::new(), wait_secs: if console { 240 } else { wait_secs }, + woken: false, })) }), ) diff --git a/src/gateway/run_approvals.rs b/src/gateway/run_approvals.rs index 6291478df..bb5a14228 100644 --- a/src/gateway/run_approvals.rs +++ b/src/gateway/run_approvals.rs @@ -135,6 +135,8 @@ pub(crate) struct RunApprovalResolver { /// the run or job also holds (pass a child token of the run's token). pub(crate) cancellation: CancellationToken, pub(crate) wait_secs: u64, + /// The run was woken by a session message and is its own root in the receiver session. + pub(crate) woken: bool, } impl Drop for RunApprovalResolver { fn drop(&mut self) { @@ -297,6 +299,12 @@ impl RunApprovalResolver { .context("approval waiter missing")?; self.frames(&request.context.envelope, &HashSet::new()) .awaiting_approval(&request.descriptor.public_name); + if self.woken { + tracing::info!( + wait_secs = self.wait_secs, + "message-woken turn is waiting for the owner's approval decision" + ); + } let fresh = created.is_some(); let mut rx = entry.outcome.subscribe(); if fresh { diff --git a/src/memory/sqlite/mod.rs b/src/memory/sqlite/mod.rs index a506d8d9d..b36fbdc52 100644 --- a/src/memory/sqlite/mod.rs +++ b/src/memory/sqlite/mod.rs @@ -30,6 +30,7 @@ mod rf_forget; mod rf_messages; mod sync_journal; mod sync_lifecycle; +mod sync_woken; mod sync_projection; mod sync_snapshot; mod write_log; diff --git a/src/memory/sqlite/sync_journal.rs b/src/memory/sqlite/sync_journal.rs index 36b85e214..76dd4a83b 100644 --- a/src/memory/sqlite/sync_journal.rs +++ b/src/memory/sqlite/sync_journal.rs @@ -183,6 +183,13 @@ pub(super) fn event_header(conn: &Connection, id: &str, kind: &str) -> anyhow::R } else { conn.query_row("WITH RECURSIVE family(run) AS (SELECT ?1 UNION SELECT e.parent_run_id FROM message_events e JOIN family f ON e.run_id=f.run WHERE e.workspace_id=?2 AND e.owner_id=?3 AND e.parent_run_id IS NOT NULL) SELECT e.session_key,s.agent_key,s.incarnation,e.run_id,s.session_key FROM message_events e JOIN agent_scopes s ON s.scope_id=e.ma_scope_id WHERE e.workspace_id=?2 AND e.owner_id=?3 AND s.agent_key GLOB 'n:*' AND e.source IN ('cron','xin') AND e.parent_run_id IS NULL AND e.run_id IN(SELECT run FROM family) LIMIT 1", params![root_run, workspace, owner], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?))).optional()? }; + // A message-woken run is its own root in the receiver session: a top-level + // run whose continuation input names the adoption row of its message. + let root = if root.is_some() { + root + } else { + conn.query_row(&format!("WITH RECURSIVE family(run) AS (SELECT ?1 UNION SELECT e.parent_run_id FROM message_events e JOIN family f ON e.run_id=f.run WHERE e.workspace_id=?2 AND e.owner_id=?3 AND e.parent_run_id IS NOT NULL) SELECT e.session_key,CASE WHEN s.agent_key='m' THEN 'main' ELSE s.agent_key END,s.incarnation,e.run_id,s.session_key FROM message_events e JOIN agent_scopes s ON s.scope_id=e.ma_scope_id WHERE e.workspace_id=?2 AND e.owner_id=?3 AND e.parent_run_id IS NULL AND e.run_id IN(SELECT run FROM family) AND {} LIMIT 1", super::mailbox_continuation::CONTINUATION_PREDICATE_E), params![root_run, workspace, owner], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?))).optional()? + }; let Some((root_session, agent, incarnation, root_id, _)) = root else { return Ok(None); }; @@ -553,6 +560,10 @@ impl SyncStore for SqliteMemory { })? .collect::>>()?) } + fn cancel_orphaned_woken_approvals(&self) -> anyhow::Result { + let conn = self.pool.write(); + super::sync_woken::sweep(&conn) + } fn shutdown_signal(&self) -> CancellationToken { self.sync_runtime.shutdown.lock().clone() } diff --git a/src/memory/sqlite/sync_woken.rs b/src/memory/sqlite/sync_woken.rs new file mode 100644 index 000000000..f4a3cfb4c --- /dev/null +++ b/src/memory/sqlite/sync_woken.rs @@ -0,0 +1,81 @@ +//! Startup cancellation of approvals left open by a message-woken run that +//! died with its process. A woken run is never replayed, so nothing can +//! decide such an approval and the run can never end it. +use super::mailbox_continuation::CONTINUATION_PREDICATE_E; +use super::sync_journal::{append, event_header}; +use crate::security::approval_ledger::keys::RunCallAuthority; +use rusqlite::{Connection, Transaction, TransactionBehavior, params}; +use std::collections::BTreeSet; + +/// Close every open approval whose root is a woken run without a terminal +/// row. Returns the number of runs swept. Safe to repeat: a closed approval is +/// skipped and the interrupt header is keyed by run. +pub(super) fn sweep(conn: &Connection) -> anyhow::Result { + let tx = Transaction::new_unchecked(conn, TransactionBehavior::Immediate)?; + let candidates = { + let mut query = tx.prepare(&format!( + "SELECT p.event_id,p.workspace_id,p.owner_id, + CASE WHEN json_valid(p.raw_payload_json) THEN json_extract(p.raw_payload_json,'$.record.rf.root_run_id') END AS root, + CASE WHEN json_valid(p.raw_payload_json) THEN json_extract(p.raw_payload_json,'$.record.authority') END AS authority + FROM message_events p + WHERE p.event_type='approval.call.pending' AND root IS NOT NULL + AND NOT EXISTS(SELECT 1 FROM message_events f WHERE f.workspace_id=p.workspace_id AND f.owner_id=p.owner_id + AND f.idempotency_key IN('turn:'||root||':final','turn:'||root||':admission-failed')) + AND EXISTS(SELECT 1 FROM message_events e WHERE e.workspace_id=p.workspace_id AND e.owner_id=p.owner_id + AND e.run_id=root AND e.parent_run_id IS NULL AND {CONTINUATION_PREDICATE_E}) + ORDER BY p.id" + ))?; + query + .query_map([], |r| { + Ok(( + r.get::<_, String>(0)?, + r.get::<_, String>(1)?, + r.get::<_, String>(2)?, + r.get::<_, String>(3)?, + r.get::<_, Option>(4)?, + )) + })? + .collect::>>()? + }; + // One entry per root run: (workspace, owner, root run), the first open pending row, its open count. + let mut runs: Vec<((String, String, String), String, usize)> = Vec::new(); + let mut seen = BTreeSet::new(); + for (event, workspace, owner, root, authority) in candidates { + let Some(authority) = authority + .and_then(|raw| serde_json::from_str::(&raw).ok()) + else { + continue; + }; + let decided: bool = tx.query_row( + "SELECT EXISTS(SELECT 1 FROM message_events WHERE workspace_id=?1 AND owner_id=?2 AND idempotency_key=?3)", + params![workspace, owner, format!("rf-decision:{}", authority.call_id())], + |r| r.get(0), + )?; + if decided || !seen.insert(authority.call_id()) { + continue; + } + let key = (workspace, owner, root); + if let Some(entry) = runs.iter_mut().find(|entry| entry.0 == key) { + entry.2 += 1; + } else { + runs.push((key, event, 1)); + } + } + let mut swept = 0; + for ((workspace, _, run), event, open) in runs { + let Some(mut header) = event_header(&tx, &event, "turn.failed")? else { + continue; + }; + header.source_ref = format!("interrupt:{run}"); + header.event_id = format!("interrupt:{run}"); + append(&tx, &header)?; + super::sync_lifecycle::cancel_approvals(&tx, &header, &workspace, &run, true)?; + tracing::info!( + open_approvals = open, + "startup sweep cancelled a leftover approval of an interrupted message-woken turn" + ); + swept += 1; + } + tx.commit()?; + Ok(swept) +} diff --git a/src/memory/sync.rs b/src/memory/sync.rs index b0fe073db..4dd69d06b 100644 --- a/src/memory/sync.rs +++ b/src/memory/sync.rs @@ -59,5 +59,7 @@ pub trait SyncStore: Send + Sync { fn configure(&self, workspace: &str, owner: &str) -> anyhow::Result<()>; fn refresh_config(&self, config: &crate::config::Config, revision: &str) -> anyhow::Result<()>; fn restart_candidates(&self, after: &str) -> anyhow::Result>; + /// Cancel the approvals that message-woken runs of a dead process left open; returns the runs swept. + fn cancel_orphaned_woken_approvals(&self) -> anyhow::Result; fn shutdown_signal(&self) -> CancellationToken; } From 7f48897846b08d879303ad93d9f158387c9d6595 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:23:13 +0400 Subject: [PATCH 0109/1567] fix(doctor): report a missing daemon state file as not running instead of an error --- src/doctor/implementation/section_2.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/doctor/implementation/section_2.rs b/src/doctor/implementation/section_2.rs index 8b0e77020..a6ca2f57d 100644 --- a/src/doctor/implementation/section_2.rs +++ b/src/doctor/implementation/section_2.rs @@ -677,10 +677,13 @@ fn check_daemon_state(config: &Config, items: &mut Vec) { let state_file = crate::daemon::state_file_path(config); if !state_file.exists() { - items.push(DiagItem::error( + // No state file means no daemon ever ran here (a fresh state + // directory): report it as not running, not as a failure. A file that + // exists but is unreadable, corrupt or stale stays an error below. + items.push(DiagItem::warn( cat, format!( - "state file not found: {} — is the daemon running?", + "daemon not running (no state file at {}); start it with `prx daemon`", state_file.display() ), )); From 08be0656685e046b1a56bfd488019f8d16c461bc Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:29:13 +0400 Subject: [PATCH 0110/1567] fix(agent): replace a still-unexecuted tool claim with a notice after the corrective retry --- src/agent/response_guard.rs | 5 +++++ src/agent/turn_engine.rs | 30 ++++++++++++++++++++---------- 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/src/agent/response_guard.rs b/src/agent/response_guard.rs index ff95521b4..4bfa2254d 100644 --- a/src/agent/response_guard.rs +++ b/src/agent/response_guard.rs @@ -12,6 +12,11 @@ pub(super) const TOOL_SUMMARY_ONLY_RESPONSE_MESSAGE: &str = "The previous assist Either invoke the required tools now or provide a complete final answer. \ Do not output a '[Used tools: ...]' summary."; +/// Delivered instead of a reply that still claims a tool ran after the one +/// corrective retry, when no tool ran in the turn. The fabricated text is +/// dropped entirely so it is never shown, stored or fed back to the model. +pub(super) const UNEXECUTED_TOOL_CLAIM_NOTICE: &str = "The model said it used a tool, but no tool was run in this turn. Please try again."; + /// Marks the runtime's own words inside a user turn. /// /// A corrective retry instruction is not something the operator said, so it is diff --git a/src/agent/turn_engine.rs b/src/agent/turn_engine.rs index c2bc2f28a..bbf761501 100644 --- a/src/agent/turn_engine.rs +++ b/src/agent/turn_engine.rs @@ -53,7 +53,8 @@ use crate::agent::response_guard::{ CORRECTIVE_ASIDE_PREFIX, contains_fabricated_tool_marker, strip_fabricated_tool_markers, }; use crate::agent::response_guard::{ - EMPTY_ASSISTANT_RESPONSE_RETRY_MESSAGE, TOOL_SUMMARY_ONLY_RESPONSE_MESSAGE, append_corrective_aside, + EMPTY_ASSISTANT_RESPONSE_RETRY_MESSAGE, TOOL_SUMMARY_ONLY_RESPONSE_MESSAGE, UNEXECUTED_TOOL_CLAIM_NOTICE, + append_corrective_aside, contains_assistant_fabricated_tool_marker, is_empty_assistant_response, is_tool_summary_only_response, strip_assistant_fabricated_tool_markers, }; @@ -1869,15 +1870,24 @@ async fn run_turn_unguarded( continue; } if fabricated_marker { - // Retry spent (or tools really ran): keep whatever the model - // actually answered and drop only the marker lines, so the - // fabrication never reaches the user, the history, or the next - // turn's prompt where it would be imitated again. - if let Cow::Owned(cleaned) = strip_assistant_fabricated_tool_markers(&display_text) { - display_text = cleaned; - } - if display_text.trim().is_empty() { - anyhow::bail!("model returned a tool-summary-only response after one corrective retry"); + if executed_any_tool_call { + // A tool really ran: keep whatever the model actually + // answered and drop only the marker lines, so the + // fabrication never reaches the user, the history, or the + // next turn's prompt where it would be imitated again. + if let Cow::Owned(cleaned) = strip_assistant_fabricated_tool_markers(&display_text) { + display_text = cleaned; + } + if display_text.trim().is_empty() { + anyhow::bail!("model returned a tool-summary-only response after one corrective retry"); + } + } else { + // Retry spent and no tool ran: the rest of the reply is + // built on a claim that did not happen, so it is replaced + // whole by a fixed notice. `display_text` is what is + // streamed, pushed to history and returned, so all three + // carry the notice and none the fabricated text. + display_text = UNEXECUTED_TOOL_CLAIM_NOTICE.to_owned(); } } // Tool evidence is written by the runtime only: every evidence From ae18d4d269e2cccd978a16462229623ca22ec93f Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:40:24 +0400 Subject: [PATCH 0111/1567] refactor(tools): remove the git_operations tool --- CHANGELOG.md | 6 + docs/channels.md | 2 +- docs/configuration.md | 9 +- docs/providers.md | 4 +- ...tool-schema-and-child-capability-parity.md | 6 - docs/tools.md | 23 +- src/agent/tool_scheduler.rs | 2 +- src/agent/turn_tests/execution_policy.rs | 1 - src/config/schema/security.rs | 1 - src/config/schema/tests/channels.rs | 4 +- src/cron/scheduler.rs | 3 +- .../child_source/golden_effective_config.json | 2 +- src/runtime/shell_process.rs | 4 +- src/security/approval_operation.rs | 22 - src/security/git_launch.rs | 8 +- src/session_worker/protocol.rs | 2 +- .../runner/tests/tool_selection.rs | 9 +- src/skills/lifecycle/tests/evaluate.rs | 1 - src/tools/capability/catalog/section_1.rs | 2 +- src/tools/git_operations.rs | 1799 ----------------- src/tools/mod.rs | 6 +- src/tools/schema/execution_contract.rs | 2 - src/tools/schema/goldens/git_operations.json | 126 -- .../goldens/published/git_operations.json | 73 - src/tools/shell_parity_tests.rs | 9 +- tests/fixtures/config-schema.json | 2 +- tests/support/legacy_tool_surface_budget.rs | 14 +- 27 files changed, 49 insertions(+), 2093 deletions(-) delete mode 100644 src/tools/git_operations.rs delete mode 100644 src/tools/schema/goldens/git_operations.json delete mode 100644 src/tools/schema/goldens/published/git_operations.json diff --git a/CHANGELOG.md b/CHANGELOG.md index a2418f399..b88586fc9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Removed +- BREAKING (agents): the structured `git_operations` tool is removed. Agents + run git through the `shell` tool, whose git policy is unchanged: effective + Full runs plain git; Supervised and ReadOnly shells refuse git. A + configuration that still names `git_operations` (`tool_tiering`, + `agents..allowed_tools`, scope-rule `tools_allow` / `tools_deny`) + loads normally; the name matches nothing and is ignored. - BREAKING (operators): the legacy decision plane is gone and no decision data is carried over. `decisions.db`, `self/causal_tree/.decision_key` and `self/child_authority/journal.db` are never opened; if any exists, one diff --git a/docs/channels.md b/docs/channels.md index e5bb1e11b..0b27c56b1 100644 --- a/docs/channels.md +++ b/docs/channels.md @@ -175,7 +175,7 @@ and defaults to the operations/development surface: `wasm_plugins_manage`, `wasm_plugin_reload`, `wasm_plugins_status`, `hooks_manage`, `hooks_status`, `proxy_config`, `config_reload`, `gateway`, -`mcp_status`, `nodes`, `git_operations`, `skills_manage`, `memory_reindex`, +`mcp_status`, `nodes`, `skills_manage`, `memory_reindex`, `document_sync`, `document_ingest`. These are not advertised to the model on a channel turn even when the message diff --git a/docs/configuration.md b/docs/configuration.md index 927a92a7a..090726995 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -721,7 +721,7 @@ low_priority_tools = ["sessions_spawn", "delegate"] # channel sessions only (Signal / Telegram / Discord / WhatsApp / …) and defaults # to the operations/development surface: wasm_plugins_manage, wasm_plugin_reload, # wasm_plugins_status, hooks_manage, hooks_status, proxy_config, config_reload, -# gateway, mcp_status, nodes, git_operations, skills_manage, memory_reindex, +# gateway, mcp_status, nodes, skills_manage, memory_reindex, # document_sync, document_ingest. Terminal chat, the gateway and the console are # unaffected. Name a tool in `always_include` to put it back on channels, or set # `channel_exclude = []` to drop the default entirely. `always_include` does not @@ -2216,8 +2216,7 @@ A command hook that runs: Writing or editing `hooks.json` or `mcp.json` at the workspace root, or any file under `/plugins/` (WASM plugin code and manifests), with the file tools is a high-risk operation of its own (`write-launch-definition`, -`edit-launch-definition`); git operations that change those paths are treated -the same way. Every other surface classifies a `hooks.json` +`edit-launch-definition`). Every other surface classifies a `hooks.json` change the same way: a change that installs, changes or runs a hook command (its program, arguments or event) is high risk (`hooks_manage` `replace` and `test`, Gateway `POST /api/hooks` and a `PUT /api/hooks/{id}` that sets @@ -3424,7 +3423,7 @@ three turn limits above replace its former limits. Roll back by setting ### Native tool working directory and Full autonomy `runtime.workdir` optionally selects an absolute, existing directory for the shell, -native file tools and `git_operations`. `prx chat --workdir /absolute/task` overrides +and native file tools. `prx chat --workdir /absolute/task` overrides it before chat startup (every chat mode, including `--message`); invalid CLI paths fail with exit 2, invalid configuration paths with exit 1. The CLI canonicalizes the directory. The default remains the workspace directory. Changes require restart and setting or changing the directory @@ -3455,7 +3454,7 @@ A child's effective level cannot exceed its manifest or the current service leve Direct tool calls without runtime authority keep the Supervised behavior. Docker continues to use the shell environment allowlist at every level. Native Full ignores that allowlist for admission, but invalid entries are still rejected. -`git_operations`, skill scripts and scheduled shell jobs retain their existing git policy. +Skill scripts and scheduled shell jobs retain their existing git policy. ### Named-agent rf admission limits diff --git a/docs/providers.md b/docs/providers.md index 28495ed98..2825c94a7 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -669,11 +669,11 @@ Fail-closed is **per request**: a turn whose offered tool slice contains even one refused tool is not sent at all. The first unrouted turn of the fullscreen chat offers the whole registry by design, so on a `no_root_combinators` endpoint it is refused unless the tools are excluded. -On a current build these fourteen published tools carry a root conditional or +On a current build these thirteen published tools carry a root conditional or alternative and are refused: `chat_profile_update`, `composio`, `cron`, `document_get_chunk`, -`document_ingest`, `gateway`, `git_operations`, `mcp_call`, `memory_get`, +`document_ingest`, `gateway`, `mcp_call`, `memory_get`, `nodes`, `proxy_config`, `skills_manage`, `subagents`, `xin` (`tests/tool_schema_contract.rs` pins this list; a change is a finding either diff --git a/docs/tool-schema-and-child-capability-parity.md b/docs/tool-schema-and-child-capability-parity.md index 36dd99e0c..876cd4ba7 100644 --- a/docs/tool-schema-and-child-capability-parity.md +++ b/docs/tool-schema-and-child-capability-parity.md @@ -171,7 +171,6 @@ Initial migration covers every multi-action native surface: - `mcp` - `composio` - `message_send` -- `git_operations` - TUI `managed_session` - TUI `chat_schedule` @@ -272,7 +271,6 @@ wired in 0.8.133 keep their original test names): | `sessions_spawn` | `src/tools/sessions_spawn/tool.rs` | | `wasm_plugins_manage` | `src/plugins/runtime.rs` | | `mcp_call` | `src/tools/mcp.rs` | -| `git_operations` (the `stash` sub-action enum) | `src/tools/git_operations.rs` | | `gateway` | `src/tools/gateway.rs` | | `skills_manage` | `src/tools/skills.rs` | | `composio` | `src/tools/composio.rs` | @@ -283,10 +281,6 @@ wired in 0.8.133 keep their original test names): | `managed_session` | `src/chat/managed_session.rs` | | `hooks_manage` | `src/hooks/mod.rs` | -`git_operations` dispatches on `operation` and carries a second `action` enum -for the `stash` sub-command; the contract test covers that inner enum, and the -tool description names both sets. - A new action-dispatched tool is expected to add its own `action_tool_contract` test in the same change that introduces the executor branches. diff --git a/docs/tools.md b/docs/tools.md index b47a10532..5f3520d2f 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -10,7 +10,7 @@ and the active WASM generation feed the registry. The resulting immutable iteration; see [Unified turn context](unified-turn-context.md) and [Runtime security — tool surface owner](security.md#tool-surface-owner). -The complete static public inventory contains 55 tool names. Runtime discovery +The complete static public inventory contains 54 tool names. Runtime discovery can add Skill, MCP, and WASM aliases. MCP aliases remain in the discovery catalog and are resolved by exact name; the default MCP tool surface contains only `mcp_call`. Its schema does not enumerate configured servers or tools. @@ -43,7 +43,7 @@ session controls remain available independently. | Category | Tools | |----------|-------| | **Capability discovery** | `capability_search` (tool-capable turns with eligible deferred features) | -| **Shell & Files** | `shell`, `file_read`, `file_write`, `file_edit`, `git_operations` | +| **Shell & Files** | `shell`, `file_read`, `file_write`, `file_edit` | | **Web** | `web_search_tool`, `web_fetch`, `http_request` | | **Memory & Documents** | `memory_store`, `memory_recall`, `memory_search`, `memory_get`, `transcript_history_lookup`, `memory_forget`, `memory_reindex`, `chat_profile_update`, `document_search`, `document_get_chunk`, `document_ingest`, `document_sync` | | **Skills** | `skills_list`, `skill_read`, `skills_manage`, `skill_execute`, plus up to 32 declared skill-tool aliases | @@ -99,11 +99,10 @@ can read, and does not change command authorization or process lifetime. Effective Full shells run ordinary git, including repository hooks. Supervised and ReadOnly shells refuse git before spawning; approval does not change that -policy. `git_operations` keeps its hardened launch at every level. Skill scripts -and cron/Xin shell jobs keep their existing git policy. +policy. Skill scripts and cron/Xin shell jobs keep their existing git policy. `runtime.workdir` or `prx chat --workdir /absolute/task` selects the working root -for shell, native file tools and `git_operations`; otherwise they use the workspace. +for shell and native file tools; otherwise they use the workspace. Restricted native file and shell path checks resolve relative requests against that root before evaluating forbidden paths and workspace confinement. ReadOnly still refuses mutations. Configured roots follow symlinks to their canonical directory. @@ -279,7 +278,7 @@ partner rather than by the operator. The default excluded set is `wasm_plugins_manage`, `wasm_plugin_reload`, `wasm_plugins_status`, `hooks_manage`, `hooks_status`, `proxy_config`, `config_reload`, `gateway`, -`mcp_status`, `nodes`, `git_operations`, `skills_manage`, `memory_reindex`, +`mcp_status`, `nodes`, `skills_manage`, `memory_reindex`, `document_sync`, `document_ingest`. Nothing else is hidden by the channel surface. See @@ -354,7 +353,7 @@ hides the operations/development surface from a conversation partner: `wasm_plugins_manage`, `wasm_plugin_reload`, `wasm_plugins_status`, `hooks_manage`, `hooks_status`, `proxy_config`, `config_reload`, `gateway`, -`mcp_status`, `nodes`, `git_operations`, `skills_manage`, `memory_reindex`, +`mcp_status`, `nodes`, `skills_manage`, `memory_reindex`, `document_sync`, `document_ingest`. These names are folded into that turn's `always_exclude`, so they stay hidden @@ -365,8 +364,8 @@ the whole default off, set `channel_exclude = []`: ```toml [tool_tiering] -# Re-enable repository access for channel conversations. -always_include = ["git_operations"] +# Re-enable a channel-excluded tool for channel conversations. +always_include = ["nodes"] # Or drop the channel default entirely. # channel_exclude = [] ``` @@ -1575,9 +1574,9 @@ creating surface does not; and a **shell** job (`job_type = "shell"`, or a xin policy at all, whoever created it — deny the `cron` and `xin` tools to a scope that must not run shell commands. -Git has a separate execution boundary. Use `git_operations` for model-driven -Git actions; PRX refuses recognized Git command strings in the `shell` tool, -skill shell/script tools, and +Git has a separate execution boundary. Effective Full autonomy runs git +through the `shell` tool; PRX refuses recognized Git command strings in the +`shell` tool below Full, in skill shell/script tools, and in cron or xin shell jobs created or rewritten by an agent tool. Operator-created cron and xin shell jobs, xin system tasks, and node `exec_shell` allowlists may run Git with fixed program settings and hooks disabled. PRX records who last diff --git a/src/agent/tool_scheduler.rs b/src/agent/tool_scheduler.rs index 6debb5af7..477c961e4 100644 --- a/src/agent/tool_scheduler.rs +++ b/src/agent/tool_scheduler.rs @@ -21,7 +21,7 @@ static TOOL_BARRIERS: LazyLock Option<&'static str> { match name { // Workspace mutations / command execution. - "file_write" | "shell" | "git_operations" => Some("workspace_write"), + "file_write" | "shell" => Some("workspace_write"), // Shared runtime configuration / scheduler state. "config_reload" | "cron" | "proxy_config" => Some("runtime_config"), // Shared long-term memory writes. diff --git a/src/agent/turn_tests/execution_policy.rs b/src/agent/turn_tests/execution_policy.rs index fd384c079..8558a7a13 100644 --- a/src/agent/turn_tests/execution_policy.rs +++ b/src/agent/turn_tests/execution_policy.rs @@ -239,7 +239,6 @@ fn is_write_tool_classifies_mutating_tools_as_writes() { for name in [ "file_write", "shell", - "git_operations", "memory_store", "memory_forget", "memory_reindex", diff --git a/src/config/schema/security.rs b/src/config/schema/security.rs index 0bbbb7426..21d3f4942 100644 --- a/src/config/schema/security.rs +++ b/src/config/schema/security.rs @@ -209,7 +209,6 @@ pub const DEFAULT_CHANNEL_EXCLUDED_TOOLS: &[&str] = &[ "gateway", "mcp_status", "nodes", - "git_operations", "skills_manage", "memory_reindex", "document_sync", diff --git a/src/config/schema/tests/channels.rs b/src/config/schema/tests/channels.rs index 36b2069fc..97971ca1b 100644 --- a/src/config/schema/tests/channels.rs +++ b/src/config/schema/tests/channels.rs @@ -18,7 +18,7 @@ async fn channel_tiering_folds_defaults_in_without_overriding_the_operator() { "the default must not touch the operator surface" ); - config.always_include.push("git_operations".to_string()); + config.always_include.push("gateway".to_string()); config.always_exclude.push("shell".to_string()); let channel = config.for_channel_surface(); @@ -31,7 +31,7 @@ async fn channel_tiering_folds_defaults_in_without_overriding_the_operator() { "channel_exclude entries are folded in" ); assert!( - !channel.always_exclude.contains(&"git_operations".to_string()), + !channel.always_exclude.contains(&"gateway".to_string()), "a tool the operator re-enabled must not be folded into the exclusion" ); assert_eq!( diff --git a/src/cron/scheduler.rs b/src/cron/scheduler.rs index 95655bc96..645079de7 100644 --- a/src/cron/scheduler.rs +++ b/src/cron/scheduler.rs @@ -1611,7 +1611,7 @@ mod tests { /// D-107: a cron shell job an agent tool created (or one stored before /// the creator was recorded) is model-driven, so a command that runs git - /// is refused and names the tool to use instead. + /// is refused. #[tokio::test] async fn a_cron_shell_job_that_runs_git_is_refused() { let tmp = TempDir::new().unwrap(); @@ -1621,7 +1621,6 @@ mod tests { let (success, output) = run_job_command(&config, &job).await; assert!(!success); assert!(output.contains("refusing to run git through the shell"), "{output}"); - assert!(output.contains("git_operations"), "{output}"); } /// D-107 amendment: a job the operator added with `prx cron` runs git diff --git a/src/runtime/child_source/golden_effective_config.json b/src/runtime/child_source/golden_effective_config.json index 19e5a18ef..0d16f1d38 100644 --- a/src/runtime/child_source/golden_effective_config.json +++ b/src/runtime/child_source/golden_effective_config.json @@ -1 +1 @@ -{"a2a":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trust_domain":"prx.local","trusted_trust_domains":[]},"agent":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"messaging":{"inbound":true},"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2},"agents":{},"api_key":null,"api_url":null,"auth":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"},"autonomy":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":500,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true},"browser":{"allowed_domains":[],"computer_use":{"api_key":null}},"channels_config":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null},"chat":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2},"compliance":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}},"composio":{"api_key":null,"entity_id":"default"},"cost":{"allow_override":false,"daily_limit_usd":10.0,"monthly_limit_usd":100.0,"prices":{"alpha/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0},"zeta/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0}},"warn_at_percent":80},"cron":{"max_run_history":50},"decision_engine":{"backend":{"circuit_breaker":{"cooldown_secs":60,"failure_threshold":5},"credential_ref":"","endpoint":"","kind":"auto","max_request_bytes":65536,"max_response_bytes":262144,"model":"","pinned_snapshot":"","remote_enabled":false,"timeout_ms":250},"candidates":5,"enabled":false,"latency_budget_ms":500,"max_candidates":12,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"token_ratio_limit":0.3499999940395355},"default_model":"anthropic/claude-sonnet-5","default_provider":"openrouter","default_temperature":0.7,"embedding_routes":[],"gateway":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":false,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60},"heartbeat":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."},"http_request":{"max_response_size":1000000,"timeout_secs":30},"identity":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"},"identity_bindings":[],"mcp":{"servers":{}},"mcp_server":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true},"media":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"},"memory":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7},"model_routes":[],"model_settings":{},"multimodal":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4},"nodes":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}},"observability":{"backend":"none","otel_endpoint":null,"otel_service_name":null},"plugins":{"enabled":false},"providers":{"ollama":{"num_ctx":null}},"proxy":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]},"query_classification":{"rules":[]},"reliability":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2},"router":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]},"runtime":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null},"scheduler":{"claim_lease_secs":90,"max_tasks":64},"secrets":{"encrypt":true},"security":{"audit":{"log_path":"audit.log","max_size_mb":100}},"self_system":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24},"sessions_spawn":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null},"skill_rag":{"top_k":32},"skills":{"open_skills_dir":null,"openclaw_skills_dir":null},"skills_lifecycle":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]},"smart_group":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5},"storage":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}},"task_routing":{"default_intent":"simple","rules":[]},"tool_tiering":{"always_exclude":[],"always_include":[],"channel_exclude":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","git_operations","skills_manage","memory_reindex","document_sync","document_ingest"]},"tunnel":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null},"user_policies":[],"web_search":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15},"webhook":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null},"xin":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}} \ No newline at end of file +{"a2a":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trust_domain":"prx.local","trusted_trust_domains":[]},"agent":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"messaging":{"inbound":true},"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2},"agents":{},"api_key":null,"api_url":null,"auth":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"},"autonomy":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":500,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true},"browser":{"allowed_domains":[],"computer_use":{"api_key":null}},"channels_config":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null},"chat":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2},"compliance":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}},"composio":{"api_key":null,"entity_id":"default"},"cost":{"allow_override":false,"daily_limit_usd":10.0,"monthly_limit_usd":100.0,"prices":{"alpha/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0},"zeta/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0}},"warn_at_percent":80},"cron":{"max_run_history":50},"decision_engine":{"backend":{"circuit_breaker":{"cooldown_secs":60,"failure_threshold":5},"credential_ref":"","endpoint":"","kind":"auto","max_request_bytes":65536,"max_response_bytes":262144,"model":"","pinned_snapshot":"","remote_enabled":false,"timeout_ms":250},"candidates":5,"enabled":false,"latency_budget_ms":500,"max_candidates":12,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"token_ratio_limit":0.3499999940395355},"default_model":"anthropic/claude-sonnet-5","default_provider":"openrouter","default_temperature":0.7,"embedding_routes":[],"gateway":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":false,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60},"heartbeat":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."},"http_request":{"max_response_size":1000000,"timeout_secs":30},"identity":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"},"identity_bindings":[],"mcp":{"servers":{}},"mcp_server":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true},"media":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"},"memory":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7},"model_routes":[],"model_settings":{},"multimodal":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4},"nodes":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}},"observability":{"backend":"none","otel_endpoint":null,"otel_service_name":null},"plugins":{"enabled":false},"providers":{"ollama":{"num_ctx":null}},"proxy":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]},"query_classification":{"rules":[]},"reliability":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2},"router":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]},"runtime":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null},"scheduler":{"claim_lease_secs":90,"max_tasks":64},"secrets":{"encrypt":true},"security":{"audit":{"log_path":"audit.log","max_size_mb":100}},"self_system":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24},"sessions_spawn":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null},"skill_rag":{"top_k":32},"skills":{"open_skills_dir":null,"openclaw_skills_dir":null},"skills_lifecycle":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]},"smart_group":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5},"storage":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}},"task_routing":{"default_intent":"simple","rules":[]},"tool_tiering":{"always_exclude":[],"always_include":[],"channel_exclude":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","skills_manage","memory_reindex","document_sync","document_ingest"]},"tunnel":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null},"user_policies":[],"web_search":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15},"webhook":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null},"xin":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}} \ No newline at end of file diff --git a/src/runtime/shell_process.rs b/src/runtime/shell_process.rs index 6a7a41de2..f128c14a1 100644 --- a/src/runtime/shell_process.rs +++ b/src/runtime/shell_process.rs @@ -127,8 +127,8 @@ pub enum ShellProcessError { /// Effective Full shell, skill, cron and Xin invocations select PlainGit /// instead. #[error( - "refusing to run git through the shell: use the git_operations tool, which disables the programs a \ - repository's configuration names" + "refusing to run git through the shell: a restricted command may not run git, because a repository's \ + configuration can name programs git would execute" )] GitRefused, } diff --git a/src/security/approval_operation.rs b/src/security/approval_operation.rs index 190df8586..da10d00f6 100644 --- a/src/security/approval_operation.rs +++ b/src/security/approval_operation.rs @@ -78,28 +78,6 @@ pub(crate) fn grant_op_for_call(tool_name: &str, args: &serde_json::Value) -> Op }; Some(GrantOp::ResourceExact(operation, risk)) } - "git_operations" => { - let operation = string_arg("operation").unwrap_or_default(); - let (resource_operation, risk) = match operation { - "push" => ( - format!("git_operations:push:{}", string_arg("remote").unwrap_or("origin")), - RiskLevel::High, - ), - "reset_hard" => ("git_operations:reset_hard".to_string(), RiskLevel::High), - "commit" => ("git_operations:commit".to_string(), RiskLevel::Medium), - "add" => ("git_operations:add".to_string(), RiskLevel::Medium), - "checkout" => { - let branch = string_arg("branch").unwrap_or("unknown"); - (format!("git_operations:checkout:{branch}"), RiskLevel::Medium) - } - "stash" => { - let action = string_arg("stash_action").unwrap_or("push"); - (format!("git_operations:stash:{action}"), RiskLevel::Medium) - } - other => (format!("git_operations:{other}"), RiskLevel::Medium), - }; - Some(GrantOp::ResourceExact(resource_operation, risk)) - } "sessions_send" => { let run_id = string_arg("run_id").unwrap_or_default(); Some(GrantOp::ResourceExact( diff --git a/src/security/git_launch.rs b/src/security/git_launch.rs index 367af63ac..5b5e169b9 100644 --- a/src/security/git_launch.rs +++ b/src/security/git_launch.rs @@ -813,7 +813,7 @@ pub fn warn_operator_git_once(surface: &str, job: &str) { job, "an operator-configured shell job runs git: fsmonitor, hook scripts, bare discovery, ext:: and lazy \ fetch are disabled for it, but the repository's own drivers, credential helpers and transport \ - settings are not inspected; prefer the git_operations tool" + settings are not inspected" ); } } @@ -1220,12 +1220,6 @@ const fn has_other_hard_links(_target: &Path) -> bool { false } -/// The workspace launch definitions (`hooks.json`, `mcp.json` at the -/// workspace root, and everything under `plugins/`, which holds WASM plugin -/// code and manifests) as git pathspecs relative to the workspace, matched in -/// any letter case. -pub const LAUNCH_DEFINITION_PATHSPECS: [&str; 3] = [":(icase)hooks.json", ":(icase)mcp.json", ":(icase)plugins"]; - /// Test support: every git process of the lib tests reads a scratch global /// file and no system file, never the host's configuration (D-103). The /// production launch passes `GIT_CONFIG_GLOBAL`/`GIT_CONFIG_NOSYSTEM` diff --git a/src/session_worker/protocol.rs b/src/session_worker/protocol.rs index 4c9be75a7..c06280905 100644 --- a/src/session_worker/protocol.rs +++ b/src/session_worker/protocol.rs @@ -198,7 +198,7 @@ pub struct WorkerManifest { /// IM channel and the operations surface, and until 0.8.131 it stopped at /// the OS process boundary — a `mode: "process"` spawn, or a worker resumed /// from this manifest, got `gateway`, `config_reload`, `proxy_config`, - /// `nodes` and `git_operations` back. The list is covered by the manifest + /// and `nodes` back. The list is covered by the manifest /// capability seal, so a worker cannot be started with it stripped. #[serde(default)] pub channel_excluded_tools: Vec, diff --git a/src/session_worker/runner/tests/tool_selection.rs b/src/session_worker/runner/tests/tool_selection.rs index 15f7b3e1e..1346f7689 100644 --- a/src/session_worker/runner/tests/tool_selection.rs +++ b/src/session_worker/runner/tests/tool_selection.rs @@ -56,7 +56,6 @@ fn worker_surface_fixture() -> Vec> { "proxy_config", "config_reload", "nodes", - "git_operations", "shell", ] .into_iter() @@ -80,7 +79,7 @@ async fn a_process_worker_cannot_regain_the_operations_surface_its_channel_hides // fails if `channel_exclude` ever stops hiding the operations tools. let surface = crate::config::ToolTieringConfig::default().for_channel_surface(); let hidden = surface.always_exclude.clone(); - for name in ["gateway", "proxy_config", "config_reload", "nodes", "git_operations"] { + for name in ["gateway", "proxy_config", "config_reload", "nodes"] { assert!( hidden.iter().any(|entry| entry == name), "the default channel surface must hide '{name}' for this fixture to mean anything" @@ -88,7 +87,7 @@ async fn a_process_worker_cannot_regain_the_operations_surface_its_channel_hides } let filtered = worker_tool_names(&[], &hidden).await; - for name in ["gateway", "proxy_config", "config_reload", "nodes", "git_operations"] { + for name in ["gateway", "proxy_config", "config_reload", "nodes"] { assert!( !filtered.iter().any(|entry| entry == name), "a worker started from an IM turn must not publish '{name}': {filtered:?}" @@ -157,7 +156,7 @@ async fn a_worker_manifest_binds_its_channel_exclusions_to_the_tool_filter() { let hidden = crate::config::ToolTieringConfig::default() .for_channel_surface() .always_exclude; - for name in ["gateway", "proxy_config", "config_reload", "nodes", "git_operations"] { + for name in ["gateway", "proxy_config", "config_reload", "nodes"] { assert!( hidden.iter().any(|entry| entry == name), "the default channel surface must hide '{name}' for this fixture to mean anything" @@ -169,7 +168,7 @@ async fn a_worker_manifest_binds_its_channel_exclusions_to_the_tool_filter() { manifest.channel_excluded_tools = hidden; let filtered = manifest_tool_names(&manifest).await; - for name in ["gateway", "proxy_config", "config_reload", "nodes", "git_operations"] { + for name in ["gateway", "proxy_config", "config_reload", "nodes"] { assert!( !filtered.iter().any(|entry| entry == name), "a worker resumed from this manifest must not publish '{name}': {filtered:?}" diff --git a/src/skills/lifecycle/tests/evaluate.rs b/src/skills/lifecycle/tests/evaluate.rs index b4708d2e9..1326fc2fe 100644 --- a/src/skills/lifecycle/tests/evaluate.rs +++ b/src/skills/lifecycle/tests/evaluate.rs @@ -1732,7 +1732,6 @@ fn only_declared_read_tools_and_declared_writes_can_be_required() { "proxy_config", "document_ingest", "composio", - "git_operations", ] { assert!(ok(&[tool], SideEffects::WorkspaceWrite).is_err(), "{tool}"); } diff --git a/src/tools/capability/catalog/section_1.rs b/src/tools/capability/catalog/section_1.rs index d78e5bb1d..3bd1b36a8 100644 --- a/src/tools/capability/catalog/section_1.rs +++ b/src/tools/capability/catalog/section_1.rs @@ -1019,7 +1019,7 @@ fn effect_for(descriptor: &ToolDescriptor) -> SideEffectClass { match descriptor.effect { ToolEffect::Read => SideEffectClass::ReadOnly, ToolEffect::Act => match descriptor.public_name.as_str() { - "shell" | "git_operations" => SideEffectClass::ProcessExec, + "shell" => SideEffectClass::ProcessExec, "message_send" | "http_request" => SideEffectClass::ExternalSend, "sessions_send" if descriptor.parameters.get("oneOf").is_some() => SideEffectClass::ExternalSend, "config_reload" | "proxy_config" => SideEffectClass::CredentialOrConfig, diff --git a/src/tools/git_operations.rs b/src/tools/git_operations.rs deleted file mode 100644 index e60336bf9..000000000 --- a/src/tools/git_operations.rs +++ /dev/null @@ -1,1799 +0,0 @@ -use super::traits::{Tool, ToolCategory, ToolResult, ToolTier}; -use crate::security::SideEffectGate; -use crate::security::git_launch::{self, GitScope}; -use crate::security::policy::{ApprovalGrant, ResourceRiskLevel}; -use crate::security::{AutonomyLevel, SecurityPolicy}; -use async_trait::async_trait; -use serde_json::json; -use std::sync::Arc; - -/// Git operations tool for structured repository management. -/// Provides safe, parsed git operations with JSON output. -pub struct GitOperationsTool { - security: Arc, - workspace_dir: std::path::PathBuf, -} - -impl GitOperationsTool { - pub const fn new(security: Arc, workspace_dir: std::path::PathBuf) -> Self { - Self { - security, - workspace_dir, - } - } - - /// Sanitize git arguments to prevent injection attacks - fn sanitize_git_args(&self, args: &str) -> anyhow::Result> { - let mut result = Vec::new(); - for arg in args.split_whitespace() { - // Block dangerous git options that could lead to command injection - let arg_lower = arg.to_lowercase(); - if arg_lower.starts_with("--exec=") - || arg_lower.starts_with("--upload-pack=") - || arg_lower.starts_with("--receive-pack=") - || arg_lower.starts_with("--pager=") - || arg_lower.starts_with("--editor=") - || arg_lower == "--no-verify" - || arg_lower.contains("$(") - || arg_lower.contains('`') - || arg.contains('|') - || arg.contains(';') - || arg.contains('>') - { - anyhow::bail!("Blocked potentially dangerous git argument: {arg}"); - } - // Block `-c` config injection (exact match or `-c=...` prefix). - // This must not false-positive on `--cached` or `-cached`. - if arg_lower == "-c" || arg_lower.starts_with("-c=") { - anyhow::bail!("Blocked potentially dangerous git argument: {arg}"); - } - result.push(arg.to_string()); - } - Ok(result) - } - - /// Check if an operation requires write access - fn requires_write_access(&self, operation: &str) -> bool { - matches!( - operation, - "commit" | "add" | "checkout" | "stash" | "push" | "reset_hard" | "reset" | "revert" - ) - } - - fn resource_operation_name(&self, operation: &str, args: &serde_json::Value) -> Option { - match operation { - "commit" => Some("git_operations:commit".to_string()), - "add" => Some("git_operations:add".to_string()), - "checkout" => { - let branch = args.get("branch").and_then(|value| value.as_str()).unwrap_or("*"); - Some(format!("git_operations:checkout:{branch}")) - } - "stash" => { - let action = args.get("action").and_then(|value| value.as_str()).unwrap_or("push"); - Some(format!("git_operations:stash:{action}")) - } - "push" => { - let remote = args.get("remote").and_then(|value| value.as_str()).unwrap_or("origin"); - Some(format!("git_operations:push:{remote}")) - } - "reset_hard" => Some("git_operations:reset_hard".to_string()), - "reset" => Some("git_operations:reset".to_string()), - "revert" => Some("git_operations:revert".to_string()), - _ => None, - } - } - - /// Check if an operation is read-only - #[cfg(test)] - fn is_read_only(&self, operation: &str) -> bool { - matches!(operation, "status" | "diff" | "log" | "show" | "branch" | "rev-parse") - } - - /// Run `git` in the workspace through the hardened launch (GIT-ENV, - /// D-100): a cleared environment, and every program the repository's own - /// configuration names (fsmonitor, hooks, filters, credential helpers, - /// ...) neutralised, while the operator's global configuration applies. - /// An effective Full call runs git plainly in the cleared environment. - async fn run_git_command(&self, args: &[&str]) -> anyhow::Result { - let output = self.run_git_output(args).await?; - if !output.status.success() { - let stderr = String::from_utf8_lossy(&output.stderr); - anyhow::bail!("Git command failed: {stderr}"); - } - - Ok(String::from_utf8_lossy(&output.stdout).to_string()) - } - - /// [`Self::run_git_command`] without judging the exit status. - async fn run_git_output(&self, args: &[&str]) -> anyhow::Result { - // `git` forks its own helpers (git-remote-https, credential helpers), - // so cancelling this future must tear down the whole process group. - // The call's carried level: only an effective Full call runs git - // plainly (owner D1); a missing level keeps the hardened launch. - let scope = if super::effective_autonomy::current() == Some(AutonomyLevel::Full) { - GitScope::PlainRepository(&self.workspace_dir) - } else { - GitScope::Repository(&self.workspace_dir) - }; - let mut command = git_launch::git_command(scope).await?; - command.args(args); - Ok(crate::runtime::shell_process::run_managed_output(command).await?) - } - - async fn git_status(&self, _args: serde_json::Value) -> anyhow::Result { - let output = self - .run_git_command(&["status", "--porcelain=v2", "--branch", "-z"]) - .await?; - let PorcelainStatus { - branch, - staged, - unstaged, - untracked, - conflicted, - } = parse_porcelain_v2(&output); - - let mut result = serde_json::Map::new(); - result.insert("branch".to_string(), json!(branch)); - result.insert("staged".to_string(), json!(staged)); - result.insert("unstaged".to_string(), json!(unstaged)); - result.insert("untracked".to_string(), json!(untracked)); - result.insert("conflicted".to_string(), json!(conflicted)); - result.insert( - "clean".to_string(), - json!(staged.is_empty() && unstaged.is_empty() && untracked.is_empty() && conflicted.is_empty()), - ); - - Ok(ToolResult { - success: true, - output: serde_json::to_string_pretty(&result).unwrap_or_default(), - error: None, - }) - } - - async fn git_diff(&self, args: serde_json::Value) -> anyhow::Result { - let files = args.get("files").and_then(|v| v.as_str()).unwrap_or("."); - let cached = args.get("cached").and_then(|v| v.as_bool()).unwrap_or(false); - - // Validate files argument against injection patterns - self.sanitize_git_args(files)?; - - let mut git_args = vec!["diff", "--unified=3"]; - git_args.extend(git_launch::DIFF_SAFETY_ARGS); - if cached { - git_args.push("--cached"); - } - git_args.push("--"); - git_args.push(files); - - let output = self.run_git_command(&git_args).await?; - - // Parse diff into structured hunks - let mut result = serde_json::Map::new(); - let mut hunks = Vec::new(); - let mut current_file = String::new(); - let mut current_hunk = serde_json::Map::new(); - let mut lines = Vec::new(); - - for line in output.lines() { - if line.starts_with("diff --git ") { - if !lines.is_empty() { - current_hunk.insert("lines".to_string(), json!(lines)); - if !current_hunk.is_empty() { - hunks.push(serde_json::Value::Object(current_hunk.clone())); - } - lines = Vec::new(); - current_hunk = serde_json::Map::new(); - } - let parts: Vec<&str> = line.split_whitespace().collect(); - if let Some(p3) = parts.get(3) { - current_file = p3.trim_start_matches("b/").to_string(); - current_hunk.insert("file".to_string(), json!(current_file)); - } - } else if line.starts_with("@@ ") { - if !lines.is_empty() { - current_hunk.insert("lines".to_string(), json!(lines)); - if !current_hunk.is_empty() { - hunks.push(serde_json::Value::Object(current_hunk.clone())); - } - lines = Vec::new(); - current_hunk = serde_json::Map::new(); - current_hunk.insert("file".to_string(), json!(current_file)); - } - current_hunk.insert("header".to_string(), json!(line)); - } else if !line.is_empty() { - lines.push(json!({ - "text": line, - "type": if line.starts_with('+') { "add" } - else if line.starts_with('-') { "delete" } - else { "context" } - })); - } - } - - if !lines.is_empty() { - current_hunk.insert("lines".to_string(), json!(lines)); - if !current_hunk.is_empty() { - hunks.push(serde_json::Value::Object(current_hunk)); - } - } - - result.insert("hunks".to_string(), json!(hunks)); - result.insert("file_count".to_string(), json!(hunks.len())); - - Ok(ToolResult { - success: true, - output: serde_json::to_string_pretty(&result).unwrap_or_default(), - error: None, - }) - } - - async fn git_log(&self, args: serde_json::Value) -> anyhow::Result { - let limit_raw = args.get("limit").and_then(|v| v.as_u64()).unwrap_or(10); - let limit = usize::try_from(limit_raw).unwrap_or(usize::MAX).min(1000); - let limit_str = limit.to_string(); - - let output = self - .run_git_command(&[ - "log", - &format!("-{limit_str}"), - "--pretty=format:%H|%an|%ae|%ad|%s", - "--date=iso", - ]) - .await?; - - let mut commits = Vec::new(); - - for line in output.lines() { - let parts: Vec<&str> = line.split('|').collect(); - if let [hash, author, email, date, message, ..] = parts.as_slice() { - commits.push(json!({ - "hash": hash, - "author": author, - "email": email, - "date": date, - "message": message - })); - } - } - - Ok(ToolResult { - success: true, - output: serde_json::to_string_pretty(&json!({ "commits": commits })).unwrap_or_default(), - error: None, - }) - } - - async fn git_branch(&self, _args: serde_json::Value) -> anyhow::Result { - let output = self - .run_git_command(&["branch", "--format=%(refname:short)|%(HEAD)"]) - .await?; - - let mut branches = Vec::new(); - let mut current = String::new(); - - for line in output.lines() { - if let Some((name, head)) = line.split_once('|') { - let is_current = head == "*"; - if is_current { - current = name.to_string(); - } - branches.push(json!({ - "name": name, - "current": is_current - })); - } - } - - Ok(ToolResult { - success: true, - output: serde_json::to_string_pretty(&json!({ - "current": current, - "branches": branches - })) - .unwrap_or_default(), - error: None, - }) - } - - fn truncate_commit_message(message: &str) -> String { - if message.chars().count() > 2000 { - format!("{}...", message.chars().take(1997).collect::()) - } else { - message.to_string() - } - } - - async fn git_commit(&self, args: serde_json::Value) -> anyhow::Result { - let message = args - .get("message") - .and_then(|v| v.as_str()) - .ok_or_else(|| anyhow::anyhow!("Missing 'message' parameter"))?; - - // Sanitize commit message - let sanitized = message - .lines() - .map(|l| l.trim()) - .filter(|l| !l.is_empty()) - .collect::>() - .join("\n"); - - if sanitized.is_empty() { - anyhow::bail!("Commit message cannot be empty"); - } - - // Limit message length - let message = Self::truncate_commit_message(&sanitized); - - let output = self.run_git_command(&["commit", "-m", &message]).await; - - match output { - Ok(_) => Ok(ToolResult { - success: true, - output: format!("Committed: {message}"), - error: None, - }), - Err(e) => Ok(ToolResult { - success: false, - output: String::new(), - error: Some(format!("Commit failed: {e}")), - }), - } - } - - async fn git_add(&self, args: serde_json::Value) -> anyhow::Result { - let paths = args - .get("paths") - .and_then(|v| v.as_str()) - .ok_or_else(|| anyhow::anyhow!("Missing 'paths' parameter"))?; - - // Validate paths against injection patterns - self.sanitize_git_args(paths)?; - - let output = self.run_git_command(&["add", "--", paths]).await; - - match output { - Ok(_) => Ok(ToolResult { - success: true, - output: format!("Staged: {paths}"), - error: None, - }), - Err(e) => Ok(ToolResult { - success: false, - output: String::new(), - error: Some(format!("Add failed: {e}")), - }), - } - } - - /// The validated target of a `checkout`. - fn checkout_target(&self, args: &serde_json::Value) -> anyhow::Result { - let branch = args - .get("branch") - .and_then(|v| v.as_str()) - .ok_or_else(|| anyhow::anyhow!("Missing 'branch' parameter"))?; - - // Sanitize branch name - let mut sanitized = self.sanitize_git_args(branch)?; - if sanitized.len() != 1 { - anyhow::bail!("Invalid branch specification"); - } - let branch_name = sanitized - .pop() - .ok_or_else(|| anyhow::anyhow!("Invalid branch specification"))?; - - // Block dangerous branch names - if branch_name.contains('@') || branch_name.contains('^') || branch_name.contains('~') { - anyhow::bail!("Branch name contains invalid characters"); - } - Ok(branch_name) - } - - /// Whether `operation` would change a workspace launch definition - /// (`hooks.json` or `mcp.json` at the workspace root, in any letter - /// case) in the working tree: a checkout of a revision whose copy - /// differs, a stash push that reverts a modified one, or a stash pop - /// that brings one back (GIT-ENV). Such an operation decides which - /// programs PRX runs, so it is high risk like the file tools' write of - /// one. The check reads the repository through the same hardened - /// launch, and fails closed: a check that cannot run (an unknown - /// revision, a path given as the branch, no stash entry) counts as a - /// change. - async fn changes_launch_definition(&self, operation: &str, args: &serde_json::Value) -> bool { - let checked = match operation { - "checkout" => match self.checkout_target(args) { - // `-` is the previous branch; any other leading dash would be - // read as an option of the check itself. - Ok(target) if target == "-" => self.revision_changes_launch_definition("@{-1}").await, - Ok(target) if !target.starts_with('-') => self.revision_changes_launch_definition(&target).await, - Ok(_) => Err(anyhow::anyhow!("a checkout target starting with '-'")), - Err(error) => Err(error), - }, - "stash" => match args.get("action").and_then(|value| value.as_str()).unwrap_or("push") { - "push" | "save" => { - self.launch_definition_paths(&["status", "--porcelain", "-z", "--untracked-files=no"]) - .await - } - "pop" => self.stash_pop_changes_launch_definition().await, - _ => Ok(false), - }, - _ => Ok(false), - }; - checked.unwrap_or_else(|error| { - tracing::warn!( - operation, - error = %error, - "could not tell whether a git operation changes hooks.json or mcp.json; treating it as a change" - ); - true - }) - } - - /// Whether the read-only git command `args`, limited to the launch - /// definition paths, prints any path. - async fn launch_definition_paths(&self, args: &[&str]) -> anyhow::Result { - let mut full = args.to_vec(); - full.push("--"); - full.extend(git_launch::LAUNCH_DEFINITION_PATHSPECS); - let output = self.run_git_command(&full).await?; - Ok(!output - .trim_matches(|character: char| character == '\0' || character.is_whitespace()) - .is_empty()) - } - - async fn revision_changes_launch_definition(&self, target: &str) -> anyhow::Result { - let mut args = vec!["diff"]; - args.extend(git_launch::DIFF_SAFETY_ARGS); - args.extend(["--name-only", "-z", "HEAD", target]); - self.launch_definition_paths(&args).await - } - - async fn stash_pop_changes_launch_definition(&self) -> anyhow::Result { - let mut tracked = vec!["diff"]; - tracked.extend(git_launch::DIFF_SAFETY_ARGS); - tracked.extend(["--name-only", "-z", "stash@{0}^1", "stash@{0}"]); - if self.launch_definition_paths(&tracked).await? { - return Ok(true); - } - // The untracked files of `stash push --include-untracked` are the - // root commit `stash@{0}^3`, when there is one. - // Exit 1 with no output is "no such revision"; anything else that is - // not success (a launch refusal, an unreadable configuration) fails - // the check, which counts as a change. - let verify = self - .run_git_output(&["rev-parse", "-q", "--verify", "stash@{0}^3"]) - .await?; - if !verify.status.success() { - if verify.status.code() == Some(1) && verify.stdout.is_empty() { - return Ok(false); - } - anyhow::bail!( - "could not tell whether the stash has untracked files: {}", - String::from_utf8_lossy(&verify.stderr) - .lines() - .next() - .unwrap_or("unknown error") - ); - } - let mut untracked = vec!["show"]; - untracked.extend(git_launch::DIFF_SAFETY_ARGS); - untracked.extend(["--name-only", "--format=", "-z", "stash@{0}^3"]); - self.launch_definition_paths(&untracked).await - } - - async fn git_checkout(&self, args: serde_json::Value) -> anyhow::Result { - let branch_name = self.checkout_target(&args)?; - let output = self.run_git_command(&["checkout", branch_name.as_str()]).await; - - match output { - Ok(_) => Ok(ToolResult { - success: true, - output: format!("Switched to branch: {branch_name}"), - error: None, - }), - Err(e) => Ok(ToolResult { - success: false, - output: String::new(), - error: Some(format!("Checkout failed: {e}")), - }), - } - } - - async fn git_stash(&self, args: serde_json::Value) -> anyhow::Result { - let action = args.get("action").and_then(|v| v.as_str()).unwrap_or("push"); - - let output = match action { - "push" | "save" => self.run_git_command(&["stash", "push", "-m", "auto-stash"]).await, - "pop" => self.run_git_command(&["stash", "pop"]).await, - "list" => self.run_git_command(&["stash", "list"]).await, - "drop" => { - let index_raw = args.get("index").and_then(|v| v.as_u64()).unwrap_or(0); - let index = - i32::try_from(index_raw).map_err(|_| anyhow::anyhow!("stash index too large: {index_raw}"))?; - self.run_git_command(&["stash", "drop", &format!("stash@{{{index}}}")]) - .await - } - _ => anyhow::bail!("Unknown stash action: {action}. Use: push, pop, list, drop"), - }; - - match output { - Ok(out) => Ok(ToolResult { - success: true, - output: out, - error: None, - }), - Err(e) => Ok(ToolResult { - success: false, - output: String::new(), - error: Some(format!("Stash {action} failed: {e}")), - }), - } - } - - async fn git_push(&self, args: serde_json::Value) -> anyhow::Result { - let remote = args.get("remote").and_then(|v| v.as_str()).unwrap_or("origin"); - let remote_args = self.sanitize_git_args(remote)?; - if remote_args.len() != 1 { - anyhow::bail!("Invalid remote specification"); - } - let remote_arg = remote_args - .first() - .ok_or_else(|| anyhow::anyhow!("Invalid remote specification"))?; - - let mut git_args = vec!["push"]; - git_args.extend(git_launch::PUSH_SAFETY_ARGS); - git_args.push(remote_arg.as_str()); - let branch_holder; - if let Some(branch) = args.get("branch").and_then(|v| v.as_str()) { - let branch_args = self.sanitize_git_args(branch)?; - if branch_args.len() != 1 { - anyhow::bail!("Invalid branch specification"); - } - branch_holder = branch_args; - let branch_arg = branch_holder - .first() - .ok_or_else(|| anyhow::anyhow!("Invalid branch specification"))?; - git_args.push(branch_arg.as_str()); - } - - let output = self.run_git_command(&git_args).await; - match output { - Ok(out) => Ok(ToolResult { - success: true, - output: out, - error: None, - }), - Err(error) => Ok(ToolResult { - success: false, - output: String::new(), - error: Some(format!("Push failed: {error}")), - }), - } - } - - async fn git_reset_hard(&self, args: serde_json::Value) -> anyhow::Result { - let target = args.get("target").and_then(|v| v.as_str()).unwrap_or("HEAD"); - let target_args = self.sanitize_git_args(target)?; - if target_args.len() != 1 { - anyhow::bail!("Invalid reset target specification"); - } - let target_arg = target_args - .first() - .ok_or_else(|| anyhow::anyhow!("Invalid reset target specification"))?; - - let output = self.run_git_command(&["reset", "--hard", target_arg.as_str()]).await; - match output { - Ok(out) => Ok(ToolResult { - success: true, - output: out, - error: None, - }), - Err(error) => Ok(ToolResult { - success: false, - output: String::new(), - error: Some(format!("Reset hard failed: {error}")), - }), - } - } -} - -/// `git status --porcelain=v2 --branch -z`, parsed. -#[derive(Debug, Default)] -struct PorcelainStatus { - branch: String, - staged: Vec, - unstaged: Vec, - untracked: Vec, - conflicted: Vec, -} - -/// Parse `git status --porcelain=v2 --branch -z`. Records are NUL -/// separated, so a path may hold spaces: -/// -/// - `1 XY sub mH mI mW hH hI path` (ordinary change); -/// - `2 XY sub mH mI mW hH hI Xscore path` followed by the original path as -/// its own NUL-separated field (rename or copy); -/// - `u XY sub m1 m2 m3 mW h1 h2 h3 path` (unmerged); -/// - `? path` (untracked); `! path` (ignored) is skipped. -fn parse_porcelain_v2(output: &str) -> PorcelainStatus { - let mut status = PorcelainStatus::default(); - let mut records = output.split('\0'); - while let Some(record) = records.next() { - if let Some(head) = record.strip_prefix("# branch.head ") { - status.branch = head.to_string(); - } else if let Some(rest) = record.strip_prefix("1 ") { - let fields = rest.splitn(8, ' ').collect::>(); - if let (Some(xy), Some(path)) = (fields.first(), fields.get(7)) { - status.record_change(xy, path, None); - } - } else if let Some(rest) = record.strip_prefix("2 ") { - let fields = rest.splitn(9, ' ').collect::>(); - // The original path is the next NUL-separated field. - let original = records.next(); - if let (Some(xy), Some(path)) = (fields.first(), fields.get(8)) { - status.record_change(xy, path, original); - } - } else if let Some(rest) = record.strip_prefix("u ") { - let fields = rest.splitn(10, ' ').collect::>(); - if let (Some(xy), Some(path)) = (fields.first(), fields.get(9)) { - status.conflicted.push(json!({"path": path, "status": xy})); - } - } else if let Some(path) = record.strip_prefix("? ") { - status.untracked.push(path.to_string()); - } - } - status -} - -impl PorcelainStatus { - /// Record a changed path under its index (`X`) and working-tree (`Y`) - /// codes; `.` means unchanged. - fn record_change(&mut self, xy: &str, path: &str, original: Option<&str>) { - let mut codes = xy.chars(); - let entry = |code: char| { - let mut entry = json!({"path": path, "status": code}); - if let (Some(original), Some(object)) = (original, entry.as_object_mut()) { - object.insert("original_path".to_string(), json!(original)); - } - entry - }; - if let Some(code) = codes.next().filter(|code| *code != '.') { - self.staged.push(entry(code)); - } - if let Some(code) = codes.next().filter(|code| *code != '.') { - self.unstaged.push(entry(code)); - } - } -} - -impl GitOperationsTool { - fn execution_schema(&self) -> &'static std::sync::Arc { - static SCHEMA: std::sync::LazyLock> = std::sync::LazyLock::new(|| { - std::sync::Arc::new({ - crate::tools::schema::with_action_requirements( - json!({ - "type": "object", - "properties": { - "operation": { - "type": "string", - "enum": ["status", "diff", "log", "branch", "commit", "add", "checkout", "stash", "push", "reset_hard"], - "description": "Git operation to perform" - }, - "message": { - "type": "string", - "description": "Commit message (for 'commit' operation)" - }, - "paths": { - "type": "string", - "description": "File paths to stage (for 'add' operation)" - }, - "branch": { - "type": "string", - "description": "Branch name (for 'checkout' or 'push' operation)" - }, - "remote": { - "type": "string", - "description": "Remote name (for 'push' operation, default: origin)" - }, - "target": { - "type": "string", - "description": "Revision target (for 'reset_hard' operation, default: HEAD)" - }, - "files": { - "type": "string", - "description": "File or path to diff (for 'diff' operation, default: '.')" - }, - "cached": { - "type": "boolean", - "description": "Show staged changes (for 'diff' operation)" - }, - "limit": { - "type": "integer", - "description": "Number of log entries (for 'log' operation, default: 10)" - }, - "action": { - "type": "string", - "enum": ["push", "pop", "list", "drop"], - "description": "Sub-action of the 'stash' operation: 'push' saves the working tree, 'pop' restores the latest entry, 'list' shows the entries, 'drop' deletes one by index" - }, - "index": { - "type": "integer", - "description": "Stash index (for 'stash' with 'drop' action)" - } - }, - "required": ["operation"] - }), - "operation", - &[ - crate::tools::schema::ActionRequirement { - action: "commit", - required: &["message"], - }, - crate::tools::schema::ActionRequirement { - action: "add", - required: &["paths"], - }, - crate::tools::schema::ActionRequirement { - action: "checkout", - required: &["branch"], - }, - ], - ) - }) - }); - &SCHEMA - } -} - -#[async_trait] -impl Tool for GitOperationsTool { - fn name(&self) -> &str { - "git_operations" - } - - fn description(&self) -> &str { - "Perform structured Git operations: 'status', 'diff', 'log', 'branch', 'commit', 'add', 'checkout', 'stash', 'push' and 'reset_hard'. The 'stash' operation takes an action of 'push' (save), 'pop' (restore), 'list' (show entries) or 'drop' (delete one). Provides parsed JSON output and integrates with security policy for autonomy controls." - } - - fn parameters_schema(&self) -> serde_json::Value { - crate::tools::schema::publish_flat_schema(self.execution_schema()) - } - - fn execution_parameters_schema(&self) -> Option> { - Some(std::sync::Arc::clone(self.execution_schema())) - } - - async fn execute(&self, mut args: serde_json::Value) -> anyhow::Result { - crate::tools::schema::validate_execution_contract(self.name(), self.execution_schema(), &mut args)?; - let operation = match args.get("operation").and_then(|v| v.as_str()) { - Some(op) => op, - None => { - return Ok(ToolResult { - success: false, - output: String::new(), - error: Some("Missing 'operation' parameter".into()), - }); - } - }; - let approval_grant = ApprovalGrant::from_runtime_args(self.name(), &args); - - // Check if we're in a git repository - if !self.workspace_dir.join(".git").exists() { - // Try to find .git in parent directories - let mut current_dir = self.workspace_dir.as_path(); - let mut found_git = false; - while let Some(parent) = current_dir.parent() { - if current_dir.join(".git").exists() { - found_git = true; - break; - } - current_dir = parent; - } - - if !found_git { - return Ok(ToolResult { - success: false, - output: String::new(), - error: Some("Not in a git repository".into()), - }); - } - } - - // Check autonomy level for write operations - if self.requires_write_access(operation) { - if !crate::tools::effective_autonomy::call_policy(&self.security).can_act() { - return Ok(ToolResult { - success: false, - output: String::new(), - error: Some("Action blocked: git write operations require higher autonomy level".into()), - }); - } - - match crate::tools::effective_autonomy::call_policy(&self.security).autonomy { - AutonomyLevel::ReadOnly => { - return Ok(ToolResult { - success: false, - output: String::new(), - error: Some("Action blocked: read-only mode".into()), - }); - } - AutonomyLevel::Supervised | AutonomyLevel::Full => {} - } - - if let Some(operation_name) = self.resource_operation_name(operation, &args) { - // An operation that rewrites `hooks.json` or `mcp.json` in the - // working tree is its own, high-risk operation, so an approval - // of the ordinary one does not cover it (GIT-ENV). - let launch_definition = self.changes_launch_definition(operation, &args).await; - let (operation_name, risk) = if launch_definition { - (format!("{operation_name}:launch-definition"), ResourceRiskLevel::High) - } else { - let risk = match operation { - "push" | "reset_hard" => ResourceRiskLevel::High, - _ => ResourceRiskLevel::Medium, - }; - (operation_name, risk) - }; - if let Err(error) = SideEffectGate::new(&crate::tools::effective_autonomy::call_policy(&self.security)) - .authorize_resource_operation(self.name(), &operation_name, risk, approval_grant.as_ref()) - { - let error = if launch_definition { - format!( - "{error} (this git operation changes a workspace launch definition: hooks.json and \ - mcp.json decide which programs run as PRX's user, so changing one is a high-risk \ - operation of its own)" - ) - } else { - error - }; - return Ok(ToolResult { - success: false, - output: String::new(), - error: Some(error), - }); - } - } - } - - // Execute the requested operation - match operation { - "status" => self.git_status(args).await, - "diff" => self.git_diff(args).await, - "log" => self.git_log(args).await, - "branch" => self.git_branch(args).await, - "commit" => self.git_commit(args).await, - "add" => self.git_add(args).await, - "checkout" => self.git_checkout(args).await, - "stash" => self.git_stash(args).await, - "push" => self.git_push(args).await, - "reset_hard" => self.git_reset_hard(args).await, - _ => Ok(ToolResult { - success: false, - output: String::new(), - error: Some(format!("Unknown operation: {operation}")), - }), - } - } - - fn tier(&self) -> ToolTier { - ToolTier::Standard - } - - fn categories(&self) -> &'static [ToolCategory] { - &[ToolCategory::DevOps] - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::security::SecurityPolicy; - use tempfile::TempDir; - - fn test_tool(dir: &std::path::Path) -> GitOperationsTool { - crate::security::git_launch::hermetic_git_for_tests(); - let security = Arc::new(SecurityPolicy { - autonomy: AutonomyLevel::Supervised, - ..SecurityPolicy::default() - }); - GitOperationsTool::new(security, dir.to_path_buf()) - } - - /// Initialize a git repository without blocking the test runtime. - async fn init_git_repo(dir: &std::path::Path) { - tokio::process::Command::new("git") - .args(["init"]) - .current_dir(dir) - .kill_on_drop(true) - .output() - .await - .unwrap(); - } - - /// The shared action contract every action-dispatched tool is held to: - /// the tool-list description and the `action` parameter's own description - /// must each name every enumerated action, and no parameter may ship - /// undescribed. - #[tokio::test] - async fn git_operations_action_tool_contract() { - let tmp = TempDir::new().unwrap(); - let tool = test_tool(tmp.path()); - crate::tools::schema::assert_flat_execution_contract(&tool, tool.execution_schema()).await; - crate::tools::schema::action_contract::assert_action_tool_contract( - tool.name(), - tool.description(), - tool.execution_schema(), - ); - } - - #[test] - fn sanitize_git_blocks_injection() { - let tmp = TempDir::new().unwrap(); - let tool = test_tool(tmp.path()); - - // Should block dangerous arguments - assert!(tool.sanitize_git_args("--exec=rm -rf /").is_err()); - assert!(tool.sanitize_git_args("$(echo pwned)").is_err()); - assert!(tool.sanitize_git_args("`malicious`").is_err()); - assert!(tool.sanitize_git_args("arg | cat").is_err()); - assert!(tool.sanitize_git_args("arg; rm file").is_err()); - } - - #[test] - fn sanitize_git_blocks_pager_editor_injection() { - let tmp = TempDir::new().unwrap(); - let tool = test_tool(tmp.path()); - - assert!(tool.sanitize_git_args("--pager=less").is_err()); - assert!(tool.sanitize_git_args("--editor=vim").is_err()); - } - - #[test] - fn sanitize_git_blocks_config_injection() { - let tmp = TempDir::new().unwrap(); - let tool = test_tool(tmp.path()); - - // Exact `-c` flag (config injection) - assert!(tool.sanitize_git_args("-c core.sshCommand=evil").is_err()); - assert!(tool.sanitize_git_args("-c=core.pager=less").is_err()); - } - - #[test] - fn sanitize_git_blocks_no_verify() { - let tmp = TempDir::new().unwrap(); - let tool = test_tool(tmp.path()); - - assert!(tool.sanitize_git_args("--no-verify").is_err()); - } - - #[test] - fn sanitize_git_blocks_redirect_in_args() { - let tmp = TempDir::new().unwrap(); - let tool = test_tool(tmp.path()); - - assert!(tool.sanitize_git_args("file.txt > /tmp/out").is_err()); - } - - #[test] - fn sanitize_git_cached_not_blocked() { - let tmp = TempDir::new().unwrap(); - let tool = test_tool(tmp.path()); - - // --cached must NOT be blocked by the `-c` check - assert!(tool.sanitize_git_args("--cached").is_ok()); - // Other safe flags starting with -c prefix - assert!(tool.sanitize_git_args("-cached").is_ok()); - } - - #[test] - fn sanitize_git_allows_safe() { - let tmp = TempDir::new().unwrap(); - let tool = test_tool(tmp.path()); - - // Should allow safe arguments - assert!(tool.sanitize_git_args("main").is_ok()); - assert!(tool.sanitize_git_args("feature/test-branch").is_ok()); - assert!(tool.sanitize_git_args("--cached").is_ok()); - assert!(tool.sanitize_git_args("src/main.rs").is_ok()); - assert!(tool.sanitize_git_args(".").is_ok()); - } - - #[test] - fn requires_write_detection() { - let tmp = TempDir::new().unwrap(); - let tool = test_tool(tmp.path()); - - assert!(tool.requires_write_access("commit")); - assert!(tool.requires_write_access("add")); - assert!(tool.requires_write_access("checkout")); - assert!(tool.requires_write_access("push")); - assert!(tool.requires_write_access("reset_hard")); - - assert!(!tool.requires_write_access("status")); - assert!(!tool.requires_write_access("diff")); - assert!(!tool.requires_write_access("log")); - } - - #[test] - fn resource_operation_names_are_canonical() { - let tmp = TempDir::new().unwrap(); - let tool = test_tool(tmp.path()); - - assert_eq!( - tool.resource_operation_name("commit", &json!({})).as_deref(), - Some("git_operations:commit") - ); - assert_eq!( - tool.resource_operation_name("checkout", &json!({"branch": "main"})) - .as_deref(), - Some("git_operations:checkout:main") - ); - assert_eq!( - tool.resource_operation_name("stash", &json!({"action": "drop"})) - .as_deref(), - Some("git_operations:stash:drop") - ); - assert_eq!( - tool.resource_operation_name("push", &json!({"remote": "origin"})) - .as_deref(), - Some("git_operations:push:origin") - ); - assert_eq!( - tool.resource_operation_name("reset_hard", &json!({})).as_deref(), - Some("git_operations:reset_hard") - ); - } - - #[test] - fn branch_is_not_write_gated() { - let tmp = TempDir::new().unwrap(); - let tool = test_tool(tmp.path()); - - // Branch listing is read-only; it must not require write access - assert!(!tool.requires_write_access("branch")); - assert!(tool.is_read_only("branch")); - } - - #[test] - fn is_read_only_detection() { - let tmp = TempDir::new().unwrap(); - let tool = test_tool(tmp.path()); - - assert!(tool.is_read_only("status")); - assert!(tool.is_read_only("diff")); - assert!(tool.is_read_only("log")); - assert!(tool.is_read_only("branch")); - - assert!(!tool.is_read_only("commit")); - assert!(!tool.is_read_only("add")); - } - - #[tokio::test] - async fn blocks_readonly_mode_for_write_ops() { - let tmp = TempDir::new().unwrap(); - // Initialize a git repository - init_git_repo(tmp.path()).await; - - let security = Arc::new(SecurityPolicy { - autonomy: AutonomyLevel::ReadOnly, - ..SecurityPolicy::default() - }); - let tool = GitOperationsTool::new(security, tmp.path().to_path_buf()); - - let result = tool - .execute(json!({"operation": "commit", "message": "test"})) - .await - .unwrap(); - assert!(!result.success); - // can_act() returns false for ReadOnly, so we get the "higher autonomy level" message - assert!(result.error.as_deref().unwrap_or("").contains("higher autonomy")); - } - - #[tokio::test] - async fn supervised_write_ops_require_runtime_grant() { - let tmp = TempDir::new().unwrap(); - init_git_repo(tmp.path()).await; - - let tool = test_tool(tmp.path()); - let result = tool - .execute(json!({"operation": "commit", "message": "test"})) - .await - .unwrap(); - - assert!(!result.success); - assert!(result.error.as_deref().unwrap_or("").contains("runtime approval grant")); - } - - #[tokio::test] - async fn supervised_push_and_reset_hard_require_runtime_grant() { - let tmp = TempDir::new().unwrap(); - init_git_repo(tmp.path()).await; - - let tool = test_tool(tmp.path()); - let push = tool - .execute(json!({"operation": "push", "remote": "origin"})) - .await - .unwrap(); - assert!(!push.success); - assert!(push.error.as_deref().unwrap_or("").contains("runtime approval grant")); - - let reset = tool - .execute(json!({"operation": "reset_hard", "target": "HEAD"})) - .await - .unwrap(); - assert!(!reset.success); - assert!(reset.error.as_deref().unwrap_or("").contains("runtime approval grant")); - } - - #[tokio::test] - async fn supervised_push_accepts_matching_runtime_grant() { - let tmp = TempDir::new().unwrap(); - init_git_repo(tmp.path()).await; - - let tool = test_tool(tmp.path()); - let grant = ApprovalGrant::for_resource_operation("git_operations", "git_operations:push:origin", "test", None); - let result = tool - .execute(json!({ - "operation": "push", - "remote": "origin", - (crate::security::policy::RUNTIME_APPROVAL_GRANT_ARG): serde_json::to_value(grant).unwrap() - })) - .await - .unwrap(); - - assert!(!result.success); - assert!(!result.error.as_deref().unwrap_or("").contains("runtime approval grant")); - } - - #[tokio::test] - async fn supervised_write_ops_accept_matching_runtime_grant() { - let tmp = TempDir::new().unwrap(); - init_git_repo(tmp.path()).await; - - let tool = test_tool(tmp.path()); - let grant = ApprovalGrant::for_resource_operation("git_operations", "git_operations:commit", "test", None); - let result = tool - .execute(json!({ - "operation": "commit", - "message": "test", - (crate::security::policy::RUNTIME_APPROVAL_GRANT_ARG): serde_json::to_value(grant).unwrap() - })) - .await - .unwrap(); - - assert!(!result.success); - assert!(!result.error.as_deref().unwrap_or("").contains("runtime approval grant")); - } - - #[tokio::test] - async fn allows_branch_listing_in_readonly_mode() { - let tmp = TempDir::new().unwrap(); - // Initialize a git repository so the command can succeed - init_git_repo(tmp.path()).await; - - let security = Arc::new(SecurityPolicy { - autonomy: AutonomyLevel::ReadOnly, - ..SecurityPolicy::default() - }); - let tool = GitOperationsTool::new(security, tmp.path().to_path_buf()); - - let result = tool.execute(json!({"operation": "branch"})).await.unwrap(); - // Branch listing must not be blocked by read-only autonomy - let error_msg = result.error.as_deref().unwrap_or(""); - assert!( - !error_msg.contains("read-only") && !error_msg.contains("higher autonomy"), - "branch listing should not be blocked in read-only mode, got: {error_msg}" - ); - } - - #[tokio::test] - async fn allows_readonly_ops_in_readonly_mode() { - let tmp = TempDir::new().unwrap(); - init_git_repo(tmp.path()).await; - - let security = Arc::new(SecurityPolicy { - autonomy: AutonomyLevel::ReadOnly, - ..SecurityPolicy::default() - }); - let tool = GitOperationsTool::new(security, tmp.path().to_path_buf()); - - let result = tool.execute(json!({"operation": "status"})).await.unwrap(); - assert!( - result.success, - "read-only git status should be allowed: {:?}", - result.error - ); - } - - #[tokio::test] - async fn rejects_missing_operation() { - let tmp = TempDir::new().unwrap(); - let tool = test_tool(tmp.path()); - - let error = tool.execute(json!({})).await.unwrap_err(); - let typed = error.downcast_ref::().unwrap(); - assert!(typed.issues.iter().any(|issue| issue.path.contains("operation"))); - assert_eq!(std::fs::read_dir(tmp.path()).unwrap().count(), 0); - init_git_repo(tmp.path()).await; - let status = tool.execute(json!({"operation":"status"})).await.unwrap(); - assert!(status.success, "{:?}", status.error); - assert_eq!( - serde_json::from_str::(&status.output) - .unwrap() - .get("clean") - .and_then(serde_json::Value::as_bool), - Some(true) - ); - } - - #[tokio::test] - async fn rejects_unknown_operation() { - let tmp = TempDir::new().unwrap(); - // Initialize a git repository - init_git_repo(tmp.path()).await; - - let tool = test_tool(tmp.path()); - - let error = tool.execute(json!({"operation": "fetch_all"})).await.unwrap_err(); - let typed = error.downcast_ref::().unwrap(); - assert!(typed.issues.iter().any(|issue| issue.path.contains("operation"))); - let status = tool.execute(json!({"operation":"status"})).await.unwrap(); - assert!(status.success, "{:?}", status.error); - assert_eq!( - serde_json::from_str::(&status.output) - .unwrap() - .get("clean") - .and_then(serde_json::Value::as_bool), - Some(true) - ); - } - - // ── GIT-ENV (D-098): a repository's configuration is a launch definition ── - - /// A provider-key stand-in in PRX's own environment. No program a - /// repository configures may see it (and none may run at all). - #[cfg(unix)] - const PARENT_SENTINEL_NAME: &str = "PRX_GIT_ENV_TEST_PROVIDER_KEY"; - #[cfg(unix)] - const PARENT_SENTINEL_VALUE: &str = "git-env-parent-sentinel-5d1c"; - - #[cfg(unix)] - #[allow(unsafe_code)] - fn plant_parent_sentinel() { - static PLANTED: std::sync::Once = std::sync::Once::new(); - PLANTED.call_once(|| { - // SAFETY: test-only; set once, to a name no other code reads, - // before any git process of these tests is started. - unsafe { std::env::set_var(PARENT_SENTINEL_NAME, PARENT_SENTINEL_VALUE) }; - }); - } - - #[cfg(unix)] - fn full_tool(dir: &std::path::Path) -> GitOperationsTool { - crate::security::git_launch::hermetic_git_for_tests(); - let security = Arc::new(SecurityPolicy { - autonomy: AutonomyLevel::Full, - ..SecurityPolicy::default() - }); - GitOperationsTool::new(security, dir.to_path_buf()) - } - - /// Test-side git (repository setup), itself kept away from the - /// developer's configuration and from what the test plants. - async fn setup_git(dir: &std::path::Path, args: &[&str]) { - let output = tokio::process::Command::new("git") - .args([ - "-c", - "core.hooksPath=/dev/null", - "-c", - "core.fsmonitor=false", - "-c", - "commit.gpgSign=false", - ]) - .args(args) - .current_dir(dir) - .env("GIT_CONFIG_GLOBAL", "/dev/null") - .env("GIT_CONFIG_NOSYSTEM", "1") - .kill_on_drop(true) - .output() - .await - .expect("test: git runs"); - assert!( - output.status.success(), - "git {args:?}: {}", - String::from_utf8_lossy(&output.stderr) - ); - } - - /// [`setup_git`] for a command expected to fail (a conflicting merge). - async fn setup_git_may_fail(dir: &std::path::Path, args: &[&str]) { - let _ = tokio::process::Command::new("git") - .args(["-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false"]) - .args(args) - .current_dir(dir) - .env("GIT_CONFIG_GLOBAL", "/dev/null") - .env("GIT_CONFIG_NOSYSTEM", "1") - .kill_on_drop(true) - .output() - .await - .expect("test: git runs"); - } - - /// A repository at `dir` with an identity and one commit of `files`. - async fn committed_repo(dir: &std::path::Path, files: &[(&str, &str)]) { - std::fs::create_dir_all(dir).expect("test: workspace"); - setup_git(dir, &["init", "-q"]).await; - setup_git(dir, &["checkout", "-q", "-b", "main"]).await; - setup_git(dir, &["config", "user.name", "PRX Test"]).await; - setup_git(dir, &["config", "user.email", "prx@example.invalid"]).await; - for (name, content) in files { - std::fs::write(dir.join(name), content).expect("test: write file"); - } - setup_git(dir, &["add", "-A"]).await; - setup_git(dir, &["commit", "-q", "-m", "one"]).await; - } - - /// An executable script that dumps its environment to `marker` (and, - /// for a filter, passes its input through). - #[cfg(unix)] - fn plant_script(path: &std::path::Path, marker: &std::path::Path, pass_through: bool) -> String { - use std::os::unix::fs::PermissionsExt as _; - let body = format!( - "#!/bin/sh\nenv > '{}'\n{}", - marker.display(), - if pass_through { "cat\n" } else { "" } - ); - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent).expect("test: script directory"); - } - std::fs::write(path, body).expect("test: write script"); - std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).expect("test: chmod"); - path.display().to_string() - } - - /// The planted program never ran, and so never saw PRX's environment. - #[cfg(unix)] - fn assert_not_run(marker: &std::path::Path, what: &str) { - let dump = std::fs::read_to_string(marker).ok(); - assert!( - dump.as_deref() - .is_none_or(|environment| !environment.contains(PARENT_SENTINEL_VALUE)), - "{what} ran with PRX's environment: the parent sentinel reached it" - ); - assert!(dump.is_none(), "{what} ran (with a cleared environment)"); - } - - async fn run(tool: &GitOperationsTool, args: serde_json::Value) -> ToolResult { - // D-103: the tool's git reads a scratch global file, no system file. - crate::security::git_launch::hermetic_git_for_tests(); - tokio::time::timeout(std::time::Duration::from_mins(1), tool.execute(args)) - .await - .expect("test: git operation finished") - .expect("test: git operation executes") - } - - fn granted(operation_name: &str, mut args: serde_json::Value) -> serde_json::Value { - let grant = ApprovalGrant::for_resource_operation("git_operations", operation_name, "test", None); - if let Some(object) = args.as_object_mut() { - object.insert( - crate::security::policy::RUNTIME_APPROVAL_GRANT_ARG.to_string(), - serde_json::to_value(grant).expect("test: grant serialises"), - ); - } - args - } - - /// RED before GIT-ENV (R-HOOKSENV F-2): a workspace `.git/config` with - /// `core.fsmonitor` made a plain `status`, at supervised autonomy and - /// with no approval, run that command with PRX's full environment. It - /// must not run at all, whether set directly or through `include.path`. - #[cfg(unix)] - #[tokio::test] - async fn status_does_not_run_a_workspace_fsmonitor() { - plant_parent_sentinel(); - let tmp = TempDir::new().expect("test: temp dir"); - let workspace = tmp.path().join("ws"); - committed_repo(&workspace, &[("a.txt", "a\n")]).await; - let marker = tmp.path().join("fsmonitor-ran"); - let script = plant_script(&tmp.path().join("bin/fsmonitor.sh"), &marker, false); - setup_git(&workspace, &["config", "core.fsmonitor", &script]).await; - std::fs::write(workspace.join("a.txt"), "changed\n").expect("test: modify"); - - let tool = test_tool(&workspace); - let result = run(&tool, json!({"operation": "status"})).await; - assert!(result.success, "{:?}", result.error); - assert!(result.output.contains("\"clean\": false"), "{}", result.output); - assert!(result.output.contains("\"path\": \"a.txt\""), "{}", result.output); - assert_not_run(&marker, "core.fsmonitor"); - - // The same setting pulled in from an included file. - setup_git(&workspace, &["config", "--unset", "core.fsmonitor"]).await; - let included_marker = tmp.path().join("included-fsmonitor-ran"); - let included_script = plant_script(&tmp.path().join("bin/included.sh"), &included_marker, false); - let included = tmp.path().join("included.cfg"); - std::fs::write(&included, format!("[core]\n\tfsmonitor = {included_script}\n")).expect("test: include"); - setup_git(&workspace, &["config", "include.path", &included.display().to_string()]).await; - let result = run(&tool, json!({"operation": "diff"})).await; - assert!(result.success, "{:?}", result.error); - assert_not_run(&included_marker, "an included core.fsmonitor"); - } - - /// RED before GIT-ENV: `commit` ran the hooks of `.git/hooks` (and of a - /// repository-chosen `core.hooksPath`) with PRX's environment. - #[cfg(unix)] - #[tokio::test] - async fn commit_does_not_run_repository_hooks() { - plant_parent_sentinel(); - let tmp = TempDir::new().expect("test: temp dir"); - let workspace = tmp.path().join("ws"); - committed_repo(&workspace, &[("a.txt", "a\n")]).await; - let marker = tmp.path().join("hook-ran"); - for hook in [ - "pre-commit", - "prepare-commit-msg", - "commit-msg", - "post-commit", - "reference-transaction", - ] { - plant_script(&workspace.join(".git/hooks").join(hook), &marker, false); - } - let chosen_marker = tmp.path().join("chosen-hook-ran"); - plant_script(&workspace.join(".githooks/pre-commit"), &chosen_marker, false); - - let tool = full_tool(&workspace); - std::fs::write(workspace.join("b.txt"), "b\n").expect("test: new file"); - let add = run(&tool, json!({"operation": "add", "paths": "b.txt"})).await; - assert!(add.success, "{:?}", add.error); - let commit = run(&tool, json!({"operation": "commit", "message": "two"})).await; - assert!(commit.success, "{:?}", commit.error); - assert_not_run(&marker, "a .git/hooks hook"); - - setup_git(&workspace, &["config", "core.hooksPath", ".githooks"]).await; - std::fs::write(workspace.join("b.txt"), "b2\n").expect("test: modify"); - let add = run(&tool, json!({"operation": "add", "paths": "b.txt"})).await; - assert!(add.success, "{:?}", add.error); - let commit = run(&tool, json!({"operation": "commit", "message": "three"})).await; - assert!(commit.success, "{:?}", commit.error); - assert_not_run(&chosen_marker, "a core.hooksPath hook"); - - // The commits landed, under the repository's own identity. - let log = run(&tool, json!({"operation": "log", "limit": 3})).await; - assert!(log.success, "{:?}", log.error); - assert!( - log.output.contains("three") && log.output.contains("two"), - "{}", - log.output - ); - assert!(log.output.contains("prx@example.invalid"), "{}", log.output); - } - - /// RED before GIT-ENV: `add` ran a filter driver's `clean` command (and - /// stash pop its `smudge`) named by `.gitattributes` and defined in - /// `.git/config`. The driver is neutralised; the content passes through. - #[cfg(unix)] - #[tokio::test] - async fn add_stash_and_diff_do_not_run_filter_or_diff_drivers() { - plant_parent_sentinel(); - let tmp = TempDir::new().expect("test: temp dir"); - let workspace = tmp.path().join("ws"); - committed_repo( - &workspace, - &[ - ("a.txt", "a\n"), - (".gitattributes", "*.txt filter=ev diff=ev merge=ev\n"), - ], - ) - .await; - let marker = tmp.path().join("driver-ran"); - let filter = plant_script(&tmp.path().join("bin/filter.sh"), &marker, true); - for (key, value) in [ - ("filter.ev.clean", filter.as_str()), - ("filter.ev.smudge", filter.as_str()), - ("filter.ev.required", "true"), - ("diff.ev.textconv", filter.as_str()), - ("diff.ev.command", filter.as_str()), - ("diff.external", filter.as_str()), - ("merge.ev.driver", filter.as_str()), - ] { - setup_git(&workspace, &["config", key, value]).await; - } - - let tool = full_tool(&workspace); - std::fs::write(workspace.join("a.txt"), "a2\n").expect("test: modify"); - let diff = run(&tool, json!({"operation": "diff"})).await; - assert!(diff.success, "{:?}", diff.error); - assert!(diff.output.contains("a2"), "{}", diff.output); - let add = run(&tool, json!({"operation": "add", "paths": "a.txt"})).await; - assert!(add.success, "{:?}", add.error); - let commit = run(&tool, json!({"operation": "commit", "message": "two"})).await; - assert!(commit.success, "{:?}", commit.error); - std::fs::write(workspace.join("a.txt"), "a3\n").expect("test: modify"); - let push = run(&tool, json!({"operation": "stash", "action": "push"})).await; - assert!(push.success, "{:?}", push.error); - let pop = run(&tool, json!({"operation": "stash", "action": "pop"})).await; - assert!(pop.success, "{:?}", pop.error); - assert_eq!( - std::fs::read_to_string(workspace.join("a.txt")).expect("test: read"), - "a3\n" - ); - assert_not_run(&marker, "a filter or diff driver"); - } - - /// RED before GIT-ENV: an authenticated transfer ran the repository's - /// `credential.helper` with PRX's environment. A loopback server that - /// answers every request with 401 makes git ask for credentials. - #[cfg(unix)] - #[tokio::test] - async fn push_does_not_run_a_repository_credential_helper() { - use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; - plant_parent_sentinel(); - let tmp = TempDir::new().expect("test: temp dir"); - let workspace = tmp.path().join("ws"); - committed_repo(&workspace, &[("a.txt", "a\n")]).await; - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.expect("test: bind"); - let port = listener.local_addr().expect("test: address").port(); - let server = tokio::spawn(async move { - while let Ok((mut socket, _)) = listener.accept().await { - let mut request = vec![0_u8; 8192]; - let _ = socket.read(&mut request).await; - let _ = socket - .write_all( - b"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Basic realm=\"prx\"\r\n\ - Content-Length: 0\r\nConnection: close\r\n\r\n", - ) - .await; - } - }); - let marker = tmp.path().join("credential-helper-ran"); - let helper = plant_script(&tmp.path().join("bin/credential.sh"), &marker, false); - let url = format!("http://127.0.0.1:{port}/r.git"); - setup_git(&workspace, &["remote", "add", "origin", &url]).await; - setup_git(&workspace, &["config", "http.proxy", ""]).await; - setup_git(&workspace, &["config", "credential.helper", &helper]).await; - setup_git(&workspace, &["config", &format!("credential.{url}.helper"), &helper]).await; - - let tool = full_tool(&workspace); - let push = run( - &tool, - json!({"operation": "push", "remote": "origin", "branch": "main"}), - ) - .await; - server.abort(); - assert!(!push.success, "the push to a 401 server cannot succeed"); - assert_not_run(&marker, "credential.helper"); - } - - /// RED before GIT-ENV (R-HOOKSENV I-3): a checkout that rewrites the - /// workspace `hooks.json` was an ordinary, medium-risk checkout, so its - /// ordinary approval covered it. It is now a high-risk operation of its - /// own; a checkout that leaves the launch definitions alone keeps its - /// ordinary approval. - #[tokio::test] - async fn a_checkout_that_changes_hooks_json_needs_its_own_approval() { - let tmp = TempDir::new().expect("test: temp dir"); - let workspace = tmp.path().join("ws"); - committed_repo(&workspace, &[("a.txt", "a\n"), ("hooks.json", "{\"v\":1}\n")]).await; - setup_git(&workspace, &["checkout", "-q", "-b", "other"]).await; - std::fs::write(workspace.join("hooks.json"), "{\"v\":2}\n").expect("test: hooks v2"); - setup_git(&workspace, &["commit", "-q", "-am", "hooks v2"]).await; - setup_git(&workspace, &["checkout", "-q", "main"]).await; - setup_git(&workspace, &["checkout", "-q", "-b", "same"]).await; - std::fs::write(workspace.join("a.txt"), "a2\n").expect("test: a2"); - setup_git(&workspace, &["commit", "-q", "-am", "a2"]).await; - setup_git(&workspace, &["checkout", "-q", "main"]).await; - - let tool = test_tool(&workspace); - let result = run( - &tool, - granted( - "git_operations:checkout:other", - json!({"operation": "checkout", "branch": "other"}), - ), - ) - .await; - assert!( - !result.success, - "an ordinary checkout approval covered a hooks.json change" - ); - let error = result.error.unwrap_or_default(); - assert!(error.contains("workspace launch definition"), "{error}"); - assert_eq!( - std::fs::read_to_string(workspace.join("hooks.json")).expect("test: read"), - "{\"v\":1}\n" - ); - - let result = run( - &tool, - granted( - "git_operations:checkout:same", - json!({"operation": "checkout", "branch": "same"}), - ), - ) - .await; - assert!(result.success, "{:?}", result.error); - assert_eq!( - std::fs::read_to_string(workspace.join("a.txt")).expect("test: read"), - "a2\n" - ); - } - - /// RED before GIT-ENV: `stash pop` bringing back a changed `mcp.json`, - /// and `stash push` reverting a changed `hooks.json`, were ordinary - /// stash operations. - #[tokio::test] - async fn a_stash_that_changes_a_launch_definition_needs_its_own_approval() { - let tmp = TempDir::new().expect("test: temp dir"); - let workspace = tmp.path().join("ws"); - committed_repo(&workspace, &[("hooks.json", "{\"v\":1}\n"), ("mcp.json", "{}\n")]).await; - std::fs::write(workspace.join("mcp.json"), "{\"servers\":{}}\n").expect("test: mcp v2"); - setup_git(&workspace, &["stash", "push", "-q"]).await; - std::fs::write(workspace.join("hooks.json"), "{\"v\":2}\n").expect("test: hooks v2"); - - let tool = test_tool(&workspace); - let push = run( - &tool, - granted( - "git_operations:stash:push", - json!({"operation": "stash", "action": "push"}), - ), - ) - .await; - assert!(!push.success, "an ordinary stash approval covered reverting hooks.json"); - assert!( - push.error.unwrap_or_default().contains("workspace launch definition"), - "the refusal names the launch definition" - ); - assert_eq!( - std::fs::read_to_string(workspace.join("hooks.json")).expect("test: read"), - "{\"v\":2}\n" - ); - - setup_git(&workspace, &["checkout", "-q", "--", "hooks.json"]).await; - let pop = run( - &tool, - granted( - "git_operations:stash:pop", - json!({"operation": "stash", "action": "pop"}), - ), - ) - .await; - assert!(!pop.success, "an ordinary stash approval covered restoring mcp.json"); - assert!( - pop.error.unwrap_or_default().contains("workspace launch definition"), - "the refusal names the launch definition" - ); - assert_eq!( - std::fs::read_to_string(workspace.join("mcp.json")).expect("test: read"), - "{}\n" - ); - } - - /// R-GITENV F-1: a push to a local-path remote whose - /// `remote.origin.receivepack` names a program (first-wins, so no `-c` - /// replaces it) runs git's own receive-pack. - #[cfg(unix)] - #[tokio::test] - async fn push_does_not_run_a_repository_receive_pack() { - plant_parent_sentinel(); - let tmp = TempDir::new().expect("test: temp dir"); - let workspace = tmp.path().join("ws"); - committed_repo(&workspace, &[("a.txt", "a\n")]).await; - let remote = tmp.path().join("remote.git"); - std::fs::create_dir_all(&remote).expect("test: remote"); - setup_git(&remote, &["init", "-q", "--bare"]).await; - let marker = tmp.path().join("receive-pack-ran"); - let program = plant_script(&tmp.path().join("bin/receive.sh"), &marker, false); - setup_git(&workspace, &["remote", "add", "origin", &remote.display().to_string()]).await; - setup_git(&workspace, &["config", "remote.origin.receivepack", &program]).await; - - let tool = full_tool(&workspace); - let push = run( - &tool, - json!({"operation": "push", "remote": "origin", "branch": "main"}), - ) - .await; - assert!(!push.success, "a repository receive-pack program must refuse the push"); - assert!( - push.error.as_deref().is_some_and(|error| error.contains("receivepack")), - "{:?}", - push.error - ); - assert_not_run(&marker, "remote.origin.receivepack"); - setup_git(&workspace, &["config", "--unset", "remote.origin.receivepack"]).await; - let push = run( - &tool, - json!({"operation": "push", "remote": "origin", "branch": "main"}), - ) - .await; - assert!(push.success, "{:?}", push.error); - setup_git(&remote, &["rev-parse", "--verify", "refs/heads/main"]).await; - } - - /// R-GITENV F-11: the porcelain-v2 records, NUL separated. - #[test] - fn the_status_parser_reads_every_porcelain_v2_record() { - let output = [ - "# branch.oid 0123", - "# branch.head main", - "1 M. N... 100644 100644 100644 aaaa bbbb staged.txt", - "1 .M N... 100644 100644 100644 aaaa aaaa with space.txt", - "2 R. N... 100644 100644 100644 aaaa aaaa R100 new name.txt", - "old name.txt", - "u UU N... 100644 100644 100644 100644 aaaa bbbb cccc conflict.txt", - "? untracked file.txt", - "! ignored.txt", - "", - ] - .join("\0"); - let status = parse_porcelain_v2(&output); - assert_eq!(status.branch, "main"); - assert_eq!( - status.staged, - vec![ - json!({"path": "staged.txt", "status": "M"}), - json!({"path": "new name.txt", "status": "R", "original_path": "old name.txt"}), - ] - ); - assert_eq!(status.unstaged, vec![json!({"path": "with space.txt", "status": "M"})]); - assert_eq!(status.conflicted, vec![json!({"path": "conflict.txt", "status": "UU"})]); - assert_eq!(status.untracked, vec!["untracked file.txt".to_string()]); - } - - /// R-GITENV F-11 through the tool: staged, unstaged, a space in a path, - /// a rename and a conflict. - #[tokio::test] - async fn status_reports_staged_unstaged_renamed_and_conflicted_paths() { - let tmp = TempDir::new().expect("test: temp dir"); - let workspace = tmp.path().join("ws"); - committed_repo( - &workspace, - &[ - ("a.txt", "a\n"), - ("b c.txt", "b\n"), - ("old.txt", "o\n"), - ("conflict.txt", "base\n"), - ], - ) - .await; - setup_git(&workspace, &["checkout", "-q", "-b", "other"]).await; - std::fs::write(workspace.join("conflict.txt"), "other\n").expect("test: other side"); - setup_git(&workspace, &["commit", "-q", "-am", "other"]).await; - setup_git(&workspace, &["checkout", "-q", "main"]).await; - std::fs::write(workspace.join("conflict.txt"), "main\n").expect("test: main side"); - setup_git(&workspace, &["commit", "-q", "-am", "main"]).await; - setup_git_may_fail(&workspace, &["merge", "-q", "other"]).await; - std::fs::write(workspace.join("a.txt"), "a2\n").expect("test: staged"); - setup_git(&workspace, &["add", "a.txt"]).await; - std::fs::write(workspace.join("b c.txt"), "b2\n").expect("test: unstaged"); - setup_git(&workspace, &["mv", "old.txt", "new.txt"]).await; - - let result = run(&test_tool(&workspace), json!({"operation": "status"})).await; - assert!(result.success, "{:?}", result.error); - let status: serde_json::Value = serde_json::from_str(&result.output).expect("test: json"); - let paths = |list: &str| { - status - .get(list) - .and_then(serde_json::Value::as_array) - .map(|entries| { - entries - .iter() - .filter_map(|entry| entry.get("path").and_then(serde_json::Value::as_str)) - .map(ToString::to_string) - .collect::>() - }) - .unwrap_or_default() - }; - assert!(paths("staged").contains(&"a.txt".to_string()), "{status}"); - assert!(paths("staged").contains(&"new.txt".to_string()), "{status}"); - assert!(paths("unstaged").contains(&"b c.txt".to_string()), "{status}"); - assert_eq!(paths("conflicted"), vec!["conflict.txt".to_string()], "{status}"); - assert_eq!(status.get("clean"), Some(&json!(false))); - } - - #[test] - fn truncates_multibyte_commit_message_without_panicking() { - let long = "🦀".repeat(2500); - let truncated = GitOperationsTool::truncate_commit_message(&long); - - assert_eq!(truncated.chars().count(), 2000); - } -} diff --git a/src/tools/mod.rs b/src/tools/mod.rs index 733d3c5ac..c73d6c0de 100644 --- a/src/tools/mod.rs +++ b/src/tools/mod.rs @@ -37,7 +37,6 @@ pub mod file_edit; pub mod file_read; pub mod file_write; pub mod gateway; -pub mod git_operations; pub mod http_request; pub mod image; pub mod image_info; @@ -107,7 +106,6 @@ pub use file_edit::FileEditTool; pub use file_read::FileReadTool; pub use file_write::FileWriteTool; pub use gateway::GatewayTool; -pub use git_operations::GitOperationsTool; pub use http_request::HttpRequestTool; pub use image::ImageTool; pub use image_info::ImageInfoTool; @@ -148,7 +146,6 @@ pub const STATIC_PUBLIC_TOOL_NAMES: &[&str] = &[ "file_read", "file_write", "file_edit", - "git_operations", "web_search_tool", "web_fetch", "http_request", @@ -537,7 +534,6 @@ pub fn all_tools_with_runtime_ext_and_extensions( Arc::new(FileWriteTool::new(security.clone()).with_workdir(Some(working_root.to_path_buf()))), Arc::new(FileEditTool::new(security.clone()).with_workdir(Some(working_root.to_path_buf()))), Arc::new(ProxyConfigTool::new(shared_config.clone(), security.clone())), - Arc::new(GitOperationsTool::new(security.clone(), working_root.to_path_buf())), Arc::new(PushoverTool::new(security.clone(), workspace_dir.to_path_buf())), Arc::new(SkillsListTool::new(workspace_dir.to_path_buf(), root_config.clone())), Arc::new(SkillReadTool::new(workspace_dir.to_path_buf(), root_config.clone())), @@ -752,7 +748,7 @@ mod tests { #[test] fn static_public_tool_inventory_is_complete_unique_and_documented() { - assert_eq!(STATIC_PUBLIC_TOOL_NAMES.len(), 55); + assert_eq!(STATIC_PUBLIC_TOOL_NAMES.len(), 54); let unique = STATIC_PUBLIC_TOOL_NAMES.iter().copied().collect::>(); assert_eq!(unique.len(), STATIC_PUBLIC_TOOL_NAMES.len()); diff --git a/src/tools/schema/execution_contract.rs b/src/tools/schema/execution_contract.rs index 32375759a..69760f8b5 100644 --- a/src/tools/schema/execution_contract.rs +++ b/src/tools/schema/execution_contract.rs @@ -117,7 +117,6 @@ pub(crate) fn assert_execution_schema_golden(name: &str, schema: &Value) { "document_get_chunk" => include_str!("goldens/document_get_chunk.json"), "document_ingest" => include_str!("goldens/document_ingest.json"), "gateway" => include_str!("goldens/gateway.json"), - "git_operations" => include_str!("goldens/git_operations.json"), "hooks_manage" => include_str!("goldens/hooks_manage.json"), "image" => include_str!("goldens/image.json"), "managed_session" => include_str!("goldens/managed_session.json"), @@ -147,7 +146,6 @@ pub(crate) fn assert_published_schema_golden(name: &str, schema: &Value) { "document_get_chunk" => include_str!("goldens/published/document_get_chunk.json"), "document_ingest" => include_str!("goldens/published/document_ingest.json"), "gateway" => include_str!("goldens/published/gateway.json"), - "git_operations" => include_str!("goldens/published/git_operations.json"), "hooks_manage" => include_str!("goldens/published/hooks_manage.json"), "image" => include_str!("goldens/published/image.json"), "managed_session" => include_str!("goldens/published/managed_session.json"), diff --git a/src/tools/schema/goldens/git_operations.json b/src/tools/schema/goldens/git_operations.json deleted file mode 100644 index 1d3d788db..000000000 --- a/src/tools/schema/goldens/git_operations.json +++ /dev/null @@ -1,126 +0,0 @@ -{ - "allOf": [ - { - "if": { - "properties": { - "operation": { - "const": "commit" - } - }, - "required": [ - "operation" - ] - }, - "then": { - "required": [ - "message" - ] - } - }, - { - "if": { - "properties": { - "operation": { - "const": "add" - } - }, - "required": [ - "operation" - ] - }, - "then": { - "required": [ - "paths" - ] - } - }, - { - "if": { - "properties": { - "operation": { - "const": "checkout" - } - }, - "required": [ - "operation" - ] - }, - "then": { - "required": [ - "branch" - ] - } - } - ], - "properties": { - "action": { - "description": "Sub-action of the 'stash' operation: 'push' saves the working tree, 'pop' restores the latest entry, 'list' shows the entries, 'drop' deletes one by index", - "enum": [ - "push", - "pop", - "list", - "drop" - ], - "type": "string" - }, - "branch": { - "description": "Branch name (for 'checkout' or 'push' operation)", - "minLength": 1, - "type": "string" - }, - "cached": { - "description": "Show staged changes (for 'diff' operation)", - "type": "boolean" - }, - "files": { - "description": "File or path to diff (for 'diff' operation, default: '.')", - "type": "string" - }, - "index": { - "description": "Stash index (for 'stash' with 'drop' action)", - "type": "integer" - }, - "limit": { - "description": "Number of log entries (for 'log' operation, default: 10)", - "type": "integer" - }, - "message": { - "description": "Commit message (for 'commit' operation)", - "minLength": 1, - "type": "string" - }, - "operation": { - "description": "Git operation to perform", - "enum": [ - "status", - "diff", - "log", - "branch", - "commit", - "add", - "checkout", - "stash", - "push", - "reset_hard" - ], - "type": "string" - }, - "paths": { - "description": "File paths to stage (for 'add' operation)", - "minLength": 1, - "type": "string" - }, - "remote": { - "description": "Remote name (for 'push' operation, default: origin)", - "type": "string" - }, - "target": { - "description": "Revision target (for 'reset_hard' operation, default: HEAD)", - "type": "string" - } - }, - "required": [ - "operation" - ], - "type": "object" -} diff --git a/src/tools/schema/goldens/published/git_operations.json b/src/tools/schema/goldens/published/git_operations.json deleted file mode 100644 index 06551f1af..000000000 --- a/src/tools/schema/goldens/published/git_operations.json +++ /dev/null @@ -1,73 +0,0 @@ -{ - "properties": { - "action": { - "description": "Sub-action of the 'stash' operation: 'push' saves the working tree, 'pop' restores the latest entry, 'list' shows the entries, 'drop' deletes one by index", - "enum": [ - "push", - "pop", - "list", - "drop" - ], - "type": "string" - }, - "branch": { - "description": "Branch name (for 'checkout' or 'push' operation)", - "minLength": 1, - "type": "string" - }, - "cached": { - "description": "Show staged changes (for 'diff' operation)", - "type": "boolean" - }, - "files": { - "description": "File or path to diff (for 'diff' operation, default: '.')", - "type": "string" - }, - "index": { - "description": "Stash index (for 'stash' with 'drop' action)", - "type": "integer" - }, - "limit": { - "description": "Number of log entries (for 'log' operation, default: 10)", - "type": "integer" - }, - "message": { - "description": "Commit message (for 'commit' operation)", - "minLength": 1, - "type": "string" - }, - "operation": { - "description": "Git operation to perform", - "enum": [ - "status", - "diff", - "log", - "branch", - "commit", - "add", - "checkout", - "stash", - "push", - "reset_hard" - ], - "type": "string" - }, - "paths": { - "description": "File paths to stage (for 'add' operation)", - "minLength": 1, - "type": "string" - }, - "remote": { - "description": "Remote name (for 'push' operation, default: origin)", - "type": "string" - }, - "target": { - "description": "Revision target (for 'reset_hard' operation, default: HEAD)", - "type": "string" - } - }, - "required": [ - "operation" - ], - "type": "object" -} diff --git a/src/tools/shell_parity_tests.rs b/src/tools/shell_parity_tests.rs index b57890b4a..8a35d8069 100644 --- a/src/tools/shell_parity_tests.rs +++ b/src/tools/shell_parity_tests.rs @@ -326,15 +326,10 @@ async fn configured_workdir_is_shared_by_shell_files_and_git() { write.success && workdir.path().join("relative.txt").exists(), "test: native root: {write:?}" ); - let status = direct( - find("git_operations"), - AutonomyLevel::Full, - json!({"operation":"status"}), - ) - .await; + let status = direct(find("shell"), AutonomyLevel::Full, json!({"command":"git status --short"})).await; assert!( status.success && status.output.contains("relative.txt"), - "test: hardened git root: {status:?}" + "test: shell git root: {status:?}" ); assert!( !workspace.path().join("relative.txt").exists(), diff --git a/tests/fixtures/config-schema.json b/tests/fixtures/config-schema.json index 7300d84c3..766fb54c9 100644 --- a/tests/fixtures/config-schema.json +++ b/tests/fixtures/config-schema.json @@ -1 +1 @@ -{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Config","description":"Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).","type":"object","properties":{"a2a":{"description":"Agent-to-Agent compatibility configuration (`[a2a]`).","$ref":"#/$defs/A2aConfig","default":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trusted_trust_domains":[],"trust_domain":"prx.local"}},"agent":{"description":"Agent orchestration settings (`[agent]`).","$ref":"#/$defs/AgentConfig","default":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2,"messaging":{"inbound":true}}},"agents":{"description":"Delegate agent configurations for multi-agent workflows.","type":"object","additionalProperties":{"$ref":"#/$defs/DelegateAgentConfig"},"default":{}},"api_key":{"description":"API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.","type":["string","null"],"default":null},"api_url":{"description":"Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)","type":["string","null"],"default":null},"auth":{"description":"Auth profile and external credential import settings (`[auth]`).","$ref":"#/$defs/AuthConfig","default":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"}},"autonomy":{"description":"Autonomy and security policy configuration (`[autonomy]`).","$ref":"#/$defs/AutonomyConfig","default":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":500,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true}},"browser":{"description":"Browser automation configuration (`[browser]`).","$ref":"#/$defs/BrowserConfig","default":{"allowed_domains":[],"computer_use":{"api_key":null}}},"channels_config":{"description":"Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).","$ref":"#/$defs/ChannelsConfig","default":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null}},"chat":{"description":"Interactive chat UI configuration (`[chat]`).","$ref":"#/$defs/ChatConfig","default":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2}},"compliance":{"description":"Operator-owned compliance controls (`[compliance]`).","$ref":"#/$defs/ComplianceConfig","default":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}},"composio":{"description":"Composio managed OAuth tools integration (`[composio]`).","$ref":"#/$defs/ComposioConfig","default":{"api_key":null,"entity_id":"default"}},"cost":{"description":"Cost tracking and budget enforcement configuration (`[cost]`).","$ref":"#/$defs/CostConfig","default":{"allow_override":false,"daily_limit_usd":10.0,"monthly_limit_usd":100.0,"prices":{},"warn_at_percent":80}},"cron":{"description":"Cron job configuration (`[cron]`).","$ref":"#/$defs/CronConfig","default":{"max_run_history":50}},"decision_engine":{"description":"Optional advisory decision engine, disabled by default.","$ref":"#/$defs/DecisionEngineConfig","default":{"candidates":5,"enabled":false,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"latency_budget_ms":500,"max_candidates":12,"token_ratio_limit":0.3499999940395355}},"default_model":{"description":"Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.","type":["string","null"]},"default_provider":{"description":"Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.","type":["string","null"]},"default_temperature":{"description":"Default model temperature (0.0–2.0). Default: `0.7`.","type":"number","format":"double","default":0.7},"embedding_routes":{"description":"Embedding routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/EmbeddingRouteConfig"}},"gateway":{"description":"Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).","$ref":"#/$defs/GatewayConfig","default":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":false,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60}},"heartbeat":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]`).","$ref":"#/$defs/HeartbeatConfig","default":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."}},"http_request":{"description":"HTTP request tool configuration (`[http_request]`).","$ref":"#/$defs/HttpRequestConfig","default":{"max_response_size":1000000,"timeout_secs":30}},"identity":{"description":"Identity format configuration: OpenClaw or AIEOS (`[identity]`).","$ref":"#/$defs/IdentityConfig","default":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"}},"identity_bindings":{"description":"Static identity bindings loaded at startup (`[[identity_bindings]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/IdentityBindingConfig"}},"mcp":{"description":"Secrets encryption configuration (`[secrets]`).","$ref":"#/$defs/McpConfig","default":{"servers":{}}},"mcp_server":{"description":"MCP server compatibility configuration (`[mcp_server]`).","$ref":"#/$defs/McpServerRuntimeConfig","default":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true}},"media":{"description":"Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.","$ref":"#/$defs/MediaConfig","default":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"}},"memory":{"description":"Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).","$ref":"#/$defs/MemoryConfig","default":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7}},"model_routes":{"description":"Model routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/ModelRouteConfig"}},"model_settings":{"description":"Catalog model levels and explicit parameters, keyed by canonical release ID.","type":"object","additionalProperties":{"$ref":"#/$defs/ModelSettings"},"default":{}},"multimodal":{"description":"Multimodal (image) handling configuration (`[multimodal]`).","$ref":"#/$defs/MultimodalConfig","default":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4}},"nodes":{"description":"Remote node proxy configuration (`[nodes]`).","$ref":"#/$defs/NodesConfig","default":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}},"observability":{"description":"Observability backend configuration (`[observability]`).","$ref":"#/$defs/ObservabilityConfig","default":{"backend":"none","otel_endpoint":null,"otel_service_name":null}},"plugins":{"description":"WASM plugin runtime switch (`[plugins]`), off by default.","$ref":"#/$defs/PluginsConfig","default":{"enabled":false}},"providers":{"description":"Provider-specific runtime options (`[providers.]`).","$ref":"#/$defs/ProvidersConfig","default":{"ollama":{"num_ctx":null}}},"proxy":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).","$ref":"#/$defs/ProxyConfig","default":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]}},"query_classification":{"description":"Automatic query classification — maps user messages to model hints.","$ref":"#/$defs/QueryClassificationConfig","default":{"rules":[]}},"reliability":{"description":"Reliability settings: retries, fallback providers, backoff (`[reliability]`).","$ref":"#/$defs/ReliabilityConfig","default":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2}},"router":{"description":"Heuristic LLM router configuration (`[router]`).","$ref":"#/$defs/RouterConfig","default":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]}},"runtime":{"description":"Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.","$ref":"#/$defs/RuntimeConfig","default":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null}},"scheduler":{"description":"Scheduler configuration for periodic task execution (`[scheduler]`).","$ref":"#/$defs/SchedulerConfig","default":{"claim_lease_secs":90,"max_tasks":64}},"secrets":{"$ref":"#/$defs/SecretsConfig","default":{"encrypt":true}},"security":{"description":"Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).","$ref":"#/$defs/SecurityConfig","default":{"audit":{"log_path":"audit.log","max_size_mb":100}}},"self_system":{"description":"Self-system experimental automation controls (`[self_system]`).","$ref":"#/$defs/SelfSystemConfig","default":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24}},"sessions_spawn":{"description":"Session spawning configuration (`[sessions_spawn]`).","$ref":"#/$defs/SessionsSpawnConfig","default":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null}},"skill_rag":{"description":"Dynamic skill retrieval settings (`[skill_rag]`).","$ref":"#/$defs/SkillRagConfig","default":{"top_k":32}},"skills":{"description":"Skills loading and community repository behavior (`[skills]`).","$ref":"#/$defs/SkillsConfig","default":{"open_skills_dir":null,"openclaw_skills_dir":null}},"skills_lifecycle":{"description":"Skill lifecycle (`[skills_lifecycle]`), off by default.","$ref":"#/$defs/SkillsLifecycleConfig","default":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]}},"smart_group":{"description":"Smart group-reply pre-gate configuration (`[smart_group]`).","$ref":"#/$defs/SmartGroupConfig","default":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5}},"storage":{"description":"Persistent storage provider configuration (`[storage]`).","$ref":"#/$defs/StorageConfig","default":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"task_routing":{"description":"Task routing configuration — classifies work by intent before the main agent loop.","$ref":"#/$defs/TaskRoutingConfig","default":{"default_intent":"simple","rules":[]}},"tool_tiering":{"description":"Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).","$ref":"#/$defs/ToolTieringConfig","default":{"always_exclude":[],"always_include":[],"channel_exclude":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","git_operations","skills_manage","memory_reindex","document_sync","document_ingest"]}},"tunnel":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]`).","$ref":"#/$defs/TunnelConfig","default":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null}},"user_policies":{"description":"Static user policy records loaded at startup (`[[user_policies]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/UserPolicyConfig"}},"web_search":{"description":"Web search tool configuration (`[web_search]`).","$ref":"#/$defs/WebSearchConfig","default":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15}},"webhook":{"description":"Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).","$ref":"#/$defs/MemoryWebhookConfig","default":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null}},"xin":{"description":"Xin autonomous task engine configuration (`[xin]`).","$ref":"#/$defs/XinConfig","default":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}}},"$defs":{"A2aConfig":{"type":"object","properties":{"agent_id":{"description":"Stable PRX agent identifier advertised to peers.","type":"string","default":"prx-default"},"allowed_peer_issuers":{"description":"Accepted external peer issuers.","type":"array","default":[],"items":{"type":"string"}},"bind":{"description":"Advertised bind address.","type":"string","default":"127.0.0.1:16832"},"card_jwks_uri":{"description":"Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.","type":["string","null"],"default":null},"card_signing_key_path":{"description":"On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).","type":["string","null"],"default":null},"card_ttl_seconds":{"description":"Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.","type":"integer","format":"uint64","default":3600,"minimum":0},"discovery_advertised":{"description":"Whether to advertise into an external A2A registry.","type":"boolean","default":false},"handoff_nonce_ttl_seconds":{"description":"Replay window for future handoff delegation tokens.","type":"integer","format":"uint64","default":3600,"minimum":0},"messaging_enabled":{"description":"Enable the dedicated pinned mTLS messaging listener.","type":"boolean","default":false},"peers":{"type":"object","additionalProperties":{"$ref":"#/$defs/A2aPeer"},"default":{}},"spiffe_id":{"description":"Local SPIFFE-style identifier placeholder.","type":"string","default":"spiffe://prx-local/agent/prx-default"},"spiffe_strict_validation":{"description":"When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.","type":"boolean","default":false},"spiffe_trust_bundle_pem":{"description":"Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).","type":["string","null"],"default":null},"trusted_trust_domains":{"description":"Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).","type":"array","default":[],"items":{"type":"string"}},"trust_domain":{"description":"SPIFFE trust domain for new instance identities.","type":"string","default":"prx.local"}}},"A2aPeer":{"description":"Explicit pinned identity and local recipient grant.","type":"object","properties":{"spiffe_id":{"type":"string"},"fingerprints":{"type":"array","items":{"type":"string"}},"address":{"type":"string"},"owner":{"type":"string"},"sessions":{"type":"array","default":["*"],"items":{"type":"string"}},"agents":{"type":"array","default":["*"],"items":{"type":"string"}}},"required":["spiffe_id","fingerprints","address","owner"],"additionalProperties":false},"AgentCompactionConfig":{"description":"Agent context compaction configuration (`[agent.compaction]`).","type":"object","properties":{"keep_recent_messages":{"description":"Number of recent non-system messages to keep after compaction.","type":"integer","format":"uint","default":12,"minimum":0},"max_context_tokens":{"description":"Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.","type":"integer","format":"uint","default":128000,"minimum":0},"memory_flush":{"description":"Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.","type":"boolean","default":true},"mode":{"description":"Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).","$ref":"#/$defs/AgentCompactionMode","default":"switch"},"os_paging":{"description":"Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.","$ref":"#/$defs/OsPagingConfig","default":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"}},"reserve_tokens":{"description":"Tokens reserved for the next model response.","type":"integer","format":"uint","default":4096,"minimum":0}}},"AgentCompactionMode":{"description":"Compaction mode for long conversation contexts.","oneOf":[{"description":"Disable proactive compaction.","type":"string","const":"off"},{"description":"Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.","type":"string","const":"switch"},{"description":"Conservative compaction that prefers summary replacement.","type":"string","const":"safeguard"},{"description":"Aggressive truncation mode for tighter contexts.","type":"string","const":"aggressive"}]},"AgentConfig":{"description":"Agent orchestration configuration (`[agent]` section).","type":"object","properties":{"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"compact_context":{"description":"When true: bootstrap_max_chars=6000. Use for 13B or smaller models.","type":"boolean","default":false},"compaction":{"description":"Context compaction controls (`[agent.compaction]`).","$ref":"#/$defs/AgentCompactionConfig","default":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096}},"low_priority_tools":{"description":"Tool names treated as low-priority when `priority_scheduling_enabled = true`.","type":"array","default":["sessions_spawn","delegate"],"items":{"type":"string"}},"priority_scheduling_enabled":{"description":"Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.","type":"boolean","default":false},"read_only_tool_concurrency_window":{"description":"Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.","type":"integer","format":"uint","default":2,"minimum":0},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}}},"AgentLimits":{"description":"Optional admission limits for rf-started turns of a named agent.","type":"object","properties":{"max_concurrent_turns":{"type":["integer","null"],"format":"uint32","minimum":0},"max_cost_per_day_cents":{"type":["integer","null"],"format":"uint64","minimum":0}},"additionalProperties":false},"AuditConfig":{"description":"Audit logging configuration","type":"object","properties":{"log_path":{"description":"Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).","type":"string","default":"audit.log"},"max_size_mb":{"description":"Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).","type":"integer","format":"uint32","default":100,"minimum":0}}},"AuthConfig":{"description":"Authentication and external credential import configuration (`[auth]` section).","type":"object","properties":{"codex_auth_json_auto_import":{"description":"Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.","type":"boolean","default":false},"codex_auth_json_path":{"description":"Source path for Codex CLI auth.json import.","type":"string","default":"~/.codex/auth.json"}}},"AutonomyConfig":{"type":"object","properties":{"acknowledge_unrestricted_profile":{"description":"Operator acknowledgement for an intentionally unrestricted profile.\nThis suppresses doctor noise only; it does not alter policy behavior.","type":"boolean","default":false},"forbidden_paths":{"description":"Explicit path denylist. Default includes system-critical paths.\n\nFails closed: omitting the key keeps the built-in list rather than\nemptying it, so a partial `[autonomy]` section never removes the\ndenylist.","type":"array","default":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"items":{"type":"string"}},"level":{"description":"Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).","$ref":"#/$defs/AutonomyLevel","default":"full"},"max_cost_per_day_cents":{"description":"Maximum cost per day in cents per policy. Default: `500`.","type":"integer","format":"uint32","default":500,"minimum":0},"scopes":{"description":"Scope-based tool access control: per-user/channel/chat-type allow/deny rules.","$ref":"#/$defs/ScopeConfig","default":{"assign_owners":[],"default":"allow","rules":[]}},"workspace_only":{"description":"Restrict file writes and command paths to the workspace directory. Default: `true`.\n\nFails closed: a `[autonomy]` section that omits this key keeps the\nworkspace restriction on, so a partial section can never widen the\nfilesystem reach by accident.","type":"boolean","default":true}}},"AutonomyLevel":{"description":"How much autonomy the agent has","oneOf":[{"description":"Read-only: can observe but not act","type":"string","const":"readonly"},{"description":"Supervised: acts but requires approval for risky operations","type":"string","const":"supervised"},{"description":"Full: autonomous execution within policy bounds","type":"string","const":"full"}]},"BackendSelection":{"description":"Which decision backend runs: `auto` (the factory's order) or one kind.","type":"string"},"BrowserComputerUseConfig":{"description":"Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.","type":"object","properties":{"api_key":{"description":"Optional bearer token (retained only for config secret handling).","type":["string","null"],"default":null}}},"BrowserConfig":{"description":"Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.","type":"object","properties":{"allowed_domains":{"description":"Allowed domains for `web_fetch` (exact or subdomain match).","type":"array","default":[],"items":{"type":"string"}},"computer_use":{"description":"Computer-use sidecar config (retained only for `api_key` secret handling).","$ref":"#/$defs/BrowserComputerUseConfig","default":{"api_key":null}}}},"ChannelsConfig":{"description":"Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.","type":"object","properties":{"cli":{"description":"Enable the CLI interactive channel. Default: `true`.","type":"boolean","default":true},"dingtalk":{"description":"DingTalk channel configuration.","anyOf":[{"$ref":"#/$defs/DingTalkConfig"},{"type":"null"}]},"discord":{"description":"Discord bot channel configuration.","anyOf":[{"$ref":"#/$defs/DiscordConfig"},{"type":"null"}]},"email":{"description":"Email channel configuration.","anyOf":[{"$ref":"#/$defs/EmailConfig"},{"type":"null"}]},"imessage":{"description":"iMessage channel configuration (macOS only).","anyOf":[{"$ref":"#/$defs/IMessageConfig"},{"type":"null"}]},"irc":{"description":"IRC channel configuration.","anyOf":[{"$ref":"#/$defs/IrcConfig"},{"type":"null"}]},"lark":{"description":"Lark/Feishu channel configuration.","anyOf":[{"$ref":"#/$defs/LarkConfig"},{"type":"null"}]},"linq":{"description":"Linq Partner API channel configuration.","anyOf":[{"$ref":"#/$defs/LinqConfig"},{"type":"null"}]},"mattermost":{"description":"Mattermost bot channel configuration.","anyOf":[{"$ref":"#/$defs/MattermostConfig"},{"type":"null"}]},"nextcloud_talk":{"description":"Nextcloud Talk bot channel configuration.","anyOf":[{"$ref":"#/$defs/NextcloudTalkConfig"},{"type":"null"}]},"qq":{"description":"QQ Official Bot channel configuration.","anyOf":[{"$ref":"#/$defs/QQConfig"},{"type":"null"}]},"ramflux":{"description":"Local ramflux agent-host bridge.","anyOf":[{"$ref":"#/$defs/RamfluxConfig"},{"type":"null"}],"default":null},"signal":{"description":"Signal channel configuration.","anyOf":[{"$ref":"#/$defs/SignalConfig"},{"type":"null"}]},"slack":{"description":"Slack bot channel configuration.","anyOf":[{"$ref":"#/$defs/SlackConfig"},{"type":"null"}]},"telegram":{"description":"Telegram bot channel configuration.","anyOf":[{"$ref":"#/$defs/TelegramConfig"},{"type":"null"}]},"wacli":{"description":"wacli JSON-RPC daemon channel configuration.","anyOf":[{"$ref":"#/$defs/WacliConfig"},{"type":"null"}],"default":null},"webhook":{"description":"Webhook channel configuration.","anyOf":[{"$ref":"#/$defs/WebhookConfig"},{"type":"null"}]},"whatsapp":{"description":"WhatsApp channel configuration (Cloud API or Web mode).","anyOf":[{"$ref":"#/$defs/WhatsAppConfig"},{"type":"null"}]}}},"ChatConfig":{"description":"Interactive chat configuration (`[chat]`).","type":"object","properties":{"daemon":{"description":"How this chat process reaches the daemon it borrows channels from.","$ref":"#/$defs/ChatDaemonConfig","default":{"token":"","url":""}},"max_concurrent_visible_turns":{"description":"Maximum concurrent visible provider turns in the TUI Redux driver.","type":"integer","format":"uint","default":2,"minimum":0}}},"ChatDaemonConfig":{"description":"Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.","type":"object","properties":{"token":{"description":"Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.","type":"string","default":""},"url":{"description":"Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.","type":"string","default":""}}},"CircuitBreakerConfig":{"description":"The per-backend circuit breaker.","type":"object","properties":{"cooldown_secs":{"description":"Seconds the breaker stays open (1 to 3600).","type":"integer","format":"uint32","default":60,"minimum":0},"failure_threshold":{"description":"Consecutive failures before the breaker opens (1 to 100).","type":"integer","format":"uint32","default":5,"minimum":0}}},"ClassificationRule":{"description":"A single classification rule mapping message patterns to a model hint.","type":"object","properties":{"hint":{"description":"Must match a `[[model_routes]]` hint value.","type":"string"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"max_length":{"description":"Only match if message length <= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"min_length":{"description":"Only match if message length >= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"patterns":{"description":"Case-sensitive literal matches (for \"```\", \"fn \", etc.).","type":"array","default":[],"items":{"type":"string"}},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0}},"required":["hint"]},"CloudflareTunnelConfig":{"type":"object","properties":{"token":{"description":"Cloudflare Tunnel token (from Zero Trust dashboard)","type":"string"}},"required":["token"]},"ComplianceConfig":{"type":"object","properties":{"eu_ai_act":{"$ref":"#/$defs/EuAiActComplianceConfig","default":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null}},"interaction_notice":{"$ref":"#/$defs/InteractionNoticeConfig","default":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}}},"ComposioConfig":{"description":"Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.","type":"object","properties":{"api_key":{"description":"Composio API key (stored encrypted when secrets.encrypt = true)","type":["string","null"],"default":null},"entity_id":{"description":"Default entity ID for multi-user setups","type":"string","default":"default"}}},"CostConfig":{"description":"Cost tracking and budget enforcement configuration (`[cost]` section).","type":"object","properties":{"allow_override":{"description":"Allow requests to exceed budget with --override flag (default: false)","type":"boolean","default":false},"daily_limit_usd":{"description":"Daily spending limit in USD (default: 10.00)","type":"number","format":"double","default":10.0},"monthly_limit_usd":{"description":"Monthly spending limit in USD (default: 100.00)","type":"number","format":"double","default":100.0},"prices":{"description":"Per-model pricing (USD per 1M tokens)","type":"object","additionalProperties":{"$ref":"#/$defs/ModelPricing"},"default":{}},"warn_at_percent":{"description":"Warn when spending reaches this percentage of limit (default: 80)","type":"integer","format":"uint8","default":80,"maximum":255,"minimum":0}}},"CredentialRefSetting":{"description":"Which credential a decision backend uses. A reference, never a secret.","type":"string"},"CronConfig":{"description":"Cron job configuration (`[cron]` section).","type":"object","properties":{"max_run_history":{"description":"Maximum number of historical cron run records to retain. Default: `50`.","type":"integer","format":"uint32","default":50,"minimum":0}}},"CustomTunnelConfig":{"type":"object","properties":{"health_url":{"description":"Optional URL to check tunnel health","type":["string","null"]},"start_command":{"description":"Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"","type":"string"},"url_pattern":{"description":"Optional regex to extract public URL from command stdout","type":["string","null"]}},"required":["start_command"]},"DecisionBackendConfig":{"description":"The decision backend (`[decision_engine.backend]`).","type":"object","properties":{"circuit_breaker":{"description":"The circuit breaker.","$ref":"#/$defs/CircuitBreakerConfig","default":{"cooldown_secs":60,"failure_threshold":5}},"credential_ref":{"description":"The credential reference: `\"\"`, `\"none\"` or `cred-`.","$ref":"#/$defs/CredentialRefSetting","default":""},"endpoint":{"description":"The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.","type":"string","default":""},"kind":{"description":"`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).","$ref":"#/$defs/BackendSelection","default":"auto"},"max_request_bytes":{"description":"Largest request body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":65536,"minimum":0},"max_response_bytes":{"description":"Largest response body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":262144,"minimum":0},"model":{"description":"The model the endpoint serves; one exact version for a hosted\nservice.","type":"string","default":""},"pinned_snapshot":{"description":"The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.","type":"string"},"remote_enabled":{"description":"Whether decision state may leave this machine. Default `false`.","type":"boolean","default":false},"timeout_ms":{"description":"Transport timeout (10 ms up to the extra latency budget).","type":"integer","format":"uint32","default":250,"minimum":0}}},"DecisionEngineConfig":{"type":"object","properties":{"backend":{"anyOf":[{"$ref":"#/$defs/DecisionBackendConfig"},{"type":"null"}]},"candidates":{"type":"integer","format":"uint32","default":5,"minimum":0},"enabled":{"type":"boolean","default":false},"mode":{"$ref":"#/$defs/DecisionMode","default":"pre"},"observe_queue":{"type":"integer","format":"uint32","default":64,"minimum":0},"prompt_budget_tokens":{"type":"integer","format":"uint32","default":300,"minimum":0},"telemetry_cap":{"type":"integer","format":"uint32","default":1000,"minimum":0},"timeout_ms":{"type":"integer","format":"uint32","default":1500,"minimum":0},"latency_budget_ms":{"description":"The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.","type":"integer","format":"uint64","default":500,"minimum":0},"token_ratio_limit":{"description":"Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).","type":"number","format":"float","default":0.3499999940395355},"max_candidates":{"description":"The most candidates a turn considers (1 to 32).","type":"integer","format":"uint8","default":12,"maximum":255,"minimum":0}}},"DecisionMode":{"type":"string","enum":["pre","post","both"]},"DeclarationOfConformityConfig":{"type":"object","properties":{"applicable_union_law":{"type":"array","default":[],"items":{"type":"string"}},"artifact_path":{"type":["string","null"],"default":null},"artifact_version":{"type":["string","null"],"default":null},"conformity_assessment_procedure":{"type":["string","null"],"default":null},"conformity_statement":{"type":["string","null"],"default":null},"harmonised_standards":{"type":"array","default":[],"items":{"type":"string"}},"issue_date":{"type":["string","null"],"default":null},"issue_place":{"type":["string","null"],"default":null},"notified_body_certificate":{"type":["string","null"],"default":null},"notified_body_identification_number":{"type":["string","null"],"default":null},"notified_body_name":{"type":["string","null"],"default":null},"personal_data_compliance_statement":{"type":["string","null"],"default":null},"processes_personal_data":{"type":"boolean","default":false},"provider_address":{"type":["string","null"],"default":null},"provider_name":{"type":["string","null"],"default":null},"signer_function":{"type":["string","null"],"default":null},"signer_name":{"type":["string","null"],"default":null},"signer_on_behalf_of":{"type":["string","null"],"default":null},"sole_responsibility_statement":{"type":["string","null"],"default":null},"standards_not_applicable_reason":{"type":["string","null"],"default":null},"system_name":{"type":["string","null"],"default":null},"system_reference":{"type":["string","null"],"default":null},"system_type":{"type":["string","null"],"default":null}}},"DelegateAgentConfig":{"description":"Configuration for a delegate sub-agent used by the `delegate` tool.","type":"object","properties":{"agentic":{"description":"Enable agentic sub-agent mode (multi-turn tool-call loop).","type":"boolean","default":false},"allowed_tools":{"description":"Allowlist of tool names available to the sub-agent in agentic mode.","type":"array","default":[],"items":{"type":"string"}},"api_key":{"description":"Optional API key override","type":["string","null"],"default":null},"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"autonomy":{"description":"The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.","anyOf":[{"$ref":"#/$defs/AutonomyLevel"},{"type":"null"}]},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"enabled":{"description":"Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.","type":"boolean","default":true},"identity_dir":{"description":"Optional identity files directory relative to workspace root.","type":["string","null"],"default":null},"limits":{"$ref":"#/$defs/AgentLimits","default":{"max_concurrent_turns":null,"max_cost_per_day_cents":null}},"max_depth":{"description":"Max recursion depth for nested delegation","type":"integer","format":"uint32","default":8,"minimum":0},"memory_scope":{"description":"Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".","type":["string","null"],"default":null},"model":{"description":"Model name","type":"string"},"provider":{"description":"Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")","type":"string"},"spawn_enabled":{"description":"Whether this agent is allowed to be targeted by sessions_spawn (default: true).","type":["boolean","null"],"default":null},"system_prompt":{"description":"Optional system prompt for the sub-agent","type":["string","null"],"default":null},"temperature":{"description":"Temperature override","type":["number","null"],"format":"double","default":null},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}},"required":["provider","model"]},"DingTalkConfig":{"description":"DingTalk configuration for Stream Mode messaging","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"client_id":{"description":"Client ID (AppKey) from DingTalk developer console","type":"string"},"client_secret":{"description":"Client Secret (AppSecret) from DingTalk developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["client_id","client_secret"]},"DiscordConfig":{"description":"Discord bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Discord user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Discord bot token (from Discord Developer Portal).","type":"string"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"guild_id":{"description":"Optional guild (server) ID to restrict the bot to a single guild.","type":["string","null"]},"listen_to_bots":{"description":"When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.","type":"boolean","default":false}},"required":["bot_token"]},"DmPolicy":{"description":"Policy for direct-message handling.","oneOf":[{"description":"Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).","type":"string","const":"pairing"},{"description":"Accept only senders listed in `allowed_from`.","type":"string","const":"allowlist"},{"description":"Accept any direct sender.","type":"string","const":"open"},{"description":"Ignore direct messages.","type":"string","const":"disabled"}]},"DockerRuntimeConfig":{"description":"Docker runtime configuration (`[runtime.docker]` section).","type":"object","properties":{"allowed_workspace_roots":{"description":"Optional workspace root allowlist for Docker mount validation.","type":"array","default":[],"items":{"type":"string"}},"cpu_limit":{"description":"Optional CPU limit (`None` = no explicit limit).","type":["number","null"],"format":"double","default":1.0},"image":{"description":"Runtime image used to execute shell commands.","type":"string","default":"alpine:3.20"},"memory_limit_mb":{"description":"Optional memory limit in MB (`None` = no explicit limit).","type":["integer","null"],"format":"uint64","default":512,"minimum":0},"mount_workspace":{"description":"Mount configured workspace into `/workspace`.","type":"boolean","default":true},"network":{"description":"Docker network mode (`none`, `bridge`, etc.).","type":"string","default":"none"},"read_only_rootfs":{"description":"Mount root filesystem as read-only.","type":"boolean","default":true}}},"EmailConfig":{"description":"Email channel configuration","type":"object","properties":{"allowed_senders":{"description":"Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)","type":"array","default":[],"items":{"type":"string"}},"from_address":{"description":"From address for outgoing emails","type":"string"},"idle_timeout_secs":{"description":"IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes","type":"integer","format":"uint64","default":1740,"minimum":0},"imap_folder":{"description":"IMAP folder to poll (default: INBOX)","type":"string","default":"INBOX"},"imap_host":{"description":"IMAP server hostname","type":"string"},"imap_port":{"description":"IMAP server port (default: 993 for TLS)","type":"integer","format":"uint16","default":993,"maximum":65535,"minimum":0},"password":{"description":"Email password for authentication","type":"string"},"smtp_host":{"description":"SMTP server hostname","type":"string"},"smtp_port":{"description":"SMTP server port (default: 465 for TLS)","type":"integer","format":"uint16","default":465,"maximum":65535,"minimum":0},"smtp_tls":{"description":"Use TLS for SMTP (default: true)","type":"boolean","default":true},"username":{"description":"Email username for authentication","type":"string"}},"required":["imap_host","smtp_host","username","password","from_address"]},"EmbeddingRouteConfig":{"description":"Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"dimensions":{"description":"Optional embedding dimension override for this route","type":["integer","null"],"format":"uint","default":null,"minimum":0},"hint":{"description":"Route hint name (e.g. \"semantic\", \"archive\", \"faq\")","type":"string"},"model":{"description":"Embedding model to use with that provider","type":"string"},"provider":{"description":"Embedding provider (`none`, `openai`, or `custom:`)","type":"string"}},"required":["hint","provider","model"]},"EuAiActClassificationConfig":{"type":"object","properties":{"assessed_at":{"type":["string","null"],"default":null},"owner":{"type":["string","null"],"default":null},"status":{"$ref":"#/$defs/EuAiActRiskClassification","default":"unclassified"}}},"EuAiActComplianceConfig":{"type":"object","properties":{"classification":{"$ref":"#/$defs/EuAiActClassificationConfig","default":{"assessed_at":null,"owner":null,"status":"unclassified"}},"declaration":{"$ref":"#/$defs/DeclarationOfConformityConfig","default":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null}},"incident_store_path":{"type":["string","null"],"default":null}}},"EuAiActRiskClassification":{"type":"string","enum":["unclassified","high_risk","not_high_risk"]},"FitnessConfig":{"description":"Calendar schedule, evidence thresholds, and retention for fitness v2.","type":"object","properties":{"auto_run":{"description":"Run the daily fitness worker in daemon mode.","type":"boolean","default":true},"max_backfill_days":{"description":"Maximum number of closed days recovered after downtime.","type":"integer","format":"uint32","default":7,"minimum":0},"min_coverage":{"description":"Minimum available metric weight required to publish a final score.","type":"number","format":"double","default":0.6},"min_samples":{"description":"Minimum samples required before an evidence-derived subscore is usable.","type":"integer","format":"uint","default":5,"minimum":0},"retention_days":{"description":"Number of daily JSON reports retained on disk.","type":"integer","format":"uint32","default":180,"minimum":0},"run_at":{"description":"Local wall-clock time (`HH:MM`) at which the previous day is scored.","type":"string","default":"00:10"},"timezone":{"description":"IANA timezone used to define closed calendar days.","type":"string","default":"UTC"}}},"GatewayConfig":{"description":"Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.","type":"object","properties":{"allow_public_bind":{"description":"Allow binding to non-localhost without a tunnel (default: false)","type":"boolean","default":false},"api_rate_limit_per_minute":{"description":"Max `/api/*` requests per minute per authenticated token.","type":"integer","format":"uint32","default":60,"minimum":0},"channel_webhook_dedup_ttl_secs":{"description":"How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.","type":"integer","format":"uint64","default":86400,"minimum":0},"host":{"description":"Gateway host (default: 127.0.0.1)","type":"string","default":"127.0.0.1"},"idempotency_max_keys":{"description":"Maximum distinct idempotency keys retained in memory.","type":"integer","format":"uint","default":10000,"minimum":0},"idempotency_ttl_secs":{"description":"TTL for webhook idempotency keys.","type":"integer","format":"uint64","default":300,"minimum":0},"pair_rate_limit_per_minute":{"description":"Max `/pair` requests per minute per client key.","type":"integer","format":"uint32","default":10,"minimum":0},"paired_tokens":{"description":"Paired bearer tokens (managed automatically, not user-edited)","type":"array","default":[],"items":{"type":"string"}},"port":{"description":"Gateway port (default: 16830)","type":"integer","format":"uint16","default":16830,"maximum":65535,"minimum":0},"rate_limit_max_keys":{"description":"Maximum distinct client keys tracked by gateway rate limiter maps.","type":"integer","format":"uint","default":10000,"minimum":0},"require_pairing":{"description":"Require pairing before accepting requests (default: true)","type":"boolean","default":true},"targeted_agents":{"description":"Rollout switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). While false, any otherwise-valid\nnamed target answers 409 `agent_disabled` and never runs as Main.","type":"boolean","default":false},"trust_forwarded_headers":{"description":"Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.","type":"boolean","default":false},"webhook_rate_limit_per_minute":{"description":"Max `/webhook` requests per minute per client key.","type":"integer","format":"uint32","default":60,"minimum":0}}},"GroupPolicy":{"description":"Policy for group-message handling.","oneOf":[{"description":"Accept only groups listed in `group_allow_from`.","type":"string","const":"allowlist"},{"description":"Accept any group.","type":"string","const":"open"},{"description":"Ignore group messages.","type":"string","const":"disabled"}]},"GroupReplyMode":{"description":"How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.","oneOf":[{"description":"Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).","type":"string","const":"off"},{"description":"Reply only when the bot is @-mentioned (legacy `mention_only = true`).","type":"string","const":"mention-only"},{"description":"Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).","type":"string","const":"smart"}]},"HeartbeatConfig":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]` section).","type":"object","properties":{"active_hours":{"description":"Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.","type":"array","default":[8,23],"items":{"type":"integer","format":"uint8","maximum":255,"minimum":0}},"interval_minutes":{"description":"Interval in minutes between heartbeat pings. Default: `30`.","type":"integer","format":"uint32","default":30,"minimum":0},"prompt":{"description":"Prompt used by heartbeat worker when dispatching tasks.","type":"string","default":"Check HEARTBEAT.md and follow instructions."}}},"HttpRequestConfig":{"description":"HTTP request tool configuration (`[http_request]` section).","type":"object","properties":{"max_response_size":{"description":"Maximum response size in bytes (default: 1MB)","type":"integer","format":"uint","default":1000000,"minimum":0},"timeout_secs":{"description":"Request timeout in seconds (default: 30)","type":"integer","format":"uint64","default":30,"minimum":0}}},"IMessageConfig":{"description":"iMessage channel configuration (macOS only).","type":"object","properties":{"allowed_contacts":{"description":"Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.","type":"array","items":{"type":"string"}},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["allowed_contacts"]},"IdentityBindingConfig":{"description":"Startup identity binding entry (`[[identity_bindings]]`).","type":"object","properties":{"channel":{"type":"string"},"channel_account":{"type":"string"},"display_name":{"type":["string","null"],"default":null},"user_id":{"type":"string"}},"required":["user_id","channel","channel_account"]},"IdentityConfig":{"description":"Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.","type":"object","properties":{"aieos_inline":{"description":"Inline AIEOS JSON (alternative to file path)","type":["string","null"],"default":null},"aieos_path":{"description":"Path to AIEOS JSON file (relative to workspace)","type":["string","null"],"default":null},"format":{"description":"Identity format: \"openclaw\" (default) or \"aieos\"","type":"string","default":"openclaw"}}},"InteractionNoticeApplicability":{"type":"string","enum":["required","not_applicable"]},"InteractionNoticeConfig":{"type":"object","properties":{"applicability":{"$ref":"#/$defs/InteractionNoticeApplicability","default":"required"},"exception_owner":{"type":["string","null"],"default":null},"exception_reviewed_at":{"type":["string","null"],"default":null},"text":{"type":"string","default":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers."},"version":{"type":"string","default":"1"}}},"IrcConfig":{"description":"IRC channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed nicknames (case-insensitive) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"channels":{"description":"Channels to join on connect","type":"array","default":[],"items":{"type":"string"}},"mention_only":{"description":"When true, only process channel/group messages that mention the bot.","type":"boolean","default":false},"nickname":{"description":"Bot nickname","type":"string"},"nickserv_password":{"description":"NickServ IDENTIFY password","type":["string","null"]},"port":{"description":"IRC server port (default: 6697 for TLS)","type":"integer","format":"uint16","default":6697,"maximum":65535,"minimum":0},"sasl_password":{"description":"SASL PLAIN password (IRCv3)","type":["string","null"]},"server":{"description":"IRC server hostname","type":"string"},"server_password":{"description":"Server password (for bouncers like ZNC)","type":["string","null"]},"username":{"description":"Username (defaults to nickname if not set)","type":["string","null"]},"verify_tls":{"description":"Verify TLS certificate (default: true)","type":["boolean","null"]}},"required":["server","nickname"]},"LarkConfig":{"description":"Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from Lark/Feishu developer console","type":"string"},"app_secret":{"description":"App Secret from Lark/Feishu developer console","type":"string"},"encrypt_key":{"description":"Encrypt key for webhook message decryption (optional)","type":["string","null"],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"port":{"description":"HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"receive_mode":{"description":"Event receive mode: \"websocket\" (default) or \"webhook\"","$ref":"#/$defs/LarkReceiveMode","default":"websocket"},"use_feishu":{"description":"Whether to use the Feishu (Chinese) endpoint instead of Lark (International)","type":"boolean","default":false},"verification_token":{"description":"Verification token for webhook validation (optional)","type":["string","null"],"default":null}},"required":["app_id","app_secret"]},"LarkReceiveMode":{"description":"How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.","type":"string","enum":["websocket","webhook"]},"LinqConfig":{"type":"object","properties":{"allowed_senders":{"description":"Allowed sender handles (phone numbers) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"api_token":{"description":"Linq Partner API token (Bearer auth)","type":"string"},"from_phone":{"description":"Phone number to send from (E.164 format)","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"signing_secret":{"description":"Webhook signing secret for signature verification","type":["string","null"],"default":null}},"required":["api_token","from_phone"]},"MattermostConfig":{"description":"Mattermost bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Mattermost user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Mattermost bot access token.","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.","type":["boolean","null"],"default":null},"thread_replies":{"description":"When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.","type":["boolean","null"],"default":null},"url":{"description":"Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).","type":"string"}},"required":["url","bot_token"]},"McpConfig":{"type":"object","properties":{"servers":{"description":"Named MCP server definitions","type":"object","additionalProperties":{"$ref":"#/$defs/McpServerConfig"},"default":{}},"workspace_servers":{"description":"Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.","$ref":"#/$defs/WorkspaceMcpServers"}}},"McpServerConfig":{"type":"object","properties":{"allow_tools":{"description":"Optional allow-list of exposed tools (empty = all)","type":"array","default":[],"items":{"type":"string"}},"args":{"description":"Command args for stdio mode","type":"array","default":[],"items":{"type":"string"}},"command":{"description":"Command for stdio mode","type":["string","null"],"default":null},"deny_tools":{"description":"Optional deny-list of exposed tools","type":"array","default":[],"items":{"type":"string"}},"env":{"description":"Environment variables for stdio mode","type":"object","additionalProperties":{"type":"string"},"default":{}},"request_timeout_ms":{"description":"Request timeout in milliseconds","type":"integer","format":"uint64","default":30000,"minimum":0},"startup_timeout_ms":{"description":"Startup timeout in milliseconds","type":"integer","format":"uint64","default":10000,"minimum":0},"tool_name_prefix":{"description":"Prefix used in tool naming and routing","type":"string","default":"mcp"},"transport":{"description":"Transport type: stdio or http","$ref":"#/$defs/McpTransport","default":"stdio"},"url":{"description":"URL for HTTP mode (streamable HTTP endpoint)","type":["string","null"],"default":null},"working_dir":{"description":"Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).","type":["string","null"]}}},"McpServerRuntimeConfig":{"type":"object","properties":{"allowed_origins":{"description":"Allowed browser origins for future streamable HTTP clients.","type":"array","default":["claude.ai","openai.com","localhost"],"items":{"type":"string"}},"bind":{"description":"Advertised bind address. The gateway may still be started with a CLI port override.","type":"string","default":"127.0.0.1:16831"},"exposed_tools":{"description":"Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.","type":"array","default":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"items":{"type":"string"}},"jwt_algorithms":{"description":"Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.","type":"array","default":["RS256"],"items":{"type":"string"}},"jwt_audience":{"description":"Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.","type":["string","null"],"default":null},"jwt_issuer":{"description":"Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.","type":["string","null"],"default":null},"jwt_jwks":{"description":"Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.","type":["string","null"],"default":null},"jwt_jwks_cache_ttl_secs":{"description":"Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.","type":"integer","format":"uint64","default":300,"minimum":0},"jwt_jwks_uri":{"description":"Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.","type":["string","null"],"default":null},"jwt_public_key_pem":{"description":"PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.","type":["string","null"],"default":null},"rate_limit_rps":{"description":"Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.","type":"integer","format":"uint32","default":10,"minimum":0},"require_auth":{"description":"Require an authenticated external identity for mutating calls.","type":"boolean","default":true}}},"McpTransport":{"type":"string","enum":["stdio","http"]},"MediaConfig":{"description":"Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.","type":"object","properties":{"audio_model":{"description":"Audio model name (Ollama model or OpenAI model). Default: \"whisper\".","type":"string","default":"whisper"},"audio_ollama_url":{"description":"Ollama base URL for audio transcription. Default: \"http://localhost:11434\".","type":"string","default":"http://localhost:11434"},"audio_provider":{"description":"Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".","type":"string","default":"none"},"max_audio_size_mb":{"description":"Maximum audio attachment size in MiB. Default: 20.","type":"integer","format":"uint","default":20,"minimum":0},"max_video_size_mb":{"description":"Maximum video attachment size in MiB. Default: 50.","type":"integer","format":"uint","default":50,"minimum":0},"video_max_frames":{"description":"Maximum video frames to extract per video. Default: 4.","type":"integer","format":"uint","default":4,"minimum":0},"video_provider":{"description":"Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".","type":"string","default":"none"}}},"MemoryConfig":{"description":"Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.","type":"object","properties":{"acl_enabled":{"description":"Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.","type":"boolean","default":false},"archive_after_days":{"description":"Archive daily/session files older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"auto_hydrate":{"description":"Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing","type":"boolean","default":true},"auto_save":{"description":"Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.","type":"boolean","default":true},"backend":{"description":"\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).","type":"string","default":"sqlite"},"conversation_retention_days":{"description":"For sqlite backend: prune conversation rows older than this many days","type":"integer","format":"uint32","default":3,"minimum":0},"daily_retention_days":{"description":"For sqlite backend: prune daily rows older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"embedding_cache_size":{"description":"Max embedding cache entries before LRU eviction","type":"integer","format":"uint","default":10000,"minimum":0},"embedding_dimensions":{"description":"Embedding vector dimensions","type":"integer","format":"uint","default":384,"minimum":0},"embedding_model":{"description":"Embedding model name (e.g. \"text-embedding-3-small\")","type":"string","default":"prx-local-hash-v1"},"embedding_provider":{"description":"Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"","type":"string","default":"local"},"events":{"description":"Raw/quasi-raw message event recording controls (`[memory.events]`).","$ref":"#/$defs/MemoryEventsConfig","default":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true}},"keyword_weight":{"description":"Weight for keyword BM25 in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.3},"legacy_conversation_turns_visible":{"description":"Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.","type":"boolean","default":true},"lucid_budget":{"description":"Token budget for lucid (replaces OPENPRX_LUCID_BUDGET)","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"lucid_cmd":{"description":"Path to lucid binary (replaces OPENPRX_LUCID_CMD)","type":["string","null"],"default":null},"lucid_failure_cooldown_ms":{"description":"Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)","type":"integer","format":"uint64","default":60000,"minimum":0},"lucid_local_hit_threshold":{"description":"Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)","type":"integer","format":"uint","default":3,"minimum":0},"lucid_recall_timeout_ms":{"description":"Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)","type":"integer","format":"uint64","default":5000,"minimum":0},"lucid_store_timeout_ms":{"description":"Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)","type":"integer","format":"uint64","default":3000,"minimum":0},"min_relevance_score":{"description":"Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4","type":"number","format":"double","default":0.4},"purge_after_days":{"description":"Purge archived files older than this many days","type":"integer","format":"uint32","default":30,"minimum":0},"semantic":{"description":"Semantic memory promotion controls (`[memory.semantic]`).","$ref":"#/$defs/MemorySemanticConfig","default":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30}},"sqlite_open_timeout_secs":{"description":"For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"sqlite_read_pool_size":{"description":"For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"vector_candidate_cap":{"description":"How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.","type":"integer","format":"uint","default":2000,"minimum":0},"vector_weight":{"description":"Weight for vector similarity in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.7}}},"MemoryEventsConfig":{"description":"Raw message event recording configuration (`[memory.events]`).","type":"object","properties":{"record_assistant_messages":{"description":"Record assistant replies.","type":"boolean","default":true},"record_tool_events":{"description":"Record tool/event payloads by default.","type":"boolean","default":false},"record_user_messages":{"description":"Record inbound/user messages.","type":"boolean","default":true}}},"MemorySemanticConfig":{"description":"Semantic memory promotion configuration (`[memory.semantic]`).","type":"object","properties":{"auto_promote_assistant_messages":{"description":"Auto-promote eligible assistant messages. Disabled by default to reduce noise.","type":"boolean","default":false},"auto_promote_user_messages":{"description":"Auto-promote eligible user messages into long-term semantic memories.","type":"boolean","default":true},"min_chars":{"description":"Minimum content length for semantic auto-promotion.","type":"integer","format":"uint","default":30,"minimum":0}}},"MemoryWebhookConfig":{"type":"object","properties":{"bind":{"description":"Socket address for the receiver (e.g. \"0.0.0.0:16899\").","type":"string","default":"0.0.0.0:16899"},"signing_secret":{"description":"Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.","type":["string","null"],"default":null},"token":{"description":"Required bearer token for incoming webhook events.","type":["string","null"],"default":null}}},"ModelOperationSetting":{"description":"The operations a `[[providers.models]]` entry may list.","type":"string","enum":["chat","embedding","decision_endpoint","rerank","image_generation","audio_generation","video_generation"]},"ModelPricing":{"description":"Per-model pricing entry (USD per 1M tokens).","type":"object","properties":{"cache_read":{"description":"Cache read input price per 1M tokens.","type":"number","format":"double","default":0.0},"cache_write":{"description":"Cache write/creation input price per 1M tokens.","type":"number","format":"double","default":0.0},"input":{"description":"Input price per 1M tokens","type":"number","format":"double","default":0.0},"output":{"description":"Output price per 1M tokens","type":"number","format":"double","default":0.0}}},"ModelRouteConfig":{"description":"Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"hint":{"description":"Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")","type":"string"},"level":{"type":["string","null"]},"model":{"description":"Model to use with that provider","type":"string"},"provider":{"description":"Provider to route to (must match a known provider name)","type":"string"},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true,"required":["hint","provider","model"]},"ModelSettings":{"description":"A model level plus explicit parameter overrides in `[model_settings.\"\"]`.","type":"object","properties":{"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"level":{"type":["string","null"]},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true},"MultimodalConfig":{"description":"Multimodal (image) handling configuration (`[multimodal]` section).","type":"object","properties":{"allow_remote_fetch":{"description":"Allow fetching remote image URLs (http/https). Disabled by default.","type":"boolean","default":false},"max_image_size_mb":{"description":"Maximum image payload size in MiB before base64 encoding.","type":"integer","format":"uint","default":5,"minimum":0},"max_images":{"description":"Maximum number of image attachments accepted per request.","type":"integer","format":"uint","default":4,"minimum":0}}},"NextcloudTalkConfig":{"description":"Nextcloud Talk bot configuration (webhook receive + OCS send API).","type":"object","properties":{"allowed_users":{"description":"Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Bot app token used for OCS API bearer auth.","type":"string"},"base_url":{"description":"Nextcloud base URL (e.g. \"https://cloud.example.com\").","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"webhook_secret":{"description":"Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).","type":["string","null"],"default":null}},"required":["base_url","app_token"]},"NgrokTunnelConfig":{"type":"object","properties":{"auth_token":{"description":"ngrok auth token","type":"string"},"domain":{"description":"Optional custom domain","type":["string","null"]}},"required":["auth_token"]},"NodeServerConfig":{"description":"Node daemon runtime config used by `prx-node`.","type":"object","properties":{"allowed_commands":{"description":"Command allowlist matched on first token.\n\nIn restricted mode this list is required unless explicitly set to `[\"*\"]`.","type":"array","default":["echo"],"items":{"type":"string"}},"bearer_token":{"description":"Required bearer token for /rpc.","type":"string","default":""},"blocked_commands":{"description":"Command denylist matched on first token. Always enforced.","type":"array","default":[],"items":{"type":"string"}},"exec_timeout_ms":{"description":"Default command timeout in milliseconds.","type":"integer","format":"uint64","default":15000,"minimum":0},"hmac_secret":{"description":"Optional HMAC signing secret.","type":["string","null"],"default":null},"listen_addr":{"description":"Listen address for node daemon.","type":"string","default":"127.0.0.1:8787"},"max_concurrent_tasks":{"description":"Maximum number of concurrent async command tasks.","type":"integer","format":"uint","default":8,"minimum":0},"max_output_bytes":{"description":"Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.","type":"integer","format":"uint","default":1048576,"minimum":0},"sandbox_root":{"description":"Sandbox root directory for read/write/cwd constraints.","type":"string","default":"."},"task_result_ttl_ms":{"description":"TTL for completed task results in milliseconds.","type":"integer","format":"uint64","default":3600000,"minimum":0},"tls_cert":{"description":"TLS certificate path (PEM).","type":["string","null"],"default":null},"tls_key":{"description":"TLS private key path (PEM).","type":["string","null"],"default":null},"tls_required":{"description":"Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.","type":"boolean","default":true}}},"NodesConfig":{"description":"Remote node proxy configuration for core-side RPC calls and node daemon defaults.","type":"object","properties":{"nodes":{"description":"Configured remote nodes.","type":"array","default":[],"items":{"$ref":"#/$defs/RemoteNodeConfig"}},"request_timeout_ms":{"description":"Default request timeout for node RPC calls.","type":"integer","format":"uint64","default":15000,"minimum":0},"retry_max":{"description":"Default max retries for node RPC calls.","type":"integer","format":"uint8","default":2,"maximum":255,"minimum":0},"server":{"description":"Embedded node server defaults used by `prx-node`.","$ref":"#/$defs/NodeServerConfig","default":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}}},"ObservabilityConfig":{"description":"Observability backend configuration (`[observability]` section).","type":"object","properties":{"backend":{"description":"\"none\" | \"log\" | \"prometheus\" | \"otel\"","type":"string","default":"none"},"otel_endpoint":{"description":"OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".","type":["string","null"],"default":null},"otel_service_name":{"description":"Service name reported to the OTel collector. Defaults to \"prx\".","type":["string","null"],"default":null}}},"OllamaProviderConfig":{"description":"Ollama-specific request options (`[providers.ollama]`).","type":"object","properties":{"num_ctx":{"description":"Explicit context window sent as Ollama `options.num_ctx`.","type":["integer","null"],"format":"uint","default":null,"minimum":0}}},"OsPagingConfig":{"description":"Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.","type":"object","properties":{"eviction_threshold":{"description":"Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.","type":"number","format":"double","default":0.7},"keep_recent_messages":{"description":"Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).","type":"integer","format":"uint","default":12,"minimum":0},"max_recalled_pages":{"description":"Maximum number of evicted pages (document chunks) recalled per turn.","type":"integer","format":"uint","default":10,"minimum":0},"proactive_retrieval":{"description":"Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.","type":"boolean","default":true},"retrieval_injection_role":{"description":"Role under which recalled pages are injected.","$ref":"#/$defs/RetrievalInjectionRole","default":"system"}}},"PluginsConfig":{"description":"WASM plugin runtime configuration.","type":"object","properties":{"enabled":{"description":"Load WASM plugins from `/plugins`. Default: `false`.","type":"boolean","default":false}},"additionalProperties":false},"ProviderModelConfig":{"description":"One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.","type":"object","properties":{"context_window":{"description":"The model's context window in tokens.","type":["integer","null"],"format":"uint32","minimum":0},"model":{"description":"The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.","type":["string","null"]},"native_tools":{"description":"Whether the model accepts native tool calls.","type":["boolean","null"]},"operations":{"description":"The complete list of operations the model executes; every operation not\nlisted is unsupported.","type":["array","null"],"items":{"$ref":"#/$defs/ModelOperationSetting"}},"provider":{"description":"The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.","type":"string"},"streaming":{"description":"Whether the model streams responses.","type":["boolean","null"]},"structured_output":{"description":"Whether the model honours a JSON-schema response format.","type":["boolean","null"]},"tool_call_dialect":{"description":"The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema_dialect":{"description":"The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]},"vision_input":{"description":"Whether the model accepts image input.","type":["boolean","null"]}},"required":["provider"]},"ProviderToolDialectConfig":{"description":"One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.","type":"object","properties":{"model":{"description":"The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.","type":["string","null"]},"provider":{"description":"The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.","type":"string"},"tool_call":{"description":"The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema":{"description":"The tool-schema dialect the endpoint accepts.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]}},"required":["provider"]},"ProvidersConfig":{"description":"Provider-specific runtime configuration (`[providers]`).","type":"object","properties":{"models":{"description":"Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.","type":"array","items":{"$ref":"#/$defs/ProviderModelConfig"}},"ollama":{"description":"Ollama-specific request options (`[providers.ollama]`).","$ref":"#/$defs/OllamaProviderConfig","default":{"num_ctx":null}},"tool_dialects":{"description":"Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).","type":"array","items":{"$ref":"#/$defs/ProviderToolDialectConfig"}}}},"ProxyConfig":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).","type":"object","properties":{"all_proxy":{"description":"Fallback proxy URL for all schemes.","type":["string","null"],"default":null},"http_proxy":{"description":"Proxy URL for HTTP requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"https_proxy":{"description":"Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"no_proxy":{"description":"No-proxy bypass list. Same format as NO_PROXY.","type":"array","default":[],"items":{"type":"string"}},"scope":{"description":"Proxy application scope.","$ref":"#/$defs/ProxyScope","default":"prx"},"services":{"description":"Service selectors used when scope = \"services\".","type":"array","default":[],"items":{"type":"string"}}}},"ProxyScope":{"description":"Proxy application scope — determines which outbound traffic uses the proxy.","oneOf":[{"description":"Use system environment proxy variables only.","type":"string","const":"environment"},{"description":"Apply proxy to all OpenPRX-managed HTTP traffic (default).","type":"string","const":"prx"},{"description":"Apply proxy only to explicitly listed service selectors.","type":"string","const":"services"}]},"QQConfig":{"description":"QQ Official Bot configuration (Tencent QQ Bot SDK)","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs. Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from QQ Bot developer console","type":"string"},"app_secret":{"description":"App Secret from QQ Bot developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["app_id","app_secret"]},"QueryClassificationConfig":{"description":"Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.","type":"object","properties":{"rules":{"description":"Classification rules evaluated in priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/ClassificationRule"}}}},"RamfluxAccountConfig":{"description":"Persona for one ramflux AI account. Missing fields fall back to the global agent.","type":"object","properties":{"cross_conversation_retrieval":{"description":"Cross-conversation memory retrieval. Off unless the owner sets it.","type":"boolean","default":false},"model":{"type":["string","null"],"default":null},"provider":{"type":["string","null"],"default":null},"scope_profile":{"type":["string","null"],"default":null},"system_prompt_file":{"description":"Path to a system-prompt file. Relative paths are resolved from the workspace.","type":["string","null"],"default":null}},"additionalProperties":false},"RamfluxAttachmentFetch":{"description":"Per-turn caps for `attachment.fetch`.","type":"object","properties":{"max_bytes":{"type":"integer","format":"uint64","default":5242880,"minimum":0},"max_per_turn":{"type":"integer","format":"uint8","default":4,"maximum":255,"minimum":0}},"additionalProperties":false},"RamfluxAuthorizationMode":{"description":"How prx combines its own setting with `bridge.hello.authorization`.","oneOf":[{"description":"Use the agent-host value. Until hello arrives, the effective mode is supervised.","type":"string","const":"follow_rf"},{"description":"Always supervised, even when the agent-host declares full.","type":"string","const":"supervised"},{"description":"Full only when the agent-host also declares full. Config alone never yields full.","type":"string","const":"full"}]},"RamfluxConfig":{"description":"Local ramflux agent-host bridge (`[channels_config.ramflux]`).","type":"object","properties":{"accounts":{"type":"object","additionalProperties":{"$ref":"#/$defs/RamfluxAccountConfig"},"default":{}},"allowed_block_types":{"type":"array","default":["Text","Markdown","Heading","KeyValue","Metric","List","TableFallback","Form","Input","Select","Progress","LogStream","Warning","Error","Success","Approval","ActionGroup","FilePreview","Fallback"],"items":{"type":"string"}},"attachment_fetch":{"$ref":"#/$defs/RamfluxAttachmentFetch","default":{"max_bytes":5242880,"max_per_turn":4}},"authorization_mode":{"$ref":"#/$defs/RamfluxAuthorizationMode","default":"follow_rf"},"encrypt_at_rest":{"type":"boolean","default":true},"max_in_flight_per_conversation":{"type":"integer","format":"uint8","default":1,"maximum":255,"minimum":0},"on_new_message":{"$ref":"#/$defs/RamfluxOnNewMessage","default":"queue"},"socket_path":{"description":"Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.","type":["string","null"],"default":null},"surface_limits":{"$ref":"#/$defs/RamfluxSurfaceLimits","default":{"max_actions":16,"max_blocks":32,"max_bytes":65536}},"turn_wall_clock_secs":{"description":"Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.","type":"integer","format":"uint64","default":120,"minimum":0}},"additionalProperties":false},"RamfluxOnNewMessage":{"description":"What to do with a new inbound message while a turn for that conversation is running.","type":"string","enum":["queue","interrupt"]},"RamfluxSurfaceLimits":{"description":"Limits for `reply.surface` blocks and actions.","type":"object","properties":{"max_actions":{"type":"integer","format":"uint32","default":16,"minimum":0},"max_blocks":{"type":"integer","format":"uint32","default":32,"minimum":0},"max_bytes":{"type":"integer","format":"uint32","default":65536,"minimum":0}},"additionalProperties":false},"ReliabilityCircuitBreakerConfig":{"description":"Process-local provider circuit policy (`[reliability.circuit_breaker]`).","type":"object","properties":{"enabled":{"description":"Enable protection for factory-built provider chains.","type":"boolean","default":true},"failure_threshold":{"description":"Consecutive transient failures that open a circuit (at least 1).","type":"integer","format":"uint32","default":5,"minimum":0},"max_open_secs":{"description":"Maximum doubled window, between open_secs and 3600 seconds.","type":"integer","format":"uint64","default":300,"minimum":0},"open_secs":{"description":"Initial open window in seconds (at least 1).","type":"integer","format":"uint64","default":30,"minimum":0}}},"ReliabilityConfig":{"description":"Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.","type":"object","properties":{"acknowledge_single_provider_risk":{"description":"Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.","type":"boolean","default":false},"api_keys":{"description":"Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.","type":"array","default":[],"items":{"type":"string"}},"channel_initial_backoff_secs":{"description":"Initial backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":2,"minimum":0},"channel_max_backoff_secs":{"description":"Max backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":60,"minimum":0},"circuit_breaker":{"description":"Per-provider consecutive failure protection.","$ref":"#/$defs/ReliabilityCircuitBreakerConfig","default":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30}},"fallback_providers":{"description":"Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).","type":"array","default":[],"items":{"type":"string"}},"model_fallbacks":{"description":"Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`","type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"default":{}},"provider_backoff_ms":{"description":"Base backoff (ms) for provider retry delay.","type":"integer","format":"uint64","default":500,"minimum":0},"provider_retries":{"description":"Retries per provider before failing over.","type":"integer","format":"uint32","default":2,"minimum":0},"scheduler_poll_secs":{"description":"Scheduler polling cadence in seconds.","type":"integer","format":"uint64","default":15,"minimum":0},"scheduler_retries":{"description":"Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.","type":"integer","format":"uint32","default":2,"minimum":0}}},"RemoteNodeConfig":{"description":"A remote node target for core-side node proxy calls.","type":"object","properties":{"bearer_token":{"description":"Bearer token for node RPC authentication.","type":"string"},"endpoint":{"description":"Base endpoint (e.g. \"http://127.0.0.1:8787\").","type":"string"},"hmac_secret":{"description":"Optional request signing key (HMAC-SHA256).","type":["string","null"],"default":null},"id":{"description":"Stable node ID used by the nodes tool.","type":"string"},"retry_max":{"description":"Optional per-node retry override.","type":["integer","null"],"format":"uint8","default":null,"maximum":255,"minimum":0},"timeout_ms":{"description":"Optional per-node timeout override.","type":["integer","null"],"format":"uint64","default":null,"minimum":0}},"required":["id","endpoint","bearer_token"]},"RetrievalInjectionRole":{"description":"Where recalled context pages are injected back into the request.","oneOf":[{"description":"Inject recalled pages as a leading `system` message (not user-visible).","type":"string","const":"system"},{"description":"Inject recalled pages as a leading `user` message.","type":"string","const":"user"}]},"RouterConfig":{"description":"Heuristic LLM router configuration (`[router]` section).","type":"object","properties":{"alpha":{"description":"Similarity score weight. Phase 1 keeps this at `0.0`.","type":"number","format":"float","default":0.0},"beta":{"description":"Capability score weight.","type":"number","format":"float","default":0.5},"delta":{"description":"Cost penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"epsilon":{"description":"Latency penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"gamma":{"description":"Elo score weight.","type":"number","format":"float","default":0.30000001192092896},"knn_k":{"description":"Number of nearest neighbors considered for voting. Default: `7`.","type":"integer","format":"uint","default":7,"minimum":0},"knn_min_records":{"description":"Minimum history records before KNN affects routing. Default: `10`.","type":"integer","format":"uint","default":10,"minimum":0},"models":{"description":"Candidate model registry.","type":"array","default":[],"items":{"$ref":"#/$defs/RouterModelConfig"}}}},"RouterModelConfig":{"description":"Static router metadata for one model candidate.","type":"object","properties":{"categories":{"description":"Capability categories such as `conversation`, `code`, or `analysis`.","type":"array","default":[],"items":{"type":"string"}},"cost_per_million_tokens":{"description":"USD cost per million tokens.","type":"number","format":"float","default":0.0},"elo_rating":{"description":"Initial Elo rating.","type":"number","format":"float","default":1000.0},"latency_ms":{"description":"Average latency in milliseconds.","type":"integer","format":"uint32","default":2000,"minimum":0},"max_context":{"description":"Maximum context window in tokens.","type":"integer","format":"uint","default":1000000,"minimum":0},"model_id":{"description":"Model identifier without provider prefix.","type":"string"},"provider":{"description":"Provider identifier.","type":"string"},"reserved_output_tokens":{"description":"Output tokens reserved for this model when planning input context.","type":["integer","null"],"format":"uint","minimum":0}},"required":["model_id","provider"]},"RuntimeConfig":{"description":"Runtime adapter configuration (`[runtime]` section).","type":"object","properties":{"codex_reasoning_effort":{"description":"Codex reasoning effort","type":["string","null"],"default":null},"codex_stream_idle_timeout_secs":{"description":"Codex stream idle timeout in seconds","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"docker":{"description":"Docker runtime settings (used when `kind = \"docker\"`).","$ref":"#/$defs/DockerRuntimeConfig","default":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true}},"idle_hang_secs":{"description":"Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"kind":{"description":"Runtime kind (`native` | `docker`).","type":"string","default":"native"},"long_task_warn_secs":{"description":"Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"managed_cgroup_root":{"description":"Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.","type":["string","null"],"default":null},"max_blocking_threads":{"description":"Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"reasoning_enabled":{"description":"Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported","type":["boolean","null"],"default":null},"shell_env_allowlist":{"description":"Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.","type":"array","default":[],"items":{"type":"string"}},"workdir":{"description":"Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.","type":["string","null"],"default":null}}},"SchedulerConfig":{"description":"Scheduler configuration for periodic task execution (`[scheduler]` section).","type":"object","properties":{"claim_lease_secs":{"description":"Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.","type":"integer","format":"uint64","default":90,"minimum":0},"max_tasks":{"description":"Maximum number of persisted scheduled tasks.","type":"integer","format":"uint","default":64,"minimum":0}}},"ScopeConfig":{"description":"Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```","type":"object","properties":{"assign_owners":{"description":"Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.","type":"array","default":[],"items":{"type":"string"}},"default":{"description":"Default action when no rule matches: \"allow\" (default) or \"deny\".","$ref":"#/$defs/ScopeDefault","default":"allow"},"rules":{"description":"Ordered list of scope rules evaluated top-to-bottom.","type":"array","default":[],"items":{"$ref":"#/$defs/ScopeRule"}}}},"ScopeDefault":{"description":"What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.","oneOf":[{"description":"Unmatched tool calls are allowed (the default).","type":"string","const":"allow"},{"description":"Unmatched tool calls are refused.","type":"string","const":"deny"}]},"ScopeRule":{"description":"A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.","type":"object","properties":{"assign_allow":{"description":"Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".","type":"array","default":[],"items":{"type":"string"}},"assign_deny":{"description":"Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.","type":"array","default":[],"items":{"type":"string"}},"channel":{"description":"Match by channel name: \"signal\", \"telegram\", \"discord\", etc.","type":["string","null"]},"chat_type":{"description":"Match by chat type: \"direct\", \"group\", or \"*\" for any type.","type":["string","null"]},"send_allow":{"description":"Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.","type":"array","default":[],"items":{"type":"string"}},"send_deny":{"description":"Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.","type":"array","default":[],"items":{"type":"string"}},"tools_allow":{"description":"Tool whitelist: only these tools are allowed (empty = all tools permitted).","type":"array","default":[],"items":{"type":"string"}},"tools_deny":{"description":"Tool blacklist: these tools are denied regardless of allow list.","type":"array","default":[],"items":{"type":"string"}},"user":{"description":"Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.","type":["string","null"]}}},"SecretsConfig":{"description":"Secrets encryption configuration (`[secrets]` section).","type":"object","properties":{"encrypt":{"description":"Enable encryption for API keys and tokens in config.toml","type":"boolean","default":true}}},"SecurityConfig":{"description":"Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.","type":"object","properties":{"audit":{"description":"Audit logging configuration","$ref":"#/$defs/AuditConfig","default":{"log_path":"audit.log","max_size_mb":100}},"workspace_hooks":{"description":"Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.","$ref":"#/$defs/WorkspaceHooks"}}},"SelfSystemConfig":{"description":"Self-system experimental automation config (`[self_system]`).","type":"object","properties":{"evolution_config_path":{"description":"Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG)","type":["string","null"],"default":null},"evolution_debug_raw":{"description":"Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW)","type":"boolean","default":false},"evolution_interval_hours":{"description":"Evolution scheduler interval in hours (daemon mode).","type":"integer","format":"uint32","default":24,"minimum":0},"evolution_judge_timeout_secs":{"description":"Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.","type":"integer","format":"uint64","default":180,"minimum":0},"evolution_model_max_micro_usd":{"description":"Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.","type":"integer","format":"uint64","default":0,"minimum":0},"evolution_model_max_tokens":{"description":"Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.","type":"integer","format":"uint64","default":16384,"minimum":0},"fitness":{"description":"Daily fitness snapshot policy.","$ref":"#/$defs/FitnessConfig","default":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"}},"fitness_interval_hours":{"description":"Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.","type":"integer","format":"uint64","default":24,"minimum":0}}},"SessionsSpawnConfig":{"description":"Sessions spawn configuration (`[sessions_spawn]` section).","type":"object","properties":{"cleanup_on_complete":{"description":"Remove worker workspace directory after process-mode completion.","type":"boolean","default":true},"default_mode":{"description":"Default execution mode for sessions_spawn (`task` or `process`).","type":"string","default":"task"},"process_memory_strategy":{"description":"Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.","type":"string","default":"shared_fabric"},"worker_workspace_root":{"description":"Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.","type":["string","null"],"default":null}}},"SignalConfig":{"type":"object","properties":{"account":{"description":"E.164 phone number of the signal-cli account (e.g. \"+1234567890\").","type":"string"},"allowed_from":{"description":"Allowed sender phone numbers (E.164) or \"*\" for all.","type":"array","default":[],"items":{"type":"string"}},"cli_path":{"description":"Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).","type":["string","null"],"default":null},"daemon_http_port":{"description":"Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"daemon_mode":{"description":"Deprecated: ignored. Accepted for backward compatibility with older config files.","type":["boolean","null"],"default":null},"data_dir":{"description":"signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_id":{"description":"Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group","type":["string","null"],"default":null},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"http_url":{"description":"Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.","type":"string","default":"http://localhost:8080"},"ignore_attachments":{"description":"Skip messages that are attachment-only (no text body).","type":"boolean","default":false},"ignore_stories":{"description":"Skip incoming story messages.","type":"boolean","default":false},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"mode":{"description":"Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.","type":["string","null"],"default":null},"startup_timeout_ms":{"description":"Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.","type":"integer","format":"uint64","default":30000,"minimum":0},"storm_protection":{"description":"Signal ingress storm protection controls.","$ref":"#/$defs/SignalStormProtectionConfig","default":{"abnormal_threshold":10,"abnormal_window_secs":60,"breaker_duration_secs":300,"dedupe_ttl_secs":60,"min_reply_interval_secs":2}}},"required":["account"]},"SignalStormProtectionConfig":{"type":"object","properties":{"abnormal_threshold":{"description":"Non-user event threshold within `abnormal_window_secs` before tripping the breaker.","type":"integer","format":"uint","default":10,"minimum":0},"abnormal_window_secs":{"description":"Sliding window in seconds for non-user event counting.","type":"integer","format":"uint64","default":60,"minimum":0},"breaker_duration_secs":{"description":"Circuit breaker duration in seconds after threshold is reached.","type":"integer","format":"uint64","default":300,"minimum":0},"dedupe_ttl_secs":{"description":"Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.","type":"integer","format":"uint64","default":60,"minimum":0},"min_reply_interval_secs":{"description":"Minimum interval in seconds between replies for the same `(channel + reply_target)`.","type":"integer","format":"uint64","default":2,"minimum":0}}},"SkillRagConfig":{"description":"Dynamic skill retrieval configuration (`[skill_rag]` section).","type":"object","properties":{"top_k":{"description":"How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).","type":"integer","format":"uint","default":32,"minimum":0}}},"SkillSuiteRegistration":{"description":"The frozen suite that governs one skill's proposals.","type":"object","properties":{"skill_id":{"description":"The skill the suite governs.","type":"string"},"suite_digest":{"description":"SHA-256 digest (64 lowercase hex digits) of the frozen suite.","type":"string"}},"additionalProperties":false,"required":["skill_id","suite_digest"]},"SkillsConfig":{"description":"Skills loading configuration (`[skills]` section).","type":"object","properties":{"open_skills_dir":{"description":"Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.","type":["string","null"],"default":null},"openclaw_skills_dir":{"description":"Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.","type":["string","null"],"default":null}}},"SkillsLifecycleConfig":{"description":"`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.","type":"object","properties":{"allow_executable_proposals":{"description":"Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.","type":"boolean","default":false},"enabled":{"description":"Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.","type":"boolean","default":false},"max_concurrent_evaluations":{"description":"Most evaluations running at once.","type":"integer","format":"uint32","default":1,"minimum":0},"max_edit_fraction":{"description":"Edit budget of a proposal as a fraction of the skill body, in (0, 1].","type":"number","format":"double","default":0.2},"max_edit_tokens":{"description":"Edit budget of a proposal, in tokens.","type":"integer","format":"uint64","default":300,"minimum":0},"max_proposals_per_cycle":{"description":"Most proposals one cycle may start.","type":"integer","format":"uint32","default":1,"minimum":0},"min_cases_floor":{"description":"Smallest `min_cases` a governing suite may declare. Below 3 is refused.","type":"integer","format":"uint32","default":3,"minimum":0},"mode":{"description":"`draft_only`, `shadow` or `auto`.","$ref":"#/$defs/SkillsLifecycleModeConfig","default":"draft_only"},"owner_scope":{"description":"The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.","type":["string","null"],"default":null},"require_holdout":{"description":"A governing suite must have a holdout split. `false` is refused.","type":"boolean","default":true},"storage_dir":{"description":"Store location under the workspace. Only the default is supported.","type":"string","default":"self/skill-lifecycle"},"suites":{"description":"The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.","type":"array","default":[],"items":{"$ref":"#/$defs/SkillSuiteRegistration"}}},"additionalProperties":false},"SkillsLifecycleModeConfig":{"description":"What the lifecycle may do. Mirrors `LifecycleMode`.","oneOf":[{"description":"Drafts and reviews only.","type":"string","const":"draft_only"},{"description":"Drafts plus evaluation and gating; never publishes.","type":"string","const":"shadow"},{"description":"Publishes an eligible proposal after every gate.","type":"string","const":"auto"}]},"SlackConfig":{"description":"Slack bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Slack user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Slack app-level token for Socket Mode (xapp-...).","type":["string","null"]},"bot_token":{"description":"Slack bot OAuth token (xoxb-...).","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["bot_token"]},"SmartGroupConfig":{"description":"Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).","type":"object","properties":{"classifier_max_context_messages":{"description":"How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.","type":"integer","format":"uint","default":3,"minimum":0},"classifier_model":{"description":"Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.","type":"string","default":""},"classifier_provider":{"description":"Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.","type":"string","default":""},"classifier_temperature":{"description":"Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).","type":"number","format":"double","default":0.0},"classifier_timeout_secs":{"description":"Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.","type":"integer","format":"uint64","default":5,"minimum":0}}},"StorageConfig":{"description":"Persistent storage configuration (`[storage]` section).","type":"object","properties":{"provider":{"description":"Storage provider settings (e.g. sqlite, postgres).","$ref":"#/$defs/StorageProviderSection","default":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}}},"StorageProviderConfig":{"description":"Storage provider backend configuration (e.g. postgres connection details).","type":"object","properties":{"connect_timeout_secs":{"description":"Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"db_url":{"description":"Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.","type":["string","null"],"default":null},"pool_max_size":{"description":"Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.","type":"integer","format":"uint","default":32,"minimum":0},"provider":{"description":"Storage engine key (e.g. \"postgres\", \"sqlite\").","type":"string","default":""},"schema":{"description":"Database schema for SQL backends.","type":"string","default":"public"},"table":{"description":"Table name for memory entries.","type":"string","default":"memories"}}},"StorageProviderSection":{"description":"Wrapper for the storage provider configuration section.","type":"object","properties":{"config":{"description":"Storage provider backend settings.","$ref":"#/$defs/StorageProviderConfig","default":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"StreamMode":{"description":"Streaming mode for channels that support progressive message updates.","oneOf":[{"description":"No streaming -- send the complete response as a single message (default).","type":"string","const":"off"},{"description":"Update a draft message with every flush interval.","type":"string","const":"partial"}]},"TailscaleTunnelConfig":{"type":"object","properties":{"funnel":{"description":"Use Tailscale Funnel (public internet) vs Serve (tailnet only)","type":"boolean","default":false},"hostname":{"description":"Optional hostname override","type":["string","null"]}}},"TaskRoutingConfig":{"description":"Lightweight pre-LLM task routing.","type":"object","properties":{"default_intent":{"description":"Fallback intent when no rule matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"rules":{"description":"Rules evaluated in descending priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/TaskRoutingRule"}}}},"TaskRoutingIntentConfig":{"description":"Task-routing default and rule intent.","type":"string","enum":["simple","delegate","stream"]},"TaskRoutingRule":{"description":"A single task-routing rule.","type":"object","properties":{"intent":{"description":"Route intent to apply when a keyword matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"model_hint":{"description":"Optional model hint/raw model for non-delegated requests.","type":["string","null"],"default":null},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0},"sub_agent_model":{"description":"Optional raw sub-agent model override for delegated tasks.","type":["string","null"],"default":null}}},"TelegramConfig":{"description":"Telegram bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Telegram user IDs or usernames. Empty = deny all.","type":"array","items":{"type":"string"}},"bot_token":{"description":"Telegram Bot API token (from @BotFather).","type":"string"},"draft_update_interval_ms":{"description":"Minimum interval (ms) between draft message edits to avoid rate limits.","type":"integer","format":"uint64","default":1000,"minimum":0},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"interrupt_on_new_message":{"description":"When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.","type":"boolean","default":false},"stream_mode":{"description":"Streaming mode for progressive response delivery via message edits.","$ref":"#/$defs/StreamMode","default":"off"}},"required":["bot_token","allowed_users"]},"ToolCallDialectSetting":{"description":"The tool-call grammars an operator may declare for an endpoint.","oneOf":[{"description":"Only the native `tool_calls` array is a tool call (the default).","type":"string","const":"native"},{"description":"Additionally read `{json}` from the content,\nfor a tool name the request registered.","type":"string","const":"xml_function_tags"}]},"ToolSchemaDialectSetting":{"description":"The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.","oneOf":[{"description":"The published document, byte for byte (the default).","type":"string","const":"raw"},{"description":"The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.","type":"string","const":"no_root_combinators"}]},"ToolTieringConfig":{"description":"Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.","type":"object","properties":{"always_exclude":{"description":"Tool names excluded from capability publication.","type":"array","default":[],"items":{"type":"string"}},"always_include":{"description":"Tool names preferred for direct publication, subject to admission gates.","type":"array","default":[],"items":{"type":"string"}},"channel_exclude":{"description":"Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefaults to [`DEFAULT_CHANNEL_EXCLUDED_TOOLS`]; set to `[]` to expose the\nfull operator surface on channels again.","type":"array","default":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","git_operations","skills_manage","memory_reindex","document_sync","document_ingest"],"items":{"type":"string"}}}},"TunnelConfig":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.","type":"object","properties":{"cloudflare":{"description":"Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).","anyOf":[{"$ref":"#/$defs/CloudflareTunnelConfig"},{"type":"null"}],"default":null},"custom":{"description":"Custom tunnel command configuration (used when `provider = \"custom\"`).","anyOf":[{"$ref":"#/$defs/CustomTunnelConfig"},{"type":"null"}],"default":null},"ngrok":{"description":"ngrok tunnel configuration (used when `provider = \"ngrok\"`).","anyOf":[{"$ref":"#/$defs/NgrokTunnelConfig"},{"type":"null"}],"default":null},"provider":{"description":"Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.","type":"string","default":"none"},"tailscale":{"description":"Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).","anyOf":[{"$ref":"#/$defs/TailscaleTunnelConfig"},{"type":"null"}],"default":null}}},"UserPolicyConfig":{"description":"Startup user policy entry (`[[user_policies]]`).","type":"object","properties":{"blocked_patterns":{"type":"array","default":[],"items":{"type":"string"}},"projects":{"type":"array","default":[],"items":{"type":"string"}},"role":{"type":"string","default":"guest"},"user_id":{"type":"string"},"visibility_ceiling":{"type":"string","default":"private"}},"required":["user_id"]},"WacliConfig":{"description":"wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```","type":"object","properties":{"allow_unsigned_loopback":{"description":"Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).","type":"boolean","default":false},"allowed_from":{"description":"Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.","type":"array","default":["*"],"items":{"type":"string"}},"bot_jid":{"description":"Bot's own JID, used for reply-to-bot mention detection.","type":["string","null"],"default":null},"bot_lid":{"description":"The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.","type":["string","null"],"default":null},"bot_number":{"description":"Bot's own phone number (digits), used for `@` mention detection.","type":["string","null"],"default":null},"cli_path":{"description":"Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.","type":["string","null"],"default":null},"group_reply_mode":{"description":"Smart group-reply mode. When `None`, derived from `mention_only`.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"host":{"description":"REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].","type":["string","null"],"writeOnly":true},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"outbound_media_workspace_only":{"description":"Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.","type":"boolean","default":false},"port":{"description":"REMOVED: legacy JSON-RPC daemon port. See `host`.","type":["integer","null"],"format":"uint16","maximum":65535,"minimum":0,"writeOnly":true},"self_chat_mode":{"description":"Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.","type":"boolean","default":false},"store_dir":{"description":"wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.","type":["string","null"],"default":null},"webhook_listen":{"description":"Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").","type":"string","default":"127.0.0.1:16868"},"webhook_path":{"description":"HTTP path the webhook server serves (default: \"/wacli\").","type":"string","default":"/wacli"},"webhook_secret":{"description":"HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.","type":["string","null"],"default":null}}},"WebSearchConfig":{"description":"Web search tool configuration (`[web_search]` section).","type":"object","properties":{"brave_api_key":{"description":"Brave Search API key (required if provider is \"brave\")","type":["string","null"],"default":null},"fetch_max_chars":{"description":"Maximum characters returned by `web_fetch` (default 10000)","type":"integer","format":"uint","default":50000,"minimum":0},"max_results":{"description":"Maximum results per search (1-20)","type":"integer","format":"uint","default":15,"minimum":0},"provider":{"description":"Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)","type":"string","default":"duckduckgo"},"timeout_secs":{"description":"Request timeout in seconds","type":"integer","format":"uint64","default":15,"minimum":0}}},"WebhookConfig":{"description":"Webhook channel configuration.","type":"object","properties":{"port":{"description":"Port to listen on for incoming webhooks.","type":"integer","format":"uint16","maximum":65535,"minimum":0},"secret":{"description":"Optional shared secret for webhook signature verification.","type":["string","null"]}},"required":["port"]},"WhatsAppConfig":{"description":"WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.","type":"object","properties":{"access_token":{"description":"Access token from Meta Business Suite (Cloud API mode)","type":["string","null"],"default":null},"allowed_numbers":{"description":"Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"app_secret":{"description":"App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"pair_code":{"description":"Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one","type":["string","null"],"default":null},"pair_phone":{"description":"Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used","type":["string","null"],"default":null},"phone_number_id":{"description":"Phone number ID from Meta Business API (Cloud API mode)","type":["string","null"],"default":null},"read_pool_size":{"description":"Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"session_path":{"description":"Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs","type":["string","null"],"default":null},"verify_token":{"description":"Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode","type":["string","null"],"default":null},"ws_url":{"description":"WebSocket URL override (replaces WHATSAPP_WS_URL)","type":["string","null"],"default":null}}},"WorkspaceHooks":{"description":"Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).","oneOf":[{"description":"They do not run (the default); `prx doctor` and `hooks_status` say so.","type":"string","const":"off"},{"description":"They run, in a cleared environment and a dedicated directory beside\n`config.toml`.","type":"string","const":"on"}]},"WorkspaceMcpServers":{"description":"Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).","oneOf":[{"description":"None: a workspace file may only narrow the servers defined in\n`config.toml`.","type":"string","const":"off"},{"description":"HTTP servers (still refused when they target a private address).","type":"string","const":"http_only"},{"description":"HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.","type":"string","const":"stdio"}]},"XinConfig":{"description":"Configuration for the xin autonomous task engine (`[xin]`).","type":"object","properties":{"adopt_legacy_tasks":{"description":"Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).","type":"boolean","default":false},"interval_minutes":{"description":"Tick interval in minutes (minimum 1). Default: 5.","type":"integer","format":"uint32","default":5,"minimum":0},"stale_timeout_minutes":{"description":"Minutes after which a running task is marked stale. Default: 60.","type":"integer","format":"uint32","default":60,"minimum":0}}},"AgentMessaging":{"description":"Owner-controlled inbound session messaging (enabled unless explicitly off).","type":"object","properties":{"inbound":{"type":"boolean","default":true}}}}} +{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Config","description":"Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).","type":"object","properties":{"a2a":{"description":"Agent-to-Agent compatibility configuration (`[a2a]`).","$ref":"#/$defs/A2aConfig","default":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trusted_trust_domains":[],"trust_domain":"prx.local"}},"agent":{"description":"Agent orchestration settings (`[agent]`).","$ref":"#/$defs/AgentConfig","default":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2,"messaging":{"inbound":true}}},"agents":{"description":"Delegate agent configurations for multi-agent workflows.","type":"object","additionalProperties":{"$ref":"#/$defs/DelegateAgentConfig"},"default":{}},"api_key":{"description":"API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.","type":["string","null"],"default":null},"api_url":{"description":"Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)","type":["string","null"],"default":null},"auth":{"description":"Auth profile and external credential import settings (`[auth]`).","$ref":"#/$defs/AuthConfig","default":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"}},"autonomy":{"description":"Autonomy and security policy configuration (`[autonomy]`).","$ref":"#/$defs/AutonomyConfig","default":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":500,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true}},"browser":{"description":"Browser automation configuration (`[browser]`).","$ref":"#/$defs/BrowserConfig","default":{"allowed_domains":[],"computer_use":{"api_key":null}}},"channels_config":{"description":"Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).","$ref":"#/$defs/ChannelsConfig","default":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null}},"chat":{"description":"Interactive chat UI configuration (`[chat]`).","$ref":"#/$defs/ChatConfig","default":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2}},"compliance":{"description":"Operator-owned compliance controls (`[compliance]`).","$ref":"#/$defs/ComplianceConfig","default":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}},"composio":{"description":"Composio managed OAuth tools integration (`[composio]`).","$ref":"#/$defs/ComposioConfig","default":{"api_key":null,"entity_id":"default"}},"cost":{"description":"Cost tracking and budget enforcement configuration (`[cost]`).","$ref":"#/$defs/CostConfig","default":{"allow_override":false,"daily_limit_usd":10.0,"monthly_limit_usd":100.0,"prices":{},"warn_at_percent":80}},"cron":{"description":"Cron job configuration (`[cron]`).","$ref":"#/$defs/CronConfig","default":{"max_run_history":50}},"decision_engine":{"description":"Optional advisory decision engine, disabled by default.","$ref":"#/$defs/DecisionEngineConfig","default":{"candidates":5,"enabled":false,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"latency_budget_ms":500,"max_candidates":12,"token_ratio_limit":0.3499999940395355}},"default_model":{"description":"Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.","type":["string","null"]},"default_provider":{"description":"Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.","type":["string","null"]},"default_temperature":{"description":"Default model temperature (0.0–2.0). Default: `0.7`.","type":"number","format":"double","default":0.7},"embedding_routes":{"description":"Embedding routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/EmbeddingRouteConfig"}},"gateway":{"description":"Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).","$ref":"#/$defs/GatewayConfig","default":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":false,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60}},"heartbeat":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]`).","$ref":"#/$defs/HeartbeatConfig","default":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."}},"http_request":{"description":"HTTP request tool configuration (`[http_request]`).","$ref":"#/$defs/HttpRequestConfig","default":{"max_response_size":1000000,"timeout_secs":30}},"identity":{"description":"Identity format configuration: OpenClaw or AIEOS (`[identity]`).","$ref":"#/$defs/IdentityConfig","default":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"}},"identity_bindings":{"description":"Static identity bindings loaded at startup (`[[identity_bindings]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/IdentityBindingConfig"}},"mcp":{"description":"Secrets encryption configuration (`[secrets]`).","$ref":"#/$defs/McpConfig","default":{"servers":{}}},"mcp_server":{"description":"MCP server compatibility configuration (`[mcp_server]`).","$ref":"#/$defs/McpServerRuntimeConfig","default":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true}},"media":{"description":"Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.","$ref":"#/$defs/MediaConfig","default":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"}},"memory":{"description":"Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).","$ref":"#/$defs/MemoryConfig","default":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7}},"model_routes":{"description":"Model routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/ModelRouteConfig"}},"model_settings":{"description":"Catalog model levels and explicit parameters, keyed by canonical release ID.","type":"object","additionalProperties":{"$ref":"#/$defs/ModelSettings"},"default":{}},"multimodal":{"description":"Multimodal (image) handling configuration (`[multimodal]`).","$ref":"#/$defs/MultimodalConfig","default":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4}},"nodes":{"description":"Remote node proxy configuration (`[nodes]`).","$ref":"#/$defs/NodesConfig","default":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}},"observability":{"description":"Observability backend configuration (`[observability]`).","$ref":"#/$defs/ObservabilityConfig","default":{"backend":"none","otel_endpoint":null,"otel_service_name":null}},"plugins":{"description":"WASM plugin runtime switch (`[plugins]`), off by default.","$ref":"#/$defs/PluginsConfig","default":{"enabled":false}},"providers":{"description":"Provider-specific runtime options (`[providers.]`).","$ref":"#/$defs/ProvidersConfig","default":{"ollama":{"num_ctx":null}}},"proxy":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).","$ref":"#/$defs/ProxyConfig","default":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]}},"query_classification":{"description":"Automatic query classification — maps user messages to model hints.","$ref":"#/$defs/QueryClassificationConfig","default":{"rules":[]}},"reliability":{"description":"Reliability settings: retries, fallback providers, backoff (`[reliability]`).","$ref":"#/$defs/ReliabilityConfig","default":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2}},"router":{"description":"Heuristic LLM router configuration (`[router]`).","$ref":"#/$defs/RouterConfig","default":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]}},"runtime":{"description":"Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.","$ref":"#/$defs/RuntimeConfig","default":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null}},"scheduler":{"description":"Scheduler configuration for periodic task execution (`[scheduler]`).","$ref":"#/$defs/SchedulerConfig","default":{"claim_lease_secs":90,"max_tasks":64}},"secrets":{"$ref":"#/$defs/SecretsConfig","default":{"encrypt":true}},"security":{"description":"Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).","$ref":"#/$defs/SecurityConfig","default":{"audit":{"log_path":"audit.log","max_size_mb":100}}},"self_system":{"description":"Self-system experimental automation controls (`[self_system]`).","$ref":"#/$defs/SelfSystemConfig","default":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24}},"sessions_spawn":{"description":"Session spawning configuration (`[sessions_spawn]`).","$ref":"#/$defs/SessionsSpawnConfig","default":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null}},"skill_rag":{"description":"Dynamic skill retrieval settings (`[skill_rag]`).","$ref":"#/$defs/SkillRagConfig","default":{"top_k":32}},"skills":{"description":"Skills loading and community repository behavior (`[skills]`).","$ref":"#/$defs/SkillsConfig","default":{"open_skills_dir":null,"openclaw_skills_dir":null}},"skills_lifecycle":{"description":"Skill lifecycle (`[skills_lifecycle]`), off by default.","$ref":"#/$defs/SkillsLifecycleConfig","default":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]}},"smart_group":{"description":"Smart group-reply pre-gate configuration (`[smart_group]`).","$ref":"#/$defs/SmartGroupConfig","default":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5}},"storage":{"description":"Persistent storage provider configuration (`[storage]`).","$ref":"#/$defs/StorageConfig","default":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"task_routing":{"description":"Task routing configuration — classifies work by intent before the main agent loop.","$ref":"#/$defs/TaskRoutingConfig","default":{"default_intent":"simple","rules":[]}},"tool_tiering":{"description":"Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).","$ref":"#/$defs/ToolTieringConfig","default":{"always_exclude":[],"always_include":[],"channel_exclude":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","skills_manage","memory_reindex","document_sync","document_ingest"]}},"tunnel":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]`).","$ref":"#/$defs/TunnelConfig","default":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null}},"user_policies":{"description":"Static user policy records loaded at startup (`[[user_policies]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/UserPolicyConfig"}},"web_search":{"description":"Web search tool configuration (`[web_search]`).","$ref":"#/$defs/WebSearchConfig","default":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15}},"webhook":{"description":"Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).","$ref":"#/$defs/MemoryWebhookConfig","default":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null}},"xin":{"description":"Xin autonomous task engine configuration (`[xin]`).","$ref":"#/$defs/XinConfig","default":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}}},"$defs":{"A2aConfig":{"type":"object","properties":{"agent_id":{"description":"Stable PRX agent identifier advertised to peers.","type":"string","default":"prx-default"},"allowed_peer_issuers":{"description":"Accepted external peer issuers.","type":"array","default":[],"items":{"type":"string"}},"bind":{"description":"Advertised bind address.","type":"string","default":"127.0.0.1:16832"},"card_jwks_uri":{"description":"Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.","type":["string","null"],"default":null},"card_signing_key_path":{"description":"On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).","type":["string","null"],"default":null},"card_ttl_seconds":{"description":"Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.","type":"integer","format":"uint64","default":3600,"minimum":0},"discovery_advertised":{"description":"Whether to advertise into an external A2A registry.","type":"boolean","default":false},"handoff_nonce_ttl_seconds":{"description":"Replay window for future handoff delegation tokens.","type":"integer","format":"uint64","default":3600,"minimum":0},"messaging_enabled":{"description":"Enable the dedicated pinned mTLS messaging listener.","type":"boolean","default":false},"peers":{"type":"object","additionalProperties":{"$ref":"#/$defs/A2aPeer"},"default":{}},"spiffe_id":{"description":"Local SPIFFE-style identifier placeholder.","type":"string","default":"spiffe://prx-local/agent/prx-default"},"spiffe_strict_validation":{"description":"When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.","type":"boolean","default":false},"spiffe_trust_bundle_pem":{"description":"Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).","type":["string","null"],"default":null},"trusted_trust_domains":{"description":"Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).","type":"array","default":[],"items":{"type":"string"}},"trust_domain":{"description":"SPIFFE trust domain for new instance identities.","type":"string","default":"prx.local"}}},"A2aPeer":{"description":"Explicit pinned identity and local recipient grant.","type":"object","properties":{"spiffe_id":{"type":"string"},"fingerprints":{"type":"array","items":{"type":"string"}},"address":{"type":"string"},"owner":{"type":"string"},"sessions":{"type":"array","default":["*"],"items":{"type":"string"}},"agents":{"type":"array","default":["*"],"items":{"type":"string"}}},"required":["spiffe_id","fingerprints","address","owner"],"additionalProperties":false},"AgentCompactionConfig":{"description":"Agent context compaction configuration (`[agent.compaction]`).","type":"object","properties":{"keep_recent_messages":{"description":"Number of recent non-system messages to keep after compaction.","type":"integer","format":"uint","default":12,"minimum":0},"max_context_tokens":{"description":"Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.","type":"integer","format":"uint","default":128000,"minimum":0},"memory_flush":{"description":"Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.","type":"boolean","default":true},"mode":{"description":"Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).","$ref":"#/$defs/AgentCompactionMode","default":"switch"},"os_paging":{"description":"Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.","$ref":"#/$defs/OsPagingConfig","default":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"}},"reserve_tokens":{"description":"Tokens reserved for the next model response.","type":"integer","format":"uint","default":4096,"minimum":0}}},"AgentCompactionMode":{"description":"Compaction mode for long conversation contexts.","oneOf":[{"description":"Disable proactive compaction.","type":"string","const":"off"},{"description":"Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.","type":"string","const":"switch"},{"description":"Conservative compaction that prefers summary replacement.","type":"string","const":"safeguard"},{"description":"Aggressive truncation mode for tighter contexts.","type":"string","const":"aggressive"}]},"AgentConfig":{"description":"Agent orchestration configuration (`[agent]` section).","type":"object","properties":{"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"compact_context":{"description":"When true: bootstrap_max_chars=6000. Use for 13B or smaller models.","type":"boolean","default":false},"compaction":{"description":"Context compaction controls (`[agent.compaction]`).","$ref":"#/$defs/AgentCompactionConfig","default":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096}},"low_priority_tools":{"description":"Tool names treated as low-priority when `priority_scheduling_enabled = true`.","type":"array","default":["sessions_spawn","delegate"],"items":{"type":"string"}},"priority_scheduling_enabled":{"description":"Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.","type":"boolean","default":false},"read_only_tool_concurrency_window":{"description":"Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.","type":"integer","format":"uint","default":2,"minimum":0},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}}},"AgentLimits":{"description":"Optional admission limits for rf-started turns of a named agent.","type":"object","properties":{"max_concurrent_turns":{"type":["integer","null"],"format":"uint32","minimum":0},"max_cost_per_day_cents":{"type":["integer","null"],"format":"uint64","minimum":0}},"additionalProperties":false},"AuditConfig":{"description":"Audit logging configuration","type":"object","properties":{"log_path":{"description":"Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).","type":"string","default":"audit.log"},"max_size_mb":{"description":"Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).","type":"integer","format":"uint32","default":100,"minimum":0}}},"AuthConfig":{"description":"Authentication and external credential import configuration (`[auth]` section).","type":"object","properties":{"codex_auth_json_auto_import":{"description":"Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.","type":"boolean","default":false},"codex_auth_json_path":{"description":"Source path for Codex CLI auth.json import.","type":"string","default":"~/.codex/auth.json"}}},"AutonomyConfig":{"type":"object","properties":{"acknowledge_unrestricted_profile":{"description":"Operator acknowledgement for an intentionally unrestricted profile.\nThis suppresses doctor noise only; it does not alter policy behavior.","type":"boolean","default":false},"forbidden_paths":{"description":"Explicit path denylist. Default includes system-critical paths.\n\nFails closed: omitting the key keeps the built-in list rather than\nemptying it, so a partial `[autonomy]` section never removes the\ndenylist.","type":"array","default":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"items":{"type":"string"}},"level":{"description":"Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).","$ref":"#/$defs/AutonomyLevel","default":"full"},"max_cost_per_day_cents":{"description":"Maximum cost per day in cents per policy. Default: `500`.","type":"integer","format":"uint32","default":500,"minimum":0},"scopes":{"description":"Scope-based tool access control: per-user/channel/chat-type allow/deny rules.","$ref":"#/$defs/ScopeConfig","default":{"assign_owners":[],"default":"allow","rules":[]}},"workspace_only":{"description":"Restrict file writes and command paths to the workspace directory. Default: `true`.\n\nFails closed: a `[autonomy]` section that omits this key keeps the\nworkspace restriction on, so a partial section can never widen the\nfilesystem reach by accident.","type":"boolean","default":true}}},"AutonomyLevel":{"description":"How much autonomy the agent has","oneOf":[{"description":"Read-only: can observe but not act","type":"string","const":"readonly"},{"description":"Supervised: acts but requires approval for risky operations","type":"string","const":"supervised"},{"description":"Full: autonomous execution within policy bounds","type":"string","const":"full"}]},"BackendSelection":{"description":"Which decision backend runs: `auto` (the factory's order) or one kind.","type":"string"},"BrowserComputerUseConfig":{"description":"Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.","type":"object","properties":{"api_key":{"description":"Optional bearer token (retained only for config secret handling).","type":["string","null"],"default":null}}},"BrowserConfig":{"description":"Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.","type":"object","properties":{"allowed_domains":{"description":"Allowed domains for `web_fetch` (exact or subdomain match).","type":"array","default":[],"items":{"type":"string"}},"computer_use":{"description":"Computer-use sidecar config (retained only for `api_key` secret handling).","$ref":"#/$defs/BrowserComputerUseConfig","default":{"api_key":null}}}},"ChannelsConfig":{"description":"Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.","type":"object","properties":{"cli":{"description":"Enable the CLI interactive channel. Default: `true`.","type":"boolean","default":true},"dingtalk":{"description":"DingTalk channel configuration.","anyOf":[{"$ref":"#/$defs/DingTalkConfig"},{"type":"null"}]},"discord":{"description":"Discord bot channel configuration.","anyOf":[{"$ref":"#/$defs/DiscordConfig"},{"type":"null"}]},"email":{"description":"Email channel configuration.","anyOf":[{"$ref":"#/$defs/EmailConfig"},{"type":"null"}]},"imessage":{"description":"iMessage channel configuration (macOS only).","anyOf":[{"$ref":"#/$defs/IMessageConfig"},{"type":"null"}]},"irc":{"description":"IRC channel configuration.","anyOf":[{"$ref":"#/$defs/IrcConfig"},{"type":"null"}]},"lark":{"description":"Lark/Feishu channel configuration.","anyOf":[{"$ref":"#/$defs/LarkConfig"},{"type":"null"}]},"linq":{"description":"Linq Partner API channel configuration.","anyOf":[{"$ref":"#/$defs/LinqConfig"},{"type":"null"}]},"mattermost":{"description":"Mattermost bot channel configuration.","anyOf":[{"$ref":"#/$defs/MattermostConfig"},{"type":"null"}]},"nextcloud_talk":{"description":"Nextcloud Talk bot channel configuration.","anyOf":[{"$ref":"#/$defs/NextcloudTalkConfig"},{"type":"null"}]},"qq":{"description":"QQ Official Bot channel configuration.","anyOf":[{"$ref":"#/$defs/QQConfig"},{"type":"null"}]},"ramflux":{"description":"Local ramflux agent-host bridge.","anyOf":[{"$ref":"#/$defs/RamfluxConfig"},{"type":"null"}],"default":null},"signal":{"description":"Signal channel configuration.","anyOf":[{"$ref":"#/$defs/SignalConfig"},{"type":"null"}]},"slack":{"description":"Slack bot channel configuration.","anyOf":[{"$ref":"#/$defs/SlackConfig"},{"type":"null"}]},"telegram":{"description":"Telegram bot channel configuration.","anyOf":[{"$ref":"#/$defs/TelegramConfig"},{"type":"null"}]},"wacli":{"description":"wacli JSON-RPC daemon channel configuration.","anyOf":[{"$ref":"#/$defs/WacliConfig"},{"type":"null"}],"default":null},"webhook":{"description":"Webhook channel configuration.","anyOf":[{"$ref":"#/$defs/WebhookConfig"},{"type":"null"}]},"whatsapp":{"description":"WhatsApp channel configuration (Cloud API or Web mode).","anyOf":[{"$ref":"#/$defs/WhatsAppConfig"},{"type":"null"}]}}},"ChatConfig":{"description":"Interactive chat configuration (`[chat]`).","type":"object","properties":{"daemon":{"description":"How this chat process reaches the daemon it borrows channels from.","$ref":"#/$defs/ChatDaemonConfig","default":{"token":"","url":""}},"max_concurrent_visible_turns":{"description":"Maximum concurrent visible provider turns in the TUI Redux driver.","type":"integer","format":"uint","default":2,"minimum":0}}},"ChatDaemonConfig":{"description":"Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.","type":"object","properties":{"token":{"description":"Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.","type":"string","default":""},"url":{"description":"Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.","type":"string","default":""}}},"CircuitBreakerConfig":{"description":"The per-backend circuit breaker.","type":"object","properties":{"cooldown_secs":{"description":"Seconds the breaker stays open (1 to 3600).","type":"integer","format":"uint32","default":60,"minimum":0},"failure_threshold":{"description":"Consecutive failures before the breaker opens (1 to 100).","type":"integer","format":"uint32","default":5,"minimum":0}}},"ClassificationRule":{"description":"A single classification rule mapping message patterns to a model hint.","type":"object","properties":{"hint":{"description":"Must match a `[[model_routes]]` hint value.","type":"string"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"max_length":{"description":"Only match if message length <= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"min_length":{"description":"Only match if message length >= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"patterns":{"description":"Case-sensitive literal matches (for \"```\", \"fn \", etc.).","type":"array","default":[],"items":{"type":"string"}},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0}},"required":["hint"]},"CloudflareTunnelConfig":{"type":"object","properties":{"token":{"description":"Cloudflare Tunnel token (from Zero Trust dashboard)","type":"string"}},"required":["token"]},"ComplianceConfig":{"type":"object","properties":{"eu_ai_act":{"$ref":"#/$defs/EuAiActComplianceConfig","default":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null}},"interaction_notice":{"$ref":"#/$defs/InteractionNoticeConfig","default":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}}},"ComposioConfig":{"description":"Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.","type":"object","properties":{"api_key":{"description":"Composio API key (stored encrypted when secrets.encrypt = true)","type":["string","null"],"default":null},"entity_id":{"description":"Default entity ID for multi-user setups","type":"string","default":"default"}}},"CostConfig":{"description":"Cost tracking and budget enforcement configuration (`[cost]` section).","type":"object","properties":{"allow_override":{"description":"Allow requests to exceed budget with --override flag (default: false)","type":"boolean","default":false},"daily_limit_usd":{"description":"Daily spending limit in USD (default: 10.00)","type":"number","format":"double","default":10.0},"monthly_limit_usd":{"description":"Monthly spending limit in USD (default: 100.00)","type":"number","format":"double","default":100.0},"prices":{"description":"Per-model pricing (USD per 1M tokens)","type":"object","additionalProperties":{"$ref":"#/$defs/ModelPricing"},"default":{}},"warn_at_percent":{"description":"Warn when spending reaches this percentage of limit (default: 80)","type":"integer","format":"uint8","default":80,"maximum":255,"minimum":0}}},"CredentialRefSetting":{"description":"Which credential a decision backend uses. A reference, never a secret.","type":"string"},"CronConfig":{"description":"Cron job configuration (`[cron]` section).","type":"object","properties":{"max_run_history":{"description":"Maximum number of historical cron run records to retain. Default: `50`.","type":"integer","format":"uint32","default":50,"minimum":0}}},"CustomTunnelConfig":{"type":"object","properties":{"health_url":{"description":"Optional URL to check tunnel health","type":["string","null"]},"start_command":{"description":"Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"","type":"string"},"url_pattern":{"description":"Optional regex to extract public URL from command stdout","type":["string","null"]}},"required":["start_command"]},"DecisionBackendConfig":{"description":"The decision backend (`[decision_engine.backend]`).","type":"object","properties":{"circuit_breaker":{"description":"The circuit breaker.","$ref":"#/$defs/CircuitBreakerConfig","default":{"cooldown_secs":60,"failure_threshold":5}},"credential_ref":{"description":"The credential reference: `\"\"`, `\"none\"` or `cred-`.","$ref":"#/$defs/CredentialRefSetting","default":""},"endpoint":{"description":"The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.","type":"string","default":""},"kind":{"description":"`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).","$ref":"#/$defs/BackendSelection","default":"auto"},"max_request_bytes":{"description":"Largest request body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":65536,"minimum":0},"max_response_bytes":{"description":"Largest response body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":262144,"minimum":0},"model":{"description":"The model the endpoint serves; one exact version for a hosted\nservice.","type":"string","default":""},"pinned_snapshot":{"description":"The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.","type":"string"},"remote_enabled":{"description":"Whether decision state may leave this machine. Default `false`.","type":"boolean","default":false},"timeout_ms":{"description":"Transport timeout (10 ms up to the extra latency budget).","type":"integer","format":"uint32","default":250,"minimum":0}}},"DecisionEngineConfig":{"type":"object","properties":{"backend":{"anyOf":[{"$ref":"#/$defs/DecisionBackendConfig"},{"type":"null"}]},"candidates":{"type":"integer","format":"uint32","default":5,"minimum":0},"enabled":{"type":"boolean","default":false},"mode":{"$ref":"#/$defs/DecisionMode","default":"pre"},"observe_queue":{"type":"integer","format":"uint32","default":64,"minimum":0},"prompt_budget_tokens":{"type":"integer","format":"uint32","default":300,"minimum":0},"telemetry_cap":{"type":"integer","format":"uint32","default":1000,"minimum":0},"timeout_ms":{"type":"integer","format":"uint32","default":1500,"minimum":0},"latency_budget_ms":{"description":"The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.","type":"integer","format":"uint64","default":500,"minimum":0},"token_ratio_limit":{"description":"Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).","type":"number","format":"float","default":0.3499999940395355},"max_candidates":{"description":"The most candidates a turn considers (1 to 32).","type":"integer","format":"uint8","default":12,"maximum":255,"minimum":0}}},"DecisionMode":{"type":"string","enum":["pre","post","both"]},"DeclarationOfConformityConfig":{"type":"object","properties":{"applicable_union_law":{"type":"array","default":[],"items":{"type":"string"}},"artifact_path":{"type":["string","null"],"default":null},"artifact_version":{"type":["string","null"],"default":null},"conformity_assessment_procedure":{"type":["string","null"],"default":null},"conformity_statement":{"type":["string","null"],"default":null},"harmonised_standards":{"type":"array","default":[],"items":{"type":"string"}},"issue_date":{"type":["string","null"],"default":null},"issue_place":{"type":["string","null"],"default":null},"notified_body_certificate":{"type":["string","null"],"default":null},"notified_body_identification_number":{"type":["string","null"],"default":null},"notified_body_name":{"type":["string","null"],"default":null},"personal_data_compliance_statement":{"type":["string","null"],"default":null},"processes_personal_data":{"type":"boolean","default":false},"provider_address":{"type":["string","null"],"default":null},"provider_name":{"type":["string","null"],"default":null},"signer_function":{"type":["string","null"],"default":null},"signer_name":{"type":["string","null"],"default":null},"signer_on_behalf_of":{"type":["string","null"],"default":null},"sole_responsibility_statement":{"type":["string","null"],"default":null},"standards_not_applicable_reason":{"type":["string","null"],"default":null},"system_name":{"type":["string","null"],"default":null},"system_reference":{"type":["string","null"],"default":null},"system_type":{"type":["string","null"],"default":null}}},"DelegateAgentConfig":{"description":"Configuration for a delegate sub-agent used by the `delegate` tool.","type":"object","properties":{"agentic":{"description":"Enable agentic sub-agent mode (multi-turn tool-call loop).","type":"boolean","default":false},"allowed_tools":{"description":"Allowlist of tool names available to the sub-agent in agentic mode.","type":"array","default":[],"items":{"type":"string"}},"api_key":{"description":"Optional API key override","type":["string","null"],"default":null},"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"autonomy":{"description":"The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.","anyOf":[{"$ref":"#/$defs/AutonomyLevel"},{"type":"null"}]},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"enabled":{"description":"Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.","type":"boolean","default":true},"identity_dir":{"description":"Optional identity files directory relative to workspace root.","type":["string","null"],"default":null},"limits":{"$ref":"#/$defs/AgentLimits","default":{"max_concurrent_turns":null,"max_cost_per_day_cents":null}},"max_depth":{"description":"Max recursion depth for nested delegation","type":"integer","format":"uint32","default":8,"minimum":0},"memory_scope":{"description":"Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".","type":["string","null"],"default":null},"model":{"description":"Model name","type":"string"},"provider":{"description":"Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")","type":"string"},"spawn_enabled":{"description":"Whether this agent is allowed to be targeted by sessions_spawn (default: true).","type":["boolean","null"],"default":null},"system_prompt":{"description":"Optional system prompt for the sub-agent","type":["string","null"],"default":null},"temperature":{"description":"Temperature override","type":["number","null"],"format":"double","default":null},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}},"required":["provider","model"]},"DingTalkConfig":{"description":"DingTalk configuration for Stream Mode messaging","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"client_id":{"description":"Client ID (AppKey) from DingTalk developer console","type":"string"},"client_secret":{"description":"Client Secret (AppSecret) from DingTalk developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["client_id","client_secret"]},"DiscordConfig":{"description":"Discord bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Discord user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Discord bot token (from Discord Developer Portal).","type":"string"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"guild_id":{"description":"Optional guild (server) ID to restrict the bot to a single guild.","type":["string","null"]},"listen_to_bots":{"description":"When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.","type":"boolean","default":false}},"required":["bot_token"]},"DmPolicy":{"description":"Policy for direct-message handling.","oneOf":[{"description":"Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).","type":"string","const":"pairing"},{"description":"Accept only senders listed in `allowed_from`.","type":"string","const":"allowlist"},{"description":"Accept any direct sender.","type":"string","const":"open"},{"description":"Ignore direct messages.","type":"string","const":"disabled"}]},"DockerRuntimeConfig":{"description":"Docker runtime configuration (`[runtime.docker]` section).","type":"object","properties":{"allowed_workspace_roots":{"description":"Optional workspace root allowlist for Docker mount validation.","type":"array","default":[],"items":{"type":"string"}},"cpu_limit":{"description":"Optional CPU limit (`None` = no explicit limit).","type":["number","null"],"format":"double","default":1.0},"image":{"description":"Runtime image used to execute shell commands.","type":"string","default":"alpine:3.20"},"memory_limit_mb":{"description":"Optional memory limit in MB (`None` = no explicit limit).","type":["integer","null"],"format":"uint64","default":512,"minimum":0},"mount_workspace":{"description":"Mount configured workspace into `/workspace`.","type":"boolean","default":true},"network":{"description":"Docker network mode (`none`, `bridge`, etc.).","type":"string","default":"none"},"read_only_rootfs":{"description":"Mount root filesystem as read-only.","type":"boolean","default":true}}},"EmailConfig":{"description":"Email channel configuration","type":"object","properties":{"allowed_senders":{"description":"Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)","type":"array","default":[],"items":{"type":"string"}},"from_address":{"description":"From address for outgoing emails","type":"string"},"idle_timeout_secs":{"description":"IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes","type":"integer","format":"uint64","default":1740,"minimum":0},"imap_folder":{"description":"IMAP folder to poll (default: INBOX)","type":"string","default":"INBOX"},"imap_host":{"description":"IMAP server hostname","type":"string"},"imap_port":{"description":"IMAP server port (default: 993 for TLS)","type":"integer","format":"uint16","default":993,"maximum":65535,"minimum":0},"password":{"description":"Email password for authentication","type":"string"},"smtp_host":{"description":"SMTP server hostname","type":"string"},"smtp_port":{"description":"SMTP server port (default: 465 for TLS)","type":"integer","format":"uint16","default":465,"maximum":65535,"minimum":0},"smtp_tls":{"description":"Use TLS for SMTP (default: true)","type":"boolean","default":true},"username":{"description":"Email username for authentication","type":"string"}},"required":["imap_host","smtp_host","username","password","from_address"]},"EmbeddingRouteConfig":{"description":"Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"dimensions":{"description":"Optional embedding dimension override for this route","type":["integer","null"],"format":"uint","default":null,"minimum":0},"hint":{"description":"Route hint name (e.g. \"semantic\", \"archive\", \"faq\")","type":"string"},"model":{"description":"Embedding model to use with that provider","type":"string"},"provider":{"description":"Embedding provider (`none`, `openai`, or `custom:`)","type":"string"}},"required":["hint","provider","model"]},"EuAiActClassificationConfig":{"type":"object","properties":{"assessed_at":{"type":["string","null"],"default":null},"owner":{"type":["string","null"],"default":null},"status":{"$ref":"#/$defs/EuAiActRiskClassification","default":"unclassified"}}},"EuAiActComplianceConfig":{"type":"object","properties":{"classification":{"$ref":"#/$defs/EuAiActClassificationConfig","default":{"assessed_at":null,"owner":null,"status":"unclassified"}},"declaration":{"$ref":"#/$defs/DeclarationOfConformityConfig","default":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null}},"incident_store_path":{"type":["string","null"],"default":null}}},"EuAiActRiskClassification":{"type":"string","enum":["unclassified","high_risk","not_high_risk"]},"FitnessConfig":{"description":"Calendar schedule, evidence thresholds, and retention for fitness v2.","type":"object","properties":{"auto_run":{"description":"Run the daily fitness worker in daemon mode.","type":"boolean","default":true},"max_backfill_days":{"description":"Maximum number of closed days recovered after downtime.","type":"integer","format":"uint32","default":7,"minimum":0},"min_coverage":{"description":"Minimum available metric weight required to publish a final score.","type":"number","format":"double","default":0.6},"min_samples":{"description":"Minimum samples required before an evidence-derived subscore is usable.","type":"integer","format":"uint","default":5,"minimum":0},"retention_days":{"description":"Number of daily JSON reports retained on disk.","type":"integer","format":"uint32","default":180,"minimum":0},"run_at":{"description":"Local wall-clock time (`HH:MM`) at which the previous day is scored.","type":"string","default":"00:10"},"timezone":{"description":"IANA timezone used to define closed calendar days.","type":"string","default":"UTC"}}},"GatewayConfig":{"description":"Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.","type":"object","properties":{"allow_public_bind":{"description":"Allow binding to non-localhost without a tunnel (default: false)","type":"boolean","default":false},"api_rate_limit_per_minute":{"description":"Max `/api/*` requests per minute per authenticated token.","type":"integer","format":"uint32","default":60,"minimum":0},"channel_webhook_dedup_ttl_secs":{"description":"How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.","type":"integer","format":"uint64","default":86400,"minimum":0},"host":{"description":"Gateway host (default: 127.0.0.1)","type":"string","default":"127.0.0.1"},"idempotency_max_keys":{"description":"Maximum distinct idempotency keys retained in memory.","type":"integer","format":"uint","default":10000,"minimum":0},"idempotency_ttl_secs":{"description":"TTL for webhook idempotency keys.","type":"integer","format":"uint64","default":300,"minimum":0},"pair_rate_limit_per_minute":{"description":"Max `/pair` requests per minute per client key.","type":"integer","format":"uint32","default":10,"minimum":0},"paired_tokens":{"description":"Paired bearer tokens (managed automatically, not user-edited)","type":"array","default":[],"items":{"type":"string"}},"port":{"description":"Gateway port (default: 16830)","type":"integer","format":"uint16","default":16830,"maximum":65535,"minimum":0},"rate_limit_max_keys":{"description":"Maximum distinct client keys tracked by gateway rate limiter maps.","type":"integer","format":"uint","default":10000,"minimum":0},"require_pairing":{"description":"Require pairing before accepting requests (default: true)","type":"boolean","default":true},"targeted_agents":{"description":"Rollout switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). While false, any otherwise-valid\nnamed target answers 409 `agent_disabled` and never runs as Main.","type":"boolean","default":false},"trust_forwarded_headers":{"description":"Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.","type":"boolean","default":false},"webhook_rate_limit_per_minute":{"description":"Max `/webhook` requests per minute per client key.","type":"integer","format":"uint32","default":60,"minimum":0}}},"GroupPolicy":{"description":"Policy for group-message handling.","oneOf":[{"description":"Accept only groups listed in `group_allow_from`.","type":"string","const":"allowlist"},{"description":"Accept any group.","type":"string","const":"open"},{"description":"Ignore group messages.","type":"string","const":"disabled"}]},"GroupReplyMode":{"description":"How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.","oneOf":[{"description":"Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).","type":"string","const":"off"},{"description":"Reply only when the bot is @-mentioned (legacy `mention_only = true`).","type":"string","const":"mention-only"},{"description":"Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).","type":"string","const":"smart"}]},"HeartbeatConfig":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]` section).","type":"object","properties":{"active_hours":{"description":"Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.","type":"array","default":[8,23],"items":{"type":"integer","format":"uint8","maximum":255,"minimum":0}},"interval_minutes":{"description":"Interval in minutes between heartbeat pings. Default: `30`.","type":"integer","format":"uint32","default":30,"minimum":0},"prompt":{"description":"Prompt used by heartbeat worker when dispatching tasks.","type":"string","default":"Check HEARTBEAT.md and follow instructions."}}},"HttpRequestConfig":{"description":"HTTP request tool configuration (`[http_request]` section).","type":"object","properties":{"max_response_size":{"description":"Maximum response size in bytes (default: 1MB)","type":"integer","format":"uint","default":1000000,"minimum":0},"timeout_secs":{"description":"Request timeout in seconds (default: 30)","type":"integer","format":"uint64","default":30,"minimum":0}}},"IMessageConfig":{"description":"iMessage channel configuration (macOS only).","type":"object","properties":{"allowed_contacts":{"description":"Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.","type":"array","items":{"type":"string"}},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["allowed_contacts"]},"IdentityBindingConfig":{"description":"Startup identity binding entry (`[[identity_bindings]]`).","type":"object","properties":{"channel":{"type":"string"},"channel_account":{"type":"string"},"display_name":{"type":["string","null"],"default":null},"user_id":{"type":"string"}},"required":["user_id","channel","channel_account"]},"IdentityConfig":{"description":"Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.","type":"object","properties":{"aieos_inline":{"description":"Inline AIEOS JSON (alternative to file path)","type":["string","null"],"default":null},"aieos_path":{"description":"Path to AIEOS JSON file (relative to workspace)","type":["string","null"],"default":null},"format":{"description":"Identity format: \"openclaw\" (default) or \"aieos\"","type":"string","default":"openclaw"}}},"InteractionNoticeApplicability":{"type":"string","enum":["required","not_applicable"]},"InteractionNoticeConfig":{"type":"object","properties":{"applicability":{"$ref":"#/$defs/InteractionNoticeApplicability","default":"required"},"exception_owner":{"type":["string","null"],"default":null},"exception_reviewed_at":{"type":["string","null"],"default":null},"text":{"type":"string","default":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers."},"version":{"type":"string","default":"1"}}},"IrcConfig":{"description":"IRC channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed nicknames (case-insensitive) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"channels":{"description":"Channels to join on connect","type":"array","default":[],"items":{"type":"string"}},"mention_only":{"description":"When true, only process channel/group messages that mention the bot.","type":"boolean","default":false},"nickname":{"description":"Bot nickname","type":"string"},"nickserv_password":{"description":"NickServ IDENTIFY password","type":["string","null"]},"port":{"description":"IRC server port (default: 6697 for TLS)","type":"integer","format":"uint16","default":6697,"maximum":65535,"minimum":0},"sasl_password":{"description":"SASL PLAIN password (IRCv3)","type":["string","null"]},"server":{"description":"IRC server hostname","type":"string"},"server_password":{"description":"Server password (for bouncers like ZNC)","type":["string","null"]},"username":{"description":"Username (defaults to nickname if not set)","type":["string","null"]},"verify_tls":{"description":"Verify TLS certificate (default: true)","type":["boolean","null"]}},"required":["server","nickname"]},"LarkConfig":{"description":"Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from Lark/Feishu developer console","type":"string"},"app_secret":{"description":"App Secret from Lark/Feishu developer console","type":"string"},"encrypt_key":{"description":"Encrypt key for webhook message decryption (optional)","type":["string","null"],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"port":{"description":"HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"receive_mode":{"description":"Event receive mode: \"websocket\" (default) or \"webhook\"","$ref":"#/$defs/LarkReceiveMode","default":"websocket"},"use_feishu":{"description":"Whether to use the Feishu (Chinese) endpoint instead of Lark (International)","type":"boolean","default":false},"verification_token":{"description":"Verification token for webhook validation (optional)","type":["string","null"],"default":null}},"required":["app_id","app_secret"]},"LarkReceiveMode":{"description":"How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.","type":"string","enum":["websocket","webhook"]},"LinqConfig":{"type":"object","properties":{"allowed_senders":{"description":"Allowed sender handles (phone numbers) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"api_token":{"description":"Linq Partner API token (Bearer auth)","type":"string"},"from_phone":{"description":"Phone number to send from (E.164 format)","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"signing_secret":{"description":"Webhook signing secret for signature verification","type":["string","null"],"default":null}},"required":["api_token","from_phone"]},"MattermostConfig":{"description":"Mattermost bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Mattermost user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Mattermost bot access token.","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.","type":["boolean","null"],"default":null},"thread_replies":{"description":"When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.","type":["boolean","null"],"default":null},"url":{"description":"Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).","type":"string"}},"required":["url","bot_token"]},"McpConfig":{"type":"object","properties":{"servers":{"description":"Named MCP server definitions","type":"object","additionalProperties":{"$ref":"#/$defs/McpServerConfig"},"default":{}},"workspace_servers":{"description":"Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.","$ref":"#/$defs/WorkspaceMcpServers"}}},"McpServerConfig":{"type":"object","properties":{"allow_tools":{"description":"Optional allow-list of exposed tools (empty = all)","type":"array","default":[],"items":{"type":"string"}},"args":{"description":"Command args for stdio mode","type":"array","default":[],"items":{"type":"string"}},"command":{"description":"Command for stdio mode","type":["string","null"],"default":null},"deny_tools":{"description":"Optional deny-list of exposed tools","type":"array","default":[],"items":{"type":"string"}},"env":{"description":"Environment variables for stdio mode","type":"object","additionalProperties":{"type":"string"},"default":{}},"request_timeout_ms":{"description":"Request timeout in milliseconds","type":"integer","format":"uint64","default":30000,"minimum":0},"startup_timeout_ms":{"description":"Startup timeout in milliseconds","type":"integer","format":"uint64","default":10000,"minimum":0},"tool_name_prefix":{"description":"Prefix used in tool naming and routing","type":"string","default":"mcp"},"transport":{"description":"Transport type: stdio or http","$ref":"#/$defs/McpTransport","default":"stdio"},"url":{"description":"URL for HTTP mode (streamable HTTP endpoint)","type":["string","null"],"default":null},"working_dir":{"description":"Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).","type":["string","null"]}}},"McpServerRuntimeConfig":{"type":"object","properties":{"allowed_origins":{"description":"Allowed browser origins for future streamable HTTP clients.","type":"array","default":["claude.ai","openai.com","localhost"],"items":{"type":"string"}},"bind":{"description":"Advertised bind address. The gateway may still be started with a CLI port override.","type":"string","default":"127.0.0.1:16831"},"exposed_tools":{"description":"Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.","type":"array","default":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"items":{"type":"string"}},"jwt_algorithms":{"description":"Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.","type":"array","default":["RS256"],"items":{"type":"string"}},"jwt_audience":{"description":"Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.","type":["string","null"],"default":null},"jwt_issuer":{"description":"Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.","type":["string","null"],"default":null},"jwt_jwks":{"description":"Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.","type":["string","null"],"default":null},"jwt_jwks_cache_ttl_secs":{"description":"Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.","type":"integer","format":"uint64","default":300,"minimum":0},"jwt_jwks_uri":{"description":"Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.","type":["string","null"],"default":null},"jwt_public_key_pem":{"description":"PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.","type":["string","null"],"default":null},"rate_limit_rps":{"description":"Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.","type":"integer","format":"uint32","default":10,"minimum":0},"require_auth":{"description":"Require an authenticated external identity for mutating calls.","type":"boolean","default":true}}},"McpTransport":{"type":"string","enum":["stdio","http"]},"MediaConfig":{"description":"Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.","type":"object","properties":{"audio_model":{"description":"Audio model name (Ollama model or OpenAI model). Default: \"whisper\".","type":"string","default":"whisper"},"audio_ollama_url":{"description":"Ollama base URL for audio transcription. Default: \"http://localhost:11434\".","type":"string","default":"http://localhost:11434"},"audio_provider":{"description":"Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".","type":"string","default":"none"},"max_audio_size_mb":{"description":"Maximum audio attachment size in MiB. Default: 20.","type":"integer","format":"uint","default":20,"minimum":0},"max_video_size_mb":{"description":"Maximum video attachment size in MiB. Default: 50.","type":"integer","format":"uint","default":50,"minimum":0},"video_max_frames":{"description":"Maximum video frames to extract per video. Default: 4.","type":"integer","format":"uint","default":4,"minimum":0},"video_provider":{"description":"Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".","type":"string","default":"none"}}},"MemoryConfig":{"description":"Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.","type":"object","properties":{"acl_enabled":{"description":"Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.","type":"boolean","default":false},"archive_after_days":{"description":"Archive daily/session files older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"auto_hydrate":{"description":"Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing","type":"boolean","default":true},"auto_save":{"description":"Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.","type":"boolean","default":true},"backend":{"description":"\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).","type":"string","default":"sqlite"},"conversation_retention_days":{"description":"For sqlite backend: prune conversation rows older than this many days","type":"integer","format":"uint32","default":3,"minimum":0},"daily_retention_days":{"description":"For sqlite backend: prune daily rows older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"embedding_cache_size":{"description":"Max embedding cache entries before LRU eviction","type":"integer","format":"uint","default":10000,"minimum":0},"embedding_dimensions":{"description":"Embedding vector dimensions","type":"integer","format":"uint","default":384,"minimum":0},"embedding_model":{"description":"Embedding model name (e.g. \"text-embedding-3-small\")","type":"string","default":"prx-local-hash-v1"},"embedding_provider":{"description":"Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"","type":"string","default":"local"},"events":{"description":"Raw/quasi-raw message event recording controls (`[memory.events]`).","$ref":"#/$defs/MemoryEventsConfig","default":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true}},"keyword_weight":{"description":"Weight for keyword BM25 in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.3},"legacy_conversation_turns_visible":{"description":"Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.","type":"boolean","default":true},"lucid_budget":{"description":"Token budget for lucid (replaces OPENPRX_LUCID_BUDGET)","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"lucid_cmd":{"description":"Path to lucid binary (replaces OPENPRX_LUCID_CMD)","type":["string","null"],"default":null},"lucid_failure_cooldown_ms":{"description":"Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)","type":"integer","format":"uint64","default":60000,"minimum":0},"lucid_local_hit_threshold":{"description":"Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)","type":"integer","format":"uint","default":3,"minimum":0},"lucid_recall_timeout_ms":{"description":"Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)","type":"integer","format":"uint64","default":5000,"minimum":0},"lucid_store_timeout_ms":{"description":"Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)","type":"integer","format":"uint64","default":3000,"minimum":0},"min_relevance_score":{"description":"Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4","type":"number","format":"double","default":0.4},"purge_after_days":{"description":"Purge archived files older than this many days","type":"integer","format":"uint32","default":30,"minimum":0},"semantic":{"description":"Semantic memory promotion controls (`[memory.semantic]`).","$ref":"#/$defs/MemorySemanticConfig","default":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30}},"sqlite_open_timeout_secs":{"description":"For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"sqlite_read_pool_size":{"description":"For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"vector_candidate_cap":{"description":"How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.","type":"integer","format":"uint","default":2000,"minimum":0},"vector_weight":{"description":"Weight for vector similarity in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.7}}},"MemoryEventsConfig":{"description":"Raw message event recording configuration (`[memory.events]`).","type":"object","properties":{"record_assistant_messages":{"description":"Record assistant replies.","type":"boolean","default":true},"record_tool_events":{"description":"Record tool/event payloads by default.","type":"boolean","default":false},"record_user_messages":{"description":"Record inbound/user messages.","type":"boolean","default":true}}},"MemorySemanticConfig":{"description":"Semantic memory promotion configuration (`[memory.semantic]`).","type":"object","properties":{"auto_promote_assistant_messages":{"description":"Auto-promote eligible assistant messages. Disabled by default to reduce noise.","type":"boolean","default":false},"auto_promote_user_messages":{"description":"Auto-promote eligible user messages into long-term semantic memories.","type":"boolean","default":true},"min_chars":{"description":"Minimum content length for semantic auto-promotion.","type":"integer","format":"uint","default":30,"minimum":0}}},"MemoryWebhookConfig":{"type":"object","properties":{"bind":{"description":"Socket address for the receiver (e.g. \"0.0.0.0:16899\").","type":"string","default":"0.0.0.0:16899"},"signing_secret":{"description":"Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.","type":["string","null"],"default":null},"token":{"description":"Required bearer token for incoming webhook events.","type":["string","null"],"default":null}}},"ModelOperationSetting":{"description":"The operations a `[[providers.models]]` entry may list.","type":"string","enum":["chat","embedding","decision_endpoint","rerank","image_generation","audio_generation","video_generation"]},"ModelPricing":{"description":"Per-model pricing entry (USD per 1M tokens).","type":"object","properties":{"cache_read":{"description":"Cache read input price per 1M tokens.","type":"number","format":"double","default":0.0},"cache_write":{"description":"Cache write/creation input price per 1M tokens.","type":"number","format":"double","default":0.0},"input":{"description":"Input price per 1M tokens","type":"number","format":"double","default":0.0},"output":{"description":"Output price per 1M tokens","type":"number","format":"double","default":0.0}}},"ModelRouteConfig":{"description":"Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"hint":{"description":"Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")","type":"string"},"level":{"type":["string","null"]},"model":{"description":"Model to use with that provider","type":"string"},"provider":{"description":"Provider to route to (must match a known provider name)","type":"string"},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true,"required":["hint","provider","model"]},"ModelSettings":{"description":"A model level plus explicit parameter overrides in `[model_settings.\"\"]`.","type":"object","properties":{"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"level":{"type":["string","null"]},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true},"MultimodalConfig":{"description":"Multimodal (image) handling configuration (`[multimodal]` section).","type":"object","properties":{"allow_remote_fetch":{"description":"Allow fetching remote image URLs (http/https). Disabled by default.","type":"boolean","default":false},"max_image_size_mb":{"description":"Maximum image payload size in MiB before base64 encoding.","type":"integer","format":"uint","default":5,"minimum":0},"max_images":{"description":"Maximum number of image attachments accepted per request.","type":"integer","format":"uint","default":4,"minimum":0}}},"NextcloudTalkConfig":{"description":"Nextcloud Talk bot configuration (webhook receive + OCS send API).","type":"object","properties":{"allowed_users":{"description":"Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Bot app token used for OCS API bearer auth.","type":"string"},"base_url":{"description":"Nextcloud base URL (e.g. \"https://cloud.example.com\").","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"webhook_secret":{"description":"Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).","type":["string","null"],"default":null}},"required":["base_url","app_token"]},"NgrokTunnelConfig":{"type":"object","properties":{"auth_token":{"description":"ngrok auth token","type":"string"},"domain":{"description":"Optional custom domain","type":["string","null"]}},"required":["auth_token"]},"NodeServerConfig":{"description":"Node daemon runtime config used by `prx-node`.","type":"object","properties":{"allowed_commands":{"description":"Command allowlist matched on first token.\n\nIn restricted mode this list is required unless explicitly set to `[\"*\"]`.","type":"array","default":["echo"],"items":{"type":"string"}},"bearer_token":{"description":"Required bearer token for /rpc.","type":"string","default":""},"blocked_commands":{"description":"Command denylist matched on first token. Always enforced.","type":"array","default":[],"items":{"type":"string"}},"exec_timeout_ms":{"description":"Default command timeout in milliseconds.","type":"integer","format":"uint64","default":15000,"minimum":0},"hmac_secret":{"description":"Optional HMAC signing secret.","type":["string","null"],"default":null},"listen_addr":{"description":"Listen address for node daemon.","type":"string","default":"127.0.0.1:8787"},"max_concurrent_tasks":{"description":"Maximum number of concurrent async command tasks.","type":"integer","format":"uint","default":8,"minimum":0},"max_output_bytes":{"description":"Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.","type":"integer","format":"uint","default":1048576,"minimum":0},"sandbox_root":{"description":"Sandbox root directory for read/write/cwd constraints.","type":"string","default":"."},"task_result_ttl_ms":{"description":"TTL for completed task results in milliseconds.","type":"integer","format":"uint64","default":3600000,"minimum":0},"tls_cert":{"description":"TLS certificate path (PEM).","type":["string","null"],"default":null},"tls_key":{"description":"TLS private key path (PEM).","type":["string","null"],"default":null},"tls_required":{"description":"Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.","type":"boolean","default":true}}},"NodesConfig":{"description":"Remote node proxy configuration for core-side RPC calls and node daemon defaults.","type":"object","properties":{"nodes":{"description":"Configured remote nodes.","type":"array","default":[],"items":{"$ref":"#/$defs/RemoteNodeConfig"}},"request_timeout_ms":{"description":"Default request timeout for node RPC calls.","type":"integer","format":"uint64","default":15000,"minimum":0},"retry_max":{"description":"Default max retries for node RPC calls.","type":"integer","format":"uint8","default":2,"maximum":255,"minimum":0},"server":{"description":"Embedded node server defaults used by `prx-node`.","$ref":"#/$defs/NodeServerConfig","default":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}}},"ObservabilityConfig":{"description":"Observability backend configuration (`[observability]` section).","type":"object","properties":{"backend":{"description":"\"none\" | \"log\" | \"prometheus\" | \"otel\"","type":"string","default":"none"},"otel_endpoint":{"description":"OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".","type":["string","null"],"default":null},"otel_service_name":{"description":"Service name reported to the OTel collector. Defaults to \"prx\".","type":["string","null"],"default":null}}},"OllamaProviderConfig":{"description":"Ollama-specific request options (`[providers.ollama]`).","type":"object","properties":{"num_ctx":{"description":"Explicit context window sent as Ollama `options.num_ctx`.","type":["integer","null"],"format":"uint","default":null,"minimum":0}}},"OsPagingConfig":{"description":"Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.","type":"object","properties":{"eviction_threshold":{"description":"Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.","type":"number","format":"double","default":0.7},"keep_recent_messages":{"description":"Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).","type":"integer","format":"uint","default":12,"minimum":0},"max_recalled_pages":{"description":"Maximum number of evicted pages (document chunks) recalled per turn.","type":"integer","format":"uint","default":10,"minimum":0},"proactive_retrieval":{"description":"Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.","type":"boolean","default":true},"retrieval_injection_role":{"description":"Role under which recalled pages are injected.","$ref":"#/$defs/RetrievalInjectionRole","default":"system"}}},"PluginsConfig":{"description":"WASM plugin runtime configuration.","type":"object","properties":{"enabled":{"description":"Load WASM plugins from `/plugins`. Default: `false`.","type":"boolean","default":false}},"additionalProperties":false},"ProviderModelConfig":{"description":"One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.","type":"object","properties":{"context_window":{"description":"The model's context window in tokens.","type":["integer","null"],"format":"uint32","minimum":0},"model":{"description":"The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.","type":["string","null"]},"native_tools":{"description":"Whether the model accepts native tool calls.","type":["boolean","null"]},"operations":{"description":"The complete list of operations the model executes; every operation not\nlisted is unsupported.","type":["array","null"],"items":{"$ref":"#/$defs/ModelOperationSetting"}},"provider":{"description":"The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.","type":"string"},"streaming":{"description":"Whether the model streams responses.","type":["boolean","null"]},"structured_output":{"description":"Whether the model honours a JSON-schema response format.","type":["boolean","null"]},"tool_call_dialect":{"description":"The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema_dialect":{"description":"The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]},"vision_input":{"description":"Whether the model accepts image input.","type":["boolean","null"]}},"required":["provider"]},"ProviderToolDialectConfig":{"description":"One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.","type":"object","properties":{"model":{"description":"The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.","type":["string","null"]},"provider":{"description":"The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.","type":"string"},"tool_call":{"description":"The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema":{"description":"The tool-schema dialect the endpoint accepts.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]}},"required":["provider"]},"ProvidersConfig":{"description":"Provider-specific runtime configuration (`[providers]`).","type":"object","properties":{"models":{"description":"Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.","type":"array","items":{"$ref":"#/$defs/ProviderModelConfig"}},"ollama":{"description":"Ollama-specific request options (`[providers.ollama]`).","$ref":"#/$defs/OllamaProviderConfig","default":{"num_ctx":null}},"tool_dialects":{"description":"Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).","type":"array","items":{"$ref":"#/$defs/ProviderToolDialectConfig"}}}},"ProxyConfig":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).","type":"object","properties":{"all_proxy":{"description":"Fallback proxy URL for all schemes.","type":["string","null"],"default":null},"http_proxy":{"description":"Proxy URL for HTTP requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"https_proxy":{"description":"Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"no_proxy":{"description":"No-proxy bypass list. Same format as NO_PROXY.","type":"array","default":[],"items":{"type":"string"}},"scope":{"description":"Proxy application scope.","$ref":"#/$defs/ProxyScope","default":"prx"},"services":{"description":"Service selectors used when scope = \"services\".","type":"array","default":[],"items":{"type":"string"}}}},"ProxyScope":{"description":"Proxy application scope — determines which outbound traffic uses the proxy.","oneOf":[{"description":"Use system environment proxy variables only.","type":"string","const":"environment"},{"description":"Apply proxy to all OpenPRX-managed HTTP traffic (default).","type":"string","const":"prx"},{"description":"Apply proxy only to explicitly listed service selectors.","type":"string","const":"services"}]},"QQConfig":{"description":"QQ Official Bot configuration (Tencent QQ Bot SDK)","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs. Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from QQ Bot developer console","type":"string"},"app_secret":{"description":"App Secret from QQ Bot developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["app_id","app_secret"]},"QueryClassificationConfig":{"description":"Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.","type":"object","properties":{"rules":{"description":"Classification rules evaluated in priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/ClassificationRule"}}}},"RamfluxAccountConfig":{"description":"Persona for one ramflux AI account. Missing fields fall back to the global agent.","type":"object","properties":{"cross_conversation_retrieval":{"description":"Cross-conversation memory retrieval. Off unless the owner sets it.","type":"boolean","default":false},"model":{"type":["string","null"],"default":null},"provider":{"type":["string","null"],"default":null},"scope_profile":{"type":["string","null"],"default":null},"system_prompt_file":{"description":"Path to a system-prompt file. Relative paths are resolved from the workspace.","type":["string","null"],"default":null}},"additionalProperties":false},"RamfluxAttachmentFetch":{"description":"Per-turn caps for `attachment.fetch`.","type":"object","properties":{"max_bytes":{"type":"integer","format":"uint64","default":5242880,"minimum":0},"max_per_turn":{"type":"integer","format":"uint8","default":4,"maximum":255,"minimum":0}},"additionalProperties":false},"RamfluxAuthorizationMode":{"description":"How prx combines its own setting with `bridge.hello.authorization`.","oneOf":[{"description":"Use the agent-host value. Until hello arrives, the effective mode is supervised.","type":"string","const":"follow_rf"},{"description":"Always supervised, even when the agent-host declares full.","type":"string","const":"supervised"},{"description":"Full only when the agent-host also declares full. Config alone never yields full.","type":"string","const":"full"}]},"RamfluxConfig":{"description":"Local ramflux agent-host bridge (`[channels_config.ramflux]`).","type":"object","properties":{"accounts":{"type":"object","additionalProperties":{"$ref":"#/$defs/RamfluxAccountConfig"},"default":{}},"allowed_block_types":{"type":"array","default":["Text","Markdown","Heading","KeyValue","Metric","List","TableFallback","Form","Input","Select","Progress","LogStream","Warning","Error","Success","Approval","ActionGroup","FilePreview","Fallback"],"items":{"type":"string"}},"attachment_fetch":{"$ref":"#/$defs/RamfluxAttachmentFetch","default":{"max_bytes":5242880,"max_per_turn":4}},"authorization_mode":{"$ref":"#/$defs/RamfluxAuthorizationMode","default":"follow_rf"},"encrypt_at_rest":{"type":"boolean","default":true},"max_in_flight_per_conversation":{"type":"integer","format":"uint8","default":1,"maximum":255,"minimum":0},"on_new_message":{"$ref":"#/$defs/RamfluxOnNewMessage","default":"queue"},"socket_path":{"description":"Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.","type":["string","null"],"default":null},"surface_limits":{"$ref":"#/$defs/RamfluxSurfaceLimits","default":{"max_actions":16,"max_blocks":32,"max_bytes":65536}},"turn_wall_clock_secs":{"description":"Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.","type":"integer","format":"uint64","default":120,"minimum":0}},"additionalProperties":false},"RamfluxOnNewMessage":{"description":"What to do with a new inbound message while a turn for that conversation is running.","type":"string","enum":["queue","interrupt"]},"RamfluxSurfaceLimits":{"description":"Limits for `reply.surface` blocks and actions.","type":"object","properties":{"max_actions":{"type":"integer","format":"uint32","default":16,"minimum":0},"max_blocks":{"type":"integer","format":"uint32","default":32,"minimum":0},"max_bytes":{"type":"integer","format":"uint32","default":65536,"minimum":0}},"additionalProperties":false},"ReliabilityCircuitBreakerConfig":{"description":"Process-local provider circuit policy (`[reliability.circuit_breaker]`).","type":"object","properties":{"enabled":{"description":"Enable protection for factory-built provider chains.","type":"boolean","default":true},"failure_threshold":{"description":"Consecutive transient failures that open a circuit (at least 1).","type":"integer","format":"uint32","default":5,"minimum":0},"max_open_secs":{"description":"Maximum doubled window, between open_secs and 3600 seconds.","type":"integer","format":"uint64","default":300,"minimum":0},"open_secs":{"description":"Initial open window in seconds (at least 1).","type":"integer","format":"uint64","default":30,"minimum":0}}},"ReliabilityConfig":{"description":"Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.","type":"object","properties":{"acknowledge_single_provider_risk":{"description":"Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.","type":"boolean","default":false},"api_keys":{"description":"Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.","type":"array","default":[],"items":{"type":"string"}},"channel_initial_backoff_secs":{"description":"Initial backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":2,"minimum":0},"channel_max_backoff_secs":{"description":"Max backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":60,"minimum":0},"circuit_breaker":{"description":"Per-provider consecutive failure protection.","$ref":"#/$defs/ReliabilityCircuitBreakerConfig","default":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30}},"fallback_providers":{"description":"Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).","type":"array","default":[],"items":{"type":"string"}},"model_fallbacks":{"description":"Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`","type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"default":{}},"provider_backoff_ms":{"description":"Base backoff (ms) for provider retry delay.","type":"integer","format":"uint64","default":500,"minimum":0},"provider_retries":{"description":"Retries per provider before failing over.","type":"integer","format":"uint32","default":2,"minimum":0},"scheduler_poll_secs":{"description":"Scheduler polling cadence in seconds.","type":"integer","format":"uint64","default":15,"minimum":0},"scheduler_retries":{"description":"Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.","type":"integer","format":"uint32","default":2,"minimum":0}}},"RemoteNodeConfig":{"description":"A remote node target for core-side node proxy calls.","type":"object","properties":{"bearer_token":{"description":"Bearer token for node RPC authentication.","type":"string"},"endpoint":{"description":"Base endpoint (e.g. \"http://127.0.0.1:8787\").","type":"string"},"hmac_secret":{"description":"Optional request signing key (HMAC-SHA256).","type":["string","null"],"default":null},"id":{"description":"Stable node ID used by the nodes tool.","type":"string"},"retry_max":{"description":"Optional per-node retry override.","type":["integer","null"],"format":"uint8","default":null,"maximum":255,"minimum":0},"timeout_ms":{"description":"Optional per-node timeout override.","type":["integer","null"],"format":"uint64","default":null,"minimum":0}},"required":["id","endpoint","bearer_token"]},"RetrievalInjectionRole":{"description":"Where recalled context pages are injected back into the request.","oneOf":[{"description":"Inject recalled pages as a leading `system` message (not user-visible).","type":"string","const":"system"},{"description":"Inject recalled pages as a leading `user` message.","type":"string","const":"user"}]},"RouterConfig":{"description":"Heuristic LLM router configuration (`[router]` section).","type":"object","properties":{"alpha":{"description":"Similarity score weight. Phase 1 keeps this at `0.0`.","type":"number","format":"float","default":0.0},"beta":{"description":"Capability score weight.","type":"number","format":"float","default":0.5},"delta":{"description":"Cost penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"epsilon":{"description":"Latency penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"gamma":{"description":"Elo score weight.","type":"number","format":"float","default":0.30000001192092896},"knn_k":{"description":"Number of nearest neighbors considered for voting. Default: `7`.","type":"integer","format":"uint","default":7,"minimum":0},"knn_min_records":{"description":"Minimum history records before KNN affects routing. Default: `10`.","type":"integer","format":"uint","default":10,"minimum":0},"models":{"description":"Candidate model registry.","type":"array","default":[],"items":{"$ref":"#/$defs/RouterModelConfig"}}}},"RouterModelConfig":{"description":"Static router metadata for one model candidate.","type":"object","properties":{"categories":{"description":"Capability categories such as `conversation`, `code`, or `analysis`.","type":"array","default":[],"items":{"type":"string"}},"cost_per_million_tokens":{"description":"USD cost per million tokens.","type":"number","format":"float","default":0.0},"elo_rating":{"description":"Initial Elo rating.","type":"number","format":"float","default":1000.0},"latency_ms":{"description":"Average latency in milliseconds.","type":"integer","format":"uint32","default":2000,"minimum":0},"max_context":{"description":"Maximum context window in tokens.","type":"integer","format":"uint","default":1000000,"minimum":0},"model_id":{"description":"Model identifier without provider prefix.","type":"string"},"provider":{"description":"Provider identifier.","type":"string"},"reserved_output_tokens":{"description":"Output tokens reserved for this model when planning input context.","type":["integer","null"],"format":"uint","minimum":0}},"required":["model_id","provider"]},"RuntimeConfig":{"description":"Runtime adapter configuration (`[runtime]` section).","type":"object","properties":{"codex_reasoning_effort":{"description":"Codex reasoning effort","type":["string","null"],"default":null},"codex_stream_idle_timeout_secs":{"description":"Codex stream idle timeout in seconds","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"docker":{"description":"Docker runtime settings (used when `kind = \"docker\"`).","$ref":"#/$defs/DockerRuntimeConfig","default":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true}},"idle_hang_secs":{"description":"Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"kind":{"description":"Runtime kind (`native` | `docker`).","type":"string","default":"native"},"long_task_warn_secs":{"description":"Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"managed_cgroup_root":{"description":"Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.","type":["string","null"],"default":null},"max_blocking_threads":{"description":"Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"reasoning_enabled":{"description":"Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported","type":["boolean","null"],"default":null},"shell_env_allowlist":{"description":"Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.","type":"array","default":[],"items":{"type":"string"}},"workdir":{"description":"Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.","type":["string","null"],"default":null}}},"SchedulerConfig":{"description":"Scheduler configuration for periodic task execution (`[scheduler]` section).","type":"object","properties":{"claim_lease_secs":{"description":"Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.","type":"integer","format":"uint64","default":90,"minimum":0},"max_tasks":{"description":"Maximum number of persisted scheduled tasks.","type":"integer","format":"uint","default":64,"minimum":0}}},"ScopeConfig":{"description":"Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```","type":"object","properties":{"assign_owners":{"description":"Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.","type":"array","default":[],"items":{"type":"string"}},"default":{"description":"Default action when no rule matches: \"allow\" (default) or \"deny\".","$ref":"#/$defs/ScopeDefault","default":"allow"},"rules":{"description":"Ordered list of scope rules evaluated top-to-bottom.","type":"array","default":[],"items":{"$ref":"#/$defs/ScopeRule"}}}},"ScopeDefault":{"description":"What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.","oneOf":[{"description":"Unmatched tool calls are allowed (the default).","type":"string","const":"allow"},{"description":"Unmatched tool calls are refused.","type":"string","const":"deny"}]},"ScopeRule":{"description":"A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.","type":"object","properties":{"assign_allow":{"description":"Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".","type":"array","default":[],"items":{"type":"string"}},"assign_deny":{"description":"Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.","type":"array","default":[],"items":{"type":"string"}},"channel":{"description":"Match by channel name: \"signal\", \"telegram\", \"discord\", etc.","type":["string","null"]},"chat_type":{"description":"Match by chat type: \"direct\", \"group\", or \"*\" for any type.","type":["string","null"]},"send_allow":{"description":"Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.","type":"array","default":[],"items":{"type":"string"}},"send_deny":{"description":"Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.","type":"array","default":[],"items":{"type":"string"}},"tools_allow":{"description":"Tool whitelist: only these tools are allowed (empty = all tools permitted).","type":"array","default":[],"items":{"type":"string"}},"tools_deny":{"description":"Tool blacklist: these tools are denied regardless of allow list.","type":"array","default":[],"items":{"type":"string"}},"user":{"description":"Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.","type":["string","null"]}}},"SecretsConfig":{"description":"Secrets encryption configuration (`[secrets]` section).","type":"object","properties":{"encrypt":{"description":"Enable encryption for API keys and tokens in config.toml","type":"boolean","default":true}}},"SecurityConfig":{"description":"Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.","type":"object","properties":{"audit":{"description":"Audit logging configuration","$ref":"#/$defs/AuditConfig","default":{"log_path":"audit.log","max_size_mb":100}},"workspace_hooks":{"description":"Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.","$ref":"#/$defs/WorkspaceHooks"}}},"SelfSystemConfig":{"description":"Self-system experimental automation config (`[self_system]`).","type":"object","properties":{"evolution_config_path":{"description":"Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG)","type":["string","null"],"default":null},"evolution_debug_raw":{"description":"Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW)","type":"boolean","default":false},"evolution_interval_hours":{"description":"Evolution scheduler interval in hours (daemon mode).","type":"integer","format":"uint32","default":24,"minimum":0},"evolution_judge_timeout_secs":{"description":"Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.","type":"integer","format":"uint64","default":180,"minimum":0},"evolution_model_max_micro_usd":{"description":"Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.","type":"integer","format":"uint64","default":0,"minimum":0},"evolution_model_max_tokens":{"description":"Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.","type":"integer","format":"uint64","default":16384,"minimum":0},"fitness":{"description":"Daily fitness snapshot policy.","$ref":"#/$defs/FitnessConfig","default":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"}},"fitness_interval_hours":{"description":"Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.","type":"integer","format":"uint64","default":24,"minimum":0}}},"SessionsSpawnConfig":{"description":"Sessions spawn configuration (`[sessions_spawn]` section).","type":"object","properties":{"cleanup_on_complete":{"description":"Remove worker workspace directory after process-mode completion.","type":"boolean","default":true},"default_mode":{"description":"Default execution mode for sessions_spawn (`task` or `process`).","type":"string","default":"task"},"process_memory_strategy":{"description":"Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.","type":"string","default":"shared_fabric"},"worker_workspace_root":{"description":"Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.","type":["string","null"],"default":null}}},"SignalConfig":{"type":"object","properties":{"account":{"description":"E.164 phone number of the signal-cli account (e.g. \"+1234567890\").","type":"string"},"allowed_from":{"description":"Allowed sender phone numbers (E.164) or \"*\" for all.","type":"array","default":[],"items":{"type":"string"}},"cli_path":{"description":"Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).","type":["string","null"],"default":null},"daemon_http_port":{"description":"Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"daemon_mode":{"description":"Deprecated: ignored. Accepted for backward compatibility with older config files.","type":["boolean","null"],"default":null},"data_dir":{"description":"signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_id":{"description":"Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group","type":["string","null"],"default":null},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"http_url":{"description":"Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.","type":"string","default":"http://localhost:8080"},"ignore_attachments":{"description":"Skip messages that are attachment-only (no text body).","type":"boolean","default":false},"ignore_stories":{"description":"Skip incoming story messages.","type":"boolean","default":false},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"mode":{"description":"Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.","type":["string","null"],"default":null},"startup_timeout_ms":{"description":"Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.","type":"integer","format":"uint64","default":30000,"minimum":0},"storm_protection":{"description":"Signal ingress storm protection controls.","$ref":"#/$defs/SignalStormProtectionConfig","default":{"abnormal_threshold":10,"abnormal_window_secs":60,"breaker_duration_secs":300,"dedupe_ttl_secs":60,"min_reply_interval_secs":2}}},"required":["account"]},"SignalStormProtectionConfig":{"type":"object","properties":{"abnormal_threshold":{"description":"Non-user event threshold within `abnormal_window_secs` before tripping the breaker.","type":"integer","format":"uint","default":10,"minimum":0},"abnormal_window_secs":{"description":"Sliding window in seconds for non-user event counting.","type":"integer","format":"uint64","default":60,"minimum":0},"breaker_duration_secs":{"description":"Circuit breaker duration in seconds after threshold is reached.","type":"integer","format":"uint64","default":300,"minimum":0},"dedupe_ttl_secs":{"description":"Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.","type":"integer","format":"uint64","default":60,"minimum":0},"min_reply_interval_secs":{"description":"Minimum interval in seconds between replies for the same `(channel + reply_target)`.","type":"integer","format":"uint64","default":2,"minimum":0}}},"SkillRagConfig":{"description":"Dynamic skill retrieval configuration (`[skill_rag]` section).","type":"object","properties":{"top_k":{"description":"How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).","type":"integer","format":"uint","default":32,"minimum":0}}},"SkillSuiteRegistration":{"description":"The frozen suite that governs one skill's proposals.","type":"object","properties":{"skill_id":{"description":"The skill the suite governs.","type":"string"},"suite_digest":{"description":"SHA-256 digest (64 lowercase hex digits) of the frozen suite.","type":"string"}},"additionalProperties":false,"required":["skill_id","suite_digest"]},"SkillsConfig":{"description":"Skills loading configuration (`[skills]` section).","type":"object","properties":{"open_skills_dir":{"description":"Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.","type":["string","null"],"default":null},"openclaw_skills_dir":{"description":"Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.","type":["string","null"],"default":null}}},"SkillsLifecycleConfig":{"description":"`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.","type":"object","properties":{"allow_executable_proposals":{"description":"Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.","type":"boolean","default":false},"enabled":{"description":"Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.","type":"boolean","default":false},"max_concurrent_evaluations":{"description":"Most evaluations running at once.","type":"integer","format":"uint32","default":1,"minimum":0},"max_edit_fraction":{"description":"Edit budget of a proposal as a fraction of the skill body, in (0, 1].","type":"number","format":"double","default":0.2},"max_edit_tokens":{"description":"Edit budget of a proposal, in tokens.","type":"integer","format":"uint64","default":300,"minimum":0},"max_proposals_per_cycle":{"description":"Most proposals one cycle may start.","type":"integer","format":"uint32","default":1,"minimum":0},"min_cases_floor":{"description":"Smallest `min_cases` a governing suite may declare. Below 3 is refused.","type":"integer","format":"uint32","default":3,"minimum":0},"mode":{"description":"`draft_only`, `shadow` or `auto`.","$ref":"#/$defs/SkillsLifecycleModeConfig","default":"draft_only"},"owner_scope":{"description":"The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.","type":["string","null"],"default":null},"require_holdout":{"description":"A governing suite must have a holdout split. `false` is refused.","type":"boolean","default":true},"storage_dir":{"description":"Store location under the workspace. Only the default is supported.","type":"string","default":"self/skill-lifecycle"},"suites":{"description":"The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.","type":"array","default":[],"items":{"$ref":"#/$defs/SkillSuiteRegistration"}}},"additionalProperties":false},"SkillsLifecycleModeConfig":{"description":"What the lifecycle may do. Mirrors `LifecycleMode`.","oneOf":[{"description":"Drafts and reviews only.","type":"string","const":"draft_only"},{"description":"Drafts plus evaluation and gating; never publishes.","type":"string","const":"shadow"},{"description":"Publishes an eligible proposal after every gate.","type":"string","const":"auto"}]},"SlackConfig":{"description":"Slack bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Slack user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Slack app-level token for Socket Mode (xapp-...).","type":["string","null"]},"bot_token":{"description":"Slack bot OAuth token (xoxb-...).","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["bot_token"]},"SmartGroupConfig":{"description":"Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).","type":"object","properties":{"classifier_max_context_messages":{"description":"How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.","type":"integer","format":"uint","default":3,"minimum":0},"classifier_model":{"description":"Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.","type":"string","default":""},"classifier_provider":{"description":"Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.","type":"string","default":""},"classifier_temperature":{"description":"Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).","type":"number","format":"double","default":0.0},"classifier_timeout_secs":{"description":"Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.","type":"integer","format":"uint64","default":5,"minimum":0}}},"StorageConfig":{"description":"Persistent storage configuration (`[storage]` section).","type":"object","properties":{"provider":{"description":"Storage provider settings (e.g. sqlite, postgres).","$ref":"#/$defs/StorageProviderSection","default":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}}},"StorageProviderConfig":{"description":"Storage provider backend configuration (e.g. postgres connection details).","type":"object","properties":{"connect_timeout_secs":{"description":"Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"db_url":{"description":"Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.","type":["string","null"],"default":null},"pool_max_size":{"description":"Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.","type":"integer","format":"uint","default":32,"minimum":0},"provider":{"description":"Storage engine key (e.g. \"postgres\", \"sqlite\").","type":"string","default":""},"schema":{"description":"Database schema for SQL backends.","type":"string","default":"public"},"table":{"description":"Table name for memory entries.","type":"string","default":"memories"}}},"StorageProviderSection":{"description":"Wrapper for the storage provider configuration section.","type":"object","properties":{"config":{"description":"Storage provider backend settings.","$ref":"#/$defs/StorageProviderConfig","default":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"StreamMode":{"description":"Streaming mode for channels that support progressive message updates.","oneOf":[{"description":"No streaming -- send the complete response as a single message (default).","type":"string","const":"off"},{"description":"Update a draft message with every flush interval.","type":"string","const":"partial"}]},"TailscaleTunnelConfig":{"type":"object","properties":{"funnel":{"description":"Use Tailscale Funnel (public internet) vs Serve (tailnet only)","type":"boolean","default":false},"hostname":{"description":"Optional hostname override","type":["string","null"]}}},"TaskRoutingConfig":{"description":"Lightweight pre-LLM task routing.","type":"object","properties":{"default_intent":{"description":"Fallback intent when no rule matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"rules":{"description":"Rules evaluated in descending priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/TaskRoutingRule"}}}},"TaskRoutingIntentConfig":{"description":"Task-routing default and rule intent.","type":"string","enum":["simple","delegate","stream"]},"TaskRoutingRule":{"description":"A single task-routing rule.","type":"object","properties":{"intent":{"description":"Route intent to apply when a keyword matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"model_hint":{"description":"Optional model hint/raw model for non-delegated requests.","type":["string","null"],"default":null},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0},"sub_agent_model":{"description":"Optional raw sub-agent model override for delegated tasks.","type":["string","null"],"default":null}}},"TelegramConfig":{"description":"Telegram bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Telegram user IDs or usernames. Empty = deny all.","type":"array","items":{"type":"string"}},"bot_token":{"description":"Telegram Bot API token (from @BotFather).","type":"string"},"draft_update_interval_ms":{"description":"Minimum interval (ms) between draft message edits to avoid rate limits.","type":"integer","format":"uint64","default":1000,"minimum":0},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"interrupt_on_new_message":{"description":"When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.","type":"boolean","default":false},"stream_mode":{"description":"Streaming mode for progressive response delivery via message edits.","$ref":"#/$defs/StreamMode","default":"off"}},"required":["bot_token","allowed_users"]},"ToolCallDialectSetting":{"description":"The tool-call grammars an operator may declare for an endpoint.","oneOf":[{"description":"Only the native `tool_calls` array is a tool call (the default).","type":"string","const":"native"},{"description":"Additionally read `{json}` from the content,\nfor a tool name the request registered.","type":"string","const":"xml_function_tags"}]},"ToolSchemaDialectSetting":{"description":"The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.","oneOf":[{"description":"The published document, byte for byte (the default).","type":"string","const":"raw"},{"description":"The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.","type":"string","const":"no_root_combinators"}]},"ToolTieringConfig":{"description":"Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.","type":"object","properties":{"always_exclude":{"description":"Tool names excluded from capability publication.","type":"array","default":[],"items":{"type":"string"}},"always_include":{"description":"Tool names preferred for direct publication, subject to admission gates.","type":"array","default":[],"items":{"type":"string"}},"channel_exclude":{"description":"Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefaults to [`DEFAULT_CHANNEL_EXCLUDED_TOOLS`]; set to `[]` to expose the\nfull operator surface on channels again.","type":"array","default":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","skills_manage","memory_reindex","document_sync","document_ingest"],"items":{"type":"string"}}}},"TunnelConfig":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.","type":"object","properties":{"cloudflare":{"description":"Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).","anyOf":[{"$ref":"#/$defs/CloudflareTunnelConfig"},{"type":"null"}],"default":null},"custom":{"description":"Custom tunnel command configuration (used when `provider = \"custom\"`).","anyOf":[{"$ref":"#/$defs/CustomTunnelConfig"},{"type":"null"}],"default":null},"ngrok":{"description":"ngrok tunnel configuration (used when `provider = \"ngrok\"`).","anyOf":[{"$ref":"#/$defs/NgrokTunnelConfig"},{"type":"null"}],"default":null},"provider":{"description":"Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.","type":"string","default":"none"},"tailscale":{"description":"Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).","anyOf":[{"$ref":"#/$defs/TailscaleTunnelConfig"},{"type":"null"}],"default":null}}},"UserPolicyConfig":{"description":"Startup user policy entry (`[[user_policies]]`).","type":"object","properties":{"blocked_patterns":{"type":"array","default":[],"items":{"type":"string"}},"projects":{"type":"array","default":[],"items":{"type":"string"}},"role":{"type":"string","default":"guest"},"user_id":{"type":"string"},"visibility_ceiling":{"type":"string","default":"private"}},"required":["user_id"]},"WacliConfig":{"description":"wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```","type":"object","properties":{"allow_unsigned_loopback":{"description":"Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).","type":"boolean","default":false},"allowed_from":{"description":"Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.","type":"array","default":["*"],"items":{"type":"string"}},"bot_jid":{"description":"Bot's own JID, used for reply-to-bot mention detection.","type":["string","null"],"default":null},"bot_lid":{"description":"The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.","type":["string","null"],"default":null},"bot_number":{"description":"Bot's own phone number (digits), used for `@` mention detection.","type":["string","null"],"default":null},"cli_path":{"description":"Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.","type":["string","null"],"default":null},"group_reply_mode":{"description":"Smart group-reply mode. When `None`, derived from `mention_only`.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"host":{"description":"REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].","type":["string","null"],"writeOnly":true},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"outbound_media_workspace_only":{"description":"Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.","type":"boolean","default":false},"port":{"description":"REMOVED: legacy JSON-RPC daemon port. See `host`.","type":["integer","null"],"format":"uint16","maximum":65535,"minimum":0,"writeOnly":true},"self_chat_mode":{"description":"Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.","type":"boolean","default":false},"store_dir":{"description":"wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.","type":["string","null"],"default":null},"webhook_listen":{"description":"Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").","type":"string","default":"127.0.0.1:16868"},"webhook_path":{"description":"HTTP path the webhook server serves (default: \"/wacli\").","type":"string","default":"/wacli"},"webhook_secret":{"description":"HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.","type":["string","null"],"default":null}}},"WebSearchConfig":{"description":"Web search tool configuration (`[web_search]` section).","type":"object","properties":{"brave_api_key":{"description":"Brave Search API key (required if provider is \"brave\")","type":["string","null"],"default":null},"fetch_max_chars":{"description":"Maximum characters returned by `web_fetch` (default 10000)","type":"integer","format":"uint","default":50000,"minimum":0},"max_results":{"description":"Maximum results per search (1-20)","type":"integer","format":"uint","default":15,"minimum":0},"provider":{"description":"Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)","type":"string","default":"duckduckgo"},"timeout_secs":{"description":"Request timeout in seconds","type":"integer","format":"uint64","default":15,"minimum":0}}},"WebhookConfig":{"description":"Webhook channel configuration.","type":"object","properties":{"port":{"description":"Port to listen on for incoming webhooks.","type":"integer","format":"uint16","maximum":65535,"minimum":0},"secret":{"description":"Optional shared secret for webhook signature verification.","type":["string","null"]}},"required":["port"]},"WhatsAppConfig":{"description":"WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.","type":"object","properties":{"access_token":{"description":"Access token from Meta Business Suite (Cloud API mode)","type":["string","null"],"default":null},"allowed_numbers":{"description":"Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"app_secret":{"description":"App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"pair_code":{"description":"Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one","type":["string","null"],"default":null},"pair_phone":{"description":"Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used","type":["string","null"],"default":null},"phone_number_id":{"description":"Phone number ID from Meta Business API (Cloud API mode)","type":["string","null"],"default":null},"read_pool_size":{"description":"Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"session_path":{"description":"Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs","type":["string","null"],"default":null},"verify_token":{"description":"Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode","type":["string","null"],"default":null},"ws_url":{"description":"WebSocket URL override (replaces WHATSAPP_WS_URL)","type":["string","null"],"default":null}}},"WorkspaceHooks":{"description":"Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).","oneOf":[{"description":"They do not run (the default); `prx doctor` and `hooks_status` say so.","type":"string","const":"off"},{"description":"They run, in a cleared environment and a dedicated directory beside\n`config.toml`.","type":"string","const":"on"}]},"WorkspaceMcpServers":{"description":"Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).","oneOf":[{"description":"None: a workspace file may only narrow the servers defined in\n`config.toml`.","type":"string","const":"off"},{"description":"HTTP servers (still refused when they target a private address).","type":"string","const":"http_only"},{"description":"HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.","type":"string","const":"stdio"}]},"XinConfig":{"description":"Configuration for the xin autonomous task engine (`[xin]`).","type":"object","properties":{"adopt_legacy_tasks":{"description":"Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).","type":"boolean","default":false},"interval_minutes":{"description":"Tick interval in minutes (minimum 1). Default: 5.","type":"integer","format":"uint32","default":5,"minimum":0},"stale_timeout_minutes":{"description":"Minutes after which a running task is marked stale. Default: 60.","type":"integer","format":"uint32","default":60,"minimum":0}}},"AgentMessaging":{"description":"Owner-controlled inbound session messaging (enabled unless explicitly off).","type":"object","properties":{"inbound":{"type":"boolean","default":true}}}}} diff --git a/tests/support/legacy_tool_surface_budget.rs b/tests/support/legacy_tool_surface_budget.rs index 057f5e0ad..5d0606a41 100644 --- a/tests/support/legacy_tool_surface_budget.rs +++ b/tests/support/legacy_tool_surface_budget.rs @@ -177,15 +177,15 @@ fn always_include_restores_a_channel_excluded_tool() { let tools = registry(&tmp); let mut operator = ToolTieringConfig::default(); - operator.always_include.push("git_operations".to_string()); + operator.always_include.push("nodes".to_string()); let channel = operator.for_channel_surface(); - // `git_operations` is DevOps-tiered, so name the capability too: the point + // `nodes` is DevOps-tiered, so name the capability too: the point // of this test is the override, not the classifier. let channel_specs = specs_for(&tools, "commit this to git", &channel); let channel_names = names(&channel_specs); assert!( - channel_names.contains(&"git_operations"), + channel_names.contains(&"nodes"), "always_include must survive the channel default: {channel_names:?}" ); } @@ -268,7 +268,7 @@ fn common_requests_reach_the_tools_they_obviously_need() { let tiering = ToolTieringConfig::default(); let cases: [(&str, &[&str]); 8] = [ - ("commit this change and push the branch", &["git_operations", "shell"]), + ("commit this change and push the branch", &["nodes", "shell"]), ("search the web for the rustls release notes", &["web_search_tool"]), ( "fetch https://example.com/report and summarise it", @@ -310,7 +310,7 @@ fn a_request_the_keyword_table_cannot_read_keeps_the_whole_registry() { let baseline = specs_for(&tools, "", &tiering); let everything = names(&baseline); assert!( - everything.contains(&"cron") && everything.contains(&"git_operations"), + everything.contains(&"cron") && everything.contains(&"nodes"), "the fixture's baseline must really be the whole catalog: {everything:?}" ); @@ -364,7 +364,7 @@ fn a_routed_english_request_is_still_narrowed() { routed.len(), everything.len() ); - assert!(routed.contains(&"git_operations"), "{routed:?}"); + assert!(routed.contains(&"nodes"), "{routed:?}"); assert!( !routed.contains(&"cron"), "an unnamed Extended capability must stay out: {routed:?}" @@ -420,7 +420,7 @@ fn a_closing_pleasantry_does_not_widen_an_established_chat_session() { "turn 1 must reach web search: {turn1_names:?}" ); assert!( - turn2_names.contains(&"git_operations") && turn2_names.contains(&"web_search_tool"), + turn2_names.contains(&"nodes") && turn2_names.contains(&"web_search_tool"), "turn 2 must add git and keep web search: {turn2_names:?}" ); assert!( From d405b0c9410a968ffdca8cffc57bde4748231bf4 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:57:50 +0400 Subject: [PATCH 0112/1567] refactor(security): remove the git refusal and hardening from the shell path --- CHANGELOG.md | 11 +- docs/configuration.md | 7 +- docs/scheduled-work.md | 3 +- docs/tools.md | 30 +- src/cron/mod.rs | 5 +- src/cron/postgres.rs | 12 - src/cron/scheduler.rs | 96 ----- src/cron/store.rs | 25 +- src/cron/types.rs | 4 +- src/doctor/implementation/section_1.rs | 98 ----- src/doctor/tests/section_1.rs | 69 ---- src/gateway/api/cron_jobs.rs | 2 +- src/gateway/tests/shell_parity.rs | 10 +- src/nodes/server.rs | 22 - src/runtime/shell_process.rs | 137 +------ src/security/git_launch.rs | 382 +----------------- src/tools/shell.rs | 21 +- src/tools/shell_parity_tests.rs | 55 --- src/tools/skills.rs | 5 - src/xin/runner.rs | 116 ------ src/xin/store.rs | 23 +- tests/architecture_boundaries/process.rs | 98 +---- .../architecture_boundaries/scanner_probes.rs | 5 +- tests/int_p1_cross_module.rs | 1 - 24 files changed, 57 insertions(+), 1180 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b88586fc9..50bea5c7a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,9 +9,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Removed +- BREAKING (operators): the git-specific rules of the shell path are removed. + A command that runs git is an ordinary shell command at every autonomy + level: below Full it is no longer refused, and operator cron and Xin jobs, + xin system tasks and node `exec_shell` commands no longer get the hardened + git environment (no forced `core.hooksPath`, `GIT_CONFIG_*` or + `GIT_NO_LAZY_FETCH`). `prx doctor` no longer lists shell jobs stored without + a recorded creator. PRX's own git invocations (skill installs, the chat diff + view) keep their hardened launch. - BREAKING (agents): the structured `git_operations` tool is removed. Agents - run git through the `shell` tool, whose git policy is unchanged: effective - Full runs plain git; Supervised and ReadOnly shells refuse git. A + run git through the `shell` tool. A configuration that still names `git_operations` (`tool_tiering`, `agents..allowed_tools`, scope-rule `tools_allow` / `tools_deny`) loads normally; the name matches nothing and is ignored. diff --git a/docs/configuration.md b/docs/configuration.md index 090726995..e447d5d03 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -3434,8 +3434,7 @@ the effective snapshot; a worker cannot replace or discard that signed root. The security workspace, memory ACL and audit/experiment roots do not move. Docker also requires the directory to satisfy `runtime.docker.allowed_workspace_roots`. -At effective Full autonomy the shell runs ordinary git (including repository hooks) -and inherits the parent environment except known provider credentials, worker secrets, +At effective Full autonomy the shell inherits the parent environment except known provider credentials, worker secrets, `MINIMAX_OAUTH_*` and `OPENPRX_*`. This environment hygiene is not a security boundary: a Full shell can read local configuration. Native file tools may access paths outside the workspace and forbidden paths; parent traversal (`..`) remains refused. Private @@ -3448,13 +3447,11 @@ With `workspace_only = true` (the default), a root outside the security workspac refuses every relative native file request and every shell path argument containing `/`. With `workspace_only = false`, a root outside the workspace under a default forbidden prefix such as `/home`, `/tmp` or `/var` still refuses those paths; the -workspace ancestor exemption applies only inside the security workspace. An approval does not enable git -in a Supervised shell. +workspace ancestor exemption applies only inside the security workspace. A child's effective level cannot exceed its manifest or the current service level. Direct tool calls without runtime authority keep the Supervised behavior. Docker continues to use the shell environment allowlist at every level. Native Full ignores that allowlist for admission, but invalid entries are still rejected. -Skill scripts and scheduled shell jobs retain their existing git policy. ### Named-agent rf admission limits diff --git a/docs/scheduled-work.md b/docs/scheduled-work.md index cda7a4dba..58e6f32ac 100644 --- a/docs/scheduled-work.md +++ b/docs/scheduled-work.md @@ -160,8 +160,7 @@ the runner stops that execution. For HEARTBEAT.md tasks, pause is undone by the next reconciliation while the bullet remains; cancel keeps status cancelled, so scheduling still skips it, until `prx xin resume`. `prx cron mark-operator` and `prx xin mark-operator` record that a pre-existing -shell command is the operator's own; agent-created shell jobs stay refused for -git. +shell command is the operator's own, so it runs at the operator level. Field defaults live in the [configuration reference](configuration.md): diff --git a/docs/tools.md b/docs/tools.md index 5f3520d2f..618e3bab6 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -95,11 +95,12 @@ stricter environment, and operator cron/Xin jobs keep their existing policy. Environment filtering does not restrict which host files native shell commands can read, and does not change command authorization or process lifetime. -## Shell git policy and file working root +## Shell git and file working root -Effective Full shells run ordinary git, including repository hooks. Supervised -and ReadOnly shells refuse git before spawning; approval does not change that -policy. Skill scripts and cron/Xin shell jobs keep their existing git policy. +Git is an ordinary shell command at every autonomy level: PRX applies no git-specific +rule, so repository hooks and configuration run as they would in a terminal. What a +level does with shell commands (approval at Supervised, refusal at ReadOnly) applies +to git unchanged. `runtime.workdir` or `prx chat --workdir /absolute/task` selects the working root for shell and native file tools; otherwise they use the workspace. @@ -1574,22 +1575,11 @@ creating surface does not; and a **shell** job (`job_type = "shell"`, or a xin policy at all, whoever created it — deny the `cron` and `xin` tools to a scope that must not run shell commands. -Git has a separate execution boundary. Effective Full autonomy runs git -through the `shell` tool; PRX refuses recognized Git command strings in the -`shell` tool below Full, in skill shell/script tools, and in -cron or xin shell jobs created or rewritten by an agent tool. Operator-created -cron and xin shell jobs, xin system tasks, and node `exec_shell` allowlists may -run Git with fixed program settings and hooks disabled. PRX records who last -wrote each shell command separately from the job's owner; rewriting a command -through an agent tool removes its operator-Git eligibility. Jobs stored before -this creator field existed are treated as agent-written. For SQLite stores, -`prx doctor` lists their IDs without printing their commands. PostgreSQL cron -jobs are not enumerated by doctor. An operator may vouch for a job they -created with `prx cron mark-operator ` or `prx xin mark-operator `. -Detection of Git inside a script is best effort, and these operator surfaces -do not inspect repository-specific Git drivers, helpers or transport settings. -The Docker runtime forwards the fixed settings into the container without -placing their values in Docker command arguments. +Git has no execution boundary of its own: a shell job, skill script or node +`exec_shell` command that runs git is treated like any other command. PRX +records who last wrote each shell command separately from the job's owner; +an operator may vouch for a job they created with `prx cron mark-operator ` +or `prx xin mark-operator `, which decides the level the job runs at. Claim timestamps currently use each scheduler caller's UTC clock. Multi-node deployments must maintain NTP synchronization and bounded clock skew well below the configured lease interval. A schedule change is rejected while any claim is still active; once that claim has expired, an explicit update may clear the stale tuple. Manual runs of nonterminal jobs use the same renewable lease, delivery, and fenced commit path as background runs. diff --git a/src/cron/mod.rs b/src/cron/mod.rs index 7b1d1db98..9436464f1 100644 --- a/src/cron/mod.rs +++ b/src/cron/mod.rs @@ -22,7 +22,7 @@ pub use store::{ abandon_job_claim, add_agent_job, add_agent_job_with_lineage, add_shell_job, add_shell_job_with_approval_grant, add_shell_job_with_lineage_and_approval_grant, add_shell_job_with_lineage_approval_and_delete, claim_job_if_current, claim_job_if_current_for_manual_run, claim_terminal_job_for_manual_rerun, due_jobs, - finish_claimed_run, get_job, job_claim_is_current, job_created_via, job_creator, job_revision, list_job_events, + finish_claimed_run, get_job, job_claim_is_current, job_creator, job_revision, list_job_events, list_jobs, list_runs, mark_job_operator, record_claim_lost, record_delivery_withheld, record_terminal_manual_run, remove_job, renew_job_claim, unmarked_shell_jobs, update_job, }; @@ -194,8 +194,7 @@ pub fn handle_command(command: crate::CronCommands, config: &Config) -> Result<( fn cli_lineage() -> CronJobLineage { CronJobLineage { origin: JobOrigin::LocalOperator, - // D-107 amendment: the operator's own command, so its git may run - // (hardened). + // The operator's own command. created_via: JobCreator::OperatorCli, ..CronJobLineage::default() } diff --git a/src/cron/postgres.rs b/src/cron/postgres.rs index 3ad7d0c32..7e8f20fb0 100644 --- a/src/cron/postgres.rs +++ b/src/cron/postgres.rs @@ -379,18 +379,6 @@ impl PostgresCronStore { }) } - pub fn job_created_via(&self, job_id: &str) -> Result { - self.with_client(|client| { - let row = client - .query_opt("SELECT created_via FROM cron_jobs WHERE id = $1", &[&job_id]) - .context("Failed to query cron job creator")?; - match row { - Some(row) => Ok(JobCreator::from_stored(row.try_get::<_, Option>(0)?.as_deref())), - None => anyhow::bail!("Cron job '{job_id}' not found"), - } - }) - } - pub fn job_revision(&self, job_id: &str) -> Result { self.with_client(|client| { let row = client diff --git a/src/cron/scheduler.rs b/src/cron/scheduler.rs index 645079de7..56dd55544 100644 --- a/src/cron/scheduler.rs +++ b/src/cron/scheduler.rs @@ -1116,29 +1116,6 @@ async fn run_job_command(config: &Config, job: &CronJob) -> (bool, String) { run_job_command_with_adapter(config, job, None, &process).await } -/// How a cron shell job's git is treated. At the run's Full level (the -/// level [`job_run_level`] computed and the caller scoped around the run; -/// unset is never Full) git runs plainly, as in the Full shell, whoever -/// created the job (owner D1). Below Full (D-107 amendment): a job the operator created -/// with `prx cron` (or marked with `prx cron mark-operator`) runs git -/// hardened, warned once; a job an agent tool created, a job stored before -/// the creator was recorded, and a failed lookup refuse it. -fn shell_git_policy(config: &Config, job: &CronJob) -> crate::runtime::shell_process::ShellGitPolicy { - if crate::tools::effective_autonomy::current() == Some(crate::security::AutonomyLevel::Full) { - return crate::tools::shell::shell_git_policy(crate::security::AutonomyLevel::Full); - } - let operator = crate::cron::job_created_via(config, &job.id) - .is_ok_and(|creator| creator == crate::cron::JobCreator::OperatorCli); - if operator { - if crate::security::git_launch::shell_command_runs_git(&job.command) { - crate::security::git_launch::warn_operator_git_once("cron", &job.id); - } - crate::runtime::shell_process::ShellGitPolicy::HardenGit - } else { - crate::runtime::shell_process::ShellGitPolicy::RefuseGit - } -} - async fn run_job_command_with_adapter( config: &Config, job: &CronJob, @@ -1151,7 +1128,6 @@ async fn run_job_command_with_adapter( workspace_dir: &config.workspace_dir, timeout, cancellation: None, - git: shell_git_policy(config, job), }) .await { @@ -1609,78 +1585,6 @@ mod tests { .unwrap() } - /// D-107: a cron shell job an agent tool created (or one stored before - /// the creator was recorded) is model-driven, so a command that runs git - /// is refused. - #[tokio::test] - async fn a_cron_shell_job_that_runs_git_is_refused() { - let tmp = TempDir::new().unwrap(); - let config = test_config(&tmp).await; - let job = test_job("cd . && git status"); - - let (success, output) = run_job_command(&config, &job).await; - assert!(!success); - assert!(output.contains("refusing to run git through the shell"), "{output}"); - } - - /// D-107 amendment: a job the operator added with `prx cron` runs git - /// (hardened); the same command added through an agent tool is refused; - /// an agent tool rewriting the operator job's command makes it an agent - /// job; `mark-operator` vouches for one again. - #[tokio::test] - async fn only_operator_cron_jobs_run_git() { - crate::security::git_launch::hermetic_git_for_tests(); - let tmp = TempDir::new().unwrap(); - let config = test_config(&tmp).await; - crate::cron::handle_command( - crate::CronCommands::Add { - expression: "*/5 * * * *".into(), - tz: None, - command: "git --version".into(), - }, - &config, - ) - .unwrap(); - let operator = crate::cron::list_jobs(&config) - .unwrap() - .into_iter() - .find(|job| job.command == "git --version") - .expect("test: the CLI job"); - let (success, output) = run_job_command(&config, &operator).await; - assert!(success, "{output}"); - assert!(output.contains("git version"), "{output}"); - - let agent = cron::add_shell_job( - &config, - None, - crate::cron::Schedule::Cron { - expr: "*/5 * * * *".into(), - tz: None, - }, - "git --version", - ) - .unwrap(); - let (success, output) = run_job_command(&config, &agent).await; - assert!(!success); - assert!(output.contains("refusing to run git"), "{output}"); - - let rewritten = cron::update_job( - &config, - &operator.id, - crate::cron::CronJobPatch { - command: Some("git status".into()), - ..crate::cron::CronJobPatch::default() - }, - ) - .unwrap(); - let (success, output) = run_job_command(&config, &rewritten).await; - assert!(!success, "an agent rewrite kept the operator's permission: {output}"); - - crate::cron::mark_job_operator(&config, &agent.id).unwrap(); - let (success, output) = run_job_command(&config, &agent).await; - assert!(success, "{output}"); - } - #[tokio::test] async fn run_job_command_success() { let tmp = TempDir::new().unwrap(); diff --git a/src/cron/store.rs b/src/cron/store.rs index 11adf304d..a895f1200 100644 --- a/src/cron/store.rs +++ b/src/cron/store.rs @@ -361,23 +361,6 @@ pub fn get_job(config: &Config, job_id: &str) -> Result { }) } -/// Which surface created the job (D-107 amendment); NULL is `agent_tool`. -pub fn job_created_via(config: &Config, job_id: &str) -> Result { - if let Some(store) = pg_store(config)? { - return store.job_created_via(job_id); - } - with_connection(config, |conn| { - let value = conn - .query_row( - "SELECT created_via FROM cron_jobs WHERE id = ?1", - params![job_id], - |row| row.get::<_, Option>(0), - ) - .with_context(|| format!("Cron job '{job_id}' not found"))?; - Ok(JobCreator::from_stored(value.as_deref())) - }) -} - /// Which surface created the job and the stored creator stamp; NULL /// `created_via` is `agent_tool`, and an unreadable stamp reads as empty. pub fn job_creator(config: &Config, job_id: &str) -> Result<(JobCreator, CreatorStamp)> { @@ -411,7 +394,7 @@ pub fn job_creator(config: &Config, job_id: &str) -> Result<(JobCreator, Creator } /// Record that the operator vouches for a job as their own (`prx cron -/// mark-operator`): its shell command may then run git, hardened. +/// mark-operator`): its runs then use the operator level. pub fn mark_job_operator(config: &Config, job_id: &str) -> Result<()> { if let Some(store) = pg_store(config)? { return store.mark_job_operator(job_id); @@ -2295,7 +2278,7 @@ fn with_connection(config: &Config, f: impl FnOnce(&mut Connection) -> Result add_column_if_missing(&conn, "cron_jobs", "origin", "TEXT")?; // D-107 amendment: which surface created the job. Nullable with no // backfill: a row stored before the column existed reads as - // `agent_tool` (its git is refused) until the operator marks it. + // `agent_tool` until the operator marks it. add_column_if_missing(&conn, "cron_jobs", "created_via", "TEXT")?; // The creating call's level and agent. Nullable with no backfill: a row // without them runs at Main's level. @@ -3851,7 +3834,7 @@ mod tests { ) .unwrap(); mark_job_operator(&config, &job.id).unwrap(); - assert_eq!(job_created_via(&config, &job.id).unwrap(), JobCreator::OperatorCli); + assert_eq!(job_creator(&config, &job.id).unwrap().0, JobCreator::OperatorCli); let updated = update_job( &config, @@ -3863,7 +3846,7 @@ mod tests { ) .unwrap(); assert_eq!(updated.command, "git status"); - assert_eq!(job_created_via(&config, &job.id).unwrap(), JobCreator::AgentTool); + assert_eq!(job_creator(&config, &job.id).unwrap().0, JobCreator::AgentTool); } } diff --git a/src/cron/types.rs b/src/cron/types.rs index 16a0d099d..978858aab 100644 --- a/src/cron/types.rs +++ b/src/cron/types.rs @@ -260,8 +260,8 @@ pub struct CronJob { pub origin: JobOrigin, } -/// Which surface created a job (D-107 amendment): decides whether its shell -/// command may run git (hardened) or not. +/// Which surface created a job: decides whether its runs use the operator +/// level. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum JobCreator { /// The operator's own command: `prx cron`/`prx xin`, an authenticated diff --git a/src/doctor/implementation/section_1.rs b/src/doctor/implementation/section_1.rs index 123b7e67d..b8bd1cc11 100644 --- a/src/doctor/implementation/section_1.rs +++ b/src/doctor/implementation/section_1.rs @@ -189,7 +189,6 @@ pub fn diagnose(config: &Config) -> DoctorReport { check_legacy_fitness_telemetry(config, &mut items); check_workspace_mcp_servers(config, &mut items); check_workspace_hooks(config, &mut items); - check_unowned_shell_jobs(config, &mut items); check_unfinished_config_changes(config, &mut items); check_daemon_state(config, &mut items); prompt_cache::check_prompt_cache(config, &mut items); @@ -242,103 +241,6 @@ fn check_workspace_hooks(config: &Config, items: &mut Vec) { } } -/// Shell jobs stored before PRX recorded who creates them (D-107 -/// amendment): they count as agent-created, so a command that runs git is -/// refused. Each is named with the one command that vouches for it. Opens -/// the stores read-only and runs no migration: a store whose table predates -/// the `created_via` column has only such rows. -fn check_unowned_shell_jobs(config: &Config, items: &mut Vec) { - let category = "git"; - let cron_in_postgres = config - .storage - .provider - .config - .provider - .trim() - .eq_ignore_ascii_case("postgres"); - let mut sources = vec![( - "xin shell task", - "prx xin mark-operator", - config.workspace_dir.join("xin").join("tasks.db"), - "xin_tasks", - "SELECT id, payload FROM xin_tasks - WHERE execution_mode = 'shell' AND kind <> 'system' AND created_via IS NULL ORDER BY id", - "SELECT id, payload FROM xin_tasks WHERE execution_mode = 'shell' AND kind <> 'system' ORDER BY id", - )]; - if cron_in_postgres { - items.push(DiagItem::ok( - category, - "cron jobs are stored in Postgres and not inspected here; a shell job created before PRX recorded its \ - creator runs no git until `prx cron mark-operator `", - )); - } else { - sources.push(( - "cron shell job", - "prx cron mark-operator", - config.workspace_dir.join("cron").join("jobs.db"), - "cron_jobs", - "SELECT id, command FROM cron_jobs WHERE job_type = 'shell' AND created_via IS NULL ORDER BY id", - "SELECT id, command FROM cron_jobs WHERE job_type = 'shell' ORDER BY id", - )); - } - let mut found = 0_usize; - for (what, mark, db_path, table, unowned_sql, legacy_sql) in sources { - match read_only_unowned_rows(&db_path, table, unowned_sql, legacy_sql) { - Ok(rows) => { - for (id, _) in rows { - found += 1; - items.push(DiagItem::warn( - category, - format!( - "{what} {id} predates creator tracking and counts as agent-created, so git in it is \ - refused; if you created it: `{mark} {id}`" - ), - )); - } - } - Err(error) => items.push(DiagItem::warn( - category, - format!("the {what}s could not be read: {error:#}"), - )), - } - } - if found == 0 { - items.push(DiagItem::healthy(category, "every shell job records who created it")); - } -} - -/// `(id, command)` of the shell rows of `table` whose `created_via` is NULL -/// (`unowned_sql`), or all of them (`legacy_sql`) when the column does not -/// exist yet; read-only, and empty when the database or the table is -/// missing. -fn read_only_unowned_rows( - db_path: &Path, - table: &str, - unowned_sql: &str, - legacy_sql: &str, -) -> Result> { - if !db_path.is_file() { - return Ok(Vec::new()); - } - let connection = rusqlite::Connection::open_with_flags(db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?; - let table_exists: bool = connection.query_row( - "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?1)", - [table], - |row| row.get(0), - )?; - if !table_exists { - return Ok(Vec::new()); - } - let has_creator: bool = connection.query_row( - "SELECT EXISTS(SELECT 1 FROM pragma_table_info(?1) WHERE name = 'created_via')", - [table], - |row| row.get(0), - )?; - let mut statement = connection.prepare(if has_creator { unowned_sql } else { legacy_sql })?; - let rows = statement.query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)))?; - Ok(rows.collect::, _>>()?) -} - /// Unfinished configuration changes (SP-PMM §2.6, D-095 L-3): a `pending` /// history record (the process stopped between commit and activation) or a /// `not_restored` one (a refused change whose restore failed). Nothing is diff --git a/src/doctor/tests/section_1.rs b/src/doctor/tests/section_1.rs index 5e2c284ac..c0fd2f6ab 100644 --- a/src/doctor/tests/section_1.rs +++ b/src/doctor/tests/section_1.rs @@ -351,75 +351,6 @@ assert!(pending.message.contains("prx config rollback"), "{}", pending.message); } - /// D-107 amendment: a shell job stored before PRX recorded its creator - /// is named with the command that vouches for it; one with a recorded - /// creator is not; the check writes nothing. - #[test] - fn doctor_names_shell_jobs_without_a_recorded_creator() { - let temp = TempDir::new().unwrap(); - let mut config = Config::default(); - config.workspace_dir = temp.path().to_path_buf(); - let legacy = crate::cron::add_shell_job( - &config, - None, - crate::cron::Schedule::Cron { - expr: "*/5 * * * *".into(), - tz: None, - }, - "git pull project_payload_marker", - ) - .unwrap(); - let recorded = crate::cron::add_shell_job( - &config, - None, - crate::cron::Schedule::Cron { - expr: "*/5 * * * *".into(), - tz: None, - }, - "echo recorded", - ) - .unwrap(); - let db_path = temp.path().join("cron").join("jobs.db"); - rusqlite::Connection::open(&db_path) - .unwrap() - .execute( - "UPDATE cron_jobs SET created_via = NULL WHERE id = ?1", - [legacy.id.as_str()], - ) - .unwrap(); - let before = std::fs::read(&db_path).unwrap(); - - let mut items = Vec::new(); - check_unowned_shell_jobs(&config, &mut items); - let warnings = items - .iter() - .filter(|item| item.category == "git" && item.severity == Severity::Warn) - .collect::>(); - assert_eq!(warnings.len(), 1, "{warnings:?}"); - let warning = warnings.first().map(|item| item.message.as_str()).unwrap_or_default(); - assert!( - warning.contains(&format!("prx cron mark-operator {}", legacy.id)), - "{warning}" - ); - assert!(!warning.contains(&recorded.id), "{warning}"); - assert!(!warning.contains("project_payload_marker"), "{warning}"); - assert_eq!( - std::fs::read(&db_path).unwrap(), - before, - "doctor wrote to the cron store" - ); - - crate::cron::mark_job_operator(&config, &legacy.id).unwrap(); - let mut items = Vec::new(); - check_unowned_shell_jobs(&config, &mut items); - assert!( - !items - .iter() - .any(|item| item.category == "git" && item.severity == Severity::Warn), - "{items:?}" - ); - } - /// SP-PMM H-4: a `pending` history record is reported with its /// recovery commands and never applied (loading the configuration and /// running the checks leave the files and the record as they were); a diff --git a/src/gateway/api/cron_jobs.rs b/src/gateway/api/cron_jobs.rs index 1a3d39060..3dcd7cdf5 100644 --- a/src/gateway/api/cron_jobs.rs +++ b/src/gateway/api/cron_jobs.rs @@ -89,7 +89,7 @@ fn scope_args(owner_id: &str) -> Value { } /// Who a write through this route records as the creator: the operator -/// (`operator_cli`, so its runs keep Main's live level and hardened git) when +/// (`operator_cli`, so its runs keep Main's live level) when /// a paired bearer authenticated the request; otherwise `agent_tool`, so a /// request accepted with pairing off gains nothing. fn route_creator(state: &AppState, headers: &axum::http::HeaderMap) -> crate::cron::JobCreator { diff --git a/src/gateway/tests/shell_parity.rs b/src/gateway/tests/shell_parity.rs index 7888bb602..529bc066a 100644 --- a/src/gateway/tests/shell_parity.rs +++ b/src/gateway/tests/shell_parity.rs @@ -252,15 +252,7 @@ async fn generation_swap_changes_git_outcome_between_calls() { let context = crate::tools::ToolExecutionContext::new(crate::runtime::envelope::RuntimeEnvelope::agent("workspace-a", "parity-reload").with_owner_id("prx_user").with_channel("terminal"), "dm"); let outcome = service.execution().with_approval(Arc::new(Approve)).execute(crate::tools::ToolExecutionCommand::new("shell", serde_json::json!({"command":"git --version"})), context, None).await; let success = outcome.result.as_ref().is_some_and(|result| result.success); - assert_eq!(success, level == crate::security::AutonomyLevel::Full, "test: existing gateway adopts generation policy"); - if level == crate::security::AutonomyLevel::Supervised { - assert!(outcome.process.as_ref().is_some_and(|process| !process.started && process.termination == crate::tools::traits::ProcessTermination::NotStarted), - "test: approved supervised git is refused before spawn"); - assert_eq!(outcome.error.as_deref(), - Some(crate::runtime::shell_process::ShellProcessError::GitRefused.to_string().as_str()), - "test: the approved call must reach the native git refusal: {outcome:?}"); - } - + assert!(success, "test: git runs through the shell at {level:?}: {outcome:?}"); } let cleanup = owner.cleanup.clone(); drop(state); diff --git a/src/nodes/server.rs b/src/nodes/server.rs index c075fd1b2..07476156f 100644 --- a/src/nodes/server.rs +++ b/src/nodes/server.rs @@ -406,11 +406,6 @@ async fn handle_exec_shell(state: &AppState, params: ExecShellParams, source_ip: &state.config.allowed_commands, &state.config.blocked_commands, )?; - // An operator allowlist entry is operator-configured (D-107): git runs, - // with the environment hardening `execute_shell_command` applies. - if crate::security::git_launch::shell_command_runs_git(command_text) { - crate::security::git_launch::warn_operator_git_once("node", &parsed_command.program); - } let cwd = if let Some(cwd) = params.cwd.as_deref() { Some(resolve_existing_sandbox_path(&state.sandbox_root.path, cwd)?) @@ -517,23 +512,6 @@ async fn execute_shell_command( if let Some(env) = env { cmd.envs(env); } - // After the caller's variables, so they cannot undo it (D-107). - cmd.env_remove("GIT_CONFIG_PARAMETERS"); - let git_environment = match crate::security::git_launch::operator_git_environment().await { - Ok(environment) => environment, - Err(error) => { - return ExecShellResult { - task_id: task_id.to_string(), - exit_code: None, - stdout: String::new(), - stderr: format!("cannot harden git for this operator command: {error}"), - duration_ms: elapsed_ms_u64(started.elapsed()), - timed_out: false, - cancelled: false, - }; - } - }; - cmd.envs(git_environment); let mut child = match crate::runtime::shell_process::spawn_managed_shell_child(cmd) { Ok(child) => child, diff --git a/src/runtime/shell_process.rs b/src/runtime/shell_process.rs index f128c14a1..06bb127bf 100644 --- a/src/runtime/shell_process.rs +++ b/src/runtime/shell_process.rs @@ -57,21 +57,6 @@ pub const SHELL_OUTPUT_TRUNCATED_MARKER: &str = "\n... [output truncated at 1MiB const OUTPUT_DRAIN_KILL_GRACE: Duration = Duration::from_secs(1); /// A single shell execution request. Policy decisions are intentionally absent. -/// How a shell job's git is treated (GIT-ENV, D-107). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ShellGitPolicy { - /// Effective Full autonomy: ordinary git, without injected settings. - PlainGit, - /// Below an effective Full level: restricted shell tools, workspace - /// skill scripts, and model-created cron/Xin jobs refuse command strings - /// that run git. - RefuseGit, - /// An operator-configured job below an effective Full level: git runs, - /// with the environment hardening - /// of [`crate::security::git_launch::operator_git_environment`]. - HardenGit, -} - pub struct ShellProcessRequest<'a> { pub command: &'a str, pub workspace_dir: &'a Path, @@ -79,8 +64,6 @@ pub struct ShellProcessRequest<'a> { /// explicitly bounded internal probes may opt into a deadline. pub timeout: Option, pub cancellation: Option, - /// Whether a command string that runs git is refused or hardened. - pub git: ShellGitPolicy, } /// Completed shell execution with independently bounded output streams. @@ -123,14 +106,6 @@ pub enum ShellProcessError { Timeout(Duration), #[error("command execution cancelled")] Cancelled, - /// A restricted command string runs git (GIT-ENV, D-106). - /// Effective Full shell, skill, cron and Xin invocations select PlainGit - /// instead. - #[error( - "refusing to run git through the shell: a restricted command may not run git, because a repository's \ - configuration can name programs git would execute" - )] - GitRefused, } impl ShellProcessError { @@ -240,20 +215,6 @@ impl ShellProcessAdapter { end_group_on_exit: bool, cgroup: Option>, ) -> Result { - if request.git == ShellGitPolicy::RefuseGit - && crate::security::git_launch::shell_command_runs_git(request.command) - { - return Err(ShellProcessError::GitRefused); - } - // An operator job's git (also inside a script it runs) gets the - // fixed settings through the environment. - let git_environment = if request.git == ShellGitPolicy::HardenGit { - crate::security::git_launch::operator_git_environment() - .await - .map_err(ShellProcessError::Runtime)? - } else { - Vec::new() - }; if request .cancellation .as_ref() @@ -286,8 +247,6 @@ impl ShellProcessAdapter { .cloned(), ); } - // Hardened Git settings win even over an explicitly inherited name. - shell_environment.extend(git_environment.iter().cloned()); let mut command = self .runtime .build_shell_command_with_env(request.command, request.workspace_dir, &shell_environment) @@ -296,7 +255,6 @@ impl ShellProcessAdapter { if let Some(environment) = filtered_environment { command.env_clear(); command.envs(environment); - command.envs(git_environment.iter().cloned()); } if end_group_on_exit && self.runtime.name() == "native" { command.env_clear(); @@ -970,7 +928,7 @@ mod tests { let outcome = ShellProcessAdapter::new(runtime.clone()).with_environment_allowlist(names.clone()) .execute(ShellProcessRequest { command: "test -n \"$PATH\" && test -z \"${PRX_RUNTIME_INTERNAL_TOKEN+x}\" && printf CLIENT_FILTERED", - workspace_dir: temp.path(), timeout: None, cancellation: None, git: ShellGitPolicy::RefuseGit, + workspace_dir: temp.path(), timeout: None, cancellation: None, }).await.unwrap(); assert!(outcome.status.success()); assert_eq!(outcome.stdout, "CLIENT_FILTERED"); @@ -993,93 +951,12 @@ mod tests { workspace_dir: temp.path(), timeout: None, cancellation: None, - git: ShellGitPolicy::RefuseGit, }) .await; assert!(result.is_err()); assert!(!temp.path().join("should-not-exist").exists()); } - /// D-107: a model-driven surface's command string that runs git is - /// refused before anything starts. - #[tokio::test] - async fn a_model_driven_shell_command_that_runs_git_is_refused() { - let temp = TempDir::new().expect("temp dir"); - let marker = temp.path().join("started"); - for command in [ - format!("touch '{}'; git status", marker.display()), - "cd . && GIT_DIR=x git log".to_string(), - "sh -c 'git status'".to_string(), - ] { - let result = adapter() - .execute(ShellProcessRequest { - command: &command, - workspace_dir: temp.path(), - timeout: None, - cancellation: None, - git: ShellGitPolicy::RefuseGit, - }) - .await; - assert!(matches!(result, Err(ShellProcessError::GitRefused)), "{command}"); - } - assert!(!marker.exists(), "part of a refused command ran"); - } - - /// D-107: an operator-configured job's git runs, with the fixed settings - /// and `GIT_NO_LAZY_FETCH` in its environment (a repository fsmonitor - /// does not run). - #[cfg(unix)] - #[tokio::test] - async fn an_operator_shell_job_runs_git_with_the_hardened_environment() { - use std::os::unix::fs::PermissionsExt as _; - crate::security::git_launch::hermetic_git_for_tests(); - let temp = TempDir::new().expect("temp dir"); - let repo = temp.path().join("repo"); - std::fs::create_dir_all(&repo).expect("repo"); - let marker = temp.path().join("fsmonitor-ran"); - let fsmonitor = temp.path().join("fsmonitor.sh"); - std::fs::write(&fsmonitor, format!("#!/bin/sh\necho ran > '{}'\n", marker.display())).expect("script"); - std::fs::set_permissions(&fsmonitor, std::fs::Permissions::from_mode(0o755)).expect("chmod"); - let setup = |args: &[&str]| { - let status = std::process::Command::new("git") - .args(["-c", "core.hooksPath=/dev/null"]) - .args(args) - .current_dir(&repo) - .env("GIT_CONFIG_GLOBAL", "/dev/null") - .env("GIT_CONFIG_NOSYSTEM", "1") - .status() - .expect("git runs"); - assert!(status.success(), "git {args:?}"); - }; - setup(&["init", "-q"]); - setup(&[ - "-c", - "user.name=t", - "-c", - "user.email=t@example.invalid", - "commit", - "-q", - "--allow-empty", - "-m", - "one", - ]); - setup(&["config", "core.fsmonitor", &fsmonitor.display().to_string()]); - let outcome = adapter() - .execute(ShellProcessRequest { - command: "git status --porcelain && git config --get core.hooksPath && printf \"$GIT_NO_LAZY_FETCH\"", - workspace_dir: &repo, - timeout: None, - cancellation: None, - git: ShellGitPolicy::HardenGit, - }) - .await - .expect("operator git runs"); - assert!(outcome.status.success(), "{}", outcome.stderr); - assert!(outcome.stdout.contains("/dev/null"), "{}", outcome.stdout); - assert!(outcome.stdout.trim_end().ends_with('1'), "{}", outcome.stdout); - assert!(!marker.exists(), "the repository's fsmonitor ran in an operator job"); - } - #[tokio::test] async fn a_joined_run_gets_only_the_contained_environment() { let temp = TempDir::new().expect("temp dir"); @@ -1089,7 +966,6 @@ mod tests { workspace_dir: dir, timeout: None, cancellation: None, - git: ShellGitPolicy::RefuseGit, } } // A plain run inherits the test process's variables; a joined one must @@ -1149,7 +1025,6 @@ mod tests { workspace_dir: temp.path(), timeout: None, cancellation: None, - git: crate::runtime::shell_process::ShellGitPolicy::RefuseGit, }) .await .expect("unbounded shell execution"); @@ -1168,7 +1043,6 @@ mod tests { workspace_dir: temp.path(), timeout: Some(Duration::from_secs(5)), cancellation: None, - git: crate::runtime::shell_process::ShellGitPolicy::RefuseGit, }) .await .expect("shell execution"); @@ -1186,7 +1060,6 @@ mod tests { workspace_dir: temp.path(), timeout: Some(Duration::from_secs(10)), cancellation: None, - git: crate::runtime::shell_process::ShellGitPolicy::RefuseGit, }) .await .expect("large-output command"); @@ -1209,7 +1082,6 @@ mod tests { workspace_dir: temp.path(), timeout: Some(Duration::from_secs(5)), cancellation: Some(cancellation), - git: crate::runtime::shell_process::ShellGitPolicy::RefuseGit, }) .await; @@ -1227,7 +1099,6 @@ mod tests { workspace_dir: temp.path(), timeout: Some(Duration::from_millis(100)), cancellation: None, - git: crate::runtime::shell_process::ShellGitPolicy::RefuseGit, }) .await; @@ -1276,7 +1147,6 @@ mod tests { workspace_dir: temp.path(), timeout: None, cancellation: Some(cancellation), - git: crate::runtime::shell_process::ShellGitPolicy::RefuseGit, }) .await; let pid = canceller.await.expect("canceller task"); @@ -1349,7 +1219,6 @@ mod tests { workspace_dir: temp.path(), timeout: Some(Duration::from_secs(10)), cancellation: Some(cancellation.clone()), - git: ShellGitPolicy::RefuseGit, }); tokio::select! { biased; @@ -1437,7 +1306,6 @@ mod tests { workspace_dir: temp.path(), timeout: Some(Duration::from_secs(10)), cancellation: Some(cancellation), - git: crate::runtime::shell_process::ShellGitPolicy::RefuseGit, }) .await; let pid = canceller.await.expect("canceller task"); @@ -1467,7 +1335,6 @@ mod tests { workspace_dir: temp.path(), timeout: Some(Duration::from_secs(10)), cancellation: Some(cancellation), - git: crate::runtime::shell_process::ShellGitPolicy::RefuseGit, }) .await; let pid = canceller.await.expect("canceller task"); @@ -1545,7 +1412,6 @@ mod tests { workspace_dir: &workspace, timeout: Some(Duration::from_mins(1)), cancellation: None, - git: crate::runtime::shell_process::ShellGitPolicy::RefuseGit, }) .await }); @@ -1564,7 +1430,6 @@ mod tests { workspace_dir: temp.path(), timeout: Some(Duration::from_secs(1)), cancellation: None, - git: ShellGitPolicy::RefuseGit, }) .await; let Err(ShellProcessError::Interrupted { reason, output }) = result else { diff --git a/src/security/git_launch.rs b/src/security/git_launch.rs index 5b5e169b9..d43ac5421 100644 --- a/src/security/git_launch.rs +++ b/src/security/git_launch.rs @@ -76,16 +76,10 @@ //! same per submodule named in the configuration or in `.gitmodules` of //! the working tree, the index or `HEAD`). //! -//! At an effective Full autonomy level (owner D1) a caller passes -//! [`GitScope::PlainRepository`]: the same cleared environment, but no -//! inspection, override, refusal or hooks path, as in the Full shell. -//! //! Callers pass [`DIFF_SAFETY_ARGS`] to every command printing a patch, -//! [`PUSH_SAFETY_ARGS`] to `push` and [`FETCH_SAFETY_ARGS`] to `fetch`, -//! `pull` and `ls-remote`: `remote..receivepack`/`uploadpack` are read -//! first-wins, so a `-c` cannot replace the repository's value, while the -//! explicit option does. A trusted value of these two keys is not used for -//! PRX's git. +//! and [`FETCH_SAFETY_ARGS`] to `fetch`, `pull` and `ls-remote`: +//! `remote..uploadpack` is read first-wins, so a `-c` cannot replace +//! the repository's value, while the explicit option does. //! //! **Residuals (time of check to time of use).** The configuration is read //! just before the command runs. A repository-controlled driver, protocol, @@ -107,10 +101,6 @@ use std::process::Stdio; /// patch PRX parses. pub const DIFF_SAFETY_ARGS: [&str; 2] = ["--no-ext-diff", "--no-textconv"]; -/// Flags every `git push` passes: the receiving program is git's own, not a -/// repository's first-wins `remote..receivepack`. -pub const PUSH_SAFETY_ARGS: [&str; 1] = ["--receive-pack=git-receive-pack"]; - /// Flags every `git fetch`, `pull` and `ls-remote` passes: the serving /// program is git's own, not a repository's first-wins /// `remote..uploadpack`. @@ -122,13 +112,6 @@ pub enum GitScope<'a> { /// An existing repository (or a directory inside one): git starts in /// that directory, and its configuration is read first. Repository(&'a Path), - /// An existing repository used at an effective Full autonomy level: - /// git runs plainly there, as in the Full shell (owner D1). Its - /// configuration is not inspected, nothing is overridden and no hooks - /// path is set, so the repository's hooks and programs run; the cleared - /// environment ([`git_environment`]) is kept, so no secret of PRX's - /// environment reaches git. - PlainRepository(&'a Path), /// A command that creates a repository (`git clone `): no /// repository configuration exists yet; the working directory is left /// to the caller. @@ -714,110 +697,6 @@ fn submodule_names(raw: &[u8]) -> Vec { .collect() } -/// Settings an operator-configured shell job's git gets through the -/// environment (D-107), where PRX cannot inspect the repository the job -/// works in: the fixed program settings ([`COMMAND_SETTINGS`], the -/// operator's system/global value or the fallback), no hook script, no bare -/// repository discovery, no `ext::` transport. -#[must_use] -pub fn operator_git_config_pairs(entries: &[ConfigEntry]) -> Vec<(String, String)> { - let mut pairs = COMMAND_SETTINGS - .iter() - .map(|(key, fallback)| { - let trusted = entries - .iter() - .rev() - .find(|entry| { - matches!(entry.scope.as_str(), "system" | "global") && entry.key.eq_ignore_ascii_case(key) - }) - .map(|entry| entry.value.clone().unwrap_or_else(|| "true".to_string())); - ((*key).to_string(), trusted.unwrap_or_else(|| (*fallback).to_string())) - }) - .collect::>(); - pairs.extend( - [("safe.bareRepository", "explicit"), ("protocol.ext.allow", "never")] - .map(|(key, value)| (key.to_string(), value.to_string())), - ); - pairs -} - -/// `GIT_CONFIG_COUNT`/`GIT_CONFIG_KEY_`/`GIT_CONFIG_VALUE_` for -/// `pairs` (command-line scope: they win over every configuration file and -/// reach every git process started below), plus `GIT_NO_LAZY_FETCH=1` (a -/// partial clone's lazy fetch would run the repository's first-wins -/// `remote..uploadpack`). -#[must_use] -pub fn git_config_environment(pairs: &[(String, String)]) -> Vec<(OsString, OsString)> { - let mut environment = vec![ - ( - OsString::from("GIT_CONFIG_COUNT"), - OsString::from(pairs.len().to_string()), - ), - (OsString::from("GIT_NO_LAZY_FETCH"), OsString::from("1")), - ]; - for (index, (key, value)) in pairs.iter().enumerate() { - environment.push((OsString::from(format!("GIT_CONFIG_KEY_{index}")), OsString::from(key))); - environment.push(( - OsString::from(format!("GIT_CONFIG_VALUE_{index}")), - OsString::from(value), - )); - } - environment -} - -/// The environment additions that harden the git of an operator-configured -/// shell job (a node allowlist entry, a system Xin task): the operator's -/// system and global configuration is read (from `/`, so no repository's -/// configuration is), and [`operator_git_config_pairs`] plus the hooks path -/// are passed through [`git_config_environment`]. A failed read falls back -/// to the fallbacks alone. -pub async fn operator_git_environment() -> anyhow::Result> { - let parent = std::env::vars_os().collect::>(); - let environment = git_environment(parent); - let neutral = if cfg!(unix) { - PathBuf::from("/") - } else { - std::env::temp_dir() - }; - let entries = match read_git( - &neutral, - &environment, - ReadKind::Listing, - &["config", "--list", "--show-scope", "--show-origin", "-z"], - ) - .await - { - Ok(raw) => parse_config_listing(&raw), - Err(error) => { - tracing::warn!(error = %error, "could not read the operator's git configuration; using the fallbacks"); - Vec::new() - } - }; - let mut pairs = operator_git_config_pairs(&entries); - let hooks = hooks_path()?; - pairs.push(("core.hooksPath".to_string(), hooks.to_string_lossy().into_owned())); - Ok(git_config_environment(&pairs)) -} - -/// Warn once per operator-configured job (a `surface` and a job key) that -/// its shell command runs git with only the environment hardening (D-107): -/// the repository's own drivers, credential helpers and transport settings -/// are not inspected there. -pub fn warn_operator_git_once(surface: &str, job: &str) { - static WARNED: std::sync::LazyLock>> = - std::sync::LazyLock::new(|| parking_lot::Mutex::new(std::collections::HashSet::new())); - let key = format!("{surface}\u{1f}{job}"); - if WARNED.lock().insert(key) { - tracing::warn!( - surface, - job, - "an operator-configured shell job runs git: fsmonitor, hook scripts, bare discovery, ext:: and lazy \ - fetch are disabled for it, but the repository's own drivers, credential helpers and transport \ - settings are not inspected" - ); - } -} - /// Whether `/.git` exists and is the repository git uses: the /// directory itself, or a `gitdir:` link file (a linked worktree, a /// submodule) pointing at it. A `core.worktree` that makes a parent (or any @@ -845,142 +724,6 @@ fn working_tree_owns_repository(toplevel: &Path, git_dir: &Path) -> bool { } } -/// Whether `program` (a path or a name) is git or one of its helper -/// programs (`git-upload-pack`, ...), in any letter case, with or without -/// `.exe`. -#[must_use] -pub fn program_is_git(program: &str) -> bool { - let name = program - .rsplit(['/', '\\']) - .next() - .unwrap_or(program) - .to_ascii_lowercase(); - let name = name.strip_suffix(".exe").unwrap_or(&name); - name == "git" || name.starts_with("git-") -} - -/// Words that precede the program of a simple shell command without being -/// it: wrappers, keywords and `!`. -const SHELL_PREFIX_WORDS: &[&str] = &[ - "sudo", "doas", "env", "command", "builtin", "exec", "nohup", "time", "nice", "ionice", "stdbuf", "timeout", - "xargs", "eval", "then", "do", "else", "elif", "if", "while", "until", "!", "{", "(", -]; - -/// Wrapper options whose next word is data, not the command to execute. -const SHELL_PREFIX_VALUE_OPTIONS: &[&str] = &[ - "-u", - "--user", - "-g", - "--group", - "-h", - "--host", - "-p", - "--prompt", - "-C", - "--close-from", - "-T", - "--command-timeout", - "--unset", - "--chdir", - "--chroot", -]; - -/// Shells whose `-c` argument is itself a command string. -const SHELLS: &[&str] = &["sh", "bash", "zsh", "dash", "ksh", "fish"]; - -/// Whether the shell command string `command` runs git (or a git helper) -/// as the program of one of its simple commands: after `;`, `&&`, `||`, -/// `|`, `&`, a newline, `$(`, a backtick or a subshell, past environment -/// assignments and wrappers (`env`, `sudo`, `xargs`, `eval`, ...), and -/// inside `sh -c`/`bash -c` strings. Quotes are removed while quoted path -/// spaces stay in their program word, so `g'i't` is `git`. This is a -/// best-effort guard: a script file or name built at run time (`$(printf git)`) -/// is not recognised. -#[must_use] -pub fn shell_command_runs_git(command: &str) -> bool { - // A Windows drive path may contain spaces before its final `git.exe`; - // splitting it into shell words would otherwise hide the program name. - let start = command.trim_start_matches(|character: char| character.is_whitespace() || character == '"'); - if start.as_bytes().get(1) == Some(&b':') - && matches!(start.as_bytes().get(2), Some(b'\\' | b'/')) - && start - .rsplit(['\\', '/']) - .next() - .and_then(|tail| tail.split_whitespace().next()) - .is_some_and(|program| program_is_git(program.trim_matches('"'))) - { - return true; - } - // Keep spaces inside literal quoted program paths in one word. A sentinel - // avoids adding a shell parser to this deliberately bounded detector. - const QUOTED_SPACE: char = '\u{1f}'; - let mut quote = None; - let mut flattened = String::with_capacity(command.len()); - for character in command.chars() { - if matches!(character, ';' | '&' | '|' | '\n' | '`' | '(' | ')' | '{' | '}') { - quote = None; - flattened.push('\n'); - continue; - } - if matches!(character, '\'' | '"') { - if quote == Some(character) { - quote = None; - } else if quote.is_none() { - quote = Some(character); - } - continue; - } - flattened.push(match character { - ' ' | '\t' if quote.is_some() => QUOTED_SPACE, - '\\' if quote.is_some() => '/', - '\\' => continue, - other => other, - }); - } - flattened.lines().any(|segment| { - let words = segment.split_whitespace().collect::>(); - let mut index = 0; - while let Some(word) = words.get(index) { - if SHELL_PREFIX_VALUE_OPTIONS.contains(word) { - index += 2; - continue; - } - let is_assignment = word.split_once('=').is_some_and(|(name, _)| { - !name.is_empty() - && name - .chars() - .all(|character| character.is_ascii_alphanumeric() || character == '_') - }); - let is_option_or_number = word.starts_with('-') || word.chars().all(|character| character.is_ascii_digit()); - if is_assignment || is_option_or_number || word.starts_with('$') || SHELL_PREFIX_WORDS.contains(word) { - index += 1; - continue; - } - break; - } - let Some(program) = words.get(index) else { - return false; - }; - if program_is_git(&program.replace(QUOTED_SPACE, " ")) { - return true; - } - let base = program.rsplit('/').next().unwrap_or(program); - SHELLS.contains(&base) - && words - .iter() - .position(|word| word.starts_with('-') && !word.starts_with("--") && word.contains('c')) - .is_some_and(|position| { - shell_command_runs_git( - &words - .get(position + 1..) - .unwrap_or_default() - .join(" ") - .replace(QUOTED_SPACE, " "), - ) - }) - }) -} - /// Read the repository at `dir`: its effective configuration with scopes /// and origins, its working tree (the launch is refused when `dir` is not /// inside it), and the submodule names of its `.gitmodules` in the working @@ -1070,7 +813,7 @@ async fn inspect_repository( /// neutralised, no hook script, `ext::` refused, no bare-repository /// discovery, no git process inside a submodule, and stdin closed. The /// caller adds the subcommand and its arguments (with -/// [`DIFF_SAFETY_ARGS`], [`PUSH_SAFETY_ARGS`] or [`FETCH_SAFETY_ARGS`] where +/// [`DIFF_SAFETY_ARGS`] or [`FETCH_SAFETY_ARGS`] where /// they apply). /// /// # Errors @@ -1089,12 +832,7 @@ async fn git_command_with_parent( scope: GitScope<'_>, parent: Vec<(OsString, OsString)>, ) -> anyhow::Result { - // Only an effective Full launch skips the hardening (and its refusals). - let hooks = if matches!(scope, GitScope::PlainRepository(_)) { - None - } else { - Some(hooks_path()?) - }; + let hooks = hooks_path()?; let mut environment = git_environment(parent); let mut overrides = if let GitScope::Repository(dir) = scope { let (entries, paths, submodules) = inspect_repository(dir, &environment).await?; @@ -1106,22 +844,19 @@ async fn git_command_with_parent( overrides.extend(repository.overrides); overrides } else { - // `clone`: no repository configuration exists yet. A plain launch - // reads none. + // `clone`: no repository configuration exists yet. Vec::new() }; - if let Some(hooks) = hooks { - overrides.extend( - ALWAYS_OVERRIDES - .iter() - .map(|(key, value)| ((*key).to_string(), (*value).to_string())), - ); - overrides.push(("core.hooksPath".to_string(), hooks.to_string_lossy().into_owned())); - } + overrides.extend( + ALWAYS_OVERRIDES + .iter() + .map(|(key, value)| ((*key).to_string(), (*value).to_string())), + ); + overrides.push(("core.hooksPath".to_string(), hooks.to_string_lossy().into_owned())); let mut command = tokio::process::Command::new("git"); command.env_clear().envs(environment).stdin(Stdio::null()); - if let GitScope::Repository(dir) | GitScope::PlainRepository(dir) = scope { + if let GitScope::Repository(dir) = scope { command.current_dir(dir); } command.arg("--no-pager"); @@ -1429,61 +1164,6 @@ mod tests { } } - #[test] - fn shell_command_strings_that_run_git_are_recognised() { - for command in [ - "git status", - " git push origin main", - "cd repo && git status", - "ls; git log", - "echo x | xargs git add", - "GIT_DIR=x git log", - "env -i PATH=/usr/bin git status", - "sudo -u prx git pull", - "sudo --user prx git pull", - "doas -u prx git status", - "env -u GIT_CONFIG_PARAMETERS git status", - "/usr/bin/git status", - "C:\\Program Files\\Git\\bin\\git.exe status", - "echo ready; \"C:\\Program Files\\Git\\bin\\git.exe\" status", - "sudo -u prx \"C:\\Program Files\\Git\\bin\\git.exe\" status", - "echo ready; \"/tmp/Program Files/git\" status", - "GIT status", - "g'i't status", - "\"git\" status", - "sh -c 'git status'", - "bash -lc \"cd x && git fetch\"", - "echo $(git rev-parse HEAD)", - "echo `git rev-parse HEAD`", - "(git status)", - "if true; then git status; fi", - "git-upload-pack /repo", - "eval git status", - "nice -n 5 git gc", - ] { - assert!(shell_command_runs_git(command), "{command}"); - } - for command in [ - "echo git", - "ls -la", - "gitleaks detect", - "cat .gitignore", - "grep -r git src", - "npm run build", - "gh pr list", - "echo 'use git later'", - "sh -c 'ls'", - "sudo -u git echo ready", - "echo C:\\Program Files\\Git\\bin\\git.exe", - "echo ready; echo \"/tmp/Program Files/git\"", - ] { - assert!(!shell_command_runs_git(command), "{command}"); - } - assert!(program_is_git("/usr/local/bin/git")); - assert!(program_is_git("GIT.EXE")); - assert!(!program_is_git("gitk")); - } - #[test] fn a_later_operator_value_wins_without_an_override() { let later = ConfigEntry { @@ -1841,9 +1521,7 @@ mod tests { let mut push = git_command_with_parent(GitScope::Repository(&repo), parent_with_home(&home)) .await .expect("test: safe launch"); - push.arg("push") - .args(PUSH_SAFETY_ARGS) - .args(["origin", "HEAD:refs/heads/main"]); + push.arg("push").args(["origin", "HEAD:refs/heads/main"]); let output = run(push).await; assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); let mut fetch = git_command_with_parent(GitScope::Repository(&repo), parent_with_home(&home)) @@ -2023,7 +1701,7 @@ mod tests { let mut command = git_command_with_parent(GitScope::Repository(&repo), parent_with_home(&home)) .await .expect("test: launch"); - command.arg("push").args(PUSH_SAFETY_ARGS).args(["origin", "HEAD"]); + command.arg("push").args(["origin", "HEAD"]); let output = tokio::time::timeout( std::time::Duration::from_mins(1), crate::runtime::shell_process::run_managed_output(command), @@ -2219,34 +1897,4 @@ mod tests { assert!(error.to_string().contains("does not hold the repository"), "{error}"); } - /// D-107: an operator shell job's git gets the fixed program settings - /// (the operator's values or the fallbacks) and the forced settings - /// through `GIT_CONFIG_*`, plus `GIT_NO_LAZY_FETCH`. - #[test] - fn operator_shell_jobs_get_the_fixed_settings_through_the_environment() { - let pairs = operator_git_config_pairs(&[ - global("core.sshcommand", "ssh -i key"), - local("core.fsmonitor", "./evil"), - ]); - for expected in [ - pair("core.sshcommand", "ssh -i key"), - pair("core.fsmonitor", "false"), - pair("safe.bareRepository", "explicit"), - pair("protocol.ext.allow", "never"), - ] { - assert!(pairs.contains(&expected), "{expected:?}: {pairs:?}"); - } - let environment = - git_config_environment(&[pair("core.fsmonitor", "false"), pair("core.hooksPath", "/dev/null")]); - let value = |name: &str| { - environment - .iter() - .find(|(key, _)| key == name) - .map(|(_, value)| value.to_string_lossy().into_owned()) - }; - assert_eq!(value("GIT_CONFIG_COUNT").as_deref(), Some("2")); - assert_eq!(value("GIT_CONFIG_KEY_1").as_deref(), Some("core.hooksPath")); - assert_eq!(value("GIT_CONFIG_VALUE_1").as_deref(), Some("/dev/null")); - assert_eq!(value("GIT_NO_LAZY_FETCH").as_deref(), Some("1")); - } } diff --git a/src/tools/shell.rs b/src/tools/shell.rs index 307af5399..65c62bd35 100644 --- a/src/tools/shell.rs +++ b/src/tools/shell.rs @@ -9,26 +9,11 @@ use serde_json::json; use std::sync::Arc; use tokio_util::sync::CancellationToken; -/// The git policy of a shell command at an effective autonomy `level`: -/// plain git at Full, refused below. Skill scripts, cron jobs and Xin tasks -/// at an effective Full level reuse it, so Full git behaves the same on -/// every shell path. -pub(crate) const fn shell_git_policy( - level: crate::security::AutonomyLevel, -) -> crate::runtime::shell_process::ShellGitPolicy { - use crate::runtime::shell_process::ShellGitPolicy::{PlainGit, RefuseGit}; - use crate::security::AutonomyLevel::Full; - match level { - Full => PlainGit, - _ => RefuseGit, - } -} - /// Direct host shell command execution tool. /// /// Authorization belongs to the orchestration boundary. This executor passes /// command text unchanged to the configured runtime after checking path arguments -/// against its execution root. Runtime authority selects git and environment policy. +/// against its execution root. pub struct ShellTool { process: ShellProcessAdapter, workspace_dir: std::path::PathBuf, @@ -69,7 +54,6 @@ impl ShellTool { ShellProcessError::Cancelled => TOOL_EXECUTION_CANCELLED.to_string(), ShellProcessError::Timeout(timeout) => format!("Command timed out after {timeout:?} and was killed"), ShellProcessError::Runtime(error) => format!("Failed to build runtime command: {error}"), - ShellProcessError::GitRefused => ShellProcessError::GitRefused.to_string(), ShellProcessError::Spawn(error) | ShellProcessError::Wait(error) | ShellProcessError::Output(error) => { format!("Failed to execute command: {error}") } @@ -113,9 +97,6 @@ impl ShellTool { workspace_dir: &self.workspace_dir, timeout: None, cancellation, - git: shell_git_policy( - super::effective_autonomy::current().unwrap_or(crate::security::AutonomyLevel::Supervised), - ), }) .await { diff --git a/src/tools/shell_parity_tests.rs b/src/tools/shell_parity_tests.rs index 8a35d8069..8c7989c88 100644 --- a/src/tools/shell_parity_tests.rs +++ b/src/tools/shell_parity_tests.rs @@ -109,36 +109,6 @@ async fn full_shell_runs_git_and_repository_hook() { ); } -#[tokio::test] -async fn restricted_shell_refuses_git_before_spawn() { - let root = tempfile::tempdir().expect("test: root"); - for level in [AutonomyLevel::Supervised, AutonomyLevel::ReadOnly] { - let result = tokio::time::timeout( - Duration::from_secs(5), - effective_autonomy::scope( - level, - shell(root.path()).execute_named_observed( - "shell", - json!({"command":"git -c user.name=t -c user.email=t@t commit --allow-empty -m x"}), - None, - ), - ), - ) - .await - .expect("test: deadline") - .expect("test: result"); - assert!(!result.result.success, "test: restricted git denied"); - assert!(result.process.as_ref().is_some_and(|p| !p.started), "test: zero spawn"); - assert!( - result - .process - .and_then(|p| p.diagnostic) - .is_some_and(|e| e.contains("git")), - "test: git refusal diagnostic" - ); - } -} - #[tokio::test] async fn full_shell_environment_keeps_proxy_and_strips_credentials() { const PROBE: &str = "PRX_FULL_ENV_TEST"; @@ -247,31 +217,6 @@ async fn dispatch( .expect("test: dispatch deadline") } -#[tokio::test] -async fn supervised_approval_does_not_enable_git() { - let root = tempfile::tempdir().expect("test: workspace"); - let outcome = dispatch( - &service(root.path(), AutonomyLevel::Supervised), - context(), - "shell", - json!({"command":"git status"}), - ) - .await; - assert_eq!( - outcome.status, - ToolExecutionStatus::Failed, - "test: approved shell reaches refusal" - ); - assert!( - outcome.process.as_ref().is_some_and(|process| !process.started - && process - .diagnostic - .as_deref() - .is_some_and(|error| error.contains("refusing to run git through the shell"))), - "test: GitRefused before spawn: {outcome:?}" - ); -} - #[tokio::test] async fn configured_workdir_is_shared_by_shell_files_and_git() { let workspace = tempfile::tempdir().expect("test: workspace"); diff --git a/src/tools/skills.rs b/src/tools/skills.rs index 182b727d9..1a93a6460 100644 --- a/src/tools/skills.rs +++ b/src/tools/skills.rs @@ -1473,11 +1473,6 @@ impl SkillExecuteTool { workspace_dir: root, timeout, cancellation, - // The call's carried level, fail-closed like the shell tool: git - // runs plainly only at an effective Full level (owner D1). - git: super::shell::shell_git_policy( - super::effective_autonomy::current().unwrap_or(crate::security::AutonomyLevel::Supervised), - ), }; // A deadline marks a managed run, which is also joined: the process // group ends with its leader. diff --git a/src/xin/runner.rs b/src/xin/runner.rs index 4da0be92f..d0953cb3f 100644 --- a/src/xin/runner.rs +++ b/src/xin/runner.rs @@ -1044,31 +1044,6 @@ fn task_run_level(config: &Config, task: &XinTask) -> Result crate::runtime::shell_process::ShellGitPolicy { - if crate::tools::effective_autonomy::current() == Some(crate::security::AutonomyLevel::Full) { - return crate::tools::shell::shell_git_policy(crate::security::AutonomyLevel::Full); - } - let operator = task.kind == crate::xin::types::TaskKind::System - || store::task_created_via(config, &task.id) - .is_ok_and(|creator| creator == crate::cron::JobCreator::OperatorCli); - if operator { - if crate::security::git_launch::shell_command_runs_git(&task.payload) { - crate::security::git_launch::warn_operator_git_once("xin", &task.id); - } - crate::runtime::shell_process::ShellGitPolicy::HardenGit - } else { - crate::runtime::shell_process::ShellGitPolicy::RefuseGit - } -} - async fn run_shell_with_adapter( config: &Config, task: &XinTask, @@ -1081,7 +1056,6 @@ async fn run_shell_with_adapter( workspace_dir: &config.workspace_dir, timeout: None, cancellation, - git: shell_git_policy(config, task), }) .await { @@ -1178,96 +1152,6 @@ mod tests { assert_eq!(tasks.len(), 3); // No duplicates } - /// D-107: only a system task (built-in or the operator's `HEARTBEAT.md`) - /// is operator-configured; any other Xin shell task may come from a - /// tool, so its git is refused. - #[test] - fn only_system_xin_tasks_run_git_hardened() { - let tmp = TempDir::new().unwrap(); - let config = test_config(&tmp); - let task = |name: &str, kind: TaskKind| { - store::add_task( - &config, - &NewXinTask { - owner_id: None, - topic_id: None, - parent_task_id: None, - source_message_event_id: None, - name: name.to_string(), - description: None, - kind, - priority: TaskPriority::Low, - execution_mode: ExecutionMode::Shell, - payload: "git pull".to_string(), - recurring: false, - interval_secs: 60, - max_failures: 1, - approval_grant_json: None, - }, - ) - .unwrap() - }; - assert_eq!( - shell_git_policy(&config, &task("system", TaskKind::System)), - crate::runtime::shell_process::ShellGitPolicy::HardenGit - ); - for (name, kind) in [("user", TaskKind::User), ("agent", TaskKind::Agent)] { - assert_eq!( - shell_git_policy(&config, &task(name, kind)), - crate::runtime::shell_process::ShellGitPolicy::RefuseGit, - "{name}" - ); - } - // D-107 amendment: `prx xin add` records the operator; a task stored - // before that is refused until marked, and an agent tool rewriting an - // operator task's command makes it an agent task again. - let operator = store::add_task_with_origin_and_creator( - &config, - &NewXinTask { - owner_id: None, - topic_id: None, - parent_task_id: None, - source_message_event_id: None, - name: "operator".to_string(), - description: None, - kind: TaskKind::User, - priority: TaskPriority::Low, - execution_mode: ExecutionMode::Shell, - payload: "git pull".to_string(), - recurring: false, - interval_secs: 60, - max_failures: 1, - approval_grant_json: None, - }, - &crate::tools::execution::JobOrigin::LocalOperator, - crate::cron::JobCreator::OperatorCli, - ) - .unwrap(); - assert_eq!( - shell_git_policy(&config, &operator), - crate::runtime::shell_process::ShellGitPolicy::HardenGit - ); - let rewritten = store::update_task( - &config, - &operator.id, - &crate::xin::types::XinTaskPatch { - payload: Some("git push".to_string()), - ..crate::xin::types::XinTaskPatch::default() - }, - ) - .unwrap(); - assert_eq!( - shell_git_policy(&config, &rewritten), - crate::runtime::shell_process::ShellGitPolicy::RefuseGit - ); - let legacy = task("legacy", TaskKind::User); - store::mark_task_operator(&config, &legacy.id).unwrap(); - assert_eq!( - shell_git_policy(&config, &legacy), - crate::runtime::shell_process::ShellGitPolicy::HardenGit - ); - } - #[test] fn register_builtin_tasks_disables_retired_duplicate_schedules() { let tmp = TempDir::new().unwrap(); diff --git a/src/xin/store.rs b/src/xin/store.rs index d686892f9..cdbff381b 100644 --- a/src/xin/store.rs +++ b/src/xin/store.rs @@ -213,21 +213,6 @@ pub fn due_tasks(config: &Config, now: DateTime) -> Result> { }) } -/// Apply a partial update to an existing task. -/// Which surface created the task (D-107 amendment); NULL is `agent_tool`. -pub fn task_created_via(config: &Config, task_id: &str) -> Result { - with_connection(config, |conn| { - let value = conn - .query_row( - "SELECT created_via FROM xin_tasks WHERE id = ?1", - params![task_id], - |row| row.get::<_, Option>(0), - ) - .with_context(|| format!("xin task '{task_id}' not found"))?; - Ok(JobCreator::from_stored(value.as_deref())) - }) -} - /// The stored creator of a task, or of the goal a step belongs to: which /// surface created it (NULL is `agent_tool`) and the creating call's level /// and agent (an unreadable stamp reads as empty). @@ -267,7 +252,7 @@ fn stored_creator(conn: &Connection, task_or_step_id: &str) -> Result<(JobCreato } /// Record that the operator vouches for a task as their own (`prx xin -/// mark-operator`): its shell command may then run git, hardened. +/// mark-operator`): its runs then use the operator level. pub fn mark_task_operator(config: &Config, task_id: &str) -> Result<()> { let changed = with_connection(config, |conn| { conn.execute( @@ -2993,7 +2978,7 @@ fn with_connection(config: &Config, f: impl FnOnce(&Connection) -> Result) add_column_if_missing(&conn, "xin_tasks", "origin", "TEXT")?; // D-107 amendment: which surface created the task. Nullable with no // backfill: a row stored before the column existed reads as - // `agent_tool` (its git is refused) until the operator marks it. + // `agent_tool` until the operator marks it. add_column_if_missing(&conn, "xin_tasks", "created_via", "TEXT")?; add_column_if_missing(&conn, "xin_goals", "origin", "TEXT")?; // The creating call's level and agent. Nullable with no backfill: a row @@ -4706,7 +4691,7 @@ mod tests { new.payload = "echo initial".into(); let task = add_task(&config, &new).unwrap(); mark_task_operator(&config, &task.id).unwrap(); - assert_eq!(task_created_via(&config, &task.id).unwrap(), JobCreator::OperatorCli); + assert_eq!(task_creator(&config, &task.id).unwrap().0, JobCreator::OperatorCli); let updated = update_task( &config, @@ -4718,7 +4703,7 @@ mod tests { ) .unwrap(); assert_eq!(updated.payload, "git status"); - assert_eq!(task_created_via(&config, &task.id).unwrap(), JobCreator::AgentTool); + assert_eq!(task_creator(&config, &task.id).unwrap().0, JobCreator::AgentTool); } } diff --git a/tests/architecture_boundaries/process.rs b/tests/architecture_boundaries/process.rs index ba3f3b459..d8094eb2c 100644 --- a/tests/architecture_boundaries/process.rs +++ b/tests/architecture_boundaries/process.rs @@ -236,10 +236,8 @@ fn every_live_hook_manager_owner_drains_at_shutdown() { /// catalogue, the doctor's `git --version` probe, a protocol name). const ALLOWED_GIT_PROGRAM_LITERALS: &[&str] = &[ "src/doctor/mod.rs::check_environment::git", - "src/doctor/mod.rs::check_unowned_shell_jobs::git", "src/security/git_launch.rs::command_fallback::git", "src/security/git_launch.rs::git_command_with_parent::git", - "src/security/git_launch.rs::program_is_git::git", "src/security/git_launch.rs::read_git::git", "src/security/policy.rs::command_risk_level::git", "src/security/policy.rs::is_args_safe::git", @@ -467,56 +465,10 @@ pub(super) fn process_command_types_are_never_aliased() { assert_inventory("aliased process command types", actual, &[]); } -/// GIT-ENV (D-106, D-107 and its amendment): git in a shell command string -/// is ordinary only at an effective Full level. Below it, restricted shells, -/// workspace skill scripts, cron jobs and Xin tasks an agent tool created -/// refuse it; git is hardened -/// through the environment on the operator's (`prx cron`/`prx xin` jobs, -/// system Xin tasks, node allowlists). +/// The shell and native file tools read the per-call effective level, never +/// the global autonomy setting. #[test] -fn shell_sites_refuse_or_harden_git() { - let body = |relative: &str, function: &str| { - let source = fs::read_to_string(repository_root().join(relative)) - .unwrap_or_else(|error| panic!("read {relative}: {error}")); - function_body(&production_part(&source), function) - }; - // `execute` and `execute_joined` both run `execute_with`, the one body. - let adapter = body("src/runtime/shell_process.rs", "execute_with"); - for required in [ - "git_launch::shell_command_runs_git(request.command)", - "ShellProcessError::GitRefused", - "git_launch::operator_git_environment()", - ] { - assert!( - adapter.contains(required), - "ShellProcessAdapter::execute_with must use {required}" - ); - } - assert!( - body("src/tools/skills.rs", "execute_resolved") - .chars() - .filter(|c| !c.is_whitespace()) - .collect::() - .contains("git:super::shell::shell_git_policy(super::effective_autonomy::current().unwrap_or(crate::security::AutonomyLevel::Supervised),)"), - "workspace skill execution must still refuse git below an effective Full level" - ); - let policy = body("src/tools/shell.rs", "shell_git_policy"); - let policy = policy - .split_once('{') - .expect("test: policy body") - .1 - .strip_suffix('}') - .expect("test: policy end"); - let compact: String = policy.chars().filter(|c| !c.is_whitespace()).collect(); - assert_eq!( - compact, - "usecrate::runtime::shell_process::ShellGitPolicy::{PlainGit,RefuseGit};usecrate::security::AutonomyLevel::Full;matchlevel{Full=>PlainGit,_=>RefuseGit,}", - "shell git policy must widen only effective Full" - ); - assert!( - body("src/tools/shell.rs", "execute_inner").contains("git: shell_git_policy("), - "shell must select git policy at invocation" - ); +fn native_tools_read_the_per_call_level() { for relative in [ "src/tools/shell.rs", "src/tools/file_read.rs", @@ -535,18 +487,6 @@ fn shell_sites_refuse_or_harden_git() { "test: {relative} must not widen from global autonomy" ); } - let shell = body("src/tools/shell.rs", "execute_inner"); - let compact: String = shell.chars().filter(|c| !c.is_whitespace()).collect(); - assert!(compact.contains("git:shell_git_policy(super::effective_autonomy::current().unwrap_or(crate::security::AutonomyLevel::Supervised),)"), "test: shell selector must use the fail-closed per-call level"); - // D-107 amendment: cron and Xin decide by the recorded creator. - assert!( - body("src/cron/scheduler.rs", "run_job_command_with_adapter").contains("git: shell_git_policy(config, job)") - ); - assert!(body("src/cron/scheduler.rs", "shell_git_policy").contains("job_created_via(")); - assert!(body("src/xin/runner.rs", "run_shell_with_adapter").contains("git: shell_git_policy(config, task)")); - let xin = body("src/xin/runner.rs", "shell_git_policy"); - assert!(xin.contains("TaskKind::System") && xin.contains("task_created_via(")); - assert!(body("src/nodes/server.rs", "execute_shell_command").contains("git_launch::operator_git_environment()")); } /// Every production `git` process is built by the one hardened launch @@ -629,38 +569,6 @@ fn stdio_mcp_launches_start_from_a_cleared_environment() { } } -/// Plain git is an explicit Full-shell exception. Every production spelling is reviewed. -#[test] -pub(super) fn plain_git_policy_has_only_the_reviewed_production_sites() { - let mut actual = Vec::new(); - for path in rust_source_files() { - let relative = relative_path(&path); - let production = production_part(&read_source(&path)); - let lines: Vec<_> = production.lines().collect(); - for (index, line) in lines.iter().enumerate() { - if line.trim_start().starts_with("//") { - continue; - } - if line.contains("PlainGit") { - actual.push(format!( - "{relative}::{}::{}", - enclosing_function(&lines, index), - normalize_line(line) - )); - } - } - } - assert_inventory( - "production PlainGit policy uses", - actual, - &[ - "src/runtime/shell_process.rs::shell_secret_environment::PlainGit,", - "src/tools/shell.rs::shell_git_policy::Full => PlainGit,", - "src/tools/shell.rs::shell_git_policy::use crate::runtime::shell_process::ShellGitPolicy::{PlainGit, RefuseGit};", - ], - ); -} - /// Root inputs and selection belong to one helper and its reviewed consumers. #[test] pub(super) fn native_working_root_selection_sites_are_explicit() { diff --git a/tests/architecture_boundaries/scanner_probes.rs b/tests/architecture_boundaries/scanner_probes.rs index d7fb6fd28..70554674b 100644 --- a/tests/architecture_boundaries/scanner_probes.rs +++ b/tests/architecture_boundaries/scanner_probes.rs @@ -49,7 +49,7 @@ use super::payload_free_logs::log_lines_carry_only_typed_metadata; use super::process::{ every_production_process_command_is_inventoried, git_is_named_only_in_the_reviewed_places, git_runs_only_through_the_hardened_launch, native_working_root_selection_sites_are_explicit, - plain_git_policy_has_only_the_reviewed_production_sites, process_command_types_are_never_aliased, + process_command_types_are_never_aliased, }; use super::providers::{ agent_entries_reach_provider_factories_only_through_the_scoped_selection, @@ -292,9 +292,6 @@ planted_violation_probes! { "src/tools/d0_planted_probe.rs", Planted::NewFile, Reads::ProductionText, "fn d0_root(config: Config) { let _ = config.runtime.workdir.unwrap_or(config.workspace_dir); }\n"; - probe_plain_git_policy: plain_git_policy_has_only_the_reviewed_production_sites, - "src/tools/d0_planted_probe.rs", Planted::NewFile, Reads::ProductionText, - "fn d0_policy() { let _ = crate::runtime::shell_process::ShellGitPolicy::PlainGit; }\n"; probe_panic_restriction_group: production_has_no_panic_shortcuts, "src/panic_policy_probe.rs", Planted::NewFile, Reads::ProductionText, "#[allow(clippy::restriction)] fn a() {}\n"; diff --git a/tests/int_p1_cross_module.rs b/tests/int_p1_cross_module.rs index 1946da757..ad60b4d28 100644 --- a/tests/int_p1_cross_module.rs +++ b/tests/int_p1_cross_module.rs @@ -641,7 +641,6 @@ async fn int_tr_05_direct_shell_process_has_no_sandbox_selection() { workspace_dir: workspace.path(), timeout: Some(Duration::from_secs(5)), cancellation: None, - git: openprx::runtime::shell_process::ShellGitPolicy::RefuseGit, }) .await .unwrap(); From a9fbb699a34f449f8b81e92a81f76da684a052dd Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:17:56 +0400 Subject: [PATCH 0113/1567] fix(sessions): root process-child tools and policy at the parent workspace The worker's private directory held the shell working root, so relative writes were removed with the directory on cleanup, and skills, MCP and Pushover saw an empty workspace. The private directory now only holds the worker's own state; tools, the security policy root and the working root use the authenticated parent workspace. --- src/session_worker/runner/run.rs | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/src/session_worker/runner/run.rs b/src/session_worker/runner/run.rs index a3d4ce3e2..199b533b1 100644 --- a/src/session_worker/runner/run.rs +++ b/src/session_worker/runner/run.rs @@ -422,6 +422,20 @@ async fn run_owned_manifest( }) .context("session-worker signed configuration binding missing")?; config.runtime.workdir = binding.working_root.clone(); + // Tool and policy root: the authenticated parent workspace. The worker's + // private `manifest.workspace_dir` only holds the worker's own state (sealed + // snapshot, isolated database, identity copy, cleanup target). + let parent_workspace = PathBuf::from(source_workspace); + let tool_working_root = binding + .working_root + .clone() + .unwrap_or_else(|| parent_workspace.clone()); + let working_root_sealed: bool = binding.working_root.is_some(); + tracing::info!( + tool_root = "parent_workspace", + working_root_sealed, + "session worker roots tools at the parent workspace" + ); let operator_snapshots = if manifest.operator_source.is_some() { Some(super::operator_source::restore( @@ -471,10 +485,16 @@ async fn run_owned_manifest( // FIX-P1-31: honour the configured `security.audit` block on the gate audit path. let security = Arc::new(SecurityPolicy { autonomy: level, - ..SecurityPolicy::from_config(&config.autonomy, &manifest.workspace_dir) + ..SecurityPolicy::from_config(&config.autonomy, &parent_workspace) .with_audit_config(config.security.audit.clone()) }); + // Config view for workspace-rooted tools. `config.runtime.workdir` itself + // stays as sealed (the seal check compares it); only this copy changes. + let mut tool_config = config.clone(); + tool_config.workspace_dir = parent_workspace.clone(); + tool_config.runtime.workdir = Some(tool_working_root); + let provider_runtime_options = crate::providers::provider_runtime_options_from_config(&config); #[cfg(feature = "wasm-plugins")] @@ -629,7 +649,7 @@ async fn run_owned_manifest( extensions }; let mut full_tools = tools::all_tools_with_runtime_ext_and_extensions( - Arc::new(config.clone()), + Arc::new(tool_config.clone()), shared_config.clone(), &security, runtime, @@ -638,10 +658,10 @@ async fn run_owned_manifest( composio_entity_id, &config.browser, &config.http_request, - &manifest.workspace_dir, + &parent_workspace, &config.agents_with_references(), credentials.root_api_key, - &config, + &tool_config, extensions, Some(Arc::clone(&hooks)), ) From 9df30f1d05bdda8df6329494817875000312eda5 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:36:16 +0400 Subject: [PATCH 0114/1567] fix(sessions): load process-child hooks and prompt skills from the parent workspace Workspace hooks and the worker prompt's skills now come from the parent workspace, matching the tool registry. Document the worker directory split. --- docs/configuration.md | 2 ++ src/session_worker/runner/prompt.rs | 17 ++++++----------- src/session_worker/runner/run.rs | 8 +++++--- 3 files changed, 13 insertions(+), 14 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index e447d5d03..7d011c1a0 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1293,6 +1293,8 @@ PRX treats `chat`, `agent`, `gateway`, `channel`, `delegate`, and `sessions_spaw For `sessions_spawn`, `task` runs an in-process sub-agent and `process` launches a worker process. Process mode uses a manifest with `memory_strategy`, `shared_memory_db_path`, and `worker_memory_db_path`; the default `shared_fabric` strategy writes worker events into the parent workspace fabric while still keeping the execution boundary explicit. Set `[sessions_spawn].process_memory_strategy = "isolated_private"` for a private worker DB. `hybrid` is fail-closed because no production merge consumer or merge/reject/ack/cleanup protocol exists; use `shared_fabric` or `isolated_private` instead. +A process worker keeps a private per-run directory (`/workers/` unless `worker_workspace_root` is set) for its own state only: the sealed manifest snapshot, the isolated memory database, the identity copy and the cleanup target. Its tools, security policy root, hooks and prompt skills use the parent workspace, and its shell and file working directory is the sealed `runtime.workdir` or, when that is unset, the parent workspace. Files a process child writes by relative path therefore persist in the parent workspace after `cleanup_on_complete` removes the private directory, and the child sees the workspace skills, `mcp.json` and `.env` like a task child. + Recursive child delegation is the default: a child session equals the main session, so a spawn without `allow_delegation` (or with `true`) lets the child spawn its own children, and an explicit `allow_delegation: false` makes a diff --git a/src/session_worker/runner/prompt.rs b/src/session_worker/runner/prompt.rs index db6555106..25c0c3080 100644 --- a/src/session_worker/runner/prompt.rs +++ b/src/session_worker/runner/prompt.rs @@ -22,14 +22,11 @@ fn resolve_system_prompt(manifest: &WorkerManifest) -> String { /// prompt as the final, task-specific section, but make the common execution /// contract identical to the other agentic entrypoints. pub(super) fn build_worker_system_prompt(manifest: &WorkerManifest, config: &Config, native_tools: bool) -> String { - // The worker may use an isolated workspace. Prompt rendering must describe - // that workspace (and load its skills), rather than the parent process's - // configured workspace path. - let mut worker_config = config.clone(); - worker_config.workspace_dir = manifest.workspace_dir.clone(); - - let skills = crate::skills::load_skills_with_config(&manifest.workspace_dir, &worker_config); - build_worker_system_prompt_with_skills(manifest, &worker_config, native_tools, &skills) + // `config` is the worker's tool view: its workspace is the parent workspace, + // which the prompt describes and loads skills from. The worker's private + // directory only holds its own state (and the identity copy, read below). + let skills = crate::skills::load_skills_with_config(&config.workspace_dir, config); + build_worker_system_prompt_with_skills(manifest, config, native_tools, &skills) } pub(super) fn build_worker_system_prompt_with_skills( @@ -38,10 +35,8 @@ pub(super) fn build_worker_system_prompt_with_skills( native_tools: bool, skills: &[crate::skills::Skill], ) -> String { - let mut worker_config = config.clone(); - worker_config.workspace_dir = manifest.workspace_dir.clone(); crate::agent::runtime_prompt::build_delegated_system_prompt( - &worker_config, + config, &manifest.model, skills, native_tools, diff --git a/src/session_worker/runner/run.rs b/src/session_worker/runner/run.rs index 199b533b1..98feb77f5 100644 --- a/src/session_worker/runner/run.rs +++ b/src/session_worker/runner/run.rs @@ -624,7 +624,7 @@ async fn run_owned_manifest( let runtime: Arc = Arc::from(runtime::create_runtime(&config.runtime)?); let shared_config = crate::config::new_shared(config.clone()); - let hooks = Arc::new(HookManager::new(manifest.workspace_dir.clone()).with_config(Arc::clone(&shared_config))); + let hooks = Arc::new(HookManager::new(parent_workspace.clone()).with_config(Arc::clone(&shared_config))); #[cfg(feature = "wasm-plugins")] if let Some(plugin_runtime) = &wasm_plugin_runtime { hooks.set_plugin_runtime(Arc::clone(plugin_runtime)).await; @@ -969,6 +969,7 @@ async fn run_owned_manifest( let memory_ref = &memory; let provider_name_ref: &str = &manifest.provider_name; let model_ref: &str = &manifest.model; + // The tool-execution ledger is worker state, not a tool root. let workspace_dir_ref: &Path = &manifest.workspace_dir; let compaction_config_ref = manifest.compaction_config.as_ref(); let multimodal_ref = &config.multimodal; @@ -984,6 +985,7 @@ async fn run_owned_manifest( let raw_task = manifest.task.as_str(); let manifest_ref = &manifest; let config_ref = &config; + let prompt_config_ref = &tool_config; // The relay needs all three: the parent sealed it, the pipe is // authenticated, and the stdin reader that carries decisions is running. let approval_relay = @@ -1035,14 +1037,14 @@ async fn run_owned_manifest( match turn.prompt_skills() { Ok(skills) => Some(build_worker_system_prompt_with_skills( manifest_ref, - config_ref, + prompt_config_ref, native_tools, &skills, )), Err(error) => return (segment_history, Err(error)), } } else if segment_history.first().is_none_or(|message| message.role != "system") { - Some(build_worker_system_prompt(manifest_ref, config_ref, native_tools)) + Some(build_worker_system_prompt(manifest_ref, prompt_config_ref, native_tools)) } else { None }; From e3a118ebc9337bd35622138668e45b3e9d3a0821 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:04:54 +0400 Subject: [PATCH 0115/1567] fix(skills): skip the executable-skill review requirement at Full Removed restriction: running a lifecycle-managed executable skill required an operator review receipt at every autonomy level, so a learned, edited or git-installed revision was refused even at Full. At an effective Full level outside the evaluation sandbox the untrusted-origin marker refusal, the review-lineage check and the changed-since-review check are skipped. Supervised and below keep them. Pin and bundle digest verification, strict manifest and tool validation, staging read-back and the pre-spawn file hash check are unchanged. --- docs/skill-lifecycle.md | 6 +++++- src/skills/lifecycle/executable.rs | 20 +++++++++++++++++--- src/skills/lifecycle/tests/executable.rs | 1 + src/tools/skills/execute_managed.rs | 6 ++++++ 4 files changed, 29 insertions(+), 4 deletions(-) diff --git a/docs/skill-lifecycle.md b/docs/skill-lifecycle.md index 5fadb077c..c443b611c 100644 --- a/docs/skill-lifecycle.md +++ b/docs/skill-lifecycle.md @@ -352,7 +352,11 @@ SL11 adds reviewed executable revisions: a bundle with scripts or declared from it in `SKILL.md` only, with every other file and mode byte-identical. A store migrated before SL11, a rollback to an unreviewed revision and any hand-written candidate are refused with an instruction to re-import the - directory through `lifecycle_import_executable`. The whole bundle is verified, + directory through `lifecycle_import_executable`. At an effective Full level + (outside the evaluation sandbox) none of this review is required: the + untrusted-origin marker, the review lineage and the change-since-review + checks are skipped, so a learned, edited or git-installed revision runs. + Supervised and below keep the review. The whole bundle is verified, staged into a private run directory with its exact modes, verified again, and the files the tool runs are hashed once more immediately before the process spawns; a tampered or missing file fails the call. Arguments must be names the diff --git a/src/skills/lifecycle/executable.rs b/src/skills/lifecycle/executable.rs index a27baf656..4c3341795 100644 --- a/src/skills/lifecycle/executable.rs +++ b/src/skills/lifecycle/executable.rs @@ -277,8 +277,15 @@ fn check_tool(bundle: &Bundle, tool: &SkillTool) -> Result<(), ExecutableError> /// was built, and the result of this review is bound to the complete bundle /// hash, which covers every script, reference and mode. pub fn review_executable_bundle(bundle: &Bundle) -> Result { + review_bundle(bundle, false) +} + +/// The structural review of [`review_executable_bundle`]. `allow_untrusted` +/// skips only the untrusted-origin marker refusal (an operator-review +/// concern); every structural check still applies. +fn review_bundle(bundle: &Bundle, allow_untrusted: bool) -> Result { validate_manifest_strict(bundle).map_err(LifecycleError::from)?; - if bundle.file(UNTRUSTED_ORIGIN_MARKER).is_some() { + if !allow_untrusted && bundle.file(UNTRUSTED_ORIGIN_MARKER).is_some() { return Err(ExecutableError::UntrustedOrigin); } let tools = declared_tools(bundle)?; @@ -560,6 +567,11 @@ pub struct PrepareRequest<'a> { pub task_id: Option<&'a str>, pub arguments: Option<&'a serde_json::Value>, pub grant: &'a dyn ToolGrant, + /// True for a call at an effective Full level outside the evaluation + /// sandbox: the operator-review requirements (untrusted-origin marker, + /// review lineage, change since review) are skipped. The pin, bundle + /// digest and staging integrity checks always apply. + pub skip_review: bool, } /// Resolves a declared tool of a lifecycle-managed skill and stages it. @@ -587,8 +599,10 @@ pub fn prepare_execution(request: &PrepareRequest<'_>) -> Result Date: Wed, 25 Nov 2026 01:06:12 +0400 Subject: [PATCH 0116/1567] fix(skills): run managed skill scripts with the Full shell environment at Full Removed restriction: a managed skill script ran with only PATH, LANG, LC_*, TZ and HOME set to the skill run directory, while the Full shell tool strips only secret variables. At an effective Full level outside the evaluation sandbox the script now gets the Full shell environment (everything except the stripped secrets, real HOME). Below Full the contained environment is unchanged. --- docs/skill-lifecycle.md | 5 +++- src/runtime/shell_process.rs | 45 ++++++++++++++++++++++++++++++++---- src/tools/skills.rs | 9 +++++++- 3 files changed, 53 insertions(+), 6 deletions(-) diff --git a/docs/skill-lifecycle.md b/docs/skill-lifecycle.md index c443b611c..065b78aed 100644 --- a/docs/skill-lifecycle.md +++ b/docs/skill-lifecycle.md @@ -376,7 +376,10 @@ SL11 adds reviewed executable revisions: a bundle with scripts or declared native runtime the process starts with an empty environment plus `PATH`, `LANG`, `LC_*` and `TZ` from the parent, `HOME` set to its run directory, `TMPDIR` inside it, and the `PRX_SKILL_ARG_*` values of the call, so no provider key, - token or credential reaches it. Unmanaged shell callers are unchanged. + token or credential reaches it. At an effective Full level (outside the + evaluation sandbox) the script instead gets the environment of the Full shell + tool: every variable except the stripped secrets, with the real `HOME`. + Unmanaged shell callers are unchanged. - **Process containment.** The call uses the existing shell/HTTP adapters. Managed shell/script runs have a five-minute deadline and joined cleanup: the process group is ended when the leader exits, times out or is cancelled; diff --git a/src/runtime/shell_process.rs b/src/runtime/shell_process.rs index 06bb127bf..6150d326f 100644 --- a/src/runtime/shell_process.rs +++ b/src/runtime/shell_process.rs @@ -157,7 +157,7 @@ impl ShellProcessAdapter { } pub async fn execute(&self, request: ShellProcessRequest<'_>) -> Result { - self.execute_with(request, false, None) + self.execute_with(request, false, None, false) .await .map_err(ShellProcessError::without_output) } @@ -167,7 +167,7 @@ impl ShellProcessAdapter { &self, request: ShellProcessRequest<'_>, ) -> Result { - self.execute_with(request, false, None).await + self.execute_with(request, false, None, false).await } /// Like [`Self::execute`], with joined process-group cleanup: @@ -182,11 +182,31 @@ impl ShellProcessAdapter { /// `HOME` set to the request's working directory and `TMPDIR` to a /// directory inside it. No provider key, token or other credential /// reaches it. A container runtime isolates the environment itself. + /// (`execute_joined_full` replaces this with the Full shell environment.) /// /// Used where a lifecycle-managed skill script runs. pub async fn execute_joined( &self, request: ShellProcessRequest<'_>, + ) -> Result { + self.execute_joined_with(request, false).await + } + + /// Like [`Self::execute_joined`] for a call at an effective Full level: + /// on the native runtime the command gets the environment of the Full + /// shell tool (every variable except the stripped secrets, the real + /// `HOME`) instead of the contained one. + pub async fn execute_joined_full( + &self, + request: ShellProcessRequest<'_>, + ) -> Result { + self.execute_joined_with(request, true).await + } + + async fn execute_joined_with( + &self, + request: ShellProcessRequest<'_>, + full_environment: bool, ) -> Result { let group = self .cgroup_root @@ -202,7 +222,7 @@ impl ShellProcessAdapter { }) .transpose() .map_err(ShellProcessError::Spawn)?; - let result = self.execute_with(request, true, group.clone()).await; + let result = self.execute_with(request, true, group.clone(), full_environment).await; if let Some(group) = group { group.finish().await.map_err(ShellProcessError::Wait)?; } @@ -214,6 +234,7 @@ impl ShellProcessAdapter { request: ShellProcessRequest<'_>, end_group_on_exit: bool, cgroup: Option>, + full_environment: bool, ) -> Result { if request .cancellation @@ -258,7 +279,11 @@ impl ShellProcessAdapter { } if end_group_on_exit && self.runtime.name() == "native" { command.env_clear(); - command.envs(contained_environment(request.workspace_dir).map_err(ShellProcessError::Runtime)?); + if full_environment { + command.envs(full_shell_environment()); + } else { + command.envs(contained_environment(request.workspace_dir).map_err(ShellProcessError::Runtime)?); + } } let mut container = if self.runtime.name() == "docker" && command.as_std().get_program() == "docker" { Some( @@ -431,6 +456,18 @@ fn filtered_shell_environment( Ok(environment) } +/// The environment of the Full shell tool: everything except the stripped +/// secret variables, with the real `HOME`. +fn full_shell_environment() -> Vec<(std::ffi::OsString, std::ffi::OsString)> { + let mut environment: Vec<_> = std::env::vars_os() + .filter(|(key, _)| !shell_secret_environment(key)) + .collect(); + if !environment.iter().any(|(key, _)| key == "PATH") { + environment.push(("PATH".into(), "/usr/local/bin:/usr/bin:/bin".into())); + } + environment +} + /// The only environment a contained run gets (see /// [`ShellProcessAdapter::execute_joined`]). fn contained_environment(home: &Path) -> anyhow::Result> { diff --git a/src/tools/skills.rs b/src/tools/skills.rs index 1a93a6460..c3221f5c1 100644 --- a/src/tools/skills.rs +++ b/src/tools/skills.rs @@ -1477,7 +1477,14 @@ impl SkillExecuteTool { // A deadline marks a managed run, which is also joined: the process // group ends with its leader. let outcome = if timeout.is_some() { - self.shell.execute_joined(request).await + let full = !self.security.evaluation_sandbox + && crate::tools::effective_autonomy::call_policy(&self.security).autonomy + == crate::security::AutonomyLevel::Full; + if full { + self.shell.execute_joined_full(request).await + } else { + self.shell.execute_joined(request).await + } } else { self.shell.execute(request).await }; From 92cc652da7743e506910634d508f8754b60e6610 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:07:05 +0400 Subject: [PATCH 0117/1567] fix(mcp): decide MCP dispatch-time Full skips by the call's level Removed restriction: the dispatch-time MCP allow/deny list check and the HTTP private-address block keyed on the registry's held policy (Main's configured level), so a named agent or child running at Full under a non-Full Main was still restricted. Both now read the call's effective level (the per-call level carrier the native tools read). Below Full nothing changes. Load-time decisions (which servers start, workspace opt-in, launcher allowlist, catalog visibility) still use the registry's level. --- src/tools/mcp.rs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/tools/mcp.rs b/src/tools/mcp.rs index f479766c3..73076f2de 100644 --- a/src/tools/mcp.rs +++ b/src/tools/mcp.rs @@ -660,11 +660,19 @@ impl McpTool { Ok(()) } - /// Whether this registry runs at Full (its held policy's level). + /// Whether this registry runs at Full (its held policy's level). Used + /// for load-time decisions, which have no call. fn full(&self) -> bool { self.security.autonomy == crate::security::AutonomyLevel::Full } + /// Whether the current call runs at Full: the per-call level the + /// execution service set, else the held policy's level. Used for + /// dispatch-time decisions. + fn call_full(&self) -> bool { + crate::tools::effective_autonomy::call_policy(&self.security).autonomy == crate::security::AutonomyLevel::Full + } + /// Validate that a stdio server's command is safe to execute. /// /// A command is allowed if: @@ -1594,7 +1602,7 @@ impl McpTool { published.and_then(|entry| entry.binding_digest()), )?; let server = Self::resolve_server(&state.effective_config, &server_name)?; - if !self.full() && !Self::tool_allowed(server, &tool_name) { + if !self.call_full() && !Self::tool_allowed(server, &tool_name) { bail!("Tool '{tool_name}' is blocked by allow/deny rules for MCP server '{server_name}'"); } if let Some(discovered) = state.discovered_tools.get(&server_name) @@ -1609,7 +1617,7 @@ impl McpTool { match server.transport { McpTransport::Stdio => self.call_stdio(&server_name, &server, &tool_name, arguments).await, - McpTransport::Http => Self::call_http(&server_name, &server, &tool_name, arguments, self.full()).await, + McpTransport::Http => Self::call_http(&server_name, &server, &tool_name, arguments, self.call_full()).await, } } } From 84177e7f98052bbb96f06c6972409b0f0dde8261 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:08:44 +0400 Subject: [PATCH 0118/1567] fix(approval): lift the channel forced approval by the call's level Removed restriction: the rf channel's forced tool approval was lifted using Main's configured level captured at turn start, so a Full named child of a channel turn under a Supervised Main was still forced to ask. The dispatch now lifts it when the call's effective level is Full and forces it otherwise. The captured Main-level flag is removed. Below Full the forced approval is unchanged. --- src/agent/channel_approval.rs | 11 ++--------- src/channels/ramflux/tests/approval.rs | 1 - src/channels/turn.rs | 6 ++---- .../api/sessions/tests/targeting/section_1.rs | 2 +- src/tools/execution/section_3.rs | 5 +++-- src/tools/execution/tests/admission_matrix.rs | 16 ++-------------- 6 files changed, 10 insertions(+), 31 deletions(-) diff --git a/src/agent/channel_approval.rs b/src/agent/channel_approval.rs index 448dae795..d24dab975 100644 --- a/src/agent/channel_approval.rs +++ b/src/agent/channel_approval.rs @@ -18,7 +18,6 @@ pub(crate) struct Installed { turn_context: Option, resolver: Arc, force_ask: bool, - effective_full: bool, parent_run_id: Option, } @@ -33,14 +32,13 @@ tokio::task_local! { /// Remember that `run_id` must ask `resolver` before a tool runs. #[cfg(test)] -pub fn install(run_id: &str, resolver: Arc, force_ask: bool, effective_full: bool) { +pub fn install(run_id: &str, resolver: Arc, force_ask: bool) { registry().lock().insert( run_id.to_string(), Installed { turn_context: None, resolver, force_ask, - effective_full, parent_run_id: None, }, ); @@ -68,12 +66,10 @@ pub fn install_for_turn( conversation_id: &str, resolver: Arc, force_ask: bool, - effective_full: bool, ) -> Arc { let make = || Installed { resolver: Arc::clone(&resolver), force_ask, - effective_full, parent_run_id: None, turn_context: Some(TurnContext { conversation_id: conversation_id.to_owned(), @@ -100,7 +96,6 @@ pub fn clear(run_id: &str) { pub struct ApprovalContext { pub resolver: Arc, pub force_ask: bool, - pub effective_full: bool, } pub fn lookup(run_id: &str) -> Option { @@ -111,7 +106,6 @@ fn context_of(installed: &Installed) -> ApprovalContext { ApprovalContext { resolver: Arc::clone(&installed.resolver), force_ask: installed.force_ask, - effective_full: installed.effective_full, } } @@ -154,10 +148,9 @@ mod tests { fn lookup_for_call_uses_the_parent_run() { let parent = "parent-run"; let child = "child-run"; - install(parent, Arc::new(RecordingResolver), true, false); + install(parent, Arc::new(RecordingResolver), true); let found = lookup_for_call(child, Some(parent)).expect("test: parent gate"); assert!(found.force_ask); - assert!(!found.effective_full); clear(parent); assert!(lookup_for_call(child, Some(parent)).is_none()); } diff --git a/src/channels/ramflux/tests/approval.rs b/src/channels/ramflux/tests/approval.rs index 7487a979d..d6f6ffdba 100644 --- a/src/channels/ramflux/tests/approval.rs +++ b/src/channels/ramflux/tests/approval.rs @@ -181,7 +181,6 @@ async fn delegated_approval_inherits_explicit_context_and_rejects_wrong_decider( "conv-1", gate as std::sync::Arc, true, - false, ); let (pending,) = channel_approval::scope_installed(installed, async { (channel_approval::spawn(async { diff --git a/src/channels/turn.rs b/src/channels/turn.rs index f01566324..f4ba9a663 100644 --- a/src/channels/turn.rs +++ b/src/channels/turn.rs @@ -93,15 +93,13 @@ pub(super) async fn process_channel_message( let rich = channel.as_rich()?; let resolver = rich.approval_resolver()?; let force_ask = rich.forces_tool_approval(); - // PRX's own level decides (R32): a channel turn runs at Main's - // level, and at Full the channel's forced approval is satisfied. - let effective_full = ctx.config.pin().effective.autonomy.level == crate::security::AutonomyLevel::Full; + // The channel's forced approval is lifted at tool dispatch, by the + // call's effective level. Some(crate::agent::channel_approval::install_for_turn( &turn_run_id, &conversation_id, resolver, force_ask, - effective_full, )) }); let _rich_turn = rich_channel.as_ref().and_then(|channel| { diff --git a/src/gateway/api/sessions/tests/targeting/section_1.rs b/src/gateway/api/sessions/tests/targeting/section_1.rs index 34e39bd45..da005b9fb 100644 --- a/src/gateway/api/sessions/tests/targeting/section_1.rs +++ b/src/gateway/api/sessions/tests/targeting/section_1.rs @@ -709,7 +709,7 @@ async fn drive( }); if ask_gate { let run_id = envelope.run_id.clone().expect("test: run id"); - crate::agent::channel_approval::install(&run_id, resolver.clone(), true, false); + crate::agent::channel_approval::install(&run_id, resolver.clone(), true); } let service = runtime .publication_slot diff --git a/src/tools/execution/section_3.rs b/src/tools/execution/section_3.rs index ed193c998..ad6f8b319 100644 --- a/src/tools/execution/section_3.rs +++ b/src/tools/execution/section_3.rs @@ -440,12 +440,13 @@ impl ToolExecutionService { let prx_operator_ask = decision == ToolExecutionDecision::Ask; let channel_policy_ask = channel_gate.as_ref().is_some_and(|gate| gate.force_ask) && decision == ToolExecutionDecision::Allow; - let decision = if channel_policy_ask && channel_gate.as_ref().is_some_and(|gate| !gate.effective_full) { + // The call's effective level decides, not Main's configured level. + let decision = if channel_policy_ask && !full { ToolExecutionDecision::Ask } else { decision }; - if channel_policy_ask && channel_gate.as_ref().is_some_and(|gate| gate.effective_full) { + if channel_policy_ask && full { runtime_approval_granted = true; } if decision == ToolExecutionDecision::Ask && context.pending_approval_denied { diff --git a/src/tools/execution/tests/admission_matrix.rs b/src/tools/execution/tests/admission_matrix.rs index 6e8569e23..15088a9f7 100644 --- a/src/tools/execution/tests/admission_matrix.rs +++ b/src/tools/execution/tests/admission_matrix.rs @@ -213,7 +213,7 @@ impl crate::agent::turn_contracts::ApprovalResolver for ChannelResolver { } } #[tokio::test] -async fn channel_force_ask_precedes_ledger_and_effective_full_skips_it() { +async fn channel_force_ask_precedes_ledger() { let path = tempfile::tempdir().unwrap(); let fixture = fixture(); let context = ledger_context(path.path()).await; @@ -222,7 +222,7 @@ async fn channel_force_ask_precedes_ledger_and_effective_full_skips_it() { entered: tokio::sync::Notify::new(), release: tokio::sync::Notify::new(), }); - crate::agent::channel_approval::install(run, resolver.clone(), true, false); + crate::agent::channel_approval::install(run, resolver.clone(), true); let service = fixture.service("config_reload", vec![], ToolExecutionDecision::Allow, approved(), true); let task_context = context.clone(); let task = tokio::spawn(async move { service.execute(command(1), task_context, None).await }); @@ -246,19 +246,7 @@ async fn channel_force_ask_precedes_ledger_and_effective_full_skips_it() { ); resolver.release.notify_one(); assert_eq!(task.await.unwrap().status, ToolExecutionStatus::ApprovalDenied); - crate::agent::channel_approval::install(run, resolver, true, true); - let service = fixture.service("config_reload", vec![], ToolExecutionDecision::Allow, approved(), true); - let outcome = service.execute(command(1), context.clone(), None).await; crate::agent::channel_approval::clear(run); - assert_eq!(outcome.status, ToolExecutionStatus::Succeeded); - assert_eq!(fixture.calls.load(Ordering::SeqCst), 1); - assert!( - port.list_pending_calls(context.envelope.owner_id.as_deref().unwrap(), 0, 10) - .await - .unwrap() - .items - .is_empty() - ); } #[tokio::test] From c76e72917ea8f21ff60cd933f2feccd19c592a08 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:09:16 +0400 Subject: [PATCH 0119/1567] fix(chat): accept a /diff target outside the workspace at Full Removed restriction: at Full the /diff target resolves freely, but the memory-file check then failed with "target escapes workspace" for any target outside the workspace. At an effective Full level outside the evaluation sandbox an outside target now passes that check; the protected memory files (all inside the workspace) are still refused. Below Full the check is unchanged. --- src/chat/diff_apply.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/chat/diff_apply.rs b/src/chat/diff_apply.rs index 565120eb5..836527534 100644 --- a/src/chat/diff_apply.rs +++ b/src/chat/diff_apply.rs @@ -487,14 +487,15 @@ struct PreparedWrite { async fn validate_target(file: &FilePatch, security: &SecurityPolicy) -> Result { // The diff path is the operator's: `security` carries Main's configured // level. At Full the target resolves freely (symlinks followed). - let target = if security.autonomy == crate::security::AutonomyLevel::Full && !security.evaluation_sandbox { + let full = security.autonomy == crate::security::AutonomyLevel::Full && !security.evaluation_sandbox; + let target = if full { crate::security::approval_operation::resolve_full_target(&security.workspace_dir, &file.path) .await .map_err(|err| DiffApplyError::RejectedPath(format!("failed to resolve target: {err}")))? } else { confined_target(file, security).await? }; - reject_protected_memory_path(&target, security)?; + reject_protected_memory_path(&target, security, full)?; match tokio::fs::symlink_metadata(&target).await { Ok(meta) => { let file_type = meta.file_type(); @@ -552,12 +553,17 @@ async fn confined_target(file: &FilePatch, security: &SecurityPolicy) -> Result< Ok(resolved_parent.join(file_name)) } -fn reject_protected_memory_path(target: &Path, security: &SecurityPolicy) -> Result<(), DiffApplyError> { +fn reject_protected_memory_path(target: &Path, security: &SecurityPolicy, full: bool) -> Result<(), DiffApplyError> { let workspace = security .workspace_dir .canonicalize() .unwrap_or_else(|_| security.workspace_dir.clone()); let Ok(rel) = target.strip_prefix(&workspace) else { + // At Full a target outside the workspace is allowed; the protected + // memory files live inside it, so there is nothing to refuse. + if full { + return Ok(()); + } return Err(DiffApplyError::RejectedPath("target escapes workspace".to_string())); }; if rel From 50ca79ffa953e2c6244a8847753d9c0517ca0e09 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:05:10 +0400 Subject: [PATCH 0120/1567] fix(security): a live Full level wins over the stored level of a job or child Removed restriction: a cron/Xin job or a restored child created while Main was Supervised stayed Supervised after the operator moved Main to Full, because the stored level was combined with the live level by min. When the live level is Full the work now runs at Full. Below Full the lower of the stored and live levels still applies, so lowering the level still lowers earlier work. --- docs/tools.md | 3 +++ src/chat/message_inbox.rs | 3 ++- src/runtime/mailbox_child.rs | 2 +- src/security/agent_level.rs | 17 +++++++++++++++-- 4 files changed, 21 insertions(+), 4 deletions(-) diff --git a/docs/tools.md b/docs/tools.md index 618e3bab6..077cdb009 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -1476,6 +1476,9 @@ as before. The Full autonomy sentence is rendered once for Full children. A Full spawning turn starts every child at Full, including a named agent whose configured level is lower. Below Full, an unnamed child keeps its parent's level and a named child uses its configured level (or Main's when unset). +A restored child and a cron or Xin job created earlier run at Full whenever the live +level is Full, whatever level was stored at creation; below Full the lower of the stored +and the live level still applies. The default child model and provider come from the spawning turn's current selection, including terminal switches. Explicit request overrides take priority; a named agent's model and provider apply only when that agent is requested. diff --git a/src/chat/message_inbox.rs b/src/chat/message_inbox.rs index 946a399bd..c8be2f5f5 100644 --- a/src/chat/message_inbox.rs +++ b/src/chat/message_inbox.rs @@ -191,7 +191,8 @@ pub(super) async fn send_command( .into_iter() .find(|record| record.session_key == source_session && record.parent_session == parent) .ok_or_else(|| anyhow::anyhow!("child_session_unknown"))?; - record.level.min( + crate::security::agent_level::live_wins_to_full( + record.level, crate::security::agent_level::named_child_level(config, Some(&record.agent), config.autonomy.level) .unwrap_or(config.autonomy.level), ) diff --git a/src/runtime/mailbox_child.rs b/src/runtime/mailbox_child.rs index 1ff29d9d0..71c8b2d77 100644 --- a/src/runtime/mailbox_child.rs +++ b/src/runtime/mailbox_child.rs @@ -100,7 +100,7 @@ impl MailboxChildSource { }; let now = crate::security::agent_level::named_child_level(config, Some(&record.agent), root_level) .unwrap_or(root_level); - let level = record.level.min(now); + let level = crate::security::agent_level::live_wins_to_full(record.level, now); let retained = Arc::clone(parent); let configured = current.clone(); let agent = record.agent.clone(); diff --git a/src/security/agent_level.rs b/src/security/agent_level.rs index eef036de5..02a7fc096 100644 --- a/src/security/agent_level.rs +++ b/src/security/agent_level.rs @@ -137,7 +137,7 @@ pub fn scheduled_agent_refusal( /// - Named-agent work uses that agent's own live level. /// - Non-agent work the local operator created keeps Main's live level. /// - Otherwise the stored creator level, lowered to the creator's current -/// level. A row with no recorded creator runs at Main's level; a creator +/// level, except that a creator whose live level is `Full` runs at `Full`. A row with no recorded creator runs at Main's level; a creator /// with an unreadable spelling is capped at `Supervised`. A named creator /// that is gone fails the run. /// - A run started from a tool call is lowered to that call's level. @@ -158,7 +158,7 @@ pub fn scheduled_level( } else { match (creator.level, creator.agent.as_deref()) { (Some(stored), Some(agent)) => match creator_current_level(agent, config) { - Some(current) => stored.min(current?), + Some(current) => live_wins_to_full(stored, current?), None => AutonomyLevel::Supervised.min(main), }, _ => main, @@ -167,6 +167,19 @@ pub fn scheduled_level( Ok(caller.map_or(base, |caller| base.min(caller))) } +/// The stored creator level combined with the creator's live level: a live +/// `Full` runs at `Full` whatever was stored (the live level wins upward), +/// otherwise the lower of the two applies, so lowering the level still lowers +/// work created earlier at a higher one. +#[must_use] +pub fn live_wins_to_full(stored: AutonomyLevel, live: AutonomyLevel) -> AutonomyLevel { + if live == AutonomyLevel::Full { + AutonomyLevel::Full + } else { + stored.min(live) + } +} + /// `None` when `agent` is not a creator spelling (the stamp is unreadable). fn creator_current_level(agent: &str, config: &Config) -> Option> { if agent == CREATOR_MAIN { From e0b639bd5d2c4190097925d0545e9894ff5b7462 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:10:49 +0400 Subject: [PATCH 0121/1567] fix(tools): the owner's agent manages all of the owner's jobs and runs Removed restrictions: the authenticated Console Main could not manage cron jobs created through the CLI; Main could not see or kill the runs of its owner's named agents; named agents could not use chat_sessions or chat_assign. Owner scoping is kept, and owner-isolated origins still see only unstamped runs. Assignment grants still decide which chat sessions a caller may hand work to. --- docs/rf-contract/capability-tokens.md | 6 ++-- docs/tools.md | 4 ++- src/tools/cron.rs | 28 +++++++++++++++++-- src/tools/sessions_read_model.rs | 34 ++++++++++++++--------- src/tools/sessions_spawn/batch.rs | 4 ++- src/tools/sessions_spawn/batch_journal.rs | 2 +- src/tools/sessions_spawn/tool.rs | 30 -------------------- 7 files changed, 57 insertions(+), 51 deletions(-) diff --git a/docs/rf-contract/capability-tokens.md b/docs/rf-contract/capability-tokens.md index 1dc0e8c52..07df1cc69 100644 --- a/docs/rf-contract/capability-tokens.md +++ b/docs/rf-contract/capability-tokens.md @@ -511,8 +511,10 @@ turn's agent, so a named agent's children are its own rows; Main's children are unchanged. `sessions_list`, `sessions_history`, `session_status`, `subagents` and `sessions_send` show a named agent only the runs it started. `spawn_batch` and `join` retain the parent's agent partition, including the -batch journal and cached roster. `chat_sessions` and `chat_assign` answer a -named agent with `spawn_action_unpartitioned`; a child whose root partition cannot be +batch journal and cached roster. `chat_sessions` and `chat_assign` are available to a +named agent (the assignment grants still decide which sessions it may hand work to). An owner's +Main sees and can kill every run of that owner, including its named agents' runs; an +owner-isolated origin still sees only unstamped runs. A child whose root partition cannot be determined is refused with `child_partition_unresolved`. **History labels.** `GET /api/sessions/{session_id}/messages` on a diff --git a/docs/tools.md b/docs/tools.md index 077cdb009..89eb32d83 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -1532,7 +1532,9 @@ A non-operator run keeps its `cron` / `xin` runtime source and a `cron:{id}` / local-operator CLI tuple, whatever channel and sender its creator had. The origin is fixed at creation. Only the job's creator (the same owner) or the local operator can `update`, `remove`, `pause`, `resume` or `run` a cron job; the -operator doing so does not adopt it. Reads follow the same rule: `list` and +operator doing so does not adopt it. The authenticated, non-isolated Console +Main also manages the ownerless jobs the local operator created through the CLI. +Reads follow the same rule: `list` and `status` show a caller only its own owner's jobs, and `get`, `runs`/`history` and `events` answer another principal's job exactly as a missing one: an id that names no job, or a removed job, reads as `not found` too, so a read diff --git a/src/tools/cron.rs b/src/tools/cron.rs index ca3b98ea8..aaa1a9939 100644 --- a/src/tools/cron.rs +++ b/src/tools/cron.rs @@ -101,7 +101,9 @@ impl CronTool { /// changed by any update. Any other trusted caller may manage only jobs /// whose stored owner is its own owner (the same owner /// [`cron::lineage_from_trusted_scope`] records at creation); a job with no - /// stored owner belongs to no such caller. A call without a + /// stored owner belongs to no such caller, except that the authenticated + /// Console Main also manages the ownerless jobs the local operator created + /// through the CLI. A call without a /// runtime-authored scope bypassed the execution service entirely (an /// in-process call) and keeps the unrestricted behavior it always had, /// as `RunOwnerScope::from_args` does. @@ -408,6 +410,10 @@ struct RunView { enum CallerScope { Unrestricted, Owner(Option), + /// The authenticated, non-isolated Console Main: its owner's jobs, and + /// the jobs the local operator created through the CLI, which carry no + /// owner (the Console holder is the operator of this instance). + Console(Option), Named { owner: Option, creator: String }, } @@ -429,7 +435,19 @@ impl CallerScope { owner, creator: crate::security::agent_level::creator_agent_named(name.as_str(), &incarnation), }, - Ok(_) => Self::Owner(owner), + Ok(_) => { + let console = args + .get("_zc_scope") + .and_then(serde_json::Value::as_object) + .and_then(|scope| scope.get("runtime_source")) + .and_then(serde_json::Value::as_str) + == Some(crate::runtime::envelope::RuntimeSource::Console.as_str()); + if console && owner.is_some() && !crate::tools::execution::scope_requires_owner_match(args) { + Self::Console(owner) + } else { + Self::Owner(owner) + } + } Err(_) => Self::Owner(None), } } @@ -438,7 +456,11 @@ impl CallerScope { match self { Self::Unrestricted => true, Self::Owner(Some(owner)) => job.owner_id.as_deref() == Some(owner.as_str()), - Self::Owner(None) => false, + Self::Owner(None) | Self::Console(None) => false, + Self::Console(Some(owner)) => { + job.owner_id.as_deref() == Some(owner.as_str()) + || (job.owner_id.is_none() && job.origin.is_local_operator()) + } Self::Named { owner, creator } => { owner .as_deref() diff --git a/src/tools/sessions_read_model.rs b/src/tools/sessions_read_model.rs index c93c3e6cc..d87fd63de 100644 --- a/src/tools/sessions_read_model.rs +++ b/src/tools/sessions_read_model.rs @@ -166,9 +166,14 @@ pub(crate) enum RunOwnerScope { /// local-operator CLI tuple), and in-process calls that bypass the execution service and so /// carry no trusted scope at all. Unrestricted, - /// Only runs registered under exactly this owner. `None` means the caller - /// has no resolvable owner, so nothing is admitted. + /// Every run registered under exactly this owner, whichever agent + /// partition stamped it: the owner's own agent sees and manages all of that + /// owner's runs, including those of its named agents. `None` means the + /// caller has no resolvable owner, so nothing is admitted. Owner(Option), + /// An owner-isolated origin (external MCP): only the unstamped runs + /// registered under exactly this owner. It never sees a named agent's run. + Isolated(Option), /// A named agent (MA-01b5): only the runs stamped with exactly its /// partition, under the partition's owner. Main and every other owner /// scope never admit a stamped run. @@ -273,7 +278,12 @@ impl RunOwnerScope { if !context.envelope.owner_isolated && context.is_local_operator() { return Self::Unrestricted; } - return Self::Owner(effective_run_owner_from_context(context)); + let owner = effective_run_owner_from_context(context); + return if context.envelope.owner_isolated { + Self::Isolated(owner) + } else { + Self::Owner(owner) + }; } // MA-01b5: a named agent sees the runs stamped with its partition; a // call whose partition cannot be read sees no run at all. @@ -286,7 +296,7 @@ impl RunOwnerScope { Err(_) => return Self::Owner(None), } if crate::tools::execution::scope_requires_owner_match(args) { - return Self::Owner( + return Self::Isolated( args.get("_zc_scope") .and_then(Value::as_object) .and_then(|scope| scope.get("owner_id")) @@ -319,7 +329,8 @@ impl RunOwnerScope { ) -> bool { match self { Self::Unrestricted => true, - Self::Owner(_) => run_partition.is_none() && self.admits_owner(run_owner_id), + Self::Owner(_) => self.admits_owner(run_owner_id), + Self::Isolated(_) => run_partition.is_none() && self.admits_owner(run_owner_id), Self::Agent(caller) => run_partition == Some(caller) && self.admits_owner(run_owner_id), } } @@ -329,17 +340,14 @@ impl RunOwnerScope { fn admits_owner(&self, run_owner_id: Option<&str>) -> bool { match self { Self::Unrestricted => true, - Self::Owner(Some(caller)) => run_owner_id.is_some_and(|owner| owner == caller), - Self::Owner(None) => false, + Self::Owner(Some(caller)) | Self::Isolated(Some(caller)) => { + run_owner_id.is_some_and(|owner| owner == caller) + } + Self::Owner(None) | Self::Isolated(None) => false, Self::Agent(caller) => run_owner_id == Some(caller.owner_id.as_str()), } } - /// Whether this caller is a named agent (MA-01b5). - pub(crate) const fn is_agent(&self) -> bool { - matches!(self, Self::Agent(_)) - } - /// Owner-qualify already-fetched projection rows. /// /// The read model is handed whole rows by the `Memory` trait, not a query @@ -356,7 +364,7 @@ impl RunOwnerScope { fn retain_admitted(&self, rows: Vec, owner_of: impl Fn(&T) -> Option<&str>) -> Vec { match self { Self::Unrestricted => rows, - Self::Owner(_) | Self::Agent(_) => rows + Self::Owner(_) | Self::Isolated(_) | Self::Agent(_) => rows .into_iter() .filter(|row| self.admits_owner(owner_of(row))) .collect(), diff --git a/src/tools/sessions_spawn/batch.rs b/src/tools/sessions_spawn/batch.rs index b8a462848..c6182b923 100644 --- a/src/tools/sessions_spawn/batch.rs +++ b/src/tools/sessions_spawn/batch.rs @@ -770,7 +770,9 @@ impl SessionsSpawnTool { owner_scope: &sessions_read_model::RunOwnerScope, ) -> anyhow::Result> { let owner = row_owner.or_else(|| match owner_scope { - sessions_read_model::RunOwnerScope::Owner(Some(owner)) => Some(owner.clone()), + sessions_read_model::RunOwnerScope::Owner(Some(owner)) | sessions_read_model::RunOwnerScope::Isolated(Some(owner)) => { + Some(owner.clone()) + } _ => None, }); match (fabric, owner) { diff --git a/src/tools/sessions_spawn/batch_journal.rs b/src/tools/sessions_spawn/batch_journal.rs index 85fa880ff..871ac7cc1 100644 --- a/src/tools/sessions_spawn/batch_journal.rs +++ b/src/tools/sessions_spawn/batch_journal.rs @@ -462,7 +462,7 @@ pub(super) async fn verify_ordinary_member( fabric, std::path::Path::new(fabric.workspace_id()), batch, - &crate::tools::sessions_read_model::RunOwnerScope::Owner(Some(owner.to_owned())), + &crate::tools::sessions_read_model::RunOwnerScope::Isolated(Some(owner.to_owned())), ) .await? .context("ordinary batch roster missing")?; diff --git a/src/tools/sessions_spawn/tool.rs b/src/tools/sessions_spawn/tool.rs index 8fd224b8b..f1179d8b6 100644 --- a/src/tools/sessions_spawn/tool.rs +++ b/src/tools/sessions_spawn/tool.rs @@ -8,29 +8,6 @@ use async_trait::async_trait; use serde_json::json; use std::sync::Arc; -/// Named agents cannot control the operator's live chat sessions. -/// Batch journals and children retain the parent agent's partition. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) struct SpawnActionUnpartitioned; - -impl SpawnActionUnpartitioned { - pub(crate) const fn code(self) -> &'static str { - "spawn_action_unpartitioned" - } -} - -impl std::fmt::Display for SpawnActionUnpartitioned { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - formatter, - "{}: chat_sessions and chat_assign are unavailable to a named agent", - self.code() - ) - } -} - -impl std::error::Error for SpawnActionUnpartitioned {} - impl SessionsSpawnTool { pub(super) fn execution_schema(&self) -> &std::sync::Arc { self.execution_schema.get_or_init(|| { @@ -236,13 +213,6 @@ impl Tool for SessionsSpawnTool { // caller's owner started; the local-process operator sees them all. A // run outside the scope answers exactly like a missing one. let owner_scope = sessions_read_model::RunOwnerScope::from_args(&args); - if owner_scope.is_agent() && matches!(action, "chat_sessions" | "chat_assign") { - return Ok(ToolResult { - success: false, - output: String::new(), - error: Some(SpawnActionUnpartitioned.to_string()), - }); - } match action { "continue" => return self.execute_continue(&args).await, From d4681e3b4a04901365a0b30025deb0d2732f06c0 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:05:56 +0400 Subject: [PATCH 0122/1567] feat(config): default gateway.targeted_agents to true A Console turn addressed to a named agent, and a session message that wakes a named agent, were refused with 409 agent_disabled unless the operator had switched gateway.targeted_agents on. The default is now true, so named targets work out of the box. The key stays: an explicit false still refuses named targets. A config that sets the key explicitly is unchanged; a config that omits it now accepts named targets. Documented default, config schema fixture and golden effective config updated. --- docs/configuration.md | 18 +++++++++--------- docs/migration-unreleased.md | 2 +- docs/rf-contract/capability-tokens.md | 2 +- src/config/schema/gateway.rs | 11 ++++++----- .../child_source/golden_effective_config.json | 2 +- tests/fixtures/config-schema.json | 2 +- 6 files changed, 19 insertions(+), 18 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 7d011c1a0..dc2354348 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -11,9 +11,9 @@ engine as owning everything: `always_exclude` / channel exclusions ∩ catalog eligibility. The surface is built even when the advisory engine is off. Authorized search stays available when deferred tools exist, including for brief inputs. -- **Targeted gateway turns** (`[gateway] targeted_agents`, default `false`) use - a named memory partition (`name` + incarnation), not Main's history. The - switch is pre-release. +- **Targeted gateway turns** (`[gateway] targeted_agents`, default `true`) use + a named memory partition (`name` + incarnation), not Main's history. Set + it to `false` to refuse named targets. - **Advisory decision engine** (`[decision_engine]`, default `enabled = false`) only advises; there is no `[causal_tree]` table any more. - **Recovery** needs the workspace database together with its `.recovery_keys` @@ -131,7 +131,7 @@ and the module-gate family are absorbed on load; they are not live switches. | `[[user_policies]]` | `user_id` required; `role = "guest"`; `projects = []`; `visibility_ceiling = "private"`; `blocked_patterns = []` | | `[storage.provider.config]` | `provider = ""`; `db_url` unset (aliases `dbURL`, `database_url`, `databaseUrl`); `schema = "public"`; `table = "memories"`; `connect_timeout_secs` unset (15s handshake); `pool_max_size = 32` | | `[tunnel]` | `provider = "none"`; `cloudflare`/`tailscale`/`ngrok`/`custom` unset. Cloudflare needs `token`; Tailscale `funnel = false`, `hostname` unset; ngrok `auth_token` required, `domain` unset; custom `start_command` required, `health_url`/`url_pattern` unset | -| `[gateway]` | `port = 16830`; `host = "127.0.0.1"`; `require_pairing = true`; `allow_public_bind = false`; `paired_tokens = []`; `pair_rate_limit_per_minute = 10`; `webhook_rate_limit_per_minute = 60`; `api_rate_limit_per_minute = 60`; `trust_forwarded_headers = false`; `rate_limit_max_keys = 10000`; `idempotency_ttl_secs = 300`; `idempotency_max_keys = 10000`; `channel_webhook_dedup_ttl_secs = 86400`; `targeted_agents = false` | +| `[gateway]` | `port = 16830`; `host = "127.0.0.1"`; `require_pairing = true`; `allow_public_bind = false`; `paired_tokens = []`; `pair_rate_limit_per_minute = 10`; `webhook_rate_limit_per_minute = 60`; `api_rate_limit_per_minute = 60`; `trust_forwarded_headers = false`; `rate_limit_max_keys = 10000`; `idempotency_ttl_secs = 300`; `idempotency_max_keys = 10000`; `channel_webhook_dedup_ttl_secs = 86400`; `targeted_agents = true` | | `[webhook]` | `bind = "0.0.0.0:16899"`; `token` unset (required when enabled); `signing_secret` unset | | `[composio]` | `api_key` unset; `entity_id = "default"` | | `[mcp]` | `servers = {}`; `workspace_servers = "off"` (`http_only` or `stdio` to widen). A server: `transport = "stdio"`; `command`/`url` unset; `args = []`; `env = {}`; `startup_timeout_ms = 10000`; `request_timeout_ms = 30000`; `tool_name_prefix = "mcp"`; `allow_tools`/`deny_tools = []`; `working_dir` unset | @@ -540,16 +540,16 @@ default_temperature = 0.3 # again. Must be greater than 0. Default: 86400 (24 hours). # channel_webhook_dedup_ttl_secs = 86400 -# Rollout switch for targeted agent turns (`agent` on -# POST /api/sessions/{id}/message). While false, any otherwise-valid named +# Switch for targeted agent turns (`agent` on +# POST /api/sessions/{id}/message). Default true. While false, any otherwise-valid named # target answers 409 `agent_disabled` and never runs as the main agent. # A named target on a memory backend that does not keep agent scope answers # 409 `agent_backend_unsupported` after the disabled and unknown checks. -# `targeted_agents` is pre-release (default false). While true, a named target +# While true (the default), a named target # uses its own memory partition (agent name + incarnation), not Main's history. # A memory backend that does not keep agent scope answers 409 # `agent_backend_unsupported`. -# targeted_agents = false +# targeted_agents = true [runtime] # `kind` accepts "native" (default) or "docker". `kind = "cloudflare"` is @@ -832,7 +832,7 @@ model = "claude-sonnet-4-6" agentic = true allowed_tools = ["web_search", "file_read"] # Targeted turns (`agent` on POST /api/sessions/{id}/message, needs -# [gateway] targeted_agents = true): `enabled = false` answers 409 +# [gateway] targeted_agents, default true): `enabled = false` answers 409 # `agent_disabled`; `autonomy` is capped at the main agent's level. # History is a named partition, not Main's. Names must match # ^[a-z][a-z0-9_-]{0,63}$ and cannot be `main`. diff --git a/docs/migration-unreleased.md b/docs/migration-unreleased.md index f0b8ab9f3..8cd7b48a8 100644 --- a/docs/migration-unreleased.md +++ b/docs/migration-unreleased.md @@ -21,7 +21,7 @@ of the [changelog](../CHANGELOG.md). | Matrix channel removed | The Matrix channel, the `channel-matrix` feature and the vendored Matrix SDK are gone. A `[channels_config.matrix]` section is ignored with one warning at load; delete it. Its values are not kept after the next config save. A `channel.matrix` proxy selector is ignored with a warning. Use ramflux for external messaging. | Only with a Matrix channel configured | | Advisory decision engine | `[decision_engine]` defaults to `enabled = false`. Off means no analysis, brief, telemetry store, or outcome writes. The engine never selects tools or grants approval, and admission does not depend on it. Set `enabled = true` and restart only to opt into bounded pre-turn briefs and/or outcome telemetry. See [the decision engine](decision-engine.md). | To use the advisory engine | | Recovery keys and database backup | SQLite recovery keys live in `.recovery_keys` beside the database. A usable backup is a consistent snapshot of that database (the runtime writes it with `VACUUM INTO`, never a live write-ahead-log copy) plus every key generation the snapshot names, published as one completed bundle. Copy that completed bundle. A database without those keys cannot recover. Keys without that database do not start a new authority. Incomplete backup directories are refused. | Before any backup or host move | -| Targeted gateway agents | `[gateway] targeted_agents` defaults to `false`. A named `agent` on `POST /api/sessions/{id}/message` then answers 409 and never runs as Main. The switch is pre-release: targeted history is not partitioned. | Only if you send a named agent field | +| Targeted gateway agents | `[gateway] targeted_agents` defaults to `true`: a named `agent` on `POST /api/sessions/{id}/message`, and a session message that wakes a named agent, now run as that agent with its own partitioned history. A config that sets the key explicitly is unchanged; set `targeted_agents = false` to get 409 `agent_disabled` again. A config that omits the key now accepts named targets. | Only to refuse named targets | | `prx agent` removed | `prx agent` is gone (clap reports an unknown subcommand). Use `prx chat --message ` (`-q`): the reply alone on stdout, exit 0, 2 on a policy refusal, 1 on failure; the turn is not saved unless `--save` or `--session` is given; `--workdir` moved to `prx chat`. Scripts and cron commands that call `prx agent` must be updated. | Only if you script `prx agent` | | Quiet CLI logs | Foreground commands (`prx chat`, `prx go`, `prx doctor`, `prx status`, and other non-service commands) default to `warn` on stderr when `RUST_LOG` is unset, so stdout stays the product. `prx daemon`, `prx gateway`, and `prx channel start` keep `info`. A set `RUST_LOG` wins when it parses; an unparseable value falls back to that command default. Interactive `prx chat` writes the same default filter to `chat.log`; if that file cannot be opened, tracing stays on stderr. | If a script parsed tracing from stdout | | Retired `[router]` continuation table | The retired continuation table under `[router]` is ignored with one warning at load; delete it. Turns keep the serving model's reply. Authenticated historical v1 replies remain readable. | Only if that table is still in the file | diff --git a/docs/rf-contract/capability-tokens.md b/docs/rf-contract/capability-tokens.md index 07df1cc69..f1c8f317c 100644 --- a/docs/rf-contract/capability-tokens.md +++ b/docs/rf-contract/capability-tokens.md @@ -535,7 +535,7 @@ pairing off the listing is unchanged. |---|---|---| | `capabilities_v1` | `GET /api/capabilities` returns the version and the sorted token list | advertised since 85ab41f7a | | `agent_catalog_v1` | `GET /api/agents/catalog` returns the fields listed above | advertised since 85ab41f7a | -| `targeted_agents_v1` | A message turn can target a named agent, with a per-agent partitioned history that reads back with an agent label and filter (see Partition and history labels) | in `capabilities` while `gateway.targeted_agents` is effective in the running daemon, in `available` otherwise (AC-1b3) | +| `targeted_agents_v1` | A message turn can target a named agent, with a per-agent partitioned history that reads back with an agent label and filter (see Partition and history labels) | in `capabilities` while `gateway.targeted_agents` (default `true`) is effective in the running daemon, in `available` otherwise (AC-1b3) | | `agent_crud_v1` | The agent routes above: `GET /api/agents`, `GET`, `PUT` and `DELETE /api/agents/{name}` with If-Match, the config revision, an incarnation and `status`; `GET`/`PUT /api/gateway/targeted-agents`; the owner-bearer-only `POST /api/config/reload`. `DELETE` retires the agent (the purge is `agent_memory_purge_v1`) | advertised since 39509eb97 | | `agent_main_readback_v1` | `GET /api/agents/main` reads back Main's configuration | advertised since 39509eb97 | | `agent_limits_v1` | `limits {max_concurrent_turns, max_cost_per_day_cents}` on an agent `PUT` (unset by default; card AC-LIM) | advertised (RF-UNIT-A) | diff --git a/src/config/schema/gateway.rs b/src/config/schema/gateway.rs index f1c0446f9..797f61740 100644 --- a/src/config/schema/gateway.rs +++ b/src/config/schema/gateway.rs @@ -67,10 +67,11 @@ pub struct GatewayConfig { #[serde(default = "default_channel_webhook_dedup_ttl_secs")] pub channel_webhook_dedup_ttl_secs: u64, - /// Rollout switch for targeted agent turns (`agent` on - /// `POST /api/sessions/{id}/message`). While false, any otherwise-valid - /// named target answers 409 `agent_disabled` and never runs as Main. - #[serde(default)] + /// Switch for targeted agent turns (`agent` on + /// `POST /api/sessions/{id}/message`). Default true. While false, any + /// otherwise-valid named target answers 409 `agent_disabled` and never + /// runs as Main. + #[serde(default = "default_true")] pub targeted_agents: bool, } @@ -130,7 +131,7 @@ impl Default for GatewayConfig { idempotency_ttl_secs: default_idempotency_ttl_secs(), idempotency_max_keys: default_gateway_idempotency_max_keys(), channel_webhook_dedup_ttl_secs: default_channel_webhook_dedup_ttl_secs(), - targeted_agents: false, + targeted_agents: true, } } } diff --git a/src/runtime/child_source/golden_effective_config.json b/src/runtime/child_source/golden_effective_config.json index 0d16f1d38..560f4f425 100644 --- a/src/runtime/child_source/golden_effective_config.json +++ b/src/runtime/child_source/golden_effective_config.json @@ -1 +1 @@ -{"a2a":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trust_domain":"prx.local","trusted_trust_domains":[]},"agent":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"messaging":{"inbound":true},"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2},"agents":{},"api_key":null,"api_url":null,"auth":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"},"autonomy":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":500,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true},"browser":{"allowed_domains":[],"computer_use":{"api_key":null}},"channels_config":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null},"chat":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2},"compliance":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}},"composio":{"api_key":null,"entity_id":"default"},"cost":{"allow_override":false,"daily_limit_usd":10.0,"monthly_limit_usd":100.0,"prices":{"alpha/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0},"zeta/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0}},"warn_at_percent":80},"cron":{"max_run_history":50},"decision_engine":{"backend":{"circuit_breaker":{"cooldown_secs":60,"failure_threshold":5},"credential_ref":"","endpoint":"","kind":"auto","max_request_bytes":65536,"max_response_bytes":262144,"model":"","pinned_snapshot":"","remote_enabled":false,"timeout_ms":250},"candidates":5,"enabled":false,"latency_budget_ms":500,"max_candidates":12,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"token_ratio_limit":0.3499999940395355},"default_model":"anthropic/claude-sonnet-5","default_provider":"openrouter","default_temperature":0.7,"embedding_routes":[],"gateway":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":false,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60},"heartbeat":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."},"http_request":{"max_response_size":1000000,"timeout_secs":30},"identity":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"},"identity_bindings":[],"mcp":{"servers":{}},"mcp_server":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true},"media":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"},"memory":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7},"model_routes":[],"model_settings":{},"multimodal":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4},"nodes":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}},"observability":{"backend":"none","otel_endpoint":null,"otel_service_name":null},"plugins":{"enabled":false},"providers":{"ollama":{"num_ctx":null}},"proxy":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]},"query_classification":{"rules":[]},"reliability":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2},"router":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]},"runtime":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null},"scheduler":{"claim_lease_secs":90,"max_tasks":64},"secrets":{"encrypt":true},"security":{"audit":{"log_path":"audit.log","max_size_mb":100}},"self_system":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24},"sessions_spawn":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null},"skill_rag":{"top_k":32},"skills":{"open_skills_dir":null,"openclaw_skills_dir":null},"skills_lifecycle":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]},"smart_group":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5},"storage":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}},"task_routing":{"default_intent":"simple","rules":[]},"tool_tiering":{"always_exclude":[],"always_include":[],"channel_exclude":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","skills_manage","memory_reindex","document_sync","document_ingest"]},"tunnel":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null},"user_policies":[],"web_search":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15},"webhook":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null},"xin":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}} \ No newline at end of file +{"a2a":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trust_domain":"prx.local","trusted_trust_domains":[]},"agent":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"messaging":{"inbound":true},"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2},"agents":{},"api_key":null,"api_url":null,"auth":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"},"autonomy":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":500,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true},"browser":{"allowed_domains":[],"computer_use":{"api_key":null}},"channels_config":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null},"chat":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2},"compliance":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}},"composio":{"api_key":null,"entity_id":"default"},"cost":{"allow_override":false,"daily_limit_usd":10.0,"monthly_limit_usd":100.0,"prices":{"alpha/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0},"zeta/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0}},"warn_at_percent":80},"cron":{"max_run_history":50},"decision_engine":{"backend":{"circuit_breaker":{"cooldown_secs":60,"failure_threshold":5},"credential_ref":"","endpoint":"","kind":"auto","max_request_bytes":65536,"max_response_bytes":262144,"model":"","pinned_snapshot":"","remote_enabled":false,"timeout_ms":250},"candidates":5,"enabled":false,"latency_budget_ms":500,"max_candidates":12,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"token_ratio_limit":0.3499999940395355},"default_model":"anthropic/claude-sonnet-5","default_provider":"openrouter","default_temperature":0.7,"embedding_routes":[],"gateway":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60},"heartbeat":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."},"http_request":{"max_response_size":1000000,"timeout_secs":30},"identity":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"},"identity_bindings":[],"mcp":{"servers":{}},"mcp_server":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true},"media":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"},"memory":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7},"model_routes":[],"model_settings":{},"multimodal":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4},"nodes":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}},"observability":{"backend":"none","otel_endpoint":null,"otel_service_name":null},"plugins":{"enabled":false},"providers":{"ollama":{"num_ctx":null}},"proxy":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]},"query_classification":{"rules":[]},"reliability":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2},"router":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]},"runtime":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null},"scheduler":{"claim_lease_secs":90,"max_tasks":64},"secrets":{"encrypt":true},"security":{"audit":{"log_path":"audit.log","max_size_mb":100}},"self_system":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24},"sessions_spawn":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null},"skill_rag":{"top_k":32},"skills":{"open_skills_dir":null,"openclaw_skills_dir":null},"skills_lifecycle":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]},"smart_group":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5},"storage":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}},"task_routing":{"default_intent":"simple","rules":[]},"tool_tiering":{"always_exclude":[],"always_include":[],"channel_exclude":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","skills_manage","memory_reindex","document_sync","document_ingest"]},"tunnel":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null},"user_policies":[],"web_search":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15},"webhook":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null},"xin":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}} \ No newline at end of file diff --git a/tests/fixtures/config-schema.json b/tests/fixtures/config-schema.json index 766fb54c9..6c8679395 100644 --- a/tests/fixtures/config-schema.json +++ b/tests/fixtures/config-schema.json @@ -1 +1 @@ -{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Config","description":"Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).","type":"object","properties":{"a2a":{"description":"Agent-to-Agent compatibility configuration (`[a2a]`).","$ref":"#/$defs/A2aConfig","default":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trusted_trust_domains":[],"trust_domain":"prx.local"}},"agent":{"description":"Agent orchestration settings (`[agent]`).","$ref":"#/$defs/AgentConfig","default":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2,"messaging":{"inbound":true}}},"agents":{"description":"Delegate agent configurations for multi-agent workflows.","type":"object","additionalProperties":{"$ref":"#/$defs/DelegateAgentConfig"},"default":{}},"api_key":{"description":"API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.","type":["string","null"],"default":null},"api_url":{"description":"Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)","type":["string","null"],"default":null},"auth":{"description":"Auth profile and external credential import settings (`[auth]`).","$ref":"#/$defs/AuthConfig","default":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"}},"autonomy":{"description":"Autonomy and security policy configuration (`[autonomy]`).","$ref":"#/$defs/AutonomyConfig","default":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":500,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true}},"browser":{"description":"Browser automation configuration (`[browser]`).","$ref":"#/$defs/BrowserConfig","default":{"allowed_domains":[],"computer_use":{"api_key":null}}},"channels_config":{"description":"Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).","$ref":"#/$defs/ChannelsConfig","default":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null}},"chat":{"description":"Interactive chat UI configuration (`[chat]`).","$ref":"#/$defs/ChatConfig","default":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2}},"compliance":{"description":"Operator-owned compliance controls (`[compliance]`).","$ref":"#/$defs/ComplianceConfig","default":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}},"composio":{"description":"Composio managed OAuth tools integration (`[composio]`).","$ref":"#/$defs/ComposioConfig","default":{"api_key":null,"entity_id":"default"}},"cost":{"description":"Cost tracking and budget enforcement configuration (`[cost]`).","$ref":"#/$defs/CostConfig","default":{"allow_override":false,"daily_limit_usd":10.0,"monthly_limit_usd":100.0,"prices":{},"warn_at_percent":80}},"cron":{"description":"Cron job configuration (`[cron]`).","$ref":"#/$defs/CronConfig","default":{"max_run_history":50}},"decision_engine":{"description":"Optional advisory decision engine, disabled by default.","$ref":"#/$defs/DecisionEngineConfig","default":{"candidates":5,"enabled":false,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"latency_budget_ms":500,"max_candidates":12,"token_ratio_limit":0.3499999940395355}},"default_model":{"description":"Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.","type":["string","null"]},"default_provider":{"description":"Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.","type":["string","null"]},"default_temperature":{"description":"Default model temperature (0.0–2.0). Default: `0.7`.","type":"number","format":"double","default":0.7},"embedding_routes":{"description":"Embedding routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/EmbeddingRouteConfig"}},"gateway":{"description":"Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).","$ref":"#/$defs/GatewayConfig","default":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":false,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60}},"heartbeat":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]`).","$ref":"#/$defs/HeartbeatConfig","default":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."}},"http_request":{"description":"HTTP request tool configuration (`[http_request]`).","$ref":"#/$defs/HttpRequestConfig","default":{"max_response_size":1000000,"timeout_secs":30}},"identity":{"description":"Identity format configuration: OpenClaw or AIEOS (`[identity]`).","$ref":"#/$defs/IdentityConfig","default":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"}},"identity_bindings":{"description":"Static identity bindings loaded at startup (`[[identity_bindings]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/IdentityBindingConfig"}},"mcp":{"description":"Secrets encryption configuration (`[secrets]`).","$ref":"#/$defs/McpConfig","default":{"servers":{}}},"mcp_server":{"description":"MCP server compatibility configuration (`[mcp_server]`).","$ref":"#/$defs/McpServerRuntimeConfig","default":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true}},"media":{"description":"Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.","$ref":"#/$defs/MediaConfig","default":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"}},"memory":{"description":"Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).","$ref":"#/$defs/MemoryConfig","default":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7}},"model_routes":{"description":"Model routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/ModelRouteConfig"}},"model_settings":{"description":"Catalog model levels and explicit parameters, keyed by canonical release ID.","type":"object","additionalProperties":{"$ref":"#/$defs/ModelSettings"},"default":{}},"multimodal":{"description":"Multimodal (image) handling configuration (`[multimodal]`).","$ref":"#/$defs/MultimodalConfig","default":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4}},"nodes":{"description":"Remote node proxy configuration (`[nodes]`).","$ref":"#/$defs/NodesConfig","default":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}},"observability":{"description":"Observability backend configuration (`[observability]`).","$ref":"#/$defs/ObservabilityConfig","default":{"backend":"none","otel_endpoint":null,"otel_service_name":null}},"plugins":{"description":"WASM plugin runtime switch (`[plugins]`), off by default.","$ref":"#/$defs/PluginsConfig","default":{"enabled":false}},"providers":{"description":"Provider-specific runtime options (`[providers.]`).","$ref":"#/$defs/ProvidersConfig","default":{"ollama":{"num_ctx":null}}},"proxy":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).","$ref":"#/$defs/ProxyConfig","default":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]}},"query_classification":{"description":"Automatic query classification — maps user messages to model hints.","$ref":"#/$defs/QueryClassificationConfig","default":{"rules":[]}},"reliability":{"description":"Reliability settings: retries, fallback providers, backoff (`[reliability]`).","$ref":"#/$defs/ReliabilityConfig","default":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2}},"router":{"description":"Heuristic LLM router configuration (`[router]`).","$ref":"#/$defs/RouterConfig","default":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]}},"runtime":{"description":"Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.","$ref":"#/$defs/RuntimeConfig","default":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null}},"scheduler":{"description":"Scheduler configuration for periodic task execution (`[scheduler]`).","$ref":"#/$defs/SchedulerConfig","default":{"claim_lease_secs":90,"max_tasks":64}},"secrets":{"$ref":"#/$defs/SecretsConfig","default":{"encrypt":true}},"security":{"description":"Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).","$ref":"#/$defs/SecurityConfig","default":{"audit":{"log_path":"audit.log","max_size_mb":100}}},"self_system":{"description":"Self-system experimental automation controls (`[self_system]`).","$ref":"#/$defs/SelfSystemConfig","default":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24}},"sessions_spawn":{"description":"Session spawning configuration (`[sessions_spawn]`).","$ref":"#/$defs/SessionsSpawnConfig","default":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null}},"skill_rag":{"description":"Dynamic skill retrieval settings (`[skill_rag]`).","$ref":"#/$defs/SkillRagConfig","default":{"top_k":32}},"skills":{"description":"Skills loading and community repository behavior (`[skills]`).","$ref":"#/$defs/SkillsConfig","default":{"open_skills_dir":null,"openclaw_skills_dir":null}},"skills_lifecycle":{"description":"Skill lifecycle (`[skills_lifecycle]`), off by default.","$ref":"#/$defs/SkillsLifecycleConfig","default":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]}},"smart_group":{"description":"Smart group-reply pre-gate configuration (`[smart_group]`).","$ref":"#/$defs/SmartGroupConfig","default":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5}},"storage":{"description":"Persistent storage provider configuration (`[storage]`).","$ref":"#/$defs/StorageConfig","default":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"task_routing":{"description":"Task routing configuration — classifies work by intent before the main agent loop.","$ref":"#/$defs/TaskRoutingConfig","default":{"default_intent":"simple","rules":[]}},"tool_tiering":{"description":"Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).","$ref":"#/$defs/ToolTieringConfig","default":{"always_exclude":[],"always_include":[],"channel_exclude":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","skills_manage","memory_reindex","document_sync","document_ingest"]}},"tunnel":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]`).","$ref":"#/$defs/TunnelConfig","default":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null}},"user_policies":{"description":"Static user policy records loaded at startup (`[[user_policies]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/UserPolicyConfig"}},"web_search":{"description":"Web search tool configuration (`[web_search]`).","$ref":"#/$defs/WebSearchConfig","default":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15}},"webhook":{"description":"Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).","$ref":"#/$defs/MemoryWebhookConfig","default":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null}},"xin":{"description":"Xin autonomous task engine configuration (`[xin]`).","$ref":"#/$defs/XinConfig","default":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}}},"$defs":{"A2aConfig":{"type":"object","properties":{"agent_id":{"description":"Stable PRX agent identifier advertised to peers.","type":"string","default":"prx-default"},"allowed_peer_issuers":{"description":"Accepted external peer issuers.","type":"array","default":[],"items":{"type":"string"}},"bind":{"description":"Advertised bind address.","type":"string","default":"127.0.0.1:16832"},"card_jwks_uri":{"description":"Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.","type":["string","null"],"default":null},"card_signing_key_path":{"description":"On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).","type":["string","null"],"default":null},"card_ttl_seconds":{"description":"Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.","type":"integer","format":"uint64","default":3600,"minimum":0},"discovery_advertised":{"description":"Whether to advertise into an external A2A registry.","type":"boolean","default":false},"handoff_nonce_ttl_seconds":{"description":"Replay window for future handoff delegation tokens.","type":"integer","format":"uint64","default":3600,"minimum":0},"messaging_enabled":{"description":"Enable the dedicated pinned mTLS messaging listener.","type":"boolean","default":false},"peers":{"type":"object","additionalProperties":{"$ref":"#/$defs/A2aPeer"},"default":{}},"spiffe_id":{"description":"Local SPIFFE-style identifier placeholder.","type":"string","default":"spiffe://prx-local/agent/prx-default"},"spiffe_strict_validation":{"description":"When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.","type":"boolean","default":false},"spiffe_trust_bundle_pem":{"description":"Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).","type":["string","null"],"default":null},"trusted_trust_domains":{"description":"Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).","type":"array","default":[],"items":{"type":"string"}},"trust_domain":{"description":"SPIFFE trust domain for new instance identities.","type":"string","default":"prx.local"}}},"A2aPeer":{"description":"Explicit pinned identity and local recipient grant.","type":"object","properties":{"spiffe_id":{"type":"string"},"fingerprints":{"type":"array","items":{"type":"string"}},"address":{"type":"string"},"owner":{"type":"string"},"sessions":{"type":"array","default":["*"],"items":{"type":"string"}},"agents":{"type":"array","default":["*"],"items":{"type":"string"}}},"required":["spiffe_id","fingerprints","address","owner"],"additionalProperties":false},"AgentCompactionConfig":{"description":"Agent context compaction configuration (`[agent.compaction]`).","type":"object","properties":{"keep_recent_messages":{"description":"Number of recent non-system messages to keep after compaction.","type":"integer","format":"uint","default":12,"minimum":0},"max_context_tokens":{"description":"Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.","type":"integer","format":"uint","default":128000,"minimum":0},"memory_flush":{"description":"Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.","type":"boolean","default":true},"mode":{"description":"Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).","$ref":"#/$defs/AgentCompactionMode","default":"switch"},"os_paging":{"description":"Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.","$ref":"#/$defs/OsPagingConfig","default":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"}},"reserve_tokens":{"description":"Tokens reserved for the next model response.","type":"integer","format":"uint","default":4096,"minimum":0}}},"AgentCompactionMode":{"description":"Compaction mode for long conversation contexts.","oneOf":[{"description":"Disable proactive compaction.","type":"string","const":"off"},{"description":"Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.","type":"string","const":"switch"},{"description":"Conservative compaction that prefers summary replacement.","type":"string","const":"safeguard"},{"description":"Aggressive truncation mode for tighter contexts.","type":"string","const":"aggressive"}]},"AgentConfig":{"description":"Agent orchestration configuration (`[agent]` section).","type":"object","properties":{"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"compact_context":{"description":"When true: bootstrap_max_chars=6000. Use for 13B or smaller models.","type":"boolean","default":false},"compaction":{"description":"Context compaction controls (`[agent.compaction]`).","$ref":"#/$defs/AgentCompactionConfig","default":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096}},"low_priority_tools":{"description":"Tool names treated as low-priority when `priority_scheduling_enabled = true`.","type":"array","default":["sessions_spawn","delegate"],"items":{"type":"string"}},"priority_scheduling_enabled":{"description":"Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.","type":"boolean","default":false},"read_only_tool_concurrency_window":{"description":"Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.","type":"integer","format":"uint","default":2,"minimum":0},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}}},"AgentLimits":{"description":"Optional admission limits for rf-started turns of a named agent.","type":"object","properties":{"max_concurrent_turns":{"type":["integer","null"],"format":"uint32","minimum":0},"max_cost_per_day_cents":{"type":["integer","null"],"format":"uint64","minimum":0}},"additionalProperties":false},"AuditConfig":{"description":"Audit logging configuration","type":"object","properties":{"log_path":{"description":"Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).","type":"string","default":"audit.log"},"max_size_mb":{"description":"Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).","type":"integer","format":"uint32","default":100,"minimum":0}}},"AuthConfig":{"description":"Authentication and external credential import configuration (`[auth]` section).","type":"object","properties":{"codex_auth_json_auto_import":{"description":"Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.","type":"boolean","default":false},"codex_auth_json_path":{"description":"Source path for Codex CLI auth.json import.","type":"string","default":"~/.codex/auth.json"}}},"AutonomyConfig":{"type":"object","properties":{"acknowledge_unrestricted_profile":{"description":"Operator acknowledgement for an intentionally unrestricted profile.\nThis suppresses doctor noise only; it does not alter policy behavior.","type":"boolean","default":false},"forbidden_paths":{"description":"Explicit path denylist. Default includes system-critical paths.\n\nFails closed: omitting the key keeps the built-in list rather than\nemptying it, so a partial `[autonomy]` section never removes the\ndenylist.","type":"array","default":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"items":{"type":"string"}},"level":{"description":"Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).","$ref":"#/$defs/AutonomyLevel","default":"full"},"max_cost_per_day_cents":{"description":"Maximum cost per day in cents per policy. Default: `500`.","type":"integer","format":"uint32","default":500,"minimum":0},"scopes":{"description":"Scope-based tool access control: per-user/channel/chat-type allow/deny rules.","$ref":"#/$defs/ScopeConfig","default":{"assign_owners":[],"default":"allow","rules":[]}},"workspace_only":{"description":"Restrict file writes and command paths to the workspace directory. Default: `true`.\n\nFails closed: a `[autonomy]` section that omits this key keeps the\nworkspace restriction on, so a partial section can never widen the\nfilesystem reach by accident.","type":"boolean","default":true}}},"AutonomyLevel":{"description":"How much autonomy the agent has","oneOf":[{"description":"Read-only: can observe but not act","type":"string","const":"readonly"},{"description":"Supervised: acts but requires approval for risky operations","type":"string","const":"supervised"},{"description":"Full: autonomous execution within policy bounds","type":"string","const":"full"}]},"BackendSelection":{"description":"Which decision backend runs: `auto` (the factory's order) or one kind.","type":"string"},"BrowserComputerUseConfig":{"description":"Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.","type":"object","properties":{"api_key":{"description":"Optional bearer token (retained only for config secret handling).","type":["string","null"],"default":null}}},"BrowserConfig":{"description":"Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.","type":"object","properties":{"allowed_domains":{"description":"Allowed domains for `web_fetch` (exact or subdomain match).","type":"array","default":[],"items":{"type":"string"}},"computer_use":{"description":"Computer-use sidecar config (retained only for `api_key` secret handling).","$ref":"#/$defs/BrowserComputerUseConfig","default":{"api_key":null}}}},"ChannelsConfig":{"description":"Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.","type":"object","properties":{"cli":{"description":"Enable the CLI interactive channel. Default: `true`.","type":"boolean","default":true},"dingtalk":{"description":"DingTalk channel configuration.","anyOf":[{"$ref":"#/$defs/DingTalkConfig"},{"type":"null"}]},"discord":{"description":"Discord bot channel configuration.","anyOf":[{"$ref":"#/$defs/DiscordConfig"},{"type":"null"}]},"email":{"description":"Email channel configuration.","anyOf":[{"$ref":"#/$defs/EmailConfig"},{"type":"null"}]},"imessage":{"description":"iMessage channel configuration (macOS only).","anyOf":[{"$ref":"#/$defs/IMessageConfig"},{"type":"null"}]},"irc":{"description":"IRC channel configuration.","anyOf":[{"$ref":"#/$defs/IrcConfig"},{"type":"null"}]},"lark":{"description":"Lark/Feishu channel configuration.","anyOf":[{"$ref":"#/$defs/LarkConfig"},{"type":"null"}]},"linq":{"description":"Linq Partner API channel configuration.","anyOf":[{"$ref":"#/$defs/LinqConfig"},{"type":"null"}]},"mattermost":{"description":"Mattermost bot channel configuration.","anyOf":[{"$ref":"#/$defs/MattermostConfig"},{"type":"null"}]},"nextcloud_talk":{"description":"Nextcloud Talk bot channel configuration.","anyOf":[{"$ref":"#/$defs/NextcloudTalkConfig"},{"type":"null"}]},"qq":{"description":"QQ Official Bot channel configuration.","anyOf":[{"$ref":"#/$defs/QQConfig"},{"type":"null"}]},"ramflux":{"description":"Local ramflux agent-host bridge.","anyOf":[{"$ref":"#/$defs/RamfluxConfig"},{"type":"null"}],"default":null},"signal":{"description":"Signal channel configuration.","anyOf":[{"$ref":"#/$defs/SignalConfig"},{"type":"null"}]},"slack":{"description":"Slack bot channel configuration.","anyOf":[{"$ref":"#/$defs/SlackConfig"},{"type":"null"}]},"telegram":{"description":"Telegram bot channel configuration.","anyOf":[{"$ref":"#/$defs/TelegramConfig"},{"type":"null"}]},"wacli":{"description":"wacli JSON-RPC daemon channel configuration.","anyOf":[{"$ref":"#/$defs/WacliConfig"},{"type":"null"}],"default":null},"webhook":{"description":"Webhook channel configuration.","anyOf":[{"$ref":"#/$defs/WebhookConfig"},{"type":"null"}]},"whatsapp":{"description":"WhatsApp channel configuration (Cloud API or Web mode).","anyOf":[{"$ref":"#/$defs/WhatsAppConfig"},{"type":"null"}]}}},"ChatConfig":{"description":"Interactive chat configuration (`[chat]`).","type":"object","properties":{"daemon":{"description":"How this chat process reaches the daemon it borrows channels from.","$ref":"#/$defs/ChatDaemonConfig","default":{"token":"","url":""}},"max_concurrent_visible_turns":{"description":"Maximum concurrent visible provider turns in the TUI Redux driver.","type":"integer","format":"uint","default":2,"minimum":0}}},"ChatDaemonConfig":{"description":"Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.","type":"object","properties":{"token":{"description":"Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.","type":"string","default":""},"url":{"description":"Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.","type":"string","default":""}}},"CircuitBreakerConfig":{"description":"The per-backend circuit breaker.","type":"object","properties":{"cooldown_secs":{"description":"Seconds the breaker stays open (1 to 3600).","type":"integer","format":"uint32","default":60,"minimum":0},"failure_threshold":{"description":"Consecutive failures before the breaker opens (1 to 100).","type":"integer","format":"uint32","default":5,"minimum":0}}},"ClassificationRule":{"description":"A single classification rule mapping message patterns to a model hint.","type":"object","properties":{"hint":{"description":"Must match a `[[model_routes]]` hint value.","type":"string"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"max_length":{"description":"Only match if message length <= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"min_length":{"description":"Only match if message length >= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"patterns":{"description":"Case-sensitive literal matches (for \"```\", \"fn \", etc.).","type":"array","default":[],"items":{"type":"string"}},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0}},"required":["hint"]},"CloudflareTunnelConfig":{"type":"object","properties":{"token":{"description":"Cloudflare Tunnel token (from Zero Trust dashboard)","type":"string"}},"required":["token"]},"ComplianceConfig":{"type":"object","properties":{"eu_ai_act":{"$ref":"#/$defs/EuAiActComplianceConfig","default":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null}},"interaction_notice":{"$ref":"#/$defs/InteractionNoticeConfig","default":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}}},"ComposioConfig":{"description":"Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.","type":"object","properties":{"api_key":{"description":"Composio API key (stored encrypted when secrets.encrypt = true)","type":["string","null"],"default":null},"entity_id":{"description":"Default entity ID for multi-user setups","type":"string","default":"default"}}},"CostConfig":{"description":"Cost tracking and budget enforcement configuration (`[cost]` section).","type":"object","properties":{"allow_override":{"description":"Allow requests to exceed budget with --override flag (default: false)","type":"boolean","default":false},"daily_limit_usd":{"description":"Daily spending limit in USD (default: 10.00)","type":"number","format":"double","default":10.0},"monthly_limit_usd":{"description":"Monthly spending limit in USD (default: 100.00)","type":"number","format":"double","default":100.0},"prices":{"description":"Per-model pricing (USD per 1M tokens)","type":"object","additionalProperties":{"$ref":"#/$defs/ModelPricing"},"default":{}},"warn_at_percent":{"description":"Warn when spending reaches this percentage of limit (default: 80)","type":"integer","format":"uint8","default":80,"maximum":255,"minimum":0}}},"CredentialRefSetting":{"description":"Which credential a decision backend uses. A reference, never a secret.","type":"string"},"CronConfig":{"description":"Cron job configuration (`[cron]` section).","type":"object","properties":{"max_run_history":{"description":"Maximum number of historical cron run records to retain. Default: `50`.","type":"integer","format":"uint32","default":50,"minimum":0}}},"CustomTunnelConfig":{"type":"object","properties":{"health_url":{"description":"Optional URL to check tunnel health","type":["string","null"]},"start_command":{"description":"Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"","type":"string"},"url_pattern":{"description":"Optional regex to extract public URL from command stdout","type":["string","null"]}},"required":["start_command"]},"DecisionBackendConfig":{"description":"The decision backend (`[decision_engine.backend]`).","type":"object","properties":{"circuit_breaker":{"description":"The circuit breaker.","$ref":"#/$defs/CircuitBreakerConfig","default":{"cooldown_secs":60,"failure_threshold":5}},"credential_ref":{"description":"The credential reference: `\"\"`, `\"none\"` or `cred-`.","$ref":"#/$defs/CredentialRefSetting","default":""},"endpoint":{"description":"The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.","type":"string","default":""},"kind":{"description":"`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).","$ref":"#/$defs/BackendSelection","default":"auto"},"max_request_bytes":{"description":"Largest request body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":65536,"minimum":0},"max_response_bytes":{"description":"Largest response body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":262144,"minimum":0},"model":{"description":"The model the endpoint serves; one exact version for a hosted\nservice.","type":"string","default":""},"pinned_snapshot":{"description":"The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.","type":"string"},"remote_enabled":{"description":"Whether decision state may leave this machine. Default `false`.","type":"boolean","default":false},"timeout_ms":{"description":"Transport timeout (10 ms up to the extra latency budget).","type":"integer","format":"uint32","default":250,"minimum":0}}},"DecisionEngineConfig":{"type":"object","properties":{"backend":{"anyOf":[{"$ref":"#/$defs/DecisionBackendConfig"},{"type":"null"}]},"candidates":{"type":"integer","format":"uint32","default":5,"minimum":0},"enabled":{"type":"boolean","default":false},"mode":{"$ref":"#/$defs/DecisionMode","default":"pre"},"observe_queue":{"type":"integer","format":"uint32","default":64,"minimum":0},"prompt_budget_tokens":{"type":"integer","format":"uint32","default":300,"minimum":0},"telemetry_cap":{"type":"integer","format":"uint32","default":1000,"minimum":0},"timeout_ms":{"type":"integer","format":"uint32","default":1500,"minimum":0},"latency_budget_ms":{"description":"The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.","type":"integer","format":"uint64","default":500,"minimum":0},"token_ratio_limit":{"description":"Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).","type":"number","format":"float","default":0.3499999940395355},"max_candidates":{"description":"The most candidates a turn considers (1 to 32).","type":"integer","format":"uint8","default":12,"maximum":255,"minimum":0}}},"DecisionMode":{"type":"string","enum":["pre","post","both"]},"DeclarationOfConformityConfig":{"type":"object","properties":{"applicable_union_law":{"type":"array","default":[],"items":{"type":"string"}},"artifact_path":{"type":["string","null"],"default":null},"artifact_version":{"type":["string","null"],"default":null},"conformity_assessment_procedure":{"type":["string","null"],"default":null},"conformity_statement":{"type":["string","null"],"default":null},"harmonised_standards":{"type":"array","default":[],"items":{"type":"string"}},"issue_date":{"type":["string","null"],"default":null},"issue_place":{"type":["string","null"],"default":null},"notified_body_certificate":{"type":["string","null"],"default":null},"notified_body_identification_number":{"type":["string","null"],"default":null},"notified_body_name":{"type":["string","null"],"default":null},"personal_data_compliance_statement":{"type":["string","null"],"default":null},"processes_personal_data":{"type":"boolean","default":false},"provider_address":{"type":["string","null"],"default":null},"provider_name":{"type":["string","null"],"default":null},"signer_function":{"type":["string","null"],"default":null},"signer_name":{"type":["string","null"],"default":null},"signer_on_behalf_of":{"type":["string","null"],"default":null},"sole_responsibility_statement":{"type":["string","null"],"default":null},"standards_not_applicable_reason":{"type":["string","null"],"default":null},"system_name":{"type":["string","null"],"default":null},"system_reference":{"type":["string","null"],"default":null},"system_type":{"type":["string","null"],"default":null}}},"DelegateAgentConfig":{"description":"Configuration for a delegate sub-agent used by the `delegate` tool.","type":"object","properties":{"agentic":{"description":"Enable agentic sub-agent mode (multi-turn tool-call loop).","type":"boolean","default":false},"allowed_tools":{"description":"Allowlist of tool names available to the sub-agent in agentic mode.","type":"array","default":[],"items":{"type":"string"}},"api_key":{"description":"Optional API key override","type":["string","null"],"default":null},"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"autonomy":{"description":"The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.","anyOf":[{"$ref":"#/$defs/AutonomyLevel"},{"type":"null"}]},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"enabled":{"description":"Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.","type":"boolean","default":true},"identity_dir":{"description":"Optional identity files directory relative to workspace root.","type":["string","null"],"default":null},"limits":{"$ref":"#/$defs/AgentLimits","default":{"max_concurrent_turns":null,"max_cost_per_day_cents":null}},"max_depth":{"description":"Max recursion depth for nested delegation","type":"integer","format":"uint32","default":8,"minimum":0},"memory_scope":{"description":"Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".","type":["string","null"],"default":null},"model":{"description":"Model name","type":"string"},"provider":{"description":"Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")","type":"string"},"spawn_enabled":{"description":"Whether this agent is allowed to be targeted by sessions_spawn (default: true).","type":["boolean","null"],"default":null},"system_prompt":{"description":"Optional system prompt for the sub-agent","type":["string","null"],"default":null},"temperature":{"description":"Temperature override","type":["number","null"],"format":"double","default":null},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}},"required":["provider","model"]},"DingTalkConfig":{"description":"DingTalk configuration for Stream Mode messaging","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"client_id":{"description":"Client ID (AppKey) from DingTalk developer console","type":"string"},"client_secret":{"description":"Client Secret (AppSecret) from DingTalk developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["client_id","client_secret"]},"DiscordConfig":{"description":"Discord bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Discord user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Discord bot token (from Discord Developer Portal).","type":"string"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"guild_id":{"description":"Optional guild (server) ID to restrict the bot to a single guild.","type":["string","null"]},"listen_to_bots":{"description":"When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.","type":"boolean","default":false}},"required":["bot_token"]},"DmPolicy":{"description":"Policy for direct-message handling.","oneOf":[{"description":"Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).","type":"string","const":"pairing"},{"description":"Accept only senders listed in `allowed_from`.","type":"string","const":"allowlist"},{"description":"Accept any direct sender.","type":"string","const":"open"},{"description":"Ignore direct messages.","type":"string","const":"disabled"}]},"DockerRuntimeConfig":{"description":"Docker runtime configuration (`[runtime.docker]` section).","type":"object","properties":{"allowed_workspace_roots":{"description":"Optional workspace root allowlist for Docker mount validation.","type":"array","default":[],"items":{"type":"string"}},"cpu_limit":{"description":"Optional CPU limit (`None` = no explicit limit).","type":["number","null"],"format":"double","default":1.0},"image":{"description":"Runtime image used to execute shell commands.","type":"string","default":"alpine:3.20"},"memory_limit_mb":{"description":"Optional memory limit in MB (`None` = no explicit limit).","type":["integer","null"],"format":"uint64","default":512,"minimum":0},"mount_workspace":{"description":"Mount configured workspace into `/workspace`.","type":"boolean","default":true},"network":{"description":"Docker network mode (`none`, `bridge`, etc.).","type":"string","default":"none"},"read_only_rootfs":{"description":"Mount root filesystem as read-only.","type":"boolean","default":true}}},"EmailConfig":{"description":"Email channel configuration","type":"object","properties":{"allowed_senders":{"description":"Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)","type":"array","default":[],"items":{"type":"string"}},"from_address":{"description":"From address for outgoing emails","type":"string"},"idle_timeout_secs":{"description":"IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes","type":"integer","format":"uint64","default":1740,"minimum":0},"imap_folder":{"description":"IMAP folder to poll (default: INBOX)","type":"string","default":"INBOX"},"imap_host":{"description":"IMAP server hostname","type":"string"},"imap_port":{"description":"IMAP server port (default: 993 for TLS)","type":"integer","format":"uint16","default":993,"maximum":65535,"minimum":0},"password":{"description":"Email password for authentication","type":"string"},"smtp_host":{"description":"SMTP server hostname","type":"string"},"smtp_port":{"description":"SMTP server port (default: 465 for TLS)","type":"integer","format":"uint16","default":465,"maximum":65535,"minimum":0},"smtp_tls":{"description":"Use TLS for SMTP (default: true)","type":"boolean","default":true},"username":{"description":"Email username for authentication","type":"string"}},"required":["imap_host","smtp_host","username","password","from_address"]},"EmbeddingRouteConfig":{"description":"Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"dimensions":{"description":"Optional embedding dimension override for this route","type":["integer","null"],"format":"uint","default":null,"minimum":0},"hint":{"description":"Route hint name (e.g. \"semantic\", \"archive\", \"faq\")","type":"string"},"model":{"description":"Embedding model to use with that provider","type":"string"},"provider":{"description":"Embedding provider (`none`, `openai`, or `custom:`)","type":"string"}},"required":["hint","provider","model"]},"EuAiActClassificationConfig":{"type":"object","properties":{"assessed_at":{"type":["string","null"],"default":null},"owner":{"type":["string","null"],"default":null},"status":{"$ref":"#/$defs/EuAiActRiskClassification","default":"unclassified"}}},"EuAiActComplianceConfig":{"type":"object","properties":{"classification":{"$ref":"#/$defs/EuAiActClassificationConfig","default":{"assessed_at":null,"owner":null,"status":"unclassified"}},"declaration":{"$ref":"#/$defs/DeclarationOfConformityConfig","default":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null}},"incident_store_path":{"type":["string","null"],"default":null}}},"EuAiActRiskClassification":{"type":"string","enum":["unclassified","high_risk","not_high_risk"]},"FitnessConfig":{"description":"Calendar schedule, evidence thresholds, and retention for fitness v2.","type":"object","properties":{"auto_run":{"description":"Run the daily fitness worker in daemon mode.","type":"boolean","default":true},"max_backfill_days":{"description":"Maximum number of closed days recovered after downtime.","type":"integer","format":"uint32","default":7,"minimum":0},"min_coverage":{"description":"Minimum available metric weight required to publish a final score.","type":"number","format":"double","default":0.6},"min_samples":{"description":"Minimum samples required before an evidence-derived subscore is usable.","type":"integer","format":"uint","default":5,"minimum":0},"retention_days":{"description":"Number of daily JSON reports retained on disk.","type":"integer","format":"uint32","default":180,"minimum":0},"run_at":{"description":"Local wall-clock time (`HH:MM`) at which the previous day is scored.","type":"string","default":"00:10"},"timezone":{"description":"IANA timezone used to define closed calendar days.","type":"string","default":"UTC"}}},"GatewayConfig":{"description":"Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.","type":"object","properties":{"allow_public_bind":{"description":"Allow binding to non-localhost without a tunnel (default: false)","type":"boolean","default":false},"api_rate_limit_per_minute":{"description":"Max `/api/*` requests per minute per authenticated token.","type":"integer","format":"uint32","default":60,"minimum":0},"channel_webhook_dedup_ttl_secs":{"description":"How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.","type":"integer","format":"uint64","default":86400,"minimum":0},"host":{"description":"Gateway host (default: 127.0.0.1)","type":"string","default":"127.0.0.1"},"idempotency_max_keys":{"description":"Maximum distinct idempotency keys retained in memory.","type":"integer","format":"uint","default":10000,"minimum":0},"idempotency_ttl_secs":{"description":"TTL for webhook idempotency keys.","type":"integer","format":"uint64","default":300,"minimum":0},"pair_rate_limit_per_minute":{"description":"Max `/pair` requests per minute per client key.","type":"integer","format":"uint32","default":10,"minimum":0},"paired_tokens":{"description":"Paired bearer tokens (managed automatically, not user-edited)","type":"array","default":[],"items":{"type":"string"}},"port":{"description":"Gateway port (default: 16830)","type":"integer","format":"uint16","default":16830,"maximum":65535,"minimum":0},"rate_limit_max_keys":{"description":"Maximum distinct client keys tracked by gateway rate limiter maps.","type":"integer","format":"uint","default":10000,"minimum":0},"require_pairing":{"description":"Require pairing before accepting requests (default: true)","type":"boolean","default":true},"targeted_agents":{"description":"Rollout switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). While false, any otherwise-valid\nnamed target answers 409 `agent_disabled` and never runs as Main.","type":"boolean","default":false},"trust_forwarded_headers":{"description":"Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.","type":"boolean","default":false},"webhook_rate_limit_per_minute":{"description":"Max `/webhook` requests per minute per client key.","type":"integer","format":"uint32","default":60,"minimum":0}}},"GroupPolicy":{"description":"Policy for group-message handling.","oneOf":[{"description":"Accept only groups listed in `group_allow_from`.","type":"string","const":"allowlist"},{"description":"Accept any group.","type":"string","const":"open"},{"description":"Ignore group messages.","type":"string","const":"disabled"}]},"GroupReplyMode":{"description":"How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.","oneOf":[{"description":"Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).","type":"string","const":"off"},{"description":"Reply only when the bot is @-mentioned (legacy `mention_only = true`).","type":"string","const":"mention-only"},{"description":"Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).","type":"string","const":"smart"}]},"HeartbeatConfig":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]` section).","type":"object","properties":{"active_hours":{"description":"Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.","type":"array","default":[8,23],"items":{"type":"integer","format":"uint8","maximum":255,"minimum":0}},"interval_minutes":{"description":"Interval in minutes between heartbeat pings. Default: `30`.","type":"integer","format":"uint32","default":30,"minimum":0},"prompt":{"description":"Prompt used by heartbeat worker when dispatching tasks.","type":"string","default":"Check HEARTBEAT.md and follow instructions."}}},"HttpRequestConfig":{"description":"HTTP request tool configuration (`[http_request]` section).","type":"object","properties":{"max_response_size":{"description":"Maximum response size in bytes (default: 1MB)","type":"integer","format":"uint","default":1000000,"minimum":0},"timeout_secs":{"description":"Request timeout in seconds (default: 30)","type":"integer","format":"uint64","default":30,"minimum":0}}},"IMessageConfig":{"description":"iMessage channel configuration (macOS only).","type":"object","properties":{"allowed_contacts":{"description":"Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.","type":"array","items":{"type":"string"}},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["allowed_contacts"]},"IdentityBindingConfig":{"description":"Startup identity binding entry (`[[identity_bindings]]`).","type":"object","properties":{"channel":{"type":"string"},"channel_account":{"type":"string"},"display_name":{"type":["string","null"],"default":null},"user_id":{"type":"string"}},"required":["user_id","channel","channel_account"]},"IdentityConfig":{"description":"Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.","type":"object","properties":{"aieos_inline":{"description":"Inline AIEOS JSON (alternative to file path)","type":["string","null"],"default":null},"aieos_path":{"description":"Path to AIEOS JSON file (relative to workspace)","type":["string","null"],"default":null},"format":{"description":"Identity format: \"openclaw\" (default) or \"aieos\"","type":"string","default":"openclaw"}}},"InteractionNoticeApplicability":{"type":"string","enum":["required","not_applicable"]},"InteractionNoticeConfig":{"type":"object","properties":{"applicability":{"$ref":"#/$defs/InteractionNoticeApplicability","default":"required"},"exception_owner":{"type":["string","null"],"default":null},"exception_reviewed_at":{"type":["string","null"],"default":null},"text":{"type":"string","default":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers."},"version":{"type":"string","default":"1"}}},"IrcConfig":{"description":"IRC channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed nicknames (case-insensitive) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"channels":{"description":"Channels to join on connect","type":"array","default":[],"items":{"type":"string"}},"mention_only":{"description":"When true, only process channel/group messages that mention the bot.","type":"boolean","default":false},"nickname":{"description":"Bot nickname","type":"string"},"nickserv_password":{"description":"NickServ IDENTIFY password","type":["string","null"]},"port":{"description":"IRC server port (default: 6697 for TLS)","type":"integer","format":"uint16","default":6697,"maximum":65535,"minimum":0},"sasl_password":{"description":"SASL PLAIN password (IRCv3)","type":["string","null"]},"server":{"description":"IRC server hostname","type":"string"},"server_password":{"description":"Server password (for bouncers like ZNC)","type":["string","null"]},"username":{"description":"Username (defaults to nickname if not set)","type":["string","null"]},"verify_tls":{"description":"Verify TLS certificate (default: true)","type":["boolean","null"]}},"required":["server","nickname"]},"LarkConfig":{"description":"Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from Lark/Feishu developer console","type":"string"},"app_secret":{"description":"App Secret from Lark/Feishu developer console","type":"string"},"encrypt_key":{"description":"Encrypt key for webhook message decryption (optional)","type":["string","null"],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"port":{"description":"HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"receive_mode":{"description":"Event receive mode: \"websocket\" (default) or \"webhook\"","$ref":"#/$defs/LarkReceiveMode","default":"websocket"},"use_feishu":{"description":"Whether to use the Feishu (Chinese) endpoint instead of Lark (International)","type":"boolean","default":false},"verification_token":{"description":"Verification token for webhook validation (optional)","type":["string","null"],"default":null}},"required":["app_id","app_secret"]},"LarkReceiveMode":{"description":"How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.","type":"string","enum":["websocket","webhook"]},"LinqConfig":{"type":"object","properties":{"allowed_senders":{"description":"Allowed sender handles (phone numbers) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"api_token":{"description":"Linq Partner API token (Bearer auth)","type":"string"},"from_phone":{"description":"Phone number to send from (E.164 format)","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"signing_secret":{"description":"Webhook signing secret for signature verification","type":["string","null"],"default":null}},"required":["api_token","from_phone"]},"MattermostConfig":{"description":"Mattermost bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Mattermost user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Mattermost bot access token.","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.","type":["boolean","null"],"default":null},"thread_replies":{"description":"When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.","type":["boolean","null"],"default":null},"url":{"description":"Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).","type":"string"}},"required":["url","bot_token"]},"McpConfig":{"type":"object","properties":{"servers":{"description":"Named MCP server definitions","type":"object","additionalProperties":{"$ref":"#/$defs/McpServerConfig"},"default":{}},"workspace_servers":{"description":"Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.","$ref":"#/$defs/WorkspaceMcpServers"}}},"McpServerConfig":{"type":"object","properties":{"allow_tools":{"description":"Optional allow-list of exposed tools (empty = all)","type":"array","default":[],"items":{"type":"string"}},"args":{"description":"Command args for stdio mode","type":"array","default":[],"items":{"type":"string"}},"command":{"description":"Command for stdio mode","type":["string","null"],"default":null},"deny_tools":{"description":"Optional deny-list of exposed tools","type":"array","default":[],"items":{"type":"string"}},"env":{"description":"Environment variables for stdio mode","type":"object","additionalProperties":{"type":"string"},"default":{}},"request_timeout_ms":{"description":"Request timeout in milliseconds","type":"integer","format":"uint64","default":30000,"minimum":0},"startup_timeout_ms":{"description":"Startup timeout in milliseconds","type":"integer","format":"uint64","default":10000,"minimum":0},"tool_name_prefix":{"description":"Prefix used in tool naming and routing","type":"string","default":"mcp"},"transport":{"description":"Transport type: stdio or http","$ref":"#/$defs/McpTransport","default":"stdio"},"url":{"description":"URL for HTTP mode (streamable HTTP endpoint)","type":["string","null"],"default":null},"working_dir":{"description":"Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).","type":["string","null"]}}},"McpServerRuntimeConfig":{"type":"object","properties":{"allowed_origins":{"description":"Allowed browser origins for future streamable HTTP clients.","type":"array","default":["claude.ai","openai.com","localhost"],"items":{"type":"string"}},"bind":{"description":"Advertised bind address. The gateway may still be started with a CLI port override.","type":"string","default":"127.0.0.1:16831"},"exposed_tools":{"description":"Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.","type":"array","default":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"items":{"type":"string"}},"jwt_algorithms":{"description":"Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.","type":"array","default":["RS256"],"items":{"type":"string"}},"jwt_audience":{"description":"Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.","type":["string","null"],"default":null},"jwt_issuer":{"description":"Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.","type":["string","null"],"default":null},"jwt_jwks":{"description":"Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.","type":["string","null"],"default":null},"jwt_jwks_cache_ttl_secs":{"description":"Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.","type":"integer","format":"uint64","default":300,"minimum":0},"jwt_jwks_uri":{"description":"Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.","type":["string","null"],"default":null},"jwt_public_key_pem":{"description":"PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.","type":["string","null"],"default":null},"rate_limit_rps":{"description":"Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.","type":"integer","format":"uint32","default":10,"minimum":0},"require_auth":{"description":"Require an authenticated external identity for mutating calls.","type":"boolean","default":true}}},"McpTransport":{"type":"string","enum":["stdio","http"]},"MediaConfig":{"description":"Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.","type":"object","properties":{"audio_model":{"description":"Audio model name (Ollama model or OpenAI model). Default: \"whisper\".","type":"string","default":"whisper"},"audio_ollama_url":{"description":"Ollama base URL for audio transcription. Default: \"http://localhost:11434\".","type":"string","default":"http://localhost:11434"},"audio_provider":{"description":"Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".","type":"string","default":"none"},"max_audio_size_mb":{"description":"Maximum audio attachment size in MiB. Default: 20.","type":"integer","format":"uint","default":20,"minimum":0},"max_video_size_mb":{"description":"Maximum video attachment size in MiB. Default: 50.","type":"integer","format":"uint","default":50,"minimum":0},"video_max_frames":{"description":"Maximum video frames to extract per video. Default: 4.","type":"integer","format":"uint","default":4,"minimum":0},"video_provider":{"description":"Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".","type":"string","default":"none"}}},"MemoryConfig":{"description":"Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.","type":"object","properties":{"acl_enabled":{"description":"Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.","type":"boolean","default":false},"archive_after_days":{"description":"Archive daily/session files older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"auto_hydrate":{"description":"Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing","type":"boolean","default":true},"auto_save":{"description":"Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.","type":"boolean","default":true},"backend":{"description":"\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).","type":"string","default":"sqlite"},"conversation_retention_days":{"description":"For sqlite backend: prune conversation rows older than this many days","type":"integer","format":"uint32","default":3,"minimum":0},"daily_retention_days":{"description":"For sqlite backend: prune daily rows older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"embedding_cache_size":{"description":"Max embedding cache entries before LRU eviction","type":"integer","format":"uint","default":10000,"minimum":0},"embedding_dimensions":{"description":"Embedding vector dimensions","type":"integer","format":"uint","default":384,"minimum":0},"embedding_model":{"description":"Embedding model name (e.g. \"text-embedding-3-small\")","type":"string","default":"prx-local-hash-v1"},"embedding_provider":{"description":"Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"","type":"string","default":"local"},"events":{"description":"Raw/quasi-raw message event recording controls (`[memory.events]`).","$ref":"#/$defs/MemoryEventsConfig","default":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true}},"keyword_weight":{"description":"Weight for keyword BM25 in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.3},"legacy_conversation_turns_visible":{"description":"Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.","type":"boolean","default":true},"lucid_budget":{"description":"Token budget for lucid (replaces OPENPRX_LUCID_BUDGET)","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"lucid_cmd":{"description":"Path to lucid binary (replaces OPENPRX_LUCID_CMD)","type":["string","null"],"default":null},"lucid_failure_cooldown_ms":{"description":"Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)","type":"integer","format":"uint64","default":60000,"minimum":0},"lucid_local_hit_threshold":{"description":"Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)","type":"integer","format":"uint","default":3,"minimum":0},"lucid_recall_timeout_ms":{"description":"Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)","type":"integer","format":"uint64","default":5000,"minimum":0},"lucid_store_timeout_ms":{"description":"Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)","type":"integer","format":"uint64","default":3000,"minimum":0},"min_relevance_score":{"description":"Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4","type":"number","format":"double","default":0.4},"purge_after_days":{"description":"Purge archived files older than this many days","type":"integer","format":"uint32","default":30,"minimum":0},"semantic":{"description":"Semantic memory promotion controls (`[memory.semantic]`).","$ref":"#/$defs/MemorySemanticConfig","default":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30}},"sqlite_open_timeout_secs":{"description":"For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"sqlite_read_pool_size":{"description":"For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"vector_candidate_cap":{"description":"How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.","type":"integer","format":"uint","default":2000,"minimum":0},"vector_weight":{"description":"Weight for vector similarity in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.7}}},"MemoryEventsConfig":{"description":"Raw message event recording configuration (`[memory.events]`).","type":"object","properties":{"record_assistant_messages":{"description":"Record assistant replies.","type":"boolean","default":true},"record_tool_events":{"description":"Record tool/event payloads by default.","type":"boolean","default":false},"record_user_messages":{"description":"Record inbound/user messages.","type":"boolean","default":true}}},"MemorySemanticConfig":{"description":"Semantic memory promotion configuration (`[memory.semantic]`).","type":"object","properties":{"auto_promote_assistant_messages":{"description":"Auto-promote eligible assistant messages. Disabled by default to reduce noise.","type":"boolean","default":false},"auto_promote_user_messages":{"description":"Auto-promote eligible user messages into long-term semantic memories.","type":"boolean","default":true},"min_chars":{"description":"Minimum content length for semantic auto-promotion.","type":"integer","format":"uint","default":30,"minimum":0}}},"MemoryWebhookConfig":{"type":"object","properties":{"bind":{"description":"Socket address for the receiver (e.g. \"0.0.0.0:16899\").","type":"string","default":"0.0.0.0:16899"},"signing_secret":{"description":"Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.","type":["string","null"],"default":null},"token":{"description":"Required bearer token for incoming webhook events.","type":["string","null"],"default":null}}},"ModelOperationSetting":{"description":"The operations a `[[providers.models]]` entry may list.","type":"string","enum":["chat","embedding","decision_endpoint","rerank","image_generation","audio_generation","video_generation"]},"ModelPricing":{"description":"Per-model pricing entry (USD per 1M tokens).","type":"object","properties":{"cache_read":{"description":"Cache read input price per 1M tokens.","type":"number","format":"double","default":0.0},"cache_write":{"description":"Cache write/creation input price per 1M tokens.","type":"number","format":"double","default":0.0},"input":{"description":"Input price per 1M tokens","type":"number","format":"double","default":0.0},"output":{"description":"Output price per 1M tokens","type":"number","format":"double","default":0.0}}},"ModelRouteConfig":{"description":"Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"hint":{"description":"Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")","type":"string"},"level":{"type":["string","null"]},"model":{"description":"Model to use with that provider","type":"string"},"provider":{"description":"Provider to route to (must match a known provider name)","type":"string"},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true,"required":["hint","provider","model"]},"ModelSettings":{"description":"A model level plus explicit parameter overrides in `[model_settings.\"\"]`.","type":"object","properties":{"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"level":{"type":["string","null"]},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true},"MultimodalConfig":{"description":"Multimodal (image) handling configuration (`[multimodal]` section).","type":"object","properties":{"allow_remote_fetch":{"description":"Allow fetching remote image URLs (http/https). Disabled by default.","type":"boolean","default":false},"max_image_size_mb":{"description":"Maximum image payload size in MiB before base64 encoding.","type":"integer","format":"uint","default":5,"minimum":0},"max_images":{"description":"Maximum number of image attachments accepted per request.","type":"integer","format":"uint","default":4,"minimum":0}}},"NextcloudTalkConfig":{"description":"Nextcloud Talk bot configuration (webhook receive + OCS send API).","type":"object","properties":{"allowed_users":{"description":"Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Bot app token used for OCS API bearer auth.","type":"string"},"base_url":{"description":"Nextcloud base URL (e.g. \"https://cloud.example.com\").","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"webhook_secret":{"description":"Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).","type":["string","null"],"default":null}},"required":["base_url","app_token"]},"NgrokTunnelConfig":{"type":"object","properties":{"auth_token":{"description":"ngrok auth token","type":"string"},"domain":{"description":"Optional custom domain","type":["string","null"]}},"required":["auth_token"]},"NodeServerConfig":{"description":"Node daemon runtime config used by `prx-node`.","type":"object","properties":{"allowed_commands":{"description":"Command allowlist matched on first token.\n\nIn restricted mode this list is required unless explicitly set to `[\"*\"]`.","type":"array","default":["echo"],"items":{"type":"string"}},"bearer_token":{"description":"Required bearer token for /rpc.","type":"string","default":""},"blocked_commands":{"description":"Command denylist matched on first token. Always enforced.","type":"array","default":[],"items":{"type":"string"}},"exec_timeout_ms":{"description":"Default command timeout in milliseconds.","type":"integer","format":"uint64","default":15000,"minimum":0},"hmac_secret":{"description":"Optional HMAC signing secret.","type":["string","null"],"default":null},"listen_addr":{"description":"Listen address for node daemon.","type":"string","default":"127.0.0.1:8787"},"max_concurrent_tasks":{"description":"Maximum number of concurrent async command tasks.","type":"integer","format":"uint","default":8,"minimum":0},"max_output_bytes":{"description":"Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.","type":"integer","format":"uint","default":1048576,"minimum":0},"sandbox_root":{"description":"Sandbox root directory for read/write/cwd constraints.","type":"string","default":"."},"task_result_ttl_ms":{"description":"TTL for completed task results in milliseconds.","type":"integer","format":"uint64","default":3600000,"minimum":0},"tls_cert":{"description":"TLS certificate path (PEM).","type":["string","null"],"default":null},"tls_key":{"description":"TLS private key path (PEM).","type":["string","null"],"default":null},"tls_required":{"description":"Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.","type":"boolean","default":true}}},"NodesConfig":{"description":"Remote node proxy configuration for core-side RPC calls and node daemon defaults.","type":"object","properties":{"nodes":{"description":"Configured remote nodes.","type":"array","default":[],"items":{"$ref":"#/$defs/RemoteNodeConfig"}},"request_timeout_ms":{"description":"Default request timeout for node RPC calls.","type":"integer","format":"uint64","default":15000,"minimum":0},"retry_max":{"description":"Default max retries for node RPC calls.","type":"integer","format":"uint8","default":2,"maximum":255,"minimum":0},"server":{"description":"Embedded node server defaults used by `prx-node`.","$ref":"#/$defs/NodeServerConfig","default":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}}},"ObservabilityConfig":{"description":"Observability backend configuration (`[observability]` section).","type":"object","properties":{"backend":{"description":"\"none\" | \"log\" | \"prometheus\" | \"otel\"","type":"string","default":"none"},"otel_endpoint":{"description":"OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".","type":["string","null"],"default":null},"otel_service_name":{"description":"Service name reported to the OTel collector. Defaults to \"prx\".","type":["string","null"],"default":null}}},"OllamaProviderConfig":{"description":"Ollama-specific request options (`[providers.ollama]`).","type":"object","properties":{"num_ctx":{"description":"Explicit context window sent as Ollama `options.num_ctx`.","type":["integer","null"],"format":"uint","default":null,"minimum":0}}},"OsPagingConfig":{"description":"Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.","type":"object","properties":{"eviction_threshold":{"description":"Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.","type":"number","format":"double","default":0.7},"keep_recent_messages":{"description":"Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).","type":"integer","format":"uint","default":12,"minimum":0},"max_recalled_pages":{"description":"Maximum number of evicted pages (document chunks) recalled per turn.","type":"integer","format":"uint","default":10,"minimum":0},"proactive_retrieval":{"description":"Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.","type":"boolean","default":true},"retrieval_injection_role":{"description":"Role under which recalled pages are injected.","$ref":"#/$defs/RetrievalInjectionRole","default":"system"}}},"PluginsConfig":{"description":"WASM plugin runtime configuration.","type":"object","properties":{"enabled":{"description":"Load WASM plugins from `/plugins`. Default: `false`.","type":"boolean","default":false}},"additionalProperties":false},"ProviderModelConfig":{"description":"One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.","type":"object","properties":{"context_window":{"description":"The model's context window in tokens.","type":["integer","null"],"format":"uint32","minimum":0},"model":{"description":"The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.","type":["string","null"]},"native_tools":{"description":"Whether the model accepts native tool calls.","type":["boolean","null"]},"operations":{"description":"The complete list of operations the model executes; every operation not\nlisted is unsupported.","type":["array","null"],"items":{"$ref":"#/$defs/ModelOperationSetting"}},"provider":{"description":"The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.","type":"string"},"streaming":{"description":"Whether the model streams responses.","type":["boolean","null"]},"structured_output":{"description":"Whether the model honours a JSON-schema response format.","type":["boolean","null"]},"tool_call_dialect":{"description":"The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema_dialect":{"description":"The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]},"vision_input":{"description":"Whether the model accepts image input.","type":["boolean","null"]}},"required":["provider"]},"ProviderToolDialectConfig":{"description":"One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.","type":"object","properties":{"model":{"description":"The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.","type":["string","null"]},"provider":{"description":"The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.","type":"string"},"tool_call":{"description":"The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema":{"description":"The tool-schema dialect the endpoint accepts.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]}},"required":["provider"]},"ProvidersConfig":{"description":"Provider-specific runtime configuration (`[providers]`).","type":"object","properties":{"models":{"description":"Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.","type":"array","items":{"$ref":"#/$defs/ProviderModelConfig"}},"ollama":{"description":"Ollama-specific request options (`[providers.ollama]`).","$ref":"#/$defs/OllamaProviderConfig","default":{"num_ctx":null}},"tool_dialects":{"description":"Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).","type":"array","items":{"$ref":"#/$defs/ProviderToolDialectConfig"}}}},"ProxyConfig":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).","type":"object","properties":{"all_proxy":{"description":"Fallback proxy URL for all schemes.","type":["string","null"],"default":null},"http_proxy":{"description":"Proxy URL for HTTP requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"https_proxy":{"description":"Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"no_proxy":{"description":"No-proxy bypass list. Same format as NO_PROXY.","type":"array","default":[],"items":{"type":"string"}},"scope":{"description":"Proxy application scope.","$ref":"#/$defs/ProxyScope","default":"prx"},"services":{"description":"Service selectors used when scope = \"services\".","type":"array","default":[],"items":{"type":"string"}}}},"ProxyScope":{"description":"Proxy application scope — determines which outbound traffic uses the proxy.","oneOf":[{"description":"Use system environment proxy variables only.","type":"string","const":"environment"},{"description":"Apply proxy to all OpenPRX-managed HTTP traffic (default).","type":"string","const":"prx"},{"description":"Apply proxy only to explicitly listed service selectors.","type":"string","const":"services"}]},"QQConfig":{"description":"QQ Official Bot configuration (Tencent QQ Bot SDK)","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs. Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from QQ Bot developer console","type":"string"},"app_secret":{"description":"App Secret from QQ Bot developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["app_id","app_secret"]},"QueryClassificationConfig":{"description":"Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.","type":"object","properties":{"rules":{"description":"Classification rules evaluated in priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/ClassificationRule"}}}},"RamfluxAccountConfig":{"description":"Persona for one ramflux AI account. Missing fields fall back to the global agent.","type":"object","properties":{"cross_conversation_retrieval":{"description":"Cross-conversation memory retrieval. Off unless the owner sets it.","type":"boolean","default":false},"model":{"type":["string","null"],"default":null},"provider":{"type":["string","null"],"default":null},"scope_profile":{"type":["string","null"],"default":null},"system_prompt_file":{"description":"Path to a system-prompt file. Relative paths are resolved from the workspace.","type":["string","null"],"default":null}},"additionalProperties":false},"RamfluxAttachmentFetch":{"description":"Per-turn caps for `attachment.fetch`.","type":"object","properties":{"max_bytes":{"type":"integer","format":"uint64","default":5242880,"minimum":0},"max_per_turn":{"type":"integer","format":"uint8","default":4,"maximum":255,"minimum":0}},"additionalProperties":false},"RamfluxAuthorizationMode":{"description":"How prx combines its own setting with `bridge.hello.authorization`.","oneOf":[{"description":"Use the agent-host value. Until hello arrives, the effective mode is supervised.","type":"string","const":"follow_rf"},{"description":"Always supervised, even when the agent-host declares full.","type":"string","const":"supervised"},{"description":"Full only when the agent-host also declares full. Config alone never yields full.","type":"string","const":"full"}]},"RamfluxConfig":{"description":"Local ramflux agent-host bridge (`[channels_config.ramflux]`).","type":"object","properties":{"accounts":{"type":"object","additionalProperties":{"$ref":"#/$defs/RamfluxAccountConfig"},"default":{}},"allowed_block_types":{"type":"array","default":["Text","Markdown","Heading","KeyValue","Metric","List","TableFallback","Form","Input","Select","Progress","LogStream","Warning","Error","Success","Approval","ActionGroup","FilePreview","Fallback"],"items":{"type":"string"}},"attachment_fetch":{"$ref":"#/$defs/RamfluxAttachmentFetch","default":{"max_bytes":5242880,"max_per_turn":4}},"authorization_mode":{"$ref":"#/$defs/RamfluxAuthorizationMode","default":"follow_rf"},"encrypt_at_rest":{"type":"boolean","default":true},"max_in_flight_per_conversation":{"type":"integer","format":"uint8","default":1,"maximum":255,"minimum":0},"on_new_message":{"$ref":"#/$defs/RamfluxOnNewMessage","default":"queue"},"socket_path":{"description":"Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.","type":["string","null"],"default":null},"surface_limits":{"$ref":"#/$defs/RamfluxSurfaceLimits","default":{"max_actions":16,"max_blocks":32,"max_bytes":65536}},"turn_wall_clock_secs":{"description":"Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.","type":"integer","format":"uint64","default":120,"minimum":0}},"additionalProperties":false},"RamfluxOnNewMessage":{"description":"What to do with a new inbound message while a turn for that conversation is running.","type":"string","enum":["queue","interrupt"]},"RamfluxSurfaceLimits":{"description":"Limits for `reply.surface` blocks and actions.","type":"object","properties":{"max_actions":{"type":"integer","format":"uint32","default":16,"minimum":0},"max_blocks":{"type":"integer","format":"uint32","default":32,"minimum":0},"max_bytes":{"type":"integer","format":"uint32","default":65536,"minimum":0}},"additionalProperties":false},"ReliabilityCircuitBreakerConfig":{"description":"Process-local provider circuit policy (`[reliability.circuit_breaker]`).","type":"object","properties":{"enabled":{"description":"Enable protection for factory-built provider chains.","type":"boolean","default":true},"failure_threshold":{"description":"Consecutive transient failures that open a circuit (at least 1).","type":"integer","format":"uint32","default":5,"minimum":0},"max_open_secs":{"description":"Maximum doubled window, between open_secs and 3600 seconds.","type":"integer","format":"uint64","default":300,"minimum":0},"open_secs":{"description":"Initial open window in seconds (at least 1).","type":"integer","format":"uint64","default":30,"minimum":0}}},"ReliabilityConfig":{"description":"Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.","type":"object","properties":{"acknowledge_single_provider_risk":{"description":"Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.","type":"boolean","default":false},"api_keys":{"description":"Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.","type":"array","default":[],"items":{"type":"string"}},"channel_initial_backoff_secs":{"description":"Initial backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":2,"minimum":0},"channel_max_backoff_secs":{"description":"Max backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":60,"minimum":0},"circuit_breaker":{"description":"Per-provider consecutive failure protection.","$ref":"#/$defs/ReliabilityCircuitBreakerConfig","default":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30}},"fallback_providers":{"description":"Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).","type":"array","default":[],"items":{"type":"string"}},"model_fallbacks":{"description":"Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`","type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"default":{}},"provider_backoff_ms":{"description":"Base backoff (ms) for provider retry delay.","type":"integer","format":"uint64","default":500,"minimum":0},"provider_retries":{"description":"Retries per provider before failing over.","type":"integer","format":"uint32","default":2,"minimum":0},"scheduler_poll_secs":{"description":"Scheduler polling cadence in seconds.","type":"integer","format":"uint64","default":15,"minimum":0},"scheduler_retries":{"description":"Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.","type":"integer","format":"uint32","default":2,"minimum":0}}},"RemoteNodeConfig":{"description":"A remote node target for core-side node proxy calls.","type":"object","properties":{"bearer_token":{"description":"Bearer token for node RPC authentication.","type":"string"},"endpoint":{"description":"Base endpoint (e.g. \"http://127.0.0.1:8787\").","type":"string"},"hmac_secret":{"description":"Optional request signing key (HMAC-SHA256).","type":["string","null"],"default":null},"id":{"description":"Stable node ID used by the nodes tool.","type":"string"},"retry_max":{"description":"Optional per-node retry override.","type":["integer","null"],"format":"uint8","default":null,"maximum":255,"minimum":0},"timeout_ms":{"description":"Optional per-node timeout override.","type":["integer","null"],"format":"uint64","default":null,"minimum":0}},"required":["id","endpoint","bearer_token"]},"RetrievalInjectionRole":{"description":"Where recalled context pages are injected back into the request.","oneOf":[{"description":"Inject recalled pages as a leading `system` message (not user-visible).","type":"string","const":"system"},{"description":"Inject recalled pages as a leading `user` message.","type":"string","const":"user"}]},"RouterConfig":{"description":"Heuristic LLM router configuration (`[router]` section).","type":"object","properties":{"alpha":{"description":"Similarity score weight. Phase 1 keeps this at `0.0`.","type":"number","format":"float","default":0.0},"beta":{"description":"Capability score weight.","type":"number","format":"float","default":0.5},"delta":{"description":"Cost penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"epsilon":{"description":"Latency penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"gamma":{"description":"Elo score weight.","type":"number","format":"float","default":0.30000001192092896},"knn_k":{"description":"Number of nearest neighbors considered for voting. Default: `7`.","type":"integer","format":"uint","default":7,"minimum":0},"knn_min_records":{"description":"Minimum history records before KNN affects routing. Default: `10`.","type":"integer","format":"uint","default":10,"minimum":0},"models":{"description":"Candidate model registry.","type":"array","default":[],"items":{"$ref":"#/$defs/RouterModelConfig"}}}},"RouterModelConfig":{"description":"Static router metadata for one model candidate.","type":"object","properties":{"categories":{"description":"Capability categories such as `conversation`, `code`, or `analysis`.","type":"array","default":[],"items":{"type":"string"}},"cost_per_million_tokens":{"description":"USD cost per million tokens.","type":"number","format":"float","default":0.0},"elo_rating":{"description":"Initial Elo rating.","type":"number","format":"float","default":1000.0},"latency_ms":{"description":"Average latency in milliseconds.","type":"integer","format":"uint32","default":2000,"minimum":0},"max_context":{"description":"Maximum context window in tokens.","type":"integer","format":"uint","default":1000000,"minimum":0},"model_id":{"description":"Model identifier without provider prefix.","type":"string"},"provider":{"description":"Provider identifier.","type":"string"},"reserved_output_tokens":{"description":"Output tokens reserved for this model when planning input context.","type":["integer","null"],"format":"uint","minimum":0}},"required":["model_id","provider"]},"RuntimeConfig":{"description":"Runtime adapter configuration (`[runtime]` section).","type":"object","properties":{"codex_reasoning_effort":{"description":"Codex reasoning effort","type":["string","null"],"default":null},"codex_stream_idle_timeout_secs":{"description":"Codex stream idle timeout in seconds","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"docker":{"description":"Docker runtime settings (used when `kind = \"docker\"`).","$ref":"#/$defs/DockerRuntimeConfig","default":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true}},"idle_hang_secs":{"description":"Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"kind":{"description":"Runtime kind (`native` | `docker`).","type":"string","default":"native"},"long_task_warn_secs":{"description":"Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"managed_cgroup_root":{"description":"Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.","type":["string","null"],"default":null},"max_blocking_threads":{"description":"Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"reasoning_enabled":{"description":"Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported","type":["boolean","null"],"default":null},"shell_env_allowlist":{"description":"Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.","type":"array","default":[],"items":{"type":"string"}},"workdir":{"description":"Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.","type":["string","null"],"default":null}}},"SchedulerConfig":{"description":"Scheduler configuration for periodic task execution (`[scheduler]` section).","type":"object","properties":{"claim_lease_secs":{"description":"Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.","type":"integer","format":"uint64","default":90,"minimum":0},"max_tasks":{"description":"Maximum number of persisted scheduled tasks.","type":"integer","format":"uint","default":64,"minimum":0}}},"ScopeConfig":{"description":"Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```","type":"object","properties":{"assign_owners":{"description":"Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.","type":"array","default":[],"items":{"type":"string"}},"default":{"description":"Default action when no rule matches: \"allow\" (default) or \"deny\".","$ref":"#/$defs/ScopeDefault","default":"allow"},"rules":{"description":"Ordered list of scope rules evaluated top-to-bottom.","type":"array","default":[],"items":{"$ref":"#/$defs/ScopeRule"}}}},"ScopeDefault":{"description":"What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.","oneOf":[{"description":"Unmatched tool calls are allowed (the default).","type":"string","const":"allow"},{"description":"Unmatched tool calls are refused.","type":"string","const":"deny"}]},"ScopeRule":{"description":"A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.","type":"object","properties":{"assign_allow":{"description":"Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".","type":"array","default":[],"items":{"type":"string"}},"assign_deny":{"description":"Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.","type":"array","default":[],"items":{"type":"string"}},"channel":{"description":"Match by channel name: \"signal\", \"telegram\", \"discord\", etc.","type":["string","null"]},"chat_type":{"description":"Match by chat type: \"direct\", \"group\", or \"*\" for any type.","type":["string","null"]},"send_allow":{"description":"Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.","type":"array","default":[],"items":{"type":"string"}},"send_deny":{"description":"Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.","type":"array","default":[],"items":{"type":"string"}},"tools_allow":{"description":"Tool whitelist: only these tools are allowed (empty = all tools permitted).","type":"array","default":[],"items":{"type":"string"}},"tools_deny":{"description":"Tool blacklist: these tools are denied regardless of allow list.","type":"array","default":[],"items":{"type":"string"}},"user":{"description":"Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.","type":["string","null"]}}},"SecretsConfig":{"description":"Secrets encryption configuration (`[secrets]` section).","type":"object","properties":{"encrypt":{"description":"Enable encryption for API keys and tokens in config.toml","type":"boolean","default":true}}},"SecurityConfig":{"description":"Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.","type":"object","properties":{"audit":{"description":"Audit logging configuration","$ref":"#/$defs/AuditConfig","default":{"log_path":"audit.log","max_size_mb":100}},"workspace_hooks":{"description":"Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.","$ref":"#/$defs/WorkspaceHooks"}}},"SelfSystemConfig":{"description":"Self-system experimental automation config (`[self_system]`).","type":"object","properties":{"evolution_config_path":{"description":"Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG)","type":["string","null"],"default":null},"evolution_debug_raw":{"description":"Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW)","type":"boolean","default":false},"evolution_interval_hours":{"description":"Evolution scheduler interval in hours (daemon mode).","type":"integer","format":"uint32","default":24,"minimum":0},"evolution_judge_timeout_secs":{"description":"Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.","type":"integer","format":"uint64","default":180,"minimum":0},"evolution_model_max_micro_usd":{"description":"Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.","type":"integer","format":"uint64","default":0,"minimum":0},"evolution_model_max_tokens":{"description":"Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.","type":"integer","format":"uint64","default":16384,"minimum":0},"fitness":{"description":"Daily fitness snapshot policy.","$ref":"#/$defs/FitnessConfig","default":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"}},"fitness_interval_hours":{"description":"Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.","type":"integer","format":"uint64","default":24,"minimum":0}}},"SessionsSpawnConfig":{"description":"Sessions spawn configuration (`[sessions_spawn]` section).","type":"object","properties":{"cleanup_on_complete":{"description":"Remove worker workspace directory after process-mode completion.","type":"boolean","default":true},"default_mode":{"description":"Default execution mode for sessions_spawn (`task` or `process`).","type":"string","default":"task"},"process_memory_strategy":{"description":"Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.","type":"string","default":"shared_fabric"},"worker_workspace_root":{"description":"Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.","type":["string","null"],"default":null}}},"SignalConfig":{"type":"object","properties":{"account":{"description":"E.164 phone number of the signal-cli account (e.g. \"+1234567890\").","type":"string"},"allowed_from":{"description":"Allowed sender phone numbers (E.164) or \"*\" for all.","type":"array","default":[],"items":{"type":"string"}},"cli_path":{"description":"Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).","type":["string","null"],"default":null},"daemon_http_port":{"description":"Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"daemon_mode":{"description":"Deprecated: ignored. Accepted for backward compatibility with older config files.","type":["boolean","null"],"default":null},"data_dir":{"description":"signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_id":{"description":"Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group","type":["string","null"],"default":null},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"http_url":{"description":"Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.","type":"string","default":"http://localhost:8080"},"ignore_attachments":{"description":"Skip messages that are attachment-only (no text body).","type":"boolean","default":false},"ignore_stories":{"description":"Skip incoming story messages.","type":"boolean","default":false},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"mode":{"description":"Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.","type":["string","null"],"default":null},"startup_timeout_ms":{"description":"Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.","type":"integer","format":"uint64","default":30000,"minimum":0},"storm_protection":{"description":"Signal ingress storm protection controls.","$ref":"#/$defs/SignalStormProtectionConfig","default":{"abnormal_threshold":10,"abnormal_window_secs":60,"breaker_duration_secs":300,"dedupe_ttl_secs":60,"min_reply_interval_secs":2}}},"required":["account"]},"SignalStormProtectionConfig":{"type":"object","properties":{"abnormal_threshold":{"description":"Non-user event threshold within `abnormal_window_secs` before tripping the breaker.","type":"integer","format":"uint","default":10,"minimum":0},"abnormal_window_secs":{"description":"Sliding window in seconds for non-user event counting.","type":"integer","format":"uint64","default":60,"minimum":0},"breaker_duration_secs":{"description":"Circuit breaker duration in seconds after threshold is reached.","type":"integer","format":"uint64","default":300,"minimum":0},"dedupe_ttl_secs":{"description":"Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.","type":"integer","format":"uint64","default":60,"minimum":0},"min_reply_interval_secs":{"description":"Minimum interval in seconds between replies for the same `(channel + reply_target)`.","type":"integer","format":"uint64","default":2,"minimum":0}}},"SkillRagConfig":{"description":"Dynamic skill retrieval configuration (`[skill_rag]` section).","type":"object","properties":{"top_k":{"description":"How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).","type":"integer","format":"uint","default":32,"minimum":0}}},"SkillSuiteRegistration":{"description":"The frozen suite that governs one skill's proposals.","type":"object","properties":{"skill_id":{"description":"The skill the suite governs.","type":"string"},"suite_digest":{"description":"SHA-256 digest (64 lowercase hex digits) of the frozen suite.","type":"string"}},"additionalProperties":false,"required":["skill_id","suite_digest"]},"SkillsConfig":{"description":"Skills loading configuration (`[skills]` section).","type":"object","properties":{"open_skills_dir":{"description":"Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.","type":["string","null"],"default":null},"openclaw_skills_dir":{"description":"Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.","type":["string","null"],"default":null}}},"SkillsLifecycleConfig":{"description":"`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.","type":"object","properties":{"allow_executable_proposals":{"description":"Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.","type":"boolean","default":false},"enabled":{"description":"Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.","type":"boolean","default":false},"max_concurrent_evaluations":{"description":"Most evaluations running at once.","type":"integer","format":"uint32","default":1,"minimum":0},"max_edit_fraction":{"description":"Edit budget of a proposal as a fraction of the skill body, in (0, 1].","type":"number","format":"double","default":0.2},"max_edit_tokens":{"description":"Edit budget of a proposal, in tokens.","type":"integer","format":"uint64","default":300,"minimum":0},"max_proposals_per_cycle":{"description":"Most proposals one cycle may start.","type":"integer","format":"uint32","default":1,"minimum":0},"min_cases_floor":{"description":"Smallest `min_cases` a governing suite may declare. Below 3 is refused.","type":"integer","format":"uint32","default":3,"minimum":0},"mode":{"description":"`draft_only`, `shadow` or `auto`.","$ref":"#/$defs/SkillsLifecycleModeConfig","default":"draft_only"},"owner_scope":{"description":"The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.","type":["string","null"],"default":null},"require_holdout":{"description":"A governing suite must have a holdout split. `false` is refused.","type":"boolean","default":true},"storage_dir":{"description":"Store location under the workspace. Only the default is supported.","type":"string","default":"self/skill-lifecycle"},"suites":{"description":"The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.","type":"array","default":[],"items":{"$ref":"#/$defs/SkillSuiteRegistration"}}},"additionalProperties":false},"SkillsLifecycleModeConfig":{"description":"What the lifecycle may do. Mirrors `LifecycleMode`.","oneOf":[{"description":"Drafts and reviews only.","type":"string","const":"draft_only"},{"description":"Drafts plus evaluation and gating; never publishes.","type":"string","const":"shadow"},{"description":"Publishes an eligible proposal after every gate.","type":"string","const":"auto"}]},"SlackConfig":{"description":"Slack bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Slack user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Slack app-level token for Socket Mode (xapp-...).","type":["string","null"]},"bot_token":{"description":"Slack bot OAuth token (xoxb-...).","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["bot_token"]},"SmartGroupConfig":{"description":"Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).","type":"object","properties":{"classifier_max_context_messages":{"description":"How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.","type":"integer","format":"uint","default":3,"minimum":0},"classifier_model":{"description":"Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.","type":"string","default":""},"classifier_provider":{"description":"Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.","type":"string","default":""},"classifier_temperature":{"description":"Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).","type":"number","format":"double","default":0.0},"classifier_timeout_secs":{"description":"Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.","type":"integer","format":"uint64","default":5,"minimum":0}}},"StorageConfig":{"description":"Persistent storage configuration (`[storage]` section).","type":"object","properties":{"provider":{"description":"Storage provider settings (e.g. sqlite, postgres).","$ref":"#/$defs/StorageProviderSection","default":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}}},"StorageProviderConfig":{"description":"Storage provider backend configuration (e.g. postgres connection details).","type":"object","properties":{"connect_timeout_secs":{"description":"Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"db_url":{"description":"Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.","type":["string","null"],"default":null},"pool_max_size":{"description":"Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.","type":"integer","format":"uint","default":32,"minimum":0},"provider":{"description":"Storage engine key (e.g. \"postgres\", \"sqlite\").","type":"string","default":""},"schema":{"description":"Database schema for SQL backends.","type":"string","default":"public"},"table":{"description":"Table name for memory entries.","type":"string","default":"memories"}}},"StorageProviderSection":{"description":"Wrapper for the storage provider configuration section.","type":"object","properties":{"config":{"description":"Storage provider backend settings.","$ref":"#/$defs/StorageProviderConfig","default":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"StreamMode":{"description":"Streaming mode for channels that support progressive message updates.","oneOf":[{"description":"No streaming -- send the complete response as a single message (default).","type":"string","const":"off"},{"description":"Update a draft message with every flush interval.","type":"string","const":"partial"}]},"TailscaleTunnelConfig":{"type":"object","properties":{"funnel":{"description":"Use Tailscale Funnel (public internet) vs Serve (tailnet only)","type":"boolean","default":false},"hostname":{"description":"Optional hostname override","type":["string","null"]}}},"TaskRoutingConfig":{"description":"Lightweight pre-LLM task routing.","type":"object","properties":{"default_intent":{"description":"Fallback intent when no rule matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"rules":{"description":"Rules evaluated in descending priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/TaskRoutingRule"}}}},"TaskRoutingIntentConfig":{"description":"Task-routing default and rule intent.","type":"string","enum":["simple","delegate","stream"]},"TaskRoutingRule":{"description":"A single task-routing rule.","type":"object","properties":{"intent":{"description":"Route intent to apply when a keyword matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"model_hint":{"description":"Optional model hint/raw model for non-delegated requests.","type":["string","null"],"default":null},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0},"sub_agent_model":{"description":"Optional raw sub-agent model override for delegated tasks.","type":["string","null"],"default":null}}},"TelegramConfig":{"description":"Telegram bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Telegram user IDs or usernames. Empty = deny all.","type":"array","items":{"type":"string"}},"bot_token":{"description":"Telegram Bot API token (from @BotFather).","type":"string"},"draft_update_interval_ms":{"description":"Minimum interval (ms) between draft message edits to avoid rate limits.","type":"integer","format":"uint64","default":1000,"minimum":0},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"interrupt_on_new_message":{"description":"When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.","type":"boolean","default":false},"stream_mode":{"description":"Streaming mode for progressive response delivery via message edits.","$ref":"#/$defs/StreamMode","default":"off"}},"required":["bot_token","allowed_users"]},"ToolCallDialectSetting":{"description":"The tool-call grammars an operator may declare for an endpoint.","oneOf":[{"description":"Only the native `tool_calls` array is a tool call (the default).","type":"string","const":"native"},{"description":"Additionally read `{json}` from the content,\nfor a tool name the request registered.","type":"string","const":"xml_function_tags"}]},"ToolSchemaDialectSetting":{"description":"The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.","oneOf":[{"description":"The published document, byte for byte (the default).","type":"string","const":"raw"},{"description":"The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.","type":"string","const":"no_root_combinators"}]},"ToolTieringConfig":{"description":"Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.","type":"object","properties":{"always_exclude":{"description":"Tool names excluded from capability publication.","type":"array","default":[],"items":{"type":"string"}},"always_include":{"description":"Tool names preferred for direct publication, subject to admission gates.","type":"array","default":[],"items":{"type":"string"}},"channel_exclude":{"description":"Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefaults to [`DEFAULT_CHANNEL_EXCLUDED_TOOLS`]; set to `[]` to expose the\nfull operator surface on channels again.","type":"array","default":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","skills_manage","memory_reindex","document_sync","document_ingest"],"items":{"type":"string"}}}},"TunnelConfig":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.","type":"object","properties":{"cloudflare":{"description":"Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).","anyOf":[{"$ref":"#/$defs/CloudflareTunnelConfig"},{"type":"null"}],"default":null},"custom":{"description":"Custom tunnel command configuration (used when `provider = \"custom\"`).","anyOf":[{"$ref":"#/$defs/CustomTunnelConfig"},{"type":"null"}],"default":null},"ngrok":{"description":"ngrok tunnel configuration (used when `provider = \"ngrok\"`).","anyOf":[{"$ref":"#/$defs/NgrokTunnelConfig"},{"type":"null"}],"default":null},"provider":{"description":"Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.","type":"string","default":"none"},"tailscale":{"description":"Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).","anyOf":[{"$ref":"#/$defs/TailscaleTunnelConfig"},{"type":"null"}],"default":null}}},"UserPolicyConfig":{"description":"Startup user policy entry (`[[user_policies]]`).","type":"object","properties":{"blocked_patterns":{"type":"array","default":[],"items":{"type":"string"}},"projects":{"type":"array","default":[],"items":{"type":"string"}},"role":{"type":"string","default":"guest"},"user_id":{"type":"string"},"visibility_ceiling":{"type":"string","default":"private"}},"required":["user_id"]},"WacliConfig":{"description":"wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```","type":"object","properties":{"allow_unsigned_loopback":{"description":"Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).","type":"boolean","default":false},"allowed_from":{"description":"Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.","type":"array","default":["*"],"items":{"type":"string"}},"bot_jid":{"description":"Bot's own JID, used for reply-to-bot mention detection.","type":["string","null"],"default":null},"bot_lid":{"description":"The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.","type":["string","null"],"default":null},"bot_number":{"description":"Bot's own phone number (digits), used for `@` mention detection.","type":["string","null"],"default":null},"cli_path":{"description":"Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.","type":["string","null"],"default":null},"group_reply_mode":{"description":"Smart group-reply mode. When `None`, derived from `mention_only`.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"host":{"description":"REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].","type":["string","null"],"writeOnly":true},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"outbound_media_workspace_only":{"description":"Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.","type":"boolean","default":false},"port":{"description":"REMOVED: legacy JSON-RPC daemon port. See `host`.","type":["integer","null"],"format":"uint16","maximum":65535,"minimum":0,"writeOnly":true},"self_chat_mode":{"description":"Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.","type":"boolean","default":false},"store_dir":{"description":"wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.","type":["string","null"],"default":null},"webhook_listen":{"description":"Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").","type":"string","default":"127.0.0.1:16868"},"webhook_path":{"description":"HTTP path the webhook server serves (default: \"/wacli\").","type":"string","default":"/wacli"},"webhook_secret":{"description":"HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.","type":["string","null"],"default":null}}},"WebSearchConfig":{"description":"Web search tool configuration (`[web_search]` section).","type":"object","properties":{"brave_api_key":{"description":"Brave Search API key (required if provider is \"brave\")","type":["string","null"],"default":null},"fetch_max_chars":{"description":"Maximum characters returned by `web_fetch` (default 10000)","type":"integer","format":"uint","default":50000,"minimum":0},"max_results":{"description":"Maximum results per search (1-20)","type":"integer","format":"uint","default":15,"minimum":0},"provider":{"description":"Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)","type":"string","default":"duckduckgo"},"timeout_secs":{"description":"Request timeout in seconds","type":"integer","format":"uint64","default":15,"minimum":0}}},"WebhookConfig":{"description":"Webhook channel configuration.","type":"object","properties":{"port":{"description":"Port to listen on for incoming webhooks.","type":"integer","format":"uint16","maximum":65535,"minimum":0},"secret":{"description":"Optional shared secret for webhook signature verification.","type":["string","null"]}},"required":["port"]},"WhatsAppConfig":{"description":"WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.","type":"object","properties":{"access_token":{"description":"Access token from Meta Business Suite (Cloud API mode)","type":["string","null"],"default":null},"allowed_numbers":{"description":"Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"app_secret":{"description":"App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"pair_code":{"description":"Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one","type":["string","null"],"default":null},"pair_phone":{"description":"Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used","type":["string","null"],"default":null},"phone_number_id":{"description":"Phone number ID from Meta Business API (Cloud API mode)","type":["string","null"],"default":null},"read_pool_size":{"description":"Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"session_path":{"description":"Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs","type":["string","null"],"default":null},"verify_token":{"description":"Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode","type":["string","null"],"default":null},"ws_url":{"description":"WebSocket URL override (replaces WHATSAPP_WS_URL)","type":["string","null"],"default":null}}},"WorkspaceHooks":{"description":"Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).","oneOf":[{"description":"They do not run (the default); `prx doctor` and `hooks_status` say so.","type":"string","const":"off"},{"description":"They run, in a cleared environment and a dedicated directory beside\n`config.toml`.","type":"string","const":"on"}]},"WorkspaceMcpServers":{"description":"Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).","oneOf":[{"description":"None: a workspace file may only narrow the servers defined in\n`config.toml`.","type":"string","const":"off"},{"description":"HTTP servers (still refused when they target a private address).","type":"string","const":"http_only"},{"description":"HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.","type":"string","const":"stdio"}]},"XinConfig":{"description":"Configuration for the xin autonomous task engine (`[xin]`).","type":"object","properties":{"adopt_legacy_tasks":{"description":"Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).","type":"boolean","default":false},"interval_minutes":{"description":"Tick interval in minutes (minimum 1). Default: 5.","type":"integer","format":"uint32","default":5,"minimum":0},"stale_timeout_minutes":{"description":"Minutes after which a running task is marked stale. Default: 60.","type":"integer","format":"uint32","default":60,"minimum":0}}},"AgentMessaging":{"description":"Owner-controlled inbound session messaging (enabled unless explicitly off).","type":"object","properties":{"inbound":{"type":"boolean","default":true}}}}} +{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Config","description":"Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).","type":"object","properties":{"a2a":{"description":"Agent-to-Agent compatibility configuration (`[a2a]`).","$ref":"#/$defs/A2aConfig","default":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trusted_trust_domains":[],"trust_domain":"prx.local"}},"agent":{"description":"Agent orchestration settings (`[agent]`).","$ref":"#/$defs/AgentConfig","default":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2,"messaging":{"inbound":true}}},"agents":{"description":"Delegate agent configurations for multi-agent workflows.","type":"object","additionalProperties":{"$ref":"#/$defs/DelegateAgentConfig"},"default":{}},"api_key":{"description":"API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.","type":["string","null"],"default":null},"api_url":{"description":"Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)","type":["string","null"],"default":null},"auth":{"description":"Auth profile and external credential import settings (`[auth]`).","$ref":"#/$defs/AuthConfig","default":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"}},"autonomy":{"description":"Autonomy and security policy configuration (`[autonomy]`).","$ref":"#/$defs/AutonomyConfig","default":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":500,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true}},"browser":{"description":"Browser automation configuration (`[browser]`).","$ref":"#/$defs/BrowserConfig","default":{"allowed_domains":[],"computer_use":{"api_key":null}}},"channels_config":{"description":"Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).","$ref":"#/$defs/ChannelsConfig","default":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null}},"chat":{"description":"Interactive chat UI configuration (`[chat]`).","$ref":"#/$defs/ChatConfig","default":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2}},"compliance":{"description":"Operator-owned compliance controls (`[compliance]`).","$ref":"#/$defs/ComplianceConfig","default":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}},"composio":{"description":"Composio managed OAuth tools integration (`[composio]`).","$ref":"#/$defs/ComposioConfig","default":{"api_key":null,"entity_id":"default"}},"cost":{"description":"Cost tracking and budget enforcement configuration (`[cost]`).","$ref":"#/$defs/CostConfig","default":{"allow_override":false,"daily_limit_usd":10.0,"monthly_limit_usd":100.0,"prices":{},"warn_at_percent":80}},"cron":{"description":"Cron job configuration (`[cron]`).","$ref":"#/$defs/CronConfig","default":{"max_run_history":50}},"decision_engine":{"description":"Optional advisory decision engine, disabled by default.","$ref":"#/$defs/DecisionEngineConfig","default":{"candidates":5,"enabled":false,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"latency_budget_ms":500,"max_candidates":12,"token_ratio_limit":0.3499999940395355}},"default_model":{"description":"Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.","type":["string","null"]},"default_provider":{"description":"Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.","type":["string","null"]},"default_temperature":{"description":"Default model temperature (0.0–2.0). Default: `0.7`.","type":"number","format":"double","default":0.7},"embedding_routes":{"description":"Embedding routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/EmbeddingRouteConfig"}},"gateway":{"description":"Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).","$ref":"#/$defs/GatewayConfig","default":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60}},"heartbeat":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]`).","$ref":"#/$defs/HeartbeatConfig","default":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."}},"http_request":{"description":"HTTP request tool configuration (`[http_request]`).","$ref":"#/$defs/HttpRequestConfig","default":{"max_response_size":1000000,"timeout_secs":30}},"identity":{"description":"Identity format configuration: OpenClaw or AIEOS (`[identity]`).","$ref":"#/$defs/IdentityConfig","default":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"}},"identity_bindings":{"description":"Static identity bindings loaded at startup (`[[identity_bindings]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/IdentityBindingConfig"}},"mcp":{"description":"Secrets encryption configuration (`[secrets]`).","$ref":"#/$defs/McpConfig","default":{"servers":{}}},"mcp_server":{"description":"MCP server compatibility configuration (`[mcp_server]`).","$ref":"#/$defs/McpServerRuntimeConfig","default":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true}},"media":{"description":"Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.","$ref":"#/$defs/MediaConfig","default":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"}},"memory":{"description":"Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).","$ref":"#/$defs/MemoryConfig","default":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7}},"model_routes":{"description":"Model routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/ModelRouteConfig"}},"model_settings":{"description":"Catalog model levels and explicit parameters, keyed by canonical release ID.","type":"object","additionalProperties":{"$ref":"#/$defs/ModelSettings"},"default":{}},"multimodal":{"description":"Multimodal (image) handling configuration (`[multimodal]`).","$ref":"#/$defs/MultimodalConfig","default":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4}},"nodes":{"description":"Remote node proxy configuration (`[nodes]`).","$ref":"#/$defs/NodesConfig","default":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}},"observability":{"description":"Observability backend configuration (`[observability]`).","$ref":"#/$defs/ObservabilityConfig","default":{"backend":"none","otel_endpoint":null,"otel_service_name":null}},"plugins":{"description":"WASM plugin runtime switch (`[plugins]`), off by default.","$ref":"#/$defs/PluginsConfig","default":{"enabled":false}},"providers":{"description":"Provider-specific runtime options (`[providers.]`).","$ref":"#/$defs/ProvidersConfig","default":{"ollama":{"num_ctx":null}}},"proxy":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).","$ref":"#/$defs/ProxyConfig","default":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]}},"query_classification":{"description":"Automatic query classification — maps user messages to model hints.","$ref":"#/$defs/QueryClassificationConfig","default":{"rules":[]}},"reliability":{"description":"Reliability settings: retries, fallback providers, backoff (`[reliability]`).","$ref":"#/$defs/ReliabilityConfig","default":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2}},"router":{"description":"Heuristic LLM router configuration (`[router]`).","$ref":"#/$defs/RouterConfig","default":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]}},"runtime":{"description":"Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.","$ref":"#/$defs/RuntimeConfig","default":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null}},"scheduler":{"description":"Scheduler configuration for periodic task execution (`[scheduler]`).","$ref":"#/$defs/SchedulerConfig","default":{"claim_lease_secs":90,"max_tasks":64}},"secrets":{"$ref":"#/$defs/SecretsConfig","default":{"encrypt":true}},"security":{"description":"Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).","$ref":"#/$defs/SecurityConfig","default":{"audit":{"log_path":"audit.log","max_size_mb":100}}},"self_system":{"description":"Self-system experimental automation controls (`[self_system]`).","$ref":"#/$defs/SelfSystemConfig","default":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24}},"sessions_spawn":{"description":"Session spawning configuration (`[sessions_spawn]`).","$ref":"#/$defs/SessionsSpawnConfig","default":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null}},"skill_rag":{"description":"Dynamic skill retrieval settings (`[skill_rag]`).","$ref":"#/$defs/SkillRagConfig","default":{"top_k":32}},"skills":{"description":"Skills loading and community repository behavior (`[skills]`).","$ref":"#/$defs/SkillsConfig","default":{"open_skills_dir":null,"openclaw_skills_dir":null}},"skills_lifecycle":{"description":"Skill lifecycle (`[skills_lifecycle]`), off by default.","$ref":"#/$defs/SkillsLifecycleConfig","default":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]}},"smart_group":{"description":"Smart group-reply pre-gate configuration (`[smart_group]`).","$ref":"#/$defs/SmartGroupConfig","default":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5}},"storage":{"description":"Persistent storage provider configuration (`[storage]`).","$ref":"#/$defs/StorageConfig","default":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"task_routing":{"description":"Task routing configuration — classifies work by intent before the main agent loop.","$ref":"#/$defs/TaskRoutingConfig","default":{"default_intent":"simple","rules":[]}},"tool_tiering":{"description":"Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).","$ref":"#/$defs/ToolTieringConfig","default":{"always_exclude":[],"always_include":[],"channel_exclude":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","skills_manage","memory_reindex","document_sync","document_ingest"]}},"tunnel":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]`).","$ref":"#/$defs/TunnelConfig","default":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null}},"user_policies":{"description":"Static user policy records loaded at startup (`[[user_policies]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/UserPolicyConfig"}},"web_search":{"description":"Web search tool configuration (`[web_search]`).","$ref":"#/$defs/WebSearchConfig","default":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15}},"webhook":{"description":"Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).","$ref":"#/$defs/MemoryWebhookConfig","default":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null}},"xin":{"description":"Xin autonomous task engine configuration (`[xin]`).","$ref":"#/$defs/XinConfig","default":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}}},"$defs":{"A2aConfig":{"type":"object","properties":{"agent_id":{"description":"Stable PRX agent identifier advertised to peers.","type":"string","default":"prx-default"},"allowed_peer_issuers":{"description":"Accepted external peer issuers.","type":"array","default":[],"items":{"type":"string"}},"bind":{"description":"Advertised bind address.","type":"string","default":"127.0.0.1:16832"},"card_jwks_uri":{"description":"Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.","type":["string","null"],"default":null},"card_signing_key_path":{"description":"On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).","type":["string","null"],"default":null},"card_ttl_seconds":{"description":"Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.","type":"integer","format":"uint64","default":3600,"minimum":0},"discovery_advertised":{"description":"Whether to advertise into an external A2A registry.","type":"boolean","default":false},"handoff_nonce_ttl_seconds":{"description":"Replay window for future handoff delegation tokens.","type":"integer","format":"uint64","default":3600,"minimum":0},"messaging_enabled":{"description":"Enable the dedicated pinned mTLS messaging listener.","type":"boolean","default":false},"peers":{"type":"object","additionalProperties":{"$ref":"#/$defs/A2aPeer"},"default":{}},"spiffe_id":{"description":"Local SPIFFE-style identifier placeholder.","type":"string","default":"spiffe://prx-local/agent/prx-default"},"spiffe_strict_validation":{"description":"When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.","type":"boolean","default":false},"spiffe_trust_bundle_pem":{"description":"Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).","type":["string","null"],"default":null},"trusted_trust_domains":{"description":"Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).","type":"array","default":[],"items":{"type":"string"}},"trust_domain":{"description":"SPIFFE trust domain for new instance identities.","type":"string","default":"prx.local"}}},"A2aPeer":{"description":"Explicit pinned identity and local recipient grant.","type":"object","properties":{"spiffe_id":{"type":"string"},"fingerprints":{"type":"array","items":{"type":"string"}},"address":{"type":"string"},"owner":{"type":"string"},"sessions":{"type":"array","default":["*"],"items":{"type":"string"}},"agents":{"type":"array","default":["*"],"items":{"type":"string"}}},"required":["spiffe_id","fingerprints","address","owner"],"additionalProperties":false},"AgentCompactionConfig":{"description":"Agent context compaction configuration (`[agent.compaction]`).","type":"object","properties":{"keep_recent_messages":{"description":"Number of recent non-system messages to keep after compaction.","type":"integer","format":"uint","default":12,"minimum":0},"max_context_tokens":{"description":"Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.","type":"integer","format":"uint","default":128000,"minimum":0},"memory_flush":{"description":"Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.","type":"boolean","default":true},"mode":{"description":"Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).","$ref":"#/$defs/AgentCompactionMode","default":"switch"},"os_paging":{"description":"Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.","$ref":"#/$defs/OsPagingConfig","default":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"}},"reserve_tokens":{"description":"Tokens reserved for the next model response.","type":"integer","format":"uint","default":4096,"minimum":0}}},"AgentCompactionMode":{"description":"Compaction mode for long conversation contexts.","oneOf":[{"description":"Disable proactive compaction.","type":"string","const":"off"},{"description":"Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.","type":"string","const":"switch"},{"description":"Conservative compaction that prefers summary replacement.","type":"string","const":"safeguard"},{"description":"Aggressive truncation mode for tighter contexts.","type":"string","const":"aggressive"}]},"AgentConfig":{"description":"Agent orchestration configuration (`[agent]` section).","type":"object","properties":{"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"compact_context":{"description":"When true: bootstrap_max_chars=6000. Use for 13B or smaller models.","type":"boolean","default":false},"compaction":{"description":"Context compaction controls (`[agent.compaction]`).","$ref":"#/$defs/AgentCompactionConfig","default":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096}},"low_priority_tools":{"description":"Tool names treated as low-priority when `priority_scheduling_enabled = true`.","type":"array","default":["sessions_spawn","delegate"],"items":{"type":"string"}},"priority_scheduling_enabled":{"description":"Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.","type":"boolean","default":false},"read_only_tool_concurrency_window":{"description":"Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.","type":"integer","format":"uint","default":2,"minimum":0},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}}},"AgentLimits":{"description":"Optional admission limits for rf-started turns of a named agent.","type":"object","properties":{"max_concurrent_turns":{"type":["integer","null"],"format":"uint32","minimum":0},"max_cost_per_day_cents":{"type":["integer","null"],"format":"uint64","minimum":0}},"additionalProperties":false},"AuditConfig":{"description":"Audit logging configuration","type":"object","properties":{"log_path":{"description":"Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).","type":"string","default":"audit.log"},"max_size_mb":{"description":"Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).","type":"integer","format":"uint32","default":100,"minimum":0}}},"AuthConfig":{"description":"Authentication and external credential import configuration (`[auth]` section).","type":"object","properties":{"codex_auth_json_auto_import":{"description":"Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.","type":"boolean","default":false},"codex_auth_json_path":{"description":"Source path for Codex CLI auth.json import.","type":"string","default":"~/.codex/auth.json"}}},"AutonomyConfig":{"type":"object","properties":{"acknowledge_unrestricted_profile":{"description":"Operator acknowledgement for an intentionally unrestricted profile.\nThis suppresses doctor noise only; it does not alter policy behavior.","type":"boolean","default":false},"forbidden_paths":{"description":"Explicit path denylist. Default includes system-critical paths.\n\nFails closed: omitting the key keeps the built-in list rather than\nemptying it, so a partial `[autonomy]` section never removes the\ndenylist.","type":"array","default":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"items":{"type":"string"}},"level":{"description":"Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).","$ref":"#/$defs/AutonomyLevel","default":"full"},"max_cost_per_day_cents":{"description":"Maximum cost per day in cents per policy. Default: `500`.","type":"integer","format":"uint32","default":500,"minimum":0},"scopes":{"description":"Scope-based tool access control: per-user/channel/chat-type allow/deny rules.","$ref":"#/$defs/ScopeConfig","default":{"assign_owners":[],"default":"allow","rules":[]}},"workspace_only":{"description":"Restrict file writes and command paths to the workspace directory. Default: `true`.\n\nFails closed: a `[autonomy]` section that omits this key keeps the\nworkspace restriction on, so a partial section can never widen the\nfilesystem reach by accident.","type":"boolean","default":true}}},"AutonomyLevel":{"description":"How much autonomy the agent has","oneOf":[{"description":"Read-only: can observe but not act","type":"string","const":"readonly"},{"description":"Supervised: acts but requires approval for risky operations","type":"string","const":"supervised"},{"description":"Full: autonomous execution within policy bounds","type":"string","const":"full"}]},"BackendSelection":{"description":"Which decision backend runs: `auto` (the factory's order) or one kind.","type":"string"},"BrowserComputerUseConfig":{"description":"Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.","type":"object","properties":{"api_key":{"description":"Optional bearer token (retained only for config secret handling).","type":["string","null"],"default":null}}},"BrowserConfig":{"description":"Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.","type":"object","properties":{"allowed_domains":{"description":"Allowed domains for `web_fetch` (exact or subdomain match).","type":"array","default":[],"items":{"type":"string"}},"computer_use":{"description":"Computer-use sidecar config (retained only for `api_key` secret handling).","$ref":"#/$defs/BrowserComputerUseConfig","default":{"api_key":null}}}},"ChannelsConfig":{"description":"Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.","type":"object","properties":{"cli":{"description":"Enable the CLI interactive channel. Default: `true`.","type":"boolean","default":true},"dingtalk":{"description":"DingTalk channel configuration.","anyOf":[{"$ref":"#/$defs/DingTalkConfig"},{"type":"null"}]},"discord":{"description":"Discord bot channel configuration.","anyOf":[{"$ref":"#/$defs/DiscordConfig"},{"type":"null"}]},"email":{"description":"Email channel configuration.","anyOf":[{"$ref":"#/$defs/EmailConfig"},{"type":"null"}]},"imessage":{"description":"iMessage channel configuration (macOS only).","anyOf":[{"$ref":"#/$defs/IMessageConfig"},{"type":"null"}]},"irc":{"description":"IRC channel configuration.","anyOf":[{"$ref":"#/$defs/IrcConfig"},{"type":"null"}]},"lark":{"description":"Lark/Feishu channel configuration.","anyOf":[{"$ref":"#/$defs/LarkConfig"},{"type":"null"}]},"linq":{"description":"Linq Partner API channel configuration.","anyOf":[{"$ref":"#/$defs/LinqConfig"},{"type":"null"}]},"mattermost":{"description":"Mattermost bot channel configuration.","anyOf":[{"$ref":"#/$defs/MattermostConfig"},{"type":"null"}]},"nextcloud_talk":{"description":"Nextcloud Talk bot channel configuration.","anyOf":[{"$ref":"#/$defs/NextcloudTalkConfig"},{"type":"null"}]},"qq":{"description":"QQ Official Bot channel configuration.","anyOf":[{"$ref":"#/$defs/QQConfig"},{"type":"null"}]},"ramflux":{"description":"Local ramflux agent-host bridge.","anyOf":[{"$ref":"#/$defs/RamfluxConfig"},{"type":"null"}],"default":null},"signal":{"description":"Signal channel configuration.","anyOf":[{"$ref":"#/$defs/SignalConfig"},{"type":"null"}]},"slack":{"description":"Slack bot channel configuration.","anyOf":[{"$ref":"#/$defs/SlackConfig"},{"type":"null"}]},"telegram":{"description":"Telegram bot channel configuration.","anyOf":[{"$ref":"#/$defs/TelegramConfig"},{"type":"null"}]},"wacli":{"description":"wacli JSON-RPC daemon channel configuration.","anyOf":[{"$ref":"#/$defs/WacliConfig"},{"type":"null"}],"default":null},"webhook":{"description":"Webhook channel configuration.","anyOf":[{"$ref":"#/$defs/WebhookConfig"},{"type":"null"}]},"whatsapp":{"description":"WhatsApp channel configuration (Cloud API or Web mode).","anyOf":[{"$ref":"#/$defs/WhatsAppConfig"},{"type":"null"}]}}},"ChatConfig":{"description":"Interactive chat configuration (`[chat]`).","type":"object","properties":{"daemon":{"description":"How this chat process reaches the daemon it borrows channels from.","$ref":"#/$defs/ChatDaemonConfig","default":{"token":"","url":""}},"max_concurrent_visible_turns":{"description":"Maximum concurrent visible provider turns in the TUI Redux driver.","type":"integer","format":"uint","default":2,"minimum":0}}},"ChatDaemonConfig":{"description":"Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.","type":"object","properties":{"token":{"description":"Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.","type":"string","default":""},"url":{"description":"Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.","type":"string","default":""}}},"CircuitBreakerConfig":{"description":"The per-backend circuit breaker.","type":"object","properties":{"cooldown_secs":{"description":"Seconds the breaker stays open (1 to 3600).","type":"integer","format":"uint32","default":60,"minimum":0},"failure_threshold":{"description":"Consecutive failures before the breaker opens (1 to 100).","type":"integer","format":"uint32","default":5,"minimum":0}}},"ClassificationRule":{"description":"A single classification rule mapping message patterns to a model hint.","type":"object","properties":{"hint":{"description":"Must match a `[[model_routes]]` hint value.","type":"string"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"max_length":{"description":"Only match if message length <= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"min_length":{"description":"Only match if message length >= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"patterns":{"description":"Case-sensitive literal matches (for \"```\", \"fn \", etc.).","type":"array","default":[],"items":{"type":"string"}},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0}},"required":["hint"]},"CloudflareTunnelConfig":{"type":"object","properties":{"token":{"description":"Cloudflare Tunnel token (from Zero Trust dashboard)","type":"string"}},"required":["token"]},"ComplianceConfig":{"type":"object","properties":{"eu_ai_act":{"$ref":"#/$defs/EuAiActComplianceConfig","default":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null}},"interaction_notice":{"$ref":"#/$defs/InteractionNoticeConfig","default":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}}},"ComposioConfig":{"description":"Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.","type":"object","properties":{"api_key":{"description":"Composio API key (stored encrypted when secrets.encrypt = true)","type":["string","null"],"default":null},"entity_id":{"description":"Default entity ID for multi-user setups","type":"string","default":"default"}}},"CostConfig":{"description":"Cost tracking and budget enforcement configuration (`[cost]` section).","type":"object","properties":{"allow_override":{"description":"Allow requests to exceed budget with --override flag (default: false)","type":"boolean","default":false},"daily_limit_usd":{"description":"Daily spending limit in USD (default: 10.00)","type":"number","format":"double","default":10.0},"monthly_limit_usd":{"description":"Monthly spending limit in USD (default: 100.00)","type":"number","format":"double","default":100.0},"prices":{"description":"Per-model pricing (USD per 1M tokens)","type":"object","additionalProperties":{"$ref":"#/$defs/ModelPricing"},"default":{}},"warn_at_percent":{"description":"Warn when spending reaches this percentage of limit (default: 80)","type":"integer","format":"uint8","default":80,"maximum":255,"minimum":0}}},"CredentialRefSetting":{"description":"Which credential a decision backend uses. A reference, never a secret.","type":"string"},"CronConfig":{"description":"Cron job configuration (`[cron]` section).","type":"object","properties":{"max_run_history":{"description":"Maximum number of historical cron run records to retain. Default: `50`.","type":"integer","format":"uint32","default":50,"minimum":0}}},"CustomTunnelConfig":{"type":"object","properties":{"health_url":{"description":"Optional URL to check tunnel health","type":["string","null"]},"start_command":{"description":"Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"","type":"string"},"url_pattern":{"description":"Optional regex to extract public URL from command stdout","type":["string","null"]}},"required":["start_command"]},"DecisionBackendConfig":{"description":"The decision backend (`[decision_engine.backend]`).","type":"object","properties":{"circuit_breaker":{"description":"The circuit breaker.","$ref":"#/$defs/CircuitBreakerConfig","default":{"cooldown_secs":60,"failure_threshold":5}},"credential_ref":{"description":"The credential reference: `\"\"`, `\"none\"` or `cred-`.","$ref":"#/$defs/CredentialRefSetting","default":""},"endpoint":{"description":"The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.","type":"string","default":""},"kind":{"description":"`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).","$ref":"#/$defs/BackendSelection","default":"auto"},"max_request_bytes":{"description":"Largest request body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":65536,"minimum":0},"max_response_bytes":{"description":"Largest response body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":262144,"minimum":0},"model":{"description":"The model the endpoint serves; one exact version for a hosted\nservice.","type":"string","default":""},"pinned_snapshot":{"description":"The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.","type":"string"},"remote_enabled":{"description":"Whether decision state may leave this machine. Default `false`.","type":"boolean","default":false},"timeout_ms":{"description":"Transport timeout (10 ms up to the extra latency budget).","type":"integer","format":"uint32","default":250,"minimum":0}}},"DecisionEngineConfig":{"type":"object","properties":{"backend":{"anyOf":[{"$ref":"#/$defs/DecisionBackendConfig"},{"type":"null"}]},"candidates":{"type":"integer","format":"uint32","default":5,"minimum":0},"enabled":{"type":"boolean","default":false},"mode":{"$ref":"#/$defs/DecisionMode","default":"pre"},"observe_queue":{"type":"integer","format":"uint32","default":64,"minimum":0},"prompt_budget_tokens":{"type":"integer","format":"uint32","default":300,"minimum":0},"telemetry_cap":{"type":"integer","format":"uint32","default":1000,"minimum":0},"timeout_ms":{"type":"integer","format":"uint32","default":1500,"minimum":0},"latency_budget_ms":{"description":"The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.","type":"integer","format":"uint64","default":500,"minimum":0},"token_ratio_limit":{"description":"Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).","type":"number","format":"float","default":0.3499999940395355},"max_candidates":{"description":"The most candidates a turn considers (1 to 32).","type":"integer","format":"uint8","default":12,"maximum":255,"minimum":0}}},"DecisionMode":{"type":"string","enum":["pre","post","both"]},"DeclarationOfConformityConfig":{"type":"object","properties":{"applicable_union_law":{"type":"array","default":[],"items":{"type":"string"}},"artifact_path":{"type":["string","null"],"default":null},"artifact_version":{"type":["string","null"],"default":null},"conformity_assessment_procedure":{"type":["string","null"],"default":null},"conformity_statement":{"type":["string","null"],"default":null},"harmonised_standards":{"type":"array","default":[],"items":{"type":"string"}},"issue_date":{"type":["string","null"],"default":null},"issue_place":{"type":["string","null"],"default":null},"notified_body_certificate":{"type":["string","null"],"default":null},"notified_body_identification_number":{"type":["string","null"],"default":null},"notified_body_name":{"type":["string","null"],"default":null},"personal_data_compliance_statement":{"type":["string","null"],"default":null},"processes_personal_data":{"type":"boolean","default":false},"provider_address":{"type":["string","null"],"default":null},"provider_name":{"type":["string","null"],"default":null},"signer_function":{"type":["string","null"],"default":null},"signer_name":{"type":["string","null"],"default":null},"signer_on_behalf_of":{"type":["string","null"],"default":null},"sole_responsibility_statement":{"type":["string","null"],"default":null},"standards_not_applicable_reason":{"type":["string","null"],"default":null},"system_name":{"type":["string","null"],"default":null},"system_reference":{"type":["string","null"],"default":null},"system_type":{"type":["string","null"],"default":null}}},"DelegateAgentConfig":{"description":"Configuration for a delegate sub-agent used by the `delegate` tool.","type":"object","properties":{"agentic":{"description":"Enable agentic sub-agent mode (multi-turn tool-call loop).","type":"boolean","default":false},"allowed_tools":{"description":"Allowlist of tool names available to the sub-agent in agentic mode.","type":"array","default":[],"items":{"type":"string"}},"api_key":{"description":"Optional API key override","type":["string","null"],"default":null},"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"autonomy":{"description":"The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.","anyOf":[{"$ref":"#/$defs/AutonomyLevel"},{"type":"null"}]},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"enabled":{"description":"Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.","type":"boolean","default":true},"identity_dir":{"description":"Optional identity files directory relative to workspace root.","type":["string","null"],"default":null},"limits":{"$ref":"#/$defs/AgentLimits","default":{"max_concurrent_turns":null,"max_cost_per_day_cents":null}},"max_depth":{"description":"Max recursion depth for nested delegation","type":"integer","format":"uint32","default":8,"minimum":0},"memory_scope":{"description":"Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".","type":["string","null"],"default":null},"model":{"description":"Model name","type":"string"},"provider":{"description":"Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")","type":"string"},"spawn_enabled":{"description":"Whether this agent is allowed to be targeted by sessions_spawn (default: true).","type":["boolean","null"],"default":null},"system_prompt":{"description":"Optional system prompt for the sub-agent","type":["string","null"],"default":null},"temperature":{"description":"Temperature override","type":["number","null"],"format":"double","default":null},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}},"required":["provider","model"]},"DingTalkConfig":{"description":"DingTalk configuration for Stream Mode messaging","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"client_id":{"description":"Client ID (AppKey) from DingTalk developer console","type":"string"},"client_secret":{"description":"Client Secret (AppSecret) from DingTalk developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["client_id","client_secret"]},"DiscordConfig":{"description":"Discord bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Discord user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Discord bot token (from Discord Developer Portal).","type":"string"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"guild_id":{"description":"Optional guild (server) ID to restrict the bot to a single guild.","type":["string","null"]},"listen_to_bots":{"description":"When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.","type":"boolean","default":false}},"required":["bot_token"]},"DmPolicy":{"description":"Policy for direct-message handling.","oneOf":[{"description":"Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).","type":"string","const":"pairing"},{"description":"Accept only senders listed in `allowed_from`.","type":"string","const":"allowlist"},{"description":"Accept any direct sender.","type":"string","const":"open"},{"description":"Ignore direct messages.","type":"string","const":"disabled"}]},"DockerRuntimeConfig":{"description":"Docker runtime configuration (`[runtime.docker]` section).","type":"object","properties":{"allowed_workspace_roots":{"description":"Optional workspace root allowlist for Docker mount validation.","type":"array","default":[],"items":{"type":"string"}},"cpu_limit":{"description":"Optional CPU limit (`None` = no explicit limit).","type":["number","null"],"format":"double","default":1.0},"image":{"description":"Runtime image used to execute shell commands.","type":"string","default":"alpine:3.20"},"memory_limit_mb":{"description":"Optional memory limit in MB (`None` = no explicit limit).","type":["integer","null"],"format":"uint64","default":512,"minimum":0},"mount_workspace":{"description":"Mount configured workspace into `/workspace`.","type":"boolean","default":true},"network":{"description":"Docker network mode (`none`, `bridge`, etc.).","type":"string","default":"none"},"read_only_rootfs":{"description":"Mount root filesystem as read-only.","type":"boolean","default":true}}},"EmailConfig":{"description":"Email channel configuration","type":"object","properties":{"allowed_senders":{"description":"Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)","type":"array","default":[],"items":{"type":"string"}},"from_address":{"description":"From address for outgoing emails","type":"string"},"idle_timeout_secs":{"description":"IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes","type":"integer","format":"uint64","default":1740,"minimum":0},"imap_folder":{"description":"IMAP folder to poll (default: INBOX)","type":"string","default":"INBOX"},"imap_host":{"description":"IMAP server hostname","type":"string"},"imap_port":{"description":"IMAP server port (default: 993 for TLS)","type":"integer","format":"uint16","default":993,"maximum":65535,"minimum":0},"password":{"description":"Email password for authentication","type":"string"},"smtp_host":{"description":"SMTP server hostname","type":"string"},"smtp_port":{"description":"SMTP server port (default: 465 for TLS)","type":"integer","format":"uint16","default":465,"maximum":65535,"minimum":0},"smtp_tls":{"description":"Use TLS for SMTP (default: true)","type":"boolean","default":true},"username":{"description":"Email username for authentication","type":"string"}},"required":["imap_host","smtp_host","username","password","from_address"]},"EmbeddingRouteConfig":{"description":"Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"dimensions":{"description":"Optional embedding dimension override for this route","type":["integer","null"],"format":"uint","default":null,"minimum":0},"hint":{"description":"Route hint name (e.g. \"semantic\", \"archive\", \"faq\")","type":"string"},"model":{"description":"Embedding model to use with that provider","type":"string"},"provider":{"description":"Embedding provider (`none`, `openai`, or `custom:`)","type":"string"}},"required":["hint","provider","model"]},"EuAiActClassificationConfig":{"type":"object","properties":{"assessed_at":{"type":["string","null"],"default":null},"owner":{"type":["string","null"],"default":null},"status":{"$ref":"#/$defs/EuAiActRiskClassification","default":"unclassified"}}},"EuAiActComplianceConfig":{"type":"object","properties":{"classification":{"$ref":"#/$defs/EuAiActClassificationConfig","default":{"assessed_at":null,"owner":null,"status":"unclassified"}},"declaration":{"$ref":"#/$defs/DeclarationOfConformityConfig","default":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null}},"incident_store_path":{"type":["string","null"],"default":null}}},"EuAiActRiskClassification":{"type":"string","enum":["unclassified","high_risk","not_high_risk"]},"FitnessConfig":{"description":"Calendar schedule, evidence thresholds, and retention for fitness v2.","type":"object","properties":{"auto_run":{"description":"Run the daily fitness worker in daemon mode.","type":"boolean","default":true},"max_backfill_days":{"description":"Maximum number of closed days recovered after downtime.","type":"integer","format":"uint32","default":7,"minimum":0},"min_coverage":{"description":"Minimum available metric weight required to publish a final score.","type":"number","format":"double","default":0.6},"min_samples":{"description":"Minimum samples required before an evidence-derived subscore is usable.","type":"integer","format":"uint","default":5,"minimum":0},"retention_days":{"description":"Number of daily JSON reports retained on disk.","type":"integer","format":"uint32","default":180,"minimum":0},"run_at":{"description":"Local wall-clock time (`HH:MM`) at which the previous day is scored.","type":"string","default":"00:10"},"timezone":{"description":"IANA timezone used to define closed calendar days.","type":"string","default":"UTC"}}},"GatewayConfig":{"description":"Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.","type":"object","properties":{"allow_public_bind":{"description":"Allow binding to non-localhost without a tunnel (default: false)","type":"boolean","default":false},"api_rate_limit_per_minute":{"description":"Max `/api/*` requests per minute per authenticated token.","type":"integer","format":"uint32","default":60,"minimum":0},"channel_webhook_dedup_ttl_secs":{"description":"How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.","type":"integer","format":"uint64","default":86400,"minimum":0},"host":{"description":"Gateway host (default: 127.0.0.1)","type":"string","default":"127.0.0.1"},"idempotency_max_keys":{"description":"Maximum distinct idempotency keys retained in memory.","type":"integer","format":"uint","default":10000,"minimum":0},"idempotency_ttl_secs":{"description":"TTL for webhook idempotency keys.","type":"integer","format":"uint64","default":300,"minimum":0},"pair_rate_limit_per_minute":{"description":"Max `/pair` requests per minute per client key.","type":"integer","format":"uint32","default":10,"minimum":0},"paired_tokens":{"description":"Paired bearer tokens (managed automatically, not user-edited)","type":"array","default":[],"items":{"type":"string"}},"port":{"description":"Gateway port (default: 16830)","type":"integer","format":"uint16","default":16830,"maximum":65535,"minimum":0},"rate_limit_max_keys":{"description":"Maximum distinct client keys tracked by gateway rate limiter maps.","type":"integer","format":"uint","default":10000,"minimum":0},"require_pairing":{"description":"Require pairing before accepting requests (default: true)","type":"boolean","default":true},"targeted_agents":{"description":"Switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). Default true. While false, any\notherwise-valid named target answers 409 `agent_disabled` and never\nruns as Main.","type":"boolean","default":true},"trust_forwarded_headers":{"description":"Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.","type":"boolean","default":false},"webhook_rate_limit_per_minute":{"description":"Max `/webhook` requests per minute per client key.","type":"integer","format":"uint32","default":60,"minimum":0}}},"GroupPolicy":{"description":"Policy for group-message handling.","oneOf":[{"description":"Accept only groups listed in `group_allow_from`.","type":"string","const":"allowlist"},{"description":"Accept any group.","type":"string","const":"open"},{"description":"Ignore group messages.","type":"string","const":"disabled"}]},"GroupReplyMode":{"description":"How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.","oneOf":[{"description":"Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).","type":"string","const":"off"},{"description":"Reply only when the bot is @-mentioned (legacy `mention_only = true`).","type":"string","const":"mention-only"},{"description":"Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).","type":"string","const":"smart"}]},"HeartbeatConfig":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]` section).","type":"object","properties":{"active_hours":{"description":"Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.","type":"array","default":[8,23],"items":{"type":"integer","format":"uint8","maximum":255,"minimum":0}},"interval_minutes":{"description":"Interval in minutes between heartbeat pings. Default: `30`.","type":"integer","format":"uint32","default":30,"minimum":0},"prompt":{"description":"Prompt used by heartbeat worker when dispatching tasks.","type":"string","default":"Check HEARTBEAT.md and follow instructions."}}},"HttpRequestConfig":{"description":"HTTP request tool configuration (`[http_request]` section).","type":"object","properties":{"max_response_size":{"description":"Maximum response size in bytes (default: 1MB)","type":"integer","format":"uint","default":1000000,"minimum":0},"timeout_secs":{"description":"Request timeout in seconds (default: 30)","type":"integer","format":"uint64","default":30,"minimum":0}}},"IMessageConfig":{"description":"iMessage channel configuration (macOS only).","type":"object","properties":{"allowed_contacts":{"description":"Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.","type":"array","items":{"type":"string"}},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["allowed_contacts"]},"IdentityBindingConfig":{"description":"Startup identity binding entry (`[[identity_bindings]]`).","type":"object","properties":{"channel":{"type":"string"},"channel_account":{"type":"string"},"display_name":{"type":["string","null"],"default":null},"user_id":{"type":"string"}},"required":["user_id","channel","channel_account"]},"IdentityConfig":{"description":"Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.","type":"object","properties":{"aieos_inline":{"description":"Inline AIEOS JSON (alternative to file path)","type":["string","null"],"default":null},"aieos_path":{"description":"Path to AIEOS JSON file (relative to workspace)","type":["string","null"],"default":null},"format":{"description":"Identity format: \"openclaw\" (default) or \"aieos\"","type":"string","default":"openclaw"}}},"InteractionNoticeApplicability":{"type":"string","enum":["required","not_applicable"]},"InteractionNoticeConfig":{"type":"object","properties":{"applicability":{"$ref":"#/$defs/InteractionNoticeApplicability","default":"required"},"exception_owner":{"type":["string","null"],"default":null},"exception_reviewed_at":{"type":["string","null"],"default":null},"text":{"type":"string","default":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers."},"version":{"type":"string","default":"1"}}},"IrcConfig":{"description":"IRC channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed nicknames (case-insensitive) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"channels":{"description":"Channels to join on connect","type":"array","default":[],"items":{"type":"string"}},"mention_only":{"description":"When true, only process channel/group messages that mention the bot.","type":"boolean","default":false},"nickname":{"description":"Bot nickname","type":"string"},"nickserv_password":{"description":"NickServ IDENTIFY password","type":["string","null"]},"port":{"description":"IRC server port (default: 6697 for TLS)","type":"integer","format":"uint16","default":6697,"maximum":65535,"minimum":0},"sasl_password":{"description":"SASL PLAIN password (IRCv3)","type":["string","null"]},"server":{"description":"IRC server hostname","type":"string"},"server_password":{"description":"Server password (for bouncers like ZNC)","type":["string","null"]},"username":{"description":"Username (defaults to nickname if not set)","type":["string","null"]},"verify_tls":{"description":"Verify TLS certificate (default: true)","type":["boolean","null"]}},"required":["server","nickname"]},"LarkConfig":{"description":"Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from Lark/Feishu developer console","type":"string"},"app_secret":{"description":"App Secret from Lark/Feishu developer console","type":"string"},"encrypt_key":{"description":"Encrypt key for webhook message decryption (optional)","type":["string","null"],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"port":{"description":"HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"receive_mode":{"description":"Event receive mode: \"websocket\" (default) or \"webhook\"","$ref":"#/$defs/LarkReceiveMode","default":"websocket"},"use_feishu":{"description":"Whether to use the Feishu (Chinese) endpoint instead of Lark (International)","type":"boolean","default":false},"verification_token":{"description":"Verification token for webhook validation (optional)","type":["string","null"],"default":null}},"required":["app_id","app_secret"]},"LarkReceiveMode":{"description":"How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.","type":"string","enum":["websocket","webhook"]},"LinqConfig":{"type":"object","properties":{"allowed_senders":{"description":"Allowed sender handles (phone numbers) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"api_token":{"description":"Linq Partner API token (Bearer auth)","type":"string"},"from_phone":{"description":"Phone number to send from (E.164 format)","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"signing_secret":{"description":"Webhook signing secret for signature verification","type":["string","null"],"default":null}},"required":["api_token","from_phone"]},"MattermostConfig":{"description":"Mattermost bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Mattermost user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Mattermost bot access token.","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.","type":["boolean","null"],"default":null},"thread_replies":{"description":"When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.","type":["boolean","null"],"default":null},"url":{"description":"Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).","type":"string"}},"required":["url","bot_token"]},"McpConfig":{"type":"object","properties":{"servers":{"description":"Named MCP server definitions","type":"object","additionalProperties":{"$ref":"#/$defs/McpServerConfig"},"default":{}},"workspace_servers":{"description":"Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.","$ref":"#/$defs/WorkspaceMcpServers"}}},"McpServerConfig":{"type":"object","properties":{"allow_tools":{"description":"Optional allow-list of exposed tools (empty = all)","type":"array","default":[],"items":{"type":"string"}},"args":{"description":"Command args for stdio mode","type":"array","default":[],"items":{"type":"string"}},"command":{"description":"Command for stdio mode","type":["string","null"],"default":null},"deny_tools":{"description":"Optional deny-list of exposed tools","type":"array","default":[],"items":{"type":"string"}},"env":{"description":"Environment variables for stdio mode","type":"object","additionalProperties":{"type":"string"},"default":{}},"request_timeout_ms":{"description":"Request timeout in milliseconds","type":"integer","format":"uint64","default":30000,"minimum":0},"startup_timeout_ms":{"description":"Startup timeout in milliseconds","type":"integer","format":"uint64","default":10000,"minimum":0},"tool_name_prefix":{"description":"Prefix used in tool naming and routing","type":"string","default":"mcp"},"transport":{"description":"Transport type: stdio or http","$ref":"#/$defs/McpTransport","default":"stdio"},"url":{"description":"URL for HTTP mode (streamable HTTP endpoint)","type":["string","null"],"default":null},"working_dir":{"description":"Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).","type":["string","null"]}}},"McpServerRuntimeConfig":{"type":"object","properties":{"allowed_origins":{"description":"Allowed browser origins for future streamable HTTP clients.","type":"array","default":["claude.ai","openai.com","localhost"],"items":{"type":"string"}},"bind":{"description":"Advertised bind address. The gateway may still be started with a CLI port override.","type":"string","default":"127.0.0.1:16831"},"exposed_tools":{"description":"Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.","type":"array","default":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"items":{"type":"string"}},"jwt_algorithms":{"description":"Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.","type":"array","default":["RS256"],"items":{"type":"string"}},"jwt_audience":{"description":"Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.","type":["string","null"],"default":null},"jwt_issuer":{"description":"Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.","type":["string","null"],"default":null},"jwt_jwks":{"description":"Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.","type":["string","null"],"default":null},"jwt_jwks_cache_ttl_secs":{"description":"Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.","type":"integer","format":"uint64","default":300,"minimum":0},"jwt_jwks_uri":{"description":"Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.","type":["string","null"],"default":null},"jwt_public_key_pem":{"description":"PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.","type":["string","null"],"default":null},"rate_limit_rps":{"description":"Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.","type":"integer","format":"uint32","default":10,"minimum":0},"require_auth":{"description":"Require an authenticated external identity for mutating calls.","type":"boolean","default":true}}},"McpTransport":{"type":"string","enum":["stdio","http"]},"MediaConfig":{"description":"Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.","type":"object","properties":{"audio_model":{"description":"Audio model name (Ollama model or OpenAI model). Default: \"whisper\".","type":"string","default":"whisper"},"audio_ollama_url":{"description":"Ollama base URL for audio transcription. Default: \"http://localhost:11434\".","type":"string","default":"http://localhost:11434"},"audio_provider":{"description":"Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".","type":"string","default":"none"},"max_audio_size_mb":{"description":"Maximum audio attachment size in MiB. Default: 20.","type":"integer","format":"uint","default":20,"minimum":0},"max_video_size_mb":{"description":"Maximum video attachment size in MiB. Default: 50.","type":"integer","format":"uint","default":50,"minimum":0},"video_max_frames":{"description":"Maximum video frames to extract per video. Default: 4.","type":"integer","format":"uint","default":4,"minimum":0},"video_provider":{"description":"Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".","type":"string","default":"none"}}},"MemoryConfig":{"description":"Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.","type":"object","properties":{"acl_enabled":{"description":"Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.","type":"boolean","default":false},"archive_after_days":{"description":"Archive daily/session files older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"auto_hydrate":{"description":"Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing","type":"boolean","default":true},"auto_save":{"description":"Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.","type":"boolean","default":true},"backend":{"description":"\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).","type":"string","default":"sqlite"},"conversation_retention_days":{"description":"For sqlite backend: prune conversation rows older than this many days","type":"integer","format":"uint32","default":3,"minimum":0},"daily_retention_days":{"description":"For sqlite backend: prune daily rows older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"embedding_cache_size":{"description":"Max embedding cache entries before LRU eviction","type":"integer","format":"uint","default":10000,"minimum":0},"embedding_dimensions":{"description":"Embedding vector dimensions","type":"integer","format":"uint","default":384,"minimum":0},"embedding_model":{"description":"Embedding model name (e.g. \"text-embedding-3-small\")","type":"string","default":"prx-local-hash-v1"},"embedding_provider":{"description":"Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"","type":"string","default":"local"},"events":{"description":"Raw/quasi-raw message event recording controls (`[memory.events]`).","$ref":"#/$defs/MemoryEventsConfig","default":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true}},"keyword_weight":{"description":"Weight for keyword BM25 in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.3},"legacy_conversation_turns_visible":{"description":"Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.","type":"boolean","default":true},"lucid_budget":{"description":"Token budget for lucid (replaces OPENPRX_LUCID_BUDGET)","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"lucid_cmd":{"description":"Path to lucid binary (replaces OPENPRX_LUCID_CMD)","type":["string","null"],"default":null},"lucid_failure_cooldown_ms":{"description":"Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)","type":"integer","format":"uint64","default":60000,"minimum":0},"lucid_local_hit_threshold":{"description":"Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)","type":"integer","format":"uint","default":3,"minimum":0},"lucid_recall_timeout_ms":{"description":"Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)","type":"integer","format":"uint64","default":5000,"minimum":0},"lucid_store_timeout_ms":{"description":"Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)","type":"integer","format":"uint64","default":3000,"minimum":0},"min_relevance_score":{"description":"Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4","type":"number","format":"double","default":0.4},"purge_after_days":{"description":"Purge archived files older than this many days","type":"integer","format":"uint32","default":30,"minimum":0},"semantic":{"description":"Semantic memory promotion controls (`[memory.semantic]`).","$ref":"#/$defs/MemorySemanticConfig","default":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30}},"sqlite_open_timeout_secs":{"description":"For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"sqlite_read_pool_size":{"description":"For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"vector_candidate_cap":{"description":"How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.","type":"integer","format":"uint","default":2000,"minimum":0},"vector_weight":{"description":"Weight for vector similarity in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.7}}},"MemoryEventsConfig":{"description":"Raw message event recording configuration (`[memory.events]`).","type":"object","properties":{"record_assistant_messages":{"description":"Record assistant replies.","type":"boolean","default":true},"record_tool_events":{"description":"Record tool/event payloads by default.","type":"boolean","default":false},"record_user_messages":{"description":"Record inbound/user messages.","type":"boolean","default":true}}},"MemorySemanticConfig":{"description":"Semantic memory promotion configuration (`[memory.semantic]`).","type":"object","properties":{"auto_promote_assistant_messages":{"description":"Auto-promote eligible assistant messages. Disabled by default to reduce noise.","type":"boolean","default":false},"auto_promote_user_messages":{"description":"Auto-promote eligible user messages into long-term semantic memories.","type":"boolean","default":true},"min_chars":{"description":"Minimum content length for semantic auto-promotion.","type":"integer","format":"uint","default":30,"minimum":0}}},"MemoryWebhookConfig":{"type":"object","properties":{"bind":{"description":"Socket address for the receiver (e.g. \"0.0.0.0:16899\").","type":"string","default":"0.0.0.0:16899"},"signing_secret":{"description":"Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.","type":["string","null"],"default":null},"token":{"description":"Required bearer token for incoming webhook events.","type":["string","null"],"default":null}}},"ModelOperationSetting":{"description":"The operations a `[[providers.models]]` entry may list.","type":"string","enum":["chat","embedding","decision_endpoint","rerank","image_generation","audio_generation","video_generation"]},"ModelPricing":{"description":"Per-model pricing entry (USD per 1M tokens).","type":"object","properties":{"cache_read":{"description":"Cache read input price per 1M tokens.","type":"number","format":"double","default":0.0},"cache_write":{"description":"Cache write/creation input price per 1M tokens.","type":"number","format":"double","default":0.0},"input":{"description":"Input price per 1M tokens","type":"number","format":"double","default":0.0},"output":{"description":"Output price per 1M tokens","type":"number","format":"double","default":0.0}}},"ModelRouteConfig":{"description":"Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"hint":{"description":"Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")","type":"string"},"level":{"type":["string","null"]},"model":{"description":"Model to use with that provider","type":"string"},"provider":{"description":"Provider to route to (must match a known provider name)","type":"string"},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true,"required":["hint","provider","model"]},"ModelSettings":{"description":"A model level plus explicit parameter overrides in `[model_settings.\"\"]`.","type":"object","properties":{"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"level":{"type":["string","null"]},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true},"MultimodalConfig":{"description":"Multimodal (image) handling configuration (`[multimodal]` section).","type":"object","properties":{"allow_remote_fetch":{"description":"Allow fetching remote image URLs (http/https). Disabled by default.","type":"boolean","default":false},"max_image_size_mb":{"description":"Maximum image payload size in MiB before base64 encoding.","type":"integer","format":"uint","default":5,"minimum":0},"max_images":{"description":"Maximum number of image attachments accepted per request.","type":"integer","format":"uint","default":4,"minimum":0}}},"NextcloudTalkConfig":{"description":"Nextcloud Talk bot configuration (webhook receive + OCS send API).","type":"object","properties":{"allowed_users":{"description":"Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Bot app token used for OCS API bearer auth.","type":"string"},"base_url":{"description":"Nextcloud base URL (e.g. \"https://cloud.example.com\").","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"webhook_secret":{"description":"Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).","type":["string","null"],"default":null}},"required":["base_url","app_token"]},"NgrokTunnelConfig":{"type":"object","properties":{"auth_token":{"description":"ngrok auth token","type":"string"},"domain":{"description":"Optional custom domain","type":["string","null"]}},"required":["auth_token"]},"NodeServerConfig":{"description":"Node daemon runtime config used by `prx-node`.","type":"object","properties":{"allowed_commands":{"description":"Command allowlist matched on first token.\n\nIn restricted mode this list is required unless explicitly set to `[\"*\"]`.","type":"array","default":["echo"],"items":{"type":"string"}},"bearer_token":{"description":"Required bearer token for /rpc.","type":"string","default":""},"blocked_commands":{"description":"Command denylist matched on first token. Always enforced.","type":"array","default":[],"items":{"type":"string"}},"exec_timeout_ms":{"description":"Default command timeout in milliseconds.","type":"integer","format":"uint64","default":15000,"minimum":0},"hmac_secret":{"description":"Optional HMAC signing secret.","type":["string","null"],"default":null},"listen_addr":{"description":"Listen address for node daemon.","type":"string","default":"127.0.0.1:8787"},"max_concurrent_tasks":{"description":"Maximum number of concurrent async command tasks.","type":"integer","format":"uint","default":8,"minimum":0},"max_output_bytes":{"description":"Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.","type":"integer","format":"uint","default":1048576,"minimum":0},"sandbox_root":{"description":"Sandbox root directory for read/write/cwd constraints.","type":"string","default":"."},"task_result_ttl_ms":{"description":"TTL for completed task results in milliseconds.","type":"integer","format":"uint64","default":3600000,"minimum":0},"tls_cert":{"description":"TLS certificate path (PEM).","type":["string","null"],"default":null},"tls_key":{"description":"TLS private key path (PEM).","type":["string","null"],"default":null},"tls_required":{"description":"Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.","type":"boolean","default":true}}},"NodesConfig":{"description":"Remote node proxy configuration for core-side RPC calls and node daemon defaults.","type":"object","properties":{"nodes":{"description":"Configured remote nodes.","type":"array","default":[],"items":{"$ref":"#/$defs/RemoteNodeConfig"}},"request_timeout_ms":{"description":"Default request timeout for node RPC calls.","type":"integer","format":"uint64","default":15000,"minimum":0},"retry_max":{"description":"Default max retries for node RPC calls.","type":"integer","format":"uint8","default":2,"maximum":255,"minimum":0},"server":{"description":"Embedded node server defaults used by `prx-node`.","$ref":"#/$defs/NodeServerConfig","default":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}}},"ObservabilityConfig":{"description":"Observability backend configuration (`[observability]` section).","type":"object","properties":{"backend":{"description":"\"none\" | \"log\" | \"prometheus\" | \"otel\"","type":"string","default":"none"},"otel_endpoint":{"description":"OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".","type":["string","null"],"default":null},"otel_service_name":{"description":"Service name reported to the OTel collector. Defaults to \"prx\".","type":["string","null"],"default":null}}},"OllamaProviderConfig":{"description":"Ollama-specific request options (`[providers.ollama]`).","type":"object","properties":{"num_ctx":{"description":"Explicit context window sent as Ollama `options.num_ctx`.","type":["integer","null"],"format":"uint","default":null,"minimum":0}}},"OsPagingConfig":{"description":"Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.","type":"object","properties":{"eviction_threshold":{"description":"Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.","type":"number","format":"double","default":0.7},"keep_recent_messages":{"description":"Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).","type":"integer","format":"uint","default":12,"minimum":0},"max_recalled_pages":{"description":"Maximum number of evicted pages (document chunks) recalled per turn.","type":"integer","format":"uint","default":10,"minimum":0},"proactive_retrieval":{"description":"Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.","type":"boolean","default":true},"retrieval_injection_role":{"description":"Role under which recalled pages are injected.","$ref":"#/$defs/RetrievalInjectionRole","default":"system"}}},"PluginsConfig":{"description":"WASM plugin runtime configuration.","type":"object","properties":{"enabled":{"description":"Load WASM plugins from `/plugins`. Default: `false`.","type":"boolean","default":false}},"additionalProperties":false},"ProviderModelConfig":{"description":"One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.","type":"object","properties":{"context_window":{"description":"The model's context window in tokens.","type":["integer","null"],"format":"uint32","minimum":0},"model":{"description":"The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.","type":["string","null"]},"native_tools":{"description":"Whether the model accepts native tool calls.","type":["boolean","null"]},"operations":{"description":"The complete list of operations the model executes; every operation not\nlisted is unsupported.","type":["array","null"],"items":{"$ref":"#/$defs/ModelOperationSetting"}},"provider":{"description":"The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.","type":"string"},"streaming":{"description":"Whether the model streams responses.","type":["boolean","null"]},"structured_output":{"description":"Whether the model honours a JSON-schema response format.","type":["boolean","null"]},"tool_call_dialect":{"description":"The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema_dialect":{"description":"The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]},"vision_input":{"description":"Whether the model accepts image input.","type":["boolean","null"]}},"required":["provider"]},"ProviderToolDialectConfig":{"description":"One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.","type":"object","properties":{"model":{"description":"The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.","type":["string","null"]},"provider":{"description":"The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.","type":"string"},"tool_call":{"description":"The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema":{"description":"The tool-schema dialect the endpoint accepts.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]}},"required":["provider"]},"ProvidersConfig":{"description":"Provider-specific runtime configuration (`[providers]`).","type":"object","properties":{"models":{"description":"Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.","type":"array","items":{"$ref":"#/$defs/ProviderModelConfig"}},"ollama":{"description":"Ollama-specific request options (`[providers.ollama]`).","$ref":"#/$defs/OllamaProviderConfig","default":{"num_ctx":null}},"tool_dialects":{"description":"Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).","type":"array","items":{"$ref":"#/$defs/ProviderToolDialectConfig"}}}},"ProxyConfig":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).","type":"object","properties":{"all_proxy":{"description":"Fallback proxy URL for all schemes.","type":["string","null"],"default":null},"http_proxy":{"description":"Proxy URL for HTTP requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"https_proxy":{"description":"Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"no_proxy":{"description":"No-proxy bypass list. Same format as NO_PROXY.","type":"array","default":[],"items":{"type":"string"}},"scope":{"description":"Proxy application scope.","$ref":"#/$defs/ProxyScope","default":"prx"},"services":{"description":"Service selectors used when scope = \"services\".","type":"array","default":[],"items":{"type":"string"}}}},"ProxyScope":{"description":"Proxy application scope — determines which outbound traffic uses the proxy.","oneOf":[{"description":"Use system environment proxy variables only.","type":"string","const":"environment"},{"description":"Apply proxy to all OpenPRX-managed HTTP traffic (default).","type":"string","const":"prx"},{"description":"Apply proxy only to explicitly listed service selectors.","type":"string","const":"services"}]},"QQConfig":{"description":"QQ Official Bot configuration (Tencent QQ Bot SDK)","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs. Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from QQ Bot developer console","type":"string"},"app_secret":{"description":"App Secret from QQ Bot developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["app_id","app_secret"]},"QueryClassificationConfig":{"description":"Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.","type":"object","properties":{"rules":{"description":"Classification rules evaluated in priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/ClassificationRule"}}}},"RamfluxAccountConfig":{"description":"Persona for one ramflux AI account. Missing fields fall back to the global agent.","type":"object","properties":{"cross_conversation_retrieval":{"description":"Cross-conversation memory retrieval. Off unless the owner sets it.","type":"boolean","default":false},"model":{"type":["string","null"],"default":null},"provider":{"type":["string","null"],"default":null},"scope_profile":{"type":["string","null"],"default":null},"system_prompt_file":{"description":"Path to a system-prompt file. Relative paths are resolved from the workspace.","type":["string","null"],"default":null}},"additionalProperties":false},"RamfluxAttachmentFetch":{"description":"Per-turn caps for `attachment.fetch`.","type":"object","properties":{"max_bytes":{"type":"integer","format":"uint64","default":5242880,"minimum":0},"max_per_turn":{"type":"integer","format":"uint8","default":4,"maximum":255,"minimum":0}},"additionalProperties":false},"RamfluxAuthorizationMode":{"description":"How prx combines its own setting with `bridge.hello.authorization`.","oneOf":[{"description":"Use the agent-host value. Until hello arrives, the effective mode is supervised.","type":"string","const":"follow_rf"},{"description":"Always supervised, even when the agent-host declares full.","type":"string","const":"supervised"},{"description":"Full only when the agent-host also declares full. Config alone never yields full.","type":"string","const":"full"}]},"RamfluxConfig":{"description":"Local ramflux agent-host bridge (`[channels_config.ramflux]`).","type":"object","properties":{"accounts":{"type":"object","additionalProperties":{"$ref":"#/$defs/RamfluxAccountConfig"},"default":{}},"allowed_block_types":{"type":"array","default":["Text","Markdown","Heading","KeyValue","Metric","List","TableFallback","Form","Input","Select","Progress","LogStream","Warning","Error","Success","Approval","ActionGroup","FilePreview","Fallback"],"items":{"type":"string"}},"attachment_fetch":{"$ref":"#/$defs/RamfluxAttachmentFetch","default":{"max_bytes":5242880,"max_per_turn":4}},"authorization_mode":{"$ref":"#/$defs/RamfluxAuthorizationMode","default":"follow_rf"},"encrypt_at_rest":{"type":"boolean","default":true},"max_in_flight_per_conversation":{"type":"integer","format":"uint8","default":1,"maximum":255,"minimum":0},"on_new_message":{"$ref":"#/$defs/RamfluxOnNewMessage","default":"queue"},"socket_path":{"description":"Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.","type":["string","null"],"default":null},"surface_limits":{"$ref":"#/$defs/RamfluxSurfaceLimits","default":{"max_actions":16,"max_blocks":32,"max_bytes":65536}},"turn_wall_clock_secs":{"description":"Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.","type":"integer","format":"uint64","default":120,"minimum":0}},"additionalProperties":false},"RamfluxOnNewMessage":{"description":"What to do with a new inbound message while a turn for that conversation is running.","type":"string","enum":["queue","interrupt"]},"RamfluxSurfaceLimits":{"description":"Limits for `reply.surface` blocks and actions.","type":"object","properties":{"max_actions":{"type":"integer","format":"uint32","default":16,"minimum":0},"max_blocks":{"type":"integer","format":"uint32","default":32,"minimum":0},"max_bytes":{"type":"integer","format":"uint32","default":65536,"minimum":0}},"additionalProperties":false},"ReliabilityCircuitBreakerConfig":{"description":"Process-local provider circuit policy (`[reliability.circuit_breaker]`).","type":"object","properties":{"enabled":{"description":"Enable protection for factory-built provider chains.","type":"boolean","default":true},"failure_threshold":{"description":"Consecutive transient failures that open a circuit (at least 1).","type":"integer","format":"uint32","default":5,"minimum":0},"max_open_secs":{"description":"Maximum doubled window, between open_secs and 3600 seconds.","type":"integer","format":"uint64","default":300,"minimum":0},"open_secs":{"description":"Initial open window in seconds (at least 1).","type":"integer","format":"uint64","default":30,"minimum":0}}},"ReliabilityConfig":{"description":"Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.","type":"object","properties":{"acknowledge_single_provider_risk":{"description":"Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.","type":"boolean","default":false},"api_keys":{"description":"Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.","type":"array","default":[],"items":{"type":"string"}},"channel_initial_backoff_secs":{"description":"Initial backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":2,"minimum":0},"channel_max_backoff_secs":{"description":"Max backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":60,"minimum":0},"circuit_breaker":{"description":"Per-provider consecutive failure protection.","$ref":"#/$defs/ReliabilityCircuitBreakerConfig","default":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30}},"fallback_providers":{"description":"Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).","type":"array","default":[],"items":{"type":"string"}},"model_fallbacks":{"description":"Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`","type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"default":{}},"provider_backoff_ms":{"description":"Base backoff (ms) for provider retry delay.","type":"integer","format":"uint64","default":500,"minimum":0},"provider_retries":{"description":"Retries per provider before failing over.","type":"integer","format":"uint32","default":2,"minimum":0},"scheduler_poll_secs":{"description":"Scheduler polling cadence in seconds.","type":"integer","format":"uint64","default":15,"minimum":0},"scheduler_retries":{"description":"Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.","type":"integer","format":"uint32","default":2,"minimum":0}}},"RemoteNodeConfig":{"description":"A remote node target for core-side node proxy calls.","type":"object","properties":{"bearer_token":{"description":"Bearer token for node RPC authentication.","type":"string"},"endpoint":{"description":"Base endpoint (e.g. \"http://127.0.0.1:8787\").","type":"string"},"hmac_secret":{"description":"Optional request signing key (HMAC-SHA256).","type":["string","null"],"default":null},"id":{"description":"Stable node ID used by the nodes tool.","type":"string"},"retry_max":{"description":"Optional per-node retry override.","type":["integer","null"],"format":"uint8","default":null,"maximum":255,"minimum":0},"timeout_ms":{"description":"Optional per-node timeout override.","type":["integer","null"],"format":"uint64","default":null,"minimum":0}},"required":["id","endpoint","bearer_token"]},"RetrievalInjectionRole":{"description":"Where recalled context pages are injected back into the request.","oneOf":[{"description":"Inject recalled pages as a leading `system` message (not user-visible).","type":"string","const":"system"},{"description":"Inject recalled pages as a leading `user` message.","type":"string","const":"user"}]},"RouterConfig":{"description":"Heuristic LLM router configuration (`[router]` section).","type":"object","properties":{"alpha":{"description":"Similarity score weight. Phase 1 keeps this at `0.0`.","type":"number","format":"float","default":0.0},"beta":{"description":"Capability score weight.","type":"number","format":"float","default":0.5},"delta":{"description":"Cost penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"epsilon":{"description":"Latency penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"gamma":{"description":"Elo score weight.","type":"number","format":"float","default":0.30000001192092896},"knn_k":{"description":"Number of nearest neighbors considered for voting. Default: `7`.","type":"integer","format":"uint","default":7,"minimum":0},"knn_min_records":{"description":"Minimum history records before KNN affects routing. Default: `10`.","type":"integer","format":"uint","default":10,"minimum":0},"models":{"description":"Candidate model registry.","type":"array","default":[],"items":{"$ref":"#/$defs/RouterModelConfig"}}}},"RouterModelConfig":{"description":"Static router metadata for one model candidate.","type":"object","properties":{"categories":{"description":"Capability categories such as `conversation`, `code`, or `analysis`.","type":"array","default":[],"items":{"type":"string"}},"cost_per_million_tokens":{"description":"USD cost per million tokens.","type":"number","format":"float","default":0.0},"elo_rating":{"description":"Initial Elo rating.","type":"number","format":"float","default":1000.0},"latency_ms":{"description":"Average latency in milliseconds.","type":"integer","format":"uint32","default":2000,"minimum":0},"max_context":{"description":"Maximum context window in tokens.","type":"integer","format":"uint","default":1000000,"minimum":0},"model_id":{"description":"Model identifier without provider prefix.","type":"string"},"provider":{"description":"Provider identifier.","type":"string"},"reserved_output_tokens":{"description":"Output tokens reserved for this model when planning input context.","type":["integer","null"],"format":"uint","minimum":0}},"required":["model_id","provider"]},"RuntimeConfig":{"description":"Runtime adapter configuration (`[runtime]` section).","type":"object","properties":{"codex_reasoning_effort":{"description":"Codex reasoning effort","type":["string","null"],"default":null},"codex_stream_idle_timeout_secs":{"description":"Codex stream idle timeout in seconds","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"docker":{"description":"Docker runtime settings (used when `kind = \"docker\"`).","$ref":"#/$defs/DockerRuntimeConfig","default":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true}},"idle_hang_secs":{"description":"Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"kind":{"description":"Runtime kind (`native` | `docker`).","type":"string","default":"native"},"long_task_warn_secs":{"description":"Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"managed_cgroup_root":{"description":"Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.","type":["string","null"],"default":null},"max_blocking_threads":{"description":"Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"reasoning_enabled":{"description":"Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported","type":["boolean","null"],"default":null},"shell_env_allowlist":{"description":"Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.","type":"array","default":[],"items":{"type":"string"}},"workdir":{"description":"Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.","type":["string","null"],"default":null}}},"SchedulerConfig":{"description":"Scheduler configuration for periodic task execution (`[scheduler]` section).","type":"object","properties":{"claim_lease_secs":{"description":"Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.","type":"integer","format":"uint64","default":90,"minimum":0},"max_tasks":{"description":"Maximum number of persisted scheduled tasks.","type":"integer","format":"uint","default":64,"minimum":0}}},"ScopeConfig":{"description":"Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```","type":"object","properties":{"assign_owners":{"description":"Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.","type":"array","default":[],"items":{"type":"string"}},"default":{"description":"Default action when no rule matches: \"allow\" (default) or \"deny\".","$ref":"#/$defs/ScopeDefault","default":"allow"},"rules":{"description":"Ordered list of scope rules evaluated top-to-bottom.","type":"array","default":[],"items":{"$ref":"#/$defs/ScopeRule"}}}},"ScopeDefault":{"description":"What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.","oneOf":[{"description":"Unmatched tool calls are allowed (the default).","type":"string","const":"allow"},{"description":"Unmatched tool calls are refused.","type":"string","const":"deny"}]},"ScopeRule":{"description":"A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.","type":"object","properties":{"assign_allow":{"description":"Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".","type":"array","default":[],"items":{"type":"string"}},"assign_deny":{"description":"Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.","type":"array","default":[],"items":{"type":"string"}},"channel":{"description":"Match by channel name: \"signal\", \"telegram\", \"discord\", etc.","type":["string","null"]},"chat_type":{"description":"Match by chat type: \"direct\", \"group\", or \"*\" for any type.","type":["string","null"]},"send_allow":{"description":"Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.","type":"array","default":[],"items":{"type":"string"}},"send_deny":{"description":"Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.","type":"array","default":[],"items":{"type":"string"}},"tools_allow":{"description":"Tool whitelist: only these tools are allowed (empty = all tools permitted).","type":"array","default":[],"items":{"type":"string"}},"tools_deny":{"description":"Tool blacklist: these tools are denied regardless of allow list.","type":"array","default":[],"items":{"type":"string"}},"user":{"description":"Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.","type":["string","null"]}}},"SecretsConfig":{"description":"Secrets encryption configuration (`[secrets]` section).","type":"object","properties":{"encrypt":{"description":"Enable encryption for API keys and tokens in config.toml","type":"boolean","default":true}}},"SecurityConfig":{"description":"Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.","type":"object","properties":{"audit":{"description":"Audit logging configuration","$ref":"#/$defs/AuditConfig","default":{"log_path":"audit.log","max_size_mb":100}},"workspace_hooks":{"description":"Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.","$ref":"#/$defs/WorkspaceHooks"}}},"SelfSystemConfig":{"description":"Self-system experimental automation config (`[self_system]`).","type":"object","properties":{"evolution_config_path":{"description":"Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG)","type":["string","null"],"default":null},"evolution_debug_raw":{"description":"Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW)","type":"boolean","default":false},"evolution_interval_hours":{"description":"Evolution scheduler interval in hours (daemon mode).","type":"integer","format":"uint32","default":24,"minimum":0},"evolution_judge_timeout_secs":{"description":"Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.","type":"integer","format":"uint64","default":180,"minimum":0},"evolution_model_max_micro_usd":{"description":"Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.","type":"integer","format":"uint64","default":0,"minimum":0},"evolution_model_max_tokens":{"description":"Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.","type":"integer","format":"uint64","default":16384,"minimum":0},"fitness":{"description":"Daily fitness snapshot policy.","$ref":"#/$defs/FitnessConfig","default":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"}},"fitness_interval_hours":{"description":"Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.","type":"integer","format":"uint64","default":24,"minimum":0}}},"SessionsSpawnConfig":{"description":"Sessions spawn configuration (`[sessions_spawn]` section).","type":"object","properties":{"cleanup_on_complete":{"description":"Remove worker workspace directory after process-mode completion.","type":"boolean","default":true},"default_mode":{"description":"Default execution mode for sessions_spawn (`task` or `process`).","type":"string","default":"task"},"process_memory_strategy":{"description":"Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.","type":"string","default":"shared_fabric"},"worker_workspace_root":{"description":"Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.","type":["string","null"],"default":null}}},"SignalConfig":{"type":"object","properties":{"account":{"description":"E.164 phone number of the signal-cli account (e.g. \"+1234567890\").","type":"string"},"allowed_from":{"description":"Allowed sender phone numbers (E.164) or \"*\" for all.","type":"array","default":[],"items":{"type":"string"}},"cli_path":{"description":"Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).","type":["string","null"],"default":null},"daemon_http_port":{"description":"Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"daemon_mode":{"description":"Deprecated: ignored. Accepted for backward compatibility with older config files.","type":["boolean","null"],"default":null},"data_dir":{"description":"signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_id":{"description":"Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group","type":["string","null"],"default":null},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"http_url":{"description":"Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.","type":"string","default":"http://localhost:8080"},"ignore_attachments":{"description":"Skip messages that are attachment-only (no text body).","type":"boolean","default":false},"ignore_stories":{"description":"Skip incoming story messages.","type":"boolean","default":false},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"mode":{"description":"Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.","type":["string","null"],"default":null},"startup_timeout_ms":{"description":"Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.","type":"integer","format":"uint64","default":30000,"minimum":0},"storm_protection":{"description":"Signal ingress storm protection controls.","$ref":"#/$defs/SignalStormProtectionConfig","default":{"abnormal_threshold":10,"abnormal_window_secs":60,"breaker_duration_secs":300,"dedupe_ttl_secs":60,"min_reply_interval_secs":2}}},"required":["account"]},"SignalStormProtectionConfig":{"type":"object","properties":{"abnormal_threshold":{"description":"Non-user event threshold within `abnormal_window_secs` before tripping the breaker.","type":"integer","format":"uint","default":10,"minimum":0},"abnormal_window_secs":{"description":"Sliding window in seconds for non-user event counting.","type":"integer","format":"uint64","default":60,"minimum":0},"breaker_duration_secs":{"description":"Circuit breaker duration in seconds after threshold is reached.","type":"integer","format":"uint64","default":300,"minimum":0},"dedupe_ttl_secs":{"description":"Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.","type":"integer","format":"uint64","default":60,"minimum":0},"min_reply_interval_secs":{"description":"Minimum interval in seconds between replies for the same `(channel + reply_target)`.","type":"integer","format":"uint64","default":2,"minimum":0}}},"SkillRagConfig":{"description":"Dynamic skill retrieval configuration (`[skill_rag]` section).","type":"object","properties":{"top_k":{"description":"How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).","type":"integer","format":"uint","default":32,"minimum":0}}},"SkillSuiteRegistration":{"description":"The frozen suite that governs one skill's proposals.","type":"object","properties":{"skill_id":{"description":"The skill the suite governs.","type":"string"},"suite_digest":{"description":"SHA-256 digest (64 lowercase hex digits) of the frozen suite.","type":"string"}},"additionalProperties":false,"required":["skill_id","suite_digest"]},"SkillsConfig":{"description":"Skills loading configuration (`[skills]` section).","type":"object","properties":{"open_skills_dir":{"description":"Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.","type":["string","null"],"default":null},"openclaw_skills_dir":{"description":"Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.","type":["string","null"],"default":null}}},"SkillsLifecycleConfig":{"description":"`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.","type":"object","properties":{"allow_executable_proposals":{"description":"Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.","type":"boolean","default":false},"enabled":{"description":"Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.","type":"boolean","default":false},"max_concurrent_evaluations":{"description":"Most evaluations running at once.","type":"integer","format":"uint32","default":1,"minimum":0},"max_edit_fraction":{"description":"Edit budget of a proposal as a fraction of the skill body, in (0, 1].","type":"number","format":"double","default":0.2},"max_edit_tokens":{"description":"Edit budget of a proposal, in tokens.","type":"integer","format":"uint64","default":300,"minimum":0},"max_proposals_per_cycle":{"description":"Most proposals one cycle may start.","type":"integer","format":"uint32","default":1,"minimum":0},"min_cases_floor":{"description":"Smallest `min_cases` a governing suite may declare. Below 3 is refused.","type":"integer","format":"uint32","default":3,"minimum":0},"mode":{"description":"`draft_only`, `shadow` or `auto`.","$ref":"#/$defs/SkillsLifecycleModeConfig","default":"draft_only"},"owner_scope":{"description":"The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.","type":["string","null"],"default":null},"require_holdout":{"description":"A governing suite must have a holdout split. `false` is refused.","type":"boolean","default":true},"storage_dir":{"description":"Store location under the workspace. Only the default is supported.","type":"string","default":"self/skill-lifecycle"},"suites":{"description":"The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.","type":"array","default":[],"items":{"$ref":"#/$defs/SkillSuiteRegistration"}}},"additionalProperties":false},"SkillsLifecycleModeConfig":{"description":"What the lifecycle may do. Mirrors `LifecycleMode`.","oneOf":[{"description":"Drafts and reviews only.","type":"string","const":"draft_only"},{"description":"Drafts plus evaluation and gating; never publishes.","type":"string","const":"shadow"},{"description":"Publishes an eligible proposal after every gate.","type":"string","const":"auto"}]},"SlackConfig":{"description":"Slack bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Slack user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Slack app-level token for Socket Mode (xapp-...).","type":["string","null"]},"bot_token":{"description":"Slack bot OAuth token (xoxb-...).","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["bot_token"]},"SmartGroupConfig":{"description":"Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).","type":"object","properties":{"classifier_max_context_messages":{"description":"How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.","type":"integer","format":"uint","default":3,"minimum":0},"classifier_model":{"description":"Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.","type":"string","default":""},"classifier_provider":{"description":"Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.","type":"string","default":""},"classifier_temperature":{"description":"Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).","type":"number","format":"double","default":0.0},"classifier_timeout_secs":{"description":"Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.","type":"integer","format":"uint64","default":5,"minimum":0}}},"StorageConfig":{"description":"Persistent storage configuration (`[storage]` section).","type":"object","properties":{"provider":{"description":"Storage provider settings (e.g. sqlite, postgres).","$ref":"#/$defs/StorageProviderSection","default":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}}},"StorageProviderConfig":{"description":"Storage provider backend configuration (e.g. postgres connection details).","type":"object","properties":{"connect_timeout_secs":{"description":"Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"db_url":{"description":"Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.","type":["string","null"],"default":null},"pool_max_size":{"description":"Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.","type":"integer","format":"uint","default":32,"minimum":0},"provider":{"description":"Storage engine key (e.g. \"postgres\", \"sqlite\").","type":"string","default":""},"schema":{"description":"Database schema for SQL backends.","type":"string","default":"public"},"table":{"description":"Table name for memory entries.","type":"string","default":"memories"}}},"StorageProviderSection":{"description":"Wrapper for the storage provider configuration section.","type":"object","properties":{"config":{"description":"Storage provider backend settings.","$ref":"#/$defs/StorageProviderConfig","default":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"StreamMode":{"description":"Streaming mode for channels that support progressive message updates.","oneOf":[{"description":"No streaming -- send the complete response as a single message (default).","type":"string","const":"off"},{"description":"Update a draft message with every flush interval.","type":"string","const":"partial"}]},"TailscaleTunnelConfig":{"type":"object","properties":{"funnel":{"description":"Use Tailscale Funnel (public internet) vs Serve (tailnet only)","type":"boolean","default":false},"hostname":{"description":"Optional hostname override","type":["string","null"]}}},"TaskRoutingConfig":{"description":"Lightweight pre-LLM task routing.","type":"object","properties":{"default_intent":{"description":"Fallback intent when no rule matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"rules":{"description":"Rules evaluated in descending priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/TaskRoutingRule"}}}},"TaskRoutingIntentConfig":{"description":"Task-routing default and rule intent.","type":"string","enum":["simple","delegate","stream"]},"TaskRoutingRule":{"description":"A single task-routing rule.","type":"object","properties":{"intent":{"description":"Route intent to apply when a keyword matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"model_hint":{"description":"Optional model hint/raw model for non-delegated requests.","type":["string","null"],"default":null},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0},"sub_agent_model":{"description":"Optional raw sub-agent model override for delegated tasks.","type":["string","null"],"default":null}}},"TelegramConfig":{"description":"Telegram bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Telegram user IDs or usernames. Empty = deny all.","type":"array","items":{"type":"string"}},"bot_token":{"description":"Telegram Bot API token (from @BotFather).","type":"string"},"draft_update_interval_ms":{"description":"Minimum interval (ms) between draft message edits to avoid rate limits.","type":"integer","format":"uint64","default":1000,"minimum":0},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"interrupt_on_new_message":{"description":"When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.","type":"boolean","default":false},"stream_mode":{"description":"Streaming mode for progressive response delivery via message edits.","$ref":"#/$defs/StreamMode","default":"off"}},"required":["bot_token","allowed_users"]},"ToolCallDialectSetting":{"description":"The tool-call grammars an operator may declare for an endpoint.","oneOf":[{"description":"Only the native `tool_calls` array is a tool call (the default).","type":"string","const":"native"},{"description":"Additionally read `{json}` from the content,\nfor a tool name the request registered.","type":"string","const":"xml_function_tags"}]},"ToolSchemaDialectSetting":{"description":"The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.","oneOf":[{"description":"The published document, byte for byte (the default).","type":"string","const":"raw"},{"description":"The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.","type":"string","const":"no_root_combinators"}]},"ToolTieringConfig":{"description":"Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.","type":"object","properties":{"always_exclude":{"description":"Tool names excluded from capability publication.","type":"array","default":[],"items":{"type":"string"}},"always_include":{"description":"Tool names preferred for direct publication, subject to admission gates.","type":"array","default":[],"items":{"type":"string"}},"channel_exclude":{"description":"Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefaults to [`DEFAULT_CHANNEL_EXCLUDED_TOOLS`]; set to `[]` to expose the\nfull operator surface on channels again.","type":"array","default":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","skills_manage","memory_reindex","document_sync","document_ingest"],"items":{"type":"string"}}}},"TunnelConfig":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.","type":"object","properties":{"cloudflare":{"description":"Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).","anyOf":[{"$ref":"#/$defs/CloudflareTunnelConfig"},{"type":"null"}],"default":null},"custom":{"description":"Custom tunnel command configuration (used when `provider = \"custom\"`).","anyOf":[{"$ref":"#/$defs/CustomTunnelConfig"},{"type":"null"}],"default":null},"ngrok":{"description":"ngrok tunnel configuration (used when `provider = \"ngrok\"`).","anyOf":[{"$ref":"#/$defs/NgrokTunnelConfig"},{"type":"null"}],"default":null},"provider":{"description":"Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.","type":"string","default":"none"},"tailscale":{"description":"Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).","anyOf":[{"$ref":"#/$defs/TailscaleTunnelConfig"},{"type":"null"}],"default":null}}},"UserPolicyConfig":{"description":"Startup user policy entry (`[[user_policies]]`).","type":"object","properties":{"blocked_patterns":{"type":"array","default":[],"items":{"type":"string"}},"projects":{"type":"array","default":[],"items":{"type":"string"}},"role":{"type":"string","default":"guest"},"user_id":{"type":"string"},"visibility_ceiling":{"type":"string","default":"private"}},"required":["user_id"]},"WacliConfig":{"description":"wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```","type":"object","properties":{"allow_unsigned_loopback":{"description":"Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).","type":"boolean","default":false},"allowed_from":{"description":"Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.","type":"array","default":["*"],"items":{"type":"string"}},"bot_jid":{"description":"Bot's own JID, used for reply-to-bot mention detection.","type":["string","null"],"default":null},"bot_lid":{"description":"The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.","type":["string","null"],"default":null},"bot_number":{"description":"Bot's own phone number (digits), used for `@` mention detection.","type":["string","null"],"default":null},"cli_path":{"description":"Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.","type":["string","null"],"default":null},"group_reply_mode":{"description":"Smart group-reply mode. When `None`, derived from `mention_only`.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"host":{"description":"REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].","type":["string","null"],"writeOnly":true},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"outbound_media_workspace_only":{"description":"Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.","type":"boolean","default":false},"port":{"description":"REMOVED: legacy JSON-RPC daemon port. See `host`.","type":["integer","null"],"format":"uint16","maximum":65535,"minimum":0,"writeOnly":true},"self_chat_mode":{"description":"Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.","type":"boolean","default":false},"store_dir":{"description":"wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.","type":["string","null"],"default":null},"webhook_listen":{"description":"Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").","type":"string","default":"127.0.0.1:16868"},"webhook_path":{"description":"HTTP path the webhook server serves (default: \"/wacli\").","type":"string","default":"/wacli"},"webhook_secret":{"description":"HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.","type":["string","null"],"default":null}}},"WebSearchConfig":{"description":"Web search tool configuration (`[web_search]` section).","type":"object","properties":{"brave_api_key":{"description":"Brave Search API key (required if provider is \"brave\")","type":["string","null"],"default":null},"fetch_max_chars":{"description":"Maximum characters returned by `web_fetch` (default 10000)","type":"integer","format":"uint","default":50000,"minimum":0},"max_results":{"description":"Maximum results per search (1-20)","type":"integer","format":"uint","default":15,"minimum":0},"provider":{"description":"Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)","type":"string","default":"duckduckgo"},"timeout_secs":{"description":"Request timeout in seconds","type":"integer","format":"uint64","default":15,"minimum":0}}},"WebhookConfig":{"description":"Webhook channel configuration.","type":"object","properties":{"port":{"description":"Port to listen on for incoming webhooks.","type":"integer","format":"uint16","maximum":65535,"minimum":0},"secret":{"description":"Optional shared secret for webhook signature verification.","type":["string","null"]}},"required":["port"]},"WhatsAppConfig":{"description":"WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.","type":"object","properties":{"access_token":{"description":"Access token from Meta Business Suite (Cloud API mode)","type":["string","null"],"default":null},"allowed_numbers":{"description":"Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"app_secret":{"description":"App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"pair_code":{"description":"Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one","type":["string","null"],"default":null},"pair_phone":{"description":"Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used","type":["string","null"],"default":null},"phone_number_id":{"description":"Phone number ID from Meta Business API (Cloud API mode)","type":["string","null"],"default":null},"read_pool_size":{"description":"Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"session_path":{"description":"Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs","type":["string","null"],"default":null},"verify_token":{"description":"Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode","type":["string","null"],"default":null},"ws_url":{"description":"WebSocket URL override (replaces WHATSAPP_WS_URL)","type":["string","null"],"default":null}}},"WorkspaceHooks":{"description":"Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).","oneOf":[{"description":"They do not run (the default); `prx doctor` and `hooks_status` say so.","type":"string","const":"off"},{"description":"They run, in a cleared environment and a dedicated directory beside\n`config.toml`.","type":"string","const":"on"}]},"WorkspaceMcpServers":{"description":"Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).","oneOf":[{"description":"None: a workspace file may only narrow the servers defined in\n`config.toml`.","type":"string","const":"off"},{"description":"HTTP servers (still refused when they target a private address).","type":"string","const":"http_only"},{"description":"HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.","type":"string","const":"stdio"}]},"XinConfig":{"description":"Configuration for the xin autonomous task engine (`[xin]`).","type":"object","properties":{"adopt_legacy_tasks":{"description":"Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).","type":"boolean","default":false},"interval_minutes":{"description":"Tick interval in minutes (minimum 1). Default: 5.","type":"integer","format":"uint32","default":5,"minimum":0},"stale_timeout_minutes":{"description":"Minutes after which a running task is marked stale. Default: 60.","type":"integer","format":"uint32","default":60,"minimum":0}}},"AgentMessaging":{"description":"Owner-controlled inbound session messaging (enabled unless explicitly off).","type":"object","properties":{"inbound":{"type":"boolean","default":true}}}}} From 07999197ea683adeda4502d4954d69971bdeb6e1 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:06:01 +0400 Subject: [PATCH 0123/1567] fix(sessions): startup wake isolation follows the live submission rule A wake recovered at gateway startup returned isolated as soon as the owner was not authenticated, before the target level was looked at. With pairing off, the same message submitted live ran unisolated for a named target at Full, because console_owner_isolated exempts a Full target. The early return is removed so the startup decision evaluates console_owner_isolated with the same inputs as the submission. An unauthenticated owner is still isolated for Main and for a target below Full; lookup failures, an unadmitted runtime and a controlled launch still isolate. --- src/gateway/api/sessions/mailbox.rs | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/gateway/api/sessions/mailbox.rs b/src/gateway/api/sessions/mailbox.rs index 334a68925..060a9531f 100644 --- a/src/gateway/api/sessions/mailbox.rs +++ b/src/gateway/api/sessions/mailbox.rs @@ -93,10 +93,12 @@ pub(in crate::gateway) async fn recover_startup(state: &AppState) { /// The isolation the owner's next submission to this session would get, /// from the current pairing and config. It evaluates the submission's own -/// rule ([`console_owner_isolated`]) with an owner-authenticated flag that is -/// true only when pairing is required, a paired token remains and the owner is -/// the install owner. Any failure (target unresolved, runtime not admitted) -/// yields isolation. +/// rule ([`console_owner_isolated`]) with the same inputs: an +/// owner-authenticated flag that is true only when pairing is required, a +/// paired token remains and the owner is the install owner, the target's +/// level and the controlled flag. An unauthenticated owner is isolated unless +/// the target runs at `Full`, exactly as on submission. Any failure (target +/// unresolved, runtime not admitted) yields isolation. fn startup_owner_isolated(state: &AppState, owner: &str, partition: &crate::memory::AgentPartition) -> bool { let owner_authenticated = state.pairing.require_pairing() && state.pairing.is_paired() @@ -104,9 +106,6 @@ fn startup_owner_isolated(state: &AppState, owner: &str, partition: &crate::memo .pairing .install_owner() .is_some_and(|install| install.as_str() == owner); - if !owner_authenticated { - return true; - } let Ok(runtime) = state.admit_turn_runtime() else { return true; }; From 010c1a8e3929e91a627580970e63a0dff3a9b27a Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:18:48 +0400 Subject: [PATCH 0124/1567] fix(config): no high-risk confirmation for config writes when the install is at Full An operator config write over HTTP or the CLI still demanded confirm_high_risk plus an If-Match revision (HTTP 428 confirmation_required, or --confirm-high-risk ) although the install ran at the Full autonomy level. When the configuration a plan is made against has autonomy.level = full (the default), the transaction no longer demands the confirmation, on every config write route and CLI command. The level is read before the change, so a write that raises the level to full from a lower one still confirms, while a write made at full, including one that lowers the level, does not. The confirm inputs (?confirm_high_risk, If-Match, --confirm-high-risk) stay accepted and are not required; a stale revision still answers 409 and --yes still gates a CLI write. The raw file secret-clear permission (--allow-credential-clear) protects stored secrets and is unchanged. Below Full nothing changes. Test fixtures that assert the confirmation now run below Full. --- docs/configuration.md | 24 +++++++++++++++++++++--- docs/rf-contract/capability-tokens.md | 7 +++++++ src/config/manage/service.rs | 10 +++++++++- src/config/manage/transaction.rs | 23 +++++++++++++++++++++-- src/gateway/api/config.rs | 2 ++ src/gateway/api/manage.rs | 2 ++ src/gateway/api/models.rs | 2 ++ src/gateway/api/providers.rs | 3 ++- src/runtime/manage_cli/section_1.rs | 2 +- src/runtime/manage_cli/section_2.rs | 27 +++++++++++++++++++++------ src/tools/gateway.rs | 4 ++++ 11 files changed, 92 insertions(+), 14 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index dc2354348..3170b4c8f 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -2698,7 +2698,7 @@ The management commands call the same service the Gateway uses, in-process: the same validation, the same plan and the same refusal text for the same change. Every mutating command prints its plan and writes nothing without `--yes`; a high-risk plan (a credential, an endpoint, a stdio MCP launch, …) -also needs `--confirm-high-risk `, where the revision is the one +also needs, below `Full`, `--confirm-high-risk `, where the revision is the one the plan printed, so a change made in between is refused (`409`-style) instead of being confirmed unseen. The CLI writes through the transaction (revision check, history record, load validation); a running PRX picks the @@ -2903,7 +2903,25 @@ Rules that hold on every endpoint: - Without `If-Match` a change is applied to whatever revision it was planned on. - The credential endpoints take no `If-Match`. -- **High-risk confirmation.** A high-risk plan answers `428` with +- **Install at `Full`: no confirmation.** When the configuration the plan + was made against has `autonomy.level = "full"` (the default), no high-risk + confirmation is demanded and no `428 confirmation_required` is returned, + on every config write route (`POST /api/config`, + `PUT /api/config/files/{name}`, `PUT /api/config/secrets`, the management + routes) and on the CLI (`prx config apply`, `prx config autonomy`, + `prx config brave-key`, `prx providers migrate --apply`, ...). The level is + read before the change: a write that raises the level from supervised or + read-only to `full` still confirms; a write made at `full`, including one + that lowers the level, does not. `?confirm_high_risk=true`, `If-Match`, + `--confirm-high-risk ` and `--allow-credential-clear` stay + accepted so existing clients and scripts keep working; the first three are + simply not required at `Full`. A stale revision still answers `409`; + `--yes` still gates a CLI write. `--allow-credential-clear` (and + `allow_secret_clear=true` on the raw file API) is not a confirmation: it + permits a raw-file replacement that would drop stored secrets and stays + required. Below `Full` the rules below apply unchanged. A rollback keeps its + own confirmation. +- **High-risk confirmation (below `Full`).** A high-risk plan answers `428` with `required`, `risk_reasons`, `revision` and the `plan` text. Examples: an endpoint change, clearing the root key, or moving the root key to another default provider (`credential_owner_changed`). To confirm, resend with @@ -3320,7 +3338,7 @@ report never changes the configured ceiling. Run `prx config brave-key --from-stdin` to inspect the current revision without reading stdin. Then pipe the key to the same command with `--yes ---confirm-high-risk REVISION`. The confirmed transaction accepts at most 16 KiB, +--confirm-high-risk REVISION` (at `Full` the flag is optional). The confirmed transaction accepts at most 16 KiB, validates the credential, and stores it through the existing secret encryption policy. The key is never a CLI argument or part of plan output. A stale revision is refused before stdin is consumed. Replacing or clearing it uses the same diff --git a/docs/rf-contract/capability-tokens.md b/docs/rf-contract/capability-tokens.md index f1c8f317c..023aa89e3 100644 --- a/docs/rf-contract/capability-tokens.md +++ b/docs/rf-contract/capability-tokens.md @@ -209,6 +209,13 @@ without a level reads back Main's level, the one it runs at. high-risk confirmation, whatever the change touches inside `agents.`. A `confirm_high_risk` query parameter on these routes is accepted and ignored. A stale or missing `If-Match` is still `409` / the refusals above. +- Config routes (`POST /api/config`, `PUT /api/config/files/{name}`, + `PUT /api/config/secrets`, `POST /api/config/apply`): when the install runs + at `autonomy.level = "full"` (the default) a high-risk change no longer + answers `428 confirmation_required`; it applies, and `confirm_high_risk` + is accepted and not required. A stale `If-Match` is still `409`. A write + that raises the level to `full` from a lower level, and any write below + `full`, still answer `428` as before. - `500 storage_unavailable`: the configuration, the registry or a reload failed. diff --git a/src/config/manage/service.rs b/src/config/manage/service.rs index 3ec054609..0ac3c6841 100644 --- a/src/config/manage/service.rs +++ b/src/config/manage/service.rs @@ -216,6 +216,14 @@ impl ManagedPlan { self.plan.summary() } + /// Whether the install runs at `Full` before this change, so that no + /// high-risk confirmation is demanded (see + /// [`ConfigPlan::applies_at_full`]). + #[must_use] + pub fn applies_at_full(&self) -> bool { + self.plan.applies_at_full() + } + /// The revision the change is based on: what a high-risk confirmation /// must name. #[must_use] @@ -545,7 +553,7 @@ impl ManagementService { actor: ConfigActor, confirmed_revision: Option<&str>, ) -> Result { - if plan.summary().risk == super::plan::ConfigChangeRisk::High { + if plan.summary().risk == super::plan::ConfigChangeRisk::High && !plan.applies_at_full() { let revision = plan.revision().map(str::to_string); match confirmed_revision { None => { diff --git a/src/config/manage/transaction.rs b/src/config/manage/transaction.rs index fafc97577..01af2e145 100644 --- a/src/config/manage/transaction.rs +++ b/src/config/manage/transaction.rs @@ -115,6 +115,20 @@ impl ConfigPlan { pub fn planned_revision(&self) -> Option<&str> { self.planned_revision.as_deref() } + + /// Whether the install this plan was made against runs at the `Full` + /// autonomy level, evaluated on the configuration before the change (a + /// write that raises the level to `Full` is judged at the lower level it + /// leaves; one that lowers it from `Full` is judged at `Full`). At + /// `Full` no high-risk confirmation is demanded; the revision guard of + /// the commit still refuses a stale write. A configuration that could + /// not be loaded is not `Full`. + #[must_use] + pub fn applies_at_full(&self) -> bool { + self.current + .as_ref() + .is_some_and(|current| current.autonomy.level == crate::security::AutonomyLevel::Full) + } } /// How the caller applies a plan. @@ -721,7 +735,10 @@ impl ConfigTransactions { // is asked of the caller: a refused model is refused, not confirmed. let warnings = check_plan_selections(&plan, actor).await?; let confined = agent.is_some_and(|agent| super::agent_scope::confines(&plan.summary, agent)); - if plan.summary.risk == ConfigChangeRisk::High && !confined { + // At an effective `Full` level nothing is confirmed: the `confirm` + // inputs stay accepted and are not required. The commit below is + // still guarded by the expected revision (a stale write is a 409). + if plan.summary.risk == ConfigChangeRisk::High && !confined && !plan.applies_at_full() { if !options.confirm_high_risk { return Err(ConfigTransactionError::ConfirmationRequired { required: "confirm_high_risk", @@ -1497,7 +1514,9 @@ mod tests { /// real load path, with the refusing participant registered. async fn fixture() -> Fixture { let dir = tempfile::TempDir::new().expect("test: temp dir"); - let config = fixture::config_in(dir.path()); + let mut config = fixture::config_in(dir.path()); + // The confirmation tests exercise the rule below Full (at Full none is demanded). + config.autonomy.level = crate::security::AutonomyLevel::Supervised; crate::config::files::write_split_config(&config, false) .await .expect("test: write split fixture"); diff --git a/src/gateway/api/config.rs b/src/gateway/api/config.rs index 8a1586e58..082e002be 100644 --- a/src/gateway/api/config.rs +++ b/src/gateway/api/config.rs @@ -1151,6 +1151,8 @@ mod tests { let mut config = Config::default(); config.config_path = dir.path().join("config.toml"); config.workspace_dir = dir.path().join("workspace"); + // The confirmation tests exercise the rule below Full (at Full none is demanded). + config.autonomy.level = AutonomyLevel::Supervised; mutate(&mut config); config.save().await.expect("test: save initial config"); let loaded = Config::load_from_path(&config.config_path, config.workspace_dir.clone()) diff --git a/src/gateway/api/manage.rs b/src/gateway/api/manage.rs index 9eb01da0e..c849808e2 100644 --- a/src/gateway/api/manage.rs +++ b/src/gateway/api/manage.rs @@ -1396,6 +1396,8 @@ mod tests { async fn with_agent() -> Served { serve_config(|config| { + // The confirmation tests exercise the rule below Full. + config.autonomy.level = crate::security::policy::AutonomyLevel::Supervised; config.agents.insert( "coder".into(), serde_json::from_value(json!({"provider": "openai", "model": "gpt-4o"})).expect("test: agent"), diff --git a/src/gateway/api/models.rs b/src/gateway/api/models.rs index c976c65ca..eac1718f9 100644 --- a/src/gateway/api/models.rs +++ b/src/gateway/api/models.rs @@ -564,6 +564,8 @@ mod tests { async fn switching_the_default_away_from_the_root_key_needs_the_choice_and_confirmation() { const KEY: &str = "pmmf-root-key-sentinel"; let served = serve_config(|config| { + // The confirmation is demanded below Full only. + config.autonomy.level = crate::security::policy::AutonomyLevel::Supervised; config.api_key = Some(KEY.into()); declare_chat_model(config, "anthropic", "claude-sonnet-4-5"); }) diff --git a/src/gateway/api/providers.rs b/src/gateway/api/providers.rs index a4793a553..2ef117879 100644 --- a/src/gateway/api/providers.rs +++ b/src/gateway/api/providers.rs @@ -636,7 +636,8 @@ mod tests { /// revision is a conflict, and only the reported revision applies it. #[tokio::test] async fn a_high_risk_confirmation_is_bound_to_the_reported_revision() { - let served = serve_config(|_| {}).await; + // The confirmation is demanded below Full only. + let served = serve_config(|config| config.autonomy.level = AutonomyLevel::Supervised).await; let before = served.disk(); let body = json!({"api_url": "https://proxy.example/v1"}); diff --git a/src/runtime/manage_cli/section_1.rs b/src/runtime/manage_cli/section_1.rs index cc0326336..f5363f123 100644 --- a/src/runtime/manage_cli/section_1.rs +++ b/src/runtime/manage_cli/section_1.rs @@ -110,7 +110,7 @@ async fn finish(service: &ManagementService, plan: ManagedPlan, apply: &ApplyArg return Ok(()); } let revision = plan.revision().unwrap_or("none").to_string(); - let high_risk = !plan.summary().risk_reasons.is_empty(); + let high_risk = !plan.summary().risk_reasons.is_empty() && !plan.applies_at_full(); if !apply.yes { if high_risk { writeln!( diff --git a/src/runtime/manage_cli/section_2.rs b/src/runtime/manage_cli/section_2.rs index 912d443b6..7127f3a1c 100644 --- a/src/runtime/manage_cli/section_2.rs +++ b/src/runtime/manage_cli/section_2.rs @@ -9,16 +9,29 @@ pub(crate) async fn run_config(command: ConfigCommands, config: Config, io: &mut Ok(()) } ConfigCommands::BraveKey { from_stdin: _, apply } => { + // At Full the confirmation flag is accepted but not required. + let at_full = config.autonomy.level == openprx::security::AutonomyLevel::Full; let service = service(config); let revision = service.revision().unwrap_or_else(|| "none".to_owned()); - if !apply.yes || apply.confirm_high_risk.is_none() { - writeln!( - io.out, - "Dry run: stdin was not read. Set web_search.brave_api_key with --from-stdin --yes --confirm-high-risk {revision}" - )?; + if !apply.yes || (!at_full && apply.confirm_high_risk.is_none()) { + if at_full { + writeln!( + io.out, + "Dry run: stdin was not read. Set web_search.brave_api_key with --from-stdin --yes" + )?; + } else { + writeln!( + io.out, + "Dry run: stdin was not read. Set web_search.brave_api_key with --from-stdin --yes --confirm-high-risk {revision}" + )?; + } return Ok(()); } - if apply.confirm_high_risk.as_deref() != Some(revision.as_str()) { + if apply + .confirm_high_risk + .as_deref() + .is_some_and(|confirmed| confirmed != revision) + { bail!("the configuration revision changed; rerun the dry run before supplying a credential"); } let mut value = String::new(); @@ -352,6 +365,8 @@ mod tests { default_model: Some("gpt-4o".into()), ..Config::default() }; + // The confirmation tests exercise the rule below Full (at Full none is demanded). + config.autonomy.level = openprx::security::AutonomyLevel::Supervised; edit(&mut config); config.save().await.expect("test: save"); let loaded = reload(&dir).await; diff --git a/src/tools/gateway.rs b/src/tools/gateway.rs index 31b724867..bdc563863 100644 --- a/src/tools/gateway.rs +++ b/src/tools/gateway.rs @@ -1157,6 +1157,8 @@ mod tests { credential_ref: None, }]; cfg.memory.auto_save = !Config::default().memory.auto_save; + // The confirmation tests exercise the rule below Full (at Full none is demanded). + cfg.autonomy.level = crate::security::AutonomyLevel::Supervised; crate::config::files::write_split_config(&cfg, false).await.unwrap(); assert!( std::fs::read_to_string(tmp.path().join("config.d/routing.toml")) @@ -1393,6 +1395,7 @@ mod tests { config_path: tmp.path().join("config.toml"), ..Config::default() }; + cfg.autonomy.level = crate::security::AutonomyLevel::Supervised; cfg.model_routes = vec![crate::config::ModelRouteConfig { settings: Default::default(), hint: "fast".into(), @@ -1455,6 +1458,7 @@ mod tests { api_key: Some("sentinel-root-owner-key".into()), ..Config::default() }; + cfg.autonomy.level = crate::security::AutonomyLevel::Supervised; cfg.providers.models = vec![crate::config::schema::ProviderModelConfig { provider: "anthropic".into(), model: Some("claude-sonnet-4-5".into()), From dd88fcf766e83b77a5647fef2ad6a4564b499c6f Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:39:34 +0400 Subject: [PATCH 0125/1567] feat(config): named agents are agentic by default and an empty allowed_tools means all tools A hand-written [agents.x] that omitted agentic got no tools even at Full, and an agentic agent with an empty allowed_tools refused to load. agentic now defaults to true; an explicit agentic = false stays the operator's answer-only switch. An agentic agent with an empty or omitted allowed_tools loads and means all tools, the same as ["*"]: the config validator no longer refuses it, targeted turns and delegate runs inherit every tool instead of failing, and the agent readback reports the wildcard for it. The management API contract is unchanged: tools stays required and agentic is still set from it, so "tools": [] yields a non-agentic agent. An existing config that omits agentic now gives its named agents tools. Documented default, schema fixture and migration note updated. --- docs/configuration.md | 4 +++- docs/migration-unreleased.md | 1 + src/config/schema/lifecycle.rs | 4 +--- src/config/schema/providers.rs | 12 +++++++++--- src/config/schema/tests/agent_features.rs | 5 ++--- src/gateway/api/agents.rs | 7 ++++++- src/gateway/api/sessions/target.rs | 5 +++-- src/tools/delegate.rs | 19 +++---------------- tests/fixtures/config-schema.json | 2 +- 9 files changed, 29 insertions(+), 30 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 3170b4c8f..08a192013 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -148,7 +148,7 @@ and the module-gate family are absorbed on load; they are not live switches. | `[cost]` | `daily_limit_usd = 10.0`; `monthly_limit_usd = 100.0`; `warn_at_percent = 80`; `allow_override = false`; `prices = {}` (each price: `input`/`output`/`cache_write`/`cache_read = 0`) | | `[nodes]` | `request_timeout_ms = 15000`; `retry_max = 2`; `nodes = []`. A node: `id`, `endpoint`, `bearer_token` required; `hmac_secret` unset; `timeout_ms`/`retry_max` unset | | `[nodes.server]` | `listen_addr = "127.0.0.1:8787"`; `bearer_token = ""`; `hmac_secret` unset; `sandbox_root = "."`; `exec_timeout_ms = 15000`; `max_output_bytes = 1048576`; `max_concurrent_tasks = 8`; `task_result_ttl_ms = 3600000`; `allowed_commands = ["echo"]`; `blocked_commands = []`; `tls_required = true`; `tls_cert`/`tls_key` unset | -| `[agents.]` | `provider`/`model` required; `system_prompt`/`api_key`/`credential_ref`/`temperature`/`identity_dir`/`memory_scope`/`spawn_enabled`/`autonomy` unset; `max_depth = 8`; `agentic = false`; `allowed_tools = []`; `enabled = true` | +| `[agents.]` | `provider`/`model` required; `system_prompt`/`api_key`/`credential_ref`/`temperature`/`identity_dir`/`memory_scope`/`spawn_enabled`/`autonomy` unset; `max_depth = 8`; `agentic = true`; `allowed_tools = []` (empty means all tools, the same as `["*"]`); `enabled = true` | | `[media]` | `audio_provider = "none"`; `audio_model = "whisper"`; `audio_ollama_url = "http://localhost:11434"`; `video_provider = "none"`; `video_max_frames = 4`; `max_audio_size_mb = 20`; `max_video_size_mb = 50` | | `[decision_engine]` | `enabled = false`; `mode = "pre"`; `prompt_budget_tokens = 300`; `candidates = 5`; `timeout_ms = 1500`; `telemetry_cap = 1000`; `observe_queue = 64`; `latency_budget_ms = 500`; `token_ratio_limit = 0.35`; `max_candidates = 12`; `backend` unset | | `[decision_engine.backend]` | optional; absent = `kind = "auto"`, `remote_enabled = false`, `endpoint = ""`, `model = ""`, `pinned_snapshot = ""`, `credential_ref` unset, `timeout_ms = 250`, `max_request_bytes = 65536`, `max_response_bytes = 262144`, `circuit_breaker = { failure_threshold = 5, cooldown_secs = 60 }` | @@ -829,6 +829,8 @@ max_cost_per_day_cents = 500 [agents.researcher] provider = "anthropic" model = "claude-sonnet-4-6" +# agentic defaults to true; `agentic = false` makes the agent answer-only +# with no tools. An empty or omitted allowed_tools means all tools. agentic = true allowed_tools = ["web_search", "file_read"] # Targeted turns (`agent` on POST /api/sessions/{id}/message, needs diff --git a/docs/migration-unreleased.md b/docs/migration-unreleased.md index 8cd7b48a8..c58aed5cf 100644 --- a/docs/migration-unreleased.md +++ b/docs/migration-unreleased.md @@ -22,6 +22,7 @@ of the [changelog](../CHANGELOG.md). | Advisory decision engine | `[decision_engine]` defaults to `enabled = false`. Off means no analysis, brief, telemetry store, or outcome writes. The engine never selects tools or grants approval, and admission does not depend on it. Set `enabled = true` and restart only to opt into bounded pre-turn briefs and/or outcome telemetry. See [the decision engine](decision-engine.md). | To use the advisory engine | | Recovery keys and database backup | SQLite recovery keys live in `.recovery_keys` beside the database. A usable backup is a consistent snapshot of that database (the runtime writes it with `VACUUM INTO`, never a live write-ahead-log copy) plus every key generation the snapshot names, published as one completed bundle. Copy that completed bundle. A database without those keys cannot recover. Keys without that database do not start a new authority. Incomplete backup directories are refused. | Before any backup or host move | | Targeted gateway agents | `[gateway] targeted_agents` defaults to `true`: a named `agent` on `POST /api/sessions/{id}/message`, and a session message that wakes a named agent, now run as that agent with its own partitioned history. A config that sets the key explicitly is unchanged; set `targeted_agents = false` to get 409 `agent_disabled` again. A config that omits the key now accepts named targets. | Only to refuse named targets | +| Named agents are agentic by default | `[agents.] agentic` defaults to `true`, and an agentic agent with an empty or omitted `allowed_tools` means all tools (the same as `["*"]`); such a config now loads. An existing config that omits `agentic` now gives its named agents tools: targeted turns, `delegate` and `sessions_spawn` runs with that agent get every tool their level allows instead of answering without tools. An explicit `agentic = false` keeps the answer-only, no-tools behavior. `PUT /api/agents/{name}` is unchanged (`tools` required, `agentic` is set from `tools`; `"tools": []` still yields a non-agentic agent). | Only to keep a named agent answer-only: set `agentic = false` | | `prx agent` removed | `prx agent` is gone (clap reports an unknown subcommand). Use `prx chat --message ` (`-q`): the reply alone on stdout, exit 0, 2 on a policy refusal, 1 on failure; the turn is not saved unless `--save` or `--session` is given; `--workdir` moved to `prx chat`. Scripts and cron commands that call `prx agent` must be updated. | Only if you script `prx agent` | | Quiet CLI logs | Foreground commands (`prx chat`, `prx go`, `prx doctor`, `prx status`, and other non-service commands) default to `warn` on stderr when `RUST_LOG` is unset, so stdout stays the product. `prx daemon`, `prx gateway`, and `prx channel start` keep `info`. A set `RUST_LOG` wins when it parses; an unparseable value falls back to that command default. Interactive `prx chat` writes the same default filter to `chat.log`; if that file cannot be opened, tracing stays on stderr. | If a script parsed tracing from stdout | | Retired `[router]` continuation table | The retired continuation table under `[router]` is ignored with one warning at load; delete it. Turns keep the serving model's reply. Authenticated historical v1 replies remain readable. | Only if that table is still in the file | diff --git a/src/config/schema/lifecycle.rs b/src/config/schema/lifecycle.rs index a1db739a0..38e088374 100644 --- a/src/config/schema/lifecycle.rs +++ b/src/config/schema/lifecycle.rs @@ -844,9 +844,7 @@ impl Config { .map(|tool| tool.trim()) .filter(|tool| !tool.is_empty()) .collect::>(); - if allowed_tools.is_empty() { - anyhow::bail!("agents.{name}.allowed_tools must not be empty when agentic=true"); - } + // An empty list means all tools, the same as `["*"]`. if allowed_tools.contains(&"*") && allowed_tools.len() != 1 { anyhow::bail!("agents.{name}.allowed_tools must use '*' exclusively"); } diff --git a/src/config/schema/providers.rs b/src/config/schema/providers.rs index 869167218..ae1b8dc73 100644 --- a/src/config/schema/providers.rs +++ b/src/config/schema/providers.rs @@ -75,10 +75,12 @@ pub struct DelegateAgentConfig { /// Max recursion depth for nested delegation #[serde(default = "default_max_depth")] pub max_depth: u32, - /// Enable agentic sub-agent mode (multi-turn tool-call loop). - #[serde(default)] + /// Agentic sub-agent mode (multi-turn tool-call loop). Default true; an + /// explicit `false` makes the agent answer-only with no tools. + #[serde(default = "default_agentic")] pub agentic: bool, /// Allowlist of tool names available to the sub-agent in agentic mode. + /// Empty or omitted means all tools, the same as `["*"]`. #[serde(default)] pub allowed_tools: Vec, /// Optional identity files directory relative to workspace root. @@ -119,7 +121,7 @@ impl DelegateAgentConfig { credential_ref: None, temperature: None, max_depth: default_max_depth(), - agentic: false, + agentic: default_agentic(), allowed_tools: Vec::new(), identity_dir: None, memory_scope: None, @@ -130,6 +132,10 @@ impl DelegateAgentConfig { } } +pub(super) const fn default_agentic() -> bool { + true +} + pub(super) const fn default_agent_enabled() -> bool { true } diff --git a/src/config/schema/tests/agent_features.rs b/src/config/schema/tests/agent_features.rs index 5f3af1d90..e81f54dbb 100644 --- a/src/config/schema/tests/agent_features.rs +++ b/src/config/schema/tests/agent_features.rs @@ -4,14 +4,13 @@ use super::*; use tokio::test; #[test] -async fn config_rejects_empty_agentic_delegate_allowlist() { +async fn config_accepts_empty_agentic_delegate_allowlist_as_all_tools() { let mut config = Config::default(); config .agents .insert("worker".into(), agentic_delegate_config(Vec::new())); - let error = config.validate().unwrap_err().to_string(); - assert!(error.contains("agents.worker.allowed_tools must not be empty")); + config.validate().expect("test: an empty allowlist means all tools"); } #[test] diff --git a/src/gateway/api/agents.rs b/src/gateway/api/agents.rs index 2ff06c9e5..2f72ab6ed 100644 --- a/src/gateway/api/agents.rs +++ b/src/gateway/api/agents.rs @@ -308,7 +308,12 @@ fn named_readback( (incarnation, retired): (String, bool), ) -> Readback { let tools = if agent.agentic { - agent.allowed_tools.clone() + if agent.allowed_tools.iter().all(|tool| tool.trim().is_empty()) { + // Empty means all tools: report it as the wildcard. + vec!["*".to_owned()] + } else { + agent.allowed_tools.clone() + } } else { Vec::new() }; diff --git a/src/gateway/api/sessions/target.rs b/src/gateway/api/sessions/target.rs index 90927d207..d5da3680e 100644 --- a/src/gateway/api/sessions/target.rs +++ b/src/gateway/api/sessions/target.rs @@ -157,10 +157,11 @@ fn allowlist_for(agent: &DelegateAgentConfig) -> Result>(); - let inherit_all = answer_only || full || requested.contains("*"); - if !answer_only && !full && inherit_all && requested.len() != 1 { + // An empty `allowed_tools` means all tools, the same as `["*"]`. + let inherit_all = answer_only || full || requested.is_empty() || requested.contains("*"); + if !answer_only && !full && requested.contains("*") && requested.len() != 1 { return Ok(DelegateAgenticExecution { child_terminal_committed: false, result: ToolResult { diff --git a/tests/fixtures/config-schema.json b/tests/fixtures/config-schema.json index 6c8679395..df17245bc 100644 --- a/tests/fixtures/config-schema.json +++ b/tests/fixtures/config-schema.json @@ -1 +1 @@ -{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Config","description":"Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).","type":"object","properties":{"a2a":{"description":"Agent-to-Agent compatibility configuration (`[a2a]`).","$ref":"#/$defs/A2aConfig","default":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trusted_trust_domains":[],"trust_domain":"prx.local"}},"agent":{"description":"Agent orchestration settings (`[agent]`).","$ref":"#/$defs/AgentConfig","default":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2,"messaging":{"inbound":true}}},"agents":{"description":"Delegate agent configurations for multi-agent workflows.","type":"object","additionalProperties":{"$ref":"#/$defs/DelegateAgentConfig"},"default":{}},"api_key":{"description":"API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.","type":["string","null"],"default":null},"api_url":{"description":"Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)","type":["string","null"],"default":null},"auth":{"description":"Auth profile and external credential import settings (`[auth]`).","$ref":"#/$defs/AuthConfig","default":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"}},"autonomy":{"description":"Autonomy and security policy configuration (`[autonomy]`).","$ref":"#/$defs/AutonomyConfig","default":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":500,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true}},"browser":{"description":"Browser automation configuration (`[browser]`).","$ref":"#/$defs/BrowserConfig","default":{"allowed_domains":[],"computer_use":{"api_key":null}}},"channels_config":{"description":"Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).","$ref":"#/$defs/ChannelsConfig","default":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null}},"chat":{"description":"Interactive chat UI configuration (`[chat]`).","$ref":"#/$defs/ChatConfig","default":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2}},"compliance":{"description":"Operator-owned compliance controls (`[compliance]`).","$ref":"#/$defs/ComplianceConfig","default":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}},"composio":{"description":"Composio managed OAuth tools integration (`[composio]`).","$ref":"#/$defs/ComposioConfig","default":{"api_key":null,"entity_id":"default"}},"cost":{"description":"Cost tracking and budget enforcement configuration (`[cost]`).","$ref":"#/$defs/CostConfig","default":{"allow_override":false,"daily_limit_usd":10.0,"monthly_limit_usd":100.0,"prices":{},"warn_at_percent":80}},"cron":{"description":"Cron job configuration (`[cron]`).","$ref":"#/$defs/CronConfig","default":{"max_run_history":50}},"decision_engine":{"description":"Optional advisory decision engine, disabled by default.","$ref":"#/$defs/DecisionEngineConfig","default":{"candidates":5,"enabled":false,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"latency_budget_ms":500,"max_candidates":12,"token_ratio_limit":0.3499999940395355}},"default_model":{"description":"Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.","type":["string","null"]},"default_provider":{"description":"Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.","type":["string","null"]},"default_temperature":{"description":"Default model temperature (0.0–2.0). Default: `0.7`.","type":"number","format":"double","default":0.7},"embedding_routes":{"description":"Embedding routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/EmbeddingRouteConfig"}},"gateway":{"description":"Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).","$ref":"#/$defs/GatewayConfig","default":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60}},"heartbeat":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]`).","$ref":"#/$defs/HeartbeatConfig","default":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."}},"http_request":{"description":"HTTP request tool configuration (`[http_request]`).","$ref":"#/$defs/HttpRequestConfig","default":{"max_response_size":1000000,"timeout_secs":30}},"identity":{"description":"Identity format configuration: OpenClaw or AIEOS (`[identity]`).","$ref":"#/$defs/IdentityConfig","default":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"}},"identity_bindings":{"description":"Static identity bindings loaded at startup (`[[identity_bindings]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/IdentityBindingConfig"}},"mcp":{"description":"Secrets encryption configuration (`[secrets]`).","$ref":"#/$defs/McpConfig","default":{"servers":{}}},"mcp_server":{"description":"MCP server compatibility configuration (`[mcp_server]`).","$ref":"#/$defs/McpServerRuntimeConfig","default":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true}},"media":{"description":"Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.","$ref":"#/$defs/MediaConfig","default":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"}},"memory":{"description":"Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).","$ref":"#/$defs/MemoryConfig","default":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7}},"model_routes":{"description":"Model routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/ModelRouteConfig"}},"model_settings":{"description":"Catalog model levels and explicit parameters, keyed by canonical release ID.","type":"object","additionalProperties":{"$ref":"#/$defs/ModelSettings"},"default":{}},"multimodal":{"description":"Multimodal (image) handling configuration (`[multimodal]`).","$ref":"#/$defs/MultimodalConfig","default":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4}},"nodes":{"description":"Remote node proxy configuration (`[nodes]`).","$ref":"#/$defs/NodesConfig","default":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}},"observability":{"description":"Observability backend configuration (`[observability]`).","$ref":"#/$defs/ObservabilityConfig","default":{"backend":"none","otel_endpoint":null,"otel_service_name":null}},"plugins":{"description":"WASM plugin runtime switch (`[plugins]`), off by default.","$ref":"#/$defs/PluginsConfig","default":{"enabled":false}},"providers":{"description":"Provider-specific runtime options (`[providers.]`).","$ref":"#/$defs/ProvidersConfig","default":{"ollama":{"num_ctx":null}}},"proxy":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).","$ref":"#/$defs/ProxyConfig","default":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]}},"query_classification":{"description":"Automatic query classification — maps user messages to model hints.","$ref":"#/$defs/QueryClassificationConfig","default":{"rules":[]}},"reliability":{"description":"Reliability settings: retries, fallback providers, backoff (`[reliability]`).","$ref":"#/$defs/ReliabilityConfig","default":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2}},"router":{"description":"Heuristic LLM router configuration (`[router]`).","$ref":"#/$defs/RouterConfig","default":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]}},"runtime":{"description":"Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.","$ref":"#/$defs/RuntimeConfig","default":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null}},"scheduler":{"description":"Scheduler configuration for periodic task execution (`[scheduler]`).","$ref":"#/$defs/SchedulerConfig","default":{"claim_lease_secs":90,"max_tasks":64}},"secrets":{"$ref":"#/$defs/SecretsConfig","default":{"encrypt":true}},"security":{"description":"Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).","$ref":"#/$defs/SecurityConfig","default":{"audit":{"log_path":"audit.log","max_size_mb":100}}},"self_system":{"description":"Self-system experimental automation controls (`[self_system]`).","$ref":"#/$defs/SelfSystemConfig","default":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24}},"sessions_spawn":{"description":"Session spawning configuration (`[sessions_spawn]`).","$ref":"#/$defs/SessionsSpawnConfig","default":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null}},"skill_rag":{"description":"Dynamic skill retrieval settings (`[skill_rag]`).","$ref":"#/$defs/SkillRagConfig","default":{"top_k":32}},"skills":{"description":"Skills loading and community repository behavior (`[skills]`).","$ref":"#/$defs/SkillsConfig","default":{"open_skills_dir":null,"openclaw_skills_dir":null}},"skills_lifecycle":{"description":"Skill lifecycle (`[skills_lifecycle]`), off by default.","$ref":"#/$defs/SkillsLifecycleConfig","default":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]}},"smart_group":{"description":"Smart group-reply pre-gate configuration (`[smart_group]`).","$ref":"#/$defs/SmartGroupConfig","default":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5}},"storage":{"description":"Persistent storage provider configuration (`[storage]`).","$ref":"#/$defs/StorageConfig","default":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"task_routing":{"description":"Task routing configuration — classifies work by intent before the main agent loop.","$ref":"#/$defs/TaskRoutingConfig","default":{"default_intent":"simple","rules":[]}},"tool_tiering":{"description":"Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).","$ref":"#/$defs/ToolTieringConfig","default":{"always_exclude":[],"always_include":[],"channel_exclude":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","skills_manage","memory_reindex","document_sync","document_ingest"]}},"tunnel":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]`).","$ref":"#/$defs/TunnelConfig","default":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null}},"user_policies":{"description":"Static user policy records loaded at startup (`[[user_policies]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/UserPolicyConfig"}},"web_search":{"description":"Web search tool configuration (`[web_search]`).","$ref":"#/$defs/WebSearchConfig","default":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15}},"webhook":{"description":"Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).","$ref":"#/$defs/MemoryWebhookConfig","default":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null}},"xin":{"description":"Xin autonomous task engine configuration (`[xin]`).","$ref":"#/$defs/XinConfig","default":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}}},"$defs":{"A2aConfig":{"type":"object","properties":{"agent_id":{"description":"Stable PRX agent identifier advertised to peers.","type":"string","default":"prx-default"},"allowed_peer_issuers":{"description":"Accepted external peer issuers.","type":"array","default":[],"items":{"type":"string"}},"bind":{"description":"Advertised bind address.","type":"string","default":"127.0.0.1:16832"},"card_jwks_uri":{"description":"Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.","type":["string","null"],"default":null},"card_signing_key_path":{"description":"On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).","type":["string","null"],"default":null},"card_ttl_seconds":{"description":"Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.","type":"integer","format":"uint64","default":3600,"minimum":0},"discovery_advertised":{"description":"Whether to advertise into an external A2A registry.","type":"boolean","default":false},"handoff_nonce_ttl_seconds":{"description":"Replay window for future handoff delegation tokens.","type":"integer","format":"uint64","default":3600,"minimum":0},"messaging_enabled":{"description":"Enable the dedicated pinned mTLS messaging listener.","type":"boolean","default":false},"peers":{"type":"object","additionalProperties":{"$ref":"#/$defs/A2aPeer"},"default":{}},"spiffe_id":{"description":"Local SPIFFE-style identifier placeholder.","type":"string","default":"spiffe://prx-local/agent/prx-default"},"spiffe_strict_validation":{"description":"When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.","type":"boolean","default":false},"spiffe_trust_bundle_pem":{"description":"Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).","type":["string","null"],"default":null},"trusted_trust_domains":{"description":"Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).","type":"array","default":[],"items":{"type":"string"}},"trust_domain":{"description":"SPIFFE trust domain for new instance identities.","type":"string","default":"prx.local"}}},"A2aPeer":{"description":"Explicit pinned identity and local recipient grant.","type":"object","properties":{"spiffe_id":{"type":"string"},"fingerprints":{"type":"array","items":{"type":"string"}},"address":{"type":"string"},"owner":{"type":"string"},"sessions":{"type":"array","default":["*"],"items":{"type":"string"}},"agents":{"type":"array","default":["*"],"items":{"type":"string"}}},"required":["spiffe_id","fingerprints","address","owner"],"additionalProperties":false},"AgentCompactionConfig":{"description":"Agent context compaction configuration (`[agent.compaction]`).","type":"object","properties":{"keep_recent_messages":{"description":"Number of recent non-system messages to keep after compaction.","type":"integer","format":"uint","default":12,"minimum":0},"max_context_tokens":{"description":"Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.","type":"integer","format":"uint","default":128000,"minimum":0},"memory_flush":{"description":"Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.","type":"boolean","default":true},"mode":{"description":"Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).","$ref":"#/$defs/AgentCompactionMode","default":"switch"},"os_paging":{"description":"Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.","$ref":"#/$defs/OsPagingConfig","default":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"}},"reserve_tokens":{"description":"Tokens reserved for the next model response.","type":"integer","format":"uint","default":4096,"minimum":0}}},"AgentCompactionMode":{"description":"Compaction mode for long conversation contexts.","oneOf":[{"description":"Disable proactive compaction.","type":"string","const":"off"},{"description":"Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.","type":"string","const":"switch"},{"description":"Conservative compaction that prefers summary replacement.","type":"string","const":"safeguard"},{"description":"Aggressive truncation mode for tighter contexts.","type":"string","const":"aggressive"}]},"AgentConfig":{"description":"Agent orchestration configuration (`[agent]` section).","type":"object","properties":{"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"compact_context":{"description":"When true: bootstrap_max_chars=6000. Use for 13B or smaller models.","type":"boolean","default":false},"compaction":{"description":"Context compaction controls (`[agent.compaction]`).","$ref":"#/$defs/AgentCompactionConfig","default":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096}},"low_priority_tools":{"description":"Tool names treated as low-priority when `priority_scheduling_enabled = true`.","type":"array","default":["sessions_spawn","delegate"],"items":{"type":"string"}},"priority_scheduling_enabled":{"description":"Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.","type":"boolean","default":false},"read_only_tool_concurrency_window":{"description":"Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.","type":"integer","format":"uint","default":2,"minimum":0},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}}},"AgentLimits":{"description":"Optional admission limits for rf-started turns of a named agent.","type":"object","properties":{"max_concurrent_turns":{"type":["integer","null"],"format":"uint32","minimum":0},"max_cost_per_day_cents":{"type":["integer","null"],"format":"uint64","minimum":0}},"additionalProperties":false},"AuditConfig":{"description":"Audit logging configuration","type":"object","properties":{"log_path":{"description":"Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).","type":"string","default":"audit.log"},"max_size_mb":{"description":"Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).","type":"integer","format":"uint32","default":100,"minimum":0}}},"AuthConfig":{"description":"Authentication and external credential import configuration (`[auth]` section).","type":"object","properties":{"codex_auth_json_auto_import":{"description":"Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.","type":"boolean","default":false},"codex_auth_json_path":{"description":"Source path for Codex CLI auth.json import.","type":"string","default":"~/.codex/auth.json"}}},"AutonomyConfig":{"type":"object","properties":{"acknowledge_unrestricted_profile":{"description":"Operator acknowledgement for an intentionally unrestricted profile.\nThis suppresses doctor noise only; it does not alter policy behavior.","type":"boolean","default":false},"forbidden_paths":{"description":"Explicit path denylist. Default includes system-critical paths.\n\nFails closed: omitting the key keeps the built-in list rather than\nemptying it, so a partial `[autonomy]` section never removes the\ndenylist.","type":"array","default":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"items":{"type":"string"}},"level":{"description":"Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).","$ref":"#/$defs/AutonomyLevel","default":"full"},"max_cost_per_day_cents":{"description":"Maximum cost per day in cents per policy. Default: `500`.","type":"integer","format":"uint32","default":500,"minimum":0},"scopes":{"description":"Scope-based tool access control: per-user/channel/chat-type allow/deny rules.","$ref":"#/$defs/ScopeConfig","default":{"assign_owners":[],"default":"allow","rules":[]}},"workspace_only":{"description":"Restrict file writes and command paths to the workspace directory. Default: `true`.\n\nFails closed: a `[autonomy]` section that omits this key keeps the\nworkspace restriction on, so a partial section can never widen the\nfilesystem reach by accident.","type":"boolean","default":true}}},"AutonomyLevel":{"description":"How much autonomy the agent has","oneOf":[{"description":"Read-only: can observe but not act","type":"string","const":"readonly"},{"description":"Supervised: acts but requires approval for risky operations","type":"string","const":"supervised"},{"description":"Full: autonomous execution within policy bounds","type":"string","const":"full"}]},"BackendSelection":{"description":"Which decision backend runs: `auto` (the factory's order) or one kind.","type":"string"},"BrowserComputerUseConfig":{"description":"Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.","type":"object","properties":{"api_key":{"description":"Optional bearer token (retained only for config secret handling).","type":["string","null"],"default":null}}},"BrowserConfig":{"description":"Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.","type":"object","properties":{"allowed_domains":{"description":"Allowed domains for `web_fetch` (exact or subdomain match).","type":"array","default":[],"items":{"type":"string"}},"computer_use":{"description":"Computer-use sidecar config (retained only for `api_key` secret handling).","$ref":"#/$defs/BrowserComputerUseConfig","default":{"api_key":null}}}},"ChannelsConfig":{"description":"Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.","type":"object","properties":{"cli":{"description":"Enable the CLI interactive channel. Default: `true`.","type":"boolean","default":true},"dingtalk":{"description":"DingTalk channel configuration.","anyOf":[{"$ref":"#/$defs/DingTalkConfig"},{"type":"null"}]},"discord":{"description":"Discord bot channel configuration.","anyOf":[{"$ref":"#/$defs/DiscordConfig"},{"type":"null"}]},"email":{"description":"Email channel configuration.","anyOf":[{"$ref":"#/$defs/EmailConfig"},{"type":"null"}]},"imessage":{"description":"iMessage channel configuration (macOS only).","anyOf":[{"$ref":"#/$defs/IMessageConfig"},{"type":"null"}]},"irc":{"description":"IRC channel configuration.","anyOf":[{"$ref":"#/$defs/IrcConfig"},{"type":"null"}]},"lark":{"description":"Lark/Feishu channel configuration.","anyOf":[{"$ref":"#/$defs/LarkConfig"},{"type":"null"}]},"linq":{"description":"Linq Partner API channel configuration.","anyOf":[{"$ref":"#/$defs/LinqConfig"},{"type":"null"}]},"mattermost":{"description":"Mattermost bot channel configuration.","anyOf":[{"$ref":"#/$defs/MattermostConfig"},{"type":"null"}]},"nextcloud_talk":{"description":"Nextcloud Talk bot channel configuration.","anyOf":[{"$ref":"#/$defs/NextcloudTalkConfig"},{"type":"null"}]},"qq":{"description":"QQ Official Bot channel configuration.","anyOf":[{"$ref":"#/$defs/QQConfig"},{"type":"null"}]},"ramflux":{"description":"Local ramflux agent-host bridge.","anyOf":[{"$ref":"#/$defs/RamfluxConfig"},{"type":"null"}],"default":null},"signal":{"description":"Signal channel configuration.","anyOf":[{"$ref":"#/$defs/SignalConfig"},{"type":"null"}]},"slack":{"description":"Slack bot channel configuration.","anyOf":[{"$ref":"#/$defs/SlackConfig"},{"type":"null"}]},"telegram":{"description":"Telegram bot channel configuration.","anyOf":[{"$ref":"#/$defs/TelegramConfig"},{"type":"null"}]},"wacli":{"description":"wacli JSON-RPC daemon channel configuration.","anyOf":[{"$ref":"#/$defs/WacliConfig"},{"type":"null"}],"default":null},"webhook":{"description":"Webhook channel configuration.","anyOf":[{"$ref":"#/$defs/WebhookConfig"},{"type":"null"}]},"whatsapp":{"description":"WhatsApp channel configuration (Cloud API or Web mode).","anyOf":[{"$ref":"#/$defs/WhatsAppConfig"},{"type":"null"}]}}},"ChatConfig":{"description":"Interactive chat configuration (`[chat]`).","type":"object","properties":{"daemon":{"description":"How this chat process reaches the daemon it borrows channels from.","$ref":"#/$defs/ChatDaemonConfig","default":{"token":"","url":""}},"max_concurrent_visible_turns":{"description":"Maximum concurrent visible provider turns in the TUI Redux driver.","type":"integer","format":"uint","default":2,"minimum":0}}},"ChatDaemonConfig":{"description":"Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.","type":"object","properties":{"token":{"description":"Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.","type":"string","default":""},"url":{"description":"Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.","type":"string","default":""}}},"CircuitBreakerConfig":{"description":"The per-backend circuit breaker.","type":"object","properties":{"cooldown_secs":{"description":"Seconds the breaker stays open (1 to 3600).","type":"integer","format":"uint32","default":60,"minimum":0},"failure_threshold":{"description":"Consecutive failures before the breaker opens (1 to 100).","type":"integer","format":"uint32","default":5,"minimum":0}}},"ClassificationRule":{"description":"A single classification rule mapping message patterns to a model hint.","type":"object","properties":{"hint":{"description":"Must match a `[[model_routes]]` hint value.","type":"string"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"max_length":{"description":"Only match if message length <= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"min_length":{"description":"Only match if message length >= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"patterns":{"description":"Case-sensitive literal matches (for \"```\", \"fn \", etc.).","type":"array","default":[],"items":{"type":"string"}},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0}},"required":["hint"]},"CloudflareTunnelConfig":{"type":"object","properties":{"token":{"description":"Cloudflare Tunnel token (from Zero Trust dashboard)","type":"string"}},"required":["token"]},"ComplianceConfig":{"type":"object","properties":{"eu_ai_act":{"$ref":"#/$defs/EuAiActComplianceConfig","default":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null}},"interaction_notice":{"$ref":"#/$defs/InteractionNoticeConfig","default":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}}},"ComposioConfig":{"description":"Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.","type":"object","properties":{"api_key":{"description":"Composio API key (stored encrypted when secrets.encrypt = true)","type":["string","null"],"default":null},"entity_id":{"description":"Default entity ID for multi-user setups","type":"string","default":"default"}}},"CostConfig":{"description":"Cost tracking and budget enforcement configuration (`[cost]` section).","type":"object","properties":{"allow_override":{"description":"Allow requests to exceed budget with --override flag (default: false)","type":"boolean","default":false},"daily_limit_usd":{"description":"Daily spending limit in USD (default: 10.00)","type":"number","format":"double","default":10.0},"monthly_limit_usd":{"description":"Monthly spending limit in USD (default: 100.00)","type":"number","format":"double","default":100.0},"prices":{"description":"Per-model pricing (USD per 1M tokens)","type":"object","additionalProperties":{"$ref":"#/$defs/ModelPricing"},"default":{}},"warn_at_percent":{"description":"Warn when spending reaches this percentage of limit (default: 80)","type":"integer","format":"uint8","default":80,"maximum":255,"minimum":0}}},"CredentialRefSetting":{"description":"Which credential a decision backend uses. A reference, never a secret.","type":"string"},"CronConfig":{"description":"Cron job configuration (`[cron]` section).","type":"object","properties":{"max_run_history":{"description":"Maximum number of historical cron run records to retain. Default: `50`.","type":"integer","format":"uint32","default":50,"minimum":0}}},"CustomTunnelConfig":{"type":"object","properties":{"health_url":{"description":"Optional URL to check tunnel health","type":["string","null"]},"start_command":{"description":"Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"","type":"string"},"url_pattern":{"description":"Optional regex to extract public URL from command stdout","type":["string","null"]}},"required":["start_command"]},"DecisionBackendConfig":{"description":"The decision backend (`[decision_engine.backend]`).","type":"object","properties":{"circuit_breaker":{"description":"The circuit breaker.","$ref":"#/$defs/CircuitBreakerConfig","default":{"cooldown_secs":60,"failure_threshold":5}},"credential_ref":{"description":"The credential reference: `\"\"`, `\"none\"` or `cred-`.","$ref":"#/$defs/CredentialRefSetting","default":""},"endpoint":{"description":"The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.","type":"string","default":""},"kind":{"description":"`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).","$ref":"#/$defs/BackendSelection","default":"auto"},"max_request_bytes":{"description":"Largest request body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":65536,"minimum":0},"max_response_bytes":{"description":"Largest response body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":262144,"minimum":0},"model":{"description":"The model the endpoint serves; one exact version for a hosted\nservice.","type":"string","default":""},"pinned_snapshot":{"description":"The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.","type":"string"},"remote_enabled":{"description":"Whether decision state may leave this machine. Default `false`.","type":"boolean","default":false},"timeout_ms":{"description":"Transport timeout (10 ms up to the extra latency budget).","type":"integer","format":"uint32","default":250,"minimum":0}}},"DecisionEngineConfig":{"type":"object","properties":{"backend":{"anyOf":[{"$ref":"#/$defs/DecisionBackendConfig"},{"type":"null"}]},"candidates":{"type":"integer","format":"uint32","default":5,"minimum":0},"enabled":{"type":"boolean","default":false},"mode":{"$ref":"#/$defs/DecisionMode","default":"pre"},"observe_queue":{"type":"integer","format":"uint32","default":64,"minimum":0},"prompt_budget_tokens":{"type":"integer","format":"uint32","default":300,"minimum":0},"telemetry_cap":{"type":"integer","format":"uint32","default":1000,"minimum":0},"timeout_ms":{"type":"integer","format":"uint32","default":1500,"minimum":0},"latency_budget_ms":{"description":"The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.","type":"integer","format":"uint64","default":500,"minimum":0},"token_ratio_limit":{"description":"Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).","type":"number","format":"float","default":0.3499999940395355},"max_candidates":{"description":"The most candidates a turn considers (1 to 32).","type":"integer","format":"uint8","default":12,"maximum":255,"minimum":0}}},"DecisionMode":{"type":"string","enum":["pre","post","both"]},"DeclarationOfConformityConfig":{"type":"object","properties":{"applicable_union_law":{"type":"array","default":[],"items":{"type":"string"}},"artifact_path":{"type":["string","null"],"default":null},"artifact_version":{"type":["string","null"],"default":null},"conformity_assessment_procedure":{"type":["string","null"],"default":null},"conformity_statement":{"type":["string","null"],"default":null},"harmonised_standards":{"type":"array","default":[],"items":{"type":"string"}},"issue_date":{"type":["string","null"],"default":null},"issue_place":{"type":["string","null"],"default":null},"notified_body_certificate":{"type":["string","null"],"default":null},"notified_body_identification_number":{"type":["string","null"],"default":null},"notified_body_name":{"type":["string","null"],"default":null},"personal_data_compliance_statement":{"type":["string","null"],"default":null},"processes_personal_data":{"type":"boolean","default":false},"provider_address":{"type":["string","null"],"default":null},"provider_name":{"type":["string","null"],"default":null},"signer_function":{"type":["string","null"],"default":null},"signer_name":{"type":["string","null"],"default":null},"signer_on_behalf_of":{"type":["string","null"],"default":null},"sole_responsibility_statement":{"type":["string","null"],"default":null},"standards_not_applicable_reason":{"type":["string","null"],"default":null},"system_name":{"type":["string","null"],"default":null},"system_reference":{"type":["string","null"],"default":null},"system_type":{"type":["string","null"],"default":null}}},"DelegateAgentConfig":{"description":"Configuration for a delegate sub-agent used by the `delegate` tool.","type":"object","properties":{"agentic":{"description":"Enable agentic sub-agent mode (multi-turn tool-call loop).","type":"boolean","default":false},"allowed_tools":{"description":"Allowlist of tool names available to the sub-agent in agentic mode.","type":"array","default":[],"items":{"type":"string"}},"api_key":{"description":"Optional API key override","type":["string","null"],"default":null},"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"autonomy":{"description":"The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.","anyOf":[{"$ref":"#/$defs/AutonomyLevel"},{"type":"null"}]},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"enabled":{"description":"Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.","type":"boolean","default":true},"identity_dir":{"description":"Optional identity files directory relative to workspace root.","type":["string","null"],"default":null},"limits":{"$ref":"#/$defs/AgentLimits","default":{"max_concurrent_turns":null,"max_cost_per_day_cents":null}},"max_depth":{"description":"Max recursion depth for nested delegation","type":"integer","format":"uint32","default":8,"minimum":0},"memory_scope":{"description":"Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".","type":["string","null"],"default":null},"model":{"description":"Model name","type":"string"},"provider":{"description":"Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")","type":"string"},"spawn_enabled":{"description":"Whether this agent is allowed to be targeted by sessions_spawn (default: true).","type":["boolean","null"],"default":null},"system_prompt":{"description":"Optional system prompt for the sub-agent","type":["string","null"],"default":null},"temperature":{"description":"Temperature override","type":["number","null"],"format":"double","default":null},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}},"required":["provider","model"]},"DingTalkConfig":{"description":"DingTalk configuration for Stream Mode messaging","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"client_id":{"description":"Client ID (AppKey) from DingTalk developer console","type":"string"},"client_secret":{"description":"Client Secret (AppSecret) from DingTalk developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["client_id","client_secret"]},"DiscordConfig":{"description":"Discord bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Discord user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Discord bot token (from Discord Developer Portal).","type":"string"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"guild_id":{"description":"Optional guild (server) ID to restrict the bot to a single guild.","type":["string","null"]},"listen_to_bots":{"description":"When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.","type":"boolean","default":false}},"required":["bot_token"]},"DmPolicy":{"description":"Policy for direct-message handling.","oneOf":[{"description":"Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).","type":"string","const":"pairing"},{"description":"Accept only senders listed in `allowed_from`.","type":"string","const":"allowlist"},{"description":"Accept any direct sender.","type":"string","const":"open"},{"description":"Ignore direct messages.","type":"string","const":"disabled"}]},"DockerRuntimeConfig":{"description":"Docker runtime configuration (`[runtime.docker]` section).","type":"object","properties":{"allowed_workspace_roots":{"description":"Optional workspace root allowlist for Docker mount validation.","type":"array","default":[],"items":{"type":"string"}},"cpu_limit":{"description":"Optional CPU limit (`None` = no explicit limit).","type":["number","null"],"format":"double","default":1.0},"image":{"description":"Runtime image used to execute shell commands.","type":"string","default":"alpine:3.20"},"memory_limit_mb":{"description":"Optional memory limit in MB (`None` = no explicit limit).","type":["integer","null"],"format":"uint64","default":512,"minimum":0},"mount_workspace":{"description":"Mount configured workspace into `/workspace`.","type":"boolean","default":true},"network":{"description":"Docker network mode (`none`, `bridge`, etc.).","type":"string","default":"none"},"read_only_rootfs":{"description":"Mount root filesystem as read-only.","type":"boolean","default":true}}},"EmailConfig":{"description":"Email channel configuration","type":"object","properties":{"allowed_senders":{"description":"Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)","type":"array","default":[],"items":{"type":"string"}},"from_address":{"description":"From address for outgoing emails","type":"string"},"idle_timeout_secs":{"description":"IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes","type":"integer","format":"uint64","default":1740,"minimum":0},"imap_folder":{"description":"IMAP folder to poll (default: INBOX)","type":"string","default":"INBOX"},"imap_host":{"description":"IMAP server hostname","type":"string"},"imap_port":{"description":"IMAP server port (default: 993 for TLS)","type":"integer","format":"uint16","default":993,"maximum":65535,"minimum":0},"password":{"description":"Email password for authentication","type":"string"},"smtp_host":{"description":"SMTP server hostname","type":"string"},"smtp_port":{"description":"SMTP server port (default: 465 for TLS)","type":"integer","format":"uint16","default":465,"maximum":65535,"minimum":0},"smtp_tls":{"description":"Use TLS for SMTP (default: true)","type":"boolean","default":true},"username":{"description":"Email username for authentication","type":"string"}},"required":["imap_host","smtp_host","username","password","from_address"]},"EmbeddingRouteConfig":{"description":"Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"dimensions":{"description":"Optional embedding dimension override for this route","type":["integer","null"],"format":"uint","default":null,"minimum":0},"hint":{"description":"Route hint name (e.g. \"semantic\", \"archive\", \"faq\")","type":"string"},"model":{"description":"Embedding model to use with that provider","type":"string"},"provider":{"description":"Embedding provider (`none`, `openai`, or `custom:`)","type":"string"}},"required":["hint","provider","model"]},"EuAiActClassificationConfig":{"type":"object","properties":{"assessed_at":{"type":["string","null"],"default":null},"owner":{"type":["string","null"],"default":null},"status":{"$ref":"#/$defs/EuAiActRiskClassification","default":"unclassified"}}},"EuAiActComplianceConfig":{"type":"object","properties":{"classification":{"$ref":"#/$defs/EuAiActClassificationConfig","default":{"assessed_at":null,"owner":null,"status":"unclassified"}},"declaration":{"$ref":"#/$defs/DeclarationOfConformityConfig","default":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null}},"incident_store_path":{"type":["string","null"],"default":null}}},"EuAiActRiskClassification":{"type":"string","enum":["unclassified","high_risk","not_high_risk"]},"FitnessConfig":{"description":"Calendar schedule, evidence thresholds, and retention for fitness v2.","type":"object","properties":{"auto_run":{"description":"Run the daily fitness worker in daemon mode.","type":"boolean","default":true},"max_backfill_days":{"description":"Maximum number of closed days recovered after downtime.","type":"integer","format":"uint32","default":7,"minimum":0},"min_coverage":{"description":"Minimum available metric weight required to publish a final score.","type":"number","format":"double","default":0.6},"min_samples":{"description":"Minimum samples required before an evidence-derived subscore is usable.","type":"integer","format":"uint","default":5,"minimum":0},"retention_days":{"description":"Number of daily JSON reports retained on disk.","type":"integer","format":"uint32","default":180,"minimum":0},"run_at":{"description":"Local wall-clock time (`HH:MM`) at which the previous day is scored.","type":"string","default":"00:10"},"timezone":{"description":"IANA timezone used to define closed calendar days.","type":"string","default":"UTC"}}},"GatewayConfig":{"description":"Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.","type":"object","properties":{"allow_public_bind":{"description":"Allow binding to non-localhost without a tunnel (default: false)","type":"boolean","default":false},"api_rate_limit_per_minute":{"description":"Max `/api/*` requests per minute per authenticated token.","type":"integer","format":"uint32","default":60,"minimum":0},"channel_webhook_dedup_ttl_secs":{"description":"How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.","type":"integer","format":"uint64","default":86400,"minimum":0},"host":{"description":"Gateway host (default: 127.0.0.1)","type":"string","default":"127.0.0.1"},"idempotency_max_keys":{"description":"Maximum distinct idempotency keys retained in memory.","type":"integer","format":"uint","default":10000,"minimum":0},"idempotency_ttl_secs":{"description":"TTL for webhook idempotency keys.","type":"integer","format":"uint64","default":300,"minimum":0},"pair_rate_limit_per_minute":{"description":"Max `/pair` requests per minute per client key.","type":"integer","format":"uint32","default":10,"minimum":0},"paired_tokens":{"description":"Paired bearer tokens (managed automatically, not user-edited)","type":"array","default":[],"items":{"type":"string"}},"port":{"description":"Gateway port (default: 16830)","type":"integer","format":"uint16","default":16830,"maximum":65535,"minimum":0},"rate_limit_max_keys":{"description":"Maximum distinct client keys tracked by gateway rate limiter maps.","type":"integer","format":"uint","default":10000,"minimum":0},"require_pairing":{"description":"Require pairing before accepting requests (default: true)","type":"boolean","default":true},"targeted_agents":{"description":"Switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). Default true. While false, any\notherwise-valid named target answers 409 `agent_disabled` and never\nruns as Main.","type":"boolean","default":true},"trust_forwarded_headers":{"description":"Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.","type":"boolean","default":false},"webhook_rate_limit_per_minute":{"description":"Max `/webhook` requests per minute per client key.","type":"integer","format":"uint32","default":60,"minimum":0}}},"GroupPolicy":{"description":"Policy for group-message handling.","oneOf":[{"description":"Accept only groups listed in `group_allow_from`.","type":"string","const":"allowlist"},{"description":"Accept any group.","type":"string","const":"open"},{"description":"Ignore group messages.","type":"string","const":"disabled"}]},"GroupReplyMode":{"description":"How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.","oneOf":[{"description":"Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).","type":"string","const":"off"},{"description":"Reply only when the bot is @-mentioned (legacy `mention_only = true`).","type":"string","const":"mention-only"},{"description":"Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).","type":"string","const":"smart"}]},"HeartbeatConfig":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]` section).","type":"object","properties":{"active_hours":{"description":"Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.","type":"array","default":[8,23],"items":{"type":"integer","format":"uint8","maximum":255,"minimum":0}},"interval_minutes":{"description":"Interval in minutes between heartbeat pings. Default: `30`.","type":"integer","format":"uint32","default":30,"minimum":0},"prompt":{"description":"Prompt used by heartbeat worker when dispatching tasks.","type":"string","default":"Check HEARTBEAT.md and follow instructions."}}},"HttpRequestConfig":{"description":"HTTP request tool configuration (`[http_request]` section).","type":"object","properties":{"max_response_size":{"description":"Maximum response size in bytes (default: 1MB)","type":"integer","format":"uint","default":1000000,"minimum":0},"timeout_secs":{"description":"Request timeout in seconds (default: 30)","type":"integer","format":"uint64","default":30,"minimum":0}}},"IMessageConfig":{"description":"iMessage channel configuration (macOS only).","type":"object","properties":{"allowed_contacts":{"description":"Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.","type":"array","items":{"type":"string"}},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["allowed_contacts"]},"IdentityBindingConfig":{"description":"Startup identity binding entry (`[[identity_bindings]]`).","type":"object","properties":{"channel":{"type":"string"},"channel_account":{"type":"string"},"display_name":{"type":["string","null"],"default":null},"user_id":{"type":"string"}},"required":["user_id","channel","channel_account"]},"IdentityConfig":{"description":"Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.","type":"object","properties":{"aieos_inline":{"description":"Inline AIEOS JSON (alternative to file path)","type":["string","null"],"default":null},"aieos_path":{"description":"Path to AIEOS JSON file (relative to workspace)","type":["string","null"],"default":null},"format":{"description":"Identity format: \"openclaw\" (default) or \"aieos\"","type":"string","default":"openclaw"}}},"InteractionNoticeApplicability":{"type":"string","enum":["required","not_applicable"]},"InteractionNoticeConfig":{"type":"object","properties":{"applicability":{"$ref":"#/$defs/InteractionNoticeApplicability","default":"required"},"exception_owner":{"type":["string","null"],"default":null},"exception_reviewed_at":{"type":["string","null"],"default":null},"text":{"type":"string","default":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers."},"version":{"type":"string","default":"1"}}},"IrcConfig":{"description":"IRC channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed nicknames (case-insensitive) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"channels":{"description":"Channels to join on connect","type":"array","default":[],"items":{"type":"string"}},"mention_only":{"description":"When true, only process channel/group messages that mention the bot.","type":"boolean","default":false},"nickname":{"description":"Bot nickname","type":"string"},"nickserv_password":{"description":"NickServ IDENTIFY password","type":["string","null"]},"port":{"description":"IRC server port (default: 6697 for TLS)","type":"integer","format":"uint16","default":6697,"maximum":65535,"minimum":0},"sasl_password":{"description":"SASL PLAIN password (IRCv3)","type":["string","null"]},"server":{"description":"IRC server hostname","type":"string"},"server_password":{"description":"Server password (for bouncers like ZNC)","type":["string","null"]},"username":{"description":"Username (defaults to nickname if not set)","type":["string","null"]},"verify_tls":{"description":"Verify TLS certificate (default: true)","type":["boolean","null"]}},"required":["server","nickname"]},"LarkConfig":{"description":"Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from Lark/Feishu developer console","type":"string"},"app_secret":{"description":"App Secret from Lark/Feishu developer console","type":"string"},"encrypt_key":{"description":"Encrypt key for webhook message decryption (optional)","type":["string","null"],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"port":{"description":"HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"receive_mode":{"description":"Event receive mode: \"websocket\" (default) or \"webhook\"","$ref":"#/$defs/LarkReceiveMode","default":"websocket"},"use_feishu":{"description":"Whether to use the Feishu (Chinese) endpoint instead of Lark (International)","type":"boolean","default":false},"verification_token":{"description":"Verification token for webhook validation (optional)","type":["string","null"],"default":null}},"required":["app_id","app_secret"]},"LarkReceiveMode":{"description":"How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.","type":"string","enum":["websocket","webhook"]},"LinqConfig":{"type":"object","properties":{"allowed_senders":{"description":"Allowed sender handles (phone numbers) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"api_token":{"description":"Linq Partner API token (Bearer auth)","type":"string"},"from_phone":{"description":"Phone number to send from (E.164 format)","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"signing_secret":{"description":"Webhook signing secret for signature verification","type":["string","null"],"default":null}},"required":["api_token","from_phone"]},"MattermostConfig":{"description":"Mattermost bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Mattermost user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Mattermost bot access token.","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.","type":["boolean","null"],"default":null},"thread_replies":{"description":"When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.","type":["boolean","null"],"default":null},"url":{"description":"Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).","type":"string"}},"required":["url","bot_token"]},"McpConfig":{"type":"object","properties":{"servers":{"description":"Named MCP server definitions","type":"object","additionalProperties":{"$ref":"#/$defs/McpServerConfig"},"default":{}},"workspace_servers":{"description":"Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.","$ref":"#/$defs/WorkspaceMcpServers"}}},"McpServerConfig":{"type":"object","properties":{"allow_tools":{"description":"Optional allow-list of exposed tools (empty = all)","type":"array","default":[],"items":{"type":"string"}},"args":{"description":"Command args for stdio mode","type":"array","default":[],"items":{"type":"string"}},"command":{"description":"Command for stdio mode","type":["string","null"],"default":null},"deny_tools":{"description":"Optional deny-list of exposed tools","type":"array","default":[],"items":{"type":"string"}},"env":{"description":"Environment variables for stdio mode","type":"object","additionalProperties":{"type":"string"},"default":{}},"request_timeout_ms":{"description":"Request timeout in milliseconds","type":"integer","format":"uint64","default":30000,"minimum":0},"startup_timeout_ms":{"description":"Startup timeout in milliseconds","type":"integer","format":"uint64","default":10000,"minimum":0},"tool_name_prefix":{"description":"Prefix used in tool naming and routing","type":"string","default":"mcp"},"transport":{"description":"Transport type: stdio or http","$ref":"#/$defs/McpTransport","default":"stdio"},"url":{"description":"URL for HTTP mode (streamable HTTP endpoint)","type":["string","null"],"default":null},"working_dir":{"description":"Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).","type":["string","null"]}}},"McpServerRuntimeConfig":{"type":"object","properties":{"allowed_origins":{"description":"Allowed browser origins for future streamable HTTP clients.","type":"array","default":["claude.ai","openai.com","localhost"],"items":{"type":"string"}},"bind":{"description":"Advertised bind address. The gateway may still be started with a CLI port override.","type":"string","default":"127.0.0.1:16831"},"exposed_tools":{"description":"Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.","type":"array","default":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"items":{"type":"string"}},"jwt_algorithms":{"description":"Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.","type":"array","default":["RS256"],"items":{"type":"string"}},"jwt_audience":{"description":"Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.","type":["string","null"],"default":null},"jwt_issuer":{"description":"Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.","type":["string","null"],"default":null},"jwt_jwks":{"description":"Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.","type":["string","null"],"default":null},"jwt_jwks_cache_ttl_secs":{"description":"Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.","type":"integer","format":"uint64","default":300,"minimum":0},"jwt_jwks_uri":{"description":"Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.","type":["string","null"],"default":null},"jwt_public_key_pem":{"description":"PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.","type":["string","null"],"default":null},"rate_limit_rps":{"description":"Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.","type":"integer","format":"uint32","default":10,"minimum":0},"require_auth":{"description":"Require an authenticated external identity for mutating calls.","type":"boolean","default":true}}},"McpTransport":{"type":"string","enum":["stdio","http"]},"MediaConfig":{"description":"Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.","type":"object","properties":{"audio_model":{"description":"Audio model name (Ollama model or OpenAI model). Default: \"whisper\".","type":"string","default":"whisper"},"audio_ollama_url":{"description":"Ollama base URL for audio transcription. Default: \"http://localhost:11434\".","type":"string","default":"http://localhost:11434"},"audio_provider":{"description":"Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".","type":"string","default":"none"},"max_audio_size_mb":{"description":"Maximum audio attachment size in MiB. Default: 20.","type":"integer","format":"uint","default":20,"minimum":0},"max_video_size_mb":{"description":"Maximum video attachment size in MiB. Default: 50.","type":"integer","format":"uint","default":50,"minimum":0},"video_max_frames":{"description":"Maximum video frames to extract per video. Default: 4.","type":"integer","format":"uint","default":4,"minimum":0},"video_provider":{"description":"Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".","type":"string","default":"none"}}},"MemoryConfig":{"description":"Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.","type":"object","properties":{"acl_enabled":{"description":"Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.","type":"boolean","default":false},"archive_after_days":{"description":"Archive daily/session files older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"auto_hydrate":{"description":"Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing","type":"boolean","default":true},"auto_save":{"description":"Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.","type":"boolean","default":true},"backend":{"description":"\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).","type":"string","default":"sqlite"},"conversation_retention_days":{"description":"For sqlite backend: prune conversation rows older than this many days","type":"integer","format":"uint32","default":3,"minimum":0},"daily_retention_days":{"description":"For sqlite backend: prune daily rows older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"embedding_cache_size":{"description":"Max embedding cache entries before LRU eviction","type":"integer","format":"uint","default":10000,"minimum":0},"embedding_dimensions":{"description":"Embedding vector dimensions","type":"integer","format":"uint","default":384,"minimum":0},"embedding_model":{"description":"Embedding model name (e.g. \"text-embedding-3-small\")","type":"string","default":"prx-local-hash-v1"},"embedding_provider":{"description":"Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"","type":"string","default":"local"},"events":{"description":"Raw/quasi-raw message event recording controls (`[memory.events]`).","$ref":"#/$defs/MemoryEventsConfig","default":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true}},"keyword_weight":{"description":"Weight for keyword BM25 in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.3},"legacy_conversation_turns_visible":{"description":"Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.","type":"boolean","default":true},"lucid_budget":{"description":"Token budget for lucid (replaces OPENPRX_LUCID_BUDGET)","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"lucid_cmd":{"description":"Path to lucid binary (replaces OPENPRX_LUCID_CMD)","type":["string","null"],"default":null},"lucid_failure_cooldown_ms":{"description":"Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)","type":"integer","format":"uint64","default":60000,"minimum":0},"lucid_local_hit_threshold":{"description":"Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)","type":"integer","format":"uint","default":3,"minimum":0},"lucid_recall_timeout_ms":{"description":"Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)","type":"integer","format":"uint64","default":5000,"minimum":0},"lucid_store_timeout_ms":{"description":"Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)","type":"integer","format":"uint64","default":3000,"minimum":0},"min_relevance_score":{"description":"Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4","type":"number","format":"double","default":0.4},"purge_after_days":{"description":"Purge archived files older than this many days","type":"integer","format":"uint32","default":30,"minimum":0},"semantic":{"description":"Semantic memory promotion controls (`[memory.semantic]`).","$ref":"#/$defs/MemorySemanticConfig","default":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30}},"sqlite_open_timeout_secs":{"description":"For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"sqlite_read_pool_size":{"description":"For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"vector_candidate_cap":{"description":"How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.","type":"integer","format":"uint","default":2000,"minimum":0},"vector_weight":{"description":"Weight for vector similarity in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.7}}},"MemoryEventsConfig":{"description":"Raw message event recording configuration (`[memory.events]`).","type":"object","properties":{"record_assistant_messages":{"description":"Record assistant replies.","type":"boolean","default":true},"record_tool_events":{"description":"Record tool/event payloads by default.","type":"boolean","default":false},"record_user_messages":{"description":"Record inbound/user messages.","type":"boolean","default":true}}},"MemorySemanticConfig":{"description":"Semantic memory promotion configuration (`[memory.semantic]`).","type":"object","properties":{"auto_promote_assistant_messages":{"description":"Auto-promote eligible assistant messages. Disabled by default to reduce noise.","type":"boolean","default":false},"auto_promote_user_messages":{"description":"Auto-promote eligible user messages into long-term semantic memories.","type":"boolean","default":true},"min_chars":{"description":"Minimum content length for semantic auto-promotion.","type":"integer","format":"uint","default":30,"minimum":0}}},"MemoryWebhookConfig":{"type":"object","properties":{"bind":{"description":"Socket address for the receiver (e.g. \"0.0.0.0:16899\").","type":"string","default":"0.0.0.0:16899"},"signing_secret":{"description":"Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.","type":["string","null"],"default":null},"token":{"description":"Required bearer token for incoming webhook events.","type":["string","null"],"default":null}}},"ModelOperationSetting":{"description":"The operations a `[[providers.models]]` entry may list.","type":"string","enum":["chat","embedding","decision_endpoint","rerank","image_generation","audio_generation","video_generation"]},"ModelPricing":{"description":"Per-model pricing entry (USD per 1M tokens).","type":"object","properties":{"cache_read":{"description":"Cache read input price per 1M tokens.","type":"number","format":"double","default":0.0},"cache_write":{"description":"Cache write/creation input price per 1M tokens.","type":"number","format":"double","default":0.0},"input":{"description":"Input price per 1M tokens","type":"number","format":"double","default":0.0},"output":{"description":"Output price per 1M tokens","type":"number","format":"double","default":0.0}}},"ModelRouteConfig":{"description":"Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"hint":{"description":"Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")","type":"string"},"level":{"type":["string","null"]},"model":{"description":"Model to use with that provider","type":"string"},"provider":{"description":"Provider to route to (must match a known provider name)","type":"string"},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true,"required":["hint","provider","model"]},"ModelSettings":{"description":"A model level plus explicit parameter overrides in `[model_settings.\"\"]`.","type":"object","properties":{"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"level":{"type":["string","null"]},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true},"MultimodalConfig":{"description":"Multimodal (image) handling configuration (`[multimodal]` section).","type":"object","properties":{"allow_remote_fetch":{"description":"Allow fetching remote image URLs (http/https). Disabled by default.","type":"boolean","default":false},"max_image_size_mb":{"description":"Maximum image payload size in MiB before base64 encoding.","type":"integer","format":"uint","default":5,"minimum":0},"max_images":{"description":"Maximum number of image attachments accepted per request.","type":"integer","format":"uint","default":4,"minimum":0}}},"NextcloudTalkConfig":{"description":"Nextcloud Talk bot configuration (webhook receive + OCS send API).","type":"object","properties":{"allowed_users":{"description":"Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Bot app token used for OCS API bearer auth.","type":"string"},"base_url":{"description":"Nextcloud base URL (e.g. \"https://cloud.example.com\").","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"webhook_secret":{"description":"Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).","type":["string","null"],"default":null}},"required":["base_url","app_token"]},"NgrokTunnelConfig":{"type":"object","properties":{"auth_token":{"description":"ngrok auth token","type":"string"},"domain":{"description":"Optional custom domain","type":["string","null"]}},"required":["auth_token"]},"NodeServerConfig":{"description":"Node daemon runtime config used by `prx-node`.","type":"object","properties":{"allowed_commands":{"description":"Command allowlist matched on first token.\n\nIn restricted mode this list is required unless explicitly set to `[\"*\"]`.","type":"array","default":["echo"],"items":{"type":"string"}},"bearer_token":{"description":"Required bearer token for /rpc.","type":"string","default":""},"blocked_commands":{"description":"Command denylist matched on first token. Always enforced.","type":"array","default":[],"items":{"type":"string"}},"exec_timeout_ms":{"description":"Default command timeout in milliseconds.","type":"integer","format":"uint64","default":15000,"minimum":0},"hmac_secret":{"description":"Optional HMAC signing secret.","type":["string","null"],"default":null},"listen_addr":{"description":"Listen address for node daemon.","type":"string","default":"127.0.0.1:8787"},"max_concurrent_tasks":{"description":"Maximum number of concurrent async command tasks.","type":"integer","format":"uint","default":8,"minimum":0},"max_output_bytes":{"description":"Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.","type":"integer","format":"uint","default":1048576,"minimum":0},"sandbox_root":{"description":"Sandbox root directory for read/write/cwd constraints.","type":"string","default":"."},"task_result_ttl_ms":{"description":"TTL for completed task results in milliseconds.","type":"integer","format":"uint64","default":3600000,"minimum":0},"tls_cert":{"description":"TLS certificate path (PEM).","type":["string","null"],"default":null},"tls_key":{"description":"TLS private key path (PEM).","type":["string","null"],"default":null},"tls_required":{"description":"Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.","type":"boolean","default":true}}},"NodesConfig":{"description":"Remote node proxy configuration for core-side RPC calls and node daemon defaults.","type":"object","properties":{"nodes":{"description":"Configured remote nodes.","type":"array","default":[],"items":{"$ref":"#/$defs/RemoteNodeConfig"}},"request_timeout_ms":{"description":"Default request timeout for node RPC calls.","type":"integer","format":"uint64","default":15000,"minimum":0},"retry_max":{"description":"Default max retries for node RPC calls.","type":"integer","format":"uint8","default":2,"maximum":255,"minimum":0},"server":{"description":"Embedded node server defaults used by `prx-node`.","$ref":"#/$defs/NodeServerConfig","default":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}}},"ObservabilityConfig":{"description":"Observability backend configuration (`[observability]` section).","type":"object","properties":{"backend":{"description":"\"none\" | \"log\" | \"prometheus\" | \"otel\"","type":"string","default":"none"},"otel_endpoint":{"description":"OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".","type":["string","null"],"default":null},"otel_service_name":{"description":"Service name reported to the OTel collector. Defaults to \"prx\".","type":["string","null"],"default":null}}},"OllamaProviderConfig":{"description":"Ollama-specific request options (`[providers.ollama]`).","type":"object","properties":{"num_ctx":{"description":"Explicit context window sent as Ollama `options.num_ctx`.","type":["integer","null"],"format":"uint","default":null,"minimum":0}}},"OsPagingConfig":{"description":"Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.","type":"object","properties":{"eviction_threshold":{"description":"Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.","type":"number","format":"double","default":0.7},"keep_recent_messages":{"description":"Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).","type":"integer","format":"uint","default":12,"minimum":0},"max_recalled_pages":{"description":"Maximum number of evicted pages (document chunks) recalled per turn.","type":"integer","format":"uint","default":10,"minimum":0},"proactive_retrieval":{"description":"Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.","type":"boolean","default":true},"retrieval_injection_role":{"description":"Role under which recalled pages are injected.","$ref":"#/$defs/RetrievalInjectionRole","default":"system"}}},"PluginsConfig":{"description":"WASM plugin runtime configuration.","type":"object","properties":{"enabled":{"description":"Load WASM plugins from `/plugins`. Default: `false`.","type":"boolean","default":false}},"additionalProperties":false},"ProviderModelConfig":{"description":"One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.","type":"object","properties":{"context_window":{"description":"The model's context window in tokens.","type":["integer","null"],"format":"uint32","minimum":0},"model":{"description":"The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.","type":["string","null"]},"native_tools":{"description":"Whether the model accepts native tool calls.","type":["boolean","null"]},"operations":{"description":"The complete list of operations the model executes; every operation not\nlisted is unsupported.","type":["array","null"],"items":{"$ref":"#/$defs/ModelOperationSetting"}},"provider":{"description":"The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.","type":"string"},"streaming":{"description":"Whether the model streams responses.","type":["boolean","null"]},"structured_output":{"description":"Whether the model honours a JSON-schema response format.","type":["boolean","null"]},"tool_call_dialect":{"description":"The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema_dialect":{"description":"The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]},"vision_input":{"description":"Whether the model accepts image input.","type":["boolean","null"]}},"required":["provider"]},"ProviderToolDialectConfig":{"description":"One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.","type":"object","properties":{"model":{"description":"The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.","type":["string","null"]},"provider":{"description":"The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.","type":"string"},"tool_call":{"description":"The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema":{"description":"The tool-schema dialect the endpoint accepts.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]}},"required":["provider"]},"ProvidersConfig":{"description":"Provider-specific runtime configuration (`[providers]`).","type":"object","properties":{"models":{"description":"Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.","type":"array","items":{"$ref":"#/$defs/ProviderModelConfig"}},"ollama":{"description":"Ollama-specific request options (`[providers.ollama]`).","$ref":"#/$defs/OllamaProviderConfig","default":{"num_ctx":null}},"tool_dialects":{"description":"Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).","type":"array","items":{"$ref":"#/$defs/ProviderToolDialectConfig"}}}},"ProxyConfig":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).","type":"object","properties":{"all_proxy":{"description":"Fallback proxy URL for all schemes.","type":["string","null"],"default":null},"http_proxy":{"description":"Proxy URL for HTTP requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"https_proxy":{"description":"Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"no_proxy":{"description":"No-proxy bypass list. Same format as NO_PROXY.","type":"array","default":[],"items":{"type":"string"}},"scope":{"description":"Proxy application scope.","$ref":"#/$defs/ProxyScope","default":"prx"},"services":{"description":"Service selectors used when scope = \"services\".","type":"array","default":[],"items":{"type":"string"}}}},"ProxyScope":{"description":"Proxy application scope — determines which outbound traffic uses the proxy.","oneOf":[{"description":"Use system environment proxy variables only.","type":"string","const":"environment"},{"description":"Apply proxy to all OpenPRX-managed HTTP traffic (default).","type":"string","const":"prx"},{"description":"Apply proxy only to explicitly listed service selectors.","type":"string","const":"services"}]},"QQConfig":{"description":"QQ Official Bot configuration (Tencent QQ Bot SDK)","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs. Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from QQ Bot developer console","type":"string"},"app_secret":{"description":"App Secret from QQ Bot developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["app_id","app_secret"]},"QueryClassificationConfig":{"description":"Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.","type":"object","properties":{"rules":{"description":"Classification rules evaluated in priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/ClassificationRule"}}}},"RamfluxAccountConfig":{"description":"Persona for one ramflux AI account. Missing fields fall back to the global agent.","type":"object","properties":{"cross_conversation_retrieval":{"description":"Cross-conversation memory retrieval. Off unless the owner sets it.","type":"boolean","default":false},"model":{"type":["string","null"],"default":null},"provider":{"type":["string","null"],"default":null},"scope_profile":{"type":["string","null"],"default":null},"system_prompt_file":{"description":"Path to a system-prompt file. Relative paths are resolved from the workspace.","type":["string","null"],"default":null}},"additionalProperties":false},"RamfluxAttachmentFetch":{"description":"Per-turn caps for `attachment.fetch`.","type":"object","properties":{"max_bytes":{"type":"integer","format":"uint64","default":5242880,"minimum":0},"max_per_turn":{"type":"integer","format":"uint8","default":4,"maximum":255,"minimum":0}},"additionalProperties":false},"RamfluxAuthorizationMode":{"description":"How prx combines its own setting with `bridge.hello.authorization`.","oneOf":[{"description":"Use the agent-host value. Until hello arrives, the effective mode is supervised.","type":"string","const":"follow_rf"},{"description":"Always supervised, even when the agent-host declares full.","type":"string","const":"supervised"},{"description":"Full only when the agent-host also declares full. Config alone never yields full.","type":"string","const":"full"}]},"RamfluxConfig":{"description":"Local ramflux agent-host bridge (`[channels_config.ramflux]`).","type":"object","properties":{"accounts":{"type":"object","additionalProperties":{"$ref":"#/$defs/RamfluxAccountConfig"},"default":{}},"allowed_block_types":{"type":"array","default":["Text","Markdown","Heading","KeyValue","Metric","List","TableFallback","Form","Input","Select","Progress","LogStream","Warning","Error","Success","Approval","ActionGroup","FilePreview","Fallback"],"items":{"type":"string"}},"attachment_fetch":{"$ref":"#/$defs/RamfluxAttachmentFetch","default":{"max_bytes":5242880,"max_per_turn":4}},"authorization_mode":{"$ref":"#/$defs/RamfluxAuthorizationMode","default":"follow_rf"},"encrypt_at_rest":{"type":"boolean","default":true},"max_in_flight_per_conversation":{"type":"integer","format":"uint8","default":1,"maximum":255,"minimum":0},"on_new_message":{"$ref":"#/$defs/RamfluxOnNewMessage","default":"queue"},"socket_path":{"description":"Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.","type":["string","null"],"default":null},"surface_limits":{"$ref":"#/$defs/RamfluxSurfaceLimits","default":{"max_actions":16,"max_blocks":32,"max_bytes":65536}},"turn_wall_clock_secs":{"description":"Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.","type":"integer","format":"uint64","default":120,"minimum":0}},"additionalProperties":false},"RamfluxOnNewMessage":{"description":"What to do with a new inbound message while a turn for that conversation is running.","type":"string","enum":["queue","interrupt"]},"RamfluxSurfaceLimits":{"description":"Limits for `reply.surface` blocks and actions.","type":"object","properties":{"max_actions":{"type":"integer","format":"uint32","default":16,"minimum":0},"max_blocks":{"type":"integer","format":"uint32","default":32,"minimum":0},"max_bytes":{"type":"integer","format":"uint32","default":65536,"minimum":0}},"additionalProperties":false},"ReliabilityCircuitBreakerConfig":{"description":"Process-local provider circuit policy (`[reliability.circuit_breaker]`).","type":"object","properties":{"enabled":{"description":"Enable protection for factory-built provider chains.","type":"boolean","default":true},"failure_threshold":{"description":"Consecutive transient failures that open a circuit (at least 1).","type":"integer","format":"uint32","default":5,"minimum":0},"max_open_secs":{"description":"Maximum doubled window, between open_secs and 3600 seconds.","type":"integer","format":"uint64","default":300,"minimum":0},"open_secs":{"description":"Initial open window in seconds (at least 1).","type":"integer","format":"uint64","default":30,"minimum":0}}},"ReliabilityConfig":{"description":"Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.","type":"object","properties":{"acknowledge_single_provider_risk":{"description":"Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.","type":"boolean","default":false},"api_keys":{"description":"Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.","type":"array","default":[],"items":{"type":"string"}},"channel_initial_backoff_secs":{"description":"Initial backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":2,"minimum":0},"channel_max_backoff_secs":{"description":"Max backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":60,"minimum":0},"circuit_breaker":{"description":"Per-provider consecutive failure protection.","$ref":"#/$defs/ReliabilityCircuitBreakerConfig","default":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30}},"fallback_providers":{"description":"Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).","type":"array","default":[],"items":{"type":"string"}},"model_fallbacks":{"description":"Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`","type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"default":{}},"provider_backoff_ms":{"description":"Base backoff (ms) for provider retry delay.","type":"integer","format":"uint64","default":500,"minimum":0},"provider_retries":{"description":"Retries per provider before failing over.","type":"integer","format":"uint32","default":2,"minimum":0},"scheduler_poll_secs":{"description":"Scheduler polling cadence in seconds.","type":"integer","format":"uint64","default":15,"minimum":0},"scheduler_retries":{"description":"Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.","type":"integer","format":"uint32","default":2,"minimum":0}}},"RemoteNodeConfig":{"description":"A remote node target for core-side node proxy calls.","type":"object","properties":{"bearer_token":{"description":"Bearer token for node RPC authentication.","type":"string"},"endpoint":{"description":"Base endpoint (e.g. \"http://127.0.0.1:8787\").","type":"string"},"hmac_secret":{"description":"Optional request signing key (HMAC-SHA256).","type":["string","null"],"default":null},"id":{"description":"Stable node ID used by the nodes tool.","type":"string"},"retry_max":{"description":"Optional per-node retry override.","type":["integer","null"],"format":"uint8","default":null,"maximum":255,"minimum":0},"timeout_ms":{"description":"Optional per-node timeout override.","type":["integer","null"],"format":"uint64","default":null,"minimum":0}},"required":["id","endpoint","bearer_token"]},"RetrievalInjectionRole":{"description":"Where recalled context pages are injected back into the request.","oneOf":[{"description":"Inject recalled pages as a leading `system` message (not user-visible).","type":"string","const":"system"},{"description":"Inject recalled pages as a leading `user` message.","type":"string","const":"user"}]},"RouterConfig":{"description":"Heuristic LLM router configuration (`[router]` section).","type":"object","properties":{"alpha":{"description":"Similarity score weight. Phase 1 keeps this at `0.0`.","type":"number","format":"float","default":0.0},"beta":{"description":"Capability score weight.","type":"number","format":"float","default":0.5},"delta":{"description":"Cost penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"epsilon":{"description":"Latency penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"gamma":{"description":"Elo score weight.","type":"number","format":"float","default":0.30000001192092896},"knn_k":{"description":"Number of nearest neighbors considered for voting. Default: `7`.","type":"integer","format":"uint","default":7,"minimum":0},"knn_min_records":{"description":"Minimum history records before KNN affects routing. Default: `10`.","type":"integer","format":"uint","default":10,"minimum":0},"models":{"description":"Candidate model registry.","type":"array","default":[],"items":{"$ref":"#/$defs/RouterModelConfig"}}}},"RouterModelConfig":{"description":"Static router metadata for one model candidate.","type":"object","properties":{"categories":{"description":"Capability categories such as `conversation`, `code`, or `analysis`.","type":"array","default":[],"items":{"type":"string"}},"cost_per_million_tokens":{"description":"USD cost per million tokens.","type":"number","format":"float","default":0.0},"elo_rating":{"description":"Initial Elo rating.","type":"number","format":"float","default":1000.0},"latency_ms":{"description":"Average latency in milliseconds.","type":"integer","format":"uint32","default":2000,"minimum":0},"max_context":{"description":"Maximum context window in tokens.","type":"integer","format":"uint","default":1000000,"minimum":0},"model_id":{"description":"Model identifier without provider prefix.","type":"string"},"provider":{"description":"Provider identifier.","type":"string"},"reserved_output_tokens":{"description":"Output tokens reserved for this model when planning input context.","type":["integer","null"],"format":"uint","minimum":0}},"required":["model_id","provider"]},"RuntimeConfig":{"description":"Runtime adapter configuration (`[runtime]` section).","type":"object","properties":{"codex_reasoning_effort":{"description":"Codex reasoning effort","type":["string","null"],"default":null},"codex_stream_idle_timeout_secs":{"description":"Codex stream idle timeout in seconds","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"docker":{"description":"Docker runtime settings (used when `kind = \"docker\"`).","$ref":"#/$defs/DockerRuntimeConfig","default":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true}},"idle_hang_secs":{"description":"Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"kind":{"description":"Runtime kind (`native` | `docker`).","type":"string","default":"native"},"long_task_warn_secs":{"description":"Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"managed_cgroup_root":{"description":"Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.","type":["string","null"],"default":null},"max_blocking_threads":{"description":"Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"reasoning_enabled":{"description":"Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported","type":["boolean","null"],"default":null},"shell_env_allowlist":{"description":"Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.","type":"array","default":[],"items":{"type":"string"}},"workdir":{"description":"Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.","type":["string","null"],"default":null}}},"SchedulerConfig":{"description":"Scheduler configuration for periodic task execution (`[scheduler]` section).","type":"object","properties":{"claim_lease_secs":{"description":"Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.","type":"integer","format":"uint64","default":90,"minimum":0},"max_tasks":{"description":"Maximum number of persisted scheduled tasks.","type":"integer","format":"uint","default":64,"minimum":0}}},"ScopeConfig":{"description":"Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```","type":"object","properties":{"assign_owners":{"description":"Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.","type":"array","default":[],"items":{"type":"string"}},"default":{"description":"Default action when no rule matches: \"allow\" (default) or \"deny\".","$ref":"#/$defs/ScopeDefault","default":"allow"},"rules":{"description":"Ordered list of scope rules evaluated top-to-bottom.","type":"array","default":[],"items":{"$ref":"#/$defs/ScopeRule"}}}},"ScopeDefault":{"description":"What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.","oneOf":[{"description":"Unmatched tool calls are allowed (the default).","type":"string","const":"allow"},{"description":"Unmatched tool calls are refused.","type":"string","const":"deny"}]},"ScopeRule":{"description":"A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.","type":"object","properties":{"assign_allow":{"description":"Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".","type":"array","default":[],"items":{"type":"string"}},"assign_deny":{"description":"Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.","type":"array","default":[],"items":{"type":"string"}},"channel":{"description":"Match by channel name: \"signal\", \"telegram\", \"discord\", etc.","type":["string","null"]},"chat_type":{"description":"Match by chat type: \"direct\", \"group\", or \"*\" for any type.","type":["string","null"]},"send_allow":{"description":"Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.","type":"array","default":[],"items":{"type":"string"}},"send_deny":{"description":"Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.","type":"array","default":[],"items":{"type":"string"}},"tools_allow":{"description":"Tool whitelist: only these tools are allowed (empty = all tools permitted).","type":"array","default":[],"items":{"type":"string"}},"tools_deny":{"description":"Tool blacklist: these tools are denied regardless of allow list.","type":"array","default":[],"items":{"type":"string"}},"user":{"description":"Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.","type":["string","null"]}}},"SecretsConfig":{"description":"Secrets encryption configuration (`[secrets]` section).","type":"object","properties":{"encrypt":{"description":"Enable encryption for API keys and tokens in config.toml","type":"boolean","default":true}}},"SecurityConfig":{"description":"Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.","type":"object","properties":{"audit":{"description":"Audit logging configuration","$ref":"#/$defs/AuditConfig","default":{"log_path":"audit.log","max_size_mb":100}},"workspace_hooks":{"description":"Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.","$ref":"#/$defs/WorkspaceHooks"}}},"SelfSystemConfig":{"description":"Self-system experimental automation config (`[self_system]`).","type":"object","properties":{"evolution_config_path":{"description":"Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG)","type":["string","null"],"default":null},"evolution_debug_raw":{"description":"Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW)","type":"boolean","default":false},"evolution_interval_hours":{"description":"Evolution scheduler interval in hours (daemon mode).","type":"integer","format":"uint32","default":24,"minimum":0},"evolution_judge_timeout_secs":{"description":"Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.","type":"integer","format":"uint64","default":180,"minimum":0},"evolution_model_max_micro_usd":{"description":"Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.","type":"integer","format":"uint64","default":0,"minimum":0},"evolution_model_max_tokens":{"description":"Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.","type":"integer","format":"uint64","default":16384,"minimum":0},"fitness":{"description":"Daily fitness snapshot policy.","$ref":"#/$defs/FitnessConfig","default":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"}},"fitness_interval_hours":{"description":"Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.","type":"integer","format":"uint64","default":24,"minimum":0}}},"SessionsSpawnConfig":{"description":"Sessions spawn configuration (`[sessions_spawn]` section).","type":"object","properties":{"cleanup_on_complete":{"description":"Remove worker workspace directory after process-mode completion.","type":"boolean","default":true},"default_mode":{"description":"Default execution mode for sessions_spawn (`task` or `process`).","type":"string","default":"task"},"process_memory_strategy":{"description":"Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.","type":"string","default":"shared_fabric"},"worker_workspace_root":{"description":"Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.","type":["string","null"],"default":null}}},"SignalConfig":{"type":"object","properties":{"account":{"description":"E.164 phone number of the signal-cli account (e.g. \"+1234567890\").","type":"string"},"allowed_from":{"description":"Allowed sender phone numbers (E.164) or \"*\" for all.","type":"array","default":[],"items":{"type":"string"}},"cli_path":{"description":"Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).","type":["string","null"],"default":null},"daemon_http_port":{"description":"Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"daemon_mode":{"description":"Deprecated: ignored. Accepted for backward compatibility with older config files.","type":["boolean","null"],"default":null},"data_dir":{"description":"signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_id":{"description":"Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group","type":["string","null"],"default":null},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"http_url":{"description":"Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.","type":"string","default":"http://localhost:8080"},"ignore_attachments":{"description":"Skip messages that are attachment-only (no text body).","type":"boolean","default":false},"ignore_stories":{"description":"Skip incoming story messages.","type":"boolean","default":false},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"mode":{"description":"Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.","type":["string","null"],"default":null},"startup_timeout_ms":{"description":"Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.","type":"integer","format":"uint64","default":30000,"minimum":0},"storm_protection":{"description":"Signal ingress storm protection controls.","$ref":"#/$defs/SignalStormProtectionConfig","default":{"abnormal_threshold":10,"abnormal_window_secs":60,"breaker_duration_secs":300,"dedupe_ttl_secs":60,"min_reply_interval_secs":2}}},"required":["account"]},"SignalStormProtectionConfig":{"type":"object","properties":{"abnormal_threshold":{"description":"Non-user event threshold within `abnormal_window_secs` before tripping the breaker.","type":"integer","format":"uint","default":10,"minimum":0},"abnormal_window_secs":{"description":"Sliding window in seconds for non-user event counting.","type":"integer","format":"uint64","default":60,"minimum":0},"breaker_duration_secs":{"description":"Circuit breaker duration in seconds after threshold is reached.","type":"integer","format":"uint64","default":300,"minimum":0},"dedupe_ttl_secs":{"description":"Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.","type":"integer","format":"uint64","default":60,"minimum":0},"min_reply_interval_secs":{"description":"Minimum interval in seconds between replies for the same `(channel + reply_target)`.","type":"integer","format":"uint64","default":2,"minimum":0}}},"SkillRagConfig":{"description":"Dynamic skill retrieval configuration (`[skill_rag]` section).","type":"object","properties":{"top_k":{"description":"How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).","type":"integer","format":"uint","default":32,"minimum":0}}},"SkillSuiteRegistration":{"description":"The frozen suite that governs one skill's proposals.","type":"object","properties":{"skill_id":{"description":"The skill the suite governs.","type":"string"},"suite_digest":{"description":"SHA-256 digest (64 lowercase hex digits) of the frozen suite.","type":"string"}},"additionalProperties":false,"required":["skill_id","suite_digest"]},"SkillsConfig":{"description":"Skills loading configuration (`[skills]` section).","type":"object","properties":{"open_skills_dir":{"description":"Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.","type":["string","null"],"default":null},"openclaw_skills_dir":{"description":"Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.","type":["string","null"],"default":null}}},"SkillsLifecycleConfig":{"description":"`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.","type":"object","properties":{"allow_executable_proposals":{"description":"Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.","type":"boolean","default":false},"enabled":{"description":"Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.","type":"boolean","default":false},"max_concurrent_evaluations":{"description":"Most evaluations running at once.","type":"integer","format":"uint32","default":1,"minimum":0},"max_edit_fraction":{"description":"Edit budget of a proposal as a fraction of the skill body, in (0, 1].","type":"number","format":"double","default":0.2},"max_edit_tokens":{"description":"Edit budget of a proposal, in tokens.","type":"integer","format":"uint64","default":300,"minimum":0},"max_proposals_per_cycle":{"description":"Most proposals one cycle may start.","type":"integer","format":"uint32","default":1,"minimum":0},"min_cases_floor":{"description":"Smallest `min_cases` a governing suite may declare. Below 3 is refused.","type":"integer","format":"uint32","default":3,"minimum":0},"mode":{"description":"`draft_only`, `shadow` or `auto`.","$ref":"#/$defs/SkillsLifecycleModeConfig","default":"draft_only"},"owner_scope":{"description":"The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.","type":["string","null"],"default":null},"require_holdout":{"description":"A governing suite must have a holdout split. `false` is refused.","type":"boolean","default":true},"storage_dir":{"description":"Store location under the workspace. Only the default is supported.","type":"string","default":"self/skill-lifecycle"},"suites":{"description":"The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.","type":"array","default":[],"items":{"$ref":"#/$defs/SkillSuiteRegistration"}}},"additionalProperties":false},"SkillsLifecycleModeConfig":{"description":"What the lifecycle may do. Mirrors `LifecycleMode`.","oneOf":[{"description":"Drafts and reviews only.","type":"string","const":"draft_only"},{"description":"Drafts plus evaluation and gating; never publishes.","type":"string","const":"shadow"},{"description":"Publishes an eligible proposal after every gate.","type":"string","const":"auto"}]},"SlackConfig":{"description":"Slack bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Slack user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Slack app-level token for Socket Mode (xapp-...).","type":["string","null"]},"bot_token":{"description":"Slack bot OAuth token (xoxb-...).","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["bot_token"]},"SmartGroupConfig":{"description":"Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).","type":"object","properties":{"classifier_max_context_messages":{"description":"How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.","type":"integer","format":"uint","default":3,"minimum":0},"classifier_model":{"description":"Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.","type":"string","default":""},"classifier_provider":{"description":"Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.","type":"string","default":""},"classifier_temperature":{"description":"Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).","type":"number","format":"double","default":0.0},"classifier_timeout_secs":{"description":"Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.","type":"integer","format":"uint64","default":5,"minimum":0}}},"StorageConfig":{"description":"Persistent storage configuration (`[storage]` section).","type":"object","properties":{"provider":{"description":"Storage provider settings (e.g. sqlite, postgres).","$ref":"#/$defs/StorageProviderSection","default":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}}},"StorageProviderConfig":{"description":"Storage provider backend configuration (e.g. postgres connection details).","type":"object","properties":{"connect_timeout_secs":{"description":"Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"db_url":{"description":"Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.","type":["string","null"],"default":null},"pool_max_size":{"description":"Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.","type":"integer","format":"uint","default":32,"minimum":0},"provider":{"description":"Storage engine key (e.g. \"postgres\", \"sqlite\").","type":"string","default":""},"schema":{"description":"Database schema for SQL backends.","type":"string","default":"public"},"table":{"description":"Table name for memory entries.","type":"string","default":"memories"}}},"StorageProviderSection":{"description":"Wrapper for the storage provider configuration section.","type":"object","properties":{"config":{"description":"Storage provider backend settings.","$ref":"#/$defs/StorageProviderConfig","default":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"StreamMode":{"description":"Streaming mode for channels that support progressive message updates.","oneOf":[{"description":"No streaming -- send the complete response as a single message (default).","type":"string","const":"off"},{"description":"Update a draft message with every flush interval.","type":"string","const":"partial"}]},"TailscaleTunnelConfig":{"type":"object","properties":{"funnel":{"description":"Use Tailscale Funnel (public internet) vs Serve (tailnet only)","type":"boolean","default":false},"hostname":{"description":"Optional hostname override","type":["string","null"]}}},"TaskRoutingConfig":{"description":"Lightweight pre-LLM task routing.","type":"object","properties":{"default_intent":{"description":"Fallback intent when no rule matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"rules":{"description":"Rules evaluated in descending priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/TaskRoutingRule"}}}},"TaskRoutingIntentConfig":{"description":"Task-routing default and rule intent.","type":"string","enum":["simple","delegate","stream"]},"TaskRoutingRule":{"description":"A single task-routing rule.","type":"object","properties":{"intent":{"description":"Route intent to apply when a keyword matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"model_hint":{"description":"Optional model hint/raw model for non-delegated requests.","type":["string","null"],"default":null},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0},"sub_agent_model":{"description":"Optional raw sub-agent model override for delegated tasks.","type":["string","null"],"default":null}}},"TelegramConfig":{"description":"Telegram bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Telegram user IDs or usernames. Empty = deny all.","type":"array","items":{"type":"string"}},"bot_token":{"description":"Telegram Bot API token (from @BotFather).","type":"string"},"draft_update_interval_ms":{"description":"Minimum interval (ms) between draft message edits to avoid rate limits.","type":"integer","format":"uint64","default":1000,"minimum":0},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"interrupt_on_new_message":{"description":"When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.","type":"boolean","default":false},"stream_mode":{"description":"Streaming mode for progressive response delivery via message edits.","$ref":"#/$defs/StreamMode","default":"off"}},"required":["bot_token","allowed_users"]},"ToolCallDialectSetting":{"description":"The tool-call grammars an operator may declare for an endpoint.","oneOf":[{"description":"Only the native `tool_calls` array is a tool call (the default).","type":"string","const":"native"},{"description":"Additionally read `{json}` from the content,\nfor a tool name the request registered.","type":"string","const":"xml_function_tags"}]},"ToolSchemaDialectSetting":{"description":"The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.","oneOf":[{"description":"The published document, byte for byte (the default).","type":"string","const":"raw"},{"description":"The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.","type":"string","const":"no_root_combinators"}]},"ToolTieringConfig":{"description":"Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.","type":"object","properties":{"always_exclude":{"description":"Tool names excluded from capability publication.","type":"array","default":[],"items":{"type":"string"}},"always_include":{"description":"Tool names preferred for direct publication, subject to admission gates.","type":"array","default":[],"items":{"type":"string"}},"channel_exclude":{"description":"Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefaults to [`DEFAULT_CHANNEL_EXCLUDED_TOOLS`]; set to `[]` to expose the\nfull operator surface on channels again.","type":"array","default":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","skills_manage","memory_reindex","document_sync","document_ingest"],"items":{"type":"string"}}}},"TunnelConfig":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.","type":"object","properties":{"cloudflare":{"description":"Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).","anyOf":[{"$ref":"#/$defs/CloudflareTunnelConfig"},{"type":"null"}],"default":null},"custom":{"description":"Custom tunnel command configuration (used when `provider = \"custom\"`).","anyOf":[{"$ref":"#/$defs/CustomTunnelConfig"},{"type":"null"}],"default":null},"ngrok":{"description":"ngrok tunnel configuration (used when `provider = \"ngrok\"`).","anyOf":[{"$ref":"#/$defs/NgrokTunnelConfig"},{"type":"null"}],"default":null},"provider":{"description":"Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.","type":"string","default":"none"},"tailscale":{"description":"Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).","anyOf":[{"$ref":"#/$defs/TailscaleTunnelConfig"},{"type":"null"}],"default":null}}},"UserPolicyConfig":{"description":"Startup user policy entry (`[[user_policies]]`).","type":"object","properties":{"blocked_patterns":{"type":"array","default":[],"items":{"type":"string"}},"projects":{"type":"array","default":[],"items":{"type":"string"}},"role":{"type":"string","default":"guest"},"user_id":{"type":"string"},"visibility_ceiling":{"type":"string","default":"private"}},"required":["user_id"]},"WacliConfig":{"description":"wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```","type":"object","properties":{"allow_unsigned_loopback":{"description":"Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).","type":"boolean","default":false},"allowed_from":{"description":"Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.","type":"array","default":["*"],"items":{"type":"string"}},"bot_jid":{"description":"Bot's own JID, used for reply-to-bot mention detection.","type":["string","null"],"default":null},"bot_lid":{"description":"The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.","type":["string","null"],"default":null},"bot_number":{"description":"Bot's own phone number (digits), used for `@` mention detection.","type":["string","null"],"default":null},"cli_path":{"description":"Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.","type":["string","null"],"default":null},"group_reply_mode":{"description":"Smart group-reply mode. When `None`, derived from `mention_only`.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"host":{"description":"REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].","type":["string","null"],"writeOnly":true},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"outbound_media_workspace_only":{"description":"Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.","type":"boolean","default":false},"port":{"description":"REMOVED: legacy JSON-RPC daemon port. See `host`.","type":["integer","null"],"format":"uint16","maximum":65535,"minimum":0,"writeOnly":true},"self_chat_mode":{"description":"Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.","type":"boolean","default":false},"store_dir":{"description":"wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.","type":["string","null"],"default":null},"webhook_listen":{"description":"Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").","type":"string","default":"127.0.0.1:16868"},"webhook_path":{"description":"HTTP path the webhook server serves (default: \"/wacli\").","type":"string","default":"/wacli"},"webhook_secret":{"description":"HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.","type":["string","null"],"default":null}}},"WebSearchConfig":{"description":"Web search tool configuration (`[web_search]` section).","type":"object","properties":{"brave_api_key":{"description":"Brave Search API key (required if provider is \"brave\")","type":["string","null"],"default":null},"fetch_max_chars":{"description":"Maximum characters returned by `web_fetch` (default 10000)","type":"integer","format":"uint","default":50000,"minimum":0},"max_results":{"description":"Maximum results per search (1-20)","type":"integer","format":"uint","default":15,"minimum":0},"provider":{"description":"Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)","type":"string","default":"duckduckgo"},"timeout_secs":{"description":"Request timeout in seconds","type":"integer","format":"uint64","default":15,"minimum":0}}},"WebhookConfig":{"description":"Webhook channel configuration.","type":"object","properties":{"port":{"description":"Port to listen on for incoming webhooks.","type":"integer","format":"uint16","maximum":65535,"minimum":0},"secret":{"description":"Optional shared secret for webhook signature verification.","type":["string","null"]}},"required":["port"]},"WhatsAppConfig":{"description":"WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.","type":"object","properties":{"access_token":{"description":"Access token from Meta Business Suite (Cloud API mode)","type":["string","null"],"default":null},"allowed_numbers":{"description":"Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"app_secret":{"description":"App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"pair_code":{"description":"Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one","type":["string","null"],"default":null},"pair_phone":{"description":"Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used","type":["string","null"],"default":null},"phone_number_id":{"description":"Phone number ID from Meta Business API (Cloud API mode)","type":["string","null"],"default":null},"read_pool_size":{"description":"Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"session_path":{"description":"Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs","type":["string","null"],"default":null},"verify_token":{"description":"Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode","type":["string","null"],"default":null},"ws_url":{"description":"WebSocket URL override (replaces WHATSAPP_WS_URL)","type":["string","null"],"default":null}}},"WorkspaceHooks":{"description":"Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).","oneOf":[{"description":"They do not run (the default); `prx doctor` and `hooks_status` say so.","type":"string","const":"off"},{"description":"They run, in a cleared environment and a dedicated directory beside\n`config.toml`.","type":"string","const":"on"}]},"WorkspaceMcpServers":{"description":"Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).","oneOf":[{"description":"None: a workspace file may only narrow the servers defined in\n`config.toml`.","type":"string","const":"off"},{"description":"HTTP servers (still refused when they target a private address).","type":"string","const":"http_only"},{"description":"HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.","type":"string","const":"stdio"}]},"XinConfig":{"description":"Configuration for the xin autonomous task engine (`[xin]`).","type":"object","properties":{"adopt_legacy_tasks":{"description":"Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).","type":"boolean","default":false},"interval_minutes":{"description":"Tick interval in minutes (minimum 1). Default: 5.","type":"integer","format":"uint32","default":5,"minimum":0},"stale_timeout_minutes":{"description":"Minutes after which a running task is marked stale. Default: 60.","type":"integer","format":"uint32","default":60,"minimum":0}}},"AgentMessaging":{"description":"Owner-controlled inbound session messaging (enabled unless explicitly off).","type":"object","properties":{"inbound":{"type":"boolean","default":true}}}}} +{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Config","description":"Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).","type":"object","properties":{"a2a":{"description":"Agent-to-Agent compatibility configuration (`[a2a]`).","$ref":"#/$defs/A2aConfig","default":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trusted_trust_domains":[],"trust_domain":"prx.local"}},"agent":{"description":"Agent orchestration settings (`[agent]`).","$ref":"#/$defs/AgentConfig","default":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2,"messaging":{"inbound":true}}},"agents":{"description":"Delegate agent configurations for multi-agent workflows.","type":"object","additionalProperties":{"$ref":"#/$defs/DelegateAgentConfig"},"default":{}},"api_key":{"description":"API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.","type":["string","null"],"default":null},"api_url":{"description":"Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)","type":["string","null"],"default":null},"auth":{"description":"Auth profile and external credential import settings (`[auth]`).","$ref":"#/$defs/AuthConfig","default":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"}},"autonomy":{"description":"Autonomy and security policy configuration (`[autonomy]`).","$ref":"#/$defs/AutonomyConfig","default":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":500,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true}},"browser":{"description":"Browser automation configuration (`[browser]`).","$ref":"#/$defs/BrowserConfig","default":{"allowed_domains":[],"computer_use":{"api_key":null}}},"channels_config":{"description":"Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).","$ref":"#/$defs/ChannelsConfig","default":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null}},"chat":{"description":"Interactive chat UI configuration (`[chat]`).","$ref":"#/$defs/ChatConfig","default":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2}},"compliance":{"description":"Operator-owned compliance controls (`[compliance]`).","$ref":"#/$defs/ComplianceConfig","default":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}},"composio":{"description":"Composio managed OAuth tools integration (`[composio]`).","$ref":"#/$defs/ComposioConfig","default":{"api_key":null,"entity_id":"default"}},"cost":{"description":"Cost tracking and budget enforcement configuration (`[cost]`).","$ref":"#/$defs/CostConfig","default":{"allow_override":false,"daily_limit_usd":10.0,"monthly_limit_usd":100.0,"prices":{},"warn_at_percent":80}},"cron":{"description":"Cron job configuration (`[cron]`).","$ref":"#/$defs/CronConfig","default":{"max_run_history":50}},"decision_engine":{"description":"Optional advisory decision engine, disabled by default.","$ref":"#/$defs/DecisionEngineConfig","default":{"candidates":5,"enabled":false,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"latency_budget_ms":500,"max_candidates":12,"token_ratio_limit":0.3499999940395355}},"default_model":{"description":"Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.","type":["string","null"]},"default_provider":{"description":"Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.","type":["string","null"]},"default_temperature":{"description":"Default model temperature (0.0–2.0). Default: `0.7`.","type":"number","format":"double","default":0.7},"embedding_routes":{"description":"Embedding routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/EmbeddingRouteConfig"}},"gateway":{"description":"Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).","$ref":"#/$defs/GatewayConfig","default":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60}},"heartbeat":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]`).","$ref":"#/$defs/HeartbeatConfig","default":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."}},"http_request":{"description":"HTTP request tool configuration (`[http_request]`).","$ref":"#/$defs/HttpRequestConfig","default":{"max_response_size":1000000,"timeout_secs":30}},"identity":{"description":"Identity format configuration: OpenClaw or AIEOS (`[identity]`).","$ref":"#/$defs/IdentityConfig","default":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"}},"identity_bindings":{"description":"Static identity bindings loaded at startup (`[[identity_bindings]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/IdentityBindingConfig"}},"mcp":{"description":"Secrets encryption configuration (`[secrets]`).","$ref":"#/$defs/McpConfig","default":{"servers":{}}},"mcp_server":{"description":"MCP server compatibility configuration (`[mcp_server]`).","$ref":"#/$defs/McpServerRuntimeConfig","default":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true}},"media":{"description":"Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.","$ref":"#/$defs/MediaConfig","default":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"}},"memory":{"description":"Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).","$ref":"#/$defs/MemoryConfig","default":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7}},"model_routes":{"description":"Model routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/ModelRouteConfig"}},"model_settings":{"description":"Catalog model levels and explicit parameters, keyed by canonical release ID.","type":"object","additionalProperties":{"$ref":"#/$defs/ModelSettings"},"default":{}},"multimodal":{"description":"Multimodal (image) handling configuration (`[multimodal]`).","$ref":"#/$defs/MultimodalConfig","default":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4}},"nodes":{"description":"Remote node proxy configuration (`[nodes]`).","$ref":"#/$defs/NodesConfig","default":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}},"observability":{"description":"Observability backend configuration (`[observability]`).","$ref":"#/$defs/ObservabilityConfig","default":{"backend":"none","otel_endpoint":null,"otel_service_name":null}},"plugins":{"description":"WASM plugin runtime switch (`[plugins]`), off by default.","$ref":"#/$defs/PluginsConfig","default":{"enabled":false}},"providers":{"description":"Provider-specific runtime options (`[providers.]`).","$ref":"#/$defs/ProvidersConfig","default":{"ollama":{"num_ctx":null}}},"proxy":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).","$ref":"#/$defs/ProxyConfig","default":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]}},"query_classification":{"description":"Automatic query classification — maps user messages to model hints.","$ref":"#/$defs/QueryClassificationConfig","default":{"rules":[]}},"reliability":{"description":"Reliability settings: retries, fallback providers, backoff (`[reliability]`).","$ref":"#/$defs/ReliabilityConfig","default":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2}},"router":{"description":"Heuristic LLM router configuration (`[router]`).","$ref":"#/$defs/RouterConfig","default":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]}},"runtime":{"description":"Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.","$ref":"#/$defs/RuntimeConfig","default":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null}},"scheduler":{"description":"Scheduler configuration for periodic task execution (`[scheduler]`).","$ref":"#/$defs/SchedulerConfig","default":{"claim_lease_secs":90,"max_tasks":64}},"secrets":{"$ref":"#/$defs/SecretsConfig","default":{"encrypt":true}},"security":{"description":"Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).","$ref":"#/$defs/SecurityConfig","default":{"audit":{"log_path":"audit.log","max_size_mb":100}}},"self_system":{"description":"Self-system experimental automation controls (`[self_system]`).","$ref":"#/$defs/SelfSystemConfig","default":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24}},"sessions_spawn":{"description":"Session spawning configuration (`[sessions_spawn]`).","$ref":"#/$defs/SessionsSpawnConfig","default":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null}},"skill_rag":{"description":"Dynamic skill retrieval settings (`[skill_rag]`).","$ref":"#/$defs/SkillRagConfig","default":{"top_k":32}},"skills":{"description":"Skills loading and community repository behavior (`[skills]`).","$ref":"#/$defs/SkillsConfig","default":{"open_skills_dir":null,"openclaw_skills_dir":null}},"skills_lifecycle":{"description":"Skill lifecycle (`[skills_lifecycle]`), off by default.","$ref":"#/$defs/SkillsLifecycleConfig","default":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]}},"smart_group":{"description":"Smart group-reply pre-gate configuration (`[smart_group]`).","$ref":"#/$defs/SmartGroupConfig","default":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5}},"storage":{"description":"Persistent storage provider configuration (`[storage]`).","$ref":"#/$defs/StorageConfig","default":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"task_routing":{"description":"Task routing configuration — classifies work by intent before the main agent loop.","$ref":"#/$defs/TaskRoutingConfig","default":{"default_intent":"simple","rules":[]}},"tool_tiering":{"description":"Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).","$ref":"#/$defs/ToolTieringConfig","default":{"always_exclude":[],"always_include":[],"channel_exclude":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","skills_manage","memory_reindex","document_sync","document_ingest"]}},"tunnel":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]`).","$ref":"#/$defs/TunnelConfig","default":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null}},"user_policies":{"description":"Static user policy records loaded at startup (`[[user_policies]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/UserPolicyConfig"}},"web_search":{"description":"Web search tool configuration (`[web_search]`).","$ref":"#/$defs/WebSearchConfig","default":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15}},"webhook":{"description":"Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).","$ref":"#/$defs/MemoryWebhookConfig","default":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null}},"xin":{"description":"Xin autonomous task engine configuration (`[xin]`).","$ref":"#/$defs/XinConfig","default":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}}},"$defs":{"A2aConfig":{"type":"object","properties":{"agent_id":{"description":"Stable PRX agent identifier advertised to peers.","type":"string","default":"prx-default"},"allowed_peer_issuers":{"description":"Accepted external peer issuers.","type":"array","default":[],"items":{"type":"string"}},"bind":{"description":"Advertised bind address.","type":"string","default":"127.0.0.1:16832"},"card_jwks_uri":{"description":"Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.","type":["string","null"],"default":null},"card_signing_key_path":{"description":"On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).","type":["string","null"],"default":null},"card_ttl_seconds":{"description":"Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.","type":"integer","format":"uint64","default":3600,"minimum":0},"discovery_advertised":{"description":"Whether to advertise into an external A2A registry.","type":"boolean","default":false},"handoff_nonce_ttl_seconds":{"description":"Replay window for future handoff delegation tokens.","type":"integer","format":"uint64","default":3600,"minimum":0},"messaging_enabled":{"description":"Enable the dedicated pinned mTLS messaging listener.","type":"boolean","default":false},"peers":{"type":"object","additionalProperties":{"$ref":"#/$defs/A2aPeer"},"default":{}},"spiffe_id":{"description":"Local SPIFFE-style identifier placeholder.","type":"string","default":"spiffe://prx-local/agent/prx-default"},"spiffe_strict_validation":{"description":"When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.","type":"boolean","default":false},"spiffe_trust_bundle_pem":{"description":"Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).","type":["string","null"],"default":null},"trusted_trust_domains":{"description":"Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).","type":"array","default":[],"items":{"type":"string"}},"trust_domain":{"description":"SPIFFE trust domain for new instance identities.","type":"string","default":"prx.local"}}},"A2aPeer":{"description":"Explicit pinned identity and local recipient grant.","type":"object","properties":{"spiffe_id":{"type":"string"},"fingerprints":{"type":"array","items":{"type":"string"}},"address":{"type":"string"},"owner":{"type":"string"},"sessions":{"type":"array","default":["*"],"items":{"type":"string"}},"agents":{"type":"array","default":["*"],"items":{"type":"string"}}},"required":["spiffe_id","fingerprints","address","owner"],"additionalProperties":false},"AgentCompactionConfig":{"description":"Agent context compaction configuration (`[agent.compaction]`).","type":"object","properties":{"keep_recent_messages":{"description":"Number of recent non-system messages to keep after compaction.","type":"integer","format":"uint","default":12,"minimum":0},"max_context_tokens":{"description":"Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.","type":"integer","format":"uint","default":128000,"minimum":0},"memory_flush":{"description":"Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.","type":"boolean","default":true},"mode":{"description":"Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).","$ref":"#/$defs/AgentCompactionMode","default":"switch"},"os_paging":{"description":"Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.","$ref":"#/$defs/OsPagingConfig","default":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"}},"reserve_tokens":{"description":"Tokens reserved for the next model response.","type":"integer","format":"uint","default":4096,"minimum":0}}},"AgentCompactionMode":{"description":"Compaction mode for long conversation contexts.","oneOf":[{"description":"Disable proactive compaction.","type":"string","const":"off"},{"description":"Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.","type":"string","const":"switch"},{"description":"Conservative compaction that prefers summary replacement.","type":"string","const":"safeguard"},{"description":"Aggressive truncation mode for tighter contexts.","type":"string","const":"aggressive"}]},"AgentConfig":{"description":"Agent orchestration configuration (`[agent]` section).","type":"object","properties":{"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"compact_context":{"description":"When true: bootstrap_max_chars=6000. Use for 13B or smaller models.","type":"boolean","default":false},"compaction":{"description":"Context compaction controls (`[agent.compaction]`).","$ref":"#/$defs/AgentCompactionConfig","default":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096}},"low_priority_tools":{"description":"Tool names treated as low-priority when `priority_scheduling_enabled = true`.","type":"array","default":["sessions_spawn","delegate"],"items":{"type":"string"}},"priority_scheduling_enabled":{"description":"Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.","type":"boolean","default":false},"read_only_tool_concurrency_window":{"description":"Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.","type":"integer","format":"uint","default":2,"minimum":0},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}}},"AgentLimits":{"description":"Optional admission limits for rf-started turns of a named agent.","type":"object","properties":{"max_concurrent_turns":{"type":["integer","null"],"format":"uint32","minimum":0},"max_cost_per_day_cents":{"type":["integer","null"],"format":"uint64","minimum":0}},"additionalProperties":false},"AuditConfig":{"description":"Audit logging configuration","type":"object","properties":{"log_path":{"description":"Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).","type":"string","default":"audit.log"},"max_size_mb":{"description":"Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).","type":"integer","format":"uint32","default":100,"minimum":0}}},"AuthConfig":{"description":"Authentication and external credential import configuration (`[auth]` section).","type":"object","properties":{"codex_auth_json_auto_import":{"description":"Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.","type":"boolean","default":false},"codex_auth_json_path":{"description":"Source path for Codex CLI auth.json import.","type":"string","default":"~/.codex/auth.json"}}},"AutonomyConfig":{"type":"object","properties":{"acknowledge_unrestricted_profile":{"description":"Operator acknowledgement for an intentionally unrestricted profile.\nThis suppresses doctor noise only; it does not alter policy behavior.","type":"boolean","default":false},"forbidden_paths":{"description":"Explicit path denylist. Default includes system-critical paths.\n\nFails closed: omitting the key keeps the built-in list rather than\nemptying it, so a partial `[autonomy]` section never removes the\ndenylist.","type":"array","default":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"items":{"type":"string"}},"level":{"description":"Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).","$ref":"#/$defs/AutonomyLevel","default":"full"},"max_cost_per_day_cents":{"description":"Maximum cost per day in cents per policy. Default: `500`.","type":"integer","format":"uint32","default":500,"minimum":0},"scopes":{"description":"Scope-based tool access control: per-user/channel/chat-type allow/deny rules.","$ref":"#/$defs/ScopeConfig","default":{"assign_owners":[],"default":"allow","rules":[]}},"workspace_only":{"description":"Restrict file writes and command paths to the workspace directory. Default: `true`.\n\nFails closed: a `[autonomy]` section that omits this key keeps the\nworkspace restriction on, so a partial section can never widen the\nfilesystem reach by accident.","type":"boolean","default":true}}},"AutonomyLevel":{"description":"How much autonomy the agent has","oneOf":[{"description":"Read-only: can observe but not act","type":"string","const":"readonly"},{"description":"Supervised: acts but requires approval for risky operations","type":"string","const":"supervised"},{"description":"Full: autonomous execution within policy bounds","type":"string","const":"full"}]},"BackendSelection":{"description":"Which decision backend runs: `auto` (the factory's order) or one kind.","type":"string"},"BrowserComputerUseConfig":{"description":"Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.","type":"object","properties":{"api_key":{"description":"Optional bearer token (retained only for config secret handling).","type":["string","null"],"default":null}}},"BrowserConfig":{"description":"Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.","type":"object","properties":{"allowed_domains":{"description":"Allowed domains for `web_fetch` (exact or subdomain match).","type":"array","default":[],"items":{"type":"string"}},"computer_use":{"description":"Computer-use sidecar config (retained only for `api_key` secret handling).","$ref":"#/$defs/BrowserComputerUseConfig","default":{"api_key":null}}}},"ChannelsConfig":{"description":"Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.","type":"object","properties":{"cli":{"description":"Enable the CLI interactive channel. Default: `true`.","type":"boolean","default":true},"dingtalk":{"description":"DingTalk channel configuration.","anyOf":[{"$ref":"#/$defs/DingTalkConfig"},{"type":"null"}]},"discord":{"description":"Discord bot channel configuration.","anyOf":[{"$ref":"#/$defs/DiscordConfig"},{"type":"null"}]},"email":{"description":"Email channel configuration.","anyOf":[{"$ref":"#/$defs/EmailConfig"},{"type":"null"}]},"imessage":{"description":"iMessage channel configuration (macOS only).","anyOf":[{"$ref":"#/$defs/IMessageConfig"},{"type":"null"}]},"irc":{"description":"IRC channel configuration.","anyOf":[{"$ref":"#/$defs/IrcConfig"},{"type":"null"}]},"lark":{"description":"Lark/Feishu channel configuration.","anyOf":[{"$ref":"#/$defs/LarkConfig"},{"type":"null"}]},"linq":{"description":"Linq Partner API channel configuration.","anyOf":[{"$ref":"#/$defs/LinqConfig"},{"type":"null"}]},"mattermost":{"description":"Mattermost bot channel configuration.","anyOf":[{"$ref":"#/$defs/MattermostConfig"},{"type":"null"}]},"nextcloud_talk":{"description":"Nextcloud Talk bot channel configuration.","anyOf":[{"$ref":"#/$defs/NextcloudTalkConfig"},{"type":"null"}]},"qq":{"description":"QQ Official Bot channel configuration.","anyOf":[{"$ref":"#/$defs/QQConfig"},{"type":"null"}]},"ramflux":{"description":"Local ramflux agent-host bridge.","anyOf":[{"$ref":"#/$defs/RamfluxConfig"},{"type":"null"}],"default":null},"signal":{"description":"Signal channel configuration.","anyOf":[{"$ref":"#/$defs/SignalConfig"},{"type":"null"}]},"slack":{"description":"Slack bot channel configuration.","anyOf":[{"$ref":"#/$defs/SlackConfig"},{"type":"null"}]},"telegram":{"description":"Telegram bot channel configuration.","anyOf":[{"$ref":"#/$defs/TelegramConfig"},{"type":"null"}]},"wacli":{"description":"wacli JSON-RPC daemon channel configuration.","anyOf":[{"$ref":"#/$defs/WacliConfig"},{"type":"null"}],"default":null},"webhook":{"description":"Webhook channel configuration.","anyOf":[{"$ref":"#/$defs/WebhookConfig"},{"type":"null"}]},"whatsapp":{"description":"WhatsApp channel configuration (Cloud API or Web mode).","anyOf":[{"$ref":"#/$defs/WhatsAppConfig"},{"type":"null"}]}}},"ChatConfig":{"description":"Interactive chat configuration (`[chat]`).","type":"object","properties":{"daemon":{"description":"How this chat process reaches the daemon it borrows channels from.","$ref":"#/$defs/ChatDaemonConfig","default":{"token":"","url":""}},"max_concurrent_visible_turns":{"description":"Maximum concurrent visible provider turns in the TUI Redux driver.","type":"integer","format":"uint","default":2,"minimum":0}}},"ChatDaemonConfig":{"description":"Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.","type":"object","properties":{"token":{"description":"Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.","type":"string","default":""},"url":{"description":"Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.","type":"string","default":""}}},"CircuitBreakerConfig":{"description":"The per-backend circuit breaker.","type":"object","properties":{"cooldown_secs":{"description":"Seconds the breaker stays open (1 to 3600).","type":"integer","format":"uint32","default":60,"minimum":0},"failure_threshold":{"description":"Consecutive failures before the breaker opens (1 to 100).","type":"integer","format":"uint32","default":5,"minimum":0}}},"ClassificationRule":{"description":"A single classification rule mapping message patterns to a model hint.","type":"object","properties":{"hint":{"description":"Must match a `[[model_routes]]` hint value.","type":"string"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"max_length":{"description":"Only match if message length <= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"min_length":{"description":"Only match if message length >= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"patterns":{"description":"Case-sensitive literal matches (for \"```\", \"fn \", etc.).","type":"array","default":[],"items":{"type":"string"}},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0}},"required":["hint"]},"CloudflareTunnelConfig":{"type":"object","properties":{"token":{"description":"Cloudflare Tunnel token (from Zero Trust dashboard)","type":"string"}},"required":["token"]},"ComplianceConfig":{"type":"object","properties":{"eu_ai_act":{"$ref":"#/$defs/EuAiActComplianceConfig","default":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null}},"interaction_notice":{"$ref":"#/$defs/InteractionNoticeConfig","default":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}}},"ComposioConfig":{"description":"Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.","type":"object","properties":{"api_key":{"description":"Composio API key (stored encrypted when secrets.encrypt = true)","type":["string","null"],"default":null},"entity_id":{"description":"Default entity ID for multi-user setups","type":"string","default":"default"}}},"CostConfig":{"description":"Cost tracking and budget enforcement configuration (`[cost]` section).","type":"object","properties":{"allow_override":{"description":"Allow requests to exceed budget with --override flag (default: false)","type":"boolean","default":false},"daily_limit_usd":{"description":"Daily spending limit in USD (default: 10.00)","type":"number","format":"double","default":10.0},"monthly_limit_usd":{"description":"Monthly spending limit in USD (default: 100.00)","type":"number","format":"double","default":100.0},"prices":{"description":"Per-model pricing (USD per 1M tokens)","type":"object","additionalProperties":{"$ref":"#/$defs/ModelPricing"},"default":{}},"warn_at_percent":{"description":"Warn when spending reaches this percentage of limit (default: 80)","type":"integer","format":"uint8","default":80,"maximum":255,"minimum":0}}},"CredentialRefSetting":{"description":"Which credential a decision backend uses. A reference, never a secret.","type":"string"},"CronConfig":{"description":"Cron job configuration (`[cron]` section).","type":"object","properties":{"max_run_history":{"description":"Maximum number of historical cron run records to retain. Default: `50`.","type":"integer","format":"uint32","default":50,"minimum":0}}},"CustomTunnelConfig":{"type":"object","properties":{"health_url":{"description":"Optional URL to check tunnel health","type":["string","null"]},"start_command":{"description":"Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"","type":"string"},"url_pattern":{"description":"Optional regex to extract public URL from command stdout","type":["string","null"]}},"required":["start_command"]},"DecisionBackendConfig":{"description":"The decision backend (`[decision_engine.backend]`).","type":"object","properties":{"circuit_breaker":{"description":"The circuit breaker.","$ref":"#/$defs/CircuitBreakerConfig","default":{"cooldown_secs":60,"failure_threshold":5}},"credential_ref":{"description":"The credential reference: `\"\"`, `\"none\"` or `cred-`.","$ref":"#/$defs/CredentialRefSetting","default":""},"endpoint":{"description":"The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.","type":"string","default":""},"kind":{"description":"`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).","$ref":"#/$defs/BackendSelection","default":"auto"},"max_request_bytes":{"description":"Largest request body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":65536,"minimum":0},"max_response_bytes":{"description":"Largest response body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":262144,"minimum":0},"model":{"description":"The model the endpoint serves; one exact version for a hosted\nservice.","type":"string","default":""},"pinned_snapshot":{"description":"The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.","type":"string"},"remote_enabled":{"description":"Whether decision state may leave this machine. Default `false`.","type":"boolean","default":false},"timeout_ms":{"description":"Transport timeout (10 ms up to the extra latency budget).","type":"integer","format":"uint32","default":250,"minimum":0}}},"DecisionEngineConfig":{"type":"object","properties":{"backend":{"anyOf":[{"$ref":"#/$defs/DecisionBackendConfig"},{"type":"null"}]},"candidates":{"type":"integer","format":"uint32","default":5,"minimum":0},"enabled":{"type":"boolean","default":false},"mode":{"$ref":"#/$defs/DecisionMode","default":"pre"},"observe_queue":{"type":"integer","format":"uint32","default":64,"minimum":0},"prompt_budget_tokens":{"type":"integer","format":"uint32","default":300,"minimum":0},"telemetry_cap":{"type":"integer","format":"uint32","default":1000,"minimum":0},"timeout_ms":{"type":"integer","format":"uint32","default":1500,"minimum":0},"latency_budget_ms":{"description":"The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.","type":"integer","format":"uint64","default":500,"minimum":0},"token_ratio_limit":{"description":"Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).","type":"number","format":"float","default":0.3499999940395355},"max_candidates":{"description":"The most candidates a turn considers (1 to 32).","type":"integer","format":"uint8","default":12,"maximum":255,"minimum":0}}},"DecisionMode":{"type":"string","enum":["pre","post","both"]},"DeclarationOfConformityConfig":{"type":"object","properties":{"applicable_union_law":{"type":"array","default":[],"items":{"type":"string"}},"artifact_path":{"type":["string","null"],"default":null},"artifact_version":{"type":["string","null"],"default":null},"conformity_assessment_procedure":{"type":["string","null"],"default":null},"conformity_statement":{"type":["string","null"],"default":null},"harmonised_standards":{"type":"array","default":[],"items":{"type":"string"}},"issue_date":{"type":["string","null"],"default":null},"issue_place":{"type":["string","null"],"default":null},"notified_body_certificate":{"type":["string","null"],"default":null},"notified_body_identification_number":{"type":["string","null"],"default":null},"notified_body_name":{"type":["string","null"],"default":null},"personal_data_compliance_statement":{"type":["string","null"],"default":null},"processes_personal_data":{"type":"boolean","default":false},"provider_address":{"type":["string","null"],"default":null},"provider_name":{"type":["string","null"],"default":null},"signer_function":{"type":["string","null"],"default":null},"signer_name":{"type":["string","null"],"default":null},"signer_on_behalf_of":{"type":["string","null"],"default":null},"sole_responsibility_statement":{"type":["string","null"],"default":null},"standards_not_applicable_reason":{"type":["string","null"],"default":null},"system_name":{"type":["string","null"],"default":null},"system_reference":{"type":["string","null"],"default":null},"system_type":{"type":["string","null"],"default":null}}},"DelegateAgentConfig":{"description":"Configuration for a delegate sub-agent used by the `delegate` tool.","type":"object","properties":{"agentic":{"description":"Agentic sub-agent mode (multi-turn tool-call loop). Default true; an\nexplicit `false` makes the agent answer-only with no tools.","type":"boolean","default":true},"allowed_tools":{"description":"Allowlist of tool names available to the sub-agent in agentic mode.\nEmpty or omitted means all tools, the same as `[\"*\"]`.","type":"array","default":[],"items":{"type":"string"}},"api_key":{"description":"Optional API key override","type":["string","null"],"default":null},"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"autonomy":{"description":"The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.","anyOf":[{"$ref":"#/$defs/AutonomyLevel"},{"type":"null"}]},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"enabled":{"description":"Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.","type":"boolean","default":true},"identity_dir":{"description":"Optional identity files directory relative to workspace root.","type":["string","null"],"default":null},"limits":{"$ref":"#/$defs/AgentLimits","default":{"max_concurrent_turns":null,"max_cost_per_day_cents":null}},"max_depth":{"description":"Max recursion depth for nested delegation","type":"integer","format":"uint32","default":8,"minimum":0},"memory_scope":{"description":"Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".","type":["string","null"],"default":null},"model":{"description":"Model name","type":"string"},"provider":{"description":"Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")","type":"string"},"spawn_enabled":{"description":"Whether this agent is allowed to be targeted by sessions_spawn (default: true).","type":["boolean","null"],"default":null},"system_prompt":{"description":"Optional system prompt for the sub-agent","type":["string","null"],"default":null},"temperature":{"description":"Temperature override","type":["number","null"],"format":"double","default":null},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}},"required":["provider","model"]},"DingTalkConfig":{"description":"DingTalk configuration for Stream Mode messaging","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"client_id":{"description":"Client ID (AppKey) from DingTalk developer console","type":"string"},"client_secret":{"description":"Client Secret (AppSecret) from DingTalk developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["client_id","client_secret"]},"DiscordConfig":{"description":"Discord bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Discord user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Discord bot token (from Discord Developer Portal).","type":"string"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"guild_id":{"description":"Optional guild (server) ID to restrict the bot to a single guild.","type":["string","null"]},"listen_to_bots":{"description":"When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.","type":"boolean","default":false}},"required":["bot_token"]},"DmPolicy":{"description":"Policy for direct-message handling.","oneOf":[{"description":"Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).","type":"string","const":"pairing"},{"description":"Accept only senders listed in `allowed_from`.","type":"string","const":"allowlist"},{"description":"Accept any direct sender.","type":"string","const":"open"},{"description":"Ignore direct messages.","type":"string","const":"disabled"}]},"DockerRuntimeConfig":{"description":"Docker runtime configuration (`[runtime.docker]` section).","type":"object","properties":{"allowed_workspace_roots":{"description":"Optional workspace root allowlist for Docker mount validation.","type":"array","default":[],"items":{"type":"string"}},"cpu_limit":{"description":"Optional CPU limit (`None` = no explicit limit).","type":["number","null"],"format":"double","default":1.0},"image":{"description":"Runtime image used to execute shell commands.","type":"string","default":"alpine:3.20"},"memory_limit_mb":{"description":"Optional memory limit in MB (`None` = no explicit limit).","type":["integer","null"],"format":"uint64","default":512,"minimum":0},"mount_workspace":{"description":"Mount configured workspace into `/workspace`.","type":"boolean","default":true},"network":{"description":"Docker network mode (`none`, `bridge`, etc.).","type":"string","default":"none"},"read_only_rootfs":{"description":"Mount root filesystem as read-only.","type":"boolean","default":true}}},"EmailConfig":{"description":"Email channel configuration","type":"object","properties":{"allowed_senders":{"description":"Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)","type":"array","default":[],"items":{"type":"string"}},"from_address":{"description":"From address for outgoing emails","type":"string"},"idle_timeout_secs":{"description":"IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes","type":"integer","format":"uint64","default":1740,"minimum":0},"imap_folder":{"description":"IMAP folder to poll (default: INBOX)","type":"string","default":"INBOX"},"imap_host":{"description":"IMAP server hostname","type":"string"},"imap_port":{"description":"IMAP server port (default: 993 for TLS)","type":"integer","format":"uint16","default":993,"maximum":65535,"minimum":0},"password":{"description":"Email password for authentication","type":"string"},"smtp_host":{"description":"SMTP server hostname","type":"string"},"smtp_port":{"description":"SMTP server port (default: 465 for TLS)","type":"integer","format":"uint16","default":465,"maximum":65535,"minimum":0},"smtp_tls":{"description":"Use TLS for SMTP (default: true)","type":"boolean","default":true},"username":{"description":"Email username for authentication","type":"string"}},"required":["imap_host","smtp_host","username","password","from_address"]},"EmbeddingRouteConfig":{"description":"Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"dimensions":{"description":"Optional embedding dimension override for this route","type":["integer","null"],"format":"uint","default":null,"minimum":0},"hint":{"description":"Route hint name (e.g. \"semantic\", \"archive\", \"faq\")","type":"string"},"model":{"description":"Embedding model to use with that provider","type":"string"},"provider":{"description":"Embedding provider (`none`, `openai`, or `custom:`)","type":"string"}},"required":["hint","provider","model"]},"EuAiActClassificationConfig":{"type":"object","properties":{"assessed_at":{"type":["string","null"],"default":null},"owner":{"type":["string","null"],"default":null},"status":{"$ref":"#/$defs/EuAiActRiskClassification","default":"unclassified"}}},"EuAiActComplianceConfig":{"type":"object","properties":{"classification":{"$ref":"#/$defs/EuAiActClassificationConfig","default":{"assessed_at":null,"owner":null,"status":"unclassified"}},"declaration":{"$ref":"#/$defs/DeclarationOfConformityConfig","default":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null}},"incident_store_path":{"type":["string","null"],"default":null}}},"EuAiActRiskClassification":{"type":"string","enum":["unclassified","high_risk","not_high_risk"]},"FitnessConfig":{"description":"Calendar schedule, evidence thresholds, and retention for fitness v2.","type":"object","properties":{"auto_run":{"description":"Run the daily fitness worker in daemon mode.","type":"boolean","default":true},"max_backfill_days":{"description":"Maximum number of closed days recovered after downtime.","type":"integer","format":"uint32","default":7,"minimum":0},"min_coverage":{"description":"Minimum available metric weight required to publish a final score.","type":"number","format":"double","default":0.6},"min_samples":{"description":"Minimum samples required before an evidence-derived subscore is usable.","type":"integer","format":"uint","default":5,"minimum":0},"retention_days":{"description":"Number of daily JSON reports retained on disk.","type":"integer","format":"uint32","default":180,"minimum":0},"run_at":{"description":"Local wall-clock time (`HH:MM`) at which the previous day is scored.","type":"string","default":"00:10"},"timezone":{"description":"IANA timezone used to define closed calendar days.","type":"string","default":"UTC"}}},"GatewayConfig":{"description":"Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.","type":"object","properties":{"allow_public_bind":{"description":"Allow binding to non-localhost without a tunnel (default: false)","type":"boolean","default":false},"api_rate_limit_per_minute":{"description":"Max `/api/*` requests per minute per authenticated token.","type":"integer","format":"uint32","default":60,"minimum":0},"channel_webhook_dedup_ttl_secs":{"description":"How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.","type":"integer","format":"uint64","default":86400,"minimum":0},"host":{"description":"Gateway host (default: 127.0.0.1)","type":"string","default":"127.0.0.1"},"idempotency_max_keys":{"description":"Maximum distinct idempotency keys retained in memory.","type":"integer","format":"uint","default":10000,"minimum":0},"idempotency_ttl_secs":{"description":"TTL for webhook idempotency keys.","type":"integer","format":"uint64","default":300,"minimum":0},"pair_rate_limit_per_minute":{"description":"Max `/pair` requests per minute per client key.","type":"integer","format":"uint32","default":10,"minimum":0},"paired_tokens":{"description":"Paired bearer tokens (managed automatically, not user-edited)","type":"array","default":[],"items":{"type":"string"}},"port":{"description":"Gateway port (default: 16830)","type":"integer","format":"uint16","default":16830,"maximum":65535,"minimum":0},"rate_limit_max_keys":{"description":"Maximum distinct client keys tracked by gateway rate limiter maps.","type":"integer","format":"uint","default":10000,"minimum":0},"require_pairing":{"description":"Require pairing before accepting requests (default: true)","type":"boolean","default":true},"targeted_agents":{"description":"Switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). Default true. While false, any\notherwise-valid named target answers 409 `agent_disabled` and never\nruns as Main.","type":"boolean","default":true},"trust_forwarded_headers":{"description":"Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.","type":"boolean","default":false},"webhook_rate_limit_per_minute":{"description":"Max `/webhook` requests per minute per client key.","type":"integer","format":"uint32","default":60,"minimum":0}}},"GroupPolicy":{"description":"Policy for group-message handling.","oneOf":[{"description":"Accept only groups listed in `group_allow_from`.","type":"string","const":"allowlist"},{"description":"Accept any group.","type":"string","const":"open"},{"description":"Ignore group messages.","type":"string","const":"disabled"}]},"GroupReplyMode":{"description":"How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.","oneOf":[{"description":"Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).","type":"string","const":"off"},{"description":"Reply only when the bot is @-mentioned (legacy `mention_only = true`).","type":"string","const":"mention-only"},{"description":"Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).","type":"string","const":"smart"}]},"HeartbeatConfig":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]` section).","type":"object","properties":{"active_hours":{"description":"Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.","type":"array","default":[8,23],"items":{"type":"integer","format":"uint8","maximum":255,"minimum":0}},"interval_minutes":{"description":"Interval in minutes between heartbeat pings. Default: `30`.","type":"integer","format":"uint32","default":30,"minimum":0},"prompt":{"description":"Prompt used by heartbeat worker when dispatching tasks.","type":"string","default":"Check HEARTBEAT.md and follow instructions."}}},"HttpRequestConfig":{"description":"HTTP request tool configuration (`[http_request]` section).","type":"object","properties":{"max_response_size":{"description":"Maximum response size in bytes (default: 1MB)","type":"integer","format":"uint","default":1000000,"minimum":0},"timeout_secs":{"description":"Request timeout in seconds (default: 30)","type":"integer","format":"uint64","default":30,"minimum":0}}},"IMessageConfig":{"description":"iMessage channel configuration (macOS only).","type":"object","properties":{"allowed_contacts":{"description":"Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.","type":"array","items":{"type":"string"}},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["allowed_contacts"]},"IdentityBindingConfig":{"description":"Startup identity binding entry (`[[identity_bindings]]`).","type":"object","properties":{"channel":{"type":"string"},"channel_account":{"type":"string"},"display_name":{"type":["string","null"],"default":null},"user_id":{"type":"string"}},"required":["user_id","channel","channel_account"]},"IdentityConfig":{"description":"Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.","type":"object","properties":{"aieos_inline":{"description":"Inline AIEOS JSON (alternative to file path)","type":["string","null"],"default":null},"aieos_path":{"description":"Path to AIEOS JSON file (relative to workspace)","type":["string","null"],"default":null},"format":{"description":"Identity format: \"openclaw\" (default) or \"aieos\"","type":"string","default":"openclaw"}}},"InteractionNoticeApplicability":{"type":"string","enum":["required","not_applicable"]},"InteractionNoticeConfig":{"type":"object","properties":{"applicability":{"$ref":"#/$defs/InteractionNoticeApplicability","default":"required"},"exception_owner":{"type":["string","null"],"default":null},"exception_reviewed_at":{"type":["string","null"],"default":null},"text":{"type":"string","default":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers."},"version":{"type":"string","default":"1"}}},"IrcConfig":{"description":"IRC channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed nicknames (case-insensitive) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"channels":{"description":"Channels to join on connect","type":"array","default":[],"items":{"type":"string"}},"mention_only":{"description":"When true, only process channel/group messages that mention the bot.","type":"boolean","default":false},"nickname":{"description":"Bot nickname","type":"string"},"nickserv_password":{"description":"NickServ IDENTIFY password","type":["string","null"]},"port":{"description":"IRC server port (default: 6697 for TLS)","type":"integer","format":"uint16","default":6697,"maximum":65535,"minimum":0},"sasl_password":{"description":"SASL PLAIN password (IRCv3)","type":["string","null"]},"server":{"description":"IRC server hostname","type":"string"},"server_password":{"description":"Server password (for bouncers like ZNC)","type":["string","null"]},"username":{"description":"Username (defaults to nickname if not set)","type":["string","null"]},"verify_tls":{"description":"Verify TLS certificate (default: true)","type":["boolean","null"]}},"required":["server","nickname"]},"LarkConfig":{"description":"Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from Lark/Feishu developer console","type":"string"},"app_secret":{"description":"App Secret from Lark/Feishu developer console","type":"string"},"encrypt_key":{"description":"Encrypt key for webhook message decryption (optional)","type":["string","null"],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"port":{"description":"HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"receive_mode":{"description":"Event receive mode: \"websocket\" (default) or \"webhook\"","$ref":"#/$defs/LarkReceiveMode","default":"websocket"},"use_feishu":{"description":"Whether to use the Feishu (Chinese) endpoint instead of Lark (International)","type":"boolean","default":false},"verification_token":{"description":"Verification token for webhook validation (optional)","type":["string","null"],"default":null}},"required":["app_id","app_secret"]},"LarkReceiveMode":{"description":"How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.","type":"string","enum":["websocket","webhook"]},"LinqConfig":{"type":"object","properties":{"allowed_senders":{"description":"Allowed sender handles (phone numbers) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"api_token":{"description":"Linq Partner API token (Bearer auth)","type":"string"},"from_phone":{"description":"Phone number to send from (E.164 format)","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"signing_secret":{"description":"Webhook signing secret for signature verification","type":["string","null"],"default":null}},"required":["api_token","from_phone"]},"MattermostConfig":{"description":"Mattermost bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Mattermost user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Mattermost bot access token.","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.","type":["boolean","null"],"default":null},"thread_replies":{"description":"When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.","type":["boolean","null"],"default":null},"url":{"description":"Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).","type":"string"}},"required":["url","bot_token"]},"McpConfig":{"type":"object","properties":{"servers":{"description":"Named MCP server definitions","type":"object","additionalProperties":{"$ref":"#/$defs/McpServerConfig"},"default":{}},"workspace_servers":{"description":"Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.","$ref":"#/$defs/WorkspaceMcpServers"}}},"McpServerConfig":{"type":"object","properties":{"allow_tools":{"description":"Optional allow-list of exposed tools (empty = all)","type":"array","default":[],"items":{"type":"string"}},"args":{"description":"Command args for stdio mode","type":"array","default":[],"items":{"type":"string"}},"command":{"description":"Command for stdio mode","type":["string","null"],"default":null},"deny_tools":{"description":"Optional deny-list of exposed tools","type":"array","default":[],"items":{"type":"string"}},"env":{"description":"Environment variables for stdio mode","type":"object","additionalProperties":{"type":"string"},"default":{}},"request_timeout_ms":{"description":"Request timeout in milliseconds","type":"integer","format":"uint64","default":30000,"minimum":0},"startup_timeout_ms":{"description":"Startup timeout in milliseconds","type":"integer","format":"uint64","default":10000,"minimum":0},"tool_name_prefix":{"description":"Prefix used in tool naming and routing","type":"string","default":"mcp"},"transport":{"description":"Transport type: stdio or http","$ref":"#/$defs/McpTransport","default":"stdio"},"url":{"description":"URL for HTTP mode (streamable HTTP endpoint)","type":["string","null"],"default":null},"working_dir":{"description":"Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).","type":["string","null"]}}},"McpServerRuntimeConfig":{"type":"object","properties":{"allowed_origins":{"description":"Allowed browser origins for future streamable HTTP clients.","type":"array","default":["claude.ai","openai.com","localhost"],"items":{"type":"string"}},"bind":{"description":"Advertised bind address. The gateway may still be started with a CLI port override.","type":"string","default":"127.0.0.1:16831"},"exposed_tools":{"description":"Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.","type":"array","default":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"items":{"type":"string"}},"jwt_algorithms":{"description":"Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.","type":"array","default":["RS256"],"items":{"type":"string"}},"jwt_audience":{"description":"Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.","type":["string","null"],"default":null},"jwt_issuer":{"description":"Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.","type":["string","null"],"default":null},"jwt_jwks":{"description":"Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.","type":["string","null"],"default":null},"jwt_jwks_cache_ttl_secs":{"description":"Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.","type":"integer","format":"uint64","default":300,"minimum":0},"jwt_jwks_uri":{"description":"Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.","type":["string","null"],"default":null},"jwt_public_key_pem":{"description":"PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.","type":["string","null"],"default":null},"rate_limit_rps":{"description":"Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.","type":"integer","format":"uint32","default":10,"minimum":0},"require_auth":{"description":"Require an authenticated external identity for mutating calls.","type":"boolean","default":true}}},"McpTransport":{"type":"string","enum":["stdio","http"]},"MediaConfig":{"description":"Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.","type":"object","properties":{"audio_model":{"description":"Audio model name (Ollama model or OpenAI model). Default: \"whisper\".","type":"string","default":"whisper"},"audio_ollama_url":{"description":"Ollama base URL for audio transcription. Default: \"http://localhost:11434\".","type":"string","default":"http://localhost:11434"},"audio_provider":{"description":"Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".","type":"string","default":"none"},"max_audio_size_mb":{"description":"Maximum audio attachment size in MiB. Default: 20.","type":"integer","format":"uint","default":20,"minimum":0},"max_video_size_mb":{"description":"Maximum video attachment size in MiB. Default: 50.","type":"integer","format":"uint","default":50,"minimum":0},"video_max_frames":{"description":"Maximum video frames to extract per video. Default: 4.","type":"integer","format":"uint","default":4,"minimum":0},"video_provider":{"description":"Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".","type":"string","default":"none"}}},"MemoryConfig":{"description":"Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.","type":"object","properties":{"acl_enabled":{"description":"Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.","type":"boolean","default":false},"archive_after_days":{"description":"Archive daily/session files older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"auto_hydrate":{"description":"Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing","type":"boolean","default":true},"auto_save":{"description":"Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.","type":"boolean","default":true},"backend":{"description":"\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).","type":"string","default":"sqlite"},"conversation_retention_days":{"description":"For sqlite backend: prune conversation rows older than this many days","type":"integer","format":"uint32","default":3,"minimum":0},"daily_retention_days":{"description":"For sqlite backend: prune daily rows older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"embedding_cache_size":{"description":"Max embedding cache entries before LRU eviction","type":"integer","format":"uint","default":10000,"minimum":0},"embedding_dimensions":{"description":"Embedding vector dimensions","type":"integer","format":"uint","default":384,"minimum":0},"embedding_model":{"description":"Embedding model name (e.g. \"text-embedding-3-small\")","type":"string","default":"prx-local-hash-v1"},"embedding_provider":{"description":"Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"","type":"string","default":"local"},"events":{"description":"Raw/quasi-raw message event recording controls (`[memory.events]`).","$ref":"#/$defs/MemoryEventsConfig","default":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true}},"keyword_weight":{"description":"Weight for keyword BM25 in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.3},"legacy_conversation_turns_visible":{"description":"Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.","type":"boolean","default":true},"lucid_budget":{"description":"Token budget for lucid (replaces OPENPRX_LUCID_BUDGET)","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"lucid_cmd":{"description":"Path to lucid binary (replaces OPENPRX_LUCID_CMD)","type":["string","null"],"default":null},"lucid_failure_cooldown_ms":{"description":"Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)","type":"integer","format":"uint64","default":60000,"minimum":0},"lucid_local_hit_threshold":{"description":"Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)","type":"integer","format":"uint","default":3,"minimum":0},"lucid_recall_timeout_ms":{"description":"Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)","type":"integer","format":"uint64","default":5000,"minimum":0},"lucid_store_timeout_ms":{"description":"Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)","type":"integer","format":"uint64","default":3000,"minimum":0},"min_relevance_score":{"description":"Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4","type":"number","format":"double","default":0.4},"purge_after_days":{"description":"Purge archived files older than this many days","type":"integer","format":"uint32","default":30,"minimum":0},"semantic":{"description":"Semantic memory promotion controls (`[memory.semantic]`).","$ref":"#/$defs/MemorySemanticConfig","default":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30}},"sqlite_open_timeout_secs":{"description":"For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"sqlite_read_pool_size":{"description":"For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"vector_candidate_cap":{"description":"How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.","type":"integer","format":"uint","default":2000,"minimum":0},"vector_weight":{"description":"Weight for vector similarity in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.7}}},"MemoryEventsConfig":{"description":"Raw message event recording configuration (`[memory.events]`).","type":"object","properties":{"record_assistant_messages":{"description":"Record assistant replies.","type":"boolean","default":true},"record_tool_events":{"description":"Record tool/event payloads by default.","type":"boolean","default":false},"record_user_messages":{"description":"Record inbound/user messages.","type":"boolean","default":true}}},"MemorySemanticConfig":{"description":"Semantic memory promotion configuration (`[memory.semantic]`).","type":"object","properties":{"auto_promote_assistant_messages":{"description":"Auto-promote eligible assistant messages. Disabled by default to reduce noise.","type":"boolean","default":false},"auto_promote_user_messages":{"description":"Auto-promote eligible user messages into long-term semantic memories.","type":"boolean","default":true},"min_chars":{"description":"Minimum content length for semantic auto-promotion.","type":"integer","format":"uint","default":30,"minimum":0}}},"MemoryWebhookConfig":{"type":"object","properties":{"bind":{"description":"Socket address for the receiver (e.g. \"0.0.0.0:16899\").","type":"string","default":"0.0.0.0:16899"},"signing_secret":{"description":"Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.","type":["string","null"],"default":null},"token":{"description":"Required bearer token for incoming webhook events.","type":["string","null"],"default":null}}},"ModelOperationSetting":{"description":"The operations a `[[providers.models]]` entry may list.","type":"string","enum":["chat","embedding","decision_endpoint","rerank","image_generation","audio_generation","video_generation"]},"ModelPricing":{"description":"Per-model pricing entry (USD per 1M tokens).","type":"object","properties":{"cache_read":{"description":"Cache read input price per 1M tokens.","type":"number","format":"double","default":0.0},"cache_write":{"description":"Cache write/creation input price per 1M tokens.","type":"number","format":"double","default":0.0},"input":{"description":"Input price per 1M tokens","type":"number","format":"double","default":0.0},"output":{"description":"Output price per 1M tokens","type":"number","format":"double","default":0.0}}},"ModelRouteConfig":{"description":"Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"hint":{"description":"Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")","type":"string"},"level":{"type":["string","null"]},"model":{"description":"Model to use with that provider","type":"string"},"provider":{"description":"Provider to route to (must match a known provider name)","type":"string"},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true,"required":["hint","provider","model"]},"ModelSettings":{"description":"A model level plus explicit parameter overrides in `[model_settings.\"\"]`.","type":"object","properties":{"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"level":{"type":["string","null"]},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true},"MultimodalConfig":{"description":"Multimodal (image) handling configuration (`[multimodal]` section).","type":"object","properties":{"allow_remote_fetch":{"description":"Allow fetching remote image URLs (http/https). Disabled by default.","type":"boolean","default":false},"max_image_size_mb":{"description":"Maximum image payload size in MiB before base64 encoding.","type":"integer","format":"uint","default":5,"minimum":0},"max_images":{"description":"Maximum number of image attachments accepted per request.","type":"integer","format":"uint","default":4,"minimum":0}}},"NextcloudTalkConfig":{"description":"Nextcloud Talk bot configuration (webhook receive + OCS send API).","type":"object","properties":{"allowed_users":{"description":"Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Bot app token used for OCS API bearer auth.","type":"string"},"base_url":{"description":"Nextcloud base URL (e.g. \"https://cloud.example.com\").","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"webhook_secret":{"description":"Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).","type":["string","null"],"default":null}},"required":["base_url","app_token"]},"NgrokTunnelConfig":{"type":"object","properties":{"auth_token":{"description":"ngrok auth token","type":"string"},"domain":{"description":"Optional custom domain","type":["string","null"]}},"required":["auth_token"]},"NodeServerConfig":{"description":"Node daemon runtime config used by `prx-node`.","type":"object","properties":{"allowed_commands":{"description":"Command allowlist matched on first token.\n\nIn restricted mode this list is required unless explicitly set to `[\"*\"]`.","type":"array","default":["echo"],"items":{"type":"string"}},"bearer_token":{"description":"Required bearer token for /rpc.","type":"string","default":""},"blocked_commands":{"description":"Command denylist matched on first token. Always enforced.","type":"array","default":[],"items":{"type":"string"}},"exec_timeout_ms":{"description":"Default command timeout in milliseconds.","type":"integer","format":"uint64","default":15000,"minimum":0},"hmac_secret":{"description":"Optional HMAC signing secret.","type":["string","null"],"default":null},"listen_addr":{"description":"Listen address for node daemon.","type":"string","default":"127.0.0.1:8787"},"max_concurrent_tasks":{"description":"Maximum number of concurrent async command tasks.","type":"integer","format":"uint","default":8,"minimum":0},"max_output_bytes":{"description":"Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.","type":"integer","format":"uint","default":1048576,"minimum":0},"sandbox_root":{"description":"Sandbox root directory for read/write/cwd constraints.","type":"string","default":"."},"task_result_ttl_ms":{"description":"TTL for completed task results in milliseconds.","type":"integer","format":"uint64","default":3600000,"minimum":0},"tls_cert":{"description":"TLS certificate path (PEM).","type":["string","null"],"default":null},"tls_key":{"description":"TLS private key path (PEM).","type":["string","null"],"default":null},"tls_required":{"description":"Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.","type":"boolean","default":true}}},"NodesConfig":{"description":"Remote node proxy configuration for core-side RPC calls and node daemon defaults.","type":"object","properties":{"nodes":{"description":"Configured remote nodes.","type":"array","default":[],"items":{"$ref":"#/$defs/RemoteNodeConfig"}},"request_timeout_ms":{"description":"Default request timeout for node RPC calls.","type":"integer","format":"uint64","default":15000,"minimum":0},"retry_max":{"description":"Default max retries for node RPC calls.","type":"integer","format":"uint8","default":2,"maximum":255,"minimum":0},"server":{"description":"Embedded node server defaults used by `prx-node`.","$ref":"#/$defs/NodeServerConfig","default":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}}},"ObservabilityConfig":{"description":"Observability backend configuration (`[observability]` section).","type":"object","properties":{"backend":{"description":"\"none\" | \"log\" | \"prometheus\" | \"otel\"","type":"string","default":"none"},"otel_endpoint":{"description":"OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".","type":["string","null"],"default":null},"otel_service_name":{"description":"Service name reported to the OTel collector. Defaults to \"prx\".","type":["string","null"],"default":null}}},"OllamaProviderConfig":{"description":"Ollama-specific request options (`[providers.ollama]`).","type":"object","properties":{"num_ctx":{"description":"Explicit context window sent as Ollama `options.num_ctx`.","type":["integer","null"],"format":"uint","default":null,"minimum":0}}},"OsPagingConfig":{"description":"Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.","type":"object","properties":{"eviction_threshold":{"description":"Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.","type":"number","format":"double","default":0.7},"keep_recent_messages":{"description":"Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).","type":"integer","format":"uint","default":12,"minimum":0},"max_recalled_pages":{"description":"Maximum number of evicted pages (document chunks) recalled per turn.","type":"integer","format":"uint","default":10,"minimum":0},"proactive_retrieval":{"description":"Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.","type":"boolean","default":true},"retrieval_injection_role":{"description":"Role under which recalled pages are injected.","$ref":"#/$defs/RetrievalInjectionRole","default":"system"}}},"PluginsConfig":{"description":"WASM plugin runtime configuration.","type":"object","properties":{"enabled":{"description":"Load WASM plugins from `/plugins`. Default: `false`.","type":"boolean","default":false}},"additionalProperties":false},"ProviderModelConfig":{"description":"One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.","type":"object","properties":{"context_window":{"description":"The model's context window in tokens.","type":["integer","null"],"format":"uint32","minimum":0},"model":{"description":"The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.","type":["string","null"]},"native_tools":{"description":"Whether the model accepts native tool calls.","type":["boolean","null"]},"operations":{"description":"The complete list of operations the model executes; every operation not\nlisted is unsupported.","type":["array","null"],"items":{"$ref":"#/$defs/ModelOperationSetting"}},"provider":{"description":"The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.","type":"string"},"streaming":{"description":"Whether the model streams responses.","type":["boolean","null"]},"structured_output":{"description":"Whether the model honours a JSON-schema response format.","type":["boolean","null"]},"tool_call_dialect":{"description":"The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema_dialect":{"description":"The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]},"vision_input":{"description":"Whether the model accepts image input.","type":["boolean","null"]}},"required":["provider"]},"ProviderToolDialectConfig":{"description":"One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.","type":"object","properties":{"model":{"description":"The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.","type":["string","null"]},"provider":{"description":"The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.","type":"string"},"tool_call":{"description":"The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema":{"description":"The tool-schema dialect the endpoint accepts.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]}},"required":["provider"]},"ProvidersConfig":{"description":"Provider-specific runtime configuration (`[providers]`).","type":"object","properties":{"models":{"description":"Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.","type":"array","items":{"$ref":"#/$defs/ProviderModelConfig"}},"ollama":{"description":"Ollama-specific request options (`[providers.ollama]`).","$ref":"#/$defs/OllamaProviderConfig","default":{"num_ctx":null}},"tool_dialects":{"description":"Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).","type":"array","items":{"$ref":"#/$defs/ProviderToolDialectConfig"}}}},"ProxyConfig":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).","type":"object","properties":{"all_proxy":{"description":"Fallback proxy URL for all schemes.","type":["string","null"],"default":null},"http_proxy":{"description":"Proxy URL for HTTP requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"https_proxy":{"description":"Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"no_proxy":{"description":"No-proxy bypass list. Same format as NO_PROXY.","type":"array","default":[],"items":{"type":"string"}},"scope":{"description":"Proxy application scope.","$ref":"#/$defs/ProxyScope","default":"prx"},"services":{"description":"Service selectors used when scope = \"services\".","type":"array","default":[],"items":{"type":"string"}}}},"ProxyScope":{"description":"Proxy application scope — determines which outbound traffic uses the proxy.","oneOf":[{"description":"Use system environment proxy variables only.","type":"string","const":"environment"},{"description":"Apply proxy to all OpenPRX-managed HTTP traffic (default).","type":"string","const":"prx"},{"description":"Apply proxy only to explicitly listed service selectors.","type":"string","const":"services"}]},"QQConfig":{"description":"QQ Official Bot configuration (Tencent QQ Bot SDK)","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs. Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from QQ Bot developer console","type":"string"},"app_secret":{"description":"App Secret from QQ Bot developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["app_id","app_secret"]},"QueryClassificationConfig":{"description":"Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.","type":"object","properties":{"rules":{"description":"Classification rules evaluated in priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/ClassificationRule"}}}},"RamfluxAccountConfig":{"description":"Persona for one ramflux AI account. Missing fields fall back to the global agent.","type":"object","properties":{"cross_conversation_retrieval":{"description":"Cross-conversation memory retrieval. Off unless the owner sets it.","type":"boolean","default":false},"model":{"type":["string","null"],"default":null},"provider":{"type":["string","null"],"default":null},"scope_profile":{"type":["string","null"],"default":null},"system_prompt_file":{"description":"Path to a system-prompt file. Relative paths are resolved from the workspace.","type":["string","null"],"default":null}},"additionalProperties":false},"RamfluxAttachmentFetch":{"description":"Per-turn caps for `attachment.fetch`.","type":"object","properties":{"max_bytes":{"type":"integer","format":"uint64","default":5242880,"minimum":0},"max_per_turn":{"type":"integer","format":"uint8","default":4,"maximum":255,"minimum":0}},"additionalProperties":false},"RamfluxAuthorizationMode":{"description":"How prx combines its own setting with `bridge.hello.authorization`.","oneOf":[{"description":"Use the agent-host value. Until hello arrives, the effective mode is supervised.","type":"string","const":"follow_rf"},{"description":"Always supervised, even when the agent-host declares full.","type":"string","const":"supervised"},{"description":"Full only when the agent-host also declares full. Config alone never yields full.","type":"string","const":"full"}]},"RamfluxConfig":{"description":"Local ramflux agent-host bridge (`[channels_config.ramflux]`).","type":"object","properties":{"accounts":{"type":"object","additionalProperties":{"$ref":"#/$defs/RamfluxAccountConfig"},"default":{}},"allowed_block_types":{"type":"array","default":["Text","Markdown","Heading","KeyValue","Metric","List","TableFallback","Form","Input","Select","Progress","LogStream","Warning","Error","Success","Approval","ActionGroup","FilePreview","Fallback"],"items":{"type":"string"}},"attachment_fetch":{"$ref":"#/$defs/RamfluxAttachmentFetch","default":{"max_bytes":5242880,"max_per_turn":4}},"authorization_mode":{"$ref":"#/$defs/RamfluxAuthorizationMode","default":"follow_rf"},"encrypt_at_rest":{"type":"boolean","default":true},"max_in_flight_per_conversation":{"type":"integer","format":"uint8","default":1,"maximum":255,"minimum":0},"on_new_message":{"$ref":"#/$defs/RamfluxOnNewMessage","default":"queue"},"socket_path":{"description":"Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.","type":["string","null"],"default":null},"surface_limits":{"$ref":"#/$defs/RamfluxSurfaceLimits","default":{"max_actions":16,"max_blocks":32,"max_bytes":65536}},"turn_wall_clock_secs":{"description":"Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.","type":"integer","format":"uint64","default":120,"minimum":0}},"additionalProperties":false},"RamfluxOnNewMessage":{"description":"What to do with a new inbound message while a turn for that conversation is running.","type":"string","enum":["queue","interrupt"]},"RamfluxSurfaceLimits":{"description":"Limits for `reply.surface` blocks and actions.","type":"object","properties":{"max_actions":{"type":"integer","format":"uint32","default":16,"minimum":0},"max_blocks":{"type":"integer","format":"uint32","default":32,"minimum":0},"max_bytes":{"type":"integer","format":"uint32","default":65536,"minimum":0}},"additionalProperties":false},"ReliabilityCircuitBreakerConfig":{"description":"Process-local provider circuit policy (`[reliability.circuit_breaker]`).","type":"object","properties":{"enabled":{"description":"Enable protection for factory-built provider chains.","type":"boolean","default":true},"failure_threshold":{"description":"Consecutive transient failures that open a circuit (at least 1).","type":"integer","format":"uint32","default":5,"minimum":0},"max_open_secs":{"description":"Maximum doubled window, between open_secs and 3600 seconds.","type":"integer","format":"uint64","default":300,"minimum":0},"open_secs":{"description":"Initial open window in seconds (at least 1).","type":"integer","format":"uint64","default":30,"minimum":0}}},"ReliabilityConfig":{"description":"Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.","type":"object","properties":{"acknowledge_single_provider_risk":{"description":"Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.","type":"boolean","default":false},"api_keys":{"description":"Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.","type":"array","default":[],"items":{"type":"string"}},"channel_initial_backoff_secs":{"description":"Initial backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":2,"minimum":0},"channel_max_backoff_secs":{"description":"Max backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":60,"minimum":0},"circuit_breaker":{"description":"Per-provider consecutive failure protection.","$ref":"#/$defs/ReliabilityCircuitBreakerConfig","default":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30}},"fallback_providers":{"description":"Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).","type":"array","default":[],"items":{"type":"string"}},"model_fallbacks":{"description":"Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`","type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"default":{}},"provider_backoff_ms":{"description":"Base backoff (ms) for provider retry delay.","type":"integer","format":"uint64","default":500,"minimum":0},"provider_retries":{"description":"Retries per provider before failing over.","type":"integer","format":"uint32","default":2,"minimum":0},"scheduler_poll_secs":{"description":"Scheduler polling cadence in seconds.","type":"integer","format":"uint64","default":15,"minimum":0},"scheduler_retries":{"description":"Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.","type":"integer","format":"uint32","default":2,"minimum":0}}},"RemoteNodeConfig":{"description":"A remote node target for core-side node proxy calls.","type":"object","properties":{"bearer_token":{"description":"Bearer token for node RPC authentication.","type":"string"},"endpoint":{"description":"Base endpoint (e.g. \"http://127.0.0.1:8787\").","type":"string"},"hmac_secret":{"description":"Optional request signing key (HMAC-SHA256).","type":["string","null"],"default":null},"id":{"description":"Stable node ID used by the nodes tool.","type":"string"},"retry_max":{"description":"Optional per-node retry override.","type":["integer","null"],"format":"uint8","default":null,"maximum":255,"minimum":0},"timeout_ms":{"description":"Optional per-node timeout override.","type":["integer","null"],"format":"uint64","default":null,"minimum":0}},"required":["id","endpoint","bearer_token"]},"RetrievalInjectionRole":{"description":"Where recalled context pages are injected back into the request.","oneOf":[{"description":"Inject recalled pages as a leading `system` message (not user-visible).","type":"string","const":"system"},{"description":"Inject recalled pages as a leading `user` message.","type":"string","const":"user"}]},"RouterConfig":{"description":"Heuristic LLM router configuration (`[router]` section).","type":"object","properties":{"alpha":{"description":"Similarity score weight. Phase 1 keeps this at `0.0`.","type":"number","format":"float","default":0.0},"beta":{"description":"Capability score weight.","type":"number","format":"float","default":0.5},"delta":{"description":"Cost penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"epsilon":{"description":"Latency penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"gamma":{"description":"Elo score weight.","type":"number","format":"float","default":0.30000001192092896},"knn_k":{"description":"Number of nearest neighbors considered for voting. Default: `7`.","type":"integer","format":"uint","default":7,"minimum":0},"knn_min_records":{"description":"Minimum history records before KNN affects routing. Default: `10`.","type":"integer","format":"uint","default":10,"minimum":0},"models":{"description":"Candidate model registry.","type":"array","default":[],"items":{"$ref":"#/$defs/RouterModelConfig"}}}},"RouterModelConfig":{"description":"Static router metadata for one model candidate.","type":"object","properties":{"categories":{"description":"Capability categories such as `conversation`, `code`, or `analysis`.","type":"array","default":[],"items":{"type":"string"}},"cost_per_million_tokens":{"description":"USD cost per million tokens.","type":"number","format":"float","default":0.0},"elo_rating":{"description":"Initial Elo rating.","type":"number","format":"float","default":1000.0},"latency_ms":{"description":"Average latency in milliseconds.","type":"integer","format":"uint32","default":2000,"minimum":0},"max_context":{"description":"Maximum context window in tokens.","type":"integer","format":"uint","default":1000000,"minimum":0},"model_id":{"description":"Model identifier without provider prefix.","type":"string"},"provider":{"description":"Provider identifier.","type":"string"},"reserved_output_tokens":{"description":"Output tokens reserved for this model when planning input context.","type":["integer","null"],"format":"uint","minimum":0}},"required":["model_id","provider"]},"RuntimeConfig":{"description":"Runtime adapter configuration (`[runtime]` section).","type":"object","properties":{"codex_reasoning_effort":{"description":"Codex reasoning effort","type":["string","null"],"default":null},"codex_stream_idle_timeout_secs":{"description":"Codex stream idle timeout in seconds","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"docker":{"description":"Docker runtime settings (used when `kind = \"docker\"`).","$ref":"#/$defs/DockerRuntimeConfig","default":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true}},"idle_hang_secs":{"description":"Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"kind":{"description":"Runtime kind (`native` | `docker`).","type":"string","default":"native"},"long_task_warn_secs":{"description":"Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"managed_cgroup_root":{"description":"Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.","type":["string","null"],"default":null},"max_blocking_threads":{"description":"Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"reasoning_enabled":{"description":"Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported","type":["boolean","null"],"default":null},"shell_env_allowlist":{"description":"Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.","type":"array","default":[],"items":{"type":"string"}},"workdir":{"description":"Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.","type":["string","null"],"default":null}}},"SchedulerConfig":{"description":"Scheduler configuration for periodic task execution (`[scheduler]` section).","type":"object","properties":{"claim_lease_secs":{"description":"Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.","type":"integer","format":"uint64","default":90,"minimum":0},"max_tasks":{"description":"Maximum number of persisted scheduled tasks.","type":"integer","format":"uint","default":64,"minimum":0}}},"ScopeConfig":{"description":"Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```","type":"object","properties":{"assign_owners":{"description":"Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.","type":"array","default":[],"items":{"type":"string"}},"default":{"description":"Default action when no rule matches: \"allow\" (default) or \"deny\".","$ref":"#/$defs/ScopeDefault","default":"allow"},"rules":{"description":"Ordered list of scope rules evaluated top-to-bottom.","type":"array","default":[],"items":{"$ref":"#/$defs/ScopeRule"}}}},"ScopeDefault":{"description":"What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.","oneOf":[{"description":"Unmatched tool calls are allowed (the default).","type":"string","const":"allow"},{"description":"Unmatched tool calls are refused.","type":"string","const":"deny"}]},"ScopeRule":{"description":"A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.","type":"object","properties":{"assign_allow":{"description":"Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".","type":"array","default":[],"items":{"type":"string"}},"assign_deny":{"description":"Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.","type":"array","default":[],"items":{"type":"string"}},"channel":{"description":"Match by channel name: \"signal\", \"telegram\", \"discord\", etc.","type":["string","null"]},"chat_type":{"description":"Match by chat type: \"direct\", \"group\", or \"*\" for any type.","type":["string","null"]},"send_allow":{"description":"Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.","type":"array","default":[],"items":{"type":"string"}},"send_deny":{"description":"Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.","type":"array","default":[],"items":{"type":"string"}},"tools_allow":{"description":"Tool whitelist: only these tools are allowed (empty = all tools permitted).","type":"array","default":[],"items":{"type":"string"}},"tools_deny":{"description":"Tool blacklist: these tools are denied regardless of allow list.","type":"array","default":[],"items":{"type":"string"}},"user":{"description":"Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.","type":["string","null"]}}},"SecretsConfig":{"description":"Secrets encryption configuration (`[secrets]` section).","type":"object","properties":{"encrypt":{"description":"Enable encryption for API keys and tokens in config.toml","type":"boolean","default":true}}},"SecurityConfig":{"description":"Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.","type":"object","properties":{"audit":{"description":"Audit logging configuration","$ref":"#/$defs/AuditConfig","default":{"log_path":"audit.log","max_size_mb":100}},"workspace_hooks":{"description":"Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.","$ref":"#/$defs/WorkspaceHooks"}}},"SelfSystemConfig":{"description":"Self-system experimental automation config (`[self_system]`).","type":"object","properties":{"evolution_config_path":{"description":"Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG)","type":["string","null"],"default":null},"evolution_debug_raw":{"description":"Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW)","type":"boolean","default":false},"evolution_interval_hours":{"description":"Evolution scheduler interval in hours (daemon mode).","type":"integer","format":"uint32","default":24,"minimum":0},"evolution_judge_timeout_secs":{"description":"Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.","type":"integer","format":"uint64","default":180,"minimum":0},"evolution_model_max_micro_usd":{"description":"Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.","type":"integer","format":"uint64","default":0,"minimum":0},"evolution_model_max_tokens":{"description":"Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.","type":"integer","format":"uint64","default":16384,"minimum":0},"fitness":{"description":"Daily fitness snapshot policy.","$ref":"#/$defs/FitnessConfig","default":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"}},"fitness_interval_hours":{"description":"Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.","type":"integer","format":"uint64","default":24,"minimum":0}}},"SessionsSpawnConfig":{"description":"Sessions spawn configuration (`[sessions_spawn]` section).","type":"object","properties":{"cleanup_on_complete":{"description":"Remove worker workspace directory after process-mode completion.","type":"boolean","default":true},"default_mode":{"description":"Default execution mode for sessions_spawn (`task` or `process`).","type":"string","default":"task"},"process_memory_strategy":{"description":"Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.","type":"string","default":"shared_fabric"},"worker_workspace_root":{"description":"Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.","type":["string","null"],"default":null}}},"SignalConfig":{"type":"object","properties":{"account":{"description":"E.164 phone number of the signal-cli account (e.g. \"+1234567890\").","type":"string"},"allowed_from":{"description":"Allowed sender phone numbers (E.164) or \"*\" for all.","type":"array","default":[],"items":{"type":"string"}},"cli_path":{"description":"Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).","type":["string","null"],"default":null},"daemon_http_port":{"description":"Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"daemon_mode":{"description":"Deprecated: ignored. Accepted for backward compatibility with older config files.","type":["boolean","null"],"default":null},"data_dir":{"description":"signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_id":{"description":"Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group","type":["string","null"],"default":null},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"http_url":{"description":"Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.","type":"string","default":"http://localhost:8080"},"ignore_attachments":{"description":"Skip messages that are attachment-only (no text body).","type":"boolean","default":false},"ignore_stories":{"description":"Skip incoming story messages.","type":"boolean","default":false},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"mode":{"description":"Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.","type":["string","null"],"default":null},"startup_timeout_ms":{"description":"Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.","type":"integer","format":"uint64","default":30000,"minimum":0},"storm_protection":{"description":"Signal ingress storm protection controls.","$ref":"#/$defs/SignalStormProtectionConfig","default":{"abnormal_threshold":10,"abnormal_window_secs":60,"breaker_duration_secs":300,"dedupe_ttl_secs":60,"min_reply_interval_secs":2}}},"required":["account"]},"SignalStormProtectionConfig":{"type":"object","properties":{"abnormal_threshold":{"description":"Non-user event threshold within `abnormal_window_secs` before tripping the breaker.","type":"integer","format":"uint","default":10,"minimum":0},"abnormal_window_secs":{"description":"Sliding window in seconds for non-user event counting.","type":"integer","format":"uint64","default":60,"minimum":0},"breaker_duration_secs":{"description":"Circuit breaker duration in seconds after threshold is reached.","type":"integer","format":"uint64","default":300,"minimum":0},"dedupe_ttl_secs":{"description":"Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.","type":"integer","format":"uint64","default":60,"minimum":0},"min_reply_interval_secs":{"description":"Minimum interval in seconds between replies for the same `(channel + reply_target)`.","type":"integer","format":"uint64","default":2,"minimum":0}}},"SkillRagConfig":{"description":"Dynamic skill retrieval configuration (`[skill_rag]` section).","type":"object","properties":{"top_k":{"description":"How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).","type":"integer","format":"uint","default":32,"minimum":0}}},"SkillSuiteRegistration":{"description":"The frozen suite that governs one skill's proposals.","type":"object","properties":{"skill_id":{"description":"The skill the suite governs.","type":"string"},"suite_digest":{"description":"SHA-256 digest (64 lowercase hex digits) of the frozen suite.","type":"string"}},"additionalProperties":false,"required":["skill_id","suite_digest"]},"SkillsConfig":{"description":"Skills loading configuration (`[skills]` section).","type":"object","properties":{"open_skills_dir":{"description":"Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.","type":["string","null"],"default":null},"openclaw_skills_dir":{"description":"Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.","type":["string","null"],"default":null}}},"SkillsLifecycleConfig":{"description":"`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.","type":"object","properties":{"allow_executable_proposals":{"description":"Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.","type":"boolean","default":false},"enabled":{"description":"Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.","type":"boolean","default":false},"max_concurrent_evaluations":{"description":"Most evaluations running at once.","type":"integer","format":"uint32","default":1,"minimum":0},"max_edit_fraction":{"description":"Edit budget of a proposal as a fraction of the skill body, in (0, 1].","type":"number","format":"double","default":0.2},"max_edit_tokens":{"description":"Edit budget of a proposal, in tokens.","type":"integer","format":"uint64","default":300,"minimum":0},"max_proposals_per_cycle":{"description":"Most proposals one cycle may start.","type":"integer","format":"uint32","default":1,"minimum":0},"min_cases_floor":{"description":"Smallest `min_cases` a governing suite may declare. Below 3 is refused.","type":"integer","format":"uint32","default":3,"minimum":0},"mode":{"description":"`draft_only`, `shadow` or `auto`.","$ref":"#/$defs/SkillsLifecycleModeConfig","default":"draft_only"},"owner_scope":{"description":"The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.","type":["string","null"],"default":null},"require_holdout":{"description":"A governing suite must have a holdout split. `false` is refused.","type":"boolean","default":true},"storage_dir":{"description":"Store location under the workspace. Only the default is supported.","type":"string","default":"self/skill-lifecycle"},"suites":{"description":"The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.","type":"array","default":[],"items":{"$ref":"#/$defs/SkillSuiteRegistration"}}},"additionalProperties":false},"SkillsLifecycleModeConfig":{"description":"What the lifecycle may do. Mirrors `LifecycleMode`.","oneOf":[{"description":"Drafts and reviews only.","type":"string","const":"draft_only"},{"description":"Drafts plus evaluation and gating; never publishes.","type":"string","const":"shadow"},{"description":"Publishes an eligible proposal after every gate.","type":"string","const":"auto"}]},"SlackConfig":{"description":"Slack bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Slack user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Slack app-level token for Socket Mode (xapp-...).","type":["string","null"]},"bot_token":{"description":"Slack bot OAuth token (xoxb-...).","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["bot_token"]},"SmartGroupConfig":{"description":"Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).","type":"object","properties":{"classifier_max_context_messages":{"description":"How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.","type":"integer","format":"uint","default":3,"minimum":0},"classifier_model":{"description":"Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.","type":"string","default":""},"classifier_provider":{"description":"Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.","type":"string","default":""},"classifier_temperature":{"description":"Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).","type":"number","format":"double","default":0.0},"classifier_timeout_secs":{"description":"Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.","type":"integer","format":"uint64","default":5,"minimum":0}}},"StorageConfig":{"description":"Persistent storage configuration (`[storage]` section).","type":"object","properties":{"provider":{"description":"Storage provider settings (e.g. sqlite, postgres).","$ref":"#/$defs/StorageProviderSection","default":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}}},"StorageProviderConfig":{"description":"Storage provider backend configuration (e.g. postgres connection details).","type":"object","properties":{"connect_timeout_secs":{"description":"Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"db_url":{"description":"Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.","type":["string","null"],"default":null},"pool_max_size":{"description":"Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.","type":"integer","format":"uint","default":32,"minimum":0},"provider":{"description":"Storage engine key (e.g. \"postgres\", \"sqlite\").","type":"string","default":""},"schema":{"description":"Database schema for SQL backends.","type":"string","default":"public"},"table":{"description":"Table name for memory entries.","type":"string","default":"memories"}}},"StorageProviderSection":{"description":"Wrapper for the storage provider configuration section.","type":"object","properties":{"config":{"description":"Storage provider backend settings.","$ref":"#/$defs/StorageProviderConfig","default":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"StreamMode":{"description":"Streaming mode for channels that support progressive message updates.","oneOf":[{"description":"No streaming -- send the complete response as a single message (default).","type":"string","const":"off"},{"description":"Update a draft message with every flush interval.","type":"string","const":"partial"}]},"TailscaleTunnelConfig":{"type":"object","properties":{"funnel":{"description":"Use Tailscale Funnel (public internet) vs Serve (tailnet only)","type":"boolean","default":false},"hostname":{"description":"Optional hostname override","type":["string","null"]}}},"TaskRoutingConfig":{"description":"Lightweight pre-LLM task routing.","type":"object","properties":{"default_intent":{"description":"Fallback intent when no rule matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"rules":{"description":"Rules evaluated in descending priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/TaskRoutingRule"}}}},"TaskRoutingIntentConfig":{"description":"Task-routing default and rule intent.","type":"string","enum":["simple","delegate","stream"]},"TaskRoutingRule":{"description":"A single task-routing rule.","type":"object","properties":{"intent":{"description":"Route intent to apply when a keyword matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"model_hint":{"description":"Optional model hint/raw model for non-delegated requests.","type":["string","null"],"default":null},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0},"sub_agent_model":{"description":"Optional raw sub-agent model override for delegated tasks.","type":["string","null"],"default":null}}},"TelegramConfig":{"description":"Telegram bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Telegram user IDs or usernames. Empty = deny all.","type":"array","items":{"type":"string"}},"bot_token":{"description":"Telegram Bot API token (from @BotFather).","type":"string"},"draft_update_interval_ms":{"description":"Minimum interval (ms) between draft message edits to avoid rate limits.","type":"integer","format":"uint64","default":1000,"minimum":0},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"interrupt_on_new_message":{"description":"When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.","type":"boolean","default":false},"stream_mode":{"description":"Streaming mode for progressive response delivery via message edits.","$ref":"#/$defs/StreamMode","default":"off"}},"required":["bot_token","allowed_users"]},"ToolCallDialectSetting":{"description":"The tool-call grammars an operator may declare for an endpoint.","oneOf":[{"description":"Only the native `tool_calls` array is a tool call (the default).","type":"string","const":"native"},{"description":"Additionally read `{json}` from the content,\nfor a tool name the request registered.","type":"string","const":"xml_function_tags"}]},"ToolSchemaDialectSetting":{"description":"The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.","oneOf":[{"description":"The published document, byte for byte (the default).","type":"string","const":"raw"},{"description":"The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.","type":"string","const":"no_root_combinators"}]},"ToolTieringConfig":{"description":"Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.","type":"object","properties":{"always_exclude":{"description":"Tool names excluded from capability publication.","type":"array","default":[],"items":{"type":"string"}},"always_include":{"description":"Tool names preferred for direct publication, subject to admission gates.","type":"array","default":[],"items":{"type":"string"}},"channel_exclude":{"description":"Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefaults to [`DEFAULT_CHANNEL_EXCLUDED_TOOLS`]; set to `[]` to expose the\nfull operator surface on channels again.","type":"array","default":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","skills_manage","memory_reindex","document_sync","document_ingest"],"items":{"type":"string"}}}},"TunnelConfig":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.","type":"object","properties":{"cloudflare":{"description":"Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).","anyOf":[{"$ref":"#/$defs/CloudflareTunnelConfig"},{"type":"null"}],"default":null},"custom":{"description":"Custom tunnel command configuration (used when `provider = \"custom\"`).","anyOf":[{"$ref":"#/$defs/CustomTunnelConfig"},{"type":"null"}],"default":null},"ngrok":{"description":"ngrok tunnel configuration (used when `provider = \"ngrok\"`).","anyOf":[{"$ref":"#/$defs/NgrokTunnelConfig"},{"type":"null"}],"default":null},"provider":{"description":"Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.","type":"string","default":"none"},"tailscale":{"description":"Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).","anyOf":[{"$ref":"#/$defs/TailscaleTunnelConfig"},{"type":"null"}],"default":null}}},"UserPolicyConfig":{"description":"Startup user policy entry (`[[user_policies]]`).","type":"object","properties":{"blocked_patterns":{"type":"array","default":[],"items":{"type":"string"}},"projects":{"type":"array","default":[],"items":{"type":"string"}},"role":{"type":"string","default":"guest"},"user_id":{"type":"string"},"visibility_ceiling":{"type":"string","default":"private"}},"required":["user_id"]},"WacliConfig":{"description":"wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```","type":"object","properties":{"allow_unsigned_loopback":{"description":"Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).","type":"boolean","default":false},"allowed_from":{"description":"Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.","type":"array","default":["*"],"items":{"type":"string"}},"bot_jid":{"description":"Bot's own JID, used for reply-to-bot mention detection.","type":["string","null"],"default":null},"bot_lid":{"description":"The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.","type":["string","null"],"default":null},"bot_number":{"description":"Bot's own phone number (digits), used for `@` mention detection.","type":["string","null"],"default":null},"cli_path":{"description":"Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.","type":["string","null"],"default":null},"group_reply_mode":{"description":"Smart group-reply mode. When `None`, derived from `mention_only`.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"host":{"description":"REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].","type":["string","null"],"writeOnly":true},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"outbound_media_workspace_only":{"description":"Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.","type":"boolean","default":false},"port":{"description":"REMOVED: legacy JSON-RPC daemon port. See `host`.","type":["integer","null"],"format":"uint16","maximum":65535,"minimum":0,"writeOnly":true},"self_chat_mode":{"description":"Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.","type":"boolean","default":false},"store_dir":{"description":"wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.","type":["string","null"],"default":null},"webhook_listen":{"description":"Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").","type":"string","default":"127.0.0.1:16868"},"webhook_path":{"description":"HTTP path the webhook server serves (default: \"/wacli\").","type":"string","default":"/wacli"},"webhook_secret":{"description":"HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.","type":["string","null"],"default":null}}},"WebSearchConfig":{"description":"Web search tool configuration (`[web_search]` section).","type":"object","properties":{"brave_api_key":{"description":"Brave Search API key (required if provider is \"brave\")","type":["string","null"],"default":null},"fetch_max_chars":{"description":"Maximum characters returned by `web_fetch` (default 10000)","type":"integer","format":"uint","default":50000,"minimum":0},"max_results":{"description":"Maximum results per search (1-20)","type":"integer","format":"uint","default":15,"minimum":0},"provider":{"description":"Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)","type":"string","default":"duckduckgo"},"timeout_secs":{"description":"Request timeout in seconds","type":"integer","format":"uint64","default":15,"minimum":0}}},"WebhookConfig":{"description":"Webhook channel configuration.","type":"object","properties":{"port":{"description":"Port to listen on for incoming webhooks.","type":"integer","format":"uint16","maximum":65535,"minimum":0},"secret":{"description":"Optional shared secret for webhook signature verification.","type":["string","null"]}},"required":["port"]},"WhatsAppConfig":{"description":"WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.","type":"object","properties":{"access_token":{"description":"Access token from Meta Business Suite (Cloud API mode)","type":["string","null"],"default":null},"allowed_numbers":{"description":"Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"app_secret":{"description":"App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"pair_code":{"description":"Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one","type":["string","null"],"default":null},"pair_phone":{"description":"Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used","type":["string","null"],"default":null},"phone_number_id":{"description":"Phone number ID from Meta Business API (Cloud API mode)","type":["string","null"],"default":null},"read_pool_size":{"description":"Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"session_path":{"description":"Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs","type":["string","null"],"default":null},"verify_token":{"description":"Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode","type":["string","null"],"default":null},"ws_url":{"description":"WebSocket URL override (replaces WHATSAPP_WS_URL)","type":["string","null"],"default":null}}},"WorkspaceHooks":{"description":"Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).","oneOf":[{"description":"They do not run (the default); `prx doctor` and `hooks_status` say so.","type":"string","const":"off"},{"description":"They run, in a cleared environment and a dedicated directory beside\n`config.toml`.","type":"string","const":"on"}]},"WorkspaceMcpServers":{"description":"Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).","oneOf":[{"description":"None: a workspace file may only narrow the servers defined in\n`config.toml`.","type":"string","const":"off"},{"description":"HTTP servers (still refused when they target a private address).","type":"string","const":"http_only"},{"description":"HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.","type":"string","const":"stdio"}]},"XinConfig":{"description":"Configuration for the xin autonomous task engine (`[xin]`).","type":"object","properties":{"adopt_legacy_tasks":{"description":"Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).","type":"boolean","default":false},"interval_minutes":{"description":"Tick interval in minutes (minimum 1). Default: 5.","type":"integer","format":"uint32","default":5,"minimum":0},"stale_timeout_minutes":{"description":"Minutes after which a running task is marked stale. Default: 60.","type":"integer","format":"uint32","default":60,"minimum":0}}},"AgentMessaging":{"description":"Owner-controlled inbound session messaging (enabled unless explicitly off).","type":"object","properties":{"inbound":{"type":"boolean","default":true}}}}} From 1c9b4dbb108a4d03da7ab09680f7dc8b35e31e9e Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:40:08 +0400 Subject: [PATCH 0126/1567] fix(config): no rollback confirmation when the install is at Full A rollback still demanded its own confirm (HTTP 428 confirm, or --yes at the transaction) although the install ran at Full. At Full the transaction no longer asks for the rollback's confirm. The expected revision binding stays (a stale If-Match is 409), and the restore_credentials and disable_encryption flags, which protect stored secrets and encryption, are unchanged, as are --allow-credential-clear and allow_secret_clear. prx config rollback still needs --yes. Below Full nothing changes. --- docs/configuration.md | 7 +++++-- docs/rf-contract/capability-tokens.md | 4 +++- src/config/manage/transaction.rs | 4 +++- src/runtime/manage_cli/section_2.rs | 6 ++++++ 4 files changed, 17 insertions(+), 4 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 08a192013..2dd3dcc55 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -2921,8 +2921,11 @@ Rules that hold on every endpoint: `--yes` still gates a CLI write. `--allow-credential-clear` (and `allow_secret_clear=true` on the raw file API) is not a confirmation: it permits a raw-file replacement that would drop stored secrets and stays - required. Below `Full` the rules below apply unchanged. A rollback keeps its - own confirmation. + required. Below `Full` the rules below apply unchanged. A rollback at `Full` + needs no `confirm` (`POST /api/config/rollback`) and no further + confirmation; its `restore_credentials` and `disable_encryption` flags are + secret protection and stay required when they apply. `prx config rollback` + still needs `--yes`. - **High-risk confirmation (below `Full`).** A high-risk plan answers `428` with `required`, `risk_reasons`, `revision` and the `plan` text. Examples: an endpoint change, clearing the root key, or moving the root key to another diff --git a/docs/rf-contract/capability-tokens.md b/docs/rf-contract/capability-tokens.md index 023aa89e3..99f31c4a9 100644 --- a/docs/rf-contract/capability-tokens.md +++ b/docs/rf-contract/capability-tokens.md @@ -215,7 +215,9 @@ without a level reads back Main's level, the one it runs at. answers `428 confirmation_required`; it applies, and `confirm_high_risk` is accepted and not required. A stale `If-Match` is still `409`. A write that raises the level to `full` from a lower level, and any write below - `full`, still answer `428` as before. + `full`, still answer `428` as before. `POST /api/config/rollback` at + `full` no longer answers `428 confirm`; `restore_credentials` and + `disable_encryption` still apply. - `500 storage_unavailable`: the configuration, the registry or a reload failed. diff --git a/src/config/manage/transaction.rs b/src/config/manage/transaction.rs index 01af2e145..2eda94e12 100644 --- a/src/config/manage/transaction.rs +++ b/src/config/manage/transaction.rs @@ -1036,7 +1036,9 @@ impl ConfigTransactions { revision: Some(request.expected_revision.to_string()), }); } - if !request.confirm { + // At Full the rollback itself needs no confirmation; the revision + // binding, `restore_credentials` and `disable_encryption` stay. + if !request.confirm && !plan.applies_at_full() { return Err(ConfigTransactionError::ConfirmationRequired { required: "confirm", reasons: reasons.clone(), diff --git a/src/runtime/manage_cli/section_2.rs b/src/runtime/manage_cli/section_2.rs index 7127f3a1c..7a82f3219 100644 --- a/src/runtime/manage_cli/section_2.rs +++ b/src/runtime/manage_cli/section_2.rs @@ -121,6 +121,12 @@ pub(crate) async fn run_config(command: ConfigCommands, config: Config, io: &mut Some(revision) => revision, None => config::files::current_config_revision(&service.config().config_path)?, }; + // At Full the transaction asks for no confirmation; `--yes` still + // gates the CLI write. + if !yes && service.config().autonomy.level == openprx::security::AutonomyLevel::Full { + writeln!(io.out, "Dry run: nothing was written. Roll back with --yes")?; + return Ok(()); + } let outcome = service .transactions() .rollback(RollbackRequest { From 0e12bce80aeb181876787aeaadf108fd69f4a218 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:48:31 +0400 Subject: [PATCH 0127/1567] fix(cost): share the parent's budget counter with in-process children and publish every tool A child no longer receives half of its parent's remaining balance as a private counter, and publication no longer hides a tool whose cost estimate exceeds the child's ceiling. The total stays enforced at spend time by the shared counter and the workspace cost journal. --- src/runtime/child_source/publication.rs | 2 +- .../child_source/recursive_allowance.rs | 58 +++++++++---------- .../child_source/recursive_allowance/tests.rs | 10 ++-- src/runtime/child_source/tests.rs | 6 +- .../decision_accounting/transport_tests.rs | 8 ++- src/runtime/operator_spawn/task.rs | 2 +- src/runtime/turn_context/opening.rs | 4 +- .../capability/execution_binding/specs.rs | 7 +-- .../search_tool/discovery_admission.rs | 10 ++-- src/tools/surface_owner/publication.rs | 23 ++------ src/tools/surface_owner/tests.rs | 9 +-- 11 files changed, 58 insertions(+), 81 deletions(-) diff --git a/src/runtime/child_source/publication.rs b/src/runtime/child_source/publication.rs index 6223a7bee..adc069f0e 100644 --- a/src/runtime/child_source/publication.rs +++ b/src/runtime/child_source/publication.rs @@ -390,7 +390,7 @@ impl OrdinaryChildPublication { self.inner .authority .allowance - .carve_ordinary_child(self.scope().gate_inputs().0.authority.max_cost_cents) + .share_with_child(self.scope().gate_inputs().0.authority.max_cost_cents) } /// The exact live registry behind the pinned parent catalog. diff --git a/src/runtime/child_source/recursive_allowance.rs b/src/runtime/child_source/recursive_allowance.rs index a39b1ada9..c0d4fc922 100644 --- a/src/runtime/child_source/recursive_allowance.rs +++ b/src/runtime/child_source/recursive_allowance.rs @@ -34,27 +34,28 @@ impl RecursiveAllowance { Arc::clone(&self.money) } - /// Each ordinary launch atomically reserves a strict share of the balance. - /// Failed launches retain their reservation; siblings cannot reuse it. - pub(crate) fn carve_ordinary_child(&self, ceiling_cents: u32) -> anyhow::Result<(u32, Arc)> { - let mut available = self.money.load(Ordering::Acquire); - loop { - let cents = u32::try_from(available.min(u64::from(ceiling_cents) * 10_000) / 20_000)?; - // A zero-price child can still run with a zero money ceiling. - // Paid requests remain denied by its accounting owner. Never give - // it the parent's sub-cent remainder or manufacture a fresh budget. - if cents == 0 { - return Ok((0, Arc::new(Self::new(0)))); - } - let share = u64::from(cents) * 10_000; - match self - .money - .compare_exchange_weak(available, available - share, Ordering::AcqRel, Ordering::Acquire) - { - Ok(_) => return Ok((cents, Arc::new(Self::new(share)))), - Err(current) => available = current, - } + /// An ordinary launch shares this run's counter: no child receives a + /// private slice, so siblings never see 1/2, 1/4, 1/8 of the balance. The + /// returned cents are the child's visible ceiling (the whole remaining + /// balance, capped by `ceiling_cents`). The total stays enforced at spend + /// time by the one atomic counter and the workspace cost journal. + pub(crate) fn share_with_child(&self, ceiling_cents: u32) -> anyhow::Result<(u32, Arc)> { + let available = self.money.load(Ordering::Acquire); + let cents = u32::try_from(available.min(u64::from(ceiling_cents) * 10_000) / 10_000)?; + // A zero-price child can still run with a zero money ceiling. + // Paid requests remain denied by its accounting owner. Never give + // it the parent's sub-cent remainder or manufacture a fresh budget. + if cents == 0 { + return Ok((0, Arc::new(Self::new(0)))); } + Ok(( + cents, + Arc::new(Self { + money: Arc::clone(&self.money), + retention: None, + contexts: AtomicUsize::new(0), + }), + )) } pub(in crate::runtime) fn retire(self: &Arc) { @@ -157,7 +158,7 @@ mod ordinary_concurrency_tests { use super::*; #[test] - fn concurrent_ordinary_reservations_conserve_the_original_envelope() { + fn concurrent_ordinary_launches_share_one_counter() { let initial = 10_000_000; let parent = Arc::new(RecursiveAllowance::new(initial)); let barrier = Arc::new(std::sync::Barrier::new(16)); @@ -169,16 +170,15 @@ mod ordinary_concurrency_tests { let barrier = Arc::clone(&barrier); std::thread::spawn(move || { barrier.wait(); - parent.carve_ordinary_child(1000).map_or(0, |(cents, child)| { - let share = u64::from(cents) * 10_000; - assert_eq!(child.money().load(Ordering::Acquire), share); - share - }) + let (cents, child) = parent.share_with_child(1000).expect("test: share"); + assert!(Arc::ptr_eq(&child.money(), &parent.money())); + cents }) }) .collect(); - let reserved: u64 = handles.into_iter().map(|h| h.join().unwrap()).sum(); - assert!(reserved > 0); - assert_eq!(reserved + parent.money().load(Ordering::Acquire), initial); + for handle in handles { + assert_eq!(handle.join().unwrap(), 1000); + } + assert_eq!(parent.money().load(Ordering::Acquire), initial); } } diff --git a/src/runtime/child_source/recursive_allowance/tests.rs b/src/runtime/child_source/recursive_allowance/tests.rs index cacdc25d7..7521d65eb 100644 --- a/src/runtime/child_source/recursive_allowance/tests.rs +++ b/src/runtime/child_source/recursive_allowance/tests.rs @@ -62,10 +62,10 @@ fn recursive_allowance_exhausted_refuses_spawn_without_decision_service() -> any ); let child = ChildCapabilityManifest::derive_strict_subset(&parent.constraints, &[])?; child.verify(&parent.constraints)?; - let (cents, child_allowance) = parent.allowance.carve_ordinary_child(child.authority.max_cost_cents)?; - assert_eq!(cents, 5); - assert_eq!(child_allowance.money().load(Ordering::Acquire), 50_000); - assert_eq!(parent.allowance.money().load(Ordering::Acquire), 50_000); - assert_eq!(RecursiveAllowance::new(0).carve_ordinary_child(10)?.0, 0); + let (cents, child_allowance) = parent.allowance.share_with_child(child.authority.max_cost_cents)?; + assert_eq!(cents, 10); + assert!(Arc::ptr_eq(&child_allowance.money(), &parent.allowance.money())); + assert_eq!(parent.allowance.money().load(Ordering::Acquire), 100_000); + assert_eq!(RecursiveAllowance::new(0).share_with_child(10)?.0, 0); Ok(()) } diff --git a/src/runtime/child_source/tests.rs b/src/runtime/child_source/tests.rs index 955d0273e..d70cf04e9 100644 --- a/src/runtime/child_source/tests.rs +++ b/src/runtime/child_source/tests.rs @@ -285,7 +285,7 @@ async fn ordinary_case(level: AutonomyLevel, workspace: &tempfile::TempDir) -> a // strict child share, in Full as in Supervised; nothing dispatches. let allowance = &publication.parent_authority().allowance; allowance.money().store(0, Ordering::Release); - assert_eq!(allowance.carve_ordinary_child(1)?.0, 0); + assert_eq!(allowance.share_with_child(1)?.0, 0); assert_eq!(calls.load(Ordering::SeqCst), executed); // Parity: a live executor that drifted from the pinned catalog is @@ -518,10 +518,10 @@ async fn operator_task_cells( // task or parent allowance funds no child share in Full as in // Supervised; nothing dispatches. authority.allowance().money().store(0, Ordering::Release); - assert_eq!(authority.allowance().carve_ordinary_child(1)?.0, 0); + assert_eq!(authority.allowance().share_with_child(1)?.0, 0); let parent = &authority.publication().parent_authority().allowance; parent.money().store(0, Ordering::Release); - assert_eq!(parent.carve_ordinary_child(1)?.0, 0); + assert_eq!(parent.share_with_child(1)?.0, 0); assert_eq!(calls.load(Ordering::SeqCst), executed); // Parity: drift of the live executor refuses the operator source, the diff --git a/src/runtime/decision_accounting/transport_tests.rs b/src/runtime/decision_accounting/transport_tests.rs index ca6578e27..a49a8c16c 100644 --- a/src/runtime/decision_accounting/transport_tests.rs +++ b/src/runtime/decision_accounting/transport_tests.rs @@ -678,9 +678,11 @@ async fn recursive_parent_child_and_leaf_reservations_share_the_original_money() ); let config = Arc::new(config); let initial_money = crate::cost::tracker::remaining_micro_usd_read_only(&config.cost, workspace.path())?; - let root = RecursiveAllowance::new(40_000); - let (_, child) = root.carve_ordinary_child(4)?; - let (_, leaf) = child.carve_ordinary_child(2)?; + // Three independent counters: each owner's reservation is checked against + // its own money, and together they hold the 40_000 envelope. + let root = RecursiveAllowance::new(20_000); + let child = RecursiveAllowance::new(10_000); + let leaf = RecursiveAllowance::new(10_000); let cleanup = Arc::new(CleanupTracker::default()); let result = cleanup .scope(Box::pin(async { diff --git a/src/runtime/operator_spawn/task.rs b/src/runtime/operator_spawn/task.rs index 198454af4..140ee0363 100644 --- a/src/runtime/operator_spawn/task.rs +++ b/src/runtime/operator_spawn/task.rs @@ -119,7 +119,7 @@ impl ChildLaunchSource { parent.ensure_child_available()?; let (_, allowance) = parent .allowance - .carve_ordinary_child(parent.constraints.authority.max_cost_cents)?; + .share_with_child(parent.constraints.authority.max_cost_cents)?; let cancellation = cancellation.child_token(); let authority = Arc::new(OperatorTaskAuthority { id: uuid::Uuid::now_v7(), diff --git a/src/runtime/turn_context/opening.rs b/src/runtime/turn_context/opening.rs index bb4891d58..a74dd34d2 100644 --- a/src/runtime/turn_context/opening.rs +++ b/src/runtime/turn_context/opening.rs @@ -249,9 +249,7 @@ impl TurnRuntimeService { facts: &facts, catalog: &catalog, } - .surface(outgoing_delegation.is_some(), &|bytes| { - crate::cost::estimate::estimate_cost(&model, &self.generation.effective.cost, bytes) - }); + .surface(outgoing_delegation.is_some()); // The turn's one accounting scope, created at opening. Without the // prediction hop nothing has been charged to it yet. let accounting = accounting_scope(self, proof, budgets, deadline); diff --git a/src/tools/capability/execution_binding/specs.rs b/src/tools/capability/execution_binding/specs.rs index db257dc1c..7aa3898b0 100644 --- a/src/tools/capability/execution_binding/specs.rs +++ b/src/tools/capability/execution_binding/specs.rs @@ -27,17 +27,14 @@ pub(crate) fn execution_specs( port: &dyn TurnSurfacePort, proof: &dyn TurnSourceProof, ) -> anyhow::Result { - let model = port.validate_turn(proof)?; + port.validate_turn(proof)?; let view = port.catalog_view(); let rules = rules(port, &view); anyhow::ensure!( rules.turn_scope_admits(), "turn scope no longer passes its execution rules" ); - let cost = &port.config().cost; - let references = rules.surface(port.outgoing_child(), &|bytes| { - crate::cost::estimate::estimate_cost(&model, cost, bytes) - }); + let references = rules.surface(port.outgoing_child()); anyhow::ensure!( references == *port.execution_refs(), "published surface changed after admission" diff --git a/src/tools/capability/search_tool/discovery_admission.rs b/src/tools/capability/search_tool/discovery_admission.rs index 5a2734824..b3d0cfa39 100644 --- a/src/tools/capability/search_tool/discovery_admission.rs +++ b/src/tools/capability/search_tool/discovery_admission.rs @@ -139,7 +139,7 @@ fn discovery_turn_states( ) -> anyhow::Result> { let view = port.catalog_view(); let rules = rules(port, &view); - let model = port.resolve_model(proof)?; + port.resolve_model(proof)?; let incoming = proof.child_scope().map(|scope| scope.gate_inputs().0); let mut states = BTreeMap::new(); for (id, discovered) in entries { @@ -158,8 +158,7 @@ fn discovery_turn_states( _ => "no_child_manifest", }) } else { - let estimate = crate::cost::estimate::estimate_cost(&model, &port.config().cost, entry.schema_bytes); - match rules.capability(entry, &discovered.reference, delegation, estimate) { + match rules.capability(entry, &discovered.reference, delegation) { PublicationAdmission::Passed => DiscoveryTurnState::Callable, PublicationAdmission::ApprovalRequired => DiscoveryTurnState::ApprovalRequired, PublicationAdmission::Blocked { reason_code, .. } => DiscoveryTurnState::Unavailable(reason_code), @@ -343,14 +342,13 @@ pub(crate) fn prepare_discovered_tool( !rules.restricts(entry), "discovered capability conflicts with turn restrictions" ); - let model = port.resolve_model(proof)?; + port.resolve_model(proof)?; let delegation = is_delegator(&entry.public_name); anyhow::ensure!( !delegation || port.outgoing_child(), "offered delegation has no source-issued child manifest" ); - let estimate = crate::cost::estimate::estimate_cost(&model, &port.config().cost, entry.schema_bytes); - let admission = rules.capability(entry, &reference, delegation, estimate); + let admission = rules.capability(entry, &reference, delegation); let descriptor = port .execution() .current_descriptor(&entry.public_name) diff --git a/src/tools/surface_owner/publication.rs b/src/tools/surface_owner/publication.rs index dfee0ec0b..167aa41e4 100644 --- a/src/tools/surface_owner/publication.rs +++ b/src/tools/surface_owner/publication.rs @@ -17,7 +17,7 @@ use std::collections::BTreeSet; use crate::capability::CapabilityAvailabilityLevel; use crate::security::AutonomyLevel; use crate::tools::capability::catalog::{CapabilityEntry, CatalogView, Exposure}; -use crate::tools::capability::contract::{CapabilityRef, CostEstimate, SideEffectClass}; +use crate::tools::capability::contract::{CapabilityRef, SideEffectClass}; use crate::tools::capability::turn_state::{SideEffectMode, TrustedParts, TurnSurfaceKind}; use crate::tools::execution::{ToolExecutionDecision, decide_tool_execution}; use crate::tools::surface_owner::facts::PublicationFacts; @@ -150,7 +150,6 @@ impl PublicationRules<'_, '_> { entry: &CapabilityEntry, reference: &CapabilityRef, delegate: bool, - estimated_cost: Option, ) -> PublicationAdmission { let trusted = self.trusted; let generation = self.catalog.generation(); @@ -164,9 +163,6 @@ impl PublicationRules<'_, '_> { || !(manifest.authority.level == AutonomyLevel::ReadOnly && entry.effect > SideEffectClass::ReadOnly)) && !(delegate && manifest.authority.remaining_depth == 0) - && estimated_cost.is_some_and(|cost| { - cost.micro_usd <= u64::from(manifest.authority.max_cost_cents).saturating_mul(10_000) - }) && self.child_membership_admits(reference) }); if trusted.workspace_id.is_empty() @@ -242,11 +238,7 @@ impl PublicationRules<'_, '_> { /// delegator when the turn sealed an outgoing child manifest on a /// non-interactive surface or at Full. Entries restricted by the turn or blocked by /// [`Self::capability`] are not published. - pub(crate) fn direct_surface( - &self, - outgoing_child: bool, - estimate: &dyn Fn(usize) -> Option, - ) -> BTreeSet { + pub(crate) fn direct_surface(&self, outgoing_child: bool) -> BTreeSet { if !self.facts.model_can_call_tools { return BTreeSet::new(); } @@ -292,19 +284,14 @@ impl PublicationRules<'_, '_> { if self.restricts(entry) { return None; } - let cost = self.facts.child_scope().and_then(|_| estimate(entry.schema_bytes)); - (!self.capability(entry, &reference, delegate, cost).is_blocked()).then_some(reference) + (!self.capability(entry, &reference, delegate).is_blocked()).then_some(reference) }) .collect() } /// The turn's published surface: the direct core. - pub(crate) fn surface( - &self, - outgoing_child: bool, - estimate: &dyn Fn(usize) -> Option, - ) -> BTreeSet { - self.direct_surface(outgoing_child, estimate) + pub(crate) fn surface(&self, outgoing_child: bool) -> BTreeSet { + self.direct_surface(outgoing_child) } /// A delegator in the published surface may bind the turn's sealed diff --git a/src/tools/surface_owner/tests.rs b/src/tools/surface_owner/tests.rs index 057f19023..b866350b9 100644 --- a/src/tools/surface_owner/tests.rs +++ b/src/tools/surface_owner/tests.rs @@ -11,7 +11,6 @@ use super::facts::PublicationFacts; use crate::decision_engine::state::fixtures; use crate::security::{AutonomyLevel, SecurityPolicy}; use crate::tools::capability::catalog::{CapabilityCatalog, CatalogScope, CatalogSources, SurfacePolicy}; -use crate::tools::capability::contract::CostEstimate; use crate::tools::capability::turn_state::{ConstraintCode, SideEffectMode, TrustedParts}; use crate::tools::traits::{Tool, ToolResult}; @@ -121,10 +120,6 @@ fn full_turn_discovery_ignores_an_attenuated_child_manifest() { .expect("test: catalog"); let view = catalog.view(&CatalogScope::default()); let entry = |name: &str| catalog.entry_for_public_name(name).expect("test: registered entry"); - let cost = Some(CostEstimate { - tokens: 0, - micro_usd: 0, - }); for (level, mode) in [ (AutonomyLevel::Full, SideEffectMode::GuardedWrite), (AutonomyLevel::Supervised, SideEffectMode::ApprovalRequired), @@ -161,8 +156,8 @@ fn full_turn_discovery_ignores_an_attenuated_child_manifest() { facts: &facts, catalog: &view, }; - let member = rules.capability(entry("file_write"), &entry_ref(entry("file_write")), false, cost); - let outside = rules.capability(entry("shell"), &entry_ref(entry("shell")), false, cost); + let member = rules.capability(entry("file_write"), &entry_ref(entry("file_write")), false); + let outside = rules.capability(entry("shell"), &entry_ref(entry("shell")), false); if level == AutonomyLevel::Full { assert_eq!( member, From 81297f5f71fb8203296acc28965c4aef2bc8ecfb Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:49:04 +0400 Subject: [PATCH 0128/1567] fix(cost): seal a worker process with the parent's whole remaining balance The manifest format, signature check and the child-not-above-parent check are unchanged; only the sealed value is larger. Docs describe the shared budget. --- docs/decision-engine.md | 2 +- docs/migration-unreleased.md | 10 +++++++--- docs/model-catalog.md | 6 +++--- .../child_source/publication/ordinary_process.rs | 3 +++ 4 files changed, 14 insertions(+), 7 deletions(-) diff --git a/docs/decision-engine.md b/docs/decision-engine.md index f4afb942a..3dd02e551 100644 --- a/docs/decision-engine.md +++ b/docs/decision-engine.md @@ -159,7 +159,7 @@ A child session equals the main session. Every child is issued through one ordinary (or operator) path from its authenticated parent. Recursive delegation is on by default: omitting `allow_delegation` on `sessions_spawn` gives a child that can spawn its own children, bounded only by the sealed -spawn depth, the funding carve from the parent's allowance and the integrity +spawn depth, the parent's shared funding allowance and the integrity checks. Where the bound leaves no room, an omitted flag gives a child that cannot spawn; an explicit `true` is then refused, and an explicit `false` always gives a non-delegating child. There are no recursive-delegation diff --git a/docs/migration-unreleased.md b/docs/migration-unreleased.md index c58aed5cf..de20a3723 100644 --- a/docs/migration-unreleased.md +++ b/docs/migration-unreleased.md @@ -116,9 +116,13 @@ latency_budget_ms = 800 ## Remaining lifecycle and runtime interfaces -Ordinary child monetary budgets now carve from their parent instead of each -receiving the full allowance. Small balances narrow a child to a zero monetary ceiling, so it can run -zero-price work while paid requests remain refused. No fresh money is created. Hook managers are explicitly inherited +Ordinary children and operator tasks now share their parent's budget counter +instead of each receiving half of the remaining balance, and a worker process +is sealed with the parent's whole remaining balance at launch. Every tool is +published to a child; a spend is refused only at spend time, when it would +exceed the real total kept in the workspace cost journal. A balance below one +cent gives a child a zero monetary ceiling, so it can run zero-price work while +paid requests remain refused. No fresh money is created. Hook managers are explicitly inherited independently of child tool exposure. Isolated `skills_manage` callers can read and cancel only their own lifecycle proposals; shared-workspace writes stay local-operator-only. `POST /api/sessions` creates an authenticated empty Console diff --git a/docs/model-catalog.md b/docs/model-catalog.md index ab8e6d61f..e6d2add11 100644 --- a/docs/model-catalog.md +++ b/docs/model-catalog.md @@ -263,9 +263,9 @@ real CLI model listing through the management service and proves release rows carry catalog provenance. Finding 98 rollback: reverting the fix commits restores the C2 adapter -serialization and pending-allowance lifecycle. Ordinary-child allowance -carving is deferred to the next phase; -ordinary children retain independent per-child allowances during closeout. +serialization and pending-allowance lifecycle. Ordinary children now +share their parent's allowance counter; the workspace cost journal remains the +single authority for the total. ## Saving a model level diff --git a/src/runtime/child_source/publication/ordinary_process.rs b/src/runtime/child_source/publication/ordinary_process.rs index 4794c732b..85c5640f7 100644 --- a/src/runtime/child_source/publication/ordinary_process.rs +++ b/src/runtime/child_source/publication/ordinary_process.rs @@ -193,6 +193,9 @@ impl OrdinaryProcessLaunch { &worker.run_id, &worker.config_generation, )?; + // The sealed ceiling is the parent's whole remaining balance (capped by its + // own ceiling). The worker's spends reserve in the parent workspace's cost + // journal, which stays the authority for the total. let (cents, _) = publication.allocate_child_budget()?; let (issued, original_parent) = publication.scope().gate_inputs(); // Seal only backends a worker can reconstruct. Interactive event-loop From 35e3ec066d15f236a420eaccf8eecadee5ce897e Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:48:34 +0400 Subject: [PATCH 0129/1567] fix(mcp): keep allow/deny-filtered MCP tools for a Full caller under a lower Main The MCP registry filtered tools by the allow/deny lists at Main's level at load time, so a named agent running at Full while Main is below Full could neither see nor call them, and dispatch also required the tool to be in the published snapshot. When an enabled named agent runs at Full and Main does not, the filtered tools now stay in the catalog tagged full_only, with the workspace mcp.json narrowing kept as a separate below-Full view. Publication admission hides a tagged tool from a turn below Full, and dispatch refuses it with today's message for a call below Full. With no Full caller configured nothing changes. --- src/decision_engine/questions.rs | 1 + .../capability/catalog/process_snapshot.rs | 4 ++ src/tools/capability/catalog/section_1.rs | 4 ++ src/tools/capability/catalog/section_2.rs | 9 +++ src/tools/capability/search/tests.rs | 3 + src/tools/execution/tests/admission_matrix.rs | 1 + .../execution/tests/exact_call_observation.rs | 1 + src/tools/mcp.rs | 69 +++++++++++++++---- src/tools/mcp/level_view.rs | 44 ++++++++++++ src/tools/mod.rs | 3 +- src/tools/surface_owner/publication.rs | 10 +++ 11 files changed, 133 insertions(+), 16 deletions(-) create mode 100644 src/tools/mcp/level_view.rs diff --git a/src/decision_engine/questions.rs b/src/decision_engine/questions.rs index 61b36b621..240623d39 100644 --- a/src/decision_engine/questions.rs +++ b/src/decision_engine/questions.rs @@ -571,6 +571,7 @@ mod tests { server: "prx_server".into(), tool: tool.clone(), state_digest: [1; 32], + full_only: false, spec: ToolSpec { name: format!("mcp__prx_server__{tool}"), description: if index == 0 { "Fixed compact summary".into() } else { "Extra inventory entry".into() }, diff --git a/src/tools/capability/catalog/process_snapshot.rs b/src/tools/capability/catalog/process_snapshot.rs index 4b5f0f16a..63d60aa84 100644 --- a/src/tools/capability/catalog/process_snapshot.rs +++ b/src/tools/capability/catalog/process_snapshot.rs @@ -50,6 +50,8 @@ struct Entry { availability: CapabilityAvailability, #[serde(default = "process_worker_compatible_by_default")] process_worker_compatible: bool, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + full_only: bool, } const fn process_worker_compatible_by_default() -> bool { @@ -90,6 +92,7 @@ impl CapabilityCatalog { exposure: entry.exposure.clone(), availability: entry.availability.clone(), process_worker_compatible: entry.process_worker_compatible, + full_only: entry.full_only, }) }) .collect::>>()?; @@ -192,6 +195,7 @@ impl CapabilityCatalog { exposure: entry.exposure, availability: entry.availability, process_worker_compatible: entry.process_worker_compatible, + full_only: entry.full_only, }, &mut entries, &mut names, diff --git a/src/tools/capability/catalog/section_1.rs b/src/tools/capability/catalog/section_1.rs index 3bd1b36a8..9d41bef53 100644 --- a/src/tools/capability/catalog/section_1.rs +++ b/src/tools/capability/catalog/section_1.rs @@ -67,6 +67,8 @@ pub(crate) struct CapabilityEntry { pub exposure: Exposure, pub availability: CapabilityAvailability, pub process_worker_compatible: bool, + /// An MCP tool the allow/deny lists hide from callers below Full. + pub full_only: bool, } impl CapabilityEntry { @@ -390,6 +392,7 @@ impl CapabilityCatalog { )?; entry.aliases.push(discovered.tool.clone()); entry.binding_digest = Some(discovered.state_digest); + entry.full_only = discovered.full_only; let op = OpId::new(&crate::security::op_id::op_id( "mcp_call", "call", @@ -951,6 +954,7 @@ fn entry_from_spec( exposure, availability, process_worker_compatible, + full_only: false, }) } diff --git a/src/tools/capability/catalog/section_2.rs b/src/tools/capability/catalog/section_2.rs index b48f16909..c95c0a5d1 100644 --- a/src/tools/capability/catalog/section_2.rs +++ b/src/tools/capability/catalog/section_2.rs @@ -335,6 +335,7 @@ mod tests { server: "notes".into(), tool: "search".into(), state_digest: [0; 32], + full_only: false, spec: ToolSpec { name: "mcp__notes__search".into(), description: "search notes".into(), @@ -404,6 +405,7 @@ mod tests { server: server.into(), tool: "search".into(), state_digest: [0; 32], + full_only: false, spec: ToolSpec { name: format!("mcp__{server}__search"), description: "search".into(), @@ -513,6 +515,7 @@ mod tests { server: "prx_server".into(), tool: "read".into(), state_digest: [3; 32], + full_only: false, spec: ToolSpec { name: "mcp__prx_server__read".into(), description: "MCP".into(), @@ -569,6 +572,7 @@ mod tests { server: "prx_server".into(), tool: "read".into(), state_digest: [1; 32], + full_only: false, spec: ToolSpec { name: "mcp__prx_server__read".into(), description: "Read remote data".into(), @@ -953,6 +957,7 @@ mod tests { server: "prx_server".into(), tool: "read".into(), state_digest: [1; 32], + full_only: false, spec: ToolSpec { name: "mcp__prx_server__read".into(), description: "Read remote data".into(), @@ -988,6 +993,7 @@ mod tests { server: "prx_server".into(), tool: "read".into(), state_digest: [1; 32], + full_only: false, spec: ToolSpec { name: "mcp__prx_server__read".into(), description: "Read remote data".into(), @@ -1107,6 +1113,7 @@ mod tests { server: "prx_server".into(), tool: format!("read_{index}"), state_digest: [0; 32], + full_only: false, spec: ToolSpec { name: format!("mcp__prx_server__read_{index}"), description: "PRX inventory fixture".into(), @@ -1142,6 +1149,7 @@ mod tests { server: "prx_server".into(), tool: "read".into(), state_digest: [0; 32], + full_only: false, spec: ToolSpec { name: "mcp__prx_server__read".into(), description: "Search local evidence".into(), @@ -1250,6 +1258,7 @@ mod tests { server: "prx_server".to_string(), tool: format!("tool_{index}"), state_digest: [0; 32], + full_only: false, spec: ToolSpec { name: format!("mcp__prx_server__tool_{index}"), description: if index == 4095 { diff --git a/src/tools/capability/search/tests.rs b/src/tools/capability/search/tests.rs index 604aee1d2..78b056277 100644 --- a/src/tools/capability/search/tests.rs +++ b/src/tools/capability/search/tests.rs @@ -253,6 +253,7 @@ fn ranked_search_preserves_mixed_alias_and_tokenizer_contracts() { server: "prx_server".into(), tool: "shared_alias".into(), state_digest: [0; 32], + full_only: false, spec: ToolSpec { name: "mcp__prx_server__first".into(), description: "alpha beta evidence".into(), @@ -263,6 +264,7 @@ fn ranked_search_preserves_mixed_alias_and_tokenizer_contracts() { server: "prx_server".into(), tool: "shared_alias".into(), state_digest: [0; 32], + full_only: false, spec: ToolSpec { name: "mcp__prx_server__second".into(), description: "beta alpha alpha evidence".into(), @@ -273,6 +275,7 @@ fn ranked_search_preserves_mixed_alias_and_tokenizer_contracts() { server: "prx_server".into(), tool: "mcp__prx_server__duplicate".into(), state_digest: [0; 32], + full_only: false, spec: ToolSpec { name: "mcp__prx_server__duplicate".into(), description: "beta evidence".into(), diff --git a/src/tools/execution/tests/admission_matrix.rs b/src/tools/execution/tests/admission_matrix.rs index 15088a9f7..6ef9aad3d 100644 --- a/src/tools/execution/tests/admission_matrix.rs +++ b/src/tools/execution/tests/admission_matrix.rs @@ -485,6 +485,7 @@ async fn pinned_mcp_alias_uses_catalog_operation_and_rejects_changed_live_target server: "prx_server__nested".into(), tool: "action".into(), state_digest: [7; 32], + full_only: false, spec: ToolSpec { name: alias.into(), description: "project action".into(), diff --git a/src/tools/execution/tests/exact_call_observation.rs b/src/tools/execution/tests/exact_call_observation.rs index 336b27153..12cb10991 100644 --- a/src/tools/execution/tests/exact_call_observation.rs +++ b/src/tools/execution/tests/exact_call_observation.rs @@ -275,6 +275,7 @@ async fn discovered_mcp_trace_preserves_the_published_server_namespace() { server: "prx_service".to_owned(), tool: "read".to_owned(), state_digest: [7; 32], + full_only: false, spec: crate::tools::ToolSpec { name: descriptor.public_name, description: descriptor.description, diff --git a/src/tools/mcp.rs b/src/tools/mcp.rs index 73076f2de..7d669cb8e 100644 --- a/src/tools/mcp.rs +++ b/src/tools/mcp.rs @@ -153,6 +153,14 @@ struct RuntimeState { /// The registry's held level is Full: per-server allow/deny lists are /// not applied to the published catalog. full_level: bool, + /// A caller that can run at Full exists although the registry's level is + /// below Full: tools its allow/deny lists remove stay in the catalog, + /// tagged `full_only`. + keep_full_only: bool, + /// Servers the workspace `mcp.json` narrows, as a caller below Full sees + /// them (filled only with `keep_full_only`; `effective_config` then holds + /// the unnarrowed definition for Full callers). + below_full: HashMap, } struct StdioSession { @@ -279,6 +287,8 @@ pub(crate) struct McpCapabilitySpec { /// Digest of the effective launch/routing config. Raw env values never /// leave the MCP tool or appear in catalog diagnostics. pub state_digest: [u8; 32], + /// Hidden from and refused to callers below Full (see `level_view`). + pub full_only: bool, } impl McpStatusTool { @@ -324,6 +334,8 @@ impl McpTool { catalog_snapshot: super::SharedToolCatalogSnapshot::default(), capability_specs: Vec::new(), full_level: security.autonomy == crate::security::AutonomyLevel::Full, + keep_full_only: false, + below_full: HashMap::new(), }; let tool = Self { @@ -356,7 +368,7 @@ impl McpTool { /// (`config.toml` alone when `mcp.json` is unreadable). Reads files /// only; starts nothing. fn effective_servers(&self) -> HashMap { - match self.load_workspace_overlay() { + match self.load_workspace_overlay(&mut HashMap::new()) { Ok(Some((config, _))) => config.servers, Ok(None) | Err(_) => self.base_config.servers.clone(), } @@ -519,14 +531,17 @@ impl McpTool { state_hasher.update(config_bytes); let state_digest: [u8; 32] = state_hasher.finalize().into(); for (tool, metadata) in tools { - // At Full the per-server allow/deny lists are ignored. - if !state.full_level && !Self::tool_allowed(server_config, tool) { + // At Full the per-server allow/deny lists are ignored. Below + // Full a filtered tool is dropped, or kept for Full callers. + let full_only = !state.full_level && state.tool_full_only(server, server_config, tool); + if full_only && !state.keep_full_only { continue; } snapshot.push(McpCapabilitySpec { server: server.clone(), tool: tool.clone(), state_digest, + full_only, spec: ToolSpec { name: Self::alias_name(&server_config.tool_name_prefix, server, tool), description: metadata @@ -726,8 +741,20 @@ impl McpTool { // ── Config loading ────────────────────────────────────────────── + #[cfg(test)] fn load_effective_config_from_json(&self) -> anyhow::Result> { - Ok(self.load_workspace_overlay()?.map(|(config, _)| config)) + Ok(self.load_effective_config_with_view()?.map(|(config, _)| config)) + } + + /// The effective config and, with `keep_full_only`, the narrowed view + /// of the servers the workspace `mcp.json` narrows. + fn load_effective_config_with_view( + &self, + ) -> anyhow::Result)>> { + let mut below_full = HashMap::new(); + Ok(self + .load_workspace_overlay(&mut below_full)? + .map(|(config, _)| (config, below_full))) } /// One sentence per workspace `mcp.json` entry that did not start as @@ -735,7 +762,7 @@ impl McpTool { /// without an `mcp.json`. Names and transports only, never a value /// (D-088 C-7). `mcp_status` and `prx doctor` report these. pub fn workspace_server_notes(&self) -> Vec { - match self.load_workspace_overlay() { + match self.load_workspace_overlay(&mut HashMap::new()) { Ok(Some((_, notes))) => notes, Ok(None) => Vec::new(), Err(error) => vec![format!( @@ -753,7 +780,10 @@ impl McpTool { /// that leaves no tool): a non-empty `mcp.json` never silently empties /// the configured set (D-088 C-7). #[allow(clippy::too_many_lines)] - fn load_workspace_overlay(&self) -> anyhow::Result)>> { + fn load_workspace_overlay( + &self, + below_full: &mut HashMap, + ) -> anyhow::Result)>> { if !self.mcp_json_path.exists() { return Ok(None); } @@ -805,6 +835,11 @@ impl McpTool { continue; } match Self::narrowed(base_server, &server.allow_tools, &server.deny_tools) { + // With a Full caller the definition stays whole and the + // narrowed one is the view of callers below Full. + Some(narrowed) if self.keeps_full_only() => { + below_full.insert(name, narrowed); + } Some(narrowed) => { cfg.servers.insert(name, narrowed); } @@ -1502,12 +1537,12 @@ impl McpTool { // stale configuration or browser/session state from the old generation. self.close_stdio_sessions().await; - let (new_config, config_error) = match self.load_effective_config_from_json() { - Ok(Some(from_file)) => (from_file, None), - Ok(None) => (self.base_config.clone(), None), + let (new_config, below_full, config_error) = match self.load_effective_config_with_view() { + Ok(Some((from_file, below_full))) => (from_file, below_full, None), + Ok(None) => (self.base_config.clone(), HashMap::new(), None), Err(error) => { tracing::warn!(path = %self.mcp_json_path.display(), error = %error, "MCP config reload failed"); - (self.base_config.clone(), Some(error.to_string())) + (self.base_config.clone(), HashMap::new(), Some(error.to_string())) } }; @@ -1532,6 +1567,7 @@ impl McpTool { let mut state = self.state.write(); state.mcp_state_epoch = state.mcp_state_epoch.saturating_add(1); state.effective_config = new_config; + state.below_full = below_full; state.discovered_tools = discovered; state.discovery_errors = discovery_errors; state.config_error = config_error; @@ -1554,15 +1590,16 @@ impl McpTool { return; } - let (new_config, config_error) = match self.load_effective_config_from_json() { - Ok(Some(from_file)) => (from_file, None), - Ok(None) => (self.base_config.clone(), None), - Err(error) => (self.base_config.clone(), Some(error.to_string())), + let (new_config, below_full, config_error) = match self.load_effective_config_with_view() { + Ok(Some((from_file, below_full))) => (from_file, below_full, None), + Ok(None) => (self.base_config.clone(), HashMap::new(), None), + Err(error) => (self.base_config.clone(), HashMap::new(), Some(error.to_string())), }; let mut state = self.state.write(); state.mcp_state_epoch = state.mcp_state_epoch.saturating_add(1); state.effective_config = new_config; + state.below_full = below_full; state.discovered_tools.clear(); state.discovery_errors.clear(); state.config_error = config_error; @@ -1602,7 +1639,7 @@ impl McpTool { published.and_then(|entry| entry.binding_digest()), )?; let server = Self::resolve_server(&state.effective_config, &server_name)?; - if !self.call_full() && !Self::tool_allowed(server, &tool_name) { + if !self.call_full() && state.tool_full_only(&server_name, server, &tool_name) { bail!("Tool '{tool_name}' is blocked by allow/deny rules for MCP server '{server_name}'"); } if let Some(discovered) = state.discovered_tools.get(&server_name) @@ -4168,5 +4205,7 @@ for line in sys.stdin: } } +pub(super) mod level_view; + #[cfg(test)] mod dispatch_binding_tests; diff --git a/src/tools/mcp/level_view.rs b/src/tools/mcp/level_view.rs new file mode 100644 index 000000000..a67cfcadf --- /dev/null +++ b/src/tools/mcp/level_view.rs @@ -0,0 +1,44 @@ +//! Tools the registry's own level would filter but a Full caller may use. +//! +//! One MCP registry serves every caller, and it is built with Main's level. +//! When Main is below Full but a named agent can run at Full, a tool that +//! the allow/deny lists remove at Main's level is still loaded and tagged +//! `full_only`: callers below Full do not see it and cannot call it, a Full +//! caller does both. With no Full caller configured the registry filters +//! exactly as before and nothing here is reachable. +use super::{McpServerConfig, McpTool, RuntimeState}; +use crate::config::DelegateAgentConfig; +use crate::security::AutonomyLevel; +use std::collections::HashMap; + +/// Whether some configured caller other than a Main below Full can run at +/// Full: an enabled named agent whose own level is Full. +pub(crate) fn has_full_agent(agents: &HashMap) -> bool { + agents + .values() + .any(|agent| agent.enabled && agent.autonomy == Some(AutonomyLevel::Full)) +} + +impl McpTool { + /// Keep tools filtered by the allow/deny lists, tagged for Full callers + /// (the registry has a Full caller although Main is below Full). + #[must_use] + pub fn with_full_caller(self, full_caller: bool) -> Self { + self.state.write().keep_full_only = full_caller && !self.full(); + self + } + + /// Whether the load step keeps what Main's level would filter. + pub(super) fn keeps_full_only(&self) -> bool { + self.state.read().keep_full_only + } +} + +impl RuntimeState { + /// Whether the allow/deny lists remove `tool` for a caller below Full: + /// the server's own lists and, when kept, the narrowed view of the + /// workspace `mcp.json` lists. + pub(super) fn tool_full_only(&self, server: &str, config: &McpServerConfig, tool: &str) -> bool { + !McpTool::tool_allowed(self.below_full.get(server).unwrap_or(config), tool) + } +} diff --git a/src/tools/mod.rs b/src/tools/mod.rs index c73d6c0de..6a032e686 100644 --- a/src/tools/mod.rs +++ b/src/tools/mod.rs @@ -626,7 +626,8 @@ pub fn all_tools_with_runtime_ext_and_extensions( // outside the agent's workspace (D-088 C-3). // Never inside the workspace: without a configuration directory, only a // server with an absolute `working_dir` starts (D-095 N-4). - let mut mcp_tool = McpTool::new(security.clone(), config.mcp.clone(), workspace_dir.to_path_buf()); + let mut mcp_tool = McpTool::new(security.clone(), config.mcp.clone(), workspace_dir.to_path_buf()) + .with_full_caller(mcp::level_view::has_full_agent(agents)); if let Some(config_dir) = root_config .config_path .parent() diff --git a/src/tools/surface_owner/publication.rs b/src/tools/surface_owner/publication.rs index 167aa41e4..2074a379f 100644 --- a/src/tools/surface_owner/publication.rs +++ b/src/tools/surface_owner/publication.rs @@ -66,6 +66,15 @@ impl PublicationRules<'_, '_> { self.facts.policy.autonomy == AutonomyLevel::Full } + /// The level this turn runs at: a child's sealed level, else the + /// policy's. A tool tagged `full_only` is published only at Full. + fn turn_full(&self) -> bool { + self.facts + .child_scope() + .map_or(self.facts.policy.autonomy, |(manifest, _)| manifest.authority.level) + == AutonomyLevel::Full + } + fn has_constraint(&self, code: &str) -> bool { self.trusted.constraints.iter().any(|item| item.as_str() == code) } @@ -199,6 +208,7 @@ impl PublicationRules<'_, '_> { || !self.catalog.contains(&entry.id) || matches!(entry.exposure, Exposure::Unavailable { .. }) || entry.availability.level < CapabilityAvailabilityLevel::Configured + || (entry.full_only && !self.turn_full()) { return blocked(3, "unavailable_or_stale"); } From a9498c4647b5d902830b09f050a19583ce39af4f Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:49:14 +0400 Subject: [PATCH 0130/1567] fix(mcp): keep loader and interpreter variables of a workspace server at Full A workspace mcp.json stdio server had dynamic-loader, interpreter, search-path, configuration-lookup and certificate or proxy variables stripped from its env at load, even when the install runs at Full. Those are not secrets. At an effective Full level (Main Full, or a Full named agent configured) they are kept; below Full they are dropped as before. The child still starts from the cleared launch environment, so PRX's own secret variables are never inherited. --- src/tools/mcp.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/tools/mcp.rs b/src/tools/mcp.rs index 7d669cb8e..8daaf36e6 100644 --- a/src/tools/mcp.rs +++ b/src/tools/mcp.rs @@ -943,7 +943,13 @@ impl McpTool { } // ── Security gate: strip variables a workspace may not set ── - let removed = Self::sanitize_env_vars(&mut converted.env); + // At an effective Full level of the install the variables are kept: + // they are not secrets, and PRX's own secrets never reach the child. + let removed = if full || self.keeps_full_only() { + Vec::new() + } else { + Self::sanitize_env_vars(&mut converted.env) + }; if !removed.is_empty() { tracing::warn!( server = %shown, From 585ee6ae51ce2b155597398e2f0ec5ae670e816e Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:49:14 +0400 Subject: [PATCH 0131/1567] docs(tools): describe MCP allow/deny and workspace env at Full --- docs/tools.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/docs/tools.md b/docs/tools.md index 89eb32d83..3b7bcec38 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -23,6 +23,17 @@ refresh. Unchanged servers reuse that discovery state. A later configuration or forced-discovery change still invalidates the old catalog; parity, policy, and approval checks remain enforced. +A server's `allow_tools`/`deny_tools` (and the lists of a workspace `mcp.json` +entry that narrows it) apply to callers below Full and are not applied at Full. +When the main agent is below Full but an enabled named agent runs at Full, the +tools those lists remove stay in the catalog for Full callers only: a turn +below Full neither sees nor can call them, a Full turn does both. A workspace +`mcp.json` server may also set loader, interpreter, search-path, +configuration-lookup and certificate or proxy variables in its `env` when the +main agent or a named agent runs at Full; below Full they are dropped as +before. Servers that the opt-in, launcher allowlist or private-address checks +block for the main agent still start only by the main agent's level. + Native tool turns start with the file/shell core (`file_read`, `file_write`, `file_edit`, `shell`). When eligible deferred capabilities exist, the request also declares `capability_search`, including for brief inputs and with the From 6ce30e7db785ea9985c492f0abfdb060389fbf86 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:36:43 +0400 Subject: [PATCH 0132/1567] feat(config): no cost ceiling by default The autonomy daily cents ceiling and the cost daily and monthly limits are now optional and unset by default. A limit applies only when configured; an absent key means no ceiling, no warning and no exhausted notice. The child manifest carries no ceiling as u32::MAX cents. --- SECURITY.md | 2 +- docs/configuration.md | 22 ++- docs/migration-unreleased.md | 1 + src/agent/turn_tests/engine_safety.rs | 2 +- src/agent/turn_tests/engine_switch.rs | 2 +- src/config/init/templates.rs | 4 +- src/config/init/tests.rs | 2 +- src/config/schema/autonomy.rs | 27 +++- src/config/schema/cost.rs | 26 ++-- .../schema/tests/defaults_and_integrations.rs | 2 +- src/config/schema/tests/partial_sections.rs | 2 +- src/config/schema/tests/persistence.rs | 6 +- src/config/schema/tests/security.rs | 2 +- src/cost/tracker.rs | 142 ++++++++++-------- .../tracker/settlement/subscription_tests.rs | 4 +- src/cost/tracker/settlement/tests.rs | 4 +- src/doctor/implementation/section_2.rs | 2 +- src/doctor/tests/section_1.rs | 4 +- .../child_source/golden_effective_config.json | 2 +- src/runtime/decision_accounting.rs | 2 +- .../lesson_delivery/tests/physical_owner.rs | 2 +- src/runtime/mode.rs | 8 +- .../turn_context/tests/publication_scope.rs | 6 +- src/runtime/turn_publication/service.rs | 4 +- src/runtime/turn_publication/service/tests.rs | 4 +- src/security/policy.rs | 6 +- .../lifecycle/service/experiments/pins.rs | 2 +- src/skills/lifecycle/tests/evaluate_agent.rs | 2 +- .../lifecycle/tests/propose/experiments.rs | 2 +- src/tools/sessions_spawn/tests/mod.rs | 2 +- src/tools/sessions_spawn/tests/recursive.rs | 2 +- tests/fixtures/config-schema.json | 2 +- 32 files changed, 167 insertions(+), 135 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index c2bf382e2..95fc5672b 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -82,7 +82,7 @@ split above. 1. **Workspace isolation** — file operations confined to the workspace when `workspace_only = true` (default) 2. **Path traversal blocking** — `..` sequences and absolute paths rejected 3. **Forbidden path list** — critical system paths (`/etc`, `/root`, `~/.ssh`, …) always blocked unless the operator replaces the list -4. **Daily cost cap** — `autonomy.max_cost_per_day_cents` (default 500) +4. **Daily cost cap** — `autonomy.max_cost_per_day_cents` (optional; no cap unless configured) 5. **Identity-scope ACLs** — `[autonomy.scopes]` can deny a tool for a sender, channel, or chat type at every autonomy level ### What We Protect Against diff --git a/docs/configuration.md b/docs/configuration.md index 2dd3dcc55..132b51712 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -79,7 +79,7 @@ and the module-gate family are absorbed on load; they are not live switches. | Section | Keys and defaults | | --- | --- | | `[observability]` | `backend = "none"`; `otel_endpoint` unset; `otel_service_name` unset (collector name `"prx"` when backend is `otel`) | -| `[autonomy]` | `level = "full"`; `workspace_only = true`; built-in `forbidden_paths`; `max_cost_per_day_cents = 500`; `acknowledge_unrestricted_profile = false`; `[autonomy.scopes] default = "allow"`, `rules = []`, `assign_owners = []`. A rule may set `user`/`channel`/`chat_type` and `tools_allow`/`tools_deny`/`send_allow`/`send_deny`/`assign_allow`/`assign_deny` (all empty when omitted) | +| `[autonomy]` | `level = "full"`; `workspace_only = true`; built-in `forbidden_paths`; `max_cost_per_day_cents` unset (no ceiling); `acknowledge_unrestricted_profile = false`; `[autonomy.scopes] default = "allow"`, `rules = []`, `assign_owners = []`. A rule may set `user`/`channel`/`chat_type` and `tools_allow`/`tools_deny`/`send_allow`/`send_deny`/`assign_allow`/`assign_deny` (all empty when omitted) | | `[runtime]` | `kind = "native"`; `shell_env_allowlist = []`; `managed_cgroup_root` unset; `reasoning_enabled` unset; `codex_stream_idle_timeout_secs` unset; `codex_reasoning_effort` unset; `max_blocking_threads` unset (derived, floor 2048); `long_task_warn_secs` unset (900); `idle_hang_secs` unset (1800) | | `[runtime.docker]` | `image = "alpine:3.20"`; `network = "none"`; `memory_limit_mb = 512`; `cpu_limit = 1.0`; `read_only_rootfs = true`; `mount_workspace = true`; `allowed_workspace_roots = []` | | `[reliability]` | `provider_retries = 2`; `provider_backoff_ms = 500`; `fallback_providers = []`; `acknowledge_single_provider_risk = false`; `api_keys = []`; `model_fallbacks = {}`; `channel_initial_backoff_secs = 2`; `channel_max_backoff_secs = 60`; `scheduler_poll_secs = 15`; `scheduler_retries = 2` | @@ -145,7 +145,7 @@ and the module-gate family are absorbed on load; they are not live switches. | `[web_search]` | `provider = "duckduckgo"`; `brave_api_key` unset; `max_results = 15`; `timeout_secs = 15`; `fetch_max_chars = 50000` | | `[proxy]` | `http_proxy`/`https_proxy`/`all_proxy` unset; `no_proxy = []`; `scope = "prx"`; `services = []` | | `[identity]` | `format = "openclaw"`; `aieos_path` unset; `aieos_inline` unset | -| `[cost]` | `daily_limit_usd = 10.0`; `monthly_limit_usd = 100.0`; `warn_at_percent = 80`; `allow_override = false`; `prices = {}` (each price: `input`/`output`/`cache_write`/`cache_read = 0`) | +| `[cost]` | `daily_limit_usd` unset (no limit); `monthly_limit_usd` unset (no limit); `warn_at_percent = 80` (applies only to a configured limit); `allow_override = false`; `prices = {}` (each price: `input`/`output`/`cache_write`/`cache_read = 0`) | | `[nodes]` | `request_timeout_ms = 15000`; `retry_max = 2`; `nodes = []`. A node: `id`, `endpoint`, `bearer_token` required; `hmac_secret` unset; `timeout_ms`/`retry_max` unset | | `[nodes.server]` | `listen_addr = "127.0.0.1:8787"`; `bearer_token = ""`; `hmac_secret` unset; `sandbox_root = "."`; `exec_timeout_ms = 15000`; `max_output_bytes = 1048576`; `max_concurrent_tasks = 8`; `task_result_ttl_ms = 3600000`; `allowed_commands = ["echo"]`; `blocked_commands = []`; `tls_required = true`; `tls_cert`/`tls_key` unset | | `[agents.]` | `provider`/`model` required; `system_prompt`/`api_key`/`credential_ref`/`temperature`/`identity_dir`/`memory_scope`/`spawn_enabled`/`autonomy` unset; `max_depth = 8`; `agentic = true`; `allowed_tools = []` (empty means all tools, the same as `["*"]`); `enabled = true` | @@ -823,7 +823,7 @@ allow_executable_proposals = false level = "full" workspace_only = true forbidden_paths = ["/etc", "/root", "/home", "/opt", "/tmp", "~/.ssh"] -max_cost_per_day_cents = 500 +# max_cost_per_day_cents = 500 # unset means no ceiling # Multi-agent setup [agents.researcher] @@ -905,11 +905,17 @@ agents, and process-isolated session workers. `forbidden path argument: `). The tool checks the same path again when it runs, because the file can change in between. -An unrestricted profile is always explicit: set `workspace_only = false`, -clear `forbidden_paths`, and set `max_cost_per_day_cents = 4294967295` -(`u32::MAX`). `prx doctor` warns when those three are active together -unless `acknowledge_unrestricted_profile = true`. There is no hourly action -cap. +There is no spend ceiling unless you configure one. Leave +`max_cost_per_day_cents`, `[cost] daily_limit_usd` and `[cost] monthly_limit_usd` +out of the file for no limit; set a key and exactly that limit applies (`0` +refuses every priced turn). The signed child manifest carries "no ceiling" as +`u32::MAX` cents (4294967295, the same value the key accepts). Spend is still +recorded in the cost journal. With no limit set, no budget warning or +"budget exhausted" notice is produced. A host-wide profile is explicit: set +`workspace_only = false` and clear `forbidden_paths`. `prx doctor` warns when +those two are active together with no cost ceiling unless +`acknowledge_unrestricted_profile = true`; the flag only silences that warning. +There is no hourly action cap. ### Decision admission and autonomy diff --git a/docs/migration-unreleased.md b/docs/migration-unreleased.md index de20a3723..cedf6ca96 100644 --- a/docs/migration-unreleased.md +++ b/docs/migration-unreleased.md @@ -28,6 +28,7 @@ of the [changelog](../CHANGELOG.md). | Retired `[router]` continuation table | The retired continuation table under `[router]` is ignored with one warning at load; delete it. Turns keep the serving model's reply. Authenticated historical v1 replies remain readable. | Only if that table is still in the file | | Source-tree layout | The repository root no longer ships a `task/` notes tree. Proptest shrinking seeds belong under `tests/proptest-regressions/`; a root `proptest-regressions/` directory is gitignored and is not replayed. | Only when working from a source clone | | Known Codex model default effort | Declared Codex rows now use `medium` rather than `xhigh`. Set an explicit supported effort if the former behavior is required. Unknown rows keep the legacy `medium` verbosity / `xhigh` effort base. See [model levels and parameters](model-catalog.md). | Only to retain the former effort | +| No spend ceiling by default | `[autonomy] max_cost_per_day_cents`, `[cost] daily_limit_usd` and `[cost] monthly_limit_usd` are now optional and unset by default. Before: a config that omitted them got 500 cents per day, 10.0 USD per day and 100.0 USD per month. Now: a config that omits them has no limit, so no spend is refused for a budget reason, no budget warning or "budget exhausted" notice is printed, and children and worker processes get the maximum allowance (`u32::MAX` cents in the signed manifest). A config that sets any of these keys keeps exactly that limit. `prx init` no longer writes `max_cost_per_day_cents`. Usage accounting and the cost journal are unchanged. To keep the old ceilings, write them into the config. Per-agent `limits` were already unset by default. No stored-data migration is required. | Only to keep the former ceilings: set the three keys explicitly | | WASM plugins off by default | Set `[plugins] enabled = true` and restart only after reviewing each plugin; install or update with `wasm_plugins_manage` and explicit `grant_permissions` to write `plugin-trust.json` beside `config.toml`. The configuration directory and `plugin-cache/` must be outside the workspace. A `.prx-managed` marker grants no trust. | To use WASM plugins | | Plugin outbound requests | An empty `http_allowlist` now denies every URL. Use URL patterns such as `https://api.example.com/*`, not string prefixes such as `https://api.example.com*`. The SSRF guard still refuses private, loopback and other unsafe destinations. See [plugin trust and networking](plugin-developer-guide.md). | For plugins needing outbound HTTP | | Workspace command hooks default off | Set `[security] workspace_hooks = "on"` only after reviewing workspace commands. Remove non-null `cwd` from `hooks.json`: the whole candidate file is refused. Commands now start with a cleared environment in the dedicated directory beside `config.toml`; use explicit paths and allowed `env` entries. See [workspace command hooks](configuration.md#workspace-command-hooks). | To run workspace command hooks | diff --git a/src/agent/turn_tests/engine_safety.rs b/src/agent/turn_tests/engine_safety.rs index e80ea0347..80e5e29f9 100644 --- a/src/agent/turn_tests/engine_safety.rs +++ b/src/agent/turn_tests/engine_safety.rs @@ -305,7 +305,7 @@ fn priced_config(workspace: &std::path::Path, daily_limit_usd: f64) -> crate::co cache_read: 0.0, }, ); - config.cost.daily_limit_usd = daily_limit_usd; + config.cost.daily_limit_usd = Some(daily_limit_usd); config.agent.compaction.max_context_tokens = 100_000; config.agent.compaction.max_context_tokens_explicit = true; config.agent.compaction.reserve_tokens = 100; diff --git a/src/agent/turn_tests/engine_switch.rs b/src/agent/turn_tests/engine_switch.rs index 5c063866a..2efead689 100644 --- a/src/agent/turn_tests/engine_switch.rs +++ b/src/agent/turn_tests/engine_switch.rs @@ -1751,7 +1751,7 @@ async fn post_deletion_turn_commits_terminal_without_decision_rows() { "(c) a differing workspace is refused" ); let mut other_cost = cost.clone(); - other_cost.daily_limit_usd += 1.0; + other_cost.daily_limit_usd = Some(1.0); assert!( finalize_turn(&fabric, draft.clone(), &other_cost, workspace.path()) .await diff --git a/src/config/init/templates.rs b/src/config/init/templates.rs index f8b4e1c24..a522b52d9 100644 --- a/src/config/init/templates.rs +++ b/src/config/init/templates.rs @@ -258,8 +258,7 @@ pub(super) fn security_template(spec: Spec) -> String { [autonomy] level = "full" workspace_only = true -# Secure autonomous defaults. Operators may explicitly widen these values. -max_cost_per_day_cents = 500 +# No daily cost ceiling unless max_cost_per_day_cents is set here. # Set true only when host-wide unrestricted operation is intentional and # reviewed. This suppresses doctor noise; it is not a capability gate. acknowledge_unrestricted_profile = false @@ -292,7 +291,6 @@ status = "unclassified" # unclassified | high_risk | not_high_risk level = "full" # read_only | supervised | full workspace_only = false forbidden_paths = [] # no extra path denylist -max_cost_per_day_cents = 4294967295 # Set true only when host-wide unrestricted operation is intentional and # reviewed. This suppresses doctor noise; it is not a capability gate. acknowledge_unrestricted_profile = false diff --git a/src/config/init/tests.rs b/src/config/init/tests.rs index 26a4abbd3..f5e3e1634 100644 --- a/src/config/init/tests.rs +++ b/src/config/init/tests.rs @@ -1197,7 +1197,7 @@ fn server_security_template_defaults_to_autonomous_with_workspace_boundary() { let content = security_template(Spec::Server); assert!(content.contains("level = \"full\"")); assert!(content.contains("workspace_only = true")); - assert!(content.contains("max_cost_per_day_cents = 500")); + assert!(!content.contains("max_cost_per_day_cents =")); assert!(content.contains("\"/etc\"")); assert!(!content.contains("level = \"supervised\"")); } diff --git a/src/config/schema/autonomy.rs b/src/config/schema/autonomy.rs index 8e1e90f10..489ffa385 100644 --- a/src/config/schema/autonomy.rs +++ b/src/config/schema/autonomy.rs @@ -330,7 +330,11 @@ pub(super) fn validate_acl_pair_entry(path: &str, left_name: &str, right_name: & /// pipeline and the per-tool `auto_approve` / `always_ask` / `allowed_commands` /// lists have been removed; coarse risk presets are governed entirely by /// `level`. Fine-grained per-risk classification is deferred to Phase 2. -pub const DEFAULT_AUTONOMY_MAX_COST_PER_DAY_CENTS: u32 = 500; +/// The value `SecurityPolicy` carries when no daily cost ceiling is configured +/// (and the value an operator may write to say the same explicitly). The signed +/// child manifest's `max_cost_cents` is a fixed-width integer compared only as +/// `child <= parent`, so the maximum stands for "no ceiling" there. +pub const UNLIMITED_AUTONOMY_MAX_COST_PER_DAY_CENTS: u32 = u32::MAX; #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] pub struct AutonomyConfig { @@ -355,9 +359,9 @@ pub struct AutonomyConfig { /// denylist. #[serde(default = "default_forbidden_paths")] pub forbidden_paths: Vec, - /// Maximum cost per day in cents per policy. Default: `500`. - #[serde(default = "default_autonomy_max_cost_per_day_cents")] - pub max_cost_per_day_cents: u32, + /// Maximum cost per day in cents per policy. Default: unset (no ceiling). + #[serde(default)] + pub max_cost_per_day_cents: Option, /// Operator acknowledgement for an intentionally unrestricted profile. /// This suppresses doctor noise only; it does not alter policy behavior. @@ -376,7 +380,7 @@ impl Default for AutonomyConfig { level: AutonomyLevel::Full, workspace_only: default_workspace_only(), forbidden_paths: default_forbidden_paths(), - max_cost_per_day_cents: default_autonomy_max_cost_per_day_cents(), + max_cost_per_day_cents: None, acknowledge_unrestricted_profile: false, scopes: ScopeConfig::default(), } @@ -418,7 +422,14 @@ pub(super) fn default_forbidden_paths() -> Vec { ] } -/// The default per-policy daily cost ceiling, in cents. -pub(super) const fn default_autonomy_max_cost_per_day_cents() -> u32 { - DEFAULT_AUTONOMY_MAX_COST_PER_DAY_CENTS +impl AutonomyConfig { + /// The per-policy daily ceiling in cents, or + /// [`UNLIMITED_AUTONOMY_MAX_COST_PER_DAY_CENTS`] when none is configured. + #[must_use] + pub const fn effective_max_cost_per_day_cents(&self) -> u32 { + match self.max_cost_per_day_cents { + Some(cents) => cents, + None => UNLIMITED_AUTONOMY_MAX_COST_PER_DAY_CENTS, + } + } } diff --git a/src/config/schema/cost.rs b/src/config/schema/cost.rs index 748264ebb..4f9215b0d 100644 --- a/src/config/schema/cost.rs +++ b/src/config/schema/cost.rs @@ -5,15 +5,15 @@ use super::{Deserialize, JsonSchema, Serialize}; /// Cost tracking and budget enforcement configuration (`[cost]` section). #[derive(Clone, PartialEq, Serialize, Deserialize, JsonSchema)] pub struct CostConfig { - /// Daily spending limit in USD (default: 10.00) - #[serde(default = "default_daily_limit")] - pub daily_limit_usd: f64, + /// Daily spending limit in USD (default: unset, no limit; 0 refuses every priced turn) + #[serde(default)] + pub daily_limit_usd: Option, - /// Monthly spending limit in USD (default: 100.00) - #[serde(default = "default_monthly_limit")] - pub monthly_limit_usd: f64, + /// Monthly spending limit in USD (default: unset, no limit). + #[serde(default)] + pub monthly_limit_usd: Option, - /// Warn when spending reaches this percentage of limit (default: 80) + /// Warn when spending reaches this percentage of a configured limit (default: 80) #[serde(default = "default_warn_percent")] pub warn_at_percent: u8, @@ -56,14 +56,6 @@ impl ModelPricing { } } -pub(super) const fn default_daily_limit() -> f64 { - 10.0 -} - -pub(super) const fn default_monthly_limit() -> f64 { - 100.0 -} - pub(super) const fn default_warn_percent() -> u8 { 80 } @@ -71,8 +63,8 @@ pub(super) const fn default_warn_percent() -> u8 { impl Default for CostConfig { fn default() -> Self { Self { - daily_limit_usd: default_daily_limit(), - monthly_limit_usd: default_monthly_limit(), + daily_limit_usd: None, + monthly_limit_usd: None, warn_at_percent: default_warn_percent(), allow_override: false, // Operator overrides only. Built-in prices come from the embedded diff --git a/src/config/schema/tests/defaults_and_integrations.rs b/src/config/schema/tests/defaults_and_integrations.rs index 09e68d795..755e193d4 100644 --- a/src/config/schema/tests/defaults_and_integrations.rs +++ b/src/config/schema/tests/defaults_and_integrations.rs @@ -608,7 +608,7 @@ async fn config_toml_roundtrip() { level: AutonomyLevel::Full, workspace_only: false, forbidden_paths: vec!["/secret".into()], - max_cost_per_day_cents: 1000, + max_cost_per_day_cents: Some(1000), scopes: ScopeConfig::default(), ..AutonomyConfig::default() }, diff --git a/src/config/schema/tests/partial_sections.rs b/src/config/schema/tests/partial_sections.rs index a86a491a1..7555e99bd 100644 --- a/src/config/schema/tests/partial_sections.rs +++ b/src/config/schema/tests/partial_sections.rs @@ -73,7 +73,7 @@ fn a_partial_autonomy_section_fails_closed() { !parsed.acknowledge_unrestricted_profile, "acknowledge_unrestricted_profile must stay false when omitted" ); - assert_eq!(parsed.max_cost_per_day_cents, 500); + assert_eq!(parsed.max_cost_per_day_cents, None); assert_eq!(parsed.level, AutonomyLevel::Full); } diff --git a/src/config/schema/tests/persistence.rs b/src/config/schema/tests/persistence.rs index 3fd3a962f..862eebac3 100644 --- a/src/config/schema/tests/persistence.rs +++ b/src/config/schema/tests/persistence.rs @@ -212,7 +212,7 @@ max_size_mb = 42 assert_eq!(loaded.default_model.as_deref(), Some("kept")); assert_eq!(loaded.agents["researcher"].model, "kept-agent-model"); assert_eq!(loaded.sessions_spawn.process_memory_strategy, "isolated_private"); - assert_eq!(loaded.autonomy.max_cost_per_day_cents, 4_294_967_295); + assert_eq!(loaded.autonomy.max_cost_per_day_cents, Some(4_294_967_295)); assert_eq!(loaded.gateway.port, 3120); assert!(loaded.memory.events.record_tool_events); assert_eq!(loaded.security.audit.max_size_mb, 42); @@ -328,7 +328,7 @@ max_memory_mb = 512 let loaded = Config::load_from_path(&dir.join("config.toml"), dir.join("workspace")) .expect("a fragment carrying removed keys must still load"); - assert_eq!(loaded.autonomy.max_cost_per_day_cents, 4_294_967_295); + assert_eq!(loaded.autonomy.max_cost_per_day_cents, Some(4_294_967_295)); let _ = fs::remove_dir_all(&dir).await; } @@ -358,7 +358,7 @@ async fn config_split_and_reload_roundtrip_matches_original() { // Keep test deterministic even if process env mutates proxy defaults elsewhere. config.proxy = ProxyConfig::default(); config.security.audit.max_size_mb = 120; - config.autonomy.max_cost_per_day_cents = 42; + config.autonomy.max_cost_per_day_cents = Some(42); config.agents.insert( "worker".into(), DelegateAgentConfig { diff --git a/src/config/schema/tests/security.rs b/src/config/schema/tests/security.rs index b926dfdd7..543ca4e5d 100644 --- a/src/config/schema/tests/security.rs +++ b/src/config/schema/tests/security.rs @@ -9,7 +9,7 @@ async fn autonomy_config_default() { assert_eq!(a.level, AutonomyLevel::Full); assert!(a.workspace_only); assert!(a.forbidden_paths.contains(&"/etc".to_string())); - assert_eq!(a.max_cost_per_day_cents, DEFAULT_AUTONOMY_MAX_COST_PER_DAY_CENTS); + assert_eq!(a.max_cost_per_day_cents, None); } #[test] diff --git a/src/cost/tracker.rs b/src/cost/tracker.rs index 71db1a724..e0ff81c20 100644 --- a/src/cost/tracker.rs +++ b/src/cost/tracker.rs @@ -162,7 +162,9 @@ fn remaining_micro_usd_read_only_inner( .saturating_sub(spend.daily) .min(spend.month_limit.saturating_sub(spend.monthly)) .min(security_daily_micro.map_or(u128::MAX, |limit| limit.saturating_sub(spend.daily))); - u64::try_from(remaining).context("remaining cost budget is out of range") + // Only reachable without any limit (the production caller always carries + // the security ceiling): unlimited, not an error. + Ok(u64::try_from(remaining).unwrap_or(u64::MAX)) } /// A daily limit that today's charged amount has used up, in micro-USD. @@ -183,6 +185,10 @@ pub(crate) fn exhausted_daily_budget_read_only( workspace_dir: &Path, max_cost_per_day_cents: u32, ) -> Result> { + // No daily limit at all: nothing can be exhausted, so skip the ledger read. + if config.daily_limit_usd.is_none() && max_cost_per_day_cents == u32::MAX { + return Ok(None); + } let spend = read_only_spend(config, workspace_dir)?; // Both limits charge the same daily figure, so the lower limit is the one // with the lower remaining. @@ -202,12 +208,10 @@ struct ReadOnlySpend { } fn read_only_spend(config: &CostConfig, workspace_dir: &Path) -> Result { - if !config.daily_limit_usd.is_finite() - || !config.monthly_limit_usd.is_finite() - || config.daily_limit_usd < 0.0 - || config.monthly_limit_usd < 0.0 - { - return Err(anyhow!("cost limits are not finite nonnegative amounts")); + for limit in [config.daily_limit_usd, config.monthly_limit_usd].into_iter().flatten() { + if !limit.is_finite() || limit < 0.0 { + return Err(anyhow!("cost limits are not finite nonnegative amounts")); + } } let workspace = workspace_dir .canonicalize() @@ -256,11 +260,21 @@ fn read_only_spend(config: &CostConfig, workspace_dir: &Path) -> Result Result { + config.daily_limit_usd.map_or(Ok(u128::MAX), floor_micro_usd) +} + +/// The monthly limit in micro-USD; `u128::MAX` when none is configured. +fn month_limit_micro_usd(config: &CostConfig) -> Result { + config.monthly_limit_usd.map_or(Ok(u128::MAX), floor_micro_usd) +} + pub(crate) fn ceil_micro_usd(usd: f64) -> Result { exact_micro_usd(usd, true) } @@ -641,9 +655,9 @@ impl CostTracker { .monthly_micro_usd .checked_add(active) .context("monthly reserved cost overflows")?; - let remaining = floor_micro_usd(config.daily_limit_usd)? + let remaining = day_limit_micro_usd(&config)? .saturating_sub(daily) - .min(floor_micro_usd(config.monthly_limit_usd)?.saturating_sub(monthly)) + .min(month_limit_micro_usd(&config)?.saturating_sub(monthly)) .min(u128::from(request.security_daily_micro_usd).saturating_sub(daily)); reservations.reserve(workspace, request, remaining) } @@ -669,9 +683,9 @@ impl CostTracker { .monthly_micro_usd .checked_add(active) .context("monthly reserved cost overflows")?; - let remaining = floor_micro_usd(config.daily_limit_usd)? + let remaining = day_limit_micro_usd(&config)? .saturating_sub(daily) - .min(floor_micro_usd(config.monthly_limit_usd)?.saturating_sub(monthly)) + .min(month_limit_micro_usd(&config)?.saturating_sub(monthly)) .min(u128::from(request.reservation.security_daily_micro_usd).saturating_sub(daily)); reservations.reserve_estimated(workspace, request, remaining) } @@ -714,9 +728,9 @@ impl CostTracker { .monthly_micro_usd .checked_add(active) .context("monthly reserved cost overflows")?; - let remaining = floor_micro_usd(config.daily_limit_usd)? + let remaining = day_limit_micro_usd(&config)? .saturating_sub(daily) - .min(floor_micro_usd(config.monthly_limit_usd)?.saturating_sub(monthly)) + .min(month_limit_micro_usd(&config)?.saturating_sub(monthly)) .min(u128::from(request.reservation.security_daily_micro_usd).saturating_sub(daily)); anyhow::ensure!(may_dispatch(), "attempt deadline elapsed before durable dispatch"); reservations.reserve_dispatched_estimated(workspace, request, remaining) @@ -974,42 +988,52 @@ fn budget_check( // configured ceilings round down. Floating-point addition can lose a // small new charge when the current total is near its limit. let estimate = ceil_micro_usd(estimated_cost_usd)?; - let day_limit = floor_micro_usd(config.daily_limit_usd)?; - let month_limit = floor_micro_usd(config.monthly_limit_usd)?; + let day_limit = day_limit_micro_usd(config)?; + let month_limit = month_limit_micro_usd(config)?; let projected_daily = daily_micro .checked_add(estimate) .context("daily projected cost overflows")?; let projected_monthly = monthly_micro .checked_add(estimate) .context("monthly projected cost overflows")?; - if projected_daily > day_limit { + // An unset limit is `u128::MAX` micro-USD and never exceeded. + if let Some(limit_usd) = config.daily_limit_usd + && projected_daily > day_limit + { return Ok(BudgetCheck::Exceeded { current_usd: daily_cost, - limit_usd: config.daily_limit_usd, + limit_usd, period: UsagePeriod::Day, }); } - if projected_monthly > month_limit { + if let Some(limit_usd) = config.monthly_limit_usd + && projected_monthly > month_limit + { return Ok(BudgetCheck::Exceeded { current_usd: monthly_cost, - limit_usd: config.monthly_limit_usd, + limit_usd, period: UsagePeriod::Month, }); } // Divide before multiplying to keep the percentage calculation bounded. let percent = u128::from(config.warn_at_percent.min(100)); let warning_at = |limit: u128| (limit / 100) * percent + ((limit % 100) * percent).div_ceil(100); - if projected_daily >= warning_at(day_limit) { + // With no limit there is nothing to warn against. + if let Some(limit_usd) = config.daily_limit_usd + && projected_daily >= warning_at(day_limit) + { return Ok(BudgetCheck::Warning { current_usd: daily_cost, - limit_usd: config.daily_limit_usd, + limit_usd, period: UsagePeriod::Day, }); } - if projected_monthly >= warning_at(month_limit) { + if let Some(limit_usd) = config.monthly_limit_usd + && projected_monthly >= warning_at(month_limit) + { return Ok(BudgetCheck::Warning { current_usd: monthly_cost, - limit_usd: config.monthly_limit_usd, + limit_usd, period: UsagePeriod::Month, }); } @@ -1578,8 +1602,8 @@ mod tests { fn estimated_attempt_overrun_records_actual_without_legacy_poison() { let tmp = TempDir::new().unwrap(); let config = CostConfig { - daily_limit_usd: 1.0, - monthly_limit_usd: 1.0, + daily_limit_usd: Some(1.0), + monthly_limit_usd: Some(1.0), ..enabled_config() }; let tracker = CostTracker::new(config.clone(), tmp.path()).unwrap(); @@ -1616,8 +1640,8 @@ mod tests { fn estimated_unknown_drop_retains_tokens_and_money_across_reopen() { let tmp = TempDir::new().unwrap(); let config = CostConfig { - daily_limit_usd: 1.0, - monthly_limit_usd: 1.0, + daily_limit_usd: Some(1.0), + monthly_limit_usd: Some(1.0), ..enabled_config() }; let tracker = CostTracker::new(config.clone(), tmp.path()).unwrap(); @@ -1641,8 +1665,8 @@ mod tests { fn estimated_dispatch_batches_existing_journal_rows_before_authority_returns() { let tmp = TempDir::new().unwrap(); let config = CostConfig { - daily_limit_usd: 1.0, - monthly_limit_usd: 1.0, + daily_limit_usd: Some(1.0), + monthly_limit_usd: Some(1.0), ..enabled_config() }; let request = estimated("prx-batched-dispatch", 250_000, 30, 30); @@ -1690,8 +1714,8 @@ mod tests { fn expired_reservation_wait_never_marks_attempt_dispatched() { let tmp = TempDir::new().unwrap(); let config = CostConfig { - daily_limit_usd: 1.0, - monthly_limit_usd: 1.0, + daily_limit_usd: Some(1.0), + monthly_limit_usd: Some(1.0), ..enabled_config() }; let tracker = Arc::new(CostTracker::new(config, tmp.path()).unwrap()); @@ -1733,8 +1757,8 @@ mod tests { fn reservation_reconciliation_requires_cost_first_and_preserves_turn_spend() { let tmp = TempDir::new().unwrap(); let config = CostConfig { - daily_limit_usd: 1.0, - monthly_limit_usd: 1.0, + daily_limit_usd: Some(1.0), + monthly_limit_usd: Some(1.0), ..enabled_config() }; let tracker = CostTracker::new(config.clone(), tmp.path()).unwrap(); @@ -1906,8 +1930,8 @@ mod tests { fn reserved_budget_survives_reopen_and_sent_liability_cannot_be_released() { let tmp = TempDir::new().unwrap(); let config = CostConfig { - daily_limit_usd: 1.0, - monthly_limit_usd: 1.0, + daily_limit_usd: Some(1.0), + monthly_limit_usd: Some(1.0), ..enabled_config() }; let first = CostTracker::new(config.clone(), tmp.path()).unwrap(); @@ -1954,8 +1978,8 @@ mod tests { fn competing_trackers_cannot_reserve_the_same_remaining_balance() { let tmp = TempDir::new().unwrap(); let config = CostConfig { - daily_limit_usd: 1.0, - monthly_limit_usd: 1.0, + daily_limit_usd: Some(1.0), + monthly_limit_usd: Some(1.0), ..enabled_config() }; let first = CostTracker::new(config.clone(), tmp.path()).unwrap(); @@ -1996,8 +2020,8 @@ mod tests { fn budget_rounds_each_charge_up_and_survives_reopen() { let tmp = TempDir::new().unwrap(); let config = CostConfig { - daily_limit_usd: 2_f64.powi(-19), - monthly_limit_usd: 1.0, + daily_limit_usd: Some(2_f64.powi(-19)), + monthly_limit_usd: Some(1.0), ..enabled_config() }; let tracker = CostTracker::new(config.clone(), tmp.path()).unwrap(); @@ -2030,8 +2054,8 @@ mod tests { fn budget_does_not_lose_small_charge_at_large_limit() { let limit = 2_f64.powi(53); let config = CostConfig { - daily_limit_usd: limit, - monthly_limit_usd: limit, + daily_limit_usd: Some(limit), + monthly_limit_usd: Some(limit), ..enabled_config() }; let total = ceil_micro_usd(limit).unwrap(); @@ -2052,9 +2076,9 @@ mod tests { let tmp = TempDir::new().unwrap(); let mut config = enabled_config(); if daily { - config.daily_limit_usd = invalid; + config.daily_limit_usd = Some(invalid); } else { - config.monthly_limit_usd = invalid; + config.monthly_limit_usd = Some(invalid); } let tracker = CostTracker::new(config, tmp.path()).unwrap(); assert!(tracker.check_budget(0.0).is_err()); @@ -2115,8 +2139,8 @@ mod tests { fn read_only_budget_snapshot_bounds_spend_without_creating_files() { let tmp = TempDir::new().unwrap(); let config = CostConfig { - daily_limit_usd: 2.0, - monthly_limit_usd: 3.0, + daily_limit_usd: Some(2.0), + monthly_limit_usd: Some(3.0), ..Default::default() }; assert_eq!(remaining_micro_usd_read_only(&config, tmp.path()).unwrap(), 2_000_000); @@ -2133,8 +2157,8 @@ mod tests { fn read_only_security_daily_ceiling_subtracts_prior_spend_and_rejects_bad_ledger() { let tmp = TempDir::new().unwrap(); let config = CostConfig { - daily_limit_usd: 100.0, - monthly_limit_usd: 100.0, + daily_limit_usd: Some(100.0), + monthly_limit_usd: Some(100.0), ..Default::default() }; assert_eq!( @@ -2230,8 +2254,8 @@ mod tests { } ledger.sync_all().unwrap(); let config = CostConfig { - daily_limit_usd: 10_000_000_001.0, - monthly_limit_usd: 10_000_000_000.5, + daily_limit_usd: Some(10_000_000_001.0), + monthly_limit_usd: Some(10_000_000_000.5), ..Default::default() }; assert_eq!(remaining_micro_usd_read_only(&config, tmp.path()).unwrap(), 499_998); @@ -2283,7 +2307,7 @@ mod tests { fn budget_exceeded_daily_limit() { let tmp = TempDir::new().unwrap(); let config = CostConfig { - daily_limit_usd: 0.01, // Very low limit + daily_limit_usd: Some(0.01), // Very low limit ..Default::default() }; @@ -2433,12 +2457,12 @@ mod tests { fn older_configuration_lookup_cannot_restore_a_new_views_limits() { let tmp = TempDir::new().unwrap(); let older_config = CostConfig { - daily_limit_usd: 10.0, - monthly_limit_usd: 20.0, + daily_limit_usd: Some(10.0), + monthly_limit_usd: Some(20.0), ..enabled_config() }; let newer_config = CostConfig { - daily_limit_usd: 0.001, + daily_limit_usd: Some(0.001), ..older_config.clone() }; let older = CostTracker::for_workspace(older_config.clone(), tmp.path()).unwrap(); @@ -2474,8 +2498,8 @@ mod tests { fn canonical_settlement_is_process_owned_idempotent_and_budgeted() { let tmp = TempDir::new().unwrap(); let config = CostConfig { - daily_limit_usd: 0.001, - monthly_limit_usd: 1.0, + daily_limit_usd: Some(0.001), + monthly_limit_usd: Some(1.0), ..Default::default() }; let first = CostTracker::for_workspace(config.clone(), tmp.path()).unwrap(); @@ -2574,8 +2598,8 @@ mod tests { fn separate_tracker_instances_refresh_budget_and_summary_from_disk() { let tmp = TempDir::new().unwrap(); let config = CostConfig { - daily_limit_usd: 1.0, - monthly_limit_usd: 10.0, + daily_limit_usd: Some(1.0), + monthly_limit_usd: Some(10.0), ..Default::default() }; let writer = CostTracker::new(config.clone(), tmp.path()).unwrap(); diff --git a/src/cost/tracker/settlement/subscription_tests.rs b/src/cost/tracker/settlement/subscription_tests.rs index 540a7845d..d05410e7b 100644 --- a/src/cost/tracker/settlement/subscription_tests.rs +++ b/src/cost/tracker/settlement/subscription_tests.rs @@ -18,8 +18,8 @@ const ATTEMPT: &str = "prx_subscription_attempt"; fn config() -> CostConfig { CostConfig { - daily_limit_usd: 1.0, - monthly_limit_usd: 1.0, + daily_limit_usd: Some(1.0), + monthly_limit_usd: Some(1.0), ..CostConfig::default() } } diff --git a/src/cost/tracker/settlement/tests.rs b/src/cost/tracker/settlement/tests.rs index ee0cecfb4..aa3a1dea8 100644 --- a/src/cost/tracker/settlement/tests.rs +++ b/src/cost/tracker/settlement/tests.rs @@ -13,8 +13,8 @@ use std::{fs, path::Path, sync::Arc}; fn config() -> CostConfig { CostConfig { - daily_limit_usd: 1.0, - monthly_limit_usd: 1.0, + daily_limit_usd: Some(1.0), + monthly_limit_usd: Some(1.0), ..CostConfig::default() } } diff --git a/src/doctor/implementation/section_2.rs b/src/doctor/implementation/section_2.rs index a6ca2f57d..4ca013e72 100644 --- a/src/doctor/implementation/section_2.rs +++ b/src/doctor/implementation/section_2.rs @@ -4,7 +4,7 @@ fn check_config_semantics(config: &Config, items: &mut Vec) { if !config.autonomy.acknowledge_unrestricted_profile && !config.autonomy.workspace_only && config.autonomy.forbidden_paths.is_empty() - && config.autonomy.max_cost_per_day_cents == u32::MAX + && config.autonomy.effective_max_cost_per_day_cents() == u32::MAX { items.push(DiagItem::warn( cat, diff --git a/src/doctor/tests/section_1.rs b/src/doctor/tests/section_1.rs index c0fd2f6ab..0a1d0a178 100644 --- a/src/doctor/tests/section_1.rs +++ b/src/doctor/tests/section_1.rs @@ -720,7 +720,7 @@ let mut config = Config::default(); config.autonomy.workspace_only = false; config.autonomy.forbidden_paths.clear(); - config.autonomy.max_cost_per_day_cents = u32::MAX; + config.autonomy.max_cost_per_day_cents = Some(u32::MAX); let mut items = Vec::new(); check_config_semantics(&config, &mut items); @@ -737,7 +737,7 @@ let mut config = Config::default(); config.autonomy.workspace_only = false; config.autonomy.forbidden_paths.clear(); - config.autonomy.max_cost_per_day_cents = u32::MAX; + config.autonomy.max_cost_per_day_cents = Some(u32::MAX); config.autonomy.acknowledge_unrestricted_profile = true; let mut items = Vec::new(); diff --git a/src/runtime/child_source/golden_effective_config.json b/src/runtime/child_source/golden_effective_config.json index 560f4f425..006c9829b 100644 --- a/src/runtime/child_source/golden_effective_config.json +++ b/src/runtime/child_source/golden_effective_config.json @@ -1 +1 @@ -{"a2a":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trust_domain":"prx.local","trusted_trust_domains":[]},"agent":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"messaging":{"inbound":true},"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2},"agents":{},"api_key":null,"api_url":null,"auth":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"},"autonomy":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":500,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true},"browser":{"allowed_domains":[],"computer_use":{"api_key":null}},"channels_config":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null},"chat":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2},"compliance":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}},"composio":{"api_key":null,"entity_id":"default"},"cost":{"allow_override":false,"daily_limit_usd":10.0,"monthly_limit_usd":100.0,"prices":{"alpha/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0},"zeta/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0}},"warn_at_percent":80},"cron":{"max_run_history":50},"decision_engine":{"backend":{"circuit_breaker":{"cooldown_secs":60,"failure_threshold":5},"credential_ref":"","endpoint":"","kind":"auto","max_request_bytes":65536,"max_response_bytes":262144,"model":"","pinned_snapshot":"","remote_enabled":false,"timeout_ms":250},"candidates":5,"enabled":false,"latency_budget_ms":500,"max_candidates":12,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"token_ratio_limit":0.3499999940395355},"default_model":"anthropic/claude-sonnet-5","default_provider":"openrouter","default_temperature":0.7,"embedding_routes":[],"gateway":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60},"heartbeat":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."},"http_request":{"max_response_size":1000000,"timeout_secs":30},"identity":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"},"identity_bindings":[],"mcp":{"servers":{}},"mcp_server":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true},"media":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"},"memory":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7},"model_routes":[],"model_settings":{},"multimodal":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4},"nodes":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}},"observability":{"backend":"none","otel_endpoint":null,"otel_service_name":null},"plugins":{"enabled":false},"providers":{"ollama":{"num_ctx":null}},"proxy":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]},"query_classification":{"rules":[]},"reliability":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2},"router":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]},"runtime":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null},"scheduler":{"claim_lease_secs":90,"max_tasks":64},"secrets":{"encrypt":true},"security":{"audit":{"log_path":"audit.log","max_size_mb":100}},"self_system":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24},"sessions_spawn":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null},"skill_rag":{"top_k":32},"skills":{"open_skills_dir":null,"openclaw_skills_dir":null},"skills_lifecycle":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]},"smart_group":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5},"storage":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}},"task_routing":{"default_intent":"simple","rules":[]},"tool_tiering":{"always_exclude":[],"always_include":[],"channel_exclude":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","skills_manage","memory_reindex","document_sync","document_ingest"]},"tunnel":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null},"user_policies":[],"web_search":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15},"webhook":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null},"xin":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}} \ No newline at end of file +{"a2a":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trust_domain":"prx.local","trusted_trust_domains":[]},"agent":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"messaging":{"inbound":true},"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2},"agents":{},"api_key":null,"api_url":null,"auth":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"},"autonomy":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true},"browser":{"allowed_domains":[],"computer_use":{"api_key":null}},"channels_config":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null},"chat":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2},"compliance":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}},"composio":{"api_key":null,"entity_id":"default"},"cost":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{"alpha/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0},"zeta/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0}},"warn_at_percent":80},"cron":{"max_run_history":50},"decision_engine":{"backend":{"circuit_breaker":{"cooldown_secs":60,"failure_threshold":5},"credential_ref":"","endpoint":"","kind":"auto","max_request_bytes":65536,"max_response_bytes":262144,"model":"","pinned_snapshot":"","remote_enabled":false,"timeout_ms":250},"candidates":5,"enabled":false,"latency_budget_ms":500,"max_candidates":12,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"token_ratio_limit":0.3499999940395355},"default_model":"anthropic/claude-sonnet-5","default_provider":"openrouter","default_temperature":0.7,"embedding_routes":[],"gateway":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60},"heartbeat":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."},"http_request":{"max_response_size":1000000,"timeout_secs":30},"identity":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"},"identity_bindings":[],"mcp":{"servers":{}},"mcp_server":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true},"media":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"},"memory":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7},"model_routes":[],"model_settings":{},"multimodal":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4},"nodes":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}},"observability":{"backend":"none","otel_endpoint":null,"otel_service_name":null},"plugins":{"enabled":false},"providers":{"ollama":{"num_ctx":null}},"proxy":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]},"query_classification":{"rules":[]},"reliability":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2},"router":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]},"runtime":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null},"scheduler":{"claim_lease_secs":90,"max_tasks":64},"secrets":{"encrypt":true},"security":{"audit":{"log_path":"audit.log","max_size_mb":100}},"self_system":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24},"sessions_spawn":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null},"skill_rag":{"top_k":32},"skills":{"open_skills_dir":null,"openclaw_skills_dir":null},"skills_lifecycle":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]},"smart_group":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5},"storage":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}},"task_routing":{"default_intent":"simple","rules":[]},"tool_tiering":{"always_exclude":[],"always_include":[],"channel_exclude":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","skills_manage","memory_reindex","document_sync","document_ingest"]},"tunnel":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null},"user_policies":[],"web_search":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15},"webhook":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null},"xin":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}} \ No newline at end of file diff --git a/src/runtime/decision_accounting.rs b/src/runtime/decision_accounting.rs index ae34ce804..8de47466a 100644 --- a/src/runtime/decision_accounting.rs +++ b/src/runtime/decision_accounting.rs @@ -546,7 +546,7 @@ impl AccountingScope { binding_sha256: hex::encode(binding), maximum_micro_usd: maximum, turn_limit_micro_usd: budgets.micro_usd, - security_daily_micro_usd: u64::from(config.autonomy.max_cost_per_day_cents) * 10_000, + security_daily_micro_usd: u64::from(config.autonomy.effective_max_cost_per_day_cents()) * 10_000, }, reserved_tokens: tokens, turn_token_limit: budgets.tokens, diff --git a/src/runtime/lesson_delivery/tests/physical_owner.rs b/src/runtime/lesson_delivery/tests/physical_owner.rs index eb0bd1635..4af3ea09b 100644 --- a/src/runtime/lesson_delivery/tests/physical_owner.rs +++ b/src/runtime/lesson_delivery/tests/physical_owner.rs @@ -128,7 +128,7 @@ async fn wrong_actual_owner_refuses_before_wire_with_real_spent_liability_and_ta ..Config::default() }; config.auth.codex_auth_json_auto_import = false; - config.autonomy.max_cost_per_day_cents = 1000; + config.autonomy.max_cost_per_day_cents = Some(1000); config.cost.prices.insert( format!("{PROVIDER}/{PROBE_MODEL}"), crate::config::schema::ModelPricing { diff --git a/src/runtime/mode.rs b/src/runtime/mode.rs index ce800d062..da2078655 100644 --- a/src/runtime/mode.rs +++ b/src/runtime/mode.rs @@ -500,10 +500,10 @@ pub async fn dispatch(command: Commands, config: Config) -> Result<()> { println!("Security:"); println!(" Autonomy level: {:?}", config.autonomy.level); println!(" Workspace only: {}", config.autonomy.workspace_only); - println!( - " Max cost/day: ${:.2}", - f64::from(config.autonomy.max_cost_per_day_cents) / 100.0 - ); + match config.autonomy.max_cost_per_day_cents { + Some(cents) => println!(" Max cost/day: ${:.2}", f64::from(cents) / 100.0), + None => println!(" Max cost/day: no limit set"), + } println!(" Audit logging: enabled"); println!(" Audit log path: {}", config.security.audit.log_path); println!(); diff --git a/src/runtime/turn_context/tests/publication_scope.rs b/src/runtime/turn_context/tests/publication_scope.rs index 89cba8953..ab2864514 100644 --- a/src/runtime/turn_context/tests/publication_scope.rs +++ b/src/runtime/turn_context/tests/publication_scope.rs @@ -14,9 +14,9 @@ async fn agent_budget_uses_pinned_route_and_read_only_spend_snapshot() { config.agent.compaction.max_context_tokens = 32_768; config.agent.compaction.max_context_tokens_explicit = true; config.agent.compaction.reserve_tokens = 4_096; - config.cost.daily_limit_usd = 100.0; - config.cost.monthly_limit_usd = 100.0; - config.autonomy.max_cost_per_day_cents = 1_000; + config.cost.daily_limit_usd = Some(100.0); + config.cost.monthly_limit_usd = Some(100.0); + config.autonomy.max_cost_per_day_cents = Some(1_000); let tracker = crate::cost::tracker::CostTracker::new(config.cost.clone(), workspace.path()).expect("test cost ledger"); tracker diff --git a/src/runtime/turn_publication/service.rs b/src/runtime/turn_publication/service.rs index 9e04f6681..7521e61da 100644 --- a/src/runtime/turn_publication/service.rs +++ b/src/runtime/turn_publication/service.rs @@ -251,8 +251,8 @@ pub(in crate::runtime) fn pinned_policy_version( &config.tool_tiering.channel_exclude, ), ( - config.cost.daily_limit_usd.to_bits(), - config.cost.monthly_limit_usd.to_bits(), + config.cost.daily_limit_usd.map(f64::to_bits), + config.cost.monthly_limit_usd.map(f64::to_bits), config.cost.warn_at_percent, config.cost.allow_override, prices, diff --git a/src/runtime/turn_publication/service/tests.rs b/src/runtime/turn_publication/service/tests.rs index a263640b6..b7b9ea2f3 100644 --- a/src/runtime/turn_publication/service/tests.rs +++ b/src/runtime/turn_publication/service/tests.rs @@ -32,12 +32,12 @@ fn pinned_policy_version_is_order_independent_and_tracks_policy_changes() { ); assert!(stable.starts_with("cdp-policy-v1:")); assert!(!stable.contains("provider/a")); - second.cost.daily_limit_usd += 1.0; + second.cost.daily_limit_usd = Some(1.0); assert_ne!( stable, pinned_policy_version(&second, &security, &surface, &key).unwrap() ); - second.cost.daily_limit_usd -= 1.0; + second.cost.daily_limit_usd = None; second.cost.prices.get_mut("provider/a").unwrap().cache_read += 0.25; assert_ne!( stable, diff --git a/src/security/policy.rs b/src/security/policy.rs index 61754f568..6f3ba1066 100644 --- a/src/security/policy.rs +++ b/src/security/policy.rs @@ -1546,7 +1546,7 @@ impl SecurityPolicy { workspace_dir: workspace_dir.to_path_buf(), workspace_only: autonomy_config.workspace_only, forbidden_paths: autonomy_config.forbidden_paths.clone(), - max_cost_per_day_cents: autonomy_config.max_cost_per_day_cents, + max_cost_per_day_cents: autonomy_config.effective_max_cost_per_day_cents(), scope_rules: autonomy_config.scopes.rules.clone(), scope_default_allow: autonomy_config.scopes.default.allows_unmatched(), assign_owners: autonomy_config.scopes.assign_owners.clone(), @@ -4121,7 +4121,7 @@ mod tests { level: AutonomyLevel::Full, workspace_only: false, forbidden_paths: vec!["/secret".into()], - max_cost_per_day_cents: 1000, + max_cost_per_day_cents: Some(1000), ..crate::config::AutonomyConfig::default() }; let workspace = PathBuf::from("/tmp/test-workspace"); @@ -4147,7 +4147,7 @@ mod tests { assert!(!p.forbidden_paths.is_empty(), "expected a non-empty value"); assert_eq!(p.workspace_only, autonomy.workspace_only); assert_eq!(p.forbidden_paths, autonomy.forbidden_paths); - assert_eq!(p.max_cost_per_day_cents, autonomy.max_cost_per_day_cents); + assert_eq!(p.max_cost_per_day_cents, autonomy.effective_max_cost_per_day_cents()); } // ── Edge cases: command injection ──────────────────────── diff --git a/src/skills/lifecycle/service/experiments/pins.rs b/src/skills/lifecycle/service/experiments/pins.rs index 0376451b2..c75024392 100644 --- a/src/skills/lifecycle/service/experiments/pins.rs +++ b/src/skills/lifecycle/service/experiments/pins.rs @@ -138,7 +138,7 @@ mod tests { let restored: Config = serde_json::from_slice(&serde_json::to_vec(&config)?)?; assert_eq!(canonical_config(&restored)?, expected); } - config.cost.daily_limit_usd += 1.0; + config.cost.daily_limit_usd = Some(1.0); assert_ne!(canonical_config(&config)?, expected); Ok(()) } diff --git a/src/skills/lifecycle/tests/evaluate_agent.rs b/src/skills/lifecycle/tests/evaluate_agent.rs index 5d913910c..bc8a7c9ee 100644 --- a/src/skills/lifecycle/tests/evaluate_agent.rs +++ b/src/skills/lifecycle/tests/evaluate_agent.rs @@ -722,7 +722,7 @@ async fn a_run_is_refused_when_the_operators_cost_limit_is_already_exceeded() { activate(&store, &skill(), &a, 0, true); let mut config = template(tmp.path(), &loopback); - config.cost.daily_limit_usd = 0.5; + config.cost.daily_limit_usd = Some(0.5); let operator = tmp.path().join("operator-ws"); std::fs::create_dir_all(&operator).expect("test: operator ws"); // The operator already spent past the daily limit through the real ledger. diff --git a/src/skills/lifecycle/tests/propose/experiments.rs b/src/skills/lifecycle/tests/propose/experiments.rs index 2ec1bb8f4..c9a5e1d56 100644 --- a/src/skills/lifecycle/tests/propose/experiments.rs +++ b/src/skills/lifecycle/tests/propose/experiments.rs @@ -725,7 +725,7 @@ async fn experiment_changed_operation_or_configuration_refuses_before_model_send .len(), 0 ); - config.cost.daily_limit_usd += 1.0; + config.cost.daily_limit_usd = Some(1.0); assert!( run_stage(&service, &config, &plan, "proposal", &inputs["proposal"]) .await diff --git a/src/tools/sessions_spawn/tests/mod.rs b/src/tools/sessions_spawn/tests/mod.rs index 6e2fa34cc..d0e2894f7 100644 --- a/src/tools/sessions_spawn/tests/mod.rs +++ b/src/tools/sessions_spawn/tests/mod.rs @@ -802,7 +802,7 @@ async fn execute_admitted_spawn_with_plane( .autonomy .forbidden_paths .clone_from(&tool.security.forbidden_paths); - config.autonomy.max_cost_per_day_cents = tool.security.max_cost_per_day_cents; + config.autonomy.max_cost_per_day_cents = Some(tool.security.max_cost_per_day_cents); config.autonomy.scopes.rules.clone_from(&tool.security.scope_rules); config.autonomy.scopes.default = if tool.security.scope_default_allow { crate::config::ScopeDefault::Allow diff --git a/src/tools/sessions_spawn/tests/recursive.rs b/src/tools/sessions_spawn/tests/recursive.rs index e53d7393f..f7c7032db 100644 --- a/src/tools/sessions_spawn/tests/recursive.rs +++ b/src/tools/sessions_spawn/tests/recursive.rs @@ -259,7 +259,7 @@ async fn build_fixture( config.reliability.provider_retries = 0; config.autonomy.level = options.level; if let Some(cap) = options.daily_cap_cents { - config.autonomy.max_cost_per_day_cents = cap; + config.autonomy.max_cost_per_day_cents = Some(cap); } for model in ["prx-local-model", FREE_MODEL] { config.providers.models.push( diff --git a/tests/fixtures/config-schema.json b/tests/fixtures/config-schema.json index df17245bc..03dedcf77 100644 --- a/tests/fixtures/config-schema.json +++ b/tests/fixtures/config-schema.json @@ -1 +1 @@ -{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Config","description":"Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).","type":"object","properties":{"a2a":{"description":"Agent-to-Agent compatibility configuration (`[a2a]`).","$ref":"#/$defs/A2aConfig","default":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trusted_trust_domains":[],"trust_domain":"prx.local"}},"agent":{"description":"Agent orchestration settings (`[agent]`).","$ref":"#/$defs/AgentConfig","default":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2,"messaging":{"inbound":true}}},"agents":{"description":"Delegate agent configurations for multi-agent workflows.","type":"object","additionalProperties":{"$ref":"#/$defs/DelegateAgentConfig"},"default":{}},"api_key":{"description":"API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.","type":["string","null"],"default":null},"api_url":{"description":"Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)","type":["string","null"],"default":null},"auth":{"description":"Auth profile and external credential import settings (`[auth]`).","$ref":"#/$defs/AuthConfig","default":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"}},"autonomy":{"description":"Autonomy and security policy configuration (`[autonomy]`).","$ref":"#/$defs/AutonomyConfig","default":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":500,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true}},"browser":{"description":"Browser automation configuration (`[browser]`).","$ref":"#/$defs/BrowserConfig","default":{"allowed_domains":[],"computer_use":{"api_key":null}}},"channels_config":{"description":"Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).","$ref":"#/$defs/ChannelsConfig","default":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null}},"chat":{"description":"Interactive chat UI configuration (`[chat]`).","$ref":"#/$defs/ChatConfig","default":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2}},"compliance":{"description":"Operator-owned compliance controls (`[compliance]`).","$ref":"#/$defs/ComplianceConfig","default":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}},"composio":{"description":"Composio managed OAuth tools integration (`[composio]`).","$ref":"#/$defs/ComposioConfig","default":{"api_key":null,"entity_id":"default"}},"cost":{"description":"Cost tracking and budget enforcement configuration (`[cost]`).","$ref":"#/$defs/CostConfig","default":{"allow_override":false,"daily_limit_usd":10.0,"monthly_limit_usd":100.0,"prices":{},"warn_at_percent":80}},"cron":{"description":"Cron job configuration (`[cron]`).","$ref":"#/$defs/CronConfig","default":{"max_run_history":50}},"decision_engine":{"description":"Optional advisory decision engine, disabled by default.","$ref":"#/$defs/DecisionEngineConfig","default":{"candidates":5,"enabled":false,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"latency_budget_ms":500,"max_candidates":12,"token_ratio_limit":0.3499999940395355}},"default_model":{"description":"Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.","type":["string","null"]},"default_provider":{"description":"Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.","type":["string","null"]},"default_temperature":{"description":"Default model temperature (0.0–2.0). Default: `0.7`.","type":"number","format":"double","default":0.7},"embedding_routes":{"description":"Embedding routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/EmbeddingRouteConfig"}},"gateway":{"description":"Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).","$ref":"#/$defs/GatewayConfig","default":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60}},"heartbeat":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]`).","$ref":"#/$defs/HeartbeatConfig","default":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."}},"http_request":{"description":"HTTP request tool configuration (`[http_request]`).","$ref":"#/$defs/HttpRequestConfig","default":{"max_response_size":1000000,"timeout_secs":30}},"identity":{"description":"Identity format configuration: OpenClaw or AIEOS (`[identity]`).","$ref":"#/$defs/IdentityConfig","default":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"}},"identity_bindings":{"description":"Static identity bindings loaded at startup (`[[identity_bindings]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/IdentityBindingConfig"}},"mcp":{"description":"Secrets encryption configuration (`[secrets]`).","$ref":"#/$defs/McpConfig","default":{"servers":{}}},"mcp_server":{"description":"MCP server compatibility configuration (`[mcp_server]`).","$ref":"#/$defs/McpServerRuntimeConfig","default":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true}},"media":{"description":"Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.","$ref":"#/$defs/MediaConfig","default":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"}},"memory":{"description":"Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).","$ref":"#/$defs/MemoryConfig","default":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7}},"model_routes":{"description":"Model routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/ModelRouteConfig"}},"model_settings":{"description":"Catalog model levels and explicit parameters, keyed by canonical release ID.","type":"object","additionalProperties":{"$ref":"#/$defs/ModelSettings"},"default":{}},"multimodal":{"description":"Multimodal (image) handling configuration (`[multimodal]`).","$ref":"#/$defs/MultimodalConfig","default":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4}},"nodes":{"description":"Remote node proxy configuration (`[nodes]`).","$ref":"#/$defs/NodesConfig","default":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}},"observability":{"description":"Observability backend configuration (`[observability]`).","$ref":"#/$defs/ObservabilityConfig","default":{"backend":"none","otel_endpoint":null,"otel_service_name":null}},"plugins":{"description":"WASM plugin runtime switch (`[plugins]`), off by default.","$ref":"#/$defs/PluginsConfig","default":{"enabled":false}},"providers":{"description":"Provider-specific runtime options (`[providers.]`).","$ref":"#/$defs/ProvidersConfig","default":{"ollama":{"num_ctx":null}}},"proxy":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).","$ref":"#/$defs/ProxyConfig","default":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]}},"query_classification":{"description":"Automatic query classification — maps user messages to model hints.","$ref":"#/$defs/QueryClassificationConfig","default":{"rules":[]}},"reliability":{"description":"Reliability settings: retries, fallback providers, backoff (`[reliability]`).","$ref":"#/$defs/ReliabilityConfig","default":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2}},"router":{"description":"Heuristic LLM router configuration (`[router]`).","$ref":"#/$defs/RouterConfig","default":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]}},"runtime":{"description":"Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.","$ref":"#/$defs/RuntimeConfig","default":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null}},"scheduler":{"description":"Scheduler configuration for periodic task execution (`[scheduler]`).","$ref":"#/$defs/SchedulerConfig","default":{"claim_lease_secs":90,"max_tasks":64}},"secrets":{"$ref":"#/$defs/SecretsConfig","default":{"encrypt":true}},"security":{"description":"Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).","$ref":"#/$defs/SecurityConfig","default":{"audit":{"log_path":"audit.log","max_size_mb":100}}},"self_system":{"description":"Self-system experimental automation controls (`[self_system]`).","$ref":"#/$defs/SelfSystemConfig","default":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24}},"sessions_spawn":{"description":"Session spawning configuration (`[sessions_spawn]`).","$ref":"#/$defs/SessionsSpawnConfig","default":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null}},"skill_rag":{"description":"Dynamic skill retrieval settings (`[skill_rag]`).","$ref":"#/$defs/SkillRagConfig","default":{"top_k":32}},"skills":{"description":"Skills loading and community repository behavior (`[skills]`).","$ref":"#/$defs/SkillsConfig","default":{"open_skills_dir":null,"openclaw_skills_dir":null}},"skills_lifecycle":{"description":"Skill lifecycle (`[skills_lifecycle]`), off by default.","$ref":"#/$defs/SkillsLifecycleConfig","default":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]}},"smart_group":{"description":"Smart group-reply pre-gate configuration (`[smart_group]`).","$ref":"#/$defs/SmartGroupConfig","default":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5}},"storage":{"description":"Persistent storage provider configuration (`[storage]`).","$ref":"#/$defs/StorageConfig","default":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"task_routing":{"description":"Task routing configuration — classifies work by intent before the main agent loop.","$ref":"#/$defs/TaskRoutingConfig","default":{"default_intent":"simple","rules":[]}},"tool_tiering":{"description":"Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).","$ref":"#/$defs/ToolTieringConfig","default":{"always_exclude":[],"always_include":[],"channel_exclude":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","skills_manage","memory_reindex","document_sync","document_ingest"]}},"tunnel":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]`).","$ref":"#/$defs/TunnelConfig","default":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null}},"user_policies":{"description":"Static user policy records loaded at startup (`[[user_policies]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/UserPolicyConfig"}},"web_search":{"description":"Web search tool configuration (`[web_search]`).","$ref":"#/$defs/WebSearchConfig","default":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15}},"webhook":{"description":"Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).","$ref":"#/$defs/MemoryWebhookConfig","default":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null}},"xin":{"description":"Xin autonomous task engine configuration (`[xin]`).","$ref":"#/$defs/XinConfig","default":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}}},"$defs":{"A2aConfig":{"type":"object","properties":{"agent_id":{"description":"Stable PRX agent identifier advertised to peers.","type":"string","default":"prx-default"},"allowed_peer_issuers":{"description":"Accepted external peer issuers.","type":"array","default":[],"items":{"type":"string"}},"bind":{"description":"Advertised bind address.","type":"string","default":"127.0.0.1:16832"},"card_jwks_uri":{"description":"Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.","type":["string","null"],"default":null},"card_signing_key_path":{"description":"On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).","type":["string","null"],"default":null},"card_ttl_seconds":{"description":"Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.","type":"integer","format":"uint64","default":3600,"minimum":0},"discovery_advertised":{"description":"Whether to advertise into an external A2A registry.","type":"boolean","default":false},"handoff_nonce_ttl_seconds":{"description":"Replay window for future handoff delegation tokens.","type":"integer","format":"uint64","default":3600,"minimum":0},"messaging_enabled":{"description":"Enable the dedicated pinned mTLS messaging listener.","type":"boolean","default":false},"peers":{"type":"object","additionalProperties":{"$ref":"#/$defs/A2aPeer"},"default":{}},"spiffe_id":{"description":"Local SPIFFE-style identifier placeholder.","type":"string","default":"spiffe://prx-local/agent/prx-default"},"spiffe_strict_validation":{"description":"When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.","type":"boolean","default":false},"spiffe_trust_bundle_pem":{"description":"Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).","type":["string","null"],"default":null},"trusted_trust_domains":{"description":"Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).","type":"array","default":[],"items":{"type":"string"}},"trust_domain":{"description":"SPIFFE trust domain for new instance identities.","type":"string","default":"prx.local"}}},"A2aPeer":{"description":"Explicit pinned identity and local recipient grant.","type":"object","properties":{"spiffe_id":{"type":"string"},"fingerprints":{"type":"array","items":{"type":"string"}},"address":{"type":"string"},"owner":{"type":"string"},"sessions":{"type":"array","default":["*"],"items":{"type":"string"}},"agents":{"type":"array","default":["*"],"items":{"type":"string"}}},"required":["spiffe_id","fingerprints","address","owner"],"additionalProperties":false},"AgentCompactionConfig":{"description":"Agent context compaction configuration (`[agent.compaction]`).","type":"object","properties":{"keep_recent_messages":{"description":"Number of recent non-system messages to keep after compaction.","type":"integer","format":"uint","default":12,"minimum":0},"max_context_tokens":{"description":"Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.","type":"integer","format":"uint","default":128000,"minimum":0},"memory_flush":{"description":"Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.","type":"boolean","default":true},"mode":{"description":"Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).","$ref":"#/$defs/AgentCompactionMode","default":"switch"},"os_paging":{"description":"Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.","$ref":"#/$defs/OsPagingConfig","default":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"}},"reserve_tokens":{"description":"Tokens reserved for the next model response.","type":"integer","format":"uint","default":4096,"minimum":0}}},"AgentCompactionMode":{"description":"Compaction mode for long conversation contexts.","oneOf":[{"description":"Disable proactive compaction.","type":"string","const":"off"},{"description":"Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.","type":"string","const":"switch"},{"description":"Conservative compaction that prefers summary replacement.","type":"string","const":"safeguard"},{"description":"Aggressive truncation mode for tighter contexts.","type":"string","const":"aggressive"}]},"AgentConfig":{"description":"Agent orchestration configuration (`[agent]` section).","type":"object","properties":{"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"compact_context":{"description":"When true: bootstrap_max_chars=6000. Use for 13B or smaller models.","type":"boolean","default":false},"compaction":{"description":"Context compaction controls (`[agent.compaction]`).","$ref":"#/$defs/AgentCompactionConfig","default":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096}},"low_priority_tools":{"description":"Tool names treated as low-priority when `priority_scheduling_enabled = true`.","type":"array","default":["sessions_spawn","delegate"],"items":{"type":"string"}},"priority_scheduling_enabled":{"description":"Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.","type":"boolean","default":false},"read_only_tool_concurrency_window":{"description":"Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.","type":"integer","format":"uint","default":2,"minimum":0},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}}},"AgentLimits":{"description":"Optional admission limits for rf-started turns of a named agent.","type":"object","properties":{"max_concurrent_turns":{"type":["integer","null"],"format":"uint32","minimum":0},"max_cost_per_day_cents":{"type":["integer","null"],"format":"uint64","minimum":0}},"additionalProperties":false},"AuditConfig":{"description":"Audit logging configuration","type":"object","properties":{"log_path":{"description":"Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).","type":"string","default":"audit.log"},"max_size_mb":{"description":"Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).","type":"integer","format":"uint32","default":100,"minimum":0}}},"AuthConfig":{"description":"Authentication and external credential import configuration (`[auth]` section).","type":"object","properties":{"codex_auth_json_auto_import":{"description":"Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.","type":"boolean","default":false},"codex_auth_json_path":{"description":"Source path for Codex CLI auth.json import.","type":"string","default":"~/.codex/auth.json"}}},"AutonomyConfig":{"type":"object","properties":{"acknowledge_unrestricted_profile":{"description":"Operator acknowledgement for an intentionally unrestricted profile.\nThis suppresses doctor noise only; it does not alter policy behavior.","type":"boolean","default":false},"forbidden_paths":{"description":"Explicit path denylist. Default includes system-critical paths.\n\nFails closed: omitting the key keeps the built-in list rather than\nemptying it, so a partial `[autonomy]` section never removes the\ndenylist.","type":"array","default":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"items":{"type":"string"}},"level":{"description":"Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).","$ref":"#/$defs/AutonomyLevel","default":"full"},"max_cost_per_day_cents":{"description":"Maximum cost per day in cents per policy. Default: `500`.","type":"integer","format":"uint32","default":500,"minimum":0},"scopes":{"description":"Scope-based tool access control: per-user/channel/chat-type allow/deny rules.","$ref":"#/$defs/ScopeConfig","default":{"assign_owners":[],"default":"allow","rules":[]}},"workspace_only":{"description":"Restrict file writes and command paths to the workspace directory. Default: `true`.\n\nFails closed: a `[autonomy]` section that omits this key keeps the\nworkspace restriction on, so a partial section can never widen the\nfilesystem reach by accident.","type":"boolean","default":true}}},"AutonomyLevel":{"description":"How much autonomy the agent has","oneOf":[{"description":"Read-only: can observe but not act","type":"string","const":"readonly"},{"description":"Supervised: acts but requires approval for risky operations","type":"string","const":"supervised"},{"description":"Full: autonomous execution within policy bounds","type":"string","const":"full"}]},"BackendSelection":{"description":"Which decision backend runs: `auto` (the factory's order) or one kind.","type":"string"},"BrowserComputerUseConfig":{"description":"Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.","type":"object","properties":{"api_key":{"description":"Optional bearer token (retained only for config secret handling).","type":["string","null"],"default":null}}},"BrowserConfig":{"description":"Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.","type":"object","properties":{"allowed_domains":{"description":"Allowed domains for `web_fetch` (exact or subdomain match).","type":"array","default":[],"items":{"type":"string"}},"computer_use":{"description":"Computer-use sidecar config (retained only for `api_key` secret handling).","$ref":"#/$defs/BrowserComputerUseConfig","default":{"api_key":null}}}},"ChannelsConfig":{"description":"Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.","type":"object","properties":{"cli":{"description":"Enable the CLI interactive channel. Default: `true`.","type":"boolean","default":true},"dingtalk":{"description":"DingTalk channel configuration.","anyOf":[{"$ref":"#/$defs/DingTalkConfig"},{"type":"null"}]},"discord":{"description":"Discord bot channel configuration.","anyOf":[{"$ref":"#/$defs/DiscordConfig"},{"type":"null"}]},"email":{"description":"Email channel configuration.","anyOf":[{"$ref":"#/$defs/EmailConfig"},{"type":"null"}]},"imessage":{"description":"iMessage channel configuration (macOS only).","anyOf":[{"$ref":"#/$defs/IMessageConfig"},{"type":"null"}]},"irc":{"description":"IRC channel configuration.","anyOf":[{"$ref":"#/$defs/IrcConfig"},{"type":"null"}]},"lark":{"description":"Lark/Feishu channel configuration.","anyOf":[{"$ref":"#/$defs/LarkConfig"},{"type":"null"}]},"linq":{"description":"Linq Partner API channel configuration.","anyOf":[{"$ref":"#/$defs/LinqConfig"},{"type":"null"}]},"mattermost":{"description":"Mattermost bot channel configuration.","anyOf":[{"$ref":"#/$defs/MattermostConfig"},{"type":"null"}]},"nextcloud_talk":{"description":"Nextcloud Talk bot channel configuration.","anyOf":[{"$ref":"#/$defs/NextcloudTalkConfig"},{"type":"null"}]},"qq":{"description":"QQ Official Bot channel configuration.","anyOf":[{"$ref":"#/$defs/QQConfig"},{"type":"null"}]},"ramflux":{"description":"Local ramflux agent-host bridge.","anyOf":[{"$ref":"#/$defs/RamfluxConfig"},{"type":"null"}],"default":null},"signal":{"description":"Signal channel configuration.","anyOf":[{"$ref":"#/$defs/SignalConfig"},{"type":"null"}]},"slack":{"description":"Slack bot channel configuration.","anyOf":[{"$ref":"#/$defs/SlackConfig"},{"type":"null"}]},"telegram":{"description":"Telegram bot channel configuration.","anyOf":[{"$ref":"#/$defs/TelegramConfig"},{"type":"null"}]},"wacli":{"description":"wacli JSON-RPC daemon channel configuration.","anyOf":[{"$ref":"#/$defs/WacliConfig"},{"type":"null"}],"default":null},"webhook":{"description":"Webhook channel configuration.","anyOf":[{"$ref":"#/$defs/WebhookConfig"},{"type":"null"}]},"whatsapp":{"description":"WhatsApp channel configuration (Cloud API or Web mode).","anyOf":[{"$ref":"#/$defs/WhatsAppConfig"},{"type":"null"}]}}},"ChatConfig":{"description":"Interactive chat configuration (`[chat]`).","type":"object","properties":{"daemon":{"description":"How this chat process reaches the daemon it borrows channels from.","$ref":"#/$defs/ChatDaemonConfig","default":{"token":"","url":""}},"max_concurrent_visible_turns":{"description":"Maximum concurrent visible provider turns in the TUI Redux driver.","type":"integer","format":"uint","default":2,"minimum":0}}},"ChatDaemonConfig":{"description":"Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.","type":"object","properties":{"token":{"description":"Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.","type":"string","default":""},"url":{"description":"Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.","type":"string","default":""}}},"CircuitBreakerConfig":{"description":"The per-backend circuit breaker.","type":"object","properties":{"cooldown_secs":{"description":"Seconds the breaker stays open (1 to 3600).","type":"integer","format":"uint32","default":60,"minimum":0},"failure_threshold":{"description":"Consecutive failures before the breaker opens (1 to 100).","type":"integer","format":"uint32","default":5,"minimum":0}}},"ClassificationRule":{"description":"A single classification rule mapping message patterns to a model hint.","type":"object","properties":{"hint":{"description":"Must match a `[[model_routes]]` hint value.","type":"string"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"max_length":{"description":"Only match if message length <= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"min_length":{"description":"Only match if message length >= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"patterns":{"description":"Case-sensitive literal matches (for \"```\", \"fn \", etc.).","type":"array","default":[],"items":{"type":"string"}},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0}},"required":["hint"]},"CloudflareTunnelConfig":{"type":"object","properties":{"token":{"description":"Cloudflare Tunnel token (from Zero Trust dashboard)","type":"string"}},"required":["token"]},"ComplianceConfig":{"type":"object","properties":{"eu_ai_act":{"$ref":"#/$defs/EuAiActComplianceConfig","default":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null}},"interaction_notice":{"$ref":"#/$defs/InteractionNoticeConfig","default":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}}},"ComposioConfig":{"description":"Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.","type":"object","properties":{"api_key":{"description":"Composio API key (stored encrypted when secrets.encrypt = true)","type":["string","null"],"default":null},"entity_id":{"description":"Default entity ID for multi-user setups","type":"string","default":"default"}}},"CostConfig":{"description":"Cost tracking and budget enforcement configuration (`[cost]` section).","type":"object","properties":{"allow_override":{"description":"Allow requests to exceed budget with --override flag (default: false)","type":"boolean","default":false},"daily_limit_usd":{"description":"Daily spending limit in USD (default: 10.00)","type":"number","format":"double","default":10.0},"monthly_limit_usd":{"description":"Monthly spending limit in USD (default: 100.00)","type":"number","format":"double","default":100.0},"prices":{"description":"Per-model pricing (USD per 1M tokens)","type":"object","additionalProperties":{"$ref":"#/$defs/ModelPricing"},"default":{}},"warn_at_percent":{"description":"Warn when spending reaches this percentage of limit (default: 80)","type":"integer","format":"uint8","default":80,"maximum":255,"minimum":0}}},"CredentialRefSetting":{"description":"Which credential a decision backend uses. A reference, never a secret.","type":"string"},"CronConfig":{"description":"Cron job configuration (`[cron]` section).","type":"object","properties":{"max_run_history":{"description":"Maximum number of historical cron run records to retain. Default: `50`.","type":"integer","format":"uint32","default":50,"minimum":0}}},"CustomTunnelConfig":{"type":"object","properties":{"health_url":{"description":"Optional URL to check tunnel health","type":["string","null"]},"start_command":{"description":"Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"","type":"string"},"url_pattern":{"description":"Optional regex to extract public URL from command stdout","type":["string","null"]}},"required":["start_command"]},"DecisionBackendConfig":{"description":"The decision backend (`[decision_engine.backend]`).","type":"object","properties":{"circuit_breaker":{"description":"The circuit breaker.","$ref":"#/$defs/CircuitBreakerConfig","default":{"cooldown_secs":60,"failure_threshold":5}},"credential_ref":{"description":"The credential reference: `\"\"`, `\"none\"` or `cred-`.","$ref":"#/$defs/CredentialRefSetting","default":""},"endpoint":{"description":"The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.","type":"string","default":""},"kind":{"description":"`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).","$ref":"#/$defs/BackendSelection","default":"auto"},"max_request_bytes":{"description":"Largest request body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":65536,"minimum":0},"max_response_bytes":{"description":"Largest response body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":262144,"minimum":0},"model":{"description":"The model the endpoint serves; one exact version for a hosted\nservice.","type":"string","default":""},"pinned_snapshot":{"description":"The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.","type":"string"},"remote_enabled":{"description":"Whether decision state may leave this machine. Default `false`.","type":"boolean","default":false},"timeout_ms":{"description":"Transport timeout (10 ms up to the extra latency budget).","type":"integer","format":"uint32","default":250,"minimum":0}}},"DecisionEngineConfig":{"type":"object","properties":{"backend":{"anyOf":[{"$ref":"#/$defs/DecisionBackendConfig"},{"type":"null"}]},"candidates":{"type":"integer","format":"uint32","default":5,"minimum":0},"enabled":{"type":"boolean","default":false},"mode":{"$ref":"#/$defs/DecisionMode","default":"pre"},"observe_queue":{"type":"integer","format":"uint32","default":64,"minimum":0},"prompt_budget_tokens":{"type":"integer","format":"uint32","default":300,"minimum":0},"telemetry_cap":{"type":"integer","format":"uint32","default":1000,"minimum":0},"timeout_ms":{"type":"integer","format":"uint32","default":1500,"minimum":0},"latency_budget_ms":{"description":"The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.","type":"integer","format":"uint64","default":500,"minimum":0},"token_ratio_limit":{"description":"Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).","type":"number","format":"float","default":0.3499999940395355},"max_candidates":{"description":"The most candidates a turn considers (1 to 32).","type":"integer","format":"uint8","default":12,"maximum":255,"minimum":0}}},"DecisionMode":{"type":"string","enum":["pre","post","both"]},"DeclarationOfConformityConfig":{"type":"object","properties":{"applicable_union_law":{"type":"array","default":[],"items":{"type":"string"}},"artifact_path":{"type":["string","null"],"default":null},"artifact_version":{"type":["string","null"],"default":null},"conformity_assessment_procedure":{"type":["string","null"],"default":null},"conformity_statement":{"type":["string","null"],"default":null},"harmonised_standards":{"type":"array","default":[],"items":{"type":"string"}},"issue_date":{"type":["string","null"],"default":null},"issue_place":{"type":["string","null"],"default":null},"notified_body_certificate":{"type":["string","null"],"default":null},"notified_body_identification_number":{"type":["string","null"],"default":null},"notified_body_name":{"type":["string","null"],"default":null},"personal_data_compliance_statement":{"type":["string","null"],"default":null},"processes_personal_data":{"type":"boolean","default":false},"provider_address":{"type":["string","null"],"default":null},"provider_name":{"type":["string","null"],"default":null},"signer_function":{"type":["string","null"],"default":null},"signer_name":{"type":["string","null"],"default":null},"signer_on_behalf_of":{"type":["string","null"],"default":null},"sole_responsibility_statement":{"type":["string","null"],"default":null},"standards_not_applicable_reason":{"type":["string","null"],"default":null},"system_name":{"type":["string","null"],"default":null},"system_reference":{"type":["string","null"],"default":null},"system_type":{"type":["string","null"],"default":null}}},"DelegateAgentConfig":{"description":"Configuration for a delegate sub-agent used by the `delegate` tool.","type":"object","properties":{"agentic":{"description":"Agentic sub-agent mode (multi-turn tool-call loop). Default true; an\nexplicit `false` makes the agent answer-only with no tools.","type":"boolean","default":true},"allowed_tools":{"description":"Allowlist of tool names available to the sub-agent in agentic mode.\nEmpty or omitted means all tools, the same as `[\"*\"]`.","type":"array","default":[],"items":{"type":"string"}},"api_key":{"description":"Optional API key override","type":["string","null"],"default":null},"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"autonomy":{"description":"The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.","anyOf":[{"$ref":"#/$defs/AutonomyLevel"},{"type":"null"}]},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"enabled":{"description":"Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.","type":"boolean","default":true},"identity_dir":{"description":"Optional identity files directory relative to workspace root.","type":["string","null"],"default":null},"limits":{"$ref":"#/$defs/AgentLimits","default":{"max_concurrent_turns":null,"max_cost_per_day_cents":null}},"max_depth":{"description":"Max recursion depth for nested delegation","type":"integer","format":"uint32","default":8,"minimum":0},"memory_scope":{"description":"Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".","type":["string","null"],"default":null},"model":{"description":"Model name","type":"string"},"provider":{"description":"Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")","type":"string"},"spawn_enabled":{"description":"Whether this agent is allowed to be targeted by sessions_spawn (default: true).","type":["boolean","null"],"default":null},"system_prompt":{"description":"Optional system prompt for the sub-agent","type":["string","null"],"default":null},"temperature":{"description":"Temperature override","type":["number","null"],"format":"double","default":null},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}},"required":["provider","model"]},"DingTalkConfig":{"description":"DingTalk configuration for Stream Mode messaging","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"client_id":{"description":"Client ID (AppKey) from DingTalk developer console","type":"string"},"client_secret":{"description":"Client Secret (AppSecret) from DingTalk developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["client_id","client_secret"]},"DiscordConfig":{"description":"Discord bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Discord user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Discord bot token (from Discord Developer Portal).","type":"string"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"guild_id":{"description":"Optional guild (server) ID to restrict the bot to a single guild.","type":["string","null"]},"listen_to_bots":{"description":"When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.","type":"boolean","default":false}},"required":["bot_token"]},"DmPolicy":{"description":"Policy for direct-message handling.","oneOf":[{"description":"Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).","type":"string","const":"pairing"},{"description":"Accept only senders listed in `allowed_from`.","type":"string","const":"allowlist"},{"description":"Accept any direct sender.","type":"string","const":"open"},{"description":"Ignore direct messages.","type":"string","const":"disabled"}]},"DockerRuntimeConfig":{"description":"Docker runtime configuration (`[runtime.docker]` section).","type":"object","properties":{"allowed_workspace_roots":{"description":"Optional workspace root allowlist for Docker mount validation.","type":"array","default":[],"items":{"type":"string"}},"cpu_limit":{"description":"Optional CPU limit (`None` = no explicit limit).","type":["number","null"],"format":"double","default":1.0},"image":{"description":"Runtime image used to execute shell commands.","type":"string","default":"alpine:3.20"},"memory_limit_mb":{"description":"Optional memory limit in MB (`None` = no explicit limit).","type":["integer","null"],"format":"uint64","default":512,"minimum":0},"mount_workspace":{"description":"Mount configured workspace into `/workspace`.","type":"boolean","default":true},"network":{"description":"Docker network mode (`none`, `bridge`, etc.).","type":"string","default":"none"},"read_only_rootfs":{"description":"Mount root filesystem as read-only.","type":"boolean","default":true}}},"EmailConfig":{"description":"Email channel configuration","type":"object","properties":{"allowed_senders":{"description":"Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)","type":"array","default":[],"items":{"type":"string"}},"from_address":{"description":"From address for outgoing emails","type":"string"},"idle_timeout_secs":{"description":"IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes","type":"integer","format":"uint64","default":1740,"minimum":0},"imap_folder":{"description":"IMAP folder to poll (default: INBOX)","type":"string","default":"INBOX"},"imap_host":{"description":"IMAP server hostname","type":"string"},"imap_port":{"description":"IMAP server port (default: 993 for TLS)","type":"integer","format":"uint16","default":993,"maximum":65535,"minimum":0},"password":{"description":"Email password for authentication","type":"string"},"smtp_host":{"description":"SMTP server hostname","type":"string"},"smtp_port":{"description":"SMTP server port (default: 465 for TLS)","type":"integer","format":"uint16","default":465,"maximum":65535,"minimum":0},"smtp_tls":{"description":"Use TLS for SMTP (default: true)","type":"boolean","default":true},"username":{"description":"Email username for authentication","type":"string"}},"required":["imap_host","smtp_host","username","password","from_address"]},"EmbeddingRouteConfig":{"description":"Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"dimensions":{"description":"Optional embedding dimension override for this route","type":["integer","null"],"format":"uint","default":null,"minimum":0},"hint":{"description":"Route hint name (e.g. \"semantic\", \"archive\", \"faq\")","type":"string"},"model":{"description":"Embedding model to use with that provider","type":"string"},"provider":{"description":"Embedding provider (`none`, `openai`, or `custom:`)","type":"string"}},"required":["hint","provider","model"]},"EuAiActClassificationConfig":{"type":"object","properties":{"assessed_at":{"type":["string","null"],"default":null},"owner":{"type":["string","null"],"default":null},"status":{"$ref":"#/$defs/EuAiActRiskClassification","default":"unclassified"}}},"EuAiActComplianceConfig":{"type":"object","properties":{"classification":{"$ref":"#/$defs/EuAiActClassificationConfig","default":{"assessed_at":null,"owner":null,"status":"unclassified"}},"declaration":{"$ref":"#/$defs/DeclarationOfConformityConfig","default":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null}},"incident_store_path":{"type":["string","null"],"default":null}}},"EuAiActRiskClassification":{"type":"string","enum":["unclassified","high_risk","not_high_risk"]},"FitnessConfig":{"description":"Calendar schedule, evidence thresholds, and retention for fitness v2.","type":"object","properties":{"auto_run":{"description":"Run the daily fitness worker in daemon mode.","type":"boolean","default":true},"max_backfill_days":{"description":"Maximum number of closed days recovered after downtime.","type":"integer","format":"uint32","default":7,"minimum":0},"min_coverage":{"description":"Minimum available metric weight required to publish a final score.","type":"number","format":"double","default":0.6},"min_samples":{"description":"Minimum samples required before an evidence-derived subscore is usable.","type":"integer","format":"uint","default":5,"minimum":0},"retention_days":{"description":"Number of daily JSON reports retained on disk.","type":"integer","format":"uint32","default":180,"minimum":0},"run_at":{"description":"Local wall-clock time (`HH:MM`) at which the previous day is scored.","type":"string","default":"00:10"},"timezone":{"description":"IANA timezone used to define closed calendar days.","type":"string","default":"UTC"}}},"GatewayConfig":{"description":"Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.","type":"object","properties":{"allow_public_bind":{"description":"Allow binding to non-localhost without a tunnel (default: false)","type":"boolean","default":false},"api_rate_limit_per_minute":{"description":"Max `/api/*` requests per minute per authenticated token.","type":"integer","format":"uint32","default":60,"minimum":0},"channel_webhook_dedup_ttl_secs":{"description":"How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.","type":"integer","format":"uint64","default":86400,"minimum":0},"host":{"description":"Gateway host (default: 127.0.0.1)","type":"string","default":"127.0.0.1"},"idempotency_max_keys":{"description":"Maximum distinct idempotency keys retained in memory.","type":"integer","format":"uint","default":10000,"minimum":0},"idempotency_ttl_secs":{"description":"TTL for webhook idempotency keys.","type":"integer","format":"uint64","default":300,"minimum":0},"pair_rate_limit_per_minute":{"description":"Max `/pair` requests per minute per client key.","type":"integer","format":"uint32","default":10,"minimum":0},"paired_tokens":{"description":"Paired bearer tokens (managed automatically, not user-edited)","type":"array","default":[],"items":{"type":"string"}},"port":{"description":"Gateway port (default: 16830)","type":"integer","format":"uint16","default":16830,"maximum":65535,"minimum":0},"rate_limit_max_keys":{"description":"Maximum distinct client keys tracked by gateway rate limiter maps.","type":"integer","format":"uint","default":10000,"minimum":0},"require_pairing":{"description":"Require pairing before accepting requests (default: true)","type":"boolean","default":true},"targeted_agents":{"description":"Switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). Default true. While false, any\notherwise-valid named target answers 409 `agent_disabled` and never\nruns as Main.","type":"boolean","default":true},"trust_forwarded_headers":{"description":"Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.","type":"boolean","default":false},"webhook_rate_limit_per_minute":{"description":"Max `/webhook` requests per minute per client key.","type":"integer","format":"uint32","default":60,"minimum":0}}},"GroupPolicy":{"description":"Policy for group-message handling.","oneOf":[{"description":"Accept only groups listed in `group_allow_from`.","type":"string","const":"allowlist"},{"description":"Accept any group.","type":"string","const":"open"},{"description":"Ignore group messages.","type":"string","const":"disabled"}]},"GroupReplyMode":{"description":"How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.","oneOf":[{"description":"Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).","type":"string","const":"off"},{"description":"Reply only when the bot is @-mentioned (legacy `mention_only = true`).","type":"string","const":"mention-only"},{"description":"Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).","type":"string","const":"smart"}]},"HeartbeatConfig":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]` section).","type":"object","properties":{"active_hours":{"description":"Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.","type":"array","default":[8,23],"items":{"type":"integer","format":"uint8","maximum":255,"minimum":0}},"interval_minutes":{"description":"Interval in minutes between heartbeat pings. Default: `30`.","type":"integer","format":"uint32","default":30,"minimum":0},"prompt":{"description":"Prompt used by heartbeat worker when dispatching tasks.","type":"string","default":"Check HEARTBEAT.md and follow instructions."}}},"HttpRequestConfig":{"description":"HTTP request tool configuration (`[http_request]` section).","type":"object","properties":{"max_response_size":{"description":"Maximum response size in bytes (default: 1MB)","type":"integer","format":"uint","default":1000000,"minimum":0},"timeout_secs":{"description":"Request timeout in seconds (default: 30)","type":"integer","format":"uint64","default":30,"minimum":0}}},"IMessageConfig":{"description":"iMessage channel configuration (macOS only).","type":"object","properties":{"allowed_contacts":{"description":"Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.","type":"array","items":{"type":"string"}},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["allowed_contacts"]},"IdentityBindingConfig":{"description":"Startup identity binding entry (`[[identity_bindings]]`).","type":"object","properties":{"channel":{"type":"string"},"channel_account":{"type":"string"},"display_name":{"type":["string","null"],"default":null},"user_id":{"type":"string"}},"required":["user_id","channel","channel_account"]},"IdentityConfig":{"description":"Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.","type":"object","properties":{"aieos_inline":{"description":"Inline AIEOS JSON (alternative to file path)","type":["string","null"],"default":null},"aieos_path":{"description":"Path to AIEOS JSON file (relative to workspace)","type":["string","null"],"default":null},"format":{"description":"Identity format: \"openclaw\" (default) or \"aieos\"","type":"string","default":"openclaw"}}},"InteractionNoticeApplicability":{"type":"string","enum":["required","not_applicable"]},"InteractionNoticeConfig":{"type":"object","properties":{"applicability":{"$ref":"#/$defs/InteractionNoticeApplicability","default":"required"},"exception_owner":{"type":["string","null"],"default":null},"exception_reviewed_at":{"type":["string","null"],"default":null},"text":{"type":"string","default":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers."},"version":{"type":"string","default":"1"}}},"IrcConfig":{"description":"IRC channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed nicknames (case-insensitive) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"channels":{"description":"Channels to join on connect","type":"array","default":[],"items":{"type":"string"}},"mention_only":{"description":"When true, only process channel/group messages that mention the bot.","type":"boolean","default":false},"nickname":{"description":"Bot nickname","type":"string"},"nickserv_password":{"description":"NickServ IDENTIFY password","type":["string","null"]},"port":{"description":"IRC server port (default: 6697 for TLS)","type":"integer","format":"uint16","default":6697,"maximum":65535,"minimum":0},"sasl_password":{"description":"SASL PLAIN password (IRCv3)","type":["string","null"]},"server":{"description":"IRC server hostname","type":"string"},"server_password":{"description":"Server password (for bouncers like ZNC)","type":["string","null"]},"username":{"description":"Username (defaults to nickname if not set)","type":["string","null"]},"verify_tls":{"description":"Verify TLS certificate (default: true)","type":["boolean","null"]}},"required":["server","nickname"]},"LarkConfig":{"description":"Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from Lark/Feishu developer console","type":"string"},"app_secret":{"description":"App Secret from Lark/Feishu developer console","type":"string"},"encrypt_key":{"description":"Encrypt key for webhook message decryption (optional)","type":["string","null"],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"port":{"description":"HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"receive_mode":{"description":"Event receive mode: \"websocket\" (default) or \"webhook\"","$ref":"#/$defs/LarkReceiveMode","default":"websocket"},"use_feishu":{"description":"Whether to use the Feishu (Chinese) endpoint instead of Lark (International)","type":"boolean","default":false},"verification_token":{"description":"Verification token for webhook validation (optional)","type":["string","null"],"default":null}},"required":["app_id","app_secret"]},"LarkReceiveMode":{"description":"How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.","type":"string","enum":["websocket","webhook"]},"LinqConfig":{"type":"object","properties":{"allowed_senders":{"description":"Allowed sender handles (phone numbers) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"api_token":{"description":"Linq Partner API token (Bearer auth)","type":"string"},"from_phone":{"description":"Phone number to send from (E.164 format)","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"signing_secret":{"description":"Webhook signing secret for signature verification","type":["string","null"],"default":null}},"required":["api_token","from_phone"]},"MattermostConfig":{"description":"Mattermost bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Mattermost user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Mattermost bot access token.","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.","type":["boolean","null"],"default":null},"thread_replies":{"description":"When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.","type":["boolean","null"],"default":null},"url":{"description":"Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).","type":"string"}},"required":["url","bot_token"]},"McpConfig":{"type":"object","properties":{"servers":{"description":"Named MCP server definitions","type":"object","additionalProperties":{"$ref":"#/$defs/McpServerConfig"},"default":{}},"workspace_servers":{"description":"Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.","$ref":"#/$defs/WorkspaceMcpServers"}}},"McpServerConfig":{"type":"object","properties":{"allow_tools":{"description":"Optional allow-list of exposed tools (empty = all)","type":"array","default":[],"items":{"type":"string"}},"args":{"description":"Command args for stdio mode","type":"array","default":[],"items":{"type":"string"}},"command":{"description":"Command for stdio mode","type":["string","null"],"default":null},"deny_tools":{"description":"Optional deny-list of exposed tools","type":"array","default":[],"items":{"type":"string"}},"env":{"description":"Environment variables for stdio mode","type":"object","additionalProperties":{"type":"string"},"default":{}},"request_timeout_ms":{"description":"Request timeout in milliseconds","type":"integer","format":"uint64","default":30000,"minimum":0},"startup_timeout_ms":{"description":"Startup timeout in milliseconds","type":"integer","format":"uint64","default":10000,"minimum":0},"tool_name_prefix":{"description":"Prefix used in tool naming and routing","type":"string","default":"mcp"},"transport":{"description":"Transport type: stdio or http","$ref":"#/$defs/McpTransport","default":"stdio"},"url":{"description":"URL for HTTP mode (streamable HTTP endpoint)","type":["string","null"],"default":null},"working_dir":{"description":"Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).","type":["string","null"]}}},"McpServerRuntimeConfig":{"type":"object","properties":{"allowed_origins":{"description":"Allowed browser origins for future streamable HTTP clients.","type":"array","default":["claude.ai","openai.com","localhost"],"items":{"type":"string"}},"bind":{"description":"Advertised bind address. The gateway may still be started with a CLI port override.","type":"string","default":"127.0.0.1:16831"},"exposed_tools":{"description":"Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.","type":"array","default":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"items":{"type":"string"}},"jwt_algorithms":{"description":"Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.","type":"array","default":["RS256"],"items":{"type":"string"}},"jwt_audience":{"description":"Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.","type":["string","null"],"default":null},"jwt_issuer":{"description":"Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.","type":["string","null"],"default":null},"jwt_jwks":{"description":"Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.","type":["string","null"],"default":null},"jwt_jwks_cache_ttl_secs":{"description":"Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.","type":"integer","format":"uint64","default":300,"minimum":0},"jwt_jwks_uri":{"description":"Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.","type":["string","null"],"default":null},"jwt_public_key_pem":{"description":"PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.","type":["string","null"],"default":null},"rate_limit_rps":{"description":"Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.","type":"integer","format":"uint32","default":10,"minimum":0},"require_auth":{"description":"Require an authenticated external identity for mutating calls.","type":"boolean","default":true}}},"McpTransport":{"type":"string","enum":["stdio","http"]},"MediaConfig":{"description":"Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.","type":"object","properties":{"audio_model":{"description":"Audio model name (Ollama model or OpenAI model). Default: \"whisper\".","type":"string","default":"whisper"},"audio_ollama_url":{"description":"Ollama base URL for audio transcription. Default: \"http://localhost:11434\".","type":"string","default":"http://localhost:11434"},"audio_provider":{"description":"Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".","type":"string","default":"none"},"max_audio_size_mb":{"description":"Maximum audio attachment size in MiB. Default: 20.","type":"integer","format":"uint","default":20,"minimum":0},"max_video_size_mb":{"description":"Maximum video attachment size in MiB. Default: 50.","type":"integer","format":"uint","default":50,"minimum":0},"video_max_frames":{"description":"Maximum video frames to extract per video. Default: 4.","type":"integer","format":"uint","default":4,"minimum":0},"video_provider":{"description":"Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".","type":"string","default":"none"}}},"MemoryConfig":{"description":"Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.","type":"object","properties":{"acl_enabled":{"description":"Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.","type":"boolean","default":false},"archive_after_days":{"description":"Archive daily/session files older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"auto_hydrate":{"description":"Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing","type":"boolean","default":true},"auto_save":{"description":"Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.","type":"boolean","default":true},"backend":{"description":"\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).","type":"string","default":"sqlite"},"conversation_retention_days":{"description":"For sqlite backend: prune conversation rows older than this many days","type":"integer","format":"uint32","default":3,"minimum":0},"daily_retention_days":{"description":"For sqlite backend: prune daily rows older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"embedding_cache_size":{"description":"Max embedding cache entries before LRU eviction","type":"integer","format":"uint","default":10000,"minimum":0},"embedding_dimensions":{"description":"Embedding vector dimensions","type":"integer","format":"uint","default":384,"minimum":0},"embedding_model":{"description":"Embedding model name (e.g. \"text-embedding-3-small\")","type":"string","default":"prx-local-hash-v1"},"embedding_provider":{"description":"Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"","type":"string","default":"local"},"events":{"description":"Raw/quasi-raw message event recording controls (`[memory.events]`).","$ref":"#/$defs/MemoryEventsConfig","default":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true}},"keyword_weight":{"description":"Weight for keyword BM25 in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.3},"legacy_conversation_turns_visible":{"description":"Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.","type":"boolean","default":true},"lucid_budget":{"description":"Token budget for lucid (replaces OPENPRX_LUCID_BUDGET)","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"lucid_cmd":{"description":"Path to lucid binary (replaces OPENPRX_LUCID_CMD)","type":["string","null"],"default":null},"lucid_failure_cooldown_ms":{"description":"Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)","type":"integer","format":"uint64","default":60000,"minimum":0},"lucid_local_hit_threshold":{"description":"Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)","type":"integer","format":"uint","default":3,"minimum":0},"lucid_recall_timeout_ms":{"description":"Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)","type":"integer","format":"uint64","default":5000,"minimum":0},"lucid_store_timeout_ms":{"description":"Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)","type":"integer","format":"uint64","default":3000,"minimum":0},"min_relevance_score":{"description":"Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4","type":"number","format":"double","default":0.4},"purge_after_days":{"description":"Purge archived files older than this many days","type":"integer","format":"uint32","default":30,"minimum":0},"semantic":{"description":"Semantic memory promotion controls (`[memory.semantic]`).","$ref":"#/$defs/MemorySemanticConfig","default":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30}},"sqlite_open_timeout_secs":{"description":"For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"sqlite_read_pool_size":{"description":"For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"vector_candidate_cap":{"description":"How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.","type":"integer","format":"uint","default":2000,"minimum":0},"vector_weight":{"description":"Weight for vector similarity in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.7}}},"MemoryEventsConfig":{"description":"Raw message event recording configuration (`[memory.events]`).","type":"object","properties":{"record_assistant_messages":{"description":"Record assistant replies.","type":"boolean","default":true},"record_tool_events":{"description":"Record tool/event payloads by default.","type":"boolean","default":false},"record_user_messages":{"description":"Record inbound/user messages.","type":"boolean","default":true}}},"MemorySemanticConfig":{"description":"Semantic memory promotion configuration (`[memory.semantic]`).","type":"object","properties":{"auto_promote_assistant_messages":{"description":"Auto-promote eligible assistant messages. Disabled by default to reduce noise.","type":"boolean","default":false},"auto_promote_user_messages":{"description":"Auto-promote eligible user messages into long-term semantic memories.","type":"boolean","default":true},"min_chars":{"description":"Minimum content length for semantic auto-promotion.","type":"integer","format":"uint","default":30,"minimum":0}}},"MemoryWebhookConfig":{"type":"object","properties":{"bind":{"description":"Socket address for the receiver (e.g. \"0.0.0.0:16899\").","type":"string","default":"0.0.0.0:16899"},"signing_secret":{"description":"Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.","type":["string","null"],"default":null},"token":{"description":"Required bearer token for incoming webhook events.","type":["string","null"],"default":null}}},"ModelOperationSetting":{"description":"The operations a `[[providers.models]]` entry may list.","type":"string","enum":["chat","embedding","decision_endpoint","rerank","image_generation","audio_generation","video_generation"]},"ModelPricing":{"description":"Per-model pricing entry (USD per 1M tokens).","type":"object","properties":{"cache_read":{"description":"Cache read input price per 1M tokens.","type":"number","format":"double","default":0.0},"cache_write":{"description":"Cache write/creation input price per 1M tokens.","type":"number","format":"double","default":0.0},"input":{"description":"Input price per 1M tokens","type":"number","format":"double","default":0.0},"output":{"description":"Output price per 1M tokens","type":"number","format":"double","default":0.0}}},"ModelRouteConfig":{"description":"Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"hint":{"description":"Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")","type":"string"},"level":{"type":["string","null"]},"model":{"description":"Model to use with that provider","type":"string"},"provider":{"description":"Provider to route to (must match a known provider name)","type":"string"},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true,"required":["hint","provider","model"]},"ModelSettings":{"description":"A model level plus explicit parameter overrides in `[model_settings.\"\"]`.","type":"object","properties":{"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"level":{"type":["string","null"]},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true},"MultimodalConfig":{"description":"Multimodal (image) handling configuration (`[multimodal]` section).","type":"object","properties":{"allow_remote_fetch":{"description":"Allow fetching remote image URLs (http/https). Disabled by default.","type":"boolean","default":false},"max_image_size_mb":{"description":"Maximum image payload size in MiB before base64 encoding.","type":"integer","format":"uint","default":5,"minimum":0},"max_images":{"description":"Maximum number of image attachments accepted per request.","type":"integer","format":"uint","default":4,"minimum":0}}},"NextcloudTalkConfig":{"description":"Nextcloud Talk bot configuration (webhook receive + OCS send API).","type":"object","properties":{"allowed_users":{"description":"Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Bot app token used for OCS API bearer auth.","type":"string"},"base_url":{"description":"Nextcloud base URL (e.g. \"https://cloud.example.com\").","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"webhook_secret":{"description":"Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).","type":["string","null"],"default":null}},"required":["base_url","app_token"]},"NgrokTunnelConfig":{"type":"object","properties":{"auth_token":{"description":"ngrok auth token","type":"string"},"domain":{"description":"Optional custom domain","type":["string","null"]}},"required":["auth_token"]},"NodeServerConfig":{"description":"Node daemon runtime config used by `prx-node`.","type":"object","properties":{"allowed_commands":{"description":"Command allowlist matched on first token.\n\nIn restricted mode this list is required unless explicitly set to `[\"*\"]`.","type":"array","default":["echo"],"items":{"type":"string"}},"bearer_token":{"description":"Required bearer token for /rpc.","type":"string","default":""},"blocked_commands":{"description":"Command denylist matched on first token. Always enforced.","type":"array","default":[],"items":{"type":"string"}},"exec_timeout_ms":{"description":"Default command timeout in milliseconds.","type":"integer","format":"uint64","default":15000,"minimum":0},"hmac_secret":{"description":"Optional HMAC signing secret.","type":["string","null"],"default":null},"listen_addr":{"description":"Listen address for node daemon.","type":"string","default":"127.0.0.1:8787"},"max_concurrent_tasks":{"description":"Maximum number of concurrent async command tasks.","type":"integer","format":"uint","default":8,"minimum":0},"max_output_bytes":{"description":"Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.","type":"integer","format":"uint","default":1048576,"minimum":0},"sandbox_root":{"description":"Sandbox root directory for read/write/cwd constraints.","type":"string","default":"."},"task_result_ttl_ms":{"description":"TTL for completed task results in milliseconds.","type":"integer","format":"uint64","default":3600000,"minimum":0},"tls_cert":{"description":"TLS certificate path (PEM).","type":["string","null"],"default":null},"tls_key":{"description":"TLS private key path (PEM).","type":["string","null"],"default":null},"tls_required":{"description":"Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.","type":"boolean","default":true}}},"NodesConfig":{"description":"Remote node proxy configuration for core-side RPC calls and node daemon defaults.","type":"object","properties":{"nodes":{"description":"Configured remote nodes.","type":"array","default":[],"items":{"$ref":"#/$defs/RemoteNodeConfig"}},"request_timeout_ms":{"description":"Default request timeout for node RPC calls.","type":"integer","format":"uint64","default":15000,"minimum":0},"retry_max":{"description":"Default max retries for node RPC calls.","type":"integer","format":"uint8","default":2,"maximum":255,"minimum":0},"server":{"description":"Embedded node server defaults used by `prx-node`.","$ref":"#/$defs/NodeServerConfig","default":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}}},"ObservabilityConfig":{"description":"Observability backend configuration (`[observability]` section).","type":"object","properties":{"backend":{"description":"\"none\" | \"log\" | \"prometheus\" | \"otel\"","type":"string","default":"none"},"otel_endpoint":{"description":"OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".","type":["string","null"],"default":null},"otel_service_name":{"description":"Service name reported to the OTel collector. Defaults to \"prx\".","type":["string","null"],"default":null}}},"OllamaProviderConfig":{"description":"Ollama-specific request options (`[providers.ollama]`).","type":"object","properties":{"num_ctx":{"description":"Explicit context window sent as Ollama `options.num_ctx`.","type":["integer","null"],"format":"uint","default":null,"minimum":0}}},"OsPagingConfig":{"description":"Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.","type":"object","properties":{"eviction_threshold":{"description":"Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.","type":"number","format":"double","default":0.7},"keep_recent_messages":{"description":"Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).","type":"integer","format":"uint","default":12,"minimum":0},"max_recalled_pages":{"description":"Maximum number of evicted pages (document chunks) recalled per turn.","type":"integer","format":"uint","default":10,"minimum":0},"proactive_retrieval":{"description":"Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.","type":"boolean","default":true},"retrieval_injection_role":{"description":"Role under which recalled pages are injected.","$ref":"#/$defs/RetrievalInjectionRole","default":"system"}}},"PluginsConfig":{"description":"WASM plugin runtime configuration.","type":"object","properties":{"enabled":{"description":"Load WASM plugins from `/plugins`. Default: `false`.","type":"boolean","default":false}},"additionalProperties":false},"ProviderModelConfig":{"description":"One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.","type":"object","properties":{"context_window":{"description":"The model's context window in tokens.","type":["integer","null"],"format":"uint32","minimum":0},"model":{"description":"The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.","type":["string","null"]},"native_tools":{"description":"Whether the model accepts native tool calls.","type":["boolean","null"]},"operations":{"description":"The complete list of operations the model executes; every operation not\nlisted is unsupported.","type":["array","null"],"items":{"$ref":"#/$defs/ModelOperationSetting"}},"provider":{"description":"The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.","type":"string"},"streaming":{"description":"Whether the model streams responses.","type":["boolean","null"]},"structured_output":{"description":"Whether the model honours a JSON-schema response format.","type":["boolean","null"]},"tool_call_dialect":{"description":"The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema_dialect":{"description":"The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]},"vision_input":{"description":"Whether the model accepts image input.","type":["boolean","null"]}},"required":["provider"]},"ProviderToolDialectConfig":{"description":"One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.","type":"object","properties":{"model":{"description":"The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.","type":["string","null"]},"provider":{"description":"The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.","type":"string"},"tool_call":{"description":"The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema":{"description":"The tool-schema dialect the endpoint accepts.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]}},"required":["provider"]},"ProvidersConfig":{"description":"Provider-specific runtime configuration (`[providers]`).","type":"object","properties":{"models":{"description":"Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.","type":"array","items":{"$ref":"#/$defs/ProviderModelConfig"}},"ollama":{"description":"Ollama-specific request options (`[providers.ollama]`).","$ref":"#/$defs/OllamaProviderConfig","default":{"num_ctx":null}},"tool_dialects":{"description":"Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).","type":"array","items":{"$ref":"#/$defs/ProviderToolDialectConfig"}}}},"ProxyConfig":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).","type":"object","properties":{"all_proxy":{"description":"Fallback proxy URL for all schemes.","type":["string","null"],"default":null},"http_proxy":{"description":"Proxy URL for HTTP requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"https_proxy":{"description":"Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"no_proxy":{"description":"No-proxy bypass list. Same format as NO_PROXY.","type":"array","default":[],"items":{"type":"string"}},"scope":{"description":"Proxy application scope.","$ref":"#/$defs/ProxyScope","default":"prx"},"services":{"description":"Service selectors used when scope = \"services\".","type":"array","default":[],"items":{"type":"string"}}}},"ProxyScope":{"description":"Proxy application scope — determines which outbound traffic uses the proxy.","oneOf":[{"description":"Use system environment proxy variables only.","type":"string","const":"environment"},{"description":"Apply proxy to all OpenPRX-managed HTTP traffic (default).","type":"string","const":"prx"},{"description":"Apply proxy only to explicitly listed service selectors.","type":"string","const":"services"}]},"QQConfig":{"description":"QQ Official Bot configuration (Tencent QQ Bot SDK)","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs. Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from QQ Bot developer console","type":"string"},"app_secret":{"description":"App Secret from QQ Bot developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["app_id","app_secret"]},"QueryClassificationConfig":{"description":"Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.","type":"object","properties":{"rules":{"description":"Classification rules evaluated in priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/ClassificationRule"}}}},"RamfluxAccountConfig":{"description":"Persona for one ramflux AI account. Missing fields fall back to the global agent.","type":"object","properties":{"cross_conversation_retrieval":{"description":"Cross-conversation memory retrieval. Off unless the owner sets it.","type":"boolean","default":false},"model":{"type":["string","null"],"default":null},"provider":{"type":["string","null"],"default":null},"scope_profile":{"type":["string","null"],"default":null},"system_prompt_file":{"description":"Path to a system-prompt file. Relative paths are resolved from the workspace.","type":["string","null"],"default":null}},"additionalProperties":false},"RamfluxAttachmentFetch":{"description":"Per-turn caps for `attachment.fetch`.","type":"object","properties":{"max_bytes":{"type":"integer","format":"uint64","default":5242880,"minimum":0},"max_per_turn":{"type":"integer","format":"uint8","default":4,"maximum":255,"minimum":0}},"additionalProperties":false},"RamfluxAuthorizationMode":{"description":"How prx combines its own setting with `bridge.hello.authorization`.","oneOf":[{"description":"Use the agent-host value. Until hello arrives, the effective mode is supervised.","type":"string","const":"follow_rf"},{"description":"Always supervised, even when the agent-host declares full.","type":"string","const":"supervised"},{"description":"Full only when the agent-host also declares full. Config alone never yields full.","type":"string","const":"full"}]},"RamfluxConfig":{"description":"Local ramflux agent-host bridge (`[channels_config.ramflux]`).","type":"object","properties":{"accounts":{"type":"object","additionalProperties":{"$ref":"#/$defs/RamfluxAccountConfig"},"default":{}},"allowed_block_types":{"type":"array","default":["Text","Markdown","Heading","KeyValue","Metric","List","TableFallback","Form","Input","Select","Progress","LogStream","Warning","Error","Success","Approval","ActionGroup","FilePreview","Fallback"],"items":{"type":"string"}},"attachment_fetch":{"$ref":"#/$defs/RamfluxAttachmentFetch","default":{"max_bytes":5242880,"max_per_turn":4}},"authorization_mode":{"$ref":"#/$defs/RamfluxAuthorizationMode","default":"follow_rf"},"encrypt_at_rest":{"type":"boolean","default":true},"max_in_flight_per_conversation":{"type":"integer","format":"uint8","default":1,"maximum":255,"minimum":0},"on_new_message":{"$ref":"#/$defs/RamfluxOnNewMessage","default":"queue"},"socket_path":{"description":"Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.","type":["string","null"],"default":null},"surface_limits":{"$ref":"#/$defs/RamfluxSurfaceLimits","default":{"max_actions":16,"max_blocks":32,"max_bytes":65536}},"turn_wall_clock_secs":{"description":"Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.","type":"integer","format":"uint64","default":120,"minimum":0}},"additionalProperties":false},"RamfluxOnNewMessage":{"description":"What to do with a new inbound message while a turn for that conversation is running.","type":"string","enum":["queue","interrupt"]},"RamfluxSurfaceLimits":{"description":"Limits for `reply.surface` blocks and actions.","type":"object","properties":{"max_actions":{"type":"integer","format":"uint32","default":16,"minimum":0},"max_blocks":{"type":"integer","format":"uint32","default":32,"minimum":0},"max_bytes":{"type":"integer","format":"uint32","default":65536,"minimum":0}},"additionalProperties":false},"ReliabilityCircuitBreakerConfig":{"description":"Process-local provider circuit policy (`[reliability.circuit_breaker]`).","type":"object","properties":{"enabled":{"description":"Enable protection for factory-built provider chains.","type":"boolean","default":true},"failure_threshold":{"description":"Consecutive transient failures that open a circuit (at least 1).","type":"integer","format":"uint32","default":5,"minimum":0},"max_open_secs":{"description":"Maximum doubled window, between open_secs and 3600 seconds.","type":"integer","format":"uint64","default":300,"minimum":0},"open_secs":{"description":"Initial open window in seconds (at least 1).","type":"integer","format":"uint64","default":30,"minimum":0}}},"ReliabilityConfig":{"description":"Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.","type":"object","properties":{"acknowledge_single_provider_risk":{"description":"Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.","type":"boolean","default":false},"api_keys":{"description":"Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.","type":"array","default":[],"items":{"type":"string"}},"channel_initial_backoff_secs":{"description":"Initial backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":2,"minimum":0},"channel_max_backoff_secs":{"description":"Max backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":60,"minimum":0},"circuit_breaker":{"description":"Per-provider consecutive failure protection.","$ref":"#/$defs/ReliabilityCircuitBreakerConfig","default":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30}},"fallback_providers":{"description":"Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).","type":"array","default":[],"items":{"type":"string"}},"model_fallbacks":{"description":"Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`","type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"default":{}},"provider_backoff_ms":{"description":"Base backoff (ms) for provider retry delay.","type":"integer","format":"uint64","default":500,"minimum":0},"provider_retries":{"description":"Retries per provider before failing over.","type":"integer","format":"uint32","default":2,"minimum":0},"scheduler_poll_secs":{"description":"Scheduler polling cadence in seconds.","type":"integer","format":"uint64","default":15,"minimum":0},"scheduler_retries":{"description":"Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.","type":"integer","format":"uint32","default":2,"minimum":0}}},"RemoteNodeConfig":{"description":"A remote node target for core-side node proxy calls.","type":"object","properties":{"bearer_token":{"description":"Bearer token for node RPC authentication.","type":"string"},"endpoint":{"description":"Base endpoint (e.g. \"http://127.0.0.1:8787\").","type":"string"},"hmac_secret":{"description":"Optional request signing key (HMAC-SHA256).","type":["string","null"],"default":null},"id":{"description":"Stable node ID used by the nodes tool.","type":"string"},"retry_max":{"description":"Optional per-node retry override.","type":["integer","null"],"format":"uint8","default":null,"maximum":255,"minimum":0},"timeout_ms":{"description":"Optional per-node timeout override.","type":["integer","null"],"format":"uint64","default":null,"minimum":0}},"required":["id","endpoint","bearer_token"]},"RetrievalInjectionRole":{"description":"Where recalled context pages are injected back into the request.","oneOf":[{"description":"Inject recalled pages as a leading `system` message (not user-visible).","type":"string","const":"system"},{"description":"Inject recalled pages as a leading `user` message.","type":"string","const":"user"}]},"RouterConfig":{"description":"Heuristic LLM router configuration (`[router]` section).","type":"object","properties":{"alpha":{"description":"Similarity score weight. Phase 1 keeps this at `0.0`.","type":"number","format":"float","default":0.0},"beta":{"description":"Capability score weight.","type":"number","format":"float","default":0.5},"delta":{"description":"Cost penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"epsilon":{"description":"Latency penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"gamma":{"description":"Elo score weight.","type":"number","format":"float","default":0.30000001192092896},"knn_k":{"description":"Number of nearest neighbors considered for voting. Default: `7`.","type":"integer","format":"uint","default":7,"minimum":0},"knn_min_records":{"description":"Minimum history records before KNN affects routing. Default: `10`.","type":"integer","format":"uint","default":10,"minimum":0},"models":{"description":"Candidate model registry.","type":"array","default":[],"items":{"$ref":"#/$defs/RouterModelConfig"}}}},"RouterModelConfig":{"description":"Static router metadata for one model candidate.","type":"object","properties":{"categories":{"description":"Capability categories such as `conversation`, `code`, or `analysis`.","type":"array","default":[],"items":{"type":"string"}},"cost_per_million_tokens":{"description":"USD cost per million tokens.","type":"number","format":"float","default":0.0},"elo_rating":{"description":"Initial Elo rating.","type":"number","format":"float","default":1000.0},"latency_ms":{"description":"Average latency in milliseconds.","type":"integer","format":"uint32","default":2000,"minimum":0},"max_context":{"description":"Maximum context window in tokens.","type":"integer","format":"uint","default":1000000,"minimum":0},"model_id":{"description":"Model identifier without provider prefix.","type":"string"},"provider":{"description":"Provider identifier.","type":"string"},"reserved_output_tokens":{"description":"Output tokens reserved for this model when planning input context.","type":["integer","null"],"format":"uint","minimum":0}},"required":["model_id","provider"]},"RuntimeConfig":{"description":"Runtime adapter configuration (`[runtime]` section).","type":"object","properties":{"codex_reasoning_effort":{"description":"Codex reasoning effort","type":["string","null"],"default":null},"codex_stream_idle_timeout_secs":{"description":"Codex stream idle timeout in seconds","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"docker":{"description":"Docker runtime settings (used when `kind = \"docker\"`).","$ref":"#/$defs/DockerRuntimeConfig","default":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true}},"idle_hang_secs":{"description":"Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"kind":{"description":"Runtime kind (`native` | `docker`).","type":"string","default":"native"},"long_task_warn_secs":{"description":"Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"managed_cgroup_root":{"description":"Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.","type":["string","null"],"default":null},"max_blocking_threads":{"description":"Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"reasoning_enabled":{"description":"Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported","type":["boolean","null"],"default":null},"shell_env_allowlist":{"description":"Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.","type":"array","default":[],"items":{"type":"string"}},"workdir":{"description":"Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.","type":["string","null"],"default":null}}},"SchedulerConfig":{"description":"Scheduler configuration for periodic task execution (`[scheduler]` section).","type":"object","properties":{"claim_lease_secs":{"description":"Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.","type":"integer","format":"uint64","default":90,"minimum":0},"max_tasks":{"description":"Maximum number of persisted scheduled tasks.","type":"integer","format":"uint","default":64,"minimum":0}}},"ScopeConfig":{"description":"Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```","type":"object","properties":{"assign_owners":{"description":"Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.","type":"array","default":[],"items":{"type":"string"}},"default":{"description":"Default action when no rule matches: \"allow\" (default) or \"deny\".","$ref":"#/$defs/ScopeDefault","default":"allow"},"rules":{"description":"Ordered list of scope rules evaluated top-to-bottom.","type":"array","default":[],"items":{"$ref":"#/$defs/ScopeRule"}}}},"ScopeDefault":{"description":"What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.","oneOf":[{"description":"Unmatched tool calls are allowed (the default).","type":"string","const":"allow"},{"description":"Unmatched tool calls are refused.","type":"string","const":"deny"}]},"ScopeRule":{"description":"A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.","type":"object","properties":{"assign_allow":{"description":"Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".","type":"array","default":[],"items":{"type":"string"}},"assign_deny":{"description":"Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.","type":"array","default":[],"items":{"type":"string"}},"channel":{"description":"Match by channel name: \"signal\", \"telegram\", \"discord\", etc.","type":["string","null"]},"chat_type":{"description":"Match by chat type: \"direct\", \"group\", or \"*\" for any type.","type":["string","null"]},"send_allow":{"description":"Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.","type":"array","default":[],"items":{"type":"string"}},"send_deny":{"description":"Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.","type":"array","default":[],"items":{"type":"string"}},"tools_allow":{"description":"Tool whitelist: only these tools are allowed (empty = all tools permitted).","type":"array","default":[],"items":{"type":"string"}},"tools_deny":{"description":"Tool blacklist: these tools are denied regardless of allow list.","type":"array","default":[],"items":{"type":"string"}},"user":{"description":"Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.","type":["string","null"]}}},"SecretsConfig":{"description":"Secrets encryption configuration (`[secrets]` section).","type":"object","properties":{"encrypt":{"description":"Enable encryption for API keys and tokens in config.toml","type":"boolean","default":true}}},"SecurityConfig":{"description":"Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.","type":"object","properties":{"audit":{"description":"Audit logging configuration","$ref":"#/$defs/AuditConfig","default":{"log_path":"audit.log","max_size_mb":100}},"workspace_hooks":{"description":"Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.","$ref":"#/$defs/WorkspaceHooks"}}},"SelfSystemConfig":{"description":"Self-system experimental automation config (`[self_system]`).","type":"object","properties":{"evolution_config_path":{"description":"Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG)","type":["string","null"],"default":null},"evolution_debug_raw":{"description":"Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW)","type":"boolean","default":false},"evolution_interval_hours":{"description":"Evolution scheduler interval in hours (daemon mode).","type":"integer","format":"uint32","default":24,"minimum":0},"evolution_judge_timeout_secs":{"description":"Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.","type":"integer","format":"uint64","default":180,"minimum":0},"evolution_model_max_micro_usd":{"description":"Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.","type":"integer","format":"uint64","default":0,"minimum":0},"evolution_model_max_tokens":{"description":"Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.","type":"integer","format":"uint64","default":16384,"minimum":0},"fitness":{"description":"Daily fitness snapshot policy.","$ref":"#/$defs/FitnessConfig","default":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"}},"fitness_interval_hours":{"description":"Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.","type":"integer","format":"uint64","default":24,"minimum":0}}},"SessionsSpawnConfig":{"description":"Sessions spawn configuration (`[sessions_spawn]` section).","type":"object","properties":{"cleanup_on_complete":{"description":"Remove worker workspace directory after process-mode completion.","type":"boolean","default":true},"default_mode":{"description":"Default execution mode for sessions_spawn (`task` or `process`).","type":"string","default":"task"},"process_memory_strategy":{"description":"Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.","type":"string","default":"shared_fabric"},"worker_workspace_root":{"description":"Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.","type":["string","null"],"default":null}}},"SignalConfig":{"type":"object","properties":{"account":{"description":"E.164 phone number of the signal-cli account (e.g. \"+1234567890\").","type":"string"},"allowed_from":{"description":"Allowed sender phone numbers (E.164) or \"*\" for all.","type":"array","default":[],"items":{"type":"string"}},"cli_path":{"description":"Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).","type":["string","null"],"default":null},"daemon_http_port":{"description":"Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"daemon_mode":{"description":"Deprecated: ignored. Accepted for backward compatibility with older config files.","type":["boolean","null"],"default":null},"data_dir":{"description":"signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_id":{"description":"Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group","type":["string","null"],"default":null},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"http_url":{"description":"Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.","type":"string","default":"http://localhost:8080"},"ignore_attachments":{"description":"Skip messages that are attachment-only (no text body).","type":"boolean","default":false},"ignore_stories":{"description":"Skip incoming story messages.","type":"boolean","default":false},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"mode":{"description":"Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.","type":["string","null"],"default":null},"startup_timeout_ms":{"description":"Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.","type":"integer","format":"uint64","default":30000,"minimum":0},"storm_protection":{"description":"Signal ingress storm protection controls.","$ref":"#/$defs/SignalStormProtectionConfig","default":{"abnormal_threshold":10,"abnormal_window_secs":60,"breaker_duration_secs":300,"dedupe_ttl_secs":60,"min_reply_interval_secs":2}}},"required":["account"]},"SignalStormProtectionConfig":{"type":"object","properties":{"abnormal_threshold":{"description":"Non-user event threshold within `abnormal_window_secs` before tripping the breaker.","type":"integer","format":"uint","default":10,"minimum":0},"abnormal_window_secs":{"description":"Sliding window in seconds for non-user event counting.","type":"integer","format":"uint64","default":60,"minimum":0},"breaker_duration_secs":{"description":"Circuit breaker duration in seconds after threshold is reached.","type":"integer","format":"uint64","default":300,"minimum":0},"dedupe_ttl_secs":{"description":"Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.","type":"integer","format":"uint64","default":60,"minimum":0},"min_reply_interval_secs":{"description":"Minimum interval in seconds between replies for the same `(channel + reply_target)`.","type":"integer","format":"uint64","default":2,"minimum":0}}},"SkillRagConfig":{"description":"Dynamic skill retrieval configuration (`[skill_rag]` section).","type":"object","properties":{"top_k":{"description":"How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).","type":"integer","format":"uint","default":32,"minimum":0}}},"SkillSuiteRegistration":{"description":"The frozen suite that governs one skill's proposals.","type":"object","properties":{"skill_id":{"description":"The skill the suite governs.","type":"string"},"suite_digest":{"description":"SHA-256 digest (64 lowercase hex digits) of the frozen suite.","type":"string"}},"additionalProperties":false,"required":["skill_id","suite_digest"]},"SkillsConfig":{"description":"Skills loading configuration (`[skills]` section).","type":"object","properties":{"open_skills_dir":{"description":"Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.","type":["string","null"],"default":null},"openclaw_skills_dir":{"description":"Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.","type":["string","null"],"default":null}}},"SkillsLifecycleConfig":{"description":"`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.","type":"object","properties":{"allow_executable_proposals":{"description":"Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.","type":"boolean","default":false},"enabled":{"description":"Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.","type":"boolean","default":false},"max_concurrent_evaluations":{"description":"Most evaluations running at once.","type":"integer","format":"uint32","default":1,"minimum":0},"max_edit_fraction":{"description":"Edit budget of a proposal as a fraction of the skill body, in (0, 1].","type":"number","format":"double","default":0.2},"max_edit_tokens":{"description":"Edit budget of a proposal, in tokens.","type":"integer","format":"uint64","default":300,"minimum":0},"max_proposals_per_cycle":{"description":"Most proposals one cycle may start.","type":"integer","format":"uint32","default":1,"minimum":0},"min_cases_floor":{"description":"Smallest `min_cases` a governing suite may declare. Below 3 is refused.","type":"integer","format":"uint32","default":3,"minimum":0},"mode":{"description":"`draft_only`, `shadow` or `auto`.","$ref":"#/$defs/SkillsLifecycleModeConfig","default":"draft_only"},"owner_scope":{"description":"The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.","type":["string","null"],"default":null},"require_holdout":{"description":"A governing suite must have a holdout split. `false` is refused.","type":"boolean","default":true},"storage_dir":{"description":"Store location under the workspace. Only the default is supported.","type":"string","default":"self/skill-lifecycle"},"suites":{"description":"The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.","type":"array","default":[],"items":{"$ref":"#/$defs/SkillSuiteRegistration"}}},"additionalProperties":false},"SkillsLifecycleModeConfig":{"description":"What the lifecycle may do. Mirrors `LifecycleMode`.","oneOf":[{"description":"Drafts and reviews only.","type":"string","const":"draft_only"},{"description":"Drafts plus evaluation and gating; never publishes.","type":"string","const":"shadow"},{"description":"Publishes an eligible proposal after every gate.","type":"string","const":"auto"}]},"SlackConfig":{"description":"Slack bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Slack user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Slack app-level token for Socket Mode (xapp-...).","type":["string","null"]},"bot_token":{"description":"Slack bot OAuth token (xoxb-...).","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["bot_token"]},"SmartGroupConfig":{"description":"Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).","type":"object","properties":{"classifier_max_context_messages":{"description":"How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.","type":"integer","format":"uint","default":3,"minimum":0},"classifier_model":{"description":"Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.","type":"string","default":""},"classifier_provider":{"description":"Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.","type":"string","default":""},"classifier_temperature":{"description":"Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).","type":"number","format":"double","default":0.0},"classifier_timeout_secs":{"description":"Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.","type":"integer","format":"uint64","default":5,"minimum":0}}},"StorageConfig":{"description":"Persistent storage configuration (`[storage]` section).","type":"object","properties":{"provider":{"description":"Storage provider settings (e.g. sqlite, postgres).","$ref":"#/$defs/StorageProviderSection","default":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}}},"StorageProviderConfig":{"description":"Storage provider backend configuration (e.g. postgres connection details).","type":"object","properties":{"connect_timeout_secs":{"description":"Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"db_url":{"description":"Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.","type":["string","null"],"default":null},"pool_max_size":{"description":"Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.","type":"integer","format":"uint","default":32,"minimum":0},"provider":{"description":"Storage engine key (e.g. \"postgres\", \"sqlite\").","type":"string","default":""},"schema":{"description":"Database schema for SQL backends.","type":"string","default":"public"},"table":{"description":"Table name for memory entries.","type":"string","default":"memories"}}},"StorageProviderSection":{"description":"Wrapper for the storage provider configuration section.","type":"object","properties":{"config":{"description":"Storage provider backend settings.","$ref":"#/$defs/StorageProviderConfig","default":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"StreamMode":{"description":"Streaming mode for channels that support progressive message updates.","oneOf":[{"description":"No streaming -- send the complete response as a single message (default).","type":"string","const":"off"},{"description":"Update a draft message with every flush interval.","type":"string","const":"partial"}]},"TailscaleTunnelConfig":{"type":"object","properties":{"funnel":{"description":"Use Tailscale Funnel (public internet) vs Serve (tailnet only)","type":"boolean","default":false},"hostname":{"description":"Optional hostname override","type":["string","null"]}}},"TaskRoutingConfig":{"description":"Lightweight pre-LLM task routing.","type":"object","properties":{"default_intent":{"description":"Fallback intent when no rule matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"rules":{"description":"Rules evaluated in descending priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/TaskRoutingRule"}}}},"TaskRoutingIntentConfig":{"description":"Task-routing default and rule intent.","type":"string","enum":["simple","delegate","stream"]},"TaskRoutingRule":{"description":"A single task-routing rule.","type":"object","properties":{"intent":{"description":"Route intent to apply when a keyword matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"model_hint":{"description":"Optional model hint/raw model for non-delegated requests.","type":["string","null"],"default":null},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0},"sub_agent_model":{"description":"Optional raw sub-agent model override for delegated tasks.","type":["string","null"],"default":null}}},"TelegramConfig":{"description":"Telegram bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Telegram user IDs or usernames. Empty = deny all.","type":"array","items":{"type":"string"}},"bot_token":{"description":"Telegram Bot API token (from @BotFather).","type":"string"},"draft_update_interval_ms":{"description":"Minimum interval (ms) between draft message edits to avoid rate limits.","type":"integer","format":"uint64","default":1000,"minimum":0},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"interrupt_on_new_message":{"description":"When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.","type":"boolean","default":false},"stream_mode":{"description":"Streaming mode for progressive response delivery via message edits.","$ref":"#/$defs/StreamMode","default":"off"}},"required":["bot_token","allowed_users"]},"ToolCallDialectSetting":{"description":"The tool-call grammars an operator may declare for an endpoint.","oneOf":[{"description":"Only the native `tool_calls` array is a tool call (the default).","type":"string","const":"native"},{"description":"Additionally read `{json}` from the content,\nfor a tool name the request registered.","type":"string","const":"xml_function_tags"}]},"ToolSchemaDialectSetting":{"description":"The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.","oneOf":[{"description":"The published document, byte for byte (the default).","type":"string","const":"raw"},{"description":"The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.","type":"string","const":"no_root_combinators"}]},"ToolTieringConfig":{"description":"Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.","type":"object","properties":{"always_exclude":{"description":"Tool names excluded from capability publication.","type":"array","default":[],"items":{"type":"string"}},"always_include":{"description":"Tool names preferred for direct publication, subject to admission gates.","type":"array","default":[],"items":{"type":"string"}},"channel_exclude":{"description":"Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefaults to [`DEFAULT_CHANNEL_EXCLUDED_TOOLS`]; set to `[]` to expose the\nfull operator surface on channels again.","type":"array","default":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","skills_manage","memory_reindex","document_sync","document_ingest"],"items":{"type":"string"}}}},"TunnelConfig":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.","type":"object","properties":{"cloudflare":{"description":"Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).","anyOf":[{"$ref":"#/$defs/CloudflareTunnelConfig"},{"type":"null"}],"default":null},"custom":{"description":"Custom tunnel command configuration (used when `provider = \"custom\"`).","anyOf":[{"$ref":"#/$defs/CustomTunnelConfig"},{"type":"null"}],"default":null},"ngrok":{"description":"ngrok tunnel configuration (used when `provider = \"ngrok\"`).","anyOf":[{"$ref":"#/$defs/NgrokTunnelConfig"},{"type":"null"}],"default":null},"provider":{"description":"Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.","type":"string","default":"none"},"tailscale":{"description":"Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).","anyOf":[{"$ref":"#/$defs/TailscaleTunnelConfig"},{"type":"null"}],"default":null}}},"UserPolicyConfig":{"description":"Startup user policy entry (`[[user_policies]]`).","type":"object","properties":{"blocked_patterns":{"type":"array","default":[],"items":{"type":"string"}},"projects":{"type":"array","default":[],"items":{"type":"string"}},"role":{"type":"string","default":"guest"},"user_id":{"type":"string"},"visibility_ceiling":{"type":"string","default":"private"}},"required":["user_id"]},"WacliConfig":{"description":"wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```","type":"object","properties":{"allow_unsigned_loopback":{"description":"Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).","type":"boolean","default":false},"allowed_from":{"description":"Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.","type":"array","default":["*"],"items":{"type":"string"}},"bot_jid":{"description":"Bot's own JID, used for reply-to-bot mention detection.","type":["string","null"],"default":null},"bot_lid":{"description":"The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.","type":["string","null"],"default":null},"bot_number":{"description":"Bot's own phone number (digits), used for `@` mention detection.","type":["string","null"],"default":null},"cli_path":{"description":"Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.","type":["string","null"],"default":null},"group_reply_mode":{"description":"Smart group-reply mode. When `None`, derived from `mention_only`.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"host":{"description":"REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].","type":["string","null"],"writeOnly":true},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"outbound_media_workspace_only":{"description":"Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.","type":"boolean","default":false},"port":{"description":"REMOVED: legacy JSON-RPC daemon port. See `host`.","type":["integer","null"],"format":"uint16","maximum":65535,"minimum":0,"writeOnly":true},"self_chat_mode":{"description":"Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.","type":"boolean","default":false},"store_dir":{"description":"wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.","type":["string","null"],"default":null},"webhook_listen":{"description":"Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").","type":"string","default":"127.0.0.1:16868"},"webhook_path":{"description":"HTTP path the webhook server serves (default: \"/wacli\").","type":"string","default":"/wacli"},"webhook_secret":{"description":"HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.","type":["string","null"],"default":null}}},"WebSearchConfig":{"description":"Web search tool configuration (`[web_search]` section).","type":"object","properties":{"brave_api_key":{"description":"Brave Search API key (required if provider is \"brave\")","type":["string","null"],"default":null},"fetch_max_chars":{"description":"Maximum characters returned by `web_fetch` (default 10000)","type":"integer","format":"uint","default":50000,"minimum":0},"max_results":{"description":"Maximum results per search (1-20)","type":"integer","format":"uint","default":15,"minimum":0},"provider":{"description":"Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)","type":"string","default":"duckduckgo"},"timeout_secs":{"description":"Request timeout in seconds","type":"integer","format":"uint64","default":15,"minimum":0}}},"WebhookConfig":{"description":"Webhook channel configuration.","type":"object","properties":{"port":{"description":"Port to listen on for incoming webhooks.","type":"integer","format":"uint16","maximum":65535,"minimum":0},"secret":{"description":"Optional shared secret for webhook signature verification.","type":["string","null"]}},"required":["port"]},"WhatsAppConfig":{"description":"WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.","type":"object","properties":{"access_token":{"description":"Access token from Meta Business Suite (Cloud API mode)","type":["string","null"],"default":null},"allowed_numbers":{"description":"Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"app_secret":{"description":"App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"pair_code":{"description":"Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one","type":["string","null"],"default":null},"pair_phone":{"description":"Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used","type":["string","null"],"default":null},"phone_number_id":{"description":"Phone number ID from Meta Business API (Cloud API mode)","type":["string","null"],"default":null},"read_pool_size":{"description":"Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"session_path":{"description":"Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs","type":["string","null"],"default":null},"verify_token":{"description":"Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode","type":["string","null"],"default":null},"ws_url":{"description":"WebSocket URL override (replaces WHATSAPP_WS_URL)","type":["string","null"],"default":null}}},"WorkspaceHooks":{"description":"Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).","oneOf":[{"description":"They do not run (the default); `prx doctor` and `hooks_status` say so.","type":"string","const":"off"},{"description":"They run, in a cleared environment and a dedicated directory beside\n`config.toml`.","type":"string","const":"on"}]},"WorkspaceMcpServers":{"description":"Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).","oneOf":[{"description":"None: a workspace file may only narrow the servers defined in\n`config.toml`.","type":"string","const":"off"},{"description":"HTTP servers (still refused when they target a private address).","type":"string","const":"http_only"},{"description":"HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.","type":"string","const":"stdio"}]},"XinConfig":{"description":"Configuration for the xin autonomous task engine (`[xin]`).","type":"object","properties":{"adopt_legacy_tasks":{"description":"Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).","type":"boolean","default":false},"interval_minutes":{"description":"Tick interval in minutes (minimum 1). Default: 5.","type":"integer","format":"uint32","default":5,"minimum":0},"stale_timeout_minutes":{"description":"Minutes after which a running task is marked stale. Default: 60.","type":"integer","format":"uint32","default":60,"minimum":0}}},"AgentMessaging":{"description":"Owner-controlled inbound session messaging (enabled unless explicitly off).","type":"object","properties":{"inbound":{"type":"boolean","default":true}}}}} +{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Config","description":"Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).","type":"object","properties":{"a2a":{"description":"Agent-to-Agent compatibility configuration (`[a2a]`).","$ref":"#/$defs/A2aConfig","default":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trusted_trust_domains":[],"trust_domain":"prx.local"}},"agent":{"description":"Agent orchestration settings (`[agent]`).","$ref":"#/$defs/AgentConfig","default":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2,"messaging":{"inbound":true}}},"agents":{"description":"Delegate agent configurations for multi-agent workflows.","type":"object","additionalProperties":{"$ref":"#/$defs/DelegateAgentConfig"},"default":{}},"api_key":{"description":"API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.","type":["string","null"],"default":null},"api_url":{"description":"Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)","type":["string","null"],"default":null},"auth":{"description":"Auth profile and external credential import settings (`[auth]`).","$ref":"#/$defs/AuthConfig","default":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"}},"autonomy":{"description":"Autonomy and security policy configuration (`[autonomy]`).","$ref":"#/$defs/AutonomyConfig","default":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true}},"browser":{"description":"Browser automation configuration (`[browser]`).","$ref":"#/$defs/BrowserConfig","default":{"allowed_domains":[],"computer_use":{"api_key":null}}},"channels_config":{"description":"Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).","$ref":"#/$defs/ChannelsConfig","default":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null}},"chat":{"description":"Interactive chat UI configuration (`[chat]`).","$ref":"#/$defs/ChatConfig","default":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2}},"compliance":{"description":"Operator-owned compliance controls (`[compliance]`).","$ref":"#/$defs/ComplianceConfig","default":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}},"composio":{"description":"Composio managed OAuth tools integration (`[composio]`).","$ref":"#/$defs/ComposioConfig","default":{"api_key":null,"entity_id":"default"}},"cost":{"description":"Cost tracking and budget enforcement configuration (`[cost]`).","$ref":"#/$defs/CostConfig","default":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{},"warn_at_percent":80}},"cron":{"description":"Cron job configuration (`[cron]`).","$ref":"#/$defs/CronConfig","default":{"max_run_history":50}},"decision_engine":{"description":"Optional advisory decision engine, disabled by default.","$ref":"#/$defs/DecisionEngineConfig","default":{"candidates":5,"enabled":false,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"latency_budget_ms":500,"max_candidates":12,"token_ratio_limit":0.3499999940395355}},"default_model":{"description":"Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.","type":["string","null"]},"default_provider":{"description":"Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.","type":["string","null"]},"default_temperature":{"description":"Default model temperature (0.0–2.0). Default: `0.7`.","type":"number","format":"double","default":0.7},"embedding_routes":{"description":"Embedding routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/EmbeddingRouteConfig"}},"gateway":{"description":"Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).","$ref":"#/$defs/GatewayConfig","default":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60}},"heartbeat":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]`).","$ref":"#/$defs/HeartbeatConfig","default":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."}},"http_request":{"description":"HTTP request tool configuration (`[http_request]`).","$ref":"#/$defs/HttpRequestConfig","default":{"max_response_size":1000000,"timeout_secs":30}},"identity":{"description":"Identity format configuration: OpenClaw or AIEOS (`[identity]`).","$ref":"#/$defs/IdentityConfig","default":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"}},"identity_bindings":{"description":"Static identity bindings loaded at startup (`[[identity_bindings]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/IdentityBindingConfig"}},"mcp":{"description":"Secrets encryption configuration (`[secrets]`).","$ref":"#/$defs/McpConfig","default":{"servers":{}}},"mcp_server":{"description":"MCP server compatibility configuration (`[mcp_server]`).","$ref":"#/$defs/McpServerRuntimeConfig","default":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true}},"media":{"description":"Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.","$ref":"#/$defs/MediaConfig","default":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"}},"memory":{"description":"Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).","$ref":"#/$defs/MemoryConfig","default":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7}},"model_routes":{"description":"Model routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/ModelRouteConfig"}},"model_settings":{"description":"Catalog model levels and explicit parameters, keyed by canonical release ID.","type":"object","additionalProperties":{"$ref":"#/$defs/ModelSettings"},"default":{}},"multimodal":{"description":"Multimodal (image) handling configuration (`[multimodal]`).","$ref":"#/$defs/MultimodalConfig","default":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4}},"nodes":{"description":"Remote node proxy configuration (`[nodes]`).","$ref":"#/$defs/NodesConfig","default":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}},"observability":{"description":"Observability backend configuration (`[observability]`).","$ref":"#/$defs/ObservabilityConfig","default":{"backend":"none","otel_endpoint":null,"otel_service_name":null}},"plugins":{"description":"WASM plugin runtime switch (`[plugins]`), off by default.","$ref":"#/$defs/PluginsConfig","default":{"enabled":false}},"providers":{"description":"Provider-specific runtime options (`[providers.]`).","$ref":"#/$defs/ProvidersConfig","default":{"ollama":{"num_ctx":null}}},"proxy":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).","$ref":"#/$defs/ProxyConfig","default":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]}},"query_classification":{"description":"Automatic query classification — maps user messages to model hints.","$ref":"#/$defs/QueryClassificationConfig","default":{"rules":[]}},"reliability":{"description":"Reliability settings: retries, fallback providers, backoff (`[reliability]`).","$ref":"#/$defs/ReliabilityConfig","default":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2}},"router":{"description":"Heuristic LLM router configuration (`[router]`).","$ref":"#/$defs/RouterConfig","default":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]}},"runtime":{"description":"Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.","$ref":"#/$defs/RuntimeConfig","default":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null}},"scheduler":{"description":"Scheduler configuration for periodic task execution (`[scheduler]`).","$ref":"#/$defs/SchedulerConfig","default":{"claim_lease_secs":90,"max_tasks":64}},"secrets":{"$ref":"#/$defs/SecretsConfig","default":{"encrypt":true}},"security":{"description":"Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).","$ref":"#/$defs/SecurityConfig","default":{"audit":{"log_path":"audit.log","max_size_mb":100}}},"self_system":{"description":"Self-system experimental automation controls (`[self_system]`).","$ref":"#/$defs/SelfSystemConfig","default":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24}},"sessions_spawn":{"description":"Session spawning configuration (`[sessions_spawn]`).","$ref":"#/$defs/SessionsSpawnConfig","default":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null}},"skill_rag":{"description":"Dynamic skill retrieval settings (`[skill_rag]`).","$ref":"#/$defs/SkillRagConfig","default":{"top_k":32}},"skills":{"description":"Skills loading and community repository behavior (`[skills]`).","$ref":"#/$defs/SkillsConfig","default":{"open_skills_dir":null,"openclaw_skills_dir":null}},"skills_lifecycle":{"description":"Skill lifecycle (`[skills_lifecycle]`), off by default.","$ref":"#/$defs/SkillsLifecycleConfig","default":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]}},"smart_group":{"description":"Smart group-reply pre-gate configuration (`[smart_group]`).","$ref":"#/$defs/SmartGroupConfig","default":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5}},"storage":{"description":"Persistent storage provider configuration (`[storage]`).","$ref":"#/$defs/StorageConfig","default":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"task_routing":{"description":"Task routing configuration — classifies work by intent before the main agent loop.","$ref":"#/$defs/TaskRoutingConfig","default":{"default_intent":"simple","rules":[]}},"tool_tiering":{"description":"Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).","$ref":"#/$defs/ToolTieringConfig","default":{"always_exclude":[],"always_include":[],"channel_exclude":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","skills_manage","memory_reindex","document_sync","document_ingest"]}},"tunnel":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]`).","$ref":"#/$defs/TunnelConfig","default":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null}},"user_policies":{"description":"Static user policy records loaded at startup (`[[user_policies]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/UserPolicyConfig"}},"web_search":{"description":"Web search tool configuration (`[web_search]`).","$ref":"#/$defs/WebSearchConfig","default":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15}},"webhook":{"description":"Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).","$ref":"#/$defs/MemoryWebhookConfig","default":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null}},"xin":{"description":"Xin autonomous task engine configuration (`[xin]`).","$ref":"#/$defs/XinConfig","default":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}}},"$defs":{"A2aConfig":{"type":"object","properties":{"agent_id":{"description":"Stable PRX agent identifier advertised to peers.","type":"string","default":"prx-default"},"allowed_peer_issuers":{"description":"Accepted external peer issuers.","type":"array","default":[],"items":{"type":"string"}},"bind":{"description":"Advertised bind address.","type":"string","default":"127.0.0.1:16832"},"card_jwks_uri":{"description":"Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.","type":["string","null"],"default":null},"card_signing_key_path":{"description":"On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).","type":["string","null"],"default":null},"card_ttl_seconds":{"description":"Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.","type":"integer","format":"uint64","default":3600,"minimum":0},"discovery_advertised":{"description":"Whether to advertise into an external A2A registry.","type":"boolean","default":false},"handoff_nonce_ttl_seconds":{"description":"Replay window for future handoff delegation tokens.","type":"integer","format":"uint64","default":3600,"minimum":0},"messaging_enabled":{"description":"Enable the dedicated pinned mTLS messaging listener.","type":"boolean","default":false},"peers":{"type":"object","additionalProperties":{"$ref":"#/$defs/A2aPeer"},"default":{}},"spiffe_id":{"description":"Local SPIFFE-style identifier placeholder.","type":"string","default":"spiffe://prx-local/agent/prx-default"},"spiffe_strict_validation":{"description":"When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.","type":"boolean","default":false},"spiffe_trust_bundle_pem":{"description":"Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).","type":["string","null"],"default":null},"trusted_trust_domains":{"description":"Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).","type":"array","default":[],"items":{"type":"string"}},"trust_domain":{"description":"SPIFFE trust domain for new instance identities.","type":"string","default":"prx.local"}}},"A2aPeer":{"description":"Explicit pinned identity and local recipient grant.","type":"object","properties":{"spiffe_id":{"type":"string"},"fingerprints":{"type":"array","items":{"type":"string"}},"address":{"type":"string"},"owner":{"type":"string"},"sessions":{"type":"array","default":["*"],"items":{"type":"string"}},"agents":{"type":"array","default":["*"],"items":{"type":"string"}}},"required":["spiffe_id","fingerprints","address","owner"],"additionalProperties":false},"AgentCompactionConfig":{"description":"Agent context compaction configuration (`[agent.compaction]`).","type":"object","properties":{"keep_recent_messages":{"description":"Number of recent non-system messages to keep after compaction.","type":"integer","format":"uint","default":12,"minimum":0},"max_context_tokens":{"description":"Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.","type":"integer","format":"uint","default":128000,"minimum":0},"memory_flush":{"description":"Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.","type":"boolean","default":true},"mode":{"description":"Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).","$ref":"#/$defs/AgentCompactionMode","default":"switch"},"os_paging":{"description":"Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.","$ref":"#/$defs/OsPagingConfig","default":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"}},"reserve_tokens":{"description":"Tokens reserved for the next model response.","type":"integer","format":"uint","default":4096,"minimum":0}}},"AgentCompactionMode":{"description":"Compaction mode for long conversation contexts.","oneOf":[{"description":"Disable proactive compaction.","type":"string","const":"off"},{"description":"Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.","type":"string","const":"switch"},{"description":"Conservative compaction that prefers summary replacement.","type":"string","const":"safeguard"},{"description":"Aggressive truncation mode for tighter contexts.","type":"string","const":"aggressive"}]},"AgentConfig":{"description":"Agent orchestration configuration (`[agent]` section).","type":"object","properties":{"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"compact_context":{"description":"When true: bootstrap_max_chars=6000. Use for 13B or smaller models.","type":"boolean","default":false},"compaction":{"description":"Context compaction controls (`[agent.compaction]`).","$ref":"#/$defs/AgentCompactionConfig","default":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096}},"low_priority_tools":{"description":"Tool names treated as low-priority when `priority_scheduling_enabled = true`.","type":"array","default":["sessions_spawn","delegate"],"items":{"type":"string"}},"priority_scheduling_enabled":{"description":"Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.","type":"boolean","default":false},"read_only_tool_concurrency_window":{"description":"Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.","type":"integer","format":"uint","default":2,"minimum":0},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}}},"AgentLimits":{"description":"Optional admission limits for rf-started turns of a named agent.","type":"object","properties":{"max_concurrent_turns":{"type":["integer","null"],"format":"uint32","minimum":0},"max_cost_per_day_cents":{"type":["integer","null"],"format":"uint64","minimum":0}},"additionalProperties":false},"AuditConfig":{"description":"Audit logging configuration","type":"object","properties":{"log_path":{"description":"Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).","type":"string","default":"audit.log"},"max_size_mb":{"description":"Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).","type":"integer","format":"uint32","default":100,"minimum":0}}},"AuthConfig":{"description":"Authentication and external credential import configuration (`[auth]` section).","type":"object","properties":{"codex_auth_json_auto_import":{"description":"Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.","type":"boolean","default":false},"codex_auth_json_path":{"description":"Source path for Codex CLI auth.json import.","type":"string","default":"~/.codex/auth.json"}}},"AutonomyConfig":{"type":"object","properties":{"acknowledge_unrestricted_profile":{"description":"Operator acknowledgement for an intentionally unrestricted profile.\nThis suppresses doctor noise only; it does not alter policy behavior.","type":"boolean","default":false},"forbidden_paths":{"description":"Explicit path denylist. Default includes system-critical paths.\n\nFails closed: omitting the key keeps the built-in list rather than\nemptying it, so a partial `[autonomy]` section never removes the\ndenylist.","type":"array","default":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"items":{"type":"string"}},"level":{"description":"Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).","$ref":"#/$defs/AutonomyLevel","default":"full"},"max_cost_per_day_cents":{"description":"Maximum cost per day in cents per policy. Default: unset (no ceiling).","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"scopes":{"description":"Scope-based tool access control: per-user/channel/chat-type allow/deny rules.","$ref":"#/$defs/ScopeConfig","default":{"assign_owners":[],"default":"allow","rules":[]}},"workspace_only":{"description":"Restrict file writes and command paths to the workspace directory. Default: `true`.\n\nFails closed: a `[autonomy]` section that omits this key keeps the\nworkspace restriction on, so a partial section can never widen the\nfilesystem reach by accident.","type":"boolean","default":true}}},"AutonomyLevel":{"description":"How much autonomy the agent has","oneOf":[{"description":"Read-only: can observe but not act","type":"string","const":"readonly"},{"description":"Supervised: acts but requires approval for risky operations","type":"string","const":"supervised"},{"description":"Full: autonomous execution within policy bounds","type":"string","const":"full"}]},"BackendSelection":{"description":"Which decision backend runs: `auto` (the factory's order) or one kind.","type":"string"},"BrowserComputerUseConfig":{"description":"Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.","type":"object","properties":{"api_key":{"description":"Optional bearer token (retained only for config secret handling).","type":["string","null"],"default":null}}},"BrowserConfig":{"description":"Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.","type":"object","properties":{"allowed_domains":{"description":"Allowed domains for `web_fetch` (exact or subdomain match).","type":"array","default":[],"items":{"type":"string"}},"computer_use":{"description":"Computer-use sidecar config (retained only for `api_key` secret handling).","$ref":"#/$defs/BrowserComputerUseConfig","default":{"api_key":null}}}},"ChannelsConfig":{"description":"Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.","type":"object","properties":{"cli":{"description":"Enable the CLI interactive channel. Default: `true`.","type":"boolean","default":true},"dingtalk":{"description":"DingTalk channel configuration.","anyOf":[{"$ref":"#/$defs/DingTalkConfig"},{"type":"null"}]},"discord":{"description":"Discord bot channel configuration.","anyOf":[{"$ref":"#/$defs/DiscordConfig"},{"type":"null"}]},"email":{"description":"Email channel configuration.","anyOf":[{"$ref":"#/$defs/EmailConfig"},{"type":"null"}]},"imessage":{"description":"iMessage channel configuration (macOS only).","anyOf":[{"$ref":"#/$defs/IMessageConfig"},{"type":"null"}]},"irc":{"description":"IRC channel configuration.","anyOf":[{"$ref":"#/$defs/IrcConfig"},{"type":"null"}]},"lark":{"description":"Lark/Feishu channel configuration.","anyOf":[{"$ref":"#/$defs/LarkConfig"},{"type":"null"}]},"linq":{"description":"Linq Partner API channel configuration.","anyOf":[{"$ref":"#/$defs/LinqConfig"},{"type":"null"}]},"mattermost":{"description":"Mattermost bot channel configuration.","anyOf":[{"$ref":"#/$defs/MattermostConfig"},{"type":"null"}]},"nextcloud_talk":{"description":"Nextcloud Talk bot channel configuration.","anyOf":[{"$ref":"#/$defs/NextcloudTalkConfig"},{"type":"null"}]},"qq":{"description":"QQ Official Bot channel configuration.","anyOf":[{"$ref":"#/$defs/QQConfig"},{"type":"null"}]},"ramflux":{"description":"Local ramflux agent-host bridge.","anyOf":[{"$ref":"#/$defs/RamfluxConfig"},{"type":"null"}],"default":null},"signal":{"description":"Signal channel configuration.","anyOf":[{"$ref":"#/$defs/SignalConfig"},{"type":"null"}]},"slack":{"description":"Slack bot channel configuration.","anyOf":[{"$ref":"#/$defs/SlackConfig"},{"type":"null"}]},"telegram":{"description":"Telegram bot channel configuration.","anyOf":[{"$ref":"#/$defs/TelegramConfig"},{"type":"null"}]},"wacli":{"description":"wacli JSON-RPC daemon channel configuration.","anyOf":[{"$ref":"#/$defs/WacliConfig"},{"type":"null"}],"default":null},"webhook":{"description":"Webhook channel configuration.","anyOf":[{"$ref":"#/$defs/WebhookConfig"},{"type":"null"}]},"whatsapp":{"description":"WhatsApp channel configuration (Cloud API or Web mode).","anyOf":[{"$ref":"#/$defs/WhatsAppConfig"},{"type":"null"}]}}},"ChatConfig":{"description":"Interactive chat configuration (`[chat]`).","type":"object","properties":{"daemon":{"description":"How this chat process reaches the daemon it borrows channels from.","$ref":"#/$defs/ChatDaemonConfig","default":{"token":"","url":""}},"max_concurrent_visible_turns":{"description":"Maximum concurrent visible provider turns in the TUI Redux driver.","type":"integer","format":"uint","default":2,"minimum":0}}},"ChatDaemonConfig":{"description":"Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.","type":"object","properties":{"token":{"description":"Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.","type":"string","default":""},"url":{"description":"Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.","type":"string","default":""}}},"CircuitBreakerConfig":{"description":"The per-backend circuit breaker.","type":"object","properties":{"cooldown_secs":{"description":"Seconds the breaker stays open (1 to 3600).","type":"integer","format":"uint32","default":60,"minimum":0},"failure_threshold":{"description":"Consecutive failures before the breaker opens (1 to 100).","type":"integer","format":"uint32","default":5,"minimum":0}}},"ClassificationRule":{"description":"A single classification rule mapping message patterns to a model hint.","type":"object","properties":{"hint":{"description":"Must match a `[[model_routes]]` hint value.","type":"string"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"max_length":{"description":"Only match if message length <= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"min_length":{"description":"Only match if message length >= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"patterns":{"description":"Case-sensitive literal matches (for \"```\", \"fn \", etc.).","type":"array","default":[],"items":{"type":"string"}},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0}},"required":["hint"]},"CloudflareTunnelConfig":{"type":"object","properties":{"token":{"description":"Cloudflare Tunnel token (from Zero Trust dashboard)","type":"string"}},"required":["token"]},"ComplianceConfig":{"type":"object","properties":{"eu_ai_act":{"$ref":"#/$defs/EuAiActComplianceConfig","default":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null}},"interaction_notice":{"$ref":"#/$defs/InteractionNoticeConfig","default":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}}},"ComposioConfig":{"description":"Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.","type":"object","properties":{"api_key":{"description":"Composio API key (stored encrypted when secrets.encrypt = true)","type":["string","null"],"default":null},"entity_id":{"description":"Default entity ID for multi-user setups","type":"string","default":"default"}}},"CostConfig":{"description":"Cost tracking and budget enforcement configuration (`[cost]` section).","type":"object","properties":{"allow_override":{"description":"Allow requests to exceed budget with --override flag (default: false)","type":"boolean","default":false},"daily_limit_usd":{"description":"Daily spending limit in USD (default: unset, no limit; 0 refuses every priced turn)","type":["number","null"],"format":"double","default":null},"monthly_limit_usd":{"description":"Monthly spending limit in USD (default: unset, no limit)","type":["number","null"],"format":"double","default":null},"prices":{"description":"Per-model pricing (USD per 1M tokens)","type":"object","additionalProperties":{"$ref":"#/$defs/ModelPricing"},"default":{}},"warn_at_percent":{"description":"Warn when spending reaches this percentage of a configured limit (default: 80)","type":"integer","format":"uint8","default":80,"maximum":255,"minimum":0}}},"CredentialRefSetting":{"description":"Which credential a decision backend uses. A reference, never a secret.","type":"string"},"CronConfig":{"description":"Cron job configuration (`[cron]` section).","type":"object","properties":{"max_run_history":{"description":"Maximum number of historical cron run records to retain. Default: `50`.","type":"integer","format":"uint32","default":50,"minimum":0}}},"CustomTunnelConfig":{"type":"object","properties":{"health_url":{"description":"Optional URL to check tunnel health","type":["string","null"]},"start_command":{"description":"Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"","type":"string"},"url_pattern":{"description":"Optional regex to extract public URL from command stdout","type":["string","null"]}},"required":["start_command"]},"DecisionBackendConfig":{"description":"The decision backend (`[decision_engine.backend]`).","type":"object","properties":{"circuit_breaker":{"description":"The circuit breaker.","$ref":"#/$defs/CircuitBreakerConfig","default":{"cooldown_secs":60,"failure_threshold":5}},"credential_ref":{"description":"The credential reference: `\"\"`, `\"none\"` or `cred-`.","$ref":"#/$defs/CredentialRefSetting","default":""},"endpoint":{"description":"The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.","type":"string","default":""},"kind":{"description":"`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).","$ref":"#/$defs/BackendSelection","default":"auto"},"max_request_bytes":{"description":"Largest request body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":65536,"minimum":0},"max_response_bytes":{"description":"Largest response body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":262144,"minimum":0},"model":{"description":"The model the endpoint serves; one exact version for a hosted\nservice.","type":"string","default":""},"pinned_snapshot":{"description":"The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.","type":"string"},"remote_enabled":{"description":"Whether decision state may leave this machine. Default `false`.","type":"boolean","default":false},"timeout_ms":{"description":"Transport timeout (10 ms up to the extra latency budget).","type":"integer","format":"uint32","default":250,"minimum":0}}},"DecisionEngineConfig":{"type":"object","properties":{"backend":{"anyOf":[{"$ref":"#/$defs/DecisionBackendConfig"},{"type":"null"}]},"candidates":{"type":"integer","format":"uint32","default":5,"minimum":0},"enabled":{"type":"boolean","default":false},"mode":{"$ref":"#/$defs/DecisionMode","default":"pre"},"observe_queue":{"type":"integer","format":"uint32","default":64,"minimum":0},"prompt_budget_tokens":{"type":"integer","format":"uint32","default":300,"minimum":0},"telemetry_cap":{"type":"integer","format":"uint32","default":1000,"minimum":0},"timeout_ms":{"type":"integer","format":"uint32","default":1500,"minimum":0},"latency_budget_ms":{"description":"The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.","type":"integer","format":"uint64","default":500,"minimum":0},"token_ratio_limit":{"description":"Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).","type":"number","format":"float","default":0.3499999940395355},"max_candidates":{"description":"The most candidates a turn considers (1 to 32).","type":"integer","format":"uint8","default":12,"maximum":255,"minimum":0}}},"DecisionMode":{"type":"string","enum":["pre","post","both"]},"DeclarationOfConformityConfig":{"type":"object","properties":{"applicable_union_law":{"type":"array","default":[],"items":{"type":"string"}},"artifact_path":{"type":["string","null"],"default":null},"artifact_version":{"type":["string","null"],"default":null},"conformity_assessment_procedure":{"type":["string","null"],"default":null},"conformity_statement":{"type":["string","null"],"default":null},"harmonised_standards":{"type":"array","default":[],"items":{"type":"string"}},"issue_date":{"type":["string","null"],"default":null},"issue_place":{"type":["string","null"],"default":null},"notified_body_certificate":{"type":["string","null"],"default":null},"notified_body_identification_number":{"type":["string","null"],"default":null},"notified_body_name":{"type":["string","null"],"default":null},"personal_data_compliance_statement":{"type":["string","null"],"default":null},"processes_personal_data":{"type":"boolean","default":false},"provider_address":{"type":["string","null"],"default":null},"provider_name":{"type":["string","null"],"default":null},"signer_function":{"type":["string","null"],"default":null},"signer_name":{"type":["string","null"],"default":null},"signer_on_behalf_of":{"type":["string","null"],"default":null},"sole_responsibility_statement":{"type":["string","null"],"default":null},"standards_not_applicable_reason":{"type":["string","null"],"default":null},"system_name":{"type":["string","null"],"default":null},"system_reference":{"type":["string","null"],"default":null},"system_type":{"type":["string","null"],"default":null}}},"DelegateAgentConfig":{"description":"Configuration for a delegate sub-agent used by the `delegate` tool.","type":"object","properties":{"agentic":{"description":"Agentic sub-agent mode (multi-turn tool-call loop). Default true; an\nexplicit `false` makes the agent answer-only with no tools.","type":"boolean","default":true},"allowed_tools":{"description":"Allowlist of tool names available to the sub-agent in agentic mode.\nEmpty or omitted means all tools, the same as `[\"*\"]`.","type":"array","default":[],"items":{"type":"string"}},"api_key":{"description":"Optional API key override","type":["string","null"],"default":null},"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"autonomy":{"description":"The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.","anyOf":[{"$ref":"#/$defs/AutonomyLevel"},{"type":"null"}]},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"enabled":{"description":"Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.","type":"boolean","default":true},"identity_dir":{"description":"Optional identity files directory relative to workspace root.","type":["string","null"],"default":null},"limits":{"$ref":"#/$defs/AgentLimits","default":{"max_concurrent_turns":null,"max_cost_per_day_cents":null}},"max_depth":{"description":"Max recursion depth for nested delegation","type":"integer","format":"uint32","default":8,"minimum":0},"memory_scope":{"description":"Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".","type":["string","null"],"default":null},"model":{"description":"Model name","type":"string"},"provider":{"description":"Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")","type":"string"},"spawn_enabled":{"description":"Whether this agent is allowed to be targeted by sessions_spawn (default: true).","type":["boolean","null"],"default":null},"system_prompt":{"description":"Optional system prompt for the sub-agent","type":["string","null"],"default":null},"temperature":{"description":"Temperature override","type":["number","null"],"format":"double","default":null},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}},"required":["provider","model"]},"DingTalkConfig":{"description":"DingTalk configuration for Stream Mode messaging","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"client_id":{"description":"Client ID (AppKey) from DingTalk developer console","type":"string"},"client_secret":{"description":"Client Secret (AppSecret) from DingTalk developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["client_id","client_secret"]},"DiscordConfig":{"description":"Discord bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Discord user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Discord bot token (from Discord Developer Portal).","type":"string"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"guild_id":{"description":"Optional guild (server) ID to restrict the bot to a single guild.","type":["string","null"]},"listen_to_bots":{"description":"When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.","type":"boolean","default":false}},"required":["bot_token"]},"DmPolicy":{"description":"Policy for direct-message handling.","oneOf":[{"description":"Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).","type":"string","const":"pairing"},{"description":"Accept only senders listed in `allowed_from`.","type":"string","const":"allowlist"},{"description":"Accept any direct sender.","type":"string","const":"open"},{"description":"Ignore direct messages.","type":"string","const":"disabled"}]},"DockerRuntimeConfig":{"description":"Docker runtime configuration (`[runtime.docker]` section).","type":"object","properties":{"allowed_workspace_roots":{"description":"Optional workspace root allowlist for Docker mount validation.","type":"array","default":[],"items":{"type":"string"}},"cpu_limit":{"description":"Optional CPU limit (`None` = no explicit limit).","type":["number","null"],"format":"double","default":1.0},"image":{"description":"Runtime image used to execute shell commands.","type":"string","default":"alpine:3.20"},"memory_limit_mb":{"description":"Optional memory limit in MB (`None` = no explicit limit).","type":["integer","null"],"format":"uint64","default":512,"minimum":0},"mount_workspace":{"description":"Mount configured workspace into `/workspace`.","type":"boolean","default":true},"network":{"description":"Docker network mode (`none`, `bridge`, etc.).","type":"string","default":"none"},"read_only_rootfs":{"description":"Mount root filesystem as read-only.","type":"boolean","default":true}}},"EmailConfig":{"description":"Email channel configuration","type":"object","properties":{"allowed_senders":{"description":"Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)","type":"array","default":[],"items":{"type":"string"}},"from_address":{"description":"From address for outgoing emails","type":"string"},"idle_timeout_secs":{"description":"IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes","type":"integer","format":"uint64","default":1740,"minimum":0},"imap_folder":{"description":"IMAP folder to poll (default: INBOX)","type":"string","default":"INBOX"},"imap_host":{"description":"IMAP server hostname","type":"string"},"imap_port":{"description":"IMAP server port (default: 993 for TLS)","type":"integer","format":"uint16","default":993,"maximum":65535,"minimum":0},"password":{"description":"Email password for authentication","type":"string"},"smtp_host":{"description":"SMTP server hostname","type":"string"},"smtp_port":{"description":"SMTP server port (default: 465 for TLS)","type":"integer","format":"uint16","default":465,"maximum":65535,"minimum":0},"smtp_tls":{"description":"Use TLS for SMTP (default: true)","type":"boolean","default":true},"username":{"description":"Email username for authentication","type":"string"}},"required":["imap_host","smtp_host","username","password","from_address"]},"EmbeddingRouteConfig":{"description":"Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"dimensions":{"description":"Optional embedding dimension override for this route","type":["integer","null"],"format":"uint","default":null,"minimum":0},"hint":{"description":"Route hint name (e.g. \"semantic\", \"archive\", \"faq\")","type":"string"},"model":{"description":"Embedding model to use with that provider","type":"string"},"provider":{"description":"Embedding provider (`none`, `openai`, or `custom:`)","type":"string"}},"required":["hint","provider","model"]},"EuAiActClassificationConfig":{"type":"object","properties":{"assessed_at":{"type":["string","null"],"default":null},"owner":{"type":["string","null"],"default":null},"status":{"$ref":"#/$defs/EuAiActRiskClassification","default":"unclassified"}}},"EuAiActComplianceConfig":{"type":"object","properties":{"classification":{"$ref":"#/$defs/EuAiActClassificationConfig","default":{"assessed_at":null,"owner":null,"status":"unclassified"}},"declaration":{"$ref":"#/$defs/DeclarationOfConformityConfig","default":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null}},"incident_store_path":{"type":["string","null"],"default":null}}},"EuAiActRiskClassification":{"type":"string","enum":["unclassified","high_risk","not_high_risk"]},"FitnessConfig":{"description":"Calendar schedule, evidence thresholds, and retention for fitness v2.","type":"object","properties":{"auto_run":{"description":"Run the daily fitness worker in daemon mode.","type":"boolean","default":true},"max_backfill_days":{"description":"Maximum number of closed days recovered after downtime.","type":"integer","format":"uint32","default":7,"minimum":0},"min_coverage":{"description":"Minimum available metric weight required to publish a final score.","type":"number","format":"double","default":0.6},"min_samples":{"description":"Minimum samples required before an evidence-derived subscore is usable.","type":"integer","format":"uint","default":5,"minimum":0},"retention_days":{"description":"Number of daily JSON reports retained on disk.","type":"integer","format":"uint32","default":180,"minimum":0},"run_at":{"description":"Local wall-clock time (`HH:MM`) at which the previous day is scored.","type":"string","default":"00:10"},"timezone":{"description":"IANA timezone used to define closed calendar days.","type":"string","default":"UTC"}}},"GatewayConfig":{"description":"Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.","type":"object","properties":{"allow_public_bind":{"description":"Allow binding to non-localhost without a tunnel (default: false)","type":"boolean","default":false},"api_rate_limit_per_minute":{"description":"Max `/api/*` requests per minute per authenticated token.","type":"integer","format":"uint32","default":60,"minimum":0},"channel_webhook_dedup_ttl_secs":{"description":"How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.","type":"integer","format":"uint64","default":86400,"minimum":0},"host":{"description":"Gateway host (default: 127.0.0.1)","type":"string","default":"127.0.0.1"},"idempotency_max_keys":{"description":"Maximum distinct idempotency keys retained in memory.","type":"integer","format":"uint","default":10000,"minimum":0},"idempotency_ttl_secs":{"description":"TTL for webhook idempotency keys.","type":"integer","format":"uint64","default":300,"minimum":0},"pair_rate_limit_per_minute":{"description":"Max `/pair` requests per minute per client key.","type":"integer","format":"uint32","default":10,"minimum":0},"paired_tokens":{"description":"Paired bearer tokens (managed automatically, not user-edited)","type":"array","default":[],"items":{"type":"string"}},"port":{"description":"Gateway port (default: 16830)","type":"integer","format":"uint16","default":16830,"maximum":65535,"minimum":0},"rate_limit_max_keys":{"description":"Maximum distinct client keys tracked by gateway rate limiter maps.","type":"integer","format":"uint","default":10000,"minimum":0},"require_pairing":{"description":"Require pairing before accepting requests (default: true)","type":"boolean","default":true},"targeted_agents":{"description":"Switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). Default true. While false, any\notherwise-valid named target answers 409 `agent_disabled` and never\nruns as Main.","type":"boolean","default":true},"trust_forwarded_headers":{"description":"Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.","type":"boolean","default":false},"webhook_rate_limit_per_minute":{"description":"Max `/webhook` requests per minute per client key.","type":"integer","format":"uint32","default":60,"minimum":0}}},"GroupPolicy":{"description":"Policy for group-message handling.","oneOf":[{"description":"Accept only groups listed in `group_allow_from`.","type":"string","const":"allowlist"},{"description":"Accept any group.","type":"string","const":"open"},{"description":"Ignore group messages.","type":"string","const":"disabled"}]},"GroupReplyMode":{"description":"How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.","oneOf":[{"description":"Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).","type":"string","const":"off"},{"description":"Reply only when the bot is @-mentioned (legacy `mention_only = true`).","type":"string","const":"mention-only"},{"description":"Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).","type":"string","const":"smart"}]},"HeartbeatConfig":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]` section).","type":"object","properties":{"active_hours":{"description":"Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.","type":"array","default":[8,23],"items":{"type":"integer","format":"uint8","maximum":255,"minimum":0}},"interval_minutes":{"description":"Interval in minutes between heartbeat pings. Default: `30`.","type":"integer","format":"uint32","default":30,"minimum":0},"prompt":{"description":"Prompt used by heartbeat worker when dispatching tasks.","type":"string","default":"Check HEARTBEAT.md and follow instructions."}}},"HttpRequestConfig":{"description":"HTTP request tool configuration (`[http_request]` section).","type":"object","properties":{"max_response_size":{"description":"Maximum response size in bytes (default: 1MB)","type":"integer","format":"uint","default":1000000,"minimum":0},"timeout_secs":{"description":"Request timeout in seconds (default: 30)","type":"integer","format":"uint64","default":30,"minimum":0}}},"IMessageConfig":{"description":"iMessage channel configuration (macOS only).","type":"object","properties":{"allowed_contacts":{"description":"Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.","type":"array","items":{"type":"string"}},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["allowed_contacts"]},"IdentityBindingConfig":{"description":"Startup identity binding entry (`[[identity_bindings]]`).","type":"object","properties":{"channel":{"type":"string"},"channel_account":{"type":"string"},"display_name":{"type":["string","null"],"default":null},"user_id":{"type":"string"}},"required":["user_id","channel","channel_account"]},"IdentityConfig":{"description":"Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.","type":"object","properties":{"aieos_inline":{"description":"Inline AIEOS JSON (alternative to file path)","type":["string","null"],"default":null},"aieos_path":{"description":"Path to AIEOS JSON file (relative to workspace)","type":["string","null"],"default":null},"format":{"description":"Identity format: \"openclaw\" (default) or \"aieos\"","type":"string","default":"openclaw"}}},"InteractionNoticeApplicability":{"type":"string","enum":["required","not_applicable"]},"InteractionNoticeConfig":{"type":"object","properties":{"applicability":{"$ref":"#/$defs/InteractionNoticeApplicability","default":"required"},"exception_owner":{"type":["string","null"],"default":null},"exception_reviewed_at":{"type":["string","null"],"default":null},"text":{"type":"string","default":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers."},"version":{"type":"string","default":"1"}}},"IrcConfig":{"description":"IRC channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed nicknames (case-insensitive) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"channels":{"description":"Channels to join on connect","type":"array","default":[],"items":{"type":"string"}},"mention_only":{"description":"When true, only process channel/group messages that mention the bot.","type":"boolean","default":false},"nickname":{"description":"Bot nickname","type":"string"},"nickserv_password":{"description":"NickServ IDENTIFY password","type":["string","null"]},"port":{"description":"IRC server port (default: 6697 for TLS)","type":"integer","format":"uint16","default":6697,"maximum":65535,"minimum":0},"sasl_password":{"description":"SASL PLAIN password (IRCv3)","type":["string","null"]},"server":{"description":"IRC server hostname","type":"string"},"server_password":{"description":"Server password (for bouncers like ZNC)","type":["string","null"]},"username":{"description":"Username (defaults to nickname if not set)","type":["string","null"]},"verify_tls":{"description":"Verify TLS certificate (default: true)","type":["boolean","null"]}},"required":["server","nickname"]},"LarkConfig":{"description":"Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from Lark/Feishu developer console","type":"string"},"app_secret":{"description":"App Secret from Lark/Feishu developer console","type":"string"},"encrypt_key":{"description":"Encrypt key for webhook message decryption (optional)","type":["string","null"],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"port":{"description":"HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"receive_mode":{"description":"Event receive mode: \"websocket\" (default) or \"webhook\"","$ref":"#/$defs/LarkReceiveMode","default":"websocket"},"use_feishu":{"description":"Whether to use the Feishu (Chinese) endpoint instead of Lark (International)","type":"boolean","default":false},"verification_token":{"description":"Verification token for webhook validation (optional)","type":["string","null"],"default":null}},"required":["app_id","app_secret"]},"LarkReceiveMode":{"description":"How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.","type":"string","enum":["websocket","webhook"]},"LinqConfig":{"type":"object","properties":{"allowed_senders":{"description":"Allowed sender handles (phone numbers) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"api_token":{"description":"Linq Partner API token (Bearer auth)","type":"string"},"from_phone":{"description":"Phone number to send from (E.164 format)","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"signing_secret":{"description":"Webhook signing secret for signature verification","type":["string","null"],"default":null}},"required":["api_token","from_phone"]},"MattermostConfig":{"description":"Mattermost bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Mattermost user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Mattermost bot access token.","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.","type":["boolean","null"],"default":null},"thread_replies":{"description":"When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.","type":["boolean","null"],"default":null},"url":{"description":"Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).","type":"string"}},"required":["url","bot_token"]},"McpConfig":{"type":"object","properties":{"servers":{"description":"Named MCP server definitions","type":"object","additionalProperties":{"$ref":"#/$defs/McpServerConfig"},"default":{}},"workspace_servers":{"description":"Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.","$ref":"#/$defs/WorkspaceMcpServers"}}},"McpServerConfig":{"type":"object","properties":{"allow_tools":{"description":"Optional allow-list of exposed tools (empty = all)","type":"array","default":[],"items":{"type":"string"}},"args":{"description":"Command args for stdio mode","type":"array","default":[],"items":{"type":"string"}},"command":{"description":"Command for stdio mode","type":["string","null"],"default":null},"deny_tools":{"description":"Optional deny-list of exposed tools","type":"array","default":[],"items":{"type":"string"}},"env":{"description":"Environment variables for stdio mode","type":"object","additionalProperties":{"type":"string"},"default":{}},"request_timeout_ms":{"description":"Request timeout in milliseconds","type":"integer","format":"uint64","default":30000,"minimum":0},"startup_timeout_ms":{"description":"Startup timeout in milliseconds","type":"integer","format":"uint64","default":10000,"minimum":0},"tool_name_prefix":{"description":"Prefix used in tool naming and routing","type":"string","default":"mcp"},"transport":{"description":"Transport type: stdio or http","$ref":"#/$defs/McpTransport","default":"stdio"},"url":{"description":"URL for HTTP mode (streamable HTTP endpoint)","type":["string","null"],"default":null},"working_dir":{"description":"Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).","type":["string","null"]}}},"McpServerRuntimeConfig":{"type":"object","properties":{"allowed_origins":{"description":"Allowed browser origins for future streamable HTTP clients.","type":"array","default":["claude.ai","openai.com","localhost"],"items":{"type":"string"}},"bind":{"description":"Advertised bind address. The gateway may still be started with a CLI port override.","type":"string","default":"127.0.0.1:16831"},"exposed_tools":{"description":"Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.","type":"array","default":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"items":{"type":"string"}},"jwt_algorithms":{"description":"Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.","type":"array","default":["RS256"],"items":{"type":"string"}},"jwt_audience":{"description":"Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.","type":["string","null"],"default":null},"jwt_issuer":{"description":"Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.","type":["string","null"],"default":null},"jwt_jwks":{"description":"Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.","type":["string","null"],"default":null},"jwt_jwks_cache_ttl_secs":{"description":"Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.","type":"integer","format":"uint64","default":300,"minimum":0},"jwt_jwks_uri":{"description":"Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.","type":["string","null"],"default":null},"jwt_public_key_pem":{"description":"PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.","type":["string","null"],"default":null},"rate_limit_rps":{"description":"Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.","type":"integer","format":"uint32","default":10,"minimum":0},"require_auth":{"description":"Require an authenticated external identity for mutating calls.","type":"boolean","default":true}}},"McpTransport":{"type":"string","enum":["stdio","http"]},"MediaConfig":{"description":"Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.","type":"object","properties":{"audio_model":{"description":"Audio model name (Ollama model or OpenAI model). Default: \"whisper\".","type":"string","default":"whisper"},"audio_ollama_url":{"description":"Ollama base URL for audio transcription. Default: \"http://localhost:11434\".","type":"string","default":"http://localhost:11434"},"audio_provider":{"description":"Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".","type":"string","default":"none"},"max_audio_size_mb":{"description":"Maximum audio attachment size in MiB. Default: 20.","type":"integer","format":"uint","default":20,"minimum":0},"max_video_size_mb":{"description":"Maximum video attachment size in MiB. Default: 50.","type":"integer","format":"uint","default":50,"minimum":0},"video_max_frames":{"description":"Maximum video frames to extract per video. Default: 4.","type":"integer","format":"uint","default":4,"minimum":0},"video_provider":{"description":"Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".","type":"string","default":"none"}}},"MemoryConfig":{"description":"Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.","type":"object","properties":{"acl_enabled":{"description":"Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.","type":"boolean","default":false},"archive_after_days":{"description":"Archive daily/session files older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"auto_hydrate":{"description":"Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing","type":"boolean","default":true},"auto_save":{"description":"Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.","type":"boolean","default":true},"backend":{"description":"\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).","type":"string","default":"sqlite"},"conversation_retention_days":{"description":"For sqlite backend: prune conversation rows older than this many days","type":"integer","format":"uint32","default":3,"minimum":0},"daily_retention_days":{"description":"For sqlite backend: prune daily rows older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"embedding_cache_size":{"description":"Max embedding cache entries before LRU eviction","type":"integer","format":"uint","default":10000,"minimum":0},"embedding_dimensions":{"description":"Embedding vector dimensions","type":"integer","format":"uint","default":384,"minimum":0},"embedding_model":{"description":"Embedding model name (e.g. \"text-embedding-3-small\")","type":"string","default":"prx-local-hash-v1"},"embedding_provider":{"description":"Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"","type":"string","default":"local"},"events":{"description":"Raw/quasi-raw message event recording controls (`[memory.events]`).","$ref":"#/$defs/MemoryEventsConfig","default":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true}},"keyword_weight":{"description":"Weight for keyword BM25 in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.3},"legacy_conversation_turns_visible":{"description":"Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.","type":"boolean","default":true},"lucid_budget":{"description":"Token budget for lucid (replaces OPENPRX_LUCID_BUDGET)","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"lucid_cmd":{"description":"Path to lucid binary (replaces OPENPRX_LUCID_CMD)","type":["string","null"],"default":null},"lucid_failure_cooldown_ms":{"description":"Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)","type":"integer","format":"uint64","default":60000,"minimum":0},"lucid_local_hit_threshold":{"description":"Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)","type":"integer","format":"uint","default":3,"minimum":0},"lucid_recall_timeout_ms":{"description":"Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)","type":"integer","format":"uint64","default":5000,"minimum":0},"lucid_store_timeout_ms":{"description":"Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)","type":"integer","format":"uint64","default":3000,"minimum":0},"min_relevance_score":{"description":"Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4","type":"number","format":"double","default":0.4},"purge_after_days":{"description":"Purge archived files older than this many days","type":"integer","format":"uint32","default":30,"minimum":0},"semantic":{"description":"Semantic memory promotion controls (`[memory.semantic]`).","$ref":"#/$defs/MemorySemanticConfig","default":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30}},"sqlite_open_timeout_secs":{"description":"For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"sqlite_read_pool_size":{"description":"For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"vector_candidate_cap":{"description":"How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.","type":"integer","format":"uint","default":2000,"minimum":0},"vector_weight":{"description":"Weight for vector similarity in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.7}}},"MemoryEventsConfig":{"description":"Raw message event recording configuration (`[memory.events]`).","type":"object","properties":{"record_assistant_messages":{"description":"Record assistant replies.","type":"boolean","default":true},"record_tool_events":{"description":"Record tool/event payloads by default.","type":"boolean","default":false},"record_user_messages":{"description":"Record inbound/user messages.","type":"boolean","default":true}}},"MemorySemanticConfig":{"description":"Semantic memory promotion configuration (`[memory.semantic]`).","type":"object","properties":{"auto_promote_assistant_messages":{"description":"Auto-promote eligible assistant messages. Disabled by default to reduce noise.","type":"boolean","default":false},"auto_promote_user_messages":{"description":"Auto-promote eligible user messages into long-term semantic memories.","type":"boolean","default":true},"min_chars":{"description":"Minimum content length for semantic auto-promotion.","type":"integer","format":"uint","default":30,"minimum":0}}},"MemoryWebhookConfig":{"type":"object","properties":{"bind":{"description":"Socket address for the receiver (e.g. \"0.0.0.0:16899\").","type":"string","default":"0.0.0.0:16899"},"signing_secret":{"description":"Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.","type":["string","null"],"default":null},"token":{"description":"Required bearer token for incoming webhook events.","type":["string","null"],"default":null}}},"ModelOperationSetting":{"description":"The operations a `[[providers.models]]` entry may list.","type":"string","enum":["chat","embedding","decision_endpoint","rerank","image_generation","audio_generation","video_generation"]},"ModelPricing":{"description":"Per-model pricing entry (USD per 1M tokens).","type":"object","properties":{"cache_read":{"description":"Cache read input price per 1M tokens.","type":"number","format":"double","default":0.0},"cache_write":{"description":"Cache write/creation input price per 1M tokens.","type":"number","format":"double","default":0.0},"input":{"description":"Input price per 1M tokens","type":"number","format":"double","default":0.0},"output":{"description":"Output price per 1M tokens","type":"number","format":"double","default":0.0}}},"ModelRouteConfig":{"description":"Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"hint":{"description":"Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")","type":"string"},"level":{"type":["string","null"]},"model":{"description":"Model to use with that provider","type":"string"},"provider":{"description":"Provider to route to (must match a known provider name)","type":"string"},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true,"required":["hint","provider","model"]},"ModelSettings":{"description":"A model level plus explicit parameter overrides in `[model_settings.\"\"]`.","type":"object","properties":{"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"level":{"type":["string","null"]},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true},"MultimodalConfig":{"description":"Multimodal (image) handling configuration (`[multimodal]` section).","type":"object","properties":{"allow_remote_fetch":{"description":"Allow fetching remote image URLs (http/https). Disabled by default.","type":"boolean","default":false},"max_image_size_mb":{"description":"Maximum image payload size in MiB before base64 encoding.","type":"integer","format":"uint","default":5,"minimum":0},"max_images":{"description":"Maximum number of image attachments accepted per request.","type":"integer","format":"uint","default":4,"minimum":0}}},"NextcloudTalkConfig":{"description":"Nextcloud Talk bot configuration (webhook receive + OCS send API).","type":"object","properties":{"allowed_users":{"description":"Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Bot app token used for OCS API bearer auth.","type":"string"},"base_url":{"description":"Nextcloud base URL (e.g. \"https://cloud.example.com\").","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"webhook_secret":{"description":"Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).","type":["string","null"],"default":null}},"required":["base_url","app_token"]},"NgrokTunnelConfig":{"type":"object","properties":{"auth_token":{"description":"ngrok auth token","type":"string"},"domain":{"description":"Optional custom domain","type":["string","null"]}},"required":["auth_token"]},"NodeServerConfig":{"description":"Node daemon runtime config used by `prx-node`.","type":"object","properties":{"allowed_commands":{"description":"Command allowlist matched on first token.\n\nIn restricted mode this list is required unless explicitly set to `[\"*\"]`.","type":"array","default":["echo"],"items":{"type":"string"}},"bearer_token":{"description":"Required bearer token for /rpc.","type":"string","default":""},"blocked_commands":{"description":"Command denylist matched on first token. Always enforced.","type":"array","default":[],"items":{"type":"string"}},"exec_timeout_ms":{"description":"Default command timeout in milliseconds.","type":"integer","format":"uint64","default":15000,"minimum":0},"hmac_secret":{"description":"Optional HMAC signing secret.","type":["string","null"],"default":null},"listen_addr":{"description":"Listen address for node daemon.","type":"string","default":"127.0.0.1:8787"},"max_concurrent_tasks":{"description":"Maximum number of concurrent async command tasks.","type":"integer","format":"uint","default":8,"minimum":0},"max_output_bytes":{"description":"Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.","type":"integer","format":"uint","default":1048576,"minimum":0},"sandbox_root":{"description":"Sandbox root directory for read/write/cwd constraints.","type":"string","default":"."},"task_result_ttl_ms":{"description":"TTL for completed task results in milliseconds.","type":"integer","format":"uint64","default":3600000,"minimum":0},"tls_cert":{"description":"TLS certificate path (PEM).","type":["string","null"],"default":null},"tls_key":{"description":"TLS private key path (PEM).","type":["string","null"],"default":null},"tls_required":{"description":"Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.","type":"boolean","default":true}}},"NodesConfig":{"description":"Remote node proxy configuration for core-side RPC calls and node daemon defaults.","type":"object","properties":{"nodes":{"description":"Configured remote nodes.","type":"array","default":[],"items":{"$ref":"#/$defs/RemoteNodeConfig"}},"request_timeout_ms":{"description":"Default request timeout for node RPC calls.","type":"integer","format":"uint64","default":15000,"minimum":0},"retry_max":{"description":"Default max retries for node RPC calls.","type":"integer","format":"uint8","default":2,"maximum":255,"minimum":0},"server":{"description":"Embedded node server defaults used by `prx-node`.","$ref":"#/$defs/NodeServerConfig","default":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}}},"ObservabilityConfig":{"description":"Observability backend configuration (`[observability]` section).","type":"object","properties":{"backend":{"description":"\"none\" | \"log\" | \"prometheus\" | \"otel\"","type":"string","default":"none"},"otel_endpoint":{"description":"OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".","type":["string","null"],"default":null},"otel_service_name":{"description":"Service name reported to the OTel collector. Defaults to \"prx\".","type":["string","null"],"default":null}}},"OllamaProviderConfig":{"description":"Ollama-specific request options (`[providers.ollama]`).","type":"object","properties":{"num_ctx":{"description":"Explicit context window sent as Ollama `options.num_ctx`.","type":["integer","null"],"format":"uint","default":null,"minimum":0}}},"OsPagingConfig":{"description":"Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.","type":"object","properties":{"eviction_threshold":{"description":"Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.","type":"number","format":"double","default":0.7},"keep_recent_messages":{"description":"Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).","type":"integer","format":"uint","default":12,"minimum":0},"max_recalled_pages":{"description":"Maximum number of evicted pages (document chunks) recalled per turn.","type":"integer","format":"uint","default":10,"minimum":0},"proactive_retrieval":{"description":"Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.","type":"boolean","default":true},"retrieval_injection_role":{"description":"Role under which recalled pages are injected.","$ref":"#/$defs/RetrievalInjectionRole","default":"system"}}},"PluginsConfig":{"description":"WASM plugin runtime configuration.","type":"object","properties":{"enabled":{"description":"Load WASM plugins from `/plugins`. Default: `false`.","type":"boolean","default":false}},"additionalProperties":false},"ProviderModelConfig":{"description":"One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.","type":"object","properties":{"context_window":{"description":"The model's context window in tokens.","type":["integer","null"],"format":"uint32","minimum":0},"model":{"description":"The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.","type":["string","null"]},"native_tools":{"description":"Whether the model accepts native tool calls.","type":["boolean","null"]},"operations":{"description":"The complete list of operations the model executes; every operation not\nlisted is unsupported.","type":["array","null"],"items":{"$ref":"#/$defs/ModelOperationSetting"}},"provider":{"description":"The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.","type":"string"},"streaming":{"description":"Whether the model streams responses.","type":["boolean","null"]},"structured_output":{"description":"Whether the model honours a JSON-schema response format.","type":["boolean","null"]},"tool_call_dialect":{"description":"The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema_dialect":{"description":"The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]},"vision_input":{"description":"Whether the model accepts image input.","type":["boolean","null"]}},"required":["provider"]},"ProviderToolDialectConfig":{"description":"One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.","type":"object","properties":{"model":{"description":"The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.","type":["string","null"]},"provider":{"description":"The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.","type":"string"},"tool_call":{"description":"The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema":{"description":"The tool-schema dialect the endpoint accepts.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]}},"required":["provider"]},"ProvidersConfig":{"description":"Provider-specific runtime configuration (`[providers]`).","type":"object","properties":{"models":{"description":"Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.","type":"array","items":{"$ref":"#/$defs/ProviderModelConfig"}},"ollama":{"description":"Ollama-specific request options (`[providers.ollama]`).","$ref":"#/$defs/OllamaProviderConfig","default":{"num_ctx":null}},"tool_dialects":{"description":"Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).","type":"array","items":{"$ref":"#/$defs/ProviderToolDialectConfig"}}}},"ProxyConfig":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).","type":"object","properties":{"all_proxy":{"description":"Fallback proxy URL for all schemes.","type":["string","null"],"default":null},"http_proxy":{"description":"Proxy URL for HTTP requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"https_proxy":{"description":"Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"no_proxy":{"description":"No-proxy bypass list. Same format as NO_PROXY.","type":"array","default":[],"items":{"type":"string"}},"scope":{"description":"Proxy application scope.","$ref":"#/$defs/ProxyScope","default":"prx"},"services":{"description":"Service selectors used when scope = \"services\".","type":"array","default":[],"items":{"type":"string"}}}},"ProxyScope":{"description":"Proxy application scope — determines which outbound traffic uses the proxy.","oneOf":[{"description":"Use system environment proxy variables only.","type":"string","const":"environment"},{"description":"Apply proxy to all OpenPRX-managed HTTP traffic (default).","type":"string","const":"prx"},{"description":"Apply proxy only to explicitly listed service selectors.","type":"string","const":"services"}]},"QQConfig":{"description":"QQ Official Bot configuration (Tencent QQ Bot SDK)","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs. Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from QQ Bot developer console","type":"string"},"app_secret":{"description":"App Secret from QQ Bot developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["app_id","app_secret"]},"QueryClassificationConfig":{"description":"Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.","type":"object","properties":{"rules":{"description":"Classification rules evaluated in priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/ClassificationRule"}}}},"RamfluxAccountConfig":{"description":"Persona for one ramflux AI account. Missing fields fall back to the global agent.","type":"object","properties":{"cross_conversation_retrieval":{"description":"Cross-conversation memory retrieval. Off unless the owner sets it.","type":"boolean","default":false},"model":{"type":["string","null"],"default":null},"provider":{"type":["string","null"],"default":null},"scope_profile":{"type":["string","null"],"default":null},"system_prompt_file":{"description":"Path to a system-prompt file. Relative paths are resolved from the workspace.","type":["string","null"],"default":null}},"additionalProperties":false},"RamfluxAttachmentFetch":{"description":"Per-turn caps for `attachment.fetch`.","type":"object","properties":{"max_bytes":{"type":"integer","format":"uint64","default":5242880,"minimum":0},"max_per_turn":{"type":"integer","format":"uint8","default":4,"maximum":255,"minimum":0}},"additionalProperties":false},"RamfluxAuthorizationMode":{"description":"How prx combines its own setting with `bridge.hello.authorization`.","oneOf":[{"description":"Use the agent-host value. Until hello arrives, the effective mode is supervised.","type":"string","const":"follow_rf"},{"description":"Always supervised, even when the agent-host declares full.","type":"string","const":"supervised"},{"description":"Full only when the agent-host also declares full. Config alone never yields full.","type":"string","const":"full"}]},"RamfluxConfig":{"description":"Local ramflux agent-host bridge (`[channels_config.ramflux]`).","type":"object","properties":{"accounts":{"type":"object","additionalProperties":{"$ref":"#/$defs/RamfluxAccountConfig"},"default":{}},"allowed_block_types":{"type":"array","default":["Text","Markdown","Heading","KeyValue","Metric","List","TableFallback","Form","Input","Select","Progress","LogStream","Warning","Error","Success","Approval","ActionGroup","FilePreview","Fallback"],"items":{"type":"string"}},"attachment_fetch":{"$ref":"#/$defs/RamfluxAttachmentFetch","default":{"max_bytes":5242880,"max_per_turn":4}},"authorization_mode":{"$ref":"#/$defs/RamfluxAuthorizationMode","default":"follow_rf"},"encrypt_at_rest":{"type":"boolean","default":true},"max_in_flight_per_conversation":{"type":"integer","format":"uint8","default":1,"maximum":255,"minimum":0},"on_new_message":{"$ref":"#/$defs/RamfluxOnNewMessage","default":"queue"},"socket_path":{"description":"Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.","type":["string","null"],"default":null},"surface_limits":{"$ref":"#/$defs/RamfluxSurfaceLimits","default":{"max_actions":16,"max_blocks":32,"max_bytes":65536}},"turn_wall_clock_secs":{"description":"Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.","type":"integer","format":"uint64","default":120,"minimum":0}},"additionalProperties":false},"RamfluxOnNewMessage":{"description":"What to do with a new inbound message while a turn for that conversation is running.","type":"string","enum":["queue","interrupt"]},"RamfluxSurfaceLimits":{"description":"Limits for `reply.surface` blocks and actions.","type":"object","properties":{"max_actions":{"type":"integer","format":"uint32","default":16,"minimum":0},"max_blocks":{"type":"integer","format":"uint32","default":32,"minimum":0},"max_bytes":{"type":"integer","format":"uint32","default":65536,"minimum":0}},"additionalProperties":false},"ReliabilityCircuitBreakerConfig":{"description":"Process-local provider circuit policy (`[reliability.circuit_breaker]`).","type":"object","properties":{"enabled":{"description":"Enable protection for factory-built provider chains.","type":"boolean","default":true},"failure_threshold":{"description":"Consecutive transient failures that open a circuit (at least 1).","type":"integer","format":"uint32","default":5,"minimum":0},"max_open_secs":{"description":"Maximum doubled window, between open_secs and 3600 seconds.","type":"integer","format":"uint64","default":300,"minimum":0},"open_secs":{"description":"Initial open window in seconds (at least 1).","type":"integer","format":"uint64","default":30,"minimum":0}}},"ReliabilityConfig":{"description":"Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.","type":"object","properties":{"acknowledge_single_provider_risk":{"description":"Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.","type":"boolean","default":false},"api_keys":{"description":"Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.","type":"array","default":[],"items":{"type":"string"}},"channel_initial_backoff_secs":{"description":"Initial backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":2,"minimum":0},"channel_max_backoff_secs":{"description":"Max backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":60,"minimum":0},"circuit_breaker":{"description":"Per-provider consecutive failure protection.","$ref":"#/$defs/ReliabilityCircuitBreakerConfig","default":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30}},"fallback_providers":{"description":"Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).","type":"array","default":[],"items":{"type":"string"}},"model_fallbacks":{"description":"Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`","type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"default":{}},"provider_backoff_ms":{"description":"Base backoff (ms) for provider retry delay.","type":"integer","format":"uint64","default":500,"minimum":0},"provider_retries":{"description":"Retries per provider before failing over.","type":"integer","format":"uint32","default":2,"minimum":0},"scheduler_poll_secs":{"description":"Scheduler polling cadence in seconds.","type":"integer","format":"uint64","default":15,"minimum":0},"scheduler_retries":{"description":"Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.","type":"integer","format":"uint32","default":2,"minimum":0}}},"RemoteNodeConfig":{"description":"A remote node target for core-side node proxy calls.","type":"object","properties":{"bearer_token":{"description":"Bearer token for node RPC authentication.","type":"string"},"endpoint":{"description":"Base endpoint (e.g. \"http://127.0.0.1:8787\").","type":"string"},"hmac_secret":{"description":"Optional request signing key (HMAC-SHA256).","type":["string","null"],"default":null},"id":{"description":"Stable node ID used by the nodes tool.","type":"string"},"retry_max":{"description":"Optional per-node retry override.","type":["integer","null"],"format":"uint8","default":null,"maximum":255,"minimum":0},"timeout_ms":{"description":"Optional per-node timeout override.","type":["integer","null"],"format":"uint64","default":null,"minimum":0}},"required":["id","endpoint","bearer_token"]},"RetrievalInjectionRole":{"description":"Where recalled context pages are injected back into the request.","oneOf":[{"description":"Inject recalled pages as a leading `system` message (not user-visible).","type":"string","const":"system"},{"description":"Inject recalled pages as a leading `user` message.","type":"string","const":"user"}]},"RouterConfig":{"description":"Heuristic LLM router configuration (`[router]` section).","type":"object","properties":{"alpha":{"description":"Similarity score weight. Phase 1 keeps this at `0.0`.","type":"number","format":"float","default":0.0},"beta":{"description":"Capability score weight.","type":"number","format":"float","default":0.5},"delta":{"description":"Cost penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"epsilon":{"description":"Latency penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"gamma":{"description":"Elo score weight.","type":"number","format":"float","default":0.30000001192092896},"knn_k":{"description":"Number of nearest neighbors considered for voting. Default: `7`.","type":"integer","format":"uint","default":7,"minimum":0},"knn_min_records":{"description":"Minimum history records before KNN affects routing. Default: `10`.","type":"integer","format":"uint","default":10,"minimum":0},"models":{"description":"Candidate model registry.","type":"array","default":[],"items":{"$ref":"#/$defs/RouterModelConfig"}}}},"RouterModelConfig":{"description":"Static router metadata for one model candidate.","type":"object","properties":{"categories":{"description":"Capability categories such as `conversation`, `code`, or `analysis`.","type":"array","default":[],"items":{"type":"string"}},"cost_per_million_tokens":{"description":"USD cost per million tokens.","type":"number","format":"float","default":0.0},"elo_rating":{"description":"Initial Elo rating.","type":"number","format":"float","default":1000.0},"latency_ms":{"description":"Average latency in milliseconds.","type":"integer","format":"uint32","default":2000,"minimum":0},"max_context":{"description":"Maximum context window in tokens.","type":"integer","format":"uint","default":1000000,"minimum":0},"model_id":{"description":"Model identifier without provider prefix.","type":"string"},"provider":{"description":"Provider identifier.","type":"string"},"reserved_output_tokens":{"description":"Output tokens reserved for this model when planning input context.","type":["integer","null"],"format":"uint","minimum":0}},"required":["model_id","provider"]},"RuntimeConfig":{"description":"Runtime adapter configuration (`[runtime]` section).","type":"object","properties":{"codex_reasoning_effort":{"description":"Codex reasoning effort","type":["string","null"],"default":null},"codex_stream_idle_timeout_secs":{"description":"Codex stream idle timeout in seconds","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"docker":{"description":"Docker runtime settings (used when `kind = \"docker\"`).","$ref":"#/$defs/DockerRuntimeConfig","default":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true}},"idle_hang_secs":{"description":"Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"kind":{"description":"Runtime kind (`native` | `docker`).","type":"string","default":"native"},"long_task_warn_secs":{"description":"Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"managed_cgroup_root":{"description":"Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.","type":["string","null"],"default":null},"max_blocking_threads":{"description":"Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"reasoning_enabled":{"description":"Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported","type":["boolean","null"],"default":null},"shell_env_allowlist":{"description":"Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.","type":"array","default":[],"items":{"type":"string"}},"workdir":{"description":"Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.","type":["string","null"],"default":null}}},"SchedulerConfig":{"description":"Scheduler configuration for periodic task execution (`[scheduler]` section).","type":"object","properties":{"claim_lease_secs":{"description":"Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.","type":"integer","format":"uint64","default":90,"minimum":0},"max_tasks":{"description":"Maximum number of persisted scheduled tasks.","type":"integer","format":"uint","default":64,"minimum":0}}},"ScopeConfig":{"description":"Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```","type":"object","properties":{"assign_owners":{"description":"Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.","type":"array","default":[],"items":{"type":"string"}},"default":{"description":"Default action when no rule matches: \"allow\" (default) or \"deny\".","$ref":"#/$defs/ScopeDefault","default":"allow"},"rules":{"description":"Ordered list of scope rules evaluated top-to-bottom.","type":"array","default":[],"items":{"$ref":"#/$defs/ScopeRule"}}}},"ScopeDefault":{"description":"What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.","oneOf":[{"description":"Unmatched tool calls are allowed (the default).","type":"string","const":"allow"},{"description":"Unmatched tool calls are refused.","type":"string","const":"deny"}]},"ScopeRule":{"description":"A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.","type":"object","properties":{"assign_allow":{"description":"Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".","type":"array","default":[],"items":{"type":"string"}},"assign_deny":{"description":"Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.","type":"array","default":[],"items":{"type":"string"}},"channel":{"description":"Match by channel name: \"signal\", \"telegram\", \"discord\", etc.","type":["string","null"]},"chat_type":{"description":"Match by chat type: \"direct\", \"group\", or \"*\" for any type.","type":["string","null"]},"send_allow":{"description":"Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.","type":"array","default":[],"items":{"type":"string"}},"send_deny":{"description":"Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.","type":"array","default":[],"items":{"type":"string"}},"tools_allow":{"description":"Tool whitelist: only these tools are allowed (empty = all tools permitted).","type":"array","default":[],"items":{"type":"string"}},"tools_deny":{"description":"Tool blacklist: these tools are denied regardless of allow list.","type":"array","default":[],"items":{"type":"string"}},"user":{"description":"Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.","type":["string","null"]}}},"SecretsConfig":{"description":"Secrets encryption configuration (`[secrets]` section).","type":"object","properties":{"encrypt":{"description":"Enable encryption for API keys and tokens in config.toml","type":"boolean","default":true}}},"SecurityConfig":{"description":"Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.","type":"object","properties":{"audit":{"description":"Audit logging configuration","$ref":"#/$defs/AuditConfig","default":{"log_path":"audit.log","max_size_mb":100}},"workspace_hooks":{"description":"Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.","$ref":"#/$defs/WorkspaceHooks"}}},"SelfSystemConfig":{"description":"Self-system experimental automation config (`[self_system]`).","type":"object","properties":{"evolution_config_path":{"description":"Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG)","type":["string","null"],"default":null},"evolution_debug_raw":{"description":"Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW)","type":"boolean","default":false},"evolution_interval_hours":{"description":"Evolution scheduler interval in hours (daemon mode).","type":"integer","format":"uint32","default":24,"minimum":0},"evolution_judge_timeout_secs":{"description":"Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.","type":"integer","format":"uint64","default":180,"minimum":0},"evolution_model_max_micro_usd":{"description":"Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.","type":"integer","format":"uint64","default":0,"minimum":0},"evolution_model_max_tokens":{"description":"Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.","type":"integer","format":"uint64","default":16384,"minimum":0},"fitness":{"description":"Daily fitness snapshot policy.","$ref":"#/$defs/FitnessConfig","default":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"}},"fitness_interval_hours":{"description":"Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.","type":"integer","format":"uint64","default":24,"minimum":0}}},"SessionsSpawnConfig":{"description":"Sessions spawn configuration (`[sessions_spawn]` section).","type":"object","properties":{"cleanup_on_complete":{"description":"Remove worker workspace directory after process-mode completion.","type":"boolean","default":true},"default_mode":{"description":"Default execution mode for sessions_spawn (`task` or `process`).","type":"string","default":"task"},"process_memory_strategy":{"description":"Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.","type":"string","default":"shared_fabric"},"worker_workspace_root":{"description":"Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.","type":["string","null"],"default":null}}},"SignalConfig":{"type":"object","properties":{"account":{"description":"E.164 phone number of the signal-cli account (e.g. \"+1234567890\").","type":"string"},"allowed_from":{"description":"Allowed sender phone numbers (E.164) or \"*\" for all.","type":"array","default":[],"items":{"type":"string"}},"cli_path":{"description":"Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).","type":["string","null"],"default":null},"daemon_http_port":{"description":"Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"daemon_mode":{"description":"Deprecated: ignored. Accepted for backward compatibility with older config files.","type":["boolean","null"],"default":null},"data_dir":{"description":"signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_id":{"description":"Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group","type":["string","null"],"default":null},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"http_url":{"description":"Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.","type":"string","default":"http://localhost:8080"},"ignore_attachments":{"description":"Skip messages that are attachment-only (no text body).","type":"boolean","default":false},"ignore_stories":{"description":"Skip incoming story messages.","type":"boolean","default":false},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"mode":{"description":"Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.","type":["string","null"],"default":null},"startup_timeout_ms":{"description":"Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.","type":"integer","format":"uint64","default":30000,"minimum":0},"storm_protection":{"description":"Signal ingress storm protection controls.","$ref":"#/$defs/SignalStormProtectionConfig","default":{"abnormal_threshold":10,"abnormal_window_secs":60,"breaker_duration_secs":300,"dedupe_ttl_secs":60,"min_reply_interval_secs":2}}},"required":["account"]},"SignalStormProtectionConfig":{"type":"object","properties":{"abnormal_threshold":{"description":"Non-user event threshold within `abnormal_window_secs` before tripping the breaker.","type":"integer","format":"uint","default":10,"minimum":0},"abnormal_window_secs":{"description":"Sliding window in seconds for non-user event counting.","type":"integer","format":"uint64","default":60,"minimum":0},"breaker_duration_secs":{"description":"Circuit breaker duration in seconds after threshold is reached.","type":"integer","format":"uint64","default":300,"minimum":0},"dedupe_ttl_secs":{"description":"Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.","type":"integer","format":"uint64","default":60,"minimum":0},"min_reply_interval_secs":{"description":"Minimum interval in seconds between replies for the same `(channel + reply_target)`.","type":"integer","format":"uint64","default":2,"minimum":0}}},"SkillRagConfig":{"description":"Dynamic skill retrieval configuration (`[skill_rag]` section).","type":"object","properties":{"top_k":{"description":"How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).","type":"integer","format":"uint","default":32,"minimum":0}}},"SkillSuiteRegistration":{"description":"The frozen suite that governs one skill's proposals.","type":"object","properties":{"skill_id":{"description":"The skill the suite governs.","type":"string"},"suite_digest":{"description":"SHA-256 digest (64 lowercase hex digits) of the frozen suite.","type":"string"}},"additionalProperties":false,"required":["skill_id","suite_digest"]},"SkillsConfig":{"description":"Skills loading configuration (`[skills]` section).","type":"object","properties":{"open_skills_dir":{"description":"Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.","type":["string","null"],"default":null},"openclaw_skills_dir":{"description":"Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.","type":["string","null"],"default":null}}},"SkillsLifecycleConfig":{"description":"`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.","type":"object","properties":{"allow_executable_proposals":{"description":"Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.","type":"boolean","default":false},"enabled":{"description":"Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.","type":"boolean","default":false},"max_concurrent_evaluations":{"description":"Most evaluations running at once.","type":"integer","format":"uint32","default":1,"minimum":0},"max_edit_fraction":{"description":"Edit budget of a proposal as a fraction of the skill body, in (0, 1].","type":"number","format":"double","default":0.2},"max_edit_tokens":{"description":"Edit budget of a proposal, in tokens.","type":"integer","format":"uint64","default":300,"minimum":0},"max_proposals_per_cycle":{"description":"Most proposals one cycle may start.","type":"integer","format":"uint32","default":1,"minimum":0},"min_cases_floor":{"description":"Smallest `min_cases` a governing suite may declare. Below 3 is refused.","type":"integer","format":"uint32","default":3,"minimum":0},"mode":{"description":"`draft_only`, `shadow` or `auto`.","$ref":"#/$defs/SkillsLifecycleModeConfig","default":"draft_only"},"owner_scope":{"description":"The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.","type":["string","null"],"default":null},"require_holdout":{"description":"A governing suite must have a holdout split. `false` is refused.","type":"boolean","default":true},"storage_dir":{"description":"Store location under the workspace. Only the default is supported.","type":"string","default":"self/skill-lifecycle"},"suites":{"description":"The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.","type":"array","default":[],"items":{"$ref":"#/$defs/SkillSuiteRegistration"}}},"additionalProperties":false},"SkillsLifecycleModeConfig":{"description":"What the lifecycle may do. Mirrors `LifecycleMode`.","oneOf":[{"description":"Drafts and reviews only.","type":"string","const":"draft_only"},{"description":"Drafts plus evaluation and gating; never publishes.","type":"string","const":"shadow"},{"description":"Publishes an eligible proposal after every gate.","type":"string","const":"auto"}]},"SlackConfig":{"description":"Slack bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Slack user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Slack app-level token for Socket Mode (xapp-...).","type":["string","null"]},"bot_token":{"description":"Slack bot OAuth token (xoxb-...).","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["bot_token"]},"SmartGroupConfig":{"description":"Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).","type":"object","properties":{"classifier_max_context_messages":{"description":"How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.","type":"integer","format":"uint","default":3,"minimum":0},"classifier_model":{"description":"Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.","type":"string","default":""},"classifier_provider":{"description":"Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.","type":"string","default":""},"classifier_temperature":{"description":"Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).","type":"number","format":"double","default":0.0},"classifier_timeout_secs":{"description":"Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.","type":"integer","format":"uint64","default":5,"minimum":0}}},"StorageConfig":{"description":"Persistent storage configuration (`[storage]` section).","type":"object","properties":{"provider":{"description":"Storage provider settings (e.g. sqlite, postgres).","$ref":"#/$defs/StorageProviderSection","default":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}}},"StorageProviderConfig":{"description":"Storage provider backend configuration (e.g. postgres connection details).","type":"object","properties":{"connect_timeout_secs":{"description":"Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"db_url":{"description":"Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.","type":["string","null"],"default":null},"pool_max_size":{"description":"Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.","type":"integer","format":"uint","default":32,"minimum":0},"provider":{"description":"Storage engine key (e.g. \"postgres\", \"sqlite\").","type":"string","default":""},"schema":{"description":"Database schema for SQL backends.","type":"string","default":"public"},"table":{"description":"Table name for memory entries.","type":"string","default":"memories"}}},"StorageProviderSection":{"description":"Wrapper for the storage provider configuration section.","type":"object","properties":{"config":{"description":"Storage provider backend settings.","$ref":"#/$defs/StorageProviderConfig","default":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"StreamMode":{"description":"Streaming mode for channels that support progressive message updates.","oneOf":[{"description":"No streaming -- send the complete response as a single message (default).","type":"string","const":"off"},{"description":"Update a draft message with every flush interval.","type":"string","const":"partial"}]},"TailscaleTunnelConfig":{"type":"object","properties":{"funnel":{"description":"Use Tailscale Funnel (public internet) vs Serve (tailnet only)","type":"boolean","default":false},"hostname":{"description":"Optional hostname override","type":["string","null"]}}},"TaskRoutingConfig":{"description":"Lightweight pre-LLM task routing.","type":"object","properties":{"default_intent":{"description":"Fallback intent when no rule matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"rules":{"description":"Rules evaluated in descending priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/TaskRoutingRule"}}}},"TaskRoutingIntentConfig":{"description":"Task-routing default and rule intent.","type":"string","enum":["simple","delegate","stream"]},"TaskRoutingRule":{"description":"A single task-routing rule.","type":"object","properties":{"intent":{"description":"Route intent to apply when a keyword matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"model_hint":{"description":"Optional model hint/raw model for non-delegated requests.","type":["string","null"],"default":null},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0},"sub_agent_model":{"description":"Optional raw sub-agent model override for delegated tasks.","type":["string","null"],"default":null}}},"TelegramConfig":{"description":"Telegram bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Telegram user IDs or usernames. Empty = deny all.","type":"array","items":{"type":"string"}},"bot_token":{"description":"Telegram Bot API token (from @BotFather).","type":"string"},"draft_update_interval_ms":{"description":"Minimum interval (ms) between draft message edits to avoid rate limits.","type":"integer","format":"uint64","default":1000,"minimum":0},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"interrupt_on_new_message":{"description":"When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.","type":"boolean","default":false},"stream_mode":{"description":"Streaming mode for progressive response delivery via message edits.","$ref":"#/$defs/StreamMode","default":"off"}},"required":["bot_token","allowed_users"]},"ToolCallDialectSetting":{"description":"The tool-call grammars an operator may declare for an endpoint.","oneOf":[{"description":"Only the native `tool_calls` array is a tool call (the default).","type":"string","const":"native"},{"description":"Additionally read `{json}` from the content,\nfor a tool name the request registered.","type":"string","const":"xml_function_tags"}]},"ToolSchemaDialectSetting":{"description":"The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.","oneOf":[{"description":"The published document, byte for byte (the default).","type":"string","const":"raw"},{"description":"The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.","type":"string","const":"no_root_combinators"}]},"ToolTieringConfig":{"description":"Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.","type":"object","properties":{"always_exclude":{"description":"Tool names excluded from capability publication.","type":"array","default":[],"items":{"type":"string"}},"always_include":{"description":"Tool names preferred for direct publication, subject to admission gates.","type":"array","default":[],"items":{"type":"string"}},"channel_exclude":{"description":"Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefaults to [`DEFAULT_CHANNEL_EXCLUDED_TOOLS`]; set to `[]` to expose the\nfull operator surface on channels again.","type":"array","default":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","skills_manage","memory_reindex","document_sync","document_ingest"],"items":{"type":"string"}}}},"TunnelConfig":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.","type":"object","properties":{"cloudflare":{"description":"Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).","anyOf":[{"$ref":"#/$defs/CloudflareTunnelConfig"},{"type":"null"}],"default":null},"custom":{"description":"Custom tunnel command configuration (used when `provider = \"custom\"`).","anyOf":[{"$ref":"#/$defs/CustomTunnelConfig"},{"type":"null"}],"default":null},"ngrok":{"description":"ngrok tunnel configuration (used when `provider = \"ngrok\"`).","anyOf":[{"$ref":"#/$defs/NgrokTunnelConfig"},{"type":"null"}],"default":null},"provider":{"description":"Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.","type":"string","default":"none"},"tailscale":{"description":"Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).","anyOf":[{"$ref":"#/$defs/TailscaleTunnelConfig"},{"type":"null"}],"default":null}}},"UserPolicyConfig":{"description":"Startup user policy entry (`[[user_policies]]`).","type":"object","properties":{"blocked_patterns":{"type":"array","default":[],"items":{"type":"string"}},"projects":{"type":"array","default":[],"items":{"type":"string"}},"role":{"type":"string","default":"guest"},"user_id":{"type":"string"},"visibility_ceiling":{"type":"string","default":"private"}},"required":["user_id"]},"WacliConfig":{"description":"wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```","type":"object","properties":{"allow_unsigned_loopback":{"description":"Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).","type":"boolean","default":false},"allowed_from":{"description":"Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.","type":"array","default":["*"],"items":{"type":"string"}},"bot_jid":{"description":"Bot's own JID, used for reply-to-bot mention detection.","type":["string","null"],"default":null},"bot_lid":{"description":"The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.","type":["string","null"],"default":null},"bot_number":{"description":"Bot's own phone number (digits), used for `@` mention detection.","type":["string","null"],"default":null},"cli_path":{"description":"Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.","type":["string","null"],"default":null},"group_reply_mode":{"description":"Smart group-reply mode. When `None`, derived from `mention_only`.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"host":{"description":"REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].","type":["string","null"],"writeOnly":true},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"outbound_media_workspace_only":{"description":"Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.","type":"boolean","default":false},"port":{"description":"REMOVED: legacy JSON-RPC daemon port. See `host`.","type":["integer","null"],"format":"uint16","maximum":65535,"minimum":0,"writeOnly":true},"self_chat_mode":{"description":"Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.","type":"boolean","default":false},"store_dir":{"description":"wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.","type":["string","null"],"default":null},"webhook_listen":{"description":"Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").","type":"string","default":"127.0.0.1:16868"},"webhook_path":{"description":"HTTP path the webhook server serves (default: \"/wacli\").","type":"string","default":"/wacli"},"webhook_secret":{"description":"HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.","type":["string","null"],"default":null}}},"WebSearchConfig":{"description":"Web search tool configuration (`[web_search]` section).","type":"object","properties":{"brave_api_key":{"description":"Brave Search API key (required if provider is \"brave\")","type":["string","null"],"default":null},"fetch_max_chars":{"description":"Maximum characters returned by `web_fetch` (default 10000)","type":"integer","format":"uint","default":50000,"minimum":0},"max_results":{"description":"Maximum results per search (1-20)","type":"integer","format":"uint","default":15,"minimum":0},"provider":{"description":"Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)","type":"string","default":"duckduckgo"},"timeout_secs":{"description":"Request timeout in seconds","type":"integer","format":"uint64","default":15,"minimum":0}}},"WebhookConfig":{"description":"Webhook channel configuration.","type":"object","properties":{"port":{"description":"Port to listen on for incoming webhooks.","type":"integer","format":"uint16","maximum":65535,"minimum":0},"secret":{"description":"Optional shared secret for webhook signature verification.","type":["string","null"]}},"required":["port"]},"WhatsAppConfig":{"description":"WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.","type":"object","properties":{"access_token":{"description":"Access token from Meta Business Suite (Cloud API mode)","type":["string","null"],"default":null},"allowed_numbers":{"description":"Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"app_secret":{"description":"App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"pair_code":{"description":"Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one","type":["string","null"],"default":null},"pair_phone":{"description":"Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used","type":["string","null"],"default":null},"phone_number_id":{"description":"Phone number ID from Meta Business API (Cloud API mode)","type":["string","null"],"default":null},"read_pool_size":{"description":"Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"session_path":{"description":"Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs","type":["string","null"],"default":null},"verify_token":{"description":"Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode","type":["string","null"],"default":null},"ws_url":{"description":"WebSocket URL override (replaces WHATSAPP_WS_URL)","type":["string","null"],"default":null}}},"WorkspaceHooks":{"description":"Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).","oneOf":[{"description":"They do not run (the default); `prx doctor` and `hooks_status` say so.","type":"string","const":"off"},{"description":"They run, in a cleared environment and a dedicated directory beside\n`config.toml`.","type":"string","const":"on"}]},"WorkspaceMcpServers":{"description":"Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).","oneOf":[{"description":"None: a workspace file may only narrow the servers defined in\n`config.toml`.","type":"string","const":"off"},{"description":"HTTP servers (still refused when they target a private address).","type":"string","const":"http_only"},{"description":"HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.","type":"string","const":"stdio"}]},"XinConfig":{"description":"Configuration for the xin autonomous task engine (`[xin]`).","type":"object","properties":{"adopt_legacy_tasks":{"description":"Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).","type":"boolean","default":false},"interval_minutes":{"description":"Tick interval in minutes (minimum 1). Default: 5.","type":"integer","format":"uint32","default":5,"minimum":0},"stale_timeout_minutes":{"description":"Minutes after which a running task is marked stale. Default: 60.","type":"integer","format":"uint32","default":60,"minimum":0}}},"AgentMessaging":{"description":"Owner-controlled inbound session messaging (enabled unless explicitly off).","type":"object","properties":{"inbound":{"type":"boolean","default":true}}}}} From b605d2f452de506dd146f1b06239c1706f6fabb8 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:40:03 +0400 Subject: [PATCH 0133/1567] feat(config): hide no tools from channel sessions by default channel_exclude now defaults to an empty list. The former built-in set is kept as RECOMMENDED_CHANNEL_EXCLUDED_TOOLS for operators who want to copy it. --- docs/channels.md | 18 ++++----- docs/tools.md | 8 ++-- src/channels/tests/provider_switch.rs | 3 +- src/config/manage/plan.rs | 2 +- src/config/mod.rs | 2 +- src/config/schema/security.rs | 39 +++++++++++-------- src/config/schema/tests/channels.rs | 6 +-- .../runner/tests/tool_selection.rs | 6 +-- src/tools/sessions_spawn/tests/tool_setup.rs | 2 +- tests/support/legacy_tool_surface_budget.rs | 21 +++++----- 10 files changed, 57 insertions(+), 50 deletions(-) diff --git a/docs/channels.md b/docs/channels.md index 0b27c56b1..c4e89365c 100644 --- a/docs/channels.md +++ b/docs/channels.md @@ -167,21 +167,21 @@ reply such as "yes" does not manufacture a grant, and lack of an approval UI does not authorize automatic execution. Review and revoke behavior is specified in [Approvals](decision-engine.md#approvals). -A channel message is written by a conversation partner, not by the operator at -the host, so a channel turn runs under a narrower tool policy than terminal chat -or the gateway. On top of ordinary per-turn capability routing, the -`[tool_tiering] channel_exclude` list is folded into that turn's `always_exclude` -and defaults to the operations/development surface: +A channel turn runs under the same tool policy as terminal chat or the +gateway: nothing is hidden by default. On top of ordinary per-turn capability +routing, the `[tool_tiering] channel_exclude` list (empty by default) is folded +into that turn's `always_exclude`. An operator who wants a narrower channel +surface can list the operations/development tools, for example: `wasm_plugins_manage`, `wasm_plugin_reload`, `wasm_plugins_status`, `hooks_manage`, `hooks_status`, `proxy_config`, `config_reload`, `gateway`, `mcp_status`, `nodes`, `skills_manage`, `memory_reindex`, `document_sync`, `document_ingest`. -These are not advertised to the model on a channel turn even when the message -names their capability, which both removes their schemas from every request and -puts runtime reconfiguration out of reach of a misread sentence. Naming one in -`always_include` restores it; `channel_exclude = []` drops the default entirely. +Names listed in `channel_exclude` are not advertised to the model on a channel +turn even when the message names their capability. Naming one in +`always_include` restores it; an empty `channel_exclude` (the default) hides +nothing. See [Tools](tools.md#per-turn-capability-routing). ## Sub-Agents On A Gateway Without Signal diff --git a/docs/tools.md b/docs/tools.md index 3b7bcec38..fb0742420 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -284,16 +284,16 @@ every model-running entrypoint: still *runs*: skills are usable, MCP and WASM plugin tools are callable, and hooks fire on the turn exactly as they do in terminal chat. What `channel_exclude` removes is the operations surface — the tools that manage or -inspect those subsystems — because a channel turn is driven by a conversation -partner rather than by the operator. The default excluded set is -`DEFAULT_CHANNEL_EXCLUDED_TOOLS` (`src/config/schema/security.rs`): +inspect those subsystems. The default excluded set is empty. The list an +operator may copy into `channel_exclude` to hide them is +`RECOMMENDED_CHANNEL_EXCLUDED_TOOLS` (`src/config/schema/security.rs`): `wasm_plugins_manage`, `wasm_plugin_reload`, `wasm_plugins_status`, `hooks_manage`, `hooks_status`, `proxy_config`, `config_reload`, `gateway`, `mcp_status`, `nodes`, `skills_manage`, `memory_reindex`, `document_sync`, `document_ingest`. -Nothing else is hidden by the channel surface. See +Nothing is hidden by the channel surface unless `channel_exclude` lists it. See [Per-turn capability routing](#per-turn-capability-routing) for how to override it. diff --git a/src/channels/tests/provider_switch.rs b/src/channels/tests/provider_switch.rs index a0f67a5cb..bb7123787 100644 --- a/src/channels/tests/provider_switch.rs +++ b/src/channels/tests/provider_switch.rs @@ -353,6 +353,7 @@ fn channel_message_runtime_hides_the_operations_tools_by_default() { let manager = crate::config::new_shared({ let mut config = Config::default(); config.autonomy.level = crate::security::AutonomyLevel::Supervised; + config.tool_tiering = crate::config::ToolTieringConfig::with_recommended_channel_exclusions(); config }); let generation = manager.pin(); @@ -366,7 +367,7 @@ fn channel_message_runtime_hides_the_operations_tools_by_default() { generation.effective.tool_tiering.always_exclude.is_empty(), "fixture must start from an operator config that excludes nothing" ); - for hidden in crate::config::DEFAULT_CHANNEL_EXCLUDED_TOOLS { + for hidden in &generation.effective.tool_tiering.channel_exclude { assert!( snapshot .tool_tiering diff --git a/src/config/manage/plan.rs b/src/config/manage/plan.rs index 1c053c024..8860aeae2 100644 --- a/src/config/manage/plan.rs +++ b/src/config/manage/plan.rs @@ -3252,7 +3252,7 @@ mod tests { ), ( "operator tools exposed to channel sessions (R-SECRETSfg P27)", - |_| {}, + |c| c.tool_tiering = crate::config::ToolTieringConfig::with_recommended_channel_exclusions(), |c| c.tool_tiering.channel_exclude.clear(), Some("tool_tiering"), ), diff --git a/src/config/mod.rs b/src/config/mod.rs index 86ee49ca8..030e7ad24 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -25,7 +25,7 @@ pub(crate) use schema::set_runtime_proxy_config; pub use schema::{ A2aConfig, A2aPeer, AgentCompactionConfig, AgentCompactionMode, AgentConfig, AgentLimits, AuditConfig, AuthConfig, AutonomyConfig, BrowserComputerUseConfig, BrowserConfig, ChannelsConfig, ChatConfig, ClassificationRule, - ComposioConfig, Config, CostConfig, CronConfig, DEFAULT_CHANNEL_EXCLUDED_TOOLS, DelegateAgentConfig, DiscordConfig, + ComposioConfig, Config, CostConfig, CronConfig, DelegateAgentConfig, DiscordConfig, DmPolicy, DockerRuntimeConfig, EMBEDDING_DEFAULT_UPGRADE_NOTICE, EmbeddingRouteConfig, FitnessConfig, GatewayConfig, GroupPolicy, GroupReplyMode, HYBRID_PROCESS_MEMORY_UNAVAILABLE, HeartbeatConfig, HttpRequestConfig, IMessageConfig, IdentityBindingConfig, IdentityConfig, LarkConfig, McpConfig, McpServerConfig, diff --git a/src/config/schema/security.rs b/src/config/schema/security.rs index 21d3f4942..355f8c141 100644 --- a/src/config/schema/security.rs +++ b/src/config/schema/security.rs @@ -185,20 +185,16 @@ impl WorkspaceHooks { } } -/// Operations/development tools hidden from IM channel sessions by default. +/// Operations/development tools an operator may hide from IM channel sessions. /// -/// A chat message arriving over Signal / Telegram / Discord / WhatsApp is written -/// by a conversation partner, not by the operator sitting at the host. Advertising -/// the plugin, hook, proxy, node, repository and index-maintenance surfaces on that -/// path costs tokens on every turn and puts a misfire one sentence away from -/// changing how the runtime itself is configured. None of these is reachable by -/// accident from a conversation that actually needs them: listing a name in -/// `[tool_tiering] always_include` restores it, and `channel_exclude = []` turns -/// the whole default off. +/// Not applied by default: a fresh install hides nothing, and a limit exists +/// only when the operator configures one. Copy the names into +/// `[tool_tiering] channel_exclude` to hide them on Signal / Telegram / Discord / +/// WhatsApp turns; listing a name in `[tool_tiering] always_include` restores it. /// -/// Terminal chat, the gateway/webhook surface and the web console are unaffected — -/// those callers are the operator. -pub const DEFAULT_CHANNEL_EXCLUDED_TOOLS: &[&str] = &[ +/// Terminal chat, the gateway/webhook surface and the web console are unaffected +/// by `channel_exclude`: those callers are the operator. +pub const RECOMMENDED_CHANNEL_EXCLUDED_TOOLS: &[&str] = &[ "wasm_plugins_manage", "wasm_plugin_reload", "wasm_plugins_status", @@ -227,8 +223,7 @@ pub struct ToolTieringConfig { /// Tool names excluded from capability publication. pub always_exclude: Vec, /// Tool names hidden from IM channel sessions only, on top of `always_exclude`. - /// Defaults to [`DEFAULT_CHANNEL_EXCLUDED_TOOLS`]; set to `[]` to expose the - /// full operator surface on channels again. + /// Default: empty (nothing is hidden); list tool names to hide them on channels. pub channel_exclude: Vec, } @@ -237,15 +232,25 @@ impl Default for ToolTieringConfig { Self { always_include: Vec::new(), always_exclude: Vec::new(), - channel_exclude: DEFAULT_CHANNEL_EXCLUDED_TOOLS + channel_exclude: Vec::new(), + } + } +} + +impl ToolTieringConfig { + /// A policy that hides [`RECOMMENDED_CHANNEL_EXCLUDED_TOOLS`] from channel + /// sessions: what an operator gets by copying that list into the config. + #[must_use] + pub fn with_recommended_channel_exclusions() -> Self { + Self { + channel_exclude: RECOMMENDED_CHANNEL_EXCLUDED_TOOLS .iter() .map(|name| (*name).to_string()) .collect(), + ..Self::default() } } -} -impl ToolTieringConfig { /// The tiering policy an IM channel session runs under. /// /// `channel_exclude` is folded into `always_exclude` rather than applied as a diff --git a/src/config/schema/tests/channels.rs b/src/config/schema/tests/channels.rs index 97971ca1b..fe2eaf6b9 100644 --- a/src/config/schema/tests/channels.rs +++ b/src/config/schema/tests/channels.rs @@ -8,10 +8,10 @@ use tokio::test; /// exclusion the higher priority — silently un-doing the operator override. #[test] async fn channel_tiering_folds_defaults_in_without_overriding_the_operator() { - let mut config = ToolTieringConfig::default(); + let mut config = ToolTieringConfig::with_recommended_channel_exclusions(); assert!( config.channel_exclude.contains(&"wasm_plugins_manage".to_string()), - "the operations surface must be excluded from channels by default" + "the recommended operations surface is excluded from channels" ); assert!( config.always_exclude.is_empty(), @@ -55,7 +55,7 @@ async fn channel_tiering_is_identity_when_the_default_is_emptied() { async fn channel_tiering_does_not_duplicate_an_already_excluded_tool() { let config = ToolTieringConfig { always_exclude: vec!["nodes".to_string()], - ..ToolTieringConfig::default() + ..ToolTieringConfig::with_recommended_channel_exclusions() }; let channel = config.for_channel_surface(); assert_eq!( diff --git a/src/session_worker/runner/tests/tool_selection.rs b/src/session_worker/runner/tests/tool_selection.rs index 1346f7689..7fc7ad960 100644 --- a/src/session_worker/runner/tests/tool_selection.rs +++ b/src/session_worker/runner/tests/tool_selection.rs @@ -77,7 +77,7 @@ async fn a_process_worker_cannot_regain_the_operations_surface_its_channel_hides // Fixture validity first: the exclusions come from the real default // channel surface, not from a list written for this test, so the test // fails if `channel_exclude` ever stops hiding the operations tools. - let surface = crate::config::ToolTieringConfig::default().for_channel_surface(); + let surface = crate::config::ToolTieringConfig::with_recommended_channel_exclusions().for_channel_surface(); let hidden = surface.always_exclude.clone(); for name in ["gateway", "proxy_config", "config_reload", "nodes"] { assert!( @@ -117,7 +117,7 @@ async fn a_process_worker_cannot_regain_the_operations_surface_its_channel_hides // An operator who re-enables one keeps it: `for_channel_surface` never // folds an `always_include` name into the hidden set. - let mut reopened = crate::config::ToolTieringConfig::default(); + let mut reopened = crate::config::ToolTieringConfig::with_recommended_channel_exclusions(); reopened.always_include.push("gateway".to_string()); let reopened = reopened.for_channel_surface().always_exclude; let names = worker_tool_names(&[], &reopened).await; @@ -153,7 +153,7 @@ async fn manifest_tool_names(manifest: &WorkerManifest) -> Vec { async fn a_worker_manifest_binds_its_channel_exclusions_to_the_tool_filter() { // Fixture validity first: the hidden set is the real default channel // surface, so the test dies if `channel_exclude` stops hiding these. - let hidden = crate::config::ToolTieringConfig::default() + let hidden = crate::config::ToolTieringConfig::with_recommended_channel_exclusions() .for_channel_surface() .always_exclude; for name in ["gateway", "proxy_config", "config_reload", "nodes"] { diff --git a/src/tools/sessions_spawn/tests/tool_setup.rs b/src/tools/sessions_spawn/tests/tool_setup.rs index d2fe8d209..c153a9128 100644 --- a/src/tools/sessions_spawn/tests/tool_setup.rs +++ b/src/tools/sessions_spawn/tests/tool_setup.rs @@ -264,7 +264,7 @@ fn sessions_spawn_process_manifest_carries_the_channel_exclusions_under_the_seal parent_task_id: None, source_message_event_id: None, }; - let hidden = crate::config::ToolTieringConfig::default() + let hidden = crate::config::ToolTieringConfig::with_recommended_channel_exclusions() .for_channel_surface() .always_exclude; assert!( diff --git a/tests/support/legacy_tool_surface_budget.rs b/tests/support/legacy_tool_surface_budget.rs index 5d0606a41..2c4ed3bff 100644 --- a/tests/support/legacy_tool_surface_budget.rs +++ b/tests/support/legacy_tool_surface_budget.rs @@ -14,7 +14,7 @@ #![allow(clippy::unwrap_used, clippy::print_stdout, clippy::expect_used)] -use crate::config::{Config, DEFAULT_CHANNEL_EXCLUDED_TOOLS, MemoryConfig, ToolTieringConfig}; +use crate::config::{Config, MemoryConfig, ToolTieringConfig}; use crate::memory::Memory; use crate::security::SecurityPolicy; use crate::tools::{Tool, ToolCatalog, ToolSpec, all_tools, legacy_intent_tests as intent}; @@ -106,7 +106,7 @@ fn channel_sessions_do_not_advertise_the_operations_surface() { let tmp = TempDir::new().unwrap(); let tools = registry(&tmp); - let operator = ToolTieringConfig::default(); + let operator = ToolTieringConfig::with_recommended_channel_exclusions(); let channel = operator.for_channel_surface(); let operator_specs = specs_for(&tools, NEUTRAL_MESSAGE, &operator); @@ -122,9 +122,9 @@ fn channel_sessions_do_not_advertise_the_operations_surface() { ); let channel_names = names(&channel_specs); - for excluded in DEFAULT_CHANNEL_EXCLUDED_TOOLS { + for excluded in &operator.channel_exclude { assert!( - !channel_names.contains(excluded), + !channel_names.contains(&excluded.as_str()), "`{excluded}` must not be advertised to an IM channel session: {channel_names:?}" ); } @@ -141,9 +141,10 @@ fn channel_sessions_do_not_advertise_the_operations_surface() { let channel_broad = specs_for(&tools, broad, &channel); let operator_broad_names = names(&operator_broad); let channel_broad_names = names(&channel_broad); - let reachable: Vec<&str> = DEFAULT_CHANNEL_EXCLUDED_TOOLS + let reachable: Vec<&str> = operator + .channel_exclude .iter() - .copied() + .map(String::as_str) .filter(|name| operator_broad_names.contains(name)) .collect(); assert!( @@ -176,7 +177,7 @@ fn always_include_restores_a_channel_excluded_tool() { let tmp = TempDir::new().unwrap(); let tools = registry(&tmp); - let mut operator = ToolTieringConfig::default(); + let mut operator = ToolTieringConfig::with_recommended_channel_exclusions(); operator.always_include.push("nodes".to_string()); let channel = operator.for_channel_surface(); @@ -199,7 +200,7 @@ fn an_empty_channel_exclude_list_restores_the_full_surface() { let operator = ToolTieringConfig { channel_exclude: Vec::new(), - ..ToolTieringConfig::default() + ..ToolTieringConfig::with_recommended_channel_exclusions() }; let channel = operator.for_channel_surface(); assert!(channel.always_exclude.is_empty(), "nothing may be folded in"); @@ -221,7 +222,7 @@ fn an_empty_channel_exclude_list_restores_the_full_surface() { fn channel_exclusion_survives_a_capability_matching_message() { let tmp = TempDir::new().unwrap(); let tools = registry(&tmp); - let channel = ToolTieringConfig::default().for_channel_surface(); + let channel = ToolTieringConfig::with_recommended_channel_exclusions().for_channel_surface(); let message = "reload the wasm plugins and check the proxy config on the remote node"; let operator_specs = specs_for(&tools, message, &ToolTieringConfig::default()); @@ -516,7 +517,7 @@ fn a_chat_session_opening_on_an_unrouted_turn_keeps_the_whole_registry() { fn a_stateless_entry_point_still_publishes_everything_on_an_unrouted_turn() { let tmp = TempDir::new().unwrap(); let tools = registry(&tmp); - let channel = ToolTieringConfig::default().for_channel_surface(); + let channel = ToolTieringConfig::with_recommended_channel_exclusions().for_channel_surface(); let allowed_specs = specs_for(&tools, "", &channel); let allowed = names(&allowed_specs); From 73ad0061892e657e0f88368327755f0bc583dcc4 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:40:03 +0400 Subject: [PATCH 0134/1567] feat(init): generate no restrictive keys and stop nagging on unrestricted autonomy The server init spec no longer writes workspace_only, forbidden_paths or acknowledge_unrestricted_profile, and the full spec no longer writes the acknowledgement. prx doctor prints one neutral autonomy-level line instead of an unrestricted-profile warning. --- docs/configuration.md | 22 ++++++++++--------- docs/migration-unreleased.md | 1 + src/config/init/templates.rs | 15 ++----------- src/config/init/tests.rs | 5 +++-- src/config/schema/autonomy.rs | 2 +- src/doctor/implementation/section_2.rs | 17 ++++++-------- src/doctor/tests/section_1.rs | 12 +++++----- .../child_source/golden_effective_config.json | 2 +- tests/fixtures/config-schema.json | 2 +- 9 files changed, 34 insertions(+), 44 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 132b51712..9dd73c770 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -156,7 +156,7 @@ and the module-gate family are absorbed on load; they are not live switches. | `[security]` | `workspace_hooks` omitted when off | | `[compliance.interaction_notice]` | `version = "1"`; default notice text; `applicability = "required"`; `exception_owner`/`exception_reviewed_at` unset | | `[compliance.eu_ai_act]` | classification `status = "unclassified"`; `owner`/`assessed_at` unset; `incident_store_path` unset; declaration fields all optional/empty | -| `[tool_tiering]` | `always_include = []`; `always_exclude = []`; `channel_exclude` the operations/development set | +| `[tool_tiering]` | `always_include = []`; `always_exclude = []`; `channel_exclude = []` (nothing hidden from channel sessions) | | `[providers]` | `[providers.ollama] num_ctx` unset. `[[providers.tool_dialects]]`: `provider` required; `model` unset (all models); `tool_schema`/`tool_call` unset (`raw` / `native`). `[[providers.models]]`: `provider` required; `model` unset; `operations`, `native_tools`, `vision_input`, `streaming`, `structured_output`, `tool_schema_dialect`, `tool_call_dialect`, `context_window` all unset. See later sections | | `[model_settings.]` | catalog levels and explicit parameters; omitted keys stay with the catalog | @@ -718,14 +718,15 @@ low_priority_tools = ["sessions_spawn", "delegate"] # Per-turn capability policy. The surface owner applies these filters (they are # not owned by the decision engine). `always_include` prefers direct publication; # `always_exclude` removes names from the surface. `channel_exclude` applies to IM -# channel sessions only (Signal / Telegram / Discord / WhatsApp / …) and defaults -# to the operations/development surface: wasm_plugins_manage, wasm_plugin_reload, +# channel sessions only (Signal / Telegram / Discord / WhatsApp / …) and is empty +# by default, so nothing is hidden. To hide the operations/development surface on +# channels list its names, for example: wasm_plugins_manage, wasm_plugin_reload, # wasm_plugins_status, hooks_manage, hooks_status, proxy_config, config_reload, # gateway, mcp_status, nodes, skills_manage, memory_reindex, # document_sync, document_ingest. Terminal chat, the gateway and the console are -# unaffected. Name a tool in `always_include` to put it back on channels, or set -# `channel_exclude = []` to drop the default entirely. `always_include` does not -# override `always_exclude`: a name in `always_exclude` is excluded everywhere. +# unaffected. Name a tool in `always_include` to put it back on channels. +# `always_include` does not override `always_exclude`: a name in `always_exclude` +# is excluded everywhere. [tool_tiering] always_include = [] always_exclude = [] @@ -912,10 +913,11 @@ refuses every priced turn). The signed child manifest carries "no ceiling" as `u32::MAX` cents (4294967295, the same value the key accepts). Spend is still recorded in the cost journal. With no limit set, no budget warning or "budget exhausted" notice is produced. A host-wide profile is explicit: set -`workspace_only = false` and clear `forbidden_paths`. `prx doctor` warns when -those two are active together with no cost ceiling unless -`acknowledge_unrestricted_profile = true`; the flag only silences that warning. -There is no hourly action cap. +`workspace_only = false` and clear `forbidden_paths`; at level `full` the file +tools and shell ignore both keys anyway. `prx doctor` prints one neutral line +with the active autonomy level and never warns about absent limits. +`acknowledge_unrestricted_profile` is kept so existing configs still load and +no longer changes any output. There is no hourly action cap. ### Decision admission and autonomy diff --git a/docs/migration-unreleased.md b/docs/migration-unreleased.md index cedf6ca96..79f0535bb 100644 --- a/docs/migration-unreleased.md +++ b/docs/migration-unreleased.md @@ -29,6 +29,7 @@ of the [changelog](../CHANGELOG.md). | Source-tree layout | The repository root no longer ships a `task/` notes tree. Proptest shrinking seeds belong under `tests/proptest-regressions/`; a root `proptest-regressions/` directory is gitignored and is not replayed. | Only when working from a source clone | | Known Codex model default effort | Declared Codex rows now use `medium` rather than `xhigh`. Set an explicit supported effort if the former behavior is required. Unknown rows keep the legacy `medium` verbosity / `xhigh` effort base. See [model levels and parameters](model-catalog.md). | Only to retain the former effort | | No spend ceiling by default | `[autonomy] max_cost_per_day_cents`, `[cost] daily_limit_usd` and `[cost] monthly_limit_usd` are now optional and unset by default. Before: a config that omitted them got 500 cents per day, 10.0 USD per day and 100.0 USD per month. Now: a config that omits them has no limit, so no spend is refused for a budget reason, no budget warning or "budget exhausted" notice is printed, and children and worker processes get the maximum allowance (`u32::MAX` cents in the signed manifest). A config that sets any of these keys keeps exactly that limit. `prx init` no longer writes `max_cost_per_day_cents`. Usage accounting and the cost journal are unchanged. To keep the old ceilings, write them into the config. Per-agent `limits` were already unset by default. No stored-data migration is required. | Only to keep the former ceilings: set the three keys explicitly | +| Nothing restricted by default on a fresh install | `[tool_tiering] channel_exclude` now defaults to an empty list (before: 14 operations tools such as `gateway`, `config_reload`, `nodes`, `skills_manage` were hidden from IM channel turns); a config that omits it now exposes those tools on channel turns, and a config that lists names keeps hiding them. `prx init --spec server` no longer writes `workspace_only`, `forbidden_paths` or `acknowledge_unrestricted_profile` (the built-in values are unchanged and have no effect at level `full`); `--spec full` no longer writes `acknowledge_unrestricted_profile`. `prx doctor` no longer warns for an explicit unrestricted profile; it prints one neutral autonomy-level line, and `acknowledge_unrestricted_profile` is accepted and ignored. Gateway pairing, channel sender allowlists, secret protection and integrity checks are unchanged. | Only to keep the old channel tool hiding: list the names in `channel_exclude` | | WASM plugins off by default | Set `[plugins] enabled = true` and restart only after reviewing each plugin; install or update with `wasm_plugins_manage` and explicit `grant_permissions` to write `plugin-trust.json` beside `config.toml`. The configuration directory and `plugin-cache/` must be outside the workspace. A `.prx-managed` marker grants no trust. | To use WASM plugins | | Plugin outbound requests | An empty `http_allowlist` now denies every URL. Use URL patterns such as `https://api.example.com/*`, not string prefixes such as `https://api.example.com*`. The SSRF guard still refuses private, loopback and other unsafe destinations. See [plugin trust and networking](plugin-developer-guide.md). | For plugins needing outbound HTTP | | Workspace command hooks default off | Set `[security] workspace_hooks = "on"` only after reviewing workspace commands. Remove non-null `cwd` from `hooks.json`: the whole candidate file is refused. Commands now start with a cleared environment in the dedicated directory beside `config.toml`; use explicit paths and allowed `env` entries. See [workspace command hooks](configuration.md#workspace-command-hooks). | To run workspace command hooks | diff --git a/src/config/init/templates.rs b/src/config/init/templates.rs index a522b52d9..a6485847a 100644 --- a/src/config/init/templates.rs +++ b/src/config/init/templates.rs @@ -257,16 +257,8 @@ pub(super) fn security_template(spec: Spec) -> String { [autonomy] level = "full" -workspace_only = true -# No daily cost ceiling unless max_cost_per_day_cents is set here. -# Set true only when host-wide unrestricted operation is intentional and -# reviewed. This suppresses doctor noise; it is not a capability gate. -acknowledge_unrestricted_profile = false -forbidden_paths = [ - "/etc", "/root", "/home", "/usr", "/bin", "/sbin", "/lib", "/opt", - "/boot", "/dev", "/proc", "/sys", "/var", "/tmp", - "~/.ssh", "~/.gnupg", "~/.aws", "~/.config", -] +# No limit is set unless you add one: max_cost_per_day_cents, workspace_only, +# forbidden_paths (the last two take effect below level "full"). [secrets] encrypt = true @@ -291,9 +283,6 @@ status = "unclassified" # unclassified | high_risk | not_high_risk level = "full" # read_only | supervised | full workspace_only = false forbidden_paths = [] # no extra path denylist -# Set true only when host-wide unrestricted operation is intentional and -# reviewed. This suppresses doctor noise; it is not a capability gate. -acknowledge_unrestricted_profile = false [secrets] encrypt = true diff --git a/src/config/init/tests.rs b/src/config/init/tests.rs index f5e3e1634..2a9b999f6 100644 --- a/src/config/init/tests.rs +++ b/src/config/init/tests.rs @@ -1196,9 +1196,10 @@ fn full_security_template_is_open_by_default() { fn server_security_template_defaults_to_autonomous_with_workspace_boundary() { let content = security_template(Spec::Server); assert!(content.contains("level = \"full\"")); - assert!(content.contains("workspace_only = true")); + assert!(!content.contains("workspace_only =")); assert!(!content.contains("max_cost_per_day_cents =")); - assert!(content.contains("\"/etc\"")); + assert!(!content.contains("forbidden_paths =")); + assert!(!content.contains("acknowledge_unrestricted_profile")); assert!(!content.contains("level = \"supervised\"")); } diff --git a/src/config/schema/autonomy.rs b/src/config/schema/autonomy.rs index 489ffa385..54f77bdd0 100644 --- a/src/config/schema/autonomy.rs +++ b/src/config/schema/autonomy.rs @@ -364,7 +364,7 @@ pub struct AutonomyConfig { pub max_cost_per_day_cents: Option, /// Operator acknowledgement for an intentionally unrestricted profile. - /// This suppresses doctor noise only; it does not alter policy behavior. + /// Retained for existing configs; it no longer changes any output or policy behavior. #[serde(default)] pub acknowledge_unrestricted_profile: bool, diff --git a/src/doctor/implementation/section_2.rs b/src/doctor/implementation/section_2.rs index 4ca013e72..e3e925e3f 100644 --- a/src/doctor/implementation/section_2.rs +++ b/src/doctor/implementation/section_2.rs @@ -1,16 +1,13 @@ fn check_config_semantics(config: &Config, items: &mut Vec) { let cat = "config"; - if !config.autonomy.acknowledge_unrestricted_profile - && !config.autonomy.workspace_only - && config.autonomy.forbidden_paths.is_empty() - && config.autonomy.effective_max_cost_per_day_cents() == u32::MAX - { - items.push(DiagItem::warn( - cat, - "explicit unrestricted autonomy profile: host-wide paths and an unbounded cost ceiling", - )); - } + // A neutral statement of the active level; limits being absent is the + // default and never a warning. `acknowledge_unrestricted_profile` is kept + // for existing configs and no longer changes any output. + items.push(DiagItem::configured( + cat, + format!("autonomy level: {:?}", config.autonomy.level), + )); // Config file exists if config.config_path.exists() { diff --git a/src/doctor/tests/section_1.rs b/src/doctor/tests/section_1.rs index 0a1d0a178..8728aaad6 100644 --- a/src/doctor/tests/section_1.rs +++ b/src/doctor/tests/section_1.rs @@ -716,7 +716,7 @@ } #[test] - fn config_validation_warns_for_explicit_unrestricted_autonomy() { + fn config_validation_does_not_warn_for_explicit_unrestricted_autonomy() { let mut config = Config::default(); config.autonomy.workspace_only = false; config.autonomy.forbidden_paths.clear(); @@ -725,11 +725,11 @@ check_config_semantics(&config, &mut items); - let item = items - .iter() - .find(|item| item.message.contains("explicit unrestricted autonomy profile")) - .expect("unrestricted posture warning"); - assert_eq!(item.severity, Severity::Warn); + assert!( + !items + .iter() + .any(|item| item.message.contains("unrestricted autonomy profile")) + ); } #[test] diff --git a/src/runtime/child_source/golden_effective_config.json b/src/runtime/child_source/golden_effective_config.json index 006c9829b..c9f8c7340 100644 --- a/src/runtime/child_source/golden_effective_config.json +++ b/src/runtime/child_source/golden_effective_config.json @@ -1 +1 @@ -{"a2a":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trust_domain":"prx.local","trusted_trust_domains":[]},"agent":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"messaging":{"inbound":true},"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2},"agents":{},"api_key":null,"api_url":null,"auth":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"},"autonomy":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true},"browser":{"allowed_domains":[],"computer_use":{"api_key":null}},"channels_config":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null},"chat":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2},"compliance":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}},"composio":{"api_key":null,"entity_id":"default"},"cost":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{"alpha/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0},"zeta/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0}},"warn_at_percent":80},"cron":{"max_run_history":50},"decision_engine":{"backend":{"circuit_breaker":{"cooldown_secs":60,"failure_threshold":5},"credential_ref":"","endpoint":"","kind":"auto","max_request_bytes":65536,"max_response_bytes":262144,"model":"","pinned_snapshot":"","remote_enabled":false,"timeout_ms":250},"candidates":5,"enabled":false,"latency_budget_ms":500,"max_candidates":12,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"token_ratio_limit":0.3499999940395355},"default_model":"anthropic/claude-sonnet-5","default_provider":"openrouter","default_temperature":0.7,"embedding_routes":[],"gateway":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60},"heartbeat":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."},"http_request":{"max_response_size":1000000,"timeout_secs":30},"identity":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"},"identity_bindings":[],"mcp":{"servers":{}},"mcp_server":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true},"media":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"},"memory":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7},"model_routes":[],"model_settings":{},"multimodal":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4},"nodes":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}},"observability":{"backend":"none","otel_endpoint":null,"otel_service_name":null},"plugins":{"enabled":false},"providers":{"ollama":{"num_ctx":null}},"proxy":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]},"query_classification":{"rules":[]},"reliability":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2},"router":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]},"runtime":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null},"scheduler":{"claim_lease_secs":90,"max_tasks":64},"secrets":{"encrypt":true},"security":{"audit":{"log_path":"audit.log","max_size_mb":100}},"self_system":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24},"sessions_spawn":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null},"skill_rag":{"top_k":32},"skills":{"open_skills_dir":null,"openclaw_skills_dir":null},"skills_lifecycle":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]},"smart_group":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5},"storage":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}},"task_routing":{"default_intent":"simple","rules":[]},"tool_tiering":{"always_exclude":[],"always_include":[],"channel_exclude":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","skills_manage","memory_reindex","document_sync","document_ingest"]},"tunnel":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null},"user_policies":[],"web_search":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15},"webhook":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null},"xin":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}} \ No newline at end of file +{"a2a":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trust_domain":"prx.local","trusted_trust_domains":[]},"agent":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"messaging":{"inbound":true},"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2},"agents":{},"api_key":null,"api_url":null,"auth":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"},"autonomy":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true},"browser":{"allowed_domains":[],"computer_use":{"api_key":null}},"channels_config":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null},"chat":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2},"compliance":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}},"composio":{"api_key":null,"entity_id":"default"},"cost":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{"alpha/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0},"zeta/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0}},"warn_at_percent":80},"cron":{"max_run_history":50},"decision_engine":{"backend":{"circuit_breaker":{"cooldown_secs":60,"failure_threshold":5},"credential_ref":"","endpoint":"","kind":"auto","max_request_bytes":65536,"max_response_bytes":262144,"model":"","pinned_snapshot":"","remote_enabled":false,"timeout_ms":250},"candidates":5,"enabled":false,"latency_budget_ms":500,"max_candidates":12,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"token_ratio_limit":0.3499999940395355},"default_model":"anthropic/claude-sonnet-5","default_provider":"openrouter","default_temperature":0.7,"embedding_routes":[],"gateway":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60},"heartbeat":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."},"http_request":{"max_response_size":1000000,"timeout_secs":30},"identity":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"},"identity_bindings":[],"mcp":{"servers":{}},"mcp_server":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true},"media":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"},"memory":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7},"model_routes":[],"model_settings":{},"multimodal":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4},"nodes":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}},"observability":{"backend":"none","otel_endpoint":null,"otel_service_name":null},"plugins":{"enabled":false},"providers":{"ollama":{"num_ctx":null}},"proxy":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]},"query_classification":{"rules":[]},"reliability":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2},"router":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]},"runtime":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null},"scheduler":{"claim_lease_secs":90,"max_tasks":64},"secrets":{"encrypt":true},"security":{"audit":{"log_path":"audit.log","max_size_mb":100}},"self_system":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24},"sessions_spawn":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null},"skill_rag":{"top_k":32},"skills":{"open_skills_dir":null,"openclaw_skills_dir":null},"skills_lifecycle":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]},"smart_group":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5},"storage":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}},"task_routing":{"default_intent":"simple","rules":[]},"tool_tiering":{"always_exclude":[],"always_include":[],"channel_exclude":[]},"tunnel":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null},"user_policies":[],"web_search":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15},"webhook":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null},"xin":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}} \ No newline at end of file diff --git a/tests/fixtures/config-schema.json b/tests/fixtures/config-schema.json index 03dedcf77..7d0040a06 100644 --- a/tests/fixtures/config-schema.json +++ b/tests/fixtures/config-schema.json @@ -1 +1 @@ -{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Config","description":"Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).","type":"object","properties":{"a2a":{"description":"Agent-to-Agent compatibility configuration (`[a2a]`).","$ref":"#/$defs/A2aConfig","default":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trusted_trust_domains":[],"trust_domain":"prx.local"}},"agent":{"description":"Agent orchestration settings (`[agent]`).","$ref":"#/$defs/AgentConfig","default":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2,"messaging":{"inbound":true}}},"agents":{"description":"Delegate agent configurations for multi-agent workflows.","type":"object","additionalProperties":{"$ref":"#/$defs/DelegateAgentConfig"},"default":{}},"api_key":{"description":"API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.","type":["string","null"],"default":null},"api_url":{"description":"Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)","type":["string","null"],"default":null},"auth":{"description":"Auth profile and external credential import settings (`[auth]`).","$ref":"#/$defs/AuthConfig","default":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"}},"autonomy":{"description":"Autonomy and security policy configuration (`[autonomy]`).","$ref":"#/$defs/AutonomyConfig","default":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true}},"browser":{"description":"Browser automation configuration (`[browser]`).","$ref":"#/$defs/BrowserConfig","default":{"allowed_domains":[],"computer_use":{"api_key":null}}},"channels_config":{"description":"Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).","$ref":"#/$defs/ChannelsConfig","default":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null}},"chat":{"description":"Interactive chat UI configuration (`[chat]`).","$ref":"#/$defs/ChatConfig","default":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2}},"compliance":{"description":"Operator-owned compliance controls (`[compliance]`).","$ref":"#/$defs/ComplianceConfig","default":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}},"composio":{"description":"Composio managed OAuth tools integration (`[composio]`).","$ref":"#/$defs/ComposioConfig","default":{"api_key":null,"entity_id":"default"}},"cost":{"description":"Cost tracking and budget enforcement configuration (`[cost]`).","$ref":"#/$defs/CostConfig","default":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{},"warn_at_percent":80}},"cron":{"description":"Cron job configuration (`[cron]`).","$ref":"#/$defs/CronConfig","default":{"max_run_history":50}},"decision_engine":{"description":"Optional advisory decision engine, disabled by default.","$ref":"#/$defs/DecisionEngineConfig","default":{"candidates":5,"enabled":false,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"latency_budget_ms":500,"max_candidates":12,"token_ratio_limit":0.3499999940395355}},"default_model":{"description":"Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.","type":["string","null"]},"default_provider":{"description":"Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.","type":["string","null"]},"default_temperature":{"description":"Default model temperature (0.0–2.0). Default: `0.7`.","type":"number","format":"double","default":0.7},"embedding_routes":{"description":"Embedding routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/EmbeddingRouteConfig"}},"gateway":{"description":"Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).","$ref":"#/$defs/GatewayConfig","default":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60}},"heartbeat":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]`).","$ref":"#/$defs/HeartbeatConfig","default":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."}},"http_request":{"description":"HTTP request tool configuration (`[http_request]`).","$ref":"#/$defs/HttpRequestConfig","default":{"max_response_size":1000000,"timeout_secs":30}},"identity":{"description":"Identity format configuration: OpenClaw or AIEOS (`[identity]`).","$ref":"#/$defs/IdentityConfig","default":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"}},"identity_bindings":{"description":"Static identity bindings loaded at startup (`[[identity_bindings]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/IdentityBindingConfig"}},"mcp":{"description":"Secrets encryption configuration (`[secrets]`).","$ref":"#/$defs/McpConfig","default":{"servers":{}}},"mcp_server":{"description":"MCP server compatibility configuration (`[mcp_server]`).","$ref":"#/$defs/McpServerRuntimeConfig","default":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true}},"media":{"description":"Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.","$ref":"#/$defs/MediaConfig","default":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"}},"memory":{"description":"Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).","$ref":"#/$defs/MemoryConfig","default":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7}},"model_routes":{"description":"Model routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/ModelRouteConfig"}},"model_settings":{"description":"Catalog model levels and explicit parameters, keyed by canonical release ID.","type":"object","additionalProperties":{"$ref":"#/$defs/ModelSettings"},"default":{}},"multimodal":{"description":"Multimodal (image) handling configuration (`[multimodal]`).","$ref":"#/$defs/MultimodalConfig","default":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4}},"nodes":{"description":"Remote node proxy configuration (`[nodes]`).","$ref":"#/$defs/NodesConfig","default":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}},"observability":{"description":"Observability backend configuration (`[observability]`).","$ref":"#/$defs/ObservabilityConfig","default":{"backend":"none","otel_endpoint":null,"otel_service_name":null}},"plugins":{"description":"WASM plugin runtime switch (`[plugins]`), off by default.","$ref":"#/$defs/PluginsConfig","default":{"enabled":false}},"providers":{"description":"Provider-specific runtime options (`[providers.]`).","$ref":"#/$defs/ProvidersConfig","default":{"ollama":{"num_ctx":null}}},"proxy":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).","$ref":"#/$defs/ProxyConfig","default":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]}},"query_classification":{"description":"Automatic query classification — maps user messages to model hints.","$ref":"#/$defs/QueryClassificationConfig","default":{"rules":[]}},"reliability":{"description":"Reliability settings: retries, fallback providers, backoff (`[reliability]`).","$ref":"#/$defs/ReliabilityConfig","default":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2}},"router":{"description":"Heuristic LLM router configuration (`[router]`).","$ref":"#/$defs/RouterConfig","default":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]}},"runtime":{"description":"Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.","$ref":"#/$defs/RuntimeConfig","default":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null}},"scheduler":{"description":"Scheduler configuration for periodic task execution (`[scheduler]`).","$ref":"#/$defs/SchedulerConfig","default":{"claim_lease_secs":90,"max_tasks":64}},"secrets":{"$ref":"#/$defs/SecretsConfig","default":{"encrypt":true}},"security":{"description":"Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).","$ref":"#/$defs/SecurityConfig","default":{"audit":{"log_path":"audit.log","max_size_mb":100}}},"self_system":{"description":"Self-system experimental automation controls (`[self_system]`).","$ref":"#/$defs/SelfSystemConfig","default":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24}},"sessions_spawn":{"description":"Session spawning configuration (`[sessions_spawn]`).","$ref":"#/$defs/SessionsSpawnConfig","default":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null}},"skill_rag":{"description":"Dynamic skill retrieval settings (`[skill_rag]`).","$ref":"#/$defs/SkillRagConfig","default":{"top_k":32}},"skills":{"description":"Skills loading and community repository behavior (`[skills]`).","$ref":"#/$defs/SkillsConfig","default":{"open_skills_dir":null,"openclaw_skills_dir":null}},"skills_lifecycle":{"description":"Skill lifecycle (`[skills_lifecycle]`), off by default.","$ref":"#/$defs/SkillsLifecycleConfig","default":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]}},"smart_group":{"description":"Smart group-reply pre-gate configuration (`[smart_group]`).","$ref":"#/$defs/SmartGroupConfig","default":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5}},"storage":{"description":"Persistent storage provider configuration (`[storage]`).","$ref":"#/$defs/StorageConfig","default":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"task_routing":{"description":"Task routing configuration — classifies work by intent before the main agent loop.","$ref":"#/$defs/TaskRoutingConfig","default":{"default_intent":"simple","rules":[]}},"tool_tiering":{"description":"Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).","$ref":"#/$defs/ToolTieringConfig","default":{"always_exclude":[],"always_include":[],"channel_exclude":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","skills_manage","memory_reindex","document_sync","document_ingest"]}},"tunnel":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]`).","$ref":"#/$defs/TunnelConfig","default":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null}},"user_policies":{"description":"Static user policy records loaded at startup (`[[user_policies]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/UserPolicyConfig"}},"web_search":{"description":"Web search tool configuration (`[web_search]`).","$ref":"#/$defs/WebSearchConfig","default":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15}},"webhook":{"description":"Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).","$ref":"#/$defs/MemoryWebhookConfig","default":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null}},"xin":{"description":"Xin autonomous task engine configuration (`[xin]`).","$ref":"#/$defs/XinConfig","default":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}}},"$defs":{"A2aConfig":{"type":"object","properties":{"agent_id":{"description":"Stable PRX agent identifier advertised to peers.","type":"string","default":"prx-default"},"allowed_peer_issuers":{"description":"Accepted external peer issuers.","type":"array","default":[],"items":{"type":"string"}},"bind":{"description":"Advertised bind address.","type":"string","default":"127.0.0.1:16832"},"card_jwks_uri":{"description":"Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.","type":["string","null"],"default":null},"card_signing_key_path":{"description":"On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).","type":["string","null"],"default":null},"card_ttl_seconds":{"description":"Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.","type":"integer","format":"uint64","default":3600,"minimum":0},"discovery_advertised":{"description":"Whether to advertise into an external A2A registry.","type":"boolean","default":false},"handoff_nonce_ttl_seconds":{"description":"Replay window for future handoff delegation tokens.","type":"integer","format":"uint64","default":3600,"minimum":0},"messaging_enabled":{"description":"Enable the dedicated pinned mTLS messaging listener.","type":"boolean","default":false},"peers":{"type":"object","additionalProperties":{"$ref":"#/$defs/A2aPeer"},"default":{}},"spiffe_id":{"description":"Local SPIFFE-style identifier placeholder.","type":"string","default":"spiffe://prx-local/agent/prx-default"},"spiffe_strict_validation":{"description":"When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.","type":"boolean","default":false},"spiffe_trust_bundle_pem":{"description":"Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).","type":["string","null"],"default":null},"trusted_trust_domains":{"description":"Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).","type":"array","default":[],"items":{"type":"string"}},"trust_domain":{"description":"SPIFFE trust domain for new instance identities.","type":"string","default":"prx.local"}}},"A2aPeer":{"description":"Explicit pinned identity and local recipient grant.","type":"object","properties":{"spiffe_id":{"type":"string"},"fingerprints":{"type":"array","items":{"type":"string"}},"address":{"type":"string"},"owner":{"type":"string"},"sessions":{"type":"array","default":["*"],"items":{"type":"string"}},"agents":{"type":"array","default":["*"],"items":{"type":"string"}}},"required":["spiffe_id","fingerprints","address","owner"],"additionalProperties":false},"AgentCompactionConfig":{"description":"Agent context compaction configuration (`[agent.compaction]`).","type":"object","properties":{"keep_recent_messages":{"description":"Number of recent non-system messages to keep after compaction.","type":"integer","format":"uint","default":12,"minimum":0},"max_context_tokens":{"description":"Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.","type":"integer","format":"uint","default":128000,"minimum":0},"memory_flush":{"description":"Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.","type":"boolean","default":true},"mode":{"description":"Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).","$ref":"#/$defs/AgentCompactionMode","default":"switch"},"os_paging":{"description":"Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.","$ref":"#/$defs/OsPagingConfig","default":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"}},"reserve_tokens":{"description":"Tokens reserved for the next model response.","type":"integer","format":"uint","default":4096,"minimum":0}}},"AgentCompactionMode":{"description":"Compaction mode for long conversation contexts.","oneOf":[{"description":"Disable proactive compaction.","type":"string","const":"off"},{"description":"Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.","type":"string","const":"switch"},{"description":"Conservative compaction that prefers summary replacement.","type":"string","const":"safeguard"},{"description":"Aggressive truncation mode for tighter contexts.","type":"string","const":"aggressive"}]},"AgentConfig":{"description":"Agent orchestration configuration (`[agent]` section).","type":"object","properties":{"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"compact_context":{"description":"When true: bootstrap_max_chars=6000. Use for 13B or smaller models.","type":"boolean","default":false},"compaction":{"description":"Context compaction controls (`[agent.compaction]`).","$ref":"#/$defs/AgentCompactionConfig","default":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096}},"low_priority_tools":{"description":"Tool names treated as low-priority when `priority_scheduling_enabled = true`.","type":"array","default":["sessions_spawn","delegate"],"items":{"type":"string"}},"priority_scheduling_enabled":{"description":"Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.","type":"boolean","default":false},"read_only_tool_concurrency_window":{"description":"Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.","type":"integer","format":"uint","default":2,"minimum":0},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}}},"AgentLimits":{"description":"Optional admission limits for rf-started turns of a named agent.","type":"object","properties":{"max_concurrent_turns":{"type":["integer","null"],"format":"uint32","minimum":0},"max_cost_per_day_cents":{"type":["integer","null"],"format":"uint64","minimum":0}},"additionalProperties":false},"AuditConfig":{"description":"Audit logging configuration","type":"object","properties":{"log_path":{"description":"Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).","type":"string","default":"audit.log"},"max_size_mb":{"description":"Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).","type":"integer","format":"uint32","default":100,"minimum":0}}},"AuthConfig":{"description":"Authentication and external credential import configuration (`[auth]` section).","type":"object","properties":{"codex_auth_json_auto_import":{"description":"Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.","type":"boolean","default":false},"codex_auth_json_path":{"description":"Source path for Codex CLI auth.json import.","type":"string","default":"~/.codex/auth.json"}}},"AutonomyConfig":{"type":"object","properties":{"acknowledge_unrestricted_profile":{"description":"Operator acknowledgement for an intentionally unrestricted profile.\nThis suppresses doctor noise only; it does not alter policy behavior.","type":"boolean","default":false},"forbidden_paths":{"description":"Explicit path denylist. Default includes system-critical paths.\n\nFails closed: omitting the key keeps the built-in list rather than\nemptying it, so a partial `[autonomy]` section never removes the\ndenylist.","type":"array","default":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"items":{"type":"string"}},"level":{"description":"Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).","$ref":"#/$defs/AutonomyLevel","default":"full"},"max_cost_per_day_cents":{"description":"Maximum cost per day in cents per policy. Default: unset (no ceiling).","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"scopes":{"description":"Scope-based tool access control: per-user/channel/chat-type allow/deny rules.","$ref":"#/$defs/ScopeConfig","default":{"assign_owners":[],"default":"allow","rules":[]}},"workspace_only":{"description":"Restrict file writes and command paths to the workspace directory. Default: `true`.\n\nFails closed: a `[autonomy]` section that omits this key keeps the\nworkspace restriction on, so a partial section can never widen the\nfilesystem reach by accident.","type":"boolean","default":true}}},"AutonomyLevel":{"description":"How much autonomy the agent has","oneOf":[{"description":"Read-only: can observe but not act","type":"string","const":"readonly"},{"description":"Supervised: acts but requires approval for risky operations","type":"string","const":"supervised"},{"description":"Full: autonomous execution within policy bounds","type":"string","const":"full"}]},"BackendSelection":{"description":"Which decision backend runs: `auto` (the factory's order) or one kind.","type":"string"},"BrowserComputerUseConfig":{"description":"Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.","type":"object","properties":{"api_key":{"description":"Optional bearer token (retained only for config secret handling).","type":["string","null"],"default":null}}},"BrowserConfig":{"description":"Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.","type":"object","properties":{"allowed_domains":{"description":"Allowed domains for `web_fetch` (exact or subdomain match).","type":"array","default":[],"items":{"type":"string"}},"computer_use":{"description":"Computer-use sidecar config (retained only for `api_key` secret handling).","$ref":"#/$defs/BrowserComputerUseConfig","default":{"api_key":null}}}},"ChannelsConfig":{"description":"Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.","type":"object","properties":{"cli":{"description":"Enable the CLI interactive channel. Default: `true`.","type":"boolean","default":true},"dingtalk":{"description":"DingTalk channel configuration.","anyOf":[{"$ref":"#/$defs/DingTalkConfig"},{"type":"null"}]},"discord":{"description":"Discord bot channel configuration.","anyOf":[{"$ref":"#/$defs/DiscordConfig"},{"type":"null"}]},"email":{"description":"Email channel configuration.","anyOf":[{"$ref":"#/$defs/EmailConfig"},{"type":"null"}]},"imessage":{"description":"iMessage channel configuration (macOS only).","anyOf":[{"$ref":"#/$defs/IMessageConfig"},{"type":"null"}]},"irc":{"description":"IRC channel configuration.","anyOf":[{"$ref":"#/$defs/IrcConfig"},{"type":"null"}]},"lark":{"description":"Lark/Feishu channel configuration.","anyOf":[{"$ref":"#/$defs/LarkConfig"},{"type":"null"}]},"linq":{"description":"Linq Partner API channel configuration.","anyOf":[{"$ref":"#/$defs/LinqConfig"},{"type":"null"}]},"mattermost":{"description":"Mattermost bot channel configuration.","anyOf":[{"$ref":"#/$defs/MattermostConfig"},{"type":"null"}]},"nextcloud_talk":{"description":"Nextcloud Talk bot channel configuration.","anyOf":[{"$ref":"#/$defs/NextcloudTalkConfig"},{"type":"null"}]},"qq":{"description":"QQ Official Bot channel configuration.","anyOf":[{"$ref":"#/$defs/QQConfig"},{"type":"null"}]},"ramflux":{"description":"Local ramflux agent-host bridge.","anyOf":[{"$ref":"#/$defs/RamfluxConfig"},{"type":"null"}],"default":null},"signal":{"description":"Signal channel configuration.","anyOf":[{"$ref":"#/$defs/SignalConfig"},{"type":"null"}]},"slack":{"description":"Slack bot channel configuration.","anyOf":[{"$ref":"#/$defs/SlackConfig"},{"type":"null"}]},"telegram":{"description":"Telegram bot channel configuration.","anyOf":[{"$ref":"#/$defs/TelegramConfig"},{"type":"null"}]},"wacli":{"description":"wacli JSON-RPC daemon channel configuration.","anyOf":[{"$ref":"#/$defs/WacliConfig"},{"type":"null"}],"default":null},"webhook":{"description":"Webhook channel configuration.","anyOf":[{"$ref":"#/$defs/WebhookConfig"},{"type":"null"}]},"whatsapp":{"description":"WhatsApp channel configuration (Cloud API or Web mode).","anyOf":[{"$ref":"#/$defs/WhatsAppConfig"},{"type":"null"}]}}},"ChatConfig":{"description":"Interactive chat configuration (`[chat]`).","type":"object","properties":{"daemon":{"description":"How this chat process reaches the daemon it borrows channels from.","$ref":"#/$defs/ChatDaemonConfig","default":{"token":"","url":""}},"max_concurrent_visible_turns":{"description":"Maximum concurrent visible provider turns in the TUI Redux driver.","type":"integer","format":"uint","default":2,"minimum":0}}},"ChatDaemonConfig":{"description":"Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.","type":"object","properties":{"token":{"description":"Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.","type":"string","default":""},"url":{"description":"Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.","type":"string","default":""}}},"CircuitBreakerConfig":{"description":"The per-backend circuit breaker.","type":"object","properties":{"cooldown_secs":{"description":"Seconds the breaker stays open (1 to 3600).","type":"integer","format":"uint32","default":60,"minimum":0},"failure_threshold":{"description":"Consecutive failures before the breaker opens (1 to 100).","type":"integer","format":"uint32","default":5,"minimum":0}}},"ClassificationRule":{"description":"A single classification rule mapping message patterns to a model hint.","type":"object","properties":{"hint":{"description":"Must match a `[[model_routes]]` hint value.","type":"string"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"max_length":{"description":"Only match if message length <= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"min_length":{"description":"Only match if message length >= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"patterns":{"description":"Case-sensitive literal matches (for \"```\", \"fn \", etc.).","type":"array","default":[],"items":{"type":"string"}},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0}},"required":["hint"]},"CloudflareTunnelConfig":{"type":"object","properties":{"token":{"description":"Cloudflare Tunnel token (from Zero Trust dashboard)","type":"string"}},"required":["token"]},"ComplianceConfig":{"type":"object","properties":{"eu_ai_act":{"$ref":"#/$defs/EuAiActComplianceConfig","default":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null}},"interaction_notice":{"$ref":"#/$defs/InteractionNoticeConfig","default":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}}},"ComposioConfig":{"description":"Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.","type":"object","properties":{"api_key":{"description":"Composio API key (stored encrypted when secrets.encrypt = true)","type":["string","null"],"default":null},"entity_id":{"description":"Default entity ID for multi-user setups","type":"string","default":"default"}}},"CostConfig":{"description":"Cost tracking and budget enforcement configuration (`[cost]` section).","type":"object","properties":{"allow_override":{"description":"Allow requests to exceed budget with --override flag (default: false)","type":"boolean","default":false},"daily_limit_usd":{"description":"Daily spending limit in USD (default: unset, no limit; 0 refuses every priced turn)","type":["number","null"],"format":"double","default":null},"monthly_limit_usd":{"description":"Monthly spending limit in USD (default: unset, no limit)","type":["number","null"],"format":"double","default":null},"prices":{"description":"Per-model pricing (USD per 1M tokens)","type":"object","additionalProperties":{"$ref":"#/$defs/ModelPricing"},"default":{}},"warn_at_percent":{"description":"Warn when spending reaches this percentage of a configured limit (default: 80)","type":"integer","format":"uint8","default":80,"maximum":255,"minimum":0}}},"CredentialRefSetting":{"description":"Which credential a decision backend uses. A reference, never a secret.","type":"string"},"CronConfig":{"description":"Cron job configuration (`[cron]` section).","type":"object","properties":{"max_run_history":{"description":"Maximum number of historical cron run records to retain. Default: `50`.","type":"integer","format":"uint32","default":50,"minimum":0}}},"CustomTunnelConfig":{"type":"object","properties":{"health_url":{"description":"Optional URL to check tunnel health","type":["string","null"]},"start_command":{"description":"Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"","type":"string"},"url_pattern":{"description":"Optional regex to extract public URL from command stdout","type":["string","null"]}},"required":["start_command"]},"DecisionBackendConfig":{"description":"The decision backend (`[decision_engine.backend]`).","type":"object","properties":{"circuit_breaker":{"description":"The circuit breaker.","$ref":"#/$defs/CircuitBreakerConfig","default":{"cooldown_secs":60,"failure_threshold":5}},"credential_ref":{"description":"The credential reference: `\"\"`, `\"none\"` or `cred-`.","$ref":"#/$defs/CredentialRefSetting","default":""},"endpoint":{"description":"The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.","type":"string","default":""},"kind":{"description":"`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).","$ref":"#/$defs/BackendSelection","default":"auto"},"max_request_bytes":{"description":"Largest request body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":65536,"minimum":0},"max_response_bytes":{"description":"Largest response body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":262144,"minimum":0},"model":{"description":"The model the endpoint serves; one exact version for a hosted\nservice.","type":"string","default":""},"pinned_snapshot":{"description":"The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.","type":"string"},"remote_enabled":{"description":"Whether decision state may leave this machine. Default `false`.","type":"boolean","default":false},"timeout_ms":{"description":"Transport timeout (10 ms up to the extra latency budget).","type":"integer","format":"uint32","default":250,"minimum":0}}},"DecisionEngineConfig":{"type":"object","properties":{"backend":{"anyOf":[{"$ref":"#/$defs/DecisionBackendConfig"},{"type":"null"}]},"candidates":{"type":"integer","format":"uint32","default":5,"minimum":0},"enabled":{"type":"boolean","default":false},"mode":{"$ref":"#/$defs/DecisionMode","default":"pre"},"observe_queue":{"type":"integer","format":"uint32","default":64,"minimum":0},"prompt_budget_tokens":{"type":"integer","format":"uint32","default":300,"minimum":0},"telemetry_cap":{"type":"integer","format":"uint32","default":1000,"minimum":0},"timeout_ms":{"type":"integer","format":"uint32","default":1500,"minimum":0},"latency_budget_ms":{"description":"The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.","type":"integer","format":"uint64","default":500,"minimum":0},"token_ratio_limit":{"description":"Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).","type":"number","format":"float","default":0.3499999940395355},"max_candidates":{"description":"The most candidates a turn considers (1 to 32).","type":"integer","format":"uint8","default":12,"maximum":255,"minimum":0}}},"DecisionMode":{"type":"string","enum":["pre","post","both"]},"DeclarationOfConformityConfig":{"type":"object","properties":{"applicable_union_law":{"type":"array","default":[],"items":{"type":"string"}},"artifact_path":{"type":["string","null"],"default":null},"artifact_version":{"type":["string","null"],"default":null},"conformity_assessment_procedure":{"type":["string","null"],"default":null},"conformity_statement":{"type":["string","null"],"default":null},"harmonised_standards":{"type":"array","default":[],"items":{"type":"string"}},"issue_date":{"type":["string","null"],"default":null},"issue_place":{"type":["string","null"],"default":null},"notified_body_certificate":{"type":["string","null"],"default":null},"notified_body_identification_number":{"type":["string","null"],"default":null},"notified_body_name":{"type":["string","null"],"default":null},"personal_data_compliance_statement":{"type":["string","null"],"default":null},"processes_personal_data":{"type":"boolean","default":false},"provider_address":{"type":["string","null"],"default":null},"provider_name":{"type":["string","null"],"default":null},"signer_function":{"type":["string","null"],"default":null},"signer_name":{"type":["string","null"],"default":null},"signer_on_behalf_of":{"type":["string","null"],"default":null},"sole_responsibility_statement":{"type":["string","null"],"default":null},"standards_not_applicable_reason":{"type":["string","null"],"default":null},"system_name":{"type":["string","null"],"default":null},"system_reference":{"type":["string","null"],"default":null},"system_type":{"type":["string","null"],"default":null}}},"DelegateAgentConfig":{"description":"Configuration for a delegate sub-agent used by the `delegate` tool.","type":"object","properties":{"agentic":{"description":"Agentic sub-agent mode (multi-turn tool-call loop). Default true; an\nexplicit `false` makes the agent answer-only with no tools.","type":"boolean","default":true},"allowed_tools":{"description":"Allowlist of tool names available to the sub-agent in agentic mode.\nEmpty or omitted means all tools, the same as `[\"*\"]`.","type":"array","default":[],"items":{"type":"string"}},"api_key":{"description":"Optional API key override","type":["string","null"],"default":null},"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"autonomy":{"description":"The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.","anyOf":[{"$ref":"#/$defs/AutonomyLevel"},{"type":"null"}]},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"enabled":{"description":"Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.","type":"boolean","default":true},"identity_dir":{"description":"Optional identity files directory relative to workspace root.","type":["string","null"],"default":null},"limits":{"$ref":"#/$defs/AgentLimits","default":{"max_concurrent_turns":null,"max_cost_per_day_cents":null}},"max_depth":{"description":"Max recursion depth for nested delegation","type":"integer","format":"uint32","default":8,"minimum":0},"memory_scope":{"description":"Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".","type":["string","null"],"default":null},"model":{"description":"Model name","type":"string"},"provider":{"description":"Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")","type":"string"},"spawn_enabled":{"description":"Whether this agent is allowed to be targeted by sessions_spawn (default: true).","type":["boolean","null"],"default":null},"system_prompt":{"description":"Optional system prompt for the sub-agent","type":["string","null"],"default":null},"temperature":{"description":"Temperature override","type":["number","null"],"format":"double","default":null},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}},"required":["provider","model"]},"DingTalkConfig":{"description":"DingTalk configuration for Stream Mode messaging","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"client_id":{"description":"Client ID (AppKey) from DingTalk developer console","type":"string"},"client_secret":{"description":"Client Secret (AppSecret) from DingTalk developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["client_id","client_secret"]},"DiscordConfig":{"description":"Discord bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Discord user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Discord bot token (from Discord Developer Portal).","type":"string"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"guild_id":{"description":"Optional guild (server) ID to restrict the bot to a single guild.","type":["string","null"]},"listen_to_bots":{"description":"When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.","type":"boolean","default":false}},"required":["bot_token"]},"DmPolicy":{"description":"Policy for direct-message handling.","oneOf":[{"description":"Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).","type":"string","const":"pairing"},{"description":"Accept only senders listed in `allowed_from`.","type":"string","const":"allowlist"},{"description":"Accept any direct sender.","type":"string","const":"open"},{"description":"Ignore direct messages.","type":"string","const":"disabled"}]},"DockerRuntimeConfig":{"description":"Docker runtime configuration (`[runtime.docker]` section).","type":"object","properties":{"allowed_workspace_roots":{"description":"Optional workspace root allowlist for Docker mount validation.","type":"array","default":[],"items":{"type":"string"}},"cpu_limit":{"description":"Optional CPU limit (`None` = no explicit limit).","type":["number","null"],"format":"double","default":1.0},"image":{"description":"Runtime image used to execute shell commands.","type":"string","default":"alpine:3.20"},"memory_limit_mb":{"description":"Optional memory limit in MB (`None` = no explicit limit).","type":["integer","null"],"format":"uint64","default":512,"minimum":0},"mount_workspace":{"description":"Mount configured workspace into `/workspace`.","type":"boolean","default":true},"network":{"description":"Docker network mode (`none`, `bridge`, etc.).","type":"string","default":"none"},"read_only_rootfs":{"description":"Mount root filesystem as read-only.","type":"boolean","default":true}}},"EmailConfig":{"description":"Email channel configuration","type":"object","properties":{"allowed_senders":{"description":"Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)","type":"array","default":[],"items":{"type":"string"}},"from_address":{"description":"From address for outgoing emails","type":"string"},"idle_timeout_secs":{"description":"IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes","type":"integer","format":"uint64","default":1740,"minimum":0},"imap_folder":{"description":"IMAP folder to poll (default: INBOX)","type":"string","default":"INBOX"},"imap_host":{"description":"IMAP server hostname","type":"string"},"imap_port":{"description":"IMAP server port (default: 993 for TLS)","type":"integer","format":"uint16","default":993,"maximum":65535,"minimum":0},"password":{"description":"Email password for authentication","type":"string"},"smtp_host":{"description":"SMTP server hostname","type":"string"},"smtp_port":{"description":"SMTP server port (default: 465 for TLS)","type":"integer","format":"uint16","default":465,"maximum":65535,"minimum":0},"smtp_tls":{"description":"Use TLS for SMTP (default: true)","type":"boolean","default":true},"username":{"description":"Email username for authentication","type":"string"}},"required":["imap_host","smtp_host","username","password","from_address"]},"EmbeddingRouteConfig":{"description":"Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"dimensions":{"description":"Optional embedding dimension override for this route","type":["integer","null"],"format":"uint","default":null,"minimum":0},"hint":{"description":"Route hint name (e.g. \"semantic\", \"archive\", \"faq\")","type":"string"},"model":{"description":"Embedding model to use with that provider","type":"string"},"provider":{"description":"Embedding provider (`none`, `openai`, or `custom:`)","type":"string"}},"required":["hint","provider","model"]},"EuAiActClassificationConfig":{"type":"object","properties":{"assessed_at":{"type":["string","null"],"default":null},"owner":{"type":["string","null"],"default":null},"status":{"$ref":"#/$defs/EuAiActRiskClassification","default":"unclassified"}}},"EuAiActComplianceConfig":{"type":"object","properties":{"classification":{"$ref":"#/$defs/EuAiActClassificationConfig","default":{"assessed_at":null,"owner":null,"status":"unclassified"}},"declaration":{"$ref":"#/$defs/DeclarationOfConformityConfig","default":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null}},"incident_store_path":{"type":["string","null"],"default":null}}},"EuAiActRiskClassification":{"type":"string","enum":["unclassified","high_risk","not_high_risk"]},"FitnessConfig":{"description":"Calendar schedule, evidence thresholds, and retention for fitness v2.","type":"object","properties":{"auto_run":{"description":"Run the daily fitness worker in daemon mode.","type":"boolean","default":true},"max_backfill_days":{"description":"Maximum number of closed days recovered after downtime.","type":"integer","format":"uint32","default":7,"minimum":0},"min_coverage":{"description":"Minimum available metric weight required to publish a final score.","type":"number","format":"double","default":0.6},"min_samples":{"description":"Minimum samples required before an evidence-derived subscore is usable.","type":"integer","format":"uint","default":5,"minimum":0},"retention_days":{"description":"Number of daily JSON reports retained on disk.","type":"integer","format":"uint32","default":180,"minimum":0},"run_at":{"description":"Local wall-clock time (`HH:MM`) at which the previous day is scored.","type":"string","default":"00:10"},"timezone":{"description":"IANA timezone used to define closed calendar days.","type":"string","default":"UTC"}}},"GatewayConfig":{"description":"Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.","type":"object","properties":{"allow_public_bind":{"description":"Allow binding to non-localhost without a tunnel (default: false)","type":"boolean","default":false},"api_rate_limit_per_minute":{"description":"Max `/api/*` requests per minute per authenticated token.","type":"integer","format":"uint32","default":60,"minimum":0},"channel_webhook_dedup_ttl_secs":{"description":"How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.","type":"integer","format":"uint64","default":86400,"minimum":0},"host":{"description":"Gateway host (default: 127.0.0.1)","type":"string","default":"127.0.0.1"},"idempotency_max_keys":{"description":"Maximum distinct idempotency keys retained in memory.","type":"integer","format":"uint","default":10000,"minimum":0},"idempotency_ttl_secs":{"description":"TTL for webhook idempotency keys.","type":"integer","format":"uint64","default":300,"minimum":0},"pair_rate_limit_per_minute":{"description":"Max `/pair` requests per minute per client key.","type":"integer","format":"uint32","default":10,"minimum":0},"paired_tokens":{"description":"Paired bearer tokens (managed automatically, not user-edited)","type":"array","default":[],"items":{"type":"string"}},"port":{"description":"Gateway port (default: 16830)","type":"integer","format":"uint16","default":16830,"maximum":65535,"minimum":0},"rate_limit_max_keys":{"description":"Maximum distinct client keys tracked by gateway rate limiter maps.","type":"integer","format":"uint","default":10000,"minimum":0},"require_pairing":{"description":"Require pairing before accepting requests (default: true)","type":"boolean","default":true},"targeted_agents":{"description":"Switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). Default true. While false, any\notherwise-valid named target answers 409 `agent_disabled` and never\nruns as Main.","type":"boolean","default":true},"trust_forwarded_headers":{"description":"Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.","type":"boolean","default":false},"webhook_rate_limit_per_minute":{"description":"Max `/webhook` requests per minute per client key.","type":"integer","format":"uint32","default":60,"minimum":0}}},"GroupPolicy":{"description":"Policy for group-message handling.","oneOf":[{"description":"Accept only groups listed in `group_allow_from`.","type":"string","const":"allowlist"},{"description":"Accept any group.","type":"string","const":"open"},{"description":"Ignore group messages.","type":"string","const":"disabled"}]},"GroupReplyMode":{"description":"How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.","oneOf":[{"description":"Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).","type":"string","const":"off"},{"description":"Reply only when the bot is @-mentioned (legacy `mention_only = true`).","type":"string","const":"mention-only"},{"description":"Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).","type":"string","const":"smart"}]},"HeartbeatConfig":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]` section).","type":"object","properties":{"active_hours":{"description":"Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.","type":"array","default":[8,23],"items":{"type":"integer","format":"uint8","maximum":255,"minimum":0}},"interval_minutes":{"description":"Interval in minutes between heartbeat pings. Default: `30`.","type":"integer","format":"uint32","default":30,"minimum":0},"prompt":{"description":"Prompt used by heartbeat worker when dispatching tasks.","type":"string","default":"Check HEARTBEAT.md and follow instructions."}}},"HttpRequestConfig":{"description":"HTTP request tool configuration (`[http_request]` section).","type":"object","properties":{"max_response_size":{"description":"Maximum response size in bytes (default: 1MB)","type":"integer","format":"uint","default":1000000,"minimum":0},"timeout_secs":{"description":"Request timeout in seconds (default: 30)","type":"integer","format":"uint64","default":30,"minimum":0}}},"IMessageConfig":{"description":"iMessage channel configuration (macOS only).","type":"object","properties":{"allowed_contacts":{"description":"Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.","type":"array","items":{"type":"string"}},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["allowed_contacts"]},"IdentityBindingConfig":{"description":"Startup identity binding entry (`[[identity_bindings]]`).","type":"object","properties":{"channel":{"type":"string"},"channel_account":{"type":"string"},"display_name":{"type":["string","null"],"default":null},"user_id":{"type":"string"}},"required":["user_id","channel","channel_account"]},"IdentityConfig":{"description":"Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.","type":"object","properties":{"aieos_inline":{"description":"Inline AIEOS JSON (alternative to file path)","type":["string","null"],"default":null},"aieos_path":{"description":"Path to AIEOS JSON file (relative to workspace)","type":["string","null"],"default":null},"format":{"description":"Identity format: \"openclaw\" (default) or \"aieos\"","type":"string","default":"openclaw"}}},"InteractionNoticeApplicability":{"type":"string","enum":["required","not_applicable"]},"InteractionNoticeConfig":{"type":"object","properties":{"applicability":{"$ref":"#/$defs/InteractionNoticeApplicability","default":"required"},"exception_owner":{"type":["string","null"],"default":null},"exception_reviewed_at":{"type":["string","null"],"default":null},"text":{"type":"string","default":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers."},"version":{"type":"string","default":"1"}}},"IrcConfig":{"description":"IRC channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed nicknames (case-insensitive) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"channels":{"description":"Channels to join on connect","type":"array","default":[],"items":{"type":"string"}},"mention_only":{"description":"When true, only process channel/group messages that mention the bot.","type":"boolean","default":false},"nickname":{"description":"Bot nickname","type":"string"},"nickserv_password":{"description":"NickServ IDENTIFY password","type":["string","null"]},"port":{"description":"IRC server port (default: 6697 for TLS)","type":"integer","format":"uint16","default":6697,"maximum":65535,"minimum":0},"sasl_password":{"description":"SASL PLAIN password (IRCv3)","type":["string","null"]},"server":{"description":"IRC server hostname","type":"string"},"server_password":{"description":"Server password (for bouncers like ZNC)","type":["string","null"]},"username":{"description":"Username (defaults to nickname if not set)","type":["string","null"]},"verify_tls":{"description":"Verify TLS certificate (default: true)","type":["boolean","null"]}},"required":["server","nickname"]},"LarkConfig":{"description":"Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from Lark/Feishu developer console","type":"string"},"app_secret":{"description":"App Secret from Lark/Feishu developer console","type":"string"},"encrypt_key":{"description":"Encrypt key for webhook message decryption (optional)","type":["string","null"],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"port":{"description":"HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"receive_mode":{"description":"Event receive mode: \"websocket\" (default) or \"webhook\"","$ref":"#/$defs/LarkReceiveMode","default":"websocket"},"use_feishu":{"description":"Whether to use the Feishu (Chinese) endpoint instead of Lark (International)","type":"boolean","default":false},"verification_token":{"description":"Verification token for webhook validation (optional)","type":["string","null"],"default":null}},"required":["app_id","app_secret"]},"LarkReceiveMode":{"description":"How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.","type":"string","enum":["websocket","webhook"]},"LinqConfig":{"type":"object","properties":{"allowed_senders":{"description":"Allowed sender handles (phone numbers) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"api_token":{"description":"Linq Partner API token (Bearer auth)","type":"string"},"from_phone":{"description":"Phone number to send from (E.164 format)","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"signing_secret":{"description":"Webhook signing secret for signature verification","type":["string","null"],"default":null}},"required":["api_token","from_phone"]},"MattermostConfig":{"description":"Mattermost bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Mattermost user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Mattermost bot access token.","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.","type":["boolean","null"],"default":null},"thread_replies":{"description":"When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.","type":["boolean","null"],"default":null},"url":{"description":"Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).","type":"string"}},"required":["url","bot_token"]},"McpConfig":{"type":"object","properties":{"servers":{"description":"Named MCP server definitions","type":"object","additionalProperties":{"$ref":"#/$defs/McpServerConfig"},"default":{}},"workspace_servers":{"description":"Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.","$ref":"#/$defs/WorkspaceMcpServers"}}},"McpServerConfig":{"type":"object","properties":{"allow_tools":{"description":"Optional allow-list of exposed tools (empty = all)","type":"array","default":[],"items":{"type":"string"}},"args":{"description":"Command args for stdio mode","type":"array","default":[],"items":{"type":"string"}},"command":{"description":"Command for stdio mode","type":["string","null"],"default":null},"deny_tools":{"description":"Optional deny-list of exposed tools","type":"array","default":[],"items":{"type":"string"}},"env":{"description":"Environment variables for stdio mode","type":"object","additionalProperties":{"type":"string"},"default":{}},"request_timeout_ms":{"description":"Request timeout in milliseconds","type":"integer","format":"uint64","default":30000,"minimum":0},"startup_timeout_ms":{"description":"Startup timeout in milliseconds","type":"integer","format":"uint64","default":10000,"minimum":0},"tool_name_prefix":{"description":"Prefix used in tool naming and routing","type":"string","default":"mcp"},"transport":{"description":"Transport type: stdio or http","$ref":"#/$defs/McpTransport","default":"stdio"},"url":{"description":"URL for HTTP mode (streamable HTTP endpoint)","type":["string","null"],"default":null},"working_dir":{"description":"Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).","type":["string","null"]}}},"McpServerRuntimeConfig":{"type":"object","properties":{"allowed_origins":{"description":"Allowed browser origins for future streamable HTTP clients.","type":"array","default":["claude.ai","openai.com","localhost"],"items":{"type":"string"}},"bind":{"description":"Advertised bind address. The gateway may still be started with a CLI port override.","type":"string","default":"127.0.0.1:16831"},"exposed_tools":{"description":"Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.","type":"array","default":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"items":{"type":"string"}},"jwt_algorithms":{"description":"Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.","type":"array","default":["RS256"],"items":{"type":"string"}},"jwt_audience":{"description":"Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.","type":["string","null"],"default":null},"jwt_issuer":{"description":"Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.","type":["string","null"],"default":null},"jwt_jwks":{"description":"Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.","type":["string","null"],"default":null},"jwt_jwks_cache_ttl_secs":{"description":"Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.","type":"integer","format":"uint64","default":300,"minimum":0},"jwt_jwks_uri":{"description":"Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.","type":["string","null"],"default":null},"jwt_public_key_pem":{"description":"PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.","type":["string","null"],"default":null},"rate_limit_rps":{"description":"Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.","type":"integer","format":"uint32","default":10,"minimum":0},"require_auth":{"description":"Require an authenticated external identity for mutating calls.","type":"boolean","default":true}}},"McpTransport":{"type":"string","enum":["stdio","http"]},"MediaConfig":{"description":"Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.","type":"object","properties":{"audio_model":{"description":"Audio model name (Ollama model or OpenAI model). Default: \"whisper\".","type":"string","default":"whisper"},"audio_ollama_url":{"description":"Ollama base URL for audio transcription. Default: \"http://localhost:11434\".","type":"string","default":"http://localhost:11434"},"audio_provider":{"description":"Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".","type":"string","default":"none"},"max_audio_size_mb":{"description":"Maximum audio attachment size in MiB. Default: 20.","type":"integer","format":"uint","default":20,"minimum":0},"max_video_size_mb":{"description":"Maximum video attachment size in MiB. Default: 50.","type":"integer","format":"uint","default":50,"minimum":0},"video_max_frames":{"description":"Maximum video frames to extract per video. Default: 4.","type":"integer","format":"uint","default":4,"minimum":0},"video_provider":{"description":"Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".","type":"string","default":"none"}}},"MemoryConfig":{"description":"Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.","type":"object","properties":{"acl_enabled":{"description":"Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.","type":"boolean","default":false},"archive_after_days":{"description":"Archive daily/session files older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"auto_hydrate":{"description":"Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing","type":"boolean","default":true},"auto_save":{"description":"Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.","type":"boolean","default":true},"backend":{"description":"\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).","type":"string","default":"sqlite"},"conversation_retention_days":{"description":"For sqlite backend: prune conversation rows older than this many days","type":"integer","format":"uint32","default":3,"minimum":0},"daily_retention_days":{"description":"For sqlite backend: prune daily rows older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"embedding_cache_size":{"description":"Max embedding cache entries before LRU eviction","type":"integer","format":"uint","default":10000,"minimum":0},"embedding_dimensions":{"description":"Embedding vector dimensions","type":"integer","format":"uint","default":384,"minimum":0},"embedding_model":{"description":"Embedding model name (e.g. \"text-embedding-3-small\")","type":"string","default":"prx-local-hash-v1"},"embedding_provider":{"description":"Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"","type":"string","default":"local"},"events":{"description":"Raw/quasi-raw message event recording controls (`[memory.events]`).","$ref":"#/$defs/MemoryEventsConfig","default":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true}},"keyword_weight":{"description":"Weight for keyword BM25 in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.3},"legacy_conversation_turns_visible":{"description":"Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.","type":"boolean","default":true},"lucid_budget":{"description":"Token budget for lucid (replaces OPENPRX_LUCID_BUDGET)","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"lucid_cmd":{"description":"Path to lucid binary (replaces OPENPRX_LUCID_CMD)","type":["string","null"],"default":null},"lucid_failure_cooldown_ms":{"description":"Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)","type":"integer","format":"uint64","default":60000,"minimum":0},"lucid_local_hit_threshold":{"description":"Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)","type":"integer","format":"uint","default":3,"minimum":0},"lucid_recall_timeout_ms":{"description":"Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)","type":"integer","format":"uint64","default":5000,"minimum":0},"lucid_store_timeout_ms":{"description":"Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)","type":"integer","format":"uint64","default":3000,"minimum":0},"min_relevance_score":{"description":"Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4","type":"number","format":"double","default":0.4},"purge_after_days":{"description":"Purge archived files older than this many days","type":"integer","format":"uint32","default":30,"minimum":0},"semantic":{"description":"Semantic memory promotion controls (`[memory.semantic]`).","$ref":"#/$defs/MemorySemanticConfig","default":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30}},"sqlite_open_timeout_secs":{"description":"For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"sqlite_read_pool_size":{"description":"For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"vector_candidate_cap":{"description":"How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.","type":"integer","format":"uint","default":2000,"minimum":0},"vector_weight":{"description":"Weight for vector similarity in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.7}}},"MemoryEventsConfig":{"description":"Raw message event recording configuration (`[memory.events]`).","type":"object","properties":{"record_assistant_messages":{"description":"Record assistant replies.","type":"boolean","default":true},"record_tool_events":{"description":"Record tool/event payloads by default.","type":"boolean","default":false},"record_user_messages":{"description":"Record inbound/user messages.","type":"boolean","default":true}}},"MemorySemanticConfig":{"description":"Semantic memory promotion configuration (`[memory.semantic]`).","type":"object","properties":{"auto_promote_assistant_messages":{"description":"Auto-promote eligible assistant messages. Disabled by default to reduce noise.","type":"boolean","default":false},"auto_promote_user_messages":{"description":"Auto-promote eligible user messages into long-term semantic memories.","type":"boolean","default":true},"min_chars":{"description":"Minimum content length for semantic auto-promotion.","type":"integer","format":"uint","default":30,"minimum":0}}},"MemoryWebhookConfig":{"type":"object","properties":{"bind":{"description":"Socket address for the receiver (e.g. \"0.0.0.0:16899\").","type":"string","default":"0.0.0.0:16899"},"signing_secret":{"description":"Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.","type":["string","null"],"default":null},"token":{"description":"Required bearer token for incoming webhook events.","type":["string","null"],"default":null}}},"ModelOperationSetting":{"description":"The operations a `[[providers.models]]` entry may list.","type":"string","enum":["chat","embedding","decision_endpoint","rerank","image_generation","audio_generation","video_generation"]},"ModelPricing":{"description":"Per-model pricing entry (USD per 1M tokens).","type":"object","properties":{"cache_read":{"description":"Cache read input price per 1M tokens.","type":"number","format":"double","default":0.0},"cache_write":{"description":"Cache write/creation input price per 1M tokens.","type":"number","format":"double","default":0.0},"input":{"description":"Input price per 1M tokens","type":"number","format":"double","default":0.0},"output":{"description":"Output price per 1M tokens","type":"number","format":"double","default":0.0}}},"ModelRouteConfig":{"description":"Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"hint":{"description":"Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")","type":"string"},"level":{"type":["string","null"]},"model":{"description":"Model to use with that provider","type":"string"},"provider":{"description":"Provider to route to (must match a known provider name)","type":"string"},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true,"required":["hint","provider","model"]},"ModelSettings":{"description":"A model level plus explicit parameter overrides in `[model_settings.\"\"]`.","type":"object","properties":{"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"level":{"type":["string","null"]},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true},"MultimodalConfig":{"description":"Multimodal (image) handling configuration (`[multimodal]` section).","type":"object","properties":{"allow_remote_fetch":{"description":"Allow fetching remote image URLs (http/https). Disabled by default.","type":"boolean","default":false},"max_image_size_mb":{"description":"Maximum image payload size in MiB before base64 encoding.","type":"integer","format":"uint","default":5,"minimum":0},"max_images":{"description":"Maximum number of image attachments accepted per request.","type":"integer","format":"uint","default":4,"minimum":0}}},"NextcloudTalkConfig":{"description":"Nextcloud Talk bot configuration (webhook receive + OCS send API).","type":"object","properties":{"allowed_users":{"description":"Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Bot app token used for OCS API bearer auth.","type":"string"},"base_url":{"description":"Nextcloud base URL (e.g. \"https://cloud.example.com\").","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"webhook_secret":{"description":"Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).","type":["string","null"],"default":null}},"required":["base_url","app_token"]},"NgrokTunnelConfig":{"type":"object","properties":{"auth_token":{"description":"ngrok auth token","type":"string"},"domain":{"description":"Optional custom domain","type":["string","null"]}},"required":["auth_token"]},"NodeServerConfig":{"description":"Node daemon runtime config used by `prx-node`.","type":"object","properties":{"allowed_commands":{"description":"Command allowlist matched on first token.\n\nIn restricted mode this list is required unless explicitly set to `[\"*\"]`.","type":"array","default":["echo"],"items":{"type":"string"}},"bearer_token":{"description":"Required bearer token for /rpc.","type":"string","default":""},"blocked_commands":{"description":"Command denylist matched on first token. Always enforced.","type":"array","default":[],"items":{"type":"string"}},"exec_timeout_ms":{"description":"Default command timeout in milliseconds.","type":"integer","format":"uint64","default":15000,"minimum":0},"hmac_secret":{"description":"Optional HMAC signing secret.","type":["string","null"],"default":null},"listen_addr":{"description":"Listen address for node daemon.","type":"string","default":"127.0.0.1:8787"},"max_concurrent_tasks":{"description":"Maximum number of concurrent async command tasks.","type":"integer","format":"uint","default":8,"minimum":0},"max_output_bytes":{"description":"Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.","type":"integer","format":"uint","default":1048576,"minimum":0},"sandbox_root":{"description":"Sandbox root directory for read/write/cwd constraints.","type":"string","default":"."},"task_result_ttl_ms":{"description":"TTL for completed task results in milliseconds.","type":"integer","format":"uint64","default":3600000,"minimum":0},"tls_cert":{"description":"TLS certificate path (PEM).","type":["string","null"],"default":null},"tls_key":{"description":"TLS private key path (PEM).","type":["string","null"],"default":null},"tls_required":{"description":"Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.","type":"boolean","default":true}}},"NodesConfig":{"description":"Remote node proxy configuration for core-side RPC calls and node daemon defaults.","type":"object","properties":{"nodes":{"description":"Configured remote nodes.","type":"array","default":[],"items":{"$ref":"#/$defs/RemoteNodeConfig"}},"request_timeout_ms":{"description":"Default request timeout for node RPC calls.","type":"integer","format":"uint64","default":15000,"minimum":0},"retry_max":{"description":"Default max retries for node RPC calls.","type":"integer","format":"uint8","default":2,"maximum":255,"minimum":0},"server":{"description":"Embedded node server defaults used by `prx-node`.","$ref":"#/$defs/NodeServerConfig","default":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}}},"ObservabilityConfig":{"description":"Observability backend configuration (`[observability]` section).","type":"object","properties":{"backend":{"description":"\"none\" | \"log\" | \"prometheus\" | \"otel\"","type":"string","default":"none"},"otel_endpoint":{"description":"OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".","type":["string","null"],"default":null},"otel_service_name":{"description":"Service name reported to the OTel collector. Defaults to \"prx\".","type":["string","null"],"default":null}}},"OllamaProviderConfig":{"description":"Ollama-specific request options (`[providers.ollama]`).","type":"object","properties":{"num_ctx":{"description":"Explicit context window sent as Ollama `options.num_ctx`.","type":["integer","null"],"format":"uint","default":null,"minimum":0}}},"OsPagingConfig":{"description":"Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.","type":"object","properties":{"eviction_threshold":{"description":"Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.","type":"number","format":"double","default":0.7},"keep_recent_messages":{"description":"Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).","type":"integer","format":"uint","default":12,"minimum":0},"max_recalled_pages":{"description":"Maximum number of evicted pages (document chunks) recalled per turn.","type":"integer","format":"uint","default":10,"minimum":0},"proactive_retrieval":{"description":"Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.","type":"boolean","default":true},"retrieval_injection_role":{"description":"Role under which recalled pages are injected.","$ref":"#/$defs/RetrievalInjectionRole","default":"system"}}},"PluginsConfig":{"description":"WASM plugin runtime configuration.","type":"object","properties":{"enabled":{"description":"Load WASM plugins from `/plugins`. Default: `false`.","type":"boolean","default":false}},"additionalProperties":false},"ProviderModelConfig":{"description":"One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.","type":"object","properties":{"context_window":{"description":"The model's context window in tokens.","type":["integer","null"],"format":"uint32","minimum":0},"model":{"description":"The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.","type":["string","null"]},"native_tools":{"description":"Whether the model accepts native tool calls.","type":["boolean","null"]},"operations":{"description":"The complete list of operations the model executes; every operation not\nlisted is unsupported.","type":["array","null"],"items":{"$ref":"#/$defs/ModelOperationSetting"}},"provider":{"description":"The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.","type":"string"},"streaming":{"description":"Whether the model streams responses.","type":["boolean","null"]},"structured_output":{"description":"Whether the model honours a JSON-schema response format.","type":["boolean","null"]},"tool_call_dialect":{"description":"The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema_dialect":{"description":"The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]},"vision_input":{"description":"Whether the model accepts image input.","type":["boolean","null"]}},"required":["provider"]},"ProviderToolDialectConfig":{"description":"One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.","type":"object","properties":{"model":{"description":"The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.","type":["string","null"]},"provider":{"description":"The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.","type":"string"},"tool_call":{"description":"The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema":{"description":"The tool-schema dialect the endpoint accepts.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]}},"required":["provider"]},"ProvidersConfig":{"description":"Provider-specific runtime configuration (`[providers]`).","type":"object","properties":{"models":{"description":"Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.","type":"array","items":{"$ref":"#/$defs/ProviderModelConfig"}},"ollama":{"description":"Ollama-specific request options (`[providers.ollama]`).","$ref":"#/$defs/OllamaProviderConfig","default":{"num_ctx":null}},"tool_dialects":{"description":"Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).","type":"array","items":{"$ref":"#/$defs/ProviderToolDialectConfig"}}}},"ProxyConfig":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).","type":"object","properties":{"all_proxy":{"description":"Fallback proxy URL for all schemes.","type":["string","null"],"default":null},"http_proxy":{"description":"Proxy URL for HTTP requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"https_proxy":{"description":"Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"no_proxy":{"description":"No-proxy bypass list. Same format as NO_PROXY.","type":"array","default":[],"items":{"type":"string"}},"scope":{"description":"Proxy application scope.","$ref":"#/$defs/ProxyScope","default":"prx"},"services":{"description":"Service selectors used when scope = \"services\".","type":"array","default":[],"items":{"type":"string"}}}},"ProxyScope":{"description":"Proxy application scope — determines which outbound traffic uses the proxy.","oneOf":[{"description":"Use system environment proxy variables only.","type":"string","const":"environment"},{"description":"Apply proxy to all OpenPRX-managed HTTP traffic (default).","type":"string","const":"prx"},{"description":"Apply proxy only to explicitly listed service selectors.","type":"string","const":"services"}]},"QQConfig":{"description":"QQ Official Bot configuration (Tencent QQ Bot SDK)","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs. Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from QQ Bot developer console","type":"string"},"app_secret":{"description":"App Secret from QQ Bot developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["app_id","app_secret"]},"QueryClassificationConfig":{"description":"Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.","type":"object","properties":{"rules":{"description":"Classification rules evaluated in priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/ClassificationRule"}}}},"RamfluxAccountConfig":{"description":"Persona for one ramflux AI account. Missing fields fall back to the global agent.","type":"object","properties":{"cross_conversation_retrieval":{"description":"Cross-conversation memory retrieval. Off unless the owner sets it.","type":"boolean","default":false},"model":{"type":["string","null"],"default":null},"provider":{"type":["string","null"],"default":null},"scope_profile":{"type":["string","null"],"default":null},"system_prompt_file":{"description":"Path to a system-prompt file. Relative paths are resolved from the workspace.","type":["string","null"],"default":null}},"additionalProperties":false},"RamfluxAttachmentFetch":{"description":"Per-turn caps for `attachment.fetch`.","type":"object","properties":{"max_bytes":{"type":"integer","format":"uint64","default":5242880,"minimum":0},"max_per_turn":{"type":"integer","format":"uint8","default":4,"maximum":255,"minimum":0}},"additionalProperties":false},"RamfluxAuthorizationMode":{"description":"How prx combines its own setting with `bridge.hello.authorization`.","oneOf":[{"description":"Use the agent-host value. Until hello arrives, the effective mode is supervised.","type":"string","const":"follow_rf"},{"description":"Always supervised, even when the agent-host declares full.","type":"string","const":"supervised"},{"description":"Full only when the agent-host also declares full. Config alone never yields full.","type":"string","const":"full"}]},"RamfluxConfig":{"description":"Local ramflux agent-host bridge (`[channels_config.ramflux]`).","type":"object","properties":{"accounts":{"type":"object","additionalProperties":{"$ref":"#/$defs/RamfluxAccountConfig"},"default":{}},"allowed_block_types":{"type":"array","default":["Text","Markdown","Heading","KeyValue","Metric","List","TableFallback","Form","Input","Select","Progress","LogStream","Warning","Error","Success","Approval","ActionGroup","FilePreview","Fallback"],"items":{"type":"string"}},"attachment_fetch":{"$ref":"#/$defs/RamfluxAttachmentFetch","default":{"max_bytes":5242880,"max_per_turn":4}},"authorization_mode":{"$ref":"#/$defs/RamfluxAuthorizationMode","default":"follow_rf"},"encrypt_at_rest":{"type":"boolean","default":true},"max_in_flight_per_conversation":{"type":"integer","format":"uint8","default":1,"maximum":255,"minimum":0},"on_new_message":{"$ref":"#/$defs/RamfluxOnNewMessage","default":"queue"},"socket_path":{"description":"Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.","type":["string","null"],"default":null},"surface_limits":{"$ref":"#/$defs/RamfluxSurfaceLimits","default":{"max_actions":16,"max_blocks":32,"max_bytes":65536}},"turn_wall_clock_secs":{"description":"Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.","type":"integer","format":"uint64","default":120,"minimum":0}},"additionalProperties":false},"RamfluxOnNewMessage":{"description":"What to do with a new inbound message while a turn for that conversation is running.","type":"string","enum":["queue","interrupt"]},"RamfluxSurfaceLimits":{"description":"Limits for `reply.surface` blocks and actions.","type":"object","properties":{"max_actions":{"type":"integer","format":"uint32","default":16,"minimum":0},"max_blocks":{"type":"integer","format":"uint32","default":32,"minimum":0},"max_bytes":{"type":"integer","format":"uint32","default":65536,"minimum":0}},"additionalProperties":false},"ReliabilityCircuitBreakerConfig":{"description":"Process-local provider circuit policy (`[reliability.circuit_breaker]`).","type":"object","properties":{"enabled":{"description":"Enable protection for factory-built provider chains.","type":"boolean","default":true},"failure_threshold":{"description":"Consecutive transient failures that open a circuit (at least 1).","type":"integer","format":"uint32","default":5,"minimum":0},"max_open_secs":{"description":"Maximum doubled window, between open_secs and 3600 seconds.","type":"integer","format":"uint64","default":300,"minimum":0},"open_secs":{"description":"Initial open window in seconds (at least 1).","type":"integer","format":"uint64","default":30,"minimum":0}}},"ReliabilityConfig":{"description":"Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.","type":"object","properties":{"acknowledge_single_provider_risk":{"description":"Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.","type":"boolean","default":false},"api_keys":{"description":"Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.","type":"array","default":[],"items":{"type":"string"}},"channel_initial_backoff_secs":{"description":"Initial backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":2,"minimum":0},"channel_max_backoff_secs":{"description":"Max backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":60,"minimum":0},"circuit_breaker":{"description":"Per-provider consecutive failure protection.","$ref":"#/$defs/ReliabilityCircuitBreakerConfig","default":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30}},"fallback_providers":{"description":"Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).","type":"array","default":[],"items":{"type":"string"}},"model_fallbacks":{"description":"Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`","type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"default":{}},"provider_backoff_ms":{"description":"Base backoff (ms) for provider retry delay.","type":"integer","format":"uint64","default":500,"minimum":0},"provider_retries":{"description":"Retries per provider before failing over.","type":"integer","format":"uint32","default":2,"minimum":0},"scheduler_poll_secs":{"description":"Scheduler polling cadence in seconds.","type":"integer","format":"uint64","default":15,"minimum":0},"scheduler_retries":{"description":"Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.","type":"integer","format":"uint32","default":2,"minimum":0}}},"RemoteNodeConfig":{"description":"A remote node target for core-side node proxy calls.","type":"object","properties":{"bearer_token":{"description":"Bearer token for node RPC authentication.","type":"string"},"endpoint":{"description":"Base endpoint (e.g. \"http://127.0.0.1:8787\").","type":"string"},"hmac_secret":{"description":"Optional request signing key (HMAC-SHA256).","type":["string","null"],"default":null},"id":{"description":"Stable node ID used by the nodes tool.","type":"string"},"retry_max":{"description":"Optional per-node retry override.","type":["integer","null"],"format":"uint8","default":null,"maximum":255,"minimum":0},"timeout_ms":{"description":"Optional per-node timeout override.","type":["integer","null"],"format":"uint64","default":null,"minimum":0}},"required":["id","endpoint","bearer_token"]},"RetrievalInjectionRole":{"description":"Where recalled context pages are injected back into the request.","oneOf":[{"description":"Inject recalled pages as a leading `system` message (not user-visible).","type":"string","const":"system"},{"description":"Inject recalled pages as a leading `user` message.","type":"string","const":"user"}]},"RouterConfig":{"description":"Heuristic LLM router configuration (`[router]` section).","type":"object","properties":{"alpha":{"description":"Similarity score weight. Phase 1 keeps this at `0.0`.","type":"number","format":"float","default":0.0},"beta":{"description":"Capability score weight.","type":"number","format":"float","default":0.5},"delta":{"description":"Cost penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"epsilon":{"description":"Latency penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"gamma":{"description":"Elo score weight.","type":"number","format":"float","default":0.30000001192092896},"knn_k":{"description":"Number of nearest neighbors considered for voting. Default: `7`.","type":"integer","format":"uint","default":7,"minimum":0},"knn_min_records":{"description":"Minimum history records before KNN affects routing. Default: `10`.","type":"integer","format":"uint","default":10,"minimum":0},"models":{"description":"Candidate model registry.","type":"array","default":[],"items":{"$ref":"#/$defs/RouterModelConfig"}}}},"RouterModelConfig":{"description":"Static router metadata for one model candidate.","type":"object","properties":{"categories":{"description":"Capability categories such as `conversation`, `code`, or `analysis`.","type":"array","default":[],"items":{"type":"string"}},"cost_per_million_tokens":{"description":"USD cost per million tokens.","type":"number","format":"float","default":0.0},"elo_rating":{"description":"Initial Elo rating.","type":"number","format":"float","default":1000.0},"latency_ms":{"description":"Average latency in milliseconds.","type":"integer","format":"uint32","default":2000,"minimum":0},"max_context":{"description":"Maximum context window in tokens.","type":"integer","format":"uint","default":1000000,"minimum":0},"model_id":{"description":"Model identifier without provider prefix.","type":"string"},"provider":{"description":"Provider identifier.","type":"string"},"reserved_output_tokens":{"description":"Output tokens reserved for this model when planning input context.","type":["integer","null"],"format":"uint","minimum":0}},"required":["model_id","provider"]},"RuntimeConfig":{"description":"Runtime adapter configuration (`[runtime]` section).","type":"object","properties":{"codex_reasoning_effort":{"description":"Codex reasoning effort","type":["string","null"],"default":null},"codex_stream_idle_timeout_secs":{"description":"Codex stream idle timeout in seconds","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"docker":{"description":"Docker runtime settings (used when `kind = \"docker\"`).","$ref":"#/$defs/DockerRuntimeConfig","default":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true}},"idle_hang_secs":{"description":"Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"kind":{"description":"Runtime kind (`native` | `docker`).","type":"string","default":"native"},"long_task_warn_secs":{"description":"Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"managed_cgroup_root":{"description":"Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.","type":["string","null"],"default":null},"max_blocking_threads":{"description":"Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"reasoning_enabled":{"description":"Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported","type":["boolean","null"],"default":null},"shell_env_allowlist":{"description":"Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.","type":"array","default":[],"items":{"type":"string"}},"workdir":{"description":"Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.","type":["string","null"],"default":null}}},"SchedulerConfig":{"description":"Scheduler configuration for periodic task execution (`[scheduler]` section).","type":"object","properties":{"claim_lease_secs":{"description":"Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.","type":"integer","format":"uint64","default":90,"minimum":0},"max_tasks":{"description":"Maximum number of persisted scheduled tasks.","type":"integer","format":"uint","default":64,"minimum":0}}},"ScopeConfig":{"description":"Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```","type":"object","properties":{"assign_owners":{"description":"Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.","type":"array","default":[],"items":{"type":"string"}},"default":{"description":"Default action when no rule matches: \"allow\" (default) or \"deny\".","$ref":"#/$defs/ScopeDefault","default":"allow"},"rules":{"description":"Ordered list of scope rules evaluated top-to-bottom.","type":"array","default":[],"items":{"$ref":"#/$defs/ScopeRule"}}}},"ScopeDefault":{"description":"What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.","oneOf":[{"description":"Unmatched tool calls are allowed (the default).","type":"string","const":"allow"},{"description":"Unmatched tool calls are refused.","type":"string","const":"deny"}]},"ScopeRule":{"description":"A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.","type":"object","properties":{"assign_allow":{"description":"Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".","type":"array","default":[],"items":{"type":"string"}},"assign_deny":{"description":"Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.","type":"array","default":[],"items":{"type":"string"}},"channel":{"description":"Match by channel name: \"signal\", \"telegram\", \"discord\", etc.","type":["string","null"]},"chat_type":{"description":"Match by chat type: \"direct\", \"group\", or \"*\" for any type.","type":["string","null"]},"send_allow":{"description":"Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.","type":"array","default":[],"items":{"type":"string"}},"send_deny":{"description":"Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.","type":"array","default":[],"items":{"type":"string"}},"tools_allow":{"description":"Tool whitelist: only these tools are allowed (empty = all tools permitted).","type":"array","default":[],"items":{"type":"string"}},"tools_deny":{"description":"Tool blacklist: these tools are denied regardless of allow list.","type":"array","default":[],"items":{"type":"string"}},"user":{"description":"Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.","type":["string","null"]}}},"SecretsConfig":{"description":"Secrets encryption configuration (`[secrets]` section).","type":"object","properties":{"encrypt":{"description":"Enable encryption for API keys and tokens in config.toml","type":"boolean","default":true}}},"SecurityConfig":{"description":"Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.","type":"object","properties":{"audit":{"description":"Audit logging configuration","$ref":"#/$defs/AuditConfig","default":{"log_path":"audit.log","max_size_mb":100}},"workspace_hooks":{"description":"Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.","$ref":"#/$defs/WorkspaceHooks"}}},"SelfSystemConfig":{"description":"Self-system experimental automation config (`[self_system]`).","type":"object","properties":{"evolution_config_path":{"description":"Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG)","type":["string","null"],"default":null},"evolution_debug_raw":{"description":"Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW)","type":"boolean","default":false},"evolution_interval_hours":{"description":"Evolution scheduler interval in hours (daemon mode).","type":"integer","format":"uint32","default":24,"minimum":0},"evolution_judge_timeout_secs":{"description":"Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.","type":"integer","format":"uint64","default":180,"minimum":0},"evolution_model_max_micro_usd":{"description":"Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.","type":"integer","format":"uint64","default":0,"minimum":0},"evolution_model_max_tokens":{"description":"Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.","type":"integer","format":"uint64","default":16384,"minimum":0},"fitness":{"description":"Daily fitness snapshot policy.","$ref":"#/$defs/FitnessConfig","default":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"}},"fitness_interval_hours":{"description":"Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.","type":"integer","format":"uint64","default":24,"minimum":0}}},"SessionsSpawnConfig":{"description":"Sessions spawn configuration (`[sessions_spawn]` section).","type":"object","properties":{"cleanup_on_complete":{"description":"Remove worker workspace directory after process-mode completion.","type":"boolean","default":true},"default_mode":{"description":"Default execution mode for sessions_spawn (`task` or `process`).","type":"string","default":"task"},"process_memory_strategy":{"description":"Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.","type":"string","default":"shared_fabric"},"worker_workspace_root":{"description":"Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.","type":["string","null"],"default":null}}},"SignalConfig":{"type":"object","properties":{"account":{"description":"E.164 phone number of the signal-cli account (e.g. \"+1234567890\").","type":"string"},"allowed_from":{"description":"Allowed sender phone numbers (E.164) or \"*\" for all.","type":"array","default":[],"items":{"type":"string"}},"cli_path":{"description":"Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).","type":["string","null"],"default":null},"daemon_http_port":{"description":"Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"daemon_mode":{"description":"Deprecated: ignored. Accepted for backward compatibility with older config files.","type":["boolean","null"],"default":null},"data_dir":{"description":"signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_id":{"description":"Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group","type":["string","null"],"default":null},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"http_url":{"description":"Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.","type":"string","default":"http://localhost:8080"},"ignore_attachments":{"description":"Skip messages that are attachment-only (no text body).","type":"boolean","default":false},"ignore_stories":{"description":"Skip incoming story messages.","type":"boolean","default":false},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"mode":{"description":"Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.","type":["string","null"],"default":null},"startup_timeout_ms":{"description":"Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.","type":"integer","format":"uint64","default":30000,"minimum":0},"storm_protection":{"description":"Signal ingress storm protection controls.","$ref":"#/$defs/SignalStormProtectionConfig","default":{"abnormal_threshold":10,"abnormal_window_secs":60,"breaker_duration_secs":300,"dedupe_ttl_secs":60,"min_reply_interval_secs":2}}},"required":["account"]},"SignalStormProtectionConfig":{"type":"object","properties":{"abnormal_threshold":{"description":"Non-user event threshold within `abnormal_window_secs` before tripping the breaker.","type":"integer","format":"uint","default":10,"minimum":0},"abnormal_window_secs":{"description":"Sliding window in seconds for non-user event counting.","type":"integer","format":"uint64","default":60,"minimum":0},"breaker_duration_secs":{"description":"Circuit breaker duration in seconds after threshold is reached.","type":"integer","format":"uint64","default":300,"minimum":0},"dedupe_ttl_secs":{"description":"Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.","type":"integer","format":"uint64","default":60,"minimum":0},"min_reply_interval_secs":{"description":"Minimum interval in seconds between replies for the same `(channel + reply_target)`.","type":"integer","format":"uint64","default":2,"minimum":0}}},"SkillRagConfig":{"description":"Dynamic skill retrieval configuration (`[skill_rag]` section).","type":"object","properties":{"top_k":{"description":"How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).","type":"integer","format":"uint","default":32,"minimum":0}}},"SkillSuiteRegistration":{"description":"The frozen suite that governs one skill's proposals.","type":"object","properties":{"skill_id":{"description":"The skill the suite governs.","type":"string"},"suite_digest":{"description":"SHA-256 digest (64 lowercase hex digits) of the frozen suite.","type":"string"}},"additionalProperties":false,"required":["skill_id","suite_digest"]},"SkillsConfig":{"description":"Skills loading configuration (`[skills]` section).","type":"object","properties":{"open_skills_dir":{"description":"Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.","type":["string","null"],"default":null},"openclaw_skills_dir":{"description":"Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.","type":["string","null"],"default":null}}},"SkillsLifecycleConfig":{"description":"`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.","type":"object","properties":{"allow_executable_proposals":{"description":"Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.","type":"boolean","default":false},"enabled":{"description":"Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.","type":"boolean","default":false},"max_concurrent_evaluations":{"description":"Most evaluations running at once.","type":"integer","format":"uint32","default":1,"minimum":0},"max_edit_fraction":{"description":"Edit budget of a proposal as a fraction of the skill body, in (0, 1].","type":"number","format":"double","default":0.2},"max_edit_tokens":{"description":"Edit budget of a proposal, in tokens.","type":"integer","format":"uint64","default":300,"minimum":0},"max_proposals_per_cycle":{"description":"Most proposals one cycle may start.","type":"integer","format":"uint32","default":1,"minimum":0},"min_cases_floor":{"description":"Smallest `min_cases` a governing suite may declare. Below 3 is refused.","type":"integer","format":"uint32","default":3,"minimum":0},"mode":{"description":"`draft_only`, `shadow` or `auto`.","$ref":"#/$defs/SkillsLifecycleModeConfig","default":"draft_only"},"owner_scope":{"description":"The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.","type":["string","null"],"default":null},"require_holdout":{"description":"A governing suite must have a holdout split. `false` is refused.","type":"boolean","default":true},"storage_dir":{"description":"Store location under the workspace. Only the default is supported.","type":"string","default":"self/skill-lifecycle"},"suites":{"description":"The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.","type":"array","default":[],"items":{"$ref":"#/$defs/SkillSuiteRegistration"}}},"additionalProperties":false},"SkillsLifecycleModeConfig":{"description":"What the lifecycle may do. Mirrors `LifecycleMode`.","oneOf":[{"description":"Drafts and reviews only.","type":"string","const":"draft_only"},{"description":"Drafts plus evaluation and gating; never publishes.","type":"string","const":"shadow"},{"description":"Publishes an eligible proposal after every gate.","type":"string","const":"auto"}]},"SlackConfig":{"description":"Slack bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Slack user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Slack app-level token for Socket Mode (xapp-...).","type":["string","null"]},"bot_token":{"description":"Slack bot OAuth token (xoxb-...).","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["bot_token"]},"SmartGroupConfig":{"description":"Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).","type":"object","properties":{"classifier_max_context_messages":{"description":"How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.","type":"integer","format":"uint","default":3,"minimum":0},"classifier_model":{"description":"Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.","type":"string","default":""},"classifier_provider":{"description":"Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.","type":"string","default":""},"classifier_temperature":{"description":"Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).","type":"number","format":"double","default":0.0},"classifier_timeout_secs":{"description":"Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.","type":"integer","format":"uint64","default":5,"minimum":0}}},"StorageConfig":{"description":"Persistent storage configuration (`[storage]` section).","type":"object","properties":{"provider":{"description":"Storage provider settings (e.g. sqlite, postgres).","$ref":"#/$defs/StorageProviderSection","default":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}}},"StorageProviderConfig":{"description":"Storage provider backend configuration (e.g. postgres connection details).","type":"object","properties":{"connect_timeout_secs":{"description":"Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"db_url":{"description":"Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.","type":["string","null"],"default":null},"pool_max_size":{"description":"Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.","type":"integer","format":"uint","default":32,"minimum":0},"provider":{"description":"Storage engine key (e.g. \"postgres\", \"sqlite\").","type":"string","default":""},"schema":{"description":"Database schema for SQL backends.","type":"string","default":"public"},"table":{"description":"Table name for memory entries.","type":"string","default":"memories"}}},"StorageProviderSection":{"description":"Wrapper for the storage provider configuration section.","type":"object","properties":{"config":{"description":"Storage provider backend settings.","$ref":"#/$defs/StorageProviderConfig","default":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"StreamMode":{"description":"Streaming mode for channels that support progressive message updates.","oneOf":[{"description":"No streaming -- send the complete response as a single message (default).","type":"string","const":"off"},{"description":"Update a draft message with every flush interval.","type":"string","const":"partial"}]},"TailscaleTunnelConfig":{"type":"object","properties":{"funnel":{"description":"Use Tailscale Funnel (public internet) vs Serve (tailnet only)","type":"boolean","default":false},"hostname":{"description":"Optional hostname override","type":["string","null"]}}},"TaskRoutingConfig":{"description":"Lightweight pre-LLM task routing.","type":"object","properties":{"default_intent":{"description":"Fallback intent when no rule matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"rules":{"description":"Rules evaluated in descending priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/TaskRoutingRule"}}}},"TaskRoutingIntentConfig":{"description":"Task-routing default and rule intent.","type":"string","enum":["simple","delegate","stream"]},"TaskRoutingRule":{"description":"A single task-routing rule.","type":"object","properties":{"intent":{"description":"Route intent to apply when a keyword matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"model_hint":{"description":"Optional model hint/raw model for non-delegated requests.","type":["string","null"],"default":null},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0},"sub_agent_model":{"description":"Optional raw sub-agent model override for delegated tasks.","type":["string","null"],"default":null}}},"TelegramConfig":{"description":"Telegram bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Telegram user IDs or usernames. Empty = deny all.","type":"array","items":{"type":"string"}},"bot_token":{"description":"Telegram Bot API token (from @BotFather).","type":"string"},"draft_update_interval_ms":{"description":"Minimum interval (ms) between draft message edits to avoid rate limits.","type":"integer","format":"uint64","default":1000,"minimum":0},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"interrupt_on_new_message":{"description":"When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.","type":"boolean","default":false},"stream_mode":{"description":"Streaming mode for progressive response delivery via message edits.","$ref":"#/$defs/StreamMode","default":"off"}},"required":["bot_token","allowed_users"]},"ToolCallDialectSetting":{"description":"The tool-call grammars an operator may declare for an endpoint.","oneOf":[{"description":"Only the native `tool_calls` array is a tool call (the default).","type":"string","const":"native"},{"description":"Additionally read `{json}` from the content,\nfor a tool name the request registered.","type":"string","const":"xml_function_tags"}]},"ToolSchemaDialectSetting":{"description":"The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.","oneOf":[{"description":"The published document, byte for byte (the default).","type":"string","const":"raw"},{"description":"The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.","type":"string","const":"no_root_combinators"}]},"ToolTieringConfig":{"description":"Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.","type":"object","properties":{"always_exclude":{"description":"Tool names excluded from capability publication.","type":"array","default":[],"items":{"type":"string"}},"always_include":{"description":"Tool names preferred for direct publication, subject to admission gates.","type":"array","default":[],"items":{"type":"string"}},"channel_exclude":{"description":"Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefaults to [`DEFAULT_CHANNEL_EXCLUDED_TOOLS`]; set to `[]` to expose the\nfull operator surface on channels again.","type":"array","default":["wasm_plugins_manage","wasm_plugin_reload","wasm_plugins_status","hooks_manage","hooks_status","proxy_config","config_reload","gateway","mcp_status","nodes","skills_manage","memory_reindex","document_sync","document_ingest"],"items":{"type":"string"}}}},"TunnelConfig":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.","type":"object","properties":{"cloudflare":{"description":"Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).","anyOf":[{"$ref":"#/$defs/CloudflareTunnelConfig"},{"type":"null"}],"default":null},"custom":{"description":"Custom tunnel command configuration (used when `provider = \"custom\"`).","anyOf":[{"$ref":"#/$defs/CustomTunnelConfig"},{"type":"null"}],"default":null},"ngrok":{"description":"ngrok tunnel configuration (used when `provider = \"ngrok\"`).","anyOf":[{"$ref":"#/$defs/NgrokTunnelConfig"},{"type":"null"}],"default":null},"provider":{"description":"Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.","type":"string","default":"none"},"tailscale":{"description":"Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).","anyOf":[{"$ref":"#/$defs/TailscaleTunnelConfig"},{"type":"null"}],"default":null}}},"UserPolicyConfig":{"description":"Startup user policy entry (`[[user_policies]]`).","type":"object","properties":{"blocked_patterns":{"type":"array","default":[],"items":{"type":"string"}},"projects":{"type":"array","default":[],"items":{"type":"string"}},"role":{"type":"string","default":"guest"},"user_id":{"type":"string"},"visibility_ceiling":{"type":"string","default":"private"}},"required":["user_id"]},"WacliConfig":{"description":"wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```","type":"object","properties":{"allow_unsigned_loopback":{"description":"Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).","type":"boolean","default":false},"allowed_from":{"description":"Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.","type":"array","default":["*"],"items":{"type":"string"}},"bot_jid":{"description":"Bot's own JID, used for reply-to-bot mention detection.","type":["string","null"],"default":null},"bot_lid":{"description":"The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.","type":["string","null"],"default":null},"bot_number":{"description":"Bot's own phone number (digits), used for `@` mention detection.","type":["string","null"],"default":null},"cli_path":{"description":"Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.","type":["string","null"],"default":null},"group_reply_mode":{"description":"Smart group-reply mode. When `None`, derived from `mention_only`.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"host":{"description":"REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].","type":["string","null"],"writeOnly":true},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"outbound_media_workspace_only":{"description":"Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.","type":"boolean","default":false},"port":{"description":"REMOVED: legacy JSON-RPC daemon port. See `host`.","type":["integer","null"],"format":"uint16","maximum":65535,"minimum":0,"writeOnly":true},"self_chat_mode":{"description":"Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.","type":"boolean","default":false},"store_dir":{"description":"wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.","type":["string","null"],"default":null},"webhook_listen":{"description":"Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").","type":"string","default":"127.0.0.1:16868"},"webhook_path":{"description":"HTTP path the webhook server serves (default: \"/wacli\").","type":"string","default":"/wacli"},"webhook_secret":{"description":"HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.","type":["string","null"],"default":null}}},"WebSearchConfig":{"description":"Web search tool configuration (`[web_search]` section).","type":"object","properties":{"brave_api_key":{"description":"Brave Search API key (required if provider is \"brave\")","type":["string","null"],"default":null},"fetch_max_chars":{"description":"Maximum characters returned by `web_fetch` (default 10000)","type":"integer","format":"uint","default":50000,"minimum":0},"max_results":{"description":"Maximum results per search (1-20)","type":"integer","format":"uint","default":15,"minimum":0},"provider":{"description":"Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)","type":"string","default":"duckduckgo"},"timeout_secs":{"description":"Request timeout in seconds","type":"integer","format":"uint64","default":15,"minimum":0}}},"WebhookConfig":{"description":"Webhook channel configuration.","type":"object","properties":{"port":{"description":"Port to listen on for incoming webhooks.","type":"integer","format":"uint16","maximum":65535,"minimum":0},"secret":{"description":"Optional shared secret for webhook signature verification.","type":["string","null"]}},"required":["port"]},"WhatsAppConfig":{"description":"WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.","type":"object","properties":{"access_token":{"description":"Access token from Meta Business Suite (Cloud API mode)","type":["string","null"],"default":null},"allowed_numbers":{"description":"Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"app_secret":{"description":"App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"pair_code":{"description":"Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one","type":["string","null"],"default":null},"pair_phone":{"description":"Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used","type":["string","null"],"default":null},"phone_number_id":{"description":"Phone number ID from Meta Business API (Cloud API mode)","type":["string","null"],"default":null},"read_pool_size":{"description":"Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"session_path":{"description":"Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs","type":["string","null"],"default":null},"verify_token":{"description":"Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode","type":["string","null"],"default":null},"ws_url":{"description":"WebSocket URL override (replaces WHATSAPP_WS_URL)","type":["string","null"],"default":null}}},"WorkspaceHooks":{"description":"Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).","oneOf":[{"description":"They do not run (the default); `prx doctor` and `hooks_status` say so.","type":"string","const":"off"},{"description":"They run, in a cleared environment and a dedicated directory beside\n`config.toml`.","type":"string","const":"on"}]},"WorkspaceMcpServers":{"description":"Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).","oneOf":[{"description":"None: a workspace file may only narrow the servers defined in\n`config.toml`.","type":"string","const":"off"},{"description":"HTTP servers (still refused when they target a private address).","type":"string","const":"http_only"},{"description":"HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.","type":"string","const":"stdio"}]},"XinConfig":{"description":"Configuration for the xin autonomous task engine (`[xin]`).","type":"object","properties":{"adopt_legacy_tasks":{"description":"Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).","type":"boolean","default":false},"interval_minutes":{"description":"Tick interval in minutes (minimum 1). Default: 5.","type":"integer","format":"uint32","default":5,"minimum":0},"stale_timeout_minutes":{"description":"Minutes after which a running task is marked stale. Default: 60.","type":"integer","format":"uint32","default":60,"minimum":0}}},"AgentMessaging":{"description":"Owner-controlled inbound session messaging (enabled unless explicitly off).","type":"object","properties":{"inbound":{"type":"boolean","default":true}}}}} +{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Config","description":"Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).","type":"object","properties":{"a2a":{"description":"Agent-to-Agent compatibility configuration (`[a2a]`).","$ref":"#/$defs/A2aConfig","default":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trusted_trust_domains":[],"trust_domain":"prx.local"}},"agent":{"description":"Agent orchestration settings (`[agent]`).","$ref":"#/$defs/AgentConfig","default":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2,"messaging":{"inbound":true}}},"agents":{"description":"Delegate agent configurations for multi-agent workflows.","type":"object","additionalProperties":{"$ref":"#/$defs/DelegateAgentConfig"},"default":{}},"api_key":{"description":"API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.","type":["string","null"],"default":null},"api_url":{"description":"Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)","type":["string","null"],"default":null},"auth":{"description":"Auth profile and external credential import settings (`[auth]`).","$ref":"#/$defs/AuthConfig","default":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"}},"autonomy":{"description":"Autonomy and security policy configuration (`[autonomy]`).","$ref":"#/$defs/AutonomyConfig","default":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true}},"browser":{"description":"Browser automation configuration (`[browser]`).","$ref":"#/$defs/BrowserConfig","default":{"allowed_domains":[],"computer_use":{"api_key":null}}},"channels_config":{"description":"Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).","$ref":"#/$defs/ChannelsConfig","default":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null}},"chat":{"description":"Interactive chat UI configuration (`[chat]`).","$ref":"#/$defs/ChatConfig","default":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2}},"compliance":{"description":"Operator-owned compliance controls (`[compliance]`).","$ref":"#/$defs/ComplianceConfig","default":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}},"composio":{"description":"Composio managed OAuth tools integration (`[composio]`).","$ref":"#/$defs/ComposioConfig","default":{"api_key":null,"entity_id":"default"}},"cost":{"description":"Cost tracking and budget enforcement configuration (`[cost]`).","$ref":"#/$defs/CostConfig","default":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{},"warn_at_percent":80}},"cron":{"description":"Cron job configuration (`[cron]`).","$ref":"#/$defs/CronConfig","default":{"max_run_history":50}},"decision_engine":{"description":"Optional advisory decision engine, disabled by default.","$ref":"#/$defs/DecisionEngineConfig","default":{"candidates":5,"enabled":false,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"latency_budget_ms":500,"max_candidates":12,"token_ratio_limit":0.3499999940395355}},"default_model":{"description":"Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.","type":["string","null"]},"default_provider":{"description":"Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.","type":["string","null"]},"default_temperature":{"description":"Default model temperature (0.0–2.0). Default: `0.7`.","type":"number","format":"double","default":0.7},"embedding_routes":{"description":"Embedding routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/EmbeddingRouteConfig"}},"gateway":{"description":"Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).","$ref":"#/$defs/GatewayConfig","default":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60}},"heartbeat":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]`).","$ref":"#/$defs/HeartbeatConfig","default":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."}},"http_request":{"description":"HTTP request tool configuration (`[http_request]`).","$ref":"#/$defs/HttpRequestConfig","default":{"max_response_size":1000000,"timeout_secs":30}},"identity":{"description":"Identity format configuration: OpenClaw or AIEOS (`[identity]`).","$ref":"#/$defs/IdentityConfig","default":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"}},"identity_bindings":{"description":"Static identity bindings loaded at startup (`[[identity_bindings]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/IdentityBindingConfig"}},"mcp":{"description":"Secrets encryption configuration (`[secrets]`).","$ref":"#/$defs/McpConfig","default":{"servers":{}}},"mcp_server":{"description":"MCP server compatibility configuration (`[mcp_server]`).","$ref":"#/$defs/McpServerRuntimeConfig","default":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true}},"media":{"description":"Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.","$ref":"#/$defs/MediaConfig","default":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"}},"memory":{"description":"Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).","$ref":"#/$defs/MemoryConfig","default":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7}},"model_routes":{"description":"Model routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/ModelRouteConfig"}},"model_settings":{"description":"Catalog model levels and explicit parameters, keyed by canonical release ID.","type":"object","additionalProperties":{"$ref":"#/$defs/ModelSettings"},"default":{}},"multimodal":{"description":"Multimodal (image) handling configuration (`[multimodal]`).","$ref":"#/$defs/MultimodalConfig","default":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4}},"nodes":{"description":"Remote node proxy configuration (`[nodes]`).","$ref":"#/$defs/NodesConfig","default":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}},"observability":{"description":"Observability backend configuration (`[observability]`).","$ref":"#/$defs/ObservabilityConfig","default":{"backend":"none","otel_endpoint":null,"otel_service_name":null}},"plugins":{"description":"WASM plugin runtime switch (`[plugins]`), off by default.","$ref":"#/$defs/PluginsConfig","default":{"enabled":false}},"providers":{"description":"Provider-specific runtime options (`[providers.]`).","$ref":"#/$defs/ProvidersConfig","default":{"ollama":{"num_ctx":null}}},"proxy":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).","$ref":"#/$defs/ProxyConfig","default":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]}},"query_classification":{"description":"Automatic query classification — maps user messages to model hints.","$ref":"#/$defs/QueryClassificationConfig","default":{"rules":[]}},"reliability":{"description":"Reliability settings: retries, fallback providers, backoff (`[reliability]`).","$ref":"#/$defs/ReliabilityConfig","default":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2}},"router":{"description":"Heuristic LLM router configuration (`[router]`).","$ref":"#/$defs/RouterConfig","default":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]}},"runtime":{"description":"Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.","$ref":"#/$defs/RuntimeConfig","default":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null}},"scheduler":{"description":"Scheduler configuration for periodic task execution (`[scheduler]`).","$ref":"#/$defs/SchedulerConfig","default":{"claim_lease_secs":90,"max_tasks":64}},"secrets":{"$ref":"#/$defs/SecretsConfig","default":{"encrypt":true}},"security":{"description":"Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).","$ref":"#/$defs/SecurityConfig","default":{"audit":{"log_path":"audit.log","max_size_mb":100}}},"self_system":{"description":"Self-system experimental automation controls (`[self_system]`).","$ref":"#/$defs/SelfSystemConfig","default":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24}},"sessions_spawn":{"description":"Session spawning configuration (`[sessions_spawn]`).","$ref":"#/$defs/SessionsSpawnConfig","default":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null}},"skill_rag":{"description":"Dynamic skill retrieval settings (`[skill_rag]`).","$ref":"#/$defs/SkillRagConfig","default":{"top_k":32}},"skills":{"description":"Skills loading and community repository behavior (`[skills]`).","$ref":"#/$defs/SkillsConfig","default":{"open_skills_dir":null,"openclaw_skills_dir":null}},"skills_lifecycle":{"description":"Skill lifecycle (`[skills_lifecycle]`), off by default.","$ref":"#/$defs/SkillsLifecycleConfig","default":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]}},"smart_group":{"description":"Smart group-reply pre-gate configuration (`[smart_group]`).","$ref":"#/$defs/SmartGroupConfig","default":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5}},"storage":{"description":"Persistent storage provider configuration (`[storage]`).","$ref":"#/$defs/StorageConfig","default":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"task_routing":{"description":"Task routing configuration — classifies work by intent before the main agent loop.","$ref":"#/$defs/TaskRoutingConfig","default":{"default_intent":"simple","rules":[]}},"tool_tiering":{"description":"Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).","$ref":"#/$defs/ToolTieringConfig","default":{"always_exclude":[],"always_include":[],"channel_exclude":[]}},"tunnel":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]`).","$ref":"#/$defs/TunnelConfig","default":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null}},"user_policies":{"description":"Static user policy records loaded at startup (`[[user_policies]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/UserPolicyConfig"}},"web_search":{"description":"Web search tool configuration (`[web_search]`).","$ref":"#/$defs/WebSearchConfig","default":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15}},"webhook":{"description":"Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).","$ref":"#/$defs/MemoryWebhookConfig","default":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null}},"xin":{"description":"Xin autonomous task engine configuration (`[xin]`).","$ref":"#/$defs/XinConfig","default":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}}},"$defs":{"A2aConfig":{"type":"object","properties":{"agent_id":{"description":"Stable PRX agent identifier advertised to peers.","type":"string","default":"prx-default"},"allowed_peer_issuers":{"description":"Accepted external peer issuers.","type":"array","default":[],"items":{"type":"string"}},"bind":{"description":"Advertised bind address.","type":"string","default":"127.0.0.1:16832"},"card_jwks_uri":{"description":"Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.","type":["string","null"],"default":null},"card_signing_key_path":{"description":"On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).","type":["string","null"],"default":null},"card_ttl_seconds":{"description":"Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.","type":"integer","format":"uint64","default":3600,"minimum":0},"discovery_advertised":{"description":"Whether to advertise into an external A2A registry.","type":"boolean","default":false},"handoff_nonce_ttl_seconds":{"description":"Replay window for future handoff delegation tokens.","type":"integer","format":"uint64","default":3600,"minimum":0},"messaging_enabled":{"description":"Enable the dedicated pinned mTLS messaging listener.","type":"boolean","default":false},"peers":{"type":"object","additionalProperties":{"$ref":"#/$defs/A2aPeer"},"default":{}},"spiffe_id":{"description":"Local SPIFFE-style identifier placeholder.","type":"string","default":"spiffe://prx-local/agent/prx-default"},"spiffe_strict_validation":{"description":"When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.","type":"boolean","default":false},"spiffe_trust_bundle_pem":{"description":"Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).","type":["string","null"],"default":null},"trusted_trust_domains":{"description":"Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).","type":"array","default":[],"items":{"type":"string"}},"trust_domain":{"description":"SPIFFE trust domain for new instance identities.","type":"string","default":"prx.local"}}},"A2aPeer":{"description":"Explicit pinned identity and local recipient grant.","type":"object","properties":{"spiffe_id":{"type":"string"},"fingerprints":{"type":"array","items":{"type":"string"}},"address":{"type":"string"},"owner":{"type":"string"},"sessions":{"type":"array","default":["*"],"items":{"type":"string"}},"agents":{"type":"array","default":["*"],"items":{"type":"string"}}},"required":["spiffe_id","fingerprints","address","owner"],"additionalProperties":false},"AgentCompactionConfig":{"description":"Agent context compaction configuration (`[agent.compaction]`).","type":"object","properties":{"keep_recent_messages":{"description":"Number of recent non-system messages to keep after compaction.","type":"integer","format":"uint","default":12,"minimum":0},"max_context_tokens":{"description":"Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.","type":"integer","format":"uint","default":128000,"minimum":0},"memory_flush":{"description":"Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.","type":"boolean","default":true},"mode":{"description":"Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).","$ref":"#/$defs/AgentCompactionMode","default":"switch"},"os_paging":{"description":"Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.","$ref":"#/$defs/OsPagingConfig","default":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"}},"reserve_tokens":{"description":"Tokens reserved for the next model response.","type":"integer","format":"uint","default":4096,"minimum":0}}},"AgentCompactionMode":{"description":"Compaction mode for long conversation contexts.","oneOf":[{"description":"Disable proactive compaction.","type":"string","const":"off"},{"description":"Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.","type":"string","const":"switch"},{"description":"Conservative compaction that prefers summary replacement.","type":"string","const":"safeguard"},{"description":"Aggressive truncation mode for tighter contexts.","type":"string","const":"aggressive"}]},"AgentConfig":{"description":"Agent orchestration configuration (`[agent]` section).","type":"object","properties":{"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"compact_context":{"description":"When true: bootstrap_max_chars=6000. Use for 13B or smaller models.","type":"boolean","default":false},"compaction":{"description":"Context compaction controls (`[agent.compaction]`).","$ref":"#/$defs/AgentCompactionConfig","default":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096}},"low_priority_tools":{"description":"Tool names treated as low-priority when `priority_scheduling_enabled = true`.","type":"array","default":["sessions_spawn","delegate"],"items":{"type":"string"}},"priority_scheduling_enabled":{"description":"Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.","type":"boolean","default":false},"read_only_tool_concurrency_window":{"description":"Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.","type":"integer","format":"uint","default":2,"minimum":0},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}}},"AgentLimits":{"description":"Optional admission limits for rf-started turns of a named agent.","type":"object","properties":{"max_concurrent_turns":{"type":["integer","null"],"format":"uint32","minimum":0},"max_cost_per_day_cents":{"type":["integer","null"],"format":"uint64","minimum":0}},"additionalProperties":false},"AuditConfig":{"description":"Audit logging configuration","type":"object","properties":{"log_path":{"description":"Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).","type":"string","default":"audit.log"},"max_size_mb":{"description":"Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).","type":"integer","format":"uint32","default":100,"minimum":0}}},"AuthConfig":{"description":"Authentication and external credential import configuration (`[auth]` section).","type":"object","properties":{"codex_auth_json_auto_import":{"description":"Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.","type":"boolean","default":false},"codex_auth_json_path":{"description":"Source path for Codex CLI auth.json import.","type":"string","default":"~/.codex/auth.json"}}},"AutonomyConfig":{"type":"object","properties":{"acknowledge_unrestricted_profile":{"description":"Operator acknowledgement for an intentionally unrestricted profile.\nRetained for existing configs; it no longer changes any output or policy behavior.","type":"boolean","default":false},"forbidden_paths":{"description":"Explicit path denylist. Default includes system-critical paths.\n\nFails closed: omitting the key keeps the built-in list rather than\nemptying it, so a partial `[autonomy]` section never removes the\ndenylist.","type":"array","default":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"items":{"type":"string"}},"level":{"description":"Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).","$ref":"#/$defs/AutonomyLevel","default":"full"},"max_cost_per_day_cents":{"description":"Maximum cost per day in cents per policy. Default: unset (no ceiling).","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"scopes":{"description":"Scope-based tool access control: per-user/channel/chat-type allow/deny rules.","$ref":"#/$defs/ScopeConfig","default":{"assign_owners":[],"default":"allow","rules":[]}},"workspace_only":{"description":"Restrict file writes and command paths to the workspace directory. Default: `true`.\n\nFails closed: a `[autonomy]` section that omits this key keeps the\nworkspace restriction on, so a partial section can never widen the\nfilesystem reach by accident.","type":"boolean","default":true}}},"AutonomyLevel":{"description":"How much autonomy the agent has","oneOf":[{"description":"Read-only: can observe but not act","type":"string","const":"readonly"},{"description":"Supervised: acts but requires approval for risky operations","type":"string","const":"supervised"},{"description":"Full: autonomous execution within policy bounds","type":"string","const":"full"}]},"BackendSelection":{"description":"Which decision backend runs: `auto` (the factory's order) or one kind.","type":"string"},"BrowserComputerUseConfig":{"description":"Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.","type":"object","properties":{"api_key":{"description":"Optional bearer token (retained only for config secret handling).","type":["string","null"],"default":null}}},"BrowserConfig":{"description":"Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.","type":"object","properties":{"allowed_domains":{"description":"Allowed domains for `web_fetch` (exact or subdomain match).","type":"array","default":[],"items":{"type":"string"}},"computer_use":{"description":"Computer-use sidecar config (retained only for `api_key` secret handling).","$ref":"#/$defs/BrowserComputerUseConfig","default":{"api_key":null}}}},"ChannelsConfig":{"description":"Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.","type":"object","properties":{"cli":{"description":"Enable the CLI interactive channel. Default: `true`.","type":"boolean","default":true},"dingtalk":{"description":"DingTalk channel configuration.","anyOf":[{"$ref":"#/$defs/DingTalkConfig"},{"type":"null"}]},"discord":{"description":"Discord bot channel configuration.","anyOf":[{"$ref":"#/$defs/DiscordConfig"},{"type":"null"}]},"email":{"description":"Email channel configuration.","anyOf":[{"$ref":"#/$defs/EmailConfig"},{"type":"null"}]},"imessage":{"description":"iMessage channel configuration (macOS only).","anyOf":[{"$ref":"#/$defs/IMessageConfig"},{"type":"null"}]},"irc":{"description":"IRC channel configuration.","anyOf":[{"$ref":"#/$defs/IrcConfig"},{"type":"null"}]},"lark":{"description":"Lark/Feishu channel configuration.","anyOf":[{"$ref":"#/$defs/LarkConfig"},{"type":"null"}]},"linq":{"description":"Linq Partner API channel configuration.","anyOf":[{"$ref":"#/$defs/LinqConfig"},{"type":"null"}]},"mattermost":{"description":"Mattermost bot channel configuration.","anyOf":[{"$ref":"#/$defs/MattermostConfig"},{"type":"null"}]},"nextcloud_talk":{"description":"Nextcloud Talk bot channel configuration.","anyOf":[{"$ref":"#/$defs/NextcloudTalkConfig"},{"type":"null"}]},"qq":{"description":"QQ Official Bot channel configuration.","anyOf":[{"$ref":"#/$defs/QQConfig"},{"type":"null"}]},"ramflux":{"description":"Local ramflux agent-host bridge.","anyOf":[{"$ref":"#/$defs/RamfluxConfig"},{"type":"null"}],"default":null},"signal":{"description":"Signal channel configuration.","anyOf":[{"$ref":"#/$defs/SignalConfig"},{"type":"null"}]},"slack":{"description":"Slack bot channel configuration.","anyOf":[{"$ref":"#/$defs/SlackConfig"},{"type":"null"}]},"telegram":{"description":"Telegram bot channel configuration.","anyOf":[{"$ref":"#/$defs/TelegramConfig"},{"type":"null"}]},"wacli":{"description":"wacli JSON-RPC daemon channel configuration.","anyOf":[{"$ref":"#/$defs/WacliConfig"},{"type":"null"}],"default":null},"webhook":{"description":"Webhook channel configuration.","anyOf":[{"$ref":"#/$defs/WebhookConfig"},{"type":"null"}]},"whatsapp":{"description":"WhatsApp channel configuration (Cloud API or Web mode).","anyOf":[{"$ref":"#/$defs/WhatsAppConfig"},{"type":"null"}]}}},"ChatConfig":{"description":"Interactive chat configuration (`[chat]`).","type":"object","properties":{"daemon":{"description":"How this chat process reaches the daemon it borrows channels from.","$ref":"#/$defs/ChatDaemonConfig","default":{"token":"","url":""}},"max_concurrent_visible_turns":{"description":"Maximum concurrent visible provider turns in the TUI Redux driver.","type":"integer","format":"uint","default":2,"minimum":0}}},"ChatDaemonConfig":{"description":"Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.","type":"object","properties":{"token":{"description":"Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.","type":"string","default":""},"url":{"description":"Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.","type":"string","default":""}}},"CircuitBreakerConfig":{"description":"The per-backend circuit breaker.","type":"object","properties":{"cooldown_secs":{"description":"Seconds the breaker stays open (1 to 3600).","type":"integer","format":"uint32","default":60,"minimum":0},"failure_threshold":{"description":"Consecutive failures before the breaker opens (1 to 100).","type":"integer","format":"uint32","default":5,"minimum":0}}},"ClassificationRule":{"description":"A single classification rule mapping message patterns to a model hint.","type":"object","properties":{"hint":{"description":"Must match a `[[model_routes]]` hint value.","type":"string"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"max_length":{"description":"Only match if message length <= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"min_length":{"description":"Only match if message length >= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"patterns":{"description":"Case-sensitive literal matches (for \"```\", \"fn \", etc.).","type":"array","default":[],"items":{"type":"string"}},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0}},"required":["hint"]},"CloudflareTunnelConfig":{"type":"object","properties":{"token":{"description":"Cloudflare Tunnel token (from Zero Trust dashboard)","type":"string"}},"required":["token"]},"ComplianceConfig":{"type":"object","properties":{"eu_ai_act":{"$ref":"#/$defs/EuAiActComplianceConfig","default":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null}},"interaction_notice":{"$ref":"#/$defs/InteractionNoticeConfig","default":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}}},"ComposioConfig":{"description":"Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.","type":"object","properties":{"api_key":{"description":"Composio API key (stored encrypted when secrets.encrypt = true)","type":["string","null"],"default":null},"entity_id":{"description":"Default entity ID for multi-user setups","type":"string","default":"default"}}},"CostConfig":{"description":"Cost tracking and budget enforcement configuration (`[cost]` section).","type":"object","properties":{"allow_override":{"description":"Allow requests to exceed budget with --override flag (default: false)","type":"boolean","default":false},"daily_limit_usd":{"description":"Daily spending limit in USD (default: unset, no limit; 0 refuses every priced turn)","type":["number","null"],"format":"double","default":null},"monthly_limit_usd":{"description":"Monthly spending limit in USD (default: unset, no limit)","type":["number","null"],"format":"double","default":null},"prices":{"description":"Per-model pricing (USD per 1M tokens)","type":"object","additionalProperties":{"$ref":"#/$defs/ModelPricing"},"default":{}},"warn_at_percent":{"description":"Warn when spending reaches this percentage of a configured limit (default: 80)","type":"integer","format":"uint8","default":80,"maximum":255,"minimum":0}}},"CredentialRefSetting":{"description":"Which credential a decision backend uses. A reference, never a secret.","type":"string"},"CronConfig":{"description":"Cron job configuration (`[cron]` section).","type":"object","properties":{"max_run_history":{"description":"Maximum number of historical cron run records to retain. Default: `50`.","type":"integer","format":"uint32","default":50,"minimum":0}}},"CustomTunnelConfig":{"type":"object","properties":{"health_url":{"description":"Optional URL to check tunnel health","type":["string","null"]},"start_command":{"description":"Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"","type":"string"},"url_pattern":{"description":"Optional regex to extract public URL from command stdout","type":["string","null"]}},"required":["start_command"]},"DecisionBackendConfig":{"description":"The decision backend (`[decision_engine.backend]`).","type":"object","properties":{"circuit_breaker":{"description":"The circuit breaker.","$ref":"#/$defs/CircuitBreakerConfig","default":{"cooldown_secs":60,"failure_threshold":5}},"credential_ref":{"description":"The credential reference: `\"\"`, `\"none\"` or `cred-`.","$ref":"#/$defs/CredentialRefSetting","default":""},"endpoint":{"description":"The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.","type":"string","default":""},"kind":{"description":"`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).","$ref":"#/$defs/BackendSelection","default":"auto"},"max_request_bytes":{"description":"Largest request body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":65536,"minimum":0},"max_response_bytes":{"description":"Largest response body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":262144,"minimum":0},"model":{"description":"The model the endpoint serves; one exact version for a hosted\nservice.","type":"string","default":""},"pinned_snapshot":{"description":"The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.","type":"string"},"remote_enabled":{"description":"Whether decision state may leave this machine. Default `false`.","type":"boolean","default":false},"timeout_ms":{"description":"Transport timeout (10 ms up to the extra latency budget).","type":"integer","format":"uint32","default":250,"minimum":0}}},"DecisionEngineConfig":{"type":"object","properties":{"backend":{"anyOf":[{"$ref":"#/$defs/DecisionBackendConfig"},{"type":"null"}]},"candidates":{"type":"integer","format":"uint32","default":5,"minimum":0},"enabled":{"type":"boolean","default":false},"mode":{"$ref":"#/$defs/DecisionMode","default":"pre"},"observe_queue":{"type":"integer","format":"uint32","default":64,"minimum":0},"prompt_budget_tokens":{"type":"integer","format":"uint32","default":300,"minimum":0},"telemetry_cap":{"type":"integer","format":"uint32","default":1000,"minimum":0},"timeout_ms":{"type":"integer","format":"uint32","default":1500,"minimum":0},"latency_budget_ms":{"description":"The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.","type":"integer","format":"uint64","default":500,"minimum":0},"token_ratio_limit":{"description":"Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).","type":"number","format":"float","default":0.3499999940395355},"max_candidates":{"description":"The most candidates a turn considers (1 to 32).","type":"integer","format":"uint8","default":12,"maximum":255,"minimum":0}}},"DecisionMode":{"type":"string","enum":["pre","post","both"]},"DeclarationOfConformityConfig":{"type":"object","properties":{"applicable_union_law":{"type":"array","default":[],"items":{"type":"string"}},"artifact_path":{"type":["string","null"],"default":null},"artifact_version":{"type":["string","null"],"default":null},"conformity_assessment_procedure":{"type":["string","null"],"default":null},"conformity_statement":{"type":["string","null"],"default":null},"harmonised_standards":{"type":"array","default":[],"items":{"type":"string"}},"issue_date":{"type":["string","null"],"default":null},"issue_place":{"type":["string","null"],"default":null},"notified_body_certificate":{"type":["string","null"],"default":null},"notified_body_identification_number":{"type":["string","null"],"default":null},"notified_body_name":{"type":["string","null"],"default":null},"personal_data_compliance_statement":{"type":["string","null"],"default":null},"processes_personal_data":{"type":"boolean","default":false},"provider_address":{"type":["string","null"],"default":null},"provider_name":{"type":["string","null"],"default":null},"signer_function":{"type":["string","null"],"default":null},"signer_name":{"type":["string","null"],"default":null},"signer_on_behalf_of":{"type":["string","null"],"default":null},"sole_responsibility_statement":{"type":["string","null"],"default":null},"standards_not_applicable_reason":{"type":["string","null"],"default":null},"system_name":{"type":["string","null"],"default":null},"system_reference":{"type":["string","null"],"default":null},"system_type":{"type":["string","null"],"default":null}}},"DelegateAgentConfig":{"description":"Configuration for a delegate sub-agent used by the `delegate` tool.","type":"object","properties":{"agentic":{"description":"Agentic sub-agent mode (multi-turn tool-call loop). Default true; an\nexplicit `false` makes the agent answer-only with no tools.","type":"boolean","default":true},"allowed_tools":{"description":"Allowlist of tool names available to the sub-agent in agentic mode.\nEmpty or omitted means all tools, the same as `[\"*\"]`.","type":"array","default":[],"items":{"type":"string"}},"api_key":{"description":"Optional API key override","type":["string","null"],"default":null},"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"autonomy":{"description":"The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.","anyOf":[{"$ref":"#/$defs/AutonomyLevel"},{"type":"null"}]},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"enabled":{"description":"Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.","type":"boolean","default":true},"identity_dir":{"description":"Optional identity files directory relative to workspace root.","type":["string","null"],"default":null},"limits":{"$ref":"#/$defs/AgentLimits","default":{"max_concurrent_turns":null,"max_cost_per_day_cents":null}},"max_depth":{"description":"Max recursion depth for nested delegation","type":"integer","format":"uint32","default":8,"minimum":0},"memory_scope":{"description":"Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".","type":["string","null"],"default":null},"model":{"description":"Model name","type":"string"},"provider":{"description":"Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")","type":"string"},"spawn_enabled":{"description":"Whether this agent is allowed to be targeted by sessions_spawn (default: true).","type":["boolean","null"],"default":null},"system_prompt":{"description":"Optional system prompt for the sub-agent","type":["string","null"],"default":null},"temperature":{"description":"Temperature override","type":["number","null"],"format":"double","default":null},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}},"required":["provider","model"]},"DingTalkConfig":{"description":"DingTalk configuration for Stream Mode messaging","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"client_id":{"description":"Client ID (AppKey) from DingTalk developer console","type":"string"},"client_secret":{"description":"Client Secret (AppSecret) from DingTalk developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["client_id","client_secret"]},"DiscordConfig":{"description":"Discord bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Discord user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Discord bot token (from Discord Developer Portal).","type":"string"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"guild_id":{"description":"Optional guild (server) ID to restrict the bot to a single guild.","type":["string","null"]},"listen_to_bots":{"description":"When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.","type":"boolean","default":false}},"required":["bot_token"]},"DmPolicy":{"description":"Policy for direct-message handling.","oneOf":[{"description":"Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).","type":"string","const":"pairing"},{"description":"Accept only senders listed in `allowed_from`.","type":"string","const":"allowlist"},{"description":"Accept any direct sender.","type":"string","const":"open"},{"description":"Ignore direct messages.","type":"string","const":"disabled"}]},"DockerRuntimeConfig":{"description":"Docker runtime configuration (`[runtime.docker]` section).","type":"object","properties":{"allowed_workspace_roots":{"description":"Optional workspace root allowlist for Docker mount validation.","type":"array","default":[],"items":{"type":"string"}},"cpu_limit":{"description":"Optional CPU limit (`None` = no explicit limit).","type":["number","null"],"format":"double","default":1.0},"image":{"description":"Runtime image used to execute shell commands.","type":"string","default":"alpine:3.20"},"memory_limit_mb":{"description":"Optional memory limit in MB (`None` = no explicit limit).","type":["integer","null"],"format":"uint64","default":512,"minimum":0},"mount_workspace":{"description":"Mount configured workspace into `/workspace`.","type":"boolean","default":true},"network":{"description":"Docker network mode (`none`, `bridge`, etc.).","type":"string","default":"none"},"read_only_rootfs":{"description":"Mount root filesystem as read-only.","type":"boolean","default":true}}},"EmailConfig":{"description":"Email channel configuration","type":"object","properties":{"allowed_senders":{"description":"Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)","type":"array","default":[],"items":{"type":"string"}},"from_address":{"description":"From address for outgoing emails","type":"string"},"idle_timeout_secs":{"description":"IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes","type":"integer","format":"uint64","default":1740,"minimum":0},"imap_folder":{"description":"IMAP folder to poll (default: INBOX)","type":"string","default":"INBOX"},"imap_host":{"description":"IMAP server hostname","type":"string"},"imap_port":{"description":"IMAP server port (default: 993 for TLS)","type":"integer","format":"uint16","default":993,"maximum":65535,"minimum":0},"password":{"description":"Email password for authentication","type":"string"},"smtp_host":{"description":"SMTP server hostname","type":"string"},"smtp_port":{"description":"SMTP server port (default: 465 for TLS)","type":"integer","format":"uint16","default":465,"maximum":65535,"minimum":0},"smtp_tls":{"description":"Use TLS for SMTP (default: true)","type":"boolean","default":true},"username":{"description":"Email username for authentication","type":"string"}},"required":["imap_host","smtp_host","username","password","from_address"]},"EmbeddingRouteConfig":{"description":"Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"dimensions":{"description":"Optional embedding dimension override for this route","type":["integer","null"],"format":"uint","default":null,"minimum":0},"hint":{"description":"Route hint name (e.g. \"semantic\", \"archive\", \"faq\")","type":"string"},"model":{"description":"Embedding model to use with that provider","type":"string"},"provider":{"description":"Embedding provider (`none`, `openai`, or `custom:`)","type":"string"}},"required":["hint","provider","model"]},"EuAiActClassificationConfig":{"type":"object","properties":{"assessed_at":{"type":["string","null"],"default":null},"owner":{"type":["string","null"],"default":null},"status":{"$ref":"#/$defs/EuAiActRiskClassification","default":"unclassified"}}},"EuAiActComplianceConfig":{"type":"object","properties":{"classification":{"$ref":"#/$defs/EuAiActClassificationConfig","default":{"assessed_at":null,"owner":null,"status":"unclassified"}},"declaration":{"$ref":"#/$defs/DeclarationOfConformityConfig","default":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null}},"incident_store_path":{"type":["string","null"],"default":null}}},"EuAiActRiskClassification":{"type":"string","enum":["unclassified","high_risk","not_high_risk"]},"FitnessConfig":{"description":"Calendar schedule, evidence thresholds, and retention for fitness v2.","type":"object","properties":{"auto_run":{"description":"Run the daily fitness worker in daemon mode.","type":"boolean","default":true},"max_backfill_days":{"description":"Maximum number of closed days recovered after downtime.","type":"integer","format":"uint32","default":7,"minimum":0},"min_coverage":{"description":"Minimum available metric weight required to publish a final score.","type":"number","format":"double","default":0.6},"min_samples":{"description":"Minimum samples required before an evidence-derived subscore is usable.","type":"integer","format":"uint","default":5,"minimum":0},"retention_days":{"description":"Number of daily JSON reports retained on disk.","type":"integer","format":"uint32","default":180,"minimum":0},"run_at":{"description":"Local wall-clock time (`HH:MM`) at which the previous day is scored.","type":"string","default":"00:10"},"timezone":{"description":"IANA timezone used to define closed calendar days.","type":"string","default":"UTC"}}},"GatewayConfig":{"description":"Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.","type":"object","properties":{"allow_public_bind":{"description":"Allow binding to non-localhost without a tunnel (default: false)","type":"boolean","default":false},"api_rate_limit_per_minute":{"description":"Max `/api/*` requests per minute per authenticated token.","type":"integer","format":"uint32","default":60,"minimum":0},"channel_webhook_dedup_ttl_secs":{"description":"How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.","type":"integer","format":"uint64","default":86400,"minimum":0},"host":{"description":"Gateway host (default: 127.0.0.1)","type":"string","default":"127.0.0.1"},"idempotency_max_keys":{"description":"Maximum distinct idempotency keys retained in memory.","type":"integer","format":"uint","default":10000,"minimum":0},"idempotency_ttl_secs":{"description":"TTL for webhook idempotency keys.","type":"integer","format":"uint64","default":300,"minimum":0},"pair_rate_limit_per_minute":{"description":"Max `/pair` requests per minute per client key.","type":"integer","format":"uint32","default":10,"minimum":0},"paired_tokens":{"description":"Paired bearer tokens (managed automatically, not user-edited)","type":"array","default":[],"items":{"type":"string"}},"port":{"description":"Gateway port (default: 16830)","type":"integer","format":"uint16","default":16830,"maximum":65535,"minimum":0},"rate_limit_max_keys":{"description":"Maximum distinct client keys tracked by gateway rate limiter maps.","type":"integer","format":"uint","default":10000,"minimum":0},"require_pairing":{"description":"Require pairing before accepting requests (default: true)","type":"boolean","default":true},"targeted_agents":{"description":"Switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). Default true. While false, any\notherwise-valid named target answers 409 `agent_disabled` and never\nruns as Main.","type":"boolean","default":true},"trust_forwarded_headers":{"description":"Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.","type":"boolean","default":false},"webhook_rate_limit_per_minute":{"description":"Max `/webhook` requests per minute per client key.","type":"integer","format":"uint32","default":60,"minimum":0}}},"GroupPolicy":{"description":"Policy for group-message handling.","oneOf":[{"description":"Accept only groups listed in `group_allow_from`.","type":"string","const":"allowlist"},{"description":"Accept any group.","type":"string","const":"open"},{"description":"Ignore group messages.","type":"string","const":"disabled"}]},"GroupReplyMode":{"description":"How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.","oneOf":[{"description":"Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).","type":"string","const":"off"},{"description":"Reply only when the bot is @-mentioned (legacy `mention_only = true`).","type":"string","const":"mention-only"},{"description":"Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).","type":"string","const":"smart"}]},"HeartbeatConfig":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]` section).","type":"object","properties":{"active_hours":{"description":"Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.","type":"array","default":[8,23],"items":{"type":"integer","format":"uint8","maximum":255,"minimum":0}},"interval_minutes":{"description":"Interval in minutes between heartbeat pings. Default: `30`.","type":"integer","format":"uint32","default":30,"minimum":0},"prompt":{"description":"Prompt used by heartbeat worker when dispatching tasks.","type":"string","default":"Check HEARTBEAT.md and follow instructions."}}},"HttpRequestConfig":{"description":"HTTP request tool configuration (`[http_request]` section).","type":"object","properties":{"max_response_size":{"description":"Maximum response size in bytes (default: 1MB)","type":"integer","format":"uint","default":1000000,"minimum":0},"timeout_secs":{"description":"Request timeout in seconds (default: 30)","type":"integer","format":"uint64","default":30,"minimum":0}}},"IMessageConfig":{"description":"iMessage channel configuration (macOS only).","type":"object","properties":{"allowed_contacts":{"description":"Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.","type":"array","items":{"type":"string"}},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["allowed_contacts"]},"IdentityBindingConfig":{"description":"Startup identity binding entry (`[[identity_bindings]]`).","type":"object","properties":{"channel":{"type":"string"},"channel_account":{"type":"string"},"display_name":{"type":["string","null"],"default":null},"user_id":{"type":"string"}},"required":["user_id","channel","channel_account"]},"IdentityConfig":{"description":"Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.","type":"object","properties":{"aieos_inline":{"description":"Inline AIEOS JSON (alternative to file path)","type":["string","null"],"default":null},"aieos_path":{"description":"Path to AIEOS JSON file (relative to workspace)","type":["string","null"],"default":null},"format":{"description":"Identity format: \"openclaw\" (default) or \"aieos\"","type":"string","default":"openclaw"}}},"InteractionNoticeApplicability":{"type":"string","enum":["required","not_applicable"]},"InteractionNoticeConfig":{"type":"object","properties":{"applicability":{"$ref":"#/$defs/InteractionNoticeApplicability","default":"required"},"exception_owner":{"type":["string","null"],"default":null},"exception_reviewed_at":{"type":["string","null"],"default":null},"text":{"type":"string","default":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers."},"version":{"type":"string","default":"1"}}},"IrcConfig":{"description":"IRC channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed nicknames (case-insensitive) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"channels":{"description":"Channels to join on connect","type":"array","default":[],"items":{"type":"string"}},"mention_only":{"description":"When true, only process channel/group messages that mention the bot.","type":"boolean","default":false},"nickname":{"description":"Bot nickname","type":"string"},"nickserv_password":{"description":"NickServ IDENTIFY password","type":["string","null"]},"port":{"description":"IRC server port (default: 6697 for TLS)","type":"integer","format":"uint16","default":6697,"maximum":65535,"minimum":0},"sasl_password":{"description":"SASL PLAIN password (IRCv3)","type":["string","null"]},"server":{"description":"IRC server hostname","type":"string"},"server_password":{"description":"Server password (for bouncers like ZNC)","type":["string","null"]},"username":{"description":"Username (defaults to nickname if not set)","type":["string","null"]},"verify_tls":{"description":"Verify TLS certificate (default: true)","type":["boolean","null"]}},"required":["server","nickname"]},"LarkConfig":{"description":"Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from Lark/Feishu developer console","type":"string"},"app_secret":{"description":"App Secret from Lark/Feishu developer console","type":"string"},"encrypt_key":{"description":"Encrypt key for webhook message decryption (optional)","type":["string","null"],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"port":{"description":"HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"receive_mode":{"description":"Event receive mode: \"websocket\" (default) or \"webhook\"","$ref":"#/$defs/LarkReceiveMode","default":"websocket"},"use_feishu":{"description":"Whether to use the Feishu (Chinese) endpoint instead of Lark (International)","type":"boolean","default":false},"verification_token":{"description":"Verification token for webhook validation (optional)","type":["string","null"],"default":null}},"required":["app_id","app_secret"]},"LarkReceiveMode":{"description":"How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.","type":"string","enum":["websocket","webhook"]},"LinqConfig":{"type":"object","properties":{"allowed_senders":{"description":"Allowed sender handles (phone numbers) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"api_token":{"description":"Linq Partner API token (Bearer auth)","type":"string"},"from_phone":{"description":"Phone number to send from (E.164 format)","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"signing_secret":{"description":"Webhook signing secret for signature verification","type":["string","null"],"default":null}},"required":["api_token","from_phone"]},"MattermostConfig":{"description":"Mattermost bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Mattermost user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Mattermost bot access token.","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.","type":["boolean","null"],"default":null},"thread_replies":{"description":"When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.","type":["boolean","null"],"default":null},"url":{"description":"Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).","type":"string"}},"required":["url","bot_token"]},"McpConfig":{"type":"object","properties":{"servers":{"description":"Named MCP server definitions","type":"object","additionalProperties":{"$ref":"#/$defs/McpServerConfig"},"default":{}},"workspace_servers":{"description":"Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.","$ref":"#/$defs/WorkspaceMcpServers"}}},"McpServerConfig":{"type":"object","properties":{"allow_tools":{"description":"Optional allow-list of exposed tools (empty = all)","type":"array","default":[],"items":{"type":"string"}},"args":{"description":"Command args for stdio mode","type":"array","default":[],"items":{"type":"string"}},"command":{"description":"Command for stdio mode","type":["string","null"],"default":null},"deny_tools":{"description":"Optional deny-list of exposed tools","type":"array","default":[],"items":{"type":"string"}},"env":{"description":"Environment variables for stdio mode","type":"object","additionalProperties":{"type":"string"},"default":{}},"request_timeout_ms":{"description":"Request timeout in milliseconds","type":"integer","format":"uint64","default":30000,"minimum":0},"startup_timeout_ms":{"description":"Startup timeout in milliseconds","type":"integer","format":"uint64","default":10000,"minimum":0},"tool_name_prefix":{"description":"Prefix used in tool naming and routing","type":"string","default":"mcp"},"transport":{"description":"Transport type: stdio or http","$ref":"#/$defs/McpTransport","default":"stdio"},"url":{"description":"URL for HTTP mode (streamable HTTP endpoint)","type":["string","null"],"default":null},"working_dir":{"description":"Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).","type":["string","null"]}}},"McpServerRuntimeConfig":{"type":"object","properties":{"allowed_origins":{"description":"Allowed browser origins for future streamable HTTP clients.","type":"array","default":["claude.ai","openai.com","localhost"],"items":{"type":"string"}},"bind":{"description":"Advertised bind address. The gateway may still be started with a CLI port override.","type":"string","default":"127.0.0.1:16831"},"exposed_tools":{"description":"Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.","type":"array","default":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"items":{"type":"string"}},"jwt_algorithms":{"description":"Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.","type":"array","default":["RS256"],"items":{"type":"string"}},"jwt_audience":{"description":"Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.","type":["string","null"],"default":null},"jwt_issuer":{"description":"Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.","type":["string","null"],"default":null},"jwt_jwks":{"description":"Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.","type":["string","null"],"default":null},"jwt_jwks_cache_ttl_secs":{"description":"Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.","type":"integer","format":"uint64","default":300,"minimum":0},"jwt_jwks_uri":{"description":"Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.","type":["string","null"],"default":null},"jwt_public_key_pem":{"description":"PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.","type":["string","null"],"default":null},"rate_limit_rps":{"description":"Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.","type":"integer","format":"uint32","default":10,"minimum":0},"require_auth":{"description":"Require an authenticated external identity for mutating calls.","type":"boolean","default":true}}},"McpTransport":{"type":"string","enum":["stdio","http"]},"MediaConfig":{"description":"Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.","type":"object","properties":{"audio_model":{"description":"Audio model name (Ollama model or OpenAI model). Default: \"whisper\".","type":"string","default":"whisper"},"audio_ollama_url":{"description":"Ollama base URL for audio transcription. Default: \"http://localhost:11434\".","type":"string","default":"http://localhost:11434"},"audio_provider":{"description":"Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".","type":"string","default":"none"},"max_audio_size_mb":{"description":"Maximum audio attachment size in MiB. Default: 20.","type":"integer","format":"uint","default":20,"minimum":0},"max_video_size_mb":{"description":"Maximum video attachment size in MiB. Default: 50.","type":"integer","format":"uint","default":50,"minimum":0},"video_max_frames":{"description":"Maximum video frames to extract per video. Default: 4.","type":"integer","format":"uint","default":4,"minimum":0},"video_provider":{"description":"Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".","type":"string","default":"none"}}},"MemoryConfig":{"description":"Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.","type":"object","properties":{"acl_enabled":{"description":"Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.","type":"boolean","default":false},"archive_after_days":{"description":"Archive daily/session files older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"auto_hydrate":{"description":"Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing","type":"boolean","default":true},"auto_save":{"description":"Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.","type":"boolean","default":true},"backend":{"description":"\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).","type":"string","default":"sqlite"},"conversation_retention_days":{"description":"For sqlite backend: prune conversation rows older than this many days","type":"integer","format":"uint32","default":3,"minimum":0},"daily_retention_days":{"description":"For sqlite backend: prune daily rows older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"embedding_cache_size":{"description":"Max embedding cache entries before LRU eviction","type":"integer","format":"uint","default":10000,"minimum":0},"embedding_dimensions":{"description":"Embedding vector dimensions","type":"integer","format":"uint","default":384,"minimum":0},"embedding_model":{"description":"Embedding model name (e.g. \"text-embedding-3-small\")","type":"string","default":"prx-local-hash-v1"},"embedding_provider":{"description":"Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"","type":"string","default":"local"},"events":{"description":"Raw/quasi-raw message event recording controls (`[memory.events]`).","$ref":"#/$defs/MemoryEventsConfig","default":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true}},"keyword_weight":{"description":"Weight for keyword BM25 in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.3},"legacy_conversation_turns_visible":{"description":"Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.","type":"boolean","default":true},"lucid_budget":{"description":"Token budget for lucid (replaces OPENPRX_LUCID_BUDGET)","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"lucid_cmd":{"description":"Path to lucid binary (replaces OPENPRX_LUCID_CMD)","type":["string","null"],"default":null},"lucid_failure_cooldown_ms":{"description":"Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)","type":"integer","format":"uint64","default":60000,"minimum":0},"lucid_local_hit_threshold":{"description":"Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)","type":"integer","format":"uint","default":3,"minimum":0},"lucid_recall_timeout_ms":{"description":"Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)","type":"integer","format":"uint64","default":5000,"minimum":0},"lucid_store_timeout_ms":{"description":"Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)","type":"integer","format":"uint64","default":3000,"minimum":0},"min_relevance_score":{"description":"Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4","type":"number","format":"double","default":0.4},"purge_after_days":{"description":"Purge archived files older than this many days","type":"integer","format":"uint32","default":30,"minimum":0},"semantic":{"description":"Semantic memory promotion controls (`[memory.semantic]`).","$ref":"#/$defs/MemorySemanticConfig","default":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30}},"sqlite_open_timeout_secs":{"description":"For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"sqlite_read_pool_size":{"description":"For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"vector_candidate_cap":{"description":"How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.","type":"integer","format":"uint","default":2000,"minimum":0},"vector_weight":{"description":"Weight for vector similarity in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.7}}},"MemoryEventsConfig":{"description":"Raw message event recording configuration (`[memory.events]`).","type":"object","properties":{"record_assistant_messages":{"description":"Record assistant replies.","type":"boolean","default":true},"record_tool_events":{"description":"Record tool/event payloads by default.","type":"boolean","default":false},"record_user_messages":{"description":"Record inbound/user messages.","type":"boolean","default":true}}},"MemorySemanticConfig":{"description":"Semantic memory promotion configuration (`[memory.semantic]`).","type":"object","properties":{"auto_promote_assistant_messages":{"description":"Auto-promote eligible assistant messages. Disabled by default to reduce noise.","type":"boolean","default":false},"auto_promote_user_messages":{"description":"Auto-promote eligible user messages into long-term semantic memories.","type":"boolean","default":true},"min_chars":{"description":"Minimum content length for semantic auto-promotion.","type":"integer","format":"uint","default":30,"minimum":0}}},"MemoryWebhookConfig":{"type":"object","properties":{"bind":{"description":"Socket address for the receiver (e.g. \"0.0.0.0:16899\").","type":"string","default":"0.0.0.0:16899"},"signing_secret":{"description":"Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.","type":["string","null"],"default":null},"token":{"description":"Required bearer token for incoming webhook events.","type":["string","null"],"default":null}}},"ModelOperationSetting":{"description":"The operations a `[[providers.models]]` entry may list.","type":"string","enum":["chat","embedding","decision_endpoint","rerank","image_generation","audio_generation","video_generation"]},"ModelPricing":{"description":"Per-model pricing entry (USD per 1M tokens).","type":"object","properties":{"cache_read":{"description":"Cache read input price per 1M tokens.","type":"number","format":"double","default":0.0},"cache_write":{"description":"Cache write/creation input price per 1M tokens.","type":"number","format":"double","default":0.0},"input":{"description":"Input price per 1M tokens","type":"number","format":"double","default":0.0},"output":{"description":"Output price per 1M tokens","type":"number","format":"double","default":0.0}}},"ModelRouteConfig":{"description":"Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"hint":{"description":"Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")","type":"string"},"level":{"type":["string","null"]},"model":{"description":"Model to use with that provider","type":"string"},"provider":{"description":"Provider to route to (must match a known provider name)","type":"string"},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true,"required":["hint","provider","model"]},"ModelSettings":{"description":"A model level plus explicit parameter overrides in `[model_settings.\"\"]`.","type":"object","properties":{"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"level":{"type":["string","null"]},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true},"MultimodalConfig":{"description":"Multimodal (image) handling configuration (`[multimodal]` section).","type":"object","properties":{"allow_remote_fetch":{"description":"Allow fetching remote image URLs (http/https). Disabled by default.","type":"boolean","default":false},"max_image_size_mb":{"description":"Maximum image payload size in MiB before base64 encoding.","type":"integer","format":"uint","default":5,"minimum":0},"max_images":{"description":"Maximum number of image attachments accepted per request.","type":"integer","format":"uint","default":4,"minimum":0}}},"NextcloudTalkConfig":{"description":"Nextcloud Talk bot configuration (webhook receive + OCS send API).","type":"object","properties":{"allowed_users":{"description":"Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Bot app token used for OCS API bearer auth.","type":"string"},"base_url":{"description":"Nextcloud base URL (e.g. \"https://cloud.example.com\").","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"webhook_secret":{"description":"Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).","type":["string","null"],"default":null}},"required":["base_url","app_token"]},"NgrokTunnelConfig":{"type":"object","properties":{"auth_token":{"description":"ngrok auth token","type":"string"},"domain":{"description":"Optional custom domain","type":["string","null"]}},"required":["auth_token"]},"NodeServerConfig":{"description":"Node daemon runtime config used by `prx-node`.","type":"object","properties":{"allowed_commands":{"description":"Command allowlist matched on first token.\n\nIn restricted mode this list is required unless explicitly set to `[\"*\"]`.","type":"array","default":["echo"],"items":{"type":"string"}},"bearer_token":{"description":"Required bearer token for /rpc.","type":"string","default":""},"blocked_commands":{"description":"Command denylist matched on first token. Always enforced.","type":"array","default":[],"items":{"type":"string"}},"exec_timeout_ms":{"description":"Default command timeout in milliseconds.","type":"integer","format":"uint64","default":15000,"minimum":0},"hmac_secret":{"description":"Optional HMAC signing secret.","type":["string","null"],"default":null},"listen_addr":{"description":"Listen address for node daemon.","type":"string","default":"127.0.0.1:8787"},"max_concurrent_tasks":{"description":"Maximum number of concurrent async command tasks.","type":"integer","format":"uint","default":8,"minimum":0},"max_output_bytes":{"description":"Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.","type":"integer","format":"uint","default":1048576,"minimum":0},"sandbox_root":{"description":"Sandbox root directory for read/write/cwd constraints.","type":"string","default":"."},"task_result_ttl_ms":{"description":"TTL for completed task results in milliseconds.","type":"integer","format":"uint64","default":3600000,"minimum":0},"tls_cert":{"description":"TLS certificate path (PEM).","type":["string","null"],"default":null},"tls_key":{"description":"TLS private key path (PEM).","type":["string","null"],"default":null},"tls_required":{"description":"Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.","type":"boolean","default":true}}},"NodesConfig":{"description":"Remote node proxy configuration for core-side RPC calls and node daemon defaults.","type":"object","properties":{"nodes":{"description":"Configured remote nodes.","type":"array","default":[],"items":{"$ref":"#/$defs/RemoteNodeConfig"}},"request_timeout_ms":{"description":"Default request timeout for node RPC calls.","type":"integer","format":"uint64","default":15000,"minimum":0},"retry_max":{"description":"Default max retries for node RPC calls.","type":"integer","format":"uint8","default":2,"maximum":255,"minimum":0},"server":{"description":"Embedded node server defaults used by `prx-node`.","$ref":"#/$defs/NodeServerConfig","default":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}}},"ObservabilityConfig":{"description":"Observability backend configuration (`[observability]` section).","type":"object","properties":{"backend":{"description":"\"none\" | \"log\" | \"prometheus\" | \"otel\"","type":"string","default":"none"},"otel_endpoint":{"description":"OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".","type":["string","null"],"default":null},"otel_service_name":{"description":"Service name reported to the OTel collector. Defaults to \"prx\".","type":["string","null"],"default":null}}},"OllamaProviderConfig":{"description":"Ollama-specific request options (`[providers.ollama]`).","type":"object","properties":{"num_ctx":{"description":"Explicit context window sent as Ollama `options.num_ctx`.","type":["integer","null"],"format":"uint","default":null,"minimum":0}}},"OsPagingConfig":{"description":"Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.","type":"object","properties":{"eviction_threshold":{"description":"Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.","type":"number","format":"double","default":0.7},"keep_recent_messages":{"description":"Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).","type":"integer","format":"uint","default":12,"minimum":0},"max_recalled_pages":{"description":"Maximum number of evicted pages (document chunks) recalled per turn.","type":"integer","format":"uint","default":10,"minimum":0},"proactive_retrieval":{"description":"Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.","type":"boolean","default":true},"retrieval_injection_role":{"description":"Role under which recalled pages are injected.","$ref":"#/$defs/RetrievalInjectionRole","default":"system"}}},"PluginsConfig":{"description":"WASM plugin runtime configuration.","type":"object","properties":{"enabled":{"description":"Load WASM plugins from `/plugins`. Default: `false`.","type":"boolean","default":false}},"additionalProperties":false},"ProviderModelConfig":{"description":"One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.","type":"object","properties":{"context_window":{"description":"The model's context window in tokens.","type":["integer","null"],"format":"uint32","minimum":0},"model":{"description":"The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.","type":["string","null"]},"native_tools":{"description":"Whether the model accepts native tool calls.","type":["boolean","null"]},"operations":{"description":"The complete list of operations the model executes; every operation not\nlisted is unsupported.","type":["array","null"],"items":{"$ref":"#/$defs/ModelOperationSetting"}},"provider":{"description":"The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.","type":"string"},"streaming":{"description":"Whether the model streams responses.","type":["boolean","null"]},"structured_output":{"description":"Whether the model honours a JSON-schema response format.","type":["boolean","null"]},"tool_call_dialect":{"description":"The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema_dialect":{"description":"The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]},"vision_input":{"description":"Whether the model accepts image input.","type":["boolean","null"]}},"required":["provider"]},"ProviderToolDialectConfig":{"description":"One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.","type":"object","properties":{"model":{"description":"The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.","type":["string","null"]},"provider":{"description":"The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.","type":"string"},"tool_call":{"description":"The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema":{"description":"The tool-schema dialect the endpoint accepts.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]}},"required":["provider"]},"ProvidersConfig":{"description":"Provider-specific runtime configuration (`[providers]`).","type":"object","properties":{"models":{"description":"Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.","type":"array","items":{"$ref":"#/$defs/ProviderModelConfig"}},"ollama":{"description":"Ollama-specific request options (`[providers.ollama]`).","$ref":"#/$defs/OllamaProviderConfig","default":{"num_ctx":null}},"tool_dialects":{"description":"Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).","type":"array","items":{"$ref":"#/$defs/ProviderToolDialectConfig"}}}},"ProxyConfig":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).","type":"object","properties":{"all_proxy":{"description":"Fallback proxy URL for all schemes.","type":["string","null"],"default":null},"http_proxy":{"description":"Proxy URL for HTTP requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"https_proxy":{"description":"Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"no_proxy":{"description":"No-proxy bypass list. Same format as NO_PROXY.","type":"array","default":[],"items":{"type":"string"}},"scope":{"description":"Proxy application scope.","$ref":"#/$defs/ProxyScope","default":"prx"},"services":{"description":"Service selectors used when scope = \"services\".","type":"array","default":[],"items":{"type":"string"}}}},"ProxyScope":{"description":"Proxy application scope — determines which outbound traffic uses the proxy.","oneOf":[{"description":"Use system environment proxy variables only.","type":"string","const":"environment"},{"description":"Apply proxy to all OpenPRX-managed HTTP traffic (default).","type":"string","const":"prx"},{"description":"Apply proxy only to explicitly listed service selectors.","type":"string","const":"services"}]},"QQConfig":{"description":"QQ Official Bot configuration (Tencent QQ Bot SDK)","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs. Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from QQ Bot developer console","type":"string"},"app_secret":{"description":"App Secret from QQ Bot developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["app_id","app_secret"]},"QueryClassificationConfig":{"description":"Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.","type":"object","properties":{"rules":{"description":"Classification rules evaluated in priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/ClassificationRule"}}}},"RamfluxAccountConfig":{"description":"Persona for one ramflux AI account. Missing fields fall back to the global agent.","type":"object","properties":{"cross_conversation_retrieval":{"description":"Cross-conversation memory retrieval. Off unless the owner sets it.","type":"boolean","default":false},"model":{"type":["string","null"],"default":null},"provider":{"type":["string","null"],"default":null},"scope_profile":{"type":["string","null"],"default":null},"system_prompt_file":{"description":"Path to a system-prompt file. Relative paths are resolved from the workspace.","type":["string","null"],"default":null}},"additionalProperties":false},"RamfluxAttachmentFetch":{"description":"Per-turn caps for `attachment.fetch`.","type":"object","properties":{"max_bytes":{"type":"integer","format":"uint64","default":5242880,"minimum":0},"max_per_turn":{"type":"integer","format":"uint8","default":4,"maximum":255,"minimum":0}},"additionalProperties":false},"RamfluxAuthorizationMode":{"description":"How prx combines its own setting with `bridge.hello.authorization`.","oneOf":[{"description":"Use the agent-host value. Until hello arrives, the effective mode is supervised.","type":"string","const":"follow_rf"},{"description":"Always supervised, even when the agent-host declares full.","type":"string","const":"supervised"},{"description":"Full only when the agent-host also declares full. Config alone never yields full.","type":"string","const":"full"}]},"RamfluxConfig":{"description":"Local ramflux agent-host bridge (`[channels_config.ramflux]`).","type":"object","properties":{"accounts":{"type":"object","additionalProperties":{"$ref":"#/$defs/RamfluxAccountConfig"},"default":{}},"allowed_block_types":{"type":"array","default":["Text","Markdown","Heading","KeyValue","Metric","List","TableFallback","Form","Input","Select","Progress","LogStream","Warning","Error","Success","Approval","ActionGroup","FilePreview","Fallback"],"items":{"type":"string"}},"attachment_fetch":{"$ref":"#/$defs/RamfluxAttachmentFetch","default":{"max_bytes":5242880,"max_per_turn":4}},"authorization_mode":{"$ref":"#/$defs/RamfluxAuthorizationMode","default":"follow_rf"},"encrypt_at_rest":{"type":"boolean","default":true},"max_in_flight_per_conversation":{"type":"integer","format":"uint8","default":1,"maximum":255,"minimum":0},"on_new_message":{"$ref":"#/$defs/RamfluxOnNewMessage","default":"queue"},"socket_path":{"description":"Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.","type":["string","null"],"default":null},"surface_limits":{"$ref":"#/$defs/RamfluxSurfaceLimits","default":{"max_actions":16,"max_blocks":32,"max_bytes":65536}},"turn_wall_clock_secs":{"description":"Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.","type":"integer","format":"uint64","default":120,"minimum":0}},"additionalProperties":false},"RamfluxOnNewMessage":{"description":"What to do with a new inbound message while a turn for that conversation is running.","type":"string","enum":["queue","interrupt"]},"RamfluxSurfaceLimits":{"description":"Limits for `reply.surface` blocks and actions.","type":"object","properties":{"max_actions":{"type":"integer","format":"uint32","default":16,"minimum":0},"max_blocks":{"type":"integer","format":"uint32","default":32,"minimum":0},"max_bytes":{"type":"integer","format":"uint32","default":65536,"minimum":0}},"additionalProperties":false},"ReliabilityCircuitBreakerConfig":{"description":"Process-local provider circuit policy (`[reliability.circuit_breaker]`).","type":"object","properties":{"enabled":{"description":"Enable protection for factory-built provider chains.","type":"boolean","default":true},"failure_threshold":{"description":"Consecutive transient failures that open a circuit (at least 1).","type":"integer","format":"uint32","default":5,"minimum":0},"max_open_secs":{"description":"Maximum doubled window, between open_secs and 3600 seconds.","type":"integer","format":"uint64","default":300,"minimum":0},"open_secs":{"description":"Initial open window in seconds (at least 1).","type":"integer","format":"uint64","default":30,"minimum":0}}},"ReliabilityConfig":{"description":"Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.","type":"object","properties":{"acknowledge_single_provider_risk":{"description":"Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.","type":"boolean","default":false},"api_keys":{"description":"Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.","type":"array","default":[],"items":{"type":"string"}},"channel_initial_backoff_secs":{"description":"Initial backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":2,"minimum":0},"channel_max_backoff_secs":{"description":"Max backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":60,"minimum":0},"circuit_breaker":{"description":"Per-provider consecutive failure protection.","$ref":"#/$defs/ReliabilityCircuitBreakerConfig","default":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30}},"fallback_providers":{"description":"Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).","type":"array","default":[],"items":{"type":"string"}},"model_fallbacks":{"description":"Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`","type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"default":{}},"provider_backoff_ms":{"description":"Base backoff (ms) for provider retry delay.","type":"integer","format":"uint64","default":500,"minimum":0},"provider_retries":{"description":"Retries per provider before failing over.","type":"integer","format":"uint32","default":2,"minimum":0},"scheduler_poll_secs":{"description":"Scheduler polling cadence in seconds.","type":"integer","format":"uint64","default":15,"minimum":0},"scheduler_retries":{"description":"Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.","type":"integer","format":"uint32","default":2,"minimum":0}}},"RemoteNodeConfig":{"description":"A remote node target for core-side node proxy calls.","type":"object","properties":{"bearer_token":{"description":"Bearer token for node RPC authentication.","type":"string"},"endpoint":{"description":"Base endpoint (e.g. \"http://127.0.0.1:8787\").","type":"string"},"hmac_secret":{"description":"Optional request signing key (HMAC-SHA256).","type":["string","null"],"default":null},"id":{"description":"Stable node ID used by the nodes tool.","type":"string"},"retry_max":{"description":"Optional per-node retry override.","type":["integer","null"],"format":"uint8","default":null,"maximum":255,"minimum":0},"timeout_ms":{"description":"Optional per-node timeout override.","type":["integer","null"],"format":"uint64","default":null,"minimum":0}},"required":["id","endpoint","bearer_token"]},"RetrievalInjectionRole":{"description":"Where recalled context pages are injected back into the request.","oneOf":[{"description":"Inject recalled pages as a leading `system` message (not user-visible).","type":"string","const":"system"},{"description":"Inject recalled pages as a leading `user` message.","type":"string","const":"user"}]},"RouterConfig":{"description":"Heuristic LLM router configuration (`[router]` section).","type":"object","properties":{"alpha":{"description":"Similarity score weight. Phase 1 keeps this at `0.0`.","type":"number","format":"float","default":0.0},"beta":{"description":"Capability score weight.","type":"number","format":"float","default":0.5},"delta":{"description":"Cost penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"epsilon":{"description":"Latency penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"gamma":{"description":"Elo score weight.","type":"number","format":"float","default":0.30000001192092896},"knn_k":{"description":"Number of nearest neighbors considered for voting. Default: `7`.","type":"integer","format":"uint","default":7,"minimum":0},"knn_min_records":{"description":"Minimum history records before KNN affects routing. Default: `10`.","type":"integer","format":"uint","default":10,"minimum":0},"models":{"description":"Candidate model registry.","type":"array","default":[],"items":{"$ref":"#/$defs/RouterModelConfig"}}}},"RouterModelConfig":{"description":"Static router metadata for one model candidate.","type":"object","properties":{"categories":{"description":"Capability categories such as `conversation`, `code`, or `analysis`.","type":"array","default":[],"items":{"type":"string"}},"cost_per_million_tokens":{"description":"USD cost per million tokens.","type":"number","format":"float","default":0.0},"elo_rating":{"description":"Initial Elo rating.","type":"number","format":"float","default":1000.0},"latency_ms":{"description":"Average latency in milliseconds.","type":"integer","format":"uint32","default":2000,"minimum":0},"max_context":{"description":"Maximum context window in tokens.","type":"integer","format":"uint","default":1000000,"minimum":0},"model_id":{"description":"Model identifier without provider prefix.","type":"string"},"provider":{"description":"Provider identifier.","type":"string"},"reserved_output_tokens":{"description":"Output tokens reserved for this model when planning input context.","type":["integer","null"],"format":"uint","minimum":0}},"required":["model_id","provider"]},"RuntimeConfig":{"description":"Runtime adapter configuration (`[runtime]` section).","type":"object","properties":{"codex_reasoning_effort":{"description":"Codex reasoning effort","type":["string","null"],"default":null},"codex_stream_idle_timeout_secs":{"description":"Codex stream idle timeout in seconds","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"docker":{"description":"Docker runtime settings (used when `kind = \"docker\"`).","$ref":"#/$defs/DockerRuntimeConfig","default":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true}},"idle_hang_secs":{"description":"Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"kind":{"description":"Runtime kind (`native` | `docker`).","type":"string","default":"native"},"long_task_warn_secs":{"description":"Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"managed_cgroup_root":{"description":"Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.","type":["string","null"],"default":null},"max_blocking_threads":{"description":"Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"reasoning_enabled":{"description":"Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported","type":["boolean","null"],"default":null},"shell_env_allowlist":{"description":"Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.","type":"array","default":[],"items":{"type":"string"}},"workdir":{"description":"Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.","type":["string","null"],"default":null}}},"SchedulerConfig":{"description":"Scheduler configuration for periodic task execution (`[scheduler]` section).","type":"object","properties":{"claim_lease_secs":{"description":"Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.","type":"integer","format":"uint64","default":90,"minimum":0},"max_tasks":{"description":"Maximum number of persisted scheduled tasks.","type":"integer","format":"uint","default":64,"minimum":0}}},"ScopeConfig":{"description":"Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```","type":"object","properties":{"assign_owners":{"description":"Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.","type":"array","default":[],"items":{"type":"string"}},"default":{"description":"Default action when no rule matches: \"allow\" (default) or \"deny\".","$ref":"#/$defs/ScopeDefault","default":"allow"},"rules":{"description":"Ordered list of scope rules evaluated top-to-bottom.","type":"array","default":[],"items":{"$ref":"#/$defs/ScopeRule"}}}},"ScopeDefault":{"description":"What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.","oneOf":[{"description":"Unmatched tool calls are allowed (the default).","type":"string","const":"allow"},{"description":"Unmatched tool calls are refused.","type":"string","const":"deny"}]},"ScopeRule":{"description":"A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.","type":"object","properties":{"assign_allow":{"description":"Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".","type":"array","default":[],"items":{"type":"string"}},"assign_deny":{"description":"Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.","type":"array","default":[],"items":{"type":"string"}},"channel":{"description":"Match by channel name: \"signal\", \"telegram\", \"discord\", etc.","type":["string","null"]},"chat_type":{"description":"Match by chat type: \"direct\", \"group\", or \"*\" for any type.","type":["string","null"]},"send_allow":{"description":"Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.","type":"array","default":[],"items":{"type":"string"}},"send_deny":{"description":"Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.","type":"array","default":[],"items":{"type":"string"}},"tools_allow":{"description":"Tool whitelist: only these tools are allowed (empty = all tools permitted).","type":"array","default":[],"items":{"type":"string"}},"tools_deny":{"description":"Tool blacklist: these tools are denied regardless of allow list.","type":"array","default":[],"items":{"type":"string"}},"user":{"description":"Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.","type":["string","null"]}}},"SecretsConfig":{"description":"Secrets encryption configuration (`[secrets]` section).","type":"object","properties":{"encrypt":{"description":"Enable encryption for API keys and tokens in config.toml","type":"boolean","default":true}}},"SecurityConfig":{"description":"Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.","type":"object","properties":{"audit":{"description":"Audit logging configuration","$ref":"#/$defs/AuditConfig","default":{"log_path":"audit.log","max_size_mb":100}},"workspace_hooks":{"description":"Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.","$ref":"#/$defs/WorkspaceHooks"}}},"SelfSystemConfig":{"description":"Self-system experimental automation config (`[self_system]`).","type":"object","properties":{"evolution_config_path":{"description":"Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG)","type":["string","null"],"default":null},"evolution_debug_raw":{"description":"Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW)","type":"boolean","default":false},"evolution_interval_hours":{"description":"Evolution scheduler interval in hours (daemon mode).","type":"integer","format":"uint32","default":24,"minimum":0},"evolution_judge_timeout_secs":{"description":"Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.","type":"integer","format":"uint64","default":180,"minimum":0},"evolution_model_max_micro_usd":{"description":"Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.","type":"integer","format":"uint64","default":0,"minimum":0},"evolution_model_max_tokens":{"description":"Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.","type":"integer","format":"uint64","default":16384,"minimum":0},"fitness":{"description":"Daily fitness snapshot policy.","$ref":"#/$defs/FitnessConfig","default":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"}},"fitness_interval_hours":{"description":"Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.","type":"integer","format":"uint64","default":24,"minimum":0}}},"SessionsSpawnConfig":{"description":"Sessions spawn configuration (`[sessions_spawn]` section).","type":"object","properties":{"cleanup_on_complete":{"description":"Remove worker workspace directory after process-mode completion.","type":"boolean","default":true},"default_mode":{"description":"Default execution mode for sessions_spawn (`task` or `process`).","type":"string","default":"task"},"process_memory_strategy":{"description":"Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.","type":"string","default":"shared_fabric"},"worker_workspace_root":{"description":"Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.","type":["string","null"],"default":null}}},"SignalConfig":{"type":"object","properties":{"account":{"description":"E.164 phone number of the signal-cli account (e.g. \"+1234567890\").","type":"string"},"allowed_from":{"description":"Allowed sender phone numbers (E.164) or \"*\" for all.","type":"array","default":[],"items":{"type":"string"}},"cli_path":{"description":"Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).","type":["string","null"],"default":null},"daemon_http_port":{"description":"Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"daemon_mode":{"description":"Deprecated: ignored. Accepted for backward compatibility with older config files.","type":["boolean","null"],"default":null},"data_dir":{"description":"signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_id":{"description":"Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group","type":["string","null"],"default":null},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"http_url":{"description":"Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.","type":"string","default":"http://localhost:8080"},"ignore_attachments":{"description":"Skip messages that are attachment-only (no text body).","type":"boolean","default":false},"ignore_stories":{"description":"Skip incoming story messages.","type":"boolean","default":false},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"mode":{"description":"Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.","type":["string","null"],"default":null},"startup_timeout_ms":{"description":"Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.","type":"integer","format":"uint64","default":30000,"minimum":0},"storm_protection":{"description":"Signal ingress storm protection controls.","$ref":"#/$defs/SignalStormProtectionConfig","default":{"abnormal_threshold":10,"abnormal_window_secs":60,"breaker_duration_secs":300,"dedupe_ttl_secs":60,"min_reply_interval_secs":2}}},"required":["account"]},"SignalStormProtectionConfig":{"type":"object","properties":{"abnormal_threshold":{"description":"Non-user event threshold within `abnormal_window_secs` before tripping the breaker.","type":"integer","format":"uint","default":10,"minimum":0},"abnormal_window_secs":{"description":"Sliding window in seconds for non-user event counting.","type":"integer","format":"uint64","default":60,"minimum":0},"breaker_duration_secs":{"description":"Circuit breaker duration in seconds after threshold is reached.","type":"integer","format":"uint64","default":300,"minimum":0},"dedupe_ttl_secs":{"description":"Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.","type":"integer","format":"uint64","default":60,"minimum":0},"min_reply_interval_secs":{"description":"Minimum interval in seconds between replies for the same `(channel + reply_target)`.","type":"integer","format":"uint64","default":2,"minimum":0}}},"SkillRagConfig":{"description":"Dynamic skill retrieval configuration (`[skill_rag]` section).","type":"object","properties":{"top_k":{"description":"How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).","type":"integer","format":"uint","default":32,"minimum":0}}},"SkillSuiteRegistration":{"description":"The frozen suite that governs one skill's proposals.","type":"object","properties":{"skill_id":{"description":"The skill the suite governs.","type":"string"},"suite_digest":{"description":"SHA-256 digest (64 lowercase hex digits) of the frozen suite.","type":"string"}},"additionalProperties":false,"required":["skill_id","suite_digest"]},"SkillsConfig":{"description":"Skills loading configuration (`[skills]` section).","type":"object","properties":{"open_skills_dir":{"description":"Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.","type":["string","null"],"default":null},"openclaw_skills_dir":{"description":"Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.","type":["string","null"],"default":null}}},"SkillsLifecycleConfig":{"description":"`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.","type":"object","properties":{"allow_executable_proposals":{"description":"Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.","type":"boolean","default":false},"enabled":{"description":"Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.","type":"boolean","default":false},"max_concurrent_evaluations":{"description":"Most evaluations running at once.","type":"integer","format":"uint32","default":1,"minimum":0},"max_edit_fraction":{"description":"Edit budget of a proposal as a fraction of the skill body, in (0, 1].","type":"number","format":"double","default":0.2},"max_edit_tokens":{"description":"Edit budget of a proposal, in tokens.","type":"integer","format":"uint64","default":300,"minimum":0},"max_proposals_per_cycle":{"description":"Most proposals one cycle may start.","type":"integer","format":"uint32","default":1,"minimum":0},"min_cases_floor":{"description":"Smallest `min_cases` a governing suite may declare. Below 3 is refused.","type":"integer","format":"uint32","default":3,"minimum":0},"mode":{"description":"`draft_only`, `shadow` or `auto`.","$ref":"#/$defs/SkillsLifecycleModeConfig","default":"draft_only"},"owner_scope":{"description":"The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.","type":["string","null"],"default":null},"require_holdout":{"description":"A governing suite must have a holdout split. `false` is refused.","type":"boolean","default":true},"storage_dir":{"description":"Store location under the workspace. Only the default is supported.","type":"string","default":"self/skill-lifecycle"},"suites":{"description":"The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.","type":"array","default":[],"items":{"$ref":"#/$defs/SkillSuiteRegistration"}}},"additionalProperties":false},"SkillsLifecycleModeConfig":{"description":"What the lifecycle may do. Mirrors `LifecycleMode`.","oneOf":[{"description":"Drafts and reviews only.","type":"string","const":"draft_only"},{"description":"Drafts plus evaluation and gating; never publishes.","type":"string","const":"shadow"},{"description":"Publishes an eligible proposal after every gate.","type":"string","const":"auto"}]},"SlackConfig":{"description":"Slack bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Slack user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Slack app-level token for Socket Mode (xapp-...).","type":["string","null"]},"bot_token":{"description":"Slack bot OAuth token (xoxb-...).","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["bot_token"]},"SmartGroupConfig":{"description":"Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).","type":"object","properties":{"classifier_max_context_messages":{"description":"How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.","type":"integer","format":"uint","default":3,"minimum":0},"classifier_model":{"description":"Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.","type":"string","default":""},"classifier_provider":{"description":"Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.","type":"string","default":""},"classifier_temperature":{"description":"Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).","type":"number","format":"double","default":0.0},"classifier_timeout_secs":{"description":"Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.","type":"integer","format":"uint64","default":5,"minimum":0}}},"StorageConfig":{"description":"Persistent storage configuration (`[storage]` section).","type":"object","properties":{"provider":{"description":"Storage provider settings (e.g. sqlite, postgres).","$ref":"#/$defs/StorageProviderSection","default":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}}},"StorageProviderConfig":{"description":"Storage provider backend configuration (e.g. postgres connection details).","type":"object","properties":{"connect_timeout_secs":{"description":"Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"db_url":{"description":"Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.","type":["string","null"],"default":null},"pool_max_size":{"description":"Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.","type":"integer","format":"uint","default":32,"minimum":0},"provider":{"description":"Storage engine key (e.g. \"postgres\", \"sqlite\").","type":"string","default":""},"schema":{"description":"Database schema for SQL backends.","type":"string","default":"public"},"table":{"description":"Table name for memory entries.","type":"string","default":"memories"}}},"StorageProviderSection":{"description":"Wrapper for the storage provider configuration section.","type":"object","properties":{"config":{"description":"Storage provider backend settings.","$ref":"#/$defs/StorageProviderConfig","default":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"StreamMode":{"description":"Streaming mode for channels that support progressive message updates.","oneOf":[{"description":"No streaming -- send the complete response as a single message (default).","type":"string","const":"off"},{"description":"Update a draft message with every flush interval.","type":"string","const":"partial"}]},"TailscaleTunnelConfig":{"type":"object","properties":{"funnel":{"description":"Use Tailscale Funnel (public internet) vs Serve (tailnet only)","type":"boolean","default":false},"hostname":{"description":"Optional hostname override","type":["string","null"]}}},"TaskRoutingConfig":{"description":"Lightweight pre-LLM task routing.","type":"object","properties":{"default_intent":{"description":"Fallback intent when no rule matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"rules":{"description":"Rules evaluated in descending priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/TaskRoutingRule"}}}},"TaskRoutingIntentConfig":{"description":"Task-routing default and rule intent.","type":"string","enum":["simple","delegate","stream"]},"TaskRoutingRule":{"description":"A single task-routing rule.","type":"object","properties":{"intent":{"description":"Route intent to apply when a keyword matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"model_hint":{"description":"Optional model hint/raw model for non-delegated requests.","type":["string","null"],"default":null},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0},"sub_agent_model":{"description":"Optional raw sub-agent model override for delegated tasks.","type":["string","null"],"default":null}}},"TelegramConfig":{"description":"Telegram bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Telegram user IDs or usernames. Empty = deny all.","type":"array","items":{"type":"string"}},"bot_token":{"description":"Telegram Bot API token (from @BotFather).","type":"string"},"draft_update_interval_ms":{"description":"Minimum interval (ms) between draft message edits to avoid rate limits.","type":"integer","format":"uint64","default":1000,"minimum":0},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"interrupt_on_new_message":{"description":"When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.","type":"boolean","default":false},"stream_mode":{"description":"Streaming mode for progressive response delivery via message edits.","$ref":"#/$defs/StreamMode","default":"off"}},"required":["bot_token","allowed_users"]},"ToolCallDialectSetting":{"description":"The tool-call grammars an operator may declare for an endpoint.","oneOf":[{"description":"Only the native `tool_calls` array is a tool call (the default).","type":"string","const":"native"},{"description":"Additionally read `{json}` from the content,\nfor a tool name the request registered.","type":"string","const":"xml_function_tags"}]},"ToolSchemaDialectSetting":{"description":"The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.","oneOf":[{"description":"The published document, byte for byte (the default).","type":"string","const":"raw"},{"description":"The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.","type":"string","const":"no_root_combinators"}]},"ToolTieringConfig":{"description":"Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.","type":"object","properties":{"always_exclude":{"description":"Tool names excluded from capability publication.","type":"array","default":[],"items":{"type":"string"}},"always_include":{"description":"Tool names preferred for direct publication, subject to admission gates.","type":"array","default":[],"items":{"type":"string"}},"channel_exclude":{"description":"Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefault: empty (nothing is hidden); list tool names to hide them on channels.","type":"array","default":[],"items":{"type":"string"}}}},"TunnelConfig":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.","type":"object","properties":{"cloudflare":{"description":"Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).","anyOf":[{"$ref":"#/$defs/CloudflareTunnelConfig"},{"type":"null"}],"default":null},"custom":{"description":"Custom tunnel command configuration (used when `provider = \"custom\"`).","anyOf":[{"$ref":"#/$defs/CustomTunnelConfig"},{"type":"null"}],"default":null},"ngrok":{"description":"ngrok tunnel configuration (used when `provider = \"ngrok\"`).","anyOf":[{"$ref":"#/$defs/NgrokTunnelConfig"},{"type":"null"}],"default":null},"provider":{"description":"Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.","type":"string","default":"none"},"tailscale":{"description":"Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).","anyOf":[{"$ref":"#/$defs/TailscaleTunnelConfig"},{"type":"null"}],"default":null}}},"UserPolicyConfig":{"description":"Startup user policy entry (`[[user_policies]]`).","type":"object","properties":{"blocked_patterns":{"type":"array","default":[],"items":{"type":"string"}},"projects":{"type":"array","default":[],"items":{"type":"string"}},"role":{"type":"string","default":"guest"},"user_id":{"type":"string"},"visibility_ceiling":{"type":"string","default":"private"}},"required":["user_id"]},"WacliConfig":{"description":"wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```","type":"object","properties":{"allow_unsigned_loopback":{"description":"Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).","type":"boolean","default":false},"allowed_from":{"description":"Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.","type":"array","default":["*"],"items":{"type":"string"}},"bot_jid":{"description":"Bot's own JID, used for reply-to-bot mention detection.","type":["string","null"],"default":null},"bot_lid":{"description":"The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.","type":["string","null"],"default":null},"bot_number":{"description":"Bot's own phone number (digits), used for `@` mention detection.","type":["string","null"],"default":null},"cli_path":{"description":"Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.","type":["string","null"],"default":null},"group_reply_mode":{"description":"Smart group-reply mode. When `None`, derived from `mention_only`.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"host":{"description":"REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].","type":["string","null"],"writeOnly":true},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"outbound_media_workspace_only":{"description":"Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.","type":"boolean","default":false},"port":{"description":"REMOVED: legacy JSON-RPC daemon port. See `host`.","type":["integer","null"],"format":"uint16","maximum":65535,"minimum":0,"writeOnly":true},"self_chat_mode":{"description":"Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.","type":"boolean","default":false},"store_dir":{"description":"wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.","type":["string","null"],"default":null},"webhook_listen":{"description":"Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").","type":"string","default":"127.0.0.1:16868"},"webhook_path":{"description":"HTTP path the webhook server serves (default: \"/wacli\").","type":"string","default":"/wacli"},"webhook_secret":{"description":"HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.","type":["string","null"],"default":null}}},"WebSearchConfig":{"description":"Web search tool configuration (`[web_search]` section).","type":"object","properties":{"brave_api_key":{"description":"Brave Search API key (required if provider is \"brave\")","type":["string","null"],"default":null},"fetch_max_chars":{"description":"Maximum characters returned by `web_fetch` (default 10000)","type":"integer","format":"uint","default":50000,"minimum":0},"max_results":{"description":"Maximum results per search (1-20)","type":"integer","format":"uint","default":15,"minimum":0},"provider":{"description":"Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)","type":"string","default":"duckduckgo"},"timeout_secs":{"description":"Request timeout in seconds","type":"integer","format":"uint64","default":15,"minimum":0}}},"WebhookConfig":{"description":"Webhook channel configuration.","type":"object","properties":{"port":{"description":"Port to listen on for incoming webhooks.","type":"integer","format":"uint16","maximum":65535,"minimum":0},"secret":{"description":"Optional shared secret for webhook signature verification.","type":["string","null"]}},"required":["port"]},"WhatsAppConfig":{"description":"WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.","type":"object","properties":{"access_token":{"description":"Access token from Meta Business Suite (Cloud API mode)","type":["string","null"],"default":null},"allowed_numbers":{"description":"Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"app_secret":{"description":"App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"pair_code":{"description":"Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one","type":["string","null"],"default":null},"pair_phone":{"description":"Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used","type":["string","null"],"default":null},"phone_number_id":{"description":"Phone number ID from Meta Business API (Cloud API mode)","type":["string","null"],"default":null},"read_pool_size":{"description":"Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"session_path":{"description":"Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs","type":["string","null"],"default":null},"verify_token":{"description":"Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode","type":["string","null"],"default":null},"ws_url":{"description":"WebSocket URL override (replaces WHATSAPP_WS_URL)","type":["string","null"],"default":null}}},"WorkspaceHooks":{"description":"Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).","oneOf":[{"description":"They do not run (the default); `prx doctor` and `hooks_status` say so.","type":"string","const":"off"},{"description":"They run, in a cleared environment and a dedicated directory beside\n`config.toml`.","type":"string","const":"on"}]},"WorkspaceMcpServers":{"description":"Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).","oneOf":[{"description":"None: a workspace file may only narrow the servers defined in\n`config.toml`.","type":"string","const":"off"},{"description":"HTTP servers (still refused when they target a private address).","type":"string","const":"http_only"},{"description":"HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.","type":"string","const":"stdio"}]},"XinConfig":{"description":"Configuration for the xin autonomous task engine (`[xin]`).","type":"object","properties":{"adopt_legacy_tasks":{"description":"Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).","type":"boolean","default":false},"interval_minutes":{"description":"Tick interval in minutes (minimum 1). Default: 5.","type":"integer","format":"uint32","default":5,"minimum":0},"stale_timeout_minutes":{"description":"Minutes after which a running task is marked stale. Default: 60.","type":"integer","format":"uint32","default":60,"minimum":0}}},"AgentMessaging":{"description":"Owner-controlled inbound session messaging (enabled unless explicitly off).","type":"object","properties":{"inbound":{"type":"boolean","default":true}}}}} From 53845f50c885a3d1c904dcbe52e96564c6a3f502 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:41:40 +0400 Subject: [PATCH 0135/1567] feat(config): fetch remote images by default --- docs/configuration.md | 2 +- docs/migration-unreleased.md | 1 + src/config/schema/agent.rs | 10 +++++++--- src/runtime/child_source/golden_effective_config.json | 2 +- tests/fixtures/config-schema.json | 2 +- 5 files changed, 11 insertions(+), 6 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 9dd73c770..789d1a5d1 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -141,7 +141,7 @@ and the module-gate family are absorbed on load; they are not live switches. | `[secrets]` | `encrypt = true` | | `[browser]` | `allowed_domains = []` (`web_fetch`); `computer_use.api_key` unset (retained for secret handling; browser automation tools are gone) | | `[http_request]` | `max_response_size = 1000000`; `timeout_secs = 30` | -| `[multimodal]` | `max_images = 4`; `max_image_size_mb = 5`; `allow_remote_fetch = false` | +| `[multimodal]` | `max_images = 4`; `max_image_size_mb = 5`; `allow_remote_fetch = true` | | `[web_search]` | `provider = "duckduckgo"`; `brave_api_key` unset; `max_results = 15`; `timeout_secs = 15`; `fetch_max_chars = 50000` | | `[proxy]` | `http_proxy`/`https_proxy`/`all_proxy` unset; `no_proxy = []`; `scope = "prx"`; `services = []` | | `[identity]` | `format = "openclaw"`; `aieos_path` unset; `aieos_inline` unset | diff --git a/docs/migration-unreleased.md b/docs/migration-unreleased.md index 79f0535bb..796bf2c71 100644 --- a/docs/migration-unreleased.md +++ b/docs/migration-unreleased.md @@ -30,6 +30,7 @@ of the [changelog](../CHANGELOG.md). | Known Codex model default effort | Declared Codex rows now use `medium` rather than `xhigh`. Set an explicit supported effort if the former behavior is required. Unknown rows keep the legacy `medium` verbosity / `xhigh` effort base. See [model levels and parameters](model-catalog.md). | Only to retain the former effort | | No spend ceiling by default | `[autonomy] max_cost_per_day_cents`, `[cost] daily_limit_usd` and `[cost] monthly_limit_usd` are now optional and unset by default. Before: a config that omitted them got 500 cents per day, 10.0 USD per day and 100.0 USD per month. Now: a config that omits them has no limit, so no spend is refused for a budget reason, no budget warning or "budget exhausted" notice is printed, and children and worker processes get the maximum allowance (`u32::MAX` cents in the signed manifest). A config that sets any of these keys keeps exactly that limit. `prx init` no longer writes `max_cost_per_day_cents`. Usage accounting and the cost journal are unchanged. To keep the old ceilings, write them into the config. Per-agent `limits` were already unset by default. No stored-data migration is required. | Only to keep the former ceilings: set the three keys explicitly | | Nothing restricted by default on a fresh install | `[tool_tiering] channel_exclude` now defaults to an empty list (before: 14 operations tools such as `gateway`, `config_reload`, `nodes`, `skills_manage` were hidden from IM channel turns); a config that omits it now exposes those tools on channel turns, and a config that lists names keeps hiding them. `prx init --spec server` no longer writes `workspace_only`, `forbidden_paths` or `acknowledge_unrestricted_profile` (the built-in values are unchanged and have no effect at level `full`); `--spec full` no longer writes `acknowledge_unrestricted_profile`. `prx doctor` no longer warns for an explicit unrestricted profile; it prints one neutral autonomy-level line, and `acknowledge_unrestricted_profile` is accepted and ignored. Gateway pairing, channel sender allowlists, secret protection and integrity checks are unchanged. | Only to keep the old channel tool hiding: list the names in `channel_exclude` | +| Remote image fetch on by default | `[multimodal] allow_remote_fetch` now defaults to `true` (before: `false`). A config that omits it now lets `http`/`https` image references be fetched into the model context; an explicit `false` keeps the old behavior. The fetch keeps the same private-address handling as `web_fetch`: below Full private, loopback and link-local hosts are refused, at Full they are reachable. | Only to keep remote fetch off: set `allow_remote_fetch = false` | | WASM plugins off by default | Set `[plugins] enabled = true` and restart only after reviewing each plugin; install or update with `wasm_plugins_manage` and explicit `grant_permissions` to write `plugin-trust.json` beside `config.toml`. The configuration directory and `plugin-cache/` must be outside the workspace. A `.prx-managed` marker grants no trust. | To use WASM plugins | | Plugin outbound requests | An empty `http_allowlist` now denies every URL. Use URL patterns such as `https://api.example.com/*`, not string prefixes such as `https://api.example.com*`. The SSRF guard still refuses private, loopback and other unsafe destinations. See [plugin trust and networking](plugin-developer-guide.md). | For plugins needing outbound HTTP | | Workspace command hooks default off | Set `[security] workspace_hooks = "on"` only after reviewing workspace commands. Remove non-null `cwd` from `hooks.json`: the whole candidate file is refused. Commands now start with a cleared environment in the dedicated directory beside `config.toml`; use explicit paths and allowed `env` entries. See [workspace command hooks](configuration.md#workspace-command-hooks). | To run workspace command hooks | diff --git a/src/config/schema/agent.rs b/src/config/schema/agent.rs index c208ca169..1138ab3d9 100644 --- a/src/config/schema/agent.rs +++ b/src/config/schema/agent.rs @@ -470,8 +470,8 @@ pub struct MultimodalConfig { /// Maximum image payload size in MiB before base64 encoding. #[serde(default = "default_multimodal_max_image_size_mb")] pub max_image_size_mb: usize, - /// Allow fetching remote image URLs (http/https). Disabled by default. - #[serde(default)] + /// Allow fetching remote image URLs (http/https). Enabled by default. + #[serde(default = "default_multimodal_allow_remote_fetch")] pub allow_remote_fetch: bool, } @@ -483,6 +483,10 @@ pub(super) const fn default_multimodal_max_image_size_mb() -> usize { 5 } +pub(super) const fn default_multimodal_allow_remote_fetch() -> bool { + true +} + impl MultimodalConfig { /// Clamp configured values to safe runtime bounds. pub fn effective_limits(&self) -> (usize, usize) { @@ -497,7 +501,7 @@ impl Default for MultimodalConfig { Self { max_images: default_multimodal_max_images(), max_image_size_mb: default_multimodal_max_image_size_mb(), - allow_remote_fetch: false, + allow_remote_fetch: default_multimodal_allow_remote_fetch(), } } } diff --git a/src/runtime/child_source/golden_effective_config.json b/src/runtime/child_source/golden_effective_config.json index c9f8c7340..bc6809f6d 100644 --- a/src/runtime/child_source/golden_effective_config.json +++ b/src/runtime/child_source/golden_effective_config.json @@ -1 +1 @@ -{"a2a":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trust_domain":"prx.local","trusted_trust_domains":[]},"agent":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"messaging":{"inbound":true},"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2},"agents":{},"api_key":null,"api_url":null,"auth":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"},"autonomy":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true},"browser":{"allowed_domains":[],"computer_use":{"api_key":null}},"channels_config":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null},"chat":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2},"compliance":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}},"composio":{"api_key":null,"entity_id":"default"},"cost":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{"alpha/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0},"zeta/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0}},"warn_at_percent":80},"cron":{"max_run_history":50},"decision_engine":{"backend":{"circuit_breaker":{"cooldown_secs":60,"failure_threshold":5},"credential_ref":"","endpoint":"","kind":"auto","max_request_bytes":65536,"max_response_bytes":262144,"model":"","pinned_snapshot":"","remote_enabled":false,"timeout_ms":250},"candidates":5,"enabled":false,"latency_budget_ms":500,"max_candidates":12,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"token_ratio_limit":0.3499999940395355},"default_model":"anthropic/claude-sonnet-5","default_provider":"openrouter","default_temperature":0.7,"embedding_routes":[],"gateway":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60},"heartbeat":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."},"http_request":{"max_response_size":1000000,"timeout_secs":30},"identity":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"},"identity_bindings":[],"mcp":{"servers":{}},"mcp_server":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true},"media":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"},"memory":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7},"model_routes":[],"model_settings":{},"multimodal":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4},"nodes":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}},"observability":{"backend":"none","otel_endpoint":null,"otel_service_name":null},"plugins":{"enabled":false},"providers":{"ollama":{"num_ctx":null}},"proxy":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]},"query_classification":{"rules":[]},"reliability":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2},"router":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]},"runtime":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null},"scheduler":{"claim_lease_secs":90,"max_tasks":64},"secrets":{"encrypt":true},"security":{"audit":{"log_path":"audit.log","max_size_mb":100}},"self_system":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24},"sessions_spawn":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null},"skill_rag":{"top_k":32},"skills":{"open_skills_dir":null,"openclaw_skills_dir":null},"skills_lifecycle":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]},"smart_group":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5},"storage":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}},"task_routing":{"default_intent":"simple","rules":[]},"tool_tiering":{"always_exclude":[],"always_include":[],"channel_exclude":[]},"tunnel":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null},"user_policies":[],"web_search":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15},"webhook":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null},"xin":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}} \ No newline at end of file +{"a2a":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trust_domain":"prx.local","trusted_trust_domains":[]},"agent":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"messaging":{"inbound":true},"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2},"agents":{},"api_key":null,"api_url":null,"auth":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"},"autonomy":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true},"browser":{"allowed_domains":[],"computer_use":{"api_key":null}},"channels_config":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null},"chat":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2},"compliance":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}},"composio":{"api_key":null,"entity_id":"default"},"cost":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{"alpha/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0},"zeta/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0}},"warn_at_percent":80},"cron":{"max_run_history":50},"decision_engine":{"backend":{"circuit_breaker":{"cooldown_secs":60,"failure_threshold":5},"credential_ref":"","endpoint":"","kind":"auto","max_request_bytes":65536,"max_response_bytes":262144,"model":"","pinned_snapshot":"","remote_enabled":false,"timeout_ms":250},"candidates":5,"enabled":false,"latency_budget_ms":500,"max_candidates":12,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"token_ratio_limit":0.3499999940395355},"default_model":"anthropic/claude-sonnet-5","default_provider":"openrouter","default_temperature":0.7,"embedding_routes":[],"gateway":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60},"heartbeat":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."},"http_request":{"max_response_size":1000000,"timeout_secs":30},"identity":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"},"identity_bindings":[],"mcp":{"servers":{}},"mcp_server":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true},"media":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"},"memory":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7},"model_routes":[],"model_settings":{},"multimodal":{"allow_remote_fetch":true,"max_image_size_mb":5,"max_images":4},"nodes":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}},"observability":{"backend":"none","otel_endpoint":null,"otel_service_name":null},"plugins":{"enabled":false},"providers":{"ollama":{"num_ctx":null}},"proxy":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]},"query_classification":{"rules":[]},"reliability":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2},"router":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]},"runtime":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null},"scheduler":{"claim_lease_secs":90,"max_tasks":64},"secrets":{"encrypt":true},"security":{"audit":{"log_path":"audit.log","max_size_mb":100}},"self_system":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24},"sessions_spawn":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null},"skill_rag":{"top_k":32},"skills":{"open_skills_dir":null,"openclaw_skills_dir":null},"skills_lifecycle":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]},"smart_group":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5},"storage":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}},"task_routing":{"default_intent":"simple","rules":[]},"tool_tiering":{"always_exclude":[],"always_include":[],"channel_exclude":[]},"tunnel":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null},"user_policies":[],"web_search":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15},"webhook":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null},"xin":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}} \ No newline at end of file diff --git a/tests/fixtures/config-schema.json b/tests/fixtures/config-schema.json index 7d0040a06..d5fd921ee 100644 --- a/tests/fixtures/config-schema.json +++ b/tests/fixtures/config-schema.json @@ -1 +1 @@ -{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Config","description":"Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).","type":"object","properties":{"a2a":{"description":"Agent-to-Agent compatibility configuration (`[a2a]`).","$ref":"#/$defs/A2aConfig","default":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trusted_trust_domains":[],"trust_domain":"prx.local"}},"agent":{"description":"Agent orchestration settings (`[agent]`).","$ref":"#/$defs/AgentConfig","default":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2,"messaging":{"inbound":true}}},"agents":{"description":"Delegate agent configurations for multi-agent workflows.","type":"object","additionalProperties":{"$ref":"#/$defs/DelegateAgentConfig"},"default":{}},"api_key":{"description":"API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.","type":["string","null"],"default":null},"api_url":{"description":"Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)","type":["string","null"],"default":null},"auth":{"description":"Auth profile and external credential import settings (`[auth]`).","$ref":"#/$defs/AuthConfig","default":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"}},"autonomy":{"description":"Autonomy and security policy configuration (`[autonomy]`).","$ref":"#/$defs/AutonomyConfig","default":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true}},"browser":{"description":"Browser automation configuration (`[browser]`).","$ref":"#/$defs/BrowserConfig","default":{"allowed_domains":[],"computer_use":{"api_key":null}}},"channels_config":{"description":"Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).","$ref":"#/$defs/ChannelsConfig","default":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null}},"chat":{"description":"Interactive chat UI configuration (`[chat]`).","$ref":"#/$defs/ChatConfig","default":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2}},"compliance":{"description":"Operator-owned compliance controls (`[compliance]`).","$ref":"#/$defs/ComplianceConfig","default":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}},"composio":{"description":"Composio managed OAuth tools integration (`[composio]`).","$ref":"#/$defs/ComposioConfig","default":{"api_key":null,"entity_id":"default"}},"cost":{"description":"Cost tracking and budget enforcement configuration (`[cost]`).","$ref":"#/$defs/CostConfig","default":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{},"warn_at_percent":80}},"cron":{"description":"Cron job configuration (`[cron]`).","$ref":"#/$defs/CronConfig","default":{"max_run_history":50}},"decision_engine":{"description":"Optional advisory decision engine, disabled by default.","$ref":"#/$defs/DecisionEngineConfig","default":{"candidates":5,"enabled":false,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"latency_budget_ms":500,"max_candidates":12,"token_ratio_limit":0.3499999940395355}},"default_model":{"description":"Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.","type":["string","null"]},"default_provider":{"description":"Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.","type":["string","null"]},"default_temperature":{"description":"Default model temperature (0.0–2.0). Default: `0.7`.","type":"number","format":"double","default":0.7},"embedding_routes":{"description":"Embedding routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/EmbeddingRouteConfig"}},"gateway":{"description":"Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).","$ref":"#/$defs/GatewayConfig","default":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60}},"heartbeat":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]`).","$ref":"#/$defs/HeartbeatConfig","default":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."}},"http_request":{"description":"HTTP request tool configuration (`[http_request]`).","$ref":"#/$defs/HttpRequestConfig","default":{"max_response_size":1000000,"timeout_secs":30}},"identity":{"description":"Identity format configuration: OpenClaw or AIEOS (`[identity]`).","$ref":"#/$defs/IdentityConfig","default":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"}},"identity_bindings":{"description":"Static identity bindings loaded at startup (`[[identity_bindings]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/IdentityBindingConfig"}},"mcp":{"description":"Secrets encryption configuration (`[secrets]`).","$ref":"#/$defs/McpConfig","default":{"servers":{}}},"mcp_server":{"description":"MCP server compatibility configuration (`[mcp_server]`).","$ref":"#/$defs/McpServerRuntimeConfig","default":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true}},"media":{"description":"Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.","$ref":"#/$defs/MediaConfig","default":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"}},"memory":{"description":"Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).","$ref":"#/$defs/MemoryConfig","default":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7}},"model_routes":{"description":"Model routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/ModelRouteConfig"}},"model_settings":{"description":"Catalog model levels and explicit parameters, keyed by canonical release ID.","type":"object","additionalProperties":{"$ref":"#/$defs/ModelSettings"},"default":{}},"multimodal":{"description":"Multimodal (image) handling configuration (`[multimodal]`).","$ref":"#/$defs/MultimodalConfig","default":{"allow_remote_fetch":false,"max_image_size_mb":5,"max_images":4}},"nodes":{"description":"Remote node proxy configuration (`[nodes]`).","$ref":"#/$defs/NodesConfig","default":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}},"observability":{"description":"Observability backend configuration (`[observability]`).","$ref":"#/$defs/ObservabilityConfig","default":{"backend":"none","otel_endpoint":null,"otel_service_name":null}},"plugins":{"description":"WASM plugin runtime switch (`[plugins]`), off by default.","$ref":"#/$defs/PluginsConfig","default":{"enabled":false}},"providers":{"description":"Provider-specific runtime options (`[providers.]`).","$ref":"#/$defs/ProvidersConfig","default":{"ollama":{"num_ctx":null}}},"proxy":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).","$ref":"#/$defs/ProxyConfig","default":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]}},"query_classification":{"description":"Automatic query classification — maps user messages to model hints.","$ref":"#/$defs/QueryClassificationConfig","default":{"rules":[]}},"reliability":{"description":"Reliability settings: retries, fallback providers, backoff (`[reliability]`).","$ref":"#/$defs/ReliabilityConfig","default":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2}},"router":{"description":"Heuristic LLM router configuration (`[router]`).","$ref":"#/$defs/RouterConfig","default":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]}},"runtime":{"description":"Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.","$ref":"#/$defs/RuntimeConfig","default":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null}},"scheduler":{"description":"Scheduler configuration for periodic task execution (`[scheduler]`).","$ref":"#/$defs/SchedulerConfig","default":{"claim_lease_secs":90,"max_tasks":64}},"secrets":{"$ref":"#/$defs/SecretsConfig","default":{"encrypt":true}},"security":{"description":"Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).","$ref":"#/$defs/SecurityConfig","default":{"audit":{"log_path":"audit.log","max_size_mb":100}}},"self_system":{"description":"Self-system experimental automation controls (`[self_system]`).","$ref":"#/$defs/SelfSystemConfig","default":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24}},"sessions_spawn":{"description":"Session spawning configuration (`[sessions_spawn]`).","$ref":"#/$defs/SessionsSpawnConfig","default":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null}},"skill_rag":{"description":"Dynamic skill retrieval settings (`[skill_rag]`).","$ref":"#/$defs/SkillRagConfig","default":{"top_k":32}},"skills":{"description":"Skills loading and community repository behavior (`[skills]`).","$ref":"#/$defs/SkillsConfig","default":{"open_skills_dir":null,"openclaw_skills_dir":null}},"skills_lifecycle":{"description":"Skill lifecycle (`[skills_lifecycle]`), off by default.","$ref":"#/$defs/SkillsLifecycleConfig","default":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]}},"smart_group":{"description":"Smart group-reply pre-gate configuration (`[smart_group]`).","$ref":"#/$defs/SmartGroupConfig","default":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5}},"storage":{"description":"Persistent storage provider configuration (`[storage]`).","$ref":"#/$defs/StorageConfig","default":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"task_routing":{"description":"Task routing configuration — classifies work by intent before the main agent loop.","$ref":"#/$defs/TaskRoutingConfig","default":{"default_intent":"simple","rules":[]}},"tool_tiering":{"description":"Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).","$ref":"#/$defs/ToolTieringConfig","default":{"always_exclude":[],"always_include":[],"channel_exclude":[]}},"tunnel":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]`).","$ref":"#/$defs/TunnelConfig","default":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null}},"user_policies":{"description":"Static user policy records loaded at startup (`[[user_policies]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/UserPolicyConfig"}},"web_search":{"description":"Web search tool configuration (`[web_search]`).","$ref":"#/$defs/WebSearchConfig","default":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15}},"webhook":{"description":"Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).","$ref":"#/$defs/MemoryWebhookConfig","default":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null}},"xin":{"description":"Xin autonomous task engine configuration (`[xin]`).","$ref":"#/$defs/XinConfig","default":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}}},"$defs":{"A2aConfig":{"type":"object","properties":{"agent_id":{"description":"Stable PRX agent identifier advertised to peers.","type":"string","default":"prx-default"},"allowed_peer_issuers":{"description":"Accepted external peer issuers.","type":"array","default":[],"items":{"type":"string"}},"bind":{"description":"Advertised bind address.","type":"string","default":"127.0.0.1:16832"},"card_jwks_uri":{"description":"Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.","type":["string","null"],"default":null},"card_signing_key_path":{"description":"On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).","type":["string","null"],"default":null},"card_ttl_seconds":{"description":"Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.","type":"integer","format":"uint64","default":3600,"minimum":0},"discovery_advertised":{"description":"Whether to advertise into an external A2A registry.","type":"boolean","default":false},"handoff_nonce_ttl_seconds":{"description":"Replay window for future handoff delegation tokens.","type":"integer","format":"uint64","default":3600,"minimum":0},"messaging_enabled":{"description":"Enable the dedicated pinned mTLS messaging listener.","type":"boolean","default":false},"peers":{"type":"object","additionalProperties":{"$ref":"#/$defs/A2aPeer"},"default":{}},"spiffe_id":{"description":"Local SPIFFE-style identifier placeholder.","type":"string","default":"spiffe://prx-local/agent/prx-default"},"spiffe_strict_validation":{"description":"When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.","type":"boolean","default":false},"spiffe_trust_bundle_pem":{"description":"Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).","type":["string","null"],"default":null},"trusted_trust_domains":{"description":"Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).","type":"array","default":[],"items":{"type":"string"}},"trust_domain":{"description":"SPIFFE trust domain for new instance identities.","type":"string","default":"prx.local"}}},"A2aPeer":{"description":"Explicit pinned identity and local recipient grant.","type":"object","properties":{"spiffe_id":{"type":"string"},"fingerprints":{"type":"array","items":{"type":"string"}},"address":{"type":"string"},"owner":{"type":"string"},"sessions":{"type":"array","default":["*"],"items":{"type":"string"}},"agents":{"type":"array","default":["*"],"items":{"type":"string"}}},"required":["spiffe_id","fingerprints","address","owner"],"additionalProperties":false},"AgentCompactionConfig":{"description":"Agent context compaction configuration (`[agent.compaction]`).","type":"object","properties":{"keep_recent_messages":{"description":"Number of recent non-system messages to keep after compaction.","type":"integer","format":"uint","default":12,"minimum":0},"max_context_tokens":{"description":"Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.","type":"integer","format":"uint","default":128000,"minimum":0},"memory_flush":{"description":"Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.","type":"boolean","default":true},"mode":{"description":"Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).","$ref":"#/$defs/AgentCompactionMode","default":"switch"},"os_paging":{"description":"Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.","$ref":"#/$defs/OsPagingConfig","default":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"}},"reserve_tokens":{"description":"Tokens reserved for the next model response.","type":"integer","format":"uint","default":4096,"minimum":0}}},"AgentCompactionMode":{"description":"Compaction mode for long conversation contexts.","oneOf":[{"description":"Disable proactive compaction.","type":"string","const":"off"},{"description":"Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.","type":"string","const":"switch"},{"description":"Conservative compaction that prefers summary replacement.","type":"string","const":"safeguard"},{"description":"Aggressive truncation mode for tighter contexts.","type":"string","const":"aggressive"}]},"AgentConfig":{"description":"Agent orchestration configuration (`[agent]` section).","type":"object","properties":{"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"compact_context":{"description":"When true: bootstrap_max_chars=6000. Use for 13B or smaller models.","type":"boolean","default":false},"compaction":{"description":"Context compaction controls (`[agent.compaction]`).","$ref":"#/$defs/AgentCompactionConfig","default":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096}},"low_priority_tools":{"description":"Tool names treated as low-priority when `priority_scheduling_enabled = true`.","type":"array","default":["sessions_spawn","delegate"],"items":{"type":"string"}},"priority_scheduling_enabled":{"description":"Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.","type":"boolean","default":false},"read_only_tool_concurrency_window":{"description":"Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.","type":"integer","format":"uint","default":2,"minimum":0},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}}},"AgentLimits":{"description":"Optional admission limits for rf-started turns of a named agent.","type":"object","properties":{"max_concurrent_turns":{"type":["integer","null"],"format":"uint32","minimum":0},"max_cost_per_day_cents":{"type":["integer","null"],"format":"uint64","minimum":0}},"additionalProperties":false},"AuditConfig":{"description":"Audit logging configuration","type":"object","properties":{"log_path":{"description":"Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).","type":"string","default":"audit.log"},"max_size_mb":{"description":"Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).","type":"integer","format":"uint32","default":100,"minimum":0}}},"AuthConfig":{"description":"Authentication and external credential import configuration (`[auth]` section).","type":"object","properties":{"codex_auth_json_auto_import":{"description":"Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.","type":"boolean","default":false},"codex_auth_json_path":{"description":"Source path for Codex CLI auth.json import.","type":"string","default":"~/.codex/auth.json"}}},"AutonomyConfig":{"type":"object","properties":{"acknowledge_unrestricted_profile":{"description":"Operator acknowledgement for an intentionally unrestricted profile.\nRetained for existing configs; it no longer changes any output or policy behavior.","type":"boolean","default":false},"forbidden_paths":{"description":"Explicit path denylist. Default includes system-critical paths.\n\nFails closed: omitting the key keeps the built-in list rather than\nemptying it, so a partial `[autonomy]` section never removes the\ndenylist.","type":"array","default":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"items":{"type":"string"}},"level":{"description":"Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).","$ref":"#/$defs/AutonomyLevel","default":"full"},"max_cost_per_day_cents":{"description":"Maximum cost per day in cents per policy. Default: unset (no ceiling).","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"scopes":{"description":"Scope-based tool access control: per-user/channel/chat-type allow/deny rules.","$ref":"#/$defs/ScopeConfig","default":{"assign_owners":[],"default":"allow","rules":[]}},"workspace_only":{"description":"Restrict file writes and command paths to the workspace directory. Default: `true`.\n\nFails closed: a `[autonomy]` section that omits this key keeps the\nworkspace restriction on, so a partial section can never widen the\nfilesystem reach by accident.","type":"boolean","default":true}}},"AutonomyLevel":{"description":"How much autonomy the agent has","oneOf":[{"description":"Read-only: can observe but not act","type":"string","const":"readonly"},{"description":"Supervised: acts but requires approval for risky operations","type":"string","const":"supervised"},{"description":"Full: autonomous execution within policy bounds","type":"string","const":"full"}]},"BackendSelection":{"description":"Which decision backend runs: `auto` (the factory's order) or one kind.","type":"string"},"BrowserComputerUseConfig":{"description":"Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.","type":"object","properties":{"api_key":{"description":"Optional bearer token (retained only for config secret handling).","type":["string","null"],"default":null}}},"BrowserConfig":{"description":"Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.","type":"object","properties":{"allowed_domains":{"description":"Allowed domains for `web_fetch` (exact or subdomain match).","type":"array","default":[],"items":{"type":"string"}},"computer_use":{"description":"Computer-use sidecar config (retained only for `api_key` secret handling).","$ref":"#/$defs/BrowserComputerUseConfig","default":{"api_key":null}}}},"ChannelsConfig":{"description":"Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.","type":"object","properties":{"cli":{"description":"Enable the CLI interactive channel. Default: `true`.","type":"boolean","default":true},"dingtalk":{"description":"DingTalk channel configuration.","anyOf":[{"$ref":"#/$defs/DingTalkConfig"},{"type":"null"}]},"discord":{"description":"Discord bot channel configuration.","anyOf":[{"$ref":"#/$defs/DiscordConfig"},{"type":"null"}]},"email":{"description":"Email channel configuration.","anyOf":[{"$ref":"#/$defs/EmailConfig"},{"type":"null"}]},"imessage":{"description":"iMessage channel configuration (macOS only).","anyOf":[{"$ref":"#/$defs/IMessageConfig"},{"type":"null"}]},"irc":{"description":"IRC channel configuration.","anyOf":[{"$ref":"#/$defs/IrcConfig"},{"type":"null"}]},"lark":{"description":"Lark/Feishu channel configuration.","anyOf":[{"$ref":"#/$defs/LarkConfig"},{"type":"null"}]},"linq":{"description":"Linq Partner API channel configuration.","anyOf":[{"$ref":"#/$defs/LinqConfig"},{"type":"null"}]},"mattermost":{"description":"Mattermost bot channel configuration.","anyOf":[{"$ref":"#/$defs/MattermostConfig"},{"type":"null"}]},"nextcloud_talk":{"description":"Nextcloud Talk bot channel configuration.","anyOf":[{"$ref":"#/$defs/NextcloudTalkConfig"},{"type":"null"}]},"qq":{"description":"QQ Official Bot channel configuration.","anyOf":[{"$ref":"#/$defs/QQConfig"},{"type":"null"}]},"ramflux":{"description":"Local ramflux agent-host bridge.","anyOf":[{"$ref":"#/$defs/RamfluxConfig"},{"type":"null"}],"default":null},"signal":{"description":"Signal channel configuration.","anyOf":[{"$ref":"#/$defs/SignalConfig"},{"type":"null"}]},"slack":{"description":"Slack bot channel configuration.","anyOf":[{"$ref":"#/$defs/SlackConfig"},{"type":"null"}]},"telegram":{"description":"Telegram bot channel configuration.","anyOf":[{"$ref":"#/$defs/TelegramConfig"},{"type":"null"}]},"wacli":{"description":"wacli JSON-RPC daemon channel configuration.","anyOf":[{"$ref":"#/$defs/WacliConfig"},{"type":"null"}],"default":null},"webhook":{"description":"Webhook channel configuration.","anyOf":[{"$ref":"#/$defs/WebhookConfig"},{"type":"null"}]},"whatsapp":{"description":"WhatsApp channel configuration (Cloud API or Web mode).","anyOf":[{"$ref":"#/$defs/WhatsAppConfig"},{"type":"null"}]}}},"ChatConfig":{"description":"Interactive chat configuration (`[chat]`).","type":"object","properties":{"daemon":{"description":"How this chat process reaches the daemon it borrows channels from.","$ref":"#/$defs/ChatDaemonConfig","default":{"token":"","url":""}},"max_concurrent_visible_turns":{"description":"Maximum concurrent visible provider turns in the TUI Redux driver.","type":"integer","format":"uint","default":2,"minimum":0}}},"ChatDaemonConfig":{"description":"Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.","type":"object","properties":{"token":{"description":"Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.","type":"string","default":""},"url":{"description":"Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.","type":"string","default":""}}},"CircuitBreakerConfig":{"description":"The per-backend circuit breaker.","type":"object","properties":{"cooldown_secs":{"description":"Seconds the breaker stays open (1 to 3600).","type":"integer","format":"uint32","default":60,"minimum":0},"failure_threshold":{"description":"Consecutive failures before the breaker opens (1 to 100).","type":"integer","format":"uint32","default":5,"minimum":0}}},"ClassificationRule":{"description":"A single classification rule mapping message patterns to a model hint.","type":"object","properties":{"hint":{"description":"Must match a `[[model_routes]]` hint value.","type":"string"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"max_length":{"description":"Only match if message length <= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"min_length":{"description":"Only match if message length >= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"patterns":{"description":"Case-sensitive literal matches (for \"```\", \"fn \", etc.).","type":"array","default":[],"items":{"type":"string"}},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0}},"required":["hint"]},"CloudflareTunnelConfig":{"type":"object","properties":{"token":{"description":"Cloudflare Tunnel token (from Zero Trust dashboard)","type":"string"}},"required":["token"]},"ComplianceConfig":{"type":"object","properties":{"eu_ai_act":{"$ref":"#/$defs/EuAiActComplianceConfig","default":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null}},"interaction_notice":{"$ref":"#/$defs/InteractionNoticeConfig","default":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}}},"ComposioConfig":{"description":"Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.","type":"object","properties":{"api_key":{"description":"Composio API key (stored encrypted when secrets.encrypt = true)","type":["string","null"],"default":null},"entity_id":{"description":"Default entity ID for multi-user setups","type":"string","default":"default"}}},"CostConfig":{"description":"Cost tracking and budget enforcement configuration (`[cost]` section).","type":"object","properties":{"allow_override":{"description":"Allow requests to exceed budget with --override flag (default: false)","type":"boolean","default":false},"daily_limit_usd":{"description":"Daily spending limit in USD (default: unset, no limit; 0 refuses every priced turn)","type":["number","null"],"format":"double","default":null},"monthly_limit_usd":{"description":"Monthly spending limit in USD (default: unset, no limit)","type":["number","null"],"format":"double","default":null},"prices":{"description":"Per-model pricing (USD per 1M tokens)","type":"object","additionalProperties":{"$ref":"#/$defs/ModelPricing"},"default":{}},"warn_at_percent":{"description":"Warn when spending reaches this percentage of a configured limit (default: 80)","type":"integer","format":"uint8","default":80,"maximum":255,"minimum":0}}},"CredentialRefSetting":{"description":"Which credential a decision backend uses. A reference, never a secret.","type":"string"},"CronConfig":{"description":"Cron job configuration (`[cron]` section).","type":"object","properties":{"max_run_history":{"description":"Maximum number of historical cron run records to retain. Default: `50`.","type":"integer","format":"uint32","default":50,"minimum":0}}},"CustomTunnelConfig":{"type":"object","properties":{"health_url":{"description":"Optional URL to check tunnel health","type":["string","null"]},"start_command":{"description":"Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"","type":"string"},"url_pattern":{"description":"Optional regex to extract public URL from command stdout","type":["string","null"]}},"required":["start_command"]},"DecisionBackendConfig":{"description":"The decision backend (`[decision_engine.backend]`).","type":"object","properties":{"circuit_breaker":{"description":"The circuit breaker.","$ref":"#/$defs/CircuitBreakerConfig","default":{"cooldown_secs":60,"failure_threshold":5}},"credential_ref":{"description":"The credential reference: `\"\"`, `\"none\"` or `cred-`.","$ref":"#/$defs/CredentialRefSetting","default":""},"endpoint":{"description":"The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.","type":"string","default":""},"kind":{"description":"`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).","$ref":"#/$defs/BackendSelection","default":"auto"},"max_request_bytes":{"description":"Largest request body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":65536,"minimum":0},"max_response_bytes":{"description":"Largest response body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":262144,"minimum":0},"model":{"description":"The model the endpoint serves; one exact version for a hosted\nservice.","type":"string","default":""},"pinned_snapshot":{"description":"The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.","type":"string"},"remote_enabled":{"description":"Whether decision state may leave this machine. Default `false`.","type":"boolean","default":false},"timeout_ms":{"description":"Transport timeout (10 ms up to the extra latency budget).","type":"integer","format":"uint32","default":250,"minimum":0}}},"DecisionEngineConfig":{"type":"object","properties":{"backend":{"anyOf":[{"$ref":"#/$defs/DecisionBackendConfig"},{"type":"null"}]},"candidates":{"type":"integer","format":"uint32","default":5,"minimum":0},"enabled":{"type":"boolean","default":false},"mode":{"$ref":"#/$defs/DecisionMode","default":"pre"},"observe_queue":{"type":"integer","format":"uint32","default":64,"minimum":0},"prompt_budget_tokens":{"type":"integer","format":"uint32","default":300,"minimum":0},"telemetry_cap":{"type":"integer","format":"uint32","default":1000,"minimum":0},"timeout_ms":{"type":"integer","format":"uint32","default":1500,"minimum":0},"latency_budget_ms":{"description":"The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.","type":"integer","format":"uint64","default":500,"minimum":0},"token_ratio_limit":{"description":"Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).","type":"number","format":"float","default":0.3499999940395355},"max_candidates":{"description":"The most candidates a turn considers (1 to 32).","type":"integer","format":"uint8","default":12,"maximum":255,"minimum":0}}},"DecisionMode":{"type":"string","enum":["pre","post","both"]},"DeclarationOfConformityConfig":{"type":"object","properties":{"applicable_union_law":{"type":"array","default":[],"items":{"type":"string"}},"artifact_path":{"type":["string","null"],"default":null},"artifact_version":{"type":["string","null"],"default":null},"conformity_assessment_procedure":{"type":["string","null"],"default":null},"conformity_statement":{"type":["string","null"],"default":null},"harmonised_standards":{"type":"array","default":[],"items":{"type":"string"}},"issue_date":{"type":["string","null"],"default":null},"issue_place":{"type":["string","null"],"default":null},"notified_body_certificate":{"type":["string","null"],"default":null},"notified_body_identification_number":{"type":["string","null"],"default":null},"notified_body_name":{"type":["string","null"],"default":null},"personal_data_compliance_statement":{"type":["string","null"],"default":null},"processes_personal_data":{"type":"boolean","default":false},"provider_address":{"type":["string","null"],"default":null},"provider_name":{"type":["string","null"],"default":null},"signer_function":{"type":["string","null"],"default":null},"signer_name":{"type":["string","null"],"default":null},"signer_on_behalf_of":{"type":["string","null"],"default":null},"sole_responsibility_statement":{"type":["string","null"],"default":null},"standards_not_applicable_reason":{"type":["string","null"],"default":null},"system_name":{"type":["string","null"],"default":null},"system_reference":{"type":["string","null"],"default":null},"system_type":{"type":["string","null"],"default":null}}},"DelegateAgentConfig":{"description":"Configuration for a delegate sub-agent used by the `delegate` tool.","type":"object","properties":{"agentic":{"description":"Agentic sub-agent mode (multi-turn tool-call loop). Default true; an\nexplicit `false` makes the agent answer-only with no tools.","type":"boolean","default":true},"allowed_tools":{"description":"Allowlist of tool names available to the sub-agent in agentic mode.\nEmpty or omitted means all tools, the same as `[\"*\"]`.","type":"array","default":[],"items":{"type":"string"}},"api_key":{"description":"Optional API key override","type":["string","null"],"default":null},"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"autonomy":{"description":"The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.","anyOf":[{"$ref":"#/$defs/AutonomyLevel"},{"type":"null"}]},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"enabled":{"description":"Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.","type":"boolean","default":true},"identity_dir":{"description":"Optional identity files directory relative to workspace root.","type":["string","null"],"default":null},"limits":{"$ref":"#/$defs/AgentLimits","default":{"max_concurrent_turns":null,"max_cost_per_day_cents":null}},"max_depth":{"description":"Max recursion depth for nested delegation","type":"integer","format":"uint32","default":8,"minimum":0},"memory_scope":{"description":"Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".","type":["string","null"],"default":null},"model":{"description":"Model name","type":"string"},"provider":{"description":"Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")","type":"string"},"spawn_enabled":{"description":"Whether this agent is allowed to be targeted by sessions_spawn (default: true).","type":["boolean","null"],"default":null},"system_prompt":{"description":"Optional system prompt for the sub-agent","type":["string","null"],"default":null},"temperature":{"description":"Temperature override","type":["number","null"],"format":"double","default":null},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}},"required":["provider","model"]},"DingTalkConfig":{"description":"DingTalk configuration for Stream Mode messaging","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"client_id":{"description":"Client ID (AppKey) from DingTalk developer console","type":"string"},"client_secret":{"description":"Client Secret (AppSecret) from DingTalk developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["client_id","client_secret"]},"DiscordConfig":{"description":"Discord bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Discord user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Discord bot token (from Discord Developer Portal).","type":"string"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"guild_id":{"description":"Optional guild (server) ID to restrict the bot to a single guild.","type":["string","null"]},"listen_to_bots":{"description":"When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.","type":"boolean","default":false}},"required":["bot_token"]},"DmPolicy":{"description":"Policy for direct-message handling.","oneOf":[{"description":"Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).","type":"string","const":"pairing"},{"description":"Accept only senders listed in `allowed_from`.","type":"string","const":"allowlist"},{"description":"Accept any direct sender.","type":"string","const":"open"},{"description":"Ignore direct messages.","type":"string","const":"disabled"}]},"DockerRuntimeConfig":{"description":"Docker runtime configuration (`[runtime.docker]` section).","type":"object","properties":{"allowed_workspace_roots":{"description":"Optional workspace root allowlist for Docker mount validation.","type":"array","default":[],"items":{"type":"string"}},"cpu_limit":{"description":"Optional CPU limit (`None` = no explicit limit).","type":["number","null"],"format":"double","default":1.0},"image":{"description":"Runtime image used to execute shell commands.","type":"string","default":"alpine:3.20"},"memory_limit_mb":{"description":"Optional memory limit in MB (`None` = no explicit limit).","type":["integer","null"],"format":"uint64","default":512,"minimum":0},"mount_workspace":{"description":"Mount configured workspace into `/workspace`.","type":"boolean","default":true},"network":{"description":"Docker network mode (`none`, `bridge`, etc.).","type":"string","default":"none"},"read_only_rootfs":{"description":"Mount root filesystem as read-only.","type":"boolean","default":true}}},"EmailConfig":{"description":"Email channel configuration","type":"object","properties":{"allowed_senders":{"description":"Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)","type":"array","default":[],"items":{"type":"string"}},"from_address":{"description":"From address for outgoing emails","type":"string"},"idle_timeout_secs":{"description":"IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes","type":"integer","format":"uint64","default":1740,"minimum":0},"imap_folder":{"description":"IMAP folder to poll (default: INBOX)","type":"string","default":"INBOX"},"imap_host":{"description":"IMAP server hostname","type":"string"},"imap_port":{"description":"IMAP server port (default: 993 for TLS)","type":"integer","format":"uint16","default":993,"maximum":65535,"minimum":0},"password":{"description":"Email password for authentication","type":"string"},"smtp_host":{"description":"SMTP server hostname","type":"string"},"smtp_port":{"description":"SMTP server port (default: 465 for TLS)","type":"integer","format":"uint16","default":465,"maximum":65535,"minimum":0},"smtp_tls":{"description":"Use TLS for SMTP (default: true)","type":"boolean","default":true},"username":{"description":"Email username for authentication","type":"string"}},"required":["imap_host","smtp_host","username","password","from_address"]},"EmbeddingRouteConfig":{"description":"Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"dimensions":{"description":"Optional embedding dimension override for this route","type":["integer","null"],"format":"uint","default":null,"minimum":0},"hint":{"description":"Route hint name (e.g. \"semantic\", \"archive\", \"faq\")","type":"string"},"model":{"description":"Embedding model to use with that provider","type":"string"},"provider":{"description":"Embedding provider (`none`, `openai`, or `custom:`)","type":"string"}},"required":["hint","provider","model"]},"EuAiActClassificationConfig":{"type":"object","properties":{"assessed_at":{"type":["string","null"],"default":null},"owner":{"type":["string","null"],"default":null},"status":{"$ref":"#/$defs/EuAiActRiskClassification","default":"unclassified"}}},"EuAiActComplianceConfig":{"type":"object","properties":{"classification":{"$ref":"#/$defs/EuAiActClassificationConfig","default":{"assessed_at":null,"owner":null,"status":"unclassified"}},"declaration":{"$ref":"#/$defs/DeclarationOfConformityConfig","default":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null}},"incident_store_path":{"type":["string","null"],"default":null}}},"EuAiActRiskClassification":{"type":"string","enum":["unclassified","high_risk","not_high_risk"]},"FitnessConfig":{"description":"Calendar schedule, evidence thresholds, and retention for fitness v2.","type":"object","properties":{"auto_run":{"description":"Run the daily fitness worker in daemon mode.","type":"boolean","default":true},"max_backfill_days":{"description":"Maximum number of closed days recovered after downtime.","type":"integer","format":"uint32","default":7,"minimum":0},"min_coverage":{"description":"Minimum available metric weight required to publish a final score.","type":"number","format":"double","default":0.6},"min_samples":{"description":"Minimum samples required before an evidence-derived subscore is usable.","type":"integer","format":"uint","default":5,"minimum":0},"retention_days":{"description":"Number of daily JSON reports retained on disk.","type":"integer","format":"uint32","default":180,"minimum":0},"run_at":{"description":"Local wall-clock time (`HH:MM`) at which the previous day is scored.","type":"string","default":"00:10"},"timezone":{"description":"IANA timezone used to define closed calendar days.","type":"string","default":"UTC"}}},"GatewayConfig":{"description":"Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.","type":"object","properties":{"allow_public_bind":{"description":"Allow binding to non-localhost without a tunnel (default: false)","type":"boolean","default":false},"api_rate_limit_per_minute":{"description":"Max `/api/*` requests per minute per authenticated token.","type":"integer","format":"uint32","default":60,"minimum":0},"channel_webhook_dedup_ttl_secs":{"description":"How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.","type":"integer","format":"uint64","default":86400,"minimum":0},"host":{"description":"Gateway host (default: 127.0.0.1)","type":"string","default":"127.0.0.1"},"idempotency_max_keys":{"description":"Maximum distinct idempotency keys retained in memory.","type":"integer","format":"uint","default":10000,"minimum":0},"idempotency_ttl_secs":{"description":"TTL for webhook idempotency keys.","type":"integer","format":"uint64","default":300,"minimum":0},"pair_rate_limit_per_minute":{"description":"Max `/pair` requests per minute per client key.","type":"integer","format":"uint32","default":10,"minimum":0},"paired_tokens":{"description":"Paired bearer tokens (managed automatically, not user-edited)","type":"array","default":[],"items":{"type":"string"}},"port":{"description":"Gateway port (default: 16830)","type":"integer","format":"uint16","default":16830,"maximum":65535,"minimum":0},"rate_limit_max_keys":{"description":"Maximum distinct client keys tracked by gateway rate limiter maps.","type":"integer","format":"uint","default":10000,"minimum":0},"require_pairing":{"description":"Require pairing before accepting requests (default: true)","type":"boolean","default":true},"targeted_agents":{"description":"Switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). Default true. While false, any\notherwise-valid named target answers 409 `agent_disabled` and never\nruns as Main.","type":"boolean","default":true},"trust_forwarded_headers":{"description":"Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.","type":"boolean","default":false},"webhook_rate_limit_per_minute":{"description":"Max `/webhook` requests per minute per client key.","type":"integer","format":"uint32","default":60,"minimum":0}}},"GroupPolicy":{"description":"Policy for group-message handling.","oneOf":[{"description":"Accept only groups listed in `group_allow_from`.","type":"string","const":"allowlist"},{"description":"Accept any group.","type":"string","const":"open"},{"description":"Ignore group messages.","type":"string","const":"disabled"}]},"GroupReplyMode":{"description":"How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.","oneOf":[{"description":"Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).","type":"string","const":"off"},{"description":"Reply only when the bot is @-mentioned (legacy `mention_only = true`).","type":"string","const":"mention-only"},{"description":"Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).","type":"string","const":"smart"}]},"HeartbeatConfig":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]` section).","type":"object","properties":{"active_hours":{"description":"Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.","type":"array","default":[8,23],"items":{"type":"integer","format":"uint8","maximum":255,"minimum":0}},"interval_minutes":{"description":"Interval in minutes between heartbeat pings. Default: `30`.","type":"integer","format":"uint32","default":30,"minimum":0},"prompt":{"description":"Prompt used by heartbeat worker when dispatching tasks.","type":"string","default":"Check HEARTBEAT.md and follow instructions."}}},"HttpRequestConfig":{"description":"HTTP request tool configuration (`[http_request]` section).","type":"object","properties":{"max_response_size":{"description":"Maximum response size in bytes (default: 1MB)","type":"integer","format":"uint","default":1000000,"minimum":0},"timeout_secs":{"description":"Request timeout in seconds (default: 30)","type":"integer","format":"uint64","default":30,"minimum":0}}},"IMessageConfig":{"description":"iMessage channel configuration (macOS only).","type":"object","properties":{"allowed_contacts":{"description":"Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.","type":"array","items":{"type":"string"}},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["allowed_contacts"]},"IdentityBindingConfig":{"description":"Startup identity binding entry (`[[identity_bindings]]`).","type":"object","properties":{"channel":{"type":"string"},"channel_account":{"type":"string"},"display_name":{"type":["string","null"],"default":null},"user_id":{"type":"string"}},"required":["user_id","channel","channel_account"]},"IdentityConfig":{"description":"Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.","type":"object","properties":{"aieos_inline":{"description":"Inline AIEOS JSON (alternative to file path)","type":["string","null"],"default":null},"aieos_path":{"description":"Path to AIEOS JSON file (relative to workspace)","type":["string","null"],"default":null},"format":{"description":"Identity format: \"openclaw\" (default) or \"aieos\"","type":"string","default":"openclaw"}}},"InteractionNoticeApplicability":{"type":"string","enum":["required","not_applicable"]},"InteractionNoticeConfig":{"type":"object","properties":{"applicability":{"$ref":"#/$defs/InteractionNoticeApplicability","default":"required"},"exception_owner":{"type":["string","null"],"default":null},"exception_reviewed_at":{"type":["string","null"],"default":null},"text":{"type":"string","default":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers."},"version":{"type":"string","default":"1"}}},"IrcConfig":{"description":"IRC channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed nicknames (case-insensitive) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"channels":{"description":"Channels to join on connect","type":"array","default":[],"items":{"type":"string"}},"mention_only":{"description":"When true, only process channel/group messages that mention the bot.","type":"boolean","default":false},"nickname":{"description":"Bot nickname","type":"string"},"nickserv_password":{"description":"NickServ IDENTIFY password","type":["string","null"]},"port":{"description":"IRC server port (default: 6697 for TLS)","type":"integer","format":"uint16","default":6697,"maximum":65535,"minimum":0},"sasl_password":{"description":"SASL PLAIN password (IRCv3)","type":["string","null"]},"server":{"description":"IRC server hostname","type":"string"},"server_password":{"description":"Server password (for bouncers like ZNC)","type":["string","null"]},"username":{"description":"Username (defaults to nickname if not set)","type":["string","null"]},"verify_tls":{"description":"Verify TLS certificate (default: true)","type":["boolean","null"]}},"required":["server","nickname"]},"LarkConfig":{"description":"Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from Lark/Feishu developer console","type":"string"},"app_secret":{"description":"App Secret from Lark/Feishu developer console","type":"string"},"encrypt_key":{"description":"Encrypt key for webhook message decryption (optional)","type":["string","null"],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"port":{"description":"HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"receive_mode":{"description":"Event receive mode: \"websocket\" (default) or \"webhook\"","$ref":"#/$defs/LarkReceiveMode","default":"websocket"},"use_feishu":{"description":"Whether to use the Feishu (Chinese) endpoint instead of Lark (International)","type":"boolean","default":false},"verification_token":{"description":"Verification token for webhook validation (optional)","type":["string","null"],"default":null}},"required":["app_id","app_secret"]},"LarkReceiveMode":{"description":"How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.","type":"string","enum":["websocket","webhook"]},"LinqConfig":{"type":"object","properties":{"allowed_senders":{"description":"Allowed sender handles (phone numbers) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"api_token":{"description":"Linq Partner API token (Bearer auth)","type":"string"},"from_phone":{"description":"Phone number to send from (E.164 format)","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"signing_secret":{"description":"Webhook signing secret for signature verification","type":["string","null"],"default":null}},"required":["api_token","from_phone"]},"MattermostConfig":{"description":"Mattermost bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Mattermost user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Mattermost bot access token.","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.","type":["boolean","null"],"default":null},"thread_replies":{"description":"When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.","type":["boolean","null"],"default":null},"url":{"description":"Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).","type":"string"}},"required":["url","bot_token"]},"McpConfig":{"type":"object","properties":{"servers":{"description":"Named MCP server definitions","type":"object","additionalProperties":{"$ref":"#/$defs/McpServerConfig"},"default":{}},"workspace_servers":{"description":"Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.","$ref":"#/$defs/WorkspaceMcpServers"}}},"McpServerConfig":{"type":"object","properties":{"allow_tools":{"description":"Optional allow-list of exposed tools (empty = all)","type":"array","default":[],"items":{"type":"string"}},"args":{"description":"Command args for stdio mode","type":"array","default":[],"items":{"type":"string"}},"command":{"description":"Command for stdio mode","type":["string","null"],"default":null},"deny_tools":{"description":"Optional deny-list of exposed tools","type":"array","default":[],"items":{"type":"string"}},"env":{"description":"Environment variables for stdio mode","type":"object","additionalProperties":{"type":"string"},"default":{}},"request_timeout_ms":{"description":"Request timeout in milliseconds","type":"integer","format":"uint64","default":30000,"minimum":0},"startup_timeout_ms":{"description":"Startup timeout in milliseconds","type":"integer","format":"uint64","default":10000,"minimum":0},"tool_name_prefix":{"description":"Prefix used in tool naming and routing","type":"string","default":"mcp"},"transport":{"description":"Transport type: stdio or http","$ref":"#/$defs/McpTransport","default":"stdio"},"url":{"description":"URL for HTTP mode (streamable HTTP endpoint)","type":["string","null"],"default":null},"working_dir":{"description":"Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).","type":["string","null"]}}},"McpServerRuntimeConfig":{"type":"object","properties":{"allowed_origins":{"description":"Allowed browser origins for future streamable HTTP clients.","type":"array","default":["claude.ai","openai.com","localhost"],"items":{"type":"string"}},"bind":{"description":"Advertised bind address. The gateway may still be started with a CLI port override.","type":"string","default":"127.0.0.1:16831"},"exposed_tools":{"description":"Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.","type":"array","default":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"items":{"type":"string"}},"jwt_algorithms":{"description":"Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.","type":"array","default":["RS256"],"items":{"type":"string"}},"jwt_audience":{"description":"Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.","type":["string","null"],"default":null},"jwt_issuer":{"description":"Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.","type":["string","null"],"default":null},"jwt_jwks":{"description":"Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.","type":["string","null"],"default":null},"jwt_jwks_cache_ttl_secs":{"description":"Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.","type":"integer","format":"uint64","default":300,"minimum":0},"jwt_jwks_uri":{"description":"Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.","type":["string","null"],"default":null},"jwt_public_key_pem":{"description":"PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.","type":["string","null"],"default":null},"rate_limit_rps":{"description":"Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.","type":"integer","format":"uint32","default":10,"minimum":0},"require_auth":{"description":"Require an authenticated external identity for mutating calls.","type":"boolean","default":true}}},"McpTransport":{"type":"string","enum":["stdio","http"]},"MediaConfig":{"description":"Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.","type":"object","properties":{"audio_model":{"description":"Audio model name (Ollama model or OpenAI model). Default: \"whisper\".","type":"string","default":"whisper"},"audio_ollama_url":{"description":"Ollama base URL for audio transcription. Default: \"http://localhost:11434\".","type":"string","default":"http://localhost:11434"},"audio_provider":{"description":"Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".","type":"string","default":"none"},"max_audio_size_mb":{"description":"Maximum audio attachment size in MiB. Default: 20.","type":"integer","format":"uint","default":20,"minimum":0},"max_video_size_mb":{"description":"Maximum video attachment size in MiB. Default: 50.","type":"integer","format":"uint","default":50,"minimum":0},"video_max_frames":{"description":"Maximum video frames to extract per video. Default: 4.","type":"integer","format":"uint","default":4,"minimum":0},"video_provider":{"description":"Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".","type":"string","default":"none"}}},"MemoryConfig":{"description":"Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.","type":"object","properties":{"acl_enabled":{"description":"Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.","type":"boolean","default":false},"archive_after_days":{"description":"Archive daily/session files older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"auto_hydrate":{"description":"Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing","type":"boolean","default":true},"auto_save":{"description":"Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.","type":"boolean","default":true},"backend":{"description":"\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).","type":"string","default":"sqlite"},"conversation_retention_days":{"description":"For sqlite backend: prune conversation rows older than this many days","type":"integer","format":"uint32","default":3,"minimum":0},"daily_retention_days":{"description":"For sqlite backend: prune daily rows older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"embedding_cache_size":{"description":"Max embedding cache entries before LRU eviction","type":"integer","format":"uint","default":10000,"minimum":0},"embedding_dimensions":{"description":"Embedding vector dimensions","type":"integer","format":"uint","default":384,"minimum":0},"embedding_model":{"description":"Embedding model name (e.g. \"text-embedding-3-small\")","type":"string","default":"prx-local-hash-v1"},"embedding_provider":{"description":"Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"","type":"string","default":"local"},"events":{"description":"Raw/quasi-raw message event recording controls (`[memory.events]`).","$ref":"#/$defs/MemoryEventsConfig","default":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true}},"keyword_weight":{"description":"Weight for keyword BM25 in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.3},"legacy_conversation_turns_visible":{"description":"Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.","type":"boolean","default":true},"lucid_budget":{"description":"Token budget for lucid (replaces OPENPRX_LUCID_BUDGET)","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"lucid_cmd":{"description":"Path to lucid binary (replaces OPENPRX_LUCID_CMD)","type":["string","null"],"default":null},"lucid_failure_cooldown_ms":{"description":"Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)","type":"integer","format":"uint64","default":60000,"minimum":0},"lucid_local_hit_threshold":{"description":"Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)","type":"integer","format":"uint","default":3,"minimum":0},"lucid_recall_timeout_ms":{"description":"Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)","type":"integer","format":"uint64","default":5000,"minimum":0},"lucid_store_timeout_ms":{"description":"Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)","type":"integer","format":"uint64","default":3000,"minimum":0},"min_relevance_score":{"description":"Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4","type":"number","format":"double","default":0.4},"purge_after_days":{"description":"Purge archived files older than this many days","type":"integer","format":"uint32","default":30,"minimum":0},"semantic":{"description":"Semantic memory promotion controls (`[memory.semantic]`).","$ref":"#/$defs/MemorySemanticConfig","default":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30}},"sqlite_open_timeout_secs":{"description":"For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"sqlite_read_pool_size":{"description":"For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"vector_candidate_cap":{"description":"How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.","type":"integer","format":"uint","default":2000,"minimum":0},"vector_weight":{"description":"Weight for vector similarity in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.7}}},"MemoryEventsConfig":{"description":"Raw message event recording configuration (`[memory.events]`).","type":"object","properties":{"record_assistant_messages":{"description":"Record assistant replies.","type":"boolean","default":true},"record_tool_events":{"description":"Record tool/event payloads by default.","type":"boolean","default":false},"record_user_messages":{"description":"Record inbound/user messages.","type":"boolean","default":true}}},"MemorySemanticConfig":{"description":"Semantic memory promotion configuration (`[memory.semantic]`).","type":"object","properties":{"auto_promote_assistant_messages":{"description":"Auto-promote eligible assistant messages. Disabled by default to reduce noise.","type":"boolean","default":false},"auto_promote_user_messages":{"description":"Auto-promote eligible user messages into long-term semantic memories.","type":"boolean","default":true},"min_chars":{"description":"Minimum content length for semantic auto-promotion.","type":"integer","format":"uint","default":30,"minimum":0}}},"MemoryWebhookConfig":{"type":"object","properties":{"bind":{"description":"Socket address for the receiver (e.g. \"0.0.0.0:16899\").","type":"string","default":"0.0.0.0:16899"},"signing_secret":{"description":"Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.","type":["string","null"],"default":null},"token":{"description":"Required bearer token for incoming webhook events.","type":["string","null"],"default":null}}},"ModelOperationSetting":{"description":"The operations a `[[providers.models]]` entry may list.","type":"string","enum":["chat","embedding","decision_endpoint","rerank","image_generation","audio_generation","video_generation"]},"ModelPricing":{"description":"Per-model pricing entry (USD per 1M tokens).","type":"object","properties":{"cache_read":{"description":"Cache read input price per 1M tokens.","type":"number","format":"double","default":0.0},"cache_write":{"description":"Cache write/creation input price per 1M tokens.","type":"number","format":"double","default":0.0},"input":{"description":"Input price per 1M tokens","type":"number","format":"double","default":0.0},"output":{"description":"Output price per 1M tokens","type":"number","format":"double","default":0.0}}},"ModelRouteConfig":{"description":"Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"hint":{"description":"Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")","type":"string"},"level":{"type":["string","null"]},"model":{"description":"Model to use with that provider","type":"string"},"provider":{"description":"Provider to route to (must match a known provider name)","type":"string"},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true,"required":["hint","provider","model"]},"ModelSettings":{"description":"A model level plus explicit parameter overrides in `[model_settings.\"\"]`.","type":"object","properties":{"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"level":{"type":["string","null"]},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true},"MultimodalConfig":{"description":"Multimodal (image) handling configuration (`[multimodal]` section).","type":"object","properties":{"allow_remote_fetch":{"description":"Allow fetching remote image URLs (http/https). Disabled by default.","type":"boolean","default":false},"max_image_size_mb":{"description":"Maximum image payload size in MiB before base64 encoding.","type":"integer","format":"uint","default":5,"minimum":0},"max_images":{"description":"Maximum number of image attachments accepted per request.","type":"integer","format":"uint","default":4,"minimum":0}}},"NextcloudTalkConfig":{"description":"Nextcloud Talk bot configuration (webhook receive + OCS send API).","type":"object","properties":{"allowed_users":{"description":"Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Bot app token used for OCS API bearer auth.","type":"string"},"base_url":{"description":"Nextcloud base URL (e.g. \"https://cloud.example.com\").","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"webhook_secret":{"description":"Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).","type":["string","null"],"default":null}},"required":["base_url","app_token"]},"NgrokTunnelConfig":{"type":"object","properties":{"auth_token":{"description":"ngrok auth token","type":"string"},"domain":{"description":"Optional custom domain","type":["string","null"]}},"required":["auth_token"]},"NodeServerConfig":{"description":"Node daemon runtime config used by `prx-node`.","type":"object","properties":{"allowed_commands":{"description":"Command allowlist matched on first token.\n\nIn restricted mode this list is required unless explicitly set to `[\"*\"]`.","type":"array","default":["echo"],"items":{"type":"string"}},"bearer_token":{"description":"Required bearer token for /rpc.","type":"string","default":""},"blocked_commands":{"description":"Command denylist matched on first token. Always enforced.","type":"array","default":[],"items":{"type":"string"}},"exec_timeout_ms":{"description":"Default command timeout in milliseconds.","type":"integer","format":"uint64","default":15000,"minimum":0},"hmac_secret":{"description":"Optional HMAC signing secret.","type":["string","null"],"default":null},"listen_addr":{"description":"Listen address for node daemon.","type":"string","default":"127.0.0.1:8787"},"max_concurrent_tasks":{"description":"Maximum number of concurrent async command tasks.","type":"integer","format":"uint","default":8,"minimum":0},"max_output_bytes":{"description":"Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.","type":"integer","format":"uint","default":1048576,"minimum":0},"sandbox_root":{"description":"Sandbox root directory for read/write/cwd constraints.","type":"string","default":"."},"task_result_ttl_ms":{"description":"TTL for completed task results in milliseconds.","type":"integer","format":"uint64","default":3600000,"minimum":0},"tls_cert":{"description":"TLS certificate path (PEM).","type":["string","null"],"default":null},"tls_key":{"description":"TLS private key path (PEM).","type":["string","null"],"default":null},"tls_required":{"description":"Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.","type":"boolean","default":true}}},"NodesConfig":{"description":"Remote node proxy configuration for core-side RPC calls and node daemon defaults.","type":"object","properties":{"nodes":{"description":"Configured remote nodes.","type":"array","default":[],"items":{"$ref":"#/$defs/RemoteNodeConfig"}},"request_timeout_ms":{"description":"Default request timeout for node RPC calls.","type":"integer","format":"uint64","default":15000,"minimum":0},"retry_max":{"description":"Default max retries for node RPC calls.","type":"integer","format":"uint8","default":2,"maximum":255,"minimum":0},"server":{"description":"Embedded node server defaults used by `prx-node`.","$ref":"#/$defs/NodeServerConfig","default":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}}},"ObservabilityConfig":{"description":"Observability backend configuration (`[observability]` section).","type":"object","properties":{"backend":{"description":"\"none\" | \"log\" | \"prometheus\" | \"otel\"","type":"string","default":"none"},"otel_endpoint":{"description":"OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".","type":["string","null"],"default":null},"otel_service_name":{"description":"Service name reported to the OTel collector. Defaults to \"prx\".","type":["string","null"],"default":null}}},"OllamaProviderConfig":{"description":"Ollama-specific request options (`[providers.ollama]`).","type":"object","properties":{"num_ctx":{"description":"Explicit context window sent as Ollama `options.num_ctx`.","type":["integer","null"],"format":"uint","default":null,"minimum":0}}},"OsPagingConfig":{"description":"Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.","type":"object","properties":{"eviction_threshold":{"description":"Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.","type":"number","format":"double","default":0.7},"keep_recent_messages":{"description":"Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).","type":"integer","format":"uint","default":12,"minimum":0},"max_recalled_pages":{"description":"Maximum number of evicted pages (document chunks) recalled per turn.","type":"integer","format":"uint","default":10,"minimum":0},"proactive_retrieval":{"description":"Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.","type":"boolean","default":true},"retrieval_injection_role":{"description":"Role under which recalled pages are injected.","$ref":"#/$defs/RetrievalInjectionRole","default":"system"}}},"PluginsConfig":{"description":"WASM plugin runtime configuration.","type":"object","properties":{"enabled":{"description":"Load WASM plugins from `/plugins`. Default: `false`.","type":"boolean","default":false}},"additionalProperties":false},"ProviderModelConfig":{"description":"One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.","type":"object","properties":{"context_window":{"description":"The model's context window in tokens.","type":["integer","null"],"format":"uint32","minimum":0},"model":{"description":"The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.","type":["string","null"]},"native_tools":{"description":"Whether the model accepts native tool calls.","type":["boolean","null"]},"operations":{"description":"The complete list of operations the model executes; every operation not\nlisted is unsupported.","type":["array","null"],"items":{"$ref":"#/$defs/ModelOperationSetting"}},"provider":{"description":"The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.","type":"string"},"streaming":{"description":"Whether the model streams responses.","type":["boolean","null"]},"structured_output":{"description":"Whether the model honours a JSON-schema response format.","type":["boolean","null"]},"tool_call_dialect":{"description":"The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema_dialect":{"description":"The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]},"vision_input":{"description":"Whether the model accepts image input.","type":["boolean","null"]}},"required":["provider"]},"ProviderToolDialectConfig":{"description":"One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.","type":"object","properties":{"model":{"description":"The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.","type":["string","null"]},"provider":{"description":"The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.","type":"string"},"tool_call":{"description":"The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema":{"description":"The tool-schema dialect the endpoint accepts.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]}},"required":["provider"]},"ProvidersConfig":{"description":"Provider-specific runtime configuration (`[providers]`).","type":"object","properties":{"models":{"description":"Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.","type":"array","items":{"$ref":"#/$defs/ProviderModelConfig"}},"ollama":{"description":"Ollama-specific request options (`[providers.ollama]`).","$ref":"#/$defs/OllamaProviderConfig","default":{"num_ctx":null}},"tool_dialects":{"description":"Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).","type":"array","items":{"$ref":"#/$defs/ProviderToolDialectConfig"}}}},"ProxyConfig":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).","type":"object","properties":{"all_proxy":{"description":"Fallback proxy URL for all schemes.","type":["string","null"],"default":null},"http_proxy":{"description":"Proxy URL for HTTP requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"https_proxy":{"description":"Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"no_proxy":{"description":"No-proxy bypass list. Same format as NO_PROXY.","type":"array","default":[],"items":{"type":"string"}},"scope":{"description":"Proxy application scope.","$ref":"#/$defs/ProxyScope","default":"prx"},"services":{"description":"Service selectors used when scope = \"services\".","type":"array","default":[],"items":{"type":"string"}}}},"ProxyScope":{"description":"Proxy application scope — determines which outbound traffic uses the proxy.","oneOf":[{"description":"Use system environment proxy variables only.","type":"string","const":"environment"},{"description":"Apply proxy to all OpenPRX-managed HTTP traffic (default).","type":"string","const":"prx"},{"description":"Apply proxy only to explicitly listed service selectors.","type":"string","const":"services"}]},"QQConfig":{"description":"QQ Official Bot configuration (Tencent QQ Bot SDK)","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs. Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from QQ Bot developer console","type":"string"},"app_secret":{"description":"App Secret from QQ Bot developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["app_id","app_secret"]},"QueryClassificationConfig":{"description":"Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.","type":"object","properties":{"rules":{"description":"Classification rules evaluated in priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/ClassificationRule"}}}},"RamfluxAccountConfig":{"description":"Persona for one ramflux AI account. Missing fields fall back to the global agent.","type":"object","properties":{"cross_conversation_retrieval":{"description":"Cross-conversation memory retrieval. Off unless the owner sets it.","type":"boolean","default":false},"model":{"type":["string","null"],"default":null},"provider":{"type":["string","null"],"default":null},"scope_profile":{"type":["string","null"],"default":null},"system_prompt_file":{"description":"Path to a system-prompt file. Relative paths are resolved from the workspace.","type":["string","null"],"default":null}},"additionalProperties":false},"RamfluxAttachmentFetch":{"description":"Per-turn caps for `attachment.fetch`.","type":"object","properties":{"max_bytes":{"type":"integer","format":"uint64","default":5242880,"minimum":0},"max_per_turn":{"type":"integer","format":"uint8","default":4,"maximum":255,"minimum":0}},"additionalProperties":false},"RamfluxAuthorizationMode":{"description":"How prx combines its own setting with `bridge.hello.authorization`.","oneOf":[{"description":"Use the agent-host value. Until hello arrives, the effective mode is supervised.","type":"string","const":"follow_rf"},{"description":"Always supervised, even when the agent-host declares full.","type":"string","const":"supervised"},{"description":"Full only when the agent-host also declares full. Config alone never yields full.","type":"string","const":"full"}]},"RamfluxConfig":{"description":"Local ramflux agent-host bridge (`[channels_config.ramflux]`).","type":"object","properties":{"accounts":{"type":"object","additionalProperties":{"$ref":"#/$defs/RamfluxAccountConfig"},"default":{}},"allowed_block_types":{"type":"array","default":["Text","Markdown","Heading","KeyValue","Metric","List","TableFallback","Form","Input","Select","Progress","LogStream","Warning","Error","Success","Approval","ActionGroup","FilePreview","Fallback"],"items":{"type":"string"}},"attachment_fetch":{"$ref":"#/$defs/RamfluxAttachmentFetch","default":{"max_bytes":5242880,"max_per_turn":4}},"authorization_mode":{"$ref":"#/$defs/RamfluxAuthorizationMode","default":"follow_rf"},"encrypt_at_rest":{"type":"boolean","default":true},"max_in_flight_per_conversation":{"type":"integer","format":"uint8","default":1,"maximum":255,"minimum":0},"on_new_message":{"$ref":"#/$defs/RamfluxOnNewMessage","default":"queue"},"socket_path":{"description":"Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.","type":["string","null"],"default":null},"surface_limits":{"$ref":"#/$defs/RamfluxSurfaceLimits","default":{"max_actions":16,"max_blocks":32,"max_bytes":65536}},"turn_wall_clock_secs":{"description":"Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.","type":"integer","format":"uint64","default":120,"minimum":0}},"additionalProperties":false},"RamfluxOnNewMessage":{"description":"What to do with a new inbound message while a turn for that conversation is running.","type":"string","enum":["queue","interrupt"]},"RamfluxSurfaceLimits":{"description":"Limits for `reply.surface` blocks and actions.","type":"object","properties":{"max_actions":{"type":"integer","format":"uint32","default":16,"minimum":0},"max_blocks":{"type":"integer","format":"uint32","default":32,"minimum":0},"max_bytes":{"type":"integer","format":"uint32","default":65536,"minimum":0}},"additionalProperties":false},"ReliabilityCircuitBreakerConfig":{"description":"Process-local provider circuit policy (`[reliability.circuit_breaker]`).","type":"object","properties":{"enabled":{"description":"Enable protection for factory-built provider chains.","type":"boolean","default":true},"failure_threshold":{"description":"Consecutive transient failures that open a circuit (at least 1).","type":"integer","format":"uint32","default":5,"minimum":0},"max_open_secs":{"description":"Maximum doubled window, between open_secs and 3600 seconds.","type":"integer","format":"uint64","default":300,"minimum":0},"open_secs":{"description":"Initial open window in seconds (at least 1).","type":"integer","format":"uint64","default":30,"minimum":0}}},"ReliabilityConfig":{"description":"Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.","type":"object","properties":{"acknowledge_single_provider_risk":{"description":"Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.","type":"boolean","default":false},"api_keys":{"description":"Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.","type":"array","default":[],"items":{"type":"string"}},"channel_initial_backoff_secs":{"description":"Initial backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":2,"minimum":0},"channel_max_backoff_secs":{"description":"Max backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":60,"minimum":0},"circuit_breaker":{"description":"Per-provider consecutive failure protection.","$ref":"#/$defs/ReliabilityCircuitBreakerConfig","default":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30}},"fallback_providers":{"description":"Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).","type":"array","default":[],"items":{"type":"string"}},"model_fallbacks":{"description":"Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`","type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"default":{}},"provider_backoff_ms":{"description":"Base backoff (ms) for provider retry delay.","type":"integer","format":"uint64","default":500,"minimum":0},"provider_retries":{"description":"Retries per provider before failing over.","type":"integer","format":"uint32","default":2,"minimum":0},"scheduler_poll_secs":{"description":"Scheduler polling cadence in seconds.","type":"integer","format":"uint64","default":15,"minimum":0},"scheduler_retries":{"description":"Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.","type":"integer","format":"uint32","default":2,"minimum":0}}},"RemoteNodeConfig":{"description":"A remote node target for core-side node proxy calls.","type":"object","properties":{"bearer_token":{"description":"Bearer token for node RPC authentication.","type":"string"},"endpoint":{"description":"Base endpoint (e.g. \"http://127.0.0.1:8787\").","type":"string"},"hmac_secret":{"description":"Optional request signing key (HMAC-SHA256).","type":["string","null"],"default":null},"id":{"description":"Stable node ID used by the nodes tool.","type":"string"},"retry_max":{"description":"Optional per-node retry override.","type":["integer","null"],"format":"uint8","default":null,"maximum":255,"minimum":0},"timeout_ms":{"description":"Optional per-node timeout override.","type":["integer","null"],"format":"uint64","default":null,"minimum":0}},"required":["id","endpoint","bearer_token"]},"RetrievalInjectionRole":{"description":"Where recalled context pages are injected back into the request.","oneOf":[{"description":"Inject recalled pages as a leading `system` message (not user-visible).","type":"string","const":"system"},{"description":"Inject recalled pages as a leading `user` message.","type":"string","const":"user"}]},"RouterConfig":{"description":"Heuristic LLM router configuration (`[router]` section).","type":"object","properties":{"alpha":{"description":"Similarity score weight. Phase 1 keeps this at `0.0`.","type":"number","format":"float","default":0.0},"beta":{"description":"Capability score weight.","type":"number","format":"float","default":0.5},"delta":{"description":"Cost penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"epsilon":{"description":"Latency penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"gamma":{"description":"Elo score weight.","type":"number","format":"float","default":0.30000001192092896},"knn_k":{"description":"Number of nearest neighbors considered for voting. Default: `7`.","type":"integer","format":"uint","default":7,"minimum":0},"knn_min_records":{"description":"Minimum history records before KNN affects routing. Default: `10`.","type":"integer","format":"uint","default":10,"minimum":0},"models":{"description":"Candidate model registry.","type":"array","default":[],"items":{"$ref":"#/$defs/RouterModelConfig"}}}},"RouterModelConfig":{"description":"Static router metadata for one model candidate.","type":"object","properties":{"categories":{"description":"Capability categories such as `conversation`, `code`, or `analysis`.","type":"array","default":[],"items":{"type":"string"}},"cost_per_million_tokens":{"description":"USD cost per million tokens.","type":"number","format":"float","default":0.0},"elo_rating":{"description":"Initial Elo rating.","type":"number","format":"float","default":1000.0},"latency_ms":{"description":"Average latency in milliseconds.","type":"integer","format":"uint32","default":2000,"minimum":0},"max_context":{"description":"Maximum context window in tokens.","type":"integer","format":"uint","default":1000000,"minimum":0},"model_id":{"description":"Model identifier without provider prefix.","type":"string"},"provider":{"description":"Provider identifier.","type":"string"},"reserved_output_tokens":{"description":"Output tokens reserved for this model when planning input context.","type":["integer","null"],"format":"uint","minimum":0}},"required":["model_id","provider"]},"RuntimeConfig":{"description":"Runtime adapter configuration (`[runtime]` section).","type":"object","properties":{"codex_reasoning_effort":{"description":"Codex reasoning effort","type":["string","null"],"default":null},"codex_stream_idle_timeout_secs":{"description":"Codex stream idle timeout in seconds","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"docker":{"description":"Docker runtime settings (used when `kind = \"docker\"`).","$ref":"#/$defs/DockerRuntimeConfig","default":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true}},"idle_hang_secs":{"description":"Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"kind":{"description":"Runtime kind (`native` | `docker`).","type":"string","default":"native"},"long_task_warn_secs":{"description":"Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"managed_cgroup_root":{"description":"Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.","type":["string","null"],"default":null},"max_blocking_threads":{"description":"Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"reasoning_enabled":{"description":"Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported","type":["boolean","null"],"default":null},"shell_env_allowlist":{"description":"Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.","type":"array","default":[],"items":{"type":"string"}},"workdir":{"description":"Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.","type":["string","null"],"default":null}}},"SchedulerConfig":{"description":"Scheduler configuration for periodic task execution (`[scheduler]` section).","type":"object","properties":{"claim_lease_secs":{"description":"Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.","type":"integer","format":"uint64","default":90,"minimum":0},"max_tasks":{"description":"Maximum number of persisted scheduled tasks.","type":"integer","format":"uint","default":64,"minimum":0}}},"ScopeConfig":{"description":"Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```","type":"object","properties":{"assign_owners":{"description":"Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.","type":"array","default":[],"items":{"type":"string"}},"default":{"description":"Default action when no rule matches: \"allow\" (default) or \"deny\".","$ref":"#/$defs/ScopeDefault","default":"allow"},"rules":{"description":"Ordered list of scope rules evaluated top-to-bottom.","type":"array","default":[],"items":{"$ref":"#/$defs/ScopeRule"}}}},"ScopeDefault":{"description":"What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.","oneOf":[{"description":"Unmatched tool calls are allowed (the default).","type":"string","const":"allow"},{"description":"Unmatched tool calls are refused.","type":"string","const":"deny"}]},"ScopeRule":{"description":"A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.","type":"object","properties":{"assign_allow":{"description":"Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".","type":"array","default":[],"items":{"type":"string"}},"assign_deny":{"description":"Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.","type":"array","default":[],"items":{"type":"string"}},"channel":{"description":"Match by channel name: \"signal\", \"telegram\", \"discord\", etc.","type":["string","null"]},"chat_type":{"description":"Match by chat type: \"direct\", \"group\", or \"*\" for any type.","type":["string","null"]},"send_allow":{"description":"Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.","type":"array","default":[],"items":{"type":"string"}},"send_deny":{"description":"Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.","type":"array","default":[],"items":{"type":"string"}},"tools_allow":{"description":"Tool whitelist: only these tools are allowed (empty = all tools permitted).","type":"array","default":[],"items":{"type":"string"}},"tools_deny":{"description":"Tool blacklist: these tools are denied regardless of allow list.","type":"array","default":[],"items":{"type":"string"}},"user":{"description":"Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.","type":["string","null"]}}},"SecretsConfig":{"description":"Secrets encryption configuration (`[secrets]` section).","type":"object","properties":{"encrypt":{"description":"Enable encryption for API keys and tokens in config.toml","type":"boolean","default":true}}},"SecurityConfig":{"description":"Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.","type":"object","properties":{"audit":{"description":"Audit logging configuration","$ref":"#/$defs/AuditConfig","default":{"log_path":"audit.log","max_size_mb":100}},"workspace_hooks":{"description":"Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.","$ref":"#/$defs/WorkspaceHooks"}}},"SelfSystemConfig":{"description":"Self-system experimental automation config (`[self_system]`).","type":"object","properties":{"evolution_config_path":{"description":"Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG)","type":["string","null"],"default":null},"evolution_debug_raw":{"description":"Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW)","type":"boolean","default":false},"evolution_interval_hours":{"description":"Evolution scheduler interval in hours (daemon mode).","type":"integer","format":"uint32","default":24,"minimum":0},"evolution_judge_timeout_secs":{"description":"Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.","type":"integer","format":"uint64","default":180,"minimum":0},"evolution_model_max_micro_usd":{"description":"Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.","type":"integer","format":"uint64","default":0,"minimum":0},"evolution_model_max_tokens":{"description":"Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.","type":"integer","format":"uint64","default":16384,"minimum":0},"fitness":{"description":"Daily fitness snapshot policy.","$ref":"#/$defs/FitnessConfig","default":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"}},"fitness_interval_hours":{"description":"Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.","type":"integer","format":"uint64","default":24,"minimum":0}}},"SessionsSpawnConfig":{"description":"Sessions spawn configuration (`[sessions_spawn]` section).","type":"object","properties":{"cleanup_on_complete":{"description":"Remove worker workspace directory after process-mode completion.","type":"boolean","default":true},"default_mode":{"description":"Default execution mode for sessions_spawn (`task` or `process`).","type":"string","default":"task"},"process_memory_strategy":{"description":"Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.","type":"string","default":"shared_fabric"},"worker_workspace_root":{"description":"Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.","type":["string","null"],"default":null}}},"SignalConfig":{"type":"object","properties":{"account":{"description":"E.164 phone number of the signal-cli account (e.g. \"+1234567890\").","type":"string"},"allowed_from":{"description":"Allowed sender phone numbers (E.164) or \"*\" for all.","type":"array","default":[],"items":{"type":"string"}},"cli_path":{"description":"Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).","type":["string","null"],"default":null},"daemon_http_port":{"description":"Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"daemon_mode":{"description":"Deprecated: ignored. Accepted for backward compatibility with older config files.","type":["boolean","null"],"default":null},"data_dir":{"description":"signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_id":{"description":"Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group","type":["string","null"],"default":null},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"http_url":{"description":"Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.","type":"string","default":"http://localhost:8080"},"ignore_attachments":{"description":"Skip messages that are attachment-only (no text body).","type":"boolean","default":false},"ignore_stories":{"description":"Skip incoming story messages.","type":"boolean","default":false},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"mode":{"description":"Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.","type":["string","null"],"default":null},"startup_timeout_ms":{"description":"Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.","type":"integer","format":"uint64","default":30000,"minimum":0},"storm_protection":{"description":"Signal ingress storm protection controls.","$ref":"#/$defs/SignalStormProtectionConfig","default":{"abnormal_threshold":10,"abnormal_window_secs":60,"breaker_duration_secs":300,"dedupe_ttl_secs":60,"min_reply_interval_secs":2}}},"required":["account"]},"SignalStormProtectionConfig":{"type":"object","properties":{"abnormal_threshold":{"description":"Non-user event threshold within `abnormal_window_secs` before tripping the breaker.","type":"integer","format":"uint","default":10,"minimum":0},"abnormal_window_secs":{"description":"Sliding window in seconds for non-user event counting.","type":"integer","format":"uint64","default":60,"minimum":0},"breaker_duration_secs":{"description":"Circuit breaker duration in seconds after threshold is reached.","type":"integer","format":"uint64","default":300,"minimum":0},"dedupe_ttl_secs":{"description":"Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.","type":"integer","format":"uint64","default":60,"minimum":0},"min_reply_interval_secs":{"description":"Minimum interval in seconds between replies for the same `(channel + reply_target)`.","type":"integer","format":"uint64","default":2,"minimum":0}}},"SkillRagConfig":{"description":"Dynamic skill retrieval configuration (`[skill_rag]` section).","type":"object","properties":{"top_k":{"description":"How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).","type":"integer","format":"uint","default":32,"minimum":0}}},"SkillSuiteRegistration":{"description":"The frozen suite that governs one skill's proposals.","type":"object","properties":{"skill_id":{"description":"The skill the suite governs.","type":"string"},"suite_digest":{"description":"SHA-256 digest (64 lowercase hex digits) of the frozen suite.","type":"string"}},"additionalProperties":false,"required":["skill_id","suite_digest"]},"SkillsConfig":{"description":"Skills loading configuration (`[skills]` section).","type":"object","properties":{"open_skills_dir":{"description":"Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.","type":["string","null"],"default":null},"openclaw_skills_dir":{"description":"Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.","type":["string","null"],"default":null}}},"SkillsLifecycleConfig":{"description":"`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.","type":"object","properties":{"allow_executable_proposals":{"description":"Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.","type":"boolean","default":false},"enabled":{"description":"Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.","type":"boolean","default":false},"max_concurrent_evaluations":{"description":"Most evaluations running at once.","type":"integer","format":"uint32","default":1,"minimum":0},"max_edit_fraction":{"description":"Edit budget of a proposal as a fraction of the skill body, in (0, 1].","type":"number","format":"double","default":0.2},"max_edit_tokens":{"description":"Edit budget of a proposal, in tokens.","type":"integer","format":"uint64","default":300,"minimum":0},"max_proposals_per_cycle":{"description":"Most proposals one cycle may start.","type":"integer","format":"uint32","default":1,"minimum":0},"min_cases_floor":{"description":"Smallest `min_cases` a governing suite may declare. Below 3 is refused.","type":"integer","format":"uint32","default":3,"minimum":0},"mode":{"description":"`draft_only`, `shadow` or `auto`.","$ref":"#/$defs/SkillsLifecycleModeConfig","default":"draft_only"},"owner_scope":{"description":"The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.","type":["string","null"],"default":null},"require_holdout":{"description":"A governing suite must have a holdout split. `false` is refused.","type":"boolean","default":true},"storage_dir":{"description":"Store location under the workspace. Only the default is supported.","type":"string","default":"self/skill-lifecycle"},"suites":{"description":"The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.","type":"array","default":[],"items":{"$ref":"#/$defs/SkillSuiteRegistration"}}},"additionalProperties":false},"SkillsLifecycleModeConfig":{"description":"What the lifecycle may do. Mirrors `LifecycleMode`.","oneOf":[{"description":"Drafts and reviews only.","type":"string","const":"draft_only"},{"description":"Drafts plus evaluation and gating; never publishes.","type":"string","const":"shadow"},{"description":"Publishes an eligible proposal after every gate.","type":"string","const":"auto"}]},"SlackConfig":{"description":"Slack bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Slack user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Slack app-level token for Socket Mode (xapp-...).","type":["string","null"]},"bot_token":{"description":"Slack bot OAuth token (xoxb-...).","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["bot_token"]},"SmartGroupConfig":{"description":"Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).","type":"object","properties":{"classifier_max_context_messages":{"description":"How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.","type":"integer","format":"uint","default":3,"minimum":0},"classifier_model":{"description":"Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.","type":"string","default":""},"classifier_provider":{"description":"Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.","type":"string","default":""},"classifier_temperature":{"description":"Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).","type":"number","format":"double","default":0.0},"classifier_timeout_secs":{"description":"Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.","type":"integer","format":"uint64","default":5,"minimum":0}}},"StorageConfig":{"description":"Persistent storage configuration (`[storage]` section).","type":"object","properties":{"provider":{"description":"Storage provider settings (e.g. sqlite, postgres).","$ref":"#/$defs/StorageProviderSection","default":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}}},"StorageProviderConfig":{"description":"Storage provider backend configuration (e.g. postgres connection details).","type":"object","properties":{"connect_timeout_secs":{"description":"Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"db_url":{"description":"Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.","type":["string","null"],"default":null},"pool_max_size":{"description":"Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.","type":"integer","format":"uint","default":32,"minimum":0},"provider":{"description":"Storage engine key (e.g. \"postgres\", \"sqlite\").","type":"string","default":""},"schema":{"description":"Database schema for SQL backends.","type":"string","default":"public"},"table":{"description":"Table name for memory entries.","type":"string","default":"memories"}}},"StorageProviderSection":{"description":"Wrapper for the storage provider configuration section.","type":"object","properties":{"config":{"description":"Storage provider backend settings.","$ref":"#/$defs/StorageProviderConfig","default":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"StreamMode":{"description":"Streaming mode for channels that support progressive message updates.","oneOf":[{"description":"No streaming -- send the complete response as a single message (default).","type":"string","const":"off"},{"description":"Update a draft message with every flush interval.","type":"string","const":"partial"}]},"TailscaleTunnelConfig":{"type":"object","properties":{"funnel":{"description":"Use Tailscale Funnel (public internet) vs Serve (tailnet only)","type":"boolean","default":false},"hostname":{"description":"Optional hostname override","type":["string","null"]}}},"TaskRoutingConfig":{"description":"Lightweight pre-LLM task routing.","type":"object","properties":{"default_intent":{"description":"Fallback intent when no rule matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"rules":{"description":"Rules evaluated in descending priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/TaskRoutingRule"}}}},"TaskRoutingIntentConfig":{"description":"Task-routing default and rule intent.","type":"string","enum":["simple","delegate","stream"]},"TaskRoutingRule":{"description":"A single task-routing rule.","type":"object","properties":{"intent":{"description":"Route intent to apply when a keyword matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"model_hint":{"description":"Optional model hint/raw model for non-delegated requests.","type":["string","null"],"default":null},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0},"sub_agent_model":{"description":"Optional raw sub-agent model override for delegated tasks.","type":["string","null"],"default":null}}},"TelegramConfig":{"description":"Telegram bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Telegram user IDs or usernames. Empty = deny all.","type":"array","items":{"type":"string"}},"bot_token":{"description":"Telegram Bot API token (from @BotFather).","type":"string"},"draft_update_interval_ms":{"description":"Minimum interval (ms) between draft message edits to avoid rate limits.","type":"integer","format":"uint64","default":1000,"minimum":0},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"interrupt_on_new_message":{"description":"When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.","type":"boolean","default":false},"stream_mode":{"description":"Streaming mode for progressive response delivery via message edits.","$ref":"#/$defs/StreamMode","default":"off"}},"required":["bot_token","allowed_users"]},"ToolCallDialectSetting":{"description":"The tool-call grammars an operator may declare for an endpoint.","oneOf":[{"description":"Only the native `tool_calls` array is a tool call (the default).","type":"string","const":"native"},{"description":"Additionally read `{json}` from the content,\nfor a tool name the request registered.","type":"string","const":"xml_function_tags"}]},"ToolSchemaDialectSetting":{"description":"The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.","oneOf":[{"description":"The published document, byte for byte (the default).","type":"string","const":"raw"},{"description":"The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.","type":"string","const":"no_root_combinators"}]},"ToolTieringConfig":{"description":"Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.","type":"object","properties":{"always_exclude":{"description":"Tool names excluded from capability publication.","type":"array","default":[],"items":{"type":"string"}},"always_include":{"description":"Tool names preferred for direct publication, subject to admission gates.","type":"array","default":[],"items":{"type":"string"}},"channel_exclude":{"description":"Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefault: empty (nothing is hidden); list tool names to hide them on channels.","type":"array","default":[],"items":{"type":"string"}}}},"TunnelConfig":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.","type":"object","properties":{"cloudflare":{"description":"Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).","anyOf":[{"$ref":"#/$defs/CloudflareTunnelConfig"},{"type":"null"}],"default":null},"custom":{"description":"Custom tunnel command configuration (used when `provider = \"custom\"`).","anyOf":[{"$ref":"#/$defs/CustomTunnelConfig"},{"type":"null"}],"default":null},"ngrok":{"description":"ngrok tunnel configuration (used when `provider = \"ngrok\"`).","anyOf":[{"$ref":"#/$defs/NgrokTunnelConfig"},{"type":"null"}],"default":null},"provider":{"description":"Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.","type":"string","default":"none"},"tailscale":{"description":"Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).","anyOf":[{"$ref":"#/$defs/TailscaleTunnelConfig"},{"type":"null"}],"default":null}}},"UserPolicyConfig":{"description":"Startup user policy entry (`[[user_policies]]`).","type":"object","properties":{"blocked_patterns":{"type":"array","default":[],"items":{"type":"string"}},"projects":{"type":"array","default":[],"items":{"type":"string"}},"role":{"type":"string","default":"guest"},"user_id":{"type":"string"},"visibility_ceiling":{"type":"string","default":"private"}},"required":["user_id"]},"WacliConfig":{"description":"wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```","type":"object","properties":{"allow_unsigned_loopback":{"description":"Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).","type":"boolean","default":false},"allowed_from":{"description":"Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.","type":"array","default":["*"],"items":{"type":"string"}},"bot_jid":{"description":"Bot's own JID, used for reply-to-bot mention detection.","type":["string","null"],"default":null},"bot_lid":{"description":"The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.","type":["string","null"],"default":null},"bot_number":{"description":"Bot's own phone number (digits), used for `@` mention detection.","type":["string","null"],"default":null},"cli_path":{"description":"Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.","type":["string","null"],"default":null},"group_reply_mode":{"description":"Smart group-reply mode. When `None`, derived from `mention_only`.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"host":{"description":"REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].","type":["string","null"],"writeOnly":true},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"outbound_media_workspace_only":{"description":"Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.","type":"boolean","default":false},"port":{"description":"REMOVED: legacy JSON-RPC daemon port. See `host`.","type":["integer","null"],"format":"uint16","maximum":65535,"minimum":0,"writeOnly":true},"self_chat_mode":{"description":"Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.","type":"boolean","default":false},"store_dir":{"description":"wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.","type":["string","null"],"default":null},"webhook_listen":{"description":"Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").","type":"string","default":"127.0.0.1:16868"},"webhook_path":{"description":"HTTP path the webhook server serves (default: \"/wacli\").","type":"string","default":"/wacli"},"webhook_secret":{"description":"HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.","type":["string","null"],"default":null}}},"WebSearchConfig":{"description":"Web search tool configuration (`[web_search]` section).","type":"object","properties":{"brave_api_key":{"description":"Brave Search API key (required if provider is \"brave\")","type":["string","null"],"default":null},"fetch_max_chars":{"description":"Maximum characters returned by `web_fetch` (default 10000)","type":"integer","format":"uint","default":50000,"minimum":0},"max_results":{"description":"Maximum results per search (1-20)","type":"integer","format":"uint","default":15,"minimum":0},"provider":{"description":"Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)","type":"string","default":"duckduckgo"},"timeout_secs":{"description":"Request timeout in seconds","type":"integer","format":"uint64","default":15,"minimum":0}}},"WebhookConfig":{"description":"Webhook channel configuration.","type":"object","properties":{"port":{"description":"Port to listen on for incoming webhooks.","type":"integer","format":"uint16","maximum":65535,"minimum":0},"secret":{"description":"Optional shared secret for webhook signature verification.","type":["string","null"]}},"required":["port"]},"WhatsAppConfig":{"description":"WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.","type":"object","properties":{"access_token":{"description":"Access token from Meta Business Suite (Cloud API mode)","type":["string","null"],"default":null},"allowed_numbers":{"description":"Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"app_secret":{"description":"App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"pair_code":{"description":"Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one","type":["string","null"],"default":null},"pair_phone":{"description":"Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used","type":["string","null"],"default":null},"phone_number_id":{"description":"Phone number ID from Meta Business API (Cloud API mode)","type":["string","null"],"default":null},"read_pool_size":{"description":"Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"session_path":{"description":"Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs","type":["string","null"],"default":null},"verify_token":{"description":"Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode","type":["string","null"],"default":null},"ws_url":{"description":"WebSocket URL override (replaces WHATSAPP_WS_URL)","type":["string","null"],"default":null}}},"WorkspaceHooks":{"description":"Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).","oneOf":[{"description":"They do not run (the default); `prx doctor` and `hooks_status` say so.","type":"string","const":"off"},{"description":"They run, in a cleared environment and a dedicated directory beside\n`config.toml`.","type":"string","const":"on"}]},"WorkspaceMcpServers":{"description":"Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).","oneOf":[{"description":"None: a workspace file may only narrow the servers defined in\n`config.toml`.","type":"string","const":"off"},{"description":"HTTP servers (still refused when they target a private address).","type":"string","const":"http_only"},{"description":"HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.","type":"string","const":"stdio"}]},"XinConfig":{"description":"Configuration for the xin autonomous task engine (`[xin]`).","type":"object","properties":{"adopt_legacy_tasks":{"description":"Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).","type":"boolean","default":false},"interval_minutes":{"description":"Tick interval in minutes (minimum 1). Default: 5.","type":"integer","format":"uint32","default":5,"minimum":0},"stale_timeout_minutes":{"description":"Minutes after which a running task is marked stale. Default: 60.","type":"integer","format":"uint32","default":60,"minimum":0}}},"AgentMessaging":{"description":"Owner-controlled inbound session messaging (enabled unless explicitly off).","type":"object","properties":{"inbound":{"type":"boolean","default":true}}}}} +{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Config","description":"Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).","type":"object","properties":{"a2a":{"description":"Agent-to-Agent compatibility configuration (`[a2a]`).","$ref":"#/$defs/A2aConfig","default":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trusted_trust_domains":[],"trust_domain":"prx.local"}},"agent":{"description":"Agent orchestration settings (`[agent]`).","$ref":"#/$defs/AgentConfig","default":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2,"messaging":{"inbound":true}}},"agents":{"description":"Delegate agent configurations for multi-agent workflows.","type":"object","additionalProperties":{"$ref":"#/$defs/DelegateAgentConfig"},"default":{}},"api_key":{"description":"API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.","type":["string","null"],"default":null},"api_url":{"description":"Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)","type":["string","null"],"default":null},"auth":{"description":"Auth profile and external credential import settings (`[auth]`).","$ref":"#/$defs/AuthConfig","default":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"}},"autonomy":{"description":"Autonomy and security policy configuration (`[autonomy]`).","$ref":"#/$defs/AutonomyConfig","default":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true}},"browser":{"description":"Browser automation configuration (`[browser]`).","$ref":"#/$defs/BrowserConfig","default":{"allowed_domains":[],"computer_use":{"api_key":null}}},"channels_config":{"description":"Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).","$ref":"#/$defs/ChannelsConfig","default":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null}},"chat":{"description":"Interactive chat UI configuration (`[chat]`).","$ref":"#/$defs/ChatConfig","default":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2}},"compliance":{"description":"Operator-owned compliance controls (`[compliance]`).","$ref":"#/$defs/ComplianceConfig","default":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}},"composio":{"description":"Composio managed OAuth tools integration (`[composio]`).","$ref":"#/$defs/ComposioConfig","default":{"api_key":null,"entity_id":"default"}},"cost":{"description":"Cost tracking and budget enforcement configuration (`[cost]`).","$ref":"#/$defs/CostConfig","default":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{},"warn_at_percent":80}},"cron":{"description":"Cron job configuration (`[cron]`).","$ref":"#/$defs/CronConfig","default":{"max_run_history":50}},"decision_engine":{"description":"Optional advisory decision engine, disabled by default.","$ref":"#/$defs/DecisionEngineConfig","default":{"candidates":5,"enabled":false,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"latency_budget_ms":500,"max_candidates":12,"token_ratio_limit":0.3499999940395355}},"default_model":{"description":"Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.","type":["string","null"]},"default_provider":{"description":"Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.","type":["string","null"]},"default_temperature":{"description":"Default model temperature (0.0–2.0). Default: `0.7`.","type":"number","format":"double","default":0.7},"embedding_routes":{"description":"Embedding routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/EmbeddingRouteConfig"}},"gateway":{"description":"Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).","$ref":"#/$defs/GatewayConfig","default":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60}},"heartbeat":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]`).","$ref":"#/$defs/HeartbeatConfig","default":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."}},"http_request":{"description":"HTTP request tool configuration (`[http_request]`).","$ref":"#/$defs/HttpRequestConfig","default":{"max_response_size":1000000,"timeout_secs":30}},"identity":{"description":"Identity format configuration: OpenClaw or AIEOS (`[identity]`).","$ref":"#/$defs/IdentityConfig","default":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"}},"identity_bindings":{"description":"Static identity bindings loaded at startup (`[[identity_bindings]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/IdentityBindingConfig"}},"mcp":{"description":"Secrets encryption configuration (`[secrets]`).","$ref":"#/$defs/McpConfig","default":{"servers":{}}},"mcp_server":{"description":"MCP server compatibility configuration (`[mcp_server]`).","$ref":"#/$defs/McpServerRuntimeConfig","default":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true}},"media":{"description":"Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.","$ref":"#/$defs/MediaConfig","default":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"}},"memory":{"description":"Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).","$ref":"#/$defs/MemoryConfig","default":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7}},"model_routes":{"description":"Model routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/ModelRouteConfig"}},"model_settings":{"description":"Catalog model levels and explicit parameters, keyed by canonical release ID.","type":"object","additionalProperties":{"$ref":"#/$defs/ModelSettings"},"default":{}},"multimodal":{"description":"Multimodal (image) handling configuration (`[multimodal]`).","$ref":"#/$defs/MultimodalConfig","default":{"allow_remote_fetch":true,"max_image_size_mb":5,"max_images":4}},"nodes":{"description":"Remote node proxy configuration (`[nodes]`).","$ref":"#/$defs/NodesConfig","default":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}},"observability":{"description":"Observability backend configuration (`[observability]`).","$ref":"#/$defs/ObservabilityConfig","default":{"backend":"none","otel_endpoint":null,"otel_service_name":null}},"plugins":{"description":"WASM plugin runtime switch (`[plugins]`), off by default.","$ref":"#/$defs/PluginsConfig","default":{"enabled":false}},"providers":{"description":"Provider-specific runtime options (`[providers.]`).","$ref":"#/$defs/ProvidersConfig","default":{"ollama":{"num_ctx":null}}},"proxy":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).","$ref":"#/$defs/ProxyConfig","default":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]}},"query_classification":{"description":"Automatic query classification — maps user messages to model hints.","$ref":"#/$defs/QueryClassificationConfig","default":{"rules":[]}},"reliability":{"description":"Reliability settings: retries, fallback providers, backoff (`[reliability]`).","$ref":"#/$defs/ReliabilityConfig","default":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2}},"router":{"description":"Heuristic LLM router configuration (`[router]`).","$ref":"#/$defs/RouterConfig","default":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]}},"runtime":{"description":"Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.","$ref":"#/$defs/RuntimeConfig","default":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null}},"scheduler":{"description":"Scheduler configuration for periodic task execution (`[scheduler]`).","$ref":"#/$defs/SchedulerConfig","default":{"claim_lease_secs":90,"max_tasks":64}},"secrets":{"$ref":"#/$defs/SecretsConfig","default":{"encrypt":true}},"security":{"description":"Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).","$ref":"#/$defs/SecurityConfig","default":{"audit":{"log_path":"audit.log","max_size_mb":100}}},"self_system":{"description":"Self-system experimental automation controls (`[self_system]`).","$ref":"#/$defs/SelfSystemConfig","default":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24}},"sessions_spawn":{"description":"Session spawning configuration (`[sessions_spawn]`).","$ref":"#/$defs/SessionsSpawnConfig","default":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null}},"skill_rag":{"description":"Dynamic skill retrieval settings (`[skill_rag]`).","$ref":"#/$defs/SkillRagConfig","default":{"top_k":32}},"skills":{"description":"Skills loading and community repository behavior (`[skills]`).","$ref":"#/$defs/SkillsConfig","default":{"open_skills_dir":null,"openclaw_skills_dir":null}},"skills_lifecycle":{"description":"Skill lifecycle (`[skills_lifecycle]`), off by default.","$ref":"#/$defs/SkillsLifecycleConfig","default":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]}},"smart_group":{"description":"Smart group-reply pre-gate configuration (`[smart_group]`).","$ref":"#/$defs/SmartGroupConfig","default":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5}},"storage":{"description":"Persistent storage provider configuration (`[storage]`).","$ref":"#/$defs/StorageConfig","default":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"task_routing":{"description":"Task routing configuration — classifies work by intent before the main agent loop.","$ref":"#/$defs/TaskRoutingConfig","default":{"default_intent":"simple","rules":[]}},"tool_tiering":{"description":"Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).","$ref":"#/$defs/ToolTieringConfig","default":{"always_exclude":[],"always_include":[],"channel_exclude":[]}},"tunnel":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]`).","$ref":"#/$defs/TunnelConfig","default":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null}},"user_policies":{"description":"Static user policy records loaded at startup (`[[user_policies]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/UserPolicyConfig"}},"web_search":{"description":"Web search tool configuration (`[web_search]`).","$ref":"#/$defs/WebSearchConfig","default":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15}},"webhook":{"description":"Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).","$ref":"#/$defs/MemoryWebhookConfig","default":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null}},"xin":{"description":"Xin autonomous task engine configuration (`[xin]`).","$ref":"#/$defs/XinConfig","default":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}}},"$defs":{"A2aConfig":{"type":"object","properties":{"agent_id":{"description":"Stable PRX agent identifier advertised to peers.","type":"string","default":"prx-default"},"allowed_peer_issuers":{"description":"Accepted external peer issuers.","type":"array","default":[],"items":{"type":"string"}},"bind":{"description":"Advertised bind address.","type":"string","default":"127.0.0.1:16832"},"card_jwks_uri":{"description":"Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.","type":["string","null"],"default":null},"card_signing_key_path":{"description":"On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).","type":["string","null"],"default":null},"card_ttl_seconds":{"description":"Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.","type":"integer","format":"uint64","default":3600,"minimum":0},"discovery_advertised":{"description":"Whether to advertise into an external A2A registry.","type":"boolean","default":false},"handoff_nonce_ttl_seconds":{"description":"Replay window for future handoff delegation tokens.","type":"integer","format":"uint64","default":3600,"minimum":0},"messaging_enabled":{"description":"Enable the dedicated pinned mTLS messaging listener.","type":"boolean","default":false},"peers":{"type":"object","additionalProperties":{"$ref":"#/$defs/A2aPeer"},"default":{}},"spiffe_id":{"description":"Local SPIFFE-style identifier placeholder.","type":"string","default":"spiffe://prx-local/agent/prx-default"},"spiffe_strict_validation":{"description":"When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.","type":"boolean","default":false},"spiffe_trust_bundle_pem":{"description":"Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).","type":["string","null"],"default":null},"trusted_trust_domains":{"description":"Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).","type":"array","default":[],"items":{"type":"string"}},"trust_domain":{"description":"SPIFFE trust domain for new instance identities.","type":"string","default":"prx.local"}}},"A2aPeer":{"description":"Explicit pinned identity and local recipient grant.","type":"object","properties":{"spiffe_id":{"type":"string"},"fingerprints":{"type":"array","items":{"type":"string"}},"address":{"type":"string"},"owner":{"type":"string"},"sessions":{"type":"array","default":["*"],"items":{"type":"string"}},"agents":{"type":"array","default":["*"],"items":{"type":"string"}}},"required":["spiffe_id","fingerprints","address","owner"],"additionalProperties":false},"AgentCompactionConfig":{"description":"Agent context compaction configuration (`[agent.compaction]`).","type":"object","properties":{"keep_recent_messages":{"description":"Number of recent non-system messages to keep after compaction.","type":"integer","format":"uint","default":12,"minimum":0},"max_context_tokens":{"description":"Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.","type":"integer","format":"uint","default":128000,"minimum":0},"memory_flush":{"description":"Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.","type":"boolean","default":true},"mode":{"description":"Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).","$ref":"#/$defs/AgentCompactionMode","default":"switch"},"os_paging":{"description":"Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.","$ref":"#/$defs/OsPagingConfig","default":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"}},"reserve_tokens":{"description":"Tokens reserved for the next model response.","type":"integer","format":"uint","default":4096,"minimum":0}}},"AgentCompactionMode":{"description":"Compaction mode for long conversation contexts.","oneOf":[{"description":"Disable proactive compaction.","type":"string","const":"off"},{"description":"Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.","type":"string","const":"switch"},{"description":"Conservative compaction that prefers summary replacement.","type":"string","const":"safeguard"},{"description":"Aggressive truncation mode for tighter contexts.","type":"string","const":"aggressive"}]},"AgentConfig":{"description":"Agent orchestration configuration (`[agent]` section).","type":"object","properties":{"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"compact_context":{"description":"When true: bootstrap_max_chars=6000. Use for 13B or smaller models.","type":"boolean","default":false},"compaction":{"description":"Context compaction controls (`[agent.compaction]`).","$ref":"#/$defs/AgentCompactionConfig","default":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096}},"low_priority_tools":{"description":"Tool names treated as low-priority when `priority_scheduling_enabled = true`.","type":"array","default":["sessions_spawn","delegate"],"items":{"type":"string"}},"priority_scheduling_enabled":{"description":"Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.","type":"boolean","default":false},"read_only_tool_concurrency_window":{"description":"Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.","type":"integer","format":"uint","default":2,"minimum":0},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}}},"AgentLimits":{"description":"Optional admission limits for rf-started turns of a named agent.","type":"object","properties":{"max_concurrent_turns":{"type":["integer","null"],"format":"uint32","minimum":0},"max_cost_per_day_cents":{"type":["integer","null"],"format":"uint64","minimum":0}},"additionalProperties":false},"AuditConfig":{"description":"Audit logging configuration","type":"object","properties":{"log_path":{"description":"Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).","type":"string","default":"audit.log"},"max_size_mb":{"description":"Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).","type":"integer","format":"uint32","default":100,"minimum":0}}},"AuthConfig":{"description":"Authentication and external credential import configuration (`[auth]` section).","type":"object","properties":{"codex_auth_json_auto_import":{"description":"Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.","type":"boolean","default":false},"codex_auth_json_path":{"description":"Source path for Codex CLI auth.json import.","type":"string","default":"~/.codex/auth.json"}}},"AutonomyConfig":{"type":"object","properties":{"acknowledge_unrestricted_profile":{"description":"Operator acknowledgement for an intentionally unrestricted profile.\nRetained for existing configs; it no longer changes any output or policy behavior.","type":"boolean","default":false},"forbidden_paths":{"description":"Explicit path denylist. Default includes system-critical paths.\n\nFails closed: omitting the key keeps the built-in list rather than\nemptying it, so a partial `[autonomy]` section never removes the\ndenylist.","type":"array","default":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"items":{"type":"string"}},"level":{"description":"Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).","$ref":"#/$defs/AutonomyLevel","default":"full"},"max_cost_per_day_cents":{"description":"Maximum cost per day in cents per policy. Default: unset (no ceiling).","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"scopes":{"description":"Scope-based tool access control: per-user/channel/chat-type allow/deny rules.","$ref":"#/$defs/ScopeConfig","default":{"assign_owners":[],"default":"allow","rules":[]}},"workspace_only":{"description":"Restrict file writes and command paths to the workspace directory. Default: `true`.\n\nFails closed: a `[autonomy]` section that omits this key keeps the\nworkspace restriction on, so a partial section can never widen the\nfilesystem reach by accident.","type":"boolean","default":true}}},"AutonomyLevel":{"description":"How much autonomy the agent has","oneOf":[{"description":"Read-only: can observe but not act","type":"string","const":"readonly"},{"description":"Supervised: acts but requires approval for risky operations","type":"string","const":"supervised"},{"description":"Full: autonomous execution within policy bounds","type":"string","const":"full"}]},"BackendSelection":{"description":"Which decision backend runs: `auto` (the factory's order) or one kind.","type":"string"},"BrowserComputerUseConfig":{"description":"Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.","type":"object","properties":{"api_key":{"description":"Optional bearer token (retained only for config secret handling).","type":["string","null"],"default":null}}},"BrowserConfig":{"description":"Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.","type":"object","properties":{"allowed_domains":{"description":"Allowed domains for `web_fetch` (exact or subdomain match).","type":"array","default":[],"items":{"type":"string"}},"computer_use":{"description":"Computer-use sidecar config (retained only for `api_key` secret handling).","$ref":"#/$defs/BrowserComputerUseConfig","default":{"api_key":null}}}},"ChannelsConfig":{"description":"Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.","type":"object","properties":{"cli":{"description":"Enable the CLI interactive channel. Default: `true`.","type":"boolean","default":true},"dingtalk":{"description":"DingTalk channel configuration.","anyOf":[{"$ref":"#/$defs/DingTalkConfig"},{"type":"null"}]},"discord":{"description":"Discord bot channel configuration.","anyOf":[{"$ref":"#/$defs/DiscordConfig"},{"type":"null"}]},"email":{"description":"Email channel configuration.","anyOf":[{"$ref":"#/$defs/EmailConfig"},{"type":"null"}]},"imessage":{"description":"iMessage channel configuration (macOS only).","anyOf":[{"$ref":"#/$defs/IMessageConfig"},{"type":"null"}]},"irc":{"description":"IRC channel configuration.","anyOf":[{"$ref":"#/$defs/IrcConfig"},{"type":"null"}]},"lark":{"description":"Lark/Feishu channel configuration.","anyOf":[{"$ref":"#/$defs/LarkConfig"},{"type":"null"}]},"linq":{"description":"Linq Partner API channel configuration.","anyOf":[{"$ref":"#/$defs/LinqConfig"},{"type":"null"}]},"mattermost":{"description":"Mattermost bot channel configuration.","anyOf":[{"$ref":"#/$defs/MattermostConfig"},{"type":"null"}]},"nextcloud_talk":{"description":"Nextcloud Talk bot channel configuration.","anyOf":[{"$ref":"#/$defs/NextcloudTalkConfig"},{"type":"null"}]},"qq":{"description":"QQ Official Bot channel configuration.","anyOf":[{"$ref":"#/$defs/QQConfig"},{"type":"null"}]},"ramflux":{"description":"Local ramflux agent-host bridge.","anyOf":[{"$ref":"#/$defs/RamfluxConfig"},{"type":"null"}],"default":null},"signal":{"description":"Signal channel configuration.","anyOf":[{"$ref":"#/$defs/SignalConfig"},{"type":"null"}]},"slack":{"description":"Slack bot channel configuration.","anyOf":[{"$ref":"#/$defs/SlackConfig"},{"type":"null"}]},"telegram":{"description":"Telegram bot channel configuration.","anyOf":[{"$ref":"#/$defs/TelegramConfig"},{"type":"null"}]},"wacli":{"description":"wacli JSON-RPC daemon channel configuration.","anyOf":[{"$ref":"#/$defs/WacliConfig"},{"type":"null"}],"default":null},"webhook":{"description":"Webhook channel configuration.","anyOf":[{"$ref":"#/$defs/WebhookConfig"},{"type":"null"}]},"whatsapp":{"description":"WhatsApp channel configuration (Cloud API or Web mode).","anyOf":[{"$ref":"#/$defs/WhatsAppConfig"},{"type":"null"}]}}},"ChatConfig":{"description":"Interactive chat configuration (`[chat]`).","type":"object","properties":{"daemon":{"description":"How this chat process reaches the daemon it borrows channels from.","$ref":"#/$defs/ChatDaemonConfig","default":{"token":"","url":""}},"max_concurrent_visible_turns":{"description":"Maximum concurrent visible provider turns in the TUI Redux driver.","type":"integer","format":"uint","default":2,"minimum":0}}},"ChatDaemonConfig":{"description":"Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.","type":"object","properties":{"token":{"description":"Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.","type":"string","default":""},"url":{"description":"Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.","type":"string","default":""}}},"CircuitBreakerConfig":{"description":"The per-backend circuit breaker.","type":"object","properties":{"cooldown_secs":{"description":"Seconds the breaker stays open (1 to 3600).","type":"integer","format":"uint32","default":60,"minimum":0},"failure_threshold":{"description":"Consecutive failures before the breaker opens (1 to 100).","type":"integer","format":"uint32","default":5,"minimum":0}}},"ClassificationRule":{"description":"A single classification rule mapping message patterns to a model hint.","type":"object","properties":{"hint":{"description":"Must match a `[[model_routes]]` hint value.","type":"string"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"max_length":{"description":"Only match if message length <= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"min_length":{"description":"Only match if message length >= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"patterns":{"description":"Case-sensitive literal matches (for \"```\", \"fn \", etc.).","type":"array","default":[],"items":{"type":"string"}},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0}},"required":["hint"]},"CloudflareTunnelConfig":{"type":"object","properties":{"token":{"description":"Cloudflare Tunnel token (from Zero Trust dashboard)","type":"string"}},"required":["token"]},"ComplianceConfig":{"type":"object","properties":{"eu_ai_act":{"$ref":"#/$defs/EuAiActComplianceConfig","default":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null}},"interaction_notice":{"$ref":"#/$defs/InteractionNoticeConfig","default":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}}},"ComposioConfig":{"description":"Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.","type":"object","properties":{"api_key":{"description":"Composio API key (stored encrypted when secrets.encrypt = true)","type":["string","null"],"default":null},"entity_id":{"description":"Default entity ID for multi-user setups","type":"string","default":"default"}}},"CostConfig":{"description":"Cost tracking and budget enforcement configuration (`[cost]` section).","type":"object","properties":{"allow_override":{"description":"Allow requests to exceed budget with --override flag (default: false)","type":"boolean","default":false},"daily_limit_usd":{"description":"Daily spending limit in USD (default: unset, no limit; 0 refuses every priced turn)","type":["number","null"],"format":"double","default":null},"monthly_limit_usd":{"description":"Monthly spending limit in USD (default: unset, no limit)","type":["number","null"],"format":"double","default":null},"prices":{"description":"Per-model pricing (USD per 1M tokens)","type":"object","additionalProperties":{"$ref":"#/$defs/ModelPricing"},"default":{}},"warn_at_percent":{"description":"Warn when spending reaches this percentage of a configured limit (default: 80)","type":"integer","format":"uint8","default":80,"maximum":255,"minimum":0}}},"CredentialRefSetting":{"description":"Which credential a decision backend uses. A reference, never a secret.","type":"string"},"CronConfig":{"description":"Cron job configuration (`[cron]` section).","type":"object","properties":{"max_run_history":{"description":"Maximum number of historical cron run records to retain. Default: `50`.","type":"integer","format":"uint32","default":50,"minimum":0}}},"CustomTunnelConfig":{"type":"object","properties":{"health_url":{"description":"Optional URL to check tunnel health","type":["string","null"]},"start_command":{"description":"Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"","type":"string"},"url_pattern":{"description":"Optional regex to extract public URL from command stdout","type":["string","null"]}},"required":["start_command"]},"DecisionBackendConfig":{"description":"The decision backend (`[decision_engine.backend]`).","type":"object","properties":{"circuit_breaker":{"description":"The circuit breaker.","$ref":"#/$defs/CircuitBreakerConfig","default":{"cooldown_secs":60,"failure_threshold":5}},"credential_ref":{"description":"The credential reference: `\"\"`, `\"none\"` or `cred-`.","$ref":"#/$defs/CredentialRefSetting","default":""},"endpoint":{"description":"The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.","type":"string","default":""},"kind":{"description":"`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).","$ref":"#/$defs/BackendSelection","default":"auto"},"max_request_bytes":{"description":"Largest request body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":65536,"minimum":0},"max_response_bytes":{"description":"Largest response body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":262144,"minimum":0},"model":{"description":"The model the endpoint serves; one exact version for a hosted\nservice.","type":"string","default":""},"pinned_snapshot":{"description":"The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.","type":"string"},"remote_enabled":{"description":"Whether decision state may leave this machine. Default `false`.","type":"boolean","default":false},"timeout_ms":{"description":"Transport timeout (10 ms up to the extra latency budget).","type":"integer","format":"uint32","default":250,"minimum":0}}},"DecisionEngineConfig":{"type":"object","properties":{"backend":{"anyOf":[{"$ref":"#/$defs/DecisionBackendConfig"},{"type":"null"}]},"candidates":{"type":"integer","format":"uint32","default":5,"minimum":0},"enabled":{"type":"boolean","default":false},"mode":{"$ref":"#/$defs/DecisionMode","default":"pre"},"observe_queue":{"type":"integer","format":"uint32","default":64,"minimum":0},"prompt_budget_tokens":{"type":"integer","format":"uint32","default":300,"minimum":0},"telemetry_cap":{"type":"integer","format":"uint32","default":1000,"minimum":0},"timeout_ms":{"type":"integer","format":"uint32","default":1500,"minimum":0},"latency_budget_ms":{"description":"The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.","type":"integer","format":"uint64","default":500,"minimum":0},"token_ratio_limit":{"description":"Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).","type":"number","format":"float","default":0.3499999940395355},"max_candidates":{"description":"The most candidates a turn considers (1 to 32).","type":"integer","format":"uint8","default":12,"maximum":255,"minimum":0}}},"DecisionMode":{"type":"string","enum":["pre","post","both"]},"DeclarationOfConformityConfig":{"type":"object","properties":{"applicable_union_law":{"type":"array","default":[],"items":{"type":"string"}},"artifact_path":{"type":["string","null"],"default":null},"artifact_version":{"type":["string","null"],"default":null},"conformity_assessment_procedure":{"type":["string","null"],"default":null},"conformity_statement":{"type":["string","null"],"default":null},"harmonised_standards":{"type":"array","default":[],"items":{"type":"string"}},"issue_date":{"type":["string","null"],"default":null},"issue_place":{"type":["string","null"],"default":null},"notified_body_certificate":{"type":["string","null"],"default":null},"notified_body_identification_number":{"type":["string","null"],"default":null},"notified_body_name":{"type":["string","null"],"default":null},"personal_data_compliance_statement":{"type":["string","null"],"default":null},"processes_personal_data":{"type":"boolean","default":false},"provider_address":{"type":["string","null"],"default":null},"provider_name":{"type":["string","null"],"default":null},"signer_function":{"type":["string","null"],"default":null},"signer_name":{"type":["string","null"],"default":null},"signer_on_behalf_of":{"type":["string","null"],"default":null},"sole_responsibility_statement":{"type":["string","null"],"default":null},"standards_not_applicable_reason":{"type":["string","null"],"default":null},"system_name":{"type":["string","null"],"default":null},"system_reference":{"type":["string","null"],"default":null},"system_type":{"type":["string","null"],"default":null}}},"DelegateAgentConfig":{"description":"Configuration for a delegate sub-agent used by the `delegate` tool.","type":"object","properties":{"agentic":{"description":"Agentic sub-agent mode (multi-turn tool-call loop). Default true; an\nexplicit `false` makes the agent answer-only with no tools.","type":"boolean","default":true},"allowed_tools":{"description":"Allowlist of tool names available to the sub-agent in agentic mode.\nEmpty or omitted means all tools, the same as `[\"*\"]`.","type":"array","default":[],"items":{"type":"string"}},"api_key":{"description":"Optional API key override","type":["string","null"],"default":null},"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"autonomy":{"description":"The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.","anyOf":[{"$ref":"#/$defs/AutonomyLevel"},{"type":"null"}]},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"enabled":{"description":"Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.","type":"boolean","default":true},"identity_dir":{"description":"Optional identity files directory relative to workspace root.","type":["string","null"],"default":null},"limits":{"$ref":"#/$defs/AgentLimits","default":{"max_concurrent_turns":null,"max_cost_per_day_cents":null}},"max_depth":{"description":"Max recursion depth for nested delegation","type":"integer","format":"uint32","default":8,"minimum":0},"memory_scope":{"description":"Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".","type":["string","null"],"default":null},"model":{"description":"Model name","type":"string"},"provider":{"description":"Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")","type":"string"},"spawn_enabled":{"description":"Whether this agent is allowed to be targeted by sessions_spawn (default: true).","type":["boolean","null"],"default":null},"system_prompt":{"description":"Optional system prompt for the sub-agent","type":["string","null"],"default":null},"temperature":{"description":"Temperature override","type":["number","null"],"format":"double","default":null},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}},"required":["provider","model"]},"DingTalkConfig":{"description":"DingTalk configuration for Stream Mode messaging","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"client_id":{"description":"Client ID (AppKey) from DingTalk developer console","type":"string"},"client_secret":{"description":"Client Secret (AppSecret) from DingTalk developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["client_id","client_secret"]},"DiscordConfig":{"description":"Discord bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Discord user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Discord bot token (from Discord Developer Portal).","type":"string"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"guild_id":{"description":"Optional guild (server) ID to restrict the bot to a single guild.","type":["string","null"]},"listen_to_bots":{"description":"When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.","type":"boolean","default":false}},"required":["bot_token"]},"DmPolicy":{"description":"Policy for direct-message handling.","oneOf":[{"description":"Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).","type":"string","const":"pairing"},{"description":"Accept only senders listed in `allowed_from`.","type":"string","const":"allowlist"},{"description":"Accept any direct sender.","type":"string","const":"open"},{"description":"Ignore direct messages.","type":"string","const":"disabled"}]},"DockerRuntimeConfig":{"description":"Docker runtime configuration (`[runtime.docker]` section).","type":"object","properties":{"allowed_workspace_roots":{"description":"Optional workspace root allowlist for Docker mount validation.","type":"array","default":[],"items":{"type":"string"}},"cpu_limit":{"description":"Optional CPU limit (`None` = no explicit limit).","type":["number","null"],"format":"double","default":1.0},"image":{"description":"Runtime image used to execute shell commands.","type":"string","default":"alpine:3.20"},"memory_limit_mb":{"description":"Optional memory limit in MB (`None` = no explicit limit).","type":["integer","null"],"format":"uint64","default":512,"minimum":0},"mount_workspace":{"description":"Mount configured workspace into `/workspace`.","type":"boolean","default":true},"network":{"description":"Docker network mode (`none`, `bridge`, etc.).","type":"string","default":"none"},"read_only_rootfs":{"description":"Mount root filesystem as read-only.","type":"boolean","default":true}}},"EmailConfig":{"description":"Email channel configuration","type":"object","properties":{"allowed_senders":{"description":"Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)","type":"array","default":[],"items":{"type":"string"}},"from_address":{"description":"From address for outgoing emails","type":"string"},"idle_timeout_secs":{"description":"IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes","type":"integer","format":"uint64","default":1740,"minimum":0},"imap_folder":{"description":"IMAP folder to poll (default: INBOX)","type":"string","default":"INBOX"},"imap_host":{"description":"IMAP server hostname","type":"string"},"imap_port":{"description":"IMAP server port (default: 993 for TLS)","type":"integer","format":"uint16","default":993,"maximum":65535,"minimum":0},"password":{"description":"Email password for authentication","type":"string"},"smtp_host":{"description":"SMTP server hostname","type":"string"},"smtp_port":{"description":"SMTP server port (default: 465 for TLS)","type":"integer","format":"uint16","default":465,"maximum":65535,"minimum":0},"smtp_tls":{"description":"Use TLS for SMTP (default: true)","type":"boolean","default":true},"username":{"description":"Email username for authentication","type":"string"}},"required":["imap_host","smtp_host","username","password","from_address"]},"EmbeddingRouteConfig":{"description":"Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"dimensions":{"description":"Optional embedding dimension override for this route","type":["integer","null"],"format":"uint","default":null,"minimum":0},"hint":{"description":"Route hint name (e.g. \"semantic\", \"archive\", \"faq\")","type":"string"},"model":{"description":"Embedding model to use with that provider","type":"string"},"provider":{"description":"Embedding provider (`none`, `openai`, or `custom:`)","type":"string"}},"required":["hint","provider","model"]},"EuAiActClassificationConfig":{"type":"object","properties":{"assessed_at":{"type":["string","null"],"default":null},"owner":{"type":["string","null"],"default":null},"status":{"$ref":"#/$defs/EuAiActRiskClassification","default":"unclassified"}}},"EuAiActComplianceConfig":{"type":"object","properties":{"classification":{"$ref":"#/$defs/EuAiActClassificationConfig","default":{"assessed_at":null,"owner":null,"status":"unclassified"}},"declaration":{"$ref":"#/$defs/DeclarationOfConformityConfig","default":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null}},"incident_store_path":{"type":["string","null"],"default":null}}},"EuAiActRiskClassification":{"type":"string","enum":["unclassified","high_risk","not_high_risk"]},"FitnessConfig":{"description":"Calendar schedule, evidence thresholds, and retention for fitness v2.","type":"object","properties":{"auto_run":{"description":"Run the daily fitness worker in daemon mode.","type":"boolean","default":true},"max_backfill_days":{"description":"Maximum number of closed days recovered after downtime.","type":"integer","format":"uint32","default":7,"minimum":0},"min_coverage":{"description":"Minimum available metric weight required to publish a final score.","type":"number","format":"double","default":0.6},"min_samples":{"description":"Minimum samples required before an evidence-derived subscore is usable.","type":"integer","format":"uint","default":5,"minimum":0},"retention_days":{"description":"Number of daily JSON reports retained on disk.","type":"integer","format":"uint32","default":180,"minimum":0},"run_at":{"description":"Local wall-clock time (`HH:MM`) at which the previous day is scored.","type":"string","default":"00:10"},"timezone":{"description":"IANA timezone used to define closed calendar days.","type":"string","default":"UTC"}}},"GatewayConfig":{"description":"Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.","type":"object","properties":{"allow_public_bind":{"description":"Allow binding to non-localhost without a tunnel (default: false)","type":"boolean","default":false},"api_rate_limit_per_minute":{"description":"Max `/api/*` requests per minute per authenticated token.","type":"integer","format":"uint32","default":60,"minimum":0},"channel_webhook_dedup_ttl_secs":{"description":"How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.","type":"integer","format":"uint64","default":86400,"minimum":0},"host":{"description":"Gateway host (default: 127.0.0.1)","type":"string","default":"127.0.0.1"},"idempotency_max_keys":{"description":"Maximum distinct idempotency keys retained in memory.","type":"integer","format":"uint","default":10000,"minimum":0},"idempotency_ttl_secs":{"description":"TTL for webhook idempotency keys.","type":"integer","format":"uint64","default":300,"minimum":0},"pair_rate_limit_per_minute":{"description":"Max `/pair` requests per minute per client key.","type":"integer","format":"uint32","default":10,"minimum":0},"paired_tokens":{"description":"Paired bearer tokens (managed automatically, not user-edited)","type":"array","default":[],"items":{"type":"string"}},"port":{"description":"Gateway port (default: 16830)","type":"integer","format":"uint16","default":16830,"maximum":65535,"minimum":0},"rate_limit_max_keys":{"description":"Maximum distinct client keys tracked by gateway rate limiter maps.","type":"integer","format":"uint","default":10000,"minimum":0},"require_pairing":{"description":"Require pairing before accepting requests (default: true)","type":"boolean","default":true},"targeted_agents":{"description":"Switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). Default true. While false, any\notherwise-valid named target answers 409 `agent_disabled` and never\nruns as Main.","type":"boolean","default":true},"trust_forwarded_headers":{"description":"Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.","type":"boolean","default":false},"webhook_rate_limit_per_minute":{"description":"Max `/webhook` requests per minute per client key.","type":"integer","format":"uint32","default":60,"minimum":0}}},"GroupPolicy":{"description":"Policy for group-message handling.","oneOf":[{"description":"Accept only groups listed in `group_allow_from`.","type":"string","const":"allowlist"},{"description":"Accept any group.","type":"string","const":"open"},{"description":"Ignore group messages.","type":"string","const":"disabled"}]},"GroupReplyMode":{"description":"How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.","oneOf":[{"description":"Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).","type":"string","const":"off"},{"description":"Reply only when the bot is @-mentioned (legacy `mention_only = true`).","type":"string","const":"mention-only"},{"description":"Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).","type":"string","const":"smart"}]},"HeartbeatConfig":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]` section).","type":"object","properties":{"active_hours":{"description":"Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.","type":"array","default":[8,23],"items":{"type":"integer","format":"uint8","maximum":255,"minimum":0}},"interval_minutes":{"description":"Interval in minutes between heartbeat pings. Default: `30`.","type":"integer","format":"uint32","default":30,"minimum":0},"prompt":{"description":"Prompt used by heartbeat worker when dispatching tasks.","type":"string","default":"Check HEARTBEAT.md and follow instructions."}}},"HttpRequestConfig":{"description":"HTTP request tool configuration (`[http_request]` section).","type":"object","properties":{"max_response_size":{"description":"Maximum response size in bytes (default: 1MB)","type":"integer","format":"uint","default":1000000,"minimum":0},"timeout_secs":{"description":"Request timeout in seconds (default: 30)","type":"integer","format":"uint64","default":30,"minimum":0}}},"IMessageConfig":{"description":"iMessage channel configuration (macOS only).","type":"object","properties":{"allowed_contacts":{"description":"Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.","type":"array","items":{"type":"string"}},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["allowed_contacts"]},"IdentityBindingConfig":{"description":"Startup identity binding entry (`[[identity_bindings]]`).","type":"object","properties":{"channel":{"type":"string"},"channel_account":{"type":"string"},"display_name":{"type":["string","null"],"default":null},"user_id":{"type":"string"}},"required":["user_id","channel","channel_account"]},"IdentityConfig":{"description":"Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.","type":"object","properties":{"aieos_inline":{"description":"Inline AIEOS JSON (alternative to file path)","type":["string","null"],"default":null},"aieos_path":{"description":"Path to AIEOS JSON file (relative to workspace)","type":["string","null"],"default":null},"format":{"description":"Identity format: \"openclaw\" (default) or \"aieos\"","type":"string","default":"openclaw"}}},"InteractionNoticeApplicability":{"type":"string","enum":["required","not_applicable"]},"InteractionNoticeConfig":{"type":"object","properties":{"applicability":{"$ref":"#/$defs/InteractionNoticeApplicability","default":"required"},"exception_owner":{"type":["string","null"],"default":null},"exception_reviewed_at":{"type":["string","null"],"default":null},"text":{"type":"string","default":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers."},"version":{"type":"string","default":"1"}}},"IrcConfig":{"description":"IRC channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed nicknames (case-insensitive) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"channels":{"description":"Channels to join on connect","type":"array","default":[],"items":{"type":"string"}},"mention_only":{"description":"When true, only process channel/group messages that mention the bot.","type":"boolean","default":false},"nickname":{"description":"Bot nickname","type":"string"},"nickserv_password":{"description":"NickServ IDENTIFY password","type":["string","null"]},"port":{"description":"IRC server port (default: 6697 for TLS)","type":"integer","format":"uint16","default":6697,"maximum":65535,"minimum":0},"sasl_password":{"description":"SASL PLAIN password (IRCv3)","type":["string","null"]},"server":{"description":"IRC server hostname","type":"string"},"server_password":{"description":"Server password (for bouncers like ZNC)","type":["string","null"]},"username":{"description":"Username (defaults to nickname if not set)","type":["string","null"]},"verify_tls":{"description":"Verify TLS certificate (default: true)","type":["boolean","null"]}},"required":["server","nickname"]},"LarkConfig":{"description":"Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from Lark/Feishu developer console","type":"string"},"app_secret":{"description":"App Secret from Lark/Feishu developer console","type":"string"},"encrypt_key":{"description":"Encrypt key for webhook message decryption (optional)","type":["string","null"],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"port":{"description":"HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"receive_mode":{"description":"Event receive mode: \"websocket\" (default) or \"webhook\"","$ref":"#/$defs/LarkReceiveMode","default":"websocket"},"use_feishu":{"description":"Whether to use the Feishu (Chinese) endpoint instead of Lark (International)","type":"boolean","default":false},"verification_token":{"description":"Verification token for webhook validation (optional)","type":["string","null"],"default":null}},"required":["app_id","app_secret"]},"LarkReceiveMode":{"description":"How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.","type":"string","enum":["websocket","webhook"]},"LinqConfig":{"type":"object","properties":{"allowed_senders":{"description":"Allowed sender handles (phone numbers) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"api_token":{"description":"Linq Partner API token (Bearer auth)","type":"string"},"from_phone":{"description":"Phone number to send from (E.164 format)","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"signing_secret":{"description":"Webhook signing secret for signature verification","type":["string","null"],"default":null}},"required":["api_token","from_phone"]},"MattermostConfig":{"description":"Mattermost bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Mattermost user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Mattermost bot access token.","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.","type":["boolean","null"],"default":null},"thread_replies":{"description":"When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.","type":["boolean","null"],"default":null},"url":{"description":"Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).","type":"string"}},"required":["url","bot_token"]},"McpConfig":{"type":"object","properties":{"servers":{"description":"Named MCP server definitions","type":"object","additionalProperties":{"$ref":"#/$defs/McpServerConfig"},"default":{}},"workspace_servers":{"description":"Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.","$ref":"#/$defs/WorkspaceMcpServers"}}},"McpServerConfig":{"type":"object","properties":{"allow_tools":{"description":"Optional allow-list of exposed tools (empty = all)","type":"array","default":[],"items":{"type":"string"}},"args":{"description":"Command args for stdio mode","type":"array","default":[],"items":{"type":"string"}},"command":{"description":"Command for stdio mode","type":["string","null"],"default":null},"deny_tools":{"description":"Optional deny-list of exposed tools","type":"array","default":[],"items":{"type":"string"}},"env":{"description":"Environment variables for stdio mode","type":"object","additionalProperties":{"type":"string"},"default":{}},"request_timeout_ms":{"description":"Request timeout in milliseconds","type":"integer","format":"uint64","default":30000,"minimum":0},"startup_timeout_ms":{"description":"Startup timeout in milliseconds","type":"integer","format":"uint64","default":10000,"minimum":0},"tool_name_prefix":{"description":"Prefix used in tool naming and routing","type":"string","default":"mcp"},"transport":{"description":"Transport type: stdio or http","$ref":"#/$defs/McpTransport","default":"stdio"},"url":{"description":"URL for HTTP mode (streamable HTTP endpoint)","type":["string","null"],"default":null},"working_dir":{"description":"Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).","type":["string","null"]}}},"McpServerRuntimeConfig":{"type":"object","properties":{"allowed_origins":{"description":"Allowed browser origins for future streamable HTTP clients.","type":"array","default":["claude.ai","openai.com","localhost"],"items":{"type":"string"}},"bind":{"description":"Advertised bind address. The gateway may still be started with a CLI port override.","type":"string","default":"127.0.0.1:16831"},"exposed_tools":{"description":"Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.","type":"array","default":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"items":{"type":"string"}},"jwt_algorithms":{"description":"Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.","type":"array","default":["RS256"],"items":{"type":"string"}},"jwt_audience":{"description":"Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.","type":["string","null"],"default":null},"jwt_issuer":{"description":"Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.","type":["string","null"],"default":null},"jwt_jwks":{"description":"Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.","type":["string","null"],"default":null},"jwt_jwks_cache_ttl_secs":{"description":"Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.","type":"integer","format":"uint64","default":300,"minimum":0},"jwt_jwks_uri":{"description":"Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.","type":["string","null"],"default":null},"jwt_public_key_pem":{"description":"PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.","type":["string","null"],"default":null},"rate_limit_rps":{"description":"Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.","type":"integer","format":"uint32","default":10,"minimum":0},"require_auth":{"description":"Require an authenticated external identity for mutating calls.","type":"boolean","default":true}}},"McpTransport":{"type":"string","enum":["stdio","http"]},"MediaConfig":{"description":"Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.","type":"object","properties":{"audio_model":{"description":"Audio model name (Ollama model or OpenAI model). Default: \"whisper\".","type":"string","default":"whisper"},"audio_ollama_url":{"description":"Ollama base URL for audio transcription. Default: \"http://localhost:11434\".","type":"string","default":"http://localhost:11434"},"audio_provider":{"description":"Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".","type":"string","default":"none"},"max_audio_size_mb":{"description":"Maximum audio attachment size in MiB. Default: 20.","type":"integer","format":"uint","default":20,"minimum":0},"max_video_size_mb":{"description":"Maximum video attachment size in MiB. Default: 50.","type":"integer","format":"uint","default":50,"minimum":0},"video_max_frames":{"description":"Maximum video frames to extract per video. Default: 4.","type":"integer","format":"uint","default":4,"minimum":0},"video_provider":{"description":"Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".","type":"string","default":"none"}}},"MemoryConfig":{"description":"Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.","type":"object","properties":{"acl_enabled":{"description":"Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.","type":"boolean","default":false},"archive_after_days":{"description":"Archive daily/session files older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"auto_hydrate":{"description":"Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing","type":"boolean","default":true},"auto_save":{"description":"Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.","type":"boolean","default":true},"backend":{"description":"\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).","type":"string","default":"sqlite"},"conversation_retention_days":{"description":"For sqlite backend: prune conversation rows older than this many days","type":"integer","format":"uint32","default":3,"minimum":0},"daily_retention_days":{"description":"For sqlite backend: prune daily rows older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"embedding_cache_size":{"description":"Max embedding cache entries before LRU eviction","type":"integer","format":"uint","default":10000,"minimum":0},"embedding_dimensions":{"description":"Embedding vector dimensions","type":"integer","format":"uint","default":384,"minimum":0},"embedding_model":{"description":"Embedding model name (e.g. \"text-embedding-3-small\")","type":"string","default":"prx-local-hash-v1"},"embedding_provider":{"description":"Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"","type":"string","default":"local"},"events":{"description":"Raw/quasi-raw message event recording controls (`[memory.events]`).","$ref":"#/$defs/MemoryEventsConfig","default":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true}},"keyword_weight":{"description":"Weight for keyword BM25 in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.3},"legacy_conversation_turns_visible":{"description":"Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.","type":"boolean","default":true},"lucid_budget":{"description":"Token budget for lucid (replaces OPENPRX_LUCID_BUDGET)","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"lucid_cmd":{"description":"Path to lucid binary (replaces OPENPRX_LUCID_CMD)","type":["string","null"],"default":null},"lucid_failure_cooldown_ms":{"description":"Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)","type":"integer","format":"uint64","default":60000,"minimum":0},"lucid_local_hit_threshold":{"description":"Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)","type":"integer","format":"uint","default":3,"minimum":0},"lucid_recall_timeout_ms":{"description":"Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)","type":"integer","format":"uint64","default":5000,"minimum":0},"lucid_store_timeout_ms":{"description":"Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)","type":"integer","format":"uint64","default":3000,"minimum":0},"min_relevance_score":{"description":"Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4","type":"number","format":"double","default":0.4},"purge_after_days":{"description":"Purge archived files older than this many days","type":"integer","format":"uint32","default":30,"minimum":0},"semantic":{"description":"Semantic memory promotion controls (`[memory.semantic]`).","$ref":"#/$defs/MemorySemanticConfig","default":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30}},"sqlite_open_timeout_secs":{"description":"For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"sqlite_read_pool_size":{"description":"For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"vector_candidate_cap":{"description":"How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.","type":"integer","format":"uint","default":2000,"minimum":0},"vector_weight":{"description":"Weight for vector similarity in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.7}}},"MemoryEventsConfig":{"description":"Raw message event recording configuration (`[memory.events]`).","type":"object","properties":{"record_assistant_messages":{"description":"Record assistant replies.","type":"boolean","default":true},"record_tool_events":{"description":"Record tool/event payloads by default.","type":"boolean","default":false},"record_user_messages":{"description":"Record inbound/user messages.","type":"boolean","default":true}}},"MemorySemanticConfig":{"description":"Semantic memory promotion configuration (`[memory.semantic]`).","type":"object","properties":{"auto_promote_assistant_messages":{"description":"Auto-promote eligible assistant messages. Disabled by default to reduce noise.","type":"boolean","default":false},"auto_promote_user_messages":{"description":"Auto-promote eligible user messages into long-term semantic memories.","type":"boolean","default":true},"min_chars":{"description":"Minimum content length for semantic auto-promotion.","type":"integer","format":"uint","default":30,"minimum":0}}},"MemoryWebhookConfig":{"type":"object","properties":{"bind":{"description":"Socket address for the receiver (e.g. \"0.0.0.0:16899\").","type":"string","default":"0.0.0.0:16899"},"signing_secret":{"description":"Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.","type":["string","null"],"default":null},"token":{"description":"Required bearer token for incoming webhook events.","type":["string","null"],"default":null}}},"ModelOperationSetting":{"description":"The operations a `[[providers.models]]` entry may list.","type":"string","enum":["chat","embedding","decision_endpoint","rerank","image_generation","audio_generation","video_generation"]},"ModelPricing":{"description":"Per-model pricing entry (USD per 1M tokens).","type":"object","properties":{"cache_read":{"description":"Cache read input price per 1M tokens.","type":"number","format":"double","default":0.0},"cache_write":{"description":"Cache write/creation input price per 1M tokens.","type":"number","format":"double","default":0.0},"input":{"description":"Input price per 1M tokens","type":"number","format":"double","default":0.0},"output":{"description":"Output price per 1M tokens","type":"number","format":"double","default":0.0}}},"ModelRouteConfig":{"description":"Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"hint":{"description":"Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")","type":"string"},"level":{"type":["string","null"]},"model":{"description":"Model to use with that provider","type":"string"},"provider":{"description":"Provider to route to (must match a known provider name)","type":"string"},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true,"required":["hint","provider","model"]},"ModelSettings":{"description":"A model level plus explicit parameter overrides in `[model_settings.\"\"]`.","type":"object","properties":{"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"level":{"type":["string","null"]},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true},"MultimodalConfig":{"description":"Multimodal (image) handling configuration (`[multimodal]` section).","type":"object","properties":{"allow_remote_fetch":{"description":"Allow fetching remote image URLs (http/https). Enabled by default.","type":"boolean","default":true},"max_image_size_mb":{"description":"Maximum image payload size in MiB before base64 encoding.","type":"integer","format":"uint","default":5,"minimum":0},"max_images":{"description":"Maximum number of image attachments accepted per request.","type":"integer","format":"uint","default":4,"minimum":0}}},"NextcloudTalkConfig":{"description":"Nextcloud Talk bot configuration (webhook receive + OCS send API).","type":"object","properties":{"allowed_users":{"description":"Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Bot app token used for OCS API bearer auth.","type":"string"},"base_url":{"description":"Nextcloud base URL (e.g. \"https://cloud.example.com\").","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"webhook_secret":{"description":"Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).","type":["string","null"],"default":null}},"required":["base_url","app_token"]},"NgrokTunnelConfig":{"type":"object","properties":{"auth_token":{"description":"ngrok auth token","type":"string"},"domain":{"description":"Optional custom domain","type":["string","null"]}},"required":["auth_token"]},"NodeServerConfig":{"description":"Node daemon runtime config used by `prx-node`.","type":"object","properties":{"allowed_commands":{"description":"Command allowlist matched on first token.\n\nIn restricted mode this list is required unless explicitly set to `[\"*\"]`.","type":"array","default":["echo"],"items":{"type":"string"}},"bearer_token":{"description":"Required bearer token for /rpc.","type":"string","default":""},"blocked_commands":{"description":"Command denylist matched on first token. Always enforced.","type":"array","default":[],"items":{"type":"string"}},"exec_timeout_ms":{"description":"Default command timeout in milliseconds.","type":"integer","format":"uint64","default":15000,"minimum":0},"hmac_secret":{"description":"Optional HMAC signing secret.","type":["string","null"],"default":null},"listen_addr":{"description":"Listen address for node daemon.","type":"string","default":"127.0.0.1:8787"},"max_concurrent_tasks":{"description":"Maximum number of concurrent async command tasks.","type":"integer","format":"uint","default":8,"minimum":0},"max_output_bytes":{"description":"Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.","type":"integer","format":"uint","default":1048576,"minimum":0},"sandbox_root":{"description":"Sandbox root directory for read/write/cwd constraints.","type":"string","default":"."},"task_result_ttl_ms":{"description":"TTL for completed task results in milliseconds.","type":"integer","format":"uint64","default":3600000,"minimum":0},"tls_cert":{"description":"TLS certificate path (PEM).","type":["string","null"],"default":null},"tls_key":{"description":"TLS private key path (PEM).","type":["string","null"],"default":null},"tls_required":{"description":"Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.","type":"boolean","default":true}}},"NodesConfig":{"description":"Remote node proxy configuration for core-side RPC calls and node daemon defaults.","type":"object","properties":{"nodes":{"description":"Configured remote nodes.","type":"array","default":[],"items":{"$ref":"#/$defs/RemoteNodeConfig"}},"request_timeout_ms":{"description":"Default request timeout for node RPC calls.","type":"integer","format":"uint64","default":15000,"minimum":0},"retry_max":{"description":"Default max retries for node RPC calls.","type":"integer","format":"uint8","default":2,"maximum":255,"minimum":0},"server":{"description":"Embedded node server defaults used by `prx-node`.","$ref":"#/$defs/NodeServerConfig","default":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}}},"ObservabilityConfig":{"description":"Observability backend configuration (`[observability]` section).","type":"object","properties":{"backend":{"description":"\"none\" | \"log\" | \"prometheus\" | \"otel\"","type":"string","default":"none"},"otel_endpoint":{"description":"OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".","type":["string","null"],"default":null},"otel_service_name":{"description":"Service name reported to the OTel collector. Defaults to \"prx\".","type":["string","null"],"default":null}}},"OllamaProviderConfig":{"description":"Ollama-specific request options (`[providers.ollama]`).","type":"object","properties":{"num_ctx":{"description":"Explicit context window sent as Ollama `options.num_ctx`.","type":["integer","null"],"format":"uint","default":null,"minimum":0}}},"OsPagingConfig":{"description":"Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.","type":"object","properties":{"eviction_threshold":{"description":"Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.","type":"number","format":"double","default":0.7},"keep_recent_messages":{"description":"Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).","type":"integer","format":"uint","default":12,"minimum":0},"max_recalled_pages":{"description":"Maximum number of evicted pages (document chunks) recalled per turn.","type":"integer","format":"uint","default":10,"minimum":0},"proactive_retrieval":{"description":"Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.","type":"boolean","default":true},"retrieval_injection_role":{"description":"Role under which recalled pages are injected.","$ref":"#/$defs/RetrievalInjectionRole","default":"system"}}},"PluginsConfig":{"description":"WASM plugin runtime configuration.","type":"object","properties":{"enabled":{"description":"Load WASM plugins from `/plugins`. Default: `false`.","type":"boolean","default":false}},"additionalProperties":false},"ProviderModelConfig":{"description":"One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.","type":"object","properties":{"context_window":{"description":"The model's context window in tokens.","type":["integer","null"],"format":"uint32","minimum":0},"model":{"description":"The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.","type":["string","null"]},"native_tools":{"description":"Whether the model accepts native tool calls.","type":["boolean","null"]},"operations":{"description":"The complete list of operations the model executes; every operation not\nlisted is unsupported.","type":["array","null"],"items":{"$ref":"#/$defs/ModelOperationSetting"}},"provider":{"description":"The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.","type":"string"},"streaming":{"description":"Whether the model streams responses.","type":["boolean","null"]},"structured_output":{"description":"Whether the model honours a JSON-schema response format.","type":["boolean","null"]},"tool_call_dialect":{"description":"The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema_dialect":{"description":"The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]},"vision_input":{"description":"Whether the model accepts image input.","type":["boolean","null"]}},"required":["provider"]},"ProviderToolDialectConfig":{"description":"One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.","type":"object","properties":{"model":{"description":"The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.","type":["string","null"]},"provider":{"description":"The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.","type":"string"},"tool_call":{"description":"The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema":{"description":"The tool-schema dialect the endpoint accepts.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]}},"required":["provider"]},"ProvidersConfig":{"description":"Provider-specific runtime configuration (`[providers]`).","type":"object","properties":{"models":{"description":"Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.","type":"array","items":{"$ref":"#/$defs/ProviderModelConfig"}},"ollama":{"description":"Ollama-specific request options (`[providers.ollama]`).","$ref":"#/$defs/OllamaProviderConfig","default":{"num_ctx":null}},"tool_dialects":{"description":"Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).","type":"array","items":{"$ref":"#/$defs/ProviderToolDialectConfig"}}}},"ProxyConfig":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).","type":"object","properties":{"all_proxy":{"description":"Fallback proxy URL for all schemes.","type":["string","null"],"default":null},"http_proxy":{"description":"Proxy URL for HTTP requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"https_proxy":{"description":"Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"no_proxy":{"description":"No-proxy bypass list. Same format as NO_PROXY.","type":"array","default":[],"items":{"type":"string"}},"scope":{"description":"Proxy application scope.","$ref":"#/$defs/ProxyScope","default":"prx"},"services":{"description":"Service selectors used when scope = \"services\".","type":"array","default":[],"items":{"type":"string"}}}},"ProxyScope":{"description":"Proxy application scope — determines which outbound traffic uses the proxy.","oneOf":[{"description":"Use system environment proxy variables only.","type":"string","const":"environment"},{"description":"Apply proxy to all OpenPRX-managed HTTP traffic (default).","type":"string","const":"prx"},{"description":"Apply proxy only to explicitly listed service selectors.","type":"string","const":"services"}]},"QQConfig":{"description":"QQ Official Bot configuration (Tencent QQ Bot SDK)","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs. Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from QQ Bot developer console","type":"string"},"app_secret":{"description":"App Secret from QQ Bot developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["app_id","app_secret"]},"QueryClassificationConfig":{"description":"Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.","type":"object","properties":{"rules":{"description":"Classification rules evaluated in priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/ClassificationRule"}}}},"RamfluxAccountConfig":{"description":"Persona for one ramflux AI account. Missing fields fall back to the global agent.","type":"object","properties":{"cross_conversation_retrieval":{"description":"Cross-conversation memory retrieval. Off unless the owner sets it.","type":"boolean","default":false},"model":{"type":["string","null"],"default":null},"provider":{"type":["string","null"],"default":null},"scope_profile":{"type":["string","null"],"default":null},"system_prompt_file":{"description":"Path to a system-prompt file. Relative paths are resolved from the workspace.","type":["string","null"],"default":null}},"additionalProperties":false},"RamfluxAttachmentFetch":{"description":"Per-turn caps for `attachment.fetch`.","type":"object","properties":{"max_bytes":{"type":"integer","format":"uint64","default":5242880,"minimum":0},"max_per_turn":{"type":"integer","format":"uint8","default":4,"maximum":255,"minimum":0}},"additionalProperties":false},"RamfluxAuthorizationMode":{"description":"How prx combines its own setting with `bridge.hello.authorization`.","oneOf":[{"description":"Use the agent-host value. Until hello arrives, the effective mode is supervised.","type":"string","const":"follow_rf"},{"description":"Always supervised, even when the agent-host declares full.","type":"string","const":"supervised"},{"description":"Full only when the agent-host also declares full. Config alone never yields full.","type":"string","const":"full"}]},"RamfluxConfig":{"description":"Local ramflux agent-host bridge (`[channels_config.ramflux]`).","type":"object","properties":{"accounts":{"type":"object","additionalProperties":{"$ref":"#/$defs/RamfluxAccountConfig"},"default":{}},"allowed_block_types":{"type":"array","default":["Text","Markdown","Heading","KeyValue","Metric","List","TableFallback","Form","Input","Select","Progress","LogStream","Warning","Error","Success","Approval","ActionGroup","FilePreview","Fallback"],"items":{"type":"string"}},"attachment_fetch":{"$ref":"#/$defs/RamfluxAttachmentFetch","default":{"max_bytes":5242880,"max_per_turn":4}},"authorization_mode":{"$ref":"#/$defs/RamfluxAuthorizationMode","default":"follow_rf"},"encrypt_at_rest":{"type":"boolean","default":true},"max_in_flight_per_conversation":{"type":"integer","format":"uint8","default":1,"maximum":255,"minimum":0},"on_new_message":{"$ref":"#/$defs/RamfluxOnNewMessage","default":"queue"},"socket_path":{"description":"Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.","type":["string","null"],"default":null},"surface_limits":{"$ref":"#/$defs/RamfluxSurfaceLimits","default":{"max_actions":16,"max_blocks":32,"max_bytes":65536}},"turn_wall_clock_secs":{"description":"Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.","type":"integer","format":"uint64","default":120,"minimum":0}},"additionalProperties":false},"RamfluxOnNewMessage":{"description":"What to do with a new inbound message while a turn for that conversation is running.","type":"string","enum":["queue","interrupt"]},"RamfluxSurfaceLimits":{"description":"Limits for `reply.surface` blocks and actions.","type":"object","properties":{"max_actions":{"type":"integer","format":"uint32","default":16,"minimum":0},"max_blocks":{"type":"integer","format":"uint32","default":32,"minimum":0},"max_bytes":{"type":"integer","format":"uint32","default":65536,"minimum":0}},"additionalProperties":false},"ReliabilityCircuitBreakerConfig":{"description":"Process-local provider circuit policy (`[reliability.circuit_breaker]`).","type":"object","properties":{"enabled":{"description":"Enable protection for factory-built provider chains.","type":"boolean","default":true},"failure_threshold":{"description":"Consecutive transient failures that open a circuit (at least 1).","type":"integer","format":"uint32","default":5,"minimum":0},"max_open_secs":{"description":"Maximum doubled window, between open_secs and 3600 seconds.","type":"integer","format":"uint64","default":300,"minimum":0},"open_secs":{"description":"Initial open window in seconds (at least 1).","type":"integer","format":"uint64","default":30,"minimum":0}}},"ReliabilityConfig":{"description":"Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.","type":"object","properties":{"acknowledge_single_provider_risk":{"description":"Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.","type":"boolean","default":false},"api_keys":{"description":"Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.","type":"array","default":[],"items":{"type":"string"}},"channel_initial_backoff_secs":{"description":"Initial backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":2,"minimum":0},"channel_max_backoff_secs":{"description":"Max backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":60,"minimum":0},"circuit_breaker":{"description":"Per-provider consecutive failure protection.","$ref":"#/$defs/ReliabilityCircuitBreakerConfig","default":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30}},"fallback_providers":{"description":"Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).","type":"array","default":[],"items":{"type":"string"}},"model_fallbacks":{"description":"Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`","type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"default":{}},"provider_backoff_ms":{"description":"Base backoff (ms) for provider retry delay.","type":"integer","format":"uint64","default":500,"minimum":0},"provider_retries":{"description":"Retries per provider before failing over.","type":"integer","format":"uint32","default":2,"minimum":0},"scheduler_poll_secs":{"description":"Scheduler polling cadence in seconds.","type":"integer","format":"uint64","default":15,"minimum":0},"scheduler_retries":{"description":"Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.","type":"integer","format":"uint32","default":2,"minimum":0}}},"RemoteNodeConfig":{"description":"A remote node target for core-side node proxy calls.","type":"object","properties":{"bearer_token":{"description":"Bearer token for node RPC authentication.","type":"string"},"endpoint":{"description":"Base endpoint (e.g. \"http://127.0.0.1:8787\").","type":"string"},"hmac_secret":{"description":"Optional request signing key (HMAC-SHA256).","type":["string","null"],"default":null},"id":{"description":"Stable node ID used by the nodes tool.","type":"string"},"retry_max":{"description":"Optional per-node retry override.","type":["integer","null"],"format":"uint8","default":null,"maximum":255,"minimum":0},"timeout_ms":{"description":"Optional per-node timeout override.","type":["integer","null"],"format":"uint64","default":null,"minimum":0}},"required":["id","endpoint","bearer_token"]},"RetrievalInjectionRole":{"description":"Where recalled context pages are injected back into the request.","oneOf":[{"description":"Inject recalled pages as a leading `system` message (not user-visible).","type":"string","const":"system"},{"description":"Inject recalled pages as a leading `user` message.","type":"string","const":"user"}]},"RouterConfig":{"description":"Heuristic LLM router configuration (`[router]` section).","type":"object","properties":{"alpha":{"description":"Similarity score weight. Phase 1 keeps this at `0.0`.","type":"number","format":"float","default":0.0},"beta":{"description":"Capability score weight.","type":"number","format":"float","default":0.5},"delta":{"description":"Cost penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"epsilon":{"description":"Latency penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"gamma":{"description":"Elo score weight.","type":"number","format":"float","default":0.30000001192092896},"knn_k":{"description":"Number of nearest neighbors considered for voting. Default: `7`.","type":"integer","format":"uint","default":7,"minimum":0},"knn_min_records":{"description":"Minimum history records before KNN affects routing. Default: `10`.","type":"integer","format":"uint","default":10,"minimum":0},"models":{"description":"Candidate model registry.","type":"array","default":[],"items":{"$ref":"#/$defs/RouterModelConfig"}}}},"RouterModelConfig":{"description":"Static router metadata for one model candidate.","type":"object","properties":{"categories":{"description":"Capability categories such as `conversation`, `code`, or `analysis`.","type":"array","default":[],"items":{"type":"string"}},"cost_per_million_tokens":{"description":"USD cost per million tokens.","type":"number","format":"float","default":0.0},"elo_rating":{"description":"Initial Elo rating.","type":"number","format":"float","default":1000.0},"latency_ms":{"description":"Average latency in milliseconds.","type":"integer","format":"uint32","default":2000,"minimum":0},"max_context":{"description":"Maximum context window in tokens.","type":"integer","format":"uint","default":1000000,"minimum":0},"model_id":{"description":"Model identifier without provider prefix.","type":"string"},"provider":{"description":"Provider identifier.","type":"string"},"reserved_output_tokens":{"description":"Output tokens reserved for this model when planning input context.","type":["integer","null"],"format":"uint","minimum":0}},"required":["model_id","provider"]},"RuntimeConfig":{"description":"Runtime adapter configuration (`[runtime]` section).","type":"object","properties":{"codex_reasoning_effort":{"description":"Codex reasoning effort","type":["string","null"],"default":null},"codex_stream_idle_timeout_secs":{"description":"Codex stream idle timeout in seconds","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"docker":{"description":"Docker runtime settings (used when `kind = \"docker\"`).","$ref":"#/$defs/DockerRuntimeConfig","default":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true}},"idle_hang_secs":{"description":"Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"kind":{"description":"Runtime kind (`native` | `docker`).","type":"string","default":"native"},"long_task_warn_secs":{"description":"Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"managed_cgroup_root":{"description":"Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.","type":["string","null"],"default":null},"max_blocking_threads":{"description":"Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"reasoning_enabled":{"description":"Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported","type":["boolean","null"],"default":null},"shell_env_allowlist":{"description":"Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.","type":"array","default":[],"items":{"type":"string"}},"workdir":{"description":"Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.","type":["string","null"],"default":null}}},"SchedulerConfig":{"description":"Scheduler configuration for periodic task execution (`[scheduler]` section).","type":"object","properties":{"claim_lease_secs":{"description":"Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.","type":"integer","format":"uint64","default":90,"minimum":0},"max_tasks":{"description":"Maximum number of persisted scheduled tasks.","type":"integer","format":"uint","default":64,"minimum":0}}},"ScopeConfig":{"description":"Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```","type":"object","properties":{"assign_owners":{"description":"Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.","type":"array","default":[],"items":{"type":"string"}},"default":{"description":"Default action when no rule matches: \"allow\" (default) or \"deny\".","$ref":"#/$defs/ScopeDefault","default":"allow"},"rules":{"description":"Ordered list of scope rules evaluated top-to-bottom.","type":"array","default":[],"items":{"$ref":"#/$defs/ScopeRule"}}}},"ScopeDefault":{"description":"What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.","oneOf":[{"description":"Unmatched tool calls are allowed (the default).","type":"string","const":"allow"},{"description":"Unmatched tool calls are refused.","type":"string","const":"deny"}]},"ScopeRule":{"description":"A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.","type":"object","properties":{"assign_allow":{"description":"Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".","type":"array","default":[],"items":{"type":"string"}},"assign_deny":{"description":"Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.","type":"array","default":[],"items":{"type":"string"}},"channel":{"description":"Match by channel name: \"signal\", \"telegram\", \"discord\", etc.","type":["string","null"]},"chat_type":{"description":"Match by chat type: \"direct\", \"group\", or \"*\" for any type.","type":["string","null"]},"send_allow":{"description":"Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.","type":"array","default":[],"items":{"type":"string"}},"send_deny":{"description":"Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.","type":"array","default":[],"items":{"type":"string"}},"tools_allow":{"description":"Tool whitelist: only these tools are allowed (empty = all tools permitted).","type":"array","default":[],"items":{"type":"string"}},"tools_deny":{"description":"Tool blacklist: these tools are denied regardless of allow list.","type":"array","default":[],"items":{"type":"string"}},"user":{"description":"Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.","type":["string","null"]}}},"SecretsConfig":{"description":"Secrets encryption configuration (`[secrets]` section).","type":"object","properties":{"encrypt":{"description":"Enable encryption for API keys and tokens in config.toml","type":"boolean","default":true}}},"SecurityConfig":{"description":"Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.","type":"object","properties":{"audit":{"description":"Audit logging configuration","$ref":"#/$defs/AuditConfig","default":{"log_path":"audit.log","max_size_mb":100}},"workspace_hooks":{"description":"Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.","$ref":"#/$defs/WorkspaceHooks"}}},"SelfSystemConfig":{"description":"Self-system experimental automation config (`[self_system]`).","type":"object","properties":{"evolution_config_path":{"description":"Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG)","type":["string","null"],"default":null},"evolution_debug_raw":{"description":"Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW)","type":"boolean","default":false},"evolution_interval_hours":{"description":"Evolution scheduler interval in hours (daemon mode).","type":"integer","format":"uint32","default":24,"minimum":0},"evolution_judge_timeout_secs":{"description":"Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.","type":"integer","format":"uint64","default":180,"minimum":0},"evolution_model_max_micro_usd":{"description":"Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.","type":"integer","format":"uint64","default":0,"minimum":0},"evolution_model_max_tokens":{"description":"Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.","type":"integer","format":"uint64","default":16384,"minimum":0},"fitness":{"description":"Daily fitness snapshot policy.","$ref":"#/$defs/FitnessConfig","default":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"}},"fitness_interval_hours":{"description":"Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.","type":"integer","format":"uint64","default":24,"minimum":0}}},"SessionsSpawnConfig":{"description":"Sessions spawn configuration (`[sessions_spawn]` section).","type":"object","properties":{"cleanup_on_complete":{"description":"Remove worker workspace directory after process-mode completion.","type":"boolean","default":true},"default_mode":{"description":"Default execution mode for sessions_spawn (`task` or `process`).","type":"string","default":"task"},"process_memory_strategy":{"description":"Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.","type":"string","default":"shared_fabric"},"worker_workspace_root":{"description":"Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.","type":["string","null"],"default":null}}},"SignalConfig":{"type":"object","properties":{"account":{"description":"E.164 phone number of the signal-cli account (e.g. \"+1234567890\").","type":"string"},"allowed_from":{"description":"Allowed sender phone numbers (E.164) or \"*\" for all.","type":"array","default":[],"items":{"type":"string"}},"cli_path":{"description":"Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).","type":["string","null"],"default":null},"daemon_http_port":{"description":"Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"daemon_mode":{"description":"Deprecated: ignored. Accepted for backward compatibility with older config files.","type":["boolean","null"],"default":null},"data_dir":{"description":"signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_id":{"description":"Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group","type":["string","null"],"default":null},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"http_url":{"description":"Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.","type":"string","default":"http://localhost:8080"},"ignore_attachments":{"description":"Skip messages that are attachment-only (no text body).","type":"boolean","default":false},"ignore_stories":{"description":"Skip incoming story messages.","type":"boolean","default":false},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"mode":{"description":"Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.","type":["string","null"],"default":null},"startup_timeout_ms":{"description":"Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.","type":"integer","format":"uint64","default":30000,"minimum":0},"storm_protection":{"description":"Signal ingress storm protection controls.","$ref":"#/$defs/SignalStormProtectionConfig","default":{"abnormal_threshold":10,"abnormal_window_secs":60,"breaker_duration_secs":300,"dedupe_ttl_secs":60,"min_reply_interval_secs":2}}},"required":["account"]},"SignalStormProtectionConfig":{"type":"object","properties":{"abnormal_threshold":{"description":"Non-user event threshold within `abnormal_window_secs` before tripping the breaker.","type":"integer","format":"uint","default":10,"minimum":0},"abnormal_window_secs":{"description":"Sliding window in seconds for non-user event counting.","type":"integer","format":"uint64","default":60,"minimum":0},"breaker_duration_secs":{"description":"Circuit breaker duration in seconds after threshold is reached.","type":"integer","format":"uint64","default":300,"minimum":0},"dedupe_ttl_secs":{"description":"Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.","type":"integer","format":"uint64","default":60,"minimum":0},"min_reply_interval_secs":{"description":"Minimum interval in seconds between replies for the same `(channel + reply_target)`.","type":"integer","format":"uint64","default":2,"minimum":0}}},"SkillRagConfig":{"description":"Dynamic skill retrieval configuration (`[skill_rag]` section).","type":"object","properties":{"top_k":{"description":"How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).","type":"integer","format":"uint","default":32,"minimum":0}}},"SkillSuiteRegistration":{"description":"The frozen suite that governs one skill's proposals.","type":"object","properties":{"skill_id":{"description":"The skill the suite governs.","type":"string"},"suite_digest":{"description":"SHA-256 digest (64 lowercase hex digits) of the frozen suite.","type":"string"}},"additionalProperties":false,"required":["skill_id","suite_digest"]},"SkillsConfig":{"description":"Skills loading configuration (`[skills]` section).","type":"object","properties":{"open_skills_dir":{"description":"Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.","type":["string","null"],"default":null},"openclaw_skills_dir":{"description":"Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.","type":["string","null"],"default":null}}},"SkillsLifecycleConfig":{"description":"`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.","type":"object","properties":{"allow_executable_proposals":{"description":"Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.","type":"boolean","default":false},"enabled":{"description":"Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.","type":"boolean","default":false},"max_concurrent_evaluations":{"description":"Most evaluations running at once.","type":"integer","format":"uint32","default":1,"minimum":0},"max_edit_fraction":{"description":"Edit budget of a proposal as a fraction of the skill body, in (0, 1].","type":"number","format":"double","default":0.2},"max_edit_tokens":{"description":"Edit budget of a proposal, in tokens.","type":"integer","format":"uint64","default":300,"minimum":0},"max_proposals_per_cycle":{"description":"Most proposals one cycle may start.","type":"integer","format":"uint32","default":1,"minimum":0},"min_cases_floor":{"description":"Smallest `min_cases` a governing suite may declare. Below 3 is refused.","type":"integer","format":"uint32","default":3,"minimum":0},"mode":{"description":"`draft_only`, `shadow` or `auto`.","$ref":"#/$defs/SkillsLifecycleModeConfig","default":"draft_only"},"owner_scope":{"description":"The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.","type":["string","null"],"default":null},"require_holdout":{"description":"A governing suite must have a holdout split. `false` is refused.","type":"boolean","default":true},"storage_dir":{"description":"Store location under the workspace. Only the default is supported.","type":"string","default":"self/skill-lifecycle"},"suites":{"description":"The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.","type":"array","default":[],"items":{"$ref":"#/$defs/SkillSuiteRegistration"}}},"additionalProperties":false},"SkillsLifecycleModeConfig":{"description":"What the lifecycle may do. Mirrors `LifecycleMode`.","oneOf":[{"description":"Drafts and reviews only.","type":"string","const":"draft_only"},{"description":"Drafts plus evaluation and gating; never publishes.","type":"string","const":"shadow"},{"description":"Publishes an eligible proposal after every gate.","type":"string","const":"auto"}]},"SlackConfig":{"description":"Slack bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Slack user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Slack app-level token for Socket Mode (xapp-...).","type":["string","null"]},"bot_token":{"description":"Slack bot OAuth token (xoxb-...).","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["bot_token"]},"SmartGroupConfig":{"description":"Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).","type":"object","properties":{"classifier_max_context_messages":{"description":"How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.","type":"integer","format":"uint","default":3,"minimum":0},"classifier_model":{"description":"Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.","type":"string","default":""},"classifier_provider":{"description":"Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.","type":"string","default":""},"classifier_temperature":{"description":"Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).","type":"number","format":"double","default":0.0},"classifier_timeout_secs":{"description":"Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.","type":"integer","format":"uint64","default":5,"minimum":0}}},"StorageConfig":{"description":"Persistent storage configuration (`[storage]` section).","type":"object","properties":{"provider":{"description":"Storage provider settings (e.g. sqlite, postgres).","$ref":"#/$defs/StorageProviderSection","default":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}}},"StorageProviderConfig":{"description":"Storage provider backend configuration (e.g. postgres connection details).","type":"object","properties":{"connect_timeout_secs":{"description":"Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"db_url":{"description":"Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.","type":["string","null"],"default":null},"pool_max_size":{"description":"Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.","type":"integer","format":"uint","default":32,"minimum":0},"provider":{"description":"Storage engine key (e.g. \"postgres\", \"sqlite\").","type":"string","default":""},"schema":{"description":"Database schema for SQL backends.","type":"string","default":"public"},"table":{"description":"Table name for memory entries.","type":"string","default":"memories"}}},"StorageProviderSection":{"description":"Wrapper for the storage provider configuration section.","type":"object","properties":{"config":{"description":"Storage provider backend settings.","$ref":"#/$defs/StorageProviderConfig","default":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"StreamMode":{"description":"Streaming mode for channels that support progressive message updates.","oneOf":[{"description":"No streaming -- send the complete response as a single message (default).","type":"string","const":"off"},{"description":"Update a draft message with every flush interval.","type":"string","const":"partial"}]},"TailscaleTunnelConfig":{"type":"object","properties":{"funnel":{"description":"Use Tailscale Funnel (public internet) vs Serve (tailnet only)","type":"boolean","default":false},"hostname":{"description":"Optional hostname override","type":["string","null"]}}},"TaskRoutingConfig":{"description":"Lightweight pre-LLM task routing.","type":"object","properties":{"default_intent":{"description":"Fallback intent when no rule matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"rules":{"description":"Rules evaluated in descending priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/TaskRoutingRule"}}}},"TaskRoutingIntentConfig":{"description":"Task-routing default and rule intent.","type":"string","enum":["simple","delegate","stream"]},"TaskRoutingRule":{"description":"A single task-routing rule.","type":"object","properties":{"intent":{"description":"Route intent to apply when a keyword matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"model_hint":{"description":"Optional model hint/raw model for non-delegated requests.","type":["string","null"],"default":null},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0},"sub_agent_model":{"description":"Optional raw sub-agent model override for delegated tasks.","type":["string","null"],"default":null}}},"TelegramConfig":{"description":"Telegram bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Telegram user IDs or usernames. Empty = deny all.","type":"array","items":{"type":"string"}},"bot_token":{"description":"Telegram Bot API token (from @BotFather).","type":"string"},"draft_update_interval_ms":{"description":"Minimum interval (ms) between draft message edits to avoid rate limits.","type":"integer","format":"uint64","default":1000,"minimum":0},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"interrupt_on_new_message":{"description":"When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.","type":"boolean","default":false},"stream_mode":{"description":"Streaming mode for progressive response delivery via message edits.","$ref":"#/$defs/StreamMode","default":"off"}},"required":["bot_token","allowed_users"]},"ToolCallDialectSetting":{"description":"The tool-call grammars an operator may declare for an endpoint.","oneOf":[{"description":"Only the native `tool_calls` array is a tool call (the default).","type":"string","const":"native"},{"description":"Additionally read `{json}` from the content,\nfor a tool name the request registered.","type":"string","const":"xml_function_tags"}]},"ToolSchemaDialectSetting":{"description":"The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.","oneOf":[{"description":"The published document, byte for byte (the default).","type":"string","const":"raw"},{"description":"The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.","type":"string","const":"no_root_combinators"}]},"ToolTieringConfig":{"description":"Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.","type":"object","properties":{"always_exclude":{"description":"Tool names excluded from capability publication.","type":"array","default":[],"items":{"type":"string"}},"always_include":{"description":"Tool names preferred for direct publication, subject to admission gates.","type":"array","default":[],"items":{"type":"string"}},"channel_exclude":{"description":"Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefault: empty (nothing is hidden); list tool names to hide them on channels.","type":"array","default":[],"items":{"type":"string"}}}},"TunnelConfig":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.","type":"object","properties":{"cloudflare":{"description":"Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).","anyOf":[{"$ref":"#/$defs/CloudflareTunnelConfig"},{"type":"null"}],"default":null},"custom":{"description":"Custom tunnel command configuration (used when `provider = \"custom\"`).","anyOf":[{"$ref":"#/$defs/CustomTunnelConfig"},{"type":"null"}],"default":null},"ngrok":{"description":"ngrok tunnel configuration (used when `provider = \"ngrok\"`).","anyOf":[{"$ref":"#/$defs/NgrokTunnelConfig"},{"type":"null"}],"default":null},"provider":{"description":"Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.","type":"string","default":"none"},"tailscale":{"description":"Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).","anyOf":[{"$ref":"#/$defs/TailscaleTunnelConfig"},{"type":"null"}],"default":null}}},"UserPolicyConfig":{"description":"Startup user policy entry (`[[user_policies]]`).","type":"object","properties":{"blocked_patterns":{"type":"array","default":[],"items":{"type":"string"}},"projects":{"type":"array","default":[],"items":{"type":"string"}},"role":{"type":"string","default":"guest"},"user_id":{"type":"string"},"visibility_ceiling":{"type":"string","default":"private"}},"required":["user_id"]},"WacliConfig":{"description":"wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```","type":"object","properties":{"allow_unsigned_loopback":{"description":"Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).","type":"boolean","default":false},"allowed_from":{"description":"Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.","type":"array","default":["*"],"items":{"type":"string"}},"bot_jid":{"description":"Bot's own JID, used for reply-to-bot mention detection.","type":["string","null"],"default":null},"bot_lid":{"description":"The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.","type":["string","null"],"default":null},"bot_number":{"description":"Bot's own phone number (digits), used for `@` mention detection.","type":["string","null"],"default":null},"cli_path":{"description":"Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.","type":["string","null"],"default":null},"group_reply_mode":{"description":"Smart group-reply mode. When `None`, derived from `mention_only`.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"host":{"description":"REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].","type":["string","null"],"writeOnly":true},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"outbound_media_workspace_only":{"description":"Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.","type":"boolean","default":false},"port":{"description":"REMOVED: legacy JSON-RPC daemon port. See `host`.","type":["integer","null"],"format":"uint16","maximum":65535,"minimum":0,"writeOnly":true},"self_chat_mode":{"description":"Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.","type":"boolean","default":false},"store_dir":{"description":"wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.","type":["string","null"],"default":null},"webhook_listen":{"description":"Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").","type":"string","default":"127.0.0.1:16868"},"webhook_path":{"description":"HTTP path the webhook server serves (default: \"/wacli\").","type":"string","default":"/wacli"},"webhook_secret":{"description":"HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.","type":["string","null"],"default":null}}},"WebSearchConfig":{"description":"Web search tool configuration (`[web_search]` section).","type":"object","properties":{"brave_api_key":{"description":"Brave Search API key (required if provider is \"brave\")","type":["string","null"],"default":null},"fetch_max_chars":{"description":"Maximum characters returned by `web_fetch` (default 10000)","type":"integer","format":"uint","default":50000,"minimum":0},"max_results":{"description":"Maximum results per search (1-20)","type":"integer","format":"uint","default":15,"minimum":0},"provider":{"description":"Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)","type":"string","default":"duckduckgo"},"timeout_secs":{"description":"Request timeout in seconds","type":"integer","format":"uint64","default":15,"minimum":0}}},"WebhookConfig":{"description":"Webhook channel configuration.","type":"object","properties":{"port":{"description":"Port to listen on for incoming webhooks.","type":"integer","format":"uint16","maximum":65535,"minimum":0},"secret":{"description":"Optional shared secret for webhook signature verification.","type":["string","null"]}},"required":["port"]},"WhatsAppConfig":{"description":"WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.","type":"object","properties":{"access_token":{"description":"Access token from Meta Business Suite (Cloud API mode)","type":["string","null"],"default":null},"allowed_numbers":{"description":"Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"app_secret":{"description":"App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"pair_code":{"description":"Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one","type":["string","null"],"default":null},"pair_phone":{"description":"Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used","type":["string","null"],"default":null},"phone_number_id":{"description":"Phone number ID from Meta Business API (Cloud API mode)","type":["string","null"],"default":null},"read_pool_size":{"description":"Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"session_path":{"description":"Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs","type":["string","null"],"default":null},"verify_token":{"description":"Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode","type":["string","null"],"default":null},"ws_url":{"description":"WebSocket URL override (replaces WHATSAPP_WS_URL)","type":["string","null"],"default":null}}},"WorkspaceHooks":{"description":"Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).","oneOf":[{"description":"They do not run (the default); `prx doctor` and `hooks_status` say so.","type":"string","const":"off"},{"description":"They run, in a cleared environment and a dedicated directory beside\n`config.toml`.","type":"string","const":"on"}]},"WorkspaceMcpServers":{"description":"Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).","oneOf":[{"description":"None: a workspace file may only narrow the servers defined in\n`config.toml`.","type":"string","const":"off"},{"description":"HTTP servers (still refused when they target a private address).","type":"string","const":"http_only"},{"description":"HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.","type":"string","const":"stdio"}]},"XinConfig":{"description":"Configuration for the xin autonomous task engine (`[xin]`).","type":"object","properties":{"adopt_legacy_tasks":{"description":"Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).","type":"boolean","default":false},"interval_minutes":{"description":"Tick interval in minutes (minimum 1). Default: 5.","type":"integer","format":"uint32","default":5,"minimum":0},"stale_timeout_minutes":{"description":"Minutes after which a running task is marked stale. Default: 60.","type":"integer","format":"uint32","default":60,"minimum":0}}},"AgentMessaging":{"description":"Owner-controlled inbound session messaging (enabled unless explicitly off).","type":"object","properties":{"inbound":{"type":"boolean","default":true}}}}} From c0058a7e27bc69d7ccfd06b012d8d3fcce05818a Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:42:50 +0400 Subject: [PATCH 0136/1567] feat(nodes): allow any command from an authenticated caller by default nodes.server.allowed_commands now defaults to an empty list, which the validator already treats as no allowlist. Authentication and TLS defaults are unchanged; a configured allowlist keeps working. The config plan now reports an allowlist becoming empty or * as a widening. --- docs/configuration.md | 2 +- docs/migration-unreleased.md | 1 + docs/remote-nodes.md | 4 ++-- src/config/manage/plan.rs | 14 ++++++++++++-- src/config/schema/nodes.rs | 13 ++++--------- .../child_source/golden_effective_config.json | 2 +- tests/fixtures/config-schema.json | 2 +- 7 files changed, 22 insertions(+), 16 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 789d1a5d1..6f172eaab 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -147,7 +147,7 @@ and the module-gate family are absorbed on load; they are not live switches. | `[identity]` | `format = "openclaw"`; `aieos_path` unset; `aieos_inline` unset | | `[cost]` | `daily_limit_usd` unset (no limit); `monthly_limit_usd` unset (no limit); `warn_at_percent = 80` (applies only to a configured limit); `allow_override = false`; `prices = {}` (each price: `input`/`output`/`cache_write`/`cache_read = 0`) | | `[nodes]` | `request_timeout_ms = 15000`; `retry_max = 2`; `nodes = []`. A node: `id`, `endpoint`, `bearer_token` required; `hmac_secret` unset; `timeout_ms`/`retry_max` unset | -| `[nodes.server]` | `listen_addr = "127.0.0.1:8787"`; `bearer_token = ""`; `hmac_secret` unset; `sandbox_root = "."`; `exec_timeout_ms = 15000`; `max_output_bytes = 1048576`; `max_concurrent_tasks = 8`; `task_result_ttl_ms = 3600000`; `allowed_commands = ["echo"]`; `blocked_commands = []`; `tls_required = true`; `tls_cert`/`tls_key` unset | +| `[nodes.server]` | `listen_addr = "127.0.0.1:8787"`; `bearer_token = ""`; `hmac_secret` unset; `sandbox_root = "."`; `exec_timeout_ms = 15000`; `max_output_bytes = 1048576`; `max_concurrent_tasks = 8`; `task_result_ttl_ms = 3600000`; `allowed_commands = []` (any command from an authenticated caller; `["*"]` is the same); `blocked_commands = []`; `tls_required = true`; `tls_cert`/`tls_key` unset | | `[agents.]` | `provider`/`model` required; `system_prompt`/`api_key`/`credential_ref`/`temperature`/`identity_dir`/`memory_scope`/`spawn_enabled`/`autonomy` unset; `max_depth = 8`; `agentic = true`; `allowed_tools = []` (empty means all tools, the same as `["*"]`); `enabled = true` | | `[media]` | `audio_provider = "none"`; `audio_model = "whisper"`; `audio_ollama_url = "http://localhost:11434"`; `video_provider = "none"`; `video_max_frames = 4`; `max_audio_size_mb = 20`; `max_video_size_mb = 50` | | `[decision_engine]` | `enabled = false`; `mode = "pre"`; `prompt_budget_tokens = 300`; `candidates = 5`; `timeout_ms = 1500`; `telemetry_cap = 1000`; `observe_queue = 64`; `latency_budget_ms = 500`; `token_ratio_limit = 0.35`; `max_candidates = 12`; `backend` unset | diff --git a/docs/migration-unreleased.md b/docs/migration-unreleased.md index 796bf2c71..652465f15 100644 --- a/docs/migration-unreleased.md +++ b/docs/migration-unreleased.md @@ -31,6 +31,7 @@ of the [changelog](../CHANGELOG.md). | No spend ceiling by default | `[autonomy] max_cost_per_day_cents`, `[cost] daily_limit_usd` and `[cost] monthly_limit_usd` are now optional and unset by default. Before: a config that omitted them got 500 cents per day, 10.0 USD per day and 100.0 USD per month. Now: a config that omits them has no limit, so no spend is refused for a budget reason, no budget warning or "budget exhausted" notice is printed, and children and worker processes get the maximum allowance (`u32::MAX` cents in the signed manifest). A config that sets any of these keys keeps exactly that limit. `prx init` no longer writes `max_cost_per_day_cents`. Usage accounting and the cost journal are unchanged. To keep the old ceilings, write them into the config. Per-agent `limits` were already unset by default. No stored-data migration is required. | Only to keep the former ceilings: set the three keys explicitly | | Nothing restricted by default on a fresh install | `[tool_tiering] channel_exclude` now defaults to an empty list (before: 14 operations tools such as `gateway`, `config_reload`, `nodes`, `skills_manage` were hidden from IM channel turns); a config that omits it now exposes those tools on channel turns, and a config that lists names keeps hiding them. `prx init --spec server` no longer writes `workspace_only`, `forbidden_paths` or `acknowledge_unrestricted_profile` (the built-in values are unchanged and have no effect at level `full`); `--spec full` no longer writes `acknowledge_unrestricted_profile`. `prx doctor` no longer warns for an explicit unrestricted profile; it prints one neutral autonomy-level line, and `acknowledge_unrestricted_profile` is accepted and ignored. Gateway pairing, channel sender allowlists, secret protection and integrity checks are unchanged. | Only to keep the old channel tool hiding: list the names in `channel_exclude` | | Remote image fetch on by default | `[multimodal] allow_remote_fetch` now defaults to `true` (before: `false`). A config that omits it now lets `http`/`https` image references be fetched into the model context; an explicit `false` keeps the old behavior. The fetch keeps the same private-address handling as `web_fetch`: below Full private, loopback and link-local hosts are refused, at Full they are reachable. | Only to keep remote fetch off: set `allow_remote_fetch = false` | +| Node agent allows any command by default | `[nodes.server] allowed_commands` now defaults to an empty list, which allows any command (before: `["echo"]`, so every other command was refused). A config that omits the key now lets an authenticated caller run any command; a config that lists commands keeps that allowlist. Authentication is unchanged: a non-empty bearer token is required at startup, `hmac_secret` is checked when set, `tls_required = true` still demands TLS on non-loopback binds, and the default bind is loopback. `blocked_commands` is still enforced. | Only to keep the old restriction: set `allowed_commands = ["echo"]` | | WASM plugins off by default | Set `[plugins] enabled = true` and restart only after reviewing each plugin; install or update with `wasm_plugins_manage` and explicit `grant_permissions` to write `plugin-trust.json` beside `config.toml`. The configuration directory and `plugin-cache/` must be outside the workspace. A `.prx-managed` marker grants no trust. | To use WASM plugins | | Plugin outbound requests | An empty `http_allowlist` now denies every URL. Use URL patterns such as `https://api.example.com/*`, not string prefixes such as `https://api.example.com*`. The SSRF guard still refuses private, loopback and other unsafe destinations. See [plugin trust and networking](plugin-developer-guide.md). | For plugins needing outbound HTTP | | Workspace command hooks default off | Set `[security] workspace_hooks = "on"` only after reviewing workspace commands. Remove non-null `cwd` from `hooks.json`: the whole candidate file is refused. Commands now start with a cleared environment in the dedicated directory beside `config.toml`; use explicit paths and allowed `env` entries. See [workspace command hooks](configuration.md#workspace-command-hooks). | To run workspace command hooks | diff --git a/docs/remote-nodes.md b/docs/remote-nodes.md index d2c0573f7..decb5ba51 100644 --- a/docs/remote-nodes.md +++ b/docs/remote-nodes.md @@ -46,7 +46,7 @@ exec_timeout_ms = 15000 max_output_bytes = 1048576 max_concurrent_tasks = 8 task_result_ttl_ms = 3600000 -allowed_commands = ["echo"] +# allowed_commands = ["echo"] # unset or empty: any command from an authenticated caller blocked_commands = [] tls_required = true tls_cert = "/etc/prx-node/tls.crt" @@ -91,7 +91,7 @@ addresses are pinned into a no-proxy client, and redirects are not followed. - Bearer authentication is mandatory; optional HMAC signing adds request integrity and timestamp freshness. - Non-loopback listeners require valid TLS material by default. -- Command allowlist and blocklist checks apply before process creation. +- Command allowlist and blocklist checks apply before process creation. With no allowlist configured (the default) any command from an authenticated caller is allowed; the blocklist still applies. - Timeout and cancellation terminate and reap the child process. - Command output, file payloads, RPC bodies, mutation replays, concurrent async tasks, and completed task retention are bounded. diff --git a/src/config/manage/plan.rs b/src/config/manage/plan.rs index 8860aeae2..da2c4177b 100644 --- a/src/config/manage/plan.rs +++ b/src/config/manage/plan.rs @@ -1057,7 +1057,7 @@ fn exposure_and_execution_widenings(before: &Config, after: &Config, reasons: &m ); let (old_server, new_server) = (&before.nodes.server, &after.nodes.server); push( - adds_entries(&old_server.allowed_commands, &new_server.allowed_commands), + allowlist_widened(&old_server.allowed_commands, &new_server.allowed_commands), "nodes.server.allowed_commands", ); push( @@ -1178,6 +1178,16 @@ fn adds_entries(before: &[String], after: &[String]) -> bool { after.iter().any(|entry| !before.contains(entry)) } +/// Whether a node command allowlist became wider. An empty list or a `"*"` +/// entry allows any command, so it is the widest state. +fn allowlist_widened(before: &[String], after: &[String]) -> bool { + let allows_any = |list: &[String]| list.is_empty() || list.iter().any(|entry| entry == "*"); + if allows_any(before) { + return false; + } + allows_any(after) || adds_entries(before, after) +} + /// Whether `before` holds an entry `after` dropped. fn drops_entries(before: &[String], after: &[String]) -> bool { adds_entries(after, before) @@ -3155,7 +3165,7 @@ mod tests { ), ( "a node command allowed", - |_| {}, + |c| c.nodes.server.allowed_commands = strings(&["echo"]), |c| c.nodes.server.allowed_commands.push("sh".into()), Some("nodes.server.allowed_commands"), ), diff --git a/src/config/schema/nodes.rs b/src/config/schema/nodes.rs index 6f4b179b5..7259b6939 100644 --- a/src/config/schema/nodes.rs +++ b/src/config/schema/nodes.rs @@ -86,10 +86,9 @@ pub struct NodeServerConfig { /// TTL for completed task results in milliseconds. #[serde(default = "default_node_server_task_result_ttl_ms")] pub task_result_ttl_ms: u64, - /// Command allowlist matched on first token. - /// - /// In restricted mode this list is required unless explicitly set to `["*"]`. - #[serde(default = "default_node_server_allowed_commands")] + /// Command allowlist matched on first token. Default: empty, which allows any + /// command from an authenticated caller; `["*"]` means the same. + #[serde(default)] pub allowed_commands: Vec, /// Command denylist matched on first token. Always enforced. #[serde(default, alias = "command_blacklist")] @@ -131,10 +130,6 @@ pub(super) const fn default_node_server_task_result_ttl_ms() -> u64 { 3_600_000 } -pub(super) fn default_node_server_allowed_commands() -> Vec { - vec!["echo".to_string()] -} - pub(super) const fn default_node_server_tls_required() -> bool { true } @@ -150,7 +145,7 @@ impl Default for NodeServerConfig { max_output_bytes: default_node_server_max_output_bytes(), max_concurrent_tasks: default_node_server_max_concurrent_tasks(), task_result_ttl_ms: default_node_server_task_result_ttl_ms(), - allowed_commands: default_node_server_allowed_commands(), + allowed_commands: Vec::new(), blocked_commands: Vec::new(), tls_required: default_node_server_tls_required(), tls_cert: None, diff --git a/src/runtime/child_source/golden_effective_config.json b/src/runtime/child_source/golden_effective_config.json index bc6809f6d..738a6b4f0 100644 --- a/src/runtime/child_source/golden_effective_config.json +++ b/src/runtime/child_source/golden_effective_config.json @@ -1 +1 @@ -{"a2a":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trust_domain":"prx.local","trusted_trust_domains":[]},"agent":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"messaging":{"inbound":true},"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2},"agents":{},"api_key":null,"api_url":null,"auth":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"},"autonomy":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true},"browser":{"allowed_domains":[],"computer_use":{"api_key":null}},"channels_config":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null},"chat":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2},"compliance":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}},"composio":{"api_key":null,"entity_id":"default"},"cost":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{"alpha/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0},"zeta/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0}},"warn_at_percent":80},"cron":{"max_run_history":50},"decision_engine":{"backend":{"circuit_breaker":{"cooldown_secs":60,"failure_threshold":5},"credential_ref":"","endpoint":"","kind":"auto","max_request_bytes":65536,"max_response_bytes":262144,"model":"","pinned_snapshot":"","remote_enabled":false,"timeout_ms":250},"candidates":5,"enabled":false,"latency_budget_ms":500,"max_candidates":12,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"token_ratio_limit":0.3499999940395355},"default_model":"anthropic/claude-sonnet-5","default_provider":"openrouter","default_temperature":0.7,"embedding_routes":[],"gateway":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60},"heartbeat":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."},"http_request":{"max_response_size":1000000,"timeout_secs":30},"identity":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"},"identity_bindings":[],"mcp":{"servers":{}},"mcp_server":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true},"media":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"},"memory":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7},"model_routes":[],"model_settings":{},"multimodal":{"allow_remote_fetch":true,"max_image_size_mb":5,"max_images":4},"nodes":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}},"observability":{"backend":"none","otel_endpoint":null,"otel_service_name":null},"plugins":{"enabled":false},"providers":{"ollama":{"num_ctx":null}},"proxy":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]},"query_classification":{"rules":[]},"reliability":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2},"router":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]},"runtime":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null},"scheduler":{"claim_lease_secs":90,"max_tasks":64},"secrets":{"encrypt":true},"security":{"audit":{"log_path":"audit.log","max_size_mb":100}},"self_system":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24},"sessions_spawn":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null},"skill_rag":{"top_k":32},"skills":{"open_skills_dir":null,"openclaw_skills_dir":null},"skills_lifecycle":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]},"smart_group":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5},"storage":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}},"task_routing":{"default_intent":"simple","rules":[]},"tool_tiering":{"always_exclude":[],"always_include":[],"channel_exclude":[]},"tunnel":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null},"user_policies":[],"web_search":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15},"webhook":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null},"xin":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}} \ No newline at end of file +{"a2a":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trust_domain":"prx.local","trusted_trust_domains":[]},"agent":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"messaging":{"inbound":true},"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2},"agents":{},"api_key":null,"api_url":null,"auth":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"},"autonomy":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true},"browser":{"allowed_domains":[],"computer_use":{"api_key":null}},"channels_config":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null},"chat":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2},"compliance":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}},"composio":{"api_key":null,"entity_id":"default"},"cost":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{"alpha/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0},"zeta/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0}},"warn_at_percent":80},"cron":{"max_run_history":50},"decision_engine":{"backend":{"circuit_breaker":{"cooldown_secs":60,"failure_threshold":5},"credential_ref":"","endpoint":"","kind":"auto","max_request_bytes":65536,"max_response_bytes":262144,"model":"","pinned_snapshot":"","remote_enabled":false,"timeout_ms":250},"candidates":5,"enabled":false,"latency_budget_ms":500,"max_candidates":12,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"token_ratio_limit":0.3499999940395355},"default_model":"anthropic/claude-sonnet-5","default_provider":"openrouter","default_temperature":0.7,"embedding_routes":[],"gateway":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60},"heartbeat":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."},"http_request":{"max_response_size":1000000,"timeout_secs":30},"identity":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"},"identity_bindings":[],"mcp":{"servers":{}},"mcp_server":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true},"media":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"},"memory":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7},"model_routes":[],"model_settings":{},"multimodal":{"allow_remote_fetch":true,"max_image_size_mb":5,"max_images":4},"nodes":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":[],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}},"observability":{"backend":"none","otel_endpoint":null,"otel_service_name":null},"plugins":{"enabled":false},"providers":{"ollama":{"num_ctx":null}},"proxy":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]},"query_classification":{"rules":[]},"reliability":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2},"router":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]},"runtime":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null},"scheduler":{"claim_lease_secs":90,"max_tasks":64},"secrets":{"encrypt":true},"security":{"audit":{"log_path":"audit.log","max_size_mb":100}},"self_system":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24},"sessions_spawn":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null},"skill_rag":{"top_k":32},"skills":{"open_skills_dir":null,"openclaw_skills_dir":null},"skills_lifecycle":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]},"smart_group":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5},"storage":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}},"task_routing":{"default_intent":"simple","rules":[]},"tool_tiering":{"always_exclude":[],"always_include":[],"channel_exclude":[]},"tunnel":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null},"user_policies":[],"web_search":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15},"webhook":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null},"xin":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}} \ No newline at end of file diff --git a/tests/fixtures/config-schema.json b/tests/fixtures/config-schema.json index d5fd921ee..7c34f0d35 100644 --- a/tests/fixtures/config-schema.json +++ b/tests/fixtures/config-schema.json @@ -1 +1 @@ -{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Config","description":"Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).","type":"object","properties":{"a2a":{"description":"Agent-to-Agent compatibility configuration (`[a2a]`).","$ref":"#/$defs/A2aConfig","default":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trusted_trust_domains":[],"trust_domain":"prx.local"}},"agent":{"description":"Agent orchestration settings (`[agent]`).","$ref":"#/$defs/AgentConfig","default":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2,"messaging":{"inbound":true}}},"agents":{"description":"Delegate agent configurations for multi-agent workflows.","type":"object","additionalProperties":{"$ref":"#/$defs/DelegateAgentConfig"},"default":{}},"api_key":{"description":"API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.","type":["string","null"],"default":null},"api_url":{"description":"Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)","type":["string","null"],"default":null},"auth":{"description":"Auth profile and external credential import settings (`[auth]`).","$ref":"#/$defs/AuthConfig","default":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"}},"autonomy":{"description":"Autonomy and security policy configuration (`[autonomy]`).","$ref":"#/$defs/AutonomyConfig","default":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true}},"browser":{"description":"Browser automation configuration (`[browser]`).","$ref":"#/$defs/BrowserConfig","default":{"allowed_domains":[],"computer_use":{"api_key":null}}},"channels_config":{"description":"Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).","$ref":"#/$defs/ChannelsConfig","default":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null}},"chat":{"description":"Interactive chat UI configuration (`[chat]`).","$ref":"#/$defs/ChatConfig","default":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2}},"compliance":{"description":"Operator-owned compliance controls (`[compliance]`).","$ref":"#/$defs/ComplianceConfig","default":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}},"composio":{"description":"Composio managed OAuth tools integration (`[composio]`).","$ref":"#/$defs/ComposioConfig","default":{"api_key":null,"entity_id":"default"}},"cost":{"description":"Cost tracking and budget enforcement configuration (`[cost]`).","$ref":"#/$defs/CostConfig","default":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{},"warn_at_percent":80}},"cron":{"description":"Cron job configuration (`[cron]`).","$ref":"#/$defs/CronConfig","default":{"max_run_history":50}},"decision_engine":{"description":"Optional advisory decision engine, disabled by default.","$ref":"#/$defs/DecisionEngineConfig","default":{"candidates":5,"enabled":false,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"latency_budget_ms":500,"max_candidates":12,"token_ratio_limit":0.3499999940395355}},"default_model":{"description":"Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.","type":["string","null"]},"default_provider":{"description":"Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.","type":["string","null"]},"default_temperature":{"description":"Default model temperature (0.0–2.0). Default: `0.7`.","type":"number","format":"double","default":0.7},"embedding_routes":{"description":"Embedding routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/EmbeddingRouteConfig"}},"gateway":{"description":"Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).","$ref":"#/$defs/GatewayConfig","default":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60}},"heartbeat":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]`).","$ref":"#/$defs/HeartbeatConfig","default":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."}},"http_request":{"description":"HTTP request tool configuration (`[http_request]`).","$ref":"#/$defs/HttpRequestConfig","default":{"max_response_size":1000000,"timeout_secs":30}},"identity":{"description":"Identity format configuration: OpenClaw or AIEOS (`[identity]`).","$ref":"#/$defs/IdentityConfig","default":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"}},"identity_bindings":{"description":"Static identity bindings loaded at startup (`[[identity_bindings]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/IdentityBindingConfig"}},"mcp":{"description":"Secrets encryption configuration (`[secrets]`).","$ref":"#/$defs/McpConfig","default":{"servers":{}}},"mcp_server":{"description":"MCP server compatibility configuration (`[mcp_server]`).","$ref":"#/$defs/McpServerRuntimeConfig","default":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true}},"media":{"description":"Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.","$ref":"#/$defs/MediaConfig","default":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"}},"memory":{"description":"Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).","$ref":"#/$defs/MemoryConfig","default":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7}},"model_routes":{"description":"Model routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/ModelRouteConfig"}},"model_settings":{"description":"Catalog model levels and explicit parameters, keyed by canonical release ID.","type":"object","additionalProperties":{"$ref":"#/$defs/ModelSettings"},"default":{}},"multimodal":{"description":"Multimodal (image) handling configuration (`[multimodal]`).","$ref":"#/$defs/MultimodalConfig","default":{"allow_remote_fetch":true,"max_image_size_mb":5,"max_images":4}},"nodes":{"description":"Remote node proxy configuration (`[nodes]`).","$ref":"#/$defs/NodesConfig","default":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}},"observability":{"description":"Observability backend configuration (`[observability]`).","$ref":"#/$defs/ObservabilityConfig","default":{"backend":"none","otel_endpoint":null,"otel_service_name":null}},"plugins":{"description":"WASM plugin runtime switch (`[plugins]`), off by default.","$ref":"#/$defs/PluginsConfig","default":{"enabled":false}},"providers":{"description":"Provider-specific runtime options (`[providers.]`).","$ref":"#/$defs/ProvidersConfig","default":{"ollama":{"num_ctx":null}}},"proxy":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).","$ref":"#/$defs/ProxyConfig","default":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]}},"query_classification":{"description":"Automatic query classification — maps user messages to model hints.","$ref":"#/$defs/QueryClassificationConfig","default":{"rules":[]}},"reliability":{"description":"Reliability settings: retries, fallback providers, backoff (`[reliability]`).","$ref":"#/$defs/ReliabilityConfig","default":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2}},"router":{"description":"Heuristic LLM router configuration (`[router]`).","$ref":"#/$defs/RouterConfig","default":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]}},"runtime":{"description":"Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.","$ref":"#/$defs/RuntimeConfig","default":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null}},"scheduler":{"description":"Scheduler configuration for periodic task execution (`[scheduler]`).","$ref":"#/$defs/SchedulerConfig","default":{"claim_lease_secs":90,"max_tasks":64}},"secrets":{"$ref":"#/$defs/SecretsConfig","default":{"encrypt":true}},"security":{"description":"Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).","$ref":"#/$defs/SecurityConfig","default":{"audit":{"log_path":"audit.log","max_size_mb":100}}},"self_system":{"description":"Self-system experimental automation controls (`[self_system]`).","$ref":"#/$defs/SelfSystemConfig","default":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24}},"sessions_spawn":{"description":"Session spawning configuration (`[sessions_spawn]`).","$ref":"#/$defs/SessionsSpawnConfig","default":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null}},"skill_rag":{"description":"Dynamic skill retrieval settings (`[skill_rag]`).","$ref":"#/$defs/SkillRagConfig","default":{"top_k":32}},"skills":{"description":"Skills loading and community repository behavior (`[skills]`).","$ref":"#/$defs/SkillsConfig","default":{"open_skills_dir":null,"openclaw_skills_dir":null}},"skills_lifecycle":{"description":"Skill lifecycle (`[skills_lifecycle]`), off by default.","$ref":"#/$defs/SkillsLifecycleConfig","default":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]}},"smart_group":{"description":"Smart group-reply pre-gate configuration (`[smart_group]`).","$ref":"#/$defs/SmartGroupConfig","default":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5}},"storage":{"description":"Persistent storage provider configuration (`[storage]`).","$ref":"#/$defs/StorageConfig","default":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"task_routing":{"description":"Task routing configuration — classifies work by intent before the main agent loop.","$ref":"#/$defs/TaskRoutingConfig","default":{"default_intent":"simple","rules":[]}},"tool_tiering":{"description":"Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).","$ref":"#/$defs/ToolTieringConfig","default":{"always_exclude":[],"always_include":[],"channel_exclude":[]}},"tunnel":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]`).","$ref":"#/$defs/TunnelConfig","default":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null}},"user_policies":{"description":"Static user policy records loaded at startup (`[[user_policies]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/UserPolicyConfig"}},"web_search":{"description":"Web search tool configuration (`[web_search]`).","$ref":"#/$defs/WebSearchConfig","default":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15}},"webhook":{"description":"Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).","$ref":"#/$defs/MemoryWebhookConfig","default":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null}},"xin":{"description":"Xin autonomous task engine configuration (`[xin]`).","$ref":"#/$defs/XinConfig","default":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}}},"$defs":{"A2aConfig":{"type":"object","properties":{"agent_id":{"description":"Stable PRX agent identifier advertised to peers.","type":"string","default":"prx-default"},"allowed_peer_issuers":{"description":"Accepted external peer issuers.","type":"array","default":[],"items":{"type":"string"}},"bind":{"description":"Advertised bind address.","type":"string","default":"127.0.0.1:16832"},"card_jwks_uri":{"description":"Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.","type":["string","null"],"default":null},"card_signing_key_path":{"description":"On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).","type":["string","null"],"default":null},"card_ttl_seconds":{"description":"Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.","type":"integer","format":"uint64","default":3600,"minimum":0},"discovery_advertised":{"description":"Whether to advertise into an external A2A registry.","type":"boolean","default":false},"handoff_nonce_ttl_seconds":{"description":"Replay window for future handoff delegation tokens.","type":"integer","format":"uint64","default":3600,"minimum":0},"messaging_enabled":{"description":"Enable the dedicated pinned mTLS messaging listener.","type":"boolean","default":false},"peers":{"type":"object","additionalProperties":{"$ref":"#/$defs/A2aPeer"},"default":{}},"spiffe_id":{"description":"Local SPIFFE-style identifier placeholder.","type":"string","default":"spiffe://prx-local/agent/prx-default"},"spiffe_strict_validation":{"description":"When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.","type":"boolean","default":false},"spiffe_trust_bundle_pem":{"description":"Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).","type":["string","null"],"default":null},"trusted_trust_domains":{"description":"Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).","type":"array","default":[],"items":{"type":"string"}},"trust_domain":{"description":"SPIFFE trust domain for new instance identities.","type":"string","default":"prx.local"}}},"A2aPeer":{"description":"Explicit pinned identity and local recipient grant.","type":"object","properties":{"spiffe_id":{"type":"string"},"fingerprints":{"type":"array","items":{"type":"string"}},"address":{"type":"string"},"owner":{"type":"string"},"sessions":{"type":"array","default":["*"],"items":{"type":"string"}},"agents":{"type":"array","default":["*"],"items":{"type":"string"}}},"required":["spiffe_id","fingerprints","address","owner"],"additionalProperties":false},"AgentCompactionConfig":{"description":"Agent context compaction configuration (`[agent.compaction]`).","type":"object","properties":{"keep_recent_messages":{"description":"Number of recent non-system messages to keep after compaction.","type":"integer","format":"uint","default":12,"minimum":0},"max_context_tokens":{"description":"Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.","type":"integer","format":"uint","default":128000,"minimum":0},"memory_flush":{"description":"Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.","type":"boolean","default":true},"mode":{"description":"Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).","$ref":"#/$defs/AgentCompactionMode","default":"switch"},"os_paging":{"description":"Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.","$ref":"#/$defs/OsPagingConfig","default":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"}},"reserve_tokens":{"description":"Tokens reserved for the next model response.","type":"integer","format":"uint","default":4096,"minimum":0}}},"AgentCompactionMode":{"description":"Compaction mode for long conversation contexts.","oneOf":[{"description":"Disable proactive compaction.","type":"string","const":"off"},{"description":"Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.","type":"string","const":"switch"},{"description":"Conservative compaction that prefers summary replacement.","type":"string","const":"safeguard"},{"description":"Aggressive truncation mode for tighter contexts.","type":"string","const":"aggressive"}]},"AgentConfig":{"description":"Agent orchestration configuration (`[agent]` section).","type":"object","properties":{"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"compact_context":{"description":"When true: bootstrap_max_chars=6000. Use for 13B or smaller models.","type":"boolean","default":false},"compaction":{"description":"Context compaction controls (`[agent.compaction]`).","$ref":"#/$defs/AgentCompactionConfig","default":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096}},"low_priority_tools":{"description":"Tool names treated as low-priority when `priority_scheduling_enabled = true`.","type":"array","default":["sessions_spawn","delegate"],"items":{"type":"string"}},"priority_scheduling_enabled":{"description":"Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.","type":"boolean","default":false},"read_only_tool_concurrency_window":{"description":"Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.","type":"integer","format":"uint","default":2,"minimum":0},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}}},"AgentLimits":{"description":"Optional admission limits for rf-started turns of a named agent.","type":"object","properties":{"max_concurrent_turns":{"type":["integer","null"],"format":"uint32","minimum":0},"max_cost_per_day_cents":{"type":["integer","null"],"format":"uint64","minimum":0}},"additionalProperties":false},"AuditConfig":{"description":"Audit logging configuration","type":"object","properties":{"log_path":{"description":"Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).","type":"string","default":"audit.log"},"max_size_mb":{"description":"Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).","type":"integer","format":"uint32","default":100,"minimum":0}}},"AuthConfig":{"description":"Authentication and external credential import configuration (`[auth]` section).","type":"object","properties":{"codex_auth_json_auto_import":{"description":"Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.","type":"boolean","default":false},"codex_auth_json_path":{"description":"Source path for Codex CLI auth.json import.","type":"string","default":"~/.codex/auth.json"}}},"AutonomyConfig":{"type":"object","properties":{"acknowledge_unrestricted_profile":{"description":"Operator acknowledgement for an intentionally unrestricted profile.\nRetained for existing configs; it no longer changes any output or policy behavior.","type":"boolean","default":false},"forbidden_paths":{"description":"Explicit path denylist. Default includes system-critical paths.\n\nFails closed: omitting the key keeps the built-in list rather than\nemptying it, so a partial `[autonomy]` section never removes the\ndenylist.","type":"array","default":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"items":{"type":"string"}},"level":{"description":"Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).","$ref":"#/$defs/AutonomyLevel","default":"full"},"max_cost_per_day_cents":{"description":"Maximum cost per day in cents per policy. Default: unset (no ceiling).","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"scopes":{"description":"Scope-based tool access control: per-user/channel/chat-type allow/deny rules.","$ref":"#/$defs/ScopeConfig","default":{"assign_owners":[],"default":"allow","rules":[]}},"workspace_only":{"description":"Restrict file writes and command paths to the workspace directory. Default: `true`.\n\nFails closed: a `[autonomy]` section that omits this key keeps the\nworkspace restriction on, so a partial section can never widen the\nfilesystem reach by accident.","type":"boolean","default":true}}},"AutonomyLevel":{"description":"How much autonomy the agent has","oneOf":[{"description":"Read-only: can observe but not act","type":"string","const":"readonly"},{"description":"Supervised: acts but requires approval for risky operations","type":"string","const":"supervised"},{"description":"Full: autonomous execution within policy bounds","type":"string","const":"full"}]},"BackendSelection":{"description":"Which decision backend runs: `auto` (the factory's order) or one kind.","type":"string"},"BrowserComputerUseConfig":{"description":"Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.","type":"object","properties":{"api_key":{"description":"Optional bearer token (retained only for config secret handling).","type":["string","null"],"default":null}}},"BrowserConfig":{"description":"Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.","type":"object","properties":{"allowed_domains":{"description":"Allowed domains for `web_fetch` (exact or subdomain match).","type":"array","default":[],"items":{"type":"string"}},"computer_use":{"description":"Computer-use sidecar config (retained only for `api_key` secret handling).","$ref":"#/$defs/BrowserComputerUseConfig","default":{"api_key":null}}}},"ChannelsConfig":{"description":"Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.","type":"object","properties":{"cli":{"description":"Enable the CLI interactive channel. Default: `true`.","type":"boolean","default":true},"dingtalk":{"description":"DingTalk channel configuration.","anyOf":[{"$ref":"#/$defs/DingTalkConfig"},{"type":"null"}]},"discord":{"description":"Discord bot channel configuration.","anyOf":[{"$ref":"#/$defs/DiscordConfig"},{"type":"null"}]},"email":{"description":"Email channel configuration.","anyOf":[{"$ref":"#/$defs/EmailConfig"},{"type":"null"}]},"imessage":{"description":"iMessage channel configuration (macOS only).","anyOf":[{"$ref":"#/$defs/IMessageConfig"},{"type":"null"}]},"irc":{"description":"IRC channel configuration.","anyOf":[{"$ref":"#/$defs/IrcConfig"},{"type":"null"}]},"lark":{"description":"Lark/Feishu channel configuration.","anyOf":[{"$ref":"#/$defs/LarkConfig"},{"type":"null"}]},"linq":{"description":"Linq Partner API channel configuration.","anyOf":[{"$ref":"#/$defs/LinqConfig"},{"type":"null"}]},"mattermost":{"description":"Mattermost bot channel configuration.","anyOf":[{"$ref":"#/$defs/MattermostConfig"},{"type":"null"}]},"nextcloud_talk":{"description":"Nextcloud Talk bot channel configuration.","anyOf":[{"$ref":"#/$defs/NextcloudTalkConfig"},{"type":"null"}]},"qq":{"description":"QQ Official Bot channel configuration.","anyOf":[{"$ref":"#/$defs/QQConfig"},{"type":"null"}]},"ramflux":{"description":"Local ramflux agent-host bridge.","anyOf":[{"$ref":"#/$defs/RamfluxConfig"},{"type":"null"}],"default":null},"signal":{"description":"Signal channel configuration.","anyOf":[{"$ref":"#/$defs/SignalConfig"},{"type":"null"}]},"slack":{"description":"Slack bot channel configuration.","anyOf":[{"$ref":"#/$defs/SlackConfig"},{"type":"null"}]},"telegram":{"description":"Telegram bot channel configuration.","anyOf":[{"$ref":"#/$defs/TelegramConfig"},{"type":"null"}]},"wacli":{"description":"wacli JSON-RPC daemon channel configuration.","anyOf":[{"$ref":"#/$defs/WacliConfig"},{"type":"null"}],"default":null},"webhook":{"description":"Webhook channel configuration.","anyOf":[{"$ref":"#/$defs/WebhookConfig"},{"type":"null"}]},"whatsapp":{"description":"WhatsApp channel configuration (Cloud API or Web mode).","anyOf":[{"$ref":"#/$defs/WhatsAppConfig"},{"type":"null"}]}}},"ChatConfig":{"description":"Interactive chat configuration (`[chat]`).","type":"object","properties":{"daemon":{"description":"How this chat process reaches the daemon it borrows channels from.","$ref":"#/$defs/ChatDaemonConfig","default":{"token":"","url":""}},"max_concurrent_visible_turns":{"description":"Maximum concurrent visible provider turns in the TUI Redux driver.","type":"integer","format":"uint","default":2,"minimum":0}}},"ChatDaemonConfig":{"description":"Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.","type":"object","properties":{"token":{"description":"Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.","type":"string","default":""},"url":{"description":"Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.","type":"string","default":""}}},"CircuitBreakerConfig":{"description":"The per-backend circuit breaker.","type":"object","properties":{"cooldown_secs":{"description":"Seconds the breaker stays open (1 to 3600).","type":"integer","format":"uint32","default":60,"minimum":0},"failure_threshold":{"description":"Consecutive failures before the breaker opens (1 to 100).","type":"integer","format":"uint32","default":5,"minimum":0}}},"ClassificationRule":{"description":"A single classification rule mapping message patterns to a model hint.","type":"object","properties":{"hint":{"description":"Must match a `[[model_routes]]` hint value.","type":"string"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"max_length":{"description":"Only match if message length <= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"min_length":{"description":"Only match if message length >= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"patterns":{"description":"Case-sensitive literal matches (for \"```\", \"fn \", etc.).","type":"array","default":[],"items":{"type":"string"}},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0}},"required":["hint"]},"CloudflareTunnelConfig":{"type":"object","properties":{"token":{"description":"Cloudflare Tunnel token (from Zero Trust dashboard)","type":"string"}},"required":["token"]},"ComplianceConfig":{"type":"object","properties":{"eu_ai_act":{"$ref":"#/$defs/EuAiActComplianceConfig","default":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null}},"interaction_notice":{"$ref":"#/$defs/InteractionNoticeConfig","default":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}}},"ComposioConfig":{"description":"Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.","type":"object","properties":{"api_key":{"description":"Composio API key (stored encrypted when secrets.encrypt = true)","type":["string","null"],"default":null},"entity_id":{"description":"Default entity ID for multi-user setups","type":"string","default":"default"}}},"CostConfig":{"description":"Cost tracking and budget enforcement configuration (`[cost]` section).","type":"object","properties":{"allow_override":{"description":"Allow requests to exceed budget with --override flag (default: false)","type":"boolean","default":false},"daily_limit_usd":{"description":"Daily spending limit in USD (default: unset, no limit; 0 refuses every priced turn)","type":["number","null"],"format":"double","default":null},"monthly_limit_usd":{"description":"Monthly spending limit in USD (default: unset, no limit)","type":["number","null"],"format":"double","default":null},"prices":{"description":"Per-model pricing (USD per 1M tokens)","type":"object","additionalProperties":{"$ref":"#/$defs/ModelPricing"},"default":{}},"warn_at_percent":{"description":"Warn when spending reaches this percentage of a configured limit (default: 80)","type":"integer","format":"uint8","default":80,"maximum":255,"minimum":0}}},"CredentialRefSetting":{"description":"Which credential a decision backend uses. A reference, never a secret.","type":"string"},"CronConfig":{"description":"Cron job configuration (`[cron]` section).","type":"object","properties":{"max_run_history":{"description":"Maximum number of historical cron run records to retain. Default: `50`.","type":"integer","format":"uint32","default":50,"minimum":0}}},"CustomTunnelConfig":{"type":"object","properties":{"health_url":{"description":"Optional URL to check tunnel health","type":["string","null"]},"start_command":{"description":"Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"","type":"string"},"url_pattern":{"description":"Optional regex to extract public URL from command stdout","type":["string","null"]}},"required":["start_command"]},"DecisionBackendConfig":{"description":"The decision backend (`[decision_engine.backend]`).","type":"object","properties":{"circuit_breaker":{"description":"The circuit breaker.","$ref":"#/$defs/CircuitBreakerConfig","default":{"cooldown_secs":60,"failure_threshold":5}},"credential_ref":{"description":"The credential reference: `\"\"`, `\"none\"` or `cred-`.","$ref":"#/$defs/CredentialRefSetting","default":""},"endpoint":{"description":"The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.","type":"string","default":""},"kind":{"description":"`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).","$ref":"#/$defs/BackendSelection","default":"auto"},"max_request_bytes":{"description":"Largest request body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":65536,"minimum":0},"max_response_bytes":{"description":"Largest response body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":262144,"minimum":0},"model":{"description":"The model the endpoint serves; one exact version for a hosted\nservice.","type":"string","default":""},"pinned_snapshot":{"description":"The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.","type":"string"},"remote_enabled":{"description":"Whether decision state may leave this machine. Default `false`.","type":"boolean","default":false},"timeout_ms":{"description":"Transport timeout (10 ms up to the extra latency budget).","type":"integer","format":"uint32","default":250,"minimum":0}}},"DecisionEngineConfig":{"type":"object","properties":{"backend":{"anyOf":[{"$ref":"#/$defs/DecisionBackendConfig"},{"type":"null"}]},"candidates":{"type":"integer","format":"uint32","default":5,"minimum":0},"enabled":{"type":"boolean","default":false},"mode":{"$ref":"#/$defs/DecisionMode","default":"pre"},"observe_queue":{"type":"integer","format":"uint32","default":64,"minimum":0},"prompt_budget_tokens":{"type":"integer","format":"uint32","default":300,"minimum":0},"telemetry_cap":{"type":"integer","format":"uint32","default":1000,"minimum":0},"timeout_ms":{"type":"integer","format":"uint32","default":1500,"minimum":0},"latency_budget_ms":{"description":"The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.","type":"integer","format":"uint64","default":500,"minimum":0},"token_ratio_limit":{"description":"Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).","type":"number","format":"float","default":0.3499999940395355},"max_candidates":{"description":"The most candidates a turn considers (1 to 32).","type":"integer","format":"uint8","default":12,"maximum":255,"minimum":0}}},"DecisionMode":{"type":"string","enum":["pre","post","both"]},"DeclarationOfConformityConfig":{"type":"object","properties":{"applicable_union_law":{"type":"array","default":[],"items":{"type":"string"}},"artifact_path":{"type":["string","null"],"default":null},"artifact_version":{"type":["string","null"],"default":null},"conformity_assessment_procedure":{"type":["string","null"],"default":null},"conformity_statement":{"type":["string","null"],"default":null},"harmonised_standards":{"type":"array","default":[],"items":{"type":"string"}},"issue_date":{"type":["string","null"],"default":null},"issue_place":{"type":["string","null"],"default":null},"notified_body_certificate":{"type":["string","null"],"default":null},"notified_body_identification_number":{"type":["string","null"],"default":null},"notified_body_name":{"type":["string","null"],"default":null},"personal_data_compliance_statement":{"type":["string","null"],"default":null},"processes_personal_data":{"type":"boolean","default":false},"provider_address":{"type":["string","null"],"default":null},"provider_name":{"type":["string","null"],"default":null},"signer_function":{"type":["string","null"],"default":null},"signer_name":{"type":["string","null"],"default":null},"signer_on_behalf_of":{"type":["string","null"],"default":null},"sole_responsibility_statement":{"type":["string","null"],"default":null},"standards_not_applicable_reason":{"type":["string","null"],"default":null},"system_name":{"type":["string","null"],"default":null},"system_reference":{"type":["string","null"],"default":null},"system_type":{"type":["string","null"],"default":null}}},"DelegateAgentConfig":{"description":"Configuration for a delegate sub-agent used by the `delegate` tool.","type":"object","properties":{"agentic":{"description":"Agentic sub-agent mode (multi-turn tool-call loop). Default true; an\nexplicit `false` makes the agent answer-only with no tools.","type":"boolean","default":true},"allowed_tools":{"description":"Allowlist of tool names available to the sub-agent in agentic mode.\nEmpty or omitted means all tools, the same as `[\"*\"]`.","type":"array","default":[],"items":{"type":"string"}},"api_key":{"description":"Optional API key override","type":["string","null"],"default":null},"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"autonomy":{"description":"The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.","anyOf":[{"$ref":"#/$defs/AutonomyLevel"},{"type":"null"}]},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"enabled":{"description":"Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.","type":"boolean","default":true},"identity_dir":{"description":"Optional identity files directory relative to workspace root.","type":["string","null"],"default":null},"limits":{"$ref":"#/$defs/AgentLimits","default":{"max_concurrent_turns":null,"max_cost_per_day_cents":null}},"max_depth":{"description":"Max recursion depth for nested delegation","type":"integer","format":"uint32","default":8,"minimum":0},"memory_scope":{"description":"Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".","type":["string","null"],"default":null},"model":{"description":"Model name","type":"string"},"provider":{"description":"Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")","type":"string"},"spawn_enabled":{"description":"Whether this agent is allowed to be targeted by sessions_spawn (default: true).","type":["boolean","null"],"default":null},"system_prompt":{"description":"Optional system prompt for the sub-agent","type":["string","null"],"default":null},"temperature":{"description":"Temperature override","type":["number","null"],"format":"double","default":null},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}},"required":["provider","model"]},"DingTalkConfig":{"description":"DingTalk configuration for Stream Mode messaging","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"client_id":{"description":"Client ID (AppKey) from DingTalk developer console","type":"string"},"client_secret":{"description":"Client Secret (AppSecret) from DingTalk developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["client_id","client_secret"]},"DiscordConfig":{"description":"Discord bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Discord user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Discord bot token (from Discord Developer Portal).","type":"string"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"guild_id":{"description":"Optional guild (server) ID to restrict the bot to a single guild.","type":["string","null"]},"listen_to_bots":{"description":"When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.","type":"boolean","default":false}},"required":["bot_token"]},"DmPolicy":{"description":"Policy for direct-message handling.","oneOf":[{"description":"Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).","type":"string","const":"pairing"},{"description":"Accept only senders listed in `allowed_from`.","type":"string","const":"allowlist"},{"description":"Accept any direct sender.","type":"string","const":"open"},{"description":"Ignore direct messages.","type":"string","const":"disabled"}]},"DockerRuntimeConfig":{"description":"Docker runtime configuration (`[runtime.docker]` section).","type":"object","properties":{"allowed_workspace_roots":{"description":"Optional workspace root allowlist for Docker mount validation.","type":"array","default":[],"items":{"type":"string"}},"cpu_limit":{"description":"Optional CPU limit (`None` = no explicit limit).","type":["number","null"],"format":"double","default":1.0},"image":{"description":"Runtime image used to execute shell commands.","type":"string","default":"alpine:3.20"},"memory_limit_mb":{"description":"Optional memory limit in MB (`None` = no explicit limit).","type":["integer","null"],"format":"uint64","default":512,"minimum":0},"mount_workspace":{"description":"Mount configured workspace into `/workspace`.","type":"boolean","default":true},"network":{"description":"Docker network mode (`none`, `bridge`, etc.).","type":"string","default":"none"},"read_only_rootfs":{"description":"Mount root filesystem as read-only.","type":"boolean","default":true}}},"EmailConfig":{"description":"Email channel configuration","type":"object","properties":{"allowed_senders":{"description":"Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)","type":"array","default":[],"items":{"type":"string"}},"from_address":{"description":"From address for outgoing emails","type":"string"},"idle_timeout_secs":{"description":"IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes","type":"integer","format":"uint64","default":1740,"minimum":0},"imap_folder":{"description":"IMAP folder to poll (default: INBOX)","type":"string","default":"INBOX"},"imap_host":{"description":"IMAP server hostname","type":"string"},"imap_port":{"description":"IMAP server port (default: 993 for TLS)","type":"integer","format":"uint16","default":993,"maximum":65535,"minimum":0},"password":{"description":"Email password for authentication","type":"string"},"smtp_host":{"description":"SMTP server hostname","type":"string"},"smtp_port":{"description":"SMTP server port (default: 465 for TLS)","type":"integer","format":"uint16","default":465,"maximum":65535,"minimum":0},"smtp_tls":{"description":"Use TLS for SMTP (default: true)","type":"boolean","default":true},"username":{"description":"Email username for authentication","type":"string"}},"required":["imap_host","smtp_host","username","password","from_address"]},"EmbeddingRouteConfig":{"description":"Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"dimensions":{"description":"Optional embedding dimension override for this route","type":["integer","null"],"format":"uint","default":null,"minimum":0},"hint":{"description":"Route hint name (e.g. \"semantic\", \"archive\", \"faq\")","type":"string"},"model":{"description":"Embedding model to use with that provider","type":"string"},"provider":{"description":"Embedding provider (`none`, `openai`, or `custom:`)","type":"string"}},"required":["hint","provider","model"]},"EuAiActClassificationConfig":{"type":"object","properties":{"assessed_at":{"type":["string","null"],"default":null},"owner":{"type":["string","null"],"default":null},"status":{"$ref":"#/$defs/EuAiActRiskClassification","default":"unclassified"}}},"EuAiActComplianceConfig":{"type":"object","properties":{"classification":{"$ref":"#/$defs/EuAiActClassificationConfig","default":{"assessed_at":null,"owner":null,"status":"unclassified"}},"declaration":{"$ref":"#/$defs/DeclarationOfConformityConfig","default":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null}},"incident_store_path":{"type":["string","null"],"default":null}}},"EuAiActRiskClassification":{"type":"string","enum":["unclassified","high_risk","not_high_risk"]},"FitnessConfig":{"description":"Calendar schedule, evidence thresholds, and retention for fitness v2.","type":"object","properties":{"auto_run":{"description":"Run the daily fitness worker in daemon mode.","type":"boolean","default":true},"max_backfill_days":{"description":"Maximum number of closed days recovered after downtime.","type":"integer","format":"uint32","default":7,"minimum":0},"min_coverage":{"description":"Minimum available metric weight required to publish a final score.","type":"number","format":"double","default":0.6},"min_samples":{"description":"Minimum samples required before an evidence-derived subscore is usable.","type":"integer","format":"uint","default":5,"minimum":0},"retention_days":{"description":"Number of daily JSON reports retained on disk.","type":"integer","format":"uint32","default":180,"minimum":0},"run_at":{"description":"Local wall-clock time (`HH:MM`) at which the previous day is scored.","type":"string","default":"00:10"},"timezone":{"description":"IANA timezone used to define closed calendar days.","type":"string","default":"UTC"}}},"GatewayConfig":{"description":"Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.","type":"object","properties":{"allow_public_bind":{"description":"Allow binding to non-localhost without a tunnel (default: false)","type":"boolean","default":false},"api_rate_limit_per_minute":{"description":"Max `/api/*` requests per minute per authenticated token.","type":"integer","format":"uint32","default":60,"minimum":0},"channel_webhook_dedup_ttl_secs":{"description":"How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.","type":"integer","format":"uint64","default":86400,"minimum":0},"host":{"description":"Gateway host (default: 127.0.0.1)","type":"string","default":"127.0.0.1"},"idempotency_max_keys":{"description":"Maximum distinct idempotency keys retained in memory.","type":"integer","format":"uint","default":10000,"minimum":0},"idempotency_ttl_secs":{"description":"TTL for webhook idempotency keys.","type":"integer","format":"uint64","default":300,"minimum":0},"pair_rate_limit_per_minute":{"description":"Max `/pair` requests per minute per client key.","type":"integer","format":"uint32","default":10,"minimum":0},"paired_tokens":{"description":"Paired bearer tokens (managed automatically, not user-edited)","type":"array","default":[],"items":{"type":"string"}},"port":{"description":"Gateway port (default: 16830)","type":"integer","format":"uint16","default":16830,"maximum":65535,"minimum":0},"rate_limit_max_keys":{"description":"Maximum distinct client keys tracked by gateway rate limiter maps.","type":"integer","format":"uint","default":10000,"minimum":0},"require_pairing":{"description":"Require pairing before accepting requests (default: true)","type":"boolean","default":true},"targeted_agents":{"description":"Switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). Default true. While false, any\notherwise-valid named target answers 409 `agent_disabled` and never\nruns as Main.","type":"boolean","default":true},"trust_forwarded_headers":{"description":"Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.","type":"boolean","default":false},"webhook_rate_limit_per_minute":{"description":"Max `/webhook` requests per minute per client key.","type":"integer","format":"uint32","default":60,"minimum":0}}},"GroupPolicy":{"description":"Policy for group-message handling.","oneOf":[{"description":"Accept only groups listed in `group_allow_from`.","type":"string","const":"allowlist"},{"description":"Accept any group.","type":"string","const":"open"},{"description":"Ignore group messages.","type":"string","const":"disabled"}]},"GroupReplyMode":{"description":"How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.","oneOf":[{"description":"Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).","type":"string","const":"off"},{"description":"Reply only when the bot is @-mentioned (legacy `mention_only = true`).","type":"string","const":"mention-only"},{"description":"Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).","type":"string","const":"smart"}]},"HeartbeatConfig":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]` section).","type":"object","properties":{"active_hours":{"description":"Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.","type":"array","default":[8,23],"items":{"type":"integer","format":"uint8","maximum":255,"minimum":0}},"interval_minutes":{"description":"Interval in minutes between heartbeat pings. Default: `30`.","type":"integer","format":"uint32","default":30,"minimum":0},"prompt":{"description":"Prompt used by heartbeat worker when dispatching tasks.","type":"string","default":"Check HEARTBEAT.md and follow instructions."}}},"HttpRequestConfig":{"description":"HTTP request tool configuration (`[http_request]` section).","type":"object","properties":{"max_response_size":{"description":"Maximum response size in bytes (default: 1MB)","type":"integer","format":"uint","default":1000000,"minimum":0},"timeout_secs":{"description":"Request timeout in seconds (default: 30)","type":"integer","format":"uint64","default":30,"minimum":0}}},"IMessageConfig":{"description":"iMessage channel configuration (macOS only).","type":"object","properties":{"allowed_contacts":{"description":"Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.","type":"array","items":{"type":"string"}},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["allowed_contacts"]},"IdentityBindingConfig":{"description":"Startup identity binding entry (`[[identity_bindings]]`).","type":"object","properties":{"channel":{"type":"string"},"channel_account":{"type":"string"},"display_name":{"type":["string","null"],"default":null},"user_id":{"type":"string"}},"required":["user_id","channel","channel_account"]},"IdentityConfig":{"description":"Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.","type":"object","properties":{"aieos_inline":{"description":"Inline AIEOS JSON (alternative to file path)","type":["string","null"],"default":null},"aieos_path":{"description":"Path to AIEOS JSON file (relative to workspace)","type":["string","null"],"default":null},"format":{"description":"Identity format: \"openclaw\" (default) or \"aieos\"","type":"string","default":"openclaw"}}},"InteractionNoticeApplicability":{"type":"string","enum":["required","not_applicable"]},"InteractionNoticeConfig":{"type":"object","properties":{"applicability":{"$ref":"#/$defs/InteractionNoticeApplicability","default":"required"},"exception_owner":{"type":["string","null"],"default":null},"exception_reviewed_at":{"type":["string","null"],"default":null},"text":{"type":"string","default":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers."},"version":{"type":"string","default":"1"}}},"IrcConfig":{"description":"IRC channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed nicknames (case-insensitive) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"channels":{"description":"Channels to join on connect","type":"array","default":[],"items":{"type":"string"}},"mention_only":{"description":"When true, only process channel/group messages that mention the bot.","type":"boolean","default":false},"nickname":{"description":"Bot nickname","type":"string"},"nickserv_password":{"description":"NickServ IDENTIFY password","type":["string","null"]},"port":{"description":"IRC server port (default: 6697 for TLS)","type":"integer","format":"uint16","default":6697,"maximum":65535,"minimum":0},"sasl_password":{"description":"SASL PLAIN password (IRCv3)","type":["string","null"]},"server":{"description":"IRC server hostname","type":"string"},"server_password":{"description":"Server password (for bouncers like ZNC)","type":["string","null"]},"username":{"description":"Username (defaults to nickname if not set)","type":["string","null"]},"verify_tls":{"description":"Verify TLS certificate (default: true)","type":["boolean","null"]}},"required":["server","nickname"]},"LarkConfig":{"description":"Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from Lark/Feishu developer console","type":"string"},"app_secret":{"description":"App Secret from Lark/Feishu developer console","type":"string"},"encrypt_key":{"description":"Encrypt key for webhook message decryption (optional)","type":["string","null"],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"port":{"description":"HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"receive_mode":{"description":"Event receive mode: \"websocket\" (default) or \"webhook\"","$ref":"#/$defs/LarkReceiveMode","default":"websocket"},"use_feishu":{"description":"Whether to use the Feishu (Chinese) endpoint instead of Lark (International)","type":"boolean","default":false},"verification_token":{"description":"Verification token for webhook validation (optional)","type":["string","null"],"default":null}},"required":["app_id","app_secret"]},"LarkReceiveMode":{"description":"How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.","type":"string","enum":["websocket","webhook"]},"LinqConfig":{"type":"object","properties":{"allowed_senders":{"description":"Allowed sender handles (phone numbers) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"api_token":{"description":"Linq Partner API token (Bearer auth)","type":"string"},"from_phone":{"description":"Phone number to send from (E.164 format)","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"signing_secret":{"description":"Webhook signing secret for signature verification","type":["string","null"],"default":null}},"required":["api_token","from_phone"]},"MattermostConfig":{"description":"Mattermost bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Mattermost user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Mattermost bot access token.","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.","type":["boolean","null"],"default":null},"thread_replies":{"description":"When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.","type":["boolean","null"],"default":null},"url":{"description":"Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).","type":"string"}},"required":["url","bot_token"]},"McpConfig":{"type":"object","properties":{"servers":{"description":"Named MCP server definitions","type":"object","additionalProperties":{"$ref":"#/$defs/McpServerConfig"},"default":{}},"workspace_servers":{"description":"Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.","$ref":"#/$defs/WorkspaceMcpServers"}}},"McpServerConfig":{"type":"object","properties":{"allow_tools":{"description":"Optional allow-list of exposed tools (empty = all)","type":"array","default":[],"items":{"type":"string"}},"args":{"description":"Command args for stdio mode","type":"array","default":[],"items":{"type":"string"}},"command":{"description":"Command for stdio mode","type":["string","null"],"default":null},"deny_tools":{"description":"Optional deny-list of exposed tools","type":"array","default":[],"items":{"type":"string"}},"env":{"description":"Environment variables for stdio mode","type":"object","additionalProperties":{"type":"string"},"default":{}},"request_timeout_ms":{"description":"Request timeout in milliseconds","type":"integer","format":"uint64","default":30000,"minimum":0},"startup_timeout_ms":{"description":"Startup timeout in milliseconds","type":"integer","format":"uint64","default":10000,"minimum":0},"tool_name_prefix":{"description":"Prefix used in tool naming and routing","type":"string","default":"mcp"},"transport":{"description":"Transport type: stdio or http","$ref":"#/$defs/McpTransport","default":"stdio"},"url":{"description":"URL for HTTP mode (streamable HTTP endpoint)","type":["string","null"],"default":null},"working_dir":{"description":"Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).","type":["string","null"]}}},"McpServerRuntimeConfig":{"type":"object","properties":{"allowed_origins":{"description":"Allowed browser origins for future streamable HTTP clients.","type":"array","default":["claude.ai","openai.com","localhost"],"items":{"type":"string"}},"bind":{"description":"Advertised bind address. The gateway may still be started with a CLI port override.","type":"string","default":"127.0.0.1:16831"},"exposed_tools":{"description":"Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.","type":"array","default":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"items":{"type":"string"}},"jwt_algorithms":{"description":"Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.","type":"array","default":["RS256"],"items":{"type":"string"}},"jwt_audience":{"description":"Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.","type":["string","null"],"default":null},"jwt_issuer":{"description":"Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.","type":["string","null"],"default":null},"jwt_jwks":{"description":"Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.","type":["string","null"],"default":null},"jwt_jwks_cache_ttl_secs":{"description":"Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.","type":"integer","format":"uint64","default":300,"minimum":0},"jwt_jwks_uri":{"description":"Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.","type":["string","null"],"default":null},"jwt_public_key_pem":{"description":"PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.","type":["string","null"],"default":null},"rate_limit_rps":{"description":"Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.","type":"integer","format":"uint32","default":10,"minimum":0},"require_auth":{"description":"Require an authenticated external identity for mutating calls.","type":"boolean","default":true}}},"McpTransport":{"type":"string","enum":["stdio","http"]},"MediaConfig":{"description":"Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.","type":"object","properties":{"audio_model":{"description":"Audio model name (Ollama model or OpenAI model). Default: \"whisper\".","type":"string","default":"whisper"},"audio_ollama_url":{"description":"Ollama base URL for audio transcription. Default: \"http://localhost:11434\".","type":"string","default":"http://localhost:11434"},"audio_provider":{"description":"Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".","type":"string","default":"none"},"max_audio_size_mb":{"description":"Maximum audio attachment size in MiB. Default: 20.","type":"integer","format":"uint","default":20,"minimum":0},"max_video_size_mb":{"description":"Maximum video attachment size in MiB. Default: 50.","type":"integer","format":"uint","default":50,"minimum":0},"video_max_frames":{"description":"Maximum video frames to extract per video. Default: 4.","type":"integer","format":"uint","default":4,"minimum":0},"video_provider":{"description":"Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".","type":"string","default":"none"}}},"MemoryConfig":{"description":"Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.","type":"object","properties":{"acl_enabled":{"description":"Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.","type":"boolean","default":false},"archive_after_days":{"description":"Archive daily/session files older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"auto_hydrate":{"description":"Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing","type":"boolean","default":true},"auto_save":{"description":"Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.","type":"boolean","default":true},"backend":{"description":"\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).","type":"string","default":"sqlite"},"conversation_retention_days":{"description":"For sqlite backend: prune conversation rows older than this many days","type":"integer","format":"uint32","default":3,"minimum":0},"daily_retention_days":{"description":"For sqlite backend: prune daily rows older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"embedding_cache_size":{"description":"Max embedding cache entries before LRU eviction","type":"integer","format":"uint","default":10000,"minimum":0},"embedding_dimensions":{"description":"Embedding vector dimensions","type":"integer","format":"uint","default":384,"minimum":0},"embedding_model":{"description":"Embedding model name (e.g. \"text-embedding-3-small\")","type":"string","default":"prx-local-hash-v1"},"embedding_provider":{"description":"Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"","type":"string","default":"local"},"events":{"description":"Raw/quasi-raw message event recording controls (`[memory.events]`).","$ref":"#/$defs/MemoryEventsConfig","default":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true}},"keyword_weight":{"description":"Weight for keyword BM25 in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.3},"legacy_conversation_turns_visible":{"description":"Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.","type":"boolean","default":true},"lucid_budget":{"description":"Token budget for lucid (replaces OPENPRX_LUCID_BUDGET)","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"lucid_cmd":{"description":"Path to lucid binary (replaces OPENPRX_LUCID_CMD)","type":["string","null"],"default":null},"lucid_failure_cooldown_ms":{"description":"Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)","type":"integer","format":"uint64","default":60000,"minimum":0},"lucid_local_hit_threshold":{"description":"Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)","type":"integer","format":"uint","default":3,"minimum":0},"lucid_recall_timeout_ms":{"description":"Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)","type":"integer","format":"uint64","default":5000,"minimum":0},"lucid_store_timeout_ms":{"description":"Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)","type":"integer","format":"uint64","default":3000,"minimum":0},"min_relevance_score":{"description":"Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4","type":"number","format":"double","default":0.4},"purge_after_days":{"description":"Purge archived files older than this many days","type":"integer","format":"uint32","default":30,"minimum":0},"semantic":{"description":"Semantic memory promotion controls (`[memory.semantic]`).","$ref":"#/$defs/MemorySemanticConfig","default":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30}},"sqlite_open_timeout_secs":{"description":"For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"sqlite_read_pool_size":{"description":"For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"vector_candidate_cap":{"description":"How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.","type":"integer","format":"uint","default":2000,"minimum":0},"vector_weight":{"description":"Weight for vector similarity in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.7}}},"MemoryEventsConfig":{"description":"Raw message event recording configuration (`[memory.events]`).","type":"object","properties":{"record_assistant_messages":{"description":"Record assistant replies.","type":"boolean","default":true},"record_tool_events":{"description":"Record tool/event payloads by default.","type":"boolean","default":false},"record_user_messages":{"description":"Record inbound/user messages.","type":"boolean","default":true}}},"MemorySemanticConfig":{"description":"Semantic memory promotion configuration (`[memory.semantic]`).","type":"object","properties":{"auto_promote_assistant_messages":{"description":"Auto-promote eligible assistant messages. Disabled by default to reduce noise.","type":"boolean","default":false},"auto_promote_user_messages":{"description":"Auto-promote eligible user messages into long-term semantic memories.","type":"boolean","default":true},"min_chars":{"description":"Minimum content length for semantic auto-promotion.","type":"integer","format":"uint","default":30,"minimum":0}}},"MemoryWebhookConfig":{"type":"object","properties":{"bind":{"description":"Socket address for the receiver (e.g. \"0.0.0.0:16899\").","type":"string","default":"0.0.0.0:16899"},"signing_secret":{"description":"Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.","type":["string","null"],"default":null},"token":{"description":"Required bearer token for incoming webhook events.","type":["string","null"],"default":null}}},"ModelOperationSetting":{"description":"The operations a `[[providers.models]]` entry may list.","type":"string","enum":["chat","embedding","decision_endpoint","rerank","image_generation","audio_generation","video_generation"]},"ModelPricing":{"description":"Per-model pricing entry (USD per 1M tokens).","type":"object","properties":{"cache_read":{"description":"Cache read input price per 1M tokens.","type":"number","format":"double","default":0.0},"cache_write":{"description":"Cache write/creation input price per 1M tokens.","type":"number","format":"double","default":0.0},"input":{"description":"Input price per 1M tokens","type":"number","format":"double","default":0.0},"output":{"description":"Output price per 1M tokens","type":"number","format":"double","default":0.0}}},"ModelRouteConfig":{"description":"Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"hint":{"description":"Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")","type":"string"},"level":{"type":["string","null"]},"model":{"description":"Model to use with that provider","type":"string"},"provider":{"description":"Provider to route to (must match a known provider name)","type":"string"},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true,"required":["hint","provider","model"]},"ModelSettings":{"description":"A model level plus explicit parameter overrides in `[model_settings.\"\"]`.","type":"object","properties":{"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"level":{"type":["string","null"]},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true},"MultimodalConfig":{"description":"Multimodal (image) handling configuration (`[multimodal]` section).","type":"object","properties":{"allow_remote_fetch":{"description":"Allow fetching remote image URLs (http/https). Enabled by default.","type":"boolean","default":true},"max_image_size_mb":{"description":"Maximum image payload size in MiB before base64 encoding.","type":"integer","format":"uint","default":5,"minimum":0},"max_images":{"description":"Maximum number of image attachments accepted per request.","type":"integer","format":"uint","default":4,"minimum":0}}},"NextcloudTalkConfig":{"description":"Nextcloud Talk bot configuration (webhook receive + OCS send API).","type":"object","properties":{"allowed_users":{"description":"Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Bot app token used for OCS API bearer auth.","type":"string"},"base_url":{"description":"Nextcloud base URL (e.g. \"https://cloud.example.com\").","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"webhook_secret":{"description":"Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).","type":["string","null"],"default":null}},"required":["base_url","app_token"]},"NgrokTunnelConfig":{"type":"object","properties":{"auth_token":{"description":"ngrok auth token","type":"string"},"domain":{"description":"Optional custom domain","type":["string","null"]}},"required":["auth_token"]},"NodeServerConfig":{"description":"Node daemon runtime config used by `prx-node`.","type":"object","properties":{"allowed_commands":{"description":"Command allowlist matched on first token.\n\nIn restricted mode this list is required unless explicitly set to `[\"*\"]`.","type":"array","default":["echo"],"items":{"type":"string"}},"bearer_token":{"description":"Required bearer token for /rpc.","type":"string","default":""},"blocked_commands":{"description":"Command denylist matched on first token. Always enforced.","type":"array","default":[],"items":{"type":"string"}},"exec_timeout_ms":{"description":"Default command timeout in milliseconds.","type":"integer","format":"uint64","default":15000,"minimum":0},"hmac_secret":{"description":"Optional HMAC signing secret.","type":["string","null"],"default":null},"listen_addr":{"description":"Listen address for node daemon.","type":"string","default":"127.0.0.1:8787"},"max_concurrent_tasks":{"description":"Maximum number of concurrent async command tasks.","type":"integer","format":"uint","default":8,"minimum":0},"max_output_bytes":{"description":"Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.","type":"integer","format":"uint","default":1048576,"minimum":0},"sandbox_root":{"description":"Sandbox root directory for read/write/cwd constraints.","type":"string","default":"."},"task_result_ttl_ms":{"description":"TTL for completed task results in milliseconds.","type":"integer","format":"uint64","default":3600000,"minimum":0},"tls_cert":{"description":"TLS certificate path (PEM).","type":["string","null"],"default":null},"tls_key":{"description":"TLS private key path (PEM).","type":["string","null"],"default":null},"tls_required":{"description":"Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.","type":"boolean","default":true}}},"NodesConfig":{"description":"Remote node proxy configuration for core-side RPC calls and node daemon defaults.","type":"object","properties":{"nodes":{"description":"Configured remote nodes.","type":"array","default":[],"items":{"$ref":"#/$defs/RemoteNodeConfig"}},"request_timeout_ms":{"description":"Default request timeout for node RPC calls.","type":"integer","format":"uint64","default":15000,"minimum":0},"retry_max":{"description":"Default max retries for node RPC calls.","type":"integer","format":"uint8","default":2,"maximum":255,"minimum":0},"server":{"description":"Embedded node server defaults used by `prx-node`.","$ref":"#/$defs/NodeServerConfig","default":{"allowed_commands":["echo"],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}}},"ObservabilityConfig":{"description":"Observability backend configuration (`[observability]` section).","type":"object","properties":{"backend":{"description":"\"none\" | \"log\" | \"prometheus\" | \"otel\"","type":"string","default":"none"},"otel_endpoint":{"description":"OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".","type":["string","null"],"default":null},"otel_service_name":{"description":"Service name reported to the OTel collector. Defaults to \"prx\".","type":["string","null"],"default":null}}},"OllamaProviderConfig":{"description":"Ollama-specific request options (`[providers.ollama]`).","type":"object","properties":{"num_ctx":{"description":"Explicit context window sent as Ollama `options.num_ctx`.","type":["integer","null"],"format":"uint","default":null,"minimum":0}}},"OsPagingConfig":{"description":"Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.","type":"object","properties":{"eviction_threshold":{"description":"Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.","type":"number","format":"double","default":0.7},"keep_recent_messages":{"description":"Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).","type":"integer","format":"uint","default":12,"minimum":0},"max_recalled_pages":{"description":"Maximum number of evicted pages (document chunks) recalled per turn.","type":"integer","format":"uint","default":10,"minimum":0},"proactive_retrieval":{"description":"Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.","type":"boolean","default":true},"retrieval_injection_role":{"description":"Role under which recalled pages are injected.","$ref":"#/$defs/RetrievalInjectionRole","default":"system"}}},"PluginsConfig":{"description":"WASM plugin runtime configuration.","type":"object","properties":{"enabled":{"description":"Load WASM plugins from `/plugins`. Default: `false`.","type":"boolean","default":false}},"additionalProperties":false},"ProviderModelConfig":{"description":"One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.","type":"object","properties":{"context_window":{"description":"The model's context window in tokens.","type":["integer","null"],"format":"uint32","minimum":0},"model":{"description":"The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.","type":["string","null"]},"native_tools":{"description":"Whether the model accepts native tool calls.","type":["boolean","null"]},"operations":{"description":"The complete list of operations the model executes; every operation not\nlisted is unsupported.","type":["array","null"],"items":{"$ref":"#/$defs/ModelOperationSetting"}},"provider":{"description":"The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.","type":"string"},"streaming":{"description":"Whether the model streams responses.","type":["boolean","null"]},"structured_output":{"description":"Whether the model honours a JSON-schema response format.","type":["boolean","null"]},"tool_call_dialect":{"description":"The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema_dialect":{"description":"The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]},"vision_input":{"description":"Whether the model accepts image input.","type":["boolean","null"]}},"required":["provider"]},"ProviderToolDialectConfig":{"description":"One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.","type":"object","properties":{"model":{"description":"The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.","type":["string","null"]},"provider":{"description":"The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.","type":"string"},"tool_call":{"description":"The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema":{"description":"The tool-schema dialect the endpoint accepts.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]}},"required":["provider"]},"ProvidersConfig":{"description":"Provider-specific runtime configuration (`[providers]`).","type":"object","properties":{"models":{"description":"Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.","type":"array","items":{"$ref":"#/$defs/ProviderModelConfig"}},"ollama":{"description":"Ollama-specific request options (`[providers.ollama]`).","$ref":"#/$defs/OllamaProviderConfig","default":{"num_ctx":null}},"tool_dialects":{"description":"Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).","type":"array","items":{"$ref":"#/$defs/ProviderToolDialectConfig"}}}},"ProxyConfig":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).","type":"object","properties":{"all_proxy":{"description":"Fallback proxy URL for all schemes.","type":["string","null"],"default":null},"http_proxy":{"description":"Proxy URL for HTTP requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"https_proxy":{"description":"Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"no_proxy":{"description":"No-proxy bypass list. Same format as NO_PROXY.","type":"array","default":[],"items":{"type":"string"}},"scope":{"description":"Proxy application scope.","$ref":"#/$defs/ProxyScope","default":"prx"},"services":{"description":"Service selectors used when scope = \"services\".","type":"array","default":[],"items":{"type":"string"}}}},"ProxyScope":{"description":"Proxy application scope — determines which outbound traffic uses the proxy.","oneOf":[{"description":"Use system environment proxy variables only.","type":"string","const":"environment"},{"description":"Apply proxy to all OpenPRX-managed HTTP traffic (default).","type":"string","const":"prx"},{"description":"Apply proxy only to explicitly listed service selectors.","type":"string","const":"services"}]},"QQConfig":{"description":"QQ Official Bot configuration (Tencent QQ Bot SDK)","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs. Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from QQ Bot developer console","type":"string"},"app_secret":{"description":"App Secret from QQ Bot developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["app_id","app_secret"]},"QueryClassificationConfig":{"description":"Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.","type":"object","properties":{"rules":{"description":"Classification rules evaluated in priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/ClassificationRule"}}}},"RamfluxAccountConfig":{"description":"Persona for one ramflux AI account. Missing fields fall back to the global agent.","type":"object","properties":{"cross_conversation_retrieval":{"description":"Cross-conversation memory retrieval. Off unless the owner sets it.","type":"boolean","default":false},"model":{"type":["string","null"],"default":null},"provider":{"type":["string","null"],"default":null},"scope_profile":{"type":["string","null"],"default":null},"system_prompt_file":{"description":"Path to a system-prompt file. Relative paths are resolved from the workspace.","type":["string","null"],"default":null}},"additionalProperties":false},"RamfluxAttachmentFetch":{"description":"Per-turn caps for `attachment.fetch`.","type":"object","properties":{"max_bytes":{"type":"integer","format":"uint64","default":5242880,"minimum":0},"max_per_turn":{"type":"integer","format":"uint8","default":4,"maximum":255,"minimum":0}},"additionalProperties":false},"RamfluxAuthorizationMode":{"description":"How prx combines its own setting with `bridge.hello.authorization`.","oneOf":[{"description":"Use the agent-host value. Until hello arrives, the effective mode is supervised.","type":"string","const":"follow_rf"},{"description":"Always supervised, even when the agent-host declares full.","type":"string","const":"supervised"},{"description":"Full only when the agent-host also declares full. Config alone never yields full.","type":"string","const":"full"}]},"RamfluxConfig":{"description":"Local ramflux agent-host bridge (`[channels_config.ramflux]`).","type":"object","properties":{"accounts":{"type":"object","additionalProperties":{"$ref":"#/$defs/RamfluxAccountConfig"},"default":{}},"allowed_block_types":{"type":"array","default":["Text","Markdown","Heading","KeyValue","Metric","List","TableFallback","Form","Input","Select","Progress","LogStream","Warning","Error","Success","Approval","ActionGroup","FilePreview","Fallback"],"items":{"type":"string"}},"attachment_fetch":{"$ref":"#/$defs/RamfluxAttachmentFetch","default":{"max_bytes":5242880,"max_per_turn":4}},"authorization_mode":{"$ref":"#/$defs/RamfluxAuthorizationMode","default":"follow_rf"},"encrypt_at_rest":{"type":"boolean","default":true},"max_in_flight_per_conversation":{"type":"integer","format":"uint8","default":1,"maximum":255,"minimum":0},"on_new_message":{"$ref":"#/$defs/RamfluxOnNewMessage","default":"queue"},"socket_path":{"description":"Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.","type":["string","null"],"default":null},"surface_limits":{"$ref":"#/$defs/RamfluxSurfaceLimits","default":{"max_actions":16,"max_blocks":32,"max_bytes":65536}},"turn_wall_clock_secs":{"description":"Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.","type":"integer","format":"uint64","default":120,"minimum":0}},"additionalProperties":false},"RamfluxOnNewMessage":{"description":"What to do with a new inbound message while a turn for that conversation is running.","type":"string","enum":["queue","interrupt"]},"RamfluxSurfaceLimits":{"description":"Limits for `reply.surface` blocks and actions.","type":"object","properties":{"max_actions":{"type":"integer","format":"uint32","default":16,"minimum":0},"max_blocks":{"type":"integer","format":"uint32","default":32,"minimum":0},"max_bytes":{"type":"integer","format":"uint32","default":65536,"minimum":0}},"additionalProperties":false},"ReliabilityCircuitBreakerConfig":{"description":"Process-local provider circuit policy (`[reliability.circuit_breaker]`).","type":"object","properties":{"enabled":{"description":"Enable protection for factory-built provider chains.","type":"boolean","default":true},"failure_threshold":{"description":"Consecutive transient failures that open a circuit (at least 1).","type":"integer","format":"uint32","default":5,"minimum":0},"max_open_secs":{"description":"Maximum doubled window, between open_secs and 3600 seconds.","type":"integer","format":"uint64","default":300,"minimum":0},"open_secs":{"description":"Initial open window in seconds (at least 1).","type":"integer","format":"uint64","default":30,"minimum":0}}},"ReliabilityConfig":{"description":"Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.","type":"object","properties":{"acknowledge_single_provider_risk":{"description":"Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.","type":"boolean","default":false},"api_keys":{"description":"Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.","type":"array","default":[],"items":{"type":"string"}},"channel_initial_backoff_secs":{"description":"Initial backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":2,"minimum":0},"channel_max_backoff_secs":{"description":"Max backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":60,"minimum":0},"circuit_breaker":{"description":"Per-provider consecutive failure protection.","$ref":"#/$defs/ReliabilityCircuitBreakerConfig","default":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30}},"fallback_providers":{"description":"Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).","type":"array","default":[],"items":{"type":"string"}},"model_fallbacks":{"description":"Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`","type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"default":{}},"provider_backoff_ms":{"description":"Base backoff (ms) for provider retry delay.","type":"integer","format":"uint64","default":500,"minimum":0},"provider_retries":{"description":"Retries per provider before failing over.","type":"integer","format":"uint32","default":2,"minimum":0},"scheduler_poll_secs":{"description":"Scheduler polling cadence in seconds.","type":"integer","format":"uint64","default":15,"minimum":0},"scheduler_retries":{"description":"Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.","type":"integer","format":"uint32","default":2,"minimum":0}}},"RemoteNodeConfig":{"description":"A remote node target for core-side node proxy calls.","type":"object","properties":{"bearer_token":{"description":"Bearer token for node RPC authentication.","type":"string"},"endpoint":{"description":"Base endpoint (e.g. \"http://127.0.0.1:8787\").","type":"string"},"hmac_secret":{"description":"Optional request signing key (HMAC-SHA256).","type":["string","null"],"default":null},"id":{"description":"Stable node ID used by the nodes tool.","type":"string"},"retry_max":{"description":"Optional per-node retry override.","type":["integer","null"],"format":"uint8","default":null,"maximum":255,"minimum":0},"timeout_ms":{"description":"Optional per-node timeout override.","type":["integer","null"],"format":"uint64","default":null,"minimum":0}},"required":["id","endpoint","bearer_token"]},"RetrievalInjectionRole":{"description":"Where recalled context pages are injected back into the request.","oneOf":[{"description":"Inject recalled pages as a leading `system` message (not user-visible).","type":"string","const":"system"},{"description":"Inject recalled pages as a leading `user` message.","type":"string","const":"user"}]},"RouterConfig":{"description":"Heuristic LLM router configuration (`[router]` section).","type":"object","properties":{"alpha":{"description":"Similarity score weight. Phase 1 keeps this at `0.0`.","type":"number","format":"float","default":0.0},"beta":{"description":"Capability score weight.","type":"number","format":"float","default":0.5},"delta":{"description":"Cost penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"epsilon":{"description":"Latency penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"gamma":{"description":"Elo score weight.","type":"number","format":"float","default":0.30000001192092896},"knn_k":{"description":"Number of nearest neighbors considered for voting. Default: `7`.","type":"integer","format":"uint","default":7,"minimum":0},"knn_min_records":{"description":"Minimum history records before KNN affects routing. Default: `10`.","type":"integer","format":"uint","default":10,"minimum":0},"models":{"description":"Candidate model registry.","type":"array","default":[],"items":{"$ref":"#/$defs/RouterModelConfig"}}}},"RouterModelConfig":{"description":"Static router metadata for one model candidate.","type":"object","properties":{"categories":{"description":"Capability categories such as `conversation`, `code`, or `analysis`.","type":"array","default":[],"items":{"type":"string"}},"cost_per_million_tokens":{"description":"USD cost per million tokens.","type":"number","format":"float","default":0.0},"elo_rating":{"description":"Initial Elo rating.","type":"number","format":"float","default":1000.0},"latency_ms":{"description":"Average latency in milliseconds.","type":"integer","format":"uint32","default":2000,"minimum":0},"max_context":{"description":"Maximum context window in tokens.","type":"integer","format":"uint","default":1000000,"minimum":0},"model_id":{"description":"Model identifier without provider prefix.","type":"string"},"provider":{"description":"Provider identifier.","type":"string"},"reserved_output_tokens":{"description":"Output tokens reserved for this model when planning input context.","type":["integer","null"],"format":"uint","minimum":0}},"required":["model_id","provider"]},"RuntimeConfig":{"description":"Runtime adapter configuration (`[runtime]` section).","type":"object","properties":{"codex_reasoning_effort":{"description":"Codex reasoning effort","type":["string","null"],"default":null},"codex_stream_idle_timeout_secs":{"description":"Codex stream idle timeout in seconds","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"docker":{"description":"Docker runtime settings (used when `kind = \"docker\"`).","$ref":"#/$defs/DockerRuntimeConfig","default":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true}},"idle_hang_secs":{"description":"Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"kind":{"description":"Runtime kind (`native` | `docker`).","type":"string","default":"native"},"long_task_warn_secs":{"description":"Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"managed_cgroup_root":{"description":"Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.","type":["string","null"],"default":null},"max_blocking_threads":{"description":"Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"reasoning_enabled":{"description":"Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported","type":["boolean","null"],"default":null},"shell_env_allowlist":{"description":"Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.","type":"array","default":[],"items":{"type":"string"}},"workdir":{"description":"Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.","type":["string","null"],"default":null}}},"SchedulerConfig":{"description":"Scheduler configuration for periodic task execution (`[scheduler]` section).","type":"object","properties":{"claim_lease_secs":{"description":"Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.","type":"integer","format":"uint64","default":90,"minimum":0},"max_tasks":{"description":"Maximum number of persisted scheduled tasks.","type":"integer","format":"uint","default":64,"minimum":0}}},"ScopeConfig":{"description":"Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```","type":"object","properties":{"assign_owners":{"description":"Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.","type":"array","default":[],"items":{"type":"string"}},"default":{"description":"Default action when no rule matches: \"allow\" (default) or \"deny\".","$ref":"#/$defs/ScopeDefault","default":"allow"},"rules":{"description":"Ordered list of scope rules evaluated top-to-bottom.","type":"array","default":[],"items":{"$ref":"#/$defs/ScopeRule"}}}},"ScopeDefault":{"description":"What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.","oneOf":[{"description":"Unmatched tool calls are allowed (the default).","type":"string","const":"allow"},{"description":"Unmatched tool calls are refused.","type":"string","const":"deny"}]},"ScopeRule":{"description":"A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.","type":"object","properties":{"assign_allow":{"description":"Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".","type":"array","default":[],"items":{"type":"string"}},"assign_deny":{"description":"Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.","type":"array","default":[],"items":{"type":"string"}},"channel":{"description":"Match by channel name: \"signal\", \"telegram\", \"discord\", etc.","type":["string","null"]},"chat_type":{"description":"Match by chat type: \"direct\", \"group\", or \"*\" for any type.","type":["string","null"]},"send_allow":{"description":"Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.","type":"array","default":[],"items":{"type":"string"}},"send_deny":{"description":"Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.","type":"array","default":[],"items":{"type":"string"}},"tools_allow":{"description":"Tool whitelist: only these tools are allowed (empty = all tools permitted).","type":"array","default":[],"items":{"type":"string"}},"tools_deny":{"description":"Tool blacklist: these tools are denied regardless of allow list.","type":"array","default":[],"items":{"type":"string"}},"user":{"description":"Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.","type":["string","null"]}}},"SecretsConfig":{"description":"Secrets encryption configuration (`[secrets]` section).","type":"object","properties":{"encrypt":{"description":"Enable encryption for API keys and tokens in config.toml","type":"boolean","default":true}}},"SecurityConfig":{"description":"Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.","type":"object","properties":{"audit":{"description":"Audit logging configuration","$ref":"#/$defs/AuditConfig","default":{"log_path":"audit.log","max_size_mb":100}},"workspace_hooks":{"description":"Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.","$ref":"#/$defs/WorkspaceHooks"}}},"SelfSystemConfig":{"description":"Self-system experimental automation config (`[self_system]`).","type":"object","properties":{"evolution_config_path":{"description":"Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG)","type":["string","null"],"default":null},"evolution_debug_raw":{"description":"Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW)","type":"boolean","default":false},"evolution_interval_hours":{"description":"Evolution scheduler interval in hours (daemon mode).","type":"integer","format":"uint32","default":24,"minimum":0},"evolution_judge_timeout_secs":{"description":"Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.","type":"integer","format":"uint64","default":180,"minimum":0},"evolution_model_max_micro_usd":{"description":"Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.","type":"integer","format":"uint64","default":0,"minimum":0},"evolution_model_max_tokens":{"description":"Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.","type":"integer","format":"uint64","default":16384,"minimum":0},"fitness":{"description":"Daily fitness snapshot policy.","$ref":"#/$defs/FitnessConfig","default":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"}},"fitness_interval_hours":{"description":"Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.","type":"integer","format":"uint64","default":24,"minimum":0}}},"SessionsSpawnConfig":{"description":"Sessions spawn configuration (`[sessions_spawn]` section).","type":"object","properties":{"cleanup_on_complete":{"description":"Remove worker workspace directory after process-mode completion.","type":"boolean","default":true},"default_mode":{"description":"Default execution mode for sessions_spawn (`task` or `process`).","type":"string","default":"task"},"process_memory_strategy":{"description":"Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.","type":"string","default":"shared_fabric"},"worker_workspace_root":{"description":"Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.","type":["string","null"],"default":null}}},"SignalConfig":{"type":"object","properties":{"account":{"description":"E.164 phone number of the signal-cli account (e.g. \"+1234567890\").","type":"string"},"allowed_from":{"description":"Allowed sender phone numbers (E.164) or \"*\" for all.","type":"array","default":[],"items":{"type":"string"}},"cli_path":{"description":"Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).","type":["string","null"],"default":null},"daemon_http_port":{"description":"Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"daemon_mode":{"description":"Deprecated: ignored. Accepted for backward compatibility with older config files.","type":["boolean","null"],"default":null},"data_dir":{"description":"signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_id":{"description":"Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group","type":["string","null"],"default":null},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"http_url":{"description":"Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.","type":"string","default":"http://localhost:8080"},"ignore_attachments":{"description":"Skip messages that are attachment-only (no text body).","type":"boolean","default":false},"ignore_stories":{"description":"Skip incoming story messages.","type":"boolean","default":false},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"mode":{"description":"Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.","type":["string","null"],"default":null},"startup_timeout_ms":{"description":"Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.","type":"integer","format":"uint64","default":30000,"minimum":0},"storm_protection":{"description":"Signal ingress storm protection controls.","$ref":"#/$defs/SignalStormProtectionConfig","default":{"abnormal_threshold":10,"abnormal_window_secs":60,"breaker_duration_secs":300,"dedupe_ttl_secs":60,"min_reply_interval_secs":2}}},"required":["account"]},"SignalStormProtectionConfig":{"type":"object","properties":{"abnormal_threshold":{"description":"Non-user event threshold within `abnormal_window_secs` before tripping the breaker.","type":"integer","format":"uint","default":10,"minimum":0},"abnormal_window_secs":{"description":"Sliding window in seconds for non-user event counting.","type":"integer","format":"uint64","default":60,"minimum":0},"breaker_duration_secs":{"description":"Circuit breaker duration in seconds after threshold is reached.","type":"integer","format":"uint64","default":300,"minimum":0},"dedupe_ttl_secs":{"description":"Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.","type":"integer","format":"uint64","default":60,"minimum":0},"min_reply_interval_secs":{"description":"Minimum interval in seconds between replies for the same `(channel + reply_target)`.","type":"integer","format":"uint64","default":2,"minimum":0}}},"SkillRagConfig":{"description":"Dynamic skill retrieval configuration (`[skill_rag]` section).","type":"object","properties":{"top_k":{"description":"How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).","type":"integer","format":"uint","default":32,"minimum":0}}},"SkillSuiteRegistration":{"description":"The frozen suite that governs one skill's proposals.","type":"object","properties":{"skill_id":{"description":"The skill the suite governs.","type":"string"},"suite_digest":{"description":"SHA-256 digest (64 lowercase hex digits) of the frozen suite.","type":"string"}},"additionalProperties":false,"required":["skill_id","suite_digest"]},"SkillsConfig":{"description":"Skills loading configuration (`[skills]` section).","type":"object","properties":{"open_skills_dir":{"description":"Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.","type":["string","null"],"default":null},"openclaw_skills_dir":{"description":"Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.","type":["string","null"],"default":null}}},"SkillsLifecycleConfig":{"description":"`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.","type":"object","properties":{"allow_executable_proposals":{"description":"Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.","type":"boolean","default":false},"enabled":{"description":"Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.","type":"boolean","default":false},"max_concurrent_evaluations":{"description":"Most evaluations running at once.","type":"integer","format":"uint32","default":1,"minimum":0},"max_edit_fraction":{"description":"Edit budget of a proposal as a fraction of the skill body, in (0, 1].","type":"number","format":"double","default":0.2},"max_edit_tokens":{"description":"Edit budget of a proposal, in tokens.","type":"integer","format":"uint64","default":300,"minimum":0},"max_proposals_per_cycle":{"description":"Most proposals one cycle may start.","type":"integer","format":"uint32","default":1,"minimum":0},"min_cases_floor":{"description":"Smallest `min_cases` a governing suite may declare. Below 3 is refused.","type":"integer","format":"uint32","default":3,"minimum":0},"mode":{"description":"`draft_only`, `shadow` or `auto`.","$ref":"#/$defs/SkillsLifecycleModeConfig","default":"draft_only"},"owner_scope":{"description":"The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.","type":["string","null"],"default":null},"require_holdout":{"description":"A governing suite must have a holdout split. `false` is refused.","type":"boolean","default":true},"storage_dir":{"description":"Store location under the workspace. Only the default is supported.","type":"string","default":"self/skill-lifecycle"},"suites":{"description":"The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.","type":"array","default":[],"items":{"$ref":"#/$defs/SkillSuiteRegistration"}}},"additionalProperties":false},"SkillsLifecycleModeConfig":{"description":"What the lifecycle may do. Mirrors `LifecycleMode`.","oneOf":[{"description":"Drafts and reviews only.","type":"string","const":"draft_only"},{"description":"Drafts plus evaluation and gating; never publishes.","type":"string","const":"shadow"},{"description":"Publishes an eligible proposal after every gate.","type":"string","const":"auto"}]},"SlackConfig":{"description":"Slack bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Slack user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Slack app-level token for Socket Mode (xapp-...).","type":["string","null"]},"bot_token":{"description":"Slack bot OAuth token (xoxb-...).","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["bot_token"]},"SmartGroupConfig":{"description":"Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).","type":"object","properties":{"classifier_max_context_messages":{"description":"How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.","type":"integer","format":"uint","default":3,"minimum":0},"classifier_model":{"description":"Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.","type":"string","default":""},"classifier_provider":{"description":"Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.","type":"string","default":""},"classifier_temperature":{"description":"Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).","type":"number","format":"double","default":0.0},"classifier_timeout_secs":{"description":"Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.","type":"integer","format":"uint64","default":5,"minimum":0}}},"StorageConfig":{"description":"Persistent storage configuration (`[storage]` section).","type":"object","properties":{"provider":{"description":"Storage provider settings (e.g. sqlite, postgres).","$ref":"#/$defs/StorageProviderSection","default":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}}},"StorageProviderConfig":{"description":"Storage provider backend configuration (e.g. postgres connection details).","type":"object","properties":{"connect_timeout_secs":{"description":"Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"db_url":{"description":"Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.","type":["string","null"],"default":null},"pool_max_size":{"description":"Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.","type":"integer","format":"uint","default":32,"minimum":0},"provider":{"description":"Storage engine key (e.g. \"postgres\", \"sqlite\").","type":"string","default":""},"schema":{"description":"Database schema for SQL backends.","type":"string","default":"public"},"table":{"description":"Table name for memory entries.","type":"string","default":"memories"}}},"StorageProviderSection":{"description":"Wrapper for the storage provider configuration section.","type":"object","properties":{"config":{"description":"Storage provider backend settings.","$ref":"#/$defs/StorageProviderConfig","default":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"StreamMode":{"description":"Streaming mode for channels that support progressive message updates.","oneOf":[{"description":"No streaming -- send the complete response as a single message (default).","type":"string","const":"off"},{"description":"Update a draft message with every flush interval.","type":"string","const":"partial"}]},"TailscaleTunnelConfig":{"type":"object","properties":{"funnel":{"description":"Use Tailscale Funnel (public internet) vs Serve (tailnet only)","type":"boolean","default":false},"hostname":{"description":"Optional hostname override","type":["string","null"]}}},"TaskRoutingConfig":{"description":"Lightweight pre-LLM task routing.","type":"object","properties":{"default_intent":{"description":"Fallback intent when no rule matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"rules":{"description":"Rules evaluated in descending priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/TaskRoutingRule"}}}},"TaskRoutingIntentConfig":{"description":"Task-routing default and rule intent.","type":"string","enum":["simple","delegate","stream"]},"TaskRoutingRule":{"description":"A single task-routing rule.","type":"object","properties":{"intent":{"description":"Route intent to apply when a keyword matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"model_hint":{"description":"Optional model hint/raw model for non-delegated requests.","type":["string","null"],"default":null},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0},"sub_agent_model":{"description":"Optional raw sub-agent model override for delegated tasks.","type":["string","null"],"default":null}}},"TelegramConfig":{"description":"Telegram bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Telegram user IDs or usernames. Empty = deny all.","type":"array","items":{"type":"string"}},"bot_token":{"description":"Telegram Bot API token (from @BotFather).","type":"string"},"draft_update_interval_ms":{"description":"Minimum interval (ms) between draft message edits to avoid rate limits.","type":"integer","format":"uint64","default":1000,"minimum":0},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"interrupt_on_new_message":{"description":"When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.","type":"boolean","default":false},"stream_mode":{"description":"Streaming mode for progressive response delivery via message edits.","$ref":"#/$defs/StreamMode","default":"off"}},"required":["bot_token","allowed_users"]},"ToolCallDialectSetting":{"description":"The tool-call grammars an operator may declare for an endpoint.","oneOf":[{"description":"Only the native `tool_calls` array is a tool call (the default).","type":"string","const":"native"},{"description":"Additionally read `{json}` from the content,\nfor a tool name the request registered.","type":"string","const":"xml_function_tags"}]},"ToolSchemaDialectSetting":{"description":"The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.","oneOf":[{"description":"The published document, byte for byte (the default).","type":"string","const":"raw"},{"description":"The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.","type":"string","const":"no_root_combinators"}]},"ToolTieringConfig":{"description":"Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.","type":"object","properties":{"always_exclude":{"description":"Tool names excluded from capability publication.","type":"array","default":[],"items":{"type":"string"}},"always_include":{"description":"Tool names preferred for direct publication, subject to admission gates.","type":"array","default":[],"items":{"type":"string"}},"channel_exclude":{"description":"Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefault: empty (nothing is hidden); list tool names to hide them on channels.","type":"array","default":[],"items":{"type":"string"}}}},"TunnelConfig":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.","type":"object","properties":{"cloudflare":{"description":"Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).","anyOf":[{"$ref":"#/$defs/CloudflareTunnelConfig"},{"type":"null"}],"default":null},"custom":{"description":"Custom tunnel command configuration (used when `provider = \"custom\"`).","anyOf":[{"$ref":"#/$defs/CustomTunnelConfig"},{"type":"null"}],"default":null},"ngrok":{"description":"ngrok tunnel configuration (used when `provider = \"ngrok\"`).","anyOf":[{"$ref":"#/$defs/NgrokTunnelConfig"},{"type":"null"}],"default":null},"provider":{"description":"Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.","type":"string","default":"none"},"tailscale":{"description":"Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).","anyOf":[{"$ref":"#/$defs/TailscaleTunnelConfig"},{"type":"null"}],"default":null}}},"UserPolicyConfig":{"description":"Startup user policy entry (`[[user_policies]]`).","type":"object","properties":{"blocked_patterns":{"type":"array","default":[],"items":{"type":"string"}},"projects":{"type":"array","default":[],"items":{"type":"string"}},"role":{"type":"string","default":"guest"},"user_id":{"type":"string"},"visibility_ceiling":{"type":"string","default":"private"}},"required":["user_id"]},"WacliConfig":{"description":"wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```","type":"object","properties":{"allow_unsigned_loopback":{"description":"Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).","type":"boolean","default":false},"allowed_from":{"description":"Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.","type":"array","default":["*"],"items":{"type":"string"}},"bot_jid":{"description":"Bot's own JID, used for reply-to-bot mention detection.","type":["string","null"],"default":null},"bot_lid":{"description":"The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.","type":["string","null"],"default":null},"bot_number":{"description":"Bot's own phone number (digits), used for `@` mention detection.","type":["string","null"],"default":null},"cli_path":{"description":"Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.","type":["string","null"],"default":null},"group_reply_mode":{"description":"Smart group-reply mode. When `None`, derived from `mention_only`.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"host":{"description":"REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].","type":["string","null"],"writeOnly":true},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"outbound_media_workspace_only":{"description":"Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.","type":"boolean","default":false},"port":{"description":"REMOVED: legacy JSON-RPC daemon port. See `host`.","type":["integer","null"],"format":"uint16","maximum":65535,"minimum":0,"writeOnly":true},"self_chat_mode":{"description":"Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.","type":"boolean","default":false},"store_dir":{"description":"wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.","type":["string","null"],"default":null},"webhook_listen":{"description":"Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").","type":"string","default":"127.0.0.1:16868"},"webhook_path":{"description":"HTTP path the webhook server serves (default: \"/wacli\").","type":"string","default":"/wacli"},"webhook_secret":{"description":"HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.","type":["string","null"],"default":null}}},"WebSearchConfig":{"description":"Web search tool configuration (`[web_search]` section).","type":"object","properties":{"brave_api_key":{"description":"Brave Search API key (required if provider is \"brave\")","type":["string","null"],"default":null},"fetch_max_chars":{"description":"Maximum characters returned by `web_fetch` (default 10000)","type":"integer","format":"uint","default":50000,"minimum":0},"max_results":{"description":"Maximum results per search (1-20)","type":"integer","format":"uint","default":15,"minimum":0},"provider":{"description":"Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)","type":"string","default":"duckduckgo"},"timeout_secs":{"description":"Request timeout in seconds","type":"integer","format":"uint64","default":15,"minimum":0}}},"WebhookConfig":{"description":"Webhook channel configuration.","type":"object","properties":{"port":{"description":"Port to listen on for incoming webhooks.","type":"integer","format":"uint16","maximum":65535,"minimum":0},"secret":{"description":"Optional shared secret for webhook signature verification.","type":["string","null"]}},"required":["port"]},"WhatsAppConfig":{"description":"WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.","type":"object","properties":{"access_token":{"description":"Access token from Meta Business Suite (Cloud API mode)","type":["string","null"],"default":null},"allowed_numbers":{"description":"Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"app_secret":{"description":"App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"pair_code":{"description":"Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one","type":["string","null"],"default":null},"pair_phone":{"description":"Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used","type":["string","null"],"default":null},"phone_number_id":{"description":"Phone number ID from Meta Business API (Cloud API mode)","type":["string","null"],"default":null},"read_pool_size":{"description":"Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"session_path":{"description":"Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs","type":["string","null"],"default":null},"verify_token":{"description":"Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode","type":["string","null"],"default":null},"ws_url":{"description":"WebSocket URL override (replaces WHATSAPP_WS_URL)","type":["string","null"],"default":null}}},"WorkspaceHooks":{"description":"Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).","oneOf":[{"description":"They do not run (the default); `prx doctor` and `hooks_status` say so.","type":"string","const":"off"},{"description":"They run, in a cleared environment and a dedicated directory beside\n`config.toml`.","type":"string","const":"on"}]},"WorkspaceMcpServers":{"description":"Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).","oneOf":[{"description":"None: a workspace file may only narrow the servers defined in\n`config.toml`.","type":"string","const":"off"},{"description":"HTTP servers (still refused when they target a private address).","type":"string","const":"http_only"},{"description":"HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.","type":"string","const":"stdio"}]},"XinConfig":{"description":"Configuration for the xin autonomous task engine (`[xin]`).","type":"object","properties":{"adopt_legacy_tasks":{"description":"Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).","type":"boolean","default":false},"interval_minutes":{"description":"Tick interval in minutes (minimum 1). Default: 5.","type":"integer","format":"uint32","default":5,"minimum":0},"stale_timeout_minutes":{"description":"Minutes after which a running task is marked stale. Default: 60.","type":"integer","format":"uint32","default":60,"minimum":0}}},"AgentMessaging":{"description":"Owner-controlled inbound session messaging (enabled unless explicitly off).","type":"object","properties":{"inbound":{"type":"boolean","default":true}}}}} +{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Config","description":"Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).","type":"object","properties":{"a2a":{"description":"Agent-to-Agent compatibility configuration (`[a2a]`).","$ref":"#/$defs/A2aConfig","default":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trusted_trust_domains":[],"trust_domain":"prx.local"}},"agent":{"description":"Agent orchestration settings (`[agent]`).","$ref":"#/$defs/AgentConfig","default":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2,"messaging":{"inbound":true}}},"agents":{"description":"Delegate agent configurations for multi-agent workflows.","type":"object","additionalProperties":{"$ref":"#/$defs/DelegateAgentConfig"},"default":{}},"api_key":{"description":"API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.","type":["string","null"],"default":null},"api_url":{"description":"Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)","type":["string","null"],"default":null},"auth":{"description":"Auth profile and external credential import settings (`[auth]`).","$ref":"#/$defs/AuthConfig","default":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"}},"autonomy":{"description":"Autonomy and security policy configuration (`[autonomy]`).","$ref":"#/$defs/AutonomyConfig","default":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true}},"browser":{"description":"Browser automation configuration (`[browser]`).","$ref":"#/$defs/BrowserConfig","default":{"allowed_domains":[],"computer_use":{"api_key":null}}},"channels_config":{"description":"Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).","$ref":"#/$defs/ChannelsConfig","default":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null}},"chat":{"description":"Interactive chat UI configuration (`[chat]`).","$ref":"#/$defs/ChatConfig","default":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2}},"compliance":{"description":"Operator-owned compliance controls (`[compliance]`).","$ref":"#/$defs/ComplianceConfig","default":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}},"composio":{"description":"Composio managed OAuth tools integration (`[composio]`).","$ref":"#/$defs/ComposioConfig","default":{"api_key":null,"entity_id":"default"}},"cost":{"description":"Cost tracking and budget enforcement configuration (`[cost]`).","$ref":"#/$defs/CostConfig","default":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{},"warn_at_percent":80}},"cron":{"description":"Cron job configuration (`[cron]`).","$ref":"#/$defs/CronConfig","default":{"max_run_history":50}},"decision_engine":{"description":"Optional advisory decision engine, disabled by default.","$ref":"#/$defs/DecisionEngineConfig","default":{"candidates":5,"enabled":false,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"latency_budget_ms":500,"max_candidates":12,"token_ratio_limit":0.3499999940395355}},"default_model":{"description":"Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.","type":["string","null"]},"default_provider":{"description":"Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.","type":["string","null"]},"default_temperature":{"description":"Default model temperature (0.0–2.0). Default: `0.7`.","type":"number","format":"double","default":0.7},"embedding_routes":{"description":"Embedding routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/EmbeddingRouteConfig"}},"gateway":{"description":"Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).","$ref":"#/$defs/GatewayConfig","default":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60}},"heartbeat":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]`).","$ref":"#/$defs/HeartbeatConfig","default":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."}},"http_request":{"description":"HTTP request tool configuration (`[http_request]`).","$ref":"#/$defs/HttpRequestConfig","default":{"max_response_size":1000000,"timeout_secs":30}},"identity":{"description":"Identity format configuration: OpenClaw or AIEOS (`[identity]`).","$ref":"#/$defs/IdentityConfig","default":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"}},"identity_bindings":{"description":"Static identity bindings loaded at startup (`[[identity_bindings]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/IdentityBindingConfig"}},"mcp":{"description":"Secrets encryption configuration (`[secrets]`).","$ref":"#/$defs/McpConfig","default":{"servers":{}}},"mcp_server":{"description":"MCP server compatibility configuration (`[mcp_server]`).","$ref":"#/$defs/McpServerRuntimeConfig","default":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true}},"media":{"description":"Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.","$ref":"#/$defs/MediaConfig","default":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"}},"memory":{"description":"Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).","$ref":"#/$defs/MemoryConfig","default":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7}},"model_routes":{"description":"Model routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/ModelRouteConfig"}},"model_settings":{"description":"Catalog model levels and explicit parameters, keyed by canonical release ID.","type":"object","additionalProperties":{"$ref":"#/$defs/ModelSettings"},"default":{}},"multimodal":{"description":"Multimodal (image) handling configuration (`[multimodal]`).","$ref":"#/$defs/MultimodalConfig","default":{"allow_remote_fetch":true,"max_image_size_mb":5,"max_images":4}},"nodes":{"description":"Remote node proxy configuration (`[nodes]`).","$ref":"#/$defs/NodesConfig","default":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":[],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}},"observability":{"description":"Observability backend configuration (`[observability]`).","$ref":"#/$defs/ObservabilityConfig","default":{"backend":"none","otel_endpoint":null,"otel_service_name":null}},"plugins":{"description":"WASM plugin runtime switch (`[plugins]`), off by default.","$ref":"#/$defs/PluginsConfig","default":{"enabled":false}},"providers":{"description":"Provider-specific runtime options (`[providers.]`).","$ref":"#/$defs/ProvidersConfig","default":{"ollama":{"num_ctx":null}}},"proxy":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).","$ref":"#/$defs/ProxyConfig","default":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]}},"query_classification":{"description":"Automatic query classification — maps user messages to model hints.","$ref":"#/$defs/QueryClassificationConfig","default":{"rules":[]}},"reliability":{"description":"Reliability settings: retries, fallback providers, backoff (`[reliability]`).","$ref":"#/$defs/ReliabilityConfig","default":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2}},"router":{"description":"Heuristic LLM router configuration (`[router]`).","$ref":"#/$defs/RouterConfig","default":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]}},"runtime":{"description":"Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.","$ref":"#/$defs/RuntimeConfig","default":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null}},"scheduler":{"description":"Scheduler configuration for periodic task execution (`[scheduler]`).","$ref":"#/$defs/SchedulerConfig","default":{"claim_lease_secs":90,"max_tasks":64}},"secrets":{"$ref":"#/$defs/SecretsConfig","default":{"encrypt":true}},"security":{"description":"Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).","$ref":"#/$defs/SecurityConfig","default":{"audit":{"log_path":"audit.log","max_size_mb":100}}},"self_system":{"description":"Self-system experimental automation controls (`[self_system]`).","$ref":"#/$defs/SelfSystemConfig","default":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24}},"sessions_spawn":{"description":"Session spawning configuration (`[sessions_spawn]`).","$ref":"#/$defs/SessionsSpawnConfig","default":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null}},"skill_rag":{"description":"Dynamic skill retrieval settings (`[skill_rag]`).","$ref":"#/$defs/SkillRagConfig","default":{"top_k":32}},"skills":{"description":"Skills loading and community repository behavior (`[skills]`).","$ref":"#/$defs/SkillsConfig","default":{"open_skills_dir":null,"openclaw_skills_dir":null}},"skills_lifecycle":{"description":"Skill lifecycle (`[skills_lifecycle]`), off by default.","$ref":"#/$defs/SkillsLifecycleConfig","default":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]}},"smart_group":{"description":"Smart group-reply pre-gate configuration (`[smart_group]`).","$ref":"#/$defs/SmartGroupConfig","default":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5}},"storage":{"description":"Persistent storage provider configuration (`[storage]`).","$ref":"#/$defs/StorageConfig","default":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"task_routing":{"description":"Task routing configuration — classifies work by intent before the main agent loop.","$ref":"#/$defs/TaskRoutingConfig","default":{"default_intent":"simple","rules":[]}},"tool_tiering":{"description":"Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).","$ref":"#/$defs/ToolTieringConfig","default":{"always_exclude":[],"always_include":[],"channel_exclude":[]}},"tunnel":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]`).","$ref":"#/$defs/TunnelConfig","default":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null}},"user_policies":{"description":"Static user policy records loaded at startup (`[[user_policies]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/UserPolicyConfig"}},"web_search":{"description":"Web search tool configuration (`[web_search]`).","$ref":"#/$defs/WebSearchConfig","default":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15}},"webhook":{"description":"Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).","$ref":"#/$defs/MemoryWebhookConfig","default":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null}},"xin":{"description":"Xin autonomous task engine configuration (`[xin]`).","$ref":"#/$defs/XinConfig","default":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}}},"$defs":{"A2aConfig":{"type":"object","properties":{"agent_id":{"description":"Stable PRX agent identifier advertised to peers.","type":"string","default":"prx-default"},"allowed_peer_issuers":{"description":"Accepted external peer issuers.","type":"array","default":[],"items":{"type":"string"}},"bind":{"description":"Advertised bind address.","type":"string","default":"127.0.0.1:16832"},"card_jwks_uri":{"description":"Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.","type":["string","null"],"default":null},"card_signing_key_path":{"description":"On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).","type":["string","null"],"default":null},"card_ttl_seconds":{"description":"Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.","type":"integer","format":"uint64","default":3600,"minimum":0},"discovery_advertised":{"description":"Whether to advertise into an external A2A registry.","type":"boolean","default":false},"handoff_nonce_ttl_seconds":{"description":"Replay window for future handoff delegation tokens.","type":"integer","format":"uint64","default":3600,"minimum":0},"messaging_enabled":{"description":"Enable the dedicated pinned mTLS messaging listener.","type":"boolean","default":false},"peers":{"type":"object","additionalProperties":{"$ref":"#/$defs/A2aPeer"},"default":{}},"spiffe_id":{"description":"Local SPIFFE-style identifier placeholder.","type":"string","default":"spiffe://prx-local/agent/prx-default"},"spiffe_strict_validation":{"description":"When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.","type":"boolean","default":false},"spiffe_trust_bundle_pem":{"description":"Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).","type":["string","null"],"default":null},"trusted_trust_domains":{"description":"Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).","type":"array","default":[],"items":{"type":"string"}},"trust_domain":{"description":"SPIFFE trust domain for new instance identities.","type":"string","default":"prx.local"}}},"A2aPeer":{"description":"Explicit pinned identity and local recipient grant.","type":"object","properties":{"spiffe_id":{"type":"string"},"fingerprints":{"type":"array","items":{"type":"string"}},"address":{"type":"string"},"owner":{"type":"string"},"sessions":{"type":"array","default":["*"],"items":{"type":"string"}},"agents":{"type":"array","default":["*"],"items":{"type":"string"}}},"required":["spiffe_id","fingerprints","address","owner"],"additionalProperties":false},"AgentCompactionConfig":{"description":"Agent context compaction configuration (`[agent.compaction]`).","type":"object","properties":{"keep_recent_messages":{"description":"Number of recent non-system messages to keep after compaction.","type":"integer","format":"uint","default":12,"minimum":0},"max_context_tokens":{"description":"Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.","type":"integer","format":"uint","default":128000,"minimum":0},"memory_flush":{"description":"Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.","type":"boolean","default":true},"mode":{"description":"Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).","$ref":"#/$defs/AgentCompactionMode","default":"switch"},"os_paging":{"description":"Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.","$ref":"#/$defs/OsPagingConfig","default":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"}},"reserve_tokens":{"description":"Tokens reserved for the next model response.","type":"integer","format":"uint","default":4096,"minimum":0}}},"AgentCompactionMode":{"description":"Compaction mode for long conversation contexts.","oneOf":[{"description":"Disable proactive compaction.","type":"string","const":"off"},{"description":"Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.","type":"string","const":"switch"},{"description":"Conservative compaction that prefers summary replacement.","type":"string","const":"safeguard"},{"description":"Aggressive truncation mode for tighter contexts.","type":"string","const":"aggressive"}]},"AgentConfig":{"description":"Agent orchestration configuration (`[agent]` section).","type":"object","properties":{"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"compact_context":{"description":"When true: bootstrap_max_chars=6000. Use for 13B or smaller models.","type":"boolean","default":false},"compaction":{"description":"Context compaction controls (`[agent.compaction]`).","$ref":"#/$defs/AgentCompactionConfig","default":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096}},"low_priority_tools":{"description":"Tool names treated as low-priority when `priority_scheduling_enabled = true`.","type":"array","default":["sessions_spawn","delegate"],"items":{"type":"string"}},"priority_scheduling_enabled":{"description":"Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.","type":"boolean","default":false},"read_only_tool_concurrency_window":{"description":"Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.","type":"integer","format":"uint","default":2,"minimum":0},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}}},"AgentLimits":{"description":"Optional admission limits for rf-started turns of a named agent.","type":"object","properties":{"max_concurrent_turns":{"type":["integer","null"],"format":"uint32","minimum":0},"max_cost_per_day_cents":{"type":["integer","null"],"format":"uint64","minimum":0}},"additionalProperties":false},"AuditConfig":{"description":"Audit logging configuration","type":"object","properties":{"log_path":{"description":"Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).","type":"string","default":"audit.log"},"max_size_mb":{"description":"Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).","type":"integer","format":"uint32","default":100,"minimum":0}}},"AuthConfig":{"description":"Authentication and external credential import configuration (`[auth]` section).","type":"object","properties":{"codex_auth_json_auto_import":{"description":"Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.","type":"boolean","default":false},"codex_auth_json_path":{"description":"Source path for Codex CLI auth.json import.","type":"string","default":"~/.codex/auth.json"}}},"AutonomyConfig":{"type":"object","properties":{"acknowledge_unrestricted_profile":{"description":"Operator acknowledgement for an intentionally unrestricted profile.\nRetained for existing configs; it no longer changes any output or policy behavior.","type":"boolean","default":false},"forbidden_paths":{"description":"Explicit path denylist. Default includes system-critical paths.\n\nFails closed: omitting the key keeps the built-in list rather than\nemptying it, so a partial `[autonomy]` section never removes the\ndenylist.","type":"array","default":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"items":{"type":"string"}},"level":{"description":"Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).","$ref":"#/$defs/AutonomyLevel","default":"full"},"max_cost_per_day_cents":{"description":"Maximum cost per day in cents per policy. Default: unset (no ceiling).","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"scopes":{"description":"Scope-based tool access control: per-user/channel/chat-type allow/deny rules.","$ref":"#/$defs/ScopeConfig","default":{"assign_owners":[],"default":"allow","rules":[]}},"workspace_only":{"description":"Restrict file writes and command paths to the workspace directory. Default: `true`.\n\nFails closed: a `[autonomy]` section that omits this key keeps the\nworkspace restriction on, so a partial section can never widen the\nfilesystem reach by accident.","type":"boolean","default":true}}},"AutonomyLevel":{"description":"How much autonomy the agent has","oneOf":[{"description":"Read-only: can observe but not act","type":"string","const":"readonly"},{"description":"Supervised: acts but requires approval for risky operations","type":"string","const":"supervised"},{"description":"Full: autonomous execution within policy bounds","type":"string","const":"full"}]},"BackendSelection":{"description":"Which decision backend runs: `auto` (the factory's order) or one kind.","type":"string"},"BrowserComputerUseConfig":{"description":"Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.","type":"object","properties":{"api_key":{"description":"Optional bearer token (retained only for config secret handling).","type":["string","null"],"default":null}}},"BrowserConfig":{"description":"Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.","type":"object","properties":{"allowed_domains":{"description":"Allowed domains for `web_fetch` (exact or subdomain match).","type":"array","default":[],"items":{"type":"string"}},"computer_use":{"description":"Computer-use sidecar config (retained only for `api_key` secret handling).","$ref":"#/$defs/BrowserComputerUseConfig","default":{"api_key":null}}}},"ChannelsConfig":{"description":"Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.","type":"object","properties":{"cli":{"description":"Enable the CLI interactive channel. Default: `true`.","type":"boolean","default":true},"dingtalk":{"description":"DingTalk channel configuration.","anyOf":[{"$ref":"#/$defs/DingTalkConfig"},{"type":"null"}]},"discord":{"description":"Discord bot channel configuration.","anyOf":[{"$ref":"#/$defs/DiscordConfig"},{"type":"null"}]},"email":{"description":"Email channel configuration.","anyOf":[{"$ref":"#/$defs/EmailConfig"},{"type":"null"}]},"imessage":{"description":"iMessage channel configuration (macOS only).","anyOf":[{"$ref":"#/$defs/IMessageConfig"},{"type":"null"}]},"irc":{"description":"IRC channel configuration.","anyOf":[{"$ref":"#/$defs/IrcConfig"},{"type":"null"}]},"lark":{"description":"Lark/Feishu channel configuration.","anyOf":[{"$ref":"#/$defs/LarkConfig"},{"type":"null"}]},"linq":{"description":"Linq Partner API channel configuration.","anyOf":[{"$ref":"#/$defs/LinqConfig"},{"type":"null"}]},"mattermost":{"description":"Mattermost bot channel configuration.","anyOf":[{"$ref":"#/$defs/MattermostConfig"},{"type":"null"}]},"nextcloud_talk":{"description":"Nextcloud Talk bot channel configuration.","anyOf":[{"$ref":"#/$defs/NextcloudTalkConfig"},{"type":"null"}]},"qq":{"description":"QQ Official Bot channel configuration.","anyOf":[{"$ref":"#/$defs/QQConfig"},{"type":"null"}]},"ramflux":{"description":"Local ramflux agent-host bridge.","anyOf":[{"$ref":"#/$defs/RamfluxConfig"},{"type":"null"}],"default":null},"signal":{"description":"Signal channel configuration.","anyOf":[{"$ref":"#/$defs/SignalConfig"},{"type":"null"}]},"slack":{"description":"Slack bot channel configuration.","anyOf":[{"$ref":"#/$defs/SlackConfig"},{"type":"null"}]},"telegram":{"description":"Telegram bot channel configuration.","anyOf":[{"$ref":"#/$defs/TelegramConfig"},{"type":"null"}]},"wacli":{"description":"wacli JSON-RPC daemon channel configuration.","anyOf":[{"$ref":"#/$defs/WacliConfig"},{"type":"null"}],"default":null},"webhook":{"description":"Webhook channel configuration.","anyOf":[{"$ref":"#/$defs/WebhookConfig"},{"type":"null"}]},"whatsapp":{"description":"WhatsApp channel configuration (Cloud API or Web mode).","anyOf":[{"$ref":"#/$defs/WhatsAppConfig"},{"type":"null"}]}}},"ChatConfig":{"description":"Interactive chat configuration (`[chat]`).","type":"object","properties":{"daemon":{"description":"How this chat process reaches the daemon it borrows channels from.","$ref":"#/$defs/ChatDaemonConfig","default":{"token":"","url":""}},"max_concurrent_visible_turns":{"description":"Maximum concurrent visible provider turns in the TUI Redux driver.","type":"integer","format":"uint","default":2,"minimum":0}}},"ChatDaemonConfig":{"description":"Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.","type":"object","properties":{"token":{"description":"Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.","type":"string","default":""},"url":{"description":"Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.","type":"string","default":""}}},"CircuitBreakerConfig":{"description":"The per-backend circuit breaker.","type":"object","properties":{"cooldown_secs":{"description":"Seconds the breaker stays open (1 to 3600).","type":"integer","format":"uint32","default":60,"minimum":0},"failure_threshold":{"description":"Consecutive failures before the breaker opens (1 to 100).","type":"integer","format":"uint32","default":5,"minimum":0}}},"ClassificationRule":{"description":"A single classification rule mapping message patterns to a model hint.","type":"object","properties":{"hint":{"description":"Must match a `[[model_routes]]` hint value.","type":"string"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"max_length":{"description":"Only match if message length <= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"min_length":{"description":"Only match if message length >= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"patterns":{"description":"Case-sensitive literal matches (for \"```\", \"fn \", etc.).","type":"array","default":[],"items":{"type":"string"}},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0}},"required":["hint"]},"CloudflareTunnelConfig":{"type":"object","properties":{"token":{"description":"Cloudflare Tunnel token (from Zero Trust dashboard)","type":"string"}},"required":["token"]},"ComplianceConfig":{"type":"object","properties":{"eu_ai_act":{"$ref":"#/$defs/EuAiActComplianceConfig","default":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null}},"interaction_notice":{"$ref":"#/$defs/InteractionNoticeConfig","default":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}}},"ComposioConfig":{"description":"Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.","type":"object","properties":{"api_key":{"description":"Composio API key (stored encrypted when secrets.encrypt = true)","type":["string","null"],"default":null},"entity_id":{"description":"Default entity ID for multi-user setups","type":"string","default":"default"}}},"CostConfig":{"description":"Cost tracking and budget enforcement configuration (`[cost]` section).","type":"object","properties":{"allow_override":{"description":"Allow requests to exceed budget with --override flag (default: false)","type":"boolean","default":false},"daily_limit_usd":{"description":"Daily spending limit in USD (default: unset, no limit; 0 refuses every priced turn)","type":["number","null"],"format":"double","default":null},"monthly_limit_usd":{"description":"Monthly spending limit in USD (default: unset, no limit)","type":["number","null"],"format":"double","default":null},"prices":{"description":"Per-model pricing (USD per 1M tokens)","type":"object","additionalProperties":{"$ref":"#/$defs/ModelPricing"},"default":{}},"warn_at_percent":{"description":"Warn when spending reaches this percentage of a configured limit (default: 80)","type":"integer","format":"uint8","default":80,"maximum":255,"minimum":0}}},"CredentialRefSetting":{"description":"Which credential a decision backend uses. A reference, never a secret.","type":"string"},"CronConfig":{"description":"Cron job configuration (`[cron]` section).","type":"object","properties":{"max_run_history":{"description":"Maximum number of historical cron run records to retain. Default: `50`.","type":"integer","format":"uint32","default":50,"minimum":0}}},"CustomTunnelConfig":{"type":"object","properties":{"health_url":{"description":"Optional URL to check tunnel health","type":["string","null"]},"start_command":{"description":"Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"","type":"string"},"url_pattern":{"description":"Optional regex to extract public URL from command stdout","type":["string","null"]}},"required":["start_command"]},"DecisionBackendConfig":{"description":"The decision backend (`[decision_engine.backend]`).","type":"object","properties":{"circuit_breaker":{"description":"The circuit breaker.","$ref":"#/$defs/CircuitBreakerConfig","default":{"cooldown_secs":60,"failure_threshold":5}},"credential_ref":{"description":"The credential reference: `\"\"`, `\"none\"` or `cred-`.","$ref":"#/$defs/CredentialRefSetting","default":""},"endpoint":{"description":"The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.","type":"string","default":""},"kind":{"description":"`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).","$ref":"#/$defs/BackendSelection","default":"auto"},"max_request_bytes":{"description":"Largest request body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":65536,"minimum":0},"max_response_bytes":{"description":"Largest response body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":262144,"minimum":0},"model":{"description":"The model the endpoint serves; one exact version for a hosted\nservice.","type":"string","default":""},"pinned_snapshot":{"description":"The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.","type":"string"},"remote_enabled":{"description":"Whether decision state may leave this machine. Default `false`.","type":"boolean","default":false},"timeout_ms":{"description":"Transport timeout (10 ms up to the extra latency budget).","type":"integer","format":"uint32","default":250,"minimum":0}}},"DecisionEngineConfig":{"type":"object","properties":{"backend":{"anyOf":[{"$ref":"#/$defs/DecisionBackendConfig"},{"type":"null"}]},"candidates":{"type":"integer","format":"uint32","default":5,"minimum":0},"enabled":{"type":"boolean","default":false},"mode":{"$ref":"#/$defs/DecisionMode","default":"pre"},"observe_queue":{"type":"integer","format":"uint32","default":64,"minimum":0},"prompt_budget_tokens":{"type":"integer","format":"uint32","default":300,"minimum":0},"telemetry_cap":{"type":"integer","format":"uint32","default":1000,"minimum":0},"timeout_ms":{"type":"integer","format":"uint32","default":1500,"minimum":0},"latency_budget_ms":{"description":"The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.","type":"integer","format":"uint64","default":500,"minimum":0},"token_ratio_limit":{"description":"Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).","type":"number","format":"float","default":0.3499999940395355},"max_candidates":{"description":"The most candidates a turn considers (1 to 32).","type":"integer","format":"uint8","default":12,"maximum":255,"minimum":0}}},"DecisionMode":{"type":"string","enum":["pre","post","both"]},"DeclarationOfConformityConfig":{"type":"object","properties":{"applicable_union_law":{"type":"array","default":[],"items":{"type":"string"}},"artifact_path":{"type":["string","null"],"default":null},"artifact_version":{"type":["string","null"],"default":null},"conformity_assessment_procedure":{"type":["string","null"],"default":null},"conformity_statement":{"type":["string","null"],"default":null},"harmonised_standards":{"type":"array","default":[],"items":{"type":"string"}},"issue_date":{"type":["string","null"],"default":null},"issue_place":{"type":["string","null"],"default":null},"notified_body_certificate":{"type":["string","null"],"default":null},"notified_body_identification_number":{"type":["string","null"],"default":null},"notified_body_name":{"type":["string","null"],"default":null},"personal_data_compliance_statement":{"type":["string","null"],"default":null},"processes_personal_data":{"type":"boolean","default":false},"provider_address":{"type":["string","null"],"default":null},"provider_name":{"type":["string","null"],"default":null},"signer_function":{"type":["string","null"],"default":null},"signer_name":{"type":["string","null"],"default":null},"signer_on_behalf_of":{"type":["string","null"],"default":null},"sole_responsibility_statement":{"type":["string","null"],"default":null},"standards_not_applicable_reason":{"type":["string","null"],"default":null},"system_name":{"type":["string","null"],"default":null},"system_reference":{"type":["string","null"],"default":null},"system_type":{"type":["string","null"],"default":null}}},"DelegateAgentConfig":{"description":"Configuration for a delegate sub-agent used by the `delegate` tool.","type":"object","properties":{"agentic":{"description":"Agentic sub-agent mode (multi-turn tool-call loop). Default true; an\nexplicit `false` makes the agent answer-only with no tools.","type":"boolean","default":true},"allowed_tools":{"description":"Allowlist of tool names available to the sub-agent in agentic mode.\nEmpty or omitted means all tools, the same as `[\"*\"]`.","type":"array","default":[],"items":{"type":"string"}},"api_key":{"description":"Optional API key override","type":["string","null"],"default":null},"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"autonomy":{"description":"The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.","anyOf":[{"$ref":"#/$defs/AutonomyLevel"},{"type":"null"}]},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"enabled":{"description":"Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.","type":"boolean","default":true},"identity_dir":{"description":"Optional identity files directory relative to workspace root.","type":["string","null"],"default":null},"limits":{"$ref":"#/$defs/AgentLimits","default":{"max_concurrent_turns":null,"max_cost_per_day_cents":null}},"max_depth":{"description":"Max recursion depth for nested delegation","type":"integer","format":"uint32","default":8,"minimum":0},"memory_scope":{"description":"Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".","type":["string","null"],"default":null},"model":{"description":"Model name","type":"string"},"provider":{"description":"Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")","type":"string"},"spawn_enabled":{"description":"Whether this agent is allowed to be targeted by sessions_spawn (default: true).","type":["boolean","null"],"default":null},"system_prompt":{"description":"Optional system prompt for the sub-agent","type":["string","null"],"default":null},"temperature":{"description":"Temperature override","type":["number","null"],"format":"double","default":null},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}},"required":["provider","model"]},"DingTalkConfig":{"description":"DingTalk configuration for Stream Mode messaging","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"client_id":{"description":"Client ID (AppKey) from DingTalk developer console","type":"string"},"client_secret":{"description":"Client Secret (AppSecret) from DingTalk developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["client_id","client_secret"]},"DiscordConfig":{"description":"Discord bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Discord user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Discord bot token (from Discord Developer Portal).","type":"string"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"guild_id":{"description":"Optional guild (server) ID to restrict the bot to a single guild.","type":["string","null"]},"listen_to_bots":{"description":"When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.","type":"boolean","default":false}},"required":["bot_token"]},"DmPolicy":{"description":"Policy for direct-message handling.","oneOf":[{"description":"Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).","type":"string","const":"pairing"},{"description":"Accept only senders listed in `allowed_from`.","type":"string","const":"allowlist"},{"description":"Accept any direct sender.","type":"string","const":"open"},{"description":"Ignore direct messages.","type":"string","const":"disabled"}]},"DockerRuntimeConfig":{"description":"Docker runtime configuration (`[runtime.docker]` section).","type":"object","properties":{"allowed_workspace_roots":{"description":"Optional workspace root allowlist for Docker mount validation.","type":"array","default":[],"items":{"type":"string"}},"cpu_limit":{"description":"Optional CPU limit (`None` = no explicit limit).","type":["number","null"],"format":"double","default":1.0},"image":{"description":"Runtime image used to execute shell commands.","type":"string","default":"alpine:3.20"},"memory_limit_mb":{"description":"Optional memory limit in MB (`None` = no explicit limit).","type":["integer","null"],"format":"uint64","default":512,"minimum":0},"mount_workspace":{"description":"Mount configured workspace into `/workspace`.","type":"boolean","default":true},"network":{"description":"Docker network mode (`none`, `bridge`, etc.).","type":"string","default":"none"},"read_only_rootfs":{"description":"Mount root filesystem as read-only.","type":"boolean","default":true}}},"EmailConfig":{"description":"Email channel configuration","type":"object","properties":{"allowed_senders":{"description":"Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)","type":"array","default":[],"items":{"type":"string"}},"from_address":{"description":"From address for outgoing emails","type":"string"},"idle_timeout_secs":{"description":"IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes","type":"integer","format":"uint64","default":1740,"minimum":0},"imap_folder":{"description":"IMAP folder to poll (default: INBOX)","type":"string","default":"INBOX"},"imap_host":{"description":"IMAP server hostname","type":"string"},"imap_port":{"description":"IMAP server port (default: 993 for TLS)","type":"integer","format":"uint16","default":993,"maximum":65535,"minimum":0},"password":{"description":"Email password for authentication","type":"string"},"smtp_host":{"description":"SMTP server hostname","type":"string"},"smtp_port":{"description":"SMTP server port (default: 465 for TLS)","type":"integer","format":"uint16","default":465,"maximum":65535,"minimum":0},"smtp_tls":{"description":"Use TLS for SMTP (default: true)","type":"boolean","default":true},"username":{"description":"Email username for authentication","type":"string"}},"required":["imap_host","smtp_host","username","password","from_address"]},"EmbeddingRouteConfig":{"description":"Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"dimensions":{"description":"Optional embedding dimension override for this route","type":["integer","null"],"format":"uint","default":null,"minimum":0},"hint":{"description":"Route hint name (e.g. \"semantic\", \"archive\", \"faq\")","type":"string"},"model":{"description":"Embedding model to use with that provider","type":"string"},"provider":{"description":"Embedding provider (`none`, `openai`, or `custom:`)","type":"string"}},"required":["hint","provider","model"]},"EuAiActClassificationConfig":{"type":"object","properties":{"assessed_at":{"type":["string","null"],"default":null},"owner":{"type":["string","null"],"default":null},"status":{"$ref":"#/$defs/EuAiActRiskClassification","default":"unclassified"}}},"EuAiActComplianceConfig":{"type":"object","properties":{"classification":{"$ref":"#/$defs/EuAiActClassificationConfig","default":{"assessed_at":null,"owner":null,"status":"unclassified"}},"declaration":{"$ref":"#/$defs/DeclarationOfConformityConfig","default":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null}},"incident_store_path":{"type":["string","null"],"default":null}}},"EuAiActRiskClassification":{"type":"string","enum":["unclassified","high_risk","not_high_risk"]},"FitnessConfig":{"description":"Calendar schedule, evidence thresholds, and retention for fitness v2.","type":"object","properties":{"auto_run":{"description":"Run the daily fitness worker in daemon mode.","type":"boolean","default":true},"max_backfill_days":{"description":"Maximum number of closed days recovered after downtime.","type":"integer","format":"uint32","default":7,"minimum":0},"min_coverage":{"description":"Minimum available metric weight required to publish a final score.","type":"number","format":"double","default":0.6},"min_samples":{"description":"Minimum samples required before an evidence-derived subscore is usable.","type":"integer","format":"uint","default":5,"minimum":0},"retention_days":{"description":"Number of daily JSON reports retained on disk.","type":"integer","format":"uint32","default":180,"minimum":0},"run_at":{"description":"Local wall-clock time (`HH:MM`) at which the previous day is scored.","type":"string","default":"00:10"},"timezone":{"description":"IANA timezone used to define closed calendar days.","type":"string","default":"UTC"}}},"GatewayConfig":{"description":"Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.","type":"object","properties":{"allow_public_bind":{"description":"Allow binding to non-localhost without a tunnel (default: false)","type":"boolean","default":false},"api_rate_limit_per_minute":{"description":"Max `/api/*` requests per minute per authenticated token.","type":"integer","format":"uint32","default":60,"minimum":0},"channel_webhook_dedup_ttl_secs":{"description":"How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.","type":"integer","format":"uint64","default":86400,"minimum":0},"host":{"description":"Gateway host (default: 127.0.0.1)","type":"string","default":"127.0.0.1"},"idempotency_max_keys":{"description":"Maximum distinct idempotency keys retained in memory.","type":"integer","format":"uint","default":10000,"minimum":0},"idempotency_ttl_secs":{"description":"TTL for webhook idempotency keys.","type":"integer","format":"uint64","default":300,"minimum":0},"pair_rate_limit_per_minute":{"description":"Max `/pair` requests per minute per client key.","type":"integer","format":"uint32","default":10,"minimum":0},"paired_tokens":{"description":"Paired bearer tokens (managed automatically, not user-edited)","type":"array","default":[],"items":{"type":"string"}},"port":{"description":"Gateway port (default: 16830)","type":"integer","format":"uint16","default":16830,"maximum":65535,"minimum":0},"rate_limit_max_keys":{"description":"Maximum distinct client keys tracked by gateway rate limiter maps.","type":"integer","format":"uint","default":10000,"minimum":0},"require_pairing":{"description":"Require pairing before accepting requests (default: true)","type":"boolean","default":true},"targeted_agents":{"description":"Switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). Default true. While false, any\notherwise-valid named target answers 409 `agent_disabled` and never\nruns as Main.","type":"boolean","default":true},"trust_forwarded_headers":{"description":"Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.","type":"boolean","default":false},"webhook_rate_limit_per_minute":{"description":"Max `/webhook` requests per minute per client key.","type":"integer","format":"uint32","default":60,"minimum":0}}},"GroupPolicy":{"description":"Policy for group-message handling.","oneOf":[{"description":"Accept only groups listed in `group_allow_from`.","type":"string","const":"allowlist"},{"description":"Accept any group.","type":"string","const":"open"},{"description":"Ignore group messages.","type":"string","const":"disabled"}]},"GroupReplyMode":{"description":"How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.","oneOf":[{"description":"Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).","type":"string","const":"off"},{"description":"Reply only when the bot is @-mentioned (legacy `mention_only = true`).","type":"string","const":"mention-only"},{"description":"Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).","type":"string","const":"smart"}]},"HeartbeatConfig":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]` section).","type":"object","properties":{"active_hours":{"description":"Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.","type":"array","default":[8,23],"items":{"type":"integer","format":"uint8","maximum":255,"minimum":0}},"interval_minutes":{"description":"Interval in minutes between heartbeat pings. Default: `30`.","type":"integer","format":"uint32","default":30,"minimum":0},"prompt":{"description":"Prompt used by heartbeat worker when dispatching tasks.","type":"string","default":"Check HEARTBEAT.md and follow instructions."}}},"HttpRequestConfig":{"description":"HTTP request tool configuration (`[http_request]` section).","type":"object","properties":{"max_response_size":{"description":"Maximum response size in bytes (default: 1MB)","type":"integer","format":"uint","default":1000000,"minimum":0},"timeout_secs":{"description":"Request timeout in seconds (default: 30)","type":"integer","format":"uint64","default":30,"minimum":0}}},"IMessageConfig":{"description":"iMessage channel configuration (macOS only).","type":"object","properties":{"allowed_contacts":{"description":"Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.","type":"array","items":{"type":"string"}},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["allowed_contacts"]},"IdentityBindingConfig":{"description":"Startup identity binding entry (`[[identity_bindings]]`).","type":"object","properties":{"channel":{"type":"string"},"channel_account":{"type":"string"},"display_name":{"type":["string","null"],"default":null},"user_id":{"type":"string"}},"required":["user_id","channel","channel_account"]},"IdentityConfig":{"description":"Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.","type":"object","properties":{"aieos_inline":{"description":"Inline AIEOS JSON (alternative to file path)","type":["string","null"],"default":null},"aieos_path":{"description":"Path to AIEOS JSON file (relative to workspace)","type":["string","null"],"default":null},"format":{"description":"Identity format: \"openclaw\" (default) or \"aieos\"","type":"string","default":"openclaw"}}},"InteractionNoticeApplicability":{"type":"string","enum":["required","not_applicable"]},"InteractionNoticeConfig":{"type":"object","properties":{"applicability":{"$ref":"#/$defs/InteractionNoticeApplicability","default":"required"},"exception_owner":{"type":["string","null"],"default":null},"exception_reviewed_at":{"type":["string","null"],"default":null},"text":{"type":"string","default":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers."},"version":{"type":"string","default":"1"}}},"IrcConfig":{"description":"IRC channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed nicknames (case-insensitive) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"channels":{"description":"Channels to join on connect","type":"array","default":[],"items":{"type":"string"}},"mention_only":{"description":"When true, only process channel/group messages that mention the bot.","type":"boolean","default":false},"nickname":{"description":"Bot nickname","type":"string"},"nickserv_password":{"description":"NickServ IDENTIFY password","type":["string","null"]},"port":{"description":"IRC server port (default: 6697 for TLS)","type":"integer","format":"uint16","default":6697,"maximum":65535,"minimum":0},"sasl_password":{"description":"SASL PLAIN password (IRCv3)","type":["string","null"]},"server":{"description":"IRC server hostname","type":"string"},"server_password":{"description":"Server password (for bouncers like ZNC)","type":["string","null"]},"username":{"description":"Username (defaults to nickname if not set)","type":["string","null"]},"verify_tls":{"description":"Verify TLS certificate (default: true)","type":["boolean","null"]}},"required":["server","nickname"]},"LarkConfig":{"description":"Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from Lark/Feishu developer console","type":"string"},"app_secret":{"description":"App Secret from Lark/Feishu developer console","type":"string"},"encrypt_key":{"description":"Encrypt key for webhook message decryption (optional)","type":["string","null"],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"port":{"description":"HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"receive_mode":{"description":"Event receive mode: \"websocket\" (default) or \"webhook\"","$ref":"#/$defs/LarkReceiveMode","default":"websocket"},"use_feishu":{"description":"Whether to use the Feishu (Chinese) endpoint instead of Lark (International)","type":"boolean","default":false},"verification_token":{"description":"Verification token for webhook validation (optional)","type":["string","null"],"default":null}},"required":["app_id","app_secret"]},"LarkReceiveMode":{"description":"How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.","type":"string","enum":["websocket","webhook"]},"LinqConfig":{"type":"object","properties":{"allowed_senders":{"description":"Allowed sender handles (phone numbers) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"api_token":{"description":"Linq Partner API token (Bearer auth)","type":"string"},"from_phone":{"description":"Phone number to send from (E.164 format)","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"signing_secret":{"description":"Webhook signing secret for signature verification","type":["string","null"],"default":null}},"required":["api_token","from_phone"]},"MattermostConfig":{"description":"Mattermost bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Mattermost user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Mattermost bot access token.","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.","type":["boolean","null"],"default":null},"thread_replies":{"description":"When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.","type":["boolean","null"],"default":null},"url":{"description":"Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).","type":"string"}},"required":["url","bot_token"]},"McpConfig":{"type":"object","properties":{"servers":{"description":"Named MCP server definitions","type":"object","additionalProperties":{"$ref":"#/$defs/McpServerConfig"},"default":{}},"workspace_servers":{"description":"Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.","$ref":"#/$defs/WorkspaceMcpServers"}}},"McpServerConfig":{"type":"object","properties":{"allow_tools":{"description":"Optional allow-list of exposed tools (empty = all)","type":"array","default":[],"items":{"type":"string"}},"args":{"description":"Command args for stdio mode","type":"array","default":[],"items":{"type":"string"}},"command":{"description":"Command for stdio mode","type":["string","null"],"default":null},"deny_tools":{"description":"Optional deny-list of exposed tools","type":"array","default":[],"items":{"type":"string"}},"env":{"description":"Environment variables for stdio mode","type":"object","additionalProperties":{"type":"string"},"default":{}},"request_timeout_ms":{"description":"Request timeout in milliseconds","type":"integer","format":"uint64","default":30000,"minimum":0},"startup_timeout_ms":{"description":"Startup timeout in milliseconds","type":"integer","format":"uint64","default":10000,"minimum":0},"tool_name_prefix":{"description":"Prefix used in tool naming and routing","type":"string","default":"mcp"},"transport":{"description":"Transport type: stdio or http","$ref":"#/$defs/McpTransport","default":"stdio"},"url":{"description":"URL for HTTP mode (streamable HTTP endpoint)","type":["string","null"],"default":null},"working_dir":{"description":"Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).","type":["string","null"]}}},"McpServerRuntimeConfig":{"type":"object","properties":{"allowed_origins":{"description":"Allowed browser origins for future streamable HTTP clients.","type":"array","default":["claude.ai","openai.com","localhost"],"items":{"type":"string"}},"bind":{"description":"Advertised bind address. The gateway may still be started with a CLI port override.","type":"string","default":"127.0.0.1:16831"},"exposed_tools":{"description":"Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.","type":"array","default":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"items":{"type":"string"}},"jwt_algorithms":{"description":"Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.","type":"array","default":["RS256"],"items":{"type":"string"}},"jwt_audience":{"description":"Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.","type":["string","null"],"default":null},"jwt_issuer":{"description":"Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.","type":["string","null"],"default":null},"jwt_jwks":{"description":"Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.","type":["string","null"],"default":null},"jwt_jwks_cache_ttl_secs":{"description":"Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.","type":"integer","format":"uint64","default":300,"minimum":0},"jwt_jwks_uri":{"description":"Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.","type":["string","null"],"default":null},"jwt_public_key_pem":{"description":"PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.","type":["string","null"],"default":null},"rate_limit_rps":{"description":"Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.","type":"integer","format":"uint32","default":10,"minimum":0},"require_auth":{"description":"Require an authenticated external identity for mutating calls.","type":"boolean","default":true}}},"McpTransport":{"type":"string","enum":["stdio","http"]},"MediaConfig":{"description":"Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.","type":"object","properties":{"audio_model":{"description":"Audio model name (Ollama model or OpenAI model). Default: \"whisper\".","type":"string","default":"whisper"},"audio_ollama_url":{"description":"Ollama base URL for audio transcription. Default: \"http://localhost:11434\".","type":"string","default":"http://localhost:11434"},"audio_provider":{"description":"Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".","type":"string","default":"none"},"max_audio_size_mb":{"description":"Maximum audio attachment size in MiB. Default: 20.","type":"integer","format":"uint","default":20,"minimum":0},"max_video_size_mb":{"description":"Maximum video attachment size in MiB. Default: 50.","type":"integer","format":"uint","default":50,"minimum":0},"video_max_frames":{"description":"Maximum video frames to extract per video. Default: 4.","type":"integer","format":"uint","default":4,"minimum":0},"video_provider":{"description":"Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".","type":"string","default":"none"}}},"MemoryConfig":{"description":"Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.","type":"object","properties":{"acl_enabled":{"description":"Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.","type":"boolean","default":false},"archive_after_days":{"description":"Archive daily/session files older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"auto_hydrate":{"description":"Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing","type":"boolean","default":true},"auto_save":{"description":"Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.","type":"boolean","default":true},"backend":{"description":"\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).","type":"string","default":"sqlite"},"conversation_retention_days":{"description":"For sqlite backend: prune conversation rows older than this many days","type":"integer","format":"uint32","default":3,"minimum":0},"daily_retention_days":{"description":"For sqlite backend: prune daily rows older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"embedding_cache_size":{"description":"Max embedding cache entries before LRU eviction","type":"integer","format":"uint","default":10000,"minimum":0},"embedding_dimensions":{"description":"Embedding vector dimensions","type":"integer","format":"uint","default":384,"minimum":0},"embedding_model":{"description":"Embedding model name (e.g. \"text-embedding-3-small\")","type":"string","default":"prx-local-hash-v1"},"embedding_provider":{"description":"Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"","type":"string","default":"local"},"events":{"description":"Raw/quasi-raw message event recording controls (`[memory.events]`).","$ref":"#/$defs/MemoryEventsConfig","default":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true}},"keyword_weight":{"description":"Weight for keyword BM25 in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.3},"legacy_conversation_turns_visible":{"description":"Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.","type":"boolean","default":true},"lucid_budget":{"description":"Token budget for lucid (replaces OPENPRX_LUCID_BUDGET)","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"lucid_cmd":{"description":"Path to lucid binary (replaces OPENPRX_LUCID_CMD)","type":["string","null"],"default":null},"lucid_failure_cooldown_ms":{"description":"Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)","type":"integer","format":"uint64","default":60000,"minimum":0},"lucid_local_hit_threshold":{"description":"Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)","type":"integer","format":"uint","default":3,"minimum":0},"lucid_recall_timeout_ms":{"description":"Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)","type":"integer","format":"uint64","default":5000,"minimum":0},"lucid_store_timeout_ms":{"description":"Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)","type":"integer","format":"uint64","default":3000,"minimum":0},"min_relevance_score":{"description":"Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4","type":"number","format":"double","default":0.4},"purge_after_days":{"description":"Purge archived files older than this many days","type":"integer","format":"uint32","default":30,"minimum":0},"semantic":{"description":"Semantic memory promotion controls (`[memory.semantic]`).","$ref":"#/$defs/MemorySemanticConfig","default":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30}},"sqlite_open_timeout_secs":{"description":"For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"sqlite_read_pool_size":{"description":"For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"vector_candidate_cap":{"description":"How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.","type":"integer","format":"uint","default":2000,"minimum":0},"vector_weight":{"description":"Weight for vector similarity in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.7}}},"MemoryEventsConfig":{"description":"Raw message event recording configuration (`[memory.events]`).","type":"object","properties":{"record_assistant_messages":{"description":"Record assistant replies.","type":"boolean","default":true},"record_tool_events":{"description":"Record tool/event payloads by default.","type":"boolean","default":false},"record_user_messages":{"description":"Record inbound/user messages.","type":"boolean","default":true}}},"MemorySemanticConfig":{"description":"Semantic memory promotion configuration (`[memory.semantic]`).","type":"object","properties":{"auto_promote_assistant_messages":{"description":"Auto-promote eligible assistant messages. Disabled by default to reduce noise.","type":"boolean","default":false},"auto_promote_user_messages":{"description":"Auto-promote eligible user messages into long-term semantic memories.","type":"boolean","default":true},"min_chars":{"description":"Minimum content length for semantic auto-promotion.","type":"integer","format":"uint","default":30,"minimum":0}}},"MemoryWebhookConfig":{"type":"object","properties":{"bind":{"description":"Socket address for the receiver (e.g. \"0.0.0.0:16899\").","type":"string","default":"0.0.0.0:16899"},"signing_secret":{"description":"Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.","type":["string","null"],"default":null},"token":{"description":"Required bearer token for incoming webhook events.","type":["string","null"],"default":null}}},"ModelOperationSetting":{"description":"The operations a `[[providers.models]]` entry may list.","type":"string","enum":["chat","embedding","decision_endpoint","rerank","image_generation","audio_generation","video_generation"]},"ModelPricing":{"description":"Per-model pricing entry (USD per 1M tokens).","type":"object","properties":{"cache_read":{"description":"Cache read input price per 1M tokens.","type":"number","format":"double","default":0.0},"cache_write":{"description":"Cache write/creation input price per 1M tokens.","type":"number","format":"double","default":0.0},"input":{"description":"Input price per 1M tokens","type":"number","format":"double","default":0.0},"output":{"description":"Output price per 1M tokens","type":"number","format":"double","default":0.0}}},"ModelRouteConfig":{"description":"Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"hint":{"description":"Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")","type":"string"},"level":{"type":["string","null"]},"model":{"description":"Model to use with that provider","type":"string"},"provider":{"description":"Provider to route to (must match a known provider name)","type":"string"},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true,"required":["hint","provider","model"]},"ModelSettings":{"description":"A model level plus explicit parameter overrides in `[model_settings.\"\"]`.","type":"object","properties":{"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"level":{"type":["string","null"]},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true},"MultimodalConfig":{"description":"Multimodal (image) handling configuration (`[multimodal]` section).","type":"object","properties":{"allow_remote_fetch":{"description":"Allow fetching remote image URLs (http/https). Enabled by default.","type":"boolean","default":true},"max_image_size_mb":{"description":"Maximum image payload size in MiB before base64 encoding.","type":"integer","format":"uint","default":5,"minimum":0},"max_images":{"description":"Maximum number of image attachments accepted per request.","type":"integer","format":"uint","default":4,"minimum":0}}},"NextcloudTalkConfig":{"description":"Nextcloud Talk bot configuration (webhook receive + OCS send API).","type":"object","properties":{"allowed_users":{"description":"Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Bot app token used for OCS API bearer auth.","type":"string"},"base_url":{"description":"Nextcloud base URL (e.g. \"https://cloud.example.com\").","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"webhook_secret":{"description":"Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).","type":["string","null"],"default":null}},"required":["base_url","app_token"]},"NgrokTunnelConfig":{"type":"object","properties":{"auth_token":{"description":"ngrok auth token","type":"string"},"domain":{"description":"Optional custom domain","type":["string","null"]}},"required":["auth_token"]},"NodeServerConfig":{"description":"Node daemon runtime config used by `prx-node`.","type":"object","properties":{"allowed_commands":{"description":"Command allowlist matched on first token. Default: empty, which allows any\ncommand from an authenticated caller; `[\"*\"]` means the same.","type":"array","default":[],"items":{"type":"string"}},"bearer_token":{"description":"Required bearer token for /rpc.","type":"string","default":""},"blocked_commands":{"description":"Command denylist matched on first token. Always enforced.","type":"array","default":[],"items":{"type":"string"}},"exec_timeout_ms":{"description":"Default command timeout in milliseconds.","type":"integer","format":"uint64","default":15000,"minimum":0},"hmac_secret":{"description":"Optional HMAC signing secret.","type":["string","null"],"default":null},"listen_addr":{"description":"Listen address for node daemon.","type":"string","default":"127.0.0.1:8787"},"max_concurrent_tasks":{"description":"Maximum number of concurrent async command tasks.","type":"integer","format":"uint","default":8,"minimum":0},"max_output_bytes":{"description":"Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.","type":"integer","format":"uint","default":1048576,"minimum":0},"sandbox_root":{"description":"Sandbox root directory for read/write/cwd constraints.","type":"string","default":"."},"task_result_ttl_ms":{"description":"TTL for completed task results in milliseconds.","type":"integer","format":"uint64","default":3600000,"minimum":0},"tls_cert":{"description":"TLS certificate path (PEM).","type":["string","null"],"default":null},"tls_key":{"description":"TLS private key path (PEM).","type":["string","null"],"default":null},"tls_required":{"description":"Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.","type":"boolean","default":true}}},"NodesConfig":{"description":"Remote node proxy configuration for core-side RPC calls and node daemon defaults.","type":"object","properties":{"nodes":{"description":"Configured remote nodes.","type":"array","default":[],"items":{"$ref":"#/$defs/RemoteNodeConfig"}},"request_timeout_ms":{"description":"Default request timeout for node RPC calls.","type":"integer","format":"uint64","default":15000,"minimum":0},"retry_max":{"description":"Default max retries for node RPC calls.","type":"integer","format":"uint8","default":2,"maximum":255,"minimum":0},"server":{"description":"Embedded node server defaults used by `prx-node`.","$ref":"#/$defs/NodeServerConfig","default":{"allowed_commands":[],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}}},"ObservabilityConfig":{"description":"Observability backend configuration (`[observability]` section).","type":"object","properties":{"backend":{"description":"\"none\" | \"log\" | \"prometheus\" | \"otel\"","type":"string","default":"none"},"otel_endpoint":{"description":"OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".","type":["string","null"],"default":null},"otel_service_name":{"description":"Service name reported to the OTel collector. Defaults to \"prx\".","type":["string","null"],"default":null}}},"OllamaProviderConfig":{"description":"Ollama-specific request options (`[providers.ollama]`).","type":"object","properties":{"num_ctx":{"description":"Explicit context window sent as Ollama `options.num_ctx`.","type":["integer","null"],"format":"uint","default":null,"minimum":0}}},"OsPagingConfig":{"description":"Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.","type":"object","properties":{"eviction_threshold":{"description":"Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.","type":"number","format":"double","default":0.7},"keep_recent_messages":{"description":"Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).","type":"integer","format":"uint","default":12,"minimum":0},"max_recalled_pages":{"description":"Maximum number of evicted pages (document chunks) recalled per turn.","type":"integer","format":"uint","default":10,"minimum":0},"proactive_retrieval":{"description":"Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.","type":"boolean","default":true},"retrieval_injection_role":{"description":"Role under which recalled pages are injected.","$ref":"#/$defs/RetrievalInjectionRole","default":"system"}}},"PluginsConfig":{"description":"WASM plugin runtime configuration.","type":"object","properties":{"enabled":{"description":"Load WASM plugins from `/plugins`. Default: `false`.","type":"boolean","default":false}},"additionalProperties":false},"ProviderModelConfig":{"description":"One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.","type":"object","properties":{"context_window":{"description":"The model's context window in tokens.","type":["integer","null"],"format":"uint32","minimum":0},"model":{"description":"The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.","type":["string","null"]},"native_tools":{"description":"Whether the model accepts native tool calls.","type":["boolean","null"]},"operations":{"description":"The complete list of operations the model executes; every operation not\nlisted is unsupported.","type":["array","null"],"items":{"$ref":"#/$defs/ModelOperationSetting"}},"provider":{"description":"The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.","type":"string"},"streaming":{"description":"Whether the model streams responses.","type":["boolean","null"]},"structured_output":{"description":"Whether the model honours a JSON-schema response format.","type":["boolean","null"]},"tool_call_dialect":{"description":"The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema_dialect":{"description":"The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]},"vision_input":{"description":"Whether the model accepts image input.","type":["boolean","null"]}},"required":["provider"]},"ProviderToolDialectConfig":{"description":"One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.","type":"object","properties":{"model":{"description":"The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.","type":["string","null"]},"provider":{"description":"The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.","type":"string"},"tool_call":{"description":"The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema":{"description":"The tool-schema dialect the endpoint accepts.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]}},"required":["provider"]},"ProvidersConfig":{"description":"Provider-specific runtime configuration (`[providers]`).","type":"object","properties":{"models":{"description":"Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.","type":"array","items":{"$ref":"#/$defs/ProviderModelConfig"}},"ollama":{"description":"Ollama-specific request options (`[providers.ollama]`).","$ref":"#/$defs/OllamaProviderConfig","default":{"num_ctx":null}},"tool_dialects":{"description":"Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).","type":"array","items":{"$ref":"#/$defs/ProviderToolDialectConfig"}}}},"ProxyConfig":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).","type":"object","properties":{"all_proxy":{"description":"Fallback proxy URL for all schemes.","type":["string","null"],"default":null},"http_proxy":{"description":"Proxy URL for HTTP requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"https_proxy":{"description":"Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"no_proxy":{"description":"No-proxy bypass list. Same format as NO_PROXY.","type":"array","default":[],"items":{"type":"string"}},"scope":{"description":"Proxy application scope.","$ref":"#/$defs/ProxyScope","default":"prx"},"services":{"description":"Service selectors used when scope = \"services\".","type":"array","default":[],"items":{"type":"string"}}}},"ProxyScope":{"description":"Proxy application scope — determines which outbound traffic uses the proxy.","oneOf":[{"description":"Use system environment proxy variables only.","type":"string","const":"environment"},{"description":"Apply proxy to all OpenPRX-managed HTTP traffic (default).","type":"string","const":"prx"},{"description":"Apply proxy only to explicitly listed service selectors.","type":"string","const":"services"}]},"QQConfig":{"description":"QQ Official Bot configuration (Tencent QQ Bot SDK)","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs. Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from QQ Bot developer console","type":"string"},"app_secret":{"description":"App Secret from QQ Bot developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["app_id","app_secret"]},"QueryClassificationConfig":{"description":"Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.","type":"object","properties":{"rules":{"description":"Classification rules evaluated in priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/ClassificationRule"}}}},"RamfluxAccountConfig":{"description":"Persona for one ramflux AI account. Missing fields fall back to the global agent.","type":"object","properties":{"cross_conversation_retrieval":{"description":"Cross-conversation memory retrieval. Off unless the owner sets it.","type":"boolean","default":false},"model":{"type":["string","null"],"default":null},"provider":{"type":["string","null"],"default":null},"scope_profile":{"type":["string","null"],"default":null},"system_prompt_file":{"description":"Path to a system-prompt file. Relative paths are resolved from the workspace.","type":["string","null"],"default":null}},"additionalProperties":false},"RamfluxAttachmentFetch":{"description":"Per-turn caps for `attachment.fetch`.","type":"object","properties":{"max_bytes":{"type":"integer","format":"uint64","default":5242880,"minimum":0},"max_per_turn":{"type":"integer","format":"uint8","default":4,"maximum":255,"minimum":0}},"additionalProperties":false},"RamfluxAuthorizationMode":{"description":"How prx combines its own setting with `bridge.hello.authorization`.","oneOf":[{"description":"Use the agent-host value. Until hello arrives, the effective mode is supervised.","type":"string","const":"follow_rf"},{"description":"Always supervised, even when the agent-host declares full.","type":"string","const":"supervised"},{"description":"Full only when the agent-host also declares full. Config alone never yields full.","type":"string","const":"full"}]},"RamfluxConfig":{"description":"Local ramflux agent-host bridge (`[channels_config.ramflux]`).","type":"object","properties":{"accounts":{"type":"object","additionalProperties":{"$ref":"#/$defs/RamfluxAccountConfig"},"default":{}},"allowed_block_types":{"type":"array","default":["Text","Markdown","Heading","KeyValue","Metric","List","TableFallback","Form","Input","Select","Progress","LogStream","Warning","Error","Success","Approval","ActionGroup","FilePreview","Fallback"],"items":{"type":"string"}},"attachment_fetch":{"$ref":"#/$defs/RamfluxAttachmentFetch","default":{"max_bytes":5242880,"max_per_turn":4}},"authorization_mode":{"$ref":"#/$defs/RamfluxAuthorizationMode","default":"follow_rf"},"encrypt_at_rest":{"type":"boolean","default":true},"max_in_flight_per_conversation":{"type":"integer","format":"uint8","default":1,"maximum":255,"minimum":0},"on_new_message":{"$ref":"#/$defs/RamfluxOnNewMessage","default":"queue"},"socket_path":{"description":"Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.","type":["string","null"],"default":null},"surface_limits":{"$ref":"#/$defs/RamfluxSurfaceLimits","default":{"max_actions":16,"max_blocks":32,"max_bytes":65536}},"turn_wall_clock_secs":{"description":"Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.","type":"integer","format":"uint64","default":120,"minimum":0}},"additionalProperties":false},"RamfluxOnNewMessage":{"description":"What to do with a new inbound message while a turn for that conversation is running.","type":"string","enum":["queue","interrupt"]},"RamfluxSurfaceLimits":{"description":"Limits for `reply.surface` blocks and actions.","type":"object","properties":{"max_actions":{"type":"integer","format":"uint32","default":16,"minimum":0},"max_blocks":{"type":"integer","format":"uint32","default":32,"minimum":0},"max_bytes":{"type":"integer","format":"uint32","default":65536,"minimum":0}},"additionalProperties":false},"ReliabilityCircuitBreakerConfig":{"description":"Process-local provider circuit policy (`[reliability.circuit_breaker]`).","type":"object","properties":{"enabled":{"description":"Enable protection for factory-built provider chains.","type":"boolean","default":true},"failure_threshold":{"description":"Consecutive transient failures that open a circuit (at least 1).","type":"integer","format":"uint32","default":5,"minimum":0},"max_open_secs":{"description":"Maximum doubled window, between open_secs and 3600 seconds.","type":"integer","format":"uint64","default":300,"minimum":0},"open_secs":{"description":"Initial open window in seconds (at least 1).","type":"integer","format":"uint64","default":30,"minimum":0}}},"ReliabilityConfig":{"description":"Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.","type":"object","properties":{"acknowledge_single_provider_risk":{"description":"Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.","type":"boolean","default":false},"api_keys":{"description":"Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.","type":"array","default":[],"items":{"type":"string"}},"channel_initial_backoff_secs":{"description":"Initial backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":2,"minimum":0},"channel_max_backoff_secs":{"description":"Max backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":60,"minimum":0},"circuit_breaker":{"description":"Per-provider consecutive failure protection.","$ref":"#/$defs/ReliabilityCircuitBreakerConfig","default":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30}},"fallback_providers":{"description":"Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).","type":"array","default":[],"items":{"type":"string"}},"model_fallbacks":{"description":"Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`","type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"default":{}},"provider_backoff_ms":{"description":"Base backoff (ms) for provider retry delay.","type":"integer","format":"uint64","default":500,"minimum":0},"provider_retries":{"description":"Retries per provider before failing over.","type":"integer","format":"uint32","default":2,"minimum":0},"scheduler_poll_secs":{"description":"Scheduler polling cadence in seconds.","type":"integer","format":"uint64","default":15,"minimum":0},"scheduler_retries":{"description":"Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.","type":"integer","format":"uint32","default":2,"minimum":0}}},"RemoteNodeConfig":{"description":"A remote node target for core-side node proxy calls.","type":"object","properties":{"bearer_token":{"description":"Bearer token for node RPC authentication.","type":"string"},"endpoint":{"description":"Base endpoint (e.g. \"http://127.0.0.1:8787\").","type":"string"},"hmac_secret":{"description":"Optional request signing key (HMAC-SHA256).","type":["string","null"],"default":null},"id":{"description":"Stable node ID used by the nodes tool.","type":"string"},"retry_max":{"description":"Optional per-node retry override.","type":["integer","null"],"format":"uint8","default":null,"maximum":255,"minimum":0},"timeout_ms":{"description":"Optional per-node timeout override.","type":["integer","null"],"format":"uint64","default":null,"minimum":0}},"required":["id","endpoint","bearer_token"]},"RetrievalInjectionRole":{"description":"Where recalled context pages are injected back into the request.","oneOf":[{"description":"Inject recalled pages as a leading `system` message (not user-visible).","type":"string","const":"system"},{"description":"Inject recalled pages as a leading `user` message.","type":"string","const":"user"}]},"RouterConfig":{"description":"Heuristic LLM router configuration (`[router]` section).","type":"object","properties":{"alpha":{"description":"Similarity score weight. Phase 1 keeps this at `0.0`.","type":"number","format":"float","default":0.0},"beta":{"description":"Capability score weight.","type":"number","format":"float","default":0.5},"delta":{"description":"Cost penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"epsilon":{"description":"Latency penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"gamma":{"description":"Elo score weight.","type":"number","format":"float","default":0.30000001192092896},"knn_k":{"description":"Number of nearest neighbors considered for voting. Default: `7`.","type":"integer","format":"uint","default":7,"minimum":0},"knn_min_records":{"description":"Minimum history records before KNN affects routing. Default: `10`.","type":"integer","format":"uint","default":10,"minimum":0},"models":{"description":"Candidate model registry.","type":"array","default":[],"items":{"$ref":"#/$defs/RouterModelConfig"}}}},"RouterModelConfig":{"description":"Static router metadata for one model candidate.","type":"object","properties":{"categories":{"description":"Capability categories such as `conversation`, `code`, or `analysis`.","type":"array","default":[],"items":{"type":"string"}},"cost_per_million_tokens":{"description":"USD cost per million tokens.","type":"number","format":"float","default":0.0},"elo_rating":{"description":"Initial Elo rating.","type":"number","format":"float","default":1000.0},"latency_ms":{"description":"Average latency in milliseconds.","type":"integer","format":"uint32","default":2000,"minimum":0},"max_context":{"description":"Maximum context window in tokens.","type":"integer","format":"uint","default":1000000,"minimum":0},"model_id":{"description":"Model identifier without provider prefix.","type":"string"},"provider":{"description":"Provider identifier.","type":"string"},"reserved_output_tokens":{"description":"Output tokens reserved for this model when planning input context.","type":["integer","null"],"format":"uint","minimum":0}},"required":["model_id","provider"]},"RuntimeConfig":{"description":"Runtime adapter configuration (`[runtime]` section).","type":"object","properties":{"codex_reasoning_effort":{"description":"Codex reasoning effort","type":["string","null"],"default":null},"codex_stream_idle_timeout_secs":{"description":"Codex stream idle timeout in seconds","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"docker":{"description":"Docker runtime settings (used when `kind = \"docker\"`).","$ref":"#/$defs/DockerRuntimeConfig","default":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true}},"idle_hang_secs":{"description":"Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"kind":{"description":"Runtime kind (`native` | `docker`).","type":"string","default":"native"},"long_task_warn_secs":{"description":"Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"managed_cgroup_root":{"description":"Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.","type":["string","null"],"default":null},"max_blocking_threads":{"description":"Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"reasoning_enabled":{"description":"Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported","type":["boolean","null"],"default":null},"shell_env_allowlist":{"description":"Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.","type":"array","default":[],"items":{"type":"string"}},"workdir":{"description":"Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.","type":["string","null"],"default":null}}},"SchedulerConfig":{"description":"Scheduler configuration for periodic task execution (`[scheduler]` section).","type":"object","properties":{"claim_lease_secs":{"description":"Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.","type":"integer","format":"uint64","default":90,"minimum":0},"max_tasks":{"description":"Maximum number of persisted scheduled tasks.","type":"integer","format":"uint","default":64,"minimum":0}}},"ScopeConfig":{"description":"Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```","type":"object","properties":{"assign_owners":{"description":"Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.","type":"array","default":[],"items":{"type":"string"}},"default":{"description":"Default action when no rule matches: \"allow\" (default) or \"deny\".","$ref":"#/$defs/ScopeDefault","default":"allow"},"rules":{"description":"Ordered list of scope rules evaluated top-to-bottom.","type":"array","default":[],"items":{"$ref":"#/$defs/ScopeRule"}}}},"ScopeDefault":{"description":"What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.","oneOf":[{"description":"Unmatched tool calls are allowed (the default).","type":"string","const":"allow"},{"description":"Unmatched tool calls are refused.","type":"string","const":"deny"}]},"ScopeRule":{"description":"A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.","type":"object","properties":{"assign_allow":{"description":"Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".","type":"array","default":[],"items":{"type":"string"}},"assign_deny":{"description":"Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.","type":"array","default":[],"items":{"type":"string"}},"channel":{"description":"Match by channel name: \"signal\", \"telegram\", \"discord\", etc.","type":["string","null"]},"chat_type":{"description":"Match by chat type: \"direct\", \"group\", or \"*\" for any type.","type":["string","null"]},"send_allow":{"description":"Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.","type":"array","default":[],"items":{"type":"string"}},"send_deny":{"description":"Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.","type":"array","default":[],"items":{"type":"string"}},"tools_allow":{"description":"Tool whitelist: only these tools are allowed (empty = all tools permitted).","type":"array","default":[],"items":{"type":"string"}},"tools_deny":{"description":"Tool blacklist: these tools are denied regardless of allow list.","type":"array","default":[],"items":{"type":"string"}},"user":{"description":"Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.","type":["string","null"]}}},"SecretsConfig":{"description":"Secrets encryption configuration (`[secrets]` section).","type":"object","properties":{"encrypt":{"description":"Enable encryption for API keys and tokens in config.toml","type":"boolean","default":true}}},"SecurityConfig":{"description":"Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.","type":"object","properties":{"audit":{"description":"Audit logging configuration","$ref":"#/$defs/AuditConfig","default":{"log_path":"audit.log","max_size_mb":100}},"workspace_hooks":{"description":"Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.","$ref":"#/$defs/WorkspaceHooks"}}},"SelfSystemConfig":{"description":"Self-system experimental automation config (`[self_system]`).","type":"object","properties":{"evolution_config_path":{"description":"Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG)","type":["string","null"],"default":null},"evolution_debug_raw":{"description":"Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW)","type":"boolean","default":false},"evolution_interval_hours":{"description":"Evolution scheduler interval in hours (daemon mode).","type":"integer","format":"uint32","default":24,"minimum":0},"evolution_judge_timeout_secs":{"description":"Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.","type":"integer","format":"uint64","default":180,"minimum":0},"evolution_model_max_micro_usd":{"description":"Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.","type":"integer","format":"uint64","default":0,"minimum":0},"evolution_model_max_tokens":{"description":"Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.","type":"integer","format":"uint64","default":16384,"minimum":0},"fitness":{"description":"Daily fitness snapshot policy.","$ref":"#/$defs/FitnessConfig","default":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"}},"fitness_interval_hours":{"description":"Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.","type":"integer","format":"uint64","default":24,"minimum":0}}},"SessionsSpawnConfig":{"description":"Sessions spawn configuration (`[sessions_spawn]` section).","type":"object","properties":{"cleanup_on_complete":{"description":"Remove worker workspace directory after process-mode completion.","type":"boolean","default":true},"default_mode":{"description":"Default execution mode for sessions_spawn (`task` or `process`).","type":"string","default":"task"},"process_memory_strategy":{"description":"Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.","type":"string","default":"shared_fabric"},"worker_workspace_root":{"description":"Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.","type":["string","null"],"default":null}}},"SignalConfig":{"type":"object","properties":{"account":{"description":"E.164 phone number of the signal-cli account (e.g. \"+1234567890\").","type":"string"},"allowed_from":{"description":"Allowed sender phone numbers (E.164) or \"*\" for all.","type":"array","default":[],"items":{"type":"string"}},"cli_path":{"description":"Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).","type":["string","null"],"default":null},"daemon_http_port":{"description":"Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"daemon_mode":{"description":"Deprecated: ignored. Accepted for backward compatibility with older config files.","type":["boolean","null"],"default":null},"data_dir":{"description":"signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_id":{"description":"Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group","type":["string","null"],"default":null},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"http_url":{"description":"Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.","type":"string","default":"http://localhost:8080"},"ignore_attachments":{"description":"Skip messages that are attachment-only (no text body).","type":"boolean","default":false},"ignore_stories":{"description":"Skip incoming story messages.","type":"boolean","default":false},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"mode":{"description":"Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.","type":["string","null"],"default":null},"startup_timeout_ms":{"description":"Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.","type":"integer","format":"uint64","default":30000,"minimum":0},"storm_protection":{"description":"Signal ingress storm protection controls.","$ref":"#/$defs/SignalStormProtectionConfig","default":{"abnormal_threshold":10,"abnormal_window_secs":60,"breaker_duration_secs":300,"dedupe_ttl_secs":60,"min_reply_interval_secs":2}}},"required":["account"]},"SignalStormProtectionConfig":{"type":"object","properties":{"abnormal_threshold":{"description":"Non-user event threshold within `abnormal_window_secs` before tripping the breaker.","type":"integer","format":"uint","default":10,"minimum":0},"abnormal_window_secs":{"description":"Sliding window in seconds for non-user event counting.","type":"integer","format":"uint64","default":60,"minimum":0},"breaker_duration_secs":{"description":"Circuit breaker duration in seconds after threshold is reached.","type":"integer","format":"uint64","default":300,"minimum":0},"dedupe_ttl_secs":{"description":"Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.","type":"integer","format":"uint64","default":60,"minimum":0},"min_reply_interval_secs":{"description":"Minimum interval in seconds between replies for the same `(channel + reply_target)`.","type":"integer","format":"uint64","default":2,"minimum":0}}},"SkillRagConfig":{"description":"Dynamic skill retrieval configuration (`[skill_rag]` section).","type":"object","properties":{"top_k":{"description":"How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).","type":"integer","format":"uint","default":32,"minimum":0}}},"SkillSuiteRegistration":{"description":"The frozen suite that governs one skill's proposals.","type":"object","properties":{"skill_id":{"description":"The skill the suite governs.","type":"string"},"suite_digest":{"description":"SHA-256 digest (64 lowercase hex digits) of the frozen suite.","type":"string"}},"additionalProperties":false,"required":["skill_id","suite_digest"]},"SkillsConfig":{"description":"Skills loading configuration (`[skills]` section).","type":"object","properties":{"open_skills_dir":{"description":"Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.","type":["string","null"],"default":null},"openclaw_skills_dir":{"description":"Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.","type":["string","null"],"default":null}}},"SkillsLifecycleConfig":{"description":"`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.","type":"object","properties":{"allow_executable_proposals":{"description":"Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.","type":"boolean","default":false},"enabled":{"description":"Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.","type":"boolean","default":false},"max_concurrent_evaluations":{"description":"Most evaluations running at once.","type":"integer","format":"uint32","default":1,"minimum":0},"max_edit_fraction":{"description":"Edit budget of a proposal as a fraction of the skill body, in (0, 1].","type":"number","format":"double","default":0.2},"max_edit_tokens":{"description":"Edit budget of a proposal, in tokens.","type":"integer","format":"uint64","default":300,"minimum":0},"max_proposals_per_cycle":{"description":"Most proposals one cycle may start.","type":"integer","format":"uint32","default":1,"minimum":0},"min_cases_floor":{"description":"Smallest `min_cases` a governing suite may declare. Below 3 is refused.","type":"integer","format":"uint32","default":3,"minimum":0},"mode":{"description":"`draft_only`, `shadow` or `auto`.","$ref":"#/$defs/SkillsLifecycleModeConfig","default":"draft_only"},"owner_scope":{"description":"The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.","type":["string","null"],"default":null},"require_holdout":{"description":"A governing suite must have a holdout split. `false` is refused.","type":"boolean","default":true},"storage_dir":{"description":"Store location under the workspace. Only the default is supported.","type":"string","default":"self/skill-lifecycle"},"suites":{"description":"The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.","type":"array","default":[],"items":{"$ref":"#/$defs/SkillSuiteRegistration"}}},"additionalProperties":false},"SkillsLifecycleModeConfig":{"description":"What the lifecycle may do. Mirrors `LifecycleMode`.","oneOf":[{"description":"Drafts and reviews only.","type":"string","const":"draft_only"},{"description":"Drafts plus evaluation and gating; never publishes.","type":"string","const":"shadow"},{"description":"Publishes an eligible proposal after every gate.","type":"string","const":"auto"}]},"SlackConfig":{"description":"Slack bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Slack user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Slack app-level token for Socket Mode (xapp-...).","type":["string","null"]},"bot_token":{"description":"Slack bot OAuth token (xoxb-...).","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["bot_token"]},"SmartGroupConfig":{"description":"Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).","type":"object","properties":{"classifier_max_context_messages":{"description":"How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.","type":"integer","format":"uint","default":3,"minimum":0},"classifier_model":{"description":"Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.","type":"string","default":""},"classifier_provider":{"description":"Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.","type":"string","default":""},"classifier_temperature":{"description":"Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).","type":"number","format":"double","default":0.0},"classifier_timeout_secs":{"description":"Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.","type":"integer","format":"uint64","default":5,"minimum":0}}},"StorageConfig":{"description":"Persistent storage configuration (`[storage]` section).","type":"object","properties":{"provider":{"description":"Storage provider settings (e.g. sqlite, postgres).","$ref":"#/$defs/StorageProviderSection","default":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}}},"StorageProviderConfig":{"description":"Storage provider backend configuration (e.g. postgres connection details).","type":"object","properties":{"connect_timeout_secs":{"description":"Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"db_url":{"description":"Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.","type":["string","null"],"default":null},"pool_max_size":{"description":"Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.","type":"integer","format":"uint","default":32,"minimum":0},"provider":{"description":"Storage engine key (e.g. \"postgres\", \"sqlite\").","type":"string","default":""},"schema":{"description":"Database schema for SQL backends.","type":"string","default":"public"},"table":{"description":"Table name for memory entries.","type":"string","default":"memories"}}},"StorageProviderSection":{"description":"Wrapper for the storage provider configuration section.","type":"object","properties":{"config":{"description":"Storage provider backend settings.","$ref":"#/$defs/StorageProviderConfig","default":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"StreamMode":{"description":"Streaming mode for channels that support progressive message updates.","oneOf":[{"description":"No streaming -- send the complete response as a single message (default).","type":"string","const":"off"},{"description":"Update a draft message with every flush interval.","type":"string","const":"partial"}]},"TailscaleTunnelConfig":{"type":"object","properties":{"funnel":{"description":"Use Tailscale Funnel (public internet) vs Serve (tailnet only)","type":"boolean","default":false},"hostname":{"description":"Optional hostname override","type":["string","null"]}}},"TaskRoutingConfig":{"description":"Lightweight pre-LLM task routing.","type":"object","properties":{"default_intent":{"description":"Fallback intent when no rule matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"rules":{"description":"Rules evaluated in descending priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/TaskRoutingRule"}}}},"TaskRoutingIntentConfig":{"description":"Task-routing default and rule intent.","type":"string","enum":["simple","delegate","stream"]},"TaskRoutingRule":{"description":"A single task-routing rule.","type":"object","properties":{"intent":{"description":"Route intent to apply when a keyword matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"model_hint":{"description":"Optional model hint/raw model for non-delegated requests.","type":["string","null"],"default":null},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0},"sub_agent_model":{"description":"Optional raw sub-agent model override for delegated tasks.","type":["string","null"],"default":null}}},"TelegramConfig":{"description":"Telegram bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Telegram user IDs or usernames. Empty = deny all.","type":"array","items":{"type":"string"}},"bot_token":{"description":"Telegram Bot API token (from @BotFather).","type":"string"},"draft_update_interval_ms":{"description":"Minimum interval (ms) between draft message edits to avoid rate limits.","type":"integer","format":"uint64","default":1000,"minimum":0},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"interrupt_on_new_message":{"description":"When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.","type":"boolean","default":false},"stream_mode":{"description":"Streaming mode for progressive response delivery via message edits.","$ref":"#/$defs/StreamMode","default":"off"}},"required":["bot_token","allowed_users"]},"ToolCallDialectSetting":{"description":"The tool-call grammars an operator may declare for an endpoint.","oneOf":[{"description":"Only the native `tool_calls` array is a tool call (the default).","type":"string","const":"native"},{"description":"Additionally read `{json}` from the content,\nfor a tool name the request registered.","type":"string","const":"xml_function_tags"}]},"ToolSchemaDialectSetting":{"description":"The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.","oneOf":[{"description":"The published document, byte for byte (the default).","type":"string","const":"raw"},{"description":"The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.","type":"string","const":"no_root_combinators"}]},"ToolTieringConfig":{"description":"Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.","type":"object","properties":{"always_exclude":{"description":"Tool names excluded from capability publication.","type":"array","default":[],"items":{"type":"string"}},"always_include":{"description":"Tool names preferred for direct publication, subject to admission gates.","type":"array","default":[],"items":{"type":"string"}},"channel_exclude":{"description":"Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefault: empty (nothing is hidden); list tool names to hide them on channels.","type":"array","default":[],"items":{"type":"string"}}}},"TunnelConfig":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.","type":"object","properties":{"cloudflare":{"description":"Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).","anyOf":[{"$ref":"#/$defs/CloudflareTunnelConfig"},{"type":"null"}],"default":null},"custom":{"description":"Custom tunnel command configuration (used when `provider = \"custom\"`).","anyOf":[{"$ref":"#/$defs/CustomTunnelConfig"},{"type":"null"}],"default":null},"ngrok":{"description":"ngrok tunnel configuration (used when `provider = \"ngrok\"`).","anyOf":[{"$ref":"#/$defs/NgrokTunnelConfig"},{"type":"null"}],"default":null},"provider":{"description":"Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.","type":"string","default":"none"},"tailscale":{"description":"Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).","anyOf":[{"$ref":"#/$defs/TailscaleTunnelConfig"},{"type":"null"}],"default":null}}},"UserPolicyConfig":{"description":"Startup user policy entry (`[[user_policies]]`).","type":"object","properties":{"blocked_patterns":{"type":"array","default":[],"items":{"type":"string"}},"projects":{"type":"array","default":[],"items":{"type":"string"}},"role":{"type":"string","default":"guest"},"user_id":{"type":"string"},"visibility_ceiling":{"type":"string","default":"private"}},"required":["user_id"]},"WacliConfig":{"description":"wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```","type":"object","properties":{"allow_unsigned_loopback":{"description":"Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).","type":"boolean","default":false},"allowed_from":{"description":"Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.","type":"array","default":["*"],"items":{"type":"string"}},"bot_jid":{"description":"Bot's own JID, used for reply-to-bot mention detection.","type":["string","null"],"default":null},"bot_lid":{"description":"The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.","type":["string","null"],"default":null},"bot_number":{"description":"Bot's own phone number (digits), used for `@` mention detection.","type":["string","null"],"default":null},"cli_path":{"description":"Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.","type":["string","null"],"default":null},"group_reply_mode":{"description":"Smart group-reply mode. When `None`, derived from `mention_only`.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"host":{"description":"REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].","type":["string","null"],"writeOnly":true},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"outbound_media_workspace_only":{"description":"Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.","type":"boolean","default":false},"port":{"description":"REMOVED: legacy JSON-RPC daemon port. See `host`.","type":["integer","null"],"format":"uint16","maximum":65535,"minimum":0,"writeOnly":true},"self_chat_mode":{"description":"Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.","type":"boolean","default":false},"store_dir":{"description":"wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.","type":["string","null"],"default":null},"webhook_listen":{"description":"Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").","type":"string","default":"127.0.0.1:16868"},"webhook_path":{"description":"HTTP path the webhook server serves (default: \"/wacli\").","type":"string","default":"/wacli"},"webhook_secret":{"description":"HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.","type":["string","null"],"default":null}}},"WebSearchConfig":{"description":"Web search tool configuration (`[web_search]` section).","type":"object","properties":{"brave_api_key":{"description":"Brave Search API key (required if provider is \"brave\")","type":["string","null"],"default":null},"fetch_max_chars":{"description":"Maximum characters returned by `web_fetch` (default 10000)","type":"integer","format":"uint","default":50000,"minimum":0},"max_results":{"description":"Maximum results per search (1-20)","type":"integer","format":"uint","default":15,"minimum":0},"provider":{"description":"Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)","type":"string","default":"duckduckgo"},"timeout_secs":{"description":"Request timeout in seconds","type":"integer","format":"uint64","default":15,"minimum":0}}},"WebhookConfig":{"description":"Webhook channel configuration.","type":"object","properties":{"port":{"description":"Port to listen on for incoming webhooks.","type":"integer","format":"uint16","maximum":65535,"minimum":0},"secret":{"description":"Optional shared secret for webhook signature verification.","type":["string","null"]}},"required":["port"]},"WhatsAppConfig":{"description":"WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.","type":"object","properties":{"access_token":{"description":"Access token from Meta Business Suite (Cloud API mode)","type":["string","null"],"default":null},"allowed_numbers":{"description":"Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"app_secret":{"description":"App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"pair_code":{"description":"Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one","type":["string","null"],"default":null},"pair_phone":{"description":"Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used","type":["string","null"],"default":null},"phone_number_id":{"description":"Phone number ID from Meta Business API (Cloud API mode)","type":["string","null"],"default":null},"read_pool_size":{"description":"Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"session_path":{"description":"Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs","type":["string","null"],"default":null},"verify_token":{"description":"Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode","type":["string","null"],"default":null},"ws_url":{"description":"WebSocket URL override (replaces WHATSAPP_WS_URL)","type":["string","null"],"default":null}}},"WorkspaceHooks":{"description":"Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).","oneOf":[{"description":"They do not run (the default); `prx doctor` and `hooks_status` say so.","type":"string","const":"off"},{"description":"They run, in a cleared environment and a dedicated directory beside\n`config.toml`.","type":"string","const":"on"}]},"WorkspaceMcpServers":{"description":"Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).","oneOf":[{"description":"None: a workspace file may only narrow the servers defined in\n`config.toml`.","type":"string","const":"off"},{"description":"HTTP servers (still refused when they target a private address).","type":"string","const":"http_only"},{"description":"HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.","type":"string","const":"stdio"}]},"XinConfig":{"description":"Configuration for the xin autonomous task engine (`[xin]`).","type":"object","properties":{"adopt_legacy_tasks":{"description":"Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).","type":"boolean","default":false},"interval_minutes":{"description":"Tick interval in minutes (minimum 1). Default: 5.","type":"integer","format":"uint32","default":5,"minimum":0},"stale_timeout_minutes":{"description":"Minutes after which a running task is marked stale. Default: 60.","type":"integer","format":"uint32","default":60,"minimum":0}}},"AgentMessaging":{"description":"Owner-controlled inbound session messaging (enabled unless explicitly off).","type":"object","properties":{"inbound":{"type":"boolean","default":true}}}}} From 0cd3a88ec069c97a54614aae4641af6cbd377698 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:42:50 +0400 Subject: [PATCH 0137/1567] fix(init): drop stale cost keys from the full cost template --- src/config/init/templates.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/config/init/templates.rs b/src/config/init/templates.rs index a6485847a..8b51cb4c1 100644 --- a/src/config/init/templates.rs +++ b/src/config/init/templates.rs @@ -654,10 +654,10 @@ pub(super) fn cost_template(spec: Spec) -> String { # Token usage tracking and budget enforcement [cost] -# daily_budget_usd = 10.0 -# monthly_budget_usd = 200.0 -# alert_threshold_percent = 80 -# storage_path = "workspace/cost/usage.db" +# No spend limit is set unless you add one below. +# daily_limit_usd = 10.0 +# monthly_limit_usd = 100.0 +# warn_at_percent = 80 "# .into(), } From a6a7479c9aef106aaa1f3304887140e3623bb91a Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:12:39 +0400 Subject: [PATCH 0138/1567] fix(status): show every configured cost limit and only set path limits --- src/runtime/mode.rs | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/src/runtime/mode.rs b/src/runtime/mode.rs index da2078655..9cb9573ec 100644 --- a/src/runtime/mode.rs +++ b/src/runtime/mode.rs @@ -499,10 +499,26 @@ pub async fn dispatch(command: Commands, config: Config) -> Result<()> { println!(); println!("Security:"); println!(" Autonomy level: {:?}", config.autonomy.level); - println!(" Workspace only: {}", config.autonomy.workspace_only); - match config.autonomy.max_cost_per_day_cents { - Some(cents) => println!(" Max cost/day: ${:.2}", f64::from(cents) / 100.0), - None => println!(" Max cost/day: no limit set"), + if config.autonomy.workspace_only { + println!(" Workspace only: true (below full autonomy)"); + } + if !config.autonomy.forbidden_paths.is_empty() { + println!(" Forbidden paths: {} (below full autonomy)", config.autonomy.forbidden_paths.len()); + } + let mut limits = Vec::new(); + if let Some(cents) = config.autonomy.max_cost_per_day_cents { + limits.push(format!("policy ${:.2}/day", f64::from(cents) / 100.0)); + } + if let Some(usd) = config.cost.daily_limit_usd { + limits.push(format!("cost ${usd:.2}/day")); + } + if let Some(usd) = config.cost.monthly_limit_usd { + limits.push(format!("cost ${usd:.2}/month")); + } + if limits.is_empty() { + println!(" Cost limits: no limit set"); + } else { + println!(" Cost limits: {}", limits.join(", ")); } println!(" Audit logging: enabled"); println!(" Audit log path: {}", config.security.audit.log_path); From d00cd51c4e06dd7fc485d8f89e8dc9084f6e3f53 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:12:39 +0400 Subject: [PATCH 0139/1567] feat(config): leave workspace_only and forbidden_paths unset by default Both keys now default to off/empty and apply below level full only. The init specs no longer write them, and acknowledge_unrestricted_profile is accepted but never serialised. Owner-private file operations stay confined to the workspace independent of these keys. SecurityPolicy::default() remains a confined programmatic fallback. --- SECURITY.md | 4 +- docs/configuration.md | 28 +++++----- docs/migration-unreleased.md | 1 + src/config/init/templates.rs | 6 +-- src/config/init/tests.rs | 4 +- src/config/manage/plan.rs | 2 +- src/config/schema/autonomy.rs | 54 ++++++++++--------- src/config/schema/tests/partial_sections.rs | 13 ++--- src/config/schema/tests/security.rs | 8 +-- .../child_source/golden_effective_config.json | 2 +- src/security/path_policy.rs | 13 ++++- src/security/policy.rs | 6 ++- src/tools/owner_filesystem_dispatch.rs | 7 ++- tests/fixtures/config-schema.json | 2 +- 14 files changed, 84 insertions(+), 66 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index 95fc5672b..66e7bc5f2 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -79,9 +79,9 @@ split above. ### Sandboxing Layers -1. **Workspace isolation** — file operations confined to the workspace when `workspace_only = true` (default) +1. **Workspace isolation** — file operations confined to the workspace below level `full` when `workspace_only = true` (not set by default) 2. **Path traversal blocking** — `..` sequences and absolute paths rejected -3. **Forbidden path list** — critical system paths (`/etc`, `/root`, `~/.ssh`, …) always blocked unless the operator replaces the list +3. **Forbidden path list** — critical system paths (`/etc`, `/root`, `~/.ssh`, …) blocked below level `full` when the operator lists them (empty by default) 4. **Daily cost cap** — `autonomy.max_cost_per_day_cents` (optional; no cap unless configured) 5. **Identity-scope ACLs** — `[autonomy.scopes]` can deny a tool for a sender, channel, or chat type at every autonomy level diff --git a/docs/configuration.md b/docs/configuration.md index 6f172eaab..b8293c6fd 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -49,9 +49,9 @@ entry without its parent section's `cli` setting can load. Integration entries s credentials, endpoints, identities, and explicit allowlists where no safe default exists. An empty `config.toml` parses with `default_temperature = 0.7`; omitted `default_provider` and `default_model` remain unset so saving does not -pin a release catalog default. Security-posture defaults stay closed: -`workspace_only = true`, `acknowledge_unrestricted_profile = false`, and -`forbidden_paths` retains the built-in denylist. A `[causal_tree]` table is +pin a release catalog default. Autonomy defaults are open: `workspace_only = false` +and `forbidden_paths` is empty; a limit exists only when the operator writes it. +A `[causal_tree]` table is refused at load as an unknown configuration path; delete it and set the turn limits under `[decision_engine]` (see [the decision engine](decision-engine.md#configuration)). @@ -79,7 +79,7 @@ and the module-gate family are absorbed on load; they are not live switches. | Section | Keys and defaults | | --- | --- | | `[observability]` | `backend = "none"`; `otel_endpoint` unset; `otel_service_name` unset (collector name `"prx"` when backend is `otel`) | -| `[autonomy]` | `level = "full"`; `workspace_only = true`; built-in `forbidden_paths`; `max_cost_per_day_cents` unset (no ceiling); `acknowledge_unrestricted_profile = false`; `[autonomy.scopes] default = "allow"`, `rules = []`, `assign_owners = []`. A rule may set `user`/`channel`/`chat_type` and `tools_allow`/`tools_deny`/`send_allow`/`send_deny`/`assign_allow`/`assign_deny` (all empty when omitted) | +| `[autonomy]` | `level = "full"`; `workspace_only = false`; `forbidden_paths = []` (both apply below `full` only); `max_cost_per_day_cents` unset (no ceiling); `acknowledge_unrestricted_profile` accepted and ignored; `[autonomy.scopes] default = "allow"`, `rules = []`, `assign_owners = []`. A rule may set `user`/`channel`/`chat_type` and `tools_allow`/`tools_deny`/`send_allow`/`send_deny`/`assign_allow`/`assign_deny` (all empty when omitted) | | `[runtime]` | `kind = "native"`; `shell_env_allowlist = []`; `managed_cgroup_root` unset; `reasoning_enabled` unset; `codex_stream_idle_timeout_secs` unset; `codex_reasoning_effort` unset; `max_blocking_threads` unset (derived, floor 2048); `long_task_warn_secs` unset (900); `idle_hang_secs` unset (1800) | | `[runtime.docker]` | `image = "alpine:3.20"`; `network = "none"`; `memory_limit_mb = 512`; `cpu_limit = 1.0`; `read_only_rootfs = true`; `mount_workspace = true`; `allowed_workspace_roots = []` | | `[reliability]` | `provider_retries = 2`; `provider_backoff_ms = 500`; `fallback_providers = []`; `acknowledge_single_provider_risk = false`; `api_keys = []`; `model_fallbacks = {}`; `channel_initial_backoff_secs = 2`; `channel_max_backoff_secs = 60`; `scheduler_poll_secs = 15`; `scheduler_retries = 2` | @@ -822,8 +822,9 @@ allow_executable_proposals = false # "Path policy by autonomy level" below). [autonomy] level = "full" -workspace_only = true -forbidden_paths = ["/etc", "/root", "/home", "/opt", "/tmp", "~/.ssh"] +# For `supervised` or `readonly`, confine file and shell paths explicitly: +# workspace_only = true +# forbidden_paths = ["/etc", "/root", "/home", "/opt", "/tmp", "~/.ssh"] # max_cost_per_day_cents = 500 # unset means no ceiling # Multi-agent setup @@ -890,8 +891,9 @@ agents, and process-isolated session workers. `workspace_only` and `forbidden_paths`; the native file tools still refuse parent traversal (`..`). - `supervised` and `readonly`: a path is allowed exactly when it resolves - inside the workspace (with `workspace_only = true`) and outside every - `forbidden_paths` entry, however it is written: relative, absolute, or `~/`. + inside the workspace (with `workspace_only = true`, default `false`) and outside + every `forbidden_paths` entry (default empty), however it is written: relative, + absolute, or `~/`. Set both keys when you lower the level. An absolute path inside the workspace is allowed; a path outside it, a forbidden path, and a symlink inside the workspace that resolves outside it are refused. Parent traversal (`..`), URL-encoded traversal and NUL bytes are @@ -912,9 +914,9 @@ out of the file for no limit; set a key and exactly that limit applies (`0` refuses every priced turn). The signed child manifest carries "no ceiling" as `u32::MAX` cents (4294967295, the same value the key accepts). Spend is still recorded in the cost journal. With no limit set, no budget warning or -"budget exhausted" notice is produced. A host-wide profile is explicit: set -`workspace_only = false` and clear `forbidden_paths`; at level `full` the file -tools and shell ignore both keys anyway. `prx doctor` prints one neutral line +"budget exhausted" notice is produced. Neither `workspace_only` nor +`forbidden_paths` is set by default, and at level `full` the file tools and +shell ignore both anyway. `prx doctor` prints one neutral line with the active autonomy level and never warns about absent limits. `acknowledge_unrestricted_profile` is kept so existing configs still load and no longer changes any output. There is no hourly action cap. @@ -3476,9 +3478,9 @@ resolve relative native file requests and shell path arguments against the selec working root. All forbidden-path and workspace-only limits are evaluated on that resolved path; ReadOnly still refuses mutations. Configured roots are canonicalized at load, just like CLI roots, so a symlink alias is checked against its real directory. -With `workspace_only = true` (the default), a root outside the security workspace +With `workspace_only = true`, a root outside the security workspace refuses every relative native file request and every shell path argument containing -`/`. With `workspace_only = false`, a root outside the workspace under a default +`/`. With `workspace_only = false`, a root outside the workspace under a configured forbidden prefix such as `/home`, `/tmp` or `/var` still refuses those paths; the workspace ancestor exemption applies only inside the security workspace. A child's effective level cannot exceed its manifest or the current service level. diff --git a/docs/migration-unreleased.md b/docs/migration-unreleased.md index 652465f15..f48706fe4 100644 --- a/docs/migration-unreleased.md +++ b/docs/migration-unreleased.md @@ -32,6 +32,7 @@ of the [changelog](../CHANGELOG.md). | Nothing restricted by default on a fresh install | `[tool_tiering] channel_exclude` now defaults to an empty list (before: 14 operations tools such as `gateway`, `config_reload`, `nodes`, `skills_manage` were hidden from IM channel turns); a config that omits it now exposes those tools on channel turns, and a config that lists names keeps hiding them. `prx init --spec server` no longer writes `workspace_only`, `forbidden_paths` or `acknowledge_unrestricted_profile` (the built-in values are unchanged and have no effect at level `full`); `--spec full` no longer writes `acknowledge_unrestricted_profile`. `prx doctor` no longer warns for an explicit unrestricted profile; it prints one neutral autonomy-level line, and `acknowledge_unrestricted_profile` is accepted and ignored. Gateway pairing, channel sender allowlists, secret protection and integrity checks are unchanged. | Only to keep the old channel tool hiding: list the names in `channel_exclude` | | Remote image fetch on by default | `[multimodal] allow_remote_fetch` now defaults to `true` (before: `false`). A config that omits it now lets `http`/`https` image references be fetched into the model context; an explicit `false` keeps the old behavior. The fetch keeps the same private-address handling as `web_fetch`: below Full private, loopback and link-local hosts are refused, at Full they are reachable. | Only to keep remote fetch off: set `allow_remote_fetch = false` | | Node agent allows any command by default | `[nodes.server] allowed_commands` now defaults to an empty list, which allows any command (before: `["echo"]`, so every other command was refused). A config that omits the key now lets an authenticated caller run any command; a config that lists commands keeps that allowlist. Authentication is unchanged: a non-empty bearer token is required at startup, `hmac_secret` is checked when set, `tls_required = true` still demands TLS on non-loopback binds, and the default bind is loopback. `blocked_commands` is still enforced. | Only to keep the old restriction: set `allowed_commands = ["echo"]` | +| Autonomy path keys unset by default | `[autonomy] workspace_only` now defaults to `false` (before: `true`) and `forbidden_paths` to an empty list (before: 18 system paths). A config that omits them gets no workspace confinement and no path denylist; a config that sets them keeps exactly what it sets. Both keys are read below level `full` only (file tools, shell path arguments, image and document tools, the TUI file picker); at `full` they were already ignored. An install that runs `supervised` or `readonly` and relied on the old defaults must now write `workspace_only = true` and its `forbidden_paths`. Owner-private file operations stay confined to the workspace at every level, independent of these keys. `prx init` never writes these keys or `acknowledge_unrestricted_profile` (the latter is accepted from an existing config and ignored, and is no longer serialised). `prx status` prints a `Cost limits:` line (any configured `[cost]` or `[autonomy]` limit, or `no limit set`) instead of `Max cost/day:`, and prints `Workspace only:` and `Forbidden paths:` only when they are set. | Only for `supervised` or `readonly` installs: set `workspace_only` and `forbidden_paths` explicitly | | WASM plugins off by default | Set `[plugins] enabled = true` and restart only after reviewing each plugin; install or update with `wasm_plugins_manage` and explicit `grant_permissions` to write `plugin-trust.json` beside `config.toml`. The configuration directory and `plugin-cache/` must be outside the workspace. A `.prx-managed` marker grants no trust. | To use WASM plugins | | Plugin outbound requests | An empty `http_allowlist` now denies every URL. Use URL patterns such as `https://api.example.com/*`, not string prefixes such as `https://api.example.com*`. The SSRF guard still refuses private, loopback and other unsafe destinations. See [plugin trust and networking](plugin-developer-guide.md). | For plugins needing outbound HTTP | | Workspace command hooks default off | Set `[security] workspace_hooks = "on"` only after reviewing workspace commands. Remove non-null `cwd` from `hooks.json`: the whole candidate file is refused. Commands now start with a cleared environment in the dedicated directory beside `config.toml`; use explicit paths and allowed `env` entries. See [workspace command hooks](configuration.md#workspace-command-hooks). | To run workspace command hooks | diff --git a/src/config/init/templates.rs b/src/config/init/templates.rs index 8b51cb4c1..4ecc9d7b8 100644 --- a/src/config/init/templates.rs +++ b/src/config/init/templates.rs @@ -257,8 +257,8 @@ pub(super) fn security_template(spec: Spec) -> String { [autonomy] level = "full" -# No limit is set unless you add one: max_cost_per_day_cents, workspace_only, -# forbidden_paths (the last two take effect below level "full"). +# No limit is set unless you add one. workspace_only and forbidden_paths apply +# below level "full" only; max_cost_per_day_cents applies at every level. [secrets] encrypt = true @@ -281,8 +281,6 @@ status = "unclassified" # unclassified | high_risk | not_high_risk [autonomy] level = "full" # read_only | supervised | full -workspace_only = false -forbidden_paths = [] # no extra path denylist [secrets] encrypt = true diff --git a/src/config/init/tests.rs b/src/config/init/tests.rs index 2a9b999f6..dc3b6c6fd 100644 --- a/src/config/init/tests.rs +++ b/src/config/init/tests.rs @@ -1187,8 +1187,8 @@ fn full_security_template_configures_always_on_audit() { fn full_security_template_is_open_by_default() { let content = security_template(Spec::Full); assert!(content.contains("level = \"full\"")); - assert!(content.contains("workspace_only = false")); - assert!(content.contains("forbidden_paths = []")); + assert!(!content.contains("workspace_only =")); + assert!(!content.contains("forbidden_paths =")); assert!(!content.contains("[autonomy.sandbox]")); } diff --git a/src/config/manage/plan.rs b/src/config/manage/plan.rs index da2c4177b..9f3af51c2 100644 --- a/src/config/manage/plan.rs +++ b/src/config/manage/plan.rs @@ -3151,7 +3151,7 @@ mod tests { ), ( "a forbidden path removed", - |_| {}, + |c| c.autonomy.forbidden_paths = vec!["/etc".into()], |c| { c.autonomy.forbidden_paths.pop(); }, diff --git a/src/config/schema/autonomy.rs b/src/config/schema/autonomy.rs index 54f77bdd0..90b26644b 100644 --- a/src/config/schema/autonomy.rs +++ b/src/config/schema/autonomy.rs @@ -345,19 +345,15 @@ pub struct AutonomyConfig { /// Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default). #[serde(default)] pub level: AutonomyLevel, - /// Restrict file writes and command paths to the workspace directory. Default: `true`. + /// Restrict file writes and command paths to the workspace directory. Default: `false`. /// - /// Fails closed: a `[autonomy]` section that omits this key keeps the - /// workspace restriction on, so a partial section can never widen the - /// filesystem reach by accident. - #[serde(default = "default_workspace_only")] + /// Applies below level `full` only; set it when running `supervised` or `readonly`. + #[serde(default, skip_serializing_if = "is_false")] pub workspace_only: bool, - /// Explicit path denylist. Default includes system-critical paths. + /// Explicit path denylist. Default: empty. /// - /// Fails closed: omitting the key keeps the built-in list rather than - /// emptying it, so a partial `[autonomy]` section never removes the - /// denylist. - #[serde(default = "default_forbidden_paths")] + /// Applies below level `full` only; list paths when running `supervised` or `readonly`. + #[serde(default)] pub forbidden_paths: Vec, /// Maximum cost per day in cents per policy. Default: unset (no ceiling). #[serde(default)] @@ -365,7 +361,7 @@ pub struct AutonomyConfig { /// Operator acknowledgement for an intentionally unrestricted profile. /// Retained for existing configs; it no longer changes any output or policy behavior. - #[serde(default)] + #[serde(default, skip_serializing)] pub acknowledge_unrestricted_profile: bool, /// Scope-based tool access control: per-user/channel/chat-type allow/deny rules. @@ -378,8 +374,8 @@ impl Default for AutonomyConfig { Self { evaluation_sandbox: false, level: AutonomyLevel::Full, - workspace_only: default_workspace_only(), - forbidden_paths: default_forbidden_paths(), + workspace_only: false, + forbidden_paths: Vec::new(), max_cost_per_day_cents: None, acknowledge_unrestricted_profile: false, scopes: ScopeConfig::default(), @@ -387,19 +383,9 @@ impl Default for AutonomyConfig { } } -/// Whether file writes and command paths stay inside the workspace. -/// -/// `true` is the closed value: a `[autonomy]` section that omits the key keeps -/// the restriction, so a partial section cannot widen the filesystem reach. -pub(super) const fn default_workspace_only() -> bool { - true -} - -/// The built-in path denylist. -/// -/// Shared by `#[serde(default)]` and `impl Default` so a partial `[autonomy]` -/// section keeps the same list a default section has, instead of an empty one. -pub(super) fn default_forbidden_paths() -> Vec { +/// The system-critical paths an operator may copy into `forbidden_paths`. +/// Not applied by default. +fn recommended_forbidden_paths() -> Vec { vec![ "/etc".into(), "/root".into(), @@ -422,7 +408,23 @@ pub(super) fn default_forbidden_paths() -> Vec { ] } +/// `skip_serializing_if` predicate: an unset confinement is not written out. +fn is_false(value: &bool) -> bool { + !*value +} + impl AutonomyConfig { + /// Workspace confinement plus the recommended denylist: the shape an operator + /// writes for a `supervised` or `readonly` install. Never the default. + #[must_use] + pub fn confined() -> Self { + Self { + workspace_only: true, + forbidden_paths: recommended_forbidden_paths(), + ..Self::default() + } + } + /// The per-policy daily ceiling in cents, or /// [`UNLIMITED_AUTONOMY_MAX_COST_PER_DAY_CENTS`] when none is configured. #[must_use] diff --git a/src/config/schema/tests/partial_sections.rs b/src/config/schema/tests/partial_sections.rs index 7555e99bd..321b49cb5 100644 --- a/src/config/schema/tests/partial_sections.rs +++ b/src/config/schema/tests/partial_sections.rs @@ -54,20 +54,17 @@ fn every_touched_section_defaults_to_its_default_impl() { assert_empty_section_matches_default::("channels_config"); } -/// Item 1, the security half: a partial `[autonomy]` fails closed. -/// -/// The three keys whose absence could widen the posture keep the safe value -/// rather than an empty one, so an operator who writes only `level` never -/// silently loses the workspace restriction or the path denylist. +/// Item 1, the security half: a partial `[autonomy]` keeps the unrestricted +/// built-in values; an operator who wants confinement writes the keys. #[test] fn a_partial_autonomy_section_fails_closed() { let parsed: AutonomyConfig = toml::from_str("level = \"full\"").expect("test: partial autonomy parses"); - assert!(parsed.workspace_only, "workspace_only must stay true when omitted"); + assert!(!parsed.workspace_only, "workspace_only must stay false when omitted"); assert_eq!( parsed.forbidden_paths, AutonomyConfig::default().forbidden_paths, - "forbidden_paths must keep the built-in list when omitted" + "forbidden_paths must keep the built-in (empty) list when omitted" ); assert!( !parsed.acknowledge_unrestricted_profile, @@ -215,7 +212,7 @@ fn the_reported_partial_sections_load_together() { let loaded = loaded.expect("test: the three reported partial sections load"); assert_eq!(loaded.autonomy.level, AutonomyLevel::Full); - assert!(loaded.autonomy.workspace_only, "autonomy stays closed"); + assert!(!loaded.autonomy.workspace_only, "autonomy stays open"); assert_eq!( loaded.autonomy.forbidden_paths, AutonomyConfig::default().forbidden_paths diff --git a/src/config/schema/tests/security.rs b/src/config/schema/tests/security.rs index 543ca4e5d..d4290435d 100644 --- a/src/config/schema/tests/security.rs +++ b/src/config/schema/tests/security.rs @@ -7,8 +7,8 @@ use tokio::test; async fn autonomy_config_default() { let a = AutonomyConfig::default(); assert_eq!(a.level, AutonomyLevel::Full); - assert!(a.workspace_only); - assert!(a.forbidden_paths.contains(&"/etc".to_string())); + assert!(!a.workspace_only); + assert!(a.forbidden_paths.is_empty()); assert_eq!(a.max_cost_per_day_cents, None); } @@ -87,8 +87,8 @@ bind = "127.0.0.1:16899" } #[test] -async fn checklist_autonomy_default_is_workspace_scoped() { - let a = AutonomyConfig::default(); +async fn checklist_autonomy_confined_is_workspace_scoped() { + let a = AutonomyConfig::confined(); assert!(a.workspace_only, "Default autonomy must be workspace_only"); assert!(a.forbidden_paths.contains(&"/etc".to_string()), "Must block /etc"); assert!(a.forbidden_paths.contains(&"/proc".to_string()), "Must block /proc"); diff --git a/src/runtime/child_source/golden_effective_config.json b/src/runtime/child_source/golden_effective_config.json index 738a6b4f0..8eace6033 100644 --- a/src/runtime/child_source/golden_effective_config.json +++ b/src/runtime/child_source/golden_effective_config.json @@ -1 +1 @@ -{"a2a":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trust_domain":"prx.local","trusted_trust_domains":[]},"agent":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"messaging":{"inbound":true},"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2},"agents":{},"api_key":null,"api_url":null,"auth":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"},"autonomy":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true},"browser":{"allowed_domains":[],"computer_use":{"api_key":null}},"channels_config":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null},"chat":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2},"compliance":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}},"composio":{"api_key":null,"entity_id":"default"},"cost":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{"alpha/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0},"zeta/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0}},"warn_at_percent":80},"cron":{"max_run_history":50},"decision_engine":{"backend":{"circuit_breaker":{"cooldown_secs":60,"failure_threshold":5},"credential_ref":"","endpoint":"","kind":"auto","max_request_bytes":65536,"max_response_bytes":262144,"model":"","pinned_snapshot":"","remote_enabled":false,"timeout_ms":250},"candidates":5,"enabled":false,"latency_budget_ms":500,"max_candidates":12,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"token_ratio_limit":0.3499999940395355},"default_model":"anthropic/claude-sonnet-5","default_provider":"openrouter","default_temperature":0.7,"embedding_routes":[],"gateway":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60},"heartbeat":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."},"http_request":{"max_response_size":1000000,"timeout_secs":30},"identity":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"},"identity_bindings":[],"mcp":{"servers":{}},"mcp_server":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true},"media":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"},"memory":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7},"model_routes":[],"model_settings":{},"multimodal":{"allow_remote_fetch":true,"max_image_size_mb":5,"max_images":4},"nodes":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":[],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}},"observability":{"backend":"none","otel_endpoint":null,"otel_service_name":null},"plugins":{"enabled":false},"providers":{"ollama":{"num_ctx":null}},"proxy":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]},"query_classification":{"rules":[]},"reliability":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2},"router":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]},"runtime":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null},"scheduler":{"claim_lease_secs":90,"max_tasks":64},"secrets":{"encrypt":true},"security":{"audit":{"log_path":"audit.log","max_size_mb":100}},"self_system":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24},"sessions_spawn":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null},"skill_rag":{"top_k":32},"skills":{"open_skills_dir":null,"openclaw_skills_dir":null},"skills_lifecycle":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]},"smart_group":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5},"storage":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}},"task_routing":{"default_intent":"simple","rules":[]},"tool_tiering":{"always_exclude":[],"always_include":[],"channel_exclude":[]},"tunnel":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null},"user_policies":[],"web_search":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15},"webhook":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null},"xin":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}} \ No newline at end of file +{"a2a":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trust_domain":"prx.local","trusted_trust_domains":[]},"agent":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"messaging":{"inbound":true},"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2},"agents":{},"api_key":null,"api_url":null,"auth":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"},"autonomy":{"forbidden_paths":[],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]}},"browser":{"allowed_domains":[],"computer_use":{"api_key":null}},"channels_config":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null},"chat":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2},"compliance":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}},"composio":{"api_key":null,"entity_id":"default"},"cost":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{"alpha/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0},"zeta/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0}},"warn_at_percent":80},"cron":{"max_run_history":50},"decision_engine":{"backend":{"circuit_breaker":{"cooldown_secs":60,"failure_threshold":5},"credential_ref":"","endpoint":"","kind":"auto","max_request_bytes":65536,"max_response_bytes":262144,"model":"","pinned_snapshot":"","remote_enabled":false,"timeout_ms":250},"candidates":5,"enabled":false,"latency_budget_ms":500,"max_candidates":12,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"token_ratio_limit":0.3499999940395355},"default_model":"anthropic/claude-sonnet-5","default_provider":"openrouter","default_temperature":0.7,"embedding_routes":[],"gateway":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60},"heartbeat":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."},"http_request":{"max_response_size":1000000,"timeout_secs":30},"identity":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"},"identity_bindings":[],"mcp":{"servers":{}},"mcp_server":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true},"media":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"},"memory":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7},"model_routes":[],"model_settings":{},"multimodal":{"allow_remote_fetch":true,"max_image_size_mb":5,"max_images":4},"nodes":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":[],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}},"observability":{"backend":"none","otel_endpoint":null,"otel_service_name":null},"plugins":{"enabled":false},"providers":{"ollama":{"num_ctx":null}},"proxy":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]},"query_classification":{"rules":[]},"reliability":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2},"router":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]},"runtime":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null},"scheduler":{"claim_lease_secs":90,"max_tasks":64},"secrets":{"encrypt":true},"security":{"audit":{"log_path":"audit.log","max_size_mb":100}},"self_system":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24},"sessions_spawn":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null},"skill_rag":{"top_k":32},"skills":{"open_skills_dir":null,"openclaw_skills_dir":null},"skills_lifecycle":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]},"smart_group":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5},"storage":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}},"task_routing":{"default_intent":"simple","rules":[]},"tool_tiering":{"always_exclude":[],"always_include":[],"channel_exclude":[]},"tunnel":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null},"user_policies":[],"web_search":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15},"webhook":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null},"xin":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}} \ No newline at end of file diff --git a/src/security/path_policy.rs b/src/security/path_policy.rs index f3284305e..22b3d242d 100644 --- a/src/security/path_policy.rs +++ b/src/security/path_policy.rs @@ -196,6 +196,17 @@ impl SecurityPolicy { /// forbidden paths, however it is written: relative, absolute or `~`. /// Symlinks are the caller's canonical check (`is_resolved_path_allowed`). pub(crate) fn check_path_at(&self, root: &Path, path: &str) -> Result<(), PathRefusalReason> { + self.check_path_at_with(root, path, self.workspace_only) + } + + /// Whether `path` stays inside the workspace and outside `forbidden_paths`, + /// whatever `workspace_only` says. For origins whose confinement is part of + /// their isolation, not an operator setting. + pub(crate) fn is_path_confined_to_workspace(&self, path: &str) -> bool { + self.check_path_at_with(&self.workspace_dir, path, true).is_ok() + } + + fn check_path_at_with(&self, root: &Path, path: &str, workspace_only: bool) -> Result<(), PathRefusalReason> { let target = resolve_request_path(root, path).map_err(|_| PathRefusalReason::InvalidPath)?; let lower = path.to_lowercase(); if lower.contains("..%2f") || lower.contains("%2f..") { @@ -218,7 +229,7 @@ impl SecurityPolicy { return Err(PathRefusalReason::ForbiddenPath); } } - if self.workspace_only && !inside_workspace { + if workspace_only && !inside_workspace { return Err(PathRefusalReason::OutsideWorkspace); } Ok(()) diff --git a/src/security/policy.rs b/src/security/policy.rs index 6f3ba1066..7c9f89bf1 100644 --- a/src/security/policy.rs +++ b/src/security/policy.rs @@ -902,7 +902,9 @@ pub struct SecurityPolicy { impl Default for SecurityPolicy { fn default() -> Self { - Self::from_config(&crate::config::AutonomyConfig::default(), Path::new(".")) + // The programmatic fallback stays confined (fail closed). A running + // install builds its policy with `from_config`, whose default is open. + Self::from_config(&crate::config::AutonomyConfig::confined(), Path::new(".")) } } @@ -4141,7 +4143,7 @@ mod tests { #[test] fn default_policy_has_sane_values() { let p = SecurityPolicy::default(); - let autonomy = crate::config::AutonomyConfig::default(); + let autonomy = crate::config::AutonomyConfig::confined(); assert_eq!(p.autonomy, AutonomyLevel::Full); assert!(p.workspace_only); assert!(!p.forbidden_paths.is_empty(), "expected a non-empty value"); diff --git a/src/tools/owner_filesystem_dispatch.rs b/src/tools/owner_filesystem_dispatch.rs index dd64c85f1..34a33867c 100644 --- a/src/tools/owner_filesystem_dispatch.rs +++ b/src/tools/owner_filesystem_dispatch.rs @@ -106,7 +106,12 @@ async fn apply_file_operation_inner( .get("path") .and_then(serde_json::Value::as_str) .context("missing file path")?; - ensure!(security.is_path_allowed(path), "file path is denied by security policy"); + // Owner-private files stay confined to the workspace at every level; this + // is part of the origin's isolation and does not follow `workspace_only`. + ensure!( + security.is_path_confined_to_workspace(path), + "file path is denied by security policy" + ); let tool = operation.tool_name(); let target = if operation == NativeFileOperation::Write { filesystem.resolve(path)? diff --git a/tests/fixtures/config-schema.json b/tests/fixtures/config-schema.json index 7c34f0d35..8aaaf903b 100644 --- a/tests/fixtures/config-schema.json +++ b/tests/fixtures/config-schema.json @@ -1 +1 @@ -{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Config","description":"Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).","type":"object","properties":{"a2a":{"description":"Agent-to-Agent compatibility configuration (`[a2a]`).","$ref":"#/$defs/A2aConfig","default":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trusted_trust_domains":[],"trust_domain":"prx.local"}},"agent":{"description":"Agent orchestration settings (`[agent]`).","$ref":"#/$defs/AgentConfig","default":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2,"messaging":{"inbound":true}}},"agents":{"description":"Delegate agent configurations for multi-agent workflows.","type":"object","additionalProperties":{"$ref":"#/$defs/DelegateAgentConfig"},"default":{}},"api_key":{"description":"API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.","type":["string","null"],"default":null},"api_url":{"description":"Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)","type":["string","null"],"default":null},"auth":{"description":"Auth profile and external credential import settings (`[auth]`).","$ref":"#/$defs/AuthConfig","default":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"}},"autonomy":{"description":"Autonomy and security policy configuration (`[autonomy]`).","$ref":"#/$defs/AutonomyConfig","default":{"acknowledge_unrestricted_profile":false,"forbidden_paths":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]},"workspace_only":true}},"browser":{"description":"Browser automation configuration (`[browser]`).","$ref":"#/$defs/BrowserConfig","default":{"allowed_domains":[],"computer_use":{"api_key":null}}},"channels_config":{"description":"Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).","$ref":"#/$defs/ChannelsConfig","default":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null}},"chat":{"description":"Interactive chat UI configuration (`[chat]`).","$ref":"#/$defs/ChatConfig","default":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2}},"compliance":{"description":"Operator-owned compliance controls (`[compliance]`).","$ref":"#/$defs/ComplianceConfig","default":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}},"composio":{"description":"Composio managed OAuth tools integration (`[composio]`).","$ref":"#/$defs/ComposioConfig","default":{"api_key":null,"entity_id":"default"}},"cost":{"description":"Cost tracking and budget enforcement configuration (`[cost]`).","$ref":"#/$defs/CostConfig","default":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{},"warn_at_percent":80}},"cron":{"description":"Cron job configuration (`[cron]`).","$ref":"#/$defs/CronConfig","default":{"max_run_history":50}},"decision_engine":{"description":"Optional advisory decision engine, disabled by default.","$ref":"#/$defs/DecisionEngineConfig","default":{"candidates":5,"enabled":false,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"latency_budget_ms":500,"max_candidates":12,"token_ratio_limit":0.3499999940395355}},"default_model":{"description":"Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.","type":["string","null"]},"default_provider":{"description":"Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.","type":["string","null"]},"default_temperature":{"description":"Default model temperature (0.0–2.0). Default: `0.7`.","type":"number","format":"double","default":0.7},"embedding_routes":{"description":"Embedding routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/EmbeddingRouteConfig"}},"gateway":{"description":"Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).","$ref":"#/$defs/GatewayConfig","default":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60}},"heartbeat":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]`).","$ref":"#/$defs/HeartbeatConfig","default":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."}},"http_request":{"description":"HTTP request tool configuration (`[http_request]`).","$ref":"#/$defs/HttpRequestConfig","default":{"max_response_size":1000000,"timeout_secs":30}},"identity":{"description":"Identity format configuration: OpenClaw or AIEOS (`[identity]`).","$ref":"#/$defs/IdentityConfig","default":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"}},"identity_bindings":{"description":"Static identity bindings loaded at startup (`[[identity_bindings]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/IdentityBindingConfig"}},"mcp":{"description":"Secrets encryption configuration (`[secrets]`).","$ref":"#/$defs/McpConfig","default":{"servers":{}}},"mcp_server":{"description":"MCP server compatibility configuration (`[mcp_server]`).","$ref":"#/$defs/McpServerRuntimeConfig","default":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true}},"media":{"description":"Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.","$ref":"#/$defs/MediaConfig","default":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"}},"memory":{"description":"Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).","$ref":"#/$defs/MemoryConfig","default":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7}},"model_routes":{"description":"Model routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/ModelRouteConfig"}},"model_settings":{"description":"Catalog model levels and explicit parameters, keyed by canonical release ID.","type":"object","additionalProperties":{"$ref":"#/$defs/ModelSettings"},"default":{}},"multimodal":{"description":"Multimodal (image) handling configuration (`[multimodal]`).","$ref":"#/$defs/MultimodalConfig","default":{"allow_remote_fetch":true,"max_image_size_mb":5,"max_images":4}},"nodes":{"description":"Remote node proxy configuration (`[nodes]`).","$ref":"#/$defs/NodesConfig","default":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":[],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}},"observability":{"description":"Observability backend configuration (`[observability]`).","$ref":"#/$defs/ObservabilityConfig","default":{"backend":"none","otel_endpoint":null,"otel_service_name":null}},"plugins":{"description":"WASM plugin runtime switch (`[plugins]`), off by default.","$ref":"#/$defs/PluginsConfig","default":{"enabled":false}},"providers":{"description":"Provider-specific runtime options (`[providers.]`).","$ref":"#/$defs/ProvidersConfig","default":{"ollama":{"num_ctx":null}}},"proxy":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).","$ref":"#/$defs/ProxyConfig","default":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]}},"query_classification":{"description":"Automatic query classification — maps user messages to model hints.","$ref":"#/$defs/QueryClassificationConfig","default":{"rules":[]}},"reliability":{"description":"Reliability settings: retries, fallback providers, backoff (`[reliability]`).","$ref":"#/$defs/ReliabilityConfig","default":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2}},"router":{"description":"Heuristic LLM router configuration (`[router]`).","$ref":"#/$defs/RouterConfig","default":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]}},"runtime":{"description":"Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.","$ref":"#/$defs/RuntimeConfig","default":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null}},"scheduler":{"description":"Scheduler configuration for periodic task execution (`[scheduler]`).","$ref":"#/$defs/SchedulerConfig","default":{"claim_lease_secs":90,"max_tasks":64}},"secrets":{"$ref":"#/$defs/SecretsConfig","default":{"encrypt":true}},"security":{"description":"Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).","$ref":"#/$defs/SecurityConfig","default":{"audit":{"log_path":"audit.log","max_size_mb":100}}},"self_system":{"description":"Self-system experimental automation controls (`[self_system]`).","$ref":"#/$defs/SelfSystemConfig","default":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24}},"sessions_spawn":{"description":"Session spawning configuration (`[sessions_spawn]`).","$ref":"#/$defs/SessionsSpawnConfig","default":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null}},"skill_rag":{"description":"Dynamic skill retrieval settings (`[skill_rag]`).","$ref":"#/$defs/SkillRagConfig","default":{"top_k":32}},"skills":{"description":"Skills loading and community repository behavior (`[skills]`).","$ref":"#/$defs/SkillsConfig","default":{"open_skills_dir":null,"openclaw_skills_dir":null}},"skills_lifecycle":{"description":"Skill lifecycle (`[skills_lifecycle]`), off by default.","$ref":"#/$defs/SkillsLifecycleConfig","default":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]}},"smart_group":{"description":"Smart group-reply pre-gate configuration (`[smart_group]`).","$ref":"#/$defs/SmartGroupConfig","default":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5}},"storage":{"description":"Persistent storage provider configuration (`[storage]`).","$ref":"#/$defs/StorageConfig","default":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"task_routing":{"description":"Task routing configuration — classifies work by intent before the main agent loop.","$ref":"#/$defs/TaskRoutingConfig","default":{"default_intent":"simple","rules":[]}},"tool_tiering":{"description":"Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).","$ref":"#/$defs/ToolTieringConfig","default":{"always_exclude":[],"always_include":[],"channel_exclude":[]}},"tunnel":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]`).","$ref":"#/$defs/TunnelConfig","default":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null}},"user_policies":{"description":"Static user policy records loaded at startup (`[[user_policies]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/UserPolicyConfig"}},"web_search":{"description":"Web search tool configuration (`[web_search]`).","$ref":"#/$defs/WebSearchConfig","default":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15}},"webhook":{"description":"Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).","$ref":"#/$defs/MemoryWebhookConfig","default":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null}},"xin":{"description":"Xin autonomous task engine configuration (`[xin]`).","$ref":"#/$defs/XinConfig","default":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}}},"$defs":{"A2aConfig":{"type":"object","properties":{"agent_id":{"description":"Stable PRX agent identifier advertised to peers.","type":"string","default":"prx-default"},"allowed_peer_issuers":{"description":"Accepted external peer issuers.","type":"array","default":[],"items":{"type":"string"}},"bind":{"description":"Advertised bind address.","type":"string","default":"127.0.0.1:16832"},"card_jwks_uri":{"description":"Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.","type":["string","null"],"default":null},"card_signing_key_path":{"description":"On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).","type":["string","null"],"default":null},"card_ttl_seconds":{"description":"Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.","type":"integer","format":"uint64","default":3600,"minimum":0},"discovery_advertised":{"description":"Whether to advertise into an external A2A registry.","type":"boolean","default":false},"handoff_nonce_ttl_seconds":{"description":"Replay window for future handoff delegation tokens.","type":"integer","format":"uint64","default":3600,"minimum":0},"messaging_enabled":{"description":"Enable the dedicated pinned mTLS messaging listener.","type":"boolean","default":false},"peers":{"type":"object","additionalProperties":{"$ref":"#/$defs/A2aPeer"},"default":{}},"spiffe_id":{"description":"Local SPIFFE-style identifier placeholder.","type":"string","default":"spiffe://prx-local/agent/prx-default"},"spiffe_strict_validation":{"description":"When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.","type":"boolean","default":false},"spiffe_trust_bundle_pem":{"description":"Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).","type":["string","null"],"default":null},"trusted_trust_domains":{"description":"Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).","type":"array","default":[],"items":{"type":"string"}},"trust_domain":{"description":"SPIFFE trust domain for new instance identities.","type":"string","default":"prx.local"}}},"A2aPeer":{"description":"Explicit pinned identity and local recipient grant.","type":"object","properties":{"spiffe_id":{"type":"string"},"fingerprints":{"type":"array","items":{"type":"string"}},"address":{"type":"string"},"owner":{"type":"string"},"sessions":{"type":"array","default":["*"],"items":{"type":"string"}},"agents":{"type":"array","default":["*"],"items":{"type":"string"}}},"required":["spiffe_id","fingerprints","address","owner"],"additionalProperties":false},"AgentCompactionConfig":{"description":"Agent context compaction configuration (`[agent.compaction]`).","type":"object","properties":{"keep_recent_messages":{"description":"Number of recent non-system messages to keep after compaction.","type":"integer","format":"uint","default":12,"minimum":0},"max_context_tokens":{"description":"Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.","type":"integer","format":"uint","default":128000,"minimum":0},"memory_flush":{"description":"Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.","type":"boolean","default":true},"mode":{"description":"Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).","$ref":"#/$defs/AgentCompactionMode","default":"switch"},"os_paging":{"description":"Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.","$ref":"#/$defs/OsPagingConfig","default":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"}},"reserve_tokens":{"description":"Tokens reserved for the next model response.","type":"integer","format":"uint","default":4096,"minimum":0}}},"AgentCompactionMode":{"description":"Compaction mode for long conversation contexts.","oneOf":[{"description":"Disable proactive compaction.","type":"string","const":"off"},{"description":"Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.","type":"string","const":"switch"},{"description":"Conservative compaction that prefers summary replacement.","type":"string","const":"safeguard"},{"description":"Aggressive truncation mode for tighter contexts.","type":"string","const":"aggressive"}]},"AgentConfig":{"description":"Agent orchestration configuration (`[agent]` section).","type":"object","properties":{"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"compact_context":{"description":"When true: bootstrap_max_chars=6000. Use for 13B or smaller models.","type":"boolean","default":false},"compaction":{"description":"Context compaction controls (`[agent.compaction]`).","$ref":"#/$defs/AgentCompactionConfig","default":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096}},"low_priority_tools":{"description":"Tool names treated as low-priority when `priority_scheduling_enabled = true`.","type":"array","default":["sessions_spawn","delegate"],"items":{"type":"string"}},"priority_scheduling_enabled":{"description":"Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.","type":"boolean","default":false},"read_only_tool_concurrency_window":{"description":"Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.","type":"integer","format":"uint","default":2,"minimum":0},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}}},"AgentLimits":{"description":"Optional admission limits for rf-started turns of a named agent.","type":"object","properties":{"max_concurrent_turns":{"type":["integer","null"],"format":"uint32","minimum":0},"max_cost_per_day_cents":{"type":["integer","null"],"format":"uint64","minimum":0}},"additionalProperties":false},"AuditConfig":{"description":"Audit logging configuration","type":"object","properties":{"log_path":{"description":"Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).","type":"string","default":"audit.log"},"max_size_mb":{"description":"Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).","type":"integer","format":"uint32","default":100,"minimum":0}}},"AuthConfig":{"description":"Authentication and external credential import configuration (`[auth]` section).","type":"object","properties":{"codex_auth_json_auto_import":{"description":"Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.","type":"boolean","default":false},"codex_auth_json_path":{"description":"Source path for Codex CLI auth.json import.","type":"string","default":"~/.codex/auth.json"}}},"AutonomyConfig":{"type":"object","properties":{"acknowledge_unrestricted_profile":{"description":"Operator acknowledgement for an intentionally unrestricted profile.\nRetained for existing configs; it no longer changes any output or policy behavior.","type":"boolean","default":false},"forbidden_paths":{"description":"Explicit path denylist. Default includes system-critical paths.\n\nFails closed: omitting the key keeps the built-in list rather than\nemptying it, so a partial `[autonomy]` section never removes the\ndenylist.","type":"array","default":["/etc","/root","/home","/usr","/bin","/sbin","/lib","/opt","/boot","/dev","/proc","/sys","/var","/tmp","~/.ssh","~/.gnupg","~/.aws","~/.config"],"items":{"type":"string"}},"level":{"description":"Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).","$ref":"#/$defs/AutonomyLevel","default":"full"},"max_cost_per_day_cents":{"description":"Maximum cost per day in cents per policy. Default: unset (no ceiling).","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"scopes":{"description":"Scope-based tool access control: per-user/channel/chat-type allow/deny rules.","$ref":"#/$defs/ScopeConfig","default":{"assign_owners":[],"default":"allow","rules":[]}},"workspace_only":{"description":"Restrict file writes and command paths to the workspace directory. Default: `true`.\n\nFails closed: a `[autonomy]` section that omits this key keeps the\nworkspace restriction on, so a partial section can never widen the\nfilesystem reach by accident.","type":"boolean","default":true}}},"AutonomyLevel":{"description":"How much autonomy the agent has","oneOf":[{"description":"Read-only: can observe but not act","type":"string","const":"readonly"},{"description":"Supervised: acts but requires approval for risky operations","type":"string","const":"supervised"},{"description":"Full: autonomous execution within policy bounds","type":"string","const":"full"}]},"BackendSelection":{"description":"Which decision backend runs: `auto` (the factory's order) or one kind.","type":"string"},"BrowserComputerUseConfig":{"description":"Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.","type":"object","properties":{"api_key":{"description":"Optional bearer token (retained only for config secret handling).","type":["string","null"],"default":null}}},"BrowserConfig":{"description":"Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.","type":"object","properties":{"allowed_domains":{"description":"Allowed domains for `web_fetch` (exact or subdomain match).","type":"array","default":[],"items":{"type":"string"}},"computer_use":{"description":"Computer-use sidecar config (retained only for `api_key` secret handling).","$ref":"#/$defs/BrowserComputerUseConfig","default":{"api_key":null}}}},"ChannelsConfig":{"description":"Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.","type":"object","properties":{"cli":{"description":"Enable the CLI interactive channel. Default: `true`.","type":"boolean","default":true},"dingtalk":{"description":"DingTalk channel configuration.","anyOf":[{"$ref":"#/$defs/DingTalkConfig"},{"type":"null"}]},"discord":{"description":"Discord bot channel configuration.","anyOf":[{"$ref":"#/$defs/DiscordConfig"},{"type":"null"}]},"email":{"description":"Email channel configuration.","anyOf":[{"$ref":"#/$defs/EmailConfig"},{"type":"null"}]},"imessage":{"description":"iMessage channel configuration (macOS only).","anyOf":[{"$ref":"#/$defs/IMessageConfig"},{"type":"null"}]},"irc":{"description":"IRC channel configuration.","anyOf":[{"$ref":"#/$defs/IrcConfig"},{"type":"null"}]},"lark":{"description":"Lark/Feishu channel configuration.","anyOf":[{"$ref":"#/$defs/LarkConfig"},{"type":"null"}]},"linq":{"description":"Linq Partner API channel configuration.","anyOf":[{"$ref":"#/$defs/LinqConfig"},{"type":"null"}]},"mattermost":{"description":"Mattermost bot channel configuration.","anyOf":[{"$ref":"#/$defs/MattermostConfig"},{"type":"null"}]},"nextcloud_talk":{"description":"Nextcloud Talk bot channel configuration.","anyOf":[{"$ref":"#/$defs/NextcloudTalkConfig"},{"type":"null"}]},"qq":{"description":"QQ Official Bot channel configuration.","anyOf":[{"$ref":"#/$defs/QQConfig"},{"type":"null"}]},"ramflux":{"description":"Local ramflux agent-host bridge.","anyOf":[{"$ref":"#/$defs/RamfluxConfig"},{"type":"null"}],"default":null},"signal":{"description":"Signal channel configuration.","anyOf":[{"$ref":"#/$defs/SignalConfig"},{"type":"null"}]},"slack":{"description":"Slack bot channel configuration.","anyOf":[{"$ref":"#/$defs/SlackConfig"},{"type":"null"}]},"telegram":{"description":"Telegram bot channel configuration.","anyOf":[{"$ref":"#/$defs/TelegramConfig"},{"type":"null"}]},"wacli":{"description":"wacli JSON-RPC daemon channel configuration.","anyOf":[{"$ref":"#/$defs/WacliConfig"},{"type":"null"}],"default":null},"webhook":{"description":"Webhook channel configuration.","anyOf":[{"$ref":"#/$defs/WebhookConfig"},{"type":"null"}]},"whatsapp":{"description":"WhatsApp channel configuration (Cloud API or Web mode).","anyOf":[{"$ref":"#/$defs/WhatsAppConfig"},{"type":"null"}]}}},"ChatConfig":{"description":"Interactive chat configuration (`[chat]`).","type":"object","properties":{"daemon":{"description":"How this chat process reaches the daemon it borrows channels from.","$ref":"#/$defs/ChatDaemonConfig","default":{"token":"","url":""}},"max_concurrent_visible_turns":{"description":"Maximum concurrent visible provider turns in the TUI Redux driver.","type":"integer","format":"uint","default":2,"minimum":0}}},"ChatDaemonConfig":{"description":"Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.","type":"object","properties":{"token":{"description":"Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.","type":"string","default":""},"url":{"description":"Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.","type":"string","default":""}}},"CircuitBreakerConfig":{"description":"The per-backend circuit breaker.","type":"object","properties":{"cooldown_secs":{"description":"Seconds the breaker stays open (1 to 3600).","type":"integer","format":"uint32","default":60,"minimum":0},"failure_threshold":{"description":"Consecutive failures before the breaker opens (1 to 100).","type":"integer","format":"uint32","default":5,"minimum":0}}},"ClassificationRule":{"description":"A single classification rule mapping message patterns to a model hint.","type":"object","properties":{"hint":{"description":"Must match a `[[model_routes]]` hint value.","type":"string"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"max_length":{"description":"Only match if message length <= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"min_length":{"description":"Only match if message length >= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"patterns":{"description":"Case-sensitive literal matches (for \"```\", \"fn \", etc.).","type":"array","default":[],"items":{"type":"string"}},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0}},"required":["hint"]},"CloudflareTunnelConfig":{"type":"object","properties":{"token":{"description":"Cloudflare Tunnel token (from Zero Trust dashboard)","type":"string"}},"required":["token"]},"ComplianceConfig":{"type":"object","properties":{"eu_ai_act":{"$ref":"#/$defs/EuAiActComplianceConfig","default":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null}},"interaction_notice":{"$ref":"#/$defs/InteractionNoticeConfig","default":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}}},"ComposioConfig":{"description":"Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.","type":"object","properties":{"api_key":{"description":"Composio API key (stored encrypted when secrets.encrypt = true)","type":["string","null"],"default":null},"entity_id":{"description":"Default entity ID for multi-user setups","type":"string","default":"default"}}},"CostConfig":{"description":"Cost tracking and budget enforcement configuration (`[cost]` section).","type":"object","properties":{"allow_override":{"description":"Allow requests to exceed budget with --override flag (default: false)","type":"boolean","default":false},"daily_limit_usd":{"description":"Daily spending limit in USD (default: unset, no limit; 0 refuses every priced turn)","type":["number","null"],"format":"double","default":null},"monthly_limit_usd":{"description":"Monthly spending limit in USD (default: unset, no limit)","type":["number","null"],"format":"double","default":null},"prices":{"description":"Per-model pricing (USD per 1M tokens)","type":"object","additionalProperties":{"$ref":"#/$defs/ModelPricing"},"default":{}},"warn_at_percent":{"description":"Warn when spending reaches this percentage of a configured limit (default: 80)","type":"integer","format":"uint8","default":80,"maximum":255,"minimum":0}}},"CredentialRefSetting":{"description":"Which credential a decision backend uses. A reference, never a secret.","type":"string"},"CronConfig":{"description":"Cron job configuration (`[cron]` section).","type":"object","properties":{"max_run_history":{"description":"Maximum number of historical cron run records to retain. Default: `50`.","type":"integer","format":"uint32","default":50,"minimum":0}}},"CustomTunnelConfig":{"type":"object","properties":{"health_url":{"description":"Optional URL to check tunnel health","type":["string","null"]},"start_command":{"description":"Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"","type":"string"},"url_pattern":{"description":"Optional regex to extract public URL from command stdout","type":["string","null"]}},"required":["start_command"]},"DecisionBackendConfig":{"description":"The decision backend (`[decision_engine.backend]`).","type":"object","properties":{"circuit_breaker":{"description":"The circuit breaker.","$ref":"#/$defs/CircuitBreakerConfig","default":{"cooldown_secs":60,"failure_threshold":5}},"credential_ref":{"description":"The credential reference: `\"\"`, `\"none\"` or `cred-`.","$ref":"#/$defs/CredentialRefSetting","default":""},"endpoint":{"description":"The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.","type":"string","default":""},"kind":{"description":"`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).","$ref":"#/$defs/BackendSelection","default":"auto"},"max_request_bytes":{"description":"Largest request body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":65536,"minimum":0},"max_response_bytes":{"description":"Largest response body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":262144,"minimum":0},"model":{"description":"The model the endpoint serves; one exact version for a hosted\nservice.","type":"string","default":""},"pinned_snapshot":{"description":"The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.","type":"string"},"remote_enabled":{"description":"Whether decision state may leave this machine. Default `false`.","type":"boolean","default":false},"timeout_ms":{"description":"Transport timeout (10 ms up to the extra latency budget).","type":"integer","format":"uint32","default":250,"minimum":0}}},"DecisionEngineConfig":{"type":"object","properties":{"backend":{"anyOf":[{"$ref":"#/$defs/DecisionBackendConfig"},{"type":"null"}]},"candidates":{"type":"integer","format":"uint32","default":5,"minimum":0},"enabled":{"type":"boolean","default":false},"mode":{"$ref":"#/$defs/DecisionMode","default":"pre"},"observe_queue":{"type":"integer","format":"uint32","default":64,"minimum":0},"prompt_budget_tokens":{"type":"integer","format":"uint32","default":300,"minimum":0},"telemetry_cap":{"type":"integer","format":"uint32","default":1000,"minimum":0},"timeout_ms":{"type":"integer","format":"uint32","default":1500,"minimum":0},"latency_budget_ms":{"description":"The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.","type":"integer","format":"uint64","default":500,"minimum":0},"token_ratio_limit":{"description":"Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).","type":"number","format":"float","default":0.3499999940395355},"max_candidates":{"description":"The most candidates a turn considers (1 to 32).","type":"integer","format":"uint8","default":12,"maximum":255,"minimum":0}}},"DecisionMode":{"type":"string","enum":["pre","post","both"]},"DeclarationOfConformityConfig":{"type":"object","properties":{"applicable_union_law":{"type":"array","default":[],"items":{"type":"string"}},"artifact_path":{"type":["string","null"],"default":null},"artifact_version":{"type":["string","null"],"default":null},"conformity_assessment_procedure":{"type":["string","null"],"default":null},"conformity_statement":{"type":["string","null"],"default":null},"harmonised_standards":{"type":"array","default":[],"items":{"type":"string"}},"issue_date":{"type":["string","null"],"default":null},"issue_place":{"type":["string","null"],"default":null},"notified_body_certificate":{"type":["string","null"],"default":null},"notified_body_identification_number":{"type":["string","null"],"default":null},"notified_body_name":{"type":["string","null"],"default":null},"personal_data_compliance_statement":{"type":["string","null"],"default":null},"processes_personal_data":{"type":"boolean","default":false},"provider_address":{"type":["string","null"],"default":null},"provider_name":{"type":["string","null"],"default":null},"signer_function":{"type":["string","null"],"default":null},"signer_name":{"type":["string","null"],"default":null},"signer_on_behalf_of":{"type":["string","null"],"default":null},"sole_responsibility_statement":{"type":["string","null"],"default":null},"standards_not_applicable_reason":{"type":["string","null"],"default":null},"system_name":{"type":["string","null"],"default":null},"system_reference":{"type":["string","null"],"default":null},"system_type":{"type":["string","null"],"default":null}}},"DelegateAgentConfig":{"description":"Configuration for a delegate sub-agent used by the `delegate` tool.","type":"object","properties":{"agentic":{"description":"Agentic sub-agent mode (multi-turn tool-call loop). Default true; an\nexplicit `false` makes the agent answer-only with no tools.","type":"boolean","default":true},"allowed_tools":{"description":"Allowlist of tool names available to the sub-agent in agentic mode.\nEmpty or omitted means all tools, the same as `[\"*\"]`.","type":"array","default":[],"items":{"type":"string"}},"api_key":{"description":"Optional API key override","type":["string","null"],"default":null},"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"autonomy":{"description":"The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.","anyOf":[{"$ref":"#/$defs/AutonomyLevel"},{"type":"null"}]},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"enabled":{"description":"Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.","type":"boolean","default":true},"identity_dir":{"description":"Optional identity files directory relative to workspace root.","type":["string","null"],"default":null},"limits":{"$ref":"#/$defs/AgentLimits","default":{"max_concurrent_turns":null,"max_cost_per_day_cents":null}},"max_depth":{"description":"Max recursion depth for nested delegation","type":"integer","format":"uint32","default":8,"minimum":0},"memory_scope":{"description":"Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".","type":["string","null"],"default":null},"model":{"description":"Model name","type":"string"},"provider":{"description":"Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")","type":"string"},"spawn_enabled":{"description":"Whether this agent is allowed to be targeted by sessions_spawn (default: true).","type":["boolean","null"],"default":null},"system_prompt":{"description":"Optional system prompt for the sub-agent","type":["string","null"],"default":null},"temperature":{"description":"Temperature override","type":["number","null"],"format":"double","default":null},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}},"required":["provider","model"]},"DingTalkConfig":{"description":"DingTalk configuration for Stream Mode messaging","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"client_id":{"description":"Client ID (AppKey) from DingTalk developer console","type":"string"},"client_secret":{"description":"Client Secret (AppSecret) from DingTalk developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["client_id","client_secret"]},"DiscordConfig":{"description":"Discord bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Discord user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Discord bot token (from Discord Developer Portal).","type":"string"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"guild_id":{"description":"Optional guild (server) ID to restrict the bot to a single guild.","type":["string","null"]},"listen_to_bots":{"description":"When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.","type":"boolean","default":false}},"required":["bot_token"]},"DmPolicy":{"description":"Policy for direct-message handling.","oneOf":[{"description":"Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).","type":"string","const":"pairing"},{"description":"Accept only senders listed in `allowed_from`.","type":"string","const":"allowlist"},{"description":"Accept any direct sender.","type":"string","const":"open"},{"description":"Ignore direct messages.","type":"string","const":"disabled"}]},"DockerRuntimeConfig":{"description":"Docker runtime configuration (`[runtime.docker]` section).","type":"object","properties":{"allowed_workspace_roots":{"description":"Optional workspace root allowlist for Docker mount validation.","type":"array","default":[],"items":{"type":"string"}},"cpu_limit":{"description":"Optional CPU limit (`None` = no explicit limit).","type":["number","null"],"format":"double","default":1.0},"image":{"description":"Runtime image used to execute shell commands.","type":"string","default":"alpine:3.20"},"memory_limit_mb":{"description":"Optional memory limit in MB (`None` = no explicit limit).","type":["integer","null"],"format":"uint64","default":512,"minimum":0},"mount_workspace":{"description":"Mount configured workspace into `/workspace`.","type":"boolean","default":true},"network":{"description":"Docker network mode (`none`, `bridge`, etc.).","type":"string","default":"none"},"read_only_rootfs":{"description":"Mount root filesystem as read-only.","type":"boolean","default":true}}},"EmailConfig":{"description":"Email channel configuration","type":"object","properties":{"allowed_senders":{"description":"Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)","type":"array","default":[],"items":{"type":"string"}},"from_address":{"description":"From address for outgoing emails","type":"string"},"idle_timeout_secs":{"description":"IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes","type":"integer","format":"uint64","default":1740,"minimum":0},"imap_folder":{"description":"IMAP folder to poll (default: INBOX)","type":"string","default":"INBOX"},"imap_host":{"description":"IMAP server hostname","type":"string"},"imap_port":{"description":"IMAP server port (default: 993 for TLS)","type":"integer","format":"uint16","default":993,"maximum":65535,"minimum":0},"password":{"description":"Email password for authentication","type":"string"},"smtp_host":{"description":"SMTP server hostname","type":"string"},"smtp_port":{"description":"SMTP server port (default: 465 for TLS)","type":"integer","format":"uint16","default":465,"maximum":65535,"minimum":0},"smtp_tls":{"description":"Use TLS for SMTP (default: true)","type":"boolean","default":true},"username":{"description":"Email username for authentication","type":"string"}},"required":["imap_host","smtp_host","username","password","from_address"]},"EmbeddingRouteConfig":{"description":"Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"dimensions":{"description":"Optional embedding dimension override for this route","type":["integer","null"],"format":"uint","default":null,"minimum":0},"hint":{"description":"Route hint name (e.g. \"semantic\", \"archive\", \"faq\")","type":"string"},"model":{"description":"Embedding model to use with that provider","type":"string"},"provider":{"description":"Embedding provider (`none`, `openai`, or `custom:`)","type":"string"}},"required":["hint","provider","model"]},"EuAiActClassificationConfig":{"type":"object","properties":{"assessed_at":{"type":["string","null"],"default":null},"owner":{"type":["string","null"],"default":null},"status":{"$ref":"#/$defs/EuAiActRiskClassification","default":"unclassified"}}},"EuAiActComplianceConfig":{"type":"object","properties":{"classification":{"$ref":"#/$defs/EuAiActClassificationConfig","default":{"assessed_at":null,"owner":null,"status":"unclassified"}},"declaration":{"$ref":"#/$defs/DeclarationOfConformityConfig","default":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null}},"incident_store_path":{"type":["string","null"],"default":null}}},"EuAiActRiskClassification":{"type":"string","enum":["unclassified","high_risk","not_high_risk"]},"FitnessConfig":{"description":"Calendar schedule, evidence thresholds, and retention for fitness v2.","type":"object","properties":{"auto_run":{"description":"Run the daily fitness worker in daemon mode.","type":"boolean","default":true},"max_backfill_days":{"description":"Maximum number of closed days recovered after downtime.","type":"integer","format":"uint32","default":7,"minimum":0},"min_coverage":{"description":"Minimum available metric weight required to publish a final score.","type":"number","format":"double","default":0.6},"min_samples":{"description":"Minimum samples required before an evidence-derived subscore is usable.","type":"integer","format":"uint","default":5,"minimum":0},"retention_days":{"description":"Number of daily JSON reports retained on disk.","type":"integer","format":"uint32","default":180,"minimum":0},"run_at":{"description":"Local wall-clock time (`HH:MM`) at which the previous day is scored.","type":"string","default":"00:10"},"timezone":{"description":"IANA timezone used to define closed calendar days.","type":"string","default":"UTC"}}},"GatewayConfig":{"description":"Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.","type":"object","properties":{"allow_public_bind":{"description":"Allow binding to non-localhost without a tunnel (default: false)","type":"boolean","default":false},"api_rate_limit_per_minute":{"description":"Max `/api/*` requests per minute per authenticated token.","type":"integer","format":"uint32","default":60,"minimum":0},"channel_webhook_dedup_ttl_secs":{"description":"How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.","type":"integer","format":"uint64","default":86400,"minimum":0},"host":{"description":"Gateway host (default: 127.0.0.1)","type":"string","default":"127.0.0.1"},"idempotency_max_keys":{"description":"Maximum distinct idempotency keys retained in memory.","type":"integer","format":"uint","default":10000,"minimum":0},"idempotency_ttl_secs":{"description":"TTL for webhook idempotency keys.","type":"integer","format":"uint64","default":300,"minimum":0},"pair_rate_limit_per_minute":{"description":"Max `/pair` requests per minute per client key.","type":"integer","format":"uint32","default":10,"minimum":0},"paired_tokens":{"description":"Paired bearer tokens (managed automatically, not user-edited)","type":"array","default":[],"items":{"type":"string"}},"port":{"description":"Gateway port (default: 16830)","type":"integer","format":"uint16","default":16830,"maximum":65535,"minimum":0},"rate_limit_max_keys":{"description":"Maximum distinct client keys tracked by gateway rate limiter maps.","type":"integer","format":"uint","default":10000,"minimum":0},"require_pairing":{"description":"Require pairing before accepting requests (default: true)","type":"boolean","default":true},"targeted_agents":{"description":"Switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). Default true. While false, any\notherwise-valid named target answers 409 `agent_disabled` and never\nruns as Main.","type":"boolean","default":true},"trust_forwarded_headers":{"description":"Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.","type":"boolean","default":false},"webhook_rate_limit_per_minute":{"description":"Max `/webhook` requests per minute per client key.","type":"integer","format":"uint32","default":60,"minimum":0}}},"GroupPolicy":{"description":"Policy for group-message handling.","oneOf":[{"description":"Accept only groups listed in `group_allow_from`.","type":"string","const":"allowlist"},{"description":"Accept any group.","type":"string","const":"open"},{"description":"Ignore group messages.","type":"string","const":"disabled"}]},"GroupReplyMode":{"description":"How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.","oneOf":[{"description":"Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).","type":"string","const":"off"},{"description":"Reply only when the bot is @-mentioned (legacy `mention_only = true`).","type":"string","const":"mention-only"},{"description":"Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).","type":"string","const":"smart"}]},"HeartbeatConfig":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]` section).","type":"object","properties":{"active_hours":{"description":"Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.","type":"array","default":[8,23],"items":{"type":"integer","format":"uint8","maximum":255,"minimum":0}},"interval_minutes":{"description":"Interval in minutes between heartbeat pings. Default: `30`.","type":"integer","format":"uint32","default":30,"minimum":0},"prompt":{"description":"Prompt used by heartbeat worker when dispatching tasks.","type":"string","default":"Check HEARTBEAT.md and follow instructions."}}},"HttpRequestConfig":{"description":"HTTP request tool configuration (`[http_request]` section).","type":"object","properties":{"max_response_size":{"description":"Maximum response size in bytes (default: 1MB)","type":"integer","format":"uint","default":1000000,"minimum":0},"timeout_secs":{"description":"Request timeout in seconds (default: 30)","type":"integer","format":"uint64","default":30,"minimum":0}}},"IMessageConfig":{"description":"iMessage channel configuration (macOS only).","type":"object","properties":{"allowed_contacts":{"description":"Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.","type":"array","items":{"type":"string"}},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["allowed_contacts"]},"IdentityBindingConfig":{"description":"Startup identity binding entry (`[[identity_bindings]]`).","type":"object","properties":{"channel":{"type":"string"},"channel_account":{"type":"string"},"display_name":{"type":["string","null"],"default":null},"user_id":{"type":"string"}},"required":["user_id","channel","channel_account"]},"IdentityConfig":{"description":"Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.","type":"object","properties":{"aieos_inline":{"description":"Inline AIEOS JSON (alternative to file path)","type":["string","null"],"default":null},"aieos_path":{"description":"Path to AIEOS JSON file (relative to workspace)","type":["string","null"],"default":null},"format":{"description":"Identity format: \"openclaw\" (default) or \"aieos\"","type":"string","default":"openclaw"}}},"InteractionNoticeApplicability":{"type":"string","enum":["required","not_applicable"]},"InteractionNoticeConfig":{"type":"object","properties":{"applicability":{"$ref":"#/$defs/InteractionNoticeApplicability","default":"required"},"exception_owner":{"type":["string","null"],"default":null},"exception_reviewed_at":{"type":["string","null"],"default":null},"text":{"type":"string","default":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers."},"version":{"type":"string","default":"1"}}},"IrcConfig":{"description":"IRC channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed nicknames (case-insensitive) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"channels":{"description":"Channels to join on connect","type":"array","default":[],"items":{"type":"string"}},"mention_only":{"description":"When true, only process channel/group messages that mention the bot.","type":"boolean","default":false},"nickname":{"description":"Bot nickname","type":"string"},"nickserv_password":{"description":"NickServ IDENTIFY password","type":["string","null"]},"port":{"description":"IRC server port (default: 6697 for TLS)","type":"integer","format":"uint16","default":6697,"maximum":65535,"minimum":0},"sasl_password":{"description":"SASL PLAIN password (IRCv3)","type":["string","null"]},"server":{"description":"IRC server hostname","type":"string"},"server_password":{"description":"Server password (for bouncers like ZNC)","type":["string","null"]},"username":{"description":"Username (defaults to nickname if not set)","type":["string","null"]},"verify_tls":{"description":"Verify TLS certificate (default: true)","type":["boolean","null"]}},"required":["server","nickname"]},"LarkConfig":{"description":"Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from Lark/Feishu developer console","type":"string"},"app_secret":{"description":"App Secret from Lark/Feishu developer console","type":"string"},"encrypt_key":{"description":"Encrypt key for webhook message decryption (optional)","type":["string","null"],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"port":{"description":"HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"receive_mode":{"description":"Event receive mode: \"websocket\" (default) or \"webhook\"","$ref":"#/$defs/LarkReceiveMode","default":"websocket"},"use_feishu":{"description":"Whether to use the Feishu (Chinese) endpoint instead of Lark (International)","type":"boolean","default":false},"verification_token":{"description":"Verification token for webhook validation (optional)","type":["string","null"],"default":null}},"required":["app_id","app_secret"]},"LarkReceiveMode":{"description":"How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.","type":"string","enum":["websocket","webhook"]},"LinqConfig":{"type":"object","properties":{"allowed_senders":{"description":"Allowed sender handles (phone numbers) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"api_token":{"description":"Linq Partner API token (Bearer auth)","type":"string"},"from_phone":{"description":"Phone number to send from (E.164 format)","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"signing_secret":{"description":"Webhook signing secret for signature verification","type":["string","null"],"default":null}},"required":["api_token","from_phone"]},"MattermostConfig":{"description":"Mattermost bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Mattermost user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Mattermost bot access token.","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.","type":["boolean","null"],"default":null},"thread_replies":{"description":"When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.","type":["boolean","null"],"default":null},"url":{"description":"Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).","type":"string"}},"required":["url","bot_token"]},"McpConfig":{"type":"object","properties":{"servers":{"description":"Named MCP server definitions","type":"object","additionalProperties":{"$ref":"#/$defs/McpServerConfig"},"default":{}},"workspace_servers":{"description":"Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.","$ref":"#/$defs/WorkspaceMcpServers"}}},"McpServerConfig":{"type":"object","properties":{"allow_tools":{"description":"Optional allow-list of exposed tools (empty = all)","type":"array","default":[],"items":{"type":"string"}},"args":{"description":"Command args for stdio mode","type":"array","default":[],"items":{"type":"string"}},"command":{"description":"Command for stdio mode","type":["string","null"],"default":null},"deny_tools":{"description":"Optional deny-list of exposed tools","type":"array","default":[],"items":{"type":"string"}},"env":{"description":"Environment variables for stdio mode","type":"object","additionalProperties":{"type":"string"},"default":{}},"request_timeout_ms":{"description":"Request timeout in milliseconds","type":"integer","format":"uint64","default":30000,"minimum":0},"startup_timeout_ms":{"description":"Startup timeout in milliseconds","type":"integer","format":"uint64","default":10000,"minimum":0},"tool_name_prefix":{"description":"Prefix used in tool naming and routing","type":"string","default":"mcp"},"transport":{"description":"Transport type: stdio or http","$ref":"#/$defs/McpTransport","default":"stdio"},"url":{"description":"URL for HTTP mode (streamable HTTP endpoint)","type":["string","null"],"default":null},"working_dir":{"description":"Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).","type":["string","null"]}}},"McpServerRuntimeConfig":{"type":"object","properties":{"allowed_origins":{"description":"Allowed browser origins for future streamable HTTP clients.","type":"array","default":["claude.ai","openai.com","localhost"],"items":{"type":"string"}},"bind":{"description":"Advertised bind address. The gateway may still be started with a CLI port override.","type":"string","default":"127.0.0.1:16831"},"exposed_tools":{"description":"Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.","type":"array","default":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"items":{"type":"string"}},"jwt_algorithms":{"description":"Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.","type":"array","default":["RS256"],"items":{"type":"string"}},"jwt_audience":{"description":"Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.","type":["string","null"],"default":null},"jwt_issuer":{"description":"Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.","type":["string","null"],"default":null},"jwt_jwks":{"description":"Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.","type":["string","null"],"default":null},"jwt_jwks_cache_ttl_secs":{"description":"Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.","type":"integer","format":"uint64","default":300,"minimum":0},"jwt_jwks_uri":{"description":"Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.","type":["string","null"],"default":null},"jwt_public_key_pem":{"description":"PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.","type":["string","null"],"default":null},"rate_limit_rps":{"description":"Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.","type":"integer","format":"uint32","default":10,"minimum":0},"require_auth":{"description":"Require an authenticated external identity for mutating calls.","type":"boolean","default":true}}},"McpTransport":{"type":"string","enum":["stdio","http"]},"MediaConfig":{"description":"Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.","type":"object","properties":{"audio_model":{"description":"Audio model name (Ollama model or OpenAI model). Default: \"whisper\".","type":"string","default":"whisper"},"audio_ollama_url":{"description":"Ollama base URL for audio transcription. Default: \"http://localhost:11434\".","type":"string","default":"http://localhost:11434"},"audio_provider":{"description":"Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".","type":"string","default":"none"},"max_audio_size_mb":{"description":"Maximum audio attachment size in MiB. Default: 20.","type":"integer","format":"uint","default":20,"minimum":0},"max_video_size_mb":{"description":"Maximum video attachment size in MiB. Default: 50.","type":"integer","format":"uint","default":50,"minimum":0},"video_max_frames":{"description":"Maximum video frames to extract per video. Default: 4.","type":"integer","format":"uint","default":4,"minimum":0},"video_provider":{"description":"Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".","type":"string","default":"none"}}},"MemoryConfig":{"description":"Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.","type":"object","properties":{"acl_enabled":{"description":"Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.","type":"boolean","default":false},"archive_after_days":{"description":"Archive daily/session files older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"auto_hydrate":{"description":"Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing","type":"boolean","default":true},"auto_save":{"description":"Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.","type":"boolean","default":true},"backend":{"description":"\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).","type":"string","default":"sqlite"},"conversation_retention_days":{"description":"For sqlite backend: prune conversation rows older than this many days","type":"integer","format":"uint32","default":3,"minimum":0},"daily_retention_days":{"description":"For sqlite backend: prune daily rows older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"embedding_cache_size":{"description":"Max embedding cache entries before LRU eviction","type":"integer","format":"uint","default":10000,"minimum":0},"embedding_dimensions":{"description":"Embedding vector dimensions","type":"integer","format":"uint","default":384,"minimum":0},"embedding_model":{"description":"Embedding model name (e.g. \"text-embedding-3-small\")","type":"string","default":"prx-local-hash-v1"},"embedding_provider":{"description":"Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"","type":"string","default":"local"},"events":{"description":"Raw/quasi-raw message event recording controls (`[memory.events]`).","$ref":"#/$defs/MemoryEventsConfig","default":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true}},"keyword_weight":{"description":"Weight for keyword BM25 in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.3},"legacy_conversation_turns_visible":{"description":"Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.","type":"boolean","default":true},"lucid_budget":{"description":"Token budget for lucid (replaces OPENPRX_LUCID_BUDGET)","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"lucid_cmd":{"description":"Path to lucid binary (replaces OPENPRX_LUCID_CMD)","type":["string","null"],"default":null},"lucid_failure_cooldown_ms":{"description":"Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)","type":"integer","format":"uint64","default":60000,"minimum":0},"lucid_local_hit_threshold":{"description":"Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)","type":"integer","format":"uint","default":3,"minimum":0},"lucid_recall_timeout_ms":{"description":"Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)","type":"integer","format":"uint64","default":5000,"minimum":0},"lucid_store_timeout_ms":{"description":"Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)","type":"integer","format":"uint64","default":3000,"minimum":0},"min_relevance_score":{"description":"Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4","type":"number","format":"double","default":0.4},"purge_after_days":{"description":"Purge archived files older than this many days","type":"integer","format":"uint32","default":30,"minimum":0},"semantic":{"description":"Semantic memory promotion controls (`[memory.semantic]`).","$ref":"#/$defs/MemorySemanticConfig","default":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30}},"sqlite_open_timeout_secs":{"description":"For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"sqlite_read_pool_size":{"description":"For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"vector_candidate_cap":{"description":"How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.","type":"integer","format":"uint","default":2000,"minimum":0},"vector_weight":{"description":"Weight for vector similarity in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.7}}},"MemoryEventsConfig":{"description":"Raw message event recording configuration (`[memory.events]`).","type":"object","properties":{"record_assistant_messages":{"description":"Record assistant replies.","type":"boolean","default":true},"record_tool_events":{"description":"Record tool/event payloads by default.","type":"boolean","default":false},"record_user_messages":{"description":"Record inbound/user messages.","type":"boolean","default":true}}},"MemorySemanticConfig":{"description":"Semantic memory promotion configuration (`[memory.semantic]`).","type":"object","properties":{"auto_promote_assistant_messages":{"description":"Auto-promote eligible assistant messages. Disabled by default to reduce noise.","type":"boolean","default":false},"auto_promote_user_messages":{"description":"Auto-promote eligible user messages into long-term semantic memories.","type":"boolean","default":true},"min_chars":{"description":"Minimum content length for semantic auto-promotion.","type":"integer","format":"uint","default":30,"minimum":0}}},"MemoryWebhookConfig":{"type":"object","properties":{"bind":{"description":"Socket address for the receiver (e.g. \"0.0.0.0:16899\").","type":"string","default":"0.0.0.0:16899"},"signing_secret":{"description":"Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.","type":["string","null"],"default":null},"token":{"description":"Required bearer token for incoming webhook events.","type":["string","null"],"default":null}}},"ModelOperationSetting":{"description":"The operations a `[[providers.models]]` entry may list.","type":"string","enum":["chat","embedding","decision_endpoint","rerank","image_generation","audio_generation","video_generation"]},"ModelPricing":{"description":"Per-model pricing entry (USD per 1M tokens).","type":"object","properties":{"cache_read":{"description":"Cache read input price per 1M tokens.","type":"number","format":"double","default":0.0},"cache_write":{"description":"Cache write/creation input price per 1M tokens.","type":"number","format":"double","default":0.0},"input":{"description":"Input price per 1M tokens","type":"number","format":"double","default":0.0},"output":{"description":"Output price per 1M tokens","type":"number","format":"double","default":0.0}}},"ModelRouteConfig":{"description":"Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"hint":{"description":"Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")","type":"string"},"level":{"type":["string","null"]},"model":{"description":"Model to use with that provider","type":"string"},"provider":{"description":"Provider to route to (must match a known provider name)","type":"string"},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true,"required":["hint","provider","model"]},"ModelSettings":{"description":"A model level plus explicit parameter overrides in `[model_settings.\"\"]`.","type":"object","properties":{"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"level":{"type":["string","null"]},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true},"MultimodalConfig":{"description":"Multimodal (image) handling configuration (`[multimodal]` section).","type":"object","properties":{"allow_remote_fetch":{"description":"Allow fetching remote image URLs (http/https). Enabled by default.","type":"boolean","default":true},"max_image_size_mb":{"description":"Maximum image payload size in MiB before base64 encoding.","type":"integer","format":"uint","default":5,"minimum":0},"max_images":{"description":"Maximum number of image attachments accepted per request.","type":"integer","format":"uint","default":4,"minimum":0}}},"NextcloudTalkConfig":{"description":"Nextcloud Talk bot configuration (webhook receive + OCS send API).","type":"object","properties":{"allowed_users":{"description":"Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Bot app token used for OCS API bearer auth.","type":"string"},"base_url":{"description":"Nextcloud base URL (e.g. \"https://cloud.example.com\").","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"webhook_secret":{"description":"Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).","type":["string","null"],"default":null}},"required":["base_url","app_token"]},"NgrokTunnelConfig":{"type":"object","properties":{"auth_token":{"description":"ngrok auth token","type":"string"},"domain":{"description":"Optional custom domain","type":["string","null"]}},"required":["auth_token"]},"NodeServerConfig":{"description":"Node daemon runtime config used by `prx-node`.","type":"object","properties":{"allowed_commands":{"description":"Command allowlist matched on first token. Default: empty, which allows any\ncommand from an authenticated caller; `[\"*\"]` means the same.","type":"array","default":[],"items":{"type":"string"}},"bearer_token":{"description":"Required bearer token for /rpc.","type":"string","default":""},"blocked_commands":{"description":"Command denylist matched on first token. Always enforced.","type":"array","default":[],"items":{"type":"string"}},"exec_timeout_ms":{"description":"Default command timeout in milliseconds.","type":"integer","format":"uint64","default":15000,"minimum":0},"hmac_secret":{"description":"Optional HMAC signing secret.","type":["string","null"],"default":null},"listen_addr":{"description":"Listen address for node daemon.","type":"string","default":"127.0.0.1:8787"},"max_concurrent_tasks":{"description":"Maximum number of concurrent async command tasks.","type":"integer","format":"uint","default":8,"minimum":0},"max_output_bytes":{"description":"Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.","type":"integer","format":"uint","default":1048576,"minimum":0},"sandbox_root":{"description":"Sandbox root directory for read/write/cwd constraints.","type":"string","default":"."},"task_result_ttl_ms":{"description":"TTL for completed task results in milliseconds.","type":"integer","format":"uint64","default":3600000,"minimum":0},"tls_cert":{"description":"TLS certificate path (PEM).","type":["string","null"],"default":null},"tls_key":{"description":"TLS private key path (PEM).","type":["string","null"],"default":null},"tls_required":{"description":"Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.","type":"boolean","default":true}}},"NodesConfig":{"description":"Remote node proxy configuration for core-side RPC calls and node daemon defaults.","type":"object","properties":{"nodes":{"description":"Configured remote nodes.","type":"array","default":[],"items":{"$ref":"#/$defs/RemoteNodeConfig"}},"request_timeout_ms":{"description":"Default request timeout for node RPC calls.","type":"integer","format":"uint64","default":15000,"minimum":0},"retry_max":{"description":"Default max retries for node RPC calls.","type":"integer","format":"uint8","default":2,"maximum":255,"minimum":0},"server":{"description":"Embedded node server defaults used by `prx-node`.","$ref":"#/$defs/NodeServerConfig","default":{"allowed_commands":[],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}}},"ObservabilityConfig":{"description":"Observability backend configuration (`[observability]` section).","type":"object","properties":{"backend":{"description":"\"none\" | \"log\" | \"prometheus\" | \"otel\"","type":"string","default":"none"},"otel_endpoint":{"description":"OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".","type":["string","null"],"default":null},"otel_service_name":{"description":"Service name reported to the OTel collector. Defaults to \"prx\".","type":["string","null"],"default":null}}},"OllamaProviderConfig":{"description":"Ollama-specific request options (`[providers.ollama]`).","type":"object","properties":{"num_ctx":{"description":"Explicit context window sent as Ollama `options.num_ctx`.","type":["integer","null"],"format":"uint","default":null,"minimum":0}}},"OsPagingConfig":{"description":"Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.","type":"object","properties":{"eviction_threshold":{"description":"Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.","type":"number","format":"double","default":0.7},"keep_recent_messages":{"description":"Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).","type":"integer","format":"uint","default":12,"minimum":0},"max_recalled_pages":{"description":"Maximum number of evicted pages (document chunks) recalled per turn.","type":"integer","format":"uint","default":10,"minimum":0},"proactive_retrieval":{"description":"Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.","type":"boolean","default":true},"retrieval_injection_role":{"description":"Role under which recalled pages are injected.","$ref":"#/$defs/RetrievalInjectionRole","default":"system"}}},"PluginsConfig":{"description":"WASM plugin runtime configuration.","type":"object","properties":{"enabled":{"description":"Load WASM plugins from `/plugins`. Default: `false`.","type":"boolean","default":false}},"additionalProperties":false},"ProviderModelConfig":{"description":"One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.","type":"object","properties":{"context_window":{"description":"The model's context window in tokens.","type":["integer","null"],"format":"uint32","minimum":0},"model":{"description":"The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.","type":["string","null"]},"native_tools":{"description":"Whether the model accepts native tool calls.","type":["boolean","null"]},"operations":{"description":"The complete list of operations the model executes; every operation not\nlisted is unsupported.","type":["array","null"],"items":{"$ref":"#/$defs/ModelOperationSetting"}},"provider":{"description":"The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.","type":"string"},"streaming":{"description":"Whether the model streams responses.","type":["boolean","null"]},"structured_output":{"description":"Whether the model honours a JSON-schema response format.","type":["boolean","null"]},"tool_call_dialect":{"description":"The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema_dialect":{"description":"The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]},"vision_input":{"description":"Whether the model accepts image input.","type":["boolean","null"]}},"required":["provider"]},"ProviderToolDialectConfig":{"description":"One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.","type":"object","properties":{"model":{"description":"The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.","type":["string","null"]},"provider":{"description":"The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.","type":"string"},"tool_call":{"description":"The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema":{"description":"The tool-schema dialect the endpoint accepts.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]}},"required":["provider"]},"ProvidersConfig":{"description":"Provider-specific runtime configuration (`[providers]`).","type":"object","properties":{"models":{"description":"Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.","type":"array","items":{"$ref":"#/$defs/ProviderModelConfig"}},"ollama":{"description":"Ollama-specific request options (`[providers.ollama]`).","$ref":"#/$defs/OllamaProviderConfig","default":{"num_ctx":null}},"tool_dialects":{"description":"Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).","type":"array","items":{"$ref":"#/$defs/ProviderToolDialectConfig"}}}},"ProxyConfig":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).","type":"object","properties":{"all_proxy":{"description":"Fallback proxy URL for all schemes.","type":["string","null"],"default":null},"http_proxy":{"description":"Proxy URL for HTTP requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"https_proxy":{"description":"Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"no_proxy":{"description":"No-proxy bypass list. Same format as NO_PROXY.","type":"array","default":[],"items":{"type":"string"}},"scope":{"description":"Proxy application scope.","$ref":"#/$defs/ProxyScope","default":"prx"},"services":{"description":"Service selectors used when scope = \"services\".","type":"array","default":[],"items":{"type":"string"}}}},"ProxyScope":{"description":"Proxy application scope — determines which outbound traffic uses the proxy.","oneOf":[{"description":"Use system environment proxy variables only.","type":"string","const":"environment"},{"description":"Apply proxy to all OpenPRX-managed HTTP traffic (default).","type":"string","const":"prx"},{"description":"Apply proxy only to explicitly listed service selectors.","type":"string","const":"services"}]},"QQConfig":{"description":"QQ Official Bot configuration (Tencent QQ Bot SDK)","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs. Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from QQ Bot developer console","type":"string"},"app_secret":{"description":"App Secret from QQ Bot developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["app_id","app_secret"]},"QueryClassificationConfig":{"description":"Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.","type":"object","properties":{"rules":{"description":"Classification rules evaluated in priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/ClassificationRule"}}}},"RamfluxAccountConfig":{"description":"Persona for one ramflux AI account. Missing fields fall back to the global agent.","type":"object","properties":{"cross_conversation_retrieval":{"description":"Cross-conversation memory retrieval. Off unless the owner sets it.","type":"boolean","default":false},"model":{"type":["string","null"],"default":null},"provider":{"type":["string","null"],"default":null},"scope_profile":{"type":["string","null"],"default":null},"system_prompt_file":{"description":"Path to a system-prompt file. Relative paths are resolved from the workspace.","type":["string","null"],"default":null}},"additionalProperties":false},"RamfluxAttachmentFetch":{"description":"Per-turn caps for `attachment.fetch`.","type":"object","properties":{"max_bytes":{"type":"integer","format":"uint64","default":5242880,"minimum":0},"max_per_turn":{"type":"integer","format":"uint8","default":4,"maximum":255,"minimum":0}},"additionalProperties":false},"RamfluxAuthorizationMode":{"description":"How prx combines its own setting with `bridge.hello.authorization`.","oneOf":[{"description":"Use the agent-host value. Until hello arrives, the effective mode is supervised.","type":"string","const":"follow_rf"},{"description":"Always supervised, even when the agent-host declares full.","type":"string","const":"supervised"},{"description":"Full only when the agent-host also declares full. Config alone never yields full.","type":"string","const":"full"}]},"RamfluxConfig":{"description":"Local ramflux agent-host bridge (`[channels_config.ramflux]`).","type":"object","properties":{"accounts":{"type":"object","additionalProperties":{"$ref":"#/$defs/RamfluxAccountConfig"},"default":{}},"allowed_block_types":{"type":"array","default":["Text","Markdown","Heading","KeyValue","Metric","List","TableFallback","Form","Input","Select","Progress","LogStream","Warning","Error","Success","Approval","ActionGroup","FilePreview","Fallback"],"items":{"type":"string"}},"attachment_fetch":{"$ref":"#/$defs/RamfluxAttachmentFetch","default":{"max_bytes":5242880,"max_per_turn":4}},"authorization_mode":{"$ref":"#/$defs/RamfluxAuthorizationMode","default":"follow_rf"},"encrypt_at_rest":{"type":"boolean","default":true},"max_in_flight_per_conversation":{"type":"integer","format":"uint8","default":1,"maximum":255,"minimum":0},"on_new_message":{"$ref":"#/$defs/RamfluxOnNewMessage","default":"queue"},"socket_path":{"description":"Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.","type":["string","null"],"default":null},"surface_limits":{"$ref":"#/$defs/RamfluxSurfaceLimits","default":{"max_actions":16,"max_blocks":32,"max_bytes":65536}},"turn_wall_clock_secs":{"description":"Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.","type":"integer","format":"uint64","default":120,"minimum":0}},"additionalProperties":false},"RamfluxOnNewMessage":{"description":"What to do with a new inbound message while a turn for that conversation is running.","type":"string","enum":["queue","interrupt"]},"RamfluxSurfaceLimits":{"description":"Limits for `reply.surface` blocks and actions.","type":"object","properties":{"max_actions":{"type":"integer","format":"uint32","default":16,"minimum":0},"max_blocks":{"type":"integer","format":"uint32","default":32,"minimum":0},"max_bytes":{"type":"integer","format":"uint32","default":65536,"minimum":0}},"additionalProperties":false},"ReliabilityCircuitBreakerConfig":{"description":"Process-local provider circuit policy (`[reliability.circuit_breaker]`).","type":"object","properties":{"enabled":{"description":"Enable protection for factory-built provider chains.","type":"boolean","default":true},"failure_threshold":{"description":"Consecutive transient failures that open a circuit (at least 1).","type":"integer","format":"uint32","default":5,"minimum":0},"max_open_secs":{"description":"Maximum doubled window, between open_secs and 3600 seconds.","type":"integer","format":"uint64","default":300,"minimum":0},"open_secs":{"description":"Initial open window in seconds (at least 1).","type":"integer","format":"uint64","default":30,"minimum":0}}},"ReliabilityConfig":{"description":"Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.","type":"object","properties":{"acknowledge_single_provider_risk":{"description":"Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.","type":"boolean","default":false},"api_keys":{"description":"Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.","type":"array","default":[],"items":{"type":"string"}},"channel_initial_backoff_secs":{"description":"Initial backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":2,"minimum":0},"channel_max_backoff_secs":{"description":"Max backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":60,"minimum":0},"circuit_breaker":{"description":"Per-provider consecutive failure protection.","$ref":"#/$defs/ReliabilityCircuitBreakerConfig","default":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30}},"fallback_providers":{"description":"Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).","type":"array","default":[],"items":{"type":"string"}},"model_fallbacks":{"description":"Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`","type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"default":{}},"provider_backoff_ms":{"description":"Base backoff (ms) for provider retry delay.","type":"integer","format":"uint64","default":500,"minimum":0},"provider_retries":{"description":"Retries per provider before failing over.","type":"integer","format":"uint32","default":2,"minimum":0},"scheduler_poll_secs":{"description":"Scheduler polling cadence in seconds.","type":"integer","format":"uint64","default":15,"minimum":0},"scheduler_retries":{"description":"Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.","type":"integer","format":"uint32","default":2,"minimum":0}}},"RemoteNodeConfig":{"description":"A remote node target for core-side node proxy calls.","type":"object","properties":{"bearer_token":{"description":"Bearer token for node RPC authentication.","type":"string"},"endpoint":{"description":"Base endpoint (e.g. \"http://127.0.0.1:8787\").","type":"string"},"hmac_secret":{"description":"Optional request signing key (HMAC-SHA256).","type":["string","null"],"default":null},"id":{"description":"Stable node ID used by the nodes tool.","type":"string"},"retry_max":{"description":"Optional per-node retry override.","type":["integer","null"],"format":"uint8","default":null,"maximum":255,"minimum":0},"timeout_ms":{"description":"Optional per-node timeout override.","type":["integer","null"],"format":"uint64","default":null,"minimum":0}},"required":["id","endpoint","bearer_token"]},"RetrievalInjectionRole":{"description":"Where recalled context pages are injected back into the request.","oneOf":[{"description":"Inject recalled pages as a leading `system` message (not user-visible).","type":"string","const":"system"},{"description":"Inject recalled pages as a leading `user` message.","type":"string","const":"user"}]},"RouterConfig":{"description":"Heuristic LLM router configuration (`[router]` section).","type":"object","properties":{"alpha":{"description":"Similarity score weight. Phase 1 keeps this at `0.0`.","type":"number","format":"float","default":0.0},"beta":{"description":"Capability score weight.","type":"number","format":"float","default":0.5},"delta":{"description":"Cost penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"epsilon":{"description":"Latency penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"gamma":{"description":"Elo score weight.","type":"number","format":"float","default":0.30000001192092896},"knn_k":{"description":"Number of nearest neighbors considered for voting. Default: `7`.","type":"integer","format":"uint","default":7,"minimum":0},"knn_min_records":{"description":"Minimum history records before KNN affects routing. Default: `10`.","type":"integer","format":"uint","default":10,"minimum":0},"models":{"description":"Candidate model registry.","type":"array","default":[],"items":{"$ref":"#/$defs/RouterModelConfig"}}}},"RouterModelConfig":{"description":"Static router metadata for one model candidate.","type":"object","properties":{"categories":{"description":"Capability categories such as `conversation`, `code`, or `analysis`.","type":"array","default":[],"items":{"type":"string"}},"cost_per_million_tokens":{"description":"USD cost per million tokens.","type":"number","format":"float","default":0.0},"elo_rating":{"description":"Initial Elo rating.","type":"number","format":"float","default":1000.0},"latency_ms":{"description":"Average latency in milliseconds.","type":"integer","format":"uint32","default":2000,"minimum":0},"max_context":{"description":"Maximum context window in tokens.","type":"integer","format":"uint","default":1000000,"minimum":0},"model_id":{"description":"Model identifier without provider prefix.","type":"string"},"provider":{"description":"Provider identifier.","type":"string"},"reserved_output_tokens":{"description":"Output tokens reserved for this model when planning input context.","type":["integer","null"],"format":"uint","minimum":0}},"required":["model_id","provider"]},"RuntimeConfig":{"description":"Runtime adapter configuration (`[runtime]` section).","type":"object","properties":{"codex_reasoning_effort":{"description":"Codex reasoning effort","type":["string","null"],"default":null},"codex_stream_idle_timeout_secs":{"description":"Codex stream idle timeout in seconds","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"docker":{"description":"Docker runtime settings (used when `kind = \"docker\"`).","$ref":"#/$defs/DockerRuntimeConfig","default":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true}},"idle_hang_secs":{"description":"Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"kind":{"description":"Runtime kind (`native` | `docker`).","type":"string","default":"native"},"long_task_warn_secs":{"description":"Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"managed_cgroup_root":{"description":"Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.","type":["string","null"],"default":null},"max_blocking_threads":{"description":"Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"reasoning_enabled":{"description":"Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported","type":["boolean","null"],"default":null},"shell_env_allowlist":{"description":"Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.","type":"array","default":[],"items":{"type":"string"}},"workdir":{"description":"Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.","type":["string","null"],"default":null}}},"SchedulerConfig":{"description":"Scheduler configuration for periodic task execution (`[scheduler]` section).","type":"object","properties":{"claim_lease_secs":{"description":"Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.","type":"integer","format":"uint64","default":90,"minimum":0},"max_tasks":{"description":"Maximum number of persisted scheduled tasks.","type":"integer","format":"uint","default":64,"minimum":0}}},"ScopeConfig":{"description":"Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```","type":"object","properties":{"assign_owners":{"description":"Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.","type":"array","default":[],"items":{"type":"string"}},"default":{"description":"Default action when no rule matches: \"allow\" (default) or \"deny\".","$ref":"#/$defs/ScopeDefault","default":"allow"},"rules":{"description":"Ordered list of scope rules evaluated top-to-bottom.","type":"array","default":[],"items":{"$ref":"#/$defs/ScopeRule"}}}},"ScopeDefault":{"description":"What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.","oneOf":[{"description":"Unmatched tool calls are allowed (the default).","type":"string","const":"allow"},{"description":"Unmatched tool calls are refused.","type":"string","const":"deny"}]},"ScopeRule":{"description":"A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.","type":"object","properties":{"assign_allow":{"description":"Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".","type":"array","default":[],"items":{"type":"string"}},"assign_deny":{"description":"Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.","type":"array","default":[],"items":{"type":"string"}},"channel":{"description":"Match by channel name: \"signal\", \"telegram\", \"discord\", etc.","type":["string","null"]},"chat_type":{"description":"Match by chat type: \"direct\", \"group\", or \"*\" for any type.","type":["string","null"]},"send_allow":{"description":"Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.","type":"array","default":[],"items":{"type":"string"}},"send_deny":{"description":"Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.","type":"array","default":[],"items":{"type":"string"}},"tools_allow":{"description":"Tool whitelist: only these tools are allowed (empty = all tools permitted).","type":"array","default":[],"items":{"type":"string"}},"tools_deny":{"description":"Tool blacklist: these tools are denied regardless of allow list.","type":"array","default":[],"items":{"type":"string"}},"user":{"description":"Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.","type":["string","null"]}}},"SecretsConfig":{"description":"Secrets encryption configuration (`[secrets]` section).","type":"object","properties":{"encrypt":{"description":"Enable encryption for API keys and tokens in config.toml","type":"boolean","default":true}}},"SecurityConfig":{"description":"Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.","type":"object","properties":{"audit":{"description":"Audit logging configuration","$ref":"#/$defs/AuditConfig","default":{"log_path":"audit.log","max_size_mb":100}},"workspace_hooks":{"description":"Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.","$ref":"#/$defs/WorkspaceHooks"}}},"SelfSystemConfig":{"description":"Self-system experimental automation config (`[self_system]`).","type":"object","properties":{"evolution_config_path":{"description":"Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG)","type":["string","null"],"default":null},"evolution_debug_raw":{"description":"Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW)","type":"boolean","default":false},"evolution_interval_hours":{"description":"Evolution scheduler interval in hours (daemon mode).","type":"integer","format":"uint32","default":24,"minimum":0},"evolution_judge_timeout_secs":{"description":"Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.","type":"integer","format":"uint64","default":180,"minimum":0},"evolution_model_max_micro_usd":{"description":"Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.","type":"integer","format":"uint64","default":0,"minimum":0},"evolution_model_max_tokens":{"description":"Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.","type":"integer","format":"uint64","default":16384,"minimum":0},"fitness":{"description":"Daily fitness snapshot policy.","$ref":"#/$defs/FitnessConfig","default":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"}},"fitness_interval_hours":{"description":"Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.","type":"integer","format":"uint64","default":24,"minimum":0}}},"SessionsSpawnConfig":{"description":"Sessions spawn configuration (`[sessions_spawn]` section).","type":"object","properties":{"cleanup_on_complete":{"description":"Remove worker workspace directory after process-mode completion.","type":"boolean","default":true},"default_mode":{"description":"Default execution mode for sessions_spawn (`task` or `process`).","type":"string","default":"task"},"process_memory_strategy":{"description":"Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.","type":"string","default":"shared_fabric"},"worker_workspace_root":{"description":"Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.","type":["string","null"],"default":null}}},"SignalConfig":{"type":"object","properties":{"account":{"description":"E.164 phone number of the signal-cli account (e.g. \"+1234567890\").","type":"string"},"allowed_from":{"description":"Allowed sender phone numbers (E.164) or \"*\" for all.","type":"array","default":[],"items":{"type":"string"}},"cli_path":{"description":"Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).","type":["string","null"],"default":null},"daemon_http_port":{"description":"Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"daemon_mode":{"description":"Deprecated: ignored. Accepted for backward compatibility with older config files.","type":["boolean","null"],"default":null},"data_dir":{"description":"signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_id":{"description":"Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group","type":["string","null"],"default":null},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"http_url":{"description":"Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.","type":"string","default":"http://localhost:8080"},"ignore_attachments":{"description":"Skip messages that are attachment-only (no text body).","type":"boolean","default":false},"ignore_stories":{"description":"Skip incoming story messages.","type":"boolean","default":false},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"mode":{"description":"Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.","type":["string","null"],"default":null},"startup_timeout_ms":{"description":"Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.","type":"integer","format":"uint64","default":30000,"minimum":0},"storm_protection":{"description":"Signal ingress storm protection controls.","$ref":"#/$defs/SignalStormProtectionConfig","default":{"abnormal_threshold":10,"abnormal_window_secs":60,"breaker_duration_secs":300,"dedupe_ttl_secs":60,"min_reply_interval_secs":2}}},"required":["account"]},"SignalStormProtectionConfig":{"type":"object","properties":{"abnormal_threshold":{"description":"Non-user event threshold within `abnormal_window_secs` before tripping the breaker.","type":"integer","format":"uint","default":10,"minimum":0},"abnormal_window_secs":{"description":"Sliding window in seconds for non-user event counting.","type":"integer","format":"uint64","default":60,"minimum":0},"breaker_duration_secs":{"description":"Circuit breaker duration in seconds after threshold is reached.","type":"integer","format":"uint64","default":300,"minimum":0},"dedupe_ttl_secs":{"description":"Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.","type":"integer","format":"uint64","default":60,"minimum":0},"min_reply_interval_secs":{"description":"Minimum interval in seconds between replies for the same `(channel + reply_target)`.","type":"integer","format":"uint64","default":2,"minimum":0}}},"SkillRagConfig":{"description":"Dynamic skill retrieval configuration (`[skill_rag]` section).","type":"object","properties":{"top_k":{"description":"How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).","type":"integer","format":"uint","default":32,"minimum":0}}},"SkillSuiteRegistration":{"description":"The frozen suite that governs one skill's proposals.","type":"object","properties":{"skill_id":{"description":"The skill the suite governs.","type":"string"},"suite_digest":{"description":"SHA-256 digest (64 lowercase hex digits) of the frozen suite.","type":"string"}},"additionalProperties":false,"required":["skill_id","suite_digest"]},"SkillsConfig":{"description":"Skills loading configuration (`[skills]` section).","type":"object","properties":{"open_skills_dir":{"description":"Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.","type":["string","null"],"default":null},"openclaw_skills_dir":{"description":"Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.","type":["string","null"],"default":null}}},"SkillsLifecycleConfig":{"description":"`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.","type":"object","properties":{"allow_executable_proposals":{"description":"Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.","type":"boolean","default":false},"enabled":{"description":"Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.","type":"boolean","default":false},"max_concurrent_evaluations":{"description":"Most evaluations running at once.","type":"integer","format":"uint32","default":1,"minimum":0},"max_edit_fraction":{"description":"Edit budget of a proposal as a fraction of the skill body, in (0, 1].","type":"number","format":"double","default":0.2},"max_edit_tokens":{"description":"Edit budget of a proposal, in tokens.","type":"integer","format":"uint64","default":300,"minimum":0},"max_proposals_per_cycle":{"description":"Most proposals one cycle may start.","type":"integer","format":"uint32","default":1,"minimum":0},"min_cases_floor":{"description":"Smallest `min_cases` a governing suite may declare. Below 3 is refused.","type":"integer","format":"uint32","default":3,"minimum":0},"mode":{"description":"`draft_only`, `shadow` or `auto`.","$ref":"#/$defs/SkillsLifecycleModeConfig","default":"draft_only"},"owner_scope":{"description":"The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.","type":["string","null"],"default":null},"require_holdout":{"description":"A governing suite must have a holdout split. `false` is refused.","type":"boolean","default":true},"storage_dir":{"description":"Store location under the workspace. Only the default is supported.","type":"string","default":"self/skill-lifecycle"},"suites":{"description":"The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.","type":"array","default":[],"items":{"$ref":"#/$defs/SkillSuiteRegistration"}}},"additionalProperties":false},"SkillsLifecycleModeConfig":{"description":"What the lifecycle may do. Mirrors `LifecycleMode`.","oneOf":[{"description":"Drafts and reviews only.","type":"string","const":"draft_only"},{"description":"Drafts plus evaluation and gating; never publishes.","type":"string","const":"shadow"},{"description":"Publishes an eligible proposal after every gate.","type":"string","const":"auto"}]},"SlackConfig":{"description":"Slack bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Slack user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Slack app-level token for Socket Mode (xapp-...).","type":["string","null"]},"bot_token":{"description":"Slack bot OAuth token (xoxb-...).","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["bot_token"]},"SmartGroupConfig":{"description":"Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).","type":"object","properties":{"classifier_max_context_messages":{"description":"How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.","type":"integer","format":"uint","default":3,"minimum":0},"classifier_model":{"description":"Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.","type":"string","default":""},"classifier_provider":{"description":"Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.","type":"string","default":""},"classifier_temperature":{"description":"Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).","type":"number","format":"double","default":0.0},"classifier_timeout_secs":{"description":"Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.","type":"integer","format":"uint64","default":5,"minimum":0}}},"StorageConfig":{"description":"Persistent storage configuration (`[storage]` section).","type":"object","properties":{"provider":{"description":"Storage provider settings (e.g. sqlite, postgres).","$ref":"#/$defs/StorageProviderSection","default":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}}},"StorageProviderConfig":{"description":"Storage provider backend configuration (e.g. postgres connection details).","type":"object","properties":{"connect_timeout_secs":{"description":"Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"db_url":{"description":"Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.","type":["string","null"],"default":null},"pool_max_size":{"description":"Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.","type":"integer","format":"uint","default":32,"minimum":0},"provider":{"description":"Storage engine key (e.g. \"postgres\", \"sqlite\").","type":"string","default":""},"schema":{"description":"Database schema for SQL backends.","type":"string","default":"public"},"table":{"description":"Table name for memory entries.","type":"string","default":"memories"}}},"StorageProviderSection":{"description":"Wrapper for the storage provider configuration section.","type":"object","properties":{"config":{"description":"Storage provider backend settings.","$ref":"#/$defs/StorageProviderConfig","default":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"StreamMode":{"description":"Streaming mode for channels that support progressive message updates.","oneOf":[{"description":"No streaming -- send the complete response as a single message (default).","type":"string","const":"off"},{"description":"Update a draft message with every flush interval.","type":"string","const":"partial"}]},"TailscaleTunnelConfig":{"type":"object","properties":{"funnel":{"description":"Use Tailscale Funnel (public internet) vs Serve (tailnet only)","type":"boolean","default":false},"hostname":{"description":"Optional hostname override","type":["string","null"]}}},"TaskRoutingConfig":{"description":"Lightweight pre-LLM task routing.","type":"object","properties":{"default_intent":{"description":"Fallback intent when no rule matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"rules":{"description":"Rules evaluated in descending priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/TaskRoutingRule"}}}},"TaskRoutingIntentConfig":{"description":"Task-routing default and rule intent.","type":"string","enum":["simple","delegate","stream"]},"TaskRoutingRule":{"description":"A single task-routing rule.","type":"object","properties":{"intent":{"description":"Route intent to apply when a keyword matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"model_hint":{"description":"Optional model hint/raw model for non-delegated requests.","type":["string","null"],"default":null},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0},"sub_agent_model":{"description":"Optional raw sub-agent model override for delegated tasks.","type":["string","null"],"default":null}}},"TelegramConfig":{"description":"Telegram bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Telegram user IDs or usernames. Empty = deny all.","type":"array","items":{"type":"string"}},"bot_token":{"description":"Telegram Bot API token (from @BotFather).","type":"string"},"draft_update_interval_ms":{"description":"Minimum interval (ms) between draft message edits to avoid rate limits.","type":"integer","format":"uint64","default":1000,"minimum":0},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"interrupt_on_new_message":{"description":"When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.","type":"boolean","default":false},"stream_mode":{"description":"Streaming mode for progressive response delivery via message edits.","$ref":"#/$defs/StreamMode","default":"off"}},"required":["bot_token","allowed_users"]},"ToolCallDialectSetting":{"description":"The tool-call grammars an operator may declare for an endpoint.","oneOf":[{"description":"Only the native `tool_calls` array is a tool call (the default).","type":"string","const":"native"},{"description":"Additionally read `{json}` from the content,\nfor a tool name the request registered.","type":"string","const":"xml_function_tags"}]},"ToolSchemaDialectSetting":{"description":"The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.","oneOf":[{"description":"The published document, byte for byte (the default).","type":"string","const":"raw"},{"description":"The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.","type":"string","const":"no_root_combinators"}]},"ToolTieringConfig":{"description":"Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.","type":"object","properties":{"always_exclude":{"description":"Tool names excluded from capability publication.","type":"array","default":[],"items":{"type":"string"}},"always_include":{"description":"Tool names preferred for direct publication, subject to admission gates.","type":"array","default":[],"items":{"type":"string"}},"channel_exclude":{"description":"Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefault: empty (nothing is hidden); list tool names to hide them on channels.","type":"array","default":[],"items":{"type":"string"}}}},"TunnelConfig":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.","type":"object","properties":{"cloudflare":{"description":"Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).","anyOf":[{"$ref":"#/$defs/CloudflareTunnelConfig"},{"type":"null"}],"default":null},"custom":{"description":"Custom tunnel command configuration (used when `provider = \"custom\"`).","anyOf":[{"$ref":"#/$defs/CustomTunnelConfig"},{"type":"null"}],"default":null},"ngrok":{"description":"ngrok tunnel configuration (used when `provider = \"ngrok\"`).","anyOf":[{"$ref":"#/$defs/NgrokTunnelConfig"},{"type":"null"}],"default":null},"provider":{"description":"Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.","type":"string","default":"none"},"tailscale":{"description":"Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).","anyOf":[{"$ref":"#/$defs/TailscaleTunnelConfig"},{"type":"null"}],"default":null}}},"UserPolicyConfig":{"description":"Startup user policy entry (`[[user_policies]]`).","type":"object","properties":{"blocked_patterns":{"type":"array","default":[],"items":{"type":"string"}},"projects":{"type":"array","default":[],"items":{"type":"string"}},"role":{"type":"string","default":"guest"},"user_id":{"type":"string"},"visibility_ceiling":{"type":"string","default":"private"}},"required":["user_id"]},"WacliConfig":{"description":"wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```","type":"object","properties":{"allow_unsigned_loopback":{"description":"Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).","type":"boolean","default":false},"allowed_from":{"description":"Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.","type":"array","default":["*"],"items":{"type":"string"}},"bot_jid":{"description":"Bot's own JID, used for reply-to-bot mention detection.","type":["string","null"],"default":null},"bot_lid":{"description":"The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.","type":["string","null"],"default":null},"bot_number":{"description":"Bot's own phone number (digits), used for `@` mention detection.","type":["string","null"],"default":null},"cli_path":{"description":"Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.","type":["string","null"],"default":null},"group_reply_mode":{"description":"Smart group-reply mode. When `None`, derived from `mention_only`.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"host":{"description":"REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].","type":["string","null"],"writeOnly":true},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"outbound_media_workspace_only":{"description":"Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.","type":"boolean","default":false},"port":{"description":"REMOVED: legacy JSON-RPC daemon port. See `host`.","type":["integer","null"],"format":"uint16","maximum":65535,"minimum":0,"writeOnly":true},"self_chat_mode":{"description":"Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.","type":"boolean","default":false},"store_dir":{"description":"wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.","type":["string","null"],"default":null},"webhook_listen":{"description":"Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").","type":"string","default":"127.0.0.1:16868"},"webhook_path":{"description":"HTTP path the webhook server serves (default: \"/wacli\").","type":"string","default":"/wacli"},"webhook_secret":{"description":"HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.","type":["string","null"],"default":null}}},"WebSearchConfig":{"description":"Web search tool configuration (`[web_search]` section).","type":"object","properties":{"brave_api_key":{"description":"Brave Search API key (required if provider is \"brave\")","type":["string","null"],"default":null},"fetch_max_chars":{"description":"Maximum characters returned by `web_fetch` (default 10000)","type":"integer","format":"uint","default":50000,"minimum":0},"max_results":{"description":"Maximum results per search (1-20)","type":"integer","format":"uint","default":15,"minimum":0},"provider":{"description":"Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)","type":"string","default":"duckduckgo"},"timeout_secs":{"description":"Request timeout in seconds","type":"integer","format":"uint64","default":15,"minimum":0}}},"WebhookConfig":{"description":"Webhook channel configuration.","type":"object","properties":{"port":{"description":"Port to listen on for incoming webhooks.","type":"integer","format":"uint16","maximum":65535,"minimum":0},"secret":{"description":"Optional shared secret for webhook signature verification.","type":["string","null"]}},"required":["port"]},"WhatsAppConfig":{"description":"WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.","type":"object","properties":{"access_token":{"description":"Access token from Meta Business Suite (Cloud API mode)","type":["string","null"],"default":null},"allowed_numbers":{"description":"Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"app_secret":{"description":"App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"pair_code":{"description":"Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one","type":["string","null"],"default":null},"pair_phone":{"description":"Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used","type":["string","null"],"default":null},"phone_number_id":{"description":"Phone number ID from Meta Business API (Cloud API mode)","type":["string","null"],"default":null},"read_pool_size":{"description":"Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"session_path":{"description":"Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs","type":["string","null"],"default":null},"verify_token":{"description":"Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode","type":["string","null"],"default":null},"ws_url":{"description":"WebSocket URL override (replaces WHATSAPP_WS_URL)","type":["string","null"],"default":null}}},"WorkspaceHooks":{"description":"Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).","oneOf":[{"description":"They do not run (the default); `prx doctor` and `hooks_status` say so.","type":"string","const":"off"},{"description":"They run, in a cleared environment and a dedicated directory beside\n`config.toml`.","type":"string","const":"on"}]},"WorkspaceMcpServers":{"description":"Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).","oneOf":[{"description":"None: a workspace file may only narrow the servers defined in\n`config.toml`.","type":"string","const":"off"},{"description":"HTTP servers (still refused when they target a private address).","type":"string","const":"http_only"},{"description":"HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.","type":"string","const":"stdio"}]},"XinConfig":{"description":"Configuration for the xin autonomous task engine (`[xin]`).","type":"object","properties":{"adopt_legacy_tasks":{"description":"Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).","type":"boolean","default":false},"interval_minutes":{"description":"Tick interval in minutes (minimum 1). Default: 5.","type":"integer","format":"uint32","default":5,"minimum":0},"stale_timeout_minutes":{"description":"Minutes after which a running task is marked stale. Default: 60.","type":"integer","format":"uint32","default":60,"minimum":0}}},"AgentMessaging":{"description":"Owner-controlled inbound session messaging (enabled unless explicitly off).","type":"object","properties":{"inbound":{"type":"boolean","default":true}}}}} +{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Config","description":"Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).","type":"object","properties":{"a2a":{"description":"Agent-to-Agent compatibility configuration (`[a2a]`).","$ref":"#/$defs/A2aConfig","default":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trusted_trust_domains":[],"trust_domain":"prx.local"}},"agent":{"description":"Agent orchestration settings (`[agent]`).","$ref":"#/$defs/AgentConfig","default":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2,"messaging":{"inbound":true}}},"agents":{"description":"Delegate agent configurations for multi-agent workflows.","type":"object","additionalProperties":{"$ref":"#/$defs/DelegateAgentConfig"},"default":{}},"api_key":{"description":"API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.","type":["string","null"],"default":null},"api_url":{"description":"Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)","type":["string","null"],"default":null},"auth":{"description":"Auth profile and external credential import settings (`[auth]`).","$ref":"#/$defs/AuthConfig","default":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"}},"autonomy":{"description":"Autonomy and security policy configuration (`[autonomy]`).","$ref":"#/$defs/AutonomyConfig","default":{"forbidden_paths":[],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]}}},"browser":{"description":"Browser automation configuration (`[browser]`).","$ref":"#/$defs/BrowserConfig","default":{"allowed_domains":[],"computer_use":{"api_key":null}}},"channels_config":{"description":"Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).","$ref":"#/$defs/ChannelsConfig","default":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null}},"chat":{"description":"Interactive chat UI configuration (`[chat]`).","$ref":"#/$defs/ChatConfig","default":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2}},"compliance":{"description":"Operator-owned compliance controls (`[compliance]`).","$ref":"#/$defs/ComplianceConfig","default":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}},"composio":{"description":"Composio managed OAuth tools integration (`[composio]`).","$ref":"#/$defs/ComposioConfig","default":{"api_key":null,"entity_id":"default"}},"cost":{"description":"Cost tracking and budget enforcement configuration (`[cost]`).","$ref":"#/$defs/CostConfig","default":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{},"warn_at_percent":80}},"cron":{"description":"Cron job configuration (`[cron]`).","$ref":"#/$defs/CronConfig","default":{"max_run_history":50}},"decision_engine":{"description":"Optional advisory decision engine, disabled by default.","$ref":"#/$defs/DecisionEngineConfig","default":{"candidates":5,"enabled":false,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"latency_budget_ms":500,"max_candidates":12,"token_ratio_limit":0.3499999940395355}},"default_model":{"description":"Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.","type":["string","null"]},"default_provider":{"description":"Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.","type":["string","null"]},"default_temperature":{"description":"Default model temperature (0.0–2.0). Default: `0.7`.","type":"number","format":"double","default":0.7},"embedding_routes":{"description":"Embedding routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/EmbeddingRouteConfig"}},"gateway":{"description":"Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).","$ref":"#/$defs/GatewayConfig","default":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60}},"heartbeat":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]`).","$ref":"#/$defs/HeartbeatConfig","default":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."}},"http_request":{"description":"HTTP request tool configuration (`[http_request]`).","$ref":"#/$defs/HttpRequestConfig","default":{"max_response_size":1000000,"timeout_secs":30}},"identity":{"description":"Identity format configuration: OpenClaw or AIEOS (`[identity]`).","$ref":"#/$defs/IdentityConfig","default":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"}},"identity_bindings":{"description":"Static identity bindings loaded at startup (`[[identity_bindings]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/IdentityBindingConfig"}},"mcp":{"description":"Secrets encryption configuration (`[secrets]`).","$ref":"#/$defs/McpConfig","default":{"servers":{}}},"mcp_server":{"description":"MCP server compatibility configuration (`[mcp_server]`).","$ref":"#/$defs/McpServerRuntimeConfig","default":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true}},"media":{"description":"Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.","$ref":"#/$defs/MediaConfig","default":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"}},"memory":{"description":"Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).","$ref":"#/$defs/MemoryConfig","default":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7}},"model_routes":{"description":"Model routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/ModelRouteConfig"}},"model_settings":{"description":"Catalog model levels and explicit parameters, keyed by canonical release ID.","type":"object","additionalProperties":{"$ref":"#/$defs/ModelSettings"},"default":{}},"multimodal":{"description":"Multimodal (image) handling configuration (`[multimodal]`).","$ref":"#/$defs/MultimodalConfig","default":{"allow_remote_fetch":true,"max_image_size_mb":5,"max_images":4}},"nodes":{"description":"Remote node proxy configuration (`[nodes]`).","$ref":"#/$defs/NodesConfig","default":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":[],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}},"observability":{"description":"Observability backend configuration (`[observability]`).","$ref":"#/$defs/ObservabilityConfig","default":{"backend":"none","otel_endpoint":null,"otel_service_name":null}},"plugins":{"description":"WASM plugin runtime switch (`[plugins]`), off by default.","$ref":"#/$defs/PluginsConfig","default":{"enabled":false}},"providers":{"description":"Provider-specific runtime options (`[providers.]`).","$ref":"#/$defs/ProvidersConfig","default":{"ollama":{"num_ctx":null}}},"proxy":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).","$ref":"#/$defs/ProxyConfig","default":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]}},"query_classification":{"description":"Automatic query classification — maps user messages to model hints.","$ref":"#/$defs/QueryClassificationConfig","default":{"rules":[]}},"reliability":{"description":"Reliability settings: retries, fallback providers, backoff (`[reliability]`).","$ref":"#/$defs/ReliabilityConfig","default":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2}},"router":{"description":"Heuristic LLM router configuration (`[router]`).","$ref":"#/$defs/RouterConfig","default":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]}},"runtime":{"description":"Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.","$ref":"#/$defs/RuntimeConfig","default":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null}},"scheduler":{"description":"Scheduler configuration for periodic task execution (`[scheduler]`).","$ref":"#/$defs/SchedulerConfig","default":{"claim_lease_secs":90,"max_tasks":64}},"secrets":{"$ref":"#/$defs/SecretsConfig","default":{"encrypt":true}},"security":{"description":"Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).","$ref":"#/$defs/SecurityConfig","default":{"audit":{"log_path":"audit.log","max_size_mb":100}}},"self_system":{"description":"Self-system experimental automation controls (`[self_system]`).","$ref":"#/$defs/SelfSystemConfig","default":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24}},"sessions_spawn":{"description":"Session spawning configuration (`[sessions_spawn]`).","$ref":"#/$defs/SessionsSpawnConfig","default":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null}},"skill_rag":{"description":"Dynamic skill retrieval settings (`[skill_rag]`).","$ref":"#/$defs/SkillRagConfig","default":{"top_k":32}},"skills":{"description":"Skills loading and community repository behavior (`[skills]`).","$ref":"#/$defs/SkillsConfig","default":{"open_skills_dir":null,"openclaw_skills_dir":null}},"skills_lifecycle":{"description":"Skill lifecycle (`[skills_lifecycle]`), off by default.","$ref":"#/$defs/SkillsLifecycleConfig","default":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]}},"smart_group":{"description":"Smart group-reply pre-gate configuration (`[smart_group]`).","$ref":"#/$defs/SmartGroupConfig","default":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5}},"storage":{"description":"Persistent storage provider configuration (`[storage]`).","$ref":"#/$defs/StorageConfig","default":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"task_routing":{"description":"Task routing configuration — classifies work by intent before the main agent loop.","$ref":"#/$defs/TaskRoutingConfig","default":{"default_intent":"simple","rules":[]}},"tool_tiering":{"description":"Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).","$ref":"#/$defs/ToolTieringConfig","default":{"always_exclude":[],"always_include":[],"channel_exclude":[]}},"tunnel":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]`).","$ref":"#/$defs/TunnelConfig","default":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null}},"user_policies":{"description":"Static user policy records loaded at startup (`[[user_policies]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/UserPolicyConfig"}},"web_search":{"description":"Web search tool configuration (`[web_search]`).","$ref":"#/$defs/WebSearchConfig","default":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15}},"webhook":{"description":"Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).","$ref":"#/$defs/MemoryWebhookConfig","default":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null}},"xin":{"description":"Xin autonomous task engine configuration (`[xin]`).","$ref":"#/$defs/XinConfig","default":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}}},"$defs":{"A2aConfig":{"type":"object","properties":{"agent_id":{"description":"Stable PRX agent identifier advertised to peers.","type":"string","default":"prx-default"},"allowed_peer_issuers":{"description":"Accepted external peer issuers.","type":"array","default":[],"items":{"type":"string"}},"bind":{"description":"Advertised bind address.","type":"string","default":"127.0.0.1:16832"},"card_jwks_uri":{"description":"Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.","type":["string","null"],"default":null},"card_signing_key_path":{"description":"On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).","type":["string","null"],"default":null},"card_ttl_seconds":{"description":"Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.","type":"integer","format":"uint64","default":3600,"minimum":0},"discovery_advertised":{"description":"Whether to advertise into an external A2A registry.","type":"boolean","default":false},"handoff_nonce_ttl_seconds":{"description":"Replay window for future handoff delegation tokens.","type":"integer","format":"uint64","default":3600,"minimum":0},"messaging_enabled":{"description":"Enable the dedicated pinned mTLS messaging listener.","type":"boolean","default":false},"peers":{"type":"object","additionalProperties":{"$ref":"#/$defs/A2aPeer"},"default":{}},"spiffe_id":{"description":"Local SPIFFE-style identifier placeholder.","type":"string","default":"spiffe://prx-local/agent/prx-default"},"spiffe_strict_validation":{"description":"When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.","type":"boolean","default":false},"spiffe_trust_bundle_pem":{"description":"Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).","type":["string","null"],"default":null},"trusted_trust_domains":{"description":"Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).","type":"array","default":[],"items":{"type":"string"}},"trust_domain":{"description":"SPIFFE trust domain for new instance identities.","type":"string","default":"prx.local"}}},"A2aPeer":{"description":"Explicit pinned identity and local recipient grant.","type":"object","properties":{"spiffe_id":{"type":"string"},"fingerprints":{"type":"array","items":{"type":"string"}},"address":{"type":"string"},"owner":{"type":"string"},"sessions":{"type":"array","default":["*"],"items":{"type":"string"}},"agents":{"type":"array","default":["*"],"items":{"type":"string"}}},"required":["spiffe_id","fingerprints","address","owner"],"additionalProperties":false},"AgentCompactionConfig":{"description":"Agent context compaction configuration (`[agent.compaction]`).","type":"object","properties":{"keep_recent_messages":{"description":"Number of recent non-system messages to keep after compaction.","type":"integer","format":"uint","default":12,"minimum":0},"max_context_tokens":{"description":"Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.","type":"integer","format":"uint","default":128000,"minimum":0},"memory_flush":{"description":"Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.","type":"boolean","default":true},"mode":{"description":"Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).","$ref":"#/$defs/AgentCompactionMode","default":"switch"},"os_paging":{"description":"Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.","$ref":"#/$defs/OsPagingConfig","default":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"}},"reserve_tokens":{"description":"Tokens reserved for the next model response.","type":"integer","format":"uint","default":4096,"minimum":0}}},"AgentCompactionMode":{"description":"Compaction mode for long conversation contexts.","oneOf":[{"description":"Disable proactive compaction.","type":"string","const":"off"},{"description":"Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.","type":"string","const":"switch"},{"description":"Conservative compaction that prefers summary replacement.","type":"string","const":"safeguard"},{"description":"Aggressive truncation mode for tighter contexts.","type":"string","const":"aggressive"}]},"AgentConfig":{"description":"Agent orchestration configuration (`[agent]` section).","type":"object","properties":{"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"compact_context":{"description":"When true: bootstrap_max_chars=6000. Use for 13B or smaller models.","type":"boolean","default":false},"compaction":{"description":"Context compaction controls (`[agent.compaction]`).","$ref":"#/$defs/AgentCompactionConfig","default":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096}},"low_priority_tools":{"description":"Tool names treated as low-priority when `priority_scheduling_enabled = true`.","type":"array","default":["sessions_spawn","delegate"],"items":{"type":"string"}},"priority_scheduling_enabled":{"description":"Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.","type":"boolean","default":false},"read_only_tool_concurrency_window":{"description":"Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.","type":"integer","format":"uint","default":2,"minimum":0},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}}},"AgentLimits":{"description":"Optional admission limits for rf-started turns of a named agent.","type":"object","properties":{"max_concurrent_turns":{"type":["integer","null"],"format":"uint32","minimum":0},"max_cost_per_day_cents":{"type":["integer","null"],"format":"uint64","minimum":0}},"additionalProperties":false},"AuditConfig":{"description":"Audit logging configuration","type":"object","properties":{"log_path":{"description":"Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).","type":"string","default":"audit.log"},"max_size_mb":{"description":"Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).","type":"integer","format":"uint32","default":100,"minimum":0}}},"AuthConfig":{"description":"Authentication and external credential import configuration (`[auth]` section).","type":"object","properties":{"codex_auth_json_auto_import":{"description":"Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.","type":"boolean","default":false},"codex_auth_json_path":{"description":"Source path for Codex CLI auth.json import.","type":"string","default":"~/.codex/auth.json"}}},"AutonomyConfig":{"type":"object","properties":{"acknowledge_unrestricted_profile":{"description":"Operator acknowledgement for an intentionally unrestricted profile.\nRetained for existing configs; it no longer changes any output or policy behavior.","type":"boolean","default":false},"forbidden_paths":{"description":"Explicit path denylist. Default: empty.\n\nApplies below level `full` only; list paths when running `supervised` or `readonly`.","type":"array","default":[],"items":{"type":"string"}},"level":{"description":"Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).","$ref":"#/$defs/AutonomyLevel","default":"full"},"max_cost_per_day_cents":{"description":"Maximum cost per day in cents per policy. Default: unset (no ceiling).","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"scopes":{"description":"Scope-based tool access control: per-user/channel/chat-type allow/deny rules.","$ref":"#/$defs/ScopeConfig","default":{"assign_owners":[],"default":"allow","rules":[]}},"workspace_only":{"description":"Restrict file writes and command paths to the workspace directory. Default: `false`.\n\nApplies below level `full` only; set it when running `supervised` or `readonly`.","type":"boolean","default":false}}},"AutonomyLevel":{"description":"How much autonomy the agent has","oneOf":[{"description":"Read-only: can observe but not act","type":"string","const":"readonly"},{"description":"Supervised: acts but requires approval for risky operations","type":"string","const":"supervised"},{"description":"Full: autonomous execution within policy bounds","type":"string","const":"full"}]},"BackendSelection":{"description":"Which decision backend runs: `auto` (the factory's order) or one kind.","type":"string"},"BrowserComputerUseConfig":{"description":"Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.","type":"object","properties":{"api_key":{"description":"Optional bearer token (retained only for config secret handling).","type":["string","null"],"default":null}}},"BrowserConfig":{"description":"Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.","type":"object","properties":{"allowed_domains":{"description":"Allowed domains for `web_fetch` (exact or subdomain match).","type":"array","default":[],"items":{"type":"string"}},"computer_use":{"description":"Computer-use sidecar config (retained only for `api_key` secret handling).","$ref":"#/$defs/BrowserComputerUseConfig","default":{"api_key":null}}}},"ChannelsConfig":{"description":"Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.","type":"object","properties":{"cli":{"description":"Enable the CLI interactive channel. Default: `true`.","type":"boolean","default":true},"dingtalk":{"description":"DingTalk channel configuration.","anyOf":[{"$ref":"#/$defs/DingTalkConfig"},{"type":"null"}]},"discord":{"description":"Discord bot channel configuration.","anyOf":[{"$ref":"#/$defs/DiscordConfig"},{"type":"null"}]},"email":{"description":"Email channel configuration.","anyOf":[{"$ref":"#/$defs/EmailConfig"},{"type":"null"}]},"imessage":{"description":"iMessage channel configuration (macOS only).","anyOf":[{"$ref":"#/$defs/IMessageConfig"},{"type":"null"}]},"irc":{"description":"IRC channel configuration.","anyOf":[{"$ref":"#/$defs/IrcConfig"},{"type":"null"}]},"lark":{"description":"Lark/Feishu channel configuration.","anyOf":[{"$ref":"#/$defs/LarkConfig"},{"type":"null"}]},"linq":{"description":"Linq Partner API channel configuration.","anyOf":[{"$ref":"#/$defs/LinqConfig"},{"type":"null"}]},"mattermost":{"description":"Mattermost bot channel configuration.","anyOf":[{"$ref":"#/$defs/MattermostConfig"},{"type":"null"}]},"nextcloud_talk":{"description":"Nextcloud Talk bot channel configuration.","anyOf":[{"$ref":"#/$defs/NextcloudTalkConfig"},{"type":"null"}]},"qq":{"description":"QQ Official Bot channel configuration.","anyOf":[{"$ref":"#/$defs/QQConfig"},{"type":"null"}]},"ramflux":{"description":"Local ramflux agent-host bridge.","anyOf":[{"$ref":"#/$defs/RamfluxConfig"},{"type":"null"}],"default":null},"signal":{"description":"Signal channel configuration.","anyOf":[{"$ref":"#/$defs/SignalConfig"},{"type":"null"}]},"slack":{"description":"Slack bot channel configuration.","anyOf":[{"$ref":"#/$defs/SlackConfig"},{"type":"null"}]},"telegram":{"description":"Telegram bot channel configuration.","anyOf":[{"$ref":"#/$defs/TelegramConfig"},{"type":"null"}]},"wacli":{"description":"wacli JSON-RPC daemon channel configuration.","anyOf":[{"$ref":"#/$defs/WacliConfig"},{"type":"null"}],"default":null},"webhook":{"description":"Webhook channel configuration.","anyOf":[{"$ref":"#/$defs/WebhookConfig"},{"type":"null"}]},"whatsapp":{"description":"WhatsApp channel configuration (Cloud API or Web mode).","anyOf":[{"$ref":"#/$defs/WhatsAppConfig"},{"type":"null"}]}}},"ChatConfig":{"description":"Interactive chat configuration (`[chat]`).","type":"object","properties":{"daemon":{"description":"How this chat process reaches the daemon it borrows channels from.","$ref":"#/$defs/ChatDaemonConfig","default":{"token":"","url":""}},"max_concurrent_visible_turns":{"description":"Maximum concurrent visible provider turns in the TUI Redux driver.","type":"integer","format":"uint","default":2,"minimum":0}}},"ChatDaemonConfig":{"description":"Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.","type":"object","properties":{"token":{"description":"Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.","type":"string","default":""},"url":{"description":"Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.","type":"string","default":""}}},"CircuitBreakerConfig":{"description":"The per-backend circuit breaker.","type":"object","properties":{"cooldown_secs":{"description":"Seconds the breaker stays open (1 to 3600).","type":"integer","format":"uint32","default":60,"minimum":0},"failure_threshold":{"description":"Consecutive failures before the breaker opens (1 to 100).","type":"integer","format":"uint32","default":5,"minimum":0}}},"ClassificationRule":{"description":"A single classification rule mapping message patterns to a model hint.","type":"object","properties":{"hint":{"description":"Must match a `[[model_routes]]` hint value.","type":"string"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"max_length":{"description":"Only match if message length <= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"min_length":{"description":"Only match if message length >= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"patterns":{"description":"Case-sensitive literal matches (for \"```\", \"fn \", etc.).","type":"array","default":[],"items":{"type":"string"}},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0}},"required":["hint"]},"CloudflareTunnelConfig":{"type":"object","properties":{"token":{"description":"Cloudflare Tunnel token (from Zero Trust dashboard)","type":"string"}},"required":["token"]},"ComplianceConfig":{"type":"object","properties":{"eu_ai_act":{"$ref":"#/$defs/EuAiActComplianceConfig","default":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null}},"interaction_notice":{"$ref":"#/$defs/InteractionNoticeConfig","default":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}}},"ComposioConfig":{"description":"Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.","type":"object","properties":{"api_key":{"description":"Composio API key (stored encrypted when secrets.encrypt = true)","type":["string","null"],"default":null},"entity_id":{"description":"Default entity ID for multi-user setups","type":"string","default":"default"}}},"CostConfig":{"description":"Cost tracking and budget enforcement configuration (`[cost]` section).","type":"object","properties":{"allow_override":{"description":"Allow requests to exceed budget with --override flag (default: false)","type":"boolean","default":false},"daily_limit_usd":{"description":"Daily spending limit in USD (default: unset, no limit; 0 refuses every priced turn)","type":["number","null"],"format":"double","default":null},"monthly_limit_usd":{"description":"Monthly spending limit in USD (default: unset, no limit)","type":["number","null"],"format":"double","default":null},"prices":{"description":"Per-model pricing (USD per 1M tokens)","type":"object","additionalProperties":{"$ref":"#/$defs/ModelPricing"},"default":{}},"warn_at_percent":{"description":"Warn when spending reaches this percentage of a configured limit (default: 80)","type":"integer","format":"uint8","default":80,"maximum":255,"minimum":0}}},"CredentialRefSetting":{"description":"Which credential a decision backend uses. A reference, never a secret.","type":"string"},"CronConfig":{"description":"Cron job configuration (`[cron]` section).","type":"object","properties":{"max_run_history":{"description":"Maximum number of historical cron run records to retain. Default: `50`.","type":"integer","format":"uint32","default":50,"minimum":0}}},"CustomTunnelConfig":{"type":"object","properties":{"health_url":{"description":"Optional URL to check tunnel health","type":["string","null"]},"start_command":{"description":"Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"","type":"string"},"url_pattern":{"description":"Optional regex to extract public URL from command stdout","type":["string","null"]}},"required":["start_command"]},"DecisionBackendConfig":{"description":"The decision backend (`[decision_engine.backend]`).","type":"object","properties":{"circuit_breaker":{"description":"The circuit breaker.","$ref":"#/$defs/CircuitBreakerConfig","default":{"cooldown_secs":60,"failure_threshold":5}},"credential_ref":{"description":"The credential reference: `\"\"`, `\"none\"` or `cred-`.","$ref":"#/$defs/CredentialRefSetting","default":""},"endpoint":{"description":"The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.","type":"string","default":""},"kind":{"description":"`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).","$ref":"#/$defs/BackendSelection","default":"auto"},"max_request_bytes":{"description":"Largest request body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":65536,"minimum":0},"max_response_bytes":{"description":"Largest response body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":262144,"minimum":0},"model":{"description":"The model the endpoint serves; one exact version for a hosted\nservice.","type":"string","default":""},"pinned_snapshot":{"description":"The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.","type":"string"},"remote_enabled":{"description":"Whether decision state may leave this machine. Default `false`.","type":"boolean","default":false},"timeout_ms":{"description":"Transport timeout (10 ms up to the extra latency budget).","type":"integer","format":"uint32","default":250,"minimum":0}}},"DecisionEngineConfig":{"type":"object","properties":{"backend":{"anyOf":[{"$ref":"#/$defs/DecisionBackendConfig"},{"type":"null"}]},"candidates":{"type":"integer","format":"uint32","default":5,"minimum":0},"enabled":{"type":"boolean","default":false},"mode":{"$ref":"#/$defs/DecisionMode","default":"pre"},"observe_queue":{"type":"integer","format":"uint32","default":64,"minimum":0},"prompt_budget_tokens":{"type":"integer","format":"uint32","default":300,"minimum":0},"telemetry_cap":{"type":"integer","format":"uint32","default":1000,"minimum":0},"timeout_ms":{"type":"integer","format":"uint32","default":1500,"minimum":0},"latency_budget_ms":{"description":"The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.","type":"integer","format":"uint64","default":500,"minimum":0},"token_ratio_limit":{"description":"Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).","type":"number","format":"float","default":0.3499999940395355},"max_candidates":{"description":"The most candidates a turn considers (1 to 32).","type":"integer","format":"uint8","default":12,"maximum":255,"minimum":0}}},"DecisionMode":{"type":"string","enum":["pre","post","both"]},"DeclarationOfConformityConfig":{"type":"object","properties":{"applicable_union_law":{"type":"array","default":[],"items":{"type":"string"}},"artifact_path":{"type":["string","null"],"default":null},"artifact_version":{"type":["string","null"],"default":null},"conformity_assessment_procedure":{"type":["string","null"],"default":null},"conformity_statement":{"type":["string","null"],"default":null},"harmonised_standards":{"type":"array","default":[],"items":{"type":"string"}},"issue_date":{"type":["string","null"],"default":null},"issue_place":{"type":["string","null"],"default":null},"notified_body_certificate":{"type":["string","null"],"default":null},"notified_body_identification_number":{"type":["string","null"],"default":null},"notified_body_name":{"type":["string","null"],"default":null},"personal_data_compliance_statement":{"type":["string","null"],"default":null},"processes_personal_data":{"type":"boolean","default":false},"provider_address":{"type":["string","null"],"default":null},"provider_name":{"type":["string","null"],"default":null},"signer_function":{"type":["string","null"],"default":null},"signer_name":{"type":["string","null"],"default":null},"signer_on_behalf_of":{"type":["string","null"],"default":null},"sole_responsibility_statement":{"type":["string","null"],"default":null},"standards_not_applicable_reason":{"type":["string","null"],"default":null},"system_name":{"type":["string","null"],"default":null},"system_reference":{"type":["string","null"],"default":null},"system_type":{"type":["string","null"],"default":null}}},"DelegateAgentConfig":{"description":"Configuration for a delegate sub-agent used by the `delegate` tool.","type":"object","properties":{"agentic":{"description":"Agentic sub-agent mode (multi-turn tool-call loop). Default true; an\nexplicit `false` makes the agent answer-only with no tools.","type":"boolean","default":true},"allowed_tools":{"description":"Allowlist of tool names available to the sub-agent in agentic mode.\nEmpty or omitted means all tools, the same as `[\"*\"]`.","type":"array","default":[],"items":{"type":"string"}},"api_key":{"description":"Optional API key override","type":["string","null"],"default":null},"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"autonomy":{"description":"The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.","anyOf":[{"$ref":"#/$defs/AutonomyLevel"},{"type":"null"}]},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"enabled":{"description":"Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.","type":"boolean","default":true},"identity_dir":{"description":"Optional identity files directory relative to workspace root.","type":["string","null"],"default":null},"limits":{"$ref":"#/$defs/AgentLimits","default":{"max_concurrent_turns":null,"max_cost_per_day_cents":null}},"max_depth":{"description":"Max recursion depth for nested delegation","type":"integer","format":"uint32","default":8,"minimum":0},"memory_scope":{"description":"Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".","type":["string","null"],"default":null},"model":{"description":"Model name","type":"string"},"provider":{"description":"Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")","type":"string"},"spawn_enabled":{"description":"Whether this agent is allowed to be targeted by sessions_spawn (default: true).","type":["boolean","null"],"default":null},"system_prompt":{"description":"Optional system prompt for the sub-agent","type":["string","null"],"default":null},"temperature":{"description":"Temperature override","type":["number","null"],"format":"double","default":null},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}},"required":["provider","model"]},"DingTalkConfig":{"description":"DingTalk configuration for Stream Mode messaging","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"client_id":{"description":"Client ID (AppKey) from DingTalk developer console","type":"string"},"client_secret":{"description":"Client Secret (AppSecret) from DingTalk developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["client_id","client_secret"]},"DiscordConfig":{"description":"Discord bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Discord user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Discord bot token (from Discord Developer Portal).","type":"string"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"guild_id":{"description":"Optional guild (server) ID to restrict the bot to a single guild.","type":["string","null"]},"listen_to_bots":{"description":"When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.","type":"boolean","default":false}},"required":["bot_token"]},"DmPolicy":{"description":"Policy for direct-message handling.","oneOf":[{"description":"Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).","type":"string","const":"pairing"},{"description":"Accept only senders listed in `allowed_from`.","type":"string","const":"allowlist"},{"description":"Accept any direct sender.","type":"string","const":"open"},{"description":"Ignore direct messages.","type":"string","const":"disabled"}]},"DockerRuntimeConfig":{"description":"Docker runtime configuration (`[runtime.docker]` section).","type":"object","properties":{"allowed_workspace_roots":{"description":"Optional workspace root allowlist for Docker mount validation.","type":"array","default":[],"items":{"type":"string"}},"cpu_limit":{"description":"Optional CPU limit (`None` = no explicit limit).","type":["number","null"],"format":"double","default":1.0},"image":{"description":"Runtime image used to execute shell commands.","type":"string","default":"alpine:3.20"},"memory_limit_mb":{"description":"Optional memory limit in MB (`None` = no explicit limit).","type":["integer","null"],"format":"uint64","default":512,"minimum":0},"mount_workspace":{"description":"Mount configured workspace into `/workspace`.","type":"boolean","default":true},"network":{"description":"Docker network mode (`none`, `bridge`, etc.).","type":"string","default":"none"},"read_only_rootfs":{"description":"Mount root filesystem as read-only.","type":"boolean","default":true}}},"EmailConfig":{"description":"Email channel configuration","type":"object","properties":{"allowed_senders":{"description":"Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)","type":"array","default":[],"items":{"type":"string"}},"from_address":{"description":"From address for outgoing emails","type":"string"},"idle_timeout_secs":{"description":"IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes","type":"integer","format":"uint64","default":1740,"minimum":0},"imap_folder":{"description":"IMAP folder to poll (default: INBOX)","type":"string","default":"INBOX"},"imap_host":{"description":"IMAP server hostname","type":"string"},"imap_port":{"description":"IMAP server port (default: 993 for TLS)","type":"integer","format":"uint16","default":993,"maximum":65535,"minimum":0},"password":{"description":"Email password for authentication","type":"string"},"smtp_host":{"description":"SMTP server hostname","type":"string"},"smtp_port":{"description":"SMTP server port (default: 465 for TLS)","type":"integer","format":"uint16","default":465,"maximum":65535,"minimum":0},"smtp_tls":{"description":"Use TLS for SMTP (default: true)","type":"boolean","default":true},"username":{"description":"Email username for authentication","type":"string"}},"required":["imap_host","smtp_host","username","password","from_address"]},"EmbeddingRouteConfig":{"description":"Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"dimensions":{"description":"Optional embedding dimension override for this route","type":["integer","null"],"format":"uint","default":null,"minimum":0},"hint":{"description":"Route hint name (e.g. \"semantic\", \"archive\", \"faq\")","type":"string"},"model":{"description":"Embedding model to use with that provider","type":"string"},"provider":{"description":"Embedding provider (`none`, `openai`, or `custom:`)","type":"string"}},"required":["hint","provider","model"]},"EuAiActClassificationConfig":{"type":"object","properties":{"assessed_at":{"type":["string","null"],"default":null},"owner":{"type":["string","null"],"default":null},"status":{"$ref":"#/$defs/EuAiActRiskClassification","default":"unclassified"}}},"EuAiActComplianceConfig":{"type":"object","properties":{"classification":{"$ref":"#/$defs/EuAiActClassificationConfig","default":{"assessed_at":null,"owner":null,"status":"unclassified"}},"declaration":{"$ref":"#/$defs/DeclarationOfConformityConfig","default":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null}},"incident_store_path":{"type":["string","null"],"default":null}}},"EuAiActRiskClassification":{"type":"string","enum":["unclassified","high_risk","not_high_risk"]},"FitnessConfig":{"description":"Calendar schedule, evidence thresholds, and retention for fitness v2.","type":"object","properties":{"auto_run":{"description":"Run the daily fitness worker in daemon mode.","type":"boolean","default":true},"max_backfill_days":{"description":"Maximum number of closed days recovered after downtime.","type":"integer","format":"uint32","default":7,"minimum":0},"min_coverage":{"description":"Minimum available metric weight required to publish a final score.","type":"number","format":"double","default":0.6},"min_samples":{"description":"Minimum samples required before an evidence-derived subscore is usable.","type":"integer","format":"uint","default":5,"minimum":0},"retention_days":{"description":"Number of daily JSON reports retained on disk.","type":"integer","format":"uint32","default":180,"minimum":0},"run_at":{"description":"Local wall-clock time (`HH:MM`) at which the previous day is scored.","type":"string","default":"00:10"},"timezone":{"description":"IANA timezone used to define closed calendar days.","type":"string","default":"UTC"}}},"GatewayConfig":{"description":"Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.","type":"object","properties":{"allow_public_bind":{"description":"Allow binding to non-localhost without a tunnel (default: false)","type":"boolean","default":false},"api_rate_limit_per_minute":{"description":"Max `/api/*` requests per minute per authenticated token.","type":"integer","format":"uint32","default":60,"minimum":0},"channel_webhook_dedup_ttl_secs":{"description":"How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.","type":"integer","format":"uint64","default":86400,"minimum":0},"host":{"description":"Gateway host (default: 127.0.0.1)","type":"string","default":"127.0.0.1"},"idempotency_max_keys":{"description":"Maximum distinct idempotency keys retained in memory.","type":"integer","format":"uint","default":10000,"minimum":0},"idempotency_ttl_secs":{"description":"TTL for webhook idempotency keys.","type":"integer","format":"uint64","default":300,"minimum":0},"pair_rate_limit_per_minute":{"description":"Max `/pair` requests per minute per client key.","type":"integer","format":"uint32","default":10,"minimum":0},"paired_tokens":{"description":"Paired bearer tokens (managed automatically, not user-edited)","type":"array","default":[],"items":{"type":"string"}},"port":{"description":"Gateway port (default: 16830)","type":"integer","format":"uint16","default":16830,"maximum":65535,"minimum":0},"rate_limit_max_keys":{"description":"Maximum distinct client keys tracked by gateway rate limiter maps.","type":"integer","format":"uint","default":10000,"minimum":0},"require_pairing":{"description":"Require pairing before accepting requests (default: true)","type":"boolean","default":true},"targeted_agents":{"description":"Switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). Default true. While false, any\notherwise-valid named target answers 409 `agent_disabled` and never\nruns as Main.","type":"boolean","default":true},"trust_forwarded_headers":{"description":"Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.","type":"boolean","default":false},"webhook_rate_limit_per_minute":{"description":"Max `/webhook` requests per minute per client key.","type":"integer","format":"uint32","default":60,"minimum":0}}},"GroupPolicy":{"description":"Policy for group-message handling.","oneOf":[{"description":"Accept only groups listed in `group_allow_from`.","type":"string","const":"allowlist"},{"description":"Accept any group.","type":"string","const":"open"},{"description":"Ignore group messages.","type":"string","const":"disabled"}]},"GroupReplyMode":{"description":"How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.","oneOf":[{"description":"Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).","type":"string","const":"off"},{"description":"Reply only when the bot is @-mentioned (legacy `mention_only = true`).","type":"string","const":"mention-only"},{"description":"Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).","type":"string","const":"smart"}]},"HeartbeatConfig":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]` section).","type":"object","properties":{"active_hours":{"description":"Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.","type":"array","default":[8,23],"items":{"type":"integer","format":"uint8","maximum":255,"minimum":0}},"interval_minutes":{"description":"Interval in minutes between heartbeat pings. Default: `30`.","type":"integer","format":"uint32","default":30,"minimum":0},"prompt":{"description":"Prompt used by heartbeat worker when dispatching tasks.","type":"string","default":"Check HEARTBEAT.md and follow instructions."}}},"HttpRequestConfig":{"description":"HTTP request tool configuration (`[http_request]` section).","type":"object","properties":{"max_response_size":{"description":"Maximum response size in bytes (default: 1MB)","type":"integer","format":"uint","default":1000000,"minimum":0},"timeout_secs":{"description":"Request timeout in seconds (default: 30)","type":"integer","format":"uint64","default":30,"minimum":0}}},"IMessageConfig":{"description":"iMessage channel configuration (macOS only).","type":"object","properties":{"allowed_contacts":{"description":"Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.","type":"array","items":{"type":"string"}},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["allowed_contacts"]},"IdentityBindingConfig":{"description":"Startup identity binding entry (`[[identity_bindings]]`).","type":"object","properties":{"channel":{"type":"string"},"channel_account":{"type":"string"},"display_name":{"type":["string","null"],"default":null},"user_id":{"type":"string"}},"required":["user_id","channel","channel_account"]},"IdentityConfig":{"description":"Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.","type":"object","properties":{"aieos_inline":{"description":"Inline AIEOS JSON (alternative to file path)","type":["string","null"],"default":null},"aieos_path":{"description":"Path to AIEOS JSON file (relative to workspace)","type":["string","null"],"default":null},"format":{"description":"Identity format: \"openclaw\" (default) or \"aieos\"","type":"string","default":"openclaw"}}},"InteractionNoticeApplicability":{"type":"string","enum":["required","not_applicable"]},"InteractionNoticeConfig":{"type":"object","properties":{"applicability":{"$ref":"#/$defs/InteractionNoticeApplicability","default":"required"},"exception_owner":{"type":["string","null"],"default":null},"exception_reviewed_at":{"type":["string","null"],"default":null},"text":{"type":"string","default":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers."},"version":{"type":"string","default":"1"}}},"IrcConfig":{"description":"IRC channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed nicknames (case-insensitive) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"channels":{"description":"Channels to join on connect","type":"array","default":[],"items":{"type":"string"}},"mention_only":{"description":"When true, only process channel/group messages that mention the bot.","type":"boolean","default":false},"nickname":{"description":"Bot nickname","type":"string"},"nickserv_password":{"description":"NickServ IDENTIFY password","type":["string","null"]},"port":{"description":"IRC server port (default: 6697 for TLS)","type":"integer","format":"uint16","default":6697,"maximum":65535,"minimum":0},"sasl_password":{"description":"SASL PLAIN password (IRCv3)","type":["string","null"]},"server":{"description":"IRC server hostname","type":"string"},"server_password":{"description":"Server password (for bouncers like ZNC)","type":["string","null"]},"username":{"description":"Username (defaults to nickname if not set)","type":["string","null"]},"verify_tls":{"description":"Verify TLS certificate (default: true)","type":["boolean","null"]}},"required":["server","nickname"]},"LarkConfig":{"description":"Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from Lark/Feishu developer console","type":"string"},"app_secret":{"description":"App Secret from Lark/Feishu developer console","type":"string"},"encrypt_key":{"description":"Encrypt key for webhook message decryption (optional)","type":["string","null"],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"port":{"description":"HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"receive_mode":{"description":"Event receive mode: \"websocket\" (default) or \"webhook\"","$ref":"#/$defs/LarkReceiveMode","default":"websocket"},"use_feishu":{"description":"Whether to use the Feishu (Chinese) endpoint instead of Lark (International)","type":"boolean","default":false},"verification_token":{"description":"Verification token for webhook validation (optional)","type":["string","null"],"default":null}},"required":["app_id","app_secret"]},"LarkReceiveMode":{"description":"How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.","type":"string","enum":["websocket","webhook"]},"LinqConfig":{"type":"object","properties":{"allowed_senders":{"description":"Allowed sender handles (phone numbers) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"api_token":{"description":"Linq Partner API token (Bearer auth)","type":"string"},"from_phone":{"description":"Phone number to send from (E.164 format)","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"signing_secret":{"description":"Webhook signing secret for signature verification","type":["string","null"],"default":null}},"required":["api_token","from_phone"]},"MattermostConfig":{"description":"Mattermost bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Mattermost user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Mattermost bot access token.","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.","type":["boolean","null"],"default":null},"thread_replies":{"description":"When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.","type":["boolean","null"],"default":null},"url":{"description":"Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).","type":"string"}},"required":["url","bot_token"]},"McpConfig":{"type":"object","properties":{"servers":{"description":"Named MCP server definitions","type":"object","additionalProperties":{"$ref":"#/$defs/McpServerConfig"},"default":{}},"workspace_servers":{"description":"Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.","$ref":"#/$defs/WorkspaceMcpServers"}}},"McpServerConfig":{"type":"object","properties":{"allow_tools":{"description":"Optional allow-list of exposed tools (empty = all)","type":"array","default":[],"items":{"type":"string"}},"args":{"description":"Command args for stdio mode","type":"array","default":[],"items":{"type":"string"}},"command":{"description":"Command for stdio mode","type":["string","null"],"default":null},"deny_tools":{"description":"Optional deny-list of exposed tools","type":"array","default":[],"items":{"type":"string"}},"env":{"description":"Environment variables for stdio mode","type":"object","additionalProperties":{"type":"string"},"default":{}},"request_timeout_ms":{"description":"Request timeout in milliseconds","type":"integer","format":"uint64","default":30000,"minimum":0},"startup_timeout_ms":{"description":"Startup timeout in milliseconds","type":"integer","format":"uint64","default":10000,"minimum":0},"tool_name_prefix":{"description":"Prefix used in tool naming and routing","type":"string","default":"mcp"},"transport":{"description":"Transport type: stdio or http","$ref":"#/$defs/McpTransport","default":"stdio"},"url":{"description":"URL for HTTP mode (streamable HTTP endpoint)","type":["string","null"],"default":null},"working_dir":{"description":"Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).","type":["string","null"]}}},"McpServerRuntimeConfig":{"type":"object","properties":{"allowed_origins":{"description":"Allowed browser origins for future streamable HTTP clients.","type":"array","default":["claude.ai","openai.com","localhost"],"items":{"type":"string"}},"bind":{"description":"Advertised bind address. The gateway may still be started with a CLI port override.","type":"string","default":"127.0.0.1:16831"},"exposed_tools":{"description":"Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.","type":"array","default":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"items":{"type":"string"}},"jwt_algorithms":{"description":"Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.","type":"array","default":["RS256"],"items":{"type":"string"}},"jwt_audience":{"description":"Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.","type":["string","null"],"default":null},"jwt_issuer":{"description":"Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.","type":["string","null"],"default":null},"jwt_jwks":{"description":"Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.","type":["string","null"],"default":null},"jwt_jwks_cache_ttl_secs":{"description":"Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.","type":"integer","format":"uint64","default":300,"minimum":0},"jwt_jwks_uri":{"description":"Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.","type":["string","null"],"default":null},"jwt_public_key_pem":{"description":"PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.","type":["string","null"],"default":null},"rate_limit_rps":{"description":"Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.","type":"integer","format":"uint32","default":10,"minimum":0},"require_auth":{"description":"Require an authenticated external identity for mutating calls.","type":"boolean","default":true}}},"McpTransport":{"type":"string","enum":["stdio","http"]},"MediaConfig":{"description":"Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.","type":"object","properties":{"audio_model":{"description":"Audio model name (Ollama model or OpenAI model). Default: \"whisper\".","type":"string","default":"whisper"},"audio_ollama_url":{"description":"Ollama base URL for audio transcription. Default: \"http://localhost:11434\".","type":"string","default":"http://localhost:11434"},"audio_provider":{"description":"Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".","type":"string","default":"none"},"max_audio_size_mb":{"description":"Maximum audio attachment size in MiB. Default: 20.","type":"integer","format":"uint","default":20,"minimum":0},"max_video_size_mb":{"description":"Maximum video attachment size in MiB. Default: 50.","type":"integer","format":"uint","default":50,"minimum":0},"video_max_frames":{"description":"Maximum video frames to extract per video. Default: 4.","type":"integer","format":"uint","default":4,"minimum":0},"video_provider":{"description":"Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".","type":"string","default":"none"}}},"MemoryConfig":{"description":"Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.","type":"object","properties":{"acl_enabled":{"description":"Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.","type":"boolean","default":false},"archive_after_days":{"description":"Archive daily/session files older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"auto_hydrate":{"description":"Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing","type":"boolean","default":true},"auto_save":{"description":"Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.","type":"boolean","default":true},"backend":{"description":"\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).","type":"string","default":"sqlite"},"conversation_retention_days":{"description":"For sqlite backend: prune conversation rows older than this many days","type":"integer","format":"uint32","default":3,"minimum":0},"daily_retention_days":{"description":"For sqlite backend: prune daily rows older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"embedding_cache_size":{"description":"Max embedding cache entries before LRU eviction","type":"integer","format":"uint","default":10000,"minimum":0},"embedding_dimensions":{"description":"Embedding vector dimensions","type":"integer","format":"uint","default":384,"minimum":0},"embedding_model":{"description":"Embedding model name (e.g. \"text-embedding-3-small\")","type":"string","default":"prx-local-hash-v1"},"embedding_provider":{"description":"Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"","type":"string","default":"local"},"events":{"description":"Raw/quasi-raw message event recording controls (`[memory.events]`).","$ref":"#/$defs/MemoryEventsConfig","default":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true}},"keyword_weight":{"description":"Weight for keyword BM25 in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.3},"legacy_conversation_turns_visible":{"description":"Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.","type":"boolean","default":true},"lucid_budget":{"description":"Token budget for lucid (replaces OPENPRX_LUCID_BUDGET)","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"lucid_cmd":{"description":"Path to lucid binary (replaces OPENPRX_LUCID_CMD)","type":["string","null"],"default":null},"lucid_failure_cooldown_ms":{"description":"Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)","type":"integer","format":"uint64","default":60000,"minimum":0},"lucid_local_hit_threshold":{"description":"Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)","type":"integer","format":"uint","default":3,"minimum":0},"lucid_recall_timeout_ms":{"description":"Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)","type":"integer","format":"uint64","default":5000,"minimum":0},"lucid_store_timeout_ms":{"description":"Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)","type":"integer","format":"uint64","default":3000,"minimum":0},"min_relevance_score":{"description":"Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4","type":"number","format":"double","default":0.4},"purge_after_days":{"description":"Purge archived files older than this many days","type":"integer","format":"uint32","default":30,"minimum":0},"semantic":{"description":"Semantic memory promotion controls (`[memory.semantic]`).","$ref":"#/$defs/MemorySemanticConfig","default":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30}},"sqlite_open_timeout_secs":{"description":"For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"sqlite_read_pool_size":{"description":"For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"vector_candidate_cap":{"description":"How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.","type":"integer","format":"uint","default":2000,"minimum":0},"vector_weight":{"description":"Weight for vector similarity in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.7}}},"MemoryEventsConfig":{"description":"Raw message event recording configuration (`[memory.events]`).","type":"object","properties":{"record_assistant_messages":{"description":"Record assistant replies.","type":"boolean","default":true},"record_tool_events":{"description":"Record tool/event payloads by default.","type":"boolean","default":false},"record_user_messages":{"description":"Record inbound/user messages.","type":"boolean","default":true}}},"MemorySemanticConfig":{"description":"Semantic memory promotion configuration (`[memory.semantic]`).","type":"object","properties":{"auto_promote_assistant_messages":{"description":"Auto-promote eligible assistant messages. Disabled by default to reduce noise.","type":"boolean","default":false},"auto_promote_user_messages":{"description":"Auto-promote eligible user messages into long-term semantic memories.","type":"boolean","default":true},"min_chars":{"description":"Minimum content length for semantic auto-promotion.","type":"integer","format":"uint","default":30,"minimum":0}}},"MemoryWebhookConfig":{"type":"object","properties":{"bind":{"description":"Socket address for the receiver (e.g. \"0.0.0.0:16899\").","type":"string","default":"0.0.0.0:16899"},"signing_secret":{"description":"Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.","type":["string","null"],"default":null},"token":{"description":"Required bearer token for incoming webhook events.","type":["string","null"],"default":null}}},"ModelOperationSetting":{"description":"The operations a `[[providers.models]]` entry may list.","type":"string","enum":["chat","embedding","decision_endpoint","rerank","image_generation","audio_generation","video_generation"]},"ModelPricing":{"description":"Per-model pricing entry (USD per 1M tokens).","type":"object","properties":{"cache_read":{"description":"Cache read input price per 1M tokens.","type":"number","format":"double","default":0.0},"cache_write":{"description":"Cache write/creation input price per 1M tokens.","type":"number","format":"double","default":0.0},"input":{"description":"Input price per 1M tokens","type":"number","format":"double","default":0.0},"output":{"description":"Output price per 1M tokens","type":"number","format":"double","default":0.0}}},"ModelRouteConfig":{"description":"Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"hint":{"description":"Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")","type":"string"},"level":{"type":["string","null"]},"model":{"description":"Model to use with that provider","type":"string"},"provider":{"description":"Provider to route to (must match a known provider name)","type":"string"},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true,"required":["hint","provider","model"]},"ModelSettings":{"description":"A model level plus explicit parameter overrides in `[model_settings.\"\"]`.","type":"object","properties":{"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"level":{"type":["string","null"]},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true},"MultimodalConfig":{"description":"Multimodal (image) handling configuration (`[multimodal]` section).","type":"object","properties":{"allow_remote_fetch":{"description":"Allow fetching remote image URLs (http/https). Enabled by default.","type":"boolean","default":true},"max_image_size_mb":{"description":"Maximum image payload size in MiB before base64 encoding.","type":"integer","format":"uint","default":5,"minimum":0},"max_images":{"description":"Maximum number of image attachments accepted per request.","type":"integer","format":"uint","default":4,"minimum":0}}},"NextcloudTalkConfig":{"description":"Nextcloud Talk bot configuration (webhook receive + OCS send API).","type":"object","properties":{"allowed_users":{"description":"Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Bot app token used for OCS API bearer auth.","type":"string"},"base_url":{"description":"Nextcloud base URL (e.g. \"https://cloud.example.com\").","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"webhook_secret":{"description":"Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).","type":["string","null"],"default":null}},"required":["base_url","app_token"]},"NgrokTunnelConfig":{"type":"object","properties":{"auth_token":{"description":"ngrok auth token","type":"string"},"domain":{"description":"Optional custom domain","type":["string","null"]}},"required":["auth_token"]},"NodeServerConfig":{"description":"Node daemon runtime config used by `prx-node`.","type":"object","properties":{"allowed_commands":{"description":"Command allowlist matched on first token. Default: empty, which allows any\ncommand from an authenticated caller; `[\"*\"]` means the same.","type":"array","default":[],"items":{"type":"string"}},"bearer_token":{"description":"Required bearer token for /rpc.","type":"string","default":""},"blocked_commands":{"description":"Command denylist matched on first token. Always enforced.","type":"array","default":[],"items":{"type":"string"}},"exec_timeout_ms":{"description":"Default command timeout in milliseconds.","type":"integer","format":"uint64","default":15000,"minimum":0},"hmac_secret":{"description":"Optional HMAC signing secret.","type":["string","null"],"default":null},"listen_addr":{"description":"Listen address for node daemon.","type":"string","default":"127.0.0.1:8787"},"max_concurrent_tasks":{"description":"Maximum number of concurrent async command tasks.","type":"integer","format":"uint","default":8,"minimum":0},"max_output_bytes":{"description":"Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.","type":"integer","format":"uint","default":1048576,"minimum":0},"sandbox_root":{"description":"Sandbox root directory for read/write/cwd constraints.","type":"string","default":"."},"task_result_ttl_ms":{"description":"TTL for completed task results in milliseconds.","type":"integer","format":"uint64","default":3600000,"minimum":0},"tls_cert":{"description":"TLS certificate path (PEM).","type":["string","null"],"default":null},"tls_key":{"description":"TLS private key path (PEM).","type":["string","null"],"default":null},"tls_required":{"description":"Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.","type":"boolean","default":true}}},"NodesConfig":{"description":"Remote node proxy configuration for core-side RPC calls and node daemon defaults.","type":"object","properties":{"nodes":{"description":"Configured remote nodes.","type":"array","default":[],"items":{"$ref":"#/$defs/RemoteNodeConfig"}},"request_timeout_ms":{"description":"Default request timeout for node RPC calls.","type":"integer","format":"uint64","default":15000,"minimum":0},"retry_max":{"description":"Default max retries for node RPC calls.","type":"integer","format":"uint8","default":2,"maximum":255,"minimum":0},"server":{"description":"Embedded node server defaults used by `prx-node`.","$ref":"#/$defs/NodeServerConfig","default":{"allowed_commands":[],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}}},"ObservabilityConfig":{"description":"Observability backend configuration (`[observability]` section).","type":"object","properties":{"backend":{"description":"\"none\" | \"log\" | \"prometheus\" | \"otel\"","type":"string","default":"none"},"otel_endpoint":{"description":"OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".","type":["string","null"],"default":null},"otel_service_name":{"description":"Service name reported to the OTel collector. Defaults to \"prx\".","type":["string","null"],"default":null}}},"OllamaProviderConfig":{"description":"Ollama-specific request options (`[providers.ollama]`).","type":"object","properties":{"num_ctx":{"description":"Explicit context window sent as Ollama `options.num_ctx`.","type":["integer","null"],"format":"uint","default":null,"minimum":0}}},"OsPagingConfig":{"description":"Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.","type":"object","properties":{"eviction_threshold":{"description":"Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.","type":"number","format":"double","default":0.7},"keep_recent_messages":{"description":"Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).","type":"integer","format":"uint","default":12,"minimum":0},"max_recalled_pages":{"description":"Maximum number of evicted pages (document chunks) recalled per turn.","type":"integer","format":"uint","default":10,"minimum":0},"proactive_retrieval":{"description":"Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.","type":"boolean","default":true},"retrieval_injection_role":{"description":"Role under which recalled pages are injected.","$ref":"#/$defs/RetrievalInjectionRole","default":"system"}}},"PluginsConfig":{"description":"WASM plugin runtime configuration.","type":"object","properties":{"enabled":{"description":"Load WASM plugins from `/plugins`. Default: `false`.","type":"boolean","default":false}},"additionalProperties":false},"ProviderModelConfig":{"description":"One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.","type":"object","properties":{"context_window":{"description":"The model's context window in tokens.","type":["integer","null"],"format":"uint32","minimum":0},"model":{"description":"The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.","type":["string","null"]},"native_tools":{"description":"Whether the model accepts native tool calls.","type":["boolean","null"]},"operations":{"description":"The complete list of operations the model executes; every operation not\nlisted is unsupported.","type":["array","null"],"items":{"$ref":"#/$defs/ModelOperationSetting"}},"provider":{"description":"The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.","type":"string"},"streaming":{"description":"Whether the model streams responses.","type":["boolean","null"]},"structured_output":{"description":"Whether the model honours a JSON-schema response format.","type":["boolean","null"]},"tool_call_dialect":{"description":"The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema_dialect":{"description":"The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]},"vision_input":{"description":"Whether the model accepts image input.","type":["boolean","null"]}},"required":["provider"]},"ProviderToolDialectConfig":{"description":"One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.","type":"object","properties":{"model":{"description":"The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.","type":["string","null"]},"provider":{"description":"The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.","type":"string"},"tool_call":{"description":"The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema":{"description":"The tool-schema dialect the endpoint accepts.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]}},"required":["provider"]},"ProvidersConfig":{"description":"Provider-specific runtime configuration (`[providers]`).","type":"object","properties":{"models":{"description":"Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.","type":"array","items":{"$ref":"#/$defs/ProviderModelConfig"}},"ollama":{"description":"Ollama-specific request options (`[providers.ollama]`).","$ref":"#/$defs/OllamaProviderConfig","default":{"num_ctx":null}},"tool_dialects":{"description":"Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).","type":"array","items":{"$ref":"#/$defs/ProviderToolDialectConfig"}}}},"ProxyConfig":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).","type":"object","properties":{"all_proxy":{"description":"Fallback proxy URL for all schemes.","type":["string","null"],"default":null},"http_proxy":{"description":"Proxy URL for HTTP requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"https_proxy":{"description":"Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"no_proxy":{"description":"No-proxy bypass list. Same format as NO_PROXY.","type":"array","default":[],"items":{"type":"string"}},"scope":{"description":"Proxy application scope.","$ref":"#/$defs/ProxyScope","default":"prx"},"services":{"description":"Service selectors used when scope = \"services\".","type":"array","default":[],"items":{"type":"string"}}}},"ProxyScope":{"description":"Proxy application scope — determines which outbound traffic uses the proxy.","oneOf":[{"description":"Use system environment proxy variables only.","type":"string","const":"environment"},{"description":"Apply proxy to all OpenPRX-managed HTTP traffic (default).","type":"string","const":"prx"},{"description":"Apply proxy only to explicitly listed service selectors.","type":"string","const":"services"}]},"QQConfig":{"description":"QQ Official Bot configuration (Tencent QQ Bot SDK)","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs. Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from QQ Bot developer console","type":"string"},"app_secret":{"description":"App Secret from QQ Bot developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["app_id","app_secret"]},"QueryClassificationConfig":{"description":"Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.","type":"object","properties":{"rules":{"description":"Classification rules evaluated in priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/ClassificationRule"}}}},"RamfluxAccountConfig":{"description":"Persona for one ramflux AI account. Missing fields fall back to the global agent.","type":"object","properties":{"cross_conversation_retrieval":{"description":"Cross-conversation memory retrieval. Off unless the owner sets it.","type":"boolean","default":false},"model":{"type":["string","null"],"default":null},"provider":{"type":["string","null"],"default":null},"scope_profile":{"type":["string","null"],"default":null},"system_prompt_file":{"description":"Path to a system-prompt file. Relative paths are resolved from the workspace.","type":["string","null"],"default":null}},"additionalProperties":false},"RamfluxAttachmentFetch":{"description":"Per-turn caps for `attachment.fetch`.","type":"object","properties":{"max_bytes":{"type":"integer","format":"uint64","default":5242880,"minimum":0},"max_per_turn":{"type":"integer","format":"uint8","default":4,"maximum":255,"minimum":0}},"additionalProperties":false},"RamfluxAuthorizationMode":{"description":"How prx combines its own setting with `bridge.hello.authorization`.","oneOf":[{"description":"Use the agent-host value. Until hello arrives, the effective mode is supervised.","type":"string","const":"follow_rf"},{"description":"Always supervised, even when the agent-host declares full.","type":"string","const":"supervised"},{"description":"Full only when the agent-host also declares full. Config alone never yields full.","type":"string","const":"full"}]},"RamfluxConfig":{"description":"Local ramflux agent-host bridge (`[channels_config.ramflux]`).","type":"object","properties":{"accounts":{"type":"object","additionalProperties":{"$ref":"#/$defs/RamfluxAccountConfig"},"default":{}},"allowed_block_types":{"type":"array","default":["Text","Markdown","Heading","KeyValue","Metric","List","TableFallback","Form","Input","Select","Progress","LogStream","Warning","Error","Success","Approval","ActionGroup","FilePreview","Fallback"],"items":{"type":"string"}},"attachment_fetch":{"$ref":"#/$defs/RamfluxAttachmentFetch","default":{"max_bytes":5242880,"max_per_turn":4}},"authorization_mode":{"$ref":"#/$defs/RamfluxAuthorizationMode","default":"follow_rf"},"encrypt_at_rest":{"type":"boolean","default":true},"max_in_flight_per_conversation":{"type":"integer","format":"uint8","default":1,"maximum":255,"minimum":0},"on_new_message":{"$ref":"#/$defs/RamfluxOnNewMessage","default":"queue"},"socket_path":{"description":"Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.","type":["string","null"],"default":null},"surface_limits":{"$ref":"#/$defs/RamfluxSurfaceLimits","default":{"max_actions":16,"max_blocks":32,"max_bytes":65536}},"turn_wall_clock_secs":{"description":"Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.","type":"integer","format":"uint64","default":120,"minimum":0}},"additionalProperties":false},"RamfluxOnNewMessage":{"description":"What to do with a new inbound message while a turn for that conversation is running.","type":"string","enum":["queue","interrupt"]},"RamfluxSurfaceLimits":{"description":"Limits for `reply.surface` blocks and actions.","type":"object","properties":{"max_actions":{"type":"integer","format":"uint32","default":16,"minimum":0},"max_blocks":{"type":"integer","format":"uint32","default":32,"minimum":0},"max_bytes":{"type":"integer","format":"uint32","default":65536,"minimum":0}},"additionalProperties":false},"ReliabilityCircuitBreakerConfig":{"description":"Process-local provider circuit policy (`[reliability.circuit_breaker]`).","type":"object","properties":{"enabled":{"description":"Enable protection for factory-built provider chains.","type":"boolean","default":true},"failure_threshold":{"description":"Consecutive transient failures that open a circuit (at least 1).","type":"integer","format":"uint32","default":5,"minimum":0},"max_open_secs":{"description":"Maximum doubled window, between open_secs and 3600 seconds.","type":"integer","format":"uint64","default":300,"minimum":0},"open_secs":{"description":"Initial open window in seconds (at least 1).","type":"integer","format":"uint64","default":30,"minimum":0}}},"ReliabilityConfig":{"description":"Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.","type":"object","properties":{"acknowledge_single_provider_risk":{"description":"Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.","type":"boolean","default":false},"api_keys":{"description":"Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.","type":"array","default":[],"items":{"type":"string"}},"channel_initial_backoff_secs":{"description":"Initial backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":2,"minimum":0},"channel_max_backoff_secs":{"description":"Max backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":60,"minimum":0},"circuit_breaker":{"description":"Per-provider consecutive failure protection.","$ref":"#/$defs/ReliabilityCircuitBreakerConfig","default":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30}},"fallback_providers":{"description":"Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).","type":"array","default":[],"items":{"type":"string"}},"model_fallbacks":{"description":"Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`","type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"default":{}},"provider_backoff_ms":{"description":"Base backoff (ms) for provider retry delay.","type":"integer","format":"uint64","default":500,"minimum":0},"provider_retries":{"description":"Retries per provider before failing over.","type":"integer","format":"uint32","default":2,"minimum":0},"scheduler_poll_secs":{"description":"Scheduler polling cadence in seconds.","type":"integer","format":"uint64","default":15,"minimum":0},"scheduler_retries":{"description":"Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.","type":"integer","format":"uint32","default":2,"minimum":0}}},"RemoteNodeConfig":{"description":"A remote node target for core-side node proxy calls.","type":"object","properties":{"bearer_token":{"description":"Bearer token for node RPC authentication.","type":"string"},"endpoint":{"description":"Base endpoint (e.g. \"http://127.0.0.1:8787\").","type":"string"},"hmac_secret":{"description":"Optional request signing key (HMAC-SHA256).","type":["string","null"],"default":null},"id":{"description":"Stable node ID used by the nodes tool.","type":"string"},"retry_max":{"description":"Optional per-node retry override.","type":["integer","null"],"format":"uint8","default":null,"maximum":255,"minimum":0},"timeout_ms":{"description":"Optional per-node timeout override.","type":["integer","null"],"format":"uint64","default":null,"minimum":0}},"required":["id","endpoint","bearer_token"]},"RetrievalInjectionRole":{"description":"Where recalled context pages are injected back into the request.","oneOf":[{"description":"Inject recalled pages as a leading `system` message (not user-visible).","type":"string","const":"system"},{"description":"Inject recalled pages as a leading `user` message.","type":"string","const":"user"}]},"RouterConfig":{"description":"Heuristic LLM router configuration (`[router]` section).","type":"object","properties":{"alpha":{"description":"Similarity score weight. Phase 1 keeps this at `0.0`.","type":"number","format":"float","default":0.0},"beta":{"description":"Capability score weight.","type":"number","format":"float","default":0.5},"delta":{"description":"Cost penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"epsilon":{"description":"Latency penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"gamma":{"description":"Elo score weight.","type":"number","format":"float","default":0.30000001192092896},"knn_k":{"description":"Number of nearest neighbors considered for voting. Default: `7`.","type":"integer","format":"uint","default":7,"minimum":0},"knn_min_records":{"description":"Minimum history records before KNN affects routing. Default: `10`.","type":"integer","format":"uint","default":10,"minimum":0},"models":{"description":"Candidate model registry.","type":"array","default":[],"items":{"$ref":"#/$defs/RouterModelConfig"}}}},"RouterModelConfig":{"description":"Static router metadata for one model candidate.","type":"object","properties":{"categories":{"description":"Capability categories such as `conversation`, `code`, or `analysis`.","type":"array","default":[],"items":{"type":"string"}},"cost_per_million_tokens":{"description":"USD cost per million tokens.","type":"number","format":"float","default":0.0},"elo_rating":{"description":"Initial Elo rating.","type":"number","format":"float","default":1000.0},"latency_ms":{"description":"Average latency in milliseconds.","type":"integer","format":"uint32","default":2000,"minimum":0},"max_context":{"description":"Maximum context window in tokens.","type":"integer","format":"uint","default":1000000,"minimum":0},"model_id":{"description":"Model identifier without provider prefix.","type":"string"},"provider":{"description":"Provider identifier.","type":"string"},"reserved_output_tokens":{"description":"Output tokens reserved for this model when planning input context.","type":["integer","null"],"format":"uint","minimum":0}},"required":["model_id","provider"]},"RuntimeConfig":{"description":"Runtime adapter configuration (`[runtime]` section).","type":"object","properties":{"codex_reasoning_effort":{"description":"Codex reasoning effort","type":["string","null"],"default":null},"codex_stream_idle_timeout_secs":{"description":"Codex stream idle timeout in seconds","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"docker":{"description":"Docker runtime settings (used when `kind = \"docker\"`).","$ref":"#/$defs/DockerRuntimeConfig","default":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true}},"idle_hang_secs":{"description":"Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"kind":{"description":"Runtime kind (`native` | `docker`).","type":"string","default":"native"},"long_task_warn_secs":{"description":"Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"managed_cgroup_root":{"description":"Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.","type":["string","null"],"default":null},"max_blocking_threads":{"description":"Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"reasoning_enabled":{"description":"Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported","type":["boolean","null"],"default":null},"shell_env_allowlist":{"description":"Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.","type":"array","default":[],"items":{"type":"string"}},"workdir":{"description":"Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.","type":["string","null"],"default":null}}},"SchedulerConfig":{"description":"Scheduler configuration for periodic task execution (`[scheduler]` section).","type":"object","properties":{"claim_lease_secs":{"description":"Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.","type":"integer","format":"uint64","default":90,"minimum":0},"max_tasks":{"description":"Maximum number of persisted scheduled tasks.","type":"integer","format":"uint","default":64,"minimum":0}}},"ScopeConfig":{"description":"Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```","type":"object","properties":{"assign_owners":{"description":"Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.","type":"array","default":[],"items":{"type":"string"}},"default":{"description":"Default action when no rule matches: \"allow\" (default) or \"deny\".","$ref":"#/$defs/ScopeDefault","default":"allow"},"rules":{"description":"Ordered list of scope rules evaluated top-to-bottom.","type":"array","default":[],"items":{"$ref":"#/$defs/ScopeRule"}}}},"ScopeDefault":{"description":"What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.","oneOf":[{"description":"Unmatched tool calls are allowed (the default).","type":"string","const":"allow"},{"description":"Unmatched tool calls are refused.","type":"string","const":"deny"}]},"ScopeRule":{"description":"A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.","type":"object","properties":{"assign_allow":{"description":"Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".","type":"array","default":[],"items":{"type":"string"}},"assign_deny":{"description":"Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.","type":"array","default":[],"items":{"type":"string"}},"channel":{"description":"Match by channel name: \"signal\", \"telegram\", \"discord\", etc.","type":["string","null"]},"chat_type":{"description":"Match by chat type: \"direct\", \"group\", or \"*\" for any type.","type":["string","null"]},"send_allow":{"description":"Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.","type":"array","default":[],"items":{"type":"string"}},"send_deny":{"description":"Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.","type":"array","default":[],"items":{"type":"string"}},"tools_allow":{"description":"Tool whitelist: only these tools are allowed (empty = all tools permitted).","type":"array","default":[],"items":{"type":"string"}},"tools_deny":{"description":"Tool blacklist: these tools are denied regardless of allow list.","type":"array","default":[],"items":{"type":"string"}},"user":{"description":"Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.","type":["string","null"]}}},"SecretsConfig":{"description":"Secrets encryption configuration (`[secrets]` section).","type":"object","properties":{"encrypt":{"description":"Enable encryption for API keys and tokens in config.toml","type":"boolean","default":true}}},"SecurityConfig":{"description":"Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.","type":"object","properties":{"audit":{"description":"Audit logging configuration","$ref":"#/$defs/AuditConfig","default":{"log_path":"audit.log","max_size_mb":100}},"workspace_hooks":{"description":"Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.","$ref":"#/$defs/WorkspaceHooks"}}},"SelfSystemConfig":{"description":"Self-system experimental automation config (`[self_system]`).","type":"object","properties":{"evolution_config_path":{"description":"Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG)","type":["string","null"],"default":null},"evolution_debug_raw":{"description":"Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW)","type":"boolean","default":false},"evolution_interval_hours":{"description":"Evolution scheduler interval in hours (daemon mode).","type":"integer","format":"uint32","default":24,"minimum":0},"evolution_judge_timeout_secs":{"description":"Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.","type":"integer","format":"uint64","default":180,"minimum":0},"evolution_model_max_micro_usd":{"description":"Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.","type":"integer","format":"uint64","default":0,"minimum":0},"evolution_model_max_tokens":{"description":"Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.","type":"integer","format":"uint64","default":16384,"minimum":0},"fitness":{"description":"Daily fitness snapshot policy.","$ref":"#/$defs/FitnessConfig","default":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"}},"fitness_interval_hours":{"description":"Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.","type":"integer","format":"uint64","default":24,"minimum":0}}},"SessionsSpawnConfig":{"description":"Sessions spawn configuration (`[sessions_spawn]` section).","type":"object","properties":{"cleanup_on_complete":{"description":"Remove worker workspace directory after process-mode completion.","type":"boolean","default":true},"default_mode":{"description":"Default execution mode for sessions_spawn (`task` or `process`).","type":"string","default":"task"},"process_memory_strategy":{"description":"Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.","type":"string","default":"shared_fabric"},"worker_workspace_root":{"description":"Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.","type":["string","null"],"default":null}}},"SignalConfig":{"type":"object","properties":{"account":{"description":"E.164 phone number of the signal-cli account (e.g. \"+1234567890\").","type":"string"},"allowed_from":{"description":"Allowed sender phone numbers (E.164) or \"*\" for all.","type":"array","default":[],"items":{"type":"string"}},"cli_path":{"description":"Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).","type":["string","null"],"default":null},"daemon_http_port":{"description":"Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"daemon_mode":{"description":"Deprecated: ignored. Accepted for backward compatibility with older config files.","type":["boolean","null"],"default":null},"data_dir":{"description":"signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_id":{"description":"Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group","type":["string","null"],"default":null},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"http_url":{"description":"Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.","type":"string","default":"http://localhost:8080"},"ignore_attachments":{"description":"Skip messages that are attachment-only (no text body).","type":"boolean","default":false},"ignore_stories":{"description":"Skip incoming story messages.","type":"boolean","default":false},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"mode":{"description":"Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.","type":["string","null"],"default":null},"startup_timeout_ms":{"description":"Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.","type":"integer","format":"uint64","default":30000,"minimum":0},"storm_protection":{"description":"Signal ingress storm protection controls.","$ref":"#/$defs/SignalStormProtectionConfig","default":{"abnormal_threshold":10,"abnormal_window_secs":60,"breaker_duration_secs":300,"dedupe_ttl_secs":60,"min_reply_interval_secs":2}}},"required":["account"]},"SignalStormProtectionConfig":{"type":"object","properties":{"abnormal_threshold":{"description":"Non-user event threshold within `abnormal_window_secs` before tripping the breaker.","type":"integer","format":"uint","default":10,"minimum":0},"abnormal_window_secs":{"description":"Sliding window in seconds for non-user event counting.","type":"integer","format":"uint64","default":60,"minimum":0},"breaker_duration_secs":{"description":"Circuit breaker duration in seconds after threshold is reached.","type":"integer","format":"uint64","default":300,"minimum":0},"dedupe_ttl_secs":{"description":"Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.","type":"integer","format":"uint64","default":60,"minimum":0},"min_reply_interval_secs":{"description":"Minimum interval in seconds between replies for the same `(channel + reply_target)`.","type":"integer","format":"uint64","default":2,"minimum":0}}},"SkillRagConfig":{"description":"Dynamic skill retrieval configuration (`[skill_rag]` section).","type":"object","properties":{"top_k":{"description":"How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).","type":"integer","format":"uint","default":32,"minimum":0}}},"SkillSuiteRegistration":{"description":"The frozen suite that governs one skill's proposals.","type":"object","properties":{"skill_id":{"description":"The skill the suite governs.","type":"string"},"suite_digest":{"description":"SHA-256 digest (64 lowercase hex digits) of the frozen suite.","type":"string"}},"additionalProperties":false,"required":["skill_id","suite_digest"]},"SkillsConfig":{"description":"Skills loading configuration (`[skills]` section).","type":"object","properties":{"open_skills_dir":{"description":"Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.","type":["string","null"],"default":null},"openclaw_skills_dir":{"description":"Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.","type":["string","null"],"default":null}}},"SkillsLifecycleConfig":{"description":"`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.","type":"object","properties":{"allow_executable_proposals":{"description":"Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.","type":"boolean","default":false},"enabled":{"description":"Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.","type":"boolean","default":false},"max_concurrent_evaluations":{"description":"Most evaluations running at once.","type":"integer","format":"uint32","default":1,"minimum":0},"max_edit_fraction":{"description":"Edit budget of a proposal as a fraction of the skill body, in (0, 1].","type":"number","format":"double","default":0.2},"max_edit_tokens":{"description":"Edit budget of a proposal, in tokens.","type":"integer","format":"uint64","default":300,"minimum":0},"max_proposals_per_cycle":{"description":"Most proposals one cycle may start.","type":"integer","format":"uint32","default":1,"minimum":0},"min_cases_floor":{"description":"Smallest `min_cases` a governing suite may declare. Below 3 is refused.","type":"integer","format":"uint32","default":3,"minimum":0},"mode":{"description":"`draft_only`, `shadow` or `auto`.","$ref":"#/$defs/SkillsLifecycleModeConfig","default":"draft_only"},"owner_scope":{"description":"The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.","type":["string","null"],"default":null},"require_holdout":{"description":"A governing suite must have a holdout split. `false` is refused.","type":"boolean","default":true},"storage_dir":{"description":"Store location under the workspace. Only the default is supported.","type":"string","default":"self/skill-lifecycle"},"suites":{"description":"The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.","type":"array","default":[],"items":{"$ref":"#/$defs/SkillSuiteRegistration"}}},"additionalProperties":false},"SkillsLifecycleModeConfig":{"description":"What the lifecycle may do. Mirrors `LifecycleMode`.","oneOf":[{"description":"Drafts and reviews only.","type":"string","const":"draft_only"},{"description":"Drafts plus evaluation and gating; never publishes.","type":"string","const":"shadow"},{"description":"Publishes an eligible proposal after every gate.","type":"string","const":"auto"}]},"SlackConfig":{"description":"Slack bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Slack user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Slack app-level token for Socket Mode (xapp-...).","type":["string","null"]},"bot_token":{"description":"Slack bot OAuth token (xoxb-...).","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["bot_token"]},"SmartGroupConfig":{"description":"Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).","type":"object","properties":{"classifier_max_context_messages":{"description":"How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.","type":"integer","format":"uint","default":3,"minimum":0},"classifier_model":{"description":"Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.","type":"string","default":""},"classifier_provider":{"description":"Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.","type":"string","default":""},"classifier_temperature":{"description":"Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).","type":"number","format":"double","default":0.0},"classifier_timeout_secs":{"description":"Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.","type":"integer","format":"uint64","default":5,"minimum":0}}},"StorageConfig":{"description":"Persistent storage configuration (`[storage]` section).","type":"object","properties":{"provider":{"description":"Storage provider settings (e.g. sqlite, postgres).","$ref":"#/$defs/StorageProviderSection","default":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}}},"StorageProviderConfig":{"description":"Storage provider backend configuration (e.g. postgres connection details).","type":"object","properties":{"connect_timeout_secs":{"description":"Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"db_url":{"description":"Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.","type":["string","null"],"default":null},"pool_max_size":{"description":"Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.","type":"integer","format":"uint","default":32,"minimum":0},"provider":{"description":"Storage engine key (e.g. \"postgres\", \"sqlite\").","type":"string","default":""},"schema":{"description":"Database schema for SQL backends.","type":"string","default":"public"},"table":{"description":"Table name for memory entries.","type":"string","default":"memories"}}},"StorageProviderSection":{"description":"Wrapper for the storage provider configuration section.","type":"object","properties":{"config":{"description":"Storage provider backend settings.","$ref":"#/$defs/StorageProviderConfig","default":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"StreamMode":{"description":"Streaming mode for channels that support progressive message updates.","oneOf":[{"description":"No streaming -- send the complete response as a single message (default).","type":"string","const":"off"},{"description":"Update a draft message with every flush interval.","type":"string","const":"partial"}]},"TailscaleTunnelConfig":{"type":"object","properties":{"funnel":{"description":"Use Tailscale Funnel (public internet) vs Serve (tailnet only)","type":"boolean","default":false},"hostname":{"description":"Optional hostname override","type":["string","null"]}}},"TaskRoutingConfig":{"description":"Lightweight pre-LLM task routing.","type":"object","properties":{"default_intent":{"description":"Fallback intent when no rule matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"rules":{"description":"Rules evaluated in descending priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/TaskRoutingRule"}}}},"TaskRoutingIntentConfig":{"description":"Task-routing default and rule intent.","type":"string","enum":["simple","delegate","stream"]},"TaskRoutingRule":{"description":"A single task-routing rule.","type":"object","properties":{"intent":{"description":"Route intent to apply when a keyword matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"model_hint":{"description":"Optional model hint/raw model for non-delegated requests.","type":["string","null"],"default":null},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0},"sub_agent_model":{"description":"Optional raw sub-agent model override for delegated tasks.","type":["string","null"],"default":null}}},"TelegramConfig":{"description":"Telegram bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Telegram user IDs or usernames. Empty = deny all.","type":"array","items":{"type":"string"}},"bot_token":{"description":"Telegram Bot API token (from @BotFather).","type":"string"},"draft_update_interval_ms":{"description":"Minimum interval (ms) between draft message edits to avoid rate limits.","type":"integer","format":"uint64","default":1000,"minimum":0},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"interrupt_on_new_message":{"description":"When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.","type":"boolean","default":false},"stream_mode":{"description":"Streaming mode for progressive response delivery via message edits.","$ref":"#/$defs/StreamMode","default":"off"}},"required":["bot_token","allowed_users"]},"ToolCallDialectSetting":{"description":"The tool-call grammars an operator may declare for an endpoint.","oneOf":[{"description":"Only the native `tool_calls` array is a tool call (the default).","type":"string","const":"native"},{"description":"Additionally read `{json}` from the content,\nfor a tool name the request registered.","type":"string","const":"xml_function_tags"}]},"ToolSchemaDialectSetting":{"description":"The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.","oneOf":[{"description":"The published document, byte for byte (the default).","type":"string","const":"raw"},{"description":"The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.","type":"string","const":"no_root_combinators"}]},"ToolTieringConfig":{"description":"Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.","type":"object","properties":{"always_exclude":{"description":"Tool names excluded from capability publication.","type":"array","default":[],"items":{"type":"string"}},"always_include":{"description":"Tool names preferred for direct publication, subject to admission gates.","type":"array","default":[],"items":{"type":"string"}},"channel_exclude":{"description":"Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefault: empty (nothing is hidden); list tool names to hide them on channels.","type":"array","default":[],"items":{"type":"string"}}}},"TunnelConfig":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.","type":"object","properties":{"cloudflare":{"description":"Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).","anyOf":[{"$ref":"#/$defs/CloudflareTunnelConfig"},{"type":"null"}],"default":null},"custom":{"description":"Custom tunnel command configuration (used when `provider = \"custom\"`).","anyOf":[{"$ref":"#/$defs/CustomTunnelConfig"},{"type":"null"}],"default":null},"ngrok":{"description":"ngrok tunnel configuration (used when `provider = \"ngrok\"`).","anyOf":[{"$ref":"#/$defs/NgrokTunnelConfig"},{"type":"null"}],"default":null},"provider":{"description":"Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.","type":"string","default":"none"},"tailscale":{"description":"Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).","anyOf":[{"$ref":"#/$defs/TailscaleTunnelConfig"},{"type":"null"}],"default":null}}},"UserPolicyConfig":{"description":"Startup user policy entry (`[[user_policies]]`).","type":"object","properties":{"blocked_patterns":{"type":"array","default":[],"items":{"type":"string"}},"projects":{"type":"array","default":[],"items":{"type":"string"}},"role":{"type":"string","default":"guest"},"user_id":{"type":"string"},"visibility_ceiling":{"type":"string","default":"private"}},"required":["user_id"]},"WacliConfig":{"description":"wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```","type":"object","properties":{"allow_unsigned_loopback":{"description":"Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).","type":"boolean","default":false},"allowed_from":{"description":"Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.","type":"array","default":["*"],"items":{"type":"string"}},"bot_jid":{"description":"Bot's own JID, used for reply-to-bot mention detection.","type":["string","null"],"default":null},"bot_lid":{"description":"The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.","type":["string","null"],"default":null},"bot_number":{"description":"Bot's own phone number (digits), used for `@` mention detection.","type":["string","null"],"default":null},"cli_path":{"description":"Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.","type":["string","null"],"default":null},"group_reply_mode":{"description":"Smart group-reply mode. When `None`, derived from `mention_only`.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"host":{"description":"REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].","type":["string","null"],"writeOnly":true},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"outbound_media_workspace_only":{"description":"Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.","type":"boolean","default":false},"port":{"description":"REMOVED: legacy JSON-RPC daemon port. See `host`.","type":["integer","null"],"format":"uint16","maximum":65535,"minimum":0,"writeOnly":true},"self_chat_mode":{"description":"Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.","type":"boolean","default":false},"store_dir":{"description":"wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.","type":["string","null"],"default":null},"webhook_listen":{"description":"Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").","type":"string","default":"127.0.0.1:16868"},"webhook_path":{"description":"HTTP path the webhook server serves (default: \"/wacli\").","type":"string","default":"/wacli"},"webhook_secret":{"description":"HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.","type":["string","null"],"default":null}}},"WebSearchConfig":{"description":"Web search tool configuration (`[web_search]` section).","type":"object","properties":{"brave_api_key":{"description":"Brave Search API key (required if provider is \"brave\")","type":["string","null"],"default":null},"fetch_max_chars":{"description":"Maximum characters returned by `web_fetch` (default 10000)","type":"integer","format":"uint","default":50000,"minimum":0},"max_results":{"description":"Maximum results per search (1-20)","type":"integer","format":"uint","default":15,"minimum":0},"provider":{"description":"Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)","type":"string","default":"duckduckgo"},"timeout_secs":{"description":"Request timeout in seconds","type":"integer","format":"uint64","default":15,"minimum":0}}},"WebhookConfig":{"description":"Webhook channel configuration.","type":"object","properties":{"port":{"description":"Port to listen on for incoming webhooks.","type":"integer","format":"uint16","maximum":65535,"minimum":0},"secret":{"description":"Optional shared secret for webhook signature verification.","type":["string","null"]}},"required":["port"]},"WhatsAppConfig":{"description":"WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.","type":"object","properties":{"access_token":{"description":"Access token from Meta Business Suite (Cloud API mode)","type":["string","null"],"default":null},"allowed_numbers":{"description":"Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"app_secret":{"description":"App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"pair_code":{"description":"Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one","type":["string","null"],"default":null},"pair_phone":{"description":"Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used","type":["string","null"],"default":null},"phone_number_id":{"description":"Phone number ID from Meta Business API (Cloud API mode)","type":["string","null"],"default":null},"read_pool_size":{"description":"Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"session_path":{"description":"Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs","type":["string","null"],"default":null},"verify_token":{"description":"Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode","type":["string","null"],"default":null},"ws_url":{"description":"WebSocket URL override (replaces WHATSAPP_WS_URL)","type":["string","null"],"default":null}}},"WorkspaceHooks":{"description":"Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).","oneOf":[{"description":"They do not run (the default); `prx doctor` and `hooks_status` say so.","type":"string","const":"off"},{"description":"They run, in a cleared environment and a dedicated directory beside\n`config.toml`.","type":"string","const":"on"}]},"WorkspaceMcpServers":{"description":"Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).","oneOf":[{"description":"None: a workspace file may only narrow the servers defined in\n`config.toml`.","type":"string","const":"off"},{"description":"HTTP servers (still refused when they target a private address).","type":"string","const":"http_only"},{"description":"HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.","type":"string","const":"stdio"}]},"XinConfig":{"description":"Configuration for the xin autonomous task engine (`[xin]`).","type":"object","properties":{"adopt_legacy_tasks":{"description":"Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).","type":"boolean","default":false},"interval_minutes":{"description":"Tick interval in minutes (minimum 1). Default: 5.","type":"integer","format":"uint32","default":5,"minimum":0},"stale_timeout_minutes":{"description":"Minutes after which a running task is marked stale. Default: 60.","type":"integer","format":"uint32","default":60,"minimum":0}}},"AgentMessaging":{"description":"Owner-controlled inbound session messaging (enabled unless explicitly off).","type":"object","properties":{"inbound":{"type":"boolean","default":true}}}}} From 9fbb108c60139005fc8f3bf85a156dd44f9809ea Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:15:49 +0400 Subject: [PATCH 0140/1567] feat(config): reset old init-written defaults once on upgrade The first start after upgrade resets values that still equal a former default (cost ceilings, workspace_only, forbidden_paths, allow_remote_fetch, channel_exclude, targeted_agents, node allowed_commands) through the configuration transaction, so prx config rollback restores them. A marker file keeps it from running again, and prx doctor lists old values still present. --- docs/migration-unreleased.md | 39 +++++ src/config/defaults_migration.rs | 234 +++++++++++++++++++++++++ src/config/mod.rs | 1 + src/config/schema/lifecycle.rs | 2 + src/doctor/implementation/section_2.rs | 13 ++ 5 files changed, 289 insertions(+) create mode 100644 src/config/defaults_migration.rs diff --git a/docs/migration-unreleased.md b/docs/migration-unreleased.md index f48706fe4..d1a31fdaf 100644 --- a/docs/migration-unreleased.md +++ b/docs/migration-unreleased.md @@ -119,6 +119,45 @@ latency_budget_ms = 800 an optional accounting scope ID; older records remain readable. See [managed skill prompts](evolution.md#managed-skill-prompts). +## One-time reset of old default values + +Earlier `prx init` builds wrote every default into `config.toml` and +`config.d/*.toml`, so an installation created by one keeps the former limits +even though the built-in defaults are now unrestricted. The first start of this +build resets a value to the new default when it is exactly the old default: + +| Key | Old default reset | +| --- | --- | +| `[autonomy] max_cost_per_day_cents` | `500` | +| `[cost] daily_limit_usd` | `10.0` | +| `[cost] monthly_limit_usd` | `100.0` | +| `[autonomy] workspace_only` | `true` (only when `level = "full"`) | +| `[autonomy] forbidden_paths` | the former 18-path list, exactly (only when `level = "full"`) | +| `[multimodal] allow_remote_fetch` | `false` | +| `[tool_tiering] channel_exclude` | the former 14-tool list, exactly | +| `[gateway] targeted_agents` | `false` | +| `[nodes.server] allowed_commands` | `["echo"]` | + +`acknowledge_unrestricted_profile` is no longer written when the files are +rewritten. `autonomy.level` is never touched, and a `supervised` or `readonly` +install keeps `workspace_only` and `forbidden_paths`. Authentication keys +(`require_pairing`, tokens, sender allowlists) are never touched. + +- **Rule:** a value that differs from the old default, for example + `daily_limit_usd = 3.0`, is left alone. The tree cannot tell a value `prx init` + wrote from one the operator typed (`.init-defaults.toml` records template + values for `prx init --force` only), so equality with the old default is the + test. To keep a former limit after the upgrade, set it again once the reset + has run, or set it to any other value before upgrading. +- **How:** the reset goes through the configuration transaction (one history + record, revision check) and rewrites the configuration files in canonical form. + A marker file `.defaults-migration` beside `config.toml` records that it ran + (key names only), so it never runs again. One info line at start names the + keys reset. `prx doctor` lists old default values still present. +- **Roll back:** `prx config rollback` restores the files from before the reset. + The marker stays, so the reset is not repeated. + + ## Remaining lifecycle and runtime interfaces Ordinary children and operator tasks now share their parent's budget counter diff --git a/src/config/defaults_migration.rs b/src/config/defaults_migration.rs new file mode 100644 index 000000000..56ef73522 --- /dev/null +++ b/src/config/defaults_migration.rs @@ -0,0 +1,234 @@ +//! One-time removal of old default values that earlier `prx init` builds wrote +//! into the configuration tree. +//! +//! The built-in defaults moved to "no restriction". An installation whose files +//! still hold the former defaults written out explicitly would keep them forever, +//! so the first start of this build resets every value that is still exactly +//! its old default. +//! +//! Rules: +//! +//! - Only a value equal to the old default is reset. A value the operator changed +//! is left alone. The tree does not record which values `prx init` wrote (the +//! `.init-defaults.toml` sidecar lists template values only), so equality with +//! the old default is the criterion. +//! - `workspace_only` and `forbidden_paths` are reset only when +//! `autonomy.level = "full"`; a lowered install keeps them. +//! - The change goes through the configuration transaction (history record, +//! revision check), so `prx config rollback` restores the files. +//! - The migration runs once: the marker file records its version, and it is +//! written whether or not anything was reset. A rolled-back install is not +//! migrated again; `prx doctor` reports the old values it still holds. + +use super::Config; +use super::manage::{ConfigActor, ManagementService}; +use crate::security::AutonomyLevel; +use std::path::{Path, PathBuf}; + +/// Version of this migration. Raising it runs a later migration once more. +const MIGRATION_VERSION: u32 = 1; + +/// Marker file beside `config.toml`. +const MARKER_FILE: &str = ".defaults-migration"; + +/// The `[autonomy] forbidden_paths` list old builds wrote. +const OLD_FORBIDDEN_PATHS: &[&str] = &[ + "/etc", + "/root", + "/home", + "/usr", + "/bin", + "/sbin", + "/lib", + "/opt", + "/boot", + "/dev", + "/proc", + "/sys", + "/var", + "/tmp", + "~/.ssh", + "~/.gnupg", + "~/.aws", + "~/.config", +]; + +/// The `[tool_tiering] channel_exclude` list old builds wrote. +const OLD_CHANNEL_EXCLUDE: &[&str] = &[ + "wasm_plugins_manage", + "wasm_plugin_reload", + "wasm_plugins_status", + "hooks_manage", + "hooks_status", + "proxy_config", + "config_reload", + "gateway", + "mcp_status", + "nodes", + "skills_manage", + "memory_reindex", + "document_sync", + "document_ingest", +]; + +/// One former default: its key, the old value (inside `is_old`), and how to +/// reset it to the new built-in default. +struct LegacyDefault { + key: &'static str, + /// Reset only while `autonomy.level = "full"`. + full_only: bool, + is_old: fn(&Config) -> bool, + reset: fn(&mut Config), +} + +fn equals(list: &[String], old: &[&str]) -> bool { + list.len() == old.len() && list.iter().zip(old).all(|(a, b)| a == b) +} + +/// Every default changed by the "unrestricted by default" work, with its old value. +const LEGACY_DEFAULTS: &[LegacyDefault] = &[ + LegacyDefault { + key: "autonomy.max_cost_per_day_cents", + full_only: false, + is_old: |c| c.autonomy.max_cost_per_day_cents == Some(500), + reset: |c| c.autonomy.max_cost_per_day_cents = None, + }, + LegacyDefault { + key: "cost.daily_limit_usd", + full_only: false, + is_old: |c| c.cost.daily_limit_usd == Some(10.0), + reset: |c| c.cost.daily_limit_usd = None, + }, + LegacyDefault { + key: "cost.monthly_limit_usd", + full_only: false, + is_old: |c| c.cost.monthly_limit_usd == Some(100.0), + reset: |c| c.cost.monthly_limit_usd = None, + }, + LegacyDefault { + key: "autonomy.workspace_only", + full_only: true, + is_old: |c| c.autonomy.workspace_only, + reset: |c| c.autonomy.workspace_only = false, + }, + LegacyDefault { + key: "autonomy.forbidden_paths", + full_only: true, + is_old: |c| equals(&c.autonomy.forbidden_paths, OLD_FORBIDDEN_PATHS), + reset: |c| c.autonomy.forbidden_paths.clear(), + }, + LegacyDefault { + key: "multimodal.allow_remote_fetch", + full_only: false, + is_old: |c| !c.multimodal.allow_remote_fetch, + reset: |c| c.multimodal.allow_remote_fetch = true, + }, + LegacyDefault { + key: "tool_tiering.channel_exclude", + full_only: false, + is_old: |c| equals(&c.tool_tiering.channel_exclude, OLD_CHANNEL_EXCLUDE), + reset: |c| c.tool_tiering.channel_exclude.clear(), + }, + LegacyDefault { + key: "gateway.targeted_agents", + full_only: false, + is_old: |c| !c.gateway.targeted_agents, + reset: |c| c.gateway.targeted_agents = true, + }, + LegacyDefault { + key: "nodes.server.allowed_commands", + full_only: false, + is_old: |c| c.nodes.server.allowed_commands == ["echo"], + reset: |c| c.nodes.server.allowed_commands.clear(), + }, +]; + +/// Keys of `config` that still hold their old default (names only). +#[must_use] +pub(crate) fn legacy_default_keys(config: &Config) -> Vec<&'static str> { + let full = config.autonomy.level == AutonomyLevel::Full; + LEGACY_DEFAULTS + .iter() + .filter(|entry| (full || !entry.full_only) && (entry.is_old)(config)) + .map(|entry| entry.key) + .collect() +} + +fn marker_path(config_path: &Path) -> PathBuf { + config_path + .parent() + .unwrap_or_else(|| Path::new(".")) + .join(MARKER_FILE) +} + +/// Whether the migration has run (its marker is present at this version). +#[must_use] +pub(crate) fn migration_has_run(config_path: &Path) -> bool { + std::fs::read_to_string(marker_path(config_path)) + .ok() + .and_then(|text| text.parse::().ok()) + .and_then(|table| table.get("version").and_then(toml::Value::as_integer)) + .is_some_and(|version| version >= i64::from(MIGRATION_VERSION)) +} + +fn write_marker(config_path: &Path, removed: &[&str]) { + let list = removed + .iter() + .map(|key| format!("\"{key}\"")) + .collect::>() + .join(", "); + let text = format!( + "# Written once by prx after it reset old default values; key names only.\nversion = {MIGRATION_VERSION}\nremoved = [{list}]\n" + ); + let path = marker_path(config_path); + if let Err(error) = std::fs::write(&path, text) { + tracing::warn!(%error, "could not record the defaults migration; it will be retried at the next start"); + } +} + +/// Run the migration once for an existing configuration and return the +/// configuration to use (reloaded from disk when values were reset). +pub(crate) async fn run_once(config: Config) -> Config { + if migration_has_run(&config.config_path) { + return config; + } + let keys = legacy_default_keys(&config); + if keys.is_empty() { + write_marker(&config.config_path, &keys); + return config; + } + let mut candidate = config.clone(); + for entry in LEGACY_DEFAULTS.iter().filter(|entry| keys.contains(&entry.key)) { + (entry.reset)(&mut candidate); + } + let service = ManagementService::deferred(super::new_shared(config.clone())); + let applied = async { + let revision = service.revision(); + let plan = service + .plan_candidate(candidate, revision, ConfigActor::Cli) + .await?; + let confirmed = plan.revision().map(str::to_string); + service.apply(plan, ConfigActor::Cli, confirmed.as_deref()).await + } + .await; + match applied { + Ok(_) => match Config::load_from_path(&config.config_path, config.workspace_dir.clone()) { + Ok(reloaded) => { + tracing::info!( + removed = %keys.join(", "), + "Reset old default values to the new unrestricted defaults; `prx config rollback` restores them" + ); + write_marker(&config.config_path, &keys); + reloaded + } + Err(error) => { + tracing::warn!(%error, "defaults migration applied but the configuration could not be reloaded"); + config + } + }, + Err(error) => { + tracing::warn!(%error, "defaults migration was not applied; it will be retried at the next start"); + config + } + } +} diff --git a/src/config/mod.rs b/src/config/mod.rs index 030e7ad24..288932949 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -1,6 +1,7 @@ pub mod agent_name; pub(crate) mod agent_revision; pub mod credential_slots; +pub(crate) mod defaults_migration; pub(crate) mod deprecations; pub mod files; pub mod generation; diff --git a/src/config/schema/lifecycle.rs b/src/config/schema/lifecycle.rs index 38e088374..80a2430e3 100644 --- a/src/config/schema/lifecycle.rs +++ b/src/config/schema/lifecycle.rs @@ -243,6 +243,8 @@ impl Config { initialized = false, "Config loaded" ); + // One time: reset old init-written default values to the new defaults. + let config = crate::config::defaults_migration::run_once(config).await; // Eagerly migrate any remaining legacy enc: secrets so they are upgraded // even if they have never been accessed since the XOR-cipher era. if let Err(e) = migrate_config_legacy_secrets(&config).await { diff --git a/src/doctor/implementation/section_2.rs b/src/doctor/implementation/section_2.rs index e3e925e3f..da0e5acaf 100644 --- a/src/doctor/implementation/section_2.rs +++ b/src/doctor/implementation/section_2.rs @@ -9,6 +9,19 @@ fn check_config_semantics(config: &Config, items: &mut Vec) { format!("autonomy level: {:?}", config.autonomy.level), )); + let legacy = crate::config::defaults_migration::legacy_default_keys(config); + if !legacy.is_empty() { + let state = if crate::config::defaults_migration::migration_has_run(&config.config_path) { + "kept after the one-time reset (rolled back or set again; they apply as written)" + } else { + "the one-time reset has not run yet" + }; + items.push(DiagItem::configured( + cat, + format!("old default values present ({}): {state}", legacy.join(", ")), + )); + } + // Config file exists if config.config_path.exists() { items.push(DiagItem::configured( From 30ced910a4d66d2149972d7e24afccd98cc70d84 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:14:46 +0400 Subject: [PATCH 0141/1567] fix(memory): keep saved chat sessions out of conversation row pruning --- src/config/schema/memory.rs | 3 ++- src/memory/hygiene.rs | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/config/schema/memory.rs b/src/config/schema/memory.rs index 1954372d2..344256af9 100644 --- a/src/config/schema/memory.rs +++ b/src/config/schema/memory.rs @@ -119,7 +119,8 @@ pub struct MemoryConfig { /// Purge archived files older than this many days #[serde(default = "default_purge_after_days")] pub purge_after_days: u32, - /// For sqlite backend: prune conversation rows older than this many days + /// For sqlite backend: prune conversation rows older than this many days. + /// Saved chat sessions (`chat_session:*` keys) are never pruned by this pass. #[serde(default = "default_conversation_retention_days")] pub conversation_retention_days: u32, /// For sqlite backend: prune daily rows older than this many days diff --git a/src/memory/hygiene.rs b/src/memory/hygiene.rs index 0e2bd6273..10bbc2c4d 100644 --- a/src/memory/hygiene.rs +++ b/src/memory/hygiene.rs @@ -308,6 +308,7 @@ fn prune_conversation_rows(workspace_dir: &Path, retention_days: u32) -> Result< let affected = conn.execute( "DELETE FROM memories WHERE category = 'conversation' + AND substr(key, 1, 13) <> 'chat_session:' AND updated_at < ?1 AND COALESCE(useful_count, 0) < ?2", params![cutoff, USEFUL_COUNT_RETENTION_THRESHOLD], From b2edb0e738944ffa3af0e34010dc1643c4677e61 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:15:34 +0400 Subject: [PATCH 0142/1567] fix(agent): state exactly what a context handoff keeps and what it cannot recover --- docs/unified-turn-context.md | 9 +++++++++ src/agent/compaction.rs | 9 +++++---- src/chat/tests/handoff_view_tests.rs | 5 +++-- tests/chat_plain_compaction_cli.rs | 7 ++++--- 4 files changed, 21 insertions(+), 9 deletions(-) diff --git a/docs/unified-turn-context.md b/docs/unified-turn-context.md index eb2a776a6..2ec3ec889 100644 --- a/docs/unified-turn-context.md +++ b/docs/unified-turn-context.md @@ -144,6 +144,15 @@ deleted. A later rollover can reference the prior handoff event exactly, so repeated switches form an auditable generation chain within the same durable session. +The provider view renders each note as one line: `[context_handoff] +handoff_event_id= -- earlier user and assistant messages were moved out +of this window. They are recoverable with +transcript_history_lookup(handoff_event_id=""). The tool calls and tool +results of the replaced turns are not recoverable.` (the separator is an em +dash), followed by the folded round-trip count when it is not zero. The +system-prompt rule says the same: user and assistant messages can be read back, +tool calls and tool results of those turns cannot. + Each handoff references only the rows it replaced, its parent handoff row among them, so a fact older than the newest handoff is reached by following the chain: one lookup per generation. Once a handoff exists, the diff --git a/src/agent/compaction.rs b/src/agent/compaction.rs index 2ac331c9a..12696ac1d 100644 --- a/src/agent/compaction.rs +++ b/src/agent/compaction.rs @@ -593,7 +593,7 @@ fn validate_context_handoff(content: &str) -> Option<(ValidatedContextHandoff, & /// The system-prompt paragraph of a chat session that states what a handoff /// in its window means and how earlier turns are reached. Its bytes never /// change between turns, so the cacheable prompt prefix stays stable. -pub(crate) const CONTEXT_HANDOFF_PROMPT_RULE: &str = "A message that starts with [context_handoff] means earlier turns of this session were moved out of this window; they still exist. Never treat the oldest visible message as the start of the session. Before answering a question about anything that may have happened earlier than the visible window, call transcript_history_lookup with that handoff's handoff_event_id and read the result; if the result contains another [context_handoff], look that one up too."; +pub(crate) const CONTEXT_HANDOFF_PROMPT_RULE: &str = "A message that starts with [context_handoff] means earlier turns of this session were moved out of this window; their user and assistant messages still exist and can be read back, but the tool calls and tool results of those turns cannot be recovered. Never treat the oldest visible message as the start of the session. Before answering a question about anything that may have happened earlier than the visible window, call transcript_history_lookup with that handoff's handoff_event_id and read the result; if the result contains another [context_handoff], look that one up too."; /// Whether `messages` hold a context handoff, in its stored or its rendered /// form: both start with the handoff marker. @@ -619,9 +619,10 @@ pub(crate) fn render_context_handoff_for_provider<'a>(role: &str, content: &'a s std::borrow::Cow::Owned(format_compact_context_handoff(&handoff)) } -/// `[context_handoff] handoff_event_id= — earlier messages were moved +/// `[context_handoff] handoff_event_id= — earlier user and assistant messages were moved /// out of this window. They are recoverable with -/// transcript_history_lookup(handoff_event_id="").`, followed by +/// transcript_history_lookup(handoff_event_id=""). The tool calls and +/// tool results of the replaced turns are not recoverable.`, followed by /// ` tool round-trips were folded.` only when `k` is not zero. fn format_compact_context_handoff(handoff: &ValidatedContextHandoff) -> String { format_compact_context_handoff_parts( @@ -635,7 +636,7 @@ fn format_compact_context_handoff(handoff: &ValidatedContextHandoff) -> String { /// referenced events and `folded` folded tool round-trips. fn format_compact_context_handoff_parts(id: &str, messages: usize, folded: usize) -> String { let mut rendered = format!( - "{CONTEXT_HANDOFF_START}{COMPACT_HANDOFF_ID_FIELD}{id} — {messages} earlier messages were moved out of this window. They are recoverable with {}(handoff_event_id=\"{id}\").", + "{CONTEXT_HANDOFF_START}{COMPACT_HANDOFF_ID_FIELD}{id} — {messages} earlier user and assistant messages were moved out of this window. They are recoverable with {}(handoff_event_id=\"{id}\"). The tool calls and tool results of the replaced turns are not recoverable.", crate::tools::TRANSCRIPT_HISTORY_LOOKUP_TOOL_NAME, ); if folded > 0 { diff --git a/src/chat/tests/handoff_view_tests.rs b/src/chat/tests/handoff_view_tests.rs index 2bc8c60d2..5c78668b7 100644 --- a/src/chat/tests/handoff_view_tests.rs +++ b/src/chat/tests/handoff_view_tests.rs @@ -115,8 +115,9 @@ fn stored_handoff(session: &session::ChatSession) -> String { /// `folded` tool round-trips, as the design spells it. fn expected_rendering(id: &str, events: usize, folded: usize) -> String { let mut text = format!( - "[context_handoff] handoff_event_id={id} — {events} earlier messages were moved out of this window. \ - They are recoverable with transcript_history_lookup(handoff_event_id=\"{id}\")." + "[context_handoff] handoff_event_id={id} — {events} earlier user and assistant messages were moved out of this window. \ + They are recoverable with transcript_history_lookup(handoff_event_id=\"{id}\"). \ + The tool calls and tool results of the replaced turns are not recoverable." ); if folded > 0 { text = format!("{text} {folded} tool round-trips were folded."); diff --git a/tests/chat_plain_compaction_cli.rs b/tests/chat_plain_compaction_cli.rs index 0a7ec2fc4..055244122 100644 --- a/tests/chat_plain_compaction_cli.rs +++ b/tests/chat_plain_compaction_cli.rs @@ -1712,7 +1712,7 @@ fn a_committed_json_answer_in_the_cold_window_is_referenced_by_the_handoff() { } /// The system-prompt paragraph a chat session states about handoffs (M1). -const HANDOFF_RULE: &str = "A message that starts with [context_handoff] means earlier turns of this session were moved out of this window; they still exist. Never treat the oldest visible message as the start of the session. Before answering a question about anything that may have happened earlier than the visible window, call transcript_history_lookup with that handoff's handoff_event_id and read the result; if the result contains another [context_handoff], look that one up too."; +const HANDOFF_RULE: &str = "A message that starts with [context_handoff] means earlier turns of this session were moved out of this window; their user and assistant messages still exist and can be read back, but the tool calls and tool results of those turns cannot be recovered. Never treat the oldest visible message as the start of the session. Before answering a question about anything that may have happened earlier than the visible window, call transcript_history_lookup with that handoff's handoff_event_id and read the result; if the result contains another [context_handoff], look that one up too."; /// The compact rendering of the stored `note`, as the provider must see it. fn expected_compact_handoff(note: &serde_json::Value) -> String { @@ -1720,8 +1720,9 @@ fn expected_compact_handoff(note: &serde_json::Value) -> String { let events = note["lookup"]["arguments"]["event_ids"].as_array().map_or(0, Vec::len); let folded = note["folded_tool_roundtrips"]["count"].as_u64().unwrap_or(0); let mut text = format!( - "[context_handoff] handoff_event_id={id} — {events} earlier messages were moved out of this window. \ - They are recoverable with transcript_history_lookup(handoff_event_id=\"{id}\")." + "[context_handoff] handoff_event_id={id} — {events} earlier user and assistant messages were moved out of this window. \ + They are recoverable with transcript_history_lookup(handoff_event_id=\"{id}\"). \ + The tool calls and tool results of the replaced turns are not recoverable." ); if folded > 0 { text = format!("{text} {folded} tool round-trips were folded."); From 574119729088d1a0e5300a003d76eac1ace2bcc9 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:16:40 +0400 Subject: [PATCH 0143/1567] fix(agent): write a document reference only for a tool output that was stored --- src/agent/tool_result_recording.rs | 11 ++++++++++ src/agent/turn_engine.rs | 22 +++++++++---------- src/agent/turn_tests/engine_surface.rs | 1 + src/agent/turn_tests/tool_result_recording.rs | 4 ++-- src/agent/turn_tests/turn_engine.rs | 1 + 5 files changed, 25 insertions(+), 14 deletions(-) diff --git a/src/agent/tool_result_recording.rs b/src/agent/tool_result_recording.rs index 733ac690f..3bb739df2 100644 --- a/src/agent/tool_result_recording.rs +++ b/src/agent/tool_result_recording.rs @@ -73,6 +73,9 @@ pub(crate) fn tool_result_inline_budget_for_history( token_derived_chars.max(MIN_TOOL_RESULT_INLINE_CHARS).min(absolute_cap) } +/// Status `persist_tool_output_document` reports for a stored document. +const PERSISTED_DOCUMENT_STATUS: &str = "persisted_document_backend"; + /// Compact a large tool result before inserting it into LLM history. /// /// This is the Phase-0 document-ingest spike: the full document backend is not @@ -97,6 +100,14 @@ pub(super) fn compact_tool_result_for_history_with_status( .last() .unwrap_or(0); let preview = &content[..boundary]; + // A reference is written only for a document that was stored. Without a + // stored copy the cut is stated plainly and nothing points at a document. + if status != PERSISTED_DOCUMENT_STATUS { + return format!( + "{preview}\n\n[output truncated: {boundary} of {} bytes shown; the full output was not stored]", + content.len() + ); + } let (document_id, sha256) = tool_output_document_id(tool_name, content); let chunk_count = crate::memory::chunker::chunk_markdown(content, TOOL_OUTPUT_DOCUMENT_CHUNK_TOKENS) .len() diff --git a/src/agent/turn_engine.rs b/src/agent/turn_engine.rs index bbf761501..494e84735 100644 --- a/src/agent/turn_engine.rs +++ b/src/agent/turn_engine.rs @@ -67,7 +67,7 @@ use crate::agent::tool_evidence::{claims_tool_evidence, strip_model_written_tool #[cfg(test)] use crate::agent::tool_result_recording::INTERRUPTED_TOOL_RESULT; use crate::agent::tool_result_recording::{ - ExecutedToolRecords, MAX_TOOL_RESULT_INLINE_CHARS, ToolResultRecorder, compact_tool_result_for_history_with_status, + ExecutedToolRecords, ToolResultRecorder, compact_tool_result_for_history_with_status, tool_result_inline_budget_for_history, }; use crate::agent::tool_scheduler::{ @@ -2249,20 +2249,18 @@ async fn run_turn_unguarded( } // P0-8: Keep history bounded and persist oversized outputs in the - // document layer when a runtime document sink is available. - let document_status = persist_tool_output_document( - document_ingest.as_ref(), - &call.name, - result, - MAX_TOOL_RESULT_INLINE_CHARS, - ) - .await - .unwrap_or("pending_document_backend"); + // document layer when a runtime document sink is available. The + // storage threshold is the same budget the history cut uses, so a + // result is stored exactly when it is cut. + let max_inline_chars = + tool_result_inline_budget_for_history(&call.name, executed.history(), reserved_config.as_ref()); + let document_status = + persist_tool_output_document(document_ingest.as_ref(), &call.name, result, max_inline_chars) + .await + .unwrap_or("pending_document_backend"); // FIX-P2-02: record the status so the native-history branch can reuse // it without persisting the same document a second time. document_statuses.push(document_status); - let max_inline_chars = - tool_result_inline_budget_for_history(&call.name, executed.history(), reserved_config.as_ref()); let truncated_result = compact_tool_result_for_history_with_status(&call.name, result, max_inline_chars, document_status); let _ = writeln!( diff --git a/src/agent/turn_tests/engine_surface.rs b/src/agent/turn_tests/engine_surface.rs index 068319161..657582a76 100644 --- a/src/agent/turn_tests/engine_surface.rs +++ b/src/agent/turn_tests/engine_surface.rs @@ -11,6 +11,7 @@ )] use super::*; +use crate::agent::tool_result_recording::MAX_TOOL_RESULT_INLINE_CHARS; #[tokio::test] async fn run_tool_call_loop_executes_read_only_tools_with_bounded_parallelism() { diff --git a/src/agent/turn_tests/tool_result_recording.rs b/src/agent/turn_tests/tool_result_recording.rs index d52551a76..47175376e 100644 --- a/src/agent/turn_tests/tool_result_recording.rs +++ b/src/agent/turn_tests/tool_result_recording.rs @@ -59,7 +59,7 @@ fn compact_tool_result_for_history_emits_document_reference_for_large_output() { "shell", &content, MAX_TOOL_RESULT_INLINE_CHARS, - "pending_document_backend", + "persisted_document_backend", ); assert!(compacted.len() < content.len() + 512); @@ -67,7 +67,7 @@ fn compact_tool_result_for_history_emits_document_reference_for_large_output() { assert!(compacted.contains("document_id: tool-output:shell:")); assert!(compacted.contains("source: tool_output")); assert!(compacted.contains("vector_anchor: vector://tool-output:shell:")); - assert!(compacted.contains("status: pending_document_backend")); + assert!(compacted.contains("status: persisted_document_backend")); assert!(compacted.contains(&format!("inline_preview_bytes: {MAX_TOOL_RESULT_INLINE_CHARS}"))); } diff --git a/src/agent/turn_tests/turn_engine.rs b/src/agent/turn_tests/turn_engine.rs index b3e83452e..1f6fc88b0 100644 --- a/src/agent/turn_tests/turn_engine.rs +++ b/src/agent/turn_tests/turn_engine.rs @@ -10,6 +10,7 @@ clippy::unreadable_literal )] use super::*; +use crate::agent::tool_result_recording::MAX_TOOL_RESULT_INLINE_CHARS; use crate::agent::turn_tests::{ CONTEXT_BUDGET_FIXTURE_RESERVE_TOKENS, DelayTool, NativeScriptedProvider, RecordingTool, RefreshCountingTool, ScriptedProvider, SystemSummaryProvider, WIDE_SCHEMA_TOOL_BODY_MARKER, WideSchemaTool, business_tool_specs_of, From 7e7cbc7d686dd069ba9144429b2f82d33440fd7e Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:17:31 +0400 Subject: [PATCH 0144/1567] fix(agent): stop dropping recalled memories and documents older than an hour --- src/agent/context_recall.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/agent/context_recall.rs b/src/agent/context_recall.rs index 9cdf9e512..c0d3ea17c 100644 --- a/src/agent/context_recall.rs +++ b/src/agent/context_recall.rs @@ -255,6 +255,9 @@ pub(crate) async fn build_context_with_scope( build_semantic_context(mem, user_msg, min_relevance_score, scope_ctx, false, None, None, None).await } +/// Whether `timestamp` is within the recent-events window. Applies only to the +/// session and shared-event blocks; stored memories and documents have no age +/// cut-off. fn fresh_timestamp(timestamp: &str) -> bool { chrono::DateTime::parse_from_rfc3339(timestamp) .ok() @@ -280,7 +283,7 @@ async fn build_semantic_context( user_msg: &str, min_relevance_score: f64, scope_ctx: Option<&MemoryWriteContext>, - fresh_only: bool, + scoped_prompt: bool, excluded_key: Option<&str>, excluded_event: Option<&str>, child: Option<&ChildRecallGate<'_>>, @@ -297,13 +300,12 @@ async fn build_semantic_context( .unwrap_or_default() .into_iter() .filter(|entry| entry.score.map_or(true, |score| score >= min_relevance_score)) - .filter(|entry| !fresh_only || fresh_timestamp(&entry.timestamp)) .filter(|entry| excluded_key != Some(entry.key.as_str())) .filter(|entry| excluded_event.is_none() || entry.source_event_id.as_deref() != excluded_event) .filter(|entry| !unscoped_remote_hit(entry.origin, entry.source_event_id.as_deref())) .map(|entry| (entry.id, entry.key, entry.content, entry.source_event_id)) .collect::>(); - let entries = if fresh_only && scored_entries.is_empty() { + let entries = if scoped_prompt && scored_entries.is_empty() { // When scored recall has no matches, scoped prompt reads also use the // repository's bounded keyword contract, independent of decision selection. // Its hits have no semantic score: raw BM25 ranks are not comparable @@ -358,7 +360,6 @@ async fn build_semantic_context( }) .unwrap_or_default() .into_iter() - .filter(|hit| fresh_timestamp(&hit.created_at)) .filter(|hit| excluded_key != Some(hit.key.as_str())) .filter(|hit| excluded_event.is_none() || hit.source_event_id.as_deref() != excluded_event) .map(|hit| { @@ -888,7 +889,6 @@ async fn build_agent_context( current_session_turns.retain(|turn| fresh_timestamp(&turn.timestamp) && (record || turn.role != "user")); current_session_events.retain(|event| fresh_timestamp(&event.created_at) && (record || event.role != "user")); shared_events.retain(|event| fresh_timestamp(&event.created_at) && (record || event.role != "user")); - document_results.retain(|result| fresh_timestamp(&result.chunk.created_at)); } // FIX-P2-02: hard-filter untrusted external content copies (web_fetch / // http_request / file_read ingests) out of the trusted recall context before From 018613e103a29f272c86cbb80d08f20701cc36f7 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:27:39 +0400 Subject: [PATCH 0145/1567] fix(agent): give the model the current date and time in the live user message --- src/agent/embedded_turn.rs | 1 + src/agent/entry/section_2.rs | 3 ++- src/agent/turn_contracts.rs | 13 +++++++++++++ src/channels/turn.rs | 1 + src/chat/run/provider_turn.rs | 3 ++- src/gateway/api/sessions/section_1.rs | 3 ++- src/gateway/implementation/section_2.rs | 3 ++- src/runtime/child_turn.rs | 4 +--- src/session_worker/runner/run.rs | 5 ++++- 9 files changed, 28 insertions(+), 8 deletions(-) diff --git a/src/agent/embedded_turn.rs b/src/agent/embedded_turn.rs index 60df621fc..66b3d469d 100644 --- a/src/agent/embedded_turn.rs +++ b/src/agent/embedded_turn.rs @@ -494,6 +494,7 @@ async fn run_work( enriched.push('\n'); } enriched.push_str(input); + crate::agent::turn_contracts::push_current_time_tail(&mut enriched); history.push(crate::agent::turn_contracts::inbound_user_message_owned(enriched)); let mut history = HistoryWriteback { target: &mut agent.history, diff --git a/src/agent/entry/section_2.rs b/src/agent/entry/section_2.rs index fa2dad093..4e7c50b43 100644 --- a/src/agent/entry/section_2.rs +++ b/src/agent/entry/section_2.rs @@ -741,11 +741,12 @@ pub(crate) async fn run_with_runtime_envelope( ) .await; let context = mem_context.preamble.clone(); - let enriched = if context.is_empty() { + let mut enriched = if context.is_empty() { msg.clone() } else { format!("{context}{msg}") }; + crate::agent::turn_contracts::push_current_time_tail(&mut enriched); let mut history = vec![ ChatMessage::system(&system_prompt), diff --git a/src/agent/turn_contracts.rs b/src/agent/turn_contracts.rs index 109a4e034..509e487ce 100644 --- a/src/agent/turn_contracts.rs +++ b/src/agent/turn_contracts.rs @@ -229,6 +229,19 @@ pub(crate) fn inbound_user_message(text: &str) -> ChatMessage { ChatMessage::user(neutralize_reserved_markers(text)) } +/// Appends the current local date and time to the end of the live user message +/// the provider receives. The system prompt carries only the time zone, so its +/// bytes stay identical between turns; the clock rides in the one message that +/// is new every turn. +pub(crate) fn push_current_time_tail(content: &mut String) { + use std::fmt::Write as _; + let _ = write!( + content, + "\n\n[Current date and time: {}]", + chrono::Local::now().format("%A, %Y-%m-%d %H:%M %:z") + ); +} + /// Fresh inbound text already owned by the caller. Preserve its allocation /// unless a reserved opening needs the same escape as borrowed input. pub(crate) fn inbound_user_message_owned(text: String) -> ChatMessage { diff --git a/src/channels/turn.rs b/src/channels/turn.rs index f4ba9a663..5edd09787 100644 --- a/src/channels/turn.rs +++ b/src/channels/turn.rs @@ -817,6 +817,7 @@ pub(super) async fn run_channel_turn( last_turn.content.push('\n'); last_turn.content.push_str(context); } + crate::agent::turn_contracts::push_current_time_tail(&mut last_turn.content); } } diff --git a/src/chat/run/provider_turn.rs b/src/chat/run/provider_turn.rs index c5cd8a260..57cc5afde 100644 --- a/src/chat/run/provider_turn.rs +++ b/src/chat/run/provider_turn.rs @@ -142,11 +142,12 @@ let routing_input = admitted_binding.routing_input().to_owned(); let mem_context = admitted_binding.recalled_context(mem.as_ref()).await; let context = mem_context.preamble.clone(); - let enriched = if context.is_empty() { + let mut enriched = if context.is_empty() { user_input_for_prompt.clone() } else { format!("{context}{user_input_for_prompt}") }; + crate::agent::turn_contracts::push_current_time_tail(&mut enriched); // Build system prompt with skill selection let selected_skills = admitted_binding.prompt_skills()?; diff --git a/src/gateway/api/sessions/section_1.rs b/src/gateway/api/sessions/section_1.rs index 5bb6bb469..48202025e 100644 --- a/src/gateway/api/sessions/section_1.rs +++ b/src/gateway/api/sessions/section_1.rs @@ -824,11 +824,12 @@ async fn run_console_runtime_turn( crate::agent::context_recall::RECALL_CONTEXT_BUDGET, ) .await; - let enriched_message = if mem_context.preamble.is_empty() { + let mut enriched_message = if mem_context.preamble.is_empty() { visible_message.to_string() } else { format!("{}{}", mem_context.preamble, visible_message) }; + crate::agent::turn_contracts::push_current_time_tail(&mut enriched_message); // The stored event of each history message, index for index: none for the // system prompt, each stored turn's event, then the request's own event. diff --git a/src/gateway/implementation/section_2.rs b/src/gateway/implementation/section_2.rs index 16c66d15e..3f40d64ff 100644 --- a/src/gateway/implementation/section_2.rs +++ b/src/gateway/implementation/section_2.rs @@ -1224,11 +1224,12 @@ async fn run_gateway_chat_with_multimodal( crate::agent::context_recall::RECALL_CONTEXT_BUDGET, ) .await; - let enriched_message = if mem_context.preamble.is_empty() { + let mut enriched_message = if mem_context.preamble.is_empty() { message.to_string() } else { format!("{}{}", mem_context.preamble, message) }; + crate::agent::turn_contracts::push_current_time_tail(&mut enriched_message); let user_messages = vec![crate::agent::turn_contracts::inbound_user_message(&enriched_message)]; let image_marker_count = crate::multimodal::count_image_markers(&user_messages); diff --git a/src/runtime/child_turn.rs b/src/runtime/child_turn.rs index 46f0d7b3b..689d2a6e4 100644 --- a/src/runtime/child_turn.rs +++ b/src/runtime/child_turn.rs @@ -232,11 +232,9 @@ impl ChildSegmentTurn { input.content == self.proof.routing_input(), "child segment history differs from its admitted input" ); - if self.recalled_context.is_empty() { - return Ok(()); - } let mut enriched = self.recalled_context.clone(); enriched.push_str(&input.content); + crate::agent::turn_contracts::push_current_time_tail(&mut enriched); *input = crate::agent::turn_contracts::inbound_user_message(&enriched); Ok(()) } diff --git a/src/session_worker/runner/run.rs b/src/session_worker/runner/run.rs index 98feb77f5..63435d99a 100644 --- a/src/session_worker/runner/run.rs +++ b/src/session_worker/runner/run.rs @@ -1056,7 +1056,7 @@ async fn run_owned_manifest( } } if initial_input { - let user_task = if child_turn.is_some() { + let mut user_task = if child_turn.is_some() { raw_task.to_owned() } else { let shared_context = @@ -1067,6 +1067,9 @@ async fn run_owned_manifest( format!("{shared_context}{raw_task}") } }; + if child_turn.is_none() { + crate::agent::turn_contracts::push_current_time_tail(&mut user_task); + } segment_history.push(crate::agent::turn_contracts::inbound_user_message(&user_task)); } if let (Some(turn), Some(segments)) = (child_turn.as_ref(), child_segments.as_ref()) { From 4cce08d94de8e75f6dc9820d75eeb48634c56c19 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:28:41 +0400 Subject: [PATCH 0146/1567] fix(agent): drop the one-hour age cut-off from selected custom memory retrieval --- src/agent/memory_loader.rs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/agent/memory_loader.rs b/src/agent/memory_loader.rs index 88d29e8f0..789bb65a0 100644 --- a/src/agent/memory_loader.rs +++ b/src/agent/memory_loader.rs @@ -163,15 +163,10 @@ impl Memory for SelectedMemoryView<'_> { && hit.source_event_id.as_ref().is_none_or(|id| id.len() <= 128)), "selected Memory backend exceeded its result contract" ); - let now = chrono::Utc::now(); hits.retain(|hit| { self.excluded_key != Some(hit.key.as_str()) && (self.excluded_event.is_none() || hit.source_event_id.as_deref() != self.excluded_event) && !hit.content.trim().is_empty() - && chrono::DateTime::parse_from_rfc3339(&hit.created_at) - .ok() - .and_then(|created| u64::try_from(now.signed_duration_since(created).num_milliseconds()).ok()) - .is_some_and(|age| age <= crate::tools::capability::turn_state::STALE_ARTIFACT_MS) }); self.reserved.fetch_sub(limit - hits.len(), Ordering::AcqRel); let entries = hits From 89a2dfd49b7d49d2a0a386fdacfa6835f51358f5 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:31:46 +0400 Subject: [PATCH 0147/1567] fix(agent): rank recalled memories with a bounded recency boost --- src/agent/context_recall.rs | 41 +++++++++++++++++++++++++++++++++++-- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/src/agent/context_recall.rs b/src/agent/context_recall.rs index c0d3ea17c..8eab77b98 100644 --- a/src/agent/context_recall.rs +++ b/src/agent/context_recall.rs @@ -3,6 +3,7 @@ use crate::agent::response_guard::strip_quoted_fabricated_tool_markers; use crate::memory; use crate::memory::branch_copy::{CONTEXT_SWITCH_EVENT_TYPE, is_branch_copy}; use crate::memory::principal::{MemoryWriteContext, OwnerPrincipal, Role}; +use crate::memory::MemoryEntry; use crate::memory::traits::MemoryEntryOrigin; use crate::memory::{ ConversationTurn, DocumentSearchResult, Memory, MemoryPrincipal, MessageEvent, MessageEventSource, @@ -255,6 +256,37 @@ pub(crate) async fn build_context_with_scope( build_semantic_context(mem, user_msg, min_relevance_score, scope_ctx, false, None, None, None).await } +/// Rows recalled into the prompt per turn. +const RECALL_LIMIT: usize = 5; + +/// Candidates read from the store before recency re-ranking: three times the +/// limit, the same depth the store already scans per requested row. +const RECALL_CANDIDATES: usize = RECALL_LIMIT * 3; + +/// Largest relative boost recency gives a row's relevance score. +const RECENCY_MAX_BOOST: f64 = 0.1; + +/// Age in days over which the recency boost halves. +const RECENCY_HALF_LIFE_DAYS: f64 = 30.0; + +/// Orders candidates by `score * (1 + RECENCY_MAX_BOOST * 0.5^(age_days / +/// RECENCY_HALF_LIFE_DAYS))`: a row stored now gets up to a 10% boost, one +/// 30 days old 5%, a year old about 0%. The boost is relative, so it works on +/// both the hybrid score (0..1) and the raw keyword score. Nothing is excluded +/// by age, a row with an unreadable timestamp gets no boost, and equal +/// adjusted scores keep the store's order (the sort is stable). +fn rank_with_recency(entries: &mut [MemoryEntry]) { + let now = chrono::Utc::now(); + let adjusted = |entry: &MemoryEntry| -> f64 { + let age_days = chrono::DateTime::parse_from_rfc3339(&entry.timestamp) + .map(|created| now.signed_duration_since(created).num_seconds().max(0) as f64 / 86_400.0) + .ok(); + let boost = age_days.map_or(0.0, |age| RECENCY_MAX_BOOST * 0.5_f64.powf(age / RECENCY_HALF_LIFE_DAYS)); + entry.score.unwrap_or(0.0) * (1.0 + boost) + }; + entries.sort_by(|a, b| adjusted(b).total_cmp(&adjusted(a))); +} + /// Whether `timestamp` is within the recent-events window. Applies only to the /// session and shared-event blocks; stored memories and documents have no age /// cut-off. @@ -294,8 +326,8 @@ async fn build_semantic_context( // The current turn is already in the live input; its semantic promotion // must not count as historical recall or trigger a presentation callback. - let scored_entries = mem - .recall_with_context(user_msg, 5, None, scope_ctx) + let mut candidates = mem + .recall_with_context(user_msg, RECALL_CANDIDATES, None, scope_ctx) .await .unwrap_or_default() .into_iter() @@ -303,6 +335,11 @@ async fn build_semantic_context( .filter(|entry| excluded_key != Some(entry.key.as_str())) .filter(|entry| excluded_event.is_none() || entry.source_event_id.as_deref() != excluded_event) .filter(|entry| !unscoped_remote_hit(entry.origin, entry.source_event_id.as_deref())) + .collect::>(); + rank_with_recency(&mut candidates); + candidates.truncate(RECALL_LIMIT); + let scored_entries = candidates + .into_iter() .map(|entry| (entry.id, entry.key, entry.content, entry.source_event_id)) .collect::>(); let entries = if scoped_prompt && scored_entries.is_empty() { From 901237ae30d047f725019f83682c75cc45e40778 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:53:42 +0400 Subject: [PATCH 0148/1567] fix(agent): decide kept messages by tokens and cap reserves by window share A switch keeps the newest messages word for word while they fit a share of the window, with keep_recent_messages as an upper bound, so a short history of large messages folds on a small window. The reply reserve is capped at a quarter of the window and reply plus tool surface at half; the chat pre-turn check and the engine preflight derive the reserved budget from one function. --- docs/configuration.md | 1 + docs/unified-turn-context.md | 13 ++++++ src/agent/budget_inputs.rs | 73 +++++++++++++++++++++++++++++++++ src/agent/compaction.rs | 5 ++- src/agent/context_budget.rs | 12 +----- src/agent/mod.rs | 1 + src/chat/compaction.rs | 3 +- src/config/schema/agent.rs | 6 ++- src/providers/context_window.rs | 6 ++- 9 files changed, 105 insertions(+), 15 deletions(-) create mode 100644 src/agent/budget_inputs.rs diff --git a/docs/configuration.md b/docs/configuration.md index b8293c6fd..a9eec63b1 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -87,6 +87,7 @@ and the module-gate family are absorbed on load; they are not live switches. | `[scheduler]` | `max_tasks = 64`; `claim_lease_secs = 90` | | `[agent]` | `compact_context = false`; `read_only_tool_concurrency_window = 2`; `priority_scheduling_enabled = false`; `low_priority_tools = ["sessions_spawn", "delegate"]` | | `[agent.compaction]` | `mode = "switch"`; `reserve_tokens = 4096`; `keep_recent_messages = 12`; `memory_flush = true`; `max_context_tokens = 128000` | +| `[agent.compaction]` window rules | `reserve_tokens` is an upper bound: the reply reserve used is `min(reserve_tokens, window / 4)`, and the reply reserve plus the measured tool surface never exceed `window / 2` (never below `reserve_tokens` itself). `keep_recent_messages` is an upper bound on the messages a `switch` keeps word for word: the newest messages are kept while together they stay within `min(window / 4, (window - reserve) / 2)` tokens, and the newest message is always kept, so a short history of large messages is folded. `max_context_tokens` is the window | | `[agent.compaction.os_paging]` | `eviction_threshold = 0.70`; `proactive_retrieval = true`; `max_recalled_pages = 10`; `retrieval_injection_role = "system"`; `keep_recent_messages = 12`. Exact `switch` handoffs skip paging | | `[sessions_spawn]` | `default_mode = "task"`; `process_memory_strategy = "shared_fabric"`; `worker_workspace_root` unset; `cleanup_on_complete = true` | | `[chat]` | `max_concurrent_visible_turns = 2` | diff --git a/docs/unified-turn-context.md b/docs/unified-turn-context.md index 2ec3ec889..e9839ef31 100644 --- a/docs/unified-turn-context.md +++ b/docs/unified-turn-context.md @@ -144,6 +144,19 @@ deleted. A later rollover can reference the prior handoff event exactly, so repeated switches form an auditable generation chain within the same durable session. +The messages a switch keeps word for word are decided by tokens. Newest +first, a non-system message is kept while the kept messages together stay +within `min(window / 4, (window - reserve) / 2)` tokens (the newest message is +always kept), and `keep_recent_messages` (default 12) is the upper bound on +their count. A short history of large messages therefore folds on a small +window; on a large window with ordinary messages the count of 12 still applies. +The reply reserve is `min(reserve_tokens, window / 4)` and, together with the +measured tool surface, never exceeds `window / 2`; the terminal chat pre-turn +check and the engine preflight both derive that budget from one function +(`agent::budget_inputs::reserved_budget_config`). The system message and the +current request cannot be folded, so a window that cannot hold them still ends +in a per-request trim. + The provider view renders each note as one line: `[context_handoff] handoff_event_id= -- earlier user and assistant messages were moved out of this window. They are recoverable with diff --git a/src/agent/budget_inputs.rs b/src/agent/budget_inputs.rs new file mode 100644 index 000000000..f65b98106 --- /dev/null +++ b/src/agent/budget_inputs.rs @@ -0,0 +1,73 @@ +//! Window-relative budget inputs shared by the turn engine preflight and the +//! chat front end. +//! +//! Three fixed numbers used to be applied whatever the context window was: the +//! reply reserve, the measured tool surface and the count of messages a +//! `switch` keeps word for word. On a small window they consumed it. Each is +//! now bounded by a share of the window, and an operator's explicit value is +//! honoured as an upper bound. + +use crate::agent::context_budget::{budgeted_tokens, estimate_history_tokens_with_source}; +use crate::config::AgentCompactionConfig; +use crate::providers::ChatMessage; + +/// The reply reserve never exceeds `1 / REPLY_RESERVE_WINDOW_DIVISOR` of the window. +pub(crate) const REPLY_RESERVE_WINDOW_DIVISOR: usize = 4; + +/// The reply reserve plus the tool surface never exceed +/// `1 / TOTAL_RESERVE_WINDOW_DIVISOR` of the window. +pub(crate) const TOTAL_RESERVE_WINDOW_DIVISOR: usize = 2; + +/// The messages a switch keeps word for word occupy at most +/// `1 / KEEP_RECENT_WINDOW_DIVISOR` of the window. +pub(crate) const KEEP_RECENT_WINDOW_DIVISOR: usize = 4; + +/// The reply reserve for a window: the configured value, bounded by its share +/// of the window. +pub(crate) const fn capped_reply_reserve(max_context_tokens: usize, reserve_tokens: usize) -> usize { + let cap = max_context_tokens / REPLY_RESERVE_WINDOW_DIVISOR; + if reserve_tokens < cap { reserve_tokens } else { cap } +} + +/// The config one request is budgeted with: the reply reserve plus +/// `tool_tokens` (the budgeted tool surface), the sum bounded by its share of +/// the window and never below the configured reserve itself. +/// +/// The turn engine preflight and the chat pre-turn check both derive their +/// budget here, so the same inputs give the same limit. +pub(crate) fn reserved_budget_config(config: &AgentCompactionConfig, tool_tokens: usize) -> AgentCompactionConfig { + let total_cap = (config.max_context_tokens / TOTAL_RESERVE_WINDOW_DIVISOR).max(config.reserve_tokens); + AgentCompactionConfig { + reserve_tokens: config.reserve_tokens.saturating_add(tool_tokens).min(total_cap), + ..config.clone() + } +} + +/// Token budget of the messages kept word for word. +fn keep_recent_token_budget(config: &AgentCompactionConfig) -> usize { + let window_share = config.max_context_tokens / KEEP_RECENT_WINDOW_DIVISOR; + let input_share = config.max_context_tokens.saturating_sub(config.reserve_tokens) / 2; + window_share.min(input_share) +} + +/// How many of the newest `non_system` messages a switch keeps word for word. +/// +/// Newest first, a message is kept while the kept messages stay within a share +/// of the window; the newest one is always kept. `keep_recent_messages` is an +/// upper bound, so a short history of large messages folds, and a long one +/// keeps at most the configured count. +pub(crate) fn effective_keep_recent_messages(non_system: &[ChatMessage], config: &AgentCompactionConfig) -> usize { + let cap = config.keep_recent_messages.max(1).min(non_system.len()); + let budget = keep_recent_token_budget(config); + let mut used = 0usize; + let mut kept = 0usize; + for message in non_system.iter().rev().take(cap) { + let tokens = budgeted_tokens(estimate_history_tokens_with_source(std::slice::from_ref(message))); + used = used.saturating_add(tokens); + if kept >= 1 && used > budget { + break; + } + kept += 1; + } + kept +} diff --git a/src/agent/compaction.rs b/src/agent/compaction.rs index 12696ac1d..47d42df34 100644 --- a/src/agent/compaction.rs +++ b/src/agent/compaction.rs @@ -2148,7 +2148,10 @@ pub(crate) async fn build_configurable_compaction_patch_with_source_history( return Ok(CompactionBuild::NotNeeded); } - let requested_keep_recent = config.keep_recent_messages.max(1).min(non_system_count); + let requested_keep_recent = crate::agent::budget_inputs::effective_keep_recent_messages( + source_history.get(start..).unwrap_or_default(), + config, + ); let requested_compact_count = non_system_count.saturating_sub(requested_keep_recent); if requested_compact_count == 0 { return Ok(CompactionBuild::NotNeeded); diff --git a/src/agent/context_budget.rs b/src/agent/context_budget.rs index b094d0e51..7a6372cce 100644 --- a/src/agent/context_budget.rs +++ b/src/agent/context_budget.rs @@ -186,12 +186,7 @@ pub(crate) fn reserve_request_tool_surface( config: &crate::config::AgentCompactionConfig, tool_surface: crate::agent::turn_context::RequestToolMeasurement, ) -> crate::config::AgentCompactionConfig { - crate::config::AgentCompactionConfig { - reserve_tokens: config - .reserve_tokens - .saturating_add(budgeted_request_tool_tokens(tool_surface)), - ..config.clone() - } + crate::agent::budget_inputs::reserved_budget_config(config, budgeted_request_tool_tokens(tool_surface)) } /// The tool-surface reserve of a chat session's most recent request, shared @@ -225,10 +220,7 @@ impl ToolSurfaceReserve { &self, config: &crate::config::AgentCompactionConfig, ) -> crate::config::AgentCompactionConfig { - crate::config::AgentCompactionConfig { - reserve_tokens: config.reserve_tokens.saturating_add(self.tokens()), - ..config.clone() - } + crate::agent::budget_inputs::reserved_budget_config(config, self.tokens()) } /// Context tokens one request occupies: the history estimate plus the diff --git a/src/agent/mod.rs b/src/agent/mod.rs index 32e0eac87..649da3e40 100644 --- a/src/agent/mod.rs +++ b/src/agent/mod.rs @@ -4,6 +4,7 @@ pub(crate) mod automation; pub(crate) mod channel_approval; pub mod classifier; pub(crate) mod compaction; +pub(crate) mod budget_inputs; pub(crate) mod context_budget; pub(crate) mod context_paging; pub(crate) mod context_preflight; diff --git a/src/chat/compaction.rs b/src/chat/compaction.rs index f45ba0358..99e64df67 100644 --- a/src/chat/compaction.rs +++ b/src/chat/compaction.rs @@ -116,7 +116,8 @@ pub(super) fn manual_compact_has_compactable( compaction_config: &crate::config::AgentCompactionConfig, ) -> bool { let system_count = usize::from(source_history.first().is_some_and(|m| m.role == "system")); - source_history.len().saturating_sub(system_count) > compaction_config.keep_recent_messages.max(1) + let non_system = source_history.get(system_count..).unwrap_or_default(); + non_system.len() > crate::agent::budget_inputs::effective_keep_recent_messages(non_system, compaction_config) } /// Feedback when `/compact` finds no durable transcript to bind to (D7). diff --git a/src/config/schema/agent.rs b/src/config/schema/agent.rs index 1138ab3d9..38ca9c8ac 100644 --- a/src/config/schema/agent.rs +++ b/src/config/schema/agent.rs @@ -53,10 +53,12 @@ pub struct AgentCompactionConfig { /// Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`). #[serde(default)] pub mode: AgentCompactionMode, - /// Tokens reserved for the next model response. + /// Tokens reserved for the next model response; an upper bound, capped at + /// a quarter of the window. #[serde(default = "default_agent_compaction_reserve_tokens")] pub reserve_tokens: usize, - /// Number of recent non-system messages to keep after compaction. + /// Upper bound on the recent non-system messages kept word for word after + /// compaction; the token share of the window may keep fewer. #[serde(default = "default_agent_compaction_keep_recent_messages")] pub keep_recent_messages: usize, /// Run memory flush extraction before legacy summary/truncation modes. diff --git a/src/providers/context_window.rs b/src/providers/context_window.rs index 9b42b90b7..9ff705acb 100644 --- a/src/providers/context_window.rs +++ b/src/providers/context_window.rs @@ -291,7 +291,7 @@ const fn cap_to_kernel(tokens: usize) -> CappedContext { } const fn resolved( - config: AgentCompactionConfig, + mut config: AgentCompactionConfig, max_context_source: ContextWindowSource, model_context_tokens: Option, requested_context_tokens: Option, @@ -299,6 +299,10 @@ const fn resolved( selected_provider: String, selected_model: String, ) -> EffectiveCompactionConfig { + // The reply reserve is bounded by its share of the window, so a small + // window is not consumed by the fixed default. + config.reserve_tokens = + crate::agent::budget_inputs::capped_reply_reserve(config.max_context_tokens, config.reserve_tokens); EffectiveCompactionConfig { config, max_context_source, From 0e3462f62a4befe738a1bae914521bee94a07650 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:56:07 +0400 Subject: [PATCH 0149/1567] feat(memory): store tool calls and tool results in the durable log by default --- docs/configuration.md | 6 +- docs/migration-unreleased.md | 14 ++ src/agent/mod.rs | 1 + src/agent/tool_event_recording.rs | 171 ++++++++++++++++++ src/agent/turn_engine.rs | 13 ++ src/config/init/templates.rs | 6 +- src/config/init/tests.rs | 10 +- src/config/schema/memory.rs | 6 +- src/config/schema/tests/memory.rs | 2 +- src/memory/fabric.rs | 16 +- src/memory/sqlite/sync_journal.rs | 4 + src/memory/sqlite/sync_snapshot.rs | 2 +- .../child_source/golden_effective_config.json | 2 +- tests/fixtures/config-schema.json | 2 +- 14 files changed, 236 insertions(+), 19 deletions(-) create mode 100644 src/agent/tool_event_recording.rs diff --git a/docs/configuration.md b/docs/configuration.md index a9eec63b1..7736a75a8 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -126,7 +126,7 @@ and the module-gate family are absorbed on load; they are not live switches. | `[channels_config.qq]` | `app_id` and `app_secret` required; `allowed_users = []`; `mention_only = false` | | `[channels_config.ramflux]` | `socket_path` unset; `authorization_mode = "follow_rf"`; `max_in_flight_per_conversation = 1`; `on_new_message = "queue"`; `turn_wall_clock_secs = 120`; `encrypt_at_rest = true`; `surface_limits.max_blocks = 32`, `max_actions = 16`, `max_bytes = 65536`; `attachment_fetch.max_bytes = 5242880`, `max_per_turn = 4`; `allowed_block_types` the built-in surface set (Text, Markdown, Heading, KeyValue, Metric, List, TableFallback, Form, Input, Select, Progress, LogStream, Warning, Error, Success, Approval, ActionGroup, FilePreview, Fallback); `accounts = {}`. An account may set `system_prompt_file`, `model`, `provider`, `scope_profile`, `cross_conversation_retrieval` | | `[memory]` | `backend = "sqlite"`; `auto_save = true`; `acl_enabled = false`; `legacy_conversation_turns_visible = true`; `archive_after_days = 7`; `purge_after_days = 30`; `conversation_retention_days = 3`; `daily_retention_days = 7`; `embedding_provider = "local"`; `embedding_model = "prx-local-hash-v1"`; `embedding_dimensions = 384`; `vector_weight = 0.7`; `keyword_weight = 0.3`; `min_relevance_score = 0.4`; `embedding_cache_size = 10000`; `vector_candidate_cap = 2000`; `auto_hydrate = true`; `sqlite_open_timeout_secs` unset; `sqlite_read_pool_size` unset; `lucid_cmd` unset (`lucid`); `lucid_budget` unset (200); `lucid_recall_timeout_ms = 5000`; `lucid_store_timeout_ms = 3000`; `lucid_local_hit_threshold = 3`; `lucid_failure_cooldown_ms = 60000` | -| `[memory.events]` | `record_user_messages = true`; `record_assistant_messages = true`; `record_tool_events = false` | +| `[memory.events]` | `record_user_messages = true`; `record_assistant_messages = true`; `record_tool_events = true` | | `[memory.semantic]` | `auto_promote_user_messages = true`; `auto_promote_assistant_messages = false`; `min_chars = 30` | | `[[identity_bindings]]` | `user_id`, `channel`, `channel_account` required; `display_name` unset | | `[[user_policies]]` | `user_id` required; `role = "guest"`; `projects = []`; `visibility_ceiling = "private"`; `blocked_patterns = []` | @@ -638,7 +638,7 @@ auto_save = true [memory.events] record_user_messages = true record_assistant_messages = true -record_tool_events = false +record_tool_events = true [memory.semantic] auto_promote_user_messages = true @@ -1300,7 +1300,7 @@ PRX treats `chat`, `agent`, `gateway`, `channel`, `delegate`, and `sessions_spaw - `auto_save` no longer controls the base message log; it gates semantic promotion for backward compatibility. - The embedded `Agent` API additionally honors `semantic.auto_promote_user_messages` and `semantic.min_chars`. It promotes only original user input, using an owner-scoped `user_msg:` key and source session/event metadata. It leaves legacy `user_msg` entries intact. Unsupported owner-aware writes are skipped with a content-free warning; model execution continues. See [embedded API admission](unified-turn-context.md#embedded-agent-api-admission). -`[memory.events]` controls raw/quasi-raw event recording. Turning it off stops new fabric event rows for entrypoints wired through `MemoryFabric`. +`[memory.events]` controls raw/quasi-raw event recording. Turning it off stops new fabric event rows for entrypoints wired through `MemoryFabric`. `record_tool_events` (default `true`) controls the `tool.call.recorded` and `tool.result.recorded` rows: one per tool call and one per result, with the run, round and call id in the payload, the redacted inline result text, and the document reference when an oversized output was stored. They are not chat messages and are not sent on the gateway sync stream. `[memory.semantic]` controls promotion from event/message content into durable semantic memory. Assistant promotion is disabled by default to reduce noisy self-generated memory. diff --git a/docs/migration-unreleased.md b/docs/migration-unreleased.md index d1a31fdaf..bbf3ffc58 100644 --- a/docs/migration-unreleased.md +++ b/docs/migration-unreleased.md @@ -177,3 +177,17 @@ macOS keeps the documented process-group limitation. Model-backed memory and document retrieval reserve a versioned 100 ms decision-overhead estimate; local catalog discovery keeps zero model overhead. Actual paid requests still use the physical accounting ledger. No database schema migration is introduced. + +## Tool calls and tool results are stored + +`[memory.events] record_tool_events` now defaults to `true`. With it on, every +tool call and every tool result of a turn is appended to `message_events` as a +`tool.call.recorded` / `tool.result.recorded` row (role `tool`) carrying the run, +the round and the call id in its payload. A result keeps the inline text up to +the inline limit; above it the row holds the preview and the document +reference of the stored tool output. Stored text and arguments are redacted. +These rows are log-only: they are not `message.created`, so history loaders and +the handoff match ignore them, and the gateway sync stream carries nothing for +them. A config file that sets `record_tool_events` explicitly (including the +`false` that older generated templates wrote) keeps its value; set it to `true` +to start recording. No database schema migration is introduced. diff --git a/src/agent/mod.rs b/src/agent/mod.rs index 649da3e40..e34dfaa1d 100644 --- a/src/agent/mod.rs +++ b/src/agent/mod.rs @@ -32,6 +32,7 @@ pub(crate) mod send_admission; pub mod stream_buffer; pub mod terminal; pub(crate) mod tool_call_parser; +pub(crate) mod tool_event_recording; pub(crate) mod tool_evidence; pub(crate) mod tool_result_recording; pub(crate) mod tool_scheduler; diff --git a/src/agent/tool_event_recording.rs b/src/agent/tool_event_recording.rs new file mode 100644 index 000000000..3981a1926 --- /dev/null +++ b/src/agent/tool_event_recording.rs @@ -0,0 +1,171 @@ +//! Durable log rows for tool calls and tool results. +//! +//! Each call the model makes is appended to `message_events` when the round +//! dispatches it, and each result when the call returns. A pair shares the +//! run (the row's `run_id`), the round and the call id in its payload, so a +//! reader can match them without relying on row order. +//! +//! The rows use their own event types (`tool.call.recorded`, +//! `tool.result.recorded`) with role `tool`. They are not +//! `message.created`, so the next turn's history loaders, the handoff +//! provenance match and the sync projection all leave them alone. Whether +//! they are written is the `record_tool_events` setting of the fabric. +//! +//! Stored text is always the redacted form. A result keeps the inline text +//! the history keeps; above the inline limit the row carries the same +//! preview plus a document reference, and only when that document was +//! stored. + +use crate::agent::tool_call_parser::ParsedToolCall; +use crate::agent::tool_result_recording::{MAX_TOOL_RESULT_INLINE_CHARS, ObservedToolResult}; +use crate::memory::{MemoryFabric, MessageEventScope}; +use crate::providers::ToolCall; + +pub(crate) const TOOL_CALL_EVENT_TYPE: &str = "tool.call.recorded"; +pub(crate) const TOOL_RESULT_EVENT_TYPE: &str = "tool.result.recorded"; + +/// Status `persist_tool_output_document` reports for a stored document. +const STORED_DOCUMENT_STATUS: &str = "persisted_document_backend"; + +/// The id a call is paired by: the provider's call id, or `#` +/// for a call that has none (the same fallback the live notifications use). +pub(super) fn call_id_for(tool: &str, index: usize, native: &[ToolCall]) -> String { + native + .get(index) + .map(|call| call.id.clone()) + .filter(|id| !id.is_empty()) + .unwrap_or_else(|| format!("{tool}#{index}")) +} + +/// Cut `text` to at most `max_bytes` on a char boundary, saying so. +fn bounded(text: String, max_bytes: usize) -> String { + if text.len() <= max_bytes { + return text; + } + let mut end = max_bytes; + while end > 0 && !text.is_char_boundary(end) { + end -= 1; + } + let total = text.len(); + let shown = text.get(..end).unwrap_or_default(); + format!("{shown}\n[arguments truncated: {end} of {total} bytes shown]") +} + +/// Where one provider round writes its tool rows. +pub(super) struct RoundLog<'a> { + fabric: &'a MemoryFabric, + scope: &'a MessageEventScope, + round: usize, +} + +impl<'a> RoundLog<'a> { + /// `None` when the turn has no durable event sink. + pub(super) fn new(fabric: Option<&'a MemoryFabric>, scope: &'a MessageEventScope, round: usize) -> Option { + fabric.map(|fabric| Self { fabric, scope, round }) + } + + /// Append one `tool.call.recorded` row per call of the round. + pub(super) async fn calls(&self, calls: &[ParsedToolCall], native: &[ToolCall]) { + record_tool_calls(self.fabric, self.scope, self.round, calls, native).await; + } + + /// Append the `tool.result.recorded` row of one call. + pub(super) async fn result( + &self, + call_id: &str, + tool: &str, + outcome: &ObservedToolResult, + inline_text: &str, + document_status: &str, + ) { + record_tool_result( + self.fabric, + self.scope, + self.round, + (call_id, tool), + outcome, + inline_text, + document_status, + ) + .await; + } +} + +async fn record_tool_calls( + fabric: &MemoryFabric, + scope: &MessageEventScope, + round: usize, + calls: &[ParsedToolCall], + native: &[ToolCall], +) { + for (index, call) in calls.iter().enumerate() { + let call_id = call_id_for(&call.name, index, native); + let arguments = crate::agent::terminal::redact_persisted_json(call.arguments.clone()); + let payload = serde_json::json!({ + "schema_version": 1, + "run_id": scope.run_id, + "round": round, + "index": index, + "call_id": call_id, + "tool": call.name, + "arguments": arguments, + }); + let content = bounded(arguments.to_string(), MAX_TOOL_RESULT_INLINE_CHARS); + append( + fabric, + scope, + TOOL_CALL_EVENT_TYPE, + format!("{} {content}", call.name), + payload, + ) + .await; + } +} + +/// `inline_text` is the +/// compacted result the history carries (preview plus reference when the +/// output was stored); `document_status` is what the document store reported. +async fn record_tool_result( + fabric: &MemoryFabric, + scope: &MessageEventScope, + round: usize, + (call_id, tool): (&str, &str), + outcome: &ObservedToolResult, + inline_text: &str, + document_status: &str, +) { + let document = (document_status == STORED_DOCUMENT_STATUS).then(|| { + let (document_id, sha256) = crate::agent::document_ingest::tool_output_document_id(tool, &outcome.content); + serde_json::json!({ "document_id": document_id, "content_sha256": sha256, "source": "tool_output" }) + }); + let payload = serde_json::json!({ + "schema_version": 1, + "run_id": scope.run_id, + "round": round, + "call_id": call_id, + "tool": tool, + "status": outcome.status, + "executed": outcome.executed, + "result_bytes": outcome.content.len(), + "inline_bytes": inline_text.len(), + "document": document, + }); + let content = crate::security::redaction::redact_secrets(inline_text); + append(fabric, scope, TOOL_RESULT_EVENT_TYPE, content, payload).await; +} + +async fn append( + fabric: &MemoryFabric, + scope: &MessageEventScope, + event_type: &str, + content: String, + payload: serde_json::Value, +) { + if let Err(error) = fabric + .record_tool_round_event(scope.clone(), event_type, content, Some(payload.to_string())) + .await + { + let (error_len, error_sha256) = crate::agent::diagnostics::error_log_digest(&error); + tracing::warn!(error_len, error_sha256, event_type, "Failed to persist tool event"); + } +} diff --git a/src/agent/turn_engine.rs b/src/agent/turn_engine.rs index 494e84735..39e363f63 100644 --- a/src/agent/turn_engine.rs +++ b/src/agent/turn_engine.rs @@ -63,6 +63,7 @@ use crate::agent::stream_buffer::StreamBoundaryBuffer; use crate::agent::tool_call_parser::{ looks_like_unparsed_tool_call_syntax, parse_structured_tool_calls, parse_tool_calls, }; +use crate::agent::tool_event_recording::{RoundLog, call_id_for}; use crate::agent::tool_evidence::{claims_tool_evidence, strip_model_written_tool_evidence}; #[cfg(test)] use crate::agent::tool_result_recording::INTERRUPTED_TOOL_RESULT; @@ -2129,6 +2130,13 @@ async fn run_turn_unguarded( // run — and already had side effects — with nothing in history to attach // to, so a replay repeated every one of them. history.push(ChatMessage::assistant(assistant_history_content)); + let tool_event_scope = request_event_scope + .clone() + .unwrap_or_else(|| execution_adapter.tool_execution_context.envelope.message_scope()); + let round_log = RoundLog::new(event_fabric.as_ref(), &tool_event_scope, iteration); + if let Some(log) = round_log.as_ref() { + log.calls(&tool_calls, &native_tool_calls).await; + } let executed = ExecutedToolRecords::new(history, &recorder, &tool_calls, &native_tool_calls); let individual_results = match execute_tools_with_service( @@ -2263,6 +2271,11 @@ async fn run_turn_unguarded( document_statuses.push(document_status); let truncated_result = compact_tool_result_for_history_with_status(&call.name, result, max_inline_chars, document_status); + if let Some(log) = round_log.as_ref() { + let call_id = call_id_for(&call.name, index, &native_tool_calls); + log.result(&call_id, &call.name, outcome, &truncated_result, document_status) + .await; + } let _ = writeln!( tool_results, "\n{}{}\n", diff --git a/src/config/init/templates.rs b/src/config/init/templates.rs index 4ecc9d7b8..4d99e55ee 100644 --- a/src/config/init/templates.rs +++ b/src/config/init/templates.rs @@ -60,7 +60,7 @@ auto_save = true [memory.events] record_user_messages = true record_assistant_messages = true -record_tool_events = false +record_tool_events = true [memory.semantic] auto_promote_user_messages = true @@ -80,7 +80,7 @@ auto_save = true [memory.events] record_user_messages = true record_assistant_messages = true -record_tool_events = false +record_tool_events = true [memory.semantic] auto_promote_user_messages = true @@ -111,7 +111,7 @@ auto_save = true [memory.events] record_user_messages = true record_assistant_messages = true -record_tool_events = false +record_tool_events = true # Semantic memory promotion controls long-term durable memory extraction. [memory.semantic] diff --git a/src/config/init/tests.rs b/src/config/init/tests.rs index dc3b6c6fd..cb2b2f9c3 100644 --- a/src/config/init/tests.rs +++ b/src/config/init/tests.rs @@ -105,7 +105,7 @@ async fn force_regeneration_preserves_unrelated_explicit_settings() { .expect("test: write operator main config"); fs::write( dir.join("config.d/memory.toml"), - "[memory]\nbackend = \"sqlite\"\nauto_save = false\nconversation_retention_days = 99\n[memory.events]\nrecord_tool_events = true\n", + "[memory]\nbackend = \"sqlite\"\nauto_save = false\nconversation_retention_days = 99\n[memory.events]\nrecord_tool_events = false\n", ) .expect("test: write operator memory fragment"); fs::write( @@ -121,7 +121,7 @@ async fn force_regeneration_preserves_unrelated_explicit_settings() { assert_eq!(config.default_model.as_deref(), Some("operator-model")); assert!(!config.memory.auto_save, "an explicit false must survive regeneration"); assert_eq!(config.memory.conversation_retention_days, 99); - assert!(config.memory.events.record_tool_events); + assert!(!config.memory.events.record_tool_events); assert!(!config.channels_config.cli); let telegram = config .channels_config @@ -769,16 +769,16 @@ async fn force_refresh_separates_preserved_added_and_reset_defaults() { // templates. Only one of them was ever typed by the operator. fs::write( dir.join("config.d/memory.toml"), - "[memory]\nbackend = \"sqlite\"\nauto_save = false\n\n[memory.events]\nrecord_tool_events = true\n", + "[memory]\nbackend = \"sqlite\"\nauto_save = false\n\n[memory.events]\nrecord_tool_events = false\n", ) .expect("test: write operator memory fragment"); // The sidecar says `auto_save = false` is what the *previous* templates // shipped, so it is a stale default; `record_tool_events` is recorded at - // its shipped value, so the operator's `true` is their own choice. + // its shipped value, so the operator's `false` is their own choice. fs::write( dir.join(MANAGED_DEFAULTS_FILE), "[[entry]]\npath = [\"memory\", \"auto_save\"]\nvalue = false\n\n\ - [[entry]]\npath = [\"memory\", \"events\", \"record_tool_events\"]\nvalue = false\n", + [[entry]]\npath = [\"memory\", \"events\", \"record_tool_events\"]\nvalue = true\n", ) .expect("test: write the previous defaults record"); diff --git a/src/config/schema/memory.rs b/src/config/schema/memory.rs index 344256af9..ebb126359 100644 --- a/src/config/schema/memory.rs +++ b/src/config/schema/memory.rs @@ -230,8 +230,8 @@ pub struct MemoryEventsConfig { /// Record assistant replies. #[serde(default = "default_true")] pub record_assistant_messages: bool, - /// Record tool/event payloads by default. - #[serde(default)] + /// Record tool calls and tool results in the durable message log. + #[serde(default = "default_true")] pub record_tool_events: bool, } @@ -357,7 +357,7 @@ impl Default for MemoryEventsConfig { Self { record_user_messages: true, record_assistant_messages: true, - record_tool_events: false, + record_tool_events: true, } } } diff --git a/src/config/schema/tests/memory.rs b/src/config/schema/tests/memory.rs index 0ae60c698..fe81ad1a0 100644 --- a/src/config/schema/tests/memory.rs +++ b/src/config/schema/tests/memory.rs @@ -77,7 +77,7 @@ async fn memory_config_default_hygiene_settings() { assert!(m.auto_save); assert!(m.events.record_user_messages); assert!(m.events.record_assistant_messages); - assert!(!m.events.record_tool_events); + assert!(m.events.record_tool_events); assert!(m.semantic.auto_promote_user_messages); assert!(!m.semantic.auto_promote_assistant_messages); assert_eq!(m.semantic.min_chars, 30); diff --git a/src/memory/fabric.rs b/src/memory/fabric.rs index 05362614d..b07d517db 100644 --- a/src/memory/fabric.rs +++ b/src/memory/fabric.rs @@ -78,7 +78,7 @@ impl Default for MemoryEventRecording { enabled: true, record_user_messages: true, record_assistant_messages: true, - record_tool_events: false, + record_tool_events: true, } } } @@ -463,6 +463,20 @@ impl MemoryFabric { .await } + /// Record a tool call or tool result row of a provider round. The event + /// type is not `message.created`, so history loaders and the sync + /// projection do not pick the row up as a chat message. + pub async fn record_tool_round_event( + &self, + scope: MessageEventScope, + event_type: &str, + content: impl Into, + raw_payload_json: Option, + ) -> anyhow::Result { + self.record_message_event(scope, "tool", event_type, content, None, raw_payload_json) + .await + } + pub async fn record_worker_result( &self, scope: MessageEventScope, diff --git a/src/memory/sqlite/sync_journal.rs b/src/memory/sqlite/sync_journal.rs index 76dd4a83b..6cd30e8b2 100644 --- a/src/memory/sqlite/sync_journal.rs +++ b/src/memory/sqlite/sync_journal.rs @@ -209,6 +209,10 @@ pub(super) fn event_header(conn: &Connection, id: &str, kind: &str) -> anyhow::R } pub(super) fn event_written(conn: &Connection, event: &crate::memory::MessageEvent) -> anyhow::Result<()> { + // Tool call and tool result rows are log-only: the stream never carries them. + if event.role == "tool" { + return Ok(()); + } let Some(mut h) = event_header(conn, &event.event_id, "turn.appended")? else { return Ok(()); }; diff --git a/src/memory/sqlite/sync_snapshot.rs b/src/memory/sqlite/sync_snapshot.rs index c376bf575..69178eb7a 100644 --- a/src/memory/sqlite/sync_snapshot.rs +++ b/src/memory/sqlite/sync_snapshot.rs @@ -80,7 +80,7 @@ fn inventory(conn: &Connection, id: &str, owner: &str, head: i64, water: i64) -> ), )?; } - let mut q=conn.prepare("SELECT e.event_id FROM message_events e WHERE e.owner_id=?1 AND e.parent_run_id IS NOT NULL AND e.id<=?2 AND COALESCE(e.parent_session_key,'')<>e.session_key AND COALESCE(e.run_id,'') NOT LIKE 'child-segment:%' AND COALESCE(e.run_id,'') NOT LIKE 'operator-worker-segment:%' AND e.id=(SELECT x.id FROM message_events x WHERE x.owner_id=e.owner_id AND x.session_key=e.session_key AND x.parent_run_id IS NOT NULL AND x.id<=?2 AND COALESCE(x.parent_session_key,'')<>x.session_key AND COALESCE(x.run_id,'') NOT LIKE 'child-segment:%' AND COALESCE(x.run_id,'') NOT LIKE 'operator-worker-segment:%' ORDER BY (x.event_type IN('turn.finalized','turn.admission.failed')) DESC,x.id DESC LIMIT 1) ORDER BY e.session_key")?; + let mut q=conn.prepare("SELECT e.event_id FROM message_events e WHERE e.owner_id=?1 AND e.parent_run_id IS NOT NULL AND e.id<=?2 AND COALESCE(e.parent_session_key,'')<>e.session_key AND COALESCE(e.run_id,'') NOT LIKE 'child-segment:%' AND COALESCE(e.run_id,'') NOT LIKE 'operator-worker-segment:%' AND e.id=(SELECT x.id FROM message_events x WHERE x.owner_id=e.owner_id AND x.session_key=e.session_key AND x.parent_run_id IS NOT NULL AND x.id<=?2 AND COALESCE(x.parent_session_key,'')<>x.session_key AND COALESCE(x.run_id,'') NOT LIKE 'child-segment:%' AND COALESCE(x.run_id,'') NOT LIKE 'operator-worker-segment:%' AND x.role<>'tool' ORDER BY (x.event_type IN('turn.finalized','turn.admission.failed')) DESC,x.id DESC LIMIT 1) ORDER BY e.session_key")?; for source in q.query_map(params![owner, water], |r| r.get::<_, String>(0))? { let source = source?; if let Some(mut h) = super::sync_journal::event_header(conn, &source, "child_session.upsert")? { diff --git a/src/runtime/child_source/golden_effective_config.json b/src/runtime/child_source/golden_effective_config.json index 8eace6033..e3447a263 100644 --- a/src/runtime/child_source/golden_effective_config.json +++ b/src/runtime/child_source/golden_effective_config.json @@ -1 +1 @@ -{"a2a":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trust_domain":"prx.local","trusted_trust_domains":[]},"agent":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"messaging":{"inbound":true},"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2},"agents":{},"api_key":null,"api_url":null,"auth":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"},"autonomy":{"forbidden_paths":[],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]}},"browser":{"allowed_domains":[],"computer_use":{"api_key":null}},"channels_config":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null},"chat":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2},"compliance":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}},"composio":{"api_key":null,"entity_id":"default"},"cost":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{"alpha/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0},"zeta/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0}},"warn_at_percent":80},"cron":{"max_run_history":50},"decision_engine":{"backend":{"circuit_breaker":{"cooldown_secs":60,"failure_threshold":5},"credential_ref":"","endpoint":"","kind":"auto","max_request_bytes":65536,"max_response_bytes":262144,"model":"","pinned_snapshot":"","remote_enabled":false,"timeout_ms":250},"candidates":5,"enabled":false,"latency_budget_ms":500,"max_candidates":12,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"token_ratio_limit":0.3499999940395355},"default_model":"anthropic/claude-sonnet-5","default_provider":"openrouter","default_temperature":0.7,"embedding_routes":[],"gateway":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60},"heartbeat":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."},"http_request":{"max_response_size":1000000,"timeout_secs":30},"identity":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"},"identity_bindings":[],"mcp":{"servers":{}},"mcp_server":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true},"media":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"},"memory":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7},"model_routes":[],"model_settings":{},"multimodal":{"allow_remote_fetch":true,"max_image_size_mb":5,"max_images":4},"nodes":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":[],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}},"observability":{"backend":"none","otel_endpoint":null,"otel_service_name":null},"plugins":{"enabled":false},"providers":{"ollama":{"num_ctx":null}},"proxy":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]},"query_classification":{"rules":[]},"reliability":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2},"router":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]},"runtime":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null},"scheduler":{"claim_lease_secs":90,"max_tasks":64},"secrets":{"encrypt":true},"security":{"audit":{"log_path":"audit.log","max_size_mb":100}},"self_system":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24},"sessions_spawn":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null},"skill_rag":{"top_k":32},"skills":{"open_skills_dir":null,"openclaw_skills_dir":null},"skills_lifecycle":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]},"smart_group":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5},"storage":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}},"task_routing":{"default_intent":"simple","rules":[]},"tool_tiering":{"always_exclude":[],"always_include":[],"channel_exclude":[]},"tunnel":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null},"user_policies":[],"web_search":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15},"webhook":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null},"xin":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}} \ No newline at end of file +{"a2a":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trust_domain":"prx.local","trusted_trust_domains":[]},"agent":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"messaging":{"inbound":true},"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2},"agents":{},"api_key":null,"api_url":null,"auth":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"},"autonomy":{"forbidden_paths":[],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]}},"browser":{"allowed_domains":[],"computer_use":{"api_key":null}},"channels_config":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null},"chat":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2},"compliance":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}},"composio":{"api_key":null,"entity_id":"default"},"cost":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{"alpha/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0},"zeta/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0}},"warn_at_percent":80},"cron":{"max_run_history":50},"decision_engine":{"backend":{"circuit_breaker":{"cooldown_secs":60,"failure_threshold":5},"credential_ref":"","endpoint":"","kind":"auto","max_request_bytes":65536,"max_response_bytes":262144,"model":"","pinned_snapshot":"","remote_enabled":false,"timeout_ms":250},"candidates":5,"enabled":false,"latency_budget_ms":500,"max_candidates":12,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"token_ratio_limit":0.3499999940395355},"default_model":"anthropic/claude-sonnet-5","default_provider":"openrouter","default_temperature":0.7,"embedding_routes":[],"gateway":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60},"heartbeat":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."},"http_request":{"max_response_size":1000000,"timeout_secs":30},"identity":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"},"identity_bindings":[],"mcp":{"servers":{}},"mcp_server":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true},"media":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"},"memory":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":true,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7},"model_routes":[],"model_settings":{},"multimodal":{"allow_remote_fetch":true,"max_image_size_mb":5,"max_images":4},"nodes":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":[],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}},"observability":{"backend":"none","otel_endpoint":null,"otel_service_name":null},"plugins":{"enabled":false},"providers":{"ollama":{"num_ctx":null}},"proxy":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]},"query_classification":{"rules":[]},"reliability":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2},"router":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]},"runtime":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null},"scheduler":{"claim_lease_secs":90,"max_tasks":64},"secrets":{"encrypt":true},"security":{"audit":{"log_path":"audit.log","max_size_mb":100}},"self_system":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24},"sessions_spawn":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null},"skill_rag":{"top_k":32},"skills":{"open_skills_dir":null,"openclaw_skills_dir":null},"skills_lifecycle":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]},"smart_group":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5},"storage":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}},"task_routing":{"default_intent":"simple","rules":[]},"tool_tiering":{"always_exclude":[],"always_include":[],"channel_exclude":[]},"tunnel":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null},"user_policies":[],"web_search":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15},"webhook":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null},"xin":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}} \ No newline at end of file diff --git a/tests/fixtures/config-schema.json b/tests/fixtures/config-schema.json index 8aaaf903b..7fcf73376 100644 --- a/tests/fixtures/config-schema.json +++ b/tests/fixtures/config-schema.json @@ -1 +1 @@ -{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Config","description":"Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).","type":"object","properties":{"a2a":{"description":"Agent-to-Agent compatibility configuration (`[a2a]`).","$ref":"#/$defs/A2aConfig","default":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trusted_trust_domains":[],"trust_domain":"prx.local"}},"agent":{"description":"Agent orchestration settings (`[agent]`).","$ref":"#/$defs/AgentConfig","default":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2,"messaging":{"inbound":true}}},"agents":{"description":"Delegate agent configurations for multi-agent workflows.","type":"object","additionalProperties":{"$ref":"#/$defs/DelegateAgentConfig"},"default":{}},"api_key":{"description":"API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.","type":["string","null"],"default":null},"api_url":{"description":"Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)","type":["string","null"],"default":null},"auth":{"description":"Auth profile and external credential import settings (`[auth]`).","$ref":"#/$defs/AuthConfig","default":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"}},"autonomy":{"description":"Autonomy and security policy configuration (`[autonomy]`).","$ref":"#/$defs/AutonomyConfig","default":{"forbidden_paths":[],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]}}},"browser":{"description":"Browser automation configuration (`[browser]`).","$ref":"#/$defs/BrowserConfig","default":{"allowed_domains":[],"computer_use":{"api_key":null}}},"channels_config":{"description":"Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).","$ref":"#/$defs/ChannelsConfig","default":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null}},"chat":{"description":"Interactive chat UI configuration (`[chat]`).","$ref":"#/$defs/ChatConfig","default":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2}},"compliance":{"description":"Operator-owned compliance controls (`[compliance]`).","$ref":"#/$defs/ComplianceConfig","default":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}},"composio":{"description":"Composio managed OAuth tools integration (`[composio]`).","$ref":"#/$defs/ComposioConfig","default":{"api_key":null,"entity_id":"default"}},"cost":{"description":"Cost tracking and budget enforcement configuration (`[cost]`).","$ref":"#/$defs/CostConfig","default":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{},"warn_at_percent":80}},"cron":{"description":"Cron job configuration (`[cron]`).","$ref":"#/$defs/CronConfig","default":{"max_run_history":50}},"decision_engine":{"description":"Optional advisory decision engine, disabled by default.","$ref":"#/$defs/DecisionEngineConfig","default":{"candidates":5,"enabled":false,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"latency_budget_ms":500,"max_candidates":12,"token_ratio_limit":0.3499999940395355}},"default_model":{"description":"Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.","type":["string","null"]},"default_provider":{"description":"Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.","type":["string","null"]},"default_temperature":{"description":"Default model temperature (0.0–2.0). Default: `0.7`.","type":"number","format":"double","default":0.7},"embedding_routes":{"description":"Embedding routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/EmbeddingRouteConfig"}},"gateway":{"description":"Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).","$ref":"#/$defs/GatewayConfig","default":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60}},"heartbeat":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]`).","$ref":"#/$defs/HeartbeatConfig","default":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."}},"http_request":{"description":"HTTP request tool configuration (`[http_request]`).","$ref":"#/$defs/HttpRequestConfig","default":{"max_response_size":1000000,"timeout_secs":30}},"identity":{"description":"Identity format configuration: OpenClaw or AIEOS (`[identity]`).","$ref":"#/$defs/IdentityConfig","default":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"}},"identity_bindings":{"description":"Static identity bindings loaded at startup (`[[identity_bindings]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/IdentityBindingConfig"}},"mcp":{"description":"Secrets encryption configuration (`[secrets]`).","$ref":"#/$defs/McpConfig","default":{"servers":{}}},"mcp_server":{"description":"MCP server compatibility configuration (`[mcp_server]`).","$ref":"#/$defs/McpServerRuntimeConfig","default":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true}},"media":{"description":"Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.","$ref":"#/$defs/MediaConfig","default":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"}},"memory":{"description":"Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).","$ref":"#/$defs/MemoryConfig","default":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7}},"model_routes":{"description":"Model routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/ModelRouteConfig"}},"model_settings":{"description":"Catalog model levels and explicit parameters, keyed by canonical release ID.","type":"object","additionalProperties":{"$ref":"#/$defs/ModelSettings"},"default":{}},"multimodal":{"description":"Multimodal (image) handling configuration (`[multimodal]`).","$ref":"#/$defs/MultimodalConfig","default":{"allow_remote_fetch":true,"max_image_size_mb":5,"max_images":4}},"nodes":{"description":"Remote node proxy configuration (`[nodes]`).","$ref":"#/$defs/NodesConfig","default":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":[],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}},"observability":{"description":"Observability backend configuration (`[observability]`).","$ref":"#/$defs/ObservabilityConfig","default":{"backend":"none","otel_endpoint":null,"otel_service_name":null}},"plugins":{"description":"WASM plugin runtime switch (`[plugins]`), off by default.","$ref":"#/$defs/PluginsConfig","default":{"enabled":false}},"providers":{"description":"Provider-specific runtime options (`[providers.]`).","$ref":"#/$defs/ProvidersConfig","default":{"ollama":{"num_ctx":null}}},"proxy":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).","$ref":"#/$defs/ProxyConfig","default":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]}},"query_classification":{"description":"Automatic query classification — maps user messages to model hints.","$ref":"#/$defs/QueryClassificationConfig","default":{"rules":[]}},"reliability":{"description":"Reliability settings: retries, fallback providers, backoff (`[reliability]`).","$ref":"#/$defs/ReliabilityConfig","default":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2}},"router":{"description":"Heuristic LLM router configuration (`[router]`).","$ref":"#/$defs/RouterConfig","default":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]}},"runtime":{"description":"Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.","$ref":"#/$defs/RuntimeConfig","default":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null}},"scheduler":{"description":"Scheduler configuration for periodic task execution (`[scheduler]`).","$ref":"#/$defs/SchedulerConfig","default":{"claim_lease_secs":90,"max_tasks":64}},"secrets":{"$ref":"#/$defs/SecretsConfig","default":{"encrypt":true}},"security":{"description":"Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).","$ref":"#/$defs/SecurityConfig","default":{"audit":{"log_path":"audit.log","max_size_mb":100}}},"self_system":{"description":"Self-system experimental automation controls (`[self_system]`).","$ref":"#/$defs/SelfSystemConfig","default":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24}},"sessions_spawn":{"description":"Session spawning configuration (`[sessions_spawn]`).","$ref":"#/$defs/SessionsSpawnConfig","default":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null}},"skill_rag":{"description":"Dynamic skill retrieval settings (`[skill_rag]`).","$ref":"#/$defs/SkillRagConfig","default":{"top_k":32}},"skills":{"description":"Skills loading and community repository behavior (`[skills]`).","$ref":"#/$defs/SkillsConfig","default":{"open_skills_dir":null,"openclaw_skills_dir":null}},"skills_lifecycle":{"description":"Skill lifecycle (`[skills_lifecycle]`), off by default.","$ref":"#/$defs/SkillsLifecycleConfig","default":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]}},"smart_group":{"description":"Smart group-reply pre-gate configuration (`[smart_group]`).","$ref":"#/$defs/SmartGroupConfig","default":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5}},"storage":{"description":"Persistent storage provider configuration (`[storage]`).","$ref":"#/$defs/StorageConfig","default":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"task_routing":{"description":"Task routing configuration — classifies work by intent before the main agent loop.","$ref":"#/$defs/TaskRoutingConfig","default":{"default_intent":"simple","rules":[]}},"tool_tiering":{"description":"Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).","$ref":"#/$defs/ToolTieringConfig","default":{"always_exclude":[],"always_include":[],"channel_exclude":[]}},"tunnel":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]`).","$ref":"#/$defs/TunnelConfig","default":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null}},"user_policies":{"description":"Static user policy records loaded at startup (`[[user_policies]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/UserPolicyConfig"}},"web_search":{"description":"Web search tool configuration (`[web_search]`).","$ref":"#/$defs/WebSearchConfig","default":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15}},"webhook":{"description":"Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).","$ref":"#/$defs/MemoryWebhookConfig","default":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null}},"xin":{"description":"Xin autonomous task engine configuration (`[xin]`).","$ref":"#/$defs/XinConfig","default":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}}},"$defs":{"A2aConfig":{"type":"object","properties":{"agent_id":{"description":"Stable PRX agent identifier advertised to peers.","type":"string","default":"prx-default"},"allowed_peer_issuers":{"description":"Accepted external peer issuers.","type":"array","default":[],"items":{"type":"string"}},"bind":{"description":"Advertised bind address.","type":"string","default":"127.0.0.1:16832"},"card_jwks_uri":{"description":"Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.","type":["string","null"],"default":null},"card_signing_key_path":{"description":"On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).","type":["string","null"],"default":null},"card_ttl_seconds":{"description":"Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.","type":"integer","format":"uint64","default":3600,"minimum":0},"discovery_advertised":{"description":"Whether to advertise into an external A2A registry.","type":"boolean","default":false},"handoff_nonce_ttl_seconds":{"description":"Replay window for future handoff delegation tokens.","type":"integer","format":"uint64","default":3600,"minimum":0},"messaging_enabled":{"description":"Enable the dedicated pinned mTLS messaging listener.","type":"boolean","default":false},"peers":{"type":"object","additionalProperties":{"$ref":"#/$defs/A2aPeer"},"default":{}},"spiffe_id":{"description":"Local SPIFFE-style identifier placeholder.","type":"string","default":"spiffe://prx-local/agent/prx-default"},"spiffe_strict_validation":{"description":"When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.","type":"boolean","default":false},"spiffe_trust_bundle_pem":{"description":"Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).","type":["string","null"],"default":null},"trusted_trust_domains":{"description":"Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).","type":"array","default":[],"items":{"type":"string"}},"trust_domain":{"description":"SPIFFE trust domain for new instance identities.","type":"string","default":"prx.local"}}},"A2aPeer":{"description":"Explicit pinned identity and local recipient grant.","type":"object","properties":{"spiffe_id":{"type":"string"},"fingerprints":{"type":"array","items":{"type":"string"}},"address":{"type":"string"},"owner":{"type":"string"},"sessions":{"type":"array","default":["*"],"items":{"type":"string"}},"agents":{"type":"array","default":["*"],"items":{"type":"string"}}},"required":["spiffe_id","fingerprints","address","owner"],"additionalProperties":false},"AgentCompactionConfig":{"description":"Agent context compaction configuration (`[agent.compaction]`).","type":"object","properties":{"keep_recent_messages":{"description":"Number of recent non-system messages to keep after compaction.","type":"integer","format":"uint","default":12,"minimum":0},"max_context_tokens":{"description":"Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.","type":"integer","format":"uint","default":128000,"minimum":0},"memory_flush":{"description":"Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.","type":"boolean","default":true},"mode":{"description":"Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).","$ref":"#/$defs/AgentCompactionMode","default":"switch"},"os_paging":{"description":"Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.","$ref":"#/$defs/OsPagingConfig","default":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"}},"reserve_tokens":{"description":"Tokens reserved for the next model response.","type":"integer","format":"uint","default":4096,"minimum":0}}},"AgentCompactionMode":{"description":"Compaction mode for long conversation contexts.","oneOf":[{"description":"Disable proactive compaction.","type":"string","const":"off"},{"description":"Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.","type":"string","const":"switch"},{"description":"Conservative compaction that prefers summary replacement.","type":"string","const":"safeguard"},{"description":"Aggressive truncation mode for tighter contexts.","type":"string","const":"aggressive"}]},"AgentConfig":{"description":"Agent orchestration configuration (`[agent]` section).","type":"object","properties":{"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"compact_context":{"description":"When true: bootstrap_max_chars=6000. Use for 13B or smaller models.","type":"boolean","default":false},"compaction":{"description":"Context compaction controls (`[agent.compaction]`).","$ref":"#/$defs/AgentCompactionConfig","default":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096}},"low_priority_tools":{"description":"Tool names treated as low-priority when `priority_scheduling_enabled = true`.","type":"array","default":["sessions_spawn","delegate"],"items":{"type":"string"}},"priority_scheduling_enabled":{"description":"Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.","type":"boolean","default":false},"read_only_tool_concurrency_window":{"description":"Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.","type":"integer","format":"uint","default":2,"minimum":0},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}}},"AgentLimits":{"description":"Optional admission limits for rf-started turns of a named agent.","type":"object","properties":{"max_concurrent_turns":{"type":["integer","null"],"format":"uint32","minimum":0},"max_cost_per_day_cents":{"type":["integer","null"],"format":"uint64","minimum":0}},"additionalProperties":false},"AuditConfig":{"description":"Audit logging configuration","type":"object","properties":{"log_path":{"description":"Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).","type":"string","default":"audit.log"},"max_size_mb":{"description":"Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).","type":"integer","format":"uint32","default":100,"minimum":0}}},"AuthConfig":{"description":"Authentication and external credential import configuration (`[auth]` section).","type":"object","properties":{"codex_auth_json_auto_import":{"description":"Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.","type":"boolean","default":false},"codex_auth_json_path":{"description":"Source path for Codex CLI auth.json import.","type":"string","default":"~/.codex/auth.json"}}},"AutonomyConfig":{"type":"object","properties":{"acknowledge_unrestricted_profile":{"description":"Operator acknowledgement for an intentionally unrestricted profile.\nRetained for existing configs; it no longer changes any output or policy behavior.","type":"boolean","default":false},"forbidden_paths":{"description":"Explicit path denylist. Default: empty.\n\nApplies below level `full` only; list paths when running `supervised` or `readonly`.","type":"array","default":[],"items":{"type":"string"}},"level":{"description":"Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).","$ref":"#/$defs/AutonomyLevel","default":"full"},"max_cost_per_day_cents":{"description":"Maximum cost per day in cents per policy. Default: unset (no ceiling).","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"scopes":{"description":"Scope-based tool access control: per-user/channel/chat-type allow/deny rules.","$ref":"#/$defs/ScopeConfig","default":{"assign_owners":[],"default":"allow","rules":[]}},"workspace_only":{"description":"Restrict file writes and command paths to the workspace directory. Default: `false`.\n\nApplies below level `full` only; set it when running `supervised` or `readonly`.","type":"boolean","default":false}}},"AutonomyLevel":{"description":"How much autonomy the agent has","oneOf":[{"description":"Read-only: can observe but not act","type":"string","const":"readonly"},{"description":"Supervised: acts but requires approval for risky operations","type":"string","const":"supervised"},{"description":"Full: autonomous execution within policy bounds","type":"string","const":"full"}]},"BackendSelection":{"description":"Which decision backend runs: `auto` (the factory's order) or one kind.","type":"string"},"BrowserComputerUseConfig":{"description":"Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.","type":"object","properties":{"api_key":{"description":"Optional bearer token (retained only for config secret handling).","type":["string","null"],"default":null}}},"BrowserConfig":{"description":"Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.","type":"object","properties":{"allowed_domains":{"description":"Allowed domains for `web_fetch` (exact or subdomain match).","type":"array","default":[],"items":{"type":"string"}},"computer_use":{"description":"Computer-use sidecar config (retained only for `api_key` secret handling).","$ref":"#/$defs/BrowserComputerUseConfig","default":{"api_key":null}}}},"ChannelsConfig":{"description":"Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.","type":"object","properties":{"cli":{"description":"Enable the CLI interactive channel. Default: `true`.","type":"boolean","default":true},"dingtalk":{"description":"DingTalk channel configuration.","anyOf":[{"$ref":"#/$defs/DingTalkConfig"},{"type":"null"}]},"discord":{"description":"Discord bot channel configuration.","anyOf":[{"$ref":"#/$defs/DiscordConfig"},{"type":"null"}]},"email":{"description":"Email channel configuration.","anyOf":[{"$ref":"#/$defs/EmailConfig"},{"type":"null"}]},"imessage":{"description":"iMessage channel configuration (macOS only).","anyOf":[{"$ref":"#/$defs/IMessageConfig"},{"type":"null"}]},"irc":{"description":"IRC channel configuration.","anyOf":[{"$ref":"#/$defs/IrcConfig"},{"type":"null"}]},"lark":{"description":"Lark/Feishu channel configuration.","anyOf":[{"$ref":"#/$defs/LarkConfig"},{"type":"null"}]},"linq":{"description":"Linq Partner API channel configuration.","anyOf":[{"$ref":"#/$defs/LinqConfig"},{"type":"null"}]},"mattermost":{"description":"Mattermost bot channel configuration.","anyOf":[{"$ref":"#/$defs/MattermostConfig"},{"type":"null"}]},"nextcloud_talk":{"description":"Nextcloud Talk bot channel configuration.","anyOf":[{"$ref":"#/$defs/NextcloudTalkConfig"},{"type":"null"}]},"qq":{"description":"QQ Official Bot channel configuration.","anyOf":[{"$ref":"#/$defs/QQConfig"},{"type":"null"}]},"ramflux":{"description":"Local ramflux agent-host bridge.","anyOf":[{"$ref":"#/$defs/RamfluxConfig"},{"type":"null"}],"default":null},"signal":{"description":"Signal channel configuration.","anyOf":[{"$ref":"#/$defs/SignalConfig"},{"type":"null"}]},"slack":{"description":"Slack bot channel configuration.","anyOf":[{"$ref":"#/$defs/SlackConfig"},{"type":"null"}]},"telegram":{"description":"Telegram bot channel configuration.","anyOf":[{"$ref":"#/$defs/TelegramConfig"},{"type":"null"}]},"wacli":{"description":"wacli JSON-RPC daemon channel configuration.","anyOf":[{"$ref":"#/$defs/WacliConfig"},{"type":"null"}],"default":null},"webhook":{"description":"Webhook channel configuration.","anyOf":[{"$ref":"#/$defs/WebhookConfig"},{"type":"null"}]},"whatsapp":{"description":"WhatsApp channel configuration (Cloud API or Web mode).","anyOf":[{"$ref":"#/$defs/WhatsAppConfig"},{"type":"null"}]}}},"ChatConfig":{"description":"Interactive chat configuration (`[chat]`).","type":"object","properties":{"daemon":{"description":"How this chat process reaches the daemon it borrows channels from.","$ref":"#/$defs/ChatDaemonConfig","default":{"token":"","url":""}},"max_concurrent_visible_turns":{"description":"Maximum concurrent visible provider turns in the TUI Redux driver.","type":"integer","format":"uint","default":2,"minimum":0}}},"ChatDaemonConfig":{"description":"Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.","type":"object","properties":{"token":{"description":"Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.","type":"string","default":""},"url":{"description":"Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.","type":"string","default":""}}},"CircuitBreakerConfig":{"description":"The per-backend circuit breaker.","type":"object","properties":{"cooldown_secs":{"description":"Seconds the breaker stays open (1 to 3600).","type":"integer","format":"uint32","default":60,"minimum":0},"failure_threshold":{"description":"Consecutive failures before the breaker opens (1 to 100).","type":"integer","format":"uint32","default":5,"minimum":0}}},"ClassificationRule":{"description":"A single classification rule mapping message patterns to a model hint.","type":"object","properties":{"hint":{"description":"Must match a `[[model_routes]]` hint value.","type":"string"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"max_length":{"description":"Only match if message length <= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"min_length":{"description":"Only match if message length >= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"patterns":{"description":"Case-sensitive literal matches (for \"```\", \"fn \", etc.).","type":"array","default":[],"items":{"type":"string"}},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0}},"required":["hint"]},"CloudflareTunnelConfig":{"type":"object","properties":{"token":{"description":"Cloudflare Tunnel token (from Zero Trust dashboard)","type":"string"}},"required":["token"]},"ComplianceConfig":{"type":"object","properties":{"eu_ai_act":{"$ref":"#/$defs/EuAiActComplianceConfig","default":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null}},"interaction_notice":{"$ref":"#/$defs/InteractionNoticeConfig","default":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}}},"ComposioConfig":{"description":"Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.","type":"object","properties":{"api_key":{"description":"Composio API key (stored encrypted when secrets.encrypt = true)","type":["string","null"],"default":null},"entity_id":{"description":"Default entity ID for multi-user setups","type":"string","default":"default"}}},"CostConfig":{"description":"Cost tracking and budget enforcement configuration (`[cost]` section).","type":"object","properties":{"allow_override":{"description":"Allow requests to exceed budget with --override flag (default: false)","type":"boolean","default":false},"daily_limit_usd":{"description":"Daily spending limit in USD (default: unset, no limit; 0 refuses every priced turn)","type":["number","null"],"format":"double","default":null},"monthly_limit_usd":{"description":"Monthly spending limit in USD (default: unset, no limit)","type":["number","null"],"format":"double","default":null},"prices":{"description":"Per-model pricing (USD per 1M tokens)","type":"object","additionalProperties":{"$ref":"#/$defs/ModelPricing"},"default":{}},"warn_at_percent":{"description":"Warn when spending reaches this percentage of a configured limit (default: 80)","type":"integer","format":"uint8","default":80,"maximum":255,"minimum":0}}},"CredentialRefSetting":{"description":"Which credential a decision backend uses. A reference, never a secret.","type":"string"},"CronConfig":{"description":"Cron job configuration (`[cron]` section).","type":"object","properties":{"max_run_history":{"description":"Maximum number of historical cron run records to retain. Default: `50`.","type":"integer","format":"uint32","default":50,"minimum":0}}},"CustomTunnelConfig":{"type":"object","properties":{"health_url":{"description":"Optional URL to check tunnel health","type":["string","null"]},"start_command":{"description":"Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"","type":"string"},"url_pattern":{"description":"Optional regex to extract public URL from command stdout","type":["string","null"]}},"required":["start_command"]},"DecisionBackendConfig":{"description":"The decision backend (`[decision_engine.backend]`).","type":"object","properties":{"circuit_breaker":{"description":"The circuit breaker.","$ref":"#/$defs/CircuitBreakerConfig","default":{"cooldown_secs":60,"failure_threshold":5}},"credential_ref":{"description":"The credential reference: `\"\"`, `\"none\"` or `cred-`.","$ref":"#/$defs/CredentialRefSetting","default":""},"endpoint":{"description":"The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.","type":"string","default":""},"kind":{"description":"`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).","$ref":"#/$defs/BackendSelection","default":"auto"},"max_request_bytes":{"description":"Largest request body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":65536,"minimum":0},"max_response_bytes":{"description":"Largest response body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":262144,"minimum":0},"model":{"description":"The model the endpoint serves; one exact version for a hosted\nservice.","type":"string","default":""},"pinned_snapshot":{"description":"The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.","type":"string"},"remote_enabled":{"description":"Whether decision state may leave this machine. Default `false`.","type":"boolean","default":false},"timeout_ms":{"description":"Transport timeout (10 ms up to the extra latency budget).","type":"integer","format":"uint32","default":250,"minimum":0}}},"DecisionEngineConfig":{"type":"object","properties":{"backend":{"anyOf":[{"$ref":"#/$defs/DecisionBackendConfig"},{"type":"null"}]},"candidates":{"type":"integer","format":"uint32","default":5,"minimum":0},"enabled":{"type":"boolean","default":false},"mode":{"$ref":"#/$defs/DecisionMode","default":"pre"},"observe_queue":{"type":"integer","format":"uint32","default":64,"minimum":0},"prompt_budget_tokens":{"type":"integer","format":"uint32","default":300,"minimum":0},"telemetry_cap":{"type":"integer","format":"uint32","default":1000,"minimum":0},"timeout_ms":{"type":"integer","format":"uint32","default":1500,"minimum":0},"latency_budget_ms":{"description":"The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.","type":"integer","format":"uint64","default":500,"minimum":0},"token_ratio_limit":{"description":"Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).","type":"number","format":"float","default":0.3499999940395355},"max_candidates":{"description":"The most candidates a turn considers (1 to 32).","type":"integer","format":"uint8","default":12,"maximum":255,"minimum":0}}},"DecisionMode":{"type":"string","enum":["pre","post","both"]},"DeclarationOfConformityConfig":{"type":"object","properties":{"applicable_union_law":{"type":"array","default":[],"items":{"type":"string"}},"artifact_path":{"type":["string","null"],"default":null},"artifact_version":{"type":["string","null"],"default":null},"conformity_assessment_procedure":{"type":["string","null"],"default":null},"conformity_statement":{"type":["string","null"],"default":null},"harmonised_standards":{"type":"array","default":[],"items":{"type":"string"}},"issue_date":{"type":["string","null"],"default":null},"issue_place":{"type":["string","null"],"default":null},"notified_body_certificate":{"type":["string","null"],"default":null},"notified_body_identification_number":{"type":["string","null"],"default":null},"notified_body_name":{"type":["string","null"],"default":null},"personal_data_compliance_statement":{"type":["string","null"],"default":null},"processes_personal_data":{"type":"boolean","default":false},"provider_address":{"type":["string","null"],"default":null},"provider_name":{"type":["string","null"],"default":null},"signer_function":{"type":["string","null"],"default":null},"signer_name":{"type":["string","null"],"default":null},"signer_on_behalf_of":{"type":["string","null"],"default":null},"sole_responsibility_statement":{"type":["string","null"],"default":null},"standards_not_applicable_reason":{"type":["string","null"],"default":null},"system_name":{"type":["string","null"],"default":null},"system_reference":{"type":["string","null"],"default":null},"system_type":{"type":["string","null"],"default":null}}},"DelegateAgentConfig":{"description":"Configuration for a delegate sub-agent used by the `delegate` tool.","type":"object","properties":{"agentic":{"description":"Agentic sub-agent mode (multi-turn tool-call loop). Default true; an\nexplicit `false` makes the agent answer-only with no tools.","type":"boolean","default":true},"allowed_tools":{"description":"Allowlist of tool names available to the sub-agent in agentic mode.\nEmpty or omitted means all tools, the same as `[\"*\"]`.","type":"array","default":[],"items":{"type":"string"}},"api_key":{"description":"Optional API key override","type":["string","null"],"default":null},"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"autonomy":{"description":"The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.","anyOf":[{"$ref":"#/$defs/AutonomyLevel"},{"type":"null"}]},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"enabled":{"description":"Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.","type":"boolean","default":true},"identity_dir":{"description":"Optional identity files directory relative to workspace root.","type":["string","null"],"default":null},"limits":{"$ref":"#/$defs/AgentLimits","default":{"max_concurrent_turns":null,"max_cost_per_day_cents":null}},"max_depth":{"description":"Max recursion depth for nested delegation","type":"integer","format":"uint32","default":8,"minimum":0},"memory_scope":{"description":"Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".","type":["string","null"],"default":null},"model":{"description":"Model name","type":"string"},"provider":{"description":"Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")","type":"string"},"spawn_enabled":{"description":"Whether this agent is allowed to be targeted by sessions_spawn (default: true).","type":["boolean","null"],"default":null},"system_prompt":{"description":"Optional system prompt for the sub-agent","type":["string","null"],"default":null},"temperature":{"description":"Temperature override","type":["number","null"],"format":"double","default":null},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}},"required":["provider","model"]},"DingTalkConfig":{"description":"DingTalk configuration for Stream Mode messaging","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"client_id":{"description":"Client ID (AppKey) from DingTalk developer console","type":"string"},"client_secret":{"description":"Client Secret (AppSecret) from DingTalk developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["client_id","client_secret"]},"DiscordConfig":{"description":"Discord bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Discord user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Discord bot token (from Discord Developer Portal).","type":"string"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"guild_id":{"description":"Optional guild (server) ID to restrict the bot to a single guild.","type":["string","null"]},"listen_to_bots":{"description":"When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.","type":"boolean","default":false}},"required":["bot_token"]},"DmPolicy":{"description":"Policy for direct-message handling.","oneOf":[{"description":"Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).","type":"string","const":"pairing"},{"description":"Accept only senders listed in `allowed_from`.","type":"string","const":"allowlist"},{"description":"Accept any direct sender.","type":"string","const":"open"},{"description":"Ignore direct messages.","type":"string","const":"disabled"}]},"DockerRuntimeConfig":{"description":"Docker runtime configuration (`[runtime.docker]` section).","type":"object","properties":{"allowed_workspace_roots":{"description":"Optional workspace root allowlist for Docker mount validation.","type":"array","default":[],"items":{"type":"string"}},"cpu_limit":{"description":"Optional CPU limit (`None` = no explicit limit).","type":["number","null"],"format":"double","default":1.0},"image":{"description":"Runtime image used to execute shell commands.","type":"string","default":"alpine:3.20"},"memory_limit_mb":{"description":"Optional memory limit in MB (`None` = no explicit limit).","type":["integer","null"],"format":"uint64","default":512,"minimum":0},"mount_workspace":{"description":"Mount configured workspace into `/workspace`.","type":"boolean","default":true},"network":{"description":"Docker network mode (`none`, `bridge`, etc.).","type":"string","default":"none"},"read_only_rootfs":{"description":"Mount root filesystem as read-only.","type":"boolean","default":true}}},"EmailConfig":{"description":"Email channel configuration","type":"object","properties":{"allowed_senders":{"description":"Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)","type":"array","default":[],"items":{"type":"string"}},"from_address":{"description":"From address for outgoing emails","type":"string"},"idle_timeout_secs":{"description":"IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes","type":"integer","format":"uint64","default":1740,"minimum":0},"imap_folder":{"description":"IMAP folder to poll (default: INBOX)","type":"string","default":"INBOX"},"imap_host":{"description":"IMAP server hostname","type":"string"},"imap_port":{"description":"IMAP server port (default: 993 for TLS)","type":"integer","format":"uint16","default":993,"maximum":65535,"minimum":0},"password":{"description":"Email password for authentication","type":"string"},"smtp_host":{"description":"SMTP server hostname","type":"string"},"smtp_port":{"description":"SMTP server port (default: 465 for TLS)","type":"integer","format":"uint16","default":465,"maximum":65535,"minimum":0},"smtp_tls":{"description":"Use TLS for SMTP (default: true)","type":"boolean","default":true},"username":{"description":"Email username for authentication","type":"string"}},"required":["imap_host","smtp_host","username","password","from_address"]},"EmbeddingRouteConfig":{"description":"Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"dimensions":{"description":"Optional embedding dimension override for this route","type":["integer","null"],"format":"uint","default":null,"minimum":0},"hint":{"description":"Route hint name (e.g. \"semantic\", \"archive\", \"faq\")","type":"string"},"model":{"description":"Embedding model to use with that provider","type":"string"},"provider":{"description":"Embedding provider (`none`, `openai`, or `custom:`)","type":"string"}},"required":["hint","provider","model"]},"EuAiActClassificationConfig":{"type":"object","properties":{"assessed_at":{"type":["string","null"],"default":null},"owner":{"type":["string","null"],"default":null},"status":{"$ref":"#/$defs/EuAiActRiskClassification","default":"unclassified"}}},"EuAiActComplianceConfig":{"type":"object","properties":{"classification":{"$ref":"#/$defs/EuAiActClassificationConfig","default":{"assessed_at":null,"owner":null,"status":"unclassified"}},"declaration":{"$ref":"#/$defs/DeclarationOfConformityConfig","default":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null}},"incident_store_path":{"type":["string","null"],"default":null}}},"EuAiActRiskClassification":{"type":"string","enum":["unclassified","high_risk","not_high_risk"]},"FitnessConfig":{"description":"Calendar schedule, evidence thresholds, and retention for fitness v2.","type":"object","properties":{"auto_run":{"description":"Run the daily fitness worker in daemon mode.","type":"boolean","default":true},"max_backfill_days":{"description":"Maximum number of closed days recovered after downtime.","type":"integer","format":"uint32","default":7,"minimum":0},"min_coverage":{"description":"Minimum available metric weight required to publish a final score.","type":"number","format":"double","default":0.6},"min_samples":{"description":"Minimum samples required before an evidence-derived subscore is usable.","type":"integer","format":"uint","default":5,"minimum":0},"retention_days":{"description":"Number of daily JSON reports retained on disk.","type":"integer","format":"uint32","default":180,"minimum":0},"run_at":{"description":"Local wall-clock time (`HH:MM`) at which the previous day is scored.","type":"string","default":"00:10"},"timezone":{"description":"IANA timezone used to define closed calendar days.","type":"string","default":"UTC"}}},"GatewayConfig":{"description":"Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.","type":"object","properties":{"allow_public_bind":{"description":"Allow binding to non-localhost without a tunnel (default: false)","type":"boolean","default":false},"api_rate_limit_per_minute":{"description":"Max `/api/*` requests per minute per authenticated token.","type":"integer","format":"uint32","default":60,"minimum":0},"channel_webhook_dedup_ttl_secs":{"description":"How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.","type":"integer","format":"uint64","default":86400,"minimum":0},"host":{"description":"Gateway host (default: 127.0.0.1)","type":"string","default":"127.0.0.1"},"idempotency_max_keys":{"description":"Maximum distinct idempotency keys retained in memory.","type":"integer","format":"uint","default":10000,"minimum":0},"idempotency_ttl_secs":{"description":"TTL for webhook idempotency keys.","type":"integer","format":"uint64","default":300,"minimum":0},"pair_rate_limit_per_minute":{"description":"Max `/pair` requests per minute per client key.","type":"integer","format":"uint32","default":10,"minimum":0},"paired_tokens":{"description":"Paired bearer tokens (managed automatically, not user-edited)","type":"array","default":[],"items":{"type":"string"}},"port":{"description":"Gateway port (default: 16830)","type":"integer","format":"uint16","default":16830,"maximum":65535,"minimum":0},"rate_limit_max_keys":{"description":"Maximum distinct client keys tracked by gateway rate limiter maps.","type":"integer","format":"uint","default":10000,"minimum":0},"require_pairing":{"description":"Require pairing before accepting requests (default: true)","type":"boolean","default":true},"targeted_agents":{"description":"Switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). Default true. While false, any\notherwise-valid named target answers 409 `agent_disabled` and never\nruns as Main.","type":"boolean","default":true},"trust_forwarded_headers":{"description":"Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.","type":"boolean","default":false},"webhook_rate_limit_per_minute":{"description":"Max `/webhook` requests per minute per client key.","type":"integer","format":"uint32","default":60,"minimum":0}}},"GroupPolicy":{"description":"Policy for group-message handling.","oneOf":[{"description":"Accept only groups listed in `group_allow_from`.","type":"string","const":"allowlist"},{"description":"Accept any group.","type":"string","const":"open"},{"description":"Ignore group messages.","type":"string","const":"disabled"}]},"GroupReplyMode":{"description":"How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.","oneOf":[{"description":"Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).","type":"string","const":"off"},{"description":"Reply only when the bot is @-mentioned (legacy `mention_only = true`).","type":"string","const":"mention-only"},{"description":"Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).","type":"string","const":"smart"}]},"HeartbeatConfig":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]` section).","type":"object","properties":{"active_hours":{"description":"Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.","type":"array","default":[8,23],"items":{"type":"integer","format":"uint8","maximum":255,"minimum":0}},"interval_minutes":{"description":"Interval in minutes between heartbeat pings. Default: `30`.","type":"integer","format":"uint32","default":30,"minimum":0},"prompt":{"description":"Prompt used by heartbeat worker when dispatching tasks.","type":"string","default":"Check HEARTBEAT.md and follow instructions."}}},"HttpRequestConfig":{"description":"HTTP request tool configuration (`[http_request]` section).","type":"object","properties":{"max_response_size":{"description":"Maximum response size in bytes (default: 1MB)","type":"integer","format":"uint","default":1000000,"minimum":0},"timeout_secs":{"description":"Request timeout in seconds (default: 30)","type":"integer","format":"uint64","default":30,"minimum":0}}},"IMessageConfig":{"description":"iMessage channel configuration (macOS only).","type":"object","properties":{"allowed_contacts":{"description":"Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.","type":"array","items":{"type":"string"}},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["allowed_contacts"]},"IdentityBindingConfig":{"description":"Startup identity binding entry (`[[identity_bindings]]`).","type":"object","properties":{"channel":{"type":"string"},"channel_account":{"type":"string"},"display_name":{"type":["string","null"],"default":null},"user_id":{"type":"string"}},"required":["user_id","channel","channel_account"]},"IdentityConfig":{"description":"Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.","type":"object","properties":{"aieos_inline":{"description":"Inline AIEOS JSON (alternative to file path)","type":["string","null"],"default":null},"aieos_path":{"description":"Path to AIEOS JSON file (relative to workspace)","type":["string","null"],"default":null},"format":{"description":"Identity format: \"openclaw\" (default) or \"aieos\"","type":"string","default":"openclaw"}}},"InteractionNoticeApplicability":{"type":"string","enum":["required","not_applicable"]},"InteractionNoticeConfig":{"type":"object","properties":{"applicability":{"$ref":"#/$defs/InteractionNoticeApplicability","default":"required"},"exception_owner":{"type":["string","null"],"default":null},"exception_reviewed_at":{"type":["string","null"],"default":null},"text":{"type":"string","default":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers."},"version":{"type":"string","default":"1"}}},"IrcConfig":{"description":"IRC channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed nicknames (case-insensitive) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"channels":{"description":"Channels to join on connect","type":"array","default":[],"items":{"type":"string"}},"mention_only":{"description":"When true, only process channel/group messages that mention the bot.","type":"boolean","default":false},"nickname":{"description":"Bot nickname","type":"string"},"nickserv_password":{"description":"NickServ IDENTIFY password","type":["string","null"]},"port":{"description":"IRC server port (default: 6697 for TLS)","type":"integer","format":"uint16","default":6697,"maximum":65535,"minimum":0},"sasl_password":{"description":"SASL PLAIN password (IRCv3)","type":["string","null"]},"server":{"description":"IRC server hostname","type":"string"},"server_password":{"description":"Server password (for bouncers like ZNC)","type":["string","null"]},"username":{"description":"Username (defaults to nickname if not set)","type":["string","null"]},"verify_tls":{"description":"Verify TLS certificate (default: true)","type":["boolean","null"]}},"required":["server","nickname"]},"LarkConfig":{"description":"Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from Lark/Feishu developer console","type":"string"},"app_secret":{"description":"App Secret from Lark/Feishu developer console","type":"string"},"encrypt_key":{"description":"Encrypt key for webhook message decryption (optional)","type":["string","null"],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"port":{"description":"HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"receive_mode":{"description":"Event receive mode: \"websocket\" (default) or \"webhook\"","$ref":"#/$defs/LarkReceiveMode","default":"websocket"},"use_feishu":{"description":"Whether to use the Feishu (Chinese) endpoint instead of Lark (International)","type":"boolean","default":false},"verification_token":{"description":"Verification token for webhook validation (optional)","type":["string","null"],"default":null}},"required":["app_id","app_secret"]},"LarkReceiveMode":{"description":"How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.","type":"string","enum":["websocket","webhook"]},"LinqConfig":{"type":"object","properties":{"allowed_senders":{"description":"Allowed sender handles (phone numbers) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"api_token":{"description":"Linq Partner API token (Bearer auth)","type":"string"},"from_phone":{"description":"Phone number to send from (E.164 format)","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"signing_secret":{"description":"Webhook signing secret for signature verification","type":["string","null"],"default":null}},"required":["api_token","from_phone"]},"MattermostConfig":{"description":"Mattermost bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Mattermost user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Mattermost bot access token.","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.","type":["boolean","null"],"default":null},"thread_replies":{"description":"When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.","type":["boolean","null"],"default":null},"url":{"description":"Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).","type":"string"}},"required":["url","bot_token"]},"McpConfig":{"type":"object","properties":{"servers":{"description":"Named MCP server definitions","type":"object","additionalProperties":{"$ref":"#/$defs/McpServerConfig"},"default":{}},"workspace_servers":{"description":"Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.","$ref":"#/$defs/WorkspaceMcpServers"}}},"McpServerConfig":{"type":"object","properties":{"allow_tools":{"description":"Optional allow-list of exposed tools (empty = all)","type":"array","default":[],"items":{"type":"string"}},"args":{"description":"Command args for stdio mode","type":"array","default":[],"items":{"type":"string"}},"command":{"description":"Command for stdio mode","type":["string","null"],"default":null},"deny_tools":{"description":"Optional deny-list of exposed tools","type":"array","default":[],"items":{"type":"string"}},"env":{"description":"Environment variables for stdio mode","type":"object","additionalProperties":{"type":"string"},"default":{}},"request_timeout_ms":{"description":"Request timeout in milliseconds","type":"integer","format":"uint64","default":30000,"minimum":0},"startup_timeout_ms":{"description":"Startup timeout in milliseconds","type":"integer","format":"uint64","default":10000,"minimum":0},"tool_name_prefix":{"description":"Prefix used in tool naming and routing","type":"string","default":"mcp"},"transport":{"description":"Transport type: stdio or http","$ref":"#/$defs/McpTransport","default":"stdio"},"url":{"description":"URL for HTTP mode (streamable HTTP endpoint)","type":["string","null"],"default":null},"working_dir":{"description":"Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).","type":["string","null"]}}},"McpServerRuntimeConfig":{"type":"object","properties":{"allowed_origins":{"description":"Allowed browser origins for future streamable HTTP clients.","type":"array","default":["claude.ai","openai.com","localhost"],"items":{"type":"string"}},"bind":{"description":"Advertised bind address. The gateway may still be started with a CLI port override.","type":"string","default":"127.0.0.1:16831"},"exposed_tools":{"description":"Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.","type":"array","default":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"items":{"type":"string"}},"jwt_algorithms":{"description":"Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.","type":"array","default":["RS256"],"items":{"type":"string"}},"jwt_audience":{"description":"Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.","type":["string","null"],"default":null},"jwt_issuer":{"description":"Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.","type":["string","null"],"default":null},"jwt_jwks":{"description":"Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.","type":["string","null"],"default":null},"jwt_jwks_cache_ttl_secs":{"description":"Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.","type":"integer","format":"uint64","default":300,"minimum":0},"jwt_jwks_uri":{"description":"Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.","type":["string","null"],"default":null},"jwt_public_key_pem":{"description":"PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.","type":["string","null"],"default":null},"rate_limit_rps":{"description":"Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.","type":"integer","format":"uint32","default":10,"minimum":0},"require_auth":{"description":"Require an authenticated external identity for mutating calls.","type":"boolean","default":true}}},"McpTransport":{"type":"string","enum":["stdio","http"]},"MediaConfig":{"description":"Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.","type":"object","properties":{"audio_model":{"description":"Audio model name (Ollama model or OpenAI model). Default: \"whisper\".","type":"string","default":"whisper"},"audio_ollama_url":{"description":"Ollama base URL for audio transcription. Default: \"http://localhost:11434\".","type":"string","default":"http://localhost:11434"},"audio_provider":{"description":"Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".","type":"string","default":"none"},"max_audio_size_mb":{"description":"Maximum audio attachment size in MiB. Default: 20.","type":"integer","format":"uint","default":20,"minimum":0},"max_video_size_mb":{"description":"Maximum video attachment size in MiB. Default: 50.","type":"integer","format":"uint","default":50,"minimum":0},"video_max_frames":{"description":"Maximum video frames to extract per video. Default: 4.","type":"integer","format":"uint","default":4,"minimum":0},"video_provider":{"description":"Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".","type":"string","default":"none"}}},"MemoryConfig":{"description":"Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.","type":"object","properties":{"acl_enabled":{"description":"Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.","type":"boolean","default":false},"archive_after_days":{"description":"Archive daily/session files older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"auto_hydrate":{"description":"Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing","type":"boolean","default":true},"auto_save":{"description":"Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.","type":"boolean","default":true},"backend":{"description":"\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).","type":"string","default":"sqlite"},"conversation_retention_days":{"description":"For sqlite backend: prune conversation rows older than this many days","type":"integer","format":"uint32","default":3,"minimum":0},"daily_retention_days":{"description":"For sqlite backend: prune daily rows older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"embedding_cache_size":{"description":"Max embedding cache entries before LRU eviction","type":"integer","format":"uint","default":10000,"minimum":0},"embedding_dimensions":{"description":"Embedding vector dimensions","type":"integer","format":"uint","default":384,"minimum":0},"embedding_model":{"description":"Embedding model name (e.g. \"text-embedding-3-small\")","type":"string","default":"prx-local-hash-v1"},"embedding_provider":{"description":"Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"","type":"string","default":"local"},"events":{"description":"Raw/quasi-raw message event recording controls (`[memory.events]`).","$ref":"#/$defs/MemoryEventsConfig","default":{"record_assistant_messages":true,"record_tool_events":false,"record_user_messages":true}},"keyword_weight":{"description":"Weight for keyword BM25 in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.3},"legacy_conversation_turns_visible":{"description":"Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.","type":"boolean","default":true},"lucid_budget":{"description":"Token budget for lucid (replaces OPENPRX_LUCID_BUDGET)","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"lucid_cmd":{"description":"Path to lucid binary (replaces OPENPRX_LUCID_CMD)","type":["string","null"],"default":null},"lucid_failure_cooldown_ms":{"description":"Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)","type":"integer","format":"uint64","default":60000,"minimum":0},"lucid_local_hit_threshold":{"description":"Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)","type":"integer","format":"uint","default":3,"minimum":0},"lucid_recall_timeout_ms":{"description":"Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)","type":"integer","format":"uint64","default":5000,"minimum":0},"lucid_store_timeout_ms":{"description":"Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)","type":"integer","format":"uint64","default":3000,"minimum":0},"min_relevance_score":{"description":"Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4","type":"number","format":"double","default":0.4},"purge_after_days":{"description":"Purge archived files older than this many days","type":"integer","format":"uint32","default":30,"minimum":0},"semantic":{"description":"Semantic memory promotion controls (`[memory.semantic]`).","$ref":"#/$defs/MemorySemanticConfig","default":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30}},"sqlite_open_timeout_secs":{"description":"For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"sqlite_read_pool_size":{"description":"For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"vector_candidate_cap":{"description":"How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.","type":"integer","format":"uint","default":2000,"minimum":0},"vector_weight":{"description":"Weight for vector similarity in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.7}}},"MemoryEventsConfig":{"description":"Raw message event recording configuration (`[memory.events]`).","type":"object","properties":{"record_assistant_messages":{"description":"Record assistant replies.","type":"boolean","default":true},"record_tool_events":{"description":"Record tool/event payloads by default.","type":"boolean","default":false},"record_user_messages":{"description":"Record inbound/user messages.","type":"boolean","default":true}}},"MemorySemanticConfig":{"description":"Semantic memory promotion configuration (`[memory.semantic]`).","type":"object","properties":{"auto_promote_assistant_messages":{"description":"Auto-promote eligible assistant messages. Disabled by default to reduce noise.","type":"boolean","default":false},"auto_promote_user_messages":{"description":"Auto-promote eligible user messages into long-term semantic memories.","type":"boolean","default":true},"min_chars":{"description":"Minimum content length for semantic auto-promotion.","type":"integer","format":"uint","default":30,"minimum":0}}},"MemoryWebhookConfig":{"type":"object","properties":{"bind":{"description":"Socket address for the receiver (e.g. \"0.0.0.0:16899\").","type":"string","default":"0.0.0.0:16899"},"signing_secret":{"description":"Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.","type":["string","null"],"default":null},"token":{"description":"Required bearer token for incoming webhook events.","type":["string","null"],"default":null}}},"ModelOperationSetting":{"description":"The operations a `[[providers.models]]` entry may list.","type":"string","enum":["chat","embedding","decision_endpoint","rerank","image_generation","audio_generation","video_generation"]},"ModelPricing":{"description":"Per-model pricing entry (USD per 1M tokens).","type":"object","properties":{"cache_read":{"description":"Cache read input price per 1M tokens.","type":"number","format":"double","default":0.0},"cache_write":{"description":"Cache write/creation input price per 1M tokens.","type":"number","format":"double","default":0.0},"input":{"description":"Input price per 1M tokens","type":"number","format":"double","default":0.0},"output":{"description":"Output price per 1M tokens","type":"number","format":"double","default":0.0}}},"ModelRouteConfig":{"description":"Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"hint":{"description":"Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")","type":"string"},"level":{"type":["string","null"]},"model":{"description":"Model to use with that provider","type":"string"},"provider":{"description":"Provider to route to (must match a known provider name)","type":"string"},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true,"required":["hint","provider","model"]},"ModelSettings":{"description":"A model level plus explicit parameter overrides in `[model_settings.\"\"]`.","type":"object","properties":{"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"level":{"type":["string","null"]},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true},"MultimodalConfig":{"description":"Multimodal (image) handling configuration (`[multimodal]` section).","type":"object","properties":{"allow_remote_fetch":{"description":"Allow fetching remote image URLs (http/https). Enabled by default.","type":"boolean","default":true},"max_image_size_mb":{"description":"Maximum image payload size in MiB before base64 encoding.","type":"integer","format":"uint","default":5,"minimum":0},"max_images":{"description":"Maximum number of image attachments accepted per request.","type":"integer","format":"uint","default":4,"minimum":0}}},"NextcloudTalkConfig":{"description":"Nextcloud Talk bot configuration (webhook receive + OCS send API).","type":"object","properties":{"allowed_users":{"description":"Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Bot app token used for OCS API bearer auth.","type":"string"},"base_url":{"description":"Nextcloud base URL (e.g. \"https://cloud.example.com\").","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"webhook_secret":{"description":"Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).","type":["string","null"],"default":null}},"required":["base_url","app_token"]},"NgrokTunnelConfig":{"type":"object","properties":{"auth_token":{"description":"ngrok auth token","type":"string"},"domain":{"description":"Optional custom domain","type":["string","null"]}},"required":["auth_token"]},"NodeServerConfig":{"description":"Node daemon runtime config used by `prx-node`.","type":"object","properties":{"allowed_commands":{"description":"Command allowlist matched on first token. Default: empty, which allows any\ncommand from an authenticated caller; `[\"*\"]` means the same.","type":"array","default":[],"items":{"type":"string"}},"bearer_token":{"description":"Required bearer token for /rpc.","type":"string","default":""},"blocked_commands":{"description":"Command denylist matched on first token. Always enforced.","type":"array","default":[],"items":{"type":"string"}},"exec_timeout_ms":{"description":"Default command timeout in milliseconds.","type":"integer","format":"uint64","default":15000,"minimum":0},"hmac_secret":{"description":"Optional HMAC signing secret.","type":["string","null"],"default":null},"listen_addr":{"description":"Listen address for node daemon.","type":"string","default":"127.0.0.1:8787"},"max_concurrent_tasks":{"description":"Maximum number of concurrent async command tasks.","type":"integer","format":"uint","default":8,"minimum":0},"max_output_bytes":{"description":"Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.","type":"integer","format":"uint","default":1048576,"minimum":0},"sandbox_root":{"description":"Sandbox root directory for read/write/cwd constraints.","type":"string","default":"."},"task_result_ttl_ms":{"description":"TTL for completed task results in milliseconds.","type":"integer","format":"uint64","default":3600000,"minimum":0},"tls_cert":{"description":"TLS certificate path (PEM).","type":["string","null"],"default":null},"tls_key":{"description":"TLS private key path (PEM).","type":["string","null"],"default":null},"tls_required":{"description":"Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.","type":"boolean","default":true}}},"NodesConfig":{"description":"Remote node proxy configuration for core-side RPC calls and node daemon defaults.","type":"object","properties":{"nodes":{"description":"Configured remote nodes.","type":"array","default":[],"items":{"$ref":"#/$defs/RemoteNodeConfig"}},"request_timeout_ms":{"description":"Default request timeout for node RPC calls.","type":"integer","format":"uint64","default":15000,"minimum":0},"retry_max":{"description":"Default max retries for node RPC calls.","type":"integer","format":"uint8","default":2,"maximum":255,"minimum":0},"server":{"description":"Embedded node server defaults used by `prx-node`.","$ref":"#/$defs/NodeServerConfig","default":{"allowed_commands":[],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}}},"ObservabilityConfig":{"description":"Observability backend configuration (`[observability]` section).","type":"object","properties":{"backend":{"description":"\"none\" | \"log\" | \"prometheus\" | \"otel\"","type":"string","default":"none"},"otel_endpoint":{"description":"OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".","type":["string","null"],"default":null},"otel_service_name":{"description":"Service name reported to the OTel collector. Defaults to \"prx\".","type":["string","null"],"default":null}}},"OllamaProviderConfig":{"description":"Ollama-specific request options (`[providers.ollama]`).","type":"object","properties":{"num_ctx":{"description":"Explicit context window sent as Ollama `options.num_ctx`.","type":["integer","null"],"format":"uint","default":null,"minimum":0}}},"OsPagingConfig":{"description":"Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.","type":"object","properties":{"eviction_threshold":{"description":"Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.","type":"number","format":"double","default":0.7},"keep_recent_messages":{"description":"Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).","type":"integer","format":"uint","default":12,"minimum":0},"max_recalled_pages":{"description":"Maximum number of evicted pages (document chunks) recalled per turn.","type":"integer","format":"uint","default":10,"minimum":0},"proactive_retrieval":{"description":"Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.","type":"boolean","default":true},"retrieval_injection_role":{"description":"Role under which recalled pages are injected.","$ref":"#/$defs/RetrievalInjectionRole","default":"system"}}},"PluginsConfig":{"description":"WASM plugin runtime configuration.","type":"object","properties":{"enabled":{"description":"Load WASM plugins from `/plugins`. Default: `false`.","type":"boolean","default":false}},"additionalProperties":false},"ProviderModelConfig":{"description":"One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.","type":"object","properties":{"context_window":{"description":"The model's context window in tokens.","type":["integer","null"],"format":"uint32","minimum":0},"model":{"description":"The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.","type":["string","null"]},"native_tools":{"description":"Whether the model accepts native tool calls.","type":["boolean","null"]},"operations":{"description":"The complete list of operations the model executes; every operation not\nlisted is unsupported.","type":["array","null"],"items":{"$ref":"#/$defs/ModelOperationSetting"}},"provider":{"description":"The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.","type":"string"},"streaming":{"description":"Whether the model streams responses.","type":["boolean","null"]},"structured_output":{"description":"Whether the model honours a JSON-schema response format.","type":["boolean","null"]},"tool_call_dialect":{"description":"The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema_dialect":{"description":"The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]},"vision_input":{"description":"Whether the model accepts image input.","type":["boolean","null"]}},"required":["provider"]},"ProviderToolDialectConfig":{"description":"One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.","type":"object","properties":{"model":{"description":"The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.","type":["string","null"]},"provider":{"description":"The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.","type":"string"},"tool_call":{"description":"The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema":{"description":"The tool-schema dialect the endpoint accepts.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]}},"required":["provider"]},"ProvidersConfig":{"description":"Provider-specific runtime configuration (`[providers]`).","type":"object","properties":{"models":{"description":"Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.","type":"array","items":{"$ref":"#/$defs/ProviderModelConfig"}},"ollama":{"description":"Ollama-specific request options (`[providers.ollama]`).","$ref":"#/$defs/OllamaProviderConfig","default":{"num_ctx":null}},"tool_dialects":{"description":"Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).","type":"array","items":{"$ref":"#/$defs/ProviderToolDialectConfig"}}}},"ProxyConfig":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).","type":"object","properties":{"all_proxy":{"description":"Fallback proxy URL for all schemes.","type":["string","null"],"default":null},"http_proxy":{"description":"Proxy URL for HTTP requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"https_proxy":{"description":"Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"no_proxy":{"description":"No-proxy bypass list. Same format as NO_PROXY.","type":"array","default":[],"items":{"type":"string"}},"scope":{"description":"Proxy application scope.","$ref":"#/$defs/ProxyScope","default":"prx"},"services":{"description":"Service selectors used when scope = \"services\".","type":"array","default":[],"items":{"type":"string"}}}},"ProxyScope":{"description":"Proxy application scope — determines which outbound traffic uses the proxy.","oneOf":[{"description":"Use system environment proxy variables only.","type":"string","const":"environment"},{"description":"Apply proxy to all OpenPRX-managed HTTP traffic (default).","type":"string","const":"prx"},{"description":"Apply proxy only to explicitly listed service selectors.","type":"string","const":"services"}]},"QQConfig":{"description":"QQ Official Bot configuration (Tencent QQ Bot SDK)","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs. Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from QQ Bot developer console","type":"string"},"app_secret":{"description":"App Secret from QQ Bot developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["app_id","app_secret"]},"QueryClassificationConfig":{"description":"Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.","type":"object","properties":{"rules":{"description":"Classification rules evaluated in priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/ClassificationRule"}}}},"RamfluxAccountConfig":{"description":"Persona for one ramflux AI account. Missing fields fall back to the global agent.","type":"object","properties":{"cross_conversation_retrieval":{"description":"Cross-conversation memory retrieval. Off unless the owner sets it.","type":"boolean","default":false},"model":{"type":["string","null"],"default":null},"provider":{"type":["string","null"],"default":null},"scope_profile":{"type":["string","null"],"default":null},"system_prompt_file":{"description":"Path to a system-prompt file. Relative paths are resolved from the workspace.","type":["string","null"],"default":null}},"additionalProperties":false},"RamfluxAttachmentFetch":{"description":"Per-turn caps for `attachment.fetch`.","type":"object","properties":{"max_bytes":{"type":"integer","format":"uint64","default":5242880,"minimum":0},"max_per_turn":{"type":"integer","format":"uint8","default":4,"maximum":255,"minimum":0}},"additionalProperties":false},"RamfluxAuthorizationMode":{"description":"How prx combines its own setting with `bridge.hello.authorization`.","oneOf":[{"description":"Use the agent-host value. Until hello arrives, the effective mode is supervised.","type":"string","const":"follow_rf"},{"description":"Always supervised, even when the agent-host declares full.","type":"string","const":"supervised"},{"description":"Full only when the agent-host also declares full. Config alone never yields full.","type":"string","const":"full"}]},"RamfluxConfig":{"description":"Local ramflux agent-host bridge (`[channels_config.ramflux]`).","type":"object","properties":{"accounts":{"type":"object","additionalProperties":{"$ref":"#/$defs/RamfluxAccountConfig"},"default":{}},"allowed_block_types":{"type":"array","default":["Text","Markdown","Heading","KeyValue","Metric","List","TableFallback","Form","Input","Select","Progress","LogStream","Warning","Error","Success","Approval","ActionGroup","FilePreview","Fallback"],"items":{"type":"string"}},"attachment_fetch":{"$ref":"#/$defs/RamfluxAttachmentFetch","default":{"max_bytes":5242880,"max_per_turn":4}},"authorization_mode":{"$ref":"#/$defs/RamfluxAuthorizationMode","default":"follow_rf"},"encrypt_at_rest":{"type":"boolean","default":true},"max_in_flight_per_conversation":{"type":"integer","format":"uint8","default":1,"maximum":255,"minimum":0},"on_new_message":{"$ref":"#/$defs/RamfluxOnNewMessage","default":"queue"},"socket_path":{"description":"Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.","type":["string","null"],"default":null},"surface_limits":{"$ref":"#/$defs/RamfluxSurfaceLimits","default":{"max_actions":16,"max_blocks":32,"max_bytes":65536}},"turn_wall_clock_secs":{"description":"Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.","type":"integer","format":"uint64","default":120,"minimum":0}},"additionalProperties":false},"RamfluxOnNewMessage":{"description":"What to do with a new inbound message while a turn for that conversation is running.","type":"string","enum":["queue","interrupt"]},"RamfluxSurfaceLimits":{"description":"Limits for `reply.surface` blocks and actions.","type":"object","properties":{"max_actions":{"type":"integer","format":"uint32","default":16,"minimum":0},"max_blocks":{"type":"integer","format":"uint32","default":32,"minimum":0},"max_bytes":{"type":"integer","format":"uint32","default":65536,"minimum":0}},"additionalProperties":false},"ReliabilityCircuitBreakerConfig":{"description":"Process-local provider circuit policy (`[reliability.circuit_breaker]`).","type":"object","properties":{"enabled":{"description":"Enable protection for factory-built provider chains.","type":"boolean","default":true},"failure_threshold":{"description":"Consecutive transient failures that open a circuit (at least 1).","type":"integer","format":"uint32","default":5,"minimum":0},"max_open_secs":{"description":"Maximum doubled window, between open_secs and 3600 seconds.","type":"integer","format":"uint64","default":300,"minimum":0},"open_secs":{"description":"Initial open window in seconds (at least 1).","type":"integer","format":"uint64","default":30,"minimum":0}}},"ReliabilityConfig":{"description":"Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.","type":"object","properties":{"acknowledge_single_provider_risk":{"description":"Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.","type":"boolean","default":false},"api_keys":{"description":"Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.","type":"array","default":[],"items":{"type":"string"}},"channel_initial_backoff_secs":{"description":"Initial backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":2,"minimum":0},"channel_max_backoff_secs":{"description":"Max backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":60,"minimum":0},"circuit_breaker":{"description":"Per-provider consecutive failure protection.","$ref":"#/$defs/ReliabilityCircuitBreakerConfig","default":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30}},"fallback_providers":{"description":"Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).","type":"array","default":[],"items":{"type":"string"}},"model_fallbacks":{"description":"Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`","type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"default":{}},"provider_backoff_ms":{"description":"Base backoff (ms) for provider retry delay.","type":"integer","format":"uint64","default":500,"minimum":0},"provider_retries":{"description":"Retries per provider before failing over.","type":"integer","format":"uint32","default":2,"minimum":0},"scheduler_poll_secs":{"description":"Scheduler polling cadence in seconds.","type":"integer","format":"uint64","default":15,"minimum":0},"scheduler_retries":{"description":"Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.","type":"integer","format":"uint32","default":2,"minimum":0}}},"RemoteNodeConfig":{"description":"A remote node target for core-side node proxy calls.","type":"object","properties":{"bearer_token":{"description":"Bearer token for node RPC authentication.","type":"string"},"endpoint":{"description":"Base endpoint (e.g. \"http://127.0.0.1:8787\").","type":"string"},"hmac_secret":{"description":"Optional request signing key (HMAC-SHA256).","type":["string","null"],"default":null},"id":{"description":"Stable node ID used by the nodes tool.","type":"string"},"retry_max":{"description":"Optional per-node retry override.","type":["integer","null"],"format":"uint8","default":null,"maximum":255,"minimum":0},"timeout_ms":{"description":"Optional per-node timeout override.","type":["integer","null"],"format":"uint64","default":null,"minimum":0}},"required":["id","endpoint","bearer_token"]},"RetrievalInjectionRole":{"description":"Where recalled context pages are injected back into the request.","oneOf":[{"description":"Inject recalled pages as a leading `system` message (not user-visible).","type":"string","const":"system"},{"description":"Inject recalled pages as a leading `user` message.","type":"string","const":"user"}]},"RouterConfig":{"description":"Heuristic LLM router configuration (`[router]` section).","type":"object","properties":{"alpha":{"description":"Similarity score weight. Phase 1 keeps this at `0.0`.","type":"number","format":"float","default":0.0},"beta":{"description":"Capability score weight.","type":"number","format":"float","default":0.5},"delta":{"description":"Cost penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"epsilon":{"description":"Latency penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"gamma":{"description":"Elo score weight.","type":"number","format":"float","default":0.30000001192092896},"knn_k":{"description":"Number of nearest neighbors considered for voting. Default: `7`.","type":"integer","format":"uint","default":7,"minimum":0},"knn_min_records":{"description":"Minimum history records before KNN affects routing. Default: `10`.","type":"integer","format":"uint","default":10,"minimum":0},"models":{"description":"Candidate model registry.","type":"array","default":[],"items":{"$ref":"#/$defs/RouterModelConfig"}}}},"RouterModelConfig":{"description":"Static router metadata for one model candidate.","type":"object","properties":{"categories":{"description":"Capability categories such as `conversation`, `code`, or `analysis`.","type":"array","default":[],"items":{"type":"string"}},"cost_per_million_tokens":{"description":"USD cost per million tokens.","type":"number","format":"float","default":0.0},"elo_rating":{"description":"Initial Elo rating.","type":"number","format":"float","default":1000.0},"latency_ms":{"description":"Average latency in milliseconds.","type":"integer","format":"uint32","default":2000,"minimum":0},"max_context":{"description":"Maximum context window in tokens.","type":"integer","format":"uint","default":1000000,"minimum":0},"model_id":{"description":"Model identifier without provider prefix.","type":"string"},"provider":{"description":"Provider identifier.","type":"string"},"reserved_output_tokens":{"description":"Output tokens reserved for this model when planning input context.","type":["integer","null"],"format":"uint","minimum":0}},"required":["model_id","provider"]},"RuntimeConfig":{"description":"Runtime adapter configuration (`[runtime]` section).","type":"object","properties":{"codex_reasoning_effort":{"description":"Codex reasoning effort","type":["string","null"],"default":null},"codex_stream_idle_timeout_secs":{"description":"Codex stream idle timeout in seconds","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"docker":{"description":"Docker runtime settings (used when `kind = \"docker\"`).","$ref":"#/$defs/DockerRuntimeConfig","default":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true}},"idle_hang_secs":{"description":"Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"kind":{"description":"Runtime kind (`native` | `docker`).","type":"string","default":"native"},"long_task_warn_secs":{"description":"Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"managed_cgroup_root":{"description":"Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.","type":["string","null"],"default":null},"max_blocking_threads":{"description":"Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"reasoning_enabled":{"description":"Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported","type":["boolean","null"],"default":null},"shell_env_allowlist":{"description":"Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.","type":"array","default":[],"items":{"type":"string"}},"workdir":{"description":"Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.","type":["string","null"],"default":null}}},"SchedulerConfig":{"description":"Scheduler configuration for periodic task execution (`[scheduler]` section).","type":"object","properties":{"claim_lease_secs":{"description":"Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.","type":"integer","format":"uint64","default":90,"minimum":0},"max_tasks":{"description":"Maximum number of persisted scheduled tasks.","type":"integer","format":"uint","default":64,"minimum":0}}},"ScopeConfig":{"description":"Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```","type":"object","properties":{"assign_owners":{"description":"Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.","type":"array","default":[],"items":{"type":"string"}},"default":{"description":"Default action when no rule matches: \"allow\" (default) or \"deny\".","$ref":"#/$defs/ScopeDefault","default":"allow"},"rules":{"description":"Ordered list of scope rules evaluated top-to-bottom.","type":"array","default":[],"items":{"$ref":"#/$defs/ScopeRule"}}}},"ScopeDefault":{"description":"What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.","oneOf":[{"description":"Unmatched tool calls are allowed (the default).","type":"string","const":"allow"},{"description":"Unmatched tool calls are refused.","type":"string","const":"deny"}]},"ScopeRule":{"description":"A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.","type":"object","properties":{"assign_allow":{"description":"Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".","type":"array","default":[],"items":{"type":"string"}},"assign_deny":{"description":"Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.","type":"array","default":[],"items":{"type":"string"}},"channel":{"description":"Match by channel name: \"signal\", \"telegram\", \"discord\", etc.","type":["string","null"]},"chat_type":{"description":"Match by chat type: \"direct\", \"group\", or \"*\" for any type.","type":["string","null"]},"send_allow":{"description":"Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.","type":"array","default":[],"items":{"type":"string"}},"send_deny":{"description":"Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.","type":"array","default":[],"items":{"type":"string"}},"tools_allow":{"description":"Tool whitelist: only these tools are allowed (empty = all tools permitted).","type":"array","default":[],"items":{"type":"string"}},"tools_deny":{"description":"Tool blacklist: these tools are denied regardless of allow list.","type":"array","default":[],"items":{"type":"string"}},"user":{"description":"Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.","type":["string","null"]}}},"SecretsConfig":{"description":"Secrets encryption configuration (`[secrets]` section).","type":"object","properties":{"encrypt":{"description":"Enable encryption for API keys and tokens in config.toml","type":"boolean","default":true}}},"SecurityConfig":{"description":"Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.","type":"object","properties":{"audit":{"description":"Audit logging configuration","$ref":"#/$defs/AuditConfig","default":{"log_path":"audit.log","max_size_mb":100}},"workspace_hooks":{"description":"Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.","$ref":"#/$defs/WorkspaceHooks"}}},"SelfSystemConfig":{"description":"Self-system experimental automation config (`[self_system]`).","type":"object","properties":{"evolution_config_path":{"description":"Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG)","type":["string","null"],"default":null},"evolution_debug_raw":{"description":"Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW)","type":"boolean","default":false},"evolution_interval_hours":{"description":"Evolution scheduler interval in hours (daemon mode).","type":"integer","format":"uint32","default":24,"minimum":0},"evolution_judge_timeout_secs":{"description":"Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.","type":"integer","format":"uint64","default":180,"minimum":0},"evolution_model_max_micro_usd":{"description":"Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.","type":"integer","format":"uint64","default":0,"minimum":0},"evolution_model_max_tokens":{"description":"Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.","type":"integer","format":"uint64","default":16384,"minimum":0},"fitness":{"description":"Daily fitness snapshot policy.","$ref":"#/$defs/FitnessConfig","default":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"}},"fitness_interval_hours":{"description":"Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.","type":"integer","format":"uint64","default":24,"minimum":0}}},"SessionsSpawnConfig":{"description":"Sessions spawn configuration (`[sessions_spawn]` section).","type":"object","properties":{"cleanup_on_complete":{"description":"Remove worker workspace directory after process-mode completion.","type":"boolean","default":true},"default_mode":{"description":"Default execution mode for sessions_spawn (`task` or `process`).","type":"string","default":"task"},"process_memory_strategy":{"description":"Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.","type":"string","default":"shared_fabric"},"worker_workspace_root":{"description":"Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.","type":["string","null"],"default":null}}},"SignalConfig":{"type":"object","properties":{"account":{"description":"E.164 phone number of the signal-cli account (e.g. \"+1234567890\").","type":"string"},"allowed_from":{"description":"Allowed sender phone numbers (E.164) or \"*\" for all.","type":"array","default":[],"items":{"type":"string"}},"cli_path":{"description":"Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).","type":["string","null"],"default":null},"daemon_http_port":{"description":"Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"daemon_mode":{"description":"Deprecated: ignored. Accepted for backward compatibility with older config files.","type":["boolean","null"],"default":null},"data_dir":{"description":"signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_id":{"description":"Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group","type":["string","null"],"default":null},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"http_url":{"description":"Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.","type":"string","default":"http://localhost:8080"},"ignore_attachments":{"description":"Skip messages that are attachment-only (no text body).","type":"boolean","default":false},"ignore_stories":{"description":"Skip incoming story messages.","type":"boolean","default":false},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"mode":{"description":"Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.","type":["string","null"],"default":null},"startup_timeout_ms":{"description":"Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.","type":"integer","format":"uint64","default":30000,"minimum":0},"storm_protection":{"description":"Signal ingress storm protection controls.","$ref":"#/$defs/SignalStormProtectionConfig","default":{"abnormal_threshold":10,"abnormal_window_secs":60,"breaker_duration_secs":300,"dedupe_ttl_secs":60,"min_reply_interval_secs":2}}},"required":["account"]},"SignalStormProtectionConfig":{"type":"object","properties":{"abnormal_threshold":{"description":"Non-user event threshold within `abnormal_window_secs` before tripping the breaker.","type":"integer","format":"uint","default":10,"minimum":0},"abnormal_window_secs":{"description":"Sliding window in seconds for non-user event counting.","type":"integer","format":"uint64","default":60,"minimum":0},"breaker_duration_secs":{"description":"Circuit breaker duration in seconds after threshold is reached.","type":"integer","format":"uint64","default":300,"minimum":0},"dedupe_ttl_secs":{"description":"Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.","type":"integer","format":"uint64","default":60,"minimum":0},"min_reply_interval_secs":{"description":"Minimum interval in seconds between replies for the same `(channel + reply_target)`.","type":"integer","format":"uint64","default":2,"minimum":0}}},"SkillRagConfig":{"description":"Dynamic skill retrieval configuration (`[skill_rag]` section).","type":"object","properties":{"top_k":{"description":"How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).","type":"integer","format":"uint","default":32,"minimum":0}}},"SkillSuiteRegistration":{"description":"The frozen suite that governs one skill's proposals.","type":"object","properties":{"skill_id":{"description":"The skill the suite governs.","type":"string"},"suite_digest":{"description":"SHA-256 digest (64 lowercase hex digits) of the frozen suite.","type":"string"}},"additionalProperties":false,"required":["skill_id","suite_digest"]},"SkillsConfig":{"description":"Skills loading configuration (`[skills]` section).","type":"object","properties":{"open_skills_dir":{"description":"Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.","type":["string","null"],"default":null},"openclaw_skills_dir":{"description":"Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.","type":["string","null"],"default":null}}},"SkillsLifecycleConfig":{"description":"`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.","type":"object","properties":{"allow_executable_proposals":{"description":"Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.","type":"boolean","default":false},"enabled":{"description":"Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.","type":"boolean","default":false},"max_concurrent_evaluations":{"description":"Most evaluations running at once.","type":"integer","format":"uint32","default":1,"minimum":0},"max_edit_fraction":{"description":"Edit budget of a proposal as a fraction of the skill body, in (0, 1].","type":"number","format":"double","default":0.2},"max_edit_tokens":{"description":"Edit budget of a proposal, in tokens.","type":"integer","format":"uint64","default":300,"minimum":0},"max_proposals_per_cycle":{"description":"Most proposals one cycle may start.","type":"integer","format":"uint32","default":1,"minimum":0},"min_cases_floor":{"description":"Smallest `min_cases` a governing suite may declare. Below 3 is refused.","type":"integer","format":"uint32","default":3,"minimum":0},"mode":{"description":"`draft_only`, `shadow` or `auto`.","$ref":"#/$defs/SkillsLifecycleModeConfig","default":"draft_only"},"owner_scope":{"description":"The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.","type":["string","null"],"default":null},"require_holdout":{"description":"A governing suite must have a holdout split. `false` is refused.","type":"boolean","default":true},"storage_dir":{"description":"Store location under the workspace. Only the default is supported.","type":"string","default":"self/skill-lifecycle"},"suites":{"description":"The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.","type":"array","default":[],"items":{"$ref":"#/$defs/SkillSuiteRegistration"}}},"additionalProperties":false},"SkillsLifecycleModeConfig":{"description":"What the lifecycle may do. Mirrors `LifecycleMode`.","oneOf":[{"description":"Drafts and reviews only.","type":"string","const":"draft_only"},{"description":"Drafts plus evaluation and gating; never publishes.","type":"string","const":"shadow"},{"description":"Publishes an eligible proposal after every gate.","type":"string","const":"auto"}]},"SlackConfig":{"description":"Slack bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Slack user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Slack app-level token for Socket Mode (xapp-...).","type":["string","null"]},"bot_token":{"description":"Slack bot OAuth token (xoxb-...).","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["bot_token"]},"SmartGroupConfig":{"description":"Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).","type":"object","properties":{"classifier_max_context_messages":{"description":"How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.","type":"integer","format":"uint","default":3,"minimum":0},"classifier_model":{"description":"Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.","type":"string","default":""},"classifier_provider":{"description":"Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.","type":"string","default":""},"classifier_temperature":{"description":"Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).","type":"number","format":"double","default":0.0},"classifier_timeout_secs":{"description":"Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.","type":"integer","format":"uint64","default":5,"minimum":0}}},"StorageConfig":{"description":"Persistent storage configuration (`[storage]` section).","type":"object","properties":{"provider":{"description":"Storage provider settings (e.g. sqlite, postgres).","$ref":"#/$defs/StorageProviderSection","default":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}}},"StorageProviderConfig":{"description":"Storage provider backend configuration (e.g. postgres connection details).","type":"object","properties":{"connect_timeout_secs":{"description":"Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"db_url":{"description":"Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.","type":["string","null"],"default":null},"pool_max_size":{"description":"Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.","type":"integer","format":"uint","default":32,"minimum":0},"provider":{"description":"Storage engine key (e.g. \"postgres\", \"sqlite\").","type":"string","default":""},"schema":{"description":"Database schema for SQL backends.","type":"string","default":"public"},"table":{"description":"Table name for memory entries.","type":"string","default":"memories"}}},"StorageProviderSection":{"description":"Wrapper for the storage provider configuration section.","type":"object","properties":{"config":{"description":"Storage provider backend settings.","$ref":"#/$defs/StorageProviderConfig","default":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"StreamMode":{"description":"Streaming mode for channels that support progressive message updates.","oneOf":[{"description":"No streaming -- send the complete response as a single message (default).","type":"string","const":"off"},{"description":"Update a draft message with every flush interval.","type":"string","const":"partial"}]},"TailscaleTunnelConfig":{"type":"object","properties":{"funnel":{"description":"Use Tailscale Funnel (public internet) vs Serve (tailnet only)","type":"boolean","default":false},"hostname":{"description":"Optional hostname override","type":["string","null"]}}},"TaskRoutingConfig":{"description":"Lightweight pre-LLM task routing.","type":"object","properties":{"default_intent":{"description":"Fallback intent when no rule matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"rules":{"description":"Rules evaluated in descending priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/TaskRoutingRule"}}}},"TaskRoutingIntentConfig":{"description":"Task-routing default and rule intent.","type":"string","enum":["simple","delegate","stream"]},"TaskRoutingRule":{"description":"A single task-routing rule.","type":"object","properties":{"intent":{"description":"Route intent to apply when a keyword matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"model_hint":{"description":"Optional model hint/raw model for non-delegated requests.","type":["string","null"],"default":null},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0},"sub_agent_model":{"description":"Optional raw sub-agent model override for delegated tasks.","type":["string","null"],"default":null}}},"TelegramConfig":{"description":"Telegram bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Telegram user IDs or usernames. Empty = deny all.","type":"array","items":{"type":"string"}},"bot_token":{"description":"Telegram Bot API token (from @BotFather).","type":"string"},"draft_update_interval_ms":{"description":"Minimum interval (ms) between draft message edits to avoid rate limits.","type":"integer","format":"uint64","default":1000,"minimum":0},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"interrupt_on_new_message":{"description":"When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.","type":"boolean","default":false},"stream_mode":{"description":"Streaming mode for progressive response delivery via message edits.","$ref":"#/$defs/StreamMode","default":"off"}},"required":["bot_token","allowed_users"]},"ToolCallDialectSetting":{"description":"The tool-call grammars an operator may declare for an endpoint.","oneOf":[{"description":"Only the native `tool_calls` array is a tool call (the default).","type":"string","const":"native"},{"description":"Additionally read `{json}` from the content,\nfor a tool name the request registered.","type":"string","const":"xml_function_tags"}]},"ToolSchemaDialectSetting":{"description":"The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.","oneOf":[{"description":"The published document, byte for byte (the default).","type":"string","const":"raw"},{"description":"The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.","type":"string","const":"no_root_combinators"}]},"ToolTieringConfig":{"description":"Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.","type":"object","properties":{"always_exclude":{"description":"Tool names excluded from capability publication.","type":"array","default":[],"items":{"type":"string"}},"always_include":{"description":"Tool names preferred for direct publication, subject to admission gates.","type":"array","default":[],"items":{"type":"string"}},"channel_exclude":{"description":"Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefault: empty (nothing is hidden); list tool names to hide them on channels.","type":"array","default":[],"items":{"type":"string"}}}},"TunnelConfig":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.","type":"object","properties":{"cloudflare":{"description":"Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).","anyOf":[{"$ref":"#/$defs/CloudflareTunnelConfig"},{"type":"null"}],"default":null},"custom":{"description":"Custom tunnel command configuration (used when `provider = \"custom\"`).","anyOf":[{"$ref":"#/$defs/CustomTunnelConfig"},{"type":"null"}],"default":null},"ngrok":{"description":"ngrok tunnel configuration (used when `provider = \"ngrok\"`).","anyOf":[{"$ref":"#/$defs/NgrokTunnelConfig"},{"type":"null"}],"default":null},"provider":{"description":"Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.","type":"string","default":"none"},"tailscale":{"description":"Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).","anyOf":[{"$ref":"#/$defs/TailscaleTunnelConfig"},{"type":"null"}],"default":null}}},"UserPolicyConfig":{"description":"Startup user policy entry (`[[user_policies]]`).","type":"object","properties":{"blocked_patterns":{"type":"array","default":[],"items":{"type":"string"}},"projects":{"type":"array","default":[],"items":{"type":"string"}},"role":{"type":"string","default":"guest"},"user_id":{"type":"string"},"visibility_ceiling":{"type":"string","default":"private"}},"required":["user_id"]},"WacliConfig":{"description":"wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```","type":"object","properties":{"allow_unsigned_loopback":{"description":"Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).","type":"boolean","default":false},"allowed_from":{"description":"Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.","type":"array","default":["*"],"items":{"type":"string"}},"bot_jid":{"description":"Bot's own JID, used for reply-to-bot mention detection.","type":["string","null"],"default":null},"bot_lid":{"description":"The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.","type":["string","null"],"default":null},"bot_number":{"description":"Bot's own phone number (digits), used for `@` mention detection.","type":["string","null"],"default":null},"cli_path":{"description":"Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.","type":["string","null"],"default":null},"group_reply_mode":{"description":"Smart group-reply mode. When `None`, derived from `mention_only`.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"host":{"description":"REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].","type":["string","null"],"writeOnly":true},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"outbound_media_workspace_only":{"description":"Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.","type":"boolean","default":false},"port":{"description":"REMOVED: legacy JSON-RPC daemon port. See `host`.","type":["integer","null"],"format":"uint16","maximum":65535,"minimum":0,"writeOnly":true},"self_chat_mode":{"description":"Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.","type":"boolean","default":false},"store_dir":{"description":"wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.","type":["string","null"],"default":null},"webhook_listen":{"description":"Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").","type":"string","default":"127.0.0.1:16868"},"webhook_path":{"description":"HTTP path the webhook server serves (default: \"/wacli\").","type":"string","default":"/wacli"},"webhook_secret":{"description":"HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.","type":["string","null"],"default":null}}},"WebSearchConfig":{"description":"Web search tool configuration (`[web_search]` section).","type":"object","properties":{"brave_api_key":{"description":"Brave Search API key (required if provider is \"brave\")","type":["string","null"],"default":null},"fetch_max_chars":{"description":"Maximum characters returned by `web_fetch` (default 10000)","type":"integer","format":"uint","default":50000,"minimum":0},"max_results":{"description":"Maximum results per search (1-20)","type":"integer","format":"uint","default":15,"minimum":0},"provider":{"description":"Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)","type":"string","default":"duckduckgo"},"timeout_secs":{"description":"Request timeout in seconds","type":"integer","format":"uint64","default":15,"minimum":0}}},"WebhookConfig":{"description":"Webhook channel configuration.","type":"object","properties":{"port":{"description":"Port to listen on for incoming webhooks.","type":"integer","format":"uint16","maximum":65535,"minimum":0},"secret":{"description":"Optional shared secret for webhook signature verification.","type":["string","null"]}},"required":["port"]},"WhatsAppConfig":{"description":"WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.","type":"object","properties":{"access_token":{"description":"Access token from Meta Business Suite (Cloud API mode)","type":["string","null"],"default":null},"allowed_numbers":{"description":"Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"app_secret":{"description":"App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"pair_code":{"description":"Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one","type":["string","null"],"default":null},"pair_phone":{"description":"Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used","type":["string","null"],"default":null},"phone_number_id":{"description":"Phone number ID from Meta Business API (Cloud API mode)","type":["string","null"],"default":null},"read_pool_size":{"description":"Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"session_path":{"description":"Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs","type":["string","null"],"default":null},"verify_token":{"description":"Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode","type":["string","null"],"default":null},"ws_url":{"description":"WebSocket URL override (replaces WHATSAPP_WS_URL)","type":["string","null"],"default":null}}},"WorkspaceHooks":{"description":"Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).","oneOf":[{"description":"They do not run (the default); `prx doctor` and `hooks_status` say so.","type":"string","const":"off"},{"description":"They run, in a cleared environment and a dedicated directory beside\n`config.toml`.","type":"string","const":"on"}]},"WorkspaceMcpServers":{"description":"Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).","oneOf":[{"description":"None: a workspace file may only narrow the servers defined in\n`config.toml`.","type":"string","const":"off"},{"description":"HTTP servers (still refused when they target a private address).","type":"string","const":"http_only"},{"description":"HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.","type":"string","const":"stdio"}]},"XinConfig":{"description":"Configuration for the xin autonomous task engine (`[xin]`).","type":"object","properties":{"adopt_legacy_tasks":{"description":"Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).","type":"boolean","default":false},"interval_minutes":{"description":"Tick interval in minutes (minimum 1). Default: 5.","type":"integer","format":"uint32","default":5,"minimum":0},"stale_timeout_minutes":{"description":"Minutes after which a running task is marked stale. Default: 60.","type":"integer","format":"uint32","default":60,"minimum":0}}},"AgentMessaging":{"description":"Owner-controlled inbound session messaging (enabled unless explicitly off).","type":"object","properties":{"inbound":{"type":"boolean","default":true}}}}} +{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Config","description":"Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).","type":"object","properties":{"a2a":{"description":"Agent-to-Agent compatibility configuration (`[a2a]`).","$ref":"#/$defs/A2aConfig","default":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trusted_trust_domains":[],"trust_domain":"prx.local"}},"agent":{"description":"Agent orchestration settings (`[agent]`).","$ref":"#/$defs/AgentConfig","default":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2,"messaging":{"inbound":true}}},"agents":{"description":"Delegate agent configurations for multi-agent workflows.","type":"object","additionalProperties":{"$ref":"#/$defs/DelegateAgentConfig"},"default":{}},"api_key":{"description":"API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.","type":["string","null"],"default":null},"api_url":{"description":"Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)","type":["string","null"],"default":null},"auth":{"description":"Auth profile and external credential import settings (`[auth]`).","$ref":"#/$defs/AuthConfig","default":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"}},"autonomy":{"description":"Autonomy and security policy configuration (`[autonomy]`).","$ref":"#/$defs/AutonomyConfig","default":{"forbidden_paths":[],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]}}},"browser":{"description":"Browser automation configuration (`[browser]`).","$ref":"#/$defs/BrowserConfig","default":{"allowed_domains":[],"computer_use":{"api_key":null}}},"channels_config":{"description":"Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).","$ref":"#/$defs/ChannelsConfig","default":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null}},"chat":{"description":"Interactive chat UI configuration (`[chat]`).","$ref":"#/$defs/ChatConfig","default":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2}},"compliance":{"description":"Operator-owned compliance controls (`[compliance]`).","$ref":"#/$defs/ComplianceConfig","default":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}},"composio":{"description":"Composio managed OAuth tools integration (`[composio]`).","$ref":"#/$defs/ComposioConfig","default":{"api_key":null,"entity_id":"default"}},"cost":{"description":"Cost tracking and budget enforcement configuration (`[cost]`).","$ref":"#/$defs/CostConfig","default":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{},"warn_at_percent":80}},"cron":{"description":"Cron job configuration (`[cron]`).","$ref":"#/$defs/CronConfig","default":{"max_run_history":50}},"decision_engine":{"description":"Optional advisory decision engine, disabled by default.","$ref":"#/$defs/DecisionEngineConfig","default":{"candidates":5,"enabled":false,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"latency_budget_ms":500,"max_candidates":12,"token_ratio_limit":0.3499999940395355}},"default_model":{"description":"Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.","type":["string","null"]},"default_provider":{"description":"Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.","type":["string","null"]},"default_temperature":{"description":"Default model temperature (0.0–2.0). Default: `0.7`.","type":"number","format":"double","default":0.7},"embedding_routes":{"description":"Embedding routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/EmbeddingRouteConfig"}},"gateway":{"description":"Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).","$ref":"#/$defs/GatewayConfig","default":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60}},"heartbeat":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]`).","$ref":"#/$defs/HeartbeatConfig","default":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."}},"http_request":{"description":"HTTP request tool configuration (`[http_request]`).","$ref":"#/$defs/HttpRequestConfig","default":{"max_response_size":1000000,"timeout_secs":30}},"identity":{"description":"Identity format configuration: OpenClaw or AIEOS (`[identity]`).","$ref":"#/$defs/IdentityConfig","default":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"}},"identity_bindings":{"description":"Static identity bindings loaded at startup (`[[identity_bindings]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/IdentityBindingConfig"}},"mcp":{"description":"Secrets encryption configuration (`[secrets]`).","$ref":"#/$defs/McpConfig","default":{"servers":{}}},"mcp_server":{"description":"MCP server compatibility configuration (`[mcp_server]`).","$ref":"#/$defs/McpServerRuntimeConfig","default":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true}},"media":{"description":"Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.","$ref":"#/$defs/MediaConfig","default":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"}},"memory":{"description":"Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).","$ref":"#/$defs/MemoryConfig","default":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":true,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7}},"model_routes":{"description":"Model routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/ModelRouteConfig"}},"model_settings":{"description":"Catalog model levels and explicit parameters, keyed by canonical release ID.","type":"object","additionalProperties":{"$ref":"#/$defs/ModelSettings"},"default":{}},"multimodal":{"description":"Multimodal (image) handling configuration (`[multimodal]`).","$ref":"#/$defs/MultimodalConfig","default":{"allow_remote_fetch":true,"max_image_size_mb":5,"max_images":4}},"nodes":{"description":"Remote node proxy configuration (`[nodes]`).","$ref":"#/$defs/NodesConfig","default":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":[],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}},"observability":{"description":"Observability backend configuration (`[observability]`).","$ref":"#/$defs/ObservabilityConfig","default":{"backend":"none","otel_endpoint":null,"otel_service_name":null}},"plugins":{"description":"WASM plugin runtime switch (`[plugins]`), off by default.","$ref":"#/$defs/PluginsConfig","default":{"enabled":false}},"providers":{"description":"Provider-specific runtime options (`[providers.]`).","$ref":"#/$defs/ProvidersConfig","default":{"ollama":{"num_ctx":null}}},"proxy":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).","$ref":"#/$defs/ProxyConfig","default":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]}},"query_classification":{"description":"Automatic query classification — maps user messages to model hints.","$ref":"#/$defs/QueryClassificationConfig","default":{"rules":[]}},"reliability":{"description":"Reliability settings: retries, fallback providers, backoff (`[reliability]`).","$ref":"#/$defs/ReliabilityConfig","default":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2}},"router":{"description":"Heuristic LLM router configuration (`[router]`).","$ref":"#/$defs/RouterConfig","default":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]}},"runtime":{"description":"Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.","$ref":"#/$defs/RuntimeConfig","default":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null}},"scheduler":{"description":"Scheduler configuration for periodic task execution (`[scheduler]`).","$ref":"#/$defs/SchedulerConfig","default":{"claim_lease_secs":90,"max_tasks":64}},"secrets":{"$ref":"#/$defs/SecretsConfig","default":{"encrypt":true}},"security":{"description":"Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).","$ref":"#/$defs/SecurityConfig","default":{"audit":{"log_path":"audit.log","max_size_mb":100}}},"self_system":{"description":"Self-system experimental automation controls (`[self_system]`).","$ref":"#/$defs/SelfSystemConfig","default":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24}},"sessions_spawn":{"description":"Session spawning configuration (`[sessions_spawn]`).","$ref":"#/$defs/SessionsSpawnConfig","default":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null}},"skill_rag":{"description":"Dynamic skill retrieval settings (`[skill_rag]`).","$ref":"#/$defs/SkillRagConfig","default":{"top_k":32}},"skills":{"description":"Skills loading and community repository behavior (`[skills]`).","$ref":"#/$defs/SkillsConfig","default":{"open_skills_dir":null,"openclaw_skills_dir":null}},"skills_lifecycle":{"description":"Skill lifecycle (`[skills_lifecycle]`), off by default.","$ref":"#/$defs/SkillsLifecycleConfig","default":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]}},"smart_group":{"description":"Smart group-reply pre-gate configuration (`[smart_group]`).","$ref":"#/$defs/SmartGroupConfig","default":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5}},"storage":{"description":"Persistent storage provider configuration (`[storage]`).","$ref":"#/$defs/StorageConfig","default":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"task_routing":{"description":"Task routing configuration — classifies work by intent before the main agent loop.","$ref":"#/$defs/TaskRoutingConfig","default":{"default_intent":"simple","rules":[]}},"tool_tiering":{"description":"Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).","$ref":"#/$defs/ToolTieringConfig","default":{"always_exclude":[],"always_include":[],"channel_exclude":[]}},"tunnel":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]`).","$ref":"#/$defs/TunnelConfig","default":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null}},"user_policies":{"description":"Static user policy records loaded at startup (`[[user_policies]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/UserPolicyConfig"}},"web_search":{"description":"Web search tool configuration (`[web_search]`).","$ref":"#/$defs/WebSearchConfig","default":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15}},"webhook":{"description":"Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).","$ref":"#/$defs/MemoryWebhookConfig","default":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null}},"xin":{"description":"Xin autonomous task engine configuration (`[xin]`).","$ref":"#/$defs/XinConfig","default":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}}},"$defs":{"A2aConfig":{"type":"object","properties":{"agent_id":{"description":"Stable PRX agent identifier advertised to peers.","type":"string","default":"prx-default"},"allowed_peer_issuers":{"description":"Accepted external peer issuers.","type":"array","default":[],"items":{"type":"string"}},"bind":{"description":"Advertised bind address.","type":"string","default":"127.0.0.1:16832"},"card_jwks_uri":{"description":"Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.","type":["string","null"],"default":null},"card_signing_key_path":{"description":"On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).","type":["string","null"],"default":null},"card_ttl_seconds":{"description":"Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.","type":"integer","format":"uint64","default":3600,"minimum":0},"discovery_advertised":{"description":"Whether to advertise into an external A2A registry.","type":"boolean","default":false},"handoff_nonce_ttl_seconds":{"description":"Replay window for future handoff delegation tokens.","type":"integer","format":"uint64","default":3600,"minimum":0},"messaging_enabled":{"description":"Enable the dedicated pinned mTLS messaging listener.","type":"boolean","default":false},"peers":{"type":"object","additionalProperties":{"$ref":"#/$defs/A2aPeer"},"default":{}},"spiffe_id":{"description":"Local SPIFFE-style identifier placeholder.","type":"string","default":"spiffe://prx-local/agent/prx-default"},"spiffe_strict_validation":{"description":"When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.","type":"boolean","default":false},"spiffe_trust_bundle_pem":{"description":"Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).","type":["string","null"],"default":null},"trusted_trust_domains":{"description":"Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).","type":"array","default":[],"items":{"type":"string"}},"trust_domain":{"description":"SPIFFE trust domain for new instance identities.","type":"string","default":"prx.local"}}},"A2aPeer":{"description":"Explicit pinned identity and local recipient grant.","type":"object","properties":{"spiffe_id":{"type":"string"},"fingerprints":{"type":"array","items":{"type":"string"}},"address":{"type":"string"},"owner":{"type":"string"},"sessions":{"type":"array","default":["*"],"items":{"type":"string"}},"agents":{"type":"array","default":["*"],"items":{"type":"string"}}},"required":["spiffe_id","fingerprints","address","owner"],"additionalProperties":false},"AgentCompactionConfig":{"description":"Agent context compaction configuration (`[agent.compaction]`).","type":"object","properties":{"keep_recent_messages":{"description":"Number of recent non-system messages to keep after compaction.","type":"integer","format":"uint","default":12,"minimum":0},"max_context_tokens":{"description":"Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.","type":"integer","format":"uint","default":128000,"minimum":0},"memory_flush":{"description":"Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.","type":"boolean","default":true},"mode":{"description":"Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).","$ref":"#/$defs/AgentCompactionMode","default":"switch"},"os_paging":{"description":"Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.","$ref":"#/$defs/OsPagingConfig","default":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"}},"reserve_tokens":{"description":"Tokens reserved for the next model response.","type":"integer","format":"uint","default":4096,"minimum":0}}},"AgentCompactionMode":{"description":"Compaction mode for long conversation contexts.","oneOf":[{"description":"Disable proactive compaction.","type":"string","const":"off"},{"description":"Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.","type":"string","const":"switch"},{"description":"Conservative compaction that prefers summary replacement.","type":"string","const":"safeguard"},{"description":"Aggressive truncation mode for tighter contexts.","type":"string","const":"aggressive"}]},"AgentConfig":{"description":"Agent orchestration configuration (`[agent]` section).","type":"object","properties":{"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"compact_context":{"description":"When true: bootstrap_max_chars=6000. Use for 13B or smaller models.","type":"boolean","default":false},"compaction":{"description":"Context compaction controls (`[agent.compaction]`).","$ref":"#/$defs/AgentCompactionConfig","default":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096}},"low_priority_tools":{"description":"Tool names treated as low-priority when `priority_scheduling_enabled = true`.","type":"array","default":["sessions_spawn","delegate"],"items":{"type":"string"}},"priority_scheduling_enabled":{"description":"Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.","type":"boolean","default":false},"read_only_tool_concurrency_window":{"description":"Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.","type":"integer","format":"uint","default":2,"minimum":0},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}}},"AgentLimits":{"description":"Optional admission limits for rf-started turns of a named agent.","type":"object","properties":{"max_concurrent_turns":{"type":["integer","null"],"format":"uint32","minimum":0},"max_cost_per_day_cents":{"type":["integer","null"],"format":"uint64","minimum":0}},"additionalProperties":false},"AuditConfig":{"description":"Audit logging configuration","type":"object","properties":{"log_path":{"description":"Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).","type":"string","default":"audit.log"},"max_size_mb":{"description":"Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).","type":"integer","format":"uint32","default":100,"minimum":0}}},"AuthConfig":{"description":"Authentication and external credential import configuration (`[auth]` section).","type":"object","properties":{"codex_auth_json_auto_import":{"description":"Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.","type":"boolean","default":false},"codex_auth_json_path":{"description":"Source path for Codex CLI auth.json import.","type":"string","default":"~/.codex/auth.json"}}},"AutonomyConfig":{"type":"object","properties":{"acknowledge_unrestricted_profile":{"description":"Operator acknowledgement for an intentionally unrestricted profile.\nRetained for existing configs; it no longer changes any output or policy behavior.","type":"boolean","default":false},"forbidden_paths":{"description":"Explicit path denylist. Default: empty.\n\nApplies below level `full` only; list paths when running `supervised` or `readonly`.","type":"array","default":[],"items":{"type":"string"}},"level":{"description":"Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).","$ref":"#/$defs/AutonomyLevel","default":"full"},"max_cost_per_day_cents":{"description":"Maximum cost per day in cents per policy. Default: unset (no ceiling).","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"scopes":{"description":"Scope-based tool access control: per-user/channel/chat-type allow/deny rules.","$ref":"#/$defs/ScopeConfig","default":{"assign_owners":[],"default":"allow","rules":[]}},"workspace_only":{"description":"Restrict file writes and command paths to the workspace directory. Default: `false`.\n\nApplies below level `full` only; set it when running `supervised` or `readonly`.","type":"boolean","default":false}}},"AutonomyLevel":{"description":"How much autonomy the agent has","oneOf":[{"description":"Read-only: can observe but not act","type":"string","const":"readonly"},{"description":"Supervised: acts but requires approval for risky operations","type":"string","const":"supervised"},{"description":"Full: autonomous execution within policy bounds","type":"string","const":"full"}]},"BackendSelection":{"description":"Which decision backend runs: `auto` (the factory's order) or one kind.","type":"string"},"BrowserComputerUseConfig":{"description":"Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.","type":"object","properties":{"api_key":{"description":"Optional bearer token (retained only for config secret handling).","type":["string","null"],"default":null}}},"BrowserConfig":{"description":"Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.","type":"object","properties":{"allowed_domains":{"description":"Allowed domains for `web_fetch` (exact or subdomain match).","type":"array","default":[],"items":{"type":"string"}},"computer_use":{"description":"Computer-use sidecar config (retained only for `api_key` secret handling).","$ref":"#/$defs/BrowserComputerUseConfig","default":{"api_key":null}}}},"ChannelsConfig":{"description":"Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.","type":"object","properties":{"cli":{"description":"Enable the CLI interactive channel. Default: `true`.","type":"boolean","default":true},"dingtalk":{"description":"DingTalk channel configuration.","anyOf":[{"$ref":"#/$defs/DingTalkConfig"},{"type":"null"}]},"discord":{"description":"Discord bot channel configuration.","anyOf":[{"$ref":"#/$defs/DiscordConfig"},{"type":"null"}]},"email":{"description":"Email channel configuration.","anyOf":[{"$ref":"#/$defs/EmailConfig"},{"type":"null"}]},"imessage":{"description":"iMessage channel configuration (macOS only).","anyOf":[{"$ref":"#/$defs/IMessageConfig"},{"type":"null"}]},"irc":{"description":"IRC channel configuration.","anyOf":[{"$ref":"#/$defs/IrcConfig"},{"type":"null"}]},"lark":{"description":"Lark/Feishu channel configuration.","anyOf":[{"$ref":"#/$defs/LarkConfig"},{"type":"null"}]},"linq":{"description":"Linq Partner API channel configuration.","anyOf":[{"$ref":"#/$defs/LinqConfig"},{"type":"null"}]},"mattermost":{"description":"Mattermost bot channel configuration.","anyOf":[{"$ref":"#/$defs/MattermostConfig"},{"type":"null"}]},"nextcloud_talk":{"description":"Nextcloud Talk bot channel configuration.","anyOf":[{"$ref":"#/$defs/NextcloudTalkConfig"},{"type":"null"}]},"qq":{"description":"QQ Official Bot channel configuration.","anyOf":[{"$ref":"#/$defs/QQConfig"},{"type":"null"}]},"ramflux":{"description":"Local ramflux agent-host bridge.","anyOf":[{"$ref":"#/$defs/RamfluxConfig"},{"type":"null"}],"default":null},"signal":{"description":"Signal channel configuration.","anyOf":[{"$ref":"#/$defs/SignalConfig"},{"type":"null"}]},"slack":{"description":"Slack bot channel configuration.","anyOf":[{"$ref":"#/$defs/SlackConfig"},{"type":"null"}]},"telegram":{"description":"Telegram bot channel configuration.","anyOf":[{"$ref":"#/$defs/TelegramConfig"},{"type":"null"}]},"wacli":{"description":"wacli JSON-RPC daemon channel configuration.","anyOf":[{"$ref":"#/$defs/WacliConfig"},{"type":"null"}],"default":null},"webhook":{"description":"Webhook channel configuration.","anyOf":[{"$ref":"#/$defs/WebhookConfig"},{"type":"null"}]},"whatsapp":{"description":"WhatsApp channel configuration (Cloud API or Web mode).","anyOf":[{"$ref":"#/$defs/WhatsAppConfig"},{"type":"null"}]}}},"ChatConfig":{"description":"Interactive chat configuration (`[chat]`).","type":"object","properties":{"daemon":{"description":"How this chat process reaches the daemon it borrows channels from.","$ref":"#/$defs/ChatDaemonConfig","default":{"token":"","url":""}},"max_concurrent_visible_turns":{"description":"Maximum concurrent visible provider turns in the TUI Redux driver.","type":"integer","format":"uint","default":2,"minimum":0}}},"ChatDaemonConfig":{"description":"Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.","type":"object","properties":{"token":{"description":"Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.","type":"string","default":""},"url":{"description":"Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.","type":"string","default":""}}},"CircuitBreakerConfig":{"description":"The per-backend circuit breaker.","type":"object","properties":{"cooldown_secs":{"description":"Seconds the breaker stays open (1 to 3600).","type":"integer","format":"uint32","default":60,"minimum":0},"failure_threshold":{"description":"Consecutive failures before the breaker opens (1 to 100).","type":"integer","format":"uint32","default":5,"minimum":0}}},"ClassificationRule":{"description":"A single classification rule mapping message patterns to a model hint.","type":"object","properties":{"hint":{"description":"Must match a `[[model_routes]]` hint value.","type":"string"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"max_length":{"description":"Only match if message length <= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"min_length":{"description":"Only match if message length >= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"patterns":{"description":"Case-sensitive literal matches (for \"```\", \"fn \", etc.).","type":"array","default":[],"items":{"type":"string"}},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0}},"required":["hint"]},"CloudflareTunnelConfig":{"type":"object","properties":{"token":{"description":"Cloudflare Tunnel token (from Zero Trust dashboard)","type":"string"}},"required":["token"]},"ComplianceConfig":{"type":"object","properties":{"eu_ai_act":{"$ref":"#/$defs/EuAiActComplianceConfig","default":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null}},"interaction_notice":{"$ref":"#/$defs/InteractionNoticeConfig","default":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}}},"ComposioConfig":{"description":"Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.","type":"object","properties":{"api_key":{"description":"Composio API key (stored encrypted when secrets.encrypt = true)","type":["string","null"],"default":null},"entity_id":{"description":"Default entity ID for multi-user setups","type":"string","default":"default"}}},"CostConfig":{"description":"Cost tracking and budget enforcement configuration (`[cost]` section).","type":"object","properties":{"allow_override":{"description":"Allow requests to exceed budget with --override flag (default: false)","type":"boolean","default":false},"daily_limit_usd":{"description":"Daily spending limit in USD (default: unset, no limit; 0 refuses every priced turn)","type":["number","null"],"format":"double","default":null},"monthly_limit_usd":{"description":"Monthly spending limit in USD (default: unset, no limit)","type":["number","null"],"format":"double","default":null},"prices":{"description":"Per-model pricing (USD per 1M tokens)","type":"object","additionalProperties":{"$ref":"#/$defs/ModelPricing"},"default":{}},"warn_at_percent":{"description":"Warn when spending reaches this percentage of a configured limit (default: 80)","type":"integer","format":"uint8","default":80,"maximum":255,"minimum":0}}},"CredentialRefSetting":{"description":"Which credential a decision backend uses. A reference, never a secret.","type":"string"},"CronConfig":{"description":"Cron job configuration (`[cron]` section).","type":"object","properties":{"max_run_history":{"description":"Maximum number of historical cron run records to retain. Default: `50`.","type":"integer","format":"uint32","default":50,"minimum":0}}},"CustomTunnelConfig":{"type":"object","properties":{"health_url":{"description":"Optional URL to check tunnel health","type":["string","null"]},"start_command":{"description":"Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"","type":"string"},"url_pattern":{"description":"Optional regex to extract public URL from command stdout","type":["string","null"]}},"required":["start_command"]},"DecisionBackendConfig":{"description":"The decision backend (`[decision_engine.backend]`).","type":"object","properties":{"circuit_breaker":{"description":"The circuit breaker.","$ref":"#/$defs/CircuitBreakerConfig","default":{"cooldown_secs":60,"failure_threshold":5}},"credential_ref":{"description":"The credential reference: `\"\"`, `\"none\"` or `cred-`.","$ref":"#/$defs/CredentialRefSetting","default":""},"endpoint":{"description":"The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.","type":"string","default":""},"kind":{"description":"`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).","$ref":"#/$defs/BackendSelection","default":"auto"},"max_request_bytes":{"description":"Largest request body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":65536,"minimum":0},"max_response_bytes":{"description":"Largest response body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":262144,"minimum":0},"model":{"description":"The model the endpoint serves; one exact version for a hosted\nservice.","type":"string","default":""},"pinned_snapshot":{"description":"The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.","type":"string"},"remote_enabled":{"description":"Whether decision state may leave this machine. Default `false`.","type":"boolean","default":false},"timeout_ms":{"description":"Transport timeout (10 ms up to the extra latency budget).","type":"integer","format":"uint32","default":250,"minimum":0}}},"DecisionEngineConfig":{"type":"object","properties":{"backend":{"anyOf":[{"$ref":"#/$defs/DecisionBackendConfig"},{"type":"null"}]},"candidates":{"type":"integer","format":"uint32","default":5,"minimum":0},"enabled":{"type":"boolean","default":false},"mode":{"$ref":"#/$defs/DecisionMode","default":"pre"},"observe_queue":{"type":"integer","format":"uint32","default":64,"minimum":0},"prompt_budget_tokens":{"type":"integer","format":"uint32","default":300,"minimum":0},"telemetry_cap":{"type":"integer","format":"uint32","default":1000,"minimum":0},"timeout_ms":{"type":"integer","format":"uint32","default":1500,"minimum":0},"latency_budget_ms":{"description":"The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.","type":"integer","format":"uint64","default":500,"minimum":0},"token_ratio_limit":{"description":"Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).","type":"number","format":"float","default":0.3499999940395355},"max_candidates":{"description":"The most candidates a turn considers (1 to 32).","type":"integer","format":"uint8","default":12,"maximum":255,"minimum":0}}},"DecisionMode":{"type":"string","enum":["pre","post","both"]},"DeclarationOfConformityConfig":{"type":"object","properties":{"applicable_union_law":{"type":"array","default":[],"items":{"type":"string"}},"artifact_path":{"type":["string","null"],"default":null},"artifact_version":{"type":["string","null"],"default":null},"conformity_assessment_procedure":{"type":["string","null"],"default":null},"conformity_statement":{"type":["string","null"],"default":null},"harmonised_standards":{"type":"array","default":[],"items":{"type":"string"}},"issue_date":{"type":["string","null"],"default":null},"issue_place":{"type":["string","null"],"default":null},"notified_body_certificate":{"type":["string","null"],"default":null},"notified_body_identification_number":{"type":["string","null"],"default":null},"notified_body_name":{"type":["string","null"],"default":null},"personal_data_compliance_statement":{"type":["string","null"],"default":null},"processes_personal_data":{"type":"boolean","default":false},"provider_address":{"type":["string","null"],"default":null},"provider_name":{"type":["string","null"],"default":null},"signer_function":{"type":["string","null"],"default":null},"signer_name":{"type":["string","null"],"default":null},"signer_on_behalf_of":{"type":["string","null"],"default":null},"sole_responsibility_statement":{"type":["string","null"],"default":null},"standards_not_applicable_reason":{"type":["string","null"],"default":null},"system_name":{"type":["string","null"],"default":null},"system_reference":{"type":["string","null"],"default":null},"system_type":{"type":["string","null"],"default":null}}},"DelegateAgentConfig":{"description":"Configuration for a delegate sub-agent used by the `delegate` tool.","type":"object","properties":{"agentic":{"description":"Agentic sub-agent mode (multi-turn tool-call loop). Default true; an\nexplicit `false` makes the agent answer-only with no tools.","type":"boolean","default":true},"allowed_tools":{"description":"Allowlist of tool names available to the sub-agent in agentic mode.\nEmpty or omitted means all tools, the same as `[\"*\"]`.","type":"array","default":[],"items":{"type":"string"}},"api_key":{"description":"Optional API key override","type":["string","null"],"default":null},"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"autonomy":{"description":"The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.","anyOf":[{"$ref":"#/$defs/AutonomyLevel"},{"type":"null"}]},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"enabled":{"description":"Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.","type":"boolean","default":true},"identity_dir":{"description":"Optional identity files directory relative to workspace root.","type":["string","null"],"default":null},"limits":{"$ref":"#/$defs/AgentLimits","default":{"max_concurrent_turns":null,"max_cost_per_day_cents":null}},"max_depth":{"description":"Max recursion depth for nested delegation","type":"integer","format":"uint32","default":8,"minimum":0},"memory_scope":{"description":"Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".","type":["string","null"],"default":null},"model":{"description":"Model name","type":"string"},"provider":{"description":"Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")","type":"string"},"spawn_enabled":{"description":"Whether this agent is allowed to be targeted by sessions_spawn (default: true).","type":["boolean","null"],"default":null},"system_prompt":{"description":"Optional system prompt for the sub-agent","type":["string","null"],"default":null},"temperature":{"description":"Temperature override","type":["number","null"],"format":"double","default":null},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}},"required":["provider","model"]},"DingTalkConfig":{"description":"DingTalk configuration for Stream Mode messaging","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"client_id":{"description":"Client ID (AppKey) from DingTalk developer console","type":"string"},"client_secret":{"description":"Client Secret (AppSecret) from DingTalk developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["client_id","client_secret"]},"DiscordConfig":{"description":"Discord bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Discord user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Discord bot token (from Discord Developer Portal).","type":"string"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"guild_id":{"description":"Optional guild (server) ID to restrict the bot to a single guild.","type":["string","null"]},"listen_to_bots":{"description":"When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.","type":"boolean","default":false}},"required":["bot_token"]},"DmPolicy":{"description":"Policy for direct-message handling.","oneOf":[{"description":"Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).","type":"string","const":"pairing"},{"description":"Accept only senders listed in `allowed_from`.","type":"string","const":"allowlist"},{"description":"Accept any direct sender.","type":"string","const":"open"},{"description":"Ignore direct messages.","type":"string","const":"disabled"}]},"DockerRuntimeConfig":{"description":"Docker runtime configuration (`[runtime.docker]` section).","type":"object","properties":{"allowed_workspace_roots":{"description":"Optional workspace root allowlist for Docker mount validation.","type":"array","default":[],"items":{"type":"string"}},"cpu_limit":{"description":"Optional CPU limit (`None` = no explicit limit).","type":["number","null"],"format":"double","default":1.0},"image":{"description":"Runtime image used to execute shell commands.","type":"string","default":"alpine:3.20"},"memory_limit_mb":{"description":"Optional memory limit in MB (`None` = no explicit limit).","type":["integer","null"],"format":"uint64","default":512,"minimum":0},"mount_workspace":{"description":"Mount configured workspace into `/workspace`.","type":"boolean","default":true},"network":{"description":"Docker network mode (`none`, `bridge`, etc.).","type":"string","default":"none"},"read_only_rootfs":{"description":"Mount root filesystem as read-only.","type":"boolean","default":true}}},"EmailConfig":{"description":"Email channel configuration","type":"object","properties":{"allowed_senders":{"description":"Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)","type":"array","default":[],"items":{"type":"string"}},"from_address":{"description":"From address for outgoing emails","type":"string"},"idle_timeout_secs":{"description":"IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes","type":"integer","format":"uint64","default":1740,"minimum":0},"imap_folder":{"description":"IMAP folder to poll (default: INBOX)","type":"string","default":"INBOX"},"imap_host":{"description":"IMAP server hostname","type":"string"},"imap_port":{"description":"IMAP server port (default: 993 for TLS)","type":"integer","format":"uint16","default":993,"maximum":65535,"minimum":0},"password":{"description":"Email password for authentication","type":"string"},"smtp_host":{"description":"SMTP server hostname","type":"string"},"smtp_port":{"description":"SMTP server port (default: 465 for TLS)","type":"integer","format":"uint16","default":465,"maximum":65535,"minimum":0},"smtp_tls":{"description":"Use TLS for SMTP (default: true)","type":"boolean","default":true},"username":{"description":"Email username for authentication","type":"string"}},"required":["imap_host","smtp_host","username","password","from_address"]},"EmbeddingRouteConfig":{"description":"Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"dimensions":{"description":"Optional embedding dimension override for this route","type":["integer","null"],"format":"uint","default":null,"minimum":0},"hint":{"description":"Route hint name (e.g. \"semantic\", \"archive\", \"faq\")","type":"string"},"model":{"description":"Embedding model to use with that provider","type":"string"},"provider":{"description":"Embedding provider (`none`, `openai`, or `custom:`)","type":"string"}},"required":["hint","provider","model"]},"EuAiActClassificationConfig":{"type":"object","properties":{"assessed_at":{"type":["string","null"],"default":null},"owner":{"type":["string","null"],"default":null},"status":{"$ref":"#/$defs/EuAiActRiskClassification","default":"unclassified"}}},"EuAiActComplianceConfig":{"type":"object","properties":{"classification":{"$ref":"#/$defs/EuAiActClassificationConfig","default":{"assessed_at":null,"owner":null,"status":"unclassified"}},"declaration":{"$ref":"#/$defs/DeclarationOfConformityConfig","default":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null}},"incident_store_path":{"type":["string","null"],"default":null}}},"EuAiActRiskClassification":{"type":"string","enum":["unclassified","high_risk","not_high_risk"]},"FitnessConfig":{"description":"Calendar schedule, evidence thresholds, and retention for fitness v2.","type":"object","properties":{"auto_run":{"description":"Run the daily fitness worker in daemon mode.","type":"boolean","default":true},"max_backfill_days":{"description":"Maximum number of closed days recovered after downtime.","type":"integer","format":"uint32","default":7,"minimum":0},"min_coverage":{"description":"Minimum available metric weight required to publish a final score.","type":"number","format":"double","default":0.6},"min_samples":{"description":"Minimum samples required before an evidence-derived subscore is usable.","type":"integer","format":"uint","default":5,"minimum":0},"retention_days":{"description":"Number of daily JSON reports retained on disk.","type":"integer","format":"uint32","default":180,"minimum":0},"run_at":{"description":"Local wall-clock time (`HH:MM`) at which the previous day is scored.","type":"string","default":"00:10"},"timezone":{"description":"IANA timezone used to define closed calendar days.","type":"string","default":"UTC"}}},"GatewayConfig":{"description":"Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.","type":"object","properties":{"allow_public_bind":{"description":"Allow binding to non-localhost without a tunnel (default: false)","type":"boolean","default":false},"api_rate_limit_per_minute":{"description":"Max `/api/*` requests per minute per authenticated token.","type":"integer","format":"uint32","default":60,"minimum":0},"channel_webhook_dedup_ttl_secs":{"description":"How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.","type":"integer","format":"uint64","default":86400,"minimum":0},"host":{"description":"Gateway host (default: 127.0.0.1)","type":"string","default":"127.0.0.1"},"idempotency_max_keys":{"description":"Maximum distinct idempotency keys retained in memory.","type":"integer","format":"uint","default":10000,"minimum":0},"idempotency_ttl_secs":{"description":"TTL for webhook idempotency keys.","type":"integer","format":"uint64","default":300,"minimum":0},"pair_rate_limit_per_minute":{"description":"Max `/pair` requests per minute per client key.","type":"integer","format":"uint32","default":10,"minimum":0},"paired_tokens":{"description":"Paired bearer tokens (managed automatically, not user-edited)","type":"array","default":[],"items":{"type":"string"}},"port":{"description":"Gateway port (default: 16830)","type":"integer","format":"uint16","default":16830,"maximum":65535,"minimum":0},"rate_limit_max_keys":{"description":"Maximum distinct client keys tracked by gateway rate limiter maps.","type":"integer","format":"uint","default":10000,"minimum":0},"require_pairing":{"description":"Require pairing before accepting requests (default: true)","type":"boolean","default":true},"targeted_agents":{"description":"Switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). Default true. While false, any\notherwise-valid named target answers 409 `agent_disabled` and never\nruns as Main.","type":"boolean","default":true},"trust_forwarded_headers":{"description":"Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.","type":"boolean","default":false},"webhook_rate_limit_per_minute":{"description":"Max `/webhook` requests per minute per client key.","type":"integer","format":"uint32","default":60,"minimum":0}}},"GroupPolicy":{"description":"Policy for group-message handling.","oneOf":[{"description":"Accept only groups listed in `group_allow_from`.","type":"string","const":"allowlist"},{"description":"Accept any group.","type":"string","const":"open"},{"description":"Ignore group messages.","type":"string","const":"disabled"}]},"GroupReplyMode":{"description":"How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.","oneOf":[{"description":"Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).","type":"string","const":"off"},{"description":"Reply only when the bot is @-mentioned (legacy `mention_only = true`).","type":"string","const":"mention-only"},{"description":"Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).","type":"string","const":"smart"}]},"HeartbeatConfig":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]` section).","type":"object","properties":{"active_hours":{"description":"Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.","type":"array","default":[8,23],"items":{"type":"integer","format":"uint8","maximum":255,"minimum":0}},"interval_minutes":{"description":"Interval in minutes between heartbeat pings. Default: `30`.","type":"integer","format":"uint32","default":30,"minimum":0},"prompt":{"description":"Prompt used by heartbeat worker when dispatching tasks.","type":"string","default":"Check HEARTBEAT.md and follow instructions."}}},"HttpRequestConfig":{"description":"HTTP request tool configuration (`[http_request]` section).","type":"object","properties":{"max_response_size":{"description":"Maximum response size in bytes (default: 1MB)","type":"integer","format":"uint","default":1000000,"minimum":0},"timeout_secs":{"description":"Request timeout in seconds (default: 30)","type":"integer","format":"uint64","default":30,"minimum":0}}},"IMessageConfig":{"description":"iMessage channel configuration (macOS only).","type":"object","properties":{"allowed_contacts":{"description":"Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.","type":"array","items":{"type":"string"}},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["allowed_contacts"]},"IdentityBindingConfig":{"description":"Startup identity binding entry (`[[identity_bindings]]`).","type":"object","properties":{"channel":{"type":"string"},"channel_account":{"type":"string"},"display_name":{"type":["string","null"],"default":null},"user_id":{"type":"string"}},"required":["user_id","channel","channel_account"]},"IdentityConfig":{"description":"Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.","type":"object","properties":{"aieos_inline":{"description":"Inline AIEOS JSON (alternative to file path)","type":["string","null"],"default":null},"aieos_path":{"description":"Path to AIEOS JSON file (relative to workspace)","type":["string","null"],"default":null},"format":{"description":"Identity format: \"openclaw\" (default) or \"aieos\"","type":"string","default":"openclaw"}}},"InteractionNoticeApplicability":{"type":"string","enum":["required","not_applicable"]},"InteractionNoticeConfig":{"type":"object","properties":{"applicability":{"$ref":"#/$defs/InteractionNoticeApplicability","default":"required"},"exception_owner":{"type":["string","null"],"default":null},"exception_reviewed_at":{"type":["string","null"],"default":null},"text":{"type":"string","default":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers."},"version":{"type":"string","default":"1"}}},"IrcConfig":{"description":"IRC channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed nicknames (case-insensitive) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"channels":{"description":"Channels to join on connect","type":"array","default":[],"items":{"type":"string"}},"mention_only":{"description":"When true, only process channel/group messages that mention the bot.","type":"boolean","default":false},"nickname":{"description":"Bot nickname","type":"string"},"nickserv_password":{"description":"NickServ IDENTIFY password","type":["string","null"]},"port":{"description":"IRC server port (default: 6697 for TLS)","type":"integer","format":"uint16","default":6697,"maximum":65535,"minimum":0},"sasl_password":{"description":"SASL PLAIN password (IRCv3)","type":["string","null"]},"server":{"description":"IRC server hostname","type":"string"},"server_password":{"description":"Server password (for bouncers like ZNC)","type":["string","null"]},"username":{"description":"Username (defaults to nickname if not set)","type":["string","null"]},"verify_tls":{"description":"Verify TLS certificate (default: true)","type":["boolean","null"]}},"required":["server","nickname"]},"LarkConfig":{"description":"Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from Lark/Feishu developer console","type":"string"},"app_secret":{"description":"App Secret from Lark/Feishu developer console","type":"string"},"encrypt_key":{"description":"Encrypt key for webhook message decryption (optional)","type":["string","null"],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"port":{"description":"HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"receive_mode":{"description":"Event receive mode: \"websocket\" (default) or \"webhook\"","$ref":"#/$defs/LarkReceiveMode","default":"websocket"},"use_feishu":{"description":"Whether to use the Feishu (Chinese) endpoint instead of Lark (International)","type":"boolean","default":false},"verification_token":{"description":"Verification token for webhook validation (optional)","type":["string","null"],"default":null}},"required":["app_id","app_secret"]},"LarkReceiveMode":{"description":"How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.","type":"string","enum":["websocket","webhook"]},"LinqConfig":{"type":"object","properties":{"allowed_senders":{"description":"Allowed sender handles (phone numbers) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"api_token":{"description":"Linq Partner API token (Bearer auth)","type":"string"},"from_phone":{"description":"Phone number to send from (E.164 format)","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"signing_secret":{"description":"Webhook signing secret for signature verification","type":["string","null"],"default":null}},"required":["api_token","from_phone"]},"MattermostConfig":{"description":"Mattermost bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Mattermost user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Mattermost bot access token.","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.","type":["boolean","null"],"default":null},"thread_replies":{"description":"When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.","type":["boolean","null"],"default":null},"url":{"description":"Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).","type":"string"}},"required":["url","bot_token"]},"McpConfig":{"type":"object","properties":{"servers":{"description":"Named MCP server definitions","type":"object","additionalProperties":{"$ref":"#/$defs/McpServerConfig"},"default":{}},"workspace_servers":{"description":"Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.","$ref":"#/$defs/WorkspaceMcpServers"}}},"McpServerConfig":{"type":"object","properties":{"allow_tools":{"description":"Optional allow-list of exposed tools (empty = all)","type":"array","default":[],"items":{"type":"string"}},"args":{"description":"Command args for stdio mode","type":"array","default":[],"items":{"type":"string"}},"command":{"description":"Command for stdio mode","type":["string","null"],"default":null},"deny_tools":{"description":"Optional deny-list of exposed tools","type":"array","default":[],"items":{"type":"string"}},"env":{"description":"Environment variables for stdio mode","type":"object","additionalProperties":{"type":"string"},"default":{}},"request_timeout_ms":{"description":"Request timeout in milliseconds","type":"integer","format":"uint64","default":30000,"minimum":0},"startup_timeout_ms":{"description":"Startup timeout in milliseconds","type":"integer","format":"uint64","default":10000,"minimum":0},"tool_name_prefix":{"description":"Prefix used in tool naming and routing","type":"string","default":"mcp"},"transport":{"description":"Transport type: stdio or http","$ref":"#/$defs/McpTransport","default":"stdio"},"url":{"description":"URL for HTTP mode (streamable HTTP endpoint)","type":["string","null"],"default":null},"working_dir":{"description":"Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).","type":["string","null"]}}},"McpServerRuntimeConfig":{"type":"object","properties":{"allowed_origins":{"description":"Allowed browser origins for future streamable HTTP clients.","type":"array","default":["claude.ai","openai.com","localhost"],"items":{"type":"string"}},"bind":{"description":"Advertised bind address. The gateway may still be started with a CLI port override.","type":"string","default":"127.0.0.1:16831"},"exposed_tools":{"description":"Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.","type":"array","default":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"items":{"type":"string"}},"jwt_algorithms":{"description":"Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.","type":"array","default":["RS256"],"items":{"type":"string"}},"jwt_audience":{"description":"Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.","type":["string","null"],"default":null},"jwt_issuer":{"description":"Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.","type":["string","null"],"default":null},"jwt_jwks":{"description":"Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.","type":["string","null"],"default":null},"jwt_jwks_cache_ttl_secs":{"description":"Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.","type":"integer","format":"uint64","default":300,"minimum":0},"jwt_jwks_uri":{"description":"Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.","type":["string","null"],"default":null},"jwt_public_key_pem":{"description":"PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.","type":["string","null"],"default":null},"rate_limit_rps":{"description":"Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.","type":"integer","format":"uint32","default":10,"minimum":0},"require_auth":{"description":"Require an authenticated external identity for mutating calls.","type":"boolean","default":true}}},"McpTransport":{"type":"string","enum":["stdio","http"]},"MediaConfig":{"description":"Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.","type":"object","properties":{"audio_model":{"description":"Audio model name (Ollama model or OpenAI model). Default: \"whisper\".","type":"string","default":"whisper"},"audio_ollama_url":{"description":"Ollama base URL for audio transcription. Default: \"http://localhost:11434\".","type":"string","default":"http://localhost:11434"},"audio_provider":{"description":"Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".","type":"string","default":"none"},"max_audio_size_mb":{"description":"Maximum audio attachment size in MiB. Default: 20.","type":"integer","format":"uint","default":20,"minimum":0},"max_video_size_mb":{"description":"Maximum video attachment size in MiB. Default: 50.","type":"integer","format":"uint","default":50,"minimum":0},"video_max_frames":{"description":"Maximum video frames to extract per video. Default: 4.","type":"integer","format":"uint","default":4,"minimum":0},"video_provider":{"description":"Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".","type":"string","default":"none"}}},"MemoryConfig":{"description":"Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.","type":"object","properties":{"acl_enabled":{"description":"Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.","type":"boolean","default":false},"archive_after_days":{"description":"Archive daily/session files older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"auto_hydrate":{"description":"Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing","type":"boolean","default":true},"auto_save":{"description":"Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.","type":"boolean","default":true},"backend":{"description":"\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).","type":"string","default":"sqlite"},"conversation_retention_days":{"description":"For sqlite backend: prune conversation rows older than this many days","type":"integer","format":"uint32","default":3,"minimum":0},"daily_retention_days":{"description":"For sqlite backend: prune daily rows older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"embedding_cache_size":{"description":"Max embedding cache entries before LRU eviction","type":"integer","format":"uint","default":10000,"minimum":0},"embedding_dimensions":{"description":"Embedding vector dimensions","type":"integer","format":"uint","default":384,"minimum":0},"embedding_model":{"description":"Embedding model name (e.g. \"text-embedding-3-small\")","type":"string","default":"prx-local-hash-v1"},"embedding_provider":{"description":"Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"","type":"string","default":"local"},"events":{"description":"Raw/quasi-raw message event recording controls (`[memory.events]`).","$ref":"#/$defs/MemoryEventsConfig","default":{"record_assistant_messages":true,"record_tool_events":true,"record_user_messages":true}},"keyword_weight":{"description":"Weight for keyword BM25 in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.3},"legacy_conversation_turns_visible":{"description":"Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.","type":"boolean","default":true},"lucid_budget":{"description":"Token budget for lucid (replaces OPENPRX_LUCID_BUDGET)","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"lucid_cmd":{"description":"Path to lucid binary (replaces OPENPRX_LUCID_CMD)","type":["string","null"],"default":null},"lucid_failure_cooldown_ms":{"description":"Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)","type":"integer","format":"uint64","default":60000,"minimum":0},"lucid_local_hit_threshold":{"description":"Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)","type":"integer","format":"uint","default":3,"minimum":0},"lucid_recall_timeout_ms":{"description":"Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)","type":"integer","format":"uint64","default":5000,"minimum":0},"lucid_store_timeout_ms":{"description":"Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)","type":"integer","format":"uint64","default":3000,"minimum":0},"min_relevance_score":{"description":"Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4","type":"number","format":"double","default":0.4},"purge_after_days":{"description":"Purge archived files older than this many days","type":"integer","format":"uint32","default":30,"minimum":0},"semantic":{"description":"Semantic memory promotion controls (`[memory.semantic]`).","$ref":"#/$defs/MemorySemanticConfig","default":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30}},"sqlite_open_timeout_secs":{"description":"For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"sqlite_read_pool_size":{"description":"For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"vector_candidate_cap":{"description":"How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.","type":"integer","format":"uint","default":2000,"minimum":0},"vector_weight":{"description":"Weight for vector similarity in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.7}}},"MemoryEventsConfig":{"description":"Raw message event recording configuration (`[memory.events]`).","type":"object","properties":{"record_assistant_messages":{"description":"Record assistant replies.","type":"boolean","default":true},"record_tool_events":{"description":"Record tool calls and tool results in the durable message log.","type":"boolean","default":true},"record_user_messages":{"description":"Record inbound/user messages.","type":"boolean","default":true}}},"MemorySemanticConfig":{"description":"Semantic memory promotion configuration (`[memory.semantic]`).","type":"object","properties":{"auto_promote_assistant_messages":{"description":"Auto-promote eligible assistant messages. Disabled by default to reduce noise.","type":"boolean","default":false},"auto_promote_user_messages":{"description":"Auto-promote eligible user messages into long-term semantic memories.","type":"boolean","default":true},"min_chars":{"description":"Minimum content length for semantic auto-promotion.","type":"integer","format":"uint","default":30,"minimum":0}}},"MemoryWebhookConfig":{"type":"object","properties":{"bind":{"description":"Socket address for the receiver (e.g. \"0.0.0.0:16899\").","type":"string","default":"0.0.0.0:16899"},"signing_secret":{"description":"Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.","type":["string","null"],"default":null},"token":{"description":"Required bearer token for incoming webhook events.","type":["string","null"],"default":null}}},"ModelOperationSetting":{"description":"The operations a `[[providers.models]]` entry may list.","type":"string","enum":["chat","embedding","decision_endpoint","rerank","image_generation","audio_generation","video_generation"]},"ModelPricing":{"description":"Per-model pricing entry (USD per 1M tokens).","type":"object","properties":{"cache_read":{"description":"Cache read input price per 1M tokens.","type":"number","format":"double","default":0.0},"cache_write":{"description":"Cache write/creation input price per 1M tokens.","type":"number","format":"double","default":0.0},"input":{"description":"Input price per 1M tokens","type":"number","format":"double","default":0.0},"output":{"description":"Output price per 1M tokens","type":"number","format":"double","default":0.0}}},"ModelRouteConfig":{"description":"Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"hint":{"description":"Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")","type":"string"},"level":{"type":["string","null"]},"model":{"description":"Model to use with that provider","type":"string"},"provider":{"description":"Provider to route to (must match a known provider name)","type":"string"},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true,"required":["hint","provider","model"]},"ModelSettings":{"description":"A model level plus explicit parameter overrides in `[model_settings.\"\"]`.","type":"object","properties":{"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"level":{"type":["string","null"]},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true},"MultimodalConfig":{"description":"Multimodal (image) handling configuration (`[multimodal]` section).","type":"object","properties":{"allow_remote_fetch":{"description":"Allow fetching remote image URLs (http/https). Enabled by default.","type":"boolean","default":true},"max_image_size_mb":{"description":"Maximum image payload size in MiB before base64 encoding.","type":"integer","format":"uint","default":5,"minimum":0},"max_images":{"description":"Maximum number of image attachments accepted per request.","type":"integer","format":"uint","default":4,"minimum":0}}},"NextcloudTalkConfig":{"description":"Nextcloud Talk bot configuration (webhook receive + OCS send API).","type":"object","properties":{"allowed_users":{"description":"Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Bot app token used for OCS API bearer auth.","type":"string"},"base_url":{"description":"Nextcloud base URL (e.g. \"https://cloud.example.com\").","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"webhook_secret":{"description":"Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).","type":["string","null"],"default":null}},"required":["base_url","app_token"]},"NgrokTunnelConfig":{"type":"object","properties":{"auth_token":{"description":"ngrok auth token","type":"string"},"domain":{"description":"Optional custom domain","type":["string","null"]}},"required":["auth_token"]},"NodeServerConfig":{"description":"Node daemon runtime config used by `prx-node`.","type":"object","properties":{"allowed_commands":{"description":"Command allowlist matched on first token. Default: empty, which allows any\ncommand from an authenticated caller; `[\"*\"]` means the same.","type":"array","default":[],"items":{"type":"string"}},"bearer_token":{"description":"Required bearer token for /rpc.","type":"string","default":""},"blocked_commands":{"description":"Command denylist matched on first token. Always enforced.","type":"array","default":[],"items":{"type":"string"}},"exec_timeout_ms":{"description":"Default command timeout in milliseconds.","type":"integer","format":"uint64","default":15000,"minimum":0},"hmac_secret":{"description":"Optional HMAC signing secret.","type":["string","null"],"default":null},"listen_addr":{"description":"Listen address for node daemon.","type":"string","default":"127.0.0.1:8787"},"max_concurrent_tasks":{"description":"Maximum number of concurrent async command tasks.","type":"integer","format":"uint","default":8,"minimum":0},"max_output_bytes":{"description":"Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.","type":"integer","format":"uint","default":1048576,"minimum":0},"sandbox_root":{"description":"Sandbox root directory for read/write/cwd constraints.","type":"string","default":"."},"task_result_ttl_ms":{"description":"TTL for completed task results in milliseconds.","type":"integer","format":"uint64","default":3600000,"minimum":0},"tls_cert":{"description":"TLS certificate path (PEM).","type":["string","null"],"default":null},"tls_key":{"description":"TLS private key path (PEM).","type":["string","null"],"default":null},"tls_required":{"description":"Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.","type":"boolean","default":true}}},"NodesConfig":{"description":"Remote node proxy configuration for core-side RPC calls and node daemon defaults.","type":"object","properties":{"nodes":{"description":"Configured remote nodes.","type":"array","default":[],"items":{"$ref":"#/$defs/RemoteNodeConfig"}},"request_timeout_ms":{"description":"Default request timeout for node RPC calls.","type":"integer","format":"uint64","default":15000,"minimum":0},"retry_max":{"description":"Default max retries for node RPC calls.","type":"integer","format":"uint8","default":2,"maximum":255,"minimum":0},"server":{"description":"Embedded node server defaults used by `prx-node`.","$ref":"#/$defs/NodeServerConfig","default":{"allowed_commands":[],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}}},"ObservabilityConfig":{"description":"Observability backend configuration (`[observability]` section).","type":"object","properties":{"backend":{"description":"\"none\" | \"log\" | \"prometheus\" | \"otel\"","type":"string","default":"none"},"otel_endpoint":{"description":"OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".","type":["string","null"],"default":null},"otel_service_name":{"description":"Service name reported to the OTel collector. Defaults to \"prx\".","type":["string","null"],"default":null}}},"OllamaProviderConfig":{"description":"Ollama-specific request options (`[providers.ollama]`).","type":"object","properties":{"num_ctx":{"description":"Explicit context window sent as Ollama `options.num_ctx`.","type":["integer","null"],"format":"uint","default":null,"minimum":0}}},"OsPagingConfig":{"description":"Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.","type":"object","properties":{"eviction_threshold":{"description":"Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.","type":"number","format":"double","default":0.7},"keep_recent_messages":{"description":"Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).","type":"integer","format":"uint","default":12,"minimum":0},"max_recalled_pages":{"description":"Maximum number of evicted pages (document chunks) recalled per turn.","type":"integer","format":"uint","default":10,"minimum":0},"proactive_retrieval":{"description":"Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.","type":"boolean","default":true},"retrieval_injection_role":{"description":"Role under which recalled pages are injected.","$ref":"#/$defs/RetrievalInjectionRole","default":"system"}}},"PluginsConfig":{"description":"WASM plugin runtime configuration.","type":"object","properties":{"enabled":{"description":"Load WASM plugins from `/plugins`. Default: `false`.","type":"boolean","default":false}},"additionalProperties":false},"ProviderModelConfig":{"description":"One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.","type":"object","properties":{"context_window":{"description":"The model's context window in tokens.","type":["integer","null"],"format":"uint32","minimum":0},"model":{"description":"The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.","type":["string","null"]},"native_tools":{"description":"Whether the model accepts native tool calls.","type":["boolean","null"]},"operations":{"description":"The complete list of operations the model executes; every operation not\nlisted is unsupported.","type":["array","null"],"items":{"$ref":"#/$defs/ModelOperationSetting"}},"provider":{"description":"The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.","type":"string"},"streaming":{"description":"Whether the model streams responses.","type":["boolean","null"]},"structured_output":{"description":"Whether the model honours a JSON-schema response format.","type":["boolean","null"]},"tool_call_dialect":{"description":"The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema_dialect":{"description":"The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]},"vision_input":{"description":"Whether the model accepts image input.","type":["boolean","null"]}},"required":["provider"]},"ProviderToolDialectConfig":{"description":"One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.","type":"object","properties":{"model":{"description":"The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.","type":["string","null"]},"provider":{"description":"The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.","type":"string"},"tool_call":{"description":"The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema":{"description":"The tool-schema dialect the endpoint accepts.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]}},"required":["provider"]},"ProvidersConfig":{"description":"Provider-specific runtime configuration (`[providers]`).","type":"object","properties":{"models":{"description":"Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.","type":"array","items":{"$ref":"#/$defs/ProviderModelConfig"}},"ollama":{"description":"Ollama-specific request options (`[providers.ollama]`).","$ref":"#/$defs/OllamaProviderConfig","default":{"num_ctx":null}},"tool_dialects":{"description":"Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).","type":"array","items":{"$ref":"#/$defs/ProviderToolDialectConfig"}}}},"ProxyConfig":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).","type":"object","properties":{"all_proxy":{"description":"Fallback proxy URL for all schemes.","type":["string","null"],"default":null},"http_proxy":{"description":"Proxy URL for HTTP requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"https_proxy":{"description":"Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"no_proxy":{"description":"No-proxy bypass list. Same format as NO_PROXY.","type":"array","default":[],"items":{"type":"string"}},"scope":{"description":"Proxy application scope.","$ref":"#/$defs/ProxyScope","default":"prx"},"services":{"description":"Service selectors used when scope = \"services\".","type":"array","default":[],"items":{"type":"string"}}}},"ProxyScope":{"description":"Proxy application scope — determines which outbound traffic uses the proxy.","oneOf":[{"description":"Use system environment proxy variables only.","type":"string","const":"environment"},{"description":"Apply proxy to all OpenPRX-managed HTTP traffic (default).","type":"string","const":"prx"},{"description":"Apply proxy only to explicitly listed service selectors.","type":"string","const":"services"}]},"QQConfig":{"description":"QQ Official Bot configuration (Tencent QQ Bot SDK)","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs. Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from QQ Bot developer console","type":"string"},"app_secret":{"description":"App Secret from QQ Bot developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["app_id","app_secret"]},"QueryClassificationConfig":{"description":"Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.","type":"object","properties":{"rules":{"description":"Classification rules evaluated in priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/ClassificationRule"}}}},"RamfluxAccountConfig":{"description":"Persona for one ramflux AI account. Missing fields fall back to the global agent.","type":"object","properties":{"cross_conversation_retrieval":{"description":"Cross-conversation memory retrieval. Off unless the owner sets it.","type":"boolean","default":false},"model":{"type":["string","null"],"default":null},"provider":{"type":["string","null"],"default":null},"scope_profile":{"type":["string","null"],"default":null},"system_prompt_file":{"description":"Path to a system-prompt file. Relative paths are resolved from the workspace.","type":["string","null"],"default":null}},"additionalProperties":false},"RamfluxAttachmentFetch":{"description":"Per-turn caps for `attachment.fetch`.","type":"object","properties":{"max_bytes":{"type":"integer","format":"uint64","default":5242880,"minimum":0},"max_per_turn":{"type":"integer","format":"uint8","default":4,"maximum":255,"minimum":0}},"additionalProperties":false},"RamfluxAuthorizationMode":{"description":"How prx combines its own setting with `bridge.hello.authorization`.","oneOf":[{"description":"Use the agent-host value. Until hello arrives, the effective mode is supervised.","type":"string","const":"follow_rf"},{"description":"Always supervised, even when the agent-host declares full.","type":"string","const":"supervised"},{"description":"Full only when the agent-host also declares full. Config alone never yields full.","type":"string","const":"full"}]},"RamfluxConfig":{"description":"Local ramflux agent-host bridge (`[channels_config.ramflux]`).","type":"object","properties":{"accounts":{"type":"object","additionalProperties":{"$ref":"#/$defs/RamfluxAccountConfig"},"default":{}},"allowed_block_types":{"type":"array","default":["Text","Markdown","Heading","KeyValue","Metric","List","TableFallback","Form","Input","Select","Progress","LogStream","Warning","Error","Success","Approval","ActionGroup","FilePreview","Fallback"],"items":{"type":"string"}},"attachment_fetch":{"$ref":"#/$defs/RamfluxAttachmentFetch","default":{"max_bytes":5242880,"max_per_turn":4}},"authorization_mode":{"$ref":"#/$defs/RamfluxAuthorizationMode","default":"follow_rf"},"encrypt_at_rest":{"type":"boolean","default":true},"max_in_flight_per_conversation":{"type":"integer","format":"uint8","default":1,"maximum":255,"minimum":0},"on_new_message":{"$ref":"#/$defs/RamfluxOnNewMessage","default":"queue"},"socket_path":{"description":"Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.","type":["string","null"],"default":null},"surface_limits":{"$ref":"#/$defs/RamfluxSurfaceLimits","default":{"max_actions":16,"max_blocks":32,"max_bytes":65536}},"turn_wall_clock_secs":{"description":"Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.","type":"integer","format":"uint64","default":120,"minimum":0}},"additionalProperties":false},"RamfluxOnNewMessage":{"description":"What to do with a new inbound message while a turn for that conversation is running.","type":"string","enum":["queue","interrupt"]},"RamfluxSurfaceLimits":{"description":"Limits for `reply.surface` blocks and actions.","type":"object","properties":{"max_actions":{"type":"integer","format":"uint32","default":16,"minimum":0},"max_blocks":{"type":"integer","format":"uint32","default":32,"minimum":0},"max_bytes":{"type":"integer","format":"uint32","default":65536,"minimum":0}},"additionalProperties":false},"ReliabilityCircuitBreakerConfig":{"description":"Process-local provider circuit policy (`[reliability.circuit_breaker]`).","type":"object","properties":{"enabled":{"description":"Enable protection for factory-built provider chains.","type":"boolean","default":true},"failure_threshold":{"description":"Consecutive transient failures that open a circuit (at least 1).","type":"integer","format":"uint32","default":5,"minimum":0},"max_open_secs":{"description":"Maximum doubled window, between open_secs and 3600 seconds.","type":"integer","format":"uint64","default":300,"minimum":0},"open_secs":{"description":"Initial open window in seconds (at least 1).","type":"integer","format":"uint64","default":30,"minimum":0}}},"ReliabilityConfig":{"description":"Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.","type":"object","properties":{"acknowledge_single_provider_risk":{"description":"Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.","type":"boolean","default":false},"api_keys":{"description":"Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.","type":"array","default":[],"items":{"type":"string"}},"channel_initial_backoff_secs":{"description":"Initial backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":2,"minimum":0},"channel_max_backoff_secs":{"description":"Max backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":60,"minimum":0},"circuit_breaker":{"description":"Per-provider consecutive failure protection.","$ref":"#/$defs/ReliabilityCircuitBreakerConfig","default":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30}},"fallback_providers":{"description":"Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).","type":"array","default":[],"items":{"type":"string"}},"model_fallbacks":{"description":"Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`","type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"default":{}},"provider_backoff_ms":{"description":"Base backoff (ms) for provider retry delay.","type":"integer","format":"uint64","default":500,"minimum":0},"provider_retries":{"description":"Retries per provider before failing over.","type":"integer","format":"uint32","default":2,"minimum":0},"scheduler_poll_secs":{"description":"Scheduler polling cadence in seconds.","type":"integer","format":"uint64","default":15,"minimum":0},"scheduler_retries":{"description":"Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.","type":"integer","format":"uint32","default":2,"minimum":0}}},"RemoteNodeConfig":{"description":"A remote node target for core-side node proxy calls.","type":"object","properties":{"bearer_token":{"description":"Bearer token for node RPC authentication.","type":"string"},"endpoint":{"description":"Base endpoint (e.g. \"http://127.0.0.1:8787\").","type":"string"},"hmac_secret":{"description":"Optional request signing key (HMAC-SHA256).","type":["string","null"],"default":null},"id":{"description":"Stable node ID used by the nodes tool.","type":"string"},"retry_max":{"description":"Optional per-node retry override.","type":["integer","null"],"format":"uint8","default":null,"maximum":255,"minimum":0},"timeout_ms":{"description":"Optional per-node timeout override.","type":["integer","null"],"format":"uint64","default":null,"minimum":0}},"required":["id","endpoint","bearer_token"]},"RetrievalInjectionRole":{"description":"Where recalled context pages are injected back into the request.","oneOf":[{"description":"Inject recalled pages as a leading `system` message (not user-visible).","type":"string","const":"system"},{"description":"Inject recalled pages as a leading `user` message.","type":"string","const":"user"}]},"RouterConfig":{"description":"Heuristic LLM router configuration (`[router]` section).","type":"object","properties":{"alpha":{"description":"Similarity score weight. Phase 1 keeps this at `0.0`.","type":"number","format":"float","default":0.0},"beta":{"description":"Capability score weight.","type":"number","format":"float","default":0.5},"delta":{"description":"Cost penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"epsilon":{"description":"Latency penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"gamma":{"description":"Elo score weight.","type":"number","format":"float","default":0.30000001192092896},"knn_k":{"description":"Number of nearest neighbors considered for voting. Default: `7`.","type":"integer","format":"uint","default":7,"minimum":0},"knn_min_records":{"description":"Minimum history records before KNN affects routing. Default: `10`.","type":"integer","format":"uint","default":10,"minimum":0},"models":{"description":"Candidate model registry.","type":"array","default":[],"items":{"$ref":"#/$defs/RouterModelConfig"}}}},"RouterModelConfig":{"description":"Static router metadata for one model candidate.","type":"object","properties":{"categories":{"description":"Capability categories such as `conversation`, `code`, or `analysis`.","type":"array","default":[],"items":{"type":"string"}},"cost_per_million_tokens":{"description":"USD cost per million tokens.","type":"number","format":"float","default":0.0},"elo_rating":{"description":"Initial Elo rating.","type":"number","format":"float","default":1000.0},"latency_ms":{"description":"Average latency in milliseconds.","type":"integer","format":"uint32","default":2000,"minimum":0},"max_context":{"description":"Maximum context window in tokens.","type":"integer","format":"uint","default":1000000,"minimum":0},"model_id":{"description":"Model identifier without provider prefix.","type":"string"},"provider":{"description":"Provider identifier.","type":"string"},"reserved_output_tokens":{"description":"Output tokens reserved for this model when planning input context.","type":["integer","null"],"format":"uint","minimum":0}},"required":["model_id","provider"]},"RuntimeConfig":{"description":"Runtime adapter configuration (`[runtime]` section).","type":"object","properties":{"codex_reasoning_effort":{"description":"Codex reasoning effort","type":["string","null"],"default":null},"codex_stream_idle_timeout_secs":{"description":"Codex stream idle timeout in seconds","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"docker":{"description":"Docker runtime settings (used when `kind = \"docker\"`).","$ref":"#/$defs/DockerRuntimeConfig","default":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true}},"idle_hang_secs":{"description":"Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"kind":{"description":"Runtime kind (`native` | `docker`).","type":"string","default":"native"},"long_task_warn_secs":{"description":"Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"managed_cgroup_root":{"description":"Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.","type":["string","null"],"default":null},"max_blocking_threads":{"description":"Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"reasoning_enabled":{"description":"Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported","type":["boolean","null"],"default":null},"shell_env_allowlist":{"description":"Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.","type":"array","default":[],"items":{"type":"string"}},"workdir":{"description":"Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.","type":["string","null"],"default":null}}},"SchedulerConfig":{"description":"Scheduler configuration for periodic task execution (`[scheduler]` section).","type":"object","properties":{"claim_lease_secs":{"description":"Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.","type":"integer","format":"uint64","default":90,"minimum":0},"max_tasks":{"description":"Maximum number of persisted scheduled tasks.","type":"integer","format":"uint","default":64,"minimum":0}}},"ScopeConfig":{"description":"Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```","type":"object","properties":{"assign_owners":{"description":"Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.","type":"array","default":[],"items":{"type":"string"}},"default":{"description":"Default action when no rule matches: \"allow\" (default) or \"deny\".","$ref":"#/$defs/ScopeDefault","default":"allow"},"rules":{"description":"Ordered list of scope rules evaluated top-to-bottom.","type":"array","default":[],"items":{"$ref":"#/$defs/ScopeRule"}}}},"ScopeDefault":{"description":"What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.","oneOf":[{"description":"Unmatched tool calls are allowed (the default).","type":"string","const":"allow"},{"description":"Unmatched tool calls are refused.","type":"string","const":"deny"}]},"ScopeRule":{"description":"A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.","type":"object","properties":{"assign_allow":{"description":"Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".","type":"array","default":[],"items":{"type":"string"}},"assign_deny":{"description":"Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.","type":"array","default":[],"items":{"type":"string"}},"channel":{"description":"Match by channel name: \"signal\", \"telegram\", \"discord\", etc.","type":["string","null"]},"chat_type":{"description":"Match by chat type: \"direct\", \"group\", or \"*\" for any type.","type":["string","null"]},"send_allow":{"description":"Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.","type":"array","default":[],"items":{"type":"string"}},"send_deny":{"description":"Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.","type":"array","default":[],"items":{"type":"string"}},"tools_allow":{"description":"Tool whitelist: only these tools are allowed (empty = all tools permitted).","type":"array","default":[],"items":{"type":"string"}},"tools_deny":{"description":"Tool blacklist: these tools are denied regardless of allow list.","type":"array","default":[],"items":{"type":"string"}},"user":{"description":"Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.","type":["string","null"]}}},"SecretsConfig":{"description":"Secrets encryption configuration (`[secrets]` section).","type":"object","properties":{"encrypt":{"description":"Enable encryption for API keys and tokens in config.toml","type":"boolean","default":true}}},"SecurityConfig":{"description":"Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.","type":"object","properties":{"audit":{"description":"Audit logging configuration","$ref":"#/$defs/AuditConfig","default":{"log_path":"audit.log","max_size_mb":100}},"workspace_hooks":{"description":"Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.","$ref":"#/$defs/WorkspaceHooks"}}},"SelfSystemConfig":{"description":"Self-system experimental automation config (`[self_system]`).","type":"object","properties":{"evolution_config_path":{"description":"Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG)","type":["string","null"],"default":null},"evolution_debug_raw":{"description":"Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW)","type":"boolean","default":false},"evolution_interval_hours":{"description":"Evolution scheduler interval in hours (daemon mode).","type":"integer","format":"uint32","default":24,"minimum":0},"evolution_judge_timeout_secs":{"description":"Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.","type":"integer","format":"uint64","default":180,"minimum":0},"evolution_model_max_micro_usd":{"description":"Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.","type":"integer","format":"uint64","default":0,"minimum":0},"evolution_model_max_tokens":{"description":"Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.","type":"integer","format":"uint64","default":16384,"minimum":0},"fitness":{"description":"Daily fitness snapshot policy.","$ref":"#/$defs/FitnessConfig","default":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"}},"fitness_interval_hours":{"description":"Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.","type":"integer","format":"uint64","default":24,"minimum":0}}},"SessionsSpawnConfig":{"description":"Sessions spawn configuration (`[sessions_spawn]` section).","type":"object","properties":{"cleanup_on_complete":{"description":"Remove worker workspace directory after process-mode completion.","type":"boolean","default":true},"default_mode":{"description":"Default execution mode for sessions_spawn (`task` or `process`).","type":"string","default":"task"},"process_memory_strategy":{"description":"Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.","type":"string","default":"shared_fabric"},"worker_workspace_root":{"description":"Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.","type":["string","null"],"default":null}}},"SignalConfig":{"type":"object","properties":{"account":{"description":"E.164 phone number of the signal-cli account (e.g. \"+1234567890\").","type":"string"},"allowed_from":{"description":"Allowed sender phone numbers (E.164) or \"*\" for all.","type":"array","default":[],"items":{"type":"string"}},"cli_path":{"description":"Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).","type":["string","null"],"default":null},"daemon_http_port":{"description":"Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"daemon_mode":{"description":"Deprecated: ignored. Accepted for backward compatibility with older config files.","type":["boolean","null"],"default":null},"data_dir":{"description":"signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_id":{"description":"Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group","type":["string","null"],"default":null},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"http_url":{"description":"Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.","type":"string","default":"http://localhost:8080"},"ignore_attachments":{"description":"Skip messages that are attachment-only (no text body).","type":"boolean","default":false},"ignore_stories":{"description":"Skip incoming story messages.","type":"boolean","default":false},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"mode":{"description":"Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.","type":["string","null"],"default":null},"startup_timeout_ms":{"description":"Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.","type":"integer","format":"uint64","default":30000,"minimum":0},"storm_protection":{"description":"Signal ingress storm protection controls.","$ref":"#/$defs/SignalStormProtectionConfig","default":{"abnormal_threshold":10,"abnormal_window_secs":60,"breaker_duration_secs":300,"dedupe_ttl_secs":60,"min_reply_interval_secs":2}}},"required":["account"]},"SignalStormProtectionConfig":{"type":"object","properties":{"abnormal_threshold":{"description":"Non-user event threshold within `abnormal_window_secs` before tripping the breaker.","type":"integer","format":"uint","default":10,"minimum":0},"abnormal_window_secs":{"description":"Sliding window in seconds for non-user event counting.","type":"integer","format":"uint64","default":60,"minimum":0},"breaker_duration_secs":{"description":"Circuit breaker duration in seconds after threshold is reached.","type":"integer","format":"uint64","default":300,"minimum":0},"dedupe_ttl_secs":{"description":"Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.","type":"integer","format":"uint64","default":60,"minimum":0},"min_reply_interval_secs":{"description":"Minimum interval in seconds between replies for the same `(channel + reply_target)`.","type":"integer","format":"uint64","default":2,"minimum":0}}},"SkillRagConfig":{"description":"Dynamic skill retrieval configuration (`[skill_rag]` section).","type":"object","properties":{"top_k":{"description":"How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).","type":"integer","format":"uint","default":32,"minimum":0}}},"SkillSuiteRegistration":{"description":"The frozen suite that governs one skill's proposals.","type":"object","properties":{"skill_id":{"description":"The skill the suite governs.","type":"string"},"suite_digest":{"description":"SHA-256 digest (64 lowercase hex digits) of the frozen suite.","type":"string"}},"additionalProperties":false,"required":["skill_id","suite_digest"]},"SkillsConfig":{"description":"Skills loading configuration (`[skills]` section).","type":"object","properties":{"open_skills_dir":{"description":"Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.","type":["string","null"],"default":null},"openclaw_skills_dir":{"description":"Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.","type":["string","null"],"default":null}}},"SkillsLifecycleConfig":{"description":"`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.","type":"object","properties":{"allow_executable_proposals":{"description":"Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.","type":"boolean","default":false},"enabled":{"description":"Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.","type":"boolean","default":false},"max_concurrent_evaluations":{"description":"Most evaluations running at once.","type":"integer","format":"uint32","default":1,"minimum":0},"max_edit_fraction":{"description":"Edit budget of a proposal as a fraction of the skill body, in (0, 1].","type":"number","format":"double","default":0.2},"max_edit_tokens":{"description":"Edit budget of a proposal, in tokens.","type":"integer","format":"uint64","default":300,"minimum":0},"max_proposals_per_cycle":{"description":"Most proposals one cycle may start.","type":"integer","format":"uint32","default":1,"minimum":0},"min_cases_floor":{"description":"Smallest `min_cases` a governing suite may declare. Below 3 is refused.","type":"integer","format":"uint32","default":3,"minimum":0},"mode":{"description":"`draft_only`, `shadow` or `auto`.","$ref":"#/$defs/SkillsLifecycleModeConfig","default":"draft_only"},"owner_scope":{"description":"The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.","type":["string","null"],"default":null},"require_holdout":{"description":"A governing suite must have a holdout split. `false` is refused.","type":"boolean","default":true},"storage_dir":{"description":"Store location under the workspace. Only the default is supported.","type":"string","default":"self/skill-lifecycle"},"suites":{"description":"The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.","type":"array","default":[],"items":{"$ref":"#/$defs/SkillSuiteRegistration"}}},"additionalProperties":false},"SkillsLifecycleModeConfig":{"description":"What the lifecycle may do. Mirrors `LifecycleMode`.","oneOf":[{"description":"Drafts and reviews only.","type":"string","const":"draft_only"},{"description":"Drafts plus evaluation and gating; never publishes.","type":"string","const":"shadow"},{"description":"Publishes an eligible proposal after every gate.","type":"string","const":"auto"}]},"SlackConfig":{"description":"Slack bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Slack user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Slack app-level token for Socket Mode (xapp-...).","type":["string","null"]},"bot_token":{"description":"Slack bot OAuth token (xoxb-...).","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["bot_token"]},"SmartGroupConfig":{"description":"Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).","type":"object","properties":{"classifier_max_context_messages":{"description":"How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.","type":"integer","format":"uint","default":3,"minimum":0},"classifier_model":{"description":"Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.","type":"string","default":""},"classifier_provider":{"description":"Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.","type":"string","default":""},"classifier_temperature":{"description":"Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).","type":"number","format":"double","default":0.0},"classifier_timeout_secs":{"description":"Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.","type":"integer","format":"uint64","default":5,"minimum":0}}},"StorageConfig":{"description":"Persistent storage configuration (`[storage]` section).","type":"object","properties":{"provider":{"description":"Storage provider settings (e.g. sqlite, postgres).","$ref":"#/$defs/StorageProviderSection","default":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}}},"StorageProviderConfig":{"description":"Storage provider backend configuration (e.g. postgres connection details).","type":"object","properties":{"connect_timeout_secs":{"description":"Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"db_url":{"description":"Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.","type":["string","null"],"default":null},"pool_max_size":{"description":"Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.","type":"integer","format":"uint","default":32,"minimum":0},"provider":{"description":"Storage engine key (e.g. \"postgres\", \"sqlite\").","type":"string","default":""},"schema":{"description":"Database schema for SQL backends.","type":"string","default":"public"},"table":{"description":"Table name for memory entries.","type":"string","default":"memories"}}},"StorageProviderSection":{"description":"Wrapper for the storage provider configuration section.","type":"object","properties":{"config":{"description":"Storage provider backend settings.","$ref":"#/$defs/StorageProviderConfig","default":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"StreamMode":{"description":"Streaming mode for channels that support progressive message updates.","oneOf":[{"description":"No streaming -- send the complete response as a single message (default).","type":"string","const":"off"},{"description":"Update a draft message with every flush interval.","type":"string","const":"partial"}]},"TailscaleTunnelConfig":{"type":"object","properties":{"funnel":{"description":"Use Tailscale Funnel (public internet) vs Serve (tailnet only)","type":"boolean","default":false},"hostname":{"description":"Optional hostname override","type":["string","null"]}}},"TaskRoutingConfig":{"description":"Lightweight pre-LLM task routing.","type":"object","properties":{"default_intent":{"description":"Fallback intent when no rule matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"rules":{"description":"Rules evaluated in descending priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/TaskRoutingRule"}}}},"TaskRoutingIntentConfig":{"description":"Task-routing default and rule intent.","type":"string","enum":["simple","delegate","stream"]},"TaskRoutingRule":{"description":"A single task-routing rule.","type":"object","properties":{"intent":{"description":"Route intent to apply when a keyword matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"model_hint":{"description":"Optional model hint/raw model for non-delegated requests.","type":["string","null"],"default":null},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0},"sub_agent_model":{"description":"Optional raw sub-agent model override for delegated tasks.","type":["string","null"],"default":null}}},"TelegramConfig":{"description":"Telegram bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Telegram user IDs or usernames. Empty = deny all.","type":"array","items":{"type":"string"}},"bot_token":{"description":"Telegram Bot API token (from @BotFather).","type":"string"},"draft_update_interval_ms":{"description":"Minimum interval (ms) between draft message edits to avoid rate limits.","type":"integer","format":"uint64","default":1000,"minimum":0},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"interrupt_on_new_message":{"description":"When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.","type":"boolean","default":false},"stream_mode":{"description":"Streaming mode for progressive response delivery via message edits.","$ref":"#/$defs/StreamMode","default":"off"}},"required":["bot_token","allowed_users"]},"ToolCallDialectSetting":{"description":"The tool-call grammars an operator may declare for an endpoint.","oneOf":[{"description":"Only the native `tool_calls` array is a tool call (the default).","type":"string","const":"native"},{"description":"Additionally read `{json}` from the content,\nfor a tool name the request registered.","type":"string","const":"xml_function_tags"}]},"ToolSchemaDialectSetting":{"description":"The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.","oneOf":[{"description":"The published document, byte for byte (the default).","type":"string","const":"raw"},{"description":"The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.","type":"string","const":"no_root_combinators"}]},"ToolTieringConfig":{"description":"Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.","type":"object","properties":{"always_exclude":{"description":"Tool names excluded from capability publication.","type":"array","default":[],"items":{"type":"string"}},"always_include":{"description":"Tool names preferred for direct publication, subject to admission gates.","type":"array","default":[],"items":{"type":"string"}},"channel_exclude":{"description":"Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefault: empty (nothing is hidden); list tool names to hide them on channels.","type":"array","default":[],"items":{"type":"string"}}}},"TunnelConfig":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.","type":"object","properties":{"cloudflare":{"description":"Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).","anyOf":[{"$ref":"#/$defs/CloudflareTunnelConfig"},{"type":"null"}],"default":null},"custom":{"description":"Custom tunnel command configuration (used when `provider = \"custom\"`).","anyOf":[{"$ref":"#/$defs/CustomTunnelConfig"},{"type":"null"}],"default":null},"ngrok":{"description":"ngrok tunnel configuration (used when `provider = \"ngrok\"`).","anyOf":[{"$ref":"#/$defs/NgrokTunnelConfig"},{"type":"null"}],"default":null},"provider":{"description":"Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.","type":"string","default":"none"},"tailscale":{"description":"Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).","anyOf":[{"$ref":"#/$defs/TailscaleTunnelConfig"},{"type":"null"}],"default":null}}},"UserPolicyConfig":{"description":"Startup user policy entry (`[[user_policies]]`).","type":"object","properties":{"blocked_patterns":{"type":"array","default":[],"items":{"type":"string"}},"projects":{"type":"array","default":[],"items":{"type":"string"}},"role":{"type":"string","default":"guest"},"user_id":{"type":"string"},"visibility_ceiling":{"type":"string","default":"private"}},"required":["user_id"]},"WacliConfig":{"description":"wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```","type":"object","properties":{"allow_unsigned_loopback":{"description":"Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).","type":"boolean","default":false},"allowed_from":{"description":"Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.","type":"array","default":["*"],"items":{"type":"string"}},"bot_jid":{"description":"Bot's own JID, used for reply-to-bot mention detection.","type":["string","null"],"default":null},"bot_lid":{"description":"The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.","type":["string","null"],"default":null},"bot_number":{"description":"Bot's own phone number (digits), used for `@` mention detection.","type":["string","null"],"default":null},"cli_path":{"description":"Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.","type":["string","null"],"default":null},"group_reply_mode":{"description":"Smart group-reply mode. When `None`, derived from `mention_only`.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"host":{"description":"REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].","type":["string","null"],"writeOnly":true},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"outbound_media_workspace_only":{"description":"Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.","type":"boolean","default":false},"port":{"description":"REMOVED: legacy JSON-RPC daemon port. See `host`.","type":["integer","null"],"format":"uint16","maximum":65535,"minimum":0,"writeOnly":true},"self_chat_mode":{"description":"Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.","type":"boolean","default":false},"store_dir":{"description":"wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.","type":["string","null"],"default":null},"webhook_listen":{"description":"Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").","type":"string","default":"127.0.0.1:16868"},"webhook_path":{"description":"HTTP path the webhook server serves (default: \"/wacli\").","type":"string","default":"/wacli"},"webhook_secret":{"description":"HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.","type":["string","null"],"default":null}}},"WebSearchConfig":{"description":"Web search tool configuration (`[web_search]` section).","type":"object","properties":{"brave_api_key":{"description":"Brave Search API key (required if provider is \"brave\")","type":["string","null"],"default":null},"fetch_max_chars":{"description":"Maximum characters returned by `web_fetch` (default 10000)","type":"integer","format":"uint","default":50000,"minimum":0},"max_results":{"description":"Maximum results per search (1-20)","type":"integer","format":"uint","default":15,"minimum":0},"provider":{"description":"Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)","type":"string","default":"duckduckgo"},"timeout_secs":{"description":"Request timeout in seconds","type":"integer","format":"uint64","default":15,"minimum":0}}},"WebhookConfig":{"description":"Webhook channel configuration.","type":"object","properties":{"port":{"description":"Port to listen on for incoming webhooks.","type":"integer","format":"uint16","maximum":65535,"minimum":0},"secret":{"description":"Optional shared secret for webhook signature verification.","type":["string","null"]}},"required":["port"]},"WhatsAppConfig":{"description":"WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.","type":"object","properties":{"access_token":{"description":"Access token from Meta Business Suite (Cloud API mode)","type":["string","null"],"default":null},"allowed_numbers":{"description":"Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"app_secret":{"description":"App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"pair_code":{"description":"Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one","type":["string","null"],"default":null},"pair_phone":{"description":"Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used","type":["string","null"],"default":null},"phone_number_id":{"description":"Phone number ID from Meta Business API (Cloud API mode)","type":["string","null"],"default":null},"read_pool_size":{"description":"Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"session_path":{"description":"Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs","type":["string","null"],"default":null},"verify_token":{"description":"Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode","type":["string","null"],"default":null},"ws_url":{"description":"WebSocket URL override (replaces WHATSAPP_WS_URL)","type":["string","null"],"default":null}}},"WorkspaceHooks":{"description":"Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).","oneOf":[{"description":"They do not run (the default); `prx doctor` and `hooks_status` say so.","type":"string","const":"off"},{"description":"They run, in a cleared environment and a dedicated directory beside\n`config.toml`.","type":"string","const":"on"}]},"WorkspaceMcpServers":{"description":"Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).","oneOf":[{"description":"None: a workspace file may only narrow the servers defined in\n`config.toml`.","type":"string","const":"off"},{"description":"HTTP servers (still refused when they target a private address).","type":"string","const":"http_only"},{"description":"HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.","type":"string","const":"stdio"}]},"XinConfig":{"description":"Configuration for the xin autonomous task engine (`[xin]`).","type":"object","properties":{"adopt_legacy_tasks":{"description":"Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).","type":"boolean","default":false},"interval_minutes":{"description":"Tick interval in minutes (minimum 1). Default: 5.","type":"integer","format":"uint32","default":5,"minimum":0},"stale_timeout_minutes":{"description":"Minutes after which a running task is marked stale. Default: 60.","type":"integer","format":"uint32","default":60,"minimum":0}}},"AgentMessaging":{"description":"Owner-controlled inbound session messaging (enabled unless explicitly off).","type":"object","properties":{"inbound":{"type":"boolean","default":true}}}}} From c9844f2e4672487fb004b89419f52f9339b8daeb Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:10:14 +0400 Subject: [PATCH 0150/1567] fix(agent): store the large tool output document in its redacted form --- src/agent/document_ingest.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/agent/document_ingest.rs b/src/agent/document_ingest.rs index 79b11a0ba..c947fa5c1 100644 --- a/src/agent/document_ingest.rs +++ b/src/agent/document_ingest.rs @@ -260,11 +260,17 @@ pub(super) async fn persist_tool_output_document( ); return Some("backend_not_supported"); } + // The document id and hash name the original output (they are what the + // history reference and the tool rows quote); the stored text is the + // redacted form the persistence layer applies to every stored tool text, + // so a later chunk lookup returns the same masked text a replay shows. let (document_id, sha256) = tool_output_document_id(tool_name, content); + let stored_content = crate::security::redaction::redact_secrets(content); let metadata_json = serde_json::json!({ "tool": tool_name, "content_sha256": sha256, "bytes": content.len(), + "redacted": stored_content != content, }) .to_string(); let input = DocumentIngestInput { @@ -278,7 +284,7 @@ pub(super) async fn persist_tool_output_document( source_kind: "tool_output".to_string(), source_uri: Some(format!("tool:{tool_name}")), title: Some(format!("Tool output: {tool_name}")), - content: content.to_string(), + content: stored_content, mime_type: Some("text/plain".to_string()), visibility: runtime.visibility.clone(), metadata_json: Some(metadata_json), From 82412979855fcb1e63a1d8411bea0286d05d200e Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:10:14 +0400 Subject: [PATCH 0151/1567] feat(config): reset an old explicit record_tool_events = false in the defaults migration --- docs/migration-unreleased.md | 12 ++++++--- src/config/defaults_migration.rs | 45 +++++++++++++++++++++++++++----- 2 files changed, 47 insertions(+), 10 deletions(-) diff --git a/docs/migration-unreleased.md b/docs/migration-unreleased.md index bbf3ffc58..829498245 100644 --- a/docs/migration-unreleased.md +++ b/docs/migration-unreleased.md @@ -137,6 +137,7 @@ build resets a value to the new default when it is exactly the old default: | `[tool_tiering] channel_exclude` | the former 14-tool list, exactly | | `[gateway] targeted_agents` | `false` | | `[nodes.server] allowed_commands` | `["echo"]` | +| `[memory.events] record_tool_events` | `false` | `acknowledge_unrestricted_profile` is no longer written when the files are rewritten. `autonomy.level` is never touched, and a `supervised` or `readonly` @@ -152,7 +153,10 @@ install keeps `workspace_only` and `forbidden_paths`. Authentication keys - **How:** the reset goes through the configuration transaction (one history record, revision check) and rewrites the configuration files in canonical form. A marker file `.defaults-migration` beside `config.toml` records that it ran - (key names only), so it never runs again. One info line at start names the + (key names only) and its version, so it never runs again. A later version + adds keys to the table: an install whose marker holds an older version resets + only the keys added since (for example `record_tool_events`), never a key it + already went through. One info line at start names the keys reset. `prx doctor` lists old default values still present. - **Roll back:** `prx config rollback` restores the files from before the reset. The marker stays, so the reset is not repeated. @@ -188,6 +192,6 @@ the inline limit; above it the row holds the preview and the document reference of the stored tool output. Stored text and arguments are redacted. These rows are log-only: they are not `message.created`, so history loaders and the handoff match ignore them, and the gateway sync stream carries nothing for -them. A config file that sets `record_tool_events` explicitly (including the -`false` that older generated templates wrote) keeps its value; set it to `true` -to start recording. No database schema migration is introduced. +them. Older generated templates wrote `record_tool_events = false` explicitly, so the +one-time reset above also changes that exact value to `true`; to keep recording +off after the upgrade, set it to `false` again once the reset has run. No database schema migration is introduced. diff --git a/src/config/defaults_migration.rs b/src/config/defaults_migration.rs index 56ef73522..570e56f29 100644 --- a/src/config/defaults_migration.rs +++ b/src/config/defaults_migration.rs @@ -19,6 +19,9 @@ //! - The migration runs once: the marker file records its version, and it is //! written whether or not anything was reset. A rolled-back install is not //! migrated again; `prx doctor` reports the old values it still holds. +//! - A key added by a later version carries that version in `since`. An install +//! whose marker holds an older version resets only the keys newer than its +//! marker, so keys it already went through are not reset a second time. use super::Config; use super::manage::{ConfigActor, ManagementService}; @@ -26,7 +29,7 @@ use crate::security::AutonomyLevel; use std::path::{Path, PathBuf}; /// Version of this migration. Raising it runs a later migration once more. -const MIGRATION_VERSION: u32 = 1; +const MIGRATION_VERSION: u32 = 2; /// Marker file beside `config.toml`. const MARKER_FILE: &str = ".defaults-migration"; @@ -75,6 +78,8 @@ const OLD_CHANNEL_EXCLUDE: &[&str] = &[ /// reset it to the new built-in default. struct LegacyDefault { key: &'static str, + /// Migration version that introduced this entry. + since: u32, /// Reset only while `autonomy.level = "full"`. full_only: bool, is_old: fn(&Config) -> bool, @@ -89,58 +94,74 @@ fn equals(list: &[String], old: &[&str]) -> bool { const LEGACY_DEFAULTS: &[LegacyDefault] = &[ LegacyDefault { key: "autonomy.max_cost_per_day_cents", + since: 1, full_only: false, is_old: |c| c.autonomy.max_cost_per_day_cents == Some(500), reset: |c| c.autonomy.max_cost_per_day_cents = None, }, LegacyDefault { key: "cost.daily_limit_usd", + since: 1, full_only: false, is_old: |c| c.cost.daily_limit_usd == Some(10.0), reset: |c| c.cost.daily_limit_usd = None, }, LegacyDefault { key: "cost.monthly_limit_usd", + since: 1, full_only: false, is_old: |c| c.cost.monthly_limit_usd == Some(100.0), reset: |c| c.cost.monthly_limit_usd = None, }, LegacyDefault { key: "autonomy.workspace_only", + since: 1, full_only: true, is_old: |c| c.autonomy.workspace_only, reset: |c| c.autonomy.workspace_only = false, }, LegacyDefault { key: "autonomy.forbidden_paths", + since: 1, full_only: true, is_old: |c| equals(&c.autonomy.forbidden_paths, OLD_FORBIDDEN_PATHS), reset: |c| c.autonomy.forbidden_paths.clear(), }, LegacyDefault { key: "multimodal.allow_remote_fetch", + since: 1, full_only: false, is_old: |c| !c.multimodal.allow_remote_fetch, reset: |c| c.multimodal.allow_remote_fetch = true, }, LegacyDefault { key: "tool_tiering.channel_exclude", + since: 1, full_only: false, is_old: |c| equals(&c.tool_tiering.channel_exclude, OLD_CHANNEL_EXCLUDE), reset: |c| c.tool_tiering.channel_exclude.clear(), }, LegacyDefault { key: "gateway.targeted_agents", + since: 1, full_only: false, is_old: |c| !c.gateway.targeted_agents, reset: |c| c.gateway.targeted_agents = true, }, LegacyDefault { key: "nodes.server.allowed_commands", + since: 1, full_only: false, is_old: |c| c.nodes.server.allowed_commands == ["echo"], reset: |c| c.nodes.server.allowed_commands.clear(), }, + LegacyDefault { + key: "memory.events.record_tool_events", + since: 2, + full_only: false, + is_old: |c| !c.memory.events.record_tool_events, + reset: |c| c.memory.events.record_tool_events = true, + }, ]; /// Keys of `config` that still hold their old default (names only). @@ -161,14 +182,20 @@ fn marker_path(config_path: &Path) -> PathBuf { .join(MARKER_FILE) } -/// Whether the migration has run (its marker is present at this version). -#[must_use] -pub(crate) fn migration_has_run(config_path: &Path) -> bool { +/// Version recorded in the marker file, 0 when there is no readable marker. +fn marker_version(config_path: &Path) -> u32 { std::fs::read_to_string(marker_path(config_path)) .ok() .and_then(|text| text.parse::().ok()) .and_then(|table| table.get("version").and_then(toml::Value::as_integer)) - .is_some_and(|version| version >= i64::from(MIGRATION_VERSION)) + .and_then(|version| u32::try_from(version).ok()) + .unwrap_or(0) +} + +/// Whether the migration has run (its marker is present at this version). +#[must_use] +pub(crate) fn migration_has_run(config_path: &Path) -> bool { + marker_version(config_path) >= MIGRATION_VERSION } fn write_marker(config_path: &Path, removed: &[&str]) { @@ -192,7 +219,13 @@ pub(crate) async fn run_once(config: Config) -> Config { if migration_has_run(&config.config_path) { return config; } - let keys = legacy_default_keys(&config); + let done = marker_version(&config.config_path); + let full = config.autonomy.level == AutonomyLevel::Full; + let keys: Vec<&'static str> = LEGACY_DEFAULTS + .iter() + .filter(|entry| entry.since > done && (full || !entry.full_only) && (entry.is_old)(&config)) + .map(|entry| entry.key) + .collect(); if keys.is_empty() { write_marker(&config.config_path, &keys); return config; From ff65f146f2926b8a0cbdcd83fea5f7f7f2bb3851 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:10:14 +0400 Subject: [PATCH 0152/1567] feat(agent): replay earlier tool rounds and stored message attachments on the gateway session route --- docs/configuration.md | 2 +- docs/unified-turn-context.md | 17 ++ src/agent/mod.rs | 1 + src/agent/tool_replay.rs | 380 ++++++++++++++++++++++++++ src/agent/turn_contracts.rs | 11 +- src/gateway/api/sessions/section_1.rs | 71 +++-- 6 files changed, 450 insertions(+), 32 deletions(-) create mode 100644 src/agent/tool_replay.rs diff --git a/docs/configuration.md b/docs/configuration.md index 7736a75a8..0f9ede5e3 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1300,7 +1300,7 @@ PRX treats `chat`, `agent`, `gateway`, `channel`, `delegate`, and `sessions_spaw - `auto_save` no longer controls the base message log; it gates semantic promotion for backward compatibility. - The embedded `Agent` API additionally honors `semantic.auto_promote_user_messages` and `semantic.min_chars`. It promotes only original user input, using an owner-scoped `user_msg:` key and source session/event metadata. It leaves legacy `user_msg` entries intact. Unsupported owner-aware writes are skipped with a content-free warning; model execution continues. See [embedded API admission](unified-turn-context.md#embedded-agent-api-admission). -`[memory.events]` controls raw/quasi-raw event recording. Turning it off stops new fabric event rows for entrypoints wired through `MemoryFabric`. `record_tool_events` (default `true`) controls the `tool.call.recorded` and `tool.result.recorded` rows: one per tool call and one per result, with the run, round and call id in the payload, the redacted inline result text, and the document reference when an oversized output was stored. They are not chat messages and are not sent on the gateway sync stream. +`[memory.events]` controls raw/quasi-raw event recording. Turning it off stops new fabric event rows for entrypoints wired through `MemoryFabric`. `record_tool_events` (default `true`) controls the `tool.call.recorded` and `tool.result.recorded` rows: one per tool call and one per result, with the run, round and call id in the payload, the redacted inline result text, and the document reference when an oversized output was stored. They are not chat messages and are not sent on the gateway sync stream. On the gateway session route (Console and rf) the next turn's request replays the previous turns' tool calls and results from those rows, between the user message and the assistant reply, paired by run, round and call id; a result with a stored document is replayed as its preview plus the reference. When the request would exceed the compaction warning threshold, the oldest replayed results become one-line stubs (tool, status, size, document reference) before the context switch runs. The same setting stores, in a `message.attachment.recorded` row, the recalled-memory text and date line sent with each user message, so an earlier user message keeps its bytes on later turns; with the setting off, sessions are replayed as before. Terminal chat does not replay tool rows yet. `[memory.semantic]` controls promotion from event/message content into durable semantic memory. Assistant promotion is disabled by default to reduce noisy self-generated memory. diff --git a/docs/unified-turn-context.md b/docs/unified-turn-context.md index e9839ef31..ab99b0aa0 100644 --- a/docs/unified-turn-context.md +++ b/docs/unified-turn-context.md @@ -60,6 +60,23 @@ skill when `skill_read` is excluded by global or model-specific configuration. `skill_read` is a core prompt dependency; skill execution aliases remain subject to normal selection and exposure rules. +## Replayed history on the gateway session route + +The history of a Console or rf session turn is built from the stored +conversation turns plus the durable log rows of role `tool` +(`src/agent/tool_replay.rs`). Each earlier user message is replayed with its +stored attachment (the masked recall text before it and the date line after it, +`message.attachment.recorded`), so its bytes do not change between turns. Each +earlier assistant reply is preceded by the tool rounds of its run +(`tool.call.recorded` / `tool.result.recorded`), in the native envelope form the +turn loop uses in-turn. A call with no stored result is paired with a stub +result; a result with no stored call is dropped; a run without a stored reply +is not replayed. Replayed tool messages have no event id, so the compaction +provenance folds them into their round by shape. When the request is over the +warning threshold, the oldest replayed results become one-line stubs first. +The rows are not on the sync stream, and `conversation_turns` is unchanged. +Terminal chat, channels, scheduled turns and children are not covered yet. + ## Ownership | Concern | Owner | Rule | diff --git a/src/agent/mod.rs b/src/agent/mod.rs index e34dfaa1d..d084d7f9b 100644 --- a/src/agent/mod.rs +++ b/src/agent/mod.rs @@ -34,6 +34,7 @@ pub mod terminal; pub(crate) mod tool_call_parser; pub(crate) mod tool_event_recording; pub(crate) mod tool_evidence; +pub(crate) mod tool_replay; pub(crate) mod tool_result_recording; pub(crate) mod tool_scheduler; pub(crate) mod turn_context; diff --git a/src/agent/tool_replay.rs b/src/agent/tool_replay.rs new file mode 100644 index 000000000..1a31e4333 --- /dev/null +++ b/src/agent/tool_replay.rs @@ -0,0 +1,380 @@ +//! Replay of earlier turns' tool work, and of the attachment a user message +//! carried when it was sent, from the durable log. +//! +//! Two kinds of row are read back, both written with role `tool` so the sync +//! stream never carries them: +//! +//! - `tool.call.recorded` / `tool.result.recorded` (see +//! [`crate::agent::tool_event_recording`]): every call and result of a turn, +//! paired by run, round and call id. +//! - `message.attachment.recorded` (written by [`record_attachment`]): the text +//! put before and after a user message when it was sent (recalled memory and +//! the date line), so a later turn replays the message with the same bytes. +//! +//! A turn's tool rounds are replayed in the provider-neutral form the turn loop +//! uses for in-turn rounds (an assistant envelope carrying `tool_calls`, then +//! one `tool` message per call), between the user message and the assistant +//! reply of the run that made them. A call without a stored result is paired +//! with a stub result; a result without a stored call is dropped. A turn that +//! was interrupted before its reply was stored is never replayed. +//! +//! When the request would be over its budget, the oldest replayed results are +//! replaced by a one-line stub before anything else gives way +//! ([`ReplayedTurns::fit`]). The stored rows are never touched. + +use crate::agent::context_budget::{PRE_TURN_FLUSH_THRESHOLD, estimate_history_tokens, plan_context_budget}; +use crate::agent::history::build_native_assistant_history; +use crate::agent::tool_event_recording::{TOOL_CALL_EVENT_TYPE, TOOL_RESULT_EVENT_TYPE}; +use crate::memory::{ + ConversationTurn, MemoryFabric, MemoryPrincipal, MessageEvent, MessageEventScope, SessionContextQuery, +}; +use crate::providers::{ChatMessage, ToolCall}; +use std::collections::{BTreeMap, HashMap, HashSet}; + +/// Event type of the row that stores a user message's attachment. +pub(crate) const ATTACHMENT_EVENT_TYPE: &str = "message.attachment.recorded"; + +/// Rows read per query (the store's own page cap). +const REPLAY_ROW_LIMIT: usize = 500; + +/// What was put around a user message when it was sent. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub(crate) struct Attachment { + /// Text placed before the user's text (recalled memory). + pub prefix: String, + /// Text placed after it (the date line). + pub tail: String, +} + +#[derive(Debug, Clone)] +struct StoredCall { + call_id: String, + tool: String, + arguments: String, +} + +#[derive(Debug, Clone)] +struct StoredResult { + status: String, + result_bytes: u64, + document_id: Option, + content: String, +} + +#[derive(Debug, Default)] +struct StoredRound { + calls: BTreeMap, + results: HashMap, +} + +/// The rows of one session that replay reads. +#[derive(Debug, Default)] +pub(crate) struct ReplayLog { + /// Tool rounds by run id, in round order. + rounds: HashMap>, + /// Attachments by the event id of the user message they belong to. + attachments: HashMap, + /// The run of each stored user or assistant message, by event id. + run_of_event: HashMap, +} + +fn payload_of(event: &MessageEvent) -> Option { + event + .raw_payload_json + .as_deref() + .and_then(|raw| serde_json::from_str(raw).ok()) +} + +fn text(value: &serde_json::Value, key: &str) -> Option { + value.get(key).and_then(serde_json::Value::as_str).map(str::to_owned) +} + +/// A call id as every provider accepts it: ASCII letters, digits, `_` and `-`. +fn wire_id(call_id: &str) -> String { + let id: String = call_id + .chars() + .map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' { c } else { '_' }) + .collect(); + if id.is_empty() { "call".to_owned() } else { id } +} + +impl ReplayLog { + /// Read the session's tool, attachment and message rows. A read that fails + /// leaves the log empty, so the turn replays as it did before these rows. + pub(crate) async fn load(mem: &dyn crate::memory::Memory, principal: &MemoryPrincipal) -> Self { + let query = |roles: &[&str]| SessionContextQuery { + principal: principal.clone(), + since_event_id: None, + limit: REPLAY_ROW_LIMIT, + include_roles: roles.iter().map(|role| (*role).to_owned()).collect(), + }; + let (tool_rows, message_rows) = match ( + mem.load_recent_session_context(query(&["tool"])).await, + mem.load_recent_session_context(query(&["user", "assistant"])).await, + ) { + (Ok(tool_rows), Ok(message_rows)) => (tool_rows, message_rows), + (Err(error), _) | (_, Err(error)) => { + tracing::warn!( + error = %crate::agent::diagnostics::error_class(&error), + "tool replay rows unavailable; history is replayed without them" + ); + return Self::default(); + } + }; + Self::from_rows(&tool_rows, &message_rows) + } + + fn from_rows(tool_rows: &[MessageEvent], message_rows: &[MessageEvent]) -> Self { + let mut log = Self::default(); + for event in message_rows { + if event.event_type == "message.created" + && let Some(run_id) = &event.run_id + { + log.run_of_event.insert(event.event_id.clone(), run_id.clone()); + } + } + for event in tool_rows { + let Some(payload) = payload_of(event) else { continue }; + match event.event_type.as_str() { + TOOL_CALL_EVENT_TYPE => log.add_call(&payload), + TOOL_RESULT_EVENT_TYPE => log.add_result(event, &payload), + ATTACHMENT_EVENT_TYPE => { + if let Some(user_event_id) = text(&payload, "user_event_id") { + log.attachments.insert( + user_event_id, + Attachment { + prefix: text(&payload, "prefix").unwrap_or_default(), + tail: text(&payload, "tail").unwrap_or_default(), + }, + ); + } + } + _ => {} + } + } + log + } + + fn round_mut(&mut self, payload: &serde_json::Value) -> Option<&mut StoredRound> { + let run_id = text(payload, "run_id")?; + let round = payload.get("round").and_then(serde_json::Value::as_u64)?; + Some(self.rounds.entry(run_id).or_default().entry(round).or_default()) + } + + fn add_call(&mut self, payload: &serde_json::Value) { + let (Some(call_id), Some(tool), Some(index)) = ( + text(payload, "call_id"), + text(payload, "tool"), + payload.get("index").and_then(serde_json::Value::as_u64), + ) else { + return; + }; + let arguments = payload + .get("arguments") + .map_or_else(|| "{}".to_owned(), serde_json::Value::to_string); + if let Some(round) = self.round_mut(payload) { + round.calls.insert( + index, + StoredCall { + call_id, + tool, + arguments, + }, + ); + } + } + + fn add_result(&mut self, event: &MessageEvent, payload: &serde_json::Value) { + let Some(call_id) = text(payload, "call_id") else { + return; + }; + let result = StoredResult { + status: text(payload, "status").unwrap_or_else(|| "unknown".to_owned()), + result_bytes: payload + .get("result_bytes") + .and_then(serde_json::Value::as_u64) + .unwrap_or_default(), + document_id: payload + .get("document") + .and_then(|document| text(document, "document_id")), + content: event.content.clone(), + }; + if let Some(round) = self.round_mut(payload) { + round.results.insert(call_id, result); + } + } + + /// The stored turns as history messages, in order: each user message with + /// its stored attachment, each assistant reply preceded by the tool rounds + /// of its run. Event ids line up with the messages, `None` for a replayed + /// tool message. + pub(crate) fn expand_turns(&self, turns: Vec) -> ReplayedTurns { + let mut out = ReplayedTurns::default(); + let mut replayed_runs: HashSet<&str> = HashSet::new(); + for turn in turns { + let event_id = turn.message_event_id.clone(); + if turn.role == "assistant" + && let Some(run_id) = event_id.as_deref().and_then(|id| self.run_of_event.get(id)) + && replayed_runs.insert(run_id.as_str()) + && let Some(rounds) = self.rounds.get(run_id) + { + for round in rounds.values() { + out.push_round(round); + } + } + let content = match (turn.role.as_str(), event_id.as_deref().and_then(|id| self.attachments.get(id))) { + ("user", Some(attachment)) => format!("{}{}{}", attachment.prefix, turn.content, attachment.tail), + _ => turn.content, + }; + out.messages + .push(crate::agent::turn_contracts::stored_turn_message(turn.role, content)); + out.event_ids.push(event_id); + } + out + } +} + +/// A replayed result message, kept so it can be turned into a stub. +#[derive(Debug, Clone)] +struct ReplayedResult { + /// Index into [`ReplayedTurns::messages`]. + index: usize, + wire_id: String, + tool: String, + status: String, + bytes: u64, + document_id: Option, +} + +/// The turns of a session as history messages, with their tool rounds. +#[derive(Debug, Default)] +pub(crate) struct ReplayedTurns { + pub messages: Vec, + /// The stored event of each message, index for index. + pub event_ids: Vec>, + results: Vec, +} + +const MISSING_RESULT: &str = "[no result was stored for this call]"; + +fn result_message(wire_id: &str, content: &str) -> ChatMessage { + ChatMessage::tool(serde_json::json!({ "tool_call_id": wire_id, "content": content }).to_string()) +} + +impl ReplayedTurns { + fn push_round(&mut self, round: &StoredRound) { + if round.calls.is_empty() { + return; + } + let calls: Vec = round + .calls + .values() + .map(|call| ToolCall { + id: wire_id(&call.call_id), + name: call.tool.clone(), + arguments: call.arguments.clone(), + }) + .collect(); + self.messages + .push(ChatMessage::assistant(build_native_assistant_history("", &calls, None))); + self.event_ids.push(None); + for call in round.calls.values() { + let id = wire_id(&call.call_id); + let stored = round.results.get(&call.call_id); + let content = stored.map_or(MISSING_RESULT, |result| result.content.as_str()); + self.results.push(ReplayedResult { + index: self.messages.len(), + wire_id: id.clone(), + tool: call.tool.clone(), + status: stored.map_or_else(|| "missing".to_owned(), |result| result.status.clone()), + bytes: stored.map_or(0, |result| result.result_bytes), + document_id: stored.and_then(|result| result.document_id.clone()), + }); + self.messages.push(result_message(&id, content)); + self.event_ids.push(None); + } + } + + /// Replace the oldest replayed results by a stub, as many as it takes for + /// the request (`leading`, these turns, `request`) to fit under the + /// compaction warning threshold. Nothing else is dropped or changed. + /// Returns how many results were stubbed. + pub(crate) fn fit( + &mut self, + leading: &ChatMessage, + request: &ChatMessage, + config: &crate::config::AgentCompactionConfig, + ) -> usize { + if self.results.is_empty() { + return 0; + } + let mut whole = Vec::with_capacity(self.messages.len() + 2); + whole.push(leading.clone()); + whole.extend(self.messages.iter().cloned()); + whole.push(request.clone()); + let budget = plan_context_budget(&whole, config, PRE_TURN_FLUSH_THRESHOLD); + if !budget.over_warning { + return 0; + } + let mut excess = budget.used_tokens.saturating_sub(budget.warning_threshold_tokens); + let mut stubbed = 0; + for result in &self.results { + if excess == 0 { + break; + } + let Some(message) = self.messages.get_mut(result.index) else { continue }; + let stub = result_message(&result.wire_id, &stub_text(result)); + let saved = estimate_history_tokens(std::slice::from_ref(message)) + .saturating_sub(estimate_history_tokens(std::slice::from_ref(&stub))); + if saved == 0 { + continue; + } + *message = stub; + excess = excess.saturating_sub(saved); + stubbed += 1; + } + stubbed + } +} + +/// The one-line text a cleared result is replaced by. +fn stub_text(result: &ReplayedResult) -> String { + let lookup = result.document_id.as_ref().map_or_else( + || "the output is not kept in view; run the tool again if it is needed".to_owned(), + |id| format!("full output stored as document {id}, read it with document_get_chunk"), + ); + format!( + "[tool result cleared: tool {}, status {}, {} bytes; {lookup}]", + result.tool, result.status, result.bytes + ) +} + +/// Append the attachment row of a user message: `prefix` and `tail` are the +/// text put before and after it. Nothing is written when tool events are not +/// recorded; the message is then replayed plain, as before. +pub(crate) async fn record_attachment( + fabric: &MemoryFabric, + scope: MessageEventScope, + user_event_id: &str, + attachment: &Attachment, +) { + let payload = serde_json::json!({ + "schema_version": 1, + "run_id": scope.run_id, + "user_event_id": user_event_id, + "prefix": attachment.prefix, + "tail": attachment.tail, + }); + if let Err(error) = fabric + .record_tool_round_event( + scope, + ATTACHMENT_EVENT_TYPE, + format!("attachment of {user_event_id}"), + Some(payload.to_string()), + ) + .await + { + let (error_len, error_sha256) = crate::agent::diagnostics::error_log_digest(&error); + tracing::warn!(error_len, error_sha256, "Failed to persist message attachment"); + } +} diff --git a/src/agent/turn_contracts.rs b/src/agent/turn_contracts.rs index 509e487ce..8d7c99473 100644 --- a/src/agent/turn_contracts.rs +++ b/src/agent/turn_contracts.rs @@ -234,12 +234,15 @@ pub(crate) fn inbound_user_message(text: &str) -> ChatMessage { /// bytes stay identical between turns; the clock rides in the one message that /// is new every turn. pub(crate) fn push_current_time_tail(content: &mut String) { - use std::fmt::Write as _; - let _ = write!( - content, + content.push_str(¤t_time_tail()); +} + +/// The text [`push_current_time_tail`] appends. +pub(crate) fn current_time_tail() -> String { + format!( "\n\n[Current date and time: {}]", chrono::Local::now().format("%A, %Y-%m-%d %H:%M %:z") - ); + ) } /// Fresh inbound text already owned by the caller. Preserve its allocation diff --git a/src/gateway/api/sessions/section_1.rs b/src/gateway/api/sessions/section_1.rs index 48202025e..62e38c414 100644 --- a/src/gateway/api/sessions/section_1.rs +++ b/src/gateway/api/sessions/section_1.rs @@ -824,28 +824,55 @@ async fn run_console_runtime_turn( crate::agent::context_recall::RECALL_CONTEXT_BUDGET, ) .await; - let mut enriched_message = if mem_context.preamble.is_empty() { - visible_message.to_string() - } else { - format!("{}{}", mem_context.preamble, visible_message) + // What is put around the message is stored beside it and replayed on later + // turns, so the message keeps its bytes. It is stored (and sent) masked. + let attachment = crate::agent::tool_replay::Attachment { + prefix: crate::security::redaction::redact_secrets(&mem_context.preamble), + tail: crate::agent::turn_contracts::current_time_tail(), }; - crate::agent::turn_contracts::push_current_time_tail(&mut enriched_message); + let enriched_message = format!("{}{visible_message}{}", attachment.prefix, attachment.tail); + let replay_fabric = MemoryFabric::new(state.mem.clone(), turn_envelope.workspace_id.clone()) + .with_event_recording(config_snapshot.memory.event_recording_config()); + if let Some(user_event_id) = turn_envelope.source_message_event_id.as_deref() { + crate::agent::tool_replay::record_attachment( + &replay_fabric, + turn_envelope.message_scope(), + user_event_id, + &attachment, + ) + .await; + } + let replay_log = crate::agent::tool_replay::ReplayLog::load(state.mem.as_ref(), &turn_envelope.memory_principal()).await; - // The stored event of each history message, index for index: none for the - // system prompt, each stored turn's event, then the request's own event. + // OQ-23 / R5: budget on the *effective* window of the model this turn + // serves (the operator/discovery/catalog model limits and + // `reserved_output_tokens`), with the same arguments the CLI, TUI and + // webhook resolve with, so one request is trimmed the same way on every + // surface of this process. + let mut effective_compaction = decision + .service + .effective_compaction(&provider_label, &turn_runtime.model); + effective_compaction.config = decision.context.main_compaction().clone(); + crate::providers::context_window::trace_effective_compaction_resolution(&effective_compaction); + let system_message = ChatMessage::system(system_prompt); + let request_message = crate::agent::turn_contracts::inbound_user_message(&enriched_message); + // Earlier turns with their tool rounds; the oldest results become stubs + // when the request would be over budget. The stored event of each history + // message, index for index: none for the system prompt or a tool message, + // each stored turn's event, then the request's own event. + let mut replayed = replay_log.expand_turns(previous_turns); + let stubbed = replayed.fit(&system_message, &request_message, &effective_compaction.config); + if stubbed > 0 { + tracing::info!(stubbed, "oldest replayed tool results were replaced by stubs to fit the request"); + } let history_event_ids: Vec> = std::iter::once(None) - .chain(previous_turns.iter().map(|turn| turn.message_event_id.clone())) + .chain(replayed.event_ids) .chain(std::iter::once(turn_envelope.source_message_event_id.clone())) .collect(); - let mut history = Vec::with_capacity(previous_turns.len() + 2); - history.push(ChatMessage::system(system_prompt)); - // stored console turns are neutralised like fresh input - history.extend( - previous_turns - .into_iter() - .map(|turn| crate::agent::turn_contracts::stored_turn_message(turn.role, turn.content)), - ); - history.push(crate::agent::turn_contracts::inbound_user_message(&enriched_message)); + let mut history = Vec::with_capacity(replayed.messages.len() + 2); + history.push(system_message); + history.extend(replayed.messages); + history.push(request_message); // D2 / FIX-P1-31: build via the shared `build_security_policy` helper so this // per-turn gateway authz site cannot drift from (or forget) the audit-config @@ -876,16 +903,6 @@ async fn run_console_runtime_turn( Some((_, route)) => route.as_ref().clone(), None => console_route_decision(&turn_runtime, &turn_envelope, visible_message)?, }; - // OQ-23 / R5: budget on the *effective* window of the model this turn - // serves (the operator/discovery/catalog model limits and - // `reserved_output_tokens`), with the same arguments the CLI, TUI and - // webhook resolve with, so one request is trimmed the same way on every - // surface of this process. - let mut effective_compaction = decision - .service - .effective_compaction(&provider_label, &turn_runtime.model); - effective_compaction.config = decision.context.main_compaction().clone(); - crate::providers::context_window::trace_effective_compaction_resolution(&effective_compaction); let provider_started_at = chrono::Utc::now(); let loop_result = run_turn( &mut history, From 06d6e349f83ee40584603fb3ec020d55dcec10c2 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:11:09 +0400 Subject: [PATCH 0153/1567] feat(tools): publish every available tool by default A default install offers the model every available tool directly, in a stable order, on every surface. [tool_tiering] defer_unlisted = true is the operator option that keeps only the core tools and always_include names direct and leaves the rest behind capability_search. --- docs/configuration.md | 11 ++++++++--- docs/migration-unreleased.md | 1 + src/config/schema/security.rs | 6 ++++++ src/runtime/turn_publication.rs | 11 +++++++---- src/session_worker/runner/run.rs | 16 +++++++++++++--- src/tools/capability/catalog/section_1.rs | 16 +++++++++++++++- tests/fixtures/config-schema.json | 2 +- 7 files changed, 51 insertions(+), 12 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 0f9ede5e3..80212960a 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -157,7 +157,7 @@ and the module-gate family are absorbed on load; they are not live switches. | `[security]` | `workspace_hooks` omitted when off | | `[compliance.interaction_notice]` | `version = "1"`; default notice text; `applicability = "required"`; `exception_owner`/`exception_reviewed_at` unset | | `[compliance.eu_ai_act]` | classification `status = "unclassified"`; `owner`/`assessed_at` unset; `incident_store_path` unset; declaration fields all optional/empty | -| `[tool_tiering]` | `always_include = []`; `always_exclude = []`; `channel_exclude = []` (nothing hidden from channel sessions) | +| `[tool_tiering]` | `always_include = []`; `always_exclude = []`; `channel_exclude = []` (nothing hidden from channel sessions); `defer_unlisted = false` (every available tool is published to the model) | | `[providers]` | `[providers.ollama] num_ctx` unset. `[[providers.tool_dialects]]`: `provider` required; `model` unset (all models); `tool_schema`/`tool_call` unset (`raw` / `native`). `[[providers.models]]`: `provider` required; `model` unset; `operations`, `native_tools`, `vision_input`, `streaming`, `structured_output`, `tool_schema_dialect`, `tool_call_dialect`, `context_window` all unset. See later sections | | `[model_settings.]` | catalog levels and explicit parameters; omitted keys stay with the catalog | @@ -717,8 +717,12 @@ priority_scheduling_enabled = false low_priority_tools = ["sessions_spawn", "delegate"] # Per-turn capability policy. The surface owner applies these filters (they are -# not owned by the decision engine). `always_include` prefers direct publication; -# `always_exclude` removes names from the surface. `channel_exclude` applies to IM +# not owned by the decision engine). Every available tool is published to the +# model by default. `defer_unlisted = true` is the operator option that +# publishes only the core tools (file_read, file_write, file_edit, shell) plus +# `always_include`; every other tool then waits behind `capability_search` and +# can also be called by its exact name. `always_exclude` removes names from the +# surface. `channel_exclude` applies to IM # channel sessions only (Signal / Telegram / Discord / WhatsApp / …) and is empty # by default, so nothing is hidden. To hide the operations/development surface on # channels list its names, for example: wasm_plugins_manage, wasm_plugin_reload, @@ -732,6 +736,7 @@ low_priority_tools = ["sessions_spawn", "delegate"] always_include = [] always_exclude = [] # channel_exclude = [] +# defer_unlisted = false # A request that advertises skill metadata also admits its live skill_read # dependency. Missing or denied readers suppress that metadata with a diagnostic. diff --git a/docs/migration-unreleased.md b/docs/migration-unreleased.md index 829498245..5d222ac41 100644 --- a/docs/migration-unreleased.md +++ b/docs/migration-unreleased.md @@ -30,6 +30,7 @@ of the [changelog](../CHANGELOG.md). | Known Codex model default effort | Declared Codex rows now use `medium` rather than `xhigh`. Set an explicit supported effort if the former behavior is required. Unknown rows keep the legacy `medium` verbosity / `xhigh` effort base. See [model levels and parameters](model-catalog.md). | Only to retain the former effort | | No spend ceiling by default | `[autonomy] max_cost_per_day_cents`, `[cost] daily_limit_usd` and `[cost] monthly_limit_usd` are now optional and unset by default. Before: a config that omitted them got 500 cents per day, 10.0 USD per day and 100.0 USD per month. Now: a config that omits them has no limit, so no spend is refused for a budget reason, no budget warning or "budget exhausted" notice is printed, and children and worker processes get the maximum allowance (`u32::MAX` cents in the signed manifest). A config that sets any of these keys keeps exactly that limit. `prx init` no longer writes `max_cost_per_day_cents`. Usage accounting and the cost journal are unchanged. To keep the old ceilings, write them into the config. Per-agent `limits` were already unset by default. No stored-data migration is required. | Only to keep the former ceilings: set the three keys explicitly | | Nothing restricted by default on a fresh install | `[tool_tiering] channel_exclude` now defaults to an empty list (before: 14 operations tools such as `gateway`, `config_reload`, `nodes`, `skills_manage` were hidden from IM channel turns); a config that omits it now exposes those tools on channel turns, and a config that lists names keeps hiding them. `prx init --spec server` no longer writes `workspace_only`, `forbidden_paths` or `acknowledge_unrestricted_profile` (the built-in values are unchanged and have no effect at level `full`); `--spec full` no longer writes `acknowledge_unrestricted_profile`. `prx doctor` no longer warns for an explicit unrestricted profile; it prints one neutral autonomy-level line, and `acknowledge_unrestricted_profile` is accepted and ignored. Gateway pairing, channel sender allowlists, secret protection and integrity checks are unchanged. | Only to keep the old channel tool hiding: list the names in `channel_exclude` | +| Every tool published by default | The model is now offered every available tool directly on every surface (terminal chat, gateway, channels, scheduled runs, children), in a stable name order. Before: only `file_read`, `file_write`, `file_edit`, `shell` and a few session tools were offered and the rest sat behind `capability_search`, so `cron`, `sessions_spawn` and `skills_manage` went unused unless named in `[tool_tiering] always_include`. The request carries more tool definitions, so each request uses more of the context window. `always_exclude` and `channel_exclude` still hide names. | Only to keep the old deferral: set `[tool_tiering] defer_unlisted = true`; the core tools, `always_include` names and `capability_search` then work as before, and a deferred tool can also be called by its exact name | | Remote image fetch on by default | `[multimodal] allow_remote_fetch` now defaults to `true` (before: `false`). A config that omits it now lets `http`/`https` image references be fetched into the model context; an explicit `false` keeps the old behavior. The fetch keeps the same private-address handling as `web_fetch`: below Full private, loopback and link-local hosts are refused, at Full they are reachable. | Only to keep remote fetch off: set `allow_remote_fetch = false` | | Node agent allows any command by default | `[nodes.server] allowed_commands` now defaults to an empty list, which allows any command (before: `["echo"]`, so every other command was refused). A config that omits the key now lets an authenticated caller run any command; a config that lists commands keeps that allowlist. Authentication is unchanged: a non-empty bearer token is required at startup, `hmac_secret` is checked when set, `tls_required = true` still demands TLS on non-loopback binds, and the default bind is loopback. `blocked_commands` is still enforced. | Only to keep the old restriction: set `allowed_commands = ["echo"]` | | Autonomy path keys unset by default | `[autonomy] workspace_only` now defaults to `false` (before: `true`) and `forbidden_paths` to an empty list (before: 18 system paths). A config that omits them gets no workspace confinement and no path denylist; a config that sets them keeps exactly what it sets. Both keys are read below level `full` only (file tools, shell path arguments, image and document tools, the TUI file picker); at `full` they were already ignored. An install that runs `supervised` or `readonly` and relied on the old defaults must now write `workspace_only = true` and its `forbidden_paths`. Owner-private file operations stay confined to the workspace at every level, independent of these keys. `prx init` never writes these keys or `acknowledge_unrestricted_profile` (the latter is accepted from an existing config and ignored, and is no longer serialised). `prx status` prints a `Cost limits:` line (any configured `[cost]` or `[autonomy]` limit, or `no limit set`) instead of `Max cost/day:`, and prints `Workspace only:` and `Forbidden paths:` only when they are set. | Only for `supervised` or `readonly` installs: set `workspace_only` and `forbidden_paths` explicitly | diff --git a/src/config/schema/security.rs b/src/config/schema/security.rs index 355f8c141..a81bfb8b6 100644 --- a/src/config/schema/security.rs +++ b/src/config/schema/security.rs @@ -225,6 +225,10 @@ pub struct ToolTieringConfig { /// Tool names hidden from IM channel sessions only, on top of `always_exclude`. /// Default: empty (nothing is hidden); list tool names to hide them on channels. pub channel_exclude: Vec, + /// Operator option: publish only the core tools plus `always_include` and + /// leave every other tool behind `capability_search` and its exact name. + /// Default: false (every available tool is published to the model). + pub defer_unlisted: bool, } impl Default for ToolTieringConfig { @@ -233,6 +237,7 @@ impl Default for ToolTieringConfig { always_include: Vec::new(), always_exclude: Vec::new(), channel_exclude: Vec::new(), + defer_unlisted: false, } } } @@ -292,6 +297,7 @@ impl ToolTieringConfig { always_include: self.always_include.clone(), always_exclude: Vec::new(), channel_exclude: Vec::new(), + defer_unlisted: self.defer_unlisted, }) } else { std::borrow::Cow::Borrowed(self) diff --git a/src/runtime/turn_publication.rs b/src/runtime/turn_publication.rs index 027beb586..b4b250c8b 100644 --- a/src/runtime/turn_publication.rs +++ b/src/runtime/turn_publication.rs @@ -17,10 +17,10 @@ use crate::tools; use anyhow::Result; use std::sync::Arc; -/// The bounded native schemas kept on ordinary model turns. These are the -/// common file and shell operations from the standard progressive-disclosure -/// contract; publication still applies source, model, surface, security and -/// approval gates before any one of them can execute. +/// The core native schemas. A default install publishes every tool, so these +/// are the whole direct set only when `[tool_tiering] defer_unlisted = true`; +/// publication still applies source, model, surface, security and approval +/// gates before any one of them can execute. const DEFAULT_DIRECT_TOOLS: [&str; 4] = ["file_edit", "file_read", "file_write", "shell"]; /// The sessions tools a chat turn and its whole lineage publish directly @@ -30,9 +30,12 @@ const CHAT_SESSIONS_TOOLS: [&str; 4] = ["sessions_spawn", "sessions_send", "sess fn direct_tool_names(configured: &crate::config::ToolTieringConfig, chat: bool) -> std::collections::BTreeSet { let chat_tools: &[&str] = if chat { &CHAT_SESSIONS_TOOLS } else { &[] }; + // Every tool is published unless the operator asks to defer the rest. + let publish_all = (!configured.defer_unlisted).then_some(tools::capability::catalog::ALL_TOOLS_DIRECT); DEFAULT_DIRECT_TOOLS .into_iter() .chain(chat_tools.iter().copied()) + .chain(publish_all) .map(str::to_owned) .chain(configured.always_include.iter().cloned()) .filter(|name| !configured.always_exclude.contains(name)) diff --git a/src/session_worker/runner/run.rs b/src/session_worker/runner/run.rs index 63435d99a..afe1e3679 100644 --- a/src/session_worker/runner/run.rs +++ b/src/session_worker/runner/run.rs @@ -122,14 +122,24 @@ struct PreparedWorkerResult { } /// The worker's direct names: the sealed chat-lineage set when the parent -/// filled one (D5), else `always_include`. A name is still published only -/// where this worker's registry serves it and no exclusion hides it. +/// filled one (D5), else `always_include` plus the publish-all member unless +/// the operator defers tools. A name is still published only where this +/// worker's registry serves it and no exclusion hides it. fn worker_direct_names( manifest: &WorkerManifest, tiering: &crate::config::ToolTieringConfig, ) -> std::collections::BTreeSet { manifest.direct_tools.as_ref().map_or_else( - || tiering.always_include.iter().cloned().collect(), + || { + let publish_all = (!tiering.defer_unlisted).then_some(crate::tools::capability::catalog::ALL_TOOLS_DIRECT); + tiering + .always_include + .iter() + .map(String::as_str) + .chain(publish_all) + .map(str::to_owned) + .collect() + }, |names| names.iter().cloned().collect(), ) } diff --git a/src/tools/capability/catalog/section_1.rs b/src/tools/capability/catalog/section_1.rs index 9d41bef53..700723822 100644 --- a/src/tools/capability/catalog/section_1.rs +++ b/src/tools/capability/catalog/section_1.rs @@ -243,6 +243,16 @@ impl CatalogSources { } } +/// A `direct_names` member that publishes every tool directly: native tools, +/// MCP, plugin and node aliases. Installed skills stay discoverable through +/// the skill index and `skill_read`. Named members still count on their own, +/// so a surface that defers tools simply leaves this member out. +pub(crate) const ALL_TOOLS_DIRECT: &str = "*"; + +/// Control tools the turn engine adds to a request itself. The publish-all +/// member leaves them out so one name is never declared twice. +const ENGINE_ADDED_TOOLS: [&str; 3] = ["capability_search", "stay_silent", "transcript_history_lookup"]; + /// The entrypoint's publication boundary, applied after registry discovery. #[derive(Clone, Default)] pub(crate) struct SurfacePolicy { @@ -915,7 +925,11 @@ fn entry_from_spec( Exposure::Unavailable { reason: "not available on this surface".to_string(), } - } else if surface.direct_names.contains(&spec.name) { + } else if surface.direct_names.contains(&spec.name) + || (surface.direct_names.contains(ALL_TOOLS_DIRECT) + && !matches!(target, ExecutionTarget::Skill { .. }) + && !ENGINE_ADDED_TOOLS.contains(&spec.name.as_str())) + { Exposure::Direct } else { Exposure::Searchable diff --git a/tests/fixtures/config-schema.json b/tests/fixtures/config-schema.json index 7fcf73376..96b393cc2 100644 --- a/tests/fixtures/config-schema.json +++ b/tests/fixtures/config-schema.json @@ -1 +1 @@ -{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Config","description":"Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).","type":"object","properties":{"a2a":{"description":"Agent-to-Agent compatibility configuration (`[a2a]`).","$ref":"#/$defs/A2aConfig","default":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trusted_trust_domains":[],"trust_domain":"prx.local"}},"agent":{"description":"Agent orchestration settings (`[agent]`).","$ref":"#/$defs/AgentConfig","default":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2,"messaging":{"inbound":true}}},"agents":{"description":"Delegate agent configurations for multi-agent workflows.","type":"object","additionalProperties":{"$ref":"#/$defs/DelegateAgentConfig"},"default":{}},"api_key":{"description":"API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.","type":["string","null"],"default":null},"api_url":{"description":"Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)","type":["string","null"],"default":null},"auth":{"description":"Auth profile and external credential import settings (`[auth]`).","$ref":"#/$defs/AuthConfig","default":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"}},"autonomy":{"description":"Autonomy and security policy configuration (`[autonomy]`).","$ref":"#/$defs/AutonomyConfig","default":{"forbidden_paths":[],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]}}},"browser":{"description":"Browser automation configuration (`[browser]`).","$ref":"#/$defs/BrowserConfig","default":{"allowed_domains":[],"computer_use":{"api_key":null}}},"channels_config":{"description":"Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).","$ref":"#/$defs/ChannelsConfig","default":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null}},"chat":{"description":"Interactive chat UI configuration (`[chat]`).","$ref":"#/$defs/ChatConfig","default":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2}},"compliance":{"description":"Operator-owned compliance controls (`[compliance]`).","$ref":"#/$defs/ComplianceConfig","default":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}},"composio":{"description":"Composio managed OAuth tools integration (`[composio]`).","$ref":"#/$defs/ComposioConfig","default":{"api_key":null,"entity_id":"default"}},"cost":{"description":"Cost tracking and budget enforcement configuration (`[cost]`).","$ref":"#/$defs/CostConfig","default":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{},"warn_at_percent":80}},"cron":{"description":"Cron job configuration (`[cron]`).","$ref":"#/$defs/CronConfig","default":{"max_run_history":50}},"decision_engine":{"description":"Optional advisory decision engine, disabled by default.","$ref":"#/$defs/DecisionEngineConfig","default":{"candidates":5,"enabled":false,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"latency_budget_ms":500,"max_candidates":12,"token_ratio_limit":0.3499999940395355}},"default_model":{"description":"Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.","type":["string","null"]},"default_provider":{"description":"Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.","type":["string","null"]},"default_temperature":{"description":"Default model temperature (0.0–2.0). Default: `0.7`.","type":"number","format":"double","default":0.7},"embedding_routes":{"description":"Embedding routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/EmbeddingRouteConfig"}},"gateway":{"description":"Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).","$ref":"#/$defs/GatewayConfig","default":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60}},"heartbeat":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]`).","$ref":"#/$defs/HeartbeatConfig","default":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."}},"http_request":{"description":"HTTP request tool configuration (`[http_request]`).","$ref":"#/$defs/HttpRequestConfig","default":{"max_response_size":1000000,"timeout_secs":30}},"identity":{"description":"Identity format configuration: OpenClaw or AIEOS (`[identity]`).","$ref":"#/$defs/IdentityConfig","default":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"}},"identity_bindings":{"description":"Static identity bindings loaded at startup (`[[identity_bindings]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/IdentityBindingConfig"}},"mcp":{"description":"Secrets encryption configuration (`[secrets]`).","$ref":"#/$defs/McpConfig","default":{"servers":{}}},"mcp_server":{"description":"MCP server compatibility configuration (`[mcp_server]`).","$ref":"#/$defs/McpServerRuntimeConfig","default":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true}},"media":{"description":"Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.","$ref":"#/$defs/MediaConfig","default":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"}},"memory":{"description":"Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).","$ref":"#/$defs/MemoryConfig","default":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":true,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7}},"model_routes":{"description":"Model routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/ModelRouteConfig"}},"model_settings":{"description":"Catalog model levels and explicit parameters, keyed by canonical release ID.","type":"object","additionalProperties":{"$ref":"#/$defs/ModelSettings"},"default":{}},"multimodal":{"description":"Multimodal (image) handling configuration (`[multimodal]`).","$ref":"#/$defs/MultimodalConfig","default":{"allow_remote_fetch":true,"max_image_size_mb":5,"max_images":4}},"nodes":{"description":"Remote node proxy configuration (`[nodes]`).","$ref":"#/$defs/NodesConfig","default":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":[],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}},"observability":{"description":"Observability backend configuration (`[observability]`).","$ref":"#/$defs/ObservabilityConfig","default":{"backend":"none","otel_endpoint":null,"otel_service_name":null}},"plugins":{"description":"WASM plugin runtime switch (`[plugins]`), off by default.","$ref":"#/$defs/PluginsConfig","default":{"enabled":false}},"providers":{"description":"Provider-specific runtime options (`[providers.]`).","$ref":"#/$defs/ProvidersConfig","default":{"ollama":{"num_ctx":null}}},"proxy":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).","$ref":"#/$defs/ProxyConfig","default":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]}},"query_classification":{"description":"Automatic query classification — maps user messages to model hints.","$ref":"#/$defs/QueryClassificationConfig","default":{"rules":[]}},"reliability":{"description":"Reliability settings: retries, fallback providers, backoff (`[reliability]`).","$ref":"#/$defs/ReliabilityConfig","default":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2}},"router":{"description":"Heuristic LLM router configuration (`[router]`).","$ref":"#/$defs/RouterConfig","default":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]}},"runtime":{"description":"Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.","$ref":"#/$defs/RuntimeConfig","default":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null}},"scheduler":{"description":"Scheduler configuration for periodic task execution (`[scheduler]`).","$ref":"#/$defs/SchedulerConfig","default":{"claim_lease_secs":90,"max_tasks":64}},"secrets":{"$ref":"#/$defs/SecretsConfig","default":{"encrypt":true}},"security":{"description":"Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).","$ref":"#/$defs/SecurityConfig","default":{"audit":{"log_path":"audit.log","max_size_mb":100}}},"self_system":{"description":"Self-system experimental automation controls (`[self_system]`).","$ref":"#/$defs/SelfSystemConfig","default":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24}},"sessions_spawn":{"description":"Session spawning configuration (`[sessions_spawn]`).","$ref":"#/$defs/SessionsSpawnConfig","default":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null}},"skill_rag":{"description":"Dynamic skill retrieval settings (`[skill_rag]`).","$ref":"#/$defs/SkillRagConfig","default":{"top_k":32}},"skills":{"description":"Skills loading and community repository behavior (`[skills]`).","$ref":"#/$defs/SkillsConfig","default":{"open_skills_dir":null,"openclaw_skills_dir":null}},"skills_lifecycle":{"description":"Skill lifecycle (`[skills_lifecycle]`), off by default.","$ref":"#/$defs/SkillsLifecycleConfig","default":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]}},"smart_group":{"description":"Smart group-reply pre-gate configuration (`[smart_group]`).","$ref":"#/$defs/SmartGroupConfig","default":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5}},"storage":{"description":"Persistent storage provider configuration (`[storage]`).","$ref":"#/$defs/StorageConfig","default":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"task_routing":{"description":"Task routing configuration — classifies work by intent before the main agent loop.","$ref":"#/$defs/TaskRoutingConfig","default":{"default_intent":"simple","rules":[]}},"tool_tiering":{"description":"Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).","$ref":"#/$defs/ToolTieringConfig","default":{"always_exclude":[],"always_include":[],"channel_exclude":[]}},"tunnel":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]`).","$ref":"#/$defs/TunnelConfig","default":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null}},"user_policies":{"description":"Static user policy records loaded at startup (`[[user_policies]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/UserPolicyConfig"}},"web_search":{"description":"Web search tool configuration (`[web_search]`).","$ref":"#/$defs/WebSearchConfig","default":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15}},"webhook":{"description":"Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).","$ref":"#/$defs/MemoryWebhookConfig","default":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null}},"xin":{"description":"Xin autonomous task engine configuration (`[xin]`).","$ref":"#/$defs/XinConfig","default":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}}},"$defs":{"A2aConfig":{"type":"object","properties":{"agent_id":{"description":"Stable PRX agent identifier advertised to peers.","type":"string","default":"prx-default"},"allowed_peer_issuers":{"description":"Accepted external peer issuers.","type":"array","default":[],"items":{"type":"string"}},"bind":{"description":"Advertised bind address.","type":"string","default":"127.0.0.1:16832"},"card_jwks_uri":{"description":"Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.","type":["string","null"],"default":null},"card_signing_key_path":{"description":"On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).","type":["string","null"],"default":null},"card_ttl_seconds":{"description":"Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.","type":"integer","format":"uint64","default":3600,"minimum":0},"discovery_advertised":{"description":"Whether to advertise into an external A2A registry.","type":"boolean","default":false},"handoff_nonce_ttl_seconds":{"description":"Replay window for future handoff delegation tokens.","type":"integer","format":"uint64","default":3600,"minimum":0},"messaging_enabled":{"description":"Enable the dedicated pinned mTLS messaging listener.","type":"boolean","default":false},"peers":{"type":"object","additionalProperties":{"$ref":"#/$defs/A2aPeer"},"default":{}},"spiffe_id":{"description":"Local SPIFFE-style identifier placeholder.","type":"string","default":"spiffe://prx-local/agent/prx-default"},"spiffe_strict_validation":{"description":"When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.","type":"boolean","default":false},"spiffe_trust_bundle_pem":{"description":"Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).","type":["string","null"],"default":null},"trusted_trust_domains":{"description":"Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).","type":"array","default":[],"items":{"type":"string"}},"trust_domain":{"description":"SPIFFE trust domain for new instance identities.","type":"string","default":"prx.local"}}},"A2aPeer":{"description":"Explicit pinned identity and local recipient grant.","type":"object","properties":{"spiffe_id":{"type":"string"},"fingerprints":{"type":"array","items":{"type":"string"}},"address":{"type":"string"},"owner":{"type":"string"},"sessions":{"type":"array","default":["*"],"items":{"type":"string"}},"agents":{"type":"array","default":["*"],"items":{"type":"string"}}},"required":["spiffe_id","fingerprints","address","owner"],"additionalProperties":false},"AgentCompactionConfig":{"description":"Agent context compaction configuration (`[agent.compaction]`).","type":"object","properties":{"keep_recent_messages":{"description":"Number of recent non-system messages to keep after compaction.","type":"integer","format":"uint","default":12,"minimum":0},"max_context_tokens":{"description":"Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.","type":"integer","format":"uint","default":128000,"minimum":0},"memory_flush":{"description":"Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.","type":"boolean","default":true},"mode":{"description":"Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).","$ref":"#/$defs/AgentCompactionMode","default":"switch"},"os_paging":{"description":"Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.","$ref":"#/$defs/OsPagingConfig","default":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"}},"reserve_tokens":{"description":"Tokens reserved for the next model response.","type":"integer","format":"uint","default":4096,"minimum":0}}},"AgentCompactionMode":{"description":"Compaction mode for long conversation contexts.","oneOf":[{"description":"Disable proactive compaction.","type":"string","const":"off"},{"description":"Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.","type":"string","const":"switch"},{"description":"Conservative compaction that prefers summary replacement.","type":"string","const":"safeguard"},{"description":"Aggressive truncation mode for tighter contexts.","type":"string","const":"aggressive"}]},"AgentConfig":{"description":"Agent orchestration configuration (`[agent]` section).","type":"object","properties":{"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"compact_context":{"description":"When true: bootstrap_max_chars=6000. Use for 13B or smaller models.","type":"boolean","default":false},"compaction":{"description":"Context compaction controls (`[agent.compaction]`).","$ref":"#/$defs/AgentCompactionConfig","default":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096}},"low_priority_tools":{"description":"Tool names treated as low-priority when `priority_scheduling_enabled = true`.","type":"array","default":["sessions_spawn","delegate"],"items":{"type":"string"}},"priority_scheduling_enabled":{"description":"Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.","type":"boolean","default":false},"read_only_tool_concurrency_window":{"description":"Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.","type":"integer","format":"uint","default":2,"minimum":0},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}}},"AgentLimits":{"description":"Optional admission limits for rf-started turns of a named agent.","type":"object","properties":{"max_concurrent_turns":{"type":["integer","null"],"format":"uint32","minimum":0},"max_cost_per_day_cents":{"type":["integer","null"],"format":"uint64","minimum":0}},"additionalProperties":false},"AuditConfig":{"description":"Audit logging configuration","type":"object","properties":{"log_path":{"description":"Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).","type":"string","default":"audit.log"},"max_size_mb":{"description":"Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).","type":"integer","format":"uint32","default":100,"minimum":0}}},"AuthConfig":{"description":"Authentication and external credential import configuration (`[auth]` section).","type":"object","properties":{"codex_auth_json_auto_import":{"description":"Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.","type":"boolean","default":false},"codex_auth_json_path":{"description":"Source path for Codex CLI auth.json import.","type":"string","default":"~/.codex/auth.json"}}},"AutonomyConfig":{"type":"object","properties":{"acknowledge_unrestricted_profile":{"description":"Operator acknowledgement for an intentionally unrestricted profile.\nRetained for existing configs; it no longer changes any output or policy behavior.","type":"boolean","default":false},"forbidden_paths":{"description":"Explicit path denylist. Default: empty.\n\nApplies below level `full` only; list paths when running `supervised` or `readonly`.","type":"array","default":[],"items":{"type":"string"}},"level":{"description":"Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).","$ref":"#/$defs/AutonomyLevel","default":"full"},"max_cost_per_day_cents":{"description":"Maximum cost per day in cents per policy. Default: unset (no ceiling).","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"scopes":{"description":"Scope-based tool access control: per-user/channel/chat-type allow/deny rules.","$ref":"#/$defs/ScopeConfig","default":{"assign_owners":[],"default":"allow","rules":[]}},"workspace_only":{"description":"Restrict file writes and command paths to the workspace directory. Default: `false`.\n\nApplies below level `full` only; set it when running `supervised` or `readonly`.","type":"boolean","default":false}}},"AutonomyLevel":{"description":"How much autonomy the agent has","oneOf":[{"description":"Read-only: can observe but not act","type":"string","const":"readonly"},{"description":"Supervised: acts but requires approval for risky operations","type":"string","const":"supervised"},{"description":"Full: autonomous execution within policy bounds","type":"string","const":"full"}]},"BackendSelection":{"description":"Which decision backend runs: `auto` (the factory's order) or one kind.","type":"string"},"BrowserComputerUseConfig":{"description":"Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.","type":"object","properties":{"api_key":{"description":"Optional bearer token (retained only for config secret handling).","type":["string","null"],"default":null}}},"BrowserConfig":{"description":"Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.","type":"object","properties":{"allowed_domains":{"description":"Allowed domains for `web_fetch` (exact or subdomain match).","type":"array","default":[],"items":{"type":"string"}},"computer_use":{"description":"Computer-use sidecar config (retained only for `api_key` secret handling).","$ref":"#/$defs/BrowserComputerUseConfig","default":{"api_key":null}}}},"ChannelsConfig":{"description":"Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.","type":"object","properties":{"cli":{"description":"Enable the CLI interactive channel. Default: `true`.","type":"boolean","default":true},"dingtalk":{"description":"DingTalk channel configuration.","anyOf":[{"$ref":"#/$defs/DingTalkConfig"},{"type":"null"}]},"discord":{"description":"Discord bot channel configuration.","anyOf":[{"$ref":"#/$defs/DiscordConfig"},{"type":"null"}]},"email":{"description":"Email channel configuration.","anyOf":[{"$ref":"#/$defs/EmailConfig"},{"type":"null"}]},"imessage":{"description":"iMessage channel configuration (macOS only).","anyOf":[{"$ref":"#/$defs/IMessageConfig"},{"type":"null"}]},"irc":{"description":"IRC channel configuration.","anyOf":[{"$ref":"#/$defs/IrcConfig"},{"type":"null"}]},"lark":{"description":"Lark/Feishu channel configuration.","anyOf":[{"$ref":"#/$defs/LarkConfig"},{"type":"null"}]},"linq":{"description":"Linq Partner API channel configuration.","anyOf":[{"$ref":"#/$defs/LinqConfig"},{"type":"null"}]},"mattermost":{"description":"Mattermost bot channel configuration.","anyOf":[{"$ref":"#/$defs/MattermostConfig"},{"type":"null"}]},"nextcloud_talk":{"description":"Nextcloud Talk bot channel configuration.","anyOf":[{"$ref":"#/$defs/NextcloudTalkConfig"},{"type":"null"}]},"qq":{"description":"QQ Official Bot channel configuration.","anyOf":[{"$ref":"#/$defs/QQConfig"},{"type":"null"}]},"ramflux":{"description":"Local ramflux agent-host bridge.","anyOf":[{"$ref":"#/$defs/RamfluxConfig"},{"type":"null"}],"default":null},"signal":{"description":"Signal channel configuration.","anyOf":[{"$ref":"#/$defs/SignalConfig"},{"type":"null"}]},"slack":{"description":"Slack bot channel configuration.","anyOf":[{"$ref":"#/$defs/SlackConfig"},{"type":"null"}]},"telegram":{"description":"Telegram bot channel configuration.","anyOf":[{"$ref":"#/$defs/TelegramConfig"},{"type":"null"}]},"wacli":{"description":"wacli JSON-RPC daemon channel configuration.","anyOf":[{"$ref":"#/$defs/WacliConfig"},{"type":"null"}],"default":null},"webhook":{"description":"Webhook channel configuration.","anyOf":[{"$ref":"#/$defs/WebhookConfig"},{"type":"null"}]},"whatsapp":{"description":"WhatsApp channel configuration (Cloud API or Web mode).","anyOf":[{"$ref":"#/$defs/WhatsAppConfig"},{"type":"null"}]}}},"ChatConfig":{"description":"Interactive chat configuration (`[chat]`).","type":"object","properties":{"daemon":{"description":"How this chat process reaches the daemon it borrows channels from.","$ref":"#/$defs/ChatDaemonConfig","default":{"token":"","url":""}},"max_concurrent_visible_turns":{"description":"Maximum concurrent visible provider turns in the TUI Redux driver.","type":"integer","format":"uint","default":2,"minimum":0}}},"ChatDaemonConfig":{"description":"Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.","type":"object","properties":{"token":{"description":"Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.","type":"string","default":""},"url":{"description":"Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.","type":"string","default":""}}},"CircuitBreakerConfig":{"description":"The per-backend circuit breaker.","type":"object","properties":{"cooldown_secs":{"description":"Seconds the breaker stays open (1 to 3600).","type":"integer","format":"uint32","default":60,"minimum":0},"failure_threshold":{"description":"Consecutive failures before the breaker opens (1 to 100).","type":"integer","format":"uint32","default":5,"minimum":0}}},"ClassificationRule":{"description":"A single classification rule mapping message patterns to a model hint.","type":"object","properties":{"hint":{"description":"Must match a `[[model_routes]]` hint value.","type":"string"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"max_length":{"description":"Only match if message length <= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"min_length":{"description":"Only match if message length >= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"patterns":{"description":"Case-sensitive literal matches (for \"```\", \"fn \", etc.).","type":"array","default":[],"items":{"type":"string"}},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0}},"required":["hint"]},"CloudflareTunnelConfig":{"type":"object","properties":{"token":{"description":"Cloudflare Tunnel token (from Zero Trust dashboard)","type":"string"}},"required":["token"]},"ComplianceConfig":{"type":"object","properties":{"eu_ai_act":{"$ref":"#/$defs/EuAiActComplianceConfig","default":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null}},"interaction_notice":{"$ref":"#/$defs/InteractionNoticeConfig","default":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}}},"ComposioConfig":{"description":"Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.","type":"object","properties":{"api_key":{"description":"Composio API key (stored encrypted when secrets.encrypt = true)","type":["string","null"],"default":null},"entity_id":{"description":"Default entity ID for multi-user setups","type":"string","default":"default"}}},"CostConfig":{"description":"Cost tracking and budget enforcement configuration (`[cost]` section).","type":"object","properties":{"allow_override":{"description":"Allow requests to exceed budget with --override flag (default: false)","type":"boolean","default":false},"daily_limit_usd":{"description":"Daily spending limit in USD (default: unset, no limit; 0 refuses every priced turn)","type":["number","null"],"format":"double","default":null},"monthly_limit_usd":{"description":"Monthly spending limit in USD (default: unset, no limit)","type":["number","null"],"format":"double","default":null},"prices":{"description":"Per-model pricing (USD per 1M tokens)","type":"object","additionalProperties":{"$ref":"#/$defs/ModelPricing"},"default":{}},"warn_at_percent":{"description":"Warn when spending reaches this percentage of a configured limit (default: 80)","type":"integer","format":"uint8","default":80,"maximum":255,"minimum":0}}},"CredentialRefSetting":{"description":"Which credential a decision backend uses. A reference, never a secret.","type":"string"},"CronConfig":{"description":"Cron job configuration (`[cron]` section).","type":"object","properties":{"max_run_history":{"description":"Maximum number of historical cron run records to retain. Default: `50`.","type":"integer","format":"uint32","default":50,"minimum":0}}},"CustomTunnelConfig":{"type":"object","properties":{"health_url":{"description":"Optional URL to check tunnel health","type":["string","null"]},"start_command":{"description":"Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"","type":"string"},"url_pattern":{"description":"Optional regex to extract public URL from command stdout","type":["string","null"]}},"required":["start_command"]},"DecisionBackendConfig":{"description":"The decision backend (`[decision_engine.backend]`).","type":"object","properties":{"circuit_breaker":{"description":"The circuit breaker.","$ref":"#/$defs/CircuitBreakerConfig","default":{"cooldown_secs":60,"failure_threshold":5}},"credential_ref":{"description":"The credential reference: `\"\"`, `\"none\"` or `cred-`.","$ref":"#/$defs/CredentialRefSetting","default":""},"endpoint":{"description":"The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.","type":"string","default":""},"kind":{"description":"`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).","$ref":"#/$defs/BackendSelection","default":"auto"},"max_request_bytes":{"description":"Largest request body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":65536,"minimum":0},"max_response_bytes":{"description":"Largest response body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":262144,"minimum":0},"model":{"description":"The model the endpoint serves; one exact version for a hosted\nservice.","type":"string","default":""},"pinned_snapshot":{"description":"The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.","type":"string"},"remote_enabled":{"description":"Whether decision state may leave this machine. Default `false`.","type":"boolean","default":false},"timeout_ms":{"description":"Transport timeout (10 ms up to the extra latency budget).","type":"integer","format":"uint32","default":250,"minimum":0}}},"DecisionEngineConfig":{"type":"object","properties":{"backend":{"anyOf":[{"$ref":"#/$defs/DecisionBackendConfig"},{"type":"null"}]},"candidates":{"type":"integer","format":"uint32","default":5,"minimum":0},"enabled":{"type":"boolean","default":false},"mode":{"$ref":"#/$defs/DecisionMode","default":"pre"},"observe_queue":{"type":"integer","format":"uint32","default":64,"minimum":0},"prompt_budget_tokens":{"type":"integer","format":"uint32","default":300,"minimum":0},"telemetry_cap":{"type":"integer","format":"uint32","default":1000,"minimum":0},"timeout_ms":{"type":"integer","format":"uint32","default":1500,"minimum":0},"latency_budget_ms":{"description":"The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.","type":"integer","format":"uint64","default":500,"minimum":0},"token_ratio_limit":{"description":"Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).","type":"number","format":"float","default":0.3499999940395355},"max_candidates":{"description":"The most candidates a turn considers (1 to 32).","type":"integer","format":"uint8","default":12,"maximum":255,"minimum":0}}},"DecisionMode":{"type":"string","enum":["pre","post","both"]},"DeclarationOfConformityConfig":{"type":"object","properties":{"applicable_union_law":{"type":"array","default":[],"items":{"type":"string"}},"artifact_path":{"type":["string","null"],"default":null},"artifact_version":{"type":["string","null"],"default":null},"conformity_assessment_procedure":{"type":["string","null"],"default":null},"conformity_statement":{"type":["string","null"],"default":null},"harmonised_standards":{"type":"array","default":[],"items":{"type":"string"}},"issue_date":{"type":["string","null"],"default":null},"issue_place":{"type":["string","null"],"default":null},"notified_body_certificate":{"type":["string","null"],"default":null},"notified_body_identification_number":{"type":["string","null"],"default":null},"notified_body_name":{"type":["string","null"],"default":null},"personal_data_compliance_statement":{"type":["string","null"],"default":null},"processes_personal_data":{"type":"boolean","default":false},"provider_address":{"type":["string","null"],"default":null},"provider_name":{"type":["string","null"],"default":null},"signer_function":{"type":["string","null"],"default":null},"signer_name":{"type":["string","null"],"default":null},"signer_on_behalf_of":{"type":["string","null"],"default":null},"sole_responsibility_statement":{"type":["string","null"],"default":null},"standards_not_applicable_reason":{"type":["string","null"],"default":null},"system_name":{"type":["string","null"],"default":null},"system_reference":{"type":["string","null"],"default":null},"system_type":{"type":["string","null"],"default":null}}},"DelegateAgentConfig":{"description":"Configuration for a delegate sub-agent used by the `delegate` tool.","type":"object","properties":{"agentic":{"description":"Agentic sub-agent mode (multi-turn tool-call loop). Default true; an\nexplicit `false` makes the agent answer-only with no tools.","type":"boolean","default":true},"allowed_tools":{"description":"Allowlist of tool names available to the sub-agent in agentic mode.\nEmpty or omitted means all tools, the same as `[\"*\"]`.","type":"array","default":[],"items":{"type":"string"}},"api_key":{"description":"Optional API key override","type":["string","null"],"default":null},"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"autonomy":{"description":"The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.","anyOf":[{"$ref":"#/$defs/AutonomyLevel"},{"type":"null"}]},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"enabled":{"description":"Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.","type":"boolean","default":true},"identity_dir":{"description":"Optional identity files directory relative to workspace root.","type":["string","null"],"default":null},"limits":{"$ref":"#/$defs/AgentLimits","default":{"max_concurrent_turns":null,"max_cost_per_day_cents":null}},"max_depth":{"description":"Max recursion depth for nested delegation","type":"integer","format":"uint32","default":8,"minimum":0},"memory_scope":{"description":"Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".","type":["string","null"],"default":null},"model":{"description":"Model name","type":"string"},"provider":{"description":"Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")","type":"string"},"spawn_enabled":{"description":"Whether this agent is allowed to be targeted by sessions_spawn (default: true).","type":["boolean","null"],"default":null},"system_prompt":{"description":"Optional system prompt for the sub-agent","type":["string","null"],"default":null},"temperature":{"description":"Temperature override","type":["number","null"],"format":"double","default":null},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}},"required":["provider","model"]},"DingTalkConfig":{"description":"DingTalk configuration for Stream Mode messaging","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"client_id":{"description":"Client ID (AppKey) from DingTalk developer console","type":"string"},"client_secret":{"description":"Client Secret (AppSecret) from DingTalk developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["client_id","client_secret"]},"DiscordConfig":{"description":"Discord bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Discord user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Discord bot token (from Discord Developer Portal).","type":"string"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"guild_id":{"description":"Optional guild (server) ID to restrict the bot to a single guild.","type":["string","null"]},"listen_to_bots":{"description":"When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.","type":"boolean","default":false}},"required":["bot_token"]},"DmPolicy":{"description":"Policy for direct-message handling.","oneOf":[{"description":"Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).","type":"string","const":"pairing"},{"description":"Accept only senders listed in `allowed_from`.","type":"string","const":"allowlist"},{"description":"Accept any direct sender.","type":"string","const":"open"},{"description":"Ignore direct messages.","type":"string","const":"disabled"}]},"DockerRuntimeConfig":{"description":"Docker runtime configuration (`[runtime.docker]` section).","type":"object","properties":{"allowed_workspace_roots":{"description":"Optional workspace root allowlist for Docker mount validation.","type":"array","default":[],"items":{"type":"string"}},"cpu_limit":{"description":"Optional CPU limit (`None` = no explicit limit).","type":["number","null"],"format":"double","default":1.0},"image":{"description":"Runtime image used to execute shell commands.","type":"string","default":"alpine:3.20"},"memory_limit_mb":{"description":"Optional memory limit in MB (`None` = no explicit limit).","type":["integer","null"],"format":"uint64","default":512,"minimum":0},"mount_workspace":{"description":"Mount configured workspace into `/workspace`.","type":"boolean","default":true},"network":{"description":"Docker network mode (`none`, `bridge`, etc.).","type":"string","default":"none"},"read_only_rootfs":{"description":"Mount root filesystem as read-only.","type":"boolean","default":true}}},"EmailConfig":{"description":"Email channel configuration","type":"object","properties":{"allowed_senders":{"description":"Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)","type":"array","default":[],"items":{"type":"string"}},"from_address":{"description":"From address for outgoing emails","type":"string"},"idle_timeout_secs":{"description":"IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes","type":"integer","format":"uint64","default":1740,"minimum":0},"imap_folder":{"description":"IMAP folder to poll (default: INBOX)","type":"string","default":"INBOX"},"imap_host":{"description":"IMAP server hostname","type":"string"},"imap_port":{"description":"IMAP server port (default: 993 for TLS)","type":"integer","format":"uint16","default":993,"maximum":65535,"minimum":0},"password":{"description":"Email password for authentication","type":"string"},"smtp_host":{"description":"SMTP server hostname","type":"string"},"smtp_port":{"description":"SMTP server port (default: 465 for TLS)","type":"integer","format":"uint16","default":465,"maximum":65535,"minimum":0},"smtp_tls":{"description":"Use TLS for SMTP (default: true)","type":"boolean","default":true},"username":{"description":"Email username for authentication","type":"string"}},"required":["imap_host","smtp_host","username","password","from_address"]},"EmbeddingRouteConfig":{"description":"Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"dimensions":{"description":"Optional embedding dimension override for this route","type":["integer","null"],"format":"uint","default":null,"minimum":0},"hint":{"description":"Route hint name (e.g. \"semantic\", \"archive\", \"faq\")","type":"string"},"model":{"description":"Embedding model to use with that provider","type":"string"},"provider":{"description":"Embedding provider (`none`, `openai`, or `custom:`)","type":"string"}},"required":["hint","provider","model"]},"EuAiActClassificationConfig":{"type":"object","properties":{"assessed_at":{"type":["string","null"],"default":null},"owner":{"type":["string","null"],"default":null},"status":{"$ref":"#/$defs/EuAiActRiskClassification","default":"unclassified"}}},"EuAiActComplianceConfig":{"type":"object","properties":{"classification":{"$ref":"#/$defs/EuAiActClassificationConfig","default":{"assessed_at":null,"owner":null,"status":"unclassified"}},"declaration":{"$ref":"#/$defs/DeclarationOfConformityConfig","default":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null}},"incident_store_path":{"type":["string","null"],"default":null}}},"EuAiActRiskClassification":{"type":"string","enum":["unclassified","high_risk","not_high_risk"]},"FitnessConfig":{"description":"Calendar schedule, evidence thresholds, and retention for fitness v2.","type":"object","properties":{"auto_run":{"description":"Run the daily fitness worker in daemon mode.","type":"boolean","default":true},"max_backfill_days":{"description":"Maximum number of closed days recovered after downtime.","type":"integer","format":"uint32","default":7,"minimum":0},"min_coverage":{"description":"Minimum available metric weight required to publish a final score.","type":"number","format":"double","default":0.6},"min_samples":{"description":"Minimum samples required before an evidence-derived subscore is usable.","type":"integer","format":"uint","default":5,"minimum":0},"retention_days":{"description":"Number of daily JSON reports retained on disk.","type":"integer","format":"uint32","default":180,"minimum":0},"run_at":{"description":"Local wall-clock time (`HH:MM`) at which the previous day is scored.","type":"string","default":"00:10"},"timezone":{"description":"IANA timezone used to define closed calendar days.","type":"string","default":"UTC"}}},"GatewayConfig":{"description":"Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.","type":"object","properties":{"allow_public_bind":{"description":"Allow binding to non-localhost without a tunnel (default: false)","type":"boolean","default":false},"api_rate_limit_per_minute":{"description":"Max `/api/*` requests per minute per authenticated token.","type":"integer","format":"uint32","default":60,"minimum":0},"channel_webhook_dedup_ttl_secs":{"description":"How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.","type":"integer","format":"uint64","default":86400,"minimum":0},"host":{"description":"Gateway host (default: 127.0.0.1)","type":"string","default":"127.0.0.1"},"idempotency_max_keys":{"description":"Maximum distinct idempotency keys retained in memory.","type":"integer","format":"uint","default":10000,"minimum":0},"idempotency_ttl_secs":{"description":"TTL for webhook idempotency keys.","type":"integer","format":"uint64","default":300,"minimum":0},"pair_rate_limit_per_minute":{"description":"Max `/pair` requests per minute per client key.","type":"integer","format":"uint32","default":10,"minimum":0},"paired_tokens":{"description":"Paired bearer tokens (managed automatically, not user-edited)","type":"array","default":[],"items":{"type":"string"}},"port":{"description":"Gateway port (default: 16830)","type":"integer","format":"uint16","default":16830,"maximum":65535,"minimum":0},"rate_limit_max_keys":{"description":"Maximum distinct client keys tracked by gateway rate limiter maps.","type":"integer","format":"uint","default":10000,"minimum":0},"require_pairing":{"description":"Require pairing before accepting requests (default: true)","type":"boolean","default":true},"targeted_agents":{"description":"Switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). Default true. While false, any\notherwise-valid named target answers 409 `agent_disabled` and never\nruns as Main.","type":"boolean","default":true},"trust_forwarded_headers":{"description":"Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.","type":"boolean","default":false},"webhook_rate_limit_per_minute":{"description":"Max `/webhook` requests per minute per client key.","type":"integer","format":"uint32","default":60,"minimum":0}}},"GroupPolicy":{"description":"Policy for group-message handling.","oneOf":[{"description":"Accept only groups listed in `group_allow_from`.","type":"string","const":"allowlist"},{"description":"Accept any group.","type":"string","const":"open"},{"description":"Ignore group messages.","type":"string","const":"disabled"}]},"GroupReplyMode":{"description":"How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.","oneOf":[{"description":"Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).","type":"string","const":"off"},{"description":"Reply only when the bot is @-mentioned (legacy `mention_only = true`).","type":"string","const":"mention-only"},{"description":"Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).","type":"string","const":"smart"}]},"HeartbeatConfig":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]` section).","type":"object","properties":{"active_hours":{"description":"Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.","type":"array","default":[8,23],"items":{"type":"integer","format":"uint8","maximum":255,"minimum":0}},"interval_minutes":{"description":"Interval in minutes between heartbeat pings. Default: `30`.","type":"integer","format":"uint32","default":30,"minimum":0},"prompt":{"description":"Prompt used by heartbeat worker when dispatching tasks.","type":"string","default":"Check HEARTBEAT.md and follow instructions."}}},"HttpRequestConfig":{"description":"HTTP request tool configuration (`[http_request]` section).","type":"object","properties":{"max_response_size":{"description":"Maximum response size in bytes (default: 1MB)","type":"integer","format":"uint","default":1000000,"minimum":0},"timeout_secs":{"description":"Request timeout in seconds (default: 30)","type":"integer","format":"uint64","default":30,"minimum":0}}},"IMessageConfig":{"description":"iMessage channel configuration (macOS only).","type":"object","properties":{"allowed_contacts":{"description":"Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.","type":"array","items":{"type":"string"}},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["allowed_contacts"]},"IdentityBindingConfig":{"description":"Startup identity binding entry (`[[identity_bindings]]`).","type":"object","properties":{"channel":{"type":"string"},"channel_account":{"type":"string"},"display_name":{"type":["string","null"],"default":null},"user_id":{"type":"string"}},"required":["user_id","channel","channel_account"]},"IdentityConfig":{"description":"Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.","type":"object","properties":{"aieos_inline":{"description":"Inline AIEOS JSON (alternative to file path)","type":["string","null"],"default":null},"aieos_path":{"description":"Path to AIEOS JSON file (relative to workspace)","type":["string","null"],"default":null},"format":{"description":"Identity format: \"openclaw\" (default) or \"aieos\"","type":"string","default":"openclaw"}}},"InteractionNoticeApplicability":{"type":"string","enum":["required","not_applicable"]},"InteractionNoticeConfig":{"type":"object","properties":{"applicability":{"$ref":"#/$defs/InteractionNoticeApplicability","default":"required"},"exception_owner":{"type":["string","null"],"default":null},"exception_reviewed_at":{"type":["string","null"],"default":null},"text":{"type":"string","default":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers."},"version":{"type":"string","default":"1"}}},"IrcConfig":{"description":"IRC channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed nicknames (case-insensitive) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"channels":{"description":"Channels to join on connect","type":"array","default":[],"items":{"type":"string"}},"mention_only":{"description":"When true, only process channel/group messages that mention the bot.","type":"boolean","default":false},"nickname":{"description":"Bot nickname","type":"string"},"nickserv_password":{"description":"NickServ IDENTIFY password","type":["string","null"]},"port":{"description":"IRC server port (default: 6697 for TLS)","type":"integer","format":"uint16","default":6697,"maximum":65535,"minimum":0},"sasl_password":{"description":"SASL PLAIN password (IRCv3)","type":["string","null"]},"server":{"description":"IRC server hostname","type":"string"},"server_password":{"description":"Server password (for bouncers like ZNC)","type":["string","null"]},"username":{"description":"Username (defaults to nickname if not set)","type":["string","null"]},"verify_tls":{"description":"Verify TLS certificate (default: true)","type":["boolean","null"]}},"required":["server","nickname"]},"LarkConfig":{"description":"Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from Lark/Feishu developer console","type":"string"},"app_secret":{"description":"App Secret from Lark/Feishu developer console","type":"string"},"encrypt_key":{"description":"Encrypt key for webhook message decryption (optional)","type":["string","null"],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"port":{"description":"HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"receive_mode":{"description":"Event receive mode: \"websocket\" (default) or \"webhook\"","$ref":"#/$defs/LarkReceiveMode","default":"websocket"},"use_feishu":{"description":"Whether to use the Feishu (Chinese) endpoint instead of Lark (International)","type":"boolean","default":false},"verification_token":{"description":"Verification token for webhook validation (optional)","type":["string","null"],"default":null}},"required":["app_id","app_secret"]},"LarkReceiveMode":{"description":"How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.","type":"string","enum":["websocket","webhook"]},"LinqConfig":{"type":"object","properties":{"allowed_senders":{"description":"Allowed sender handles (phone numbers) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"api_token":{"description":"Linq Partner API token (Bearer auth)","type":"string"},"from_phone":{"description":"Phone number to send from (E.164 format)","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"signing_secret":{"description":"Webhook signing secret for signature verification","type":["string","null"],"default":null}},"required":["api_token","from_phone"]},"MattermostConfig":{"description":"Mattermost bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Mattermost user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Mattermost bot access token.","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.","type":["boolean","null"],"default":null},"thread_replies":{"description":"When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.","type":["boolean","null"],"default":null},"url":{"description":"Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).","type":"string"}},"required":["url","bot_token"]},"McpConfig":{"type":"object","properties":{"servers":{"description":"Named MCP server definitions","type":"object","additionalProperties":{"$ref":"#/$defs/McpServerConfig"},"default":{}},"workspace_servers":{"description":"Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.","$ref":"#/$defs/WorkspaceMcpServers"}}},"McpServerConfig":{"type":"object","properties":{"allow_tools":{"description":"Optional allow-list of exposed tools (empty = all)","type":"array","default":[],"items":{"type":"string"}},"args":{"description":"Command args for stdio mode","type":"array","default":[],"items":{"type":"string"}},"command":{"description":"Command for stdio mode","type":["string","null"],"default":null},"deny_tools":{"description":"Optional deny-list of exposed tools","type":"array","default":[],"items":{"type":"string"}},"env":{"description":"Environment variables for stdio mode","type":"object","additionalProperties":{"type":"string"},"default":{}},"request_timeout_ms":{"description":"Request timeout in milliseconds","type":"integer","format":"uint64","default":30000,"minimum":0},"startup_timeout_ms":{"description":"Startup timeout in milliseconds","type":"integer","format":"uint64","default":10000,"minimum":0},"tool_name_prefix":{"description":"Prefix used in tool naming and routing","type":"string","default":"mcp"},"transport":{"description":"Transport type: stdio or http","$ref":"#/$defs/McpTransport","default":"stdio"},"url":{"description":"URL for HTTP mode (streamable HTTP endpoint)","type":["string","null"],"default":null},"working_dir":{"description":"Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).","type":["string","null"]}}},"McpServerRuntimeConfig":{"type":"object","properties":{"allowed_origins":{"description":"Allowed browser origins for future streamable HTTP clients.","type":"array","default":["claude.ai","openai.com","localhost"],"items":{"type":"string"}},"bind":{"description":"Advertised bind address. The gateway may still be started with a CLI port override.","type":"string","default":"127.0.0.1:16831"},"exposed_tools":{"description":"Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.","type":"array","default":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"items":{"type":"string"}},"jwt_algorithms":{"description":"Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.","type":"array","default":["RS256"],"items":{"type":"string"}},"jwt_audience":{"description":"Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.","type":["string","null"],"default":null},"jwt_issuer":{"description":"Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.","type":["string","null"],"default":null},"jwt_jwks":{"description":"Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.","type":["string","null"],"default":null},"jwt_jwks_cache_ttl_secs":{"description":"Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.","type":"integer","format":"uint64","default":300,"minimum":0},"jwt_jwks_uri":{"description":"Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.","type":["string","null"],"default":null},"jwt_public_key_pem":{"description":"PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.","type":["string","null"],"default":null},"rate_limit_rps":{"description":"Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.","type":"integer","format":"uint32","default":10,"minimum":0},"require_auth":{"description":"Require an authenticated external identity for mutating calls.","type":"boolean","default":true}}},"McpTransport":{"type":"string","enum":["stdio","http"]},"MediaConfig":{"description":"Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.","type":"object","properties":{"audio_model":{"description":"Audio model name (Ollama model or OpenAI model). Default: \"whisper\".","type":"string","default":"whisper"},"audio_ollama_url":{"description":"Ollama base URL for audio transcription. Default: \"http://localhost:11434\".","type":"string","default":"http://localhost:11434"},"audio_provider":{"description":"Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".","type":"string","default":"none"},"max_audio_size_mb":{"description":"Maximum audio attachment size in MiB. Default: 20.","type":"integer","format":"uint","default":20,"minimum":0},"max_video_size_mb":{"description":"Maximum video attachment size in MiB. Default: 50.","type":"integer","format":"uint","default":50,"minimum":0},"video_max_frames":{"description":"Maximum video frames to extract per video. Default: 4.","type":"integer","format":"uint","default":4,"minimum":0},"video_provider":{"description":"Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".","type":"string","default":"none"}}},"MemoryConfig":{"description":"Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.","type":"object","properties":{"acl_enabled":{"description":"Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.","type":"boolean","default":false},"archive_after_days":{"description":"Archive daily/session files older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"auto_hydrate":{"description":"Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing","type":"boolean","default":true},"auto_save":{"description":"Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.","type":"boolean","default":true},"backend":{"description":"\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).","type":"string","default":"sqlite"},"conversation_retention_days":{"description":"For sqlite backend: prune conversation rows older than this many days","type":"integer","format":"uint32","default":3,"minimum":0},"daily_retention_days":{"description":"For sqlite backend: prune daily rows older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"embedding_cache_size":{"description":"Max embedding cache entries before LRU eviction","type":"integer","format":"uint","default":10000,"minimum":0},"embedding_dimensions":{"description":"Embedding vector dimensions","type":"integer","format":"uint","default":384,"minimum":0},"embedding_model":{"description":"Embedding model name (e.g. \"text-embedding-3-small\")","type":"string","default":"prx-local-hash-v1"},"embedding_provider":{"description":"Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"","type":"string","default":"local"},"events":{"description":"Raw/quasi-raw message event recording controls (`[memory.events]`).","$ref":"#/$defs/MemoryEventsConfig","default":{"record_assistant_messages":true,"record_tool_events":true,"record_user_messages":true}},"keyword_weight":{"description":"Weight for keyword BM25 in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.3},"legacy_conversation_turns_visible":{"description":"Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.","type":"boolean","default":true},"lucid_budget":{"description":"Token budget for lucid (replaces OPENPRX_LUCID_BUDGET)","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"lucid_cmd":{"description":"Path to lucid binary (replaces OPENPRX_LUCID_CMD)","type":["string","null"],"default":null},"lucid_failure_cooldown_ms":{"description":"Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)","type":"integer","format":"uint64","default":60000,"minimum":0},"lucid_local_hit_threshold":{"description":"Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)","type":"integer","format":"uint","default":3,"minimum":0},"lucid_recall_timeout_ms":{"description":"Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)","type":"integer","format":"uint64","default":5000,"minimum":0},"lucid_store_timeout_ms":{"description":"Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)","type":"integer","format":"uint64","default":3000,"minimum":0},"min_relevance_score":{"description":"Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4","type":"number","format":"double","default":0.4},"purge_after_days":{"description":"Purge archived files older than this many days","type":"integer","format":"uint32","default":30,"minimum":0},"semantic":{"description":"Semantic memory promotion controls (`[memory.semantic]`).","$ref":"#/$defs/MemorySemanticConfig","default":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30}},"sqlite_open_timeout_secs":{"description":"For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"sqlite_read_pool_size":{"description":"For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"vector_candidate_cap":{"description":"How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.","type":"integer","format":"uint","default":2000,"minimum":0},"vector_weight":{"description":"Weight for vector similarity in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.7}}},"MemoryEventsConfig":{"description":"Raw message event recording configuration (`[memory.events]`).","type":"object","properties":{"record_assistant_messages":{"description":"Record assistant replies.","type":"boolean","default":true},"record_tool_events":{"description":"Record tool calls and tool results in the durable message log.","type":"boolean","default":true},"record_user_messages":{"description":"Record inbound/user messages.","type":"boolean","default":true}}},"MemorySemanticConfig":{"description":"Semantic memory promotion configuration (`[memory.semantic]`).","type":"object","properties":{"auto_promote_assistant_messages":{"description":"Auto-promote eligible assistant messages. Disabled by default to reduce noise.","type":"boolean","default":false},"auto_promote_user_messages":{"description":"Auto-promote eligible user messages into long-term semantic memories.","type":"boolean","default":true},"min_chars":{"description":"Minimum content length for semantic auto-promotion.","type":"integer","format":"uint","default":30,"minimum":0}}},"MemoryWebhookConfig":{"type":"object","properties":{"bind":{"description":"Socket address for the receiver (e.g. \"0.0.0.0:16899\").","type":"string","default":"0.0.0.0:16899"},"signing_secret":{"description":"Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.","type":["string","null"],"default":null},"token":{"description":"Required bearer token for incoming webhook events.","type":["string","null"],"default":null}}},"ModelOperationSetting":{"description":"The operations a `[[providers.models]]` entry may list.","type":"string","enum":["chat","embedding","decision_endpoint","rerank","image_generation","audio_generation","video_generation"]},"ModelPricing":{"description":"Per-model pricing entry (USD per 1M tokens).","type":"object","properties":{"cache_read":{"description":"Cache read input price per 1M tokens.","type":"number","format":"double","default":0.0},"cache_write":{"description":"Cache write/creation input price per 1M tokens.","type":"number","format":"double","default":0.0},"input":{"description":"Input price per 1M tokens","type":"number","format":"double","default":0.0},"output":{"description":"Output price per 1M tokens","type":"number","format":"double","default":0.0}}},"ModelRouteConfig":{"description":"Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"hint":{"description":"Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")","type":"string"},"level":{"type":["string","null"]},"model":{"description":"Model to use with that provider","type":"string"},"provider":{"description":"Provider to route to (must match a known provider name)","type":"string"},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true,"required":["hint","provider","model"]},"ModelSettings":{"description":"A model level plus explicit parameter overrides in `[model_settings.\"\"]`.","type":"object","properties":{"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"level":{"type":["string","null"]},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true},"MultimodalConfig":{"description":"Multimodal (image) handling configuration (`[multimodal]` section).","type":"object","properties":{"allow_remote_fetch":{"description":"Allow fetching remote image URLs (http/https). Enabled by default.","type":"boolean","default":true},"max_image_size_mb":{"description":"Maximum image payload size in MiB before base64 encoding.","type":"integer","format":"uint","default":5,"minimum":0},"max_images":{"description":"Maximum number of image attachments accepted per request.","type":"integer","format":"uint","default":4,"minimum":0}}},"NextcloudTalkConfig":{"description":"Nextcloud Talk bot configuration (webhook receive + OCS send API).","type":"object","properties":{"allowed_users":{"description":"Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Bot app token used for OCS API bearer auth.","type":"string"},"base_url":{"description":"Nextcloud base URL (e.g. \"https://cloud.example.com\").","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"webhook_secret":{"description":"Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).","type":["string","null"],"default":null}},"required":["base_url","app_token"]},"NgrokTunnelConfig":{"type":"object","properties":{"auth_token":{"description":"ngrok auth token","type":"string"},"domain":{"description":"Optional custom domain","type":["string","null"]}},"required":["auth_token"]},"NodeServerConfig":{"description":"Node daemon runtime config used by `prx-node`.","type":"object","properties":{"allowed_commands":{"description":"Command allowlist matched on first token. Default: empty, which allows any\ncommand from an authenticated caller; `[\"*\"]` means the same.","type":"array","default":[],"items":{"type":"string"}},"bearer_token":{"description":"Required bearer token for /rpc.","type":"string","default":""},"blocked_commands":{"description":"Command denylist matched on first token. Always enforced.","type":"array","default":[],"items":{"type":"string"}},"exec_timeout_ms":{"description":"Default command timeout in milliseconds.","type":"integer","format":"uint64","default":15000,"minimum":0},"hmac_secret":{"description":"Optional HMAC signing secret.","type":["string","null"],"default":null},"listen_addr":{"description":"Listen address for node daemon.","type":"string","default":"127.0.0.1:8787"},"max_concurrent_tasks":{"description":"Maximum number of concurrent async command tasks.","type":"integer","format":"uint","default":8,"minimum":0},"max_output_bytes":{"description":"Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.","type":"integer","format":"uint","default":1048576,"minimum":0},"sandbox_root":{"description":"Sandbox root directory for read/write/cwd constraints.","type":"string","default":"."},"task_result_ttl_ms":{"description":"TTL for completed task results in milliseconds.","type":"integer","format":"uint64","default":3600000,"minimum":0},"tls_cert":{"description":"TLS certificate path (PEM).","type":["string","null"],"default":null},"tls_key":{"description":"TLS private key path (PEM).","type":["string","null"],"default":null},"tls_required":{"description":"Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.","type":"boolean","default":true}}},"NodesConfig":{"description":"Remote node proxy configuration for core-side RPC calls and node daemon defaults.","type":"object","properties":{"nodes":{"description":"Configured remote nodes.","type":"array","default":[],"items":{"$ref":"#/$defs/RemoteNodeConfig"}},"request_timeout_ms":{"description":"Default request timeout for node RPC calls.","type":"integer","format":"uint64","default":15000,"minimum":0},"retry_max":{"description":"Default max retries for node RPC calls.","type":"integer","format":"uint8","default":2,"maximum":255,"minimum":0},"server":{"description":"Embedded node server defaults used by `prx-node`.","$ref":"#/$defs/NodeServerConfig","default":{"allowed_commands":[],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}}},"ObservabilityConfig":{"description":"Observability backend configuration (`[observability]` section).","type":"object","properties":{"backend":{"description":"\"none\" | \"log\" | \"prometheus\" | \"otel\"","type":"string","default":"none"},"otel_endpoint":{"description":"OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".","type":["string","null"],"default":null},"otel_service_name":{"description":"Service name reported to the OTel collector. Defaults to \"prx\".","type":["string","null"],"default":null}}},"OllamaProviderConfig":{"description":"Ollama-specific request options (`[providers.ollama]`).","type":"object","properties":{"num_ctx":{"description":"Explicit context window sent as Ollama `options.num_ctx`.","type":["integer","null"],"format":"uint","default":null,"minimum":0}}},"OsPagingConfig":{"description":"Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.","type":"object","properties":{"eviction_threshold":{"description":"Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.","type":"number","format":"double","default":0.7},"keep_recent_messages":{"description":"Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).","type":"integer","format":"uint","default":12,"minimum":0},"max_recalled_pages":{"description":"Maximum number of evicted pages (document chunks) recalled per turn.","type":"integer","format":"uint","default":10,"minimum":0},"proactive_retrieval":{"description":"Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.","type":"boolean","default":true},"retrieval_injection_role":{"description":"Role under which recalled pages are injected.","$ref":"#/$defs/RetrievalInjectionRole","default":"system"}}},"PluginsConfig":{"description":"WASM plugin runtime configuration.","type":"object","properties":{"enabled":{"description":"Load WASM plugins from `/plugins`. Default: `false`.","type":"boolean","default":false}},"additionalProperties":false},"ProviderModelConfig":{"description":"One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.","type":"object","properties":{"context_window":{"description":"The model's context window in tokens.","type":["integer","null"],"format":"uint32","minimum":0},"model":{"description":"The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.","type":["string","null"]},"native_tools":{"description":"Whether the model accepts native tool calls.","type":["boolean","null"]},"operations":{"description":"The complete list of operations the model executes; every operation not\nlisted is unsupported.","type":["array","null"],"items":{"$ref":"#/$defs/ModelOperationSetting"}},"provider":{"description":"The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.","type":"string"},"streaming":{"description":"Whether the model streams responses.","type":["boolean","null"]},"structured_output":{"description":"Whether the model honours a JSON-schema response format.","type":["boolean","null"]},"tool_call_dialect":{"description":"The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema_dialect":{"description":"The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]},"vision_input":{"description":"Whether the model accepts image input.","type":["boolean","null"]}},"required":["provider"]},"ProviderToolDialectConfig":{"description":"One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.","type":"object","properties":{"model":{"description":"The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.","type":["string","null"]},"provider":{"description":"The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.","type":"string"},"tool_call":{"description":"The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema":{"description":"The tool-schema dialect the endpoint accepts.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]}},"required":["provider"]},"ProvidersConfig":{"description":"Provider-specific runtime configuration (`[providers]`).","type":"object","properties":{"models":{"description":"Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.","type":"array","items":{"$ref":"#/$defs/ProviderModelConfig"}},"ollama":{"description":"Ollama-specific request options (`[providers.ollama]`).","$ref":"#/$defs/OllamaProviderConfig","default":{"num_ctx":null}},"tool_dialects":{"description":"Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).","type":"array","items":{"$ref":"#/$defs/ProviderToolDialectConfig"}}}},"ProxyConfig":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).","type":"object","properties":{"all_proxy":{"description":"Fallback proxy URL for all schemes.","type":["string","null"],"default":null},"http_proxy":{"description":"Proxy URL for HTTP requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"https_proxy":{"description":"Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"no_proxy":{"description":"No-proxy bypass list. Same format as NO_PROXY.","type":"array","default":[],"items":{"type":"string"}},"scope":{"description":"Proxy application scope.","$ref":"#/$defs/ProxyScope","default":"prx"},"services":{"description":"Service selectors used when scope = \"services\".","type":"array","default":[],"items":{"type":"string"}}}},"ProxyScope":{"description":"Proxy application scope — determines which outbound traffic uses the proxy.","oneOf":[{"description":"Use system environment proxy variables only.","type":"string","const":"environment"},{"description":"Apply proxy to all OpenPRX-managed HTTP traffic (default).","type":"string","const":"prx"},{"description":"Apply proxy only to explicitly listed service selectors.","type":"string","const":"services"}]},"QQConfig":{"description":"QQ Official Bot configuration (Tencent QQ Bot SDK)","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs. Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from QQ Bot developer console","type":"string"},"app_secret":{"description":"App Secret from QQ Bot developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["app_id","app_secret"]},"QueryClassificationConfig":{"description":"Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.","type":"object","properties":{"rules":{"description":"Classification rules evaluated in priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/ClassificationRule"}}}},"RamfluxAccountConfig":{"description":"Persona for one ramflux AI account. Missing fields fall back to the global agent.","type":"object","properties":{"cross_conversation_retrieval":{"description":"Cross-conversation memory retrieval. Off unless the owner sets it.","type":"boolean","default":false},"model":{"type":["string","null"],"default":null},"provider":{"type":["string","null"],"default":null},"scope_profile":{"type":["string","null"],"default":null},"system_prompt_file":{"description":"Path to a system-prompt file. Relative paths are resolved from the workspace.","type":["string","null"],"default":null}},"additionalProperties":false},"RamfluxAttachmentFetch":{"description":"Per-turn caps for `attachment.fetch`.","type":"object","properties":{"max_bytes":{"type":"integer","format":"uint64","default":5242880,"minimum":0},"max_per_turn":{"type":"integer","format":"uint8","default":4,"maximum":255,"minimum":0}},"additionalProperties":false},"RamfluxAuthorizationMode":{"description":"How prx combines its own setting with `bridge.hello.authorization`.","oneOf":[{"description":"Use the agent-host value. Until hello arrives, the effective mode is supervised.","type":"string","const":"follow_rf"},{"description":"Always supervised, even when the agent-host declares full.","type":"string","const":"supervised"},{"description":"Full only when the agent-host also declares full. Config alone never yields full.","type":"string","const":"full"}]},"RamfluxConfig":{"description":"Local ramflux agent-host bridge (`[channels_config.ramflux]`).","type":"object","properties":{"accounts":{"type":"object","additionalProperties":{"$ref":"#/$defs/RamfluxAccountConfig"},"default":{}},"allowed_block_types":{"type":"array","default":["Text","Markdown","Heading","KeyValue","Metric","List","TableFallback","Form","Input","Select","Progress","LogStream","Warning","Error","Success","Approval","ActionGroup","FilePreview","Fallback"],"items":{"type":"string"}},"attachment_fetch":{"$ref":"#/$defs/RamfluxAttachmentFetch","default":{"max_bytes":5242880,"max_per_turn":4}},"authorization_mode":{"$ref":"#/$defs/RamfluxAuthorizationMode","default":"follow_rf"},"encrypt_at_rest":{"type":"boolean","default":true},"max_in_flight_per_conversation":{"type":"integer","format":"uint8","default":1,"maximum":255,"minimum":0},"on_new_message":{"$ref":"#/$defs/RamfluxOnNewMessage","default":"queue"},"socket_path":{"description":"Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.","type":["string","null"],"default":null},"surface_limits":{"$ref":"#/$defs/RamfluxSurfaceLimits","default":{"max_actions":16,"max_blocks":32,"max_bytes":65536}},"turn_wall_clock_secs":{"description":"Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.","type":"integer","format":"uint64","default":120,"minimum":0}},"additionalProperties":false},"RamfluxOnNewMessage":{"description":"What to do with a new inbound message while a turn for that conversation is running.","type":"string","enum":["queue","interrupt"]},"RamfluxSurfaceLimits":{"description":"Limits for `reply.surface` blocks and actions.","type":"object","properties":{"max_actions":{"type":"integer","format":"uint32","default":16,"minimum":0},"max_blocks":{"type":"integer","format":"uint32","default":32,"minimum":0},"max_bytes":{"type":"integer","format":"uint32","default":65536,"minimum":0}},"additionalProperties":false},"ReliabilityCircuitBreakerConfig":{"description":"Process-local provider circuit policy (`[reliability.circuit_breaker]`).","type":"object","properties":{"enabled":{"description":"Enable protection for factory-built provider chains.","type":"boolean","default":true},"failure_threshold":{"description":"Consecutive transient failures that open a circuit (at least 1).","type":"integer","format":"uint32","default":5,"minimum":0},"max_open_secs":{"description":"Maximum doubled window, between open_secs and 3600 seconds.","type":"integer","format":"uint64","default":300,"minimum":0},"open_secs":{"description":"Initial open window in seconds (at least 1).","type":"integer","format":"uint64","default":30,"minimum":0}}},"ReliabilityConfig":{"description":"Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.","type":"object","properties":{"acknowledge_single_provider_risk":{"description":"Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.","type":"boolean","default":false},"api_keys":{"description":"Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.","type":"array","default":[],"items":{"type":"string"}},"channel_initial_backoff_secs":{"description":"Initial backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":2,"minimum":0},"channel_max_backoff_secs":{"description":"Max backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":60,"minimum":0},"circuit_breaker":{"description":"Per-provider consecutive failure protection.","$ref":"#/$defs/ReliabilityCircuitBreakerConfig","default":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30}},"fallback_providers":{"description":"Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).","type":"array","default":[],"items":{"type":"string"}},"model_fallbacks":{"description":"Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`","type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"default":{}},"provider_backoff_ms":{"description":"Base backoff (ms) for provider retry delay.","type":"integer","format":"uint64","default":500,"minimum":0},"provider_retries":{"description":"Retries per provider before failing over.","type":"integer","format":"uint32","default":2,"minimum":0},"scheduler_poll_secs":{"description":"Scheduler polling cadence in seconds.","type":"integer","format":"uint64","default":15,"minimum":0},"scheduler_retries":{"description":"Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.","type":"integer","format":"uint32","default":2,"minimum":0}}},"RemoteNodeConfig":{"description":"A remote node target for core-side node proxy calls.","type":"object","properties":{"bearer_token":{"description":"Bearer token for node RPC authentication.","type":"string"},"endpoint":{"description":"Base endpoint (e.g. \"http://127.0.0.1:8787\").","type":"string"},"hmac_secret":{"description":"Optional request signing key (HMAC-SHA256).","type":["string","null"],"default":null},"id":{"description":"Stable node ID used by the nodes tool.","type":"string"},"retry_max":{"description":"Optional per-node retry override.","type":["integer","null"],"format":"uint8","default":null,"maximum":255,"minimum":0},"timeout_ms":{"description":"Optional per-node timeout override.","type":["integer","null"],"format":"uint64","default":null,"minimum":0}},"required":["id","endpoint","bearer_token"]},"RetrievalInjectionRole":{"description":"Where recalled context pages are injected back into the request.","oneOf":[{"description":"Inject recalled pages as a leading `system` message (not user-visible).","type":"string","const":"system"},{"description":"Inject recalled pages as a leading `user` message.","type":"string","const":"user"}]},"RouterConfig":{"description":"Heuristic LLM router configuration (`[router]` section).","type":"object","properties":{"alpha":{"description":"Similarity score weight. Phase 1 keeps this at `0.0`.","type":"number","format":"float","default":0.0},"beta":{"description":"Capability score weight.","type":"number","format":"float","default":0.5},"delta":{"description":"Cost penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"epsilon":{"description":"Latency penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"gamma":{"description":"Elo score weight.","type":"number","format":"float","default":0.30000001192092896},"knn_k":{"description":"Number of nearest neighbors considered for voting. Default: `7`.","type":"integer","format":"uint","default":7,"minimum":0},"knn_min_records":{"description":"Minimum history records before KNN affects routing. Default: `10`.","type":"integer","format":"uint","default":10,"minimum":0},"models":{"description":"Candidate model registry.","type":"array","default":[],"items":{"$ref":"#/$defs/RouterModelConfig"}}}},"RouterModelConfig":{"description":"Static router metadata for one model candidate.","type":"object","properties":{"categories":{"description":"Capability categories such as `conversation`, `code`, or `analysis`.","type":"array","default":[],"items":{"type":"string"}},"cost_per_million_tokens":{"description":"USD cost per million tokens.","type":"number","format":"float","default":0.0},"elo_rating":{"description":"Initial Elo rating.","type":"number","format":"float","default":1000.0},"latency_ms":{"description":"Average latency in milliseconds.","type":"integer","format":"uint32","default":2000,"minimum":0},"max_context":{"description":"Maximum context window in tokens.","type":"integer","format":"uint","default":1000000,"minimum":0},"model_id":{"description":"Model identifier without provider prefix.","type":"string"},"provider":{"description":"Provider identifier.","type":"string"},"reserved_output_tokens":{"description":"Output tokens reserved for this model when planning input context.","type":["integer","null"],"format":"uint","minimum":0}},"required":["model_id","provider"]},"RuntimeConfig":{"description":"Runtime adapter configuration (`[runtime]` section).","type":"object","properties":{"codex_reasoning_effort":{"description":"Codex reasoning effort","type":["string","null"],"default":null},"codex_stream_idle_timeout_secs":{"description":"Codex stream idle timeout in seconds","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"docker":{"description":"Docker runtime settings (used when `kind = \"docker\"`).","$ref":"#/$defs/DockerRuntimeConfig","default":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true}},"idle_hang_secs":{"description":"Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"kind":{"description":"Runtime kind (`native` | `docker`).","type":"string","default":"native"},"long_task_warn_secs":{"description":"Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"managed_cgroup_root":{"description":"Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.","type":["string","null"],"default":null},"max_blocking_threads":{"description":"Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"reasoning_enabled":{"description":"Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported","type":["boolean","null"],"default":null},"shell_env_allowlist":{"description":"Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.","type":"array","default":[],"items":{"type":"string"}},"workdir":{"description":"Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.","type":["string","null"],"default":null}}},"SchedulerConfig":{"description":"Scheduler configuration for periodic task execution (`[scheduler]` section).","type":"object","properties":{"claim_lease_secs":{"description":"Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.","type":"integer","format":"uint64","default":90,"minimum":0},"max_tasks":{"description":"Maximum number of persisted scheduled tasks.","type":"integer","format":"uint","default":64,"minimum":0}}},"ScopeConfig":{"description":"Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```","type":"object","properties":{"assign_owners":{"description":"Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.","type":"array","default":[],"items":{"type":"string"}},"default":{"description":"Default action when no rule matches: \"allow\" (default) or \"deny\".","$ref":"#/$defs/ScopeDefault","default":"allow"},"rules":{"description":"Ordered list of scope rules evaluated top-to-bottom.","type":"array","default":[],"items":{"$ref":"#/$defs/ScopeRule"}}}},"ScopeDefault":{"description":"What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.","oneOf":[{"description":"Unmatched tool calls are allowed (the default).","type":"string","const":"allow"},{"description":"Unmatched tool calls are refused.","type":"string","const":"deny"}]},"ScopeRule":{"description":"A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.","type":"object","properties":{"assign_allow":{"description":"Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".","type":"array","default":[],"items":{"type":"string"}},"assign_deny":{"description":"Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.","type":"array","default":[],"items":{"type":"string"}},"channel":{"description":"Match by channel name: \"signal\", \"telegram\", \"discord\", etc.","type":["string","null"]},"chat_type":{"description":"Match by chat type: \"direct\", \"group\", or \"*\" for any type.","type":["string","null"]},"send_allow":{"description":"Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.","type":"array","default":[],"items":{"type":"string"}},"send_deny":{"description":"Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.","type":"array","default":[],"items":{"type":"string"}},"tools_allow":{"description":"Tool whitelist: only these tools are allowed (empty = all tools permitted).","type":"array","default":[],"items":{"type":"string"}},"tools_deny":{"description":"Tool blacklist: these tools are denied regardless of allow list.","type":"array","default":[],"items":{"type":"string"}},"user":{"description":"Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.","type":["string","null"]}}},"SecretsConfig":{"description":"Secrets encryption configuration (`[secrets]` section).","type":"object","properties":{"encrypt":{"description":"Enable encryption for API keys and tokens in config.toml","type":"boolean","default":true}}},"SecurityConfig":{"description":"Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.","type":"object","properties":{"audit":{"description":"Audit logging configuration","$ref":"#/$defs/AuditConfig","default":{"log_path":"audit.log","max_size_mb":100}},"workspace_hooks":{"description":"Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.","$ref":"#/$defs/WorkspaceHooks"}}},"SelfSystemConfig":{"description":"Self-system experimental automation config (`[self_system]`).","type":"object","properties":{"evolution_config_path":{"description":"Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG)","type":["string","null"],"default":null},"evolution_debug_raw":{"description":"Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW)","type":"boolean","default":false},"evolution_interval_hours":{"description":"Evolution scheduler interval in hours (daemon mode).","type":"integer","format":"uint32","default":24,"minimum":0},"evolution_judge_timeout_secs":{"description":"Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.","type":"integer","format":"uint64","default":180,"minimum":0},"evolution_model_max_micro_usd":{"description":"Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.","type":"integer","format":"uint64","default":0,"minimum":0},"evolution_model_max_tokens":{"description":"Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.","type":"integer","format":"uint64","default":16384,"minimum":0},"fitness":{"description":"Daily fitness snapshot policy.","$ref":"#/$defs/FitnessConfig","default":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"}},"fitness_interval_hours":{"description":"Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.","type":"integer","format":"uint64","default":24,"minimum":0}}},"SessionsSpawnConfig":{"description":"Sessions spawn configuration (`[sessions_spawn]` section).","type":"object","properties":{"cleanup_on_complete":{"description":"Remove worker workspace directory after process-mode completion.","type":"boolean","default":true},"default_mode":{"description":"Default execution mode for sessions_spawn (`task` or `process`).","type":"string","default":"task"},"process_memory_strategy":{"description":"Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.","type":"string","default":"shared_fabric"},"worker_workspace_root":{"description":"Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.","type":["string","null"],"default":null}}},"SignalConfig":{"type":"object","properties":{"account":{"description":"E.164 phone number of the signal-cli account (e.g. \"+1234567890\").","type":"string"},"allowed_from":{"description":"Allowed sender phone numbers (E.164) or \"*\" for all.","type":"array","default":[],"items":{"type":"string"}},"cli_path":{"description":"Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).","type":["string","null"],"default":null},"daemon_http_port":{"description":"Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"daemon_mode":{"description":"Deprecated: ignored. Accepted for backward compatibility with older config files.","type":["boolean","null"],"default":null},"data_dir":{"description":"signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_id":{"description":"Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group","type":["string","null"],"default":null},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"http_url":{"description":"Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.","type":"string","default":"http://localhost:8080"},"ignore_attachments":{"description":"Skip messages that are attachment-only (no text body).","type":"boolean","default":false},"ignore_stories":{"description":"Skip incoming story messages.","type":"boolean","default":false},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"mode":{"description":"Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.","type":["string","null"],"default":null},"startup_timeout_ms":{"description":"Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.","type":"integer","format":"uint64","default":30000,"minimum":0},"storm_protection":{"description":"Signal ingress storm protection controls.","$ref":"#/$defs/SignalStormProtectionConfig","default":{"abnormal_threshold":10,"abnormal_window_secs":60,"breaker_duration_secs":300,"dedupe_ttl_secs":60,"min_reply_interval_secs":2}}},"required":["account"]},"SignalStormProtectionConfig":{"type":"object","properties":{"abnormal_threshold":{"description":"Non-user event threshold within `abnormal_window_secs` before tripping the breaker.","type":"integer","format":"uint","default":10,"minimum":0},"abnormal_window_secs":{"description":"Sliding window in seconds for non-user event counting.","type":"integer","format":"uint64","default":60,"minimum":0},"breaker_duration_secs":{"description":"Circuit breaker duration in seconds after threshold is reached.","type":"integer","format":"uint64","default":300,"minimum":0},"dedupe_ttl_secs":{"description":"Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.","type":"integer","format":"uint64","default":60,"minimum":0},"min_reply_interval_secs":{"description":"Minimum interval in seconds between replies for the same `(channel + reply_target)`.","type":"integer","format":"uint64","default":2,"minimum":0}}},"SkillRagConfig":{"description":"Dynamic skill retrieval configuration (`[skill_rag]` section).","type":"object","properties":{"top_k":{"description":"How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).","type":"integer","format":"uint","default":32,"minimum":0}}},"SkillSuiteRegistration":{"description":"The frozen suite that governs one skill's proposals.","type":"object","properties":{"skill_id":{"description":"The skill the suite governs.","type":"string"},"suite_digest":{"description":"SHA-256 digest (64 lowercase hex digits) of the frozen suite.","type":"string"}},"additionalProperties":false,"required":["skill_id","suite_digest"]},"SkillsConfig":{"description":"Skills loading configuration (`[skills]` section).","type":"object","properties":{"open_skills_dir":{"description":"Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.","type":["string","null"],"default":null},"openclaw_skills_dir":{"description":"Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.","type":["string","null"],"default":null}}},"SkillsLifecycleConfig":{"description":"`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.","type":"object","properties":{"allow_executable_proposals":{"description":"Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.","type":"boolean","default":false},"enabled":{"description":"Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.","type":"boolean","default":false},"max_concurrent_evaluations":{"description":"Most evaluations running at once.","type":"integer","format":"uint32","default":1,"minimum":0},"max_edit_fraction":{"description":"Edit budget of a proposal as a fraction of the skill body, in (0, 1].","type":"number","format":"double","default":0.2},"max_edit_tokens":{"description":"Edit budget of a proposal, in tokens.","type":"integer","format":"uint64","default":300,"minimum":0},"max_proposals_per_cycle":{"description":"Most proposals one cycle may start.","type":"integer","format":"uint32","default":1,"minimum":0},"min_cases_floor":{"description":"Smallest `min_cases` a governing suite may declare. Below 3 is refused.","type":"integer","format":"uint32","default":3,"minimum":0},"mode":{"description":"`draft_only`, `shadow` or `auto`.","$ref":"#/$defs/SkillsLifecycleModeConfig","default":"draft_only"},"owner_scope":{"description":"The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.","type":["string","null"],"default":null},"require_holdout":{"description":"A governing suite must have a holdout split. `false` is refused.","type":"boolean","default":true},"storage_dir":{"description":"Store location under the workspace. Only the default is supported.","type":"string","default":"self/skill-lifecycle"},"suites":{"description":"The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.","type":"array","default":[],"items":{"$ref":"#/$defs/SkillSuiteRegistration"}}},"additionalProperties":false},"SkillsLifecycleModeConfig":{"description":"What the lifecycle may do. Mirrors `LifecycleMode`.","oneOf":[{"description":"Drafts and reviews only.","type":"string","const":"draft_only"},{"description":"Drafts plus evaluation and gating; never publishes.","type":"string","const":"shadow"},{"description":"Publishes an eligible proposal after every gate.","type":"string","const":"auto"}]},"SlackConfig":{"description":"Slack bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Slack user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Slack app-level token for Socket Mode (xapp-...).","type":["string","null"]},"bot_token":{"description":"Slack bot OAuth token (xoxb-...).","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["bot_token"]},"SmartGroupConfig":{"description":"Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).","type":"object","properties":{"classifier_max_context_messages":{"description":"How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.","type":"integer","format":"uint","default":3,"minimum":0},"classifier_model":{"description":"Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.","type":"string","default":""},"classifier_provider":{"description":"Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.","type":"string","default":""},"classifier_temperature":{"description":"Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).","type":"number","format":"double","default":0.0},"classifier_timeout_secs":{"description":"Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.","type":"integer","format":"uint64","default":5,"minimum":0}}},"StorageConfig":{"description":"Persistent storage configuration (`[storage]` section).","type":"object","properties":{"provider":{"description":"Storage provider settings (e.g. sqlite, postgres).","$ref":"#/$defs/StorageProviderSection","default":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}}},"StorageProviderConfig":{"description":"Storage provider backend configuration (e.g. postgres connection details).","type":"object","properties":{"connect_timeout_secs":{"description":"Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"db_url":{"description":"Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.","type":["string","null"],"default":null},"pool_max_size":{"description":"Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.","type":"integer","format":"uint","default":32,"minimum":0},"provider":{"description":"Storage engine key (e.g. \"postgres\", \"sqlite\").","type":"string","default":""},"schema":{"description":"Database schema for SQL backends.","type":"string","default":"public"},"table":{"description":"Table name for memory entries.","type":"string","default":"memories"}}},"StorageProviderSection":{"description":"Wrapper for the storage provider configuration section.","type":"object","properties":{"config":{"description":"Storage provider backend settings.","$ref":"#/$defs/StorageProviderConfig","default":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"StreamMode":{"description":"Streaming mode for channels that support progressive message updates.","oneOf":[{"description":"No streaming -- send the complete response as a single message (default).","type":"string","const":"off"},{"description":"Update a draft message with every flush interval.","type":"string","const":"partial"}]},"TailscaleTunnelConfig":{"type":"object","properties":{"funnel":{"description":"Use Tailscale Funnel (public internet) vs Serve (tailnet only)","type":"boolean","default":false},"hostname":{"description":"Optional hostname override","type":["string","null"]}}},"TaskRoutingConfig":{"description":"Lightweight pre-LLM task routing.","type":"object","properties":{"default_intent":{"description":"Fallback intent when no rule matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"rules":{"description":"Rules evaluated in descending priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/TaskRoutingRule"}}}},"TaskRoutingIntentConfig":{"description":"Task-routing default and rule intent.","type":"string","enum":["simple","delegate","stream"]},"TaskRoutingRule":{"description":"A single task-routing rule.","type":"object","properties":{"intent":{"description":"Route intent to apply when a keyword matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"model_hint":{"description":"Optional model hint/raw model for non-delegated requests.","type":["string","null"],"default":null},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0},"sub_agent_model":{"description":"Optional raw sub-agent model override for delegated tasks.","type":["string","null"],"default":null}}},"TelegramConfig":{"description":"Telegram bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Telegram user IDs or usernames. Empty = deny all.","type":"array","items":{"type":"string"}},"bot_token":{"description":"Telegram Bot API token (from @BotFather).","type":"string"},"draft_update_interval_ms":{"description":"Minimum interval (ms) between draft message edits to avoid rate limits.","type":"integer","format":"uint64","default":1000,"minimum":0},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"interrupt_on_new_message":{"description":"When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.","type":"boolean","default":false},"stream_mode":{"description":"Streaming mode for progressive response delivery via message edits.","$ref":"#/$defs/StreamMode","default":"off"}},"required":["bot_token","allowed_users"]},"ToolCallDialectSetting":{"description":"The tool-call grammars an operator may declare for an endpoint.","oneOf":[{"description":"Only the native `tool_calls` array is a tool call (the default).","type":"string","const":"native"},{"description":"Additionally read `{json}` from the content,\nfor a tool name the request registered.","type":"string","const":"xml_function_tags"}]},"ToolSchemaDialectSetting":{"description":"The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.","oneOf":[{"description":"The published document, byte for byte (the default).","type":"string","const":"raw"},{"description":"The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.","type":"string","const":"no_root_combinators"}]},"ToolTieringConfig":{"description":"Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.","type":"object","properties":{"always_exclude":{"description":"Tool names excluded from capability publication.","type":"array","default":[],"items":{"type":"string"}},"always_include":{"description":"Tool names preferred for direct publication, subject to admission gates.","type":"array","default":[],"items":{"type":"string"}},"channel_exclude":{"description":"Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefault: empty (nothing is hidden); list tool names to hide them on channels.","type":"array","default":[],"items":{"type":"string"}}}},"TunnelConfig":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.","type":"object","properties":{"cloudflare":{"description":"Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).","anyOf":[{"$ref":"#/$defs/CloudflareTunnelConfig"},{"type":"null"}],"default":null},"custom":{"description":"Custom tunnel command configuration (used when `provider = \"custom\"`).","anyOf":[{"$ref":"#/$defs/CustomTunnelConfig"},{"type":"null"}],"default":null},"ngrok":{"description":"ngrok tunnel configuration (used when `provider = \"ngrok\"`).","anyOf":[{"$ref":"#/$defs/NgrokTunnelConfig"},{"type":"null"}],"default":null},"provider":{"description":"Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.","type":"string","default":"none"},"tailscale":{"description":"Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).","anyOf":[{"$ref":"#/$defs/TailscaleTunnelConfig"},{"type":"null"}],"default":null}}},"UserPolicyConfig":{"description":"Startup user policy entry (`[[user_policies]]`).","type":"object","properties":{"blocked_patterns":{"type":"array","default":[],"items":{"type":"string"}},"projects":{"type":"array","default":[],"items":{"type":"string"}},"role":{"type":"string","default":"guest"},"user_id":{"type":"string"},"visibility_ceiling":{"type":"string","default":"private"}},"required":["user_id"]},"WacliConfig":{"description":"wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```","type":"object","properties":{"allow_unsigned_loopback":{"description":"Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).","type":"boolean","default":false},"allowed_from":{"description":"Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.","type":"array","default":["*"],"items":{"type":"string"}},"bot_jid":{"description":"Bot's own JID, used for reply-to-bot mention detection.","type":["string","null"],"default":null},"bot_lid":{"description":"The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.","type":["string","null"],"default":null},"bot_number":{"description":"Bot's own phone number (digits), used for `@` mention detection.","type":["string","null"],"default":null},"cli_path":{"description":"Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.","type":["string","null"],"default":null},"group_reply_mode":{"description":"Smart group-reply mode. When `None`, derived from `mention_only`.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"host":{"description":"REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].","type":["string","null"],"writeOnly":true},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"outbound_media_workspace_only":{"description":"Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.","type":"boolean","default":false},"port":{"description":"REMOVED: legacy JSON-RPC daemon port. See `host`.","type":["integer","null"],"format":"uint16","maximum":65535,"minimum":0,"writeOnly":true},"self_chat_mode":{"description":"Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.","type":"boolean","default":false},"store_dir":{"description":"wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.","type":["string","null"],"default":null},"webhook_listen":{"description":"Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").","type":"string","default":"127.0.0.1:16868"},"webhook_path":{"description":"HTTP path the webhook server serves (default: \"/wacli\").","type":"string","default":"/wacli"},"webhook_secret":{"description":"HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.","type":["string","null"],"default":null}}},"WebSearchConfig":{"description":"Web search tool configuration (`[web_search]` section).","type":"object","properties":{"brave_api_key":{"description":"Brave Search API key (required if provider is \"brave\")","type":["string","null"],"default":null},"fetch_max_chars":{"description":"Maximum characters returned by `web_fetch` (default 10000)","type":"integer","format":"uint","default":50000,"minimum":0},"max_results":{"description":"Maximum results per search (1-20)","type":"integer","format":"uint","default":15,"minimum":0},"provider":{"description":"Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)","type":"string","default":"duckduckgo"},"timeout_secs":{"description":"Request timeout in seconds","type":"integer","format":"uint64","default":15,"minimum":0}}},"WebhookConfig":{"description":"Webhook channel configuration.","type":"object","properties":{"port":{"description":"Port to listen on for incoming webhooks.","type":"integer","format":"uint16","maximum":65535,"minimum":0},"secret":{"description":"Optional shared secret for webhook signature verification.","type":["string","null"]}},"required":["port"]},"WhatsAppConfig":{"description":"WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.","type":"object","properties":{"access_token":{"description":"Access token from Meta Business Suite (Cloud API mode)","type":["string","null"],"default":null},"allowed_numbers":{"description":"Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"app_secret":{"description":"App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"pair_code":{"description":"Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one","type":["string","null"],"default":null},"pair_phone":{"description":"Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used","type":["string","null"],"default":null},"phone_number_id":{"description":"Phone number ID from Meta Business API (Cloud API mode)","type":["string","null"],"default":null},"read_pool_size":{"description":"Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"session_path":{"description":"Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs","type":["string","null"],"default":null},"verify_token":{"description":"Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode","type":["string","null"],"default":null},"ws_url":{"description":"WebSocket URL override (replaces WHATSAPP_WS_URL)","type":["string","null"],"default":null}}},"WorkspaceHooks":{"description":"Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).","oneOf":[{"description":"They do not run (the default); `prx doctor` and `hooks_status` say so.","type":"string","const":"off"},{"description":"They run, in a cleared environment and a dedicated directory beside\n`config.toml`.","type":"string","const":"on"}]},"WorkspaceMcpServers":{"description":"Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).","oneOf":[{"description":"None: a workspace file may only narrow the servers defined in\n`config.toml`.","type":"string","const":"off"},{"description":"HTTP servers (still refused when they target a private address).","type":"string","const":"http_only"},{"description":"HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.","type":"string","const":"stdio"}]},"XinConfig":{"description":"Configuration for the xin autonomous task engine (`[xin]`).","type":"object","properties":{"adopt_legacy_tasks":{"description":"Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).","type":"boolean","default":false},"interval_minutes":{"description":"Tick interval in minutes (minimum 1). Default: 5.","type":"integer","format":"uint32","default":5,"minimum":0},"stale_timeout_minutes":{"description":"Minutes after which a running task is marked stale. Default: 60.","type":"integer","format":"uint32","default":60,"minimum":0}}},"AgentMessaging":{"description":"Owner-controlled inbound session messaging (enabled unless explicitly off).","type":"object","properties":{"inbound":{"type":"boolean","default":true}}}}} +{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Config","description":"Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).","type":"object","properties":{"a2a":{"description":"Agent-to-Agent compatibility configuration (`[a2a]`).","$ref":"#/$defs/A2aConfig","default":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trusted_trust_domains":[],"trust_domain":"prx.local"}},"agent":{"description":"Agent orchestration settings (`[agent]`).","$ref":"#/$defs/AgentConfig","default":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2,"messaging":{"inbound":true}}},"agents":{"description":"Delegate agent configurations for multi-agent workflows.","type":"object","additionalProperties":{"$ref":"#/$defs/DelegateAgentConfig"},"default":{}},"api_key":{"description":"API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.","type":["string","null"],"default":null},"api_url":{"description":"Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)","type":["string","null"],"default":null},"auth":{"description":"Auth profile and external credential import settings (`[auth]`).","$ref":"#/$defs/AuthConfig","default":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"}},"autonomy":{"description":"Autonomy and security policy configuration (`[autonomy]`).","$ref":"#/$defs/AutonomyConfig","default":{"forbidden_paths":[],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]}}},"browser":{"description":"Browser automation configuration (`[browser]`).","$ref":"#/$defs/BrowserConfig","default":{"allowed_domains":[],"computer_use":{"api_key":null}}},"channels_config":{"description":"Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).","$ref":"#/$defs/ChannelsConfig","default":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null}},"chat":{"description":"Interactive chat UI configuration (`[chat]`).","$ref":"#/$defs/ChatConfig","default":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2}},"compliance":{"description":"Operator-owned compliance controls (`[compliance]`).","$ref":"#/$defs/ComplianceConfig","default":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}},"composio":{"description":"Composio managed OAuth tools integration (`[composio]`).","$ref":"#/$defs/ComposioConfig","default":{"api_key":null,"entity_id":"default"}},"cost":{"description":"Cost tracking and budget enforcement configuration (`[cost]`).","$ref":"#/$defs/CostConfig","default":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{},"warn_at_percent":80}},"cron":{"description":"Cron job configuration (`[cron]`).","$ref":"#/$defs/CronConfig","default":{"max_run_history":50}},"decision_engine":{"description":"Optional advisory decision engine, disabled by default.","$ref":"#/$defs/DecisionEngineConfig","default":{"candidates":5,"enabled":false,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"latency_budget_ms":500,"max_candidates":12,"token_ratio_limit":0.3499999940395355}},"default_model":{"description":"Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.","type":["string","null"]},"default_provider":{"description":"Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.","type":["string","null"]},"default_temperature":{"description":"Default model temperature (0.0–2.0). Default: `0.7`.","type":"number","format":"double","default":0.7},"embedding_routes":{"description":"Embedding routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/EmbeddingRouteConfig"}},"gateway":{"description":"Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).","$ref":"#/$defs/GatewayConfig","default":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60}},"heartbeat":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]`).","$ref":"#/$defs/HeartbeatConfig","default":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."}},"http_request":{"description":"HTTP request tool configuration (`[http_request]`).","$ref":"#/$defs/HttpRequestConfig","default":{"max_response_size":1000000,"timeout_secs":30}},"identity":{"description":"Identity format configuration: OpenClaw or AIEOS (`[identity]`).","$ref":"#/$defs/IdentityConfig","default":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"}},"identity_bindings":{"description":"Static identity bindings loaded at startup (`[[identity_bindings]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/IdentityBindingConfig"}},"mcp":{"description":"Secrets encryption configuration (`[secrets]`).","$ref":"#/$defs/McpConfig","default":{"servers":{}}},"mcp_server":{"description":"MCP server compatibility configuration (`[mcp_server]`).","$ref":"#/$defs/McpServerRuntimeConfig","default":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true}},"media":{"description":"Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.","$ref":"#/$defs/MediaConfig","default":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"}},"memory":{"description":"Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).","$ref":"#/$defs/MemoryConfig","default":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":true,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7}},"model_routes":{"description":"Model routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/ModelRouteConfig"}},"model_settings":{"description":"Catalog model levels and explicit parameters, keyed by canonical release ID.","type":"object","additionalProperties":{"$ref":"#/$defs/ModelSettings"},"default":{}},"multimodal":{"description":"Multimodal (image) handling configuration (`[multimodal]`).","$ref":"#/$defs/MultimodalConfig","default":{"allow_remote_fetch":true,"max_image_size_mb":5,"max_images":4}},"nodes":{"description":"Remote node proxy configuration (`[nodes]`).","$ref":"#/$defs/NodesConfig","default":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":[],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}},"observability":{"description":"Observability backend configuration (`[observability]`).","$ref":"#/$defs/ObservabilityConfig","default":{"backend":"none","otel_endpoint":null,"otel_service_name":null}},"plugins":{"description":"WASM plugin runtime switch (`[plugins]`), off by default.","$ref":"#/$defs/PluginsConfig","default":{"enabled":false}},"providers":{"description":"Provider-specific runtime options (`[providers.]`).","$ref":"#/$defs/ProvidersConfig","default":{"ollama":{"num_ctx":null}}},"proxy":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).","$ref":"#/$defs/ProxyConfig","default":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]}},"query_classification":{"description":"Automatic query classification — maps user messages to model hints.","$ref":"#/$defs/QueryClassificationConfig","default":{"rules":[]}},"reliability":{"description":"Reliability settings: retries, fallback providers, backoff (`[reliability]`).","$ref":"#/$defs/ReliabilityConfig","default":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2}},"router":{"description":"Heuristic LLM router configuration (`[router]`).","$ref":"#/$defs/RouterConfig","default":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]}},"runtime":{"description":"Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.","$ref":"#/$defs/RuntimeConfig","default":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null}},"scheduler":{"description":"Scheduler configuration for periodic task execution (`[scheduler]`).","$ref":"#/$defs/SchedulerConfig","default":{"claim_lease_secs":90,"max_tasks":64}},"secrets":{"$ref":"#/$defs/SecretsConfig","default":{"encrypt":true}},"security":{"description":"Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).","$ref":"#/$defs/SecurityConfig","default":{"audit":{"log_path":"audit.log","max_size_mb":100}}},"self_system":{"description":"Self-system experimental automation controls (`[self_system]`).","$ref":"#/$defs/SelfSystemConfig","default":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24}},"sessions_spawn":{"description":"Session spawning configuration (`[sessions_spawn]`).","$ref":"#/$defs/SessionsSpawnConfig","default":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null}},"skill_rag":{"description":"Dynamic skill retrieval settings (`[skill_rag]`).","$ref":"#/$defs/SkillRagConfig","default":{"top_k":32}},"skills":{"description":"Skills loading and community repository behavior (`[skills]`).","$ref":"#/$defs/SkillsConfig","default":{"open_skills_dir":null,"openclaw_skills_dir":null}},"skills_lifecycle":{"description":"Skill lifecycle (`[skills_lifecycle]`), off by default.","$ref":"#/$defs/SkillsLifecycleConfig","default":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]}},"smart_group":{"description":"Smart group-reply pre-gate configuration (`[smart_group]`).","$ref":"#/$defs/SmartGroupConfig","default":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5}},"storage":{"description":"Persistent storage provider configuration (`[storage]`).","$ref":"#/$defs/StorageConfig","default":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"task_routing":{"description":"Task routing configuration — classifies work by intent before the main agent loop.","$ref":"#/$defs/TaskRoutingConfig","default":{"default_intent":"simple","rules":[]}},"tool_tiering":{"description":"Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).","$ref":"#/$defs/ToolTieringConfig","default":{"always_exclude":[],"always_include":[],"channel_exclude":[],"defer_unlisted":false}},"tunnel":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]`).","$ref":"#/$defs/TunnelConfig","default":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null}},"user_policies":{"description":"Static user policy records loaded at startup (`[[user_policies]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/UserPolicyConfig"}},"web_search":{"description":"Web search tool configuration (`[web_search]`).","$ref":"#/$defs/WebSearchConfig","default":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15}},"webhook":{"description":"Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).","$ref":"#/$defs/MemoryWebhookConfig","default":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null}},"xin":{"description":"Xin autonomous task engine configuration (`[xin]`).","$ref":"#/$defs/XinConfig","default":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}}},"$defs":{"A2aConfig":{"type":"object","properties":{"agent_id":{"description":"Stable PRX agent identifier advertised to peers.","type":"string","default":"prx-default"},"allowed_peer_issuers":{"description":"Accepted external peer issuers.","type":"array","default":[],"items":{"type":"string"}},"bind":{"description":"Advertised bind address.","type":"string","default":"127.0.0.1:16832"},"card_jwks_uri":{"description":"Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.","type":["string","null"],"default":null},"card_signing_key_path":{"description":"On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).","type":["string","null"],"default":null},"card_ttl_seconds":{"description":"Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.","type":"integer","format":"uint64","default":3600,"minimum":0},"discovery_advertised":{"description":"Whether to advertise into an external A2A registry.","type":"boolean","default":false},"handoff_nonce_ttl_seconds":{"description":"Replay window for future handoff delegation tokens.","type":"integer","format":"uint64","default":3600,"minimum":0},"messaging_enabled":{"description":"Enable the dedicated pinned mTLS messaging listener.","type":"boolean","default":false},"peers":{"type":"object","additionalProperties":{"$ref":"#/$defs/A2aPeer"},"default":{}},"spiffe_id":{"description":"Local SPIFFE-style identifier placeholder.","type":"string","default":"spiffe://prx-local/agent/prx-default"},"spiffe_strict_validation":{"description":"When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.","type":"boolean","default":false},"spiffe_trust_bundle_pem":{"description":"Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).","type":["string","null"],"default":null},"trusted_trust_domains":{"description":"Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).","type":"array","default":[],"items":{"type":"string"}},"trust_domain":{"description":"SPIFFE trust domain for new instance identities.","type":"string","default":"prx.local"}}},"A2aPeer":{"description":"Explicit pinned identity and local recipient grant.","type":"object","properties":{"spiffe_id":{"type":"string"},"fingerprints":{"type":"array","items":{"type":"string"}},"address":{"type":"string"},"owner":{"type":"string"},"sessions":{"type":"array","default":["*"],"items":{"type":"string"}},"agents":{"type":"array","default":["*"],"items":{"type":"string"}}},"required":["spiffe_id","fingerprints","address","owner"],"additionalProperties":false},"AgentCompactionConfig":{"description":"Agent context compaction configuration (`[agent.compaction]`).","type":"object","properties":{"keep_recent_messages":{"description":"Number of recent non-system messages to keep after compaction.","type":"integer","format":"uint","default":12,"minimum":0},"max_context_tokens":{"description":"Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.","type":"integer","format":"uint","default":128000,"minimum":0},"memory_flush":{"description":"Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.","type":"boolean","default":true},"mode":{"description":"Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).","$ref":"#/$defs/AgentCompactionMode","default":"switch"},"os_paging":{"description":"Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.","$ref":"#/$defs/OsPagingConfig","default":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"}},"reserve_tokens":{"description":"Tokens reserved for the next model response.","type":"integer","format":"uint","default":4096,"minimum":0}}},"AgentCompactionMode":{"description":"Compaction mode for long conversation contexts.","oneOf":[{"description":"Disable proactive compaction.","type":"string","const":"off"},{"description":"Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.","type":"string","const":"switch"},{"description":"Conservative compaction that prefers summary replacement.","type":"string","const":"safeguard"},{"description":"Aggressive truncation mode for tighter contexts.","type":"string","const":"aggressive"}]},"AgentConfig":{"description":"Agent orchestration configuration (`[agent]` section).","type":"object","properties":{"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"compact_context":{"description":"When true: bootstrap_max_chars=6000. Use for 13B or smaller models.","type":"boolean","default":false},"compaction":{"description":"Context compaction controls (`[agent.compaction]`).","$ref":"#/$defs/AgentCompactionConfig","default":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096}},"low_priority_tools":{"description":"Tool names treated as low-priority when `priority_scheduling_enabled = true`.","type":"array","default":["sessions_spawn","delegate"],"items":{"type":"string"}},"priority_scheduling_enabled":{"description":"Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.","type":"boolean","default":false},"read_only_tool_concurrency_window":{"description":"Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.","type":"integer","format":"uint","default":2,"minimum":0},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}}},"AgentLimits":{"description":"Optional admission limits for rf-started turns of a named agent.","type":"object","properties":{"max_concurrent_turns":{"type":["integer","null"],"format":"uint32","minimum":0},"max_cost_per_day_cents":{"type":["integer","null"],"format":"uint64","minimum":0}},"additionalProperties":false},"AuditConfig":{"description":"Audit logging configuration","type":"object","properties":{"log_path":{"description":"Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).","type":"string","default":"audit.log"},"max_size_mb":{"description":"Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).","type":"integer","format":"uint32","default":100,"minimum":0}}},"AuthConfig":{"description":"Authentication and external credential import configuration (`[auth]` section).","type":"object","properties":{"codex_auth_json_auto_import":{"description":"Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.","type":"boolean","default":false},"codex_auth_json_path":{"description":"Source path for Codex CLI auth.json import.","type":"string","default":"~/.codex/auth.json"}}},"AutonomyConfig":{"type":"object","properties":{"acknowledge_unrestricted_profile":{"description":"Operator acknowledgement for an intentionally unrestricted profile.\nRetained for existing configs; it no longer changes any output or policy behavior.","type":"boolean","default":false},"forbidden_paths":{"description":"Explicit path denylist. Default: empty.\n\nApplies below level `full` only; list paths when running `supervised` or `readonly`.","type":"array","default":[],"items":{"type":"string"}},"level":{"description":"Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).","$ref":"#/$defs/AutonomyLevel","default":"full"},"max_cost_per_day_cents":{"description":"Maximum cost per day in cents per policy. Default: unset (no ceiling).","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"scopes":{"description":"Scope-based tool access control: per-user/channel/chat-type allow/deny rules.","$ref":"#/$defs/ScopeConfig","default":{"assign_owners":[],"default":"allow","rules":[]}},"workspace_only":{"description":"Restrict file writes and command paths to the workspace directory. Default: `false`.\n\nApplies below level `full` only; set it when running `supervised` or `readonly`.","type":"boolean","default":false}}},"AutonomyLevel":{"description":"How much autonomy the agent has","oneOf":[{"description":"Read-only: can observe but not act","type":"string","const":"readonly"},{"description":"Supervised: acts but requires approval for risky operations","type":"string","const":"supervised"},{"description":"Full: autonomous execution within policy bounds","type":"string","const":"full"}]},"BackendSelection":{"description":"Which decision backend runs: `auto` (the factory's order) or one kind.","type":"string"},"BrowserComputerUseConfig":{"description":"Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.","type":"object","properties":{"api_key":{"description":"Optional bearer token (retained only for config secret handling).","type":["string","null"],"default":null}}},"BrowserConfig":{"description":"Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.","type":"object","properties":{"allowed_domains":{"description":"Allowed domains for `web_fetch` (exact or subdomain match).","type":"array","default":[],"items":{"type":"string"}},"computer_use":{"description":"Computer-use sidecar config (retained only for `api_key` secret handling).","$ref":"#/$defs/BrowserComputerUseConfig","default":{"api_key":null}}}},"ChannelsConfig":{"description":"Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.","type":"object","properties":{"cli":{"description":"Enable the CLI interactive channel. Default: `true`.","type":"boolean","default":true},"dingtalk":{"description":"DingTalk channel configuration.","anyOf":[{"$ref":"#/$defs/DingTalkConfig"},{"type":"null"}]},"discord":{"description":"Discord bot channel configuration.","anyOf":[{"$ref":"#/$defs/DiscordConfig"},{"type":"null"}]},"email":{"description":"Email channel configuration.","anyOf":[{"$ref":"#/$defs/EmailConfig"},{"type":"null"}]},"imessage":{"description":"iMessage channel configuration (macOS only).","anyOf":[{"$ref":"#/$defs/IMessageConfig"},{"type":"null"}]},"irc":{"description":"IRC channel configuration.","anyOf":[{"$ref":"#/$defs/IrcConfig"},{"type":"null"}]},"lark":{"description":"Lark/Feishu channel configuration.","anyOf":[{"$ref":"#/$defs/LarkConfig"},{"type":"null"}]},"linq":{"description":"Linq Partner API channel configuration.","anyOf":[{"$ref":"#/$defs/LinqConfig"},{"type":"null"}]},"mattermost":{"description":"Mattermost bot channel configuration.","anyOf":[{"$ref":"#/$defs/MattermostConfig"},{"type":"null"}]},"nextcloud_talk":{"description":"Nextcloud Talk bot channel configuration.","anyOf":[{"$ref":"#/$defs/NextcloudTalkConfig"},{"type":"null"}]},"qq":{"description":"QQ Official Bot channel configuration.","anyOf":[{"$ref":"#/$defs/QQConfig"},{"type":"null"}]},"ramflux":{"description":"Local ramflux agent-host bridge.","anyOf":[{"$ref":"#/$defs/RamfluxConfig"},{"type":"null"}],"default":null},"signal":{"description":"Signal channel configuration.","anyOf":[{"$ref":"#/$defs/SignalConfig"},{"type":"null"}]},"slack":{"description":"Slack bot channel configuration.","anyOf":[{"$ref":"#/$defs/SlackConfig"},{"type":"null"}]},"telegram":{"description":"Telegram bot channel configuration.","anyOf":[{"$ref":"#/$defs/TelegramConfig"},{"type":"null"}]},"wacli":{"description":"wacli JSON-RPC daemon channel configuration.","anyOf":[{"$ref":"#/$defs/WacliConfig"},{"type":"null"}],"default":null},"webhook":{"description":"Webhook channel configuration.","anyOf":[{"$ref":"#/$defs/WebhookConfig"},{"type":"null"}]},"whatsapp":{"description":"WhatsApp channel configuration (Cloud API or Web mode).","anyOf":[{"$ref":"#/$defs/WhatsAppConfig"},{"type":"null"}]}}},"ChatConfig":{"description":"Interactive chat configuration (`[chat]`).","type":"object","properties":{"daemon":{"description":"How this chat process reaches the daemon it borrows channels from.","$ref":"#/$defs/ChatDaemonConfig","default":{"token":"","url":""}},"max_concurrent_visible_turns":{"description":"Maximum concurrent visible provider turns in the TUI Redux driver.","type":"integer","format":"uint","default":2,"minimum":0}}},"ChatDaemonConfig":{"description":"Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.","type":"object","properties":{"token":{"description":"Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.","type":"string","default":""},"url":{"description":"Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.","type":"string","default":""}}},"CircuitBreakerConfig":{"description":"The per-backend circuit breaker.","type":"object","properties":{"cooldown_secs":{"description":"Seconds the breaker stays open (1 to 3600).","type":"integer","format":"uint32","default":60,"minimum":0},"failure_threshold":{"description":"Consecutive failures before the breaker opens (1 to 100).","type":"integer","format":"uint32","default":5,"minimum":0}}},"ClassificationRule":{"description":"A single classification rule mapping message patterns to a model hint.","type":"object","properties":{"hint":{"description":"Must match a `[[model_routes]]` hint value.","type":"string"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"max_length":{"description":"Only match if message length <= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"min_length":{"description":"Only match if message length >= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"patterns":{"description":"Case-sensitive literal matches (for \"```\", \"fn \", etc.).","type":"array","default":[],"items":{"type":"string"}},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0}},"required":["hint"]},"CloudflareTunnelConfig":{"type":"object","properties":{"token":{"description":"Cloudflare Tunnel token (from Zero Trust dashboard)","type":"string"}},"required":["token"]},"ComplianceConfig":{"type":"object","properties":{"eu_ai_act":{"$ref":"#/$defs/EuAiActComplianceConfig","default":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null}},"interaction_notice":{"$ref":"#/$defs/InteractionNoticeConfig","default":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}}},"ComposioConfig":{"description":"Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.","type":"object","properties":{"api_key":{"description":"Composio API key (stored encrypted when secrets.encrypt = true)","type":["string","null"],"default":null},"entity_id":{"description":"Default entity ID for multi-user setups","type":"string","default":"default"}}},"CostConfig":{"description":"Cost tracking and budget enforcement configuration (`[cost]` section).","type":"object","properties":{"allow_override":{"description":"Allow requests to exceed budget with --override flag (default: false)","type":"boolean","default":false},"daily_limit_usd":{"description":"Daily spending limit in USD (default: unset, no limit; 0 refuses every priced turn)","type":["number","null"],"format":"double","default":null},"monthly_limit_usd":{"description":"Monthly spending limit in USD (default: unset, no limit)","type":["number","null"],"format":"double","default":null},"prices":{"description":"Per-model pricing (USD per 1M tokens)","type":"object","additionalProperties":{"$ref":"#/$defs/ModelPricing"},"default":{}},"warn_at_percent":{"description":"Warn when spending reaches this percentage of a configured limit (default: 80)","type":"integer","format":"uint8","default":80,"maximum":255,"minimum":0}}},"CredentialRefSetting":{"description":"Which credential a decision backend uses. A reference, never a secret.","type":"string"},"CronConfig":{"description":"Cron job configuration (`[cron]` section).","type":"object","properties":{"max_run_history":{"description":"Maximum number of historical cron run records to retain. Default: `50`.","type":"integer","format":"uint32","default":50,"minimum":0}}},"CustomTunnelConfig":{"type":"object","properties":{"health_url":{"description":"Optional URL to check tunnel health","type":["string","null"]},"start_command":{"description":"Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"","type":"string"},"url_pattern":{"description":"Optional regex to extract public URL from command stdout","type":["string","null"]}},"required":["start_command"]},"DecisionBackendConfig":{"description":"The decision backend (`[decision_engine.backend]`).","type":"object","properties":{"circuit_breaker":{"description":"The circuit breaker.","$ref":"#/$defs/CircuitBreakerConfig","default":{"cooldown_secs":60,"failure_threshold":5}},"credential_ref":{"description":"The credential reference: `\"\"`, `\"none\"` or `cred-`.","$ref":"#/$defs/CredentialRefSetting","default":""},"endpoint":{"description":"The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.","type":"string","default":""},"kind":{"description":"`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).","$ref":"#/$defs/BackendSelection","default":"auto"},"max_request_bytes":{"description":"Largest request body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":65536,"minimum":0},"max_response_bytes":{"description":"Largest response body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":262144,"minimum":0},"model":{"description":"The model the endpoint serves; one exact version for a hosted\nservice.","type":"string","default":""},"pinned_snapshot":{"description":"The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.","type":"string"},"remote_enabled":{"description":"Whether decision state may leave this machine. Default `false`.","type":"boolean","default":false},"timeout_ms":{"description":"Transport timeout (10 ms up to the extra latency budget).","type":"integer","format":"uint32","default":250,"minimum":0}}},"DecisionEngineConfig":{"type":"object","properties":{"backend":{"anyOf":[{"$ref":"#/$defs/DecisionBackendConfig"},{"type":"null"}]},"candidates":{"type":"integer","format":"uint32","default":5,"minimum":0},"enabled":{"type":"boolean","default":false},"mode":{"$ref":"#/$defs/DecisionMode","default":"pre"},"observe_queue":{"type":"integer","format":"uint32","default":64,"minimum":0},"prompt_budget_tokens":{"type":"integer","format":"uint32","default":300,"minimum":0},"telemetry_cap":{"type":"integer","format":"uint32","default":1000,"minimum":0},"timeout_ms":{"type":"integer","format":"uint32","default":1500,"minimum":0},"latency_budget_ms":{"description":"The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.","type":"integer","format":"uint64","default":500,"minimum":0},"token_ratio_limit":{"description":"Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).","type":"number","format":"float","default":0.3499999940395355},"max_candidates":{"description":"The most candidates a turn considers (1 to 32).","type":"integer","format":"uint8","default":12,"maximum":255,"minimum":0}}},"DecisionMode":{"type":"string","enum":["pre","post","both"]},"DeclarationOfConformityConfig":{"type":"object","properties":{"applicable_union_law":{"type":"array","default":[],"items":{"type":"string"}},"artifact_path":{"type":["string","null"],"default":null},"artifact_version":{"type":["string","null"],"default":null},"conformity_assessment_procedure":{"type":["string","null"],"default":null},"conformity_statement":{"type":["string","null"],"default":null},"harmonised_standards":{"type":"array","default":[],"items":{"type":"string"}},"issue_date":{"type":["string","null"],"default":null},"issue_place":{"type":["string","null"],"default":null},"notified_body_certificate":{"type":["string","null"],"default":null},"notified_body_identification_number":{"type":["string","null"],"default":null},"notified_body_name":{"type":["string","null"],"default":null},"personal_data_compliance_statement":{"type":["string","null"],"default":null},"processes_personal_data":{"type":"boolean","default":false},"provider_address":{"type":["string","null"],"default":null},"provider_name":{"type":["string","null"],"default":null},"signer_function":{"type":["string","null"],"default":null},"signer_name":{"type":["string","null"],"default":null},"signer_on_behalf_of":{"type":["string","null"],"default":null},"sole_responsibility_statement":{"type":["string","null"],"default":null},"standards_not_applicable_reason":{"type":["string","null"],"default":null},"system_name":{"type":["string","null"],"default":null},"system_reference":{"type":["string","null"],"default":null},"system_type":{"type":["string","null"],"default":null}}},"DelegateAgentConfig":{"description":"Configuration for a delegate sub-agent used by the `delegate` tool.","type":"object","properties":{"agentic":{"description":"Agentic sub-agent mode (multi-turn tool-call loop). Default true; an\nexplicit `false` makes the agent answer-only with no tools.","type":"boolean","default":true},"allowed_tools":{"description":"Allowlist of tool names available to the sub-agent in agentic mode.\nEmpty or omitted means all tools, the same as `[\"*\"]`.","type":"array","default":[],"items":{"type":"string"}},"api_key":{"description":"Optional API key override","type":["string","null"],"default":null},"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"autonomy":{"description":"The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.","anyOf":[{"$ref":"#/$defs/AutonomyLevel"},{"type":"null"}]},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"enabled":{"description":"Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.","type":"boolean","default":true},"identity_dir":{"description":"Optional identity files directory relative to workspace root.","type":["string","null"],"default":null},"limits":{"$ref":"#/$defs/AgentLimits","default":{"max_concurrent_turns":null,"max_cost_per_day_cents":null}},"max_depth":{"description":"Max recursion depth for nested delegation","type":"integer","format":"uint32","default":8,"minimum":0},"memory_scope":{"description":"Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".","type":["string","null"],"default":null},"model":{"description":"Model name","type":"string"},"provider":{"description":"Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")","type":"string"},"spawn_enabled":{"description":"Whether this agent is allowed to be targeted by sessions_spawn (default: true).","type":["boolean","null"],"default":null},"system_prompt":{"description":"Optional system prompt for the sub-agent","type":["string","null"],"default":null},"temperature":{"description":"Temperature override","type":["number","null"],"format":"double","default":null},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}},"required":["provider","model"]},"DingTalkConfig":{"description":"DingTalk configuration for Stream Mode messaging","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"client_id":{"description":"Client ID (AppKey) from DingTalk developer console","type":"string"},"client_secret":{"description":"Client Secret (AppSecret) from DingTalk developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["client_id","client_secret"]},"DiscordConfig":{"description":"Discord bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Discord user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Discord bot token (from Discord Developer Portal).","type":"string"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"guild_id":{"description":"Optional guild (server) ID to restrict the bot to a single guild.","type":["string","null"]},"listen_to_bots":{"description":"When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.","type":"boolean","default":false}},"required":["bot_token"]},"DmPolicy":{"description":"Policy for direct-message handling.","oneOf":[{"description":"Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).","type":"string","const":"pairing"},{"description":"Accept only senders listed in `allowed_from`.","type":"string","const":"allowlist"},{"description":"Accept any direct sender.","type":"string","const":"open"},{"description":"Ignore direct messages.","type":"string","const":"disabled"}]},"DockerRuntimeConfig":{"description":"Docker runtime configuration (`[runtime.docker]` section).","type":"object","properties":{"allowed_workspace_roots":{"description":"Optional workspace root allowlist for Docker mount validation.","type":"array","default":[],"items":{"type":"string"}},"cpu_limit":{"description":"Optional CPU limit (`None` = no explicit limit).","type":["number","null"],"format":"double","default":1.0},"image":{"description":"Runtime image used to execute shell commands.","type":"string","default":"alpine:3.20"},"memory_limit_mb":{"description":"Optional memory limit in MB (`None` = no explicit limit).","type":["integer","null"],"format":"uint64","default":512,"minimum":0},"mount_workspace":{"description":"Mount configured workspace into `/workspace`.","type":"boolean","default":true},"network":{"description":"Docker network mode (`none`, `bridge`, etc.).","type":"string","default":"none"},"read_only_rootfs":{"description":"Mount root filesystem as read-only.","type":"boolean","default":true}}},"EmailConfig":{"description":"Email channel configuration","type":"object","properties":{"allowed_senders":{"description":"Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)","type":"array","default":[],"items":{"type":"string"}},"from_address":{"description":"From address for outgoing emails","type":"string"},"idle_timeout_secs":{"description":"IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes","type":"integer","format":"uint64","default":1740,"minimum":0},"imap_folder":{"description":"IMAP folder to poll (default: INBOX)","type":"string","default":"INBOX"},"imap_host":{"description":"IMAP server hostname","type":"string"},"imap_port":{"description":"IMAP server port (default: 993 for TLS)","type":"integer","format":"uint16","default":993,"maximum":65535,"minimum":0},"password":{"description":"Email password for authentication","type":"string"},"smtp_host":{"description":"SMTP server hostname","type":"string"},"smtp_port":{"description":"SMTP server port (default: 465 for TLS)","type":"integer","format":"uint16","default":465,"maximum":65535,"minimum":0},"smtp_tls":{"description":"Use TLS for SMTP (default: true)","type":"boolean","default":true},"username":{"description":"Email username for authentication","type":"string"}},"required":["imap_host","smtp_host","username","password","from_address"]},"EmbeddingRouteConfig":{"description":"Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"dimensions":{"description":"Optional embedding dimension override for this route","type":["integer","null"],"format":"uint","default":null,"minimum":0},"hint":{"description":"Route hint name (e.g. \"semantic\", \"archive\", \"faq\")","type":"string"},"model":{"description":"Embedding model to use with that provider","type":"string"},"provider":{"description":"Embedding provider (`none`, `openai`, or `custom:`)","type":"string"}},"required":["hint","provider","model"]},"EuAiActClassificationConfig":{"type":"object","properties":{"assessed_at":{"type":["string","null"],"default":null},"owner":{"type":["string","null"],"default":null},"status":{"$ref":"#/$defs/EuAiActRiskClassification","default":"unclassified"}}},"EuAiActComplianceConfig":{"type":"object","properties":{"classification":{"$ref":"#/$defs/EuAiActClassificationConfig","default":{"assessed_at":null,"owner":null,"status":"unclassified"}},"declaration":{"$ref":"#/$defs/DeclarationOfConformityConfig","default":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null}},"incident_store_path":{"type":["string","null"],"default":null}}},"EuAiActRiskClassification":{"type":"string","enum":["unclassified","high_risk","not_high_risk"]},"FitnessConfig":{"description":"Calendar schedule, evidence thresholds, and retention for fitness v2.","type":"object","properties":{"auto_run":{"description":"Run the daily fitness worker in daemon mode.","type":"boolean","default":true},"max_backfill_days":{"description":"Maximum number of closed days recovered after downtime.","type":"integer","format":"uint32","default":7,"minimum":0},"min_coverage":{"description":"Minimum available metric weight required to publish a final score.","type":"number","format":"double","default":0.6},"min_samples":{"description":"Minimum samples required before an evidence-derived subscore is usable.","type":"integer","format":"uint","default":5,"minimum":0},"retention_days":{"description":"Number of daily JSON reports retained on disk.","type":"integer","format":"uint32","default":180,"minimum":0},"run_at":{"description":"Local wall-clock time (`HH:MM`) at which the previous day is scored.","type":"string","default":"00:10"},"timezone":{"description":"IANA timezone used to define closed calendar days.","type":"string","default":"UTC"}}},"GatewayConfig":{"description":"Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.","type":"object","properties":{"allow_public_bind":{"description":"Allow binding to non-localhost without a tunnel (default: false)","type":"boolean","default":false},"api_rate_limit_per_minute":{"description":"Max `/api/*` requests per minute per authenticated token.","type":"integer","format":"uint32","default":60,"minimum":0},"channel_webhook_dedup_ttl_secs":{"description":"How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.","type":"integer","format":"uint64","default":86400,"minimum":0},"host":{"description":"Gateway host (default: 127.0.0.1)","type":"string","default":"127.0.0.1"},"idempotency_max_keys":{"description":"Maximum distinct idempotency keys retained in memory.","type":"integer","format":"uint","default":10000,"minimum":0},"idempotency_ttl_secs":{"description":"TTL for webhook idempotency keys.","type":"integer","format":"uint64","default":300,"minimum":0},"pair_rate_limit_per_minute":{"description":"Max `/pair` requests per minute per client key.","type":"integer","format":"uint32","default":10,"minimum":0},"paired_tokens":{"description":"Paired bearer tokens (managed automatically, not user-edited)","type":"array","default":[],"items":{"type":"string"}},"port":{"description":"Gateway port (default: 16830)","type":"integer","format":"uint16","default":16830,"maximum":65535,"minimum":0},"rate_limit_max_keys":{"description":"Maximum distinct client keys tracked by gateway rate limiter maps.","type":"integer","format":"uint","default":10000,"minimum":0},"require_pairing":{"description":"Require pairing before accepting requests (default: true)","type":"boolean","default":true},"targeted_agents":{"description":"Switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). Default true. While false, any\notherwise-valid named target answers 409 `agent_disabled` and never\nruns as Main.","type":"boolean","default":true},"trust_forwarded_headers":{"description":"Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.","type":"boolean","default":false},"webhook_rate_limit_per_minute":{"description":"Max `/webhook` requests per minute per client key.","type":"integer","format":"uint32","default":60,"minimum":0}}},"GroupPolicy":{"description":"Policy for group-message handling.","oneOf":[{"description":"Accept only groups listed in `group_allow_from`.","type":"string","const":"allowlist"},{"description":"Accept any group.","type":"string","const":"open"},{"description":"Ignore group messages.","type":"string","const":"disabled"}]},"GroupReplyMode":{"description":"How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.","oneOf":[{"description":"Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).","type":"string","const":"off"},{"description":"Reply only when the bot is @-mentioned (legacy `mention_only = true`).","type":"string","const":"mention-only"},{"description":"Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).","type":"string","const":"smart"}]},"HeartbeatConfig":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]` section).","type":"object","properties":{"active_hours":{"description":"Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.","type":"array","default":[8,23],"items":{"type":"integer","format":"uint8","maximum":255,"minimum":0}},"interval_minutes":{"description":"Interval in minutes between heartbeat pings. Default: `30`.","type":"integer","format":"uint32","default":30,"minimum":0},"prompt":{"description":"Prompt used by heartbeat worker when dispatching tasks.","type":"string","default":"Check HEARTBEAT.md and follow instructions."}}},"HttpRequestConfig":{"description":"HTTP request tool configuration (`[http_request]` section).","type":"object","properties":{"max_response_size":{"description":"Maximum response size in bytes (default: 1MB)","type":"integer","format":"uint","default":1000000,"minimum":0},"timeout_secs":{"description":"Request timeout in seconds (default: 30)","type":"integer","format":"uint64","default":30,"minimum":0}}},"IMessageConfig":{"description":"iMessage channel configuration (macOS only).","type":"object","properties":{"allowed_contacts":{"description":"Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.","type":"array","items":{"type":"string"}},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["allowed_contacts"]},"IdentityBindingConfig":{"description":"Startup identity binding entry (`[[identity_bindings]]`).","type":"object","properties":{"channel":{"type":"string"},"channel_account":{"type":"string"},"display_name":{"type":["string","null"],"default":null},"user_id":{"type":"string"}},"required":["user_id","channel","channel_account"]},"IdentityConfig":{"description":"Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.","type":"object","properties":{"aieos_inline":{"description":"Inline AIEOS JSON (alternative to file path)","type":["string","null"],"default":null},"aieos_path":{"description":"Path to AIEOS JSON file (relative to workspace)","type":["string","null"],"default":null},"format":{"description":"Identity format: \"openclaw\" (default) or \"aieos\"","type":"string","default":"openclaw"}}},"InteractionNoticeApplicability":{"type":"string","enum":["required","not_applicable"]},"InteractionNoticeConfig":{"type":"object","properties":{"applicability":{"$ref":"#/$defs/InteractionNoticeApplicability","default":"required"},"exception_owner":{"type":["string","null"],"default":null},"exception_reviewed_at":{"type":["string","null"],"default":null},"text":{"type":"string","default":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers."},"version":{"type":"string","default":"1"}}},"IrcConfig":{"description":"IRC channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed nicknames (case-insensitive) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"channels":{"description":"Channels to join on connect","type":"array","default":[],"items":{"type":"string"}},"mention_only":{"description":"When true, only process channel/group messages that mention the bot.","type":"boolean","default":false},"nickname":{"description":"Bot nickname","type":"string"},"nickserv_password":{"description":"NickServ IDENTIFY password","type":["string","null"]},"port":{"description":"IRC server port (default: 6697 for TLS)","type":"integer","format":"uint16","default":6697,"maximum":65535,"minimum":0},"sasl_password":{"description":"SASL PLAIN password (IRCv3)","type":["string","null"]},"server":{"description":"IRC server hostname","type":"string"},"server_password":{"description":"Server password (for bouncers like ZNC)","type":["string","null"]},"username":{"description":"Username (defaults to nickname if not set)","type":["string","null"]},"verify_tls":{"description":"Verify TLS certificate (default: true)","type":["boolean","null"]}},"required":["server","nickname"]},"LarkConfig":{"description":"Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from Lark/Feishu developer console","type":"string"},"app_secret":{"description":"App Secret from Lark/Feishu developer console","type":"string"},"encrypt_key":{"description":"Encrypt key for webhook message decryption (optional)","type":["string","null"],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"port":{"description":"HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"receive_mode":{"description":"Event receive mode: \"websocket\" (default) or \"webhook\"","$ref":"#/$defs/LarkReceiveMode","default":"websocket"},"use_feishu":{"description":"Whether to use the Feishu (Chinese) endpoint instead of Lark (International)","type":"boolean","default":false},"verification_token":{"description":"Verification token for webhook validation (optional)","type":["string","null"],"default":null}},"required":["app_id","app_secret"]},"LarkReceiveMode":{"description":"How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.","type":"string","enum":["websocket","webhook"]},"LinqConfig":{"type":"object","properties":{"allowed_senders":{"description":"Allowed sender handles (phone numbers) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"api_token":{"description":"Linq Partner API token (Bearer auth)","type":"string"},"from_phone":{"description":"Phone number to send from (E.164 format)","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"signing_secret":{"description":"Webhook signing secret for signature verification","type":["string","null"],"default":null}},"required":["api_token","from_phone"]},"MattermostConfig":{"description":"Mattermost bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Mattermost user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Mattermost bot access token.","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.","type":["boolean","null"],"default":null},"thread_replies":{"description":"When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.","type":["boolean","null"],"default":null},"url":{"description":"Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).","type":"string"}},"required":["url","bot_token"]},"McpConfig":{"type":"object","properties":{"servers":{"description":"Named MCP server definitions","type":"object","additionalProperties":{"$ref":"#/$defs/McpServerConfig"},"default":{}},"workspace_servers":{"description":"Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.","$ref":"#/$defs/WorkspaceMcpServers"}}},"McpServerConfig":{"type":"object","properties":{"allow_tools":{"description":"Optional allow-list of exposed tools (empty = all)","type":"array","default":[],"items":{"type":"string"}},"args":{"description":"Command args for stdio mode","type":"array","default":[],"items":{"type":"string"}},"command":{"description":"Command for stdio mode","type":["string","null"],"default":null},"deny_tools":{"description":"Optional deny-list of exposed tools","type":"array","default":[],"items":{"type":"string"}},"env":{"description":"Environment variables for stdio mode","type":"object","additionalProperties":{"type":"string"},"default":{}},"request_timeout_ms":{"description":"Request timeout in milliseconds","type":"integer","format":"uint64","default":30000,"minimum":0},"startup_timeout_ms":{"description":"Startup timeout in milliseconds","type":"integer","format":"uint64","default":10000,"minimum":0},"tool_name_prefix":{"description":"Prefix used in tool naming and routing","type":"string","default":"mcp"},"transport":{"description":"Transport type: stdio or http","$ref":"#/$defs/McpTransport","default":"stdio"},"url":{"description":"URL for HTTP mode (streamable HTTP endpoint)","type":["string","null"],"default":null},"working_dir":{"description":"Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).","type":["string","null"]}}},"McpServerRuntimeConfig":{"type":"object","properties":{"allowed_origins":{"description":"Allowed browser origins for future streamable HTTP clients.","type":"array","default":["claude.ai","openai.com","localhost"],"items":{"type":"string"}},"bind":{"description":"Advertised bind address. The gateway may still be started with a CLI port override.","type":"string","default":"127.0.0.1:16831"},"exposed_tools":{"description":"Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.","type":"array","default":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"items":{"type":"string"}},"jwt_algorithms":{"description":"Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.","type":"array","default":["RS256"],"items":{"type":"string"}},"jwt_audience":{"description":"Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.","type":["string","null"],"default":null},"jwt_issuer":{"description":"Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.","type":["string","null"],"default":null},"jwt_jwks":{"description":"Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.","type":["string","null"],"default":null},"jwt_jwks_cache_ttl_secs":{"description":"Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.","type":"integer","format":"uint64","default":300,"minimum":0},"jwt_jwks_uri":{"description":"Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.","type":["string","null"],"default":null},"jwt_public_key_pem":{"description":"PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.","type":["string","null"],"default":null},"rate_limit_rps":{"description":"Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.","type":"integer","format":"uint32","default":10,"minimum":0},"require_auth":{"description":"Require an authenticated external identity for mutating calls.","type":"boolean","default":true}}},"McpTransport":{"type":"string","enum":["stdio","http"]},"MediaConfig":{"description":"Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.","type":"object","properties":{"audio_model":{"description":"Audio model name (Ollama model or OpenAI model). Default: \"whisper\".","type":"string","default":"whisper"},"audio_ollama_url":{"description":"Ollama base URL for audio transcription. Default: \"http://localhost:11434\".","type":"string","default":"http://localhost:11434"},"audio_provider":{"description":"Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".","type":"string","default":"none"},"max_audio_size_mb":{"description":"Maximum audio attachment size in MiB. Default: 20.","type":"integer","format":"uint","default":20,"minimum":0},"max_video_size_mb":{"description":"Maximum video attachment size in MiB. Default: 50.","type":"integer","format":"uint","default":50,"minimum":0},"video_max_frames":{"description":"Maximum video frames to extract per video. Default: 4.","type":"integer","format":"uint","default":4,"minimum":0},"video_provider":{"description":"Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".","type":"string","default":"none"}}},"MemoryConfig":{"description":"Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.","type":"object","properties":{"acl_enabled":{"description":"Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.","type":"boolean","default":false},"archive_after_days":{"description":"Archive daily/session files older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"auto_hydrate":{"description":"Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing","type":"boolean","default":true},"auto_save":{"description":"Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.","type":"boolean","default":true},"backend":{"description":"\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).","type":"string","default":"sqlite"},"conversation_retention_days":{"description":"For sqlite backend: prune conversation rows older than this many days","type":"integer","format":"uint32","default":3,"minimum":0},"daily_retention_days":{"description":"For sqlite backend: prune daily rows older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"embedding_cache_size":{"description":"Max embedding cache entries before LRU eviction","type":"integer","format":"uint","default":10000,"minimum":0},"embedding_dimensions":{"description":"Embedding vector dimensions","type":"integer","format":"uint","default":384,"minimum":0},"embedding_model":{"description":"Embedding model name (e.g. \"text-embedding-3-small\")","type":"string","default":"prx-local-hash-v1"},"embedding_provider":{"description":"Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"","type":"string","default":"local"},"events":{"description":"Raw/quasi-raw message event recording controls (`[memory.events]`).","$ref":"#/$defs/MemoryEventsConfig","default":{"record_assistant_messages":true,"record_tool_events":true,"record_user_messages":true}},"keyword_weight":{"description":"Weight for keyword BM25 in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.3},"legacy_conversation_turns_visible":{"description":"Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.","type":"boolean","default":true},"lucid_budget":{"description":"Token budget for lucid (replaces OPENPRX_LUCID_BUDGET)","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"lucid_cmd":{"description":"Path to lucid binary (replaces OPENPRX_LUCID_CMD)","type":["string","null"],"default":null},"lucid_failure_cooldown_ms":{"description":"Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)","type":"integer","format":"uint64","default":60000,"minimum":0},"lucid_local_hit_threshold":{"description":"Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)","type":"integer","format":"uint","default":3,"minimum":0},"lucid_recall_timeout_ms":{"description":"Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)","type":"integer","format":"uint64","default":5000,"minimum":0},"lucid_store_timeout_ms":{"description":"Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)","type":"integer","format":"uint64","default":3000,"minimum":0},"min_relevance_score":{"description":"Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4","type":"number","format":"double","default":0.4},"purge_after_days":{"description":"Purge archived files older than this many days","type":"integer","format":"uint32","default":30,"minimum":0},"semantic":{"description":"Semantic memory promotion controls (`[memory.semantic]`).","$ref":"#/$defs/MemorySemanticConfig","default":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30}},"sqlite_open_timeout_secs":{"description":"For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"sqlite_read_pool_size":{"description":"For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"vector_candidate_cap":{"description":"How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.","type":"integer","format":"uint","default":2000,"minimum":0},"vector_weight":{"description":"Weight for vector similarity in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.7}}},"MemoryEventsConfig":{"description":"Raw message event recording configuration (`[memory.events]`).","type":"object","properties":{"record_assistant_messages":{"description":"Record assistant replies.","type":"boolean","default":true},"record_tool_events":{"description":"Record tool calls and tool results in the durable message log.","type":"boolean","default":true},"record_user_messages":{"description":"Record inbound/user messages.","type":"boolean","default":true}}},"MemorySemanticConfig":{"description":"Semantic memory promotion configuration (`[memory.semantic]`).","type":"object","properties":{"auto_promote_assistant_messages":{"description":"Auto-promote eligible assistant messages. Disabled by default to reduce noise.","type":"boolean","default":false},"auto_promote_user_messages":{"description":"Auto-promote eligible user messages into long-term semantic memories.","type":"boolean","default":true},"min_chars":{"description":"Minimum content length for semantic auto-promotion.","type":"integer","format":"uint","default":30,"minimum":0}}},"MemoryWebhookConfig":{"type":"object","properties":{"bind":{"description":"Socket address for the receiver (e.g. \"0.0.0.0:16899\").","type":"string","default":"0.0.0.0:16899"},"signing_secret":{"description":"Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.","type":["string","null"],"default":null},"token":{"description":"Required bearer token for incoming webhook events.","type":["string","null"],"default":null}}},"ModelOperationSetting":{"description":"The operations a `[[providers.models]]` entry may list.","type":"string","enum":["chat","embedding","decision_endpoint","rerank","image_generation","audio_generation","video_generation"]},"ModelPricing":{"description":"Per-model pricing entry (USD per 1M tokens).","type":"object","properties":{"cache_read":{"description":"Cache read input price per 1M tokens.","type":"number","format":"double","default":0.0},"cache_write":{"description":"Cache write/creation input price per 1M tokens.","type":"number","format":"double","default":0.0},"input":{"description":"Input price per 1M tokens","type":"number","format":"double","default":0.0},"output":{"description":"Output price per 1M tokens","type":"number","format":"double","default":0.0}}},"ModelRouteConfig":{"description":"Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"hint":{"description":"Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")","type":"string"},"level":{"type":["string","null"]},"model":{"description":"Model to use with that provider","type":"string"},"provider":{"description":"Provider to route to (must match a known provider name)","type":"string"},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true,"required":["hint","provider","model"]},"ModelSettings":{"description":"A model level plus explicit parameter overrides in `[model_settings.\"\"]`.","type":"object","properties":{"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"level":{"type":["string","null"]},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true},"MultimodalConfig":{"description":"Multimodal (image) handling configuration (`[multimodal]` section).","type":"object","properties":{"allow_remote_fetch":{"description":"Allow fetching remote image URLs (http/https). Enabled by default.","type":"boolean","default":true},"max_image_size_mb":{"description":"Maximum image payload size in MiB before base64 encoding.","type":"integer","format":"uint","default":5,"minimum":0},"max_images":{"description":"Maximum number of image attachments accepted per request.","type":"integer","format":"uint","default":4,"minimum":0}}},"NextcloudTalkConfig":{"description":"Nextcloud Talk bot configuration (webhook receive + OCS send API).","type":"object","properties":{"allowed_users":{"description":"Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Bot app token used for OCS API bearer auth.","type":"string"},"base_url":{"description":"Nextcloud base URL (e.g. \"https://cloud.example.com\").","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"webhook_secret":{"description":"Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).","type":["string","null"],"default":null}},"required":["base_url","app_token"]},"NgrokTunnelConfig":{"type":"object","properties":{"auth_token":{"description":"ngrok auth token","type":"string"},"domain":{"description":"Optional custom domain","type":["string","null"]}},"required":["auth_token"]},"NodeServerConfig":{"description":"Node daemon runtime config used by `prx-node`.","type":"object","properties":{"allowed_commands":{"description":"Command allowlist matched on first token. Default: empty, which allows any\ncommand from an authenticated caller; `[\"*\"]` means the same.","type":"array","default":[],"items":{"type":"string"}},"bearer_token":{"description":"Required bearer token for /rpc.","type":"string","default":""},"blocked_commands":{"description":"Command denylist matched on first token. Always enforced.","type":"array","default":[],"items":{"type":"string"}},"exec_timeout_ms":{"description":"Default command timeout in milliseconds.","type":"integer","format":"uint64","default":15000,"minimum":0},"hmac_secret":{"description":"Optional HMAC signing secret.","type":["string","null"],"default":null},"listen_addr":{"description":"Listen address for node daemon.","type":"string","default":"127.0.0.1:8787"},"max_concurrent_tasks":{"description":"Maximum number of concurrent async command tasks.","type":"integer","format":"uint","default":8,"minimum":0},"max_output_bytes":{"description":"Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.","type":"integer","format":"uint","default":1048576,"minimum":0},"sandbox_root":{"description":"Sandbox root directory for read/write/cwd constraints.","type":"string","default":"."},"task_result_ttl_ms":{"description":"TTL for completed task results in milliseconds.","type":"integer","format":"uint64","default":3600000,"minimum":0},"tls_cert":{"description":"TLS certificate path (PEM).","type":["string","null"],"default":null},"tls_key":{"description":"TLS private key path (PEM).","type":["string","null"],"default":null},"tls_required":{"description":"Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.","type":"boolean","default":true}}},"NodesConfig":{"description":"Remote node proxy configuration for core-side RPC calls and node daemon defaults.","type":"object","properties":{"nodes":{"description":"Configured remote nodes.","type":"array","default":[],"items":{"$ref":"#/$defs/RemoteNodeConfig"}},"request_timeout_ms":{"description":"Default request timeout for node RPC calls.","type":"integer","format":"uint64","default":15000,"minimum":0},"retry_max":{"description":"Default max retries for node RPC calls.","type":"integer","format":"uint8","default":2,"maximum":255,"minimum":0},"server":{"description":"Embedded node server defaults used by `prx-node`.","$ref":"#/$defs/NodeServerConfig","default":{"allowed_commands":[],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}}},"ObservabilityConfig":{"description":"Observability backend configuration (`[observability]` section).","type":"object","properties":{"backend":{"description":"\"none\" | \"log\" | \"prometheus\" | \"otel\"","type":"string","default":"none"},"otel_endpoint":{"description":"OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".","type":["string","null"],"default":null},"otel_service_name":{"description":"Service name reported to the OTel collector. Defaults to \"prx\".","type":["string","null"],"default":null}}},"OllamaProviderConfig":{"description":"Ollama-specific request options (`[providers.ollama]`).","type":"object","properties":{"num_ctx":{"description":"Explicit context window sent as Ollama `options.num_ctx`.","type":["integer","null"],"format":"uint","default":null,"minimum":0}}},"OsPagingConfig":{"description":"Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.","type":"object","properties":{"eviction_threshold":{"description":"Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.","type":"number","format":"double","default":0.7},"keep_recent_messages":{"description":"Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).","type":"integer","format":"uint","default":12,"minimum":0},"max_recalled_pages":{"description":"Maximum number of evicted pages (document chunks) recalled per turn.","type":"integer","format":"uint","default":10,"minimum":0},"proactive_retrieval":{"description":"Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.","type":"boolean","default":true},"retrieval_injection_role":{"description":"Role under which recalled pages are injected.","$ref":"#/$defs/RetrievalInjectionRole","default":"system"}}},"PluginsConfig":{"description":"WASM plugin runtime configuration.","type":"object","properties":{"enabled":{"description":"Load WASM plugins from `/plugins`. Default: `false`.","type":"boolean","default":false}},"additionalProperties":false},"ProviderModelConfig":{"description":"One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.","type":"object","properties":{"context_window":{"description":"The model's context window in tokens.","type":["integer","null"],"format":"uint32","minimum":0},"model":{"description":"The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.","type":["string","null"]},"native_tools":{"description":"Whether the model accepts native tool calls.","type":["boolean","null"]},"operations":{"description":"The complete list of operations the model executes; every operation not\nlisted is unsupported.","type":["array","null"],"items":{"$ref":"#/$defs/ModelOperationSetting"}},"provider":{"description":"The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.","type":"string"},"streaming":{"description":"Whether the model streams responses.","type":["boolean","null"]},"structured_output":{"description":"Whether the model honours a JSON-schema response format.","type":["boolean","null"]},"tool_call_dialect":{"description":"The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema_dialect":{"description":"The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]},"vision_input":{"description":"Whether the model accepts image input.","type":["boolean","null"]}},"required":["provider"]},"ProviderToolDialectConfig":{"description":"One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.","type":"object","properties":{"model":{"description":"The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.","type":["string","null"]},"provider":{"description":"The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.","type":"string"},"tool_call":{"description":"The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema":{"description":"The tool-schema dialect the endpoint accepts.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]}},"required":["provider"]},"ProvidersConfig":{"description":"Provider-specific runtime configuration (`[providers]`).","type":"object","properties":{"models":{"description":"Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.","type":"array","items":{"$ref":"#/$defs/ProviderModelConfig"}},"ollama":{"description":"Ollama-specific request options (`[providers.ollama]`).","$ref":"#/$defs/OllamaProviderConfig","default":{"num_ctx":null}},"tool_dialects":{"description":"Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).","type":"array","items":{"$ref":"#/$defs/ProviderToolDialectConfig"}}}},"ProxyConfig":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).","type":"object","properties":{"all_proxy":{"description":"Fallback proxy URL for all schemes.","type":["string","null"],"default":null},"http_proxy":{"description":"Proxy URL for HTTP requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"https_proxy":{"description":"Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"no_proxy":{"description":"No-proxy bypass list. Same format as NO_PROXY.","type":"array","default":[],"items":{"type":"string"}},"scope":{"description":"Proxy application scope.","$ref":"#/$defs/ProxyScope","default":"prx"},"services":{"description":"Service selectors used when scope = \"services\".","type":"array","default":[],"items":{"type":"string"}}}},"ProxyScope":{"description":"Proxy application scope — determines which outbound traffic uses the proxy.","oneOf":[{"description":"Use system environment proxy variables only.","type":"string","const":"environment"},{"description":"Apply proxy to all OpenPRX-managed HTTP traffic (default).","type":"string","const":"prx"},{"description":"Apply proxy only to explicitly listed service selectors.","type":"string","const":"services"}]},"QQConfig":{"description":"QQ Official Bot configuration (Tencent QQ Bot SDK)","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs. Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from QQ Bot developer console","type":"string"},"app_secret":{"description":"App Secret from QQ Bot developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["app_id","app_secret"]},"QueryClassificationConfig":{"description":"Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.","type":"object","properties":{"rules":{"description":"Classification rules evaluated in priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/ClassificationRule"}}}},"RamfluxAccountConfig":{"description":"Persona for one ramflux AI account. Missing fields fall back to the global agent.","type":"object","properties":{"cross_conversation_retrieval":{"description":"Cross-conversation memory retrieval. Off unless the owner sets it.","type":"boolean","default":false},"model":{"type":["string","null"],"default":null},"provider":{"type":["string","null"],"default":null},"scope_profile":{"type":["string","null"],"default":null},"system_prompt_file":{"description":"Path to a system-prompt file. Relative paths are resolved from the workspace.","type":["string","null"],"default":null}},"additionalProperties":false},"RamfluxAttachmentFetch":{"description":"Per-turn caps for `attachment.fetch`.","type":"object","properties":{"max_bytes":{"type":"integer","format":"uint64","default":5242880,"minimum":0},"max_per_turn":{"type":"integer","format":"uint8","default":4,"maximum":255,"minimum":0}},"additionalProperties":false},"RamfluxAuthorizationMode":{"description":"How prx combines its own setting with `bridge.hello.authorization`.","oneOf":[{"description":"Use the agent-host value. Until hello arrives, the effective mode is supervised.","type":"string","const":"follow_rf"},{"description":"Always supervised, even when the agent-host declares full.","type":"string","const":"supervised"},{"description":"Full only when the agent-host also declares full. Config alone never yields full.","type":"string","const":"full"}]},"RamfluxConfig":{"description":"Local ramflux agent-host bridge (`[channels_config.ramflux]`).","type":"object","properties":{"accounts":{"type":"object","additionalProperties":{"$ref":"#/$defs/RamfluxAccountConfig"},"default":{}},"allowed_block_types":{"type":"array","default":["Text","Markdown","Heading","KeyValue","Metric","List","TableFallback","Form","Input","Select","Progress","LogStream","Warning","Error","Success","Approval","ActionGroup","FilePreview","Fallback"],"items":{"type":"string"}},"attachment_fetch":{"$ref":"#/$defs/RamfluxAttachmentFetch","default":{"max_bytes":5242880,"max_per_turn":4}},"authorization_mode":{"$ref":"#/$defs/RamfluxAuthorizationMode","default":"follow_rf"},"encrypt_at_rest":{"type":"boolean","default":true},"max_in_flight_per_conversation":{"type":"integer","format":"uint8","default":1,"maximum":255,"minimum":0},"on_new_message":{"$ref":"#/$defs/RamfluxOnNewMessage","default":"queue"},"socket_path":{"description":"Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.","type":["string","null"],"default":null},"surface_limits":{"$ref":"#/$defs/RamfluxSurfaceLimits","default":{"max_actions":16,"max_blocks":32,"max_bytes":65536}},"turn_wall_clock_secs":{"description":"Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.","type":"integer","format":"uint64","default":120,"minimum":0}},"additionalProperties":false},"RamfluxOnNewMessage":{"description":"What to do with a new inbound message while a turn for that conversation is running.","type":"string","enum":["queue","interrupt"]},"RamfluxSurfaceLimits":{"description":"Limits for `reply.surface` blocks and actions.","type":"object","properties":{"max_actions":{"type":"integer","format":"uint32","default":16,"minimum":0},"max_blocks":{"type":"integer","format":"uint32","default":32,"minimum":0},"max_bytes":{"type":"integer","format":"uint32","default":65536,"minimum":0}},"additionalProperties":false},"ReliabilityCircuitBreakerConfig":{"description":"Process-local provider circuit policy (`[reliability.circuit_breaker]`).","type":"object","properties":{"enabled":{"description":"Enable protection for factory-built provider chains.","type":"boolean","default":true},"failure_threshold":{"description":"Consecutive transient failures that open a circuit (at least 1).","type":"integer","format":"uint32","default":5,"minimum":0},"max_open_secs":{"description":"Maximum doubled window, between open_secs and 3600 seconds.","type":"integer","format":"uint64","default":300,"minimum":0},"open_secs":{"description":"Initial open window in seconds (at least 1).","type":"integer","format":"uint64","default":30,"minimum":0}}},"ReliabilityConfig":{"description":"Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.","type":"object","properties":{"acknowledge_single_provider_risk":{"description":"Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.","type":"boolean","default":false},"api_keys":{"description":"Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.","type":"array","default":[],"items":{"type":"string"}},"channel_initial_backoff_secs":{"description":"Initial backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":2,"minimum":0},"channel_max_backoff_secs":{"description":"Max backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":60,"minimum":0},"circuit_breaker":{"description":"Per-provider consecutive failure protection.","$ref":"#/$defs/ReliabilityCircuitBreakerConfig","default":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30}},"fallback_providers":{"description":"Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).","type":"array","default":[],"items":{"type":"string"}},"model_fallbacks":{"description":"Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`","type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"default":{}},"provider_backoff_ms":{"description":"Base backoff (ms) for provider retry delay.","type":"integer","format":"uint64","default":500,"minimum":0},"provider_retries":{"description":"Retries per provider before failing over.","type":"integer","format":"uint32","default":2,"minimum":0},"scheduler_poll_secs":{"description":"Scheduler polling cadence in seconds.","type":"integer","format":"uint64","default":15,"minimum":0},"scheduler_retries":{"description":"Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.","type":"integer","format":"uint32","default":2,"minimum":0}}},"RemoteNodeConfig":{"description":"A remote node target for core-side node proxy calls.","type":"object","properties":{"bearer_token":{"description":"Bearer token for node RPC authentication.","type":"string"},"endpoint":{"description":"Base endpoint (e.g. \"http://127.0.0.1:8787\").","type":"string"},"hmac_secret":{"description":"Optional request signing key (HMAC-SHA256).","type":["string","null"],"default":null},"id":{"description":"Stable node ID used by the nodes tool.","type":"string"},"retry_max":{"description":"Optional per-node retry override.","type":["integer","null"],"format":"uint8","default":null,"maximum":255,"minimum":0},"timeout_ms":{"description":"Optional per-node timeout override.","type":["integer","null"],"format":"uint64","default":null,"minimum":0}},"required":["id","endpoint","bearer_token"]},"RetrievalInjectionRole":{"description":"Where recalled context pages are injected back into the request.","oneOf":[{"description":"Inject recalled pages as a leading `system` message (not user-visible).","type":"string","const":"system"},{"description":"Inject recalled pages as a leading `user` message.","type":"string","const":"user"}]},"RouterConfig":{"description":"Heuristic LLM router configuration (`[router]` section).","type":"object","properties":{"alpha":{"description":"Similarity score weight. Phase 1 keeps this at `0.0`.","type":"number","format":"float","default":0.0},"beta":{"description":"Capability score weight.","type":"number","format":"float","default":0.5},"delta":{"description":"Cost penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"epsilon":{"description":"Latency penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"gamma":{"description":"Elo score weight.","type":"number","format":"float","default":0.30000001192092896},"knn_k":{"description":"Number of nearest neighbors considered for voting. Default: `7`.","type":"integer","format":"uint","default":7,"minimum":0},"knn_min_records":{"description":"Minimum history records before KNN affects routing. Default: `10`.","type":"integer","format":"uint","default":10,"minimum":0},"models":{"description":"Candidate model registry.","type":"array","default":[],"items":{"$ref":"#/$defs/RouterModelConfig"}}}},"RouterModelConfig":{"description":"Static router metadata for one model candidate.","type":"object","properties":{"categories":{"description":"Capability categories such as `conversation`, `code`, or `analysis`.","type":"array","default":[],"items":{"type":"string"}},"cost_per_million_tokens":{"description":"USD cost per million tokens.","type":"number","format":"float","default":0.0},"elo_rating":{"description":"Initial Elo rating.","type":"number","format":"float","default":1000.0},"latency_ms":{"description":"Average latency in milliseconds.","type":"integer","format":"uint32","default":2000,"minimum":0},"max_context":{"description":"Maximum context window in tokens.","type":"integer","format":"uint","default":1000000,"minimum":0},"model_id":{"description":"Model identifier without provider prefix.","type":"string"},"provider":{"description":"Provider identifier.","type":"string"},"reserved_output_tokens":{"description":"Output tokens reserved for this model when planning input context.","type":["integer","null"],"format":"uint","minimum":0}},"required":["model_id","provider"]},"RuntimeConfig":{"description":"Runtime adapter configuration (`[runtime]` section).","type":"object","properties":{"codex_reasoning_effort":{"description":"Codex reasoning effort","type":["string","null"],"default":null},"codex_stream_idle_timeout_secs":{"description":"Codex stream idle timeout in seconds","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"docker":{"description":"Docker runtime settings (used when `kind = \"docker\"`).","$ref":"#/$defs/DockerRuntimeConfig","default":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true}},"idle_hang_secs":{"description":"Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"kind":{"description":"Runtime kind (`native` | `docker`).","type":"string","default":"native"},"long_task_warn_secs":{"description":"Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"managed_cgroup_root":{"description":"Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.","type":["string","null"],"default":null},"max_blocking_threads":{"description":"Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"reasoning_enabled":{"description":"Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported","type":["boolean","null"],"default":null},"shell_env_allowlist":{"description":"Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.","type":"array","default":[],"items":{"type":"string"}},"workdir":{"description":"Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.","type":["string","null"],"default":null}}},"SchedulerConfig":{"description":"Scheduler configuration for periodic task execution (`[scheduler]` section).","type":"object","properties":{"claim_lease_secs":{"description":"Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.","type":"integer","format":"uint64","default":90,"minimum":0},"max_tasks":{"description":"Maximum number of persisted scheduled tasks.","type":"integer","format":"uint","default":64,"minimum":0}}},"ScopeConfig":{"description":"Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```","type":"object","properties":{"assign_owners":{"description":"Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.","type":"array","default":[],"items":{"type":"string"}},"default":{"description":"Default action when no rule matches: \"allow\" (default) or \"deny\".","$ref":"#/$defs/ScopeDefault","default":"allow"},"rules":{"description":"Ordered list of scope rules evaluated top-to-bottom.","type":"array","default":[],"items":{"$ref":"#/$defs/ScopeRule"}}}},"ScopeDefault":{"description":"What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.","oneOf":[{"description":"Unmatched tool calls are allowed (the default).","type":"string","const":"allow"},{"description":"Unmatched tool calls are refused.","type":"string","const":"deny"}]},"ScopeRule":{"description":"A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.","type":"object","properties":{"assign_allow":{"description":"Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".","type":"array","default":[],"items":{"type":"string"}},"assign_deny":{"description":"Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.","type":"array","default":[],"items":{"type":"string"}},"channel":{"description":"Match by channel name: \"signal\", \"telegram\", \"discord\", etc.","type":["string","null"]},"chat_type":{"description":"Match by chat type: \"direct\", \"group\", or \"*\" for any type.","type":["string","null"]},"send_allow":{"description":"Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.","type":"array","default":[],"items":{"type":"string"}},"send_deny":{"description":"Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.","type":"array","default":[],"items":{"type":"string"}},"tools_allow":{"description":"Tool whitelist: only these tools are allowed (empty = all tools permitted).","type":"array","default":[],"items":{"type":"string"}},"tools_deny":{"description":"Tool blacklist: these tools are denied regardless of allow list.","type":"array","default":[],"items":{"type":"string"}},"user":{"description":"Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.","type":["string","null"]}}},"SecretsConfig":{"description":"Secrets encryption configuration (`[secrets]` section).","type":"object","properties":{"encrypt":{"description":"Enable encryption for API keys and tokens in config.toml","type":"boolean","default":true}}},"SecurityConfig":{"description":"Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.","type":"object","properties":{"audit":{"description":"Audit logging configuration","$ref":"#/$defs/AuditConfig","default":{"log_path":"audit.log","max_size_mb":100}},"workspace_hooks":{"description":"Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.","$ref":"#/$defs/WorkspaceHooks"}}},"SelfSystemConfig":{"description":"Self-system experimental automation config (`[self_system]`).","type":"object","properties":{"evolution_config_path":{"description":"Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG)","type":["string","null"],"default":null},"evolution_debug_raw":{"description":"Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW)","type":"boolean","default":false},"evolution_interval_hours":{"description":"Evolution scheduler interval in hours (daemon mode).","type":"integer","format":"uint32","default":24,"minimum":0},"evolution_judge_timeout_secs":{"description":"Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.","type":"integer","format":"uint64","default":180,"minimum":0},"evolution_model_max_micro_usd":{"description":"Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.","type":"integer","format":"uint64","default":0,"minimum":0},"evolution_model_max_tokens":{"description":"Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.","type":"integer","format":"uint64","default":16384,"minimum":0},"fitness":{"description":"Daily fitness snapshot policy.","$ref":"#/$defs/FitnessConfig","default":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"}},"fitness_interval_hours":{"description":"Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.","type":"integer","format":"uint64","default":24,"minimum":0}}},"SessionsSpawnConfig":{"description":"Sessions spawn configuration (`[sessions_spawn]` section).","type":"object","properties":{"cleanup_on_complete":{"description":"Remove worker workspace directory after process-mode completion.","type":"boolean","default":true},"default_mode":{"description":"Default execution mode for sessions_spawn (`task` or `process`).","type":"string","default":"task"},"process_memory_strategy":{"description":"Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.","type":"string","default":"shared_fabric"},"worker_workspace_root":{"description":"Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.","type":["string","null"],"default":null}}},"SignalConfig":{"type":"object","properties":{"account":{"description":"E.164 phone number of the signal-cli account (e.g. \"+1234567890\").","type":"string"},"allowed_from":{"description":"Allowed sender phone numbers (E.164) or \"*\" for all.","type":"array","default":[],"items":{"type":"string"}},"cli_path":{"description":"Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).","type":["string","null"],"default":null},"daemon_http_port":{"description":"Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"daemon_mode":{"description":"Deprecated: ignored. Accepted for backward compatibility with older config files.","type":["boolean","null"],"default":null},"data_dir":{"description":"signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_id":{"description":"Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group","type":["string","null"],"default":null},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"http_url":{"description":"Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.","type":"string","default":"http://localhost:8080"},"ignore_attachments":{"description":"Skip messages that are attachment-only (no text body).","type":"boolean","default":false},"ignore_stories":{"description":"Skip incoming story messages.","type":"boolean","default":false},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"mode":{"description":"Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.","type":["string","null"],"default":null},"startup_timeout_ms":{"description":"Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.","type":"integer","format":"uint64","default":30000,"minimum":0},"storm_protection":{"description":"Signal ingress storm protection controls.","$ref":"#/$defs/SignalStormProtectionConfig","default":{"abnormal_threshold":10,"abnormal_window_secs":60,"breaker_duration_secs":300,"dedupe_ttl_secs":60,"min_reply_interval_secs":2}}},"required":["account"]},"SignalStormProtectionConfig":{"type":"object","properties":{"abnormal_threshold":{"description":"Non-user event threshold within `abnormal_window_secs` before tripping the breaker.","type":"integer","format":"uint","default":10,"minimum":0},"abnormal_window_secs":{"description":"Sliding window in seconds for non-user event counting.","type":"integer","format":"uint64","default":60,"minimum":0},"breaker_duration_secs":{"description":"Circuit breaker duration in seconds after threshold is reached.","type":"integer","format":"uint64","default":300,"minimum":0},"dedupe_ttl_secs":{"description":"Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.","type":"integer","format":"uint64","default":60,"minimum":0},"min_reply_interval_secs":{"description":"Minimum interval in seconds between replies for the same `(channel + reply_target)`.","type":"integer","format":"uint64","default":2,"minimum":0}}},"SkillRagConfig":{"description":"Dynamic skill retrieval configuration (`[skill_rag]` section).","type":"object","properties":{"top_k":{"description":"How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).","type":"integer","format":"uint","default":32,"minimum":0}}},"SkillSuiteRegistration":{"description":"The frozen suite that governs one skill's proposals.","type":"object","properties":{"skill_id":{"description":"The skill the suite governs.","type":"string"},"suite_digest":{"description":"SHA-256 digest (64 lowercase hex digits) of the frozen suite.","type":"string"}},"additionalProperties":false,"required":["skill_id","suite_digest"]},"SkillsConfig":{"description":"Skills loading configuration (`[skills]` section).","type":"object","properties":{"open_skills_dir":{"description":"Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.","type":["string","null"],"default":null},"openclaw_skills_dir":{"description":"Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.","type":["string","null"],"default":null}}},"SkillsLifecycleConfig":{"description":"`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.","type":"object","properties":{"allow_executable_proposals":{"description":"Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.","type":"boolean","default":false},"enabled":{"description":"Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.","type":"boolean","default":false},"max_concurrent_evaluations":{"description":"Most evaluations running at once.","type":"integer","format":"uint32","default":1,"minimum":0},"max_edit_fraction":{"description":"Edit budget of a proposal as a fraction of the skill body, in (0, 1].","type":"number","format":"double","default":0.2},"max_edit_tokens":{"description":"Edit budget of a proposal, in tokens.","type":"integer","format":"uint64","default":300,"minimum":0},"max_proposals_per_cycle":{"description":"Most proposals one cycle may start.","type":"integer","format":"uint32","default":1,"minimum":0},"min_cases_floor":{"description":"Smallest `min_cases` a governing suite may declare. Below 3 is refused.","type":"integer","format":"uint32","default":3,"minimum":0},"mode":{"description":"`draft_only`, `shadow` or `auto`.","$ref":"#/$defs/SkillsLifecycleModeConfig","default":"draft_only"},"owner_scope":{"description":"The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.","type":["string","null"],"default":null},"require_holdout":{"description":"A governing suite must have a holdout split. `false` is refused.","type":"boolean","default":true},"storage_dir":{"description":"Store location under the workspace. Only the default is supported.","type":"string","default":"self/skill-lifecycle"},"suites":{"description":"The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.","type":"array","default":[],"items":{"$ref":"#/$defs/SkillSuiteRegistration"}}},"additionalProperties":false},"SkillsLifecycleModeConfig":{"description":"What the lifecycle may do. Mirrors `LifecycleMode`.","oneOf":[{"description":"Drafts and reviews only.","type":"string","const":"draft_only"},{"description":"Drafts plus evaluation and gating; never publishes.","type":"string","const":"shadow"},{"description":"Publishes an eligible proposal after every gate.","type":"string","const":"auto"}]},"SlackConfig":{"description":"Slack bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Slack user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Slack app-level token for Socket Mode (xapp-...).","type":["string","null"]},"bot_token":{"description":"Slack bot OAuth token (xoxb-...).","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["bot_token"]},"SmartGroupConfig":{"description":"Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).","type":"object","properties":{"classifier_max_context_messages":{"description":"How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.","type":"integer","format":"uint","default":3,"minimum":0},"classifier_model":{"description":"Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.","type":"string","default":""},"classifier_provider":{"description":"Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.","type":"string","default":""},"classifier_temperature":{"description":"Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).","type":"number","format":"double","default":0.0},"classifier_timeout_secs":{"description":"Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.","type":"integer","format":"uint64","default":5,"minimum":0}}},"StorageConfig":{"description":"Persistent storage configuration (`[storage]` section).","type":"object","properties":{"provider":{"description":"Storage provider settings (e.g. sqlite, postgres).","$ref":"#/$defs/StorageProviderSection","default":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}}},"StorageProviderConfig":{"description":"Storage provider backend configuration (e.g. postgres connection details).","type":"object","properties":{"connect_timeout_secs":{"description":"Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"db_url":{"description":"Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.","type":["string","null"],"default":null},"pool_max_size":{"description":"Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.","type":"integer","format":"uint","default":32,"minimum":0},"provider":{"description":"Storage engine key (e.g. \"postgres\", \"sqlite\").","type":"string","default":""},"schema":{"description":"Database schema for SQL backends.","type":"string","default":"public"},"table":{"description":"Table name for memory entries.","type":"string","default":"memories"}}},"StorageProviderSection":{"description":"Wrapper for the storage provider configuration section.","type":"object","properties":{"config":{"description":"Storage provider backend settings.","$ref":"#/$defs/StorageProviderConfig","default":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"StreamMode":{"description":"Streaming mode for channels that support progressive message updates.","oneOf":[{"description":"No streaming -- send the complete response as a single message (default).","type":"string","const":"off"},{"description":"Update a draft message with every flush interval.","type":"string","const":"partial"}]},"TailscaleTunnelConfig":{"type":"object","properties":{"funnel":{"description":"Use Tailscale Funnel (public internet) vs Serve (tailnet only)","type":"boolean","default":false},"hostname":{"description":"Optional hostname override","type":["string","null"]}}},"TaskRoutingConfig":{"description":"Lightweight pre-LLM task routing.","type":"object","properties":{"default_intent":{"description":"Fallback intent when no rule matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"rules":{"description":"Rules evaluated in descending priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/TaskRoutingRule"}}}},"TaskRoutingIntentConfig":{"description":"Task-routing default and rule intent.","type":"string","enum":["simple","delegate","stream"]},"TaskRoutingRule":{"description":"A single task-routing rule.","type":"object","properties":{"intent":{"description":"Route intent to apply when a keyword matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"model_hint":{"description":"Optional model hint/raw model for non-delegated requests.","type":["string","null"],"default":null},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0},"sub_agent_model":{"description":"Optional raw sub-agent model override for delegated tasks.","type":["string","null"],"default":null}}},"TelegramConfig":{"description":"Telegram bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Telegram user IDs or usernames. Empty = deny all.","type":"array","items":{"type":"string"}},"bot_token":{"description":"Telegram Bot API token (from @BotFather).","type":"string"},"draft_update_interval_ms":{"description":"Minimum interval (ms) between draft message edits to avoid rate limits.","type":"integer","format":"uint64","default":1000,"minimum":0},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"interrupt_on_new_message":{"description":"When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.","type":"boolean","default":false},"stream_mode":{"description":"Streaming mode for progressive response delivery via message edits.","$ref":"#/$defs/StreamMode","default":"off"}},"required":["bot_token","allowed_users"]},"ToolCallDialectSetting":{"description":"The tool-call grammars an operator may declare for an endpoint.","oneOf":[{"description":"Only the native `tool_calls` array is a tool call (the default).","type":"string","const":"native"},{"description":"Additionally read `{json}` from the content,\nfor a tool name the request registered.","type":"string","const":"xml_function_tags"}]},"ToolSchemaDialectSetting":{"description":"The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.","oneOf":[{"description":"The published document, byte for byte (the default).","type":"string","const":"raw"},{"description":"The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.","type":"string","const":"no_root_combinators"}]},"ToolTieringConfig":{"description":"Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.","type":"object","properties":{"always_exclude":{"description":"Tool names excluded from capability publication.","type":"array","default":[],"items":{"type":"string"}},"always_include":{"description":"Tool names preferred for direct publication, subject to admission gates.","type":"array","default":[],"items":{"type":"string"}},"channel_exclude":{"description":"Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefault: empty (nothing is hidden); list tool names to hide them on channels.","type":"array","default":[],"items":{"type":"string"}},"defer_unlisted":{"description":"Operator option: publish only the core tools plus `always_include` and\nleave every other tool behind `capability_search` and its exact name.\nDefault: false (every available tool is published to the model).","type":"boolean","default":false}}},"TunnelConfig":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.","type":"object","properties":{"cloudflare":{"description":"Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).","anyOf":[{"$ref":"#/$defs/CloudflareTunnelConfig"},{"type":"null"}],"default":null},"custom":{"description":"Custom tunnel command configuration (used when `provider = \"custom\"`).","anyOf":[{"$ref":"#/$defs/CustomTunnelConfig"},{"type":"null"}],"default":null},"ngrok":{"description":"ngrok tunnel configuration (used when `provider = \"ngrok\"`).","anyOf":[{"$ref":"#/$defs/NgrokTunnelConfig"},{"type":"null"}],"default":null},"provider":{"description":"Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.","type":"string","default":"none"},"tailscale":{"description":"Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).","anyOf":[{"$ref":"#/$defs/TailscaleTunnelConfig"},{"type":"null"}],"default":null}}},"UserPolicyConfig":{"description":"Startup user policy entry (`[[user_policies]]`).","type":"object","properties":{"blocked_patterns":{"type":"array","default":[],"items":{"type":"string"}},"projects":{"type":"array","default":[],"items":{"type":"string"}},"role":{"type":"string","default":"guest"},"user_id":{"type":"string"},"visibility_ceiling":{"type":"string","default":"private"}},"required":["user_id"]},"WacliConfig":{"description":"wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```","type":"object","properties":{"allow_unsigned_loopback":{"description":"Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).","type":"boolean","default":false},"allowed_from":{"description":"Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.","type":"array","default":["*"],"items":{"type":"string"}},"bot_jid":{"description":"Bot's own JID, used for reply-to-bot mention detection.","type":["string","null"],"default":null},"bot_lid":{"description":"The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.","type":["string","null"],"default":null},"bot_number":{"description":"Bot's own phone number (digits), used for `@` mention detection.","type":["string","null"],"default":null},"cli_path":{"description":"Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.","type":["string","null"],"default":null},"group_reply_mode":{"description":"Smart group-reply mode. When `None`, derived from `mention_only`.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"host":{"description":"REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].","type":["string","null"],"writeOnly":true},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"outbound_media_workspace_only":{"description":"Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.","type":"boolean","default":false},"port":{"description":"REMOVED: legacy JSON-RPC daemon port. See `host`.","type":["integer","null"],"format":"uint16","maximum":65535,"minimum":0,"writeOnly":true},"self_chat_mode":{"description":"Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.","type":"boolean","default":false},"store_dir":{"description":"wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.","type":["string","null"],"default":null},"webhook_listen":{"description":"Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").","type":"string","default":"127.0.0.1:16868"},"webhook_path":{"description":"HTTP path the webhook server serves (default: \"/wacli\").","type":"string","default":"/wacli"},"webhook_secret":{"description":"HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.","type":["string","null"],"default":null}}},"WebSearchConfig":{"description":"Web search tool configuration (`[web_search]` section).","type":"object","properties":{"brave_api_key":{"description":"Brave Search API key (required if provider is \"brave\")","type":["string","null"],"default":null},"fetch_max_chars":{"description":"Maximum characters returned by `web_fetch` (default 10000)","type":"integer","format":"uint","default":50000,"minimum":0},"max_results":{"description":"Maximum results per search (1-20)","type":"integer","format":"uint","default":15,"minimum":0},"provider":{"description":"Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)","type":"string","default":"duckduckgo"},"timeout_secs":{"description":"Request timeout in seconds","type":"integer","format":"uint64","default":15,"minimum":0}}},"WebhookConfig":{"description":"Webhook channel configuration.","type":"object","properties":{"port":{"description":"Port to listen on for incoming webhooks.","type":"integer","format":"uint16","maximum":65535,"minimum":0},"secret":{"description":"Optional shared secret for webhook signature verification.","type":["string","null"]}},"required":["port"]},"WhatsAppConfig":{"description":"WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.","type":"object","properties":{"access_token":{"description":"Access token from Meta Business Suite (Cloud API mode)","type":["string","null"],"default":null},"allowed_numbers":{"description":"Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"app_secret":{"description":"App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"pair_code":{"description":"Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one","type":["string","null"],"default":null},"pair_phone":{"description":"Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used","type":["string","null"],"default":null},"phone_number_id":{"description":"Phone number ID from Meta Business API (Cloud API mode)","type":["string","null"],"default":null},"read_pool_size":{"description":"Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"session_path":{"description":"Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs","type":["string","null"],"default":null},"verify_token":{"description":"Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode","type":["string","null"],"default":null},"ws_url":{"description":"WebSocket URL override (replaces WHATSAPP_WS_URL)","type":["string","null"],"default":null}}},"WorkspaceHooks":{"description":"Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).","oneOf":[{"description":"They do not run (the default); `prx doctor` and `hooks_status` say so.","type":"string","const":"off"},{"description":"They run, in a cleared environment and a dedicated directory beside\n`config.toml`.","type":"string","const":"on"}]},"WorkspaceMcpServers":{"description":"Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).","oneOf":[{"description":"None: a workspace file may only narrow the servers defined in\n`config.toml`.","type":"string","const":"off"},{"description":"HTTP servers (still refused when they target a private address).","type":"string","const":"http_only"},{"description":"HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.","type":"string","const":"stdio"}]},"XinConfig":{"description":"Configuration for the xin autonomous task engine (`[xin]`).","type":"object","properties":{"adopt_legacy_tasks":{"description":"Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).","type":"boolean","default":false},"interval_minutes":{"description":"Tick interval in minutes (minimum 1). Default: 5.","type":"integer","format":"uint32","default":5,"minimum":0},"stale_timeout_minutes":{"description":"Minutes after which a running task is marked stale. Default: 60.","type":"integer","format":"uint32","default":60,"minimum":0}}},"AgentMessaging":{"description":"Owner-controlled inbound session messaging (enabled unless explicitly off).","type":"object","properties":{"inbound":{"type":"boolean","default":true}}}}} From 5a32825d0629ad1d63d8123a1d4cbc90627cd983 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:11:14 +0400 Subject: [PATCH 0154/1567] feat(tools): call a deferred tool by its exact name A call to a tool the operator deferred is admitted under the same rules as a capability_search hit, without a prior search, and the tool is declared on the following request. Before, such a call ended in 'not exposed for this turn'. --- .../search_tool/discovery_admission.rs | 49 +++++++++++++++---- 1 file changed, 39 insertions(+), 10 deletions(-) diff --git a/src/tools/capability/search_tool/discovery_admission.rs b/src/tools/capability/search_tool/discovery_admission.rs index b3d0cfa39..ce3c8bf79 100644 --- a/src/tools/capability/search_tool/discovery_admission.rs +++ b/src/tools/capability/search_tool/discovery_admission.rs @@ -314,23 +314,52 @@ fn direct_discovery_ids(port: &dyn TurnSurfacePort) -> BTreeSet { .collect() } +/// The reference of a deferred capability named by its exact public name or +/// capability ID, when this turn's search could have returned it. +fn exact_deferred_reference( + port: &dyn TurnSurfacePort, + proof: &dyn TurnSourceProof, + name_or_id: &str, +) -> anyhow::Result> { + let entries = discovery_entries(port, proof)?; + let view = port.catalog_view(); + Ok(entries + .values() + .filter(|discovered| discovered.searchable && !discovered.core) + .find(|discovered| { + view.entry_any(&discovered.reference.id) + .is_some_and(|entry| entry.public_name == name_or_id || entry.id.as_str() == name_or_id) + }) + .map(|discovered| discovered.reference.clone())) +} + /// Recheck one actually returned offer against the turn's publication rules. pub(crate) fn prepare_discovered_tool( port: &dyn TurnSurfacePort, proof: &dyn TurnSourceProof, name_or_id: &str, ) -> anyhow::Result> { - let Some(offers) = port.discovery().offers.get() else { - return Ok(None); - }; - let reference = offers.lock().find(name_or_id); - let Some(reference) = reference else { - return Ok(None); + let offered = port + .discovery() + .offers + .get() + .and_then(|offers| offers.lock().find(name_or_id)); + let reference = match offered { + Some(reference) => { + anyhow::ensure!( + capability_search_spec(port, proof)?.is_some(), + "turn no longer permits discovered capability admission" + ); + reference + } + // A deferred tool called by its exact name needs no prior search. + // It must be one this turn's search could have returned, so it goes + // through the same eligibility and admission rules as a search hit. + None => match exact_deferred_reference(port, proof, name_or_id)? { + Some(reference) => reference, + None => return Ok(None), + }, }; - anyhow::ensure!( - capability_search_spec(port, proof)?.is_some(), - "turn no longer permits discovered capability admission" - ); let catalog = port.catalog(); let entries = catalog.resolve(std::slice::from_ref(&reference))?; let entry = entries.first().context("offered capability is absent")?; From 66cff2e98052e8738f549129f6aa5737bf3b62f1 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:15:02 +0400 Subject: [PATCH 0155/1567] fix(skills): reread the skill directories when they change The process-level skill snapshot was read once and reused until an in-process control call invalidated it, so a skill created by a shell, a child process or the operator was missing from skills_list until the gateway restarted. The snapshot is now reused only while the directory metadata is unchanged. --- src/skills/catalog_stamp.rs | 57 +++++++++++++++++++++++++++++++++++++ src/skills/mod.rs | 34 +++++++++++++++------- 2 files changed, 81 insertions(+), 10 deletions(-) create mode 100644 src/skills/catalog_stamp.rs diff --git a/src/skills/catalog_stamp.rs b/src/skills/catalog_stamp.rs new file mode 100644 index 000000000..a4cf8a0dd --- /dev/null +++ b/src/skills/catalog_stamp.rs @@ -0,0 +1,57 @@ +//! A cheap change stamp for the directories a skill catalog is read from. +//! +//! The process-level catalog snapshot is reused until this stamp changes, so a +//! skill installed, edited or removed from any process (a shell, a child, the +//! operator) is seen by the next read without a restart. The stamp reads file +//! metadata only; it never opens a skill file. + +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; +use std::path::Path; +use std::time::UNIX_EPOCH; + +/// Skill files whose own modification time matters beside their directory's. +const SKILL_FILES: [&str; 2] = ["SKILL.md", "SKILL.toml"]; + +fn hash_metadata(path: &Path, hasher: &mut DefaultHasher) { + path.hash(hasher); + match std::fs::symlink_metadata(path) { + Ok(metadata) => { + metadata.len().hash(hasher); + metadata + .modified() + .ok() + .and_then(|time| time.duration_since(UNIX_EPOCH).ok()) + .map(|age| age.as_nanos()) + .hash(hasher); + } + Err(_) => 0_u8.hash(hasher), + } +} + +fn hash_root(root: &Path, hasher: &mut DefaultHasher) { + hash_metadata(root, hasher); + let Ok(entries) = std::fs::read_dir(root) else { + return; + }; + let mut paths: Vec<_> = entries.filter_map(Result::ok).map(|entry| entry.path()).collect(); + paths.sort(); + for path in paths { + hash_metadata(&path, hasher); + if path.is_dir() { + for file in SKILL_FILES { + hash_metadata(&path.join(file), hasher); + } + } + } +} + +/// The stamp of `roots`: the directories themselves, their entries and each +/// entry's skill files. +pub(super) fn stamp_of(roots: &[&Path]) -> u64 { + let mut hasher = DefaultHasher::new(); + for root in roots { + hash_root(root, &mut hasher); + } + hasher.finish() +} diff --git a/src/skills/mod.rs b/src/skills/mod.rs index e83905aab..967d62b9a 100644 --- a/src/skills/mod.rs +++ b/src/skills/mod.rs @@ -11,6 +11,7 @@ use std::path::{Path, PathBuf}; use std::sync::{Arc, LazyLock}; pub mod discovery; +mod catalog_stamp; mod publication; pub(crate) use publication::publish_staged_skill_inactive; pub mod lifecycle; @@ -43,7 +44,7 @@ struct CatalogKey { openclaw_skills_dir: Option, } -static SKILL_CATALOGS: LazyLock>>>> = +static SKILL_CATALOGS: LazyLock>)>>> = LazyLock::new(|| Mutex::new(HashMap::new())); static SKILL_EMBEDDINGS: LazyLock>>> = LazyLock::new(|| Mutex::new(HashMap::new())); static SKILL_HYDRATION_LOCKS: LazyLock>>>> = @@ -285,8 +286,23 @@ pub fn load_skills_with_config(workspace_dir: &Path, config: &crate::config::Con open_skills_dir: config.skills.open_skills_dir.as_deref().map(PathBuf::from), openclaw_skills_dir: config.skills.openclaw_skills_dir.as_deref().map(PathBuf::from), }; + // The snapshot is reused only while the directories it was read from are + // unchanged, so a skill installed or removed by another process shows up. + let open_root = resolve_open_skills_dir(config.skills.open_skills_dir.as_deref()); + let openclaw_root = resolve_openclaw_skills_dir(config.skills.openclaw_skills_dir.as_deref()) + .map(|root| root.join("skills")); + let workspace_root = workspace_dir.join("skills"); + let disabled_root = workspace_root.join(DISABLED_SKILL_MARKER); + let roots: Vec<&Path> = [Some(&workspace_root), Some(&disabled_root), open_root.as_ref(), openclaw_root.as_ref()] + .into_iter() + .flatten() + .map(PathBuf::as_path) + .collect(); + let stamp = catalog_stamp::stamp_of(&roots); let mut catalogs = SKILL_CATALOGS.lock(); - if let Some(skills) = catalogs.get(&key) { + if let Some((cached_stamp, skills)) = catalogs.get(&key) + && *cached_stamp == stamp + { return skills.as_ref().clone(); } @@ -300,11 +316,8 @@ pub fn load_skills_with_config(workspace_dir: &Path, config: &crate::config::Con if catalogs.len() >= MAX_CATALOGS { catalogs.clear(); } - catalogs - .entry(key) - .or_insert_with(|| Arc::clone(&loaded)) - .as_ref() - .clone() + catalogs.insert(key, (stamp, Arc::clone(&loaded))); + loaded.as_ref().clone() } fn normalized_path(path: &Path) -> PathBuf { @@ -2315,7 +2328,7 @@ command = "echo hello" } #[tokio::test] - async fn catalog_snapshot_changes_only_after_explicit_invalidation() { + async fn catalog_snapshot_follows_the_skill_directories() { // Other parallel fixtures can fill the bounded process-wide cache and // evict this snapshot. Exercise invalidation with a private process cache. const ISOLATED: &str = "PRX_TEST_SKILL_CATALOG_ISOLATED"; @@ -2324,7 +2337,7 @@ command = "echo hello" command .args([ "--exact", - "skills::tests::catalog_snapshot_changes_only_after_explicit_invalidation", + "skills::tests::catalog_snapshot_follows_the_skill_directories", "--nocapture", ]) .env(ISOLATED, "1"); @@ -2356,7 +2369,8 @@ command = "echo hello" let beta = workspace_dir.join("skills").join("beta"); fs::create_dir_all(&beta).unwrap(); fs::write(beta.join("SKILL.md"), "# Beta\nSecond.\n").unwrap(); - assert_eq!(load_skills_with_config(&workspace_dir, &config).len(), 1); + // A skill added by another process is seen without an invalidation. + assert_eq!(load_skills_with_config(&workspace_dir, &config).len(), 2); invalidate_skill_catalog(&workspace_dir); let skills = load_skills_with_config(&workspace_dir, &config); From f6c2721428b1a0122764288d3dc6f666bd8f4e65 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:15:02 +0400 Subject: [PATCH 0156/1567] feat(skills): publish a fresh tool surface when the installed skills change The gateway, channel and terminal chat publications each pinned the skill snapshot for their whole lifetime, so a skill installed, edited or removed while they ran was not offered, and an edit or removal could make the pinned catalog differ from the live registry. The next turn now republishes when the skill change counter differs from the pinned one; opened turns keep theirs. --- docs/tools.md | 30 ++++--- src/channels/turn_source/publication_slot.rs | 1 + src/chat/run/provider_turn.rs | 2 +- src/gateway/api/capabilities.rs | 2 +- src/gateway/api/sessions/section_2.rs | 2 +- src/gateway/child_mailbox.rs | 2 +- src/gateway/implementation/section_2.rs | 3 +- src/gateway/turn_readiness.rs | 4 +- src/gateway/turn_source/publication_slot.rs | 92 +++++++++++--------- src/runtime/turn_publication/service.rs | 10 +++ src/tools/capability/catalog/section_1.rs | 36 +++++--- 11 files changed, 114 insertions(+), 70 deletions(-) diff --git a/docs/tools.md b/docs/tools.md index fb0742420..ad5ee0e02 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -34,22 +34,28 @@ main agent or a named agent runs at Full; below Full they are dropped as before. Servers that the opt-in, launcher allowlist or private-address checks block for the main agent still start only by the main agent's level. -Native tool turns start with the file/shell core (`file_read`, `file_write`, -`file_edit`, `shell`). When eligible deferred capabilities exist, the request -also declares `capability_search`, including for brief inputs and with the -advisory decision engine disabled. Search returns bounded, source-scoped offers; -a hit becomes a declared tool on the next request after fresh admission. Channel -exclusions, model policy and issued child scope still apply. Search does not -expand that scope. A catalog with deferred tools but no live search backend -reports a publication error rather than advertising an unusable discovery path. +Native tool turns publish every available tool directly, in a stable name +order, so a provider can cache the tool definitions as a prefix. This holds on +every surface: terminal chat, gateway, channels, scheduled runs and children +(a child still sees only the tools its parent granted). Dynamic MCP, WASM and +node tools are published too. `[tool_tiering] defer_unlisted = true` is the +operator option that turns this off: only the file/shell core (`file_read`, +`file_write`, `file_edit`, `shell`), the chat session tools and the names in +`always_include` stay direct. The request then also declares +`capability_search`. Search returns bounded, source-scoped offers; a hit +becomes a declared tool on the next request after fresh admission. A tool that +was deferred can also be called by its exact public name or capability ID +without a search: the runtime admits it under the same rules as a search hit, +declares it on the following request, and runs the call. Channel exclusions, +model policy and issued child scope still apply. Search does not expand that +scope. Eligible installed skills are advertised as metadata. A request that advertises skills includes an admitted `skill_read` definition; instruction bodies stay lazy. If the live reader cannot be admitted, the metadata is suppressed with a -diagnostic. Chat's `sessions_spawn` definition is deferred behind search by -default. An explicit `[tool_tiering] always_include = ["sessions_spawn"]` -preference can publish it directly when policy permits. Chat's slash-command -session controls remain available independently. +diagnostic. The skill catalog follows the files on disk: a skill installed, +edited or removed while a gateway, a channel listener or a chat session runs is +seen by its next turn without a restart. | Category | Tools | |----------|-------| diff --git a/src/channels/turn_source/publication_slot.rs b/src/channels/turn_source/publication_slot.rs index 4fb2f1145..8ec4540f3 100644 --- a/src/channels/turn_source/publication_slot.rs +++ b/src/channels/turn_source/publication_slot.rs @@ -39,6 +39,7 @@ impl ChannelPublicationSlot { published.generations.retain(|_, service| service.strong_count() > 0); if let Some(service) = published.generations.get(&generation.id.0).and_then(Weak::upgrade) && Arc::ptr_eq(service.memory(), &memory) + && !service.skills_changed() { owner.retain_child_service(Arc::clone(&service))?; return Ok(service); diff --git a/src/chat/run/provider_turn.rs b/src/chat/run/provider_turn.rs index 57cc5afde..85de0a62f 100644 --- a/src/chat/run/provider_turn.rs +++ b/src/chat/run/provider_turn.rs @@ -16,7 +16,7 @@ }; let provider_admission = provider_turn_visible_admission(&provider_turn_workers, provider_worker_kind, provider_admission_max); - let catalog_changed = turn_service.check_live_parity().is_err(); + let catalog_changed = turn_service.check_live_parity().is_err() || turn_service.skills_changed(); if !provider_admission.can_start_visible || (catalog_changed && provider_admission.active_workers > 0) { tracing::warn!( active_workers = provider_admission.active_workers, diff --git a/src/gateway/api/capabilities.rs b/src/gateway/api/capabilities.rs index 4ae643b65..f7a198a77 100644 --- a/src/gateway/api/capabilities.rs +++ b/src/gateway/api/capabilities.rs @@ -451,7 +451,7 @@ async fn published_tools( .map_err(|_| CatalogError::Draining)?; let service = cleanup .run(Box::pin(async { - Ok::<_, anyhow::Error>(std::sync::Arc::clone(runtime.publish(state).await?)) + Ok::<_, anyhow::Error>(runtime.publish(state).await?) })) .await .map_err(|_| CatalogError::Surface)?; diff --git a/src/gateway/api/sessions/section_2.rs b/src/gateway/api/sessions/section_2.rs index b38f6d5ce..a7814685f 100644 --- a/src/gateway/api/sessions/section_2.rs +++ b/src/gateway/api/sessions/section_2.rs @@ -777,7 +777,7 @@ async fn run_console_message_job_work( }; let provider_trace = None; ConsoleDecisionTurn { - service: std::sync::Arc::clone(service), + service: std::sync::Arc::clone(&service), provider_trace, context, advice, diff --git a/src/gateway/child_mailbox.rs b/src/gateway/child_mailbox.rs index 653bf794e..2472f71c5 100644 --- a/src/gateway/child_mailbox.rs +++ b/src/gateway/child_mailbox.rs @@ -139,7 +139,7 @@ async fn run(state: AppState, record: ChildSessionRecord, input: MessageInput, c }); let live = approvals::live(&state, &record, &input, console, wait_secs).await?; crate::runtime::mailbox_child::MailboxChildSource::admit( - publication, + &publication, record.clone(), input.clone(), Some(live), diff --git a/src/gateway/implementation/section_2.rs b/src/gateway/implementation/section_2.rs index 3f40d64ff..a3a2a1520 100644 --- a/src/gateway/implementation/section_2.rs +++ b/src/gateway/implementation/section_2.rs @@ -1161,7 +1161,7 @@ async fn run_gateway_chat_with_multimodal( Ok::<_, anyhow::Error>((service, context)) })) .await; - let (service, context) = match admission { + let (published_service, context) = match admission { Ok(admitted) => admitted, Err(error) => { // Admission is no longer polled. Settle its owned accounting work @@ -1191,6 +1191,7 @@ async fn run_gateway_chat_with_multimodal( return Err(error); } }; + let service = &published_service; // Bind before the handoff: a refusal here still has the admission guard // to record the failed input and answer the job monitor. *stage = TurnFailureClass::TerminalBinding; diff --git a/src/gateway/turn_readiness.rs b/src/gateway/turn_readiness.rs index 72818d9b8..708036b16 100644 --- a/src/gateway/turn_readiness.rs +++ b/src/gateway/turn_readiness.rs @@ -110,11 +110,11 @@ impl GatewayTurnState { } } - /// This state's published decision service (initialised once per state). + /// This state's published decision service (published again when the installed skills change). pub(super) async fn publish( &self, state: &AppState, - ) -> anyhow::Result<&Arc> { + ) -> anyhow::Result> { self.publication_slot() .publish_parts(self.config_generation(), self.tools_registry(), self.mcp_tool(), state) .await diff --git a/src/gateway/turn_source/publication_slot.rs b/src/gateway/turn_source/publication_slot.rs index cd42fd271..447678cc2 100644 --- a/src/gateway/turn_source/publication_slot.rs +++ b/src/gateway/turn_source/publication_slot.rs @@ -1,12 +1,14 @@ //! Decision publication belongs to the same immutable gateway generation as //! provider/model/tools. Initialization is shared by concurrent first turns. +//! The service is published again when the installed skills change, so a skill +//! created while the gateway runs is offered by the next turn. use crate::runtime::turn_publication::TurnRuntimeService; use std::sync::Arc; pub(in crate::gateway) struct GatewayPublicationSlot { pub(in crate::gateway) controlled: Option>, pub(in crate::gateway) cleanup: Arc, - service: tokio::sync::OnceCell>, + service: tokio::sync::Mutex>>, security: Arc, plugin_generation: u64, /// Set only for a targeted agent turn. @@ -18,7 +20,7 @@ impl GatewayPublicationSlot { Self { controlled: None, cleanup: Arc::new(super::CleanupTracker::default()), - service: tokio::sync::OnceCell::new(), + service: tokio::sync::Mutex::new(None), security, plugin_generation, targeted: None, @@ -36,7 +38,7 @@ impl GatewayPublicationSlot { Self { controlled: self.controlled.clone(), cleanup: Arc::clone(&self.cleanup), - service: tokio::sync::OnceCell::new(), + service: tokio::sync::Mutex::new(None), security, plugin_generation: self.plugin_generation, targeted: Some(surface), @@ -55,7 +57,7 @@ impl GatewayPublicationSlot { &self, runtime: &crate::gateway::TurnRuntimeGeneration, state: &crate::gateway::AppState, - ) -> anyhow::Result<&Arc> { + ) -> anyhow::Result> { self.publish_parts( &runtime.config_generation, &runtime.tools_registry, @@ -73,47 +75,42 @@ impl GatewayPublicationSlot { registry: &Arc>>, mcp_tool: Option<&Arc>, state: &crate::gateway::AppState, - ) -> anyhow::Result<&Arc> { + ) -> anyhow::Result> { if let Some(profile) = &self.controlled { profile.verify(&generation.effective)?; } - self.service - .get_or_try_init(|| async { - let service = crate::runtime::turn_publication::TurnPublication { - generation: Arc::clone(generation), - registry: Arc::clone(registry), - mcp_tool: mcp_tool.cloned(), - security: Arc::clone(&self.security), - observer: Arc::clone(&state.observer), - hooks: Arc::clone(&state.hooks), - memory: Arc::clone(&state.mem), - plugin_generation: self.plugin_generation, - } - .publish_scoped( - crate::tools::capability::turn_state::TurnSurfaceKind::Server, - None, - self.targeted.clone(), - ) - .await?; - self.cleanup.retain_service(Arc::clone(&service)); - Ok(service) - }) - .await - } -} - -#[cfg(test)] -impl Default for GatewayPublicationSlot { - fn default() -> Self { - Self::new(Arc::new(crate::security::SecurityPolicy::default()), 0) + let mut published = self.service.lock().await; + if let Some(service) = published.as_ref() + && !service.skills_changed() + { + return Ok(Arc::clone(service)); + } + let service = crate::runtime::turn_publication::TurnPublication { + generation: Arc::clone(generation), + registry: Arc::clone(registry), + mcp_tool: mcp_tool.cloned(), + security: Arc::clone(&self.security), + observer: Arc::clone(&state.observer), + hooks: Arc::clone(&state.hooks), + memory: Arc::clone(&state.mem), + plugin_generation: self.plugin_generation, + } + .publish_scoped( + crate::tools::capability::turn_state::TurnSurfaceKind::Server, + None, + self.targeted.clone(), + ) + .await?; + self.cleanup.retain_service(Arc::clone(&service)); + if let Some(previous) = published.replace(Arc::clone(&service)) { + self.retire(previous); + } + Ok(service) } -} -impl Drop for GatewayPublicationSlot { - fn drop(&mut self) { - let Some(service) = self.service.get().cloned() else { - return; - }; + /// Drain a service's decision writes in the background and register the + /// retirement with the cleanup owner. Turns that opened on it keep it alive. + fn retire(&self, service: Arc) { let ticket = match self.cleanup.retire(&service) { Ok(ticket) => ticket, Err(error) => { @@ -135,6 +132,21 @@ impl Drop for GatewayPublicationSlot { } } +#[cfg(test)] +impl Default for GatewayPublicationSlot { + fn default() -> Self { + Self::new(Arc::new(crate::security::SecurityPolicy::default()), 0) + } +} + +impl Drop for GatewayPublicationSlot { + fn drop(&mut self) { + if let Some(service) = self.service.get_mut().take() { + self.retire(service); + } + } +} + pub(in crate::gateway) use crate::runtime::turn_terminal::TurnTerminalGuard as GatewayTerminalGuard; pub(in crate::gateway) use crate::runtime::turn_terminal::commit_terminal; diff --git a/src/runtime/turn_publication/service.rs b/src/runtime/turn_publication/service.rs index 7521e61da..2e2f2462b 100644 --- a/src/runtime/turn_publication/service.rs +++ b/src/runtime/turn_publication/service.rs @@ -139,6 +139,16 @@ impl TurnRuntimeService { self.publication_scope().tool_tiering() } + /// The installed skills differ from the snapshot this publication pinned: + /// a skill was installed, edited or removed since. The owner publishes a + /// fresh service at its next turn boundary; opened turns keep their own. + #[must_use] + pub(crate) fn skills_changed(&self) -> bool { + let config = &self.generation.effective; + let live = crate::skills::catalog_skill_metadata(&config.workspace_dir, config); + crate::tools::capability::catalog::skills_epoch(&live) != self.catalog.skills_epoch() + } + #[must_use] pub(crate) const fn channel_surface(&self) -> bool { matches!(self.surface, TurnSurfaceKind::Channel) diff --git a/src/tools/capability/catalog/section_1.rs b/src/tools/capability/catalog/section_1.rs index 700723822..29123837d 100644 --- a/src/tools/capability/catalog/section_1.rs +++ b/src/tools/capability/catalog/section_1.rs @@ -192,17 +192,7 @@ impl CatalogSources { let mcp_digest = mcp_hasher.finalize(); let mut mcp_epoch_bytes = [0_u8; 8]; mcp_epoch_bytes.copy_from_slice(mcp_digest.get(..8).unwrap_or_default()); - let mut skill_hasher = Sha256::new(); - for skill in &skills { - skill_hasher.update(skill.name.len().to_be_bytes()); - skill_hasher.update(skill.name.as_bytes()); - skill_hasher.update(skill.frontmatter_sha); - skill_hasher.update(skill.location.to_string_lossy().as_bytes()); - } - let skill_digest = skill_hasher.finalize(); - let mut epoch_bytes = [0_u8; 8]; - epoch_bytes.copy_from_slice(skill_digest.get(..8).unwrap_or_default()); - let skills_dir_epoch = u64::from_be_bytes(epoch_bytes); + let skills_dir_epoch = skills_epoch(&skills); let hooks = hooks .events .iter() @@ -243,6 +233,25 @@ impl CatalogSources { } } +/// The change counter of a skill snapshot: a digest of every skill's name, +/// location and frontmatter, independent of the order they are listed in. +/// An install, edit or removal of a skill changes it. +pub(crate) fn skills_epoch<'a>(skills: impl IntoIterator) -> u64 { + let mut ordered: Vec<&SkillMetadata> = skills.into_iter().collect(); + ordered.sort_by(|left, right| (&left.name, &left.location).cmp(&(&right.name, &right.location))); + let mut hasher = Sha256::new(); + for skill in ordered { + hasher.update(skill.name.len().to_be_bytes()); + hasher.update(skill.name.as_bytes()); + hasher.update(skill.frontmatter_sha); + hasher.update(skill.location.to_string_lossy().as_bytes()); + } + let digest = hasher.finalize(); + let mut epoch_bytes = [0_u8; 8]; + epoch_bytes.copy_from_slice(digest.get(..8).unwrap_or_default()); + u64::from_be_bytes(epoch_bytes) +} + /// A `direct_names` member that publishes every tool directly: native tools, /// MCP, plugin and node aliases. Installed skills stay discoverable through /// the skill index and `skill_read`. Named members still count on their own, @@ -535,6 +544,11 @@ impl CapabilityCatalog { &self.generation } + /// The change counter of the skill snapshot this catalog was built from. + pub(crate) fn skills_epoch(&self) -> u64 { + skills_epoch(self.entries.iter().filter_map(|entry| entry.skill_metadata.as_deref())) + } + pub(crate) fn view(&self, scope: &CatalogScope) -> CatalogView<'_> { CatalogView { surface: None, From 37c24ca792d3a57faee7b29f19d220398d764ccf Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:40:38 +0400 Subject: [PATCH 0157/1567] feat(xin): open each scheduled agent run with a task card from the scheduler's store --- docs/scheduled-work.md | 32 ++++ src/agent/entry/section_2.rs | 6 +- src/agent/mod.rs | 1 + src/agent/scheduled_card.rs | 283 ++++++++++++++++++++++++++++++++++ src/agent/scheduled_source.rs | 16 ++ src/cron/scheduler.rs | 1 + src/xin/runner.rs | 10 +- 7 files changed, 345 insertions(+), 4 deletions(-) create mode 100644 src/agent/scheduled_card.rs diff --git a/docs/scheduled-work.md b/docs/scheduled-work.md index 58e6f32ac..fc4ec64b7 100644 --- a/docs/scheduled-work.md +++ b/docs/scheduled-work.md @@ -34,6 +34,38 @@ are `interval_minutes = 30`, `active_hours = [8, 23]`, and `HEARTBEAT.md` in the workspace if it is missing. Heartbeat health is an optional component owned by Xin. +## What a scheduled agent run is told + +An `agent_session` task, a goal step, a heartbeat item and an agent cron job +each run as a single-shot turn: the system message plus one user message. The +run has no transcript of earlier runs. The scheduler therefore opens the user +message with a task card, read from its own store and marked in its header as +data and not as an instruction. The task instruction follows the line +`[Task instruction]`. The card carries: + +- the kind of run (Xin task, goal step, heartbeat item or cron job), the id and + the name, and the schedule (interval, cron expression or one-shot instant); +- the run number: for a Xin task its stored run count plus one; for a cron job + the length of the retained run history plus one, shown as "N or later" once + the history has reached `[cron] max_run_history`; +- the previous run's start time, status and the last 3,000 bytes of its stored + output, each line prefixed with `| `; +- for a goal step: the goal's name and description, "step i of n", every step + with its status, and the outputs of the completed earlier steps (last 2,000 + bytes each, 8,000 bytes in total, newest steps first), and on a retry the + previous attempt's output. + +The card is redacted with the persistence redaction before it enters the +request. It is not stored with the message and is not part of recall. The +stored Xin run output is cut at 16 KiB and the cut ends with a `...[truncated]` +line. A named agent's job still gets that agent's identity text as its system +prompt, not the full interactive prompt. + +Cron `session_target` accepts `isolated` (default) and `main`. Today both take +the same path: the job runs as a single-shot turn under the session key +`cron:{job_id}` and its result stays in the run history; `main` does not +deliver anything to a main session. + ## HEARTBEAT.md materialization Each trimmed line that starts with `-` followed by a space becomes a recurring diff --git a/src/agent/entry/section_2.rs b/src/agent/entry/section_2.rs index 4e7c50b43..42345cf8d 100644 --- a/src/agent/entry/section_2.rs +++ b/src/agent/entry/section_2.rs @@ -279,6 +279,7 @@ pub(crate) async fn run_with_runtime_envelope( scope.context.envelope.agent_partition = envelope.agent_partition.clone(); } } + let scheduled_card = super::scheduled_source::current_card(); let mut scheduled_admission = super::scheduled_source::validate_current( runtime_envelope_override.as_ref(), scheduled_tool_scope.as_ref(), @@ -741,10 +742,11 @@ pub(crate) async fn run_with_runtime_envelope( ) .await; let context = mem_context.preamble.clone(); - let mut enriched = if context.is_empty() { + let card = scheduled_card.as_deref().unwrap_or_default(); + let mut enriched = if context.is_empty() && card.is_empty() { msg.clone() } else { - format!("{context}{msg}") + format!("{context}{card}{msg}") }; crate::agent::turn_contracts::push_current_time_tail(&mut enriched); diff --git a/src/agent/mod.rs b/src/agent/mod.rs index d084d7f9b..fa6ddaace 100644 --- a/src/agent/mod.rs +++ b/src/agent/mod.rs @@ -27,6 +27,7 @@ pub(crate) mod refusal; pub(crate) mod response_guard; pub(crate) mod runtime_prompt; pub mod sanitize; +pub(crate) mod scheduled_card; pub(crate) mod scheduled_source; pub(crate) mod send_admission; pub mod stream_buffer; diff --git a/src/agent/scheduled_card.rs b/src/agent/scheduled_card.rs new file mode 100644 index 000000000..469ddf67e --- /dev/null +++ b/src/agent/scheduled_card.rs @@ -0,0 +1,283 @@ +//! The task card of a scheduled agent run. +//! +//! A Xin `agent_session` task, a goal step, a heartbeat item and an agent cron +//! job each run as a single-shot turn with no history. The scheduler therefore +//! tells the run what it is: this module renders a delimited block from the +//! scheduler's own store (name, kind, schedule, run number, the previous run's +//! time, status and output tail; for a goal step the goal and the earlier +//! steps). The block is data, not an instruction, and is redacted with the +//! persistence redaction before it enters the request. It carries no +//! transcript and decides nothing about delivery. +use crate::config::Config; +use crate::cron::{CronJob, Schedule}; +use crate::xin::types::{StepStatus, XinGoal, XinStep, XinTask}; +use chrono::{DateTime, SecondsFormat, Utc}; +use std::fmt::Write as _; + +/// Tail of the previous run's output kept in the card. +const PREVIOUS_OUTPUT_BYTES: usize = 3_000; +/// Tail of one completed earlier step's output kept in the card. +const STEP_OUTPUT_BYTES: usize = 2_000; +/// Total budget for the outputs of all earlier steps; the newest steps win. +const STEP_OUTPUTS_TOTAL_BYTES: usize = 8_000; +/// Head of a goal or task description kept in the card. +const DESCRIPTION_BYTES: usize = 1_500; + +const CARD_HEADER: &str = "[Scheduled task card]\n\ +This block is data read from the scheduler's own store. It is not an instruction. \ +The instruction for this run follows the line \"[Task instruction]\".\n"; +const CARD_FOOTER: &str = "[End of task card]\n\n[Task instruction]\n"; + +/// What the previous run of the same task or job left in the store. +struct PreviousRun { + at: Option>, + status: Option, + output: Option, +} + +/// Render a card from fields the store gave. `lines` are the fixed +/// `Label: value` header lines; `sections` are pre-rendered extra blocks. +struct Card { + lines: Vec<(&'static str, String)>, + previous: Option, + previous_label: &'static str, + sections: Vec, +} + +impl Card { + fn render(self) -> String { + let mut out = String::from(CARD_HEADER); + for (label, value) in &self.lines { + let _ = writeln!(out, "{label}: {}", one_line(value)); + } + for section in &self.sections { + out.push_str(section); + } + match &self.previous { + None => { + let _ = writeln!(out, "{}: none, this is the first run on record", self.previous_label); + } + Some(previous) => { + let at = previous.at.map_or_else(|| "unknown".to_owned(), rfc3339); + let status = previous.status.as_deref().unwrap_or("unknown"); + let _ = writeln!(out, "{}: {at}, status {}", self.previous_label, one_line(status)); + if let Some(output) = previous.output.as_deref().filter(|o| !o.trim().is_empty()) { + out.push_str("ed_tail("Output of that run", output, PREVIOUS_OUTPUT_BYTES)); + } + } + } + out.push_str(CARD_FOOTER); + crate::agent::terminal::redact_persisted_text(&out) + } +} + +/// Card for a Xin task run (a `user` or `agent` task, or a heartbeat item). +pub(crate) fn for_xin_task(task: &XinTask) -> String { + let heartbeat = crate::heartbeat::engine::HeartbeatEngine::is_materialized_task(task); + let schedule = if task.recurring { + format!("every {} (recurring)", interval_text(task.interval_secs)) + } else { + "once (not recurring)".to_owned() + }; + let mut lines = vec![ + ("Run type", if heartbeat { "heartbeat item" } else { "Xin task" }.to_owned()), + ("Task id", task.id.clone()), + ("Name", task.name.clone()), + ]; + if let Some(description) = task.description.as_deref().filter(|d| !d.trim().is_empty()) { + lines.push(("Description", head(description, DESCRIPTION_BYTES))); + } + lines.push(("Schedule", schedule)); + lines.push(("Run number", task.run_count.saturating_add(1).to_string())); + let previous = (task.run_count > 0 || task.last_run_at.is_some()).then(|| PreviousRun { + at: task.last_run_at, + status: task.last_status.clone(), + output: task.last_output.clone(), + }); + Card { + lines, + previous, + previous_label: "Previous run", + sections: Vec::new(), + } + .render() +} + +/// Card for one step of a goal. The goal's other steps come from the store; +/// when they cannot be read the card still names the goal and this step. +pub(crate) fn for_xin_step(config: &Config, step: &XinStep, goal: &XinGoal) -> String { + let steps = crate::xin::store::list_steps(config, &goal.id).unwrap_or_else(|error| { + tracing::warn!(target: "xin", goal_id = %goal.id, "goal steps unavailable for the task card: {error}"); + Vec::new() + }); + let total = steps.len().max(usize::try_from(goal.steps_total).unwrap_or(0)).max(1); + let mut lines = vec![ + ("Run type", "goal step".to_owned()), + ("Goal id", goal.id.clone()), + ("Goal", goal.name.clone()), + ]; + if let Some(description) = goal.description.as_deref().filter(|d| !d.trim().is_empty()) { + lines.push(("Goal description", head(description, DESCRIPTION_BYTES))); + } + lines.push(("Step", format!("{} of {total}: {} (id {})", step.sequence, step.name, step.id))); + lines.push(("Attempt", step.retry_count.saturating_add(1).to_string())); + let mut sections = Vec::new(); + if !steps.is_empty() { + let mut list = String::from("Steps in order:\n"); + for other in &steps { + let marker = if other.id == step.id { " (this run)" } else { "" }; + let _ = writeln!( + list, + " {}. {} [{}]{marker}", + other.sequence, + one_line(&other.name), + other.status.as_str() + ); + } + sections.push(list); + sections.push(earlier_step_outputs(&steps, step)); + } + // A retry of this step: what the failed attempt left. + let previous = (step.retry_count > 0).then(|| PreviousRun { + at: step.started_at, + status: Some("earlier attempt of this step".to_owned()), + output: step.last_output.clone(), + }); + Card { + lines, + previous, + previous_label: "Previous attempt of this step", + sections, + } + .render() +} + +/// Card for an agent cron job run. The run number and the previous run come +/// from the run history, because a claimed job's own row already reads +/// `running`; the history keeps at most `[cron] max_run_history` runs. +pub(crate) fn for_cron_job(config: &Config, job: &CronJob) -> String { + let keep = usize::try_from(config.cron.max_run_history.max(1)).unwrap_or(usize::MAX); + let runs = crate::cron::list_runs(config, &job.id, keep).unwrap_or_else(|error| { + tracing::warn!(target: "cron", job_id = %job.id, "run history unavailable for the task card: {error}"); + Vec::new() + }); + let run_number = if runs.len() >= keep { + format!("{} or later (run history keeps the last {keep} runs)", runs.len() + 1) + } else { + (runs.len() + 1).to_string() + }; + let mut lines = vec![ + ("Run type", "cron job".to_owned()), + ("Job id", job.id.clone()), + ("Name", job.name.clone().unwrap_or_else(|| "(unnamed)".to_owned())), + ("Schedule", schedule_text(&job.schedule)), + ("Run number", run_number), + ]; + if job.delete_after_run { + lines.push(("Lifetime", "the job is deleted after it runs".to_owned())); + } + let previous = runs.first().map(|run| PreviousRun { + at: Some(run.started_at), + status: Some(run.status.clone()), + output: run.output.clone(), + }); + Card { + lines, + previous, + previous_label: "Previous run", + sections: Vec::new(), + } + .render() +} + +/// The outputs of completed steps before `current`, newest first within a +/// total budget; an older output that no longer fits is named and left out. +fn earlier_step_outputs(steps: &[XinStep], current: &XinStep) -> String { + let mut done: Vec<&XinStep> = steps + .iter() + .filter(|s| s.sequence < current.sequence && s.status == StepStatus::Completed) + .collect(); + if done.is_empty() { + return "Earlier steps: none completed yet\n".to_owned(); + } + let mut budget = STEP_OUTPUTS_TOTAL_BYTES; + let mut blocks = Vec::with_capacity(done.len()); + done.reverse(); + for earlier in done { + let label = format!("Output of step {} ({})", earlier.sequence, one_line(&earlier.name)); + let output = earlier.last_output.as_deref().filter(|o| !o.trim().is_empty()); + let block = match output { + None => format!("{label}: (empty)\n"), + Some(_) if budget == 0 => format!("{label}: left out to keep the card small\n"), + Some(output) => { + let take = STEP_OUTPUT_BYTES.min(budget); + budget = budget.saturating_sub(output.len().min(take)); + quoted_tail(&label, output, take) + } + }; + blocks.push(block); + } + blocks.reverse(); + blocks.concat() +} + +fn schedule_text(schedule: &Schedule) -> String { + match schedule { + Schedule::Cron { expr, tz } => match tz.as_deref().filter(|t| !t.is_empty()) { + Some(tz) => format!("cron expression `{expr}` ({tz})"), + None => format!("cron expression `{expr}`"), + }, + Schedule::At { at } => format!("once at {}", rfc3339(*at)), + Schedule::Every { every_ms } => format!("every {}", interval_text(every_ms / 1000)), + } +} + +fn interval_text(secs: u64) -> String { + match secs { + 0 => "0s".to_owned(), + s if s % 3600 == 0 => format!("{}h", s / 3600), + s if s % 60 == 0 => format!("{}m", s / 60), + s => format!("{s}s"), + } +} + +fn rfc3339(at: DateTime) -> String { + at.to_rfc3339_opts(SecondsFormat::Secs, true) +} + +fn one_line(text: &str) -> String { + text.split_whitespace().collect::>().join(" ") +} + +/// The first `max` bytes of `text`, cut on a character boundary, marked when cut. +fn head(text: &str, max: usize) -> String { + let text = text.trim(); + if text.len() <= max { + return text.to_owned(); + } + let mut end = max; + while end > 0 && !text.is_char_boundary(end) { + end -= 1; + } + format!("{} [cut]", text.get(..end).unwrap_or_default()) +} + +/// `label` and the last `max` bytes of `text`, every line prefixed with `| ` so +/// that stored text can never read as part of the card's own structure. +fn quoted_tail(label: &str, text: &str, max: usize) -> String { + let text = text.trim_end(); + let mut start = text.len().saturating_sub(max); + while start < text.len() && !text.is_char_boundary(start) { + start += 1; + } + let mut out = String::new(); + if start > 0 { + let _ = writeln!(out, "{label} (last {} of {} bytes):", text.len() - start, text.len()); + } else { + let _ = writeln!(out, "{label}:"); + } + for line in text.get(start..).unwrap_or_default().lines() { + let _ = writeln!(out, "| {line}"); + } + out +} diff --git a/src/agent/scheduled_source.rs b/src/agent/scheduled_source.rs index 34b8131db..02add1397 100644 --- a/src/agent/scheduled_source.rs +++ b/src/agent/scheduled_source.rs @@ -22,6 +22,8 @@ pub(crate) struct ScheduledAgentOrigin { origin: JobOrigin, claimed_attempt: Option, retry_boundary: ScheduledRetryBoundary, + /// Task card text built by the scheduler from its own store. + card: Option, } /// A read-only observation held by the scheduler, never a permission to replay @@ -35,6 +37,11 @@ impl ScheduledRetryBoundary { } } +/// The task card of the scheduled invocation this call runs inside, if any. +pub(super) fn current_card() -> Option { + SCHEDULED_ORIGIN.try_with(|origin| origin.card.clone()).ok().flatten() +} + pub(super) fn begin_decision() -> Result<()> { SCHEDULED_ORIGIN .try_with(|origin| { @@ -58,6 +65,7 @@ impl ScheduledAgentOrigin { origin: job.origin.clone(), claimed_attempt: claim.map(|claim| claim.attempt_id.clone()), retry_boundary: ScheduledRetryBoundary::default(), + card: None, } } @@ -71,9 +79,17 @@ impl ScheduledAgentOrigin { origin: task.origin.clone(), claimed_attempt: None, retry_boundary: ScheduledRetryBoundary::default(), + card: None, } } + /// Attach the task card the run's user message opens with. + #[must_use] + pub(crate) fn with_card(mut self, card: String) -> Self { + self.card = Some(card); + self + } + pub(crate) fn retry_boundary(&self) -> ScheduledRetryBoundary { self.retry_boundary.clone() } diff --git a/src/cron/scheduler.rs b/src/cron/scheduler.rs index 56dd55544..de53c08a0 100644 --- a/src/cron/scheduler.rs +++ b/src/cron/scheduler.rs @@ -706,6 +706,7 @@ async fn run_agent_job_with_origin( // Background cron job: no cooperative shutdown signal of its own; // the scheduler drops/aborts the task. See never_cancelled_shutdown. origin + .with_card(crate::agent::scheduled_card::for_cron_job(config, job)) .scope(crate::agent::run_with_runtime_envelope( match ( CONFIG_GENERATION.try_with(Arc::clone), diff --git a/src/xin/runner.rs b/src/xin/runner.rs index d0953cb3f..393e74164 100644 --- a/src/xin/runner.rs +++ b/src/xin/runner.rs @@ -414,7 +414,7 @@ async fn execute_single_task( let mut execution = Box::pin(async { match task.execution_mode { ExecutionMode::Internal => run_internal(config, registry, task).await, - ExecutionMode::AgentSession => run_agent(config, security, task, execution_authority).await, + ExecutionMode::AgentSession => run_agent(config, security, task, None, execution_authority).await, ExecutionMode::Shell => run_shell_with_cancellation(config, task, Some(shell_cancellation)).await, } }); @@ -824,7 +824,7 @@ async fn execute_step_inner( let bridge = step_as_task(step, goal); match step.execution_mode { ExecutionMode::Internal => run_internal(config, registry, &bridge).await, - ExecutionMode::AgentSession => run_agent(config, security, &bridge, authority).await, + ExecutionMode::AgentSession => run_agent(config, security, &bridge, Some((step, goal)), authority).await, ExecutionMode::Shell => run_shell_with_cancellation(config, &bridge, cancellation).await, } } @@ -895,6 +895,7 @@ async fn run_agent( config: &Config, security: &SecurityPolicy, task: &XinTask, + step: Option<(&XinStep, &XinGoal)>, authority: XinRuntimeAuthority, ) -> (bool, String) { if !security.can_act() @@ -929,7 +930,12 @@ async fn run_agent( let scheduled_tool_scope = task .origin .scheduled_tool_scope(runtime_envelope.clone(), config, level); + let card = match step { + Some((step, goal)) => crate::agent::scheduled_card::for_xin_step(config, step, goal), + None => crate::agent::scheduled_card::for_xin_task(task), + }; match crate::agent::scheduled_source::ScheduledAgentOrigin::from_xin(task) + .with_card(card) .scope(crate::agent::run_with_runtime_envelope( match ( CONFIG_GENERATION.try_with(Arc::clone), From 7570879a8bbaff984f894b2ee504a95dba6f2603 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:42:58 +0400 Subject: [PATCH 0158/1567] feat(chat): replay each earlier request in the form it was sent A user turn keeps what was put around its text when it was sent (masked recall text, attached file text, the date line) in an optional field of its runtime record, saved with the session JSON. The provider view replays prefix + text + tail for earlier turns, so the first message has the same bytes in every request, after a resume and after a restart. The typed text, the session list, history and exports are unchanged. --- docs/unified-turn-context.md | 18 ++++++- src/agent/tool_evidence.rs | 16 ++++++ src/agent/tool_replay.rs | 15 ++++-- src/agent/turn_history.rs | 38 ++++++------- src/chat/action.rs | 8 +++ src/chat/commands.rs | 8 +++ src/chat/mod.rs | 1 + src/chat/provider_turns/section_1.rs | 28 ++++++++-- src/chat/run/provider_turn.rs | 18 ++++--- src/chat/sanitize.rs | 5 ++ src/chat/session_store.rs | 22 +++++--- src/chat/state/mod.rs | 2 + src/chat/state/reduce_session.rs | 23 ++++++++ .../p3_directional_switch_tests/section_2.rs | 1 + src/chat/turn_replay.rs | 54 +++++++++++++++++++ 15 files changed, 215 insertions(+), 42 deletions(-) create mode 100644 src/chat/turn_replay.rs diff --git a/docs/unified-turn-context.md b/docs/unified-turn-context.md index ab99b0aa0..3042c622d 100644 --- a/docs/unified-turn-context.md +++ b/docs/unified-turn-context.md @@ -75,7 +75,23 @@ is not replayed. Replayed tool messages have no event id, so the compaction provenance folds them into their round by shape. When the request is over the warning threshold, the oldest replayed results become one-line stubs first. The rows are not on the sync stream, and `conversation_turns` is unchanged. -Terminal chat, channels, scheduled turns and children are not covered yet. +Channels, scheduled turns and children are not covered yet. + +## Replayed history in terminal chat + +`prx chat` (TUI and `--plain`) replays the form each earlier request was sent +in. A user turn keeps what was put around its text when it was sent (the masked +recall text before it, attached `@path` text and the date line after it) in the +optional `sent` field of its runtime record (`TurnToolEvidence` in +`src/agent/tool_evidence.rs`), set by the action `TurnRecordsAttached` after the +commit. The field is saved with the session JSON (`schema_version` stays 1; an +older reader ignores the unknown optional field and an older file loads with no +sent form). The provider view is rendered by `turn_history::project`, which +replays `prefix + text + tail`, so the first message has the same bytes in every +request, after `/resume` and after a restart; the canonical history, the +compaction guard and the reducer form still hold the typed text only. The TUI, +`/history`, the session list and exports show the typed text; the JSON export +drops the field. ## Ownership diff --git a/src/agent/tool_evidence.rs b/src/agent/tool_evidence.rs index 2c0789fd0..1ffc0cd41 100644 --- a/src/agent/tool_evidence.rs +++ b/src/agent/tool_evidence.rs @@ -106,6 +106,12 @@ pub struct TurnToolEvidence { pub groups: Vec, #[serde(default, skip_serializing_if = "is_zero")] pub omitted_calls: u32, + /// What was put around a `user` turn's text when it was sent (recalled + /// memory before it, the date line after it). Only a user turn carries + /// it; it is replayed with the turn so the message keeps its bytes. The + /// turn's own text stays what the user typed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sent: Option, } /// Serde's `skip_serializing_if` callback, which receives a reference. @@ -202,6 +208,16 @@ pub(crate) fn render_assistant_content<'a>(content: &'a str, evidence: Option<&T }) } +/// The one renderer of an acknowledged user message in a provider view: +/// `content` between the text that was put before and after it when it was +/// sent, borrowed when the turn has no such record. +pub(crate) fn render_user_content<'a>(content: &'a str, evidence: Option<&TurnToolEvidence>) -> Cow<'a, str> { + let Some(sent) = evidence.and_then(|evidence| evidence.sent.as_ref()) else { + return Cow::Borrowed(content); + }; + Cow::Owned(crate::agent::turn_contracts::neutralize_reserved_markers(&sent.compose(content)).into_owned()) +} + /// The body of `line` when it is a whole evidence line: its trim starts with /// [`TOOL_EVIDENCE_MARKER_PREFIX`] and ends with `]`. fn evidence_line_body(line: &str) -> Option<&str> { diff --git a/src/agent/tool_replay.rs b/src/agent/tool_replay.rs index 1a31e4333..64a0d51f7 100644 --- a/src/agent/tool_replay.rs +++ b/src/agent/tool_replay.rs @@ -38,14 +38,23 @@ pub(crate) const ATTACHMENT_EVENT_TYPE: &str = "message.attachment.recorded"; const REPLAY_ROW_LIMIT: usize = 500; /// What was put around a user message when it was sent. -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub(crate) struct Attachment { +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct Attachment { /// Text placed before the user's text (recalled memory). + #[serde(default)] pub prefix: String, - /// Text placed after it (the date line). + /// Text placed after it (attached file text, the date line). + #[serde(default)] pub tail: String, } +impl Attachment { + /// The message as it was sent: `text` between the prefix and the tail. + pub(crate) fn compose(&self, text: &str) -> String { + format!("{}{text}{}", self.prefix, self.tail) + } +} + #[derive(Debug, Clone)] struct StoredCall { call_id: String, diff --git a/src/agent/turn_history.rs b/src/agent/turn_history.rs index 3b2fcfb84..da633cab5 100644 --- a/src/agent/turn_history.rs +++ b/src/agent/turn_history.rs @@ -29,7 +29,7 @@ use crate::agent::compaction::render_context_handoff_for_provider; use crate::agent::context_paging::inject_recalled_context; use crate::agent::page_sources::MessageSources; -use crate::agent::tool_evidence::{TurnToolEvidence, render_assistant_content}; +use crate::agent::tool_evidence::{TurnToolEvidence, render_assistant_content, render_user_content}; use crate::agent::turn_contracts::{inbound_user_message, stored_turn_message}; use crate::providers::ChatMessage; use std::sync::Arc; @@ -95,7 +95,7 @@ pub(crate) struct CanonicalHistory { /// One origin per message, index for index. origins: Vec, /// One evidence slot per message, index for index; only an acknowledged - /// assistant message's slot can be filled. + /// message's slot can be filled. evidence: Vec>>, /// One set of source event ids per message, index for index; an evicted /// context page records the union over its messages. @@ -137,8 +137,8 @@ impl CanonicalHistory { ) } - /// As [`Self::from_acknowledged`], with each stored turn's tool evidence: - /// an `assistant` turn keeps it, every other turn's is ignored. + /// As [`Self::from_acknowledged`], with each stored turn's runtime record + /// (tool evidence of a reply, sent form of a request). pub(crate) fn from_acknowledged_turns<'a, I>(leading_system: Option<&str>, turns: I) -> Self where I: IntoIterator)>, @@ -147,8 +147,8 @@ impl CanonicalHistory { } /// A snapshot that holds the turn's admitted request at `request_turn` - /// (see `from_acknowledged_with_request`), with each stored turn's tool - /// evidence (kept on `assistant` turns only). + /// (see `from_acknowledged_with_request`), with each stored turn's + /// runtime record. pub(crate) fn from_acknowledged_turns_with_request<'a, I>( leading_system: Option<&str>, turns: I, @@ -209,7 +209,7 @@ impl CanonicalHistory { }; messages.push(stored_turn_message(role.to_owned(), content.to_owned())); origins.push(origin); - evidence.push(turn_evidence.filter(|_| role == "assistant")); + evidence.push(turn_evidence); sources.push(if origin == MessageOrigin::Request { MessageSources::turn_round() } else { @@ -596,12 +596,9 @@ fn shared_evidence<'a, I>(turns: I) -> impl Iterator)>, { - turns.into_iter().map(|(role, content, evidence)| { - let evidence = evidence - .filter(|_| role == "assistant") - .map(|evidence| Arc::new(evidence.clone())); - (role, content, evidence) - }) + turns + .into_iter() + .map(|(role, content, evidence)| (role, content, evidence.map(|evidence| Arc::new(evidence.clone())))) } /// The refresh aside a durable compaction appends after its replacement, and @@ -677,13 +674,16 @@ pub(crate) fn project(canonical: &CanonicalHistory, inputs: &ProjectionInputs) - } } } - // Each acknowledged assistant reply is shown with its tool evidence, by - // the one renderer, before anything is inserted (indices still align). + // Each acknowledged reply is shown with its tool evidence and each + // acknowledged request in the form it was sent, by the one renderer of + // each, before anything is inserted (indices still align). for (message, evidence) in messages.iter_mut().zip(&canonical.evidence) { - if let Some(evidence) = evidence.as_deref() - && message.role == "assistant" - && let std::borrow::Cow::Owned(rendered) = render_assistant_content(&message.content, Some(evidence)) - { + let rendered = match message.role.as_str() { + "assistant" => render_assistant_content(&message.content, evidence.as_deref()), + "user" => render_user_content(&message.content, evidence.as_deref()), + _ => continue, + }; + if let std::borrow::Cow::Owned(rendered) = rendered { message.content = rendered; } } diff --git a/src/chat/action.rs b/src/chat/action.rs index 0039093c7..d00530bf4 100644 --- a/src/chat/action.rs +++ b/src/chat/action.rs @@ -560,6 +560,13 @@ pub enum Action { /// inline path). The admission stays open until the turn commits; a /// failed or cancelled turn removes exactly this request, once. UserTurnAdmitted { admission: AdmissionId, content: String }, + /// After a turn's commit: attach the form the user's request was sent in + /// (`sent`) to the newest user turn holding `user_text` that has none, so + /// the provider view replays the request as it was sent. + TurnRecordsAttached { + user_text: String, + sent: Option, + }, /// Ask the reducer to persist the assistant turn (writes session.turns + LLM history) RecordAssistantTurn { task_id: Option, @@ -765,6 +772,7 @@ impl Action { Self::SessionSwitched { .. } => "SessionSwitched", Self::RecordUserTurn(_) => "RecordUserTurn", Self::UserTurnAdmitted { .. } => "UserTurnAdmitted", + Self::TurnRecordsAttached { .. } => "TurnRecordsAttached", Self::RecordAssistantTurn { .. } => "RecordAssistantTurn", Self::RecordSystemMessage { .. } => "RecordSystemMessage", Self::SetLeadingSystemPrompt { .. } => "SetLeadingSystemPrompt", diff --git a/src/chat/commands.rs b/src/chat/commands.rs index 198b3a3d6..8b3c0fe2b 100644 --- a/src/chat/commands.rs +++ b/src/chat/commands.rs @@ -831,6 +831,14 @@ fn export_session_json(session: &session::ChatSession) -> Result { let mut value = serde_json::to_value(session).map_err(|e| anyhow::anyhow!("JSON serialize: {e}"))?; let usage = serde_json::to_value(export_usage_metadata(session)).map_err(|e| anyhow::anyhow!("usage serialize: {e}"))?; + // An export carries the typed text of each turn, not what was put around it. + if let Some(turns) = value.get_mut("turns").and_then(serde_json::Value::as_array_mut) { + for evidence in turns.iter_mut().filter_map(|turn| turn.get_mut("tool_evidence")) { + if let Some(evidence) = evidence.as_object_mut() { + evidence.remove("sent"); + } + } + } let Some(object) = value.as_object_mut() else { anyhow::bail!("session JSON root was not an object"); }; diff --git a/src/chat/mod.rs b/src/chat/mod.rs index 925640355..389970c65 100644 --- a/src/chat/mod.rs +++ b/src/chat/mod.rs @@ -104,6 +104,7 @@ mod session_store; mod session_switch; mod terminal; mod terminal_approval; +mod turn_replay; mod tui_loop; mod views; diff --git a/src/chat/provider_turns/section_1.rs b/src/chat/provider_turns/section_1.rs index b1d513a64..71db7098e 100644 --- a/src/chat/provider_turns/section_1.rs +++ b/src/chat/provider_turns/section_1.rs @@ -78,6 +78,8 @@ pub(super) struct PerTurnContext { pub(super) draft_updater: Option>, pub(super) tool_event_forwarder: Option>, pub(super) user_input: String, + /// The form the request was sent in (see [`crate::chat::turn_replay`]). + pub(super) sent: Option, pub(super) turn_run_id: String, pub(super) route_scope: MessageEventScope, pub(super) route_decision: RouteDecision, @@ -1244,6 +1246,13 @@ async fn commit_completed_provider_turn( if let Some(guard) = pending.assignment.as_mut() { guard.failed("The turn finished without reply text."); } + crate::chat::turn_replay::attach_turn_records( + chat_dispatcher, + turn_signal, + &pending.user_input, + pending.sent.as_ref(), + ) + .await; adopt_committed_turn(history, chat_dispatcher, &pending, None); surface_turn_elapsed_message( chat_dispatcher, @@ -1299,6 +1308,13 @@ async fn commit_completed_provider_turn( ); return false; } + crate::chat::turn_replay::attach_turn_records( + chat_dispatcher, + turn_signal, + &pending.user_input, + pending.sent.as_ref(), + ) + .await; adopt_committed_turn(history, chat_dispatcher, &pending, Some(&final_text)); if let Err(e) = terminal.finalize_draft("user", &pending.draft_id, &final_text).await { tracing::warn!(error = %crate::agent::diagnostics::error_class(&e), "Redux driver: finalize_draft failed"); @@ -1333,9 +1349,9 @@ async fn commit_completed_provider_turn( /// it equals the view rebuilt from the committed snapshot /// ([`super::compaction::provider_view_from_acked`]). Without a compaction /// since the turn copied its view, the committed request and reply are -/// appended; the request is the plain stored text, never the enriched form -/// the turn sent (only a request still being sent carries its recalled -/// context and attached files). After a worker compaction the view is rebuilt +/// appended; the request is in the form it was sent (recalled context, attached +/// files and date line kept beside the turn). After a worker compaction the +/// view is rebuilt /// from the committed snapshot instead: appending to the pre-compaction view /// would resend the replaced cold prefix and force another rollover or a lossy /// fallback on the next turn. @@ -1358,7 +1374,11 @@ fn adopt_committed_turn( *history = view; return; } - history.push(crate::agent::turn_contracts::inbound_user_message(&pending.user_input)); + // The request in the form it was sent, which the snapshot's view holds too. + history.push(crate::agent::turn_contracts::inbound_user_message(&pending.sent.as_ref().map_or_else( + || pending.user_input.clone(), + |sent| sent.compose(&pending.user_input), + ))); if let Some(reply) = reply { history.push(committed_reply_message(&acked, reply)); } diff --git a/src/chat/run/provider_turn.rs b/src/chat/run/provider_turn.rs index 85de0a62f..3635b3d6d 100644 --- a/src/chat/run/provider_turn.rs +++ b/src/chat/run/provider_turn.rs @@ -141,13 +141,14 @@ #[cfg(feature = "terminal-tui")] let routing_input = admitted_binding.routing_input().to_owned(); let mem_context = admitted_binding.recalled_context(mem.as_ref()).await; - let context = mem_context.preamble.clone(); - let mut enriched = if context.is_empty() { - user_input_for_prompt.clone() - } else { - format!("{context}{user_input_for_prompt}") - }; - crate::agent::turn_contracts::push_current_time_tail(&mut enriched); + // What is put around the typed text is kept with the turn, so a later + // turn's view replays this request with the same bytes. + let (enriched, sent_form) = super::turn_replay::sent_request( + &mem_context.preamble, + &user_input, + &user_input_for_prompt, + crate::agent::turn_contracts::current_time_tail(), + ); // Build system prompt with skill selection let selected_skills = admitted_binding.prompt_skills()?; @@ -677,6 +678,7 @@ draft_updater, tool_event_forwarder: Some(tool_event_forwarder), user_input: user_input.clone(), + sent: sent_form.clone(), turn_run_id: turn_run_id.clone(), route_scope: route_scope.clone(), route_decision: route_decision.clone(), @@ -1612,6 +1614,7 @@ { anyhow::bail!("Chat stopped after an unconfirmed history commit: {error}"); } + super::turn_replay::attach_turn_records(&chat_dispatcher, &turn_signal, &user_input, sent_form.as_ref()).await; super::compaction::reconcile_inline_turn(&mut history, &chat_dispatcher); if let Some(ref d_id) = draft_id && let Err(e) = terminal.cancel_draft("user", d_id).await @@ -1729,6 +1732,7 @@ { anyhow::bail!("Chat stopped after an unconfirmed history commit: {error}"); } + super::turn_replay::attach_turn_records(&chat_dispatcher, &turn_signal, &user_input, sent_form.as_ref()).await; super::compaction::reconcile_inline_turn(&mut history, &chat_dispatcher); #[cfg(feature = "terminal-tui")] if let Some(tx) = redraw_tx_for_main.as_ref() { diff --git a/src/chat/sanitize.rs b/src/chat/sanitize.rs index 5176e5e8c..1017e8200 100644 --- a/src/chat/sanitize.rs +++ b/src/chat/sanitize.rs @@ -126,6 +126,11 @@ pub fn sanitize_session_content(session: &super::session::ChatSession) -> super: sanitized.title = sanitize_for_persistence(&sanitized.title); for turn in &mut sanitized.turns { turn.content = sanitize_turn_content(turn); + // What was put around a request is stored masked, like its text. + if let Some(sent) = turn.tool_evidence.as_mut().and_then(|evidence| evidence.sent.as_mut()) { + sent.prefix = redact_secrets(&sent.prefix); + sent.tail = redact_secrets(&sent.tail); + } for tool_call in &mut turn.tool_calls { tool_call.args_preview = sanitize_text_or_json(&tool_call.args_preview); } diff --git a/src/chat/session_store.rs b/src/chat/session_store.rs index afe991c13..2fa1d8339 100644 --- a/src/chat/session_store.rs +++ b/src/chat/session_store.rs @@ -347,27 +347,33 @@ pub(super) fn session_turns_to_history(session: &session::ChatSession) -> Vec Vec { - let mut view = session_turns_to_history(session); + let history = session_turns_to_history(session); let stored_turns = session .turns .iter() .filter(|turn| turn.role == "user" || turn.role == "assistant"); - for (message, turn) in view.iter_mut().zip(stored_turns) { + let mut view = Vec::with_capacity(history.len()); + for (mut message, turn) in history.into_iter().zip(stored_turns) { if let std::borrow::Cow::Owned(rendered) = crate::agent::compaction::render_context_handoff_for_provider(&message.role, &message.content) { message.content = rendered; } - if message.role == "assistant" - && let std::borrow::Cow::Owned(rendered) = - crate::agent::tool_evidence::render_assistant_content(&message.content, turn.tool_evidence.as_ref()) - { + let evidence = turn.tool_evidence.as_ref(); + let rendered = if message.role == "assistant" { + crate::agent::tool_evidence::render_assistant_content(&message.content, evidence) + } else { + crate::agent::tool_evidence::render_user_content(&message.content, evidence) + }; + if let std::borrow::Cow::Owned(rendered) = rendered { message.content = rendered; } + view.push(message); } view } diff --git a/src/chat/state/mod.rs b/src/chat/state/mod.rs index ed44261d2..574ace0ae 100644 --- a/src/chat/state/mod.rs +++ b/src/chat/state/mod.rs @@ -1437,6 +1437,7 @@ impl ChatState { Action::SessionSwitched { id } => self.reduce_session_switched(id), Action::RecordUserTurn(content) => self.reduce_record_user_turn(content), Action::UserTurnAdmitted { admission, content } => self.reduce_user_turn_admitted(admission, content), + Action::TurnRecordsAttached { user_text, sent } => self.reduce_turn_records_attached(&user_text, sent), Action::RecordAssistantTurn { task_id, content } => self.reduce_record_assistant_turn(task_id, content), Action::RecordSystemMessage { content } => self.reduce_record_system_message(content), Action::SetLeadingSystemPrompt { content } => self.reduce_set_leading_system_prompt(content), @@ -1562,6 +1563,7 @@ const fn ui_dirty_for(action: &Action) -> bool { // `ContextWindowUpdated`, so the history patch itself is not snapshot-dirty. Action::RecordUserTurn(_) | Action::UserTurnAdmitted { .. } + | Action::TurnRecordsAttached { .. } | Action::RecordAssistantTurn { .. } | Action::RecordSystemMessage { .. } | Action::SetLeadingSystemPrompt { .. } diff --git a/src/chat/state/reduce_session.rs b/src/chat/state/reduce_session.rs index b7e2517e1..3ffec9ffb 100644 --- a/src/chat/state/reduce_session.rs +++ b/src/chat/state/reduce_session.rs @@ -345,6 +345,29 @@ impl ChatState { effects } + /// `Action::TurnRecordsAttached` — keep, beside the turn a commit just + /// recorded, the form its request was sent in (saved with the session). + /// Nothing is attached to a turn that is not exactly the one the action + /// names; the stored text of a turn never changes. + pub(super) fn reduce_turn_records_attached( + &mut self, + user_text: &str, + sent: Option, + ) -> Vec { + let user_text = crate::agent::turn_contracts::neutralize_reserved_markers(user_text); + if let Some(sent) = sent + && let Some(turn) = self.session.turns.iter_mut().rev().find(|turn| { + turn.role == "user" + && turn.content == user_text + && turn.tool_evidence.as_ref().is_none_or(|evidence| evidence.sent.is_none()) + }) + { + turn.tool_evidence.get_or_insert_with(Default::default).sent = Some(sent); + return vec![Effect::SaveSession(self.session_commit())]; + } + Vec::new() + } + /// `Action::RecordAssistantTurn` — persist an assistant turn into the session record and LLM history. /// /// Matches `session.add_assistant_turn` semantics: diff --git a/src/chat/tests/p3_directional_switch_tests/section_2.rs b/src/chat/tests/p3_directional_switch_tests/section_2.rs index e2bcdeb44..d7eb8c3bb 100644 --- a/src/chat/tests/p3_directional_switch_tests/section_2.rs +++ b/src/chat/tests/p3_directional_switch_tests/section_2.rs @@ -1081,6 +1081,7 @@ fn provider_turn_finalizer_n3_out_of_order_releases_ordered_persistence_actions( draft_updater: None, tool_event_forwarder: None, user_input: user_input.to_string(), + sent: None, turn_run_id: format!("test-run-{}", task_id.get()), route_scope: crate::memory::MessageEventScope::new("chat", crate::memory::MemoryVisibility::Workspace), route_decision: RouteDecision::single_candidate("mock", "mock"), diff --git a/src/chat/turn_replay.rs b/src/chat/turn_replay.rs new file mode 100644 index 000000000..cc99440ec --- /dev/null +++ b/src/chat/turn_replay.rs @@ -0,0 +1,54 @@ +//! What chat keeps of a finished turn beyond its text, so a later turn's +//! provider view replays it as the turn had it: the form the user's request was +//! sent in. +//! +//! It rides on the stored turn's runtime record +//! ([`crate::agent::tool_evidence::TurnToolEvidence`]) and is rendered by +//! [`crate::agent::turn_history::project`], so the provider view, the +//! compaction guard and the reducer form keep describing the same canonical +//! messages (the canonical history holds the typed text only). + +use super::dispatcher::{ChatDispatcher, TurnCompletionSignal}; +use crate::agent::tool_replay::Attachment; + +/// The request as it is sent, and what was put around the typed `user_input`. +/// `prompt` is `user_input` possibly followed by attached file text; when it +/// does not start with `user_input`, no sent form is kept and the request is +/// `prefix + prompt + time_tail`, as it always was. +pub(super) fn sent_request( + prefix: &str, + user_input: &str, + prompt: &str, + time_tail: String, +) -> (String, Option) { + let prefix = crate::security::redaction::redact_secrets(prefix); + let Some(file_text) = prompt.strip_prefix(user_input) else { + return (format!("{prefix}{prompt}{time_tail}"), None); + }; + let sent = Attachment { + prefix, + tail: format!("{file_text}{time_tail}"), + }; + (sent.compose(user_input), Some(sent)) +} + +/// After a turn's commit: hand the reducer the sent form of the request, to +/// attach to the turn it just recorded. Nothing is sent when there is none. +pub(super) async fn attach_turn_records( + chat_dispatcher: &ChatDispatcher, + commits: &TurnCompletionSignal, + user_text: &str, + sent: Option<&Attachment>, +) { + let Some(sent) = sent else { return }; + // A failed acknowledgement latches the unconfirmed-commit stop itself. + let _ = chat_dispatcher + .dispatch_awaited( + super::action::Action::TurnRecordsAttached { + user_text: user_text.to_owned(), + sent: Some(sent.clone()), + }, + commits, + ) + .await; +} From 43097edb2f2439e1c4c8f44c335e8af369cdb5c2 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:43:26 +0400 Subject: [PATCH 0159/1567] feat(chat): replay earlier turns' tool rounds in terminal chat After each commit the run's stored tool calls and results are read back and attached to the committed assistant turn, and a loaded session ties each reply to its run by text from the newest back. The provider view holds the rounds in the gateway's native envelope form between the user message and the reply, and a reply with replayed rounds no longer carries the one-line evidence marker. The rounds are never saved with the session. Before each turn the oldest replayed results become the gateway's one-line stubs while the request is over the warning threshold; compaction runs unchanged on the canonical history. --- docs/unified-turn-context.md | 37 +++-- src/agent/tool_evidence.rs | 7 + src/agent/tool_replay.rs | 207 +++++++++++++++++++++------ src/agent/turn_history.rs | 25 +++- src/chat/action.rs | 11 +- src/chat/provider_turns/section_1.rs | 24 +++- src/chat/run/provider_turn.rs | 29 +++- src/chat/session_store.rs | 13 +- src/chat/state/mod.rs | 7 +- src/chat/state/reduce_session.rs | 35 ++++- src/chat/turn_replay.rs | 96 +++++++++++-- 11 files changed, 407 insertions(+), 84 deletions(-) diff --git a/docs/unified-turn-context.md b/docs/unified-turn-context.md index 3042c622d..9682bb7ef 100644 --- a/docs/unified-turn-context.md +++ b/docs/unified-turn-context.md @@ -79,19 +79,30 @@ Channels, scheduled turns and children are not covered yet. ## Replayed history in terminal chat -`prx chat` (TUI and `--plain`) replays the form each earlier request was sent -in. A user turn keeps what was put around its text when it was sent (the masked -recall text before it, attached `@path` text and the date line after it) in the -optional `sent` field of its runtime record (`TurnToolEvidence` in -`src/agent/tool_evidence.rs`), set by the action `TurnRecordsAttached` after the -commit. The field is saved with the session JSON (`schema_version` stays 1; an -older reader ignores the unknown optional field and an older file loads with no -sent form). The provider view is rendered by `turn_history::project`, which -replays `prefix + text + tail`, so the first message has the same bytes in every -request, after `/resume` and after a restart; the canonical history, the -compaction guard and the reducer form still hold the typed text only. The TUI, -`/history`, the session list and exports show the typed text; the JSON export -drops the field. +`prx chat` (TUI and `--plain`) replays the same two things, carried on the +stored chat turn's runtime record (`TurnToolEvidence` in +`src/agent/tool_evidence.rs`) and rendered by `turn_history::project`, so the +provider view, the compaction guard and the reducer form keep describing the same +canonical messages (the canonical history still holds the typed text only). + +- Sent form. A user turn keeps what was put around its text when it was sent + (the masked recall text before it, attached `@path` text and the date line + after it) in the optional `sent` field of its record. The field is saved with + the session JSON (`schema_version` stays 1; an older reader ignores the unknown + optional field and an older file loads with no sent form). The provider view + replays `prefix + text + tail`, so the first message has the same bytes in + every request, after `/resume` and after a restart. The TUI, `/history`, the + session list and exports show the typed text; the JSON export drops the field. +- Tool rounds. After each commit the run's `tool.call.recorded` / + `tool.result.recorded` rows are read back and attached to the committed + assistant turn (action `TurnRecordsAttached`), and when a saved session is + loaded each reply is tied to its run by its text, from the newest back. The + rounds are not saved with the session. The view holds them in the gateway's + native envelope form between the user message and the reply; a reply with + replayed rounds no longer carries the `[tool evidence: ...]` line, a reply + without stored rows (an older session) keeps it. Before each turn the oldest + replayed results become the gateway's one-line stubs while the request is over + the warning threshold; compaction then runs unchanged on the canonical history. ## Ownership diff --git a/src/agent/tool_evidence.rs b/src/agent/tool_evidence.rs index 1ffc0cd41..129bb4487 100644 --- a/src/agent/tool_evidence.rs +++ b/src/agent/tool_evidence.rs @@ -112,6 +112,11 @@ pub struct TurnToolEvidence { /// turn's own text stays what the user typed. #[serde(default, skip_serializing_if = "Option::is_none")] pub sent: Option, + /// The tool rounds of an `assistant` turn, replayed before its reply. + /// Never saved: it is rebuilt from the durable log after a commit and + /// when a session is loaded. + #[serde(skip)] + pub replay: Option>, } /// Serde's `skip_serializing_if` callback, which receives a reference. @@ -199,6 +204,8 @@ fn sanitize_tool_name(name: &str) -> String { /// `content` followed by the evidence suffix, borrowed when the turn has no /// record (an untracked turn renders nothing). pub(crate) fn render_assistant_content<'a>(content: &'a str, evidence: Option<&TurnToolEvidence>) -> Cow<'a, str> { + // A turn whose tool rounds are replayed needs no summary line. + let evidence = evidence.filter(|evidence| evidence.replay.is_none()); evidence.map_or(Cow::Borrowed(content), |evidence| { let suffix = evidence.suffix(); let mut rendered = String::with_capacity(content.len().saturating_add(suffix.len())); diff --git a/src/agent/tool_replay.rs b/src/agent/tool_replay.rs index 64a0d51f7..5dbdba9f4 100644 --- a/src/agent/tool_replay.rs +++ b/src/agent/tool_replay.rs @@ -85,6 +85,8 @@ pub(crate) struct ReplayLog { attachments: HashMap, /// The run of each stored user or assistant message, by event id. run_of_event: HashMap, + /// The stored assistant replies, oldest first: text and run. + assistant_runs: Vec<(String, String)>, } fn payload_of(event: &MessageEvent) -> Option { @@ -111,35 +113,52 @@ impl ReplayLog { /// Read the session's tool, attachment and message rows. A read that fails /// leaves the log empty, so the turn replays as it did before these rows. pub(crate) async fn load(mem: &dyn crate::memory::Memory, principal: &MemoryPrincipal) -> Self { + Self::load_rows(mem, principal, true).await + } + + /// As [`Self::load`] without the user and assistant rows: enough to build + /// [`Self::replay_of_run`]. + pub(crate) async fn load_tool_rows(mem: &dyn crate::memory::Memory, principal: &MemoryPrincipal) -> Self { + Self::load_rows(mem, principal, false).await + } + + async fn load_rows(mem: &dyn crate::memory::Memory, principal: &MemoryPrincipal, with_messages: bool) -> Self { let query = |roles: &[&str]| SessionContextQuery { principal: principal.clone(), since_event_id: None, limit: REPLAY_ROW_LIMIT, include_roles: roles.iter().map(|role| (*role).to_owned()).collect(), }; - let (tool_rows, message_rows) = match ( - mem.load_recent_session_context(query(&["tool"])).await, - mem.load_recent_session_context(query(&["user", "assistant"])).await, - ) { - (Ok(tool_rows), Ok(message_rows)) => (tool_rows, message_rows), + let tool_rows = mem.load_recent_session_context(query(&["tool"])).await; + let message_rows = if with_messages { + mem.load_recent_session_context(query(&["user", "assistant"])).await + } else { + Ok(Vec::new()) + }; + match (tool_rows, message_rows) { + (Ok(tool_rows), Ok(message_rows)) => Self::from_rows(&tool_rows, &message_rows), (Err(error), _) | (_, Err(error)) => { tracing::warn!( error = %crate::agent::diagnostics::error_class(&error), "tool replay rows unavailable; history is replayed without them" ); - return Self::default(); + Self::default() } - }; - Self::from_rows(&tool_rows, &message_rows) + } } fn from_rows(tool_rows: &[MessageEvent], message_rows: &[MessageEvent]) -> Self { let mut log = Self::default(); - for event in message_rows { + let mut ordered: Vec<&MessageEvent> = message_rows.iter().collect(); + ordered.sort_by_key(|event| event.id); + for event in ordered { if event.event_type == "message.created" && let Some(run_id) = &event.run_id { log.run_of_event.insert(event.event_id.clone(), run_id.clone()); + if event.role == "assistant" { + log.assistant_runs.push((event.content.clone(), run_id.clone())); + } } } for event in tool_rows { @@ -213,6 +232,34 @@ impl ReplayLog { } } + /// The tool rounds of `run_id` in replay form, `None` when it made none. + pub(crate) fn replay_of_run(&self, run_id: &str) -> Option { + let mut replay = TurnReplay::default(); + for round in self.rounds.get(run_id)?.values() { + replay.push_round(round); + } + (!replay.messages.is_empty()).then_some(replay) + } + + /// The run of each reply in `replies` (oldest first), matched with the + /// stored assistant messages from the newest back by their text. A reply + /// that does not match its stored message, and every older one, gets + /// `None`: a run is never guessed. + pub(crate) fn runs_of_replies(&self, replies: &[&str]) -> Vec> { + let mut runs = vec![None; replies.len()]; + let pairs = runs + .iter_mut() + .rev() + .zip(replies.iter().rev().zip(self.assistant_runs.iter().rev())); + for (slot, (reply, (stored, run))) in pairs { + if *reply != stored.as_str() { + break; + } + *slot = Some(run.as_str()); + } + runs + } + /// The stored turns as history messages, in order: each user message with /// its stored attachment, each assistant reply preceded by the tool rounds /// of its run. Event ids line up with the messages, `None` for a replayed @@ -225,11 +272,9 @@ impl ReplayLog { if turn.role == "assistant" && let Some(run_id) = event_id.as_deref().and_then(|id| self.run_of_event.get(id)) && replayed_runs.insert(run_id.as_str()) - && let Some(rounds) = self.rounds.get(run_id) + && let Some(replay) = self.replay_of_run(run_id) { - for round in rounds.values() { - out.push_round(round); - } + out.push_replay(&replay); } let content = match (turn.role.as_str(), event_id.as_deref().and_then(|id| self.attachments.get(id))) { ("user", Some(attachment)) => format!("{}{}{}", attachment.prefix, turn.content, attachment.tail), @@ -245,8 +290,8 @@ impl ReplayLog { /// A replayed result message, kept so it can be turned into a stub. #[derive(Debug, Clone)] -struct ReplayedResult { - /// Index into [`ReplayedTurns::messages`]. +pub struct ReplayedResult { + /// Index of the result message in the messages that hold it. index: usize, wire_id: String, tool: String, @@ -255,6 +300,22 @@ struct ReplayedResult { document_id: Option, } +/// The tool rounds of one run as history messages: for each round an +/// assistant envelope carrying the calls, then one `tool` message per call. +#[derive(Debug, Clone, Default)] +pub struct TurnReplay { + pub(crate) messages: Vec, + results: Vec, +} + +impl PartialEq for TurnReplay { + fn eq(&self, other: &Self) -> bool { + crate::agent::turn_history::same_messages(&self.messages, &other.messages) + } +} + +impl Eq for TurnReplay {} + /// The turns of a session as history messages, with their tool rounds. #[derive(Debug, Default)] pub(crate) struct ReplayedTurns { @@ -270,7 +331,7 @@ fn result_message(wire_id: &str, content: &str) -> ChatMessage { ChatMessage::tool(serde_json::json!({ "tool_call_id": wire_id, "content": content }).to_string()) } -impl ReplayedTurns { +impl TurnReplay { fn push_round(&mut self, round: &StoredRound) { if round.calls.is_empty() { return; @@ -286,7 +347,6 @@ impl ReplayedTurns { .collect(); self.messages .push(ChatMessage::assistant(build_native_assistant_history("", &calls, None))); - self.event_ids.push(None); for call in round.calls.values() { let id = wire_id(&call.call_id); let stored = round.results.get(&call.call_id); @@ -300,9 +360,21 @@ impl ReplayedTurns { document_id: stored.and_then(|result| result.document_id.clone()), }); self.messages.push(result_message(&id, content)); - self.event_ids.push(None); } } +} + +impl ReplayedTurns { + /// Append `replay` after the messages held so far. + fn push_replay(&mut self, replay: &TurnReplay) { + let base = self.messages.len(); + self.messages.extend(replay.messages.iter().cloned()); + self.event_ids.extend(replay.messages.iter().map(|_| None)); + self.results.extend(replay.results.iter().map(|result| ReplayedResult { + index: result.index + base, + ..result.clone() + })); + } /// Replace the oldest replayed results by a stub, as many as it takes for /// the request (`leading`, these turns, `request`) to fit under the @@ -314,36 +386,85 @@ impl ReplayedTurns { request: &ChatMessage, config: &crate::config::AgentCompactionConfig, ) -> usize { - if self.results.is_empty() { - return 0; + fit_results( + &mut self.messages, + &self.results, + std::slice::from_ref(leading), + std::slice::from_ref(request), + config, + ) + } +} + +/// Replace the oldest of `results` (in `messages`) by a stub until +/// `before`, `messages` and `after` together fit under the compaction warning +/// threshold. Returns how many were stubbed. +fn fit_results( + messages: &mut [ChatMessage], + results: &[ReplayedResult], + before: &[ChatMessage], + after: &[ChatMessage], + config: &crate::config::AgentCompactionConfig, +) -> usize { + if results.is_empty() { + return 0; + } + let mut whole = Vec::with_capacity(messages.len() + before.len() + after.len()); + whole.extend(before.iter().cloned()); + whole.extend(messages.iter().cloned()); + whole.extend(after.iter().cloned()); + let budget = plan_context_budget(&whole, config, PRE_TURN_FLUSH_THRESHOLD); + if !budget.over_warning { + return 0; + } + let mut excess = budget.used_tokens.saturating_sub(budget.warning_threshold_tokens); + let mut stubbed = 0; + for result in results { + if excess == 0 { + break; } - let mut whole = Vec::with_capacity(self.messages.len() + 2); - whole.push(leading.clone()); - whole.extend(self.messages.iter().cloned()); - whole.push(request.clone()); - let budget = plan_context_budget(&whole, config, PRE_TURN_FLUSH_THRESHOLD); - if !budget.over_warning { - return 0; + let Some(message) = messages.get_mut(result.index) else { continue }; + let stub = result_message(&result.wire_id, &stub_text(result)); + let saved = estimate_history_tokens(std::slice::from_ref(message)) + .saturating_sub(estimate_history_tokens(std::slice::from_ref(&stub))); + if saved == 0 { + continue; } - let mut excess = budget.used_tokens.saturating_sub(budget.warning_threshold_tokens); - let mut stubbed = 0; - for result in &self.results { - if excess == 0 { - break; - } - let Some(message) = self.messages.get_mut(result.index) else { continue }; - let stub = result_message(&result.wire_id, &stub_text(result)); - let saved = estimate_history_tokens(std::slice::from_ref(message)) - .saturating_sub(estimate_history_tokens(std::slice::from_ref(&stub))); - if saved == 0 { + *message = stub; + excess = excess.saturating_sub(saved); + stubbed += 1; + } + stubbed +} + +/// Terminal chat: replace the oldest replayed results held in `view` by a +/// stub until `view` and the `request` that follows it fit under the warning +/// threshold. `replays` are the replayed rounds of the view's turns, oldest +/// first; a result is found in the view by its bytes, in order, and one that +/// is not found is left alone. Returns how many were stubbed. +pub(crate) fn stub_replayed_results( + view: &mut [ChatMessage], + replays: &[&TurnReplay], + request: &ChatMessage, + config: &crate::config::AgentCompactionConfig, +) -> usize { + let mut found = Vec::new(); + let mut cursor = 0; + for replay in replays { + for result in &replay.results { + let Some(original) = replay.messages.get(result.index) else { continue }; + let Some(offset) = view + .get(cursor..) + .and_then(|rest| rest.iter().position(|m| m.role == "tool" && m.content == original.content)) + else { continue; - } - *message = stub; - excess = excess.saturating_sub(saved); - stubbed += 1; + }; + let index = cursor.saturating_add(offset); + found.push(ReplayedResult { index, ..result.clone() }); + cursor = index.saturating_add(1); } - stubbed } + fit_results(view, &found, &[], std::slice::from_ref(request), config) } /// The one-line text a cleared result is replaced by. diff --git a/src/agent/turn_history.rs b/src/agent/turn_history.rs index da633cab5..309a13c1a 100644 --- a/src/agent/turn_history.rs +++ b/src/agent/turn_history.rs @@ -138,7 +138,7 @@ impl CanonicalHistory { } /// As [`Self::from_acknowledged`], with each stored turn's runtime record - /// (tool evidence of a reply, sent form of a request). + /// (tool evidence and replayed rounds of a reply, sent form of a request). pub(crate) fn from_acknowledged_turns<'a, I>(leading_system: Option<&str>, turns: I) -> Self where I: IntoIterator)>, @@ -687,6 +687,28 @@ pub(crate) fn project(canonical: &CanonicalHistory, inputs: &ProjectionInputs) - message.content = rendered; } } + // The tool rounds of an acknowledged reply come right before it. Where + // each canonical message starts in the expanded view is kept for the + // refresh notes, which are placed by canonical index. + let mut starts = Vec::new(); + if canonical + .evidence + .iter() + .any(|evidence| evidence.as_deref().is_some_and(|evidence| evidence.replay.is_some())) + { + let mut expanded = Vec::with_capacity(messages.len()); + for (message, evidence) in std::mem::take(&mut messages).into_iter().zip(&canonical.evidence) { + starts.push(expanded.len()); + if message.role == "assistant" + && let Some(replay) = evidence.as_deref().and_then(|evidence| evidence.replay.as_ref()) + { + expanded.extend(replay.messages.iter().cloned()); + } + expanded.push(message); + } + starts.push(expanded.len()); + messages = expanded; + } if let Some((plain, enriched)) = &inputs.enriched_request && let Some(request) = messages .iter_mut() @@ -696,6 +718,7 @@ pub(crate) fn project(canonical: &CanonicalHistory, inputs: &ProjectionInputs) - *request = enriched.clone(); } for (offset, (at, note)) in inputs.refresh_notes.iter().enumerate() { + let at = starts.get(*at).copied().unwrap_or(*at); let index = at.saturating_add(offset).min(messages.len()); messages.insert(index, note.clone()); } diff --git a/src/chat/action.rs b/src/chat/action.rs index d00530bf4..fc608b55a 100644 --- a/src/chat/action.rs +++ b/src/chat/action.rs @@ -560,12 +560,17 @@ pub enum Action { /// inline path). The admission stays open until the turn commits; a /// failed or cancelled turn removes exactly this request, once. UserTurnAdmitted { admission: AdmissionId, content: String }, - /// After a turn's commit: attach the form the user's request was sent in - /// (`sent`) to the newest user turn holding `user_text` that has none, so - /// the provider view replays the request as it was sent. + /// After a turn's commit: attach what the runtime kept of the turn to the + /// stored turns it just recorded, so the provider view replays them as the + /// turn had them. `sent` is the form the user's request was sent in; it goes + /// to the newest user turn holding `user_text` that has none. `replay` holds + /// the tool rounds of the run that made `reply`; it goes to the newest + /// assistant turn when that turn is exactly `reply`. TurnRecordsAttached { user_text: String, sent: Option, + reply: Option, + replay: Option>, }, /// Ask the reducer to persist the assistant turn (writes session.turns + LLM history) RecordAssistantTurn { diff --git a/src/chat/provider_turns/section_1.rs b/src/chat/provider_turns/section_1.rs index 71db7098e..bac54afe7 100644 --- a/src/chat/provider_turns/section_1.rs +++ b/src/chat/provider_turns/section_1.rs @@ -1249,8 +1249,13 @@ async fn commit_completed_provider_turn( crate::chat::turn_replay::attach_turn_records( chat_dispatcher, turn_signal, + memory_fabric.memory().as_ref(), + memory_fabric.workspace_id(), + chat_session_key, + &pending.turn_run_id, &pending.user_input, pending.sent.as_ref(), + None, ) .await; adopt_committed_turn(history, chat_dispatcher, &pending, None); @@ -1311,8 +1316,13 @@ async fn commit_completed_provider_turn( crate::chat::turn_replay::attach_turn_records( chat_dispatcher, turn_signal, + memory_fabric.memory().as_ref(), + memory_fabric.workspace_id(), + chat_session_key, + &pending.turn_run_id, &pending.user_input, pending.sent.as_ref(), + Some(&final_text), ) .await; adopt_committed_turn(history, chat_dispatcher, &pending, Some(&final_text)); @@ -1350,8 +1360,8 @@ async fn commit_completed_provider_turn( /// ([`super::compaction::provider_view_from_acked`]). Without a compaction /// since the turn copied its view, the committed request and reply are /// appended; the request is in the form it was sent (recalled context, attached -/// files and date line kept beside the turn). After a worker compaction the -/// view is rebuilt +/// files and date line kept beside the turn), the reply is preceded by its tool +/// rounds. After a worker compaction the view is rebuilt /// from the committed snapshot instead: appending to the pre-compaction view /// would resend the replaced cold prefix and force another rollover or a lossy /// fallback on the next turn. @@ -1380,6 +1390,16 @@ fn adopt_committed_turn( |sent| sent.compose(&pending.user_input), ))); if let Some(reply) = reply { + // The tool rounds of the reply come right before it. + if let Some(replay) = acked + .session + .turns + .last() + .filter(|turn| turn.role == "assistant" && turn.content == reply) + .and_then(|turn| turn.tool_evidence.as_ref()?.replay.as_ref()) + { + history.extend(replay.messages.iter().cloned()); + } history.push(committed_reply_message(&acked, reply)); } } diff --git a/src/chat/run/provider_turn.rs b/src/chat/run/provider_turn.rs index 3635b3d6d..ffde13271 100644 --- a/src/chat/run/provider_turn.rs +++ b/src/chat/run/provider_turn.rs @@ -185,7 +185,7 @@ #[cfg(feature = "terminal-tui")] let compaction_epoch_at_start = admitted_session.compaction_epoch; #[cfg(feature = "terminal-tui")] - let history_for_provider = { + let mut history_for_provider = { let mut history_for_provider = history.clone(); history_for_provider.push(history_user_message.clone()); history_for_provider @@ -402,6 +402,21 @@ effective_compaction.config = admitted_binding.main_compaction() .ok_or_else(|| anyhow::anyhow!("chat compaction requires an admitted decision"))?.clone(); crate::providers::context_window::trace_effective_compaction_resolution(&effective_compaction); + // Earlier turns' tool results give way to one-line stubs, oldest first, + // before the request is over budget; the compaction below runs as before. + let stubbed_results = super::turn_replay::stub_replayed_results( + &mut history, + &admitted_session.session, + &history_user_message, + &tool_surface_reserve.reserved_config(&effective_compaction.config), + ); + if stubbed_results > 0 { + tracing::info!(stubbed_results, "oldest replayed tool results were replaced by stubs to fit the request"); + #[cfg(feature = "terminal-tui")] + for (target, stubbed) in history_for_provider.iter_mut().zip(&history) { + target.clone_from(stubbed); + } + } #[cfg(feature = "terminal-tui")] refresh_context_budget_for_tui( &history_for_provider, @@ -1614,7 +1629,11 @@ { anyhow::bail!("Chat stopped after an unconfirmed history commit: {error}"); } - super::turn_replay::attach_turn_records(&chat_dispatcher, &turn_signal, &user_input, sent_form.as_ref()).await; + super::turn_replay::attach_turn_records( + &chat_dispatcher, &turn_signal, memory_fabric.memory().as_ref(), memory_fabric.workspace_id(), + &chat_session_key, &turn_run_id, &user_input, sent_form.as_ref(), None, + ) + .await; super::compaction::reconcile_inline_turn(&mut history, &chat_dispatcher); if let Some(ref d_id) = draft_id && let Err(e) = terminal.cancel_draft("user", d_id).await @@ -1732,7 +1751,11 @@ { anyhow::bail!("Chat stopped after an unconfirmed history commit: {error}"); } - super::turn_replay::attach_turn_records(&chat_dispatcher, &turn_signal, &user_input, sent_form.as_ref()).await; + super::turn_replay::attach_turn_records( + &chat_dispatcher, &turn_signal, memory_fabric.memory().as_ref(), memory_fabric.workspace_id(), + &chat_session_key, &turn_run_id, &user_input, sent_form.as_ref(), Some(&response), + ) + .await; super::compaction::reconcile_inline_turn(&mut history, &chat_dispatcher); #[cfg(feature = "terminal-tui")] if let Some(tx) = redraw_tx_for_main.as_ref() { diff --git a/src/chat/session_store.rs b/src/chat/session_store.rs index 2fa1d8339..580cccd16 100644 --- a/src/chat/session_store.rs +++ b/src/chat/session_store.rs @@ -216,7 +216,9 @@ pub(super) async fn project_chat_session_from_message_events( }; } }; - let projection = apply_chat_message_event_projection(snapshot, &events, cost_config); + let mut projection = apply_chat_message_event_projection(snapshot, &events, cost_config); + // The tool rounds of each reply are read back from the durable log. + super::turn_replay::attach_stored_replays(mem, workspace_id, &mut projection.session).await; tracing::debug!( session_id = %crate::agent::diagnostics::text_class(&session_id), turns_from_events = projection.turns_from_events, @@ -348,8 +350,8 @@ pub(super) fn session_turns_to_history(session: &session::ChatSession) -> Vec Vec { let history = session_turns_to_history(session); @@ -373,6 +375,11 @@ pub(super) fn session_turns_to_provider_view(session: &session::ChatSession) -> if let std::borrow::Cow::Owned(rendered) = rendered { message.content = rendered; } + if message.role == "assistant" + && let Some(replay) = evidence.and_then(|evidence| evidence.replay.as_ref()) + { + view.extend(replay.messages.iter().cloned()); + } view.push(message); } view diff --git a/src/chat/state/mod.rs b/src/chat/state/mod.rs index 574ace0ae..a9e80cca1 100644 --- a/src/chat/state/mod.rs +++ b/src/chat/state/mod.rs @@ -1437,7 +1437,12 @@ impl ChatState { Action::SessionSwitched { id } => self.reduce_session_switched(id), Action::RecordUserTurn(content) => self.reduce_record_user_turn(content), Action::UserTurnAdmitted { admission, content } => self.reduce_user_turn_admitted(admission, content), - Action::TurnRecordsAttached { user_text, sent } => self.reduce_turn_records_attached(&user_text, sent), + Action::TurnRecordsAttached { + user_text, + sent, + reply, + replay, + } => self.reduce_turn_records_attached(&user_text, sent, reply.as_deref(), replay), Action::RecordAssistantTurn { task_id, content } => self.reduce_record_assistant_turn(task_id, content), Action::RecordSystemMessage { content } => self.reduce_record_system_message(content), Action::SetLeadingSystemPrompt { content } => self.reduce_set_leading_system_prompt(content), diff --git a/src/chat/state/reduce_session.rs b/src/chat/state/reduce_session.rs index 3ffec9ffb..bb8fde0dc 100644 --- a/src/chat/state/reduce_session.rs +++ b/src/chat/state/reduce_session.rs @@ -345,16 +345,20 @@ impl ChatState { effects } - /// `Action::TurnRecordsAttached` — keep, beside the turn a commit just - /// recorded, the form its request was sent in (saved with the session). - /// Nothing is attached to a turn that is not exactly the one the action - /// names; the stored text of a turn never changes. + /// `Action::TurnRecordsAttached` — keep, beside the turns a commit just + /// recorded, the form the request was sent in (saved with the session) and + /// the tool rounds of the reply (rebuilt from the durable log, never + /// saved). Nothing is attached to a turn that is not exactly the one the + /// action names; the stored text of a turn never changes. pub(super) fn reduce_turn_records_attached( &mut self, user_text: &str, sent: Option, + reply: Option<&str>, + replay: Option>, ) -> Vec { let user_text = crate::agent::turn_contracts::neutralize_reserved_markers(user_text); + let mut sent_attached = false; if let Some(sent) = sent && let Some(turn) = self.session.turns.iter_mut().rev().find(|turn| { turn.role == "user" @@ -363,9 +367,28 @@ impl ChatState { }) { turn.tool_evidence.get_or_insert_with(Default::default).sent = Some(sent); - return vec![Effect::SaveSession(self.session_commit())]; + sent_attached = true; + } + let mut replay_attached = false; + if let Some(replay) = replay + && let Some(turn) = self + .session + .turns + .iter_mut() + .rev() + .find(|turn| turn.role == "assistant") + .filter(|turn| Some(turn.content.as_str()) == reply) + { + turn.tool_evidence.get_or_insert_with(Default::default).replay = Some(replay); + replay_attached = true; + } + if sent_attached { + vec![Effect::SaveSession(self.session_commit())] + } else if replay_attached { + vec![Effect::PublishSession(self.session_commit())] + } else { + Vec::new() } - Vec::new() } /// `Action::RecordAssistantTurn` — persist an assistant turn into the session record and LLM history. diff --git a/src/chat/turn_replay.rs b/src/chat/turn_replay.rs index cc99440ec..80d0b3705 100644 --- a/src/chat/turn_replay.rs +++ b/src/chat/turn_replay.rs @@ -1,15 +1,22 @@ //! What chat keeps of a finished turn beyond its text, so a later turn's //! provider view replays it as the turn had it: the form the user's request was -//! sent in. +//! sent in and the tool rounds of the run that made the reply. //! -//! It rides on the stored turn's runtime record -//! ([`crate::agent::tool_evidence::TurnToolEvidence`]) and is rendered by +//! Both ride on the stored turn's runtime record +//! ([`crate::agent::tool_evidence::TurnToolEvidence`]) and are rendered by //! [`crate::agent::turn_history::project`], so the provider view, the //! compaction guard and the reducer form keep describing the same canonical -//! messages (the canonical history holds the typed text only). +//! messages. The tool rounds come from the durable log +//! ([`crate::agent::tool_replay`]); they are attached after each commit and when +//! a saved session is loaded, and never saved with the session. +use super::chat_events::chat_runtime_envelope; use super::dispatcher::{ChatDispatcher, TurnCompletionSignal}; -use crate::agent::tool_replay::Attachment; +use super::session::ChatSession; +use crate::agent::tool_replay::{Attachment, ReplayLog, TurnReplay}; +use crate::memory::Memory; +use crate::providers::ChatMessage; +use std::sync::Arc; /// The request as it is sent, and what was put around the typed `user_input`. /// `prompt` is `user_input` possibly followed by attached file text; when it @@ -32,23 +39,94 @@ pub(super) fn sent_request( (sent.compose(user_input), Some(sent)) } -/// After a turn's commit: hand the reducer the sent form of the request, to -/// attach to the turn it just recorded. Nothing is sent when there is none. +/// After a turn's commit: hand the reducer the sent form of the request and the +/// tool rounds of run `run_id`, to attach to the turns it just recorded. The +/// rounds are read back from the durable log. Nothing is sent when there is +/// nothing to attach. +#[allow(clippy::too_many_arguments)] pub(super) async fn attach_turn_records( chat_dispatcher: &ChatDispatcher, commits: &TurnCompletionSignal, + memory: &dyn Memory, + workspace_id: &str, + chat_session_key: &str, + run_id: &str, user_text: &str, sent: Option<&Attachment>, + reply: Option<&str>, ) { - let Some(sent) = sent else { return }; + let replay = if reply.is_some() { + let principal = chat_runtime_envelope(workspace_id, chat_session_key).memory_principal(); + ReplayLog::load_tool_rows(memory, &principal) + .await + .replay_of_run(run_id) + .map(Arc::new) + } else { + None + }; + if sent.is_none() && replay.is_none() { + return; + } // A failed acknowledgement latches the unconfirmed-commit stop itself. let _ = chat_dispatcher .dispatch_awaited( super::action::Action::TurnRecordsAttached { user_text: user_text.to_owned(), - sent: Some(sent.clone()), + sent: sent.cloned(), + reply: reply.map(str::to_owned), + replay, }, commits, ) .await; } + +/// A loaded session: attach to each assistant reply the tool rounds of the run +/// that made it, read from the durable log. A reply is tied to its run by its +/// text, from the newest back; a reply that does not match, and every older +/// one, keeps its tool evidence line. +pub(super) async fn attach_stored_replays(mem: &dyn Memory, workspace_id: &str, session: &mut ChatSession) { + if !session.turns.iter().any(|turn| turn.role == "assistant") { + return; + } + let principal = chat_runtime_envelope(workspace_id, &session.id).memory_principal(); + let log = ReplayLog::load(mem, &principal).await; + let runs: Vec> = { + let replies: Vec<&str> = session + .turns + .iter() + .filter(|turn| turn.role == "assistant") + .map(|turn| turn.content.as_str()) + .collect(); + log.runs_of_replies(&replies) + .into_iter() + .map(|run| run.map(str::to_owned)) + .collect() + }; + let replies = session.turns.iter_mut().filter(|turn| turn.role == "assistant"); + for (turn, run) in replies.zip(runs) { + if let Some(replay) = run.and_then(|run| log.replay_of_run(&run)) { + turn.tool_evidence.get_or_insert_with(Default::default).replay = Some(Arc::new(replay)); + } + } +} + +/// Before a turn: replace the oldest replayed tool results held in `view` by a +/// stub while `view` and `request` are over the warning threshold. The replayed +/// rounds are those of `session`'s turns. Returns how many were stubbed. +pub(super) fn stub_replayed_results( + view: &mut [ChatMessage], + session: &ChatSession, + request: &ChatMessage, + config: &crate::config::AgentCompactionConfig, +) -> usize { + let replays: Vec<&TurnReplay> = session + .turns + .iter() + .filter_map(|turn| turn.tool_evidence.as_ref()?.replay.as_deref()) + .collect(); + if replays.is_empty() { + return 0; + } + crate::agent::tool_replay::stub_replayed_results(view, &replays, request, config) +} From 1c1f3f7085203f6ef29271dba4d301204c5dac34 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:46:06 +0400 Subject: [PATCH 0160/1567] feat(tools): defer tool definitions automatically when they exceed a quarter of the model window Publish every tool when the definitions fit; otherwise keep the listed direct tools and defer the rest behind the search tool with an index of names. defer_unlisted becomes optional: unset means automatic, true or false forces it. --- docs/configuration.md | 10 +- docs/migration-unreleased.md | 2 +- docs/tools.md | 13 ++ src/agent/budget_inputs.rs | 17 +++ src/agent/context_budget.rs | 13 +- src/chat/binding.rs | 7 ++ src/chat/dispatcher.rs | 1 + src/chat/run/provider_turn.rs | 3 + src/config/generation/section_2.rs | 2 +- src/config/schema/security.rs | 19 ++- .../child_source/golden_effective_config.json | 2 +- src/runtime/turn_context.rs | 1 + src/runtime/turn_context/opened_turn.rs | 9 ++ src/runtime/turn_context/opening.rs | 34 +++-- src/runtime/turn_context/tool_fit.rs | 119 ++++++++++++++++++ src/runtime/turn_publication.rs | 2 +- src/session_worker/runner/run.rs | 4 +- src/tools/capability/catalog/section_1.rs | 9 ++ src/tools/capability/search_tool.rs | 1 + .../capability/search_tool/deferred_index.rs | 91 ++++++++++++++ .../search_tool/discovery_admission.rs | 20 ++- src/tools/surface_owner/facts.rs | 5 + src/tools/surface_owner/publication.rs | 4 +- src/tools/surface_owner/tests.rs | 1 + tests/fixtures/config-schema.json | 2 +- 25 files changed, 364 insertions(+), 27 deletions(-) create mode 100644 src/runtime/turn_context/tool_fit.rs create mode 100644 src/tools/capability/search_tool/deferred_index.rs diff --git a/docs/configuration.md b/docs/configuration.md index 80212960a..5a8a559ad 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -157,7 +157,7 @@ and the module-gate family are absorbed on load; they are not live switches. | `[security]` | `workspace_hooks` omitted when off | | `[compliance.interaction_notice]` | `version = "1"`; default notice text; `applicability = "required"`; `exception_owner`/`exception_reviewed_at` unset | | `[compliance.eu_ai_act]` | classification `status = "unclassified"`; `owner`/`assessed_at` unset; `incident_store_path` unset; declaration fields all optional/empty | -| `[tool_tiering]` | `always_include = []`; `always_exclude = []`; `channel_exclude = []` (nothing hidden from channel sessions); `defer_unlisted = false` (every available tool is published to the model) | +| `[tool_tiering]` | `always_include = []`; `always_exclude = []`; `channel_exclude = []` (nothing hidden from channel sessions); `defer_unlisted` unset (every available tool is published to the model, unless their definitions would take more than a quarter of the model's context window; then that turn defers them) | | `[providers]` | `[providers.ollama] num_ctx` unset. `[[providers.tool_dialects]]`: `provider` required; `model` unset (all models); `tool_schema`/`tool_call` unset (`raw` / `native`). `[[providers.models]]`: `provider` required; `model` unset; `operations`, `native_tools`, `vision_input`, `streaming`, `structured_output`, `tool_schema_dialect`, `tool_call_dialect`, `context_window` all unset. See later sections | | `[model_settings.]` | catalog levels and explicit parameters; omitted keys stay with the catalog | @@ -718,7 +718,11 @@ low_priority_tools = ["sessions_spawn", "delegate"] # Per-turn capability policy. The surface owner applies these filters (they are # not owned by the decision engine). Every available tool is published to the -# model by default. `defer_unlisted = true` is the operator option that +# model by default, unless their definitions would take more than a quarter of +# the model's context window: a small window (for example 8k or 32k) then +# defers them for that turn, a 128k or 200k window publishes them all. +# `defer_unlisted = false` always publishes every tool, whatever the window. +# `defer_unlisted = true` is the operator option that # publishes only the core tools (file_read, file_write, file_edit, shell) plus # `always_include`; every other tool then waits behind `capability_search` and # can also be called by its exact name. `always_exclude` removes names from the @@ -736,7 +740,7 @@ low_priority_tools = ["sessions_spawn", "delegate"] always_include = [] always_exclude = [] # channel_exclude = [] -# defer_unlisted = false +# defer_unlisted = true # unset: publish all, deferring only on a small window # A request that advertises skill metadata also admits its live skill_read # dependency. Missing or denied readers suppress that metadata with a diagnostic. diff --git a/docs/migration-unreleased.md b/docs/migration-unreleased.md index 5d222ac41..925134edf 100644 --- a/docs/migration-unreleased.md +++ b/docs/migration-unreleased.md @@ -30,7 +30,7 @@ of the [changelog](../CHANGELOG.md). | Known Codex model default effort | Declared Codex rows now use `medium` rather than `xhigh`. Set an explicit supported effort if the former behavior is required. Unknown rows keep the legacy `medium` verbosity / `xhigh` effort base. See [model levels and parameters](model-catalog.md). | Only to retain the former effort | | No spend ceiling by default | `[autonomy] max_cost_per_day_cents`, `[cost] daily_limit_usd` and `[cost] monthly_limit_usd` are now optional and unset by default. Before: a config that omitted them got 500 cents per day, 10.0 USD per day and 100.0 USD per month. Now: a config that omits them has no limit, so no spend is refused for a budget reason, no budget warning or "budget exhausted" notice is printed, and children and worker processes get the maximum allowance (`u32::MAX` cents in the signed manifest). A config that sets any of these keys keeps exactly that limit. `prx init` no longer writes `max_cost_per_day_cents`. Usage accounting and the cost journal are unchanged. To keep the old ceilings, write them into the config. Per-agent `limits` were already unset by default. No stored-data migration is required. | Only to keep the former ceilings: set the three keys explicitly | | Nothing restricted by default on a fresh install | `[tool_tiering] channel_exclude` now defaults to an empty list (before: 14 operations tools such as `gateway`, `config_reload`, `nodes`, `skills_manage` were hidden from IM channel turns); a config that omits it now exposes those tools on channel turns, and a config that lists names keeps hiding them. `prx init --spec server` no longer writes `workspace_only`, `forbidden_paths` or `acknowledge_unrestricted_profile` (the built-in values are unchanged and have no effect at level `full`); `--spec full` no longer writes `acknowledge_unrestricted_profile`. `prx doctor` no longer warns for an explicit unrestricted profile; it prints one neutral autonomy-level line, and `acknowledge_unrestricted_profile` is accepted and ignored. Gateway pairing, channel sender allowlists, secret protection and integrity checks are unchanged. | Only to keep the old channel tool hiding: list the names in `channel_exclude` | -| Every tool published by default | The model is now offered every available tool directly on every surface (terminal chat, gateway, channels, scheduled runs, children), in a stable name order. Before: only `file_read`, `file_write`, `file_edit`, `shell` and a few session tools were offered and the rest sat behind `capability_search`, so `cron`, `sessions_spawn` and `skills_manage` went unused unless named in `[tool_tiering] always_include`. The request carries more tool definitions, so each request uses more of the context window. `always_exclude` and `channel_exclude` still hide names. | Only to keep the old deferral: set `[tool_tiering] defer_unlisted = true`; the core tools, `always_include` names and `capability_search` then work as before, and a deferred tool can also be called by its exact name | +| Every tool published by default | The model is now offered every available tool directly on every surface (terminal chat, gateway, channels, scheduled runs, children), in a stable name order. Before: only `file_read`, `file_write`, `file_edit`, `shell` and a few session tools were offered and the rest sat behind `capability_search`, so `cron`, `sessions_spawn` and `skills_manage` went unused unless named in `[tool_tiering] always_include`. The request carries more tool definitions, so each request uses more of the context window. `always_exclude` and `channel_exclude` still hide names. When the definitions would take more than a quarter of the model's context window (an 8k or 32k window), that turn defers the tools as `defer_unlisted = true` does, with a name index on `capability_search`; `defer_unlisted = false` turns that off. | Only to keep the old deferral: set `[tool_tiering] defer_unlisted = true`; the core tools, `always_include` names and `capability_search` then work as before, and a deferred tool can also be called by its exact name | | Remote image fetch on by default | `[multimodal] allow_remote_fetch` now defaults to `true` (before: `false`). A config that omits it now lets `http`/`https` image references be fetched into the model context; an explicit `false` keeps the old behavior. The fetch keeps the same private-address handling as `web_fetch`: below Full private, loopback and link-local hosts are refused, at Full they are reachable. | Only to keep remote fetch off: set `allow_remote_fetch = false` | | Node agent allows any command by default | `[nodes.server] allowed_commands` now defaults to an empty list, which allows any command (before: `["echo"]`, so every other command was refused). A config that omits the key now lets an authenticated caller run any command; a config that lists commands keeps that allowlist. Authentication is unchanged: a non-empty bearer token is required at startup, `hmac_secret` is checked when set, `tls_required = true` still demands TLS on non-loopback binds, and the default bind is loopback. `blocked_commands` is still enforced. | Only to keep the old restriction: set `allowed_commands = ["echo"]` | | Autonomy path keys unset by default | `[autonomy] workspace_only` now defaults to `false` (before: `true`) and `forbidden_paths` to an empty list (before: 18 system paths). A config that omits them gets no workspace confinement and no path denylist; a config that sets them keeps exactly what it sets. Both keys are read below level `full` only (file tools, shell path arguments, image and document tools, the TUI file picker); at `full` they were already ignored. An install that runs `supervised` or `readonly` and relied on the old defaults must now write `workspace_only = true` and its `forbidden_paths`. Owner-private file operations stay confined to the workspace at every level, independent of these keys. `prx init` never writes these keys or `acknowledge_unrestricted_profile` (the latter is accepted from an existing config and ignored, and is no longer serialised). `prx status` prints a `Cost limits:` line (any configured `[cost]` or `[autonomy]` limit, or `no limit set`) instead of `Max cost/day:`, and prints `Workspace only:` and `Forbidden paths:` only when they are set. | Only for `supervised` or `readonly` installs: set `workspace_only` and `forbidden_paths` explicitly | diff --git a/docs/tools.md b/docs/tools.md index ad5ee0e02..3738810bb 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -50,6 +50,19 @@ declares it on the following request, and runs the call. Channel exclusions, model policy and issued child scope still apply. Search does not expand that scope. +The published definitions must fit the model's window. When they would take +more than a quarter of the context window, that turn defers the tools it would +otherwise publish, exactly as `defer_unlisted = true` does: the file/shell +core, the chat session tools, `always_include` names and the skill tools stay +direct, and the others stay reachable through `capability_search` and by exact +name. A compact index of the deferred tool names (about 2.4 KB at most) is +appended to the `capability_search` description, so a tool can be called by +name without a search round. The decision depends only on the window and the +tool set, so the tool definitions are the same on every turn of a session; it +is logged once per session (`window_tokens`, `tool_tokens`, `share_percent`, +`decision`). `defer_unlisted = false` turns the fit off (every tool is always +published); `defer_unlisted = true` always defers. + Eligible installed skills are advertised as metadata. A request that advertises skills includes an admitted `skill_read` definition; instruction bodies stay lazy. If the live reader cannot be admitted, the metadata is suppressed with a diff --git a/src/agent/budget_inputs.rs b/src/agent/budget_inputs.rs index f65b98106..6af3e1a40 100644 --- a/src/agent/budget_inputs.rs +++ b/src/agent/budget_inputs.rs @@ -18,6 +18,23 @@ pub(crate) const REPLY_RESERVE_WINDOW_DIVISOR: usize = 4; /// `1 / TOTAL_RESERVE_WINDOW_DIVISOR` of the window. pub(crate) const TOTAL_RESERVE_WINDOW_DIVISOR: usize = 2; +/// The published tool definitions may take at most +/// `1 / TOOL_SURFACE_WINDOW_DIVISOR` of the window and still be published in +/// full. A quarter is what is left of the half that [`reserved_budget_config`] +/// allows reply plus tools once the reply reserve has taken its own quarter, +/// so a surface within it never meets the total cap. +pub(crate) const TOOL_SURFACE_WINDOW_DIVISOR: usize = 4; + +/// Whether `tool_tokens` of tool definitions fit their share of `window_tokens`. +pub(crate) const fn tool_surface_fits_window(window_tokens: usize, tool_tokens: usize) -> bool { + tool_tokens.saturating_mul(TOOL_SURFACE_WINDOW_DIVISOR) <= window_tokens +} + +/// The share of the window the tool definitions may take, in percent. +pub(crate) const fn tool_surface_share_percent() -> usize { + 100 / TOOL_SURFACE_WINDOW_DIVISOR +} + /// The messages a switch keeps word for word occupy at most /// `1 / KEEP_RECENT_WINDOW_DIVISOR` of the window. pub(crate) const KEEP_RECENT_WINDOW_DIVISOR: usize = 4; diff --git a/src/agent/context_budget.rs b/src/agent/context_budget.rs index 7a6372cce..53c323f95 100644 --- a/src/agent/context_budget.rs +++ b/src/agent/context_budget.rs @@ -73,7 +73,7 @@ pub(super) const APPENDED_SECTION_FRAMING_TOKENS: usize = 4; /// native payload that rides beside the messages plus the prompt sections the /// compiled snapshot appends to the system message, with the framing those /// sections arrive in. -pub(super) const fn budgeted_request_tool_tokens( +pub(crate) const fn budgeted_request_tool_tokens( tool_surface: crate::agent::turn_context::RequestToolMeasurement, ) -> usize { let sections = budgeted_tokens(tool_surface.instructions); @@ -209,6 +209,17 @@ impl ToolSurfaceReserve { ); } + /// Set the reserve from the size known at turn opening, only while no + /// request has been measured yet; a measurement always replaces it. + pub(crate) fn seed_unmeasured(&self, tokens: usize) { + let _ = self.0.compare_exchange( + 0, + tokens, + std::sync::atomic::Ordering::Relaxed, + std::sync::atomic::Ordering::Relaxed, + ); + } + /// The tokens the last measured tool surface occupies in the window. pub(crate) fn tokens(&self) -> usize { self.0.load(std::sync::atomic::Ordering::Relaxed) diff --git a/src/chat/binding.rs b/src/chat/binding.rs index c8f7518ee..f8a0a5566 100644 --- a/src/chat/binding.rs +++ b/src/chat/binding.rs @@ -892,6 +892,13 @@ impl ChatTurnBinding { self.decision.get().map(|decided| decided.context.main_compaction()) } + /// Tokens the admitted turn's tool definitions are estimated to occupy. + pub(super) fn tool_surface_tokens(&self) -> usize { + self.decision + .get() + .map_or(0, |decided| decided.context.tool_surface_tokens()) + } + pub(super) fn effective_compaction( &self, ) -> anyhow::Result { diff --git a/src/chat/dispatcher.rs b/src/chat/dispatcher.rs index 37761e484..eb7919b4b 100644 --- a/src/chat/dispatcher.rs +++ b/src/chat/dispatcher.rs @@ -3012,6 +3012,7 @@ async fn drive_start_turn_stream( // One budget with the turn preflight: the last measured tool surface is // reserved here too, while the turn itself still receives the configured // budget and reserves its freshly measured surface. + tool_surface_reserve.seed_unmeasured(routing.context.tool_surface_tokens()); let reserved_compaction_config = compaction_config .as_ref() .map(|config| tool_surface_reserve.reserved_config(config)); diff --git a/src/chat/run/provider_turn.rs b/src/chat/run/provider_turn.rs index ffde13271..ae5c0a86a 100644 --- a/src/chat/run/provider_turn.rs +++ b/src/chat/run/provider_turn.rs @@ -402,6 +402,9 @@ effective_compaction.config = admitted_binding.main_compaction() .ok_or_else(|| anyhow::anyhow!("chat compaction requires an admitted decision"))?.clone(); crate::providers::context_window::trace_effective_compaction_resolution(&effective_compaction); + // The tool definitions' size is known at turn opening, so the first + // turn's capacity check reserves them like the engine preflight. + tool_surface_reserve.seed_unmeasured(admitted_binding.tool_surface_tokens()); // Earlier turns' tool results give way to one-line stubs, oldest first, // before the request is over budget; the compaction below runs as before. let stubbed_results = super::turn_replay::stub_replayed_results( diff --git a/src/config/generation/section_2.rs b/src/config/generation/section_2.rs index 1a9e636b0..12a1a50c9 100644 --- a/src/config/generation/section_2.rs +++ b/src/config/generation/section_2.rs @@ -32,7 +32,7 @@ mod tests { b"]", ] .concat(); - const FOR_CHILD_FINGERPRINT: &str = "205bb9dd92ff723b2353b3ee4bbf3d863c05c03a9befe49fe3506bfe4567f9c1"; + const FOR_CHILD_FINGERPRINT: &str = "98a73219ec8529e6afad412ada3e3009e10e6145d4d4f27b74db71ea0d367e18"; assert_eq!(format!("{:x}", sha2::Sha256::digest(&preimage)), FOR_CHILD_FINGERPRINT); assert_eq!(generation.source_revision.fingerprint_sha256, FOR_CHILD_FINGERPRINT); assert_eq!(generation.id.0, 0); diff --git a/src/config/schema/security.rs b/src/config/schema/security.rs index a81bfb8b6..16b273f0e 100644 --- a/src/config/schema/security.rs +++ b/src/config/schema/security.rs @@ -225,10 +225,11 @@ pub struct ToolTieringConfig { /// Tool names hidden from IM channel sessions only, on top of `always_exclude`. /// Default: empty (nothing is hidden); list tool names to hide them on channels. pub channel_exclude: Vec, - /// Operator option: publish only the core tools plus `always_include` and - /// leave every other tool behind `capability_search` and its exact name. - /// Default: false (every available tool is published to the model). - pub defer_unlisted: bool, + /// Operator option for the tools outside the core set. + /// - `None` (default): publish every available tool, unless their definitions would take more than a quarter of the model's context window; then the turn defers them, as `Some(true)` does. + /// - `Some(true)`: publish only the core tools plus `always_include` and leave every other tool behind `capability_search` and its exact name. + /// - `Some(false)`: always publish every available tool, whatever the window. + pub defer_unlisted: Option, } impl Default for ToolTieringConfig { @@ -237,12 +238,20 @@ impl Default for ToolTieringConfig { always_include: Vec::new(), always_exclude: Vec::new(), channel_exclude: Vec::new(), - defer_unlisted: false, + defer_unlisted: None, } } } impl ToolTieringConfig { + /// Whether the publication names every available tool directly (the + /// `"*"` member). Only an explicit `defer_unlisted = true` leaves it out; + /// the automatic window fit then decides per turn. + #[must_use] + pub const fn publishes_all_tools(&self) -> bool { + !matches!(self.defer_unlisted, Some(true)) + } + /// A policy that hides [`RECOMMENDED_CHANNEL_EXCLUDED_TOOLS`] from channel /// sessions: what an operator gets by copying that list into the config. #[must_use] diff --git a/src/runtime/child_source/golden_effective_config.json b/src/runtime/child_source/golden_effective_config.json index e3447a263..1616456d5 100644 --- a/src/runtime/child_source/golden_effective_config.json +++ b/src/runtime/child_source/golden_effective_config.json @@ -1 +1 @@ -{"a2a":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trust_domain":"prx.local","trusted_trust_domains":[]},"agent":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"messaging":{"inbound":true},"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2},"agents":{},"api_key":null,"api_url":null,"auth":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"},"autonomy":{"forbidden_paths":[],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]}},"browser":{"allowed_domains":[],"computer_use":{"api_key":null}},"channels_config":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null},"chat":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2},"compliance":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}},"composio":{"api_key":null,"entity_id":"default"},"cost":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{"alpha/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0},"zeta/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0}},"warn_at_percent":80},"cron":{"max_run_history":50},"decision_engine":{"backend":{"circuit_breaker":{"cooldown_secs":60,"failure_threshold":5},"credential_ref":"","endpoint":"","kind":"auto","max_request_bytes":65536,"max_response_bytes":262144,"model":"","pinned_snapshot":"","remote_enabled":false,"timeout_ms":250},"candidates":5,"enabled":false,"latency_budget_ms":500,"max_candidates":12,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"token_ratio_limit":0.3499999940395355},"default_model":"anthropic/claude-sonnet-5","default_provider":"openrouter","default_temperature":0.7,"embedding_routes":[],"gateway":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60},"heartbeat":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."},"http_request":{"max_response_size":1000000,"timeout_secs":30},"identity":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"},"identity_bindings":[],"mcp":{"servers":{}},"mcp_server":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true},"media":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"},"memory":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":true,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7},"model_routes":[],"model_settings":{},"multimodal":{"allow_remote_fetch":true,"max_image_size_mb":5,"max_images":4},"nodes":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":[],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}},"observability":{"backend":"none","otel_endpoint":null,"otel_service_name":null},"plugins":{"enabled":false},"providers":{"ollama":{"num_ctx":null}},"proxy":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]},"query_classification":{"rules":[]},"reliability":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2},"router":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]},"runtime":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null},"scheduler":{"claim_lease_secs":90,"max_tasks":64},"secrets":{"encrypt":true},"security":{"audit":{"log_path":"audit.log","max_size_mb":100}},"self_system":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24},"sessions_spawn":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null},"skill_rag":{"top_k":32},"skills":{"open_skills_dir":null,"openclaw_skills_dir":null},"skills_lifecycle":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]},"smart_group":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5},"storage":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}},"task_routing":{"default_intent":"simple","rules":[]},"tool_tiering":{"always_exclude":[],"always_include":[],"channel_exclude":[]},"tunnel":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null},"user_policies":[],"web_search":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15},"webhook":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null},"xin":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}} \ No newline at end of file +{"a2a":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trust_domain":"prx.local","trusted_trust_domains":[]},"agent":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"messaging":{"inbound":true},"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2},"agents":{},"api_key":null,"api_url":null,"auth":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"},"autonomy":{"forbidden_paths":[],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]}},"browser":{"allowed_domains":[],"computer_use":{"api_key":null}},"channels_config":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null},"chat":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2},"compliance":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}},"composio":{"api_key":null,"entity_id":"default"},"cost":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{"alpha/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0},"zeta/model":{"cache_read":0.0,"cache_write":0.0,"input":1.0,"output":2.0}},"warn_at_percent":80},"cron":{"max_run_history":50},"decision_engine":{"backend":{"circuit_breaker":{"cooldown_secs":60,"failure_threshold":5},"credential_ref":"","endpoint":"","kind":"auto","max_request_bytes":65536,"max_response_bytes":262144,"model":"","pinned_snapshot":"","remote_enabled":false,"timeout_ms":250},"candidates":5,"enabled":false,"latency_budget_ms":500,"max_candidates":12,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"token_ratio_limit":0.3499999940395355},"default_model":"anthropic/claude-sonnet-5","default_provider":"openrouter","default_temperature":0.7,"embedding_routes":[],"gateway":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60},"heartbeat":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."},"http_request":{"max_response_size":1000000,"timeout_secs":30},"identity":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"},"identity_bindings":[],"mcp":{"servers":{}},"mcp_server":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true},"media":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"},"memory":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":true,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7},"model_routes":[],"model_settings":{},"multimodal":{"allow_remote_fetch":true,"max_image_size_mb":5,"max_images":4},"nodes":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":[],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}},"observability":{"backend":"none","otel_endpoint":null,"otel_service_name":null},"plugins":{"enabled":false},"providers":{"ollama":{"num_ctx":null}},"proxy":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]},"query_classification":{"rules":[]},"reliability":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2},"router":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]},"runtime":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null},"scheduler":{"claim_lease_secs":90,"max_tasks":64},"secrets":{"encrypt":true},"security":{"audit":{"log_path":"audit.log","max_size_mb":100}},"self_system":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24},"sessions_spawn":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null},"skill_rag":{"top_k":32},"skills":{"open_skills_dir":null,"openclaw_skills_dir":null},"skills_lifecycle":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]},"smart_group":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5},"storage":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}},"task_routing":{"default_intent":"simple","rules":[]},"tool_tiering":{"always_exclude":[],"always_include":[],"channel_exclude":[],"defer_unlisted":null},"tunnel":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null},"user_policies":[],"web_search":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15},"webhook":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null},"xin":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}} \ No newline at end of file diff --git a/src/runtime/turn_context.rs b/src/runtime/turn_context.rs index e091e6783..81493efa1 100644 --- a/src/runtime/turn_context.rs +++ b/src/runtime/turn_context.rs @@ -418,6 +418,7 @@ mod execution_binding; mod opened_turn; mod opening; mod owner_filesystem; +mod tool_fit; pub(crate) mod publication_scope; pub(crate) mod surface_binding; diff --git a/src/runtime/turn_context/opened_turn.rs b/src/runtime/turn_context/opened_turn.rs index 610d53b45..b1932b036 100644 --- a/src/runtime/turn_context/opened_turn.rs +++ b/src/runtime/turn_context/opened_turn.rs @@ -20,6 +20,10 @@ pub(crate) struct OpenedTurn { pub(in crate::runtime) source_actor: (Arc, Arc), pub(in crate::runtime) service_id: uuid::Uuid, pub(in crate::runtime) main_compaction: crate::config::AgentCompactionConfig, + /// Budgeted tokens the published tool definitions occupy in a request, + /// measured at opening, so a budget check made before the first request + /// has been measured reserves them too. + pub(in crate::runtime) tool_surface_tokens: usize, /// The logical deadline of this turn, fixed at opening from its budget. pub(in crate::runtime) deadline: Instant, } @@ -42,6 +46,11 @@ impl OpenedTurn { &self.main_compaction } + /// Tokens the tool definitions of this turn are estimated to occupy. + pub(crate) const fn tool_surface_tokens(&self) -> usize { + self.tool_surface_tokens + } + pub(crate) fn decision_id(&self) -> DecisionId { self.runtime.decision_id } diff --git a/src/runtime/turn_context/opening.rs b/src/runtime/turn_context/opening.rs index a74dd34d2..469b743ee 100644 --- a/src/runtime/turn_context/opening.rs +++ b/src/runtime/turn_context/opening.rs @@ -216,7 +216,7 @@ impl TurnRuntimeService { }), None => None, }; - let facts = PublicationFacts { + let mut facts = PublicationFacts { policy: Arc::clone(&self.security), owner_id: Arc::from(proof.owner_id()), sender: Arc::from(proof.policy_sender()), @@ -241,15 +241,34 @@ impl TurnRuntimeService { .child_scope() .is_some_and(|scope| scope.gate_inputs().0.authority.level == crate::security::AutonomyLevel::Full) .then(|| Arc::new(self.child_served_entries(&catalog))), + fit_defers: false, }; // The published surface is an execution rule over the pinned scope, // the publication facts and the catalog (R28). - let published = crate::tools::surface_owner::publication::PublicationRules { - trusted: &trusted, - facts: &facts, - catalog: &catalog, - } - .surface(outgoing_delegation.is_some()); + let publish = |facts: &PublicationFacts| { + crate::tools::surface_owner::publication::PublicationRules { + trusted: &trusted, + facts, + catalog: &catalog, + } + .surface(outgoing_delegation.is_some()) + }; + let mut published = publish(&facts); + // Fit the tool definitions to the model's window (deterministic for + // the window and the tool set). A deferring turn is republished with + // only the tools the surface policy names. + let fit = self.fit_tool_surface( + proof.session_key(), + budget.main_compaction.max_context_tokens, + &published, + ); + let tool_surface_tokens = if fit.defers { + facts.fit_defers = true; + published = publish(&facts); + self.published_surface_tokens(&published, true) + } else { + fit.full_tokens + }; // The turn's one accounting scope, created at opening. Without the // prediction hop nothing has been charged to it yet. let accounting = accounting_scope(self, proof, budgets, deadline); @@ -284,6 +303,7 @@ impl TurnRuntimeService { source_actor: (Arc::from(proof.policy_channel()), Arc::from(proof.policy_sender())), service_id: self.service_id, main_compaction: budget.main_compaction, + tool_surface_tokens, deadline, })) } diff --git a/src/runtime/turn_context/tool_fit.rs b/src/runtime/turn_context/tool_fit.rs new file mode 100644 index 000000000..7f4d37285 --- /dev/null +++ b/src/runtime/turn_context/tool_fit.rs @@ -0,0 +1,119 @@ +//! Fit the published tool definitions to the model's context window. +//! +//! A default install publishes every available tool, which on a small window +//! leaves no room for the conversation. At turn opening the size of that +//! surface is measured with the budget's own estimator; when it would take +//! more than a fixed share of the window the turn defers every tool the +//! surface policy does not name, exactly as `defer_unlisted = true` does for +//! one turn. The deferred tools stay callable through `capability_search` and +//! by exact name; nothing becomes uncallable. +//! +//! The decision is a pure function of the window and the tool set, so the +//! tool prefix is the same on every turn of a session and stays cacheable. + +use std::collections::{BTreeMap, BTreeSet}; + +use crate::agent::budget_inputs::tool_surface_fits_window; +use crate::agent::context_budget::budgeted_request_tool_tokens; +use crate::agent::turn_context::measure_request_tool_surface_for; +use crate::runtime::turn_publication::TurnRuntimeService; +use crate::tools::ToolSpec; +use crate::tools::capability::catalog::ALL_TOOLS_DIRECT; +use crate::tools::capability::contract::CapabilityRef; + +/// Tokens reserved for the name index the deferred surface carries on the +/// `capability_search` description (its byte bound over four bytes a token). +const DEFERRED_INDEX_TOKENS: usize = 600; + +/// Sessions whose decision was already logged, with the decision logged. +/// Bounded: it is cleared when it grows past [`MAX_LOGGED_SESSIONS`]. +static LOGGED: parking_lot::Mutex> = parking_lot::Mutex::new(BTreeMap::new()); +const MAX_LOGGED_SESSIONS: usize = 4096; + +/// What the fit decided for one turn. +pub(super) struct ToolFit { + /// Defer every tool the surface policy does not name. + pub(super) defers: bool, + /// Tokens of the surface measured before the decision. + pub(super) full_tokens: usize, +} + +impl TurnRuntimeService { + /// Tokens the definitions of `published` (plus the search control when + /// `with_search`) occupy in a request, by the estimator the budget uses. + pub(super) fn published_surface_tokens(&self, published: &BTreeSet, with_search: bool) -> usize { + let Ok(entries) = self.catalog.resolve(published.iter()) else { + return 0; + }; + let mut specs: Vec = entries + .iter() + .filter_map(|entry| self.execution.current_descriptor(&entry.public_name)) + .map(|descriptor| ToolSpec { + name: descriptor.public_name, + description: descriptor.description, + parameters: descriptor.parameters, + }) + .collect(); + if with_search && let Some(descriptor) = self.execution.current_descriptor("capability_search") { + specs.push(ToolSpec { + name: descriptor.public_name, + description: descriptor.description, + parameters: descriptor.parameters, + }); + } + let measured = measure_request_tool_surface_for(true, &specs, crate::tools::ToolSchemaDialect::Raw); + let tokens = budgeted_request_tool_tokens(measured); + if with_search { + tokens.saturating_add(DEFERRED_INDEX_TOKENS) + } else { + tokens + } + } + + /// Decide whether this turn defers the publish-all tools. Only a surface + /// that names every tool, under a config that leaves the choice to the + /// fit, is ever deferred. + pub(super) fn fit_tool_surface( + &self, + session_key: &str, + window_tokens: usize, + published: &BTreeSet, + ) -> ToolFit { + let automatic = self.publication_policy.direct_names.contains(ALL_TOOLS_DIRECT) + && self.generation.effective.tool_tiering.defer_unlisted.is_none(); + if !automatic { + return ToolFit { + defers: false, + full_tokens: self.published_surface_tokens(published, false), + }; + } + let full_tokens = self.published_surface_tokens(published, false); + let defers = !tool_surface_fits_window(window_tokens, full_tokens); + log_decision_once(session_key, window_tokens, full_tokens, defers); + ToolFit { defers, full_tokens } + } +} + +/// Log the decision once per session, again only if it changes (a model with +/// another window). The line carries typed metadata only. +fn log_decision_once(session_key: &str, window_tokens: usize, tool_tokens: usize, defers: bool) { + { + let mut logged = LOGGED.lock(); + if logged.len() >= MAX_LOGGED_SESSIONS { + logged.clear(); + } + let decision = (window_tokens, defers); + if logged.insert(session_key.to_owned(), decision) == Some(decision) { + return; + } + } + let share_percent = crate::agent::budget_inputs::tool_surface_share_percent(); + let decision: &'static str = if defers { "defer_unlisted" } else { "publish_all" }; + tracing::info!( + window_tokens, + tool_tokens, + share_percent, + decision, + "tool surface fitted to the model context window" + ); +} diff --git a/src/runtime/turn_publication.rs b/src/runtime/turn_publication.rs index b4b250c8b..4c6932317 100644 --- a/src/runtime/turn_publication.rs +++ b/src/runtime/turn_publication.rs @@ -31,7 +31,7 @@ const CHAT_SESSIONS_TOOLS: [&str; 4] = ["sessions_spawn", "sessions_send", "sess fn direct_tool_names(configured: &crate::config::ToolTieringConfig, chat: bool) -> std::collections::BTreeSet { let chat_tools: &[&str] = if chat { &CHAT_SESSIONS_TOOLS } else { &[] }; // Every tool is published unless the operator asks to defer the rest. - let publish_all = (!configured.defer_unlisted).then_some(tools::capability::catalog::ALL_TOOLS_DIRECT); + let publish_all = configured.publishes_all_tools().then_some(tools::capability::catalog::ALL_TOOLS_DIRECT); DEFAULT_DIRECT_TOOLS .into_iter() .chain(chat_tools.iter().copied()) diff --git a/src/session_worker/runner/run.rs b/src/session_worker/runner/run.rs index afe1e3679..398e106c5 100644 --- a/src/session_worker/runner/run.rs +++ b/src/session_worker/runner/run.rs @@ -131,7 +131,9 @@ fn worker_direct_names( ) -> std::collections::BTreeSet { manifest.direct_tools.as_ref().map_or_else( || { - let publish_all = (!tiering.defer_unlisted).then_some(crate::tools::capability::catalog::ALL_TOOLS_DIRECT); + let publish_all = tiering + .publishes_all_tools() + .then_some(crate::tools::capability::catalog::ALL_TOOLS_DIRECT); tiering .always_include .iter() diff --git a/src/tools/capability/catalog/section_1.rs b/src/tools/capability/catalog/section_1.rs index 29123837d..0b1686042 100644 --- a/src/tools/capability/catalog/section_1.rs +++ b/src/tools/capability/catalog/section_1.rs @@ -831,6 +831,15 @@ impl<'a> CatalogView<'a> { .is_some_and(|surface| surface.direct_names.contains(&entry.public_name)) } + /// Whether the surface policy names `entry` itself as direct: the core + /// tools, the surface's session tools and `always_include`, but not the + /// publish-all member. A turn that fits its tool definitions to a small + /// window publishes only these directly. + pub(crate) fn names_directly(&self, entry: &CapabilityEntry) -> bool { + self.surface + .is_some_and(|surface| surface.direct_names.contains(&entry.public_name)) + } + pub(crate) fn surface_excludes(&self, entry: &CapabilityEntry) -> bool { self.surface.is_some_and(|surface| { !surface.permits(&entry.public_name, &entry.root, &entry.target) diff --git a/src/tools/capability/search_tool.rs b/src/tools/capability/search_tool.rs index 276b56bad..8b1c9dfbe 100644 --- a/src/tools/capability/search_tool.rs +++ b/src/tools/capability/search_tool.rs @@ -14,6 +14,7 @@ use anyhow::Context as _; use std::collections::BTreeMap; use std::sync::Weak; +mod deferred_index; pub(crate) mod discovery_admission; pub(crate) use discovery_admission::{ DiscoveredToolProposal, DiscoveryState, MAX_DISCOVERED_TOOLS_PER_TURN, admit_discovered_tool, diff --git a/src/tools/capability/search_tool/deferred_index.rs b/src/tools/capability/search_tool/deferred_index.rs new file mode 100644 index 000000000..bf0147470 --- /dev/null +++ b/src/tools/capability/search_tool/deferred_index.rs @@ -0,0 +1,91 @@ +//! A compact name-only index of the tools a window-fitted turn left out of its +//! request, carried on the `capability_search` description so the model can +//! call one by its exact name without a search round. + +use std::collections::BTreeMap; + +use super::DiscoveryEntry; +use crate::tools::capability::catalog::Exposure; +use crate::tools::capability::contract::CapabilityId; +use crate::tools::surface_owner::turn_port::TurnSurfacePort; + +/// Most bytes the index adds to the description (about 500 tokens). +const MAX_INDEX_BYTES: usize = 2_400; +/// Most words kept from a tool's own description. +const MAX_BLURB_WORDS: usize = 5; +/// Most bytes kept from those words. +const MAX_BLURB_BYTES: usize = 40; + +const INDEX_HEADER: &str = "\n\nTools left out of this request to fit the model's context window. Call one by its exact name; its schema is admitted on the call, or search for it first: "; + +/// The first few words of a description, one line, no markup. +fn blurb(description: &str) -> String { + let first = description.split(['.', '\n']).next().unwrap_or_default(); + let mut text = String::new(); + for word in first.split_whitespace().take(MAX_BLURB_WORDS) { + let word: String = word.chars().filter(|c| !c.is_control() && !matches!(c, '(' | ')' | ';')).collect(); + if word.is_empty() { + continue; + } + if text.len().saturating_add(word.len()).saturating_add(1) > MAX_BLURB_BYTES { + break; + } + if !text.is_empty() { + text.push(' '); + } + text.push_str(&word); + } + text +} + +/// The index text for the deferred entries of `entries`, in name order so it +/// is identical on every turn of the same tool set. Empty when nothing was +/// deferred. A tool the bound does not reach is counted, never dropped from +/// reach: it stays callable by name and found by search. +pub(super) fn deferred_index(port: &dyn TurnSurfacePort, entries: &BTreeMap) -> String { + let catalog = port.catalog(); + let mut items: Vec<(String, String)> = entries + .values() + .filter(|entry| entry.searchable && !entry.core) + .filter_map(|entry| { + let resolved = catalog.resolve(std::slice::from_ref(&entry.reference)).ok()?; + let capability = resolved.first()?; + if !matches!(capability.exposure, Exposure::Direct) { + return None; + } + let description = port + .execution() + .current_descriptor(&capability.public_name) + .map(|descriptor| descriptor.description) + .unwrap_or_default(); + Some((capability.public_name.clone(), blurb(&description))) + }) + .collect(); + if items.is_empty() { + return String::new(); + } + items.sort(); + let mut text = String::from(INDEX_HEADER); + let mut listed = 0usize; + for (name, words) in &items { + let piece = if words.is_empty() { + name.clone() + } else { + format!("{name} ({words})") + }; + let separator = if listed == 0 { 0 } else { 2 }; + if text.len().saturating_add(separator).saturating_add(piece.len()) > MAX_INDEX_BYTES { + break; + } + if listed > 0 { + text.push_str(", "); + } + text.push_str(&piece); + listed += 1; + } + let omitted = items.len().saturating_sub(listed); + if omitted > 0 { + text.push_str(&format!(", and {omitted} more found by search")); + } + text +} diff --git a/src/tools/capability/search_tool/discovery_admission.rs b/src/tools/capability/search_tool/discovery_admission.rs index ce3c8bf79..26ed1ef94 100644 --- a/src/tools/capability/search_tool/discovery_admission.rs +++ b/src/tools/capability/search_tool/discovery_admission.rs @@ -179,6 +179,9 @@ pub(crate) fn discovery_entries( let rules = rules(port, &view); let trusted = port.trusted(); let offered_direct = direct_discovery_ids(port); + // A turn that fitted its tool definitions to the window left every + // publish-all tool out of the request, and offers each through search. + let fit_deferred = port.facts().fit_defers; let mut entries = BTreeMap::new(); for entry in view.iter_entries() { let reference = entry_ref(entry); @@ -189,7 +192,8 @@ pub(crate) fn discovery_entries( ) && (entry.public_name != "delegate" || port.facts().policy.autonomy == crate::security::AutonomyLevel::Full) && (entry.supports_metadata_discovery() - || matches!(entry.exposure, Exposure::Direct) && (offered_direct.contains(&entry.id) || core)) + || matches!(entry.exposure, Exposure::Direct) + && (offered_direct.contains(&entry.id) || core || fit_deferred)) && rules.owner_isolation_admits(entry) && entry.availability.level >= CapabilityAvailabilityLevel::Configured && !trusted.excludes_entry(entry) @@ -213,7 +217,9 @@ pub(crate) fn discovery_entries( DiscoveryEntry { reference, core, - searchable: entry.supports_metadata_discovery() || offered_direct.contains(&entry.id), + searchable: entry.supports_metadata_discovery() + || offered_direct.contains(&entry.id) + || (fit_deferred && !core && matches!(entry.exposure, Exposure::Direct)), }, ); } @@ -233,7 +239,8 @@ pub(crate) fn capability_search_spec( { return Ok(None); } - if !discovery_entries(port, proof)?.values().any(|entry| entry.searchable) { + let discovered = discovery_entries(port, proof)?; + if !discovered.values().any(|entry| entry.searchable) { return Ok(None); } let Some(entry) = port.catalog().entry_for_public_name("capability_search") else { @@ -270,7 +277,7 @@ pub(crate) fn capability_search_spec( } return Err(SearchControlUnavailable::MissingBackend.into()); }; - let spec = ToolSpec { + let mut spec = ToolSpec { name: descriptor.public_name, description: descriptor.description, parameters: descriptor.parameters, @@ -284,6 +291,11 @@ pub(crate) fn capability_search_spec( ) == entry.fingerprint, "capability search definition changed" ); + // The index is added after the definition was verified, and every reader + // of this spec (request, execution binding) gets it from this function. + if port.facts().fit_defers { + spec.description.push_str(&super::deferred_index::deferred_index(port, &discovered)); + } Ok(Some(spec)) } diff --git a/src/tools/surface_owner/facts.rs b/src/tools/surface_owner/facts.rs index 87c00b7f0..8cdfed21e 100644 --- a/src/tools/surface_owner/facts.rs +++ b/src/tools/surface_owner/facts.rs @@ -36,6 +36,11 @@ pub(crate) struct PublicationFacts { /// `None` below Full and for non-child turns, where the manifest (or no /// child scope) bounds publication. pub(crate) child_served: Option>>, + /// The turn fits its tool definitions to the model's window: only the + /// tools the surface policy names stay direct, and the rest are reached + /// through `capability_search` or by exact name. Fixed at opening from the + /// model window and the tool set, so every later rebuild agrees. + pub(crate) fit_defers: bool, } impl PublicationFacts { diff --git a/src/tools/surface_owner/publication.rs b/src/tools/surface_owner/publication.rs index 2074a379f..bd490529f 100644 --- a/src/tools/surface_owner/publication.rs +++ b/src/tools/surface_owner/publication.rs @@ -257,7 +257,9 @@ impl PublicationRules<'_, '_> { .filter_map(|entry| { let delegate = is_delegator(&entry.public_name); let reference = entry_ref(entry); - let directly_exposed = self.catalog.directly_exposes(entry); + // A turn that fits its window keeps only the named tools direct. + let directly_exposed = self.catalog.directly_exposes(entry) + && (!self.facts.fit_defers || self.catalog.names_directly(entry)); let minted_delegator = delegate && outgoing_child && (self.trusted.surface != TurnSurfaceKind::Interactive || self.full_autonomy()); diff --git a/src/tools/surface_owner/tests.rs b/src/tools/surface_owner/tests.rs index b866350b9..dbe787813 100644 --- a/src/tools/surface_owner/tests.rs +++ b/src/tools/surface_owner/tests.rs @@ -61,6 +61,7 @@ fn facts_for(policy: Arc) -> PublicationFacts { child_scope: None, child_discovery: false, child_served: None, + fit_defers: false, } } diff --git a/tests/fixtures/config-schema.json b/tests/fixtures/config-schema.json index 96b393cc2..3fdbfe789 100644 --- a/tests/fixtures/config-schema.json +++ b/tests/fixtures/config-schema.json @@ -1 +1 @@ -{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Config","description":"Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).","type":"object","properties":{"a2a":{"description":"Agent-to-Agent compatibility configuration (`[a2a]`).","$ref":"#/$defs/A2aConfig","default":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trusted_trust_domains":[],"trust_domain":"prx.local"}},"agent":{"description":"Agent orchestration settings (`[agent]`).","$ref":"#/$defs/AgentConfig","default":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2,"messaging":{"inbound":true}}},"agents":{"description":"Delegate agent configurations for multi-agent workflows.","type":"object","additionalProperties":{"$ref":"#/$defs/DelegateAgentConfig"},"default":{}},"api_key":{"description":"API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.","type":["string","null"],"default":null},"api_url":{"description":"Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)","type":["string","null"],"default":null},"auth":{"description":"Auth profile and external credential import settings (`[auth]`).","$ref":"#/$defs/AuthConfig","default":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"}},"autonomy":{"description":"Autonomy and security policy configuration (`[autonomy]`).","$ref":"#/$defs/AutonomyConfig","default":{"forbidden_paths":[],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]}}},"browser":{"description":"Browser automation configuration (`[browser]`).","$ref":"#/$defs/BrowserConfig","default":{"allowed_domains":[],"computer_use":{"api_key":null}}},"channels_config":{"description":"Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).","$ref":"#/$defs/ChannelsConfig","default":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null}},"chat":{"description":"Interactive chat UI configuration (`[chat]`).","$ref":"#/$defs/ChatConfig","default":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2}},"compliance":{"description":"Operator-owned compliance controls (`[compliance]`).","$ref":"#/$defs/ComplianceConfig","default":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}},"composio":{"description":"Composio managed OAuth tools integration (`[composio]`).","$ref":"#/$defs/ComposioConfig","default":{"api_key":null,"entity_id":"default"}},"cost":{"description":"Cost tracking and budget enforcement configuration (`[cost]`).","$ref":"#/$defs/CostConfig","default":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{},"warn_at_percent":80}},"cron":{"description":"Cron job configuration (`[cron]`).","$ref":"#/$defs/CronConfig","default":{"max_run_history":50}},"decision_engine":{"description":"Optional advisory decision engine, disabled by default.","$ref":"#/$defs/DecisionEngineConfig","default":{"candidates":5,"enabled":false,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"latency_budget_ms":500,"max_candidates":12,"token_ratio_limit":0.3499999940395355}},"default_model":{"description":"Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.","type":["string","null"]},"default_provider":{"description":"Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.","type":["string","null"]},"default_temperature":{"description":"Default model temperature (0.0–2.0). Default: `0.7`.","type":"number","format":"double","default":0.7},"embedding_routes":{"description":"Embedding routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/EmbeddingRouteConfig"}},"gateway":{"description":"Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).","$ref":"#/$defs/GatewayConfig","default":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60}},"heartbeat":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]`).","$ref":"#/$defs/HeartbeatConfig","default":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."}},"http_request":{"description":"HTTP request tool configuration (`[http_request]`).","$ref":"#/$defs/HttpRequestConfig","default":{"max_response_size":1000000,"timeout_secs":30}},"identity":{"description":"Identity format configuration: OpenClaw or AIEOS (`[identity]`).","$ref":"#/$defs/IdentityConfig","default":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"}},"identity_bindings":{"description":"Static identity bindings loaded at startup (`[[identity_bindings]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/IdentityBindingConfig"}},"mcp":{"description":"Secrets encryption configuration (`[secrets]`).","$ref":"#/$defs/McpConfig","default":{"servers":{}}},"mcp_server":{"description":"MCP server compatibility configuration (`[mcp_server]`).","$ref":"#/$defs/McpServerRuntimeConfig","default":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true}},"media":{"description":"Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.","$ref":"#/$defs/MediaConfig","default":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"}},"memory":{"description":"Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).","$ref":"#/$defs/MemoryConfig","default":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":true,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7}},"model_routes":{"description":"Model routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/ModelRouteConfig"}},"model_settings":{"description":"Catalog model levels and explicit parameters, keyed by canonical release ID.","type":"object","additionalProperties":{"$ref":"#/$defs/ModelSettings"},"default":{}},"multimodal":{"description":"Multimodal (image) handling configuration (`[multimodal]`).","$ref":"#/$defs/MultimodalConfig","default":{"allow_remote_fetch":true,"max_image_size_mb":5,"max_images":4}},"nodes":{"description":"Remote node proxy configuration (`[nodes]`).","$ref":"#/$defs/NodesConfig","default":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":[],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}},"observability":{"description":"Observability backend configuration (`[observability]`).","$ref":"#/$defs/ObservabilityConfig","default":{"backend":"none","otel_endpoint":null,"otel_service_name":null}},"plugins":{"description":"WASM plugin runtime switch (`[plugins]`), off by default.","$ref":"#/$defs/PluginsConfig","default":{"enabled":false}},"providers":{"description":"Provider-specific runtime options (`[providers.]`).","$ref":"#/$defs/ProvidersConfig","default":{"ollama":{"num_ctx":null}}},"proxy":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).","$ref":"#/$defs/ProxyConfig","default":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]}},"query_classification":{"description":"Automatic query classification — maps user messages to model hints.","$ref":"#/$defs/QueryClassificationConfig","default":{"rules":[]}},"reliability":{"description":"Reliability settings: retries, fallback providers, backoff (`[reliability]`).","$ref":"#/$defs/ReliabilityConfig","default":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2}},"router":{"description":"Heuristic LLM router configuration (`[router]`).","$ref":"#/$defs/RouterConfig","default":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]}},"runtime":{"description":"Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.","$ref":"#/$defs/RuntimeConfig","default":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null}},"scheduler":{"description":"Scheduler configuration for periodic task execution (`[scheduler]`).","$ref":"#/$defs/SchedulerConfig","default":{"claim_lease_secs":90,"max_tasks":64}},"secrets":{"$ref":"#/$defs/SecretsConfig","default":{"encrypt":true}},"security":{"description":"Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).","$ref":"#/$defs/SecurityConfig","default":{"audit":{"log_path":"audit.log","max_size_mb":100}}},"self_system":{"description":"Self-system experimental automation controls (`[self_system]`).","$ref":"#/$defs/SelfSystemConfig","default":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24}},"sessions_spawn":{"description":"Session spawning configuration (`[sessions_spawn]`).","$ref":"#/$defs/SessionsSpawnConfig","default":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null}},"skill_rag":{"description":"Dynamic skill retrieval settings (`[skill_rag]`).","$ref":"#/$defs/SkillRagConfig","default":{"top_k":32}},"skills":{"description":"Skills loading and community repository behavior (`[skills]`).","$ref":"#/$defs/SkillsConfig","default":{"open_skills_dir":null,"openclaw_skills_dir":null}},"skills_lifecycle":{"description":"Skill lifecycle (`[skills_lifecycle]`), off by default.","$ref":"#/$defs/SkillsLifecycleConfig","default":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]}},"smart_group":{"description":"Smart group-reply pre-gate configuration (`[smart_group]`).","$ref":"#/$defs/SmartGroupConfig","default":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5}},"storage":{"description":"Persistent storage provider configuration (`[storage]`).","$ref":"#/$defs/StorageConfig","default":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"task_routing":{"description":"Task routing configuration — classifies work by intent before the main agent loop.","$ref":"#/$defs/TaskRoutingConfig","default":{"default_intent":"simple","rules":[]}},"tool_tiering":{"description":"Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).","$ref":"#/$defs/ToolTieringConfig","default":{"always_exclude":[],"always_include":[],"channel_exclude":[],"defer_unlisted":false}},"tunnel":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]`).","$ref":"#/$defs/TunnelConfig","default":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null}},"user_policies":{"description":"Static user policy records loaded at startup (`[[user_policies]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/UserPolicyConfig"}},"web_search":{"description":"Web search tool configuration (`[web_search]`).","$ref":"#/$defs/WebSearchConfig","default":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15}},"webhook":{"description":"Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).","$ref":"#/$defs/MemoryWebhookConfig","default":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null}},"xin":{"description":"Xin autonomous task engine configuration (`[xin]`).","$ref":"#/$defs/XinConfig","default":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}}},"$defs":{"A2aConfig":{"type":"object","properties":{"agent_id":{"description":"Stable PRX agent identifier advertised to peers.","type":"string","default":"prx-default"},"allowed_peer_issuers":{"description":"Accepted external peer issuers.","type":"array","default":[],"items":{"type":"string"}},"bind":{"description":"Advertised bind address.","type":"string","default":"127.0.0.1:16832"},"card_jwks_uri":{"description":"Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.","type":["string","null"],"default":null},"card_signing_key_path":{"description":"On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).","type":["string","null"],"default":null},"card_ttl_seconds":{"description":"Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.","type":"integer","format":"uint64","default":3600,"minimum":0},"discovery_advertised":{"description":"Whether to advertise into an external A2A registry.","type":"boolean","default":false},"handoff_nonce_ttl_seconds":{"description":"Replay window for future handoff delegation tokens.","type":"integer","format":"uint64","default":3600,"minimum":0},"messaging_enabled":{"description":"Enable the dedicated pinned mTLS messaging listener.","type":"boolean","default":false},"peers":{"type":"object","additionalProperties":{"$ref":"#/$defs/A2aPeer"},"default":{}},"spiffe_id":{"description":"Local SPIFFE-style identifier placeholder.","type":"string","default":"spiffe://prx-local/agent/prx-default"},"spiffe_strict_validation":{"description":"When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.","type":"boolean","default":false},"spiffe_trust_bundle_pem":{"description":"Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).","type":["string","null"],"default":null},"trusted_trust_domains":{"description":"Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).","type":"array","default":[],"items":{"type":"string"}},"trust_domain":{"description":"SPIFFE trust domain for new instance identities.","type":"string","default":"prx.local"}}},"A2aPeer":{"description":"Explicit pinned identity and local recipient grant.","type":"object","properties":{"spiffe_id":{"type":"string"},"fingerprints":{"type":"array","items":{"type":"string"}},"address":{"type":"string"},"owner":{"type":"string"},"sessions":{"type":"array","default":["*"],"items":{"type":"string"}},"agents":{"type":"array","default":["*"],"items":{"type":"string"}}},"required":["spiffe_id","fingerprints","address","owner"],"additionalProperties":false},"AgentCompactionConfig":{"description":"Agent context compaction configuration (`[agent.compaction]`).","type":"object","properties":{"keep_recent_messages":{"description":"Number of recent non-system messages to keep after compaction.","type":"integer","format":"uint","default":12,"minimum":0},"max_context_tokens":{"description":"Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.","type":"integer","format":"uint","default":128000,"minimum":0},"memory_flush":{"description":"Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.","type":"boolean","default":true},"mode":{"description":"Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).","$ref":"#/$defs/AgentCompactionMode","default":"switch"},"os_paging":{"description":"Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.","$ref":"#/$defs/OsPagingConfig","default":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"}},"reserve_tokens":{"description":"Tokens reserved for the next model response.","type":"integer","format":"uint","default":4096,"minimum":0}}},"AgentCompactionMode":{"description":"Compaction mode for long conversation contexts.","oneOf":[{"description":"Disable proactive compaction.","type":"string","const":"off"},{"description":"Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.","type":"string","const":"switch"},{"description":"Conservative compaction that prefers summary replacement.","type":"string","const":"safeguard"},{"description":"Aggressive truncation mode for tighter contexts.","type":"string","const":"aggressive"}]},"AgentConfig":{"description":"Agent orchestration configuration (`[agent]` section).","type":"object","properties":{"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"compact_context":{"description":"When true: bootstrap_max_chars=6000. Use for 13B or smaller models.","type":"boolean","default":false},"compaction":{"description":"Context compaction controls (`[agent.compaction]`).","$ref":"#/$defs/AgentCompactionConfig","default":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096}},"low_priority_tools":{"description":"Tool names treated as low-priority when `priority_scheduling_enabled = true`.","type":"array","default":["sessions_spawn","delegate"],"items":{"type":"string"}},"priority_scheduling_enabled":{"description":"Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.","type":"boolean","default":false},"read_only_tool_concurrency_window":{"description":"Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.","type":"integer","format":"uint","default":2,"minimum":0},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}}},"AgentLimits":{"description":"Optional admission limits for rf-started turns of a named agent.","type":"object","properties":{"max_concurrent_turns":{"type":["integer","null"],"format":"uint32","minimum":0},"max_cost_per_day_cents":{"type":["integer","null"],"format":"uint64","minimum":0}},"additionalProperties":false},"AuditConfig":{"description":"Audit logging configuration","type":"object","properties":{"log_path":{"description":"Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).","type":"string","default":"audit.log"},"max_size_mb":{"description":"Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).","type":"integer","format":"uint32","default":100,"minimum":0}}},"AuthConfig":{"description":"Authentication and external credential import configuration (`[auth]` section).","type":"object","properties":{"codex_auth_json_auto_import":{"description":"Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.","type":"boolean","default":false},"codex_auth_json_path":{"description":"Source path for Codex CLI auth.json import.","type":"string","default":"~/.codex/auth.json"}}},"AutonomyConfig":{"type":"object","properties":{"acknowledge_unrestricted_profile":{"description":"Operator acknowledgement for an intentionally unrestricted profile.\nRetained for existing configs; it no longer changes any output or policy behavior.","type":"boolean","default":false},"forbidden_paths":{"description":"Explicit path denylist. Default: empty.\n\nApplies below level `full` only; list paths when running `supervised` or `readonly`.","type":"array","default":[],"items":{"type":"string"}},"level":{"description":"Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).","$ref":"#/$defs/AutonomyLevel","default":"full"},"max_cost_per_day_cents":{"description":"Maximum cost per day in cents per policy. Default: unset (no ceiling).","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"scopes":{"description":"Scope-based tool access control: per-user/channel/chat-type allow/deny rules.","$ref":"#/$defs/ScopeConfig","default":{"assign_owners":[],"default":"allow","rules":[]}},"workspace_only":{"description":"Restrict file writes and command paths to the workspace directory. Default: `false`.\n\nApplies below level `full` only; set it when running `supervised` or `readonly`.","type":"boolean","default":false}}},"AutonomyLevel":{"description":"How much autonomy the agent has","oneOf":[{"description":"Read-only: can observe but not act","type":"string","const":"readonly"},{"description":"Supervised: acts but requires approval for risky operations","type":"string","const":"supervised"},{"description":"Full: autonomous execution within policy bounds","type":"string","const":"full"}]},"BackendSelection":{"description":"Which decision backend runs: `auto` (the factory's order) or one kind.","type":"string"},"BrowserComputerUseConfig":{"description":"Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.","type":"object","properties":{"api_key":{"description":"Optional bearer token (retained only for config secret handling).","type":["string","null"],"default":null}}},"BrowserConfig":{"description":"Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.","type":"object","properties":{"allowed_domains":{"description":"Allowed domains for `web_fetch` (exact or subdomain match).","type":"array","default":[],"items":{"type":"string"}},"computer_use":{"description":"Computer-use sidecar config (retained only for `api_key` secret handling).","$ref":"#/$defs/BrowserComputerUseConfig","default":{"api_key":null}}}},"ChannelsConfig":{"description":"Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.","type":"object","properties":{"cli":{"description":"Enable the CLI interactive channel. Default: `true`.","type":"boolean","default":true},"dingtalk":{"description":"DingTalk channel configuration.","anyOf":[{"$ref":"#/$defs/DingTalkConfig"},{"type":"null"}]},"discord":{"description":"Discord bot channel configuration.","anyOf":[{"$ref":"#/$defs/DiscordConfig"},{"type":"null"}]},"email":{"description":"Email channel configuration.","anyOf":[{"$ref":"#/$defs/EmailConfig"},{"type":"null"}]},"imessage":{"description":"iMessage channel configuration (macOS only).","anyOf":[{"$ref":"#/$defs/IMessageConfig"},{"type":"null"}]},"irc":{"description":"IRC channel configuration.","anyOf":[{"$ref":"#/$defs/IrcConfig"},{"type":"null"}]},"lark":{"description":"Lark/Feishu channel configuration.","anyOf":[{"$ref":"#/$defs/LarkConfig"},{"type":"null"}]},"linq":{"description":"Linq Partner API channel configuration.","anyOf":[{"$ref":"#/$defs/LinqConfig"},{"type":"null"}]},"mattermost":{"description":"Mattermost bot channel configuration.","anyOf":[{"$ref":"#/$defs/MattermostConfig"},{"type":"null"}]},"nextcloud_talk":{"description":"Nextcloud Talk bot channel configuration.","anyOf":[{"$ref":"#/$defs/NextcloudTalkConfig"},{"type":"null"}]},"qq":{"description":"QQ Official Bot channel configuration.","anyOf":[{"$ref":"#/$defs/QQConfig"},{"type":"null"}]},"ramflux":{"description":"Local ramflux agent-host bridge.","anyOf":[{"$ref":"#/$defs/RamfluxConfig"},{"type":"null"}],"default":null},"signal":{"description":"Signal channel configuration.","anyOf":[{"$ref":"#/$defs/SignalConfig"},{"type":"null"}]},"slack":{"description":"Slack bot channel configuration.","anyOf":[{"$ref":"#/$defs/SlackConfig"},{"type":"null"}]},"telegram":{"description":"Telegram bot channel configuration.","anyOf":[{"$ref":"#/$defs/TelegramConfig"},{"type":"null"}]},"wacli":{"description":"wacli JSON-RPC daemon channel configuration.","anyOf":[{"$ref":"#/$defs/WacliConfig"},{"type":"null"}],"default":null},"webhook":{"description":"Webhook channel configuration.","anyOf":[{"$ref":"#/$defs/WebhookConfig"},{"type":"null"}]},"whatsapp":{"description":"WhatsApp channel configuration (Cloud API or Web mode).","anyOf":[{"$ref":"#/$defs/WhatsAppConfig"},{"type":"null"}]}}},"ChatConfig":{"description":"Interactive chat configuration (`[chat]`).","type":"object","properties":{"daemon":{"description":"How this chat process reaches the daemon it borrows channels from.","$ref":"#/$defs/ChatDaemonConfig","default":{"token":"","url":""}},"max_concurrent_visible_turns":{"description":"Maximum concurrent visible provider turns in the TUI Redux driver.","type":"integer","format":"uint","default":2,"minimum":0}}},"ChatDaemonConfig":{"description":"Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.","type":"object","properties":{"token":{"description":"Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.","type":"string","default":""},"url":{"description":"Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.","type":"string","default":""}}},"CircuitBreakerConfig":{"description":"The per-backend circuit breaker.","type":"object","properties":{"cooldown_secs":{"description":"Seconds the breaker stays open (1 to 3600).","type":"integer","format":"uint32","default":60,"minimum":0},"failure_threshold":{"description":"Consecutive failures before the breaker opens (1 to 100).","type":"integer","format":"uint32","default":5,"minimum":0}}},"ClassificationRule":{"description":"A single classification rule mapping message patterns to a model hint.","type":"object","properties":{"hint":{"description":"Must match a `[[model_routes]]` hint value.","type":"string"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"max_length":{"description":"Only match if message length <= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"min_length":{"description":"Only match if message length >= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"patterns":{"description":"Case-sensitive literal matches (for \"```\", \"fn \", etc.).","type":"array","default":[],"items":{"type":"string"}},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0}},"required":["hint"]},"CloudflareTunnelConfig":{"type":"object","properties":{"token":{"description":"Cloudflare Tunnel token (from Zero Trust dashboard)","type":"string"}},"required":["token"]},"ComplianceConfig":{"type":"object","properties":{"eu_ai_act":{"$ref":"#/$defs/EuAiActComplianceConfig","default":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null}},"interaction_notice":{"$ref":"#/$defs/InteractionNoticeConfig","default":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}}},"ComposioConfig":{"description":"Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.","type":"object","properties":{"api_key":{"description":"Composio API key (stored encrypted when secrets.encrypt = true)","type":["string","null"],"default":null},"entity_id":{"description":"Default entity ID for multi-user setups","type":"string","default":"default"}}},"CostConfig":{"description":"Cost tracking and budget enforcement configuration (`[cost]` section).","type":"object","properties":{"allow_override":{"description":"Allow requests to exceed budget with --override flag (default: false)","type":"boolean","default":false},"daily_limit_usd":{"description":"Daily spending limit in USD (default: unset, no limit; 0 refuses every priced turn)","type":["number","null"],"format":"double","default":null},"monthly_limit_usd":{"description":"Monthly spending limit in USD (default: unset, no limit)","type":["number","null"],"format":"double","default":null},"prices":{"description":"Per-model pricing (USD per 1M tokens)","type":"object","additionalProperties":{"$ref":"#/$defs/ModelPricing"},"default":{}},"warn_at_percent":{"description":"Warn when spending reaches this percentage of a configured limit (default: 80)","type":"integer","format":"uint8","default":80,"maximum":255,"minimum":0}}},"CredentialRefSetting":{"description":"Which credential a decision backend uses. A reference, never a secret.","type":"string"},"CronConfig":{"description":"Cron job configuration (`[cron]` section).","type":"object","properties":{"max_run_history":{"description":"Maximum number of historical cron run records to retain. Default: `50`.","type":"integer","format":"uint32","default":50,"minimum":0}}},"CustomTunnelConfig":{"type":"object","properties":{"health_url":{"description":"Optional URL to check tunnel health","type":["string","null"]},"start_command":{"description":"Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"","type":"string"},"url_pattern":{"description":"Optional regex to extract public URL from command stdout","type":["string","null"]}},"required":["start_command"]},"DecisionBackendConfig":{"description":"The decision backend (`[decision_engine.backend]`).","type":"object","properties":{"circuit_breaker":{"description":"The circuit breaker.","$ref":"#/$defs/CircuitBreakerConfig","default":{"cooldown_secs":60,"failure_threshold":5}},"credential_ref":{"description":"The credential reference: `\"\"`, `\"none\"` or `cred-`.","$ref":"#/$defs/CredentialRefSetting","default":""},"endpoint":{"description":"The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.","type":"string","default":""},"kind":{"description":"`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).","$ref":"#/$defs/BackendSelection","default":"auto"},"max_request_bytes":{"description":"Largest request body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":65536,"minimum":0},"max_response_bytes":{"description":"Largest response body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":262144,"minimum":0},"model":{"description":"The model the endpoint serves; one exact version for a hosted\nservice.","type":"string","default":""},"pinned_snapshot":{"description":"The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.","type":"string"},"remote_enabled":{"description":"Whether decision state may leave this machine. Default `false`.","type":"boolean","default":false},"timeout_ms":{"description":"Transport timeout (10 ms up to the extra latency budget).","type":"integer","format":"uint32","default":250,"minimum":0}}},"DecisionEngineConfig":{"type":"object","properties":{"backend":{"anyOf":[{"$ref":"#/$defs/DecisionBackendConfig"},{"type":"null"}]},"candidates":{"type":"integer","format":"uint32","default":5,"minimum":0},"enabled":{"type":"boolean","default":false},"mode":{"$ref":"#/$defs/DecisionMode","default":"pre"},"observe_queue":{"type":"integer","format":"uint32","default":64,"minimum":0},"prompt_budget_tokens":{"type":"integer","format":"uint32","default":300,"minimum":0},"telemetry_cap":{"type":"integer","format":"uint32","default":1000,"minimum":0},"timeout_ms":{"type":"integer","format":"uint32","default":1500,"minimum":0},"latency_budget_ms":{"description":"The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.","type":"integer","format":"uint64","default":500,"minimum":0},"token_ratio_limit":{"description":"Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).","type":"number","format":"float","default":0.3499999940395355},"max_candidates":{"description":"The most candidates a turn considers (1 to 32).","type":"integer","format":"uint8","default":12,"maximum":255,"minimum":0}}},"DecisionMode":{"type":"string","enum":["pre","post","both"]},"DeclarationOfConformityConfig":{"type":"object","properties":{"applicable_union_law":{"type":"array","default":[],"items":{"type":"string"}},"artifact_path":{"type":["string","null"],"default":null},"artifact_version":{"type":["string","null"],"default":null},"conformity_assessment_procedure":{"type":["string","null"],"default":null},"conformity_statement":{"type":["string","null"],"default":null},"harmonised_standards":{"type":"array","default":[],"items":{"type":"string"}},"issue_date":{"type":["string","null"],"default":null},"issue_place":{"type":["string","null"],"default":null},"notified_body_certificate":{"type":["string","null"],"default":null},"notified_body_identification_number":{"type":["string","null"],"default":null},"notified_body_name":{"type":["string","null"],"default":null},"personal_data_compliance_statement":{"type":["string","null"],"default":null},"processes_personal_data":{"type":"boolean","default":false},"provider_address":{"type":["string","null"],"default":null},"provider_name":{"type":["string","null"],"default":null},"signer_function":{"type":["string","null"],"default":null},"signer_name":{"type":["string","null"],"default":null},"signer_on_behalf_of":{"type":["string","null"],"default":null},"sole_responsibility_statement":{"type":["string","null"],"default":null},"standards_not_applicable_reason":{"type":["string","null"],"default":null},"system_name":{"type":["string","null"],"default":null},"system_reference":{"type":["string","null"],"default":null},"system_type":{"type":["string","null"],"default":null}}},"DelegateAgentConfig":{"description":"Configuration for a delegate sub-agent used by the `delegate` tool.","type":"object","properties":{"agentic":{"description":"Agentic sub-agent mode (multi-turn tool-call loop). Default true; an\nexplicit `false` makes the agent answer-only with no tools.","type":"boolean","default":true},"allowed_tools":{"description":"Allowlist of tool names available to the sub-agent in agentic mode.\nEmpty or omitted means all tools, the same as `[\"*\"]`.","type":"array","default":[],"items":{"type":"string"}},"api_key":{"description":"Optional API key override","type":["string","null"],"default":null},"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"autonomy":{"description":"The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.","anyOf":[{"$ref":"#/$defs/AutonomyLevel"},{"type":"null"}]},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"enabled":{"description":"Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.","type":"boolean","default":true},"identity_dir":{"description":"Optional identity files directory relative to workspace root.","type":["string","null"],"default":null},"limits":{"$ref":"#/$defs/AgentLimits","default":{"max_concurrent_turns":null,"max_cost_per_day_cents":null}},"max_depth":{"description":"Max recursion depth for nested delegation","type":"integer","format":"uint32","default":8,"minimum":0},"memory_scope":{"description":"Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".","type":["string","null"],"default":null},"model":{"description":"Model name","type":"string"},"provider":{"description":"Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")","type":"string"},"spawn_enabled":{"description":"Whether this agent is allowed to be targeted by sessions_spawn (default: true).","type":["boolean","null"],"default":null},"system_prompt":{"description":"Optional system prompt for the sub-agent","type":["string","null"],"default":null},"temperature":{"description":"Temperature override","type":["number","null"],"format":"double","default":null},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}},"required":["provider","model"]},"DingTalkConfig":{"description":"DingTalk configuration for Stream Mode messaging","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"client_id":{"description":"Client ID (AppKey) from DingTalk developer console","type":"string"},"client_secret":{"description":"Client Secret (AppSecret) from DingTalk developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["client_id","client_secret"]},"DiscordConfig":{"description":"Discord bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Discord user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Discord bot token (from Discord Developer Portal).","type":"string"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"guild_id":{"description":"Optional guild (server) ID to restrict the bot to a single guild.","type":["string","null"]},"listen_to_bots":{"description":"When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.","type":"boolean","default":false}},"required":["bot_token"]},"DmPolicy":{"description":"Policy for direct-message handling.","oneOf":[{"description":"Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).","type":"string","const":"pairing"},{"description":"Accept only senders listed in `allowed_from`.","type":"string","const":"allowlist"},{"description":"Accept any direct sender.","type":"string","const":"open"},{"description":"Ignore direct messages.","type":"string","const":"disabled"}]},"DockerRuntimeConfig":{"description":"Docker runtime configuration (`[runtime.docker]` section).","type":"object","properties":{"allowed_workspace_roots":{"description":"Optional workspace root allowlist for Docker mount validation.","type":"array","default":[],"items":{"type":"string"}},"cpu_limit":{"description":"Optional CPU limit (`None` = no explicit limit).","type":["number","null"],"format":"double","default":1.0},"image":{"description":"Runtime image used to execute shell commands.","type":"string","default":"alpine:3.20"},"memory_limit_mb":{"description":"Optional memory limit in MB (`None` = no explicit limit).","type":["integer","null"],"format":"uint64","default":512,"minimum":0},"mount_workspace":{"description":"Mount configured workspace into `/workspace`.","type":"boolean","default":true},"network":{"description":"Docker network mode (`none`, `bridge`, etc.).","type":"string","default":"none"},"read_only_rootfs":{"description":"Mount root filesystem as read-only.","type":"boolean","default":true}}},"EmailConfig":{"description":"Email channel configuration","type":"object","properties":{"allowed_senders":{"description":"Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)","type":"array","default":[],"items":{"type":"string"}},"from_address":{"description":"From address for outgoing emails","type":"string"},"idle_timeout_secs":{"description":"IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes","type":"integer","format":"uint64","default":1740,"minimum":0},"imap_folder":{"description":"IMAP folder to poll (default: INBOX)","type":"string","default":"INBOX"},"imap_host":{"description":"IMAP server hostname","type":"string"},"imap_port":{"description":"IMAP server port (default: 993 for TLS)","type":"integer","format":"uint16","default":993,"maximum":65535,"minimum":0},"password":{"description":"Email password for authentication","type":"string"},"smtp_host":{"description":"SMTP server hostname","type":"string"},"smtp_port":{"description":"SMTP server port (default: 465 for TLS)","type":"integer","format":"uint16","default":465,"maximum":65535,"minimum":0},"smtp_tls":{"description":"Use TLS for SMTP (default: true)","type":"boolean","default":true},"username":{"description":"Email username for authentication","type":"string"}},"required":["imap_host","smtp_host","username","password","from_address"]},"EmbeddingRouteConfig":{"description":"Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"dimensions":{"description":"Optional embedding dimension override for this route","type":["integer","null"],"format":"uint","default":null,"minimum":0},"hint":{"description":"Route hint name (e.g. \"semantic\", \"archive\", \"faq\")","type":"string"},"model":{"description":"Embedding model to use with that provider","type":"string"},"provider":{"description":"Embedding provider (`none`, `openai`, or `custom:`)","type":"string"}},"required":["hint","provider","model"]},"EuAiActClassificationConfig":{"type":"object","properties":{"assessed_at":{"type":["string","null"],"default":null},"owner":{"type":["string","null"],"default":null},"status":{"$ref":"#/$defs/EuAiActRiskClassification","default":"unclassified"}}},"EuAiActComplianceConfig":{"type":"object","properties":{"classification":{"$ref":"#/$defs/EuAiActClassificationConfig","default":{"assessed_at":null,"owner":null,"status":"unclassified"}},"declaration":{"$ref":"#/$defs/DeclarationOfConformityConfig","default":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null}},"incident_store_path":{"type":["string","null"],"default":null}}},"EuAiActRiskClassification":{"type":"string","enum":["unclassified","high_risk","not_high_risk"]},"FitnessConfig":{"description":"Calendar schedule, evidence thresholds, and retention for fitness v2.","type":"object","properties":{"auto_run":{"description":"Run the daily fitness worker in daemon mode.","type":"boolean","default":true},"max_backfill_days":{"description":"Maximum number of closed days recovered after downtime.","type":"integer","format":"uint32","default":7,"minimum":0},"min_coverage":{"description":"Minimum available metric weight required to publish a final score.","type":"number","format":"double","default":0.6},"min_samples":{"description":"Minimum samples required before an evidence-derived subscore is usable.","type":"integer","format":"uint","default":5,"minimum":0},"retention_days":{"description":"Number of daily JSON reports retained on disk.","type":"integer","format":"uint32","default":180,"minimum":0},"run_at":{"description":"Local wall-clock time (`HH:MM`) at which the previous day is scored.","type":"string","default":"00:10"},"timezone":{"description":"IANA timezone used to define closed calendar days.","type":"string","default":"UTC"}}},"GatewayConfig":{"description":"Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.","type":"object","properties":{"allow_public_bind":{"description":"Allow binding to non-localhost without a tunnel (default: false)","type":"boolean","default":false},"api_rate_limit_per_minute":{"description":"Max `/api/*` requests per minute per authenticated token.","type":"integer","format":"uint32","default":60,"minimum":0},"channel_webhook_dedup_ttl_secs":{"description":"How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.","type":"integer","format":"uint64","default":86400,"minimum":0},"host":{"description":"Gateway host (default: 127.0.0.1)","type":"string","default":"127.0.0.1"},"idempotency_max_keys":{"description":"Maximum distinct idempotency keys retained in memory.","type":"integer","format":"uint","default":10000,"minimum":0},"idempotency_ttl_secs":{"description":"TTL for webhook idempotency keys.","type":"integer","format":"uint64","default":300,"minimum":0},"pair_rate_limit_per_minute":{"description":"Max `/pair` requests per minute per client key.","type":"integer","format":"uint32","default":10,"minimum":0},"paired_tokens":{"description":"Paired bearer tokens (managed automatically, not user-edited)","type":"array","default":[],"items":{"type":"string"}},"port":{"description":"Gateway port (default: 16830)","type":"integer","format":"uint16","default":16830,"maximum":65535,"minimum":0},"rate_limit_max_keys":{"description":"Maximum distinct client keys tracked by gateway rate limiter maps.","type":"integer","format":"uint","default":10000,"minimum":0},"require_pairing":{"description":"Require pairing before accepting requests (default: true)","type":"boolean","default":true},"targeted_agents":{"description":"Switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). Default true. While false, any\notherwise-valid named target answers 409 `agent_disabled` and never\nruns as Main.","type":"boolean","default":true},"trust_forwarded_headers":{"description":"Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.","type":"boolean","default":false},"webhook_rate_limit_per_minute":{"description":"Max `/webhook` requests per minute per client key.","type":"integer","format":"uint32","default":60,"minimum":0}}},"GroupPolicy":{"description":"Policy for group-message handling.","oneOf":[{"description":"Accept only groups listed in `group_allow_from`.","type":"string","const":"allowlist"},{"description":"Accept any group.","type":"string","const":"open"},{"description":"Ignore group messages.","type":"string","const":"disabled"}]},"GroupReplyMode":{"description":"How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.","oneOf":[{"description":"Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).","type":"string","const":"off"},{"description":"Reply only when the bot is @-mentioned (legacy `mention_only = true`).","type":"string","const":"mention-only"},{"description":"Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).","type":"string","const":"smart"}]},"HeartbeatConfig":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]` section).","type":"object","properties":{"active_hours":{"description":"Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.","type":"array","default":[8,23],"items":{"type":"integer","format":"uint8","maximum":255,"minimum":0}},"interval_minutes":{"description":"Interval in minutes between heartbeat pings. Default: `30`.","type":"integer","format":"uint32","default":30,"minimum":0},"prompt":{"description":"Prompt used by heartbeat worker when dispatching tasks.","type":"string","default":"Check HEARTBEAT.md and follow instructions."}}},"HttpRequestConfig":{"description":"HTTP request tool configuration (`[http_request]` section).","type":"object","properties":{"max_response_size":{"description":"Maximum response size in bytes (default: 1MB)","type":"integer","format":"uint","default":1000000,"minimum":0},"timeout_secs":{"description":"Request timeout in seconds (default: 30)","type":"integer","format":"uint64","default":30,"minimum":0}}},"IMessageConfig":{"description":"iMessage channel configuration (macOS only).","type":"object","properties":{"allowed_contacts":{"description":"Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.","type":"array","items":{"type":"string"}},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["allowed_contacts"]},"IdentityBindingConfig":{"description":"Startup identity binding entry (`[[identity_bindings]]`).","type":"object","properties":{"channel":{"type":"string"},"channel_account":{"type":"string"},"display_name":{"type":["string","null"],"default":null},"user_id":{"type":"string"}},"required":["user_id","channel","channel_account"]},"IdentityConfig":{"description":"Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.","type":"object","properties":{"aieos_inline":{"description":"Inline AIEOS JSON (alternative to file path)","type":["string","null"],"default":null},"aieos_path":{"description":"Path to AIEOS JSON file (relative to workspace)","type":["string","null"],"default":null},"format":{"description":"Identity format: \"openclaw\" (default) or \"aieos\"","type":"string","default":"openclaw"}}},"InteractionNoticeApplicability":{"type":"string","enum":["required","not_applicable"]},"InteractionNoticeConfig":{"type":"object","properties":{"applicability":{"$ref":"#/$defs/InteractionNoticeApplicability","default":"required"},"exception_owner":{"type":["string","null"],"default":null},"exception_reviewed_at":{"type":["string","null"],"default":null},"text":{"type":"string","default":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers."},"version":{"type":"string","default":"1"}}},"IrcConfig":{"description":"IRC channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed nicknames (case-insensitive) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"channels":{"description":"Channels to join on connect","type":"array","default":[],"items":{"type":"string"}},"mention_only":{"description":"When true, only process channel/group messages that mention the bot.","type":"boolean","default":false},"nickname":{"description":"Bot nickname","type":"string"},"nickserv_password":{"description":"NickServ IDENTIFY password","type":["string","null"]},"port":{"description":"IRC server port (default: 6697 for TLS)","type":"integer","format":"uint16","default":6697,"maximum":65535,"minimum":0},"sasl_password":{"description":"SASL PLAIN password (IRCv3)","type":["string","null"]},"server":{"description":"IRC server hostname","type":"string"},"server_password":{"description":"Server password (for bouncers like ZNC)","type":["string","null"]},"username":{"description":"Username (defaults to nickname if not set)","type":["string","null"]},"verify_tls":{"description":"Verify TLS certificate (default: true)","type":["boolean","null"]}},"required":["server","nickname"]},"LarkConfig":{"description":"Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from Lark/Feishu developer console","type":"string"},"app_secret":{"description":"App Secret from Lark/Feishu developer console","type":"string"},"encrypt_key":{"description":"Encrypt key for webhook message decryption (optional)","type":["string","null"],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"port":{"description":"HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"receive_mode":{"description":"Event receive mode: \"websocket\" (default) or \"webhook\"","$ref":"#/$defs/LarkReceiveMode","default":"websocket"},"use_feishu":{"description":"Whether to use the Feishu (Chinese) endpoint instead of Lark (International)","type":"boolean","default":false},"verification_token":{"description":"Verification token for webhook validation (optional)","type":["string","null"],"default":null}},"required":["app_id","app_secret"]},"LarkReceiveMode":{"description":"How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.","type":"string","enum":["websocket","webhook"]},"LinqConfig":{"type":"object","properties":{"allowed_senders":{"description":"Allowed sender handles (phone numbers) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"api_token":{"description":"Linq Partner API token (Bearer auth)","type":"string"},"from_phone":{"description":"Phone number to send from (E.164 format)","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"signing_secret":{"description":"Webhook signing secret for signature verification","type":["string","null"],"default":null}},"required":["api_token","from_phone"]},"MattermostConfig":{"description":"Mattermost bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Mattermost user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Mattermost bot access token.","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.","type":["boolean","null"],"default":null},"thread_replies":{"description":"When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.","type":["boolean","null"],"default":null},"url":{"description":"Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).","type":"string"}},"required":["url","bot_token"]},"McpConfig":{"type":"object","properties":{"servers":{"description":"Named MCP server definitions","type":"object","additionalProperties":{"$ref":"#/$defs/McpServerConfig"},"default":{}},"workspace_servers":{"description":"Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.","$ref":"#/$defs/WorkspaceMcpServers"}}},"McpServerConfig":{"type":"object","properties":{"allow_tools":{"description":"Optional allow-list of exposed tools (empty = all)","type":"array","default":[],"items":{"type":"string"}},"args":{"description":"Command args for stdio mode","type":"array","default":[],"items":{"type":"string"}},"command":{"description":"Command for stdio mode","type":["string","null"],"default":null},"deny_tools":{"description":"Optional deny-list of exposed tools","type":"array","default":[],"items":{"type":"string"}},"env":{"description":"Environment variables for stdio mode","type":"object","additionalProperties":{"type":"string"},"default":{}},"request_timeout_ms":{"description":"Request timeout in milliseconds","type":"integer","format":"uint64","default":30000,"minimum":0},"startup_timeout_ms":{"description":"Startup timeout in milliseconds","type":"integer","format":"uint64","default":10000,"minimum":0},"tool_name_prefix":{"description":"Prefix used in tool naming and routing","type":"string","default":"mcp"},"transport":{"description":"Transport type: stdio or http","$ref":"#/$defs/McpTransport","default":"stdio"},"url":{"description":"URL for HTTP mode (streamable HTTP endpoint)","type":["string","null"],"default":null},"working_dir":{"description":"Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).","type":["string","null"]}}},"McpServerRuntimeConfig":{"type":"object","properties":{"allowed_origins":{"description":"Allowed browser origins for future streamable HTTP clients.","type":"array","default":["claude.ai","openai.com","localhost"],"items":{"type":"string"}},"bind":{"description":"Advertised bind address. The gateway may still be started with a CLI port override.","type":"string","default":"127.0.0.1:16831"},"exposed_tools":{"description":"Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.","type":"array","default":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"items":{"type":"string"}},"jwt_algorithms":{"description":"Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.","type":"array","default":["RS256"],"items":{"type":"string"}},"jwt_audience":{"description":"Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.","type":["string","null"],"default":null},"jwt_issuer":{"description":"Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.","type":["string","null"],"default":null},"jwt_jwks":{"description":"Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.","type":["string","null"],"default":null},"jwt_jwks_cache_ttl_secs":{"description":"Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.","type":"integer","format":"uint64","default":300,"minimum":0},"jwt_jwks_uri":{"description":"Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.","type":["string","null"],"default":null},"jwt_public_key_pem":{"description":"PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.","type":["string","null"],"default":null},"rate_limit_rps":{"description":"Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.","type":"integer","format":"uint32","default":10,"minimum":0},"require_auth":{"description":"Require an authenticated external identity for mutating calls.","type":"boolean","default":true}}},"McpTransport":{"type":"string","enum":["stdio","http"]},"MediaConfig":{"description":"Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.","type":"object","properties":{"audio_model":{"description":"Audio model name (Ollama model or OpenAI model). Default: \"whisper\".","type":"string","default":"whisper"},"audio_ollama_url":{"description":"Ollama base URL for audio transcription. Default: \"http://localhost:11434\".","type":"string","default":"http://localhost:11434"},"audio_provider":{"description":"Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".","type":"string","default":"none"},"max_audio_size_mb":{"description":"Maximum audio attachment size in MiB. Default: 20.","type":"integer","format":"uint","default":20,"minimum":0},"max_video_size_mb":{"description":"Maximum video attachment size in MiB. Default: 50.","type":"integer","format":"uint","default":50,"minimum":0},"video_max_frames":{"description":"Maximum video frames to extract per video. Default: 4.","type":"integer","format":"uint","default":4,"minimum":0},"video_provider":{"description":"Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".","type":"string","default":"none"}}},"MemoryConfig":{"description":"Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.","type":"object","properties":{"acl_enabled":{"description":"Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.","type":"boolean","default":false},"archive_after_days":{"description":"Archive daily/session files older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"auto_hydrate":{"description":"Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing","type":"boolean","default":true},"auto_save":{"description":"Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.","type":"boolean","default":true},"backend":{"description":"\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).","type":"string","default":"sqlite"},"conversation_retention_days":{"description":"For sqlite backend: prune conversation rows older than this many days","type":"integer","format":"uint32","default":3,"minimum":0},"daily_retention_days":{"description":"For sqlite backend: prune daily rows older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"embedding_cache_size":{"description":"Max embedding cache entries before LRU eviction","type":"integer","format":"uint","default":10000,"minimum":0},"embedding_dimensions":{"description":"Embedding vector dimensions","type":"integer","format":"uint","default":384,"minimum":0},"embedding_model":{"description":"Embedding model name (e.g. \"text-embedding-3-small\")","type":"string","default":"prx-local-hash-v1"},"embedding_provider":{"description":"Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"","type":"string","default":"local"},"events":{"description":"Raw/quasi-raw message event recording controls (`[memory.events]`).","$ref":"#/$defs/MemoryEventsConfig","default":{"record_assistant_messages":true,"record_tool_events":true,"record_user_messages":true}},"keyword_weight":{"description":"Weight for keyword BM25 in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.3},"legacy_conversation_turns_visible":{"description":"Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.","type":"boolean","default":true},"lucid_budget":{"description":"Token budget for lucid (replaces OPENPRX_LUCID_BUDGET)","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"lucid_cmd":{"description":"Path to lucid binary (replaces OPENPRX_LUCID_CMD)","type":["string","null"],"default":null},"lucid_failure_cooldown_ms":{"description":"Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)","type":"integer","format":"uint64","default":60000,"minimum":0},"lucid_local_hit_threshold":{"description":"Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)","type":"integer","format":"uint","default":3,"minimum":0},"lucid_recall_timeout_ms":{"description":"Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)","type":"integer","format":"uint64","default":5000,"minimum":0},"lucid_store_timeout_ms":{"description":"Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)","type":"integer","format":"uint64","default":3000,"minimum":0},"min_relevance_score":{"description":"Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4","type":"number","format":"double","default":0.4},"purge_after_days":{"description":"Purge archived files older than this many days","type":"integer","format":"uint32","default":30,"minimum":0},"semantic":{"description":"Semantic memory promotion controls (`[memory.semantic]`).","$ref":"#/$defs/MemorySemanticConfig","default":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30}},"sqlite_open_timeout_secs":{"description":"For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"sqlite_read_pool_size":{"description":"For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"vector_candidate_cap":{"description":"How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.","type":"integer","format":"uint","default":2000,"minimum":0},"vector_weight":{"description":"Weight for vector similarity in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.7}}},"MemoryEventsConfig":{"description":"Raw message event recording configuration (`[memory.events]`).","type":"object","properties":{"record_assistant_messages":{"description":"Record assistant replies.","type":"boolean","default":true},"record_tool_events":{"description":"Record tool calls and tool results in the durable message log.","type":"boolean","default":true},"record_user_messages":{"description":"Record inbound/user messages.","type":"boolean","default":true}}},"MemorySemanticConfig":{"description":"Semantic memory promotion configuration (`[memory.semantic]`).","type":"object","properties":{"auto_promote_assistant_messages":{"description":"Auto-promote eligible assistant messages. Disabled by default to reduce noise.","type":"boolean","default":false},"auto_promote_user_messages":{"description":"Auto-promote eligible user messages into long-term semantic memories.","type":"boolean","default":true},"min_chars":{"description":"Minimum content length for semantic auto-promotion.","type":"integer","format":"uint","default":30,"minimum":0}}},"MemoryWebhookConfig":{"type":"object","properties":{"bind":{"description":"Socket address for the receiver (e.g. \"0.0.0.0:16899\").","type":"string","default":"0.0.0.0:16899"},"signing_secret":{"description":"Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.","type":["string","null"],"default":null},"token":{"description":"Required bearer token for incoming webhook events.","type":["string","null"],"default":null}}},"ModelOperationSetting":{"description":"The operations a `[[providers.models]]` entry may list.","type":"string","enum":["chat","embedding","decision_endpoint","rerank","image_generation","audio_generation","video_generation"]},"ModelPricing":{"description":"Per-model pricing entry (USD per 1M tokens).","type":"object","properties":{"cache_read":{"description":"Cache read input price per 1M tokens.","type":"number","format":"double","default":0.0},"cache_write":{"description":"Cache write/creation input price per 1M tokens.","type":"number","format":"double","default":0.0},"input":{"description":"Input price per 1M tokens","type":"number","format":"double","default":0.0},"output":{"description":"Output price per 1M tokens","type":"number","format":"double","default":0.0}}},"ModelRouteConfig":{"description":"Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"hint":{"description":"Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")","type":"string"},"level":{"type":["string","null"]},"model":{"description":"Model to use with that provider","type":"string"},"provider":{"description":"Provider to route to (must match a known provider name)","type":"string"},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true,"required":["hint","provider","model"]},"ModelSettings":{"description":"A model level plus explicit parameter overrides in `[model_settings.\"\"]`.","type":"object","properties":{"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"level":{"type":["string","null"]},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true},"MultimodalConfig":{"description":"Multimodal (image) handling configuration (`[multimodal]` section).","type":"object","properties":{"allow_remote_fetch":{"description":"Allow fetching remote image URLs (http/https). Enabled by default.","type":"boolean","default":true},"max_image_size_mb":{"description":"Maximum image payload size in MiB before base64 encoding.","type":"integer","format":"uint","default":5,"minimum":0},"max_images":{"description":"Maximum number of image attachments accepted per request.","type":"integer","format":"uint","default":4,"minimum":0}}},"NextcloudTalkConfig":{"description":"Nextcloud Talk bot configuration (webhook receive + OCS send API).","type":"object","properties":{"allowed_users":{"description":"Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Bot app token used for OCS API bearer auth.","type":"string"},"base_url":{"description":"Nextcloud base URL (e.g. \"https://cloud.example.com\").","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"webhook_secret":{"description":"Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).","type":["string","null"],"default":null}},"required":["base_url","app_token"]},"NgrokTunnelConfig":{"type":"object","properties":{"auth_token":{"description":"ngrok auth token","type":"string"},"domain":{"description":"Optional custom domain","type":["string","null"]}},"required":["auth_token"]},"NodeServerConfig":{"description":"Node daemon runtime config used by `prx-node`.","type":"object","properties":{"allowed_commands":{"description":"Command allowlist matched on first token. Default: empty, which allows any\ncommand from an authenticated caller; `[\"*\"]` means the same.","type":"array","default":[],"items":{"type":"string"}},"bearer_token":{"description":"Required bearer token for /rpc.","type":"string","default":""},"blocked_commands":{"description":"Command denylist matched on first token. Always enforced.","type":"array","default":[],"items":{"type":"string"}},"exec_timeout_ms":{"description":"Default command timeout in milliseconds.","type":"integer","format":"uint64","default":15000,"minimum":0},"hmac_secret":{"description":"Optional HMAC signing secret.","type":["string","null"],"default":null},"listen_addr":{"description":"Listen address for node daemon.","type":"string","default":"127.0.0.1:8787"},"max_concurrent_tasks":{"description":"Maximum number of concurrent async command tasks.","type":"integer","format":"uint","default":8,"minimum":0},"max_output_bytes":{"description":"Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.","type":"integer","format":"uint","default":1048576,"minimum":0},"sandbox_root":{"description":"Sandbox root directory for read/write/cwd constraints.","type":"string","default":"."},"task_result_ttl_ms":{"description":"TTL for completed task results in milliseconds.","type":"integer","format":"uint64","default":3600000,"minimum":0},"tls_cert":{"description":"TLS certificate path (PEM).","type":["string","null"],"default":null},"tls_key":{"description":"TLS private key path (PEM).","type":["string","null"],"default":null},"tls_required":{"description":"Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.","type":"boolean","default":true}}},"NodesConfig":{"description":"Remote node proxy configuration for core-side RPC calls and node daemon defaults.","type":"object","properties":{"nodes":{"description":"Configured remote nodes.","type":"array","default":[],"items":{"$ref":"#/$defs/RemoteNodeConfig"}},"request_timeout_ms":{"description":"Default request timeout for node RPC calls.","type":"integer","format":"uint64","default":15000,"minimum":0},"retry_max":{"description":"Default max retries for node RPC calls.","type":"integer","format":"uint8","default":2,"maximum":255,"minimum":0},"server":{"description":"Embedded node server defaults used by `prx-node`.","$ref":"#/$defs/NodeServerConfig","default":{"allowed_commands":[],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}}},"ObservabilityConfig":{"description":"Observability backend configuration (`[observability]` section).","type":"object","properties":{"backend":{"description":"\"none\" | \"log\" | \"prometheus\" | \"otel\"","type":"string","default":"none"},"otel_endpoint":{"description":"OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".","type":["string","null"],"default":null},"otel_service_name":{"description":"Service name reported to the OTel collector. Defaults to \"prx\".","type":["string","null"],"default":null}}},"OllamaProviderConfig":{"description":"Ollama-specific request options (`[providers.ollama]`).","type":"object","properties":{"num_ctx":{"description":"Explicit context window sent as Ollama `options.num_ctx`.","type":["integer","null"],"format":"uint","default":null,"minimum":0}}},"OsPagingConfig":{"description":"Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.","type":"object","properties":{"eviction_threshold":{"description":"Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.","type":"number","format":"double","default":0.7},"keep_recent_messages":{"description":"Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).","type":"integer","format":"uint","default":12,"minimum":0},"max_recalled_pages":{"description":"Maximum number of evicted pages (document chunks) recalled per turn.","type":"integer","format":"uint","default":10,"minimum":0},"proactive_retrieval":{"description":"Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.","type":"boolean","default":true},"retrieval_injection_role":{"description":"Role under which recalled pages are injected.","$ref":"#/$defs/RetrievalInjectionRole","default":"system"}}},"PluginsConfig":{"description":"WASM plugin runtime configuration.","type":"object","properties":{"enabled":{"description":"Load WASM plugins from `/plugins`. Default: `false`.","type":"boolean","default":false}},"additionalProperties":false},"ProviderModelConfig":{"description":"One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.","type":"object","properties":{"context_window":{"description":"The model's context window in tokens.","type":["integer","null"],"format":"uint32","minimum":0},"model":{"description":"The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.","type":["string","null"]},"native_tools":{"description":"Whether the model accepts native tool calls.","type":["boolean","null"]},"operations":{"description":"The complete list of operations the model executes; every operation not\nlisted is unsupported.","type":["array","null"],"items":{"$ref":"#/$defs/ModelOperationSetting"}},"provider":{"description":"The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.","type":"string"},"streaming":{"description":"Whether the model streams responses.","type":["boolean","null"]},"structured_output":{"description":"Whether the model honours a JSON-schema response format.","type":["boolean","null"]},"tool_call_dialect":{"description":"The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema_dialect":{"description":"The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]},"vision_input":{"description":"Whether the model accepts image input.","type":["boolean","null"]}},"required":["provider"]},"ProviderToolDialectConfig":{"description":"One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.","type":"object","properties":{"model":{"description":"The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.","type":["string","null"]},"provider":{"description":"The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.","type":"string"},"tool_call":{"description":"The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema":{"description":"The tool-schema dialect the endpoint accepts.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]}},"required":["provider"]},"ProvidersConfig":{"description":"Provider-specific runtime configuration (`[providers]`).","type":"object","properties":{"models":{"description":"Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.","type":"array","items":{"$ref":"#/$defs/ProviderModelConfig"}},"ollama":{"description":"Ollama-specific request options (`[providers.ollama]`).","$ref":"#/$defs/OllamaProviderConfig","default":{"num_ctx":null}},"tool_dialects":{"description":"Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).","type":"array","items":{"$ref":"#/$defs/ProviderToolDialectConfig"}}}},"ProxyConfig":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).","type":"object","properties":{"all_proxy":{"description":"Fallback proxy URL for all schemes.","type":["string","null"],"default":null},"http_proxy":{"description":"Proxy URL for HTTP requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"https_proxy":{"description":"Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"no_proxy":{"description":"No-proxy bypass list. Same format as NO_PROXY.","type":"array","default":[],"items":{"type":"string"}},"scope":{"description":"Proxy application scope.","$ref":"#/$defs/ProxyScope","default":"prx"},"services":{"description":"Service selectors used when scope = \"services\".","type":"array","default":[],"items":{"type":"string"}}}},"ProxyScope":{"description":"Proxy application scope — determines which outbound traffic uses the proxy.","oneOf":[{"description":"Use system environment proxy variables only.","type":"string","const":"environment"},{"description":"Apply proxy to all OpenPRX-managed HTTP traffic (default).","type":"string","const":"prx"},{"description":"Apply proxy only to explicitly listed service selectors.","type":"string","const":"services"}]},"QQConfig":{"description":"QQ Official Bot configuration (Tencent QQ Bot SDK)","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs. Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from QQ Bot developer console","type":"string"},"app_secret":{"description":"App Secret from QQ Bot developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["app_id","app_secret"]},"QueryClassificationConfig":{"description":"Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.","type":"object","properties":{"rules":{"description":"Classification rules evaluated in priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/ClassificationRule"}}}},"RamfluxAccountConfig":{"description":"Persona for one ramflux AI account. Missing fields fall back to the global agent.","type":"object","properties":{"cross_conversation_retrieval":{"description":"Cross-conversation memory retrieval. Off unless the owner sets it.","type":"boolean","default":false},"model":{"type":["string","null"],"default":null},"provider":{"type":["string","null"],"default":null},"scope_profile":{"type":["string","null"],"default":null},"system_prompt_file":{"description":"Path to a system-prompt file. Relative paths are resolved from the workspace.","type":["string","null"],"default":null}},"additionalProperties":false},"RamfluxAttachmentFetch":{"description":"Per-turn caps for `attachment.fetch`.","type":"object","properties":{"max_bytes":{"type":"integer","format":"uint64","default":5242880,"minimum":0},"max_per_turn":{"type":"integer","format":"uint8","default":4,"maximum":255,"minimum":0}},"additionalProperties":false},"RamfluxAuthorizationMode":{"description":"How prx combines its own setting with `bridge.hello.authorization`.","oneOf":[{"description":"Use the agent-host value. Until hello arrives, the effective mode is supervised.","type":"string","const":"follow_rf"},{"description":"Always supervised, even when the agent-host declares full.","type":"string","const":"supervised"},{"description":"Full only when the agent-host also declares full. Config alone never yields full.","type":"string","const":"full"}]},"RamfluxConfig":{"description":"Local ramflux agent-host bridge (`[channels_config.ramflux]`).","type":"object","properties":{"accounts":{"type":"object","additionalProperties":{"$ref":"#/$defs/RamfluxAccountConfig"},"default":{}},"allowed_block_types":{"type":"array","default":["Text","Markdown","Heading","KeyValue","Metric","List","TableFallback","Form","Input","Select","Progress","LogStream","Warning","Error","Success","Approval","ActionGroup","FilePreview","Fallback"],"items":{"type":"string"}},"attachment_fetch":{"$ref":"#/$defs/RamfluxAttachmentFetch","default":{"max_bytes":5242880,"max_per_turn":4}},"authorization_mode":{"$ref":"#/$defs/RamfluxAuthorizationMode","default":"follow_rf"},"encrypt_at_rest":{"type":"boolean","default":true},"max_in_flight_per_conversation":{"type":"integer","format":"uint8","default":1,"maximum":255,"minimum":0},"on_new_message":{"$ref":"#/$defs/RamfluxOnNewMessage","default":"queue"},"socket_path":{"description":"Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.","type":["string","null"],"default":null},"surface_limits":{"$ref":"#/$defs/RamfluxSurfaceLimits","default":{"max_actions":16,"max_blocks":32,"max_bytes":65536}},"turn_wall_clock_secs":{"description":"Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.","type":"integer","format":"uint64","default":120,"minimum":0}},"additionalProperties":false},"RamfluxOnNewMessage":{"description":"What to do with a new inbound message while a turn for that conversation is running.","type":"string","enum":["queue","interrupt"]},"RamfluxSurfaceLimits":{"description":"Limits for `reply.surface` blocks and actions.","type":"object","properties":{"max_actions":{"type":"integer","format":"uint32","default":16,"minimum":0},"max_blocks":{"type":"integer","format":"uint32","default":32,"minimum":0},"max_bytes":{"type":"integer","format":"uint32","default":65536,"minimum":0}},"additionalProperties":false},"ReliabilityCircuitBreakerConfig":{"description":"Process-local provider circuit policy (`[reliability.circuit_breaker]`).","type":"object","properties":{"enabled":{"description":"Enable protection for factory-built provider chains.","type":"boolean","default":true},"failure_threshold":{"description":"Consecutive transient failures that open a circuit (at least 1).","type":"integer","format":"uint32","default":5,"minimum":0},"max_open_secs":{"description":"Maximum doubled window, between open_secs and 3600 seconds.","type":"integer","format":"uint64","default":300,"minimum":0},"open_secs":{"description":"Initial open window in seconds (at least 1).","type":"integer","format":"uint64","default":30,"minimum":0}}},"ReliabilityConfig":{"description":"Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.","type":"object","properties":{"acknowledge_single_provider_risk":{"description":"Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.","type":"boolean","default":false},"api_keys":{"description":"Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.","type":"array","default":[],"items":{"type":"string"}},"channel_initial_backoff_secs":{"description":"Initial backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":2,"minimum":0},"channel_max_backoff_secs":{"description":"Max backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":60,"minimum":0},"circuit_breaker":{"description":"Per-provider consecutive failure protection.","$ref":"#/$defs/ReliabilityCircuitBreakerConfig","default":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30}},"fallback_providers":{"description":"Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).","type":"array","default":[],"items":{"type":"string"}},"model_fallbacks":{"description":"Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`","type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"default":{}},"provider_backoff_ms":{"description":"Base backoff (ms) for provider retry delay.","type":"integer","format":"uint64","default":500,"minimum":0},"provider_retries":{"description":"Retries per provider before failing over.","type":"integer","format":"uint32","default":2,"minimum":0},"scheduler_poll_secs":{"description":"Scheduler polling cadence in seconds.","type":"integer","format":"uint64","default":15,"minimum":0},"scheduler_retries":{"description":"Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.","type":"integer","format":"uint32","default":2,"minimum":0}}},"RemoteNodeConfig":{"description":"A remote node target for core-side node proxy calls.","type":"object","properties":{"bearer_token":{"description":"Bearer token for node RPC authentication.","type":"string"},"endpoint":{"description":"Base endpoint (e.g. \"http://127.0.0.1:8787\").","type":"string"},"hmac_secret":{"description":"Optional request signing key (HMAC-SHA256).","type":["string","null"],"default":null},"id":{"description":"Stable node ID used by the nodes tool.","type":"string"},"retry_max":{"description":"Optional per-node retry override.","type":["integer","null"],"format":"uint8","default":null,"maximum":255,"minimum":0},"timeout_ms":{"description":"Optional per-node timeout override.","type":["integer","null"],"format":"uint64","default":null,"minimum":0}},"required":["id","endpoint","bearer_token"]},"RetrievalInjectionRole":{"description":"Where recalled context pages are injected back into the request.","oneOf":[{"description":"Inject recalled pages as a leading `system` message (not user-visible).","type":"string","const":"system"},{"description":"Inject recalled pages as a leading `user` message.","type":"string","const":"user"}]},"RouterConfig":{"description":"Heuristic LLM router configuration (`[router]` section).","type":"object","properties":{"alpha":{"description":"Similarity score weight. Phase 1 keeps this at `0.0`.","type":"number","format":"float","default":0.0},"beta":{"description":"Capability score weight.","type":"number","format":"float","default":0.5},"delta":{"description":"Cost penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"epsilon":{"description":"Latency penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"gamma":{"description":"Elo score weight.","type":"number","format":"float","default":0.30000001192092896},"knn_k":{"description":"Number of nearest neighbors considered for voting. Default: `7`.","type":"integer","format":"uint","default":7,"minimum":0},"knn_min_records":{"description":"Minimum history records before KNN affects routing. Default: `10`.","type":"integer","format":"uint","default":10,"minimum":0},"models":{"description":"Candidate model registry.","type":"array","default":[],"items":{"$ref":"#/$defs/RouterModelConfig"}}}},"RouterModelConfig":{"description":"Static router metadata for one model candidate.","type":"object","properties":{"categories":{"description":"Capability categories such as `conversation`, `code`, or `analysis`.","type":"array","default":[],"items":{"type":"string"}},"cost_per_million_tokens":{"description":"USD cost per million tokens.","type":"number","format":"float","default":0.0},"elo_rating":{"description":"Initial Elo rating.","type":"number","format":"float","default":1000.0},"latency_ms":{"description":"Average latency in milliseconds.","type":"integer","format":"uint32","default":2000,"minimum":0},"max_context":{"description":"Maximum context window in tokens.","type":"integer","format":"uint","default":1000000,"minimum":0},"model_id":{"description":"Model identifier without provider prefix.","type":"string"},"provider":{"description":"Provider identifier.","type":"string"},"reserved_output_tokens":{"description":"Output tokens reserved for this model when planning input context.","type":["integer","null"],"format":"uint","minimum":0}},"required":["model_id","provider"]},"RuntimeConfig":{"description":"Runtime adapter configuration (`[runtime]` section).","type":"object","properties":{"codex_reasoning_effort":{"description":"Codex reasoning effort","type":["string","null"],"default":null},"codex_stream_idle_timeout_secs":{"description":"Codex stream idle timeout in seconds","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"docker":{"description":"Docker runtime settings (used when `kind = \"docker\"`).","$ref":"#/$defs/DockerRuntimeConfig","default":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true}},"idle_hang_secs":{"description":"Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"kind":{"description":"Runtime kind (`native` | `docker`).","type":"string","default":"native"},"long_task_warn_secs":{"description":"Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"managed_cgroup_root":{"description":"Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.","type":["string","null"],"default":null},"max_blocking_threads":{"description":"Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"reasoning_enabled":{"description":"Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported","type":["boolean","null"],"default":null},"shell_env_allowlist":{"description":"Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.","type":"array","default":[],"items":{"type":"string"}},"workdir":{"description":"Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.","type":["string","null"],"default":null}}},"SchedulerConfig":{"description":"Scheduler configuration for periodic task execution (`[scheduler]` section).","type":"object","properties":{"claim_lease_secs":{"description":"Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.","type":"integer","format":"uint64","default":90,"minimum":0},"max_tasks":{"description":"Maximum number of persisted scheduled tasks.","type":"integer","format":"uint","default":64,"minimum":0}}},"ScopeConfig":{"description":"Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```","type":"object","properties":{"assign_owners":{"description":"Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.","type":"array","default":[],"items":{"type":"string"}},"default":{"description":"Default action when no rule matches: \"allow\" (default) or \"deny\".","$ref":"#/$defs/ScopeDefault","default":"allow"},"rules":{"description":"Ordered list of scope rules evaluated top-to-bottom.","type":"array","default":[],"items":{"$ref":"#/$defs/ScopeRule"}}}},"ScopeDefault":{"description":"What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.","oneOf":[{"description":"Unmatched tool calls are allowed (the default).","type":"string","const":"allow"},{"description":"Unmatched tool calls are refused.","type":"string","const":"deny"}]},"ScopeRule":{"description":"A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.","type":"object","properties":{"assign_allow":{"description":"Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".","type":"array","default":[],"items":{"type":"string"}},"assign_deny":{"description":"Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.","type":"array","default":[],"items":{"type":"string"}},"channel":{"description":"Match by channel name: \"signal\", \"telegram\", \"discord\", etc.","type":["string","null"]},"chat_type":{"description":"Match by chat type: \"direct\", \"group\", or \"*\" for any type.","type":["string","null"]},"send_allow":{"description":"Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.","type":"array","default":[],"items":{"type":"string"}},"send_deny":{"description":"Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.","type":"array","default":[],"items":{"type":"string"}},"tools_allow":{"description":"Tool whitelist: only these tools are allowed (empty = all tools permitted).","type":"array","default":[],"items":{"type":"string"}},"tools_deny":{"description":"Tool blacklist: these tools are denied regardless of allow list.","type":"array","default":[],"items":{"type":"string"}},"user":{"description":"Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.","type":["string","null"]}}},"SecretsConfig":{"description":"Secrets encryption configuration (`[secrets]` section).","type":"object","properties":{"encrypt":{"description":"Enable encryption for API keys and tokens in config.toml","type":"boolean","default":true}}},"SecurityConfig":{"description":"Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.","type":"object","properties":{"audit":{"description":"Audit logging configuration","$ref":"#/$defs/AuditConfig","default":{"log_path":"audit.log","max_size_mb":100}},"workspace_hooks":{"description":"Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.","$ref":"#/$defs/WorkspaceHooks"}}},"SelfSystemConfig":{"description":"Self-system experimental automation config (`[self_system]`).","type":"object","properties":{"evolution_config_path":{"description":"Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG)","type":["string","null"],"default":null},"evolution_debug_raw":{"description":"Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW)","type":"boolean","default":false},"evolution_interval_hours":{"description":"Evolution scheduler interval in hours (daemon mode).","type":"integer","format":"uint32","default":24,"minimum":0},"evolution_judge_timeout_secs":{"description":"Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.","type":"integer","format":"uint64","default":180,"minimum":0},"evolution_model_max_micro_usd":{"description":"Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.","type":"integer","format":"uint64","default":0,"minimum":0},"evolution_model_max_tokens":{"description":"Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.","type":"integer","format":"uint64","default":16384,"minimum":0},"fitness":{"description":"Daily fitness snapshot policy.","$ref":"#/$defs/FitnessConfig","default":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"}},"fitness_interval_hours":{"description":"Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.","type":"integer","format":"uint64","default":24,"minimum":0}}},"SessionsSpawnConfig":{"description":"Sessions spawn configuration (`[sessions_spawn]` section).","type":"object","properties":{"cleanup_on_complete":{"description":"Remove worker workspace directory after process-mode completion.","type":"boolean","default":true},"default_mode":{"description":"Default execution mode for sessions_spawn (`task` or `process`).","type":"string","default":"task"},"process_memory_strategy":{"description":"Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.","type":"string","default":"shared_fabric"},"worker_workspace_root":{"description":"Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.","type":["string","null"],"default":null}}},"SignalConfig":{"type":"object","properties":{"account":{"description":"E.164 phone number of the signal-cli account (e.g. \"+1234567890\").","type":"string"},"allowed_from":{"description":"Allowed sender phone numbers (E.164) or \"*\" for all.","type":"array","default":[],"items":{"type":"string"}},"cli_path":{"description":"Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).","type":["string","null"],"default":null},"daemon_http_port":{"description":"Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"daemon_mode":{"description":"Deprecated: ignored. Accepted for backward compatibility with older config files.","type":["boolean","null"],"default":null},"data_dir":{"description":"signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_id":{"description":"Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group","type":["string","null"],"default":null},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"http_url":{"description":"Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.","type":"string","default":"http://localhost:8080"},"ignore_attachments":{"description":"Skip messages that are attachment-only (no text body).","type":"boolean","default":false},"ignore_stories":{"description":"Skip incoming story messages.","type":"boolean","default":false},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"mode":{"description":"Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.","type":["string","null"],"default":null},"startup_timeout_ms":{"description":"Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.","type":"integer","format":"uint64","default":30000,"minimum":0},"storm_protection":{"description":"Signal ingress storm protection controls.","$ref":"#/$defs/SignalStormProtectionConfig","default":{"abnormal_threshold":10,"abnormal_window_secs":60,"breaker_duration_secs":300,"dedupe_ttl_secs":60,"min_reply_interval_secs":2}}},"required":["account"]},"SignalStormProtectionConfig":{"type":"object","properties":{"abnormal_threshold":{"description":"Non-user event threshold within `abnormal_window_secs` before tripping the breaker.","type":"integer","format":"uint","default":10,"minimum":0},"abnormal_window_secs":{"description":"Sliding window in seconds for non-user event counting.","type":"integer","format":"uint64","default":60,"minimum":0},"breaker_duration_secs":{"description":"Circuit breaker duration in seconds after threshold is reached.","type":"integer","format":"uint64","default":300,"minimum":0},"dedupe_ttl_secs":{"description":"Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.","type":"integer","format":"uint64","default":60,"minimum":0},"min_reply_interval_secs":{"description":"Minimum interval in seconds between replies for the same `(channel + reply_target)`.","type":"integer","format":"uint64","default":2,"minimum":0}}},"SkillRagConfig":{"description":"Dynamic skill retrieval configuration (`[skill_rag]` section).","type":"object","properties":{"top_k":{"description":"How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).","type":"integer","format":"uint","default":32,"minimum":0}}},"SkillSuiteRegistration":{"description":"The frozen suite that governs one skill's proposals.","type":"object","properties":{"skill_id":{"description":"The skill the suite governs.","type":"string"},"suite_digest":{"description":"SHA-256 digest (64 lowercase hex digits) of the frozen suite.","type":"string"}},"additionalProperties":false,"required":["skill_id","suite_digest"]},"SkillsConfig":{"description":"Skills loading configuration (`[skills]` section).","type":"object","properties":{"open_skills_dir":{"description":"Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.","type":["string","null"],"default":null},"openclaw_skills_dir":{"description":"Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.","type":["string","null"],"default":null}}},"SkillsLifecycleConfig":{"description":"`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.","type":"object","properties":{"allow_executable_proposals":{"description":"Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.","type":"boolean","default":false},"enabled":{"description":"Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.","type":"boolean","default":false},"max_concurrent_evaluations":{"description":"Most evaluations running at once.","type":"integer","format":"uint32","default":1,"minimum":0},"max_edit_fraction":{"description":"Edit budget of a proposal as a fraction of the skill body, in (0, 1].","type":"number","format":"double","default":0.2},"max_edit_tokens":{"description":"Edit budget of a proposal, in tokens.","type":"integer","format":"uint64","default":300,"minimum":0},"max_proposals_per_cycle":{"description":"Most proposals one cycle may start.","type":"integer","format":"uint32","default":1,"minimum":0},"min_cases_floor":{"description":"Smallest `min_cases` a governing suite may declare. Below 3 is refused.","type":"integer","format":"uint32","default":3,"minimum":0},"mode":{"description":"`draft_only`, `shadow` or `auto`.","$ref":"#/$defs/SkillsLifecycleModeConfig","default":"draft_only"},"owner_scope":{"description":"The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.","type":["string","null"],"default":null},"require_holdout":{"description":"A governing suite must have a holdout split. `false` is refused.","type":"boolean","default":true},"storage_dir":{"description":"Store location under the workspace. Only the default is supported.","type":"string","default":"self/skill-lifecycle"},"suites":{"description":"The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.","type":"array","default":[],"items":{"$ref":"#/$defs/SkillSuiteRegistration"}}},"additionalProperties":false},"SkillsLifecycleModeConfig":{"description":"What the lifecycle may do. Mirrors `LifecycleMode`.","oneOf":[{"description":"Drafts and reviews only.","type":"string","const":"draft_only"},{"description":"Drafts plus evaluation and gating; never publishes.","type":"string","const":"shadow"},{"description":"Publishes an eligible proposal after every gate.","type":"string","const":"auto"}]},"SlackConfig":{"description":"Slack bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Slack user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Slack app-level token for Socket Mode (xapp-...).","type":["string","null"]},"bot_token":{"description":"Slack bot OAuth token (xoxb-...).","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["bot_token"]},"SmartGroupConfig":{"description":"Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).","type":"object","properties":{"classifier_max_context_messages":{"description":"How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.","type":"integer","format":"uint","default":3,"minimum":0},"classifier_model":{"description":"Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.","type":"string","default":""},"classifier_provider":{"description":"Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.","type":"string","default":""},"classifier_temperature":{"description":"Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).","type":"number","format":"double","default":0.0},"classifier_timeout_secs":{"description":"Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.","type":"integer","format":"uint64","default":5,"minimum":0}}},"StorageConfig":{"description":"Persistent storage configuration (`[storage]` section).","type":"object","properties":{"provider":{"description":"Storage provider settings (e.g. sqlite, postgres).","$ref":"#/$defs/StorageProviderSection","default":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}}},"StorageProviderConfig":{"description":"Storage provider backend configuration (e.g. postgres connection details).","type":"object","properties":{"connect_timeout_secs":{"description":"Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"db_url":{"description":"Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.","type":["string","null"],"default":null},"pool_max_size":{"description":"Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.","type":"integer","format":"uint","default":32,"minimum":0},"provider":{"description":"Storage engine key (e.g. \"postgres\", \"sqlite\").","type":"string","default":""},"schema":{"description":"Database schema for SQL backends.","type":"string","default":"public"},"table":{"description":"Table name for memory entries.","type":"string","default":"memories"}}},"StorageProviderSection":{"description":"Wrapper for the storage provider configuration section.","type":"object","properties":{"config":{"description":"Storage provider backend settings.","$ref":"#/$defs/StorageProviderConfig","default":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"StreamMode":{"description":"Streaming mode for channels that support progressive message updates.","oneOf":[{"description":"No streaming -- send the complete response as a single message (default).","type":"string","const":"off"},{"description":"Update a draft message with every flush interval.","type":"string","const":"partial"}]},"TailscaleTunnelConfig":{"type":"object","properties":{"funnel":{"description":"Use Tailscale Funnel (public internet) vs Serve (tailnet only)","type":"boolean","default":false},"hostname":{"description":"Optional hostname override","type":["string","null"]}}},"TaskRoutingConfig":{"description":"Lightweight pre-LLM task routing.","type":"object","properties":{"default_intent":{"description":"Fallback intent when no rule matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"rules":{"description":"Rules evaluated in descending priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/TaskRoutingRule"}}}},"TaskRoutingIntentConfig":{"description":"Task-routing default and rule intent.","type":"string","enum":["simple","delegate","stream"]},"TaskRoutingRule":{"description":"A single task-routing rule.","type":"object","properties":{"intent":{"description":"Route intent to apply when a keyword matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"model_hint":{"description":"Optional model hint/raw model for non-delegated requests.","type":["string","null"],"default":null},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0},"sub_agent_model":{"description":"Optional raw sub-agent model override for delegated tasks.","type":["string","null"],"default":null}}},"TelegramConfig":{"description":"Telegram bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Telegram user IDs or usernames. Empty = deny all.","type":"array","items":{"type":"string"}},"bot_token":{"description":"Telegram Bot API token (from @BotFather).","type":"string"},"draft_update_interval_ms":{"description":"Minimum interval (ms) between draft message edits to avoid rate limits.","type":"integer","format":"uint64","default":1000,"minimum":0},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"interrupt_on_new_message":{"description":"When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.","type":"boolean","default":false},"stream_mode":{"description":"Streaming mode for progressive response delivery via message edits.","$ref":"#/$defs/StreamMode","default":"off"}},"required":["bot_token","allowed_users"]},"ToolCallDialectSetting":{"description":"The tool-call grammars an operator may declare for an endpoint.","oneOf":[{"description":"Only the native `tool_calls` array is a tool call (the default).","type":"string","const":"native"},{"description":"Additionally read `{json}` from the content,\nfor a tool name the request registered.","type":"string","const":"xml_function_tags"}]},"ToolSchemaDialectSetting":{"description":"The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.","oneOf":[{"description":"The published document, byte for byte (the default).","type":"string","const":"raw"},{"description":"The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.","type":"string","const":"no_root_combinators"}]},"ToolTieringConfig":{"description":"Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.","type":"object","properties":{"always_exclude":{"description":"Tool names excluded from capability publication.","type":"array","default":[],"items":{"type":"string"}},"always_include":{"description":"Tool names preferred for direct publication, subject to admission gates.","type":"array","default":[],"items":{"type":"string"}},"channel_exclude":{"description":"Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefault: empty (nothing is hidden); list tool names to hide them on channels.","type":"array","default":[],"items":{"type":"string"}},"defer_unlisted":{"description":"Operator option: publish only the core tools plus `always_include` and\nleave every other tool behind `capability_search` and its exact name.\nDefault: false (every available tool is published to the model).","type":"boolean","default":false}}},"TunnelConfig":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.","type":"object","properties":{"cloudflare":{"description":"Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).","anyOf":[{"$ref":"#/$defs/CloudflareTunnelConfig"},{"type":"null"}],"default":null},"custom":{"description":"Custom tunnel command configuration (used when `provider = \"custom\"`).","anyOf":[{"$ref":"#/$defs/CustomTunnelConfig"},{"type":"null"}],"default":null},"ngrok":{"description":"ngrok tunnel configuration (used when `provider = \"ngrok\"`).","anyOf":[{"$ref":"#/$defs/NgrokTunnelConfig"},{"type":"null"}],"default":null},"provider":{"description":"Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.","type":"string","default":"none"},"tailscale":{"description":"Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).","anyOf":[{"$ref":"#/$defs/TailscaleTunnelConfig"},{"type":"null"}],"default":null}}},"UserPolicyConfig":{"description":"Startup user policy entry (`[[user_policies]]`).","type":"object","properties":{"blocked_patterns":{"type":"array","default":[],"items":{"type":"string"}},"projects":{"type":"array","default":[],"items":{"type":"string"}},"role":{"type":"string","default":"guest"},"user_id":{"type":"string"},"visibility_ceiling":{"type":"string","default":"private"}},"required":["user_id"]},"WacliConfig":{"description":"wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```","type":"object","properties":{"allow_unsigned_loopback":{"description":"Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).","type":"boolean","default":false},"allowed_from":{"description":"Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.","type":"array","default":["*"],"items":{"type":"string"}},"bot_jid":{"description":"Bot's own JID, used for reply-to-bot mention detection.","type":["string","null"],"default":null},"bot_lid":{"description":"The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.","type":["string","null"],"default":null},"bot_number":{"description":"Bot's own phone number (digits), used for `@` mention detection.","type":["string","null"],"default":null},"cli_path":{"description":"Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.","type":["string","null"],"default":null},"group_reply_mode":{"description":"Smart group-reply mode. When `None`, derived from `mention_only`.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"host":{"description":"REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].","type":["string","null"],"writeOnly":true},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"outbound_media_workspace_only":{"description":"Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.","type":"boolean","default":false},"port":{"description":"REMOVED: legacy JSON-RPC daemon port. See `host`.","type":["integer","null"],"format":"uint16","maximum":65535,"minimum":0,"writeOnly":true},"self_chat_mode":{"description":"Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.","type":"boolean","default":false},"store_dir":{"description":"wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.","type":["string","null"],"default":null},"webhook_listen":{"description":"Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").","type":"string","default":"127.0.0.1:16868"},"webhook_path":{"description":"HTTP path the webhook server serves (default: \"/wacli\").","type":"string","default":"/wacli"},"webhook_secret":{"description":"HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.","type":["string","null"],"default":null}}},"WebSearchConfig":{"description":"Web search tool configuration (`[web_search]` section).","type":"object","properties":{"brave_api_key":{"description":"Brave Search API key (required if provider is \"brave\")","type":["string","null"],"default":null},"fetch_max_chars":{"description":"Maximum characters returned by `web_fetch` (default 10000)","type":"integer","format":"uint","default":50000,"minimum":0},"max_results":{"description":"Maximum results per search (1-20)","type":"integer","format":"uint","default":15,"minimum":0},"provider":{"description":"Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)","type":"string","default":"duckduckgo"},"timeout_secs":{"description":"Request timeout in seconds","type":"integer","format":"uint64","default":15,"minimum":0}}},"WebhookConfig":{"description":"Webhook channel configuration.","type":"object","properties":{"port":{"description":"Port to listen on for incoming webhooks.","type":"integer","format":"uint16","maximum":65535,"minimum":0},"secret":{"description":"Optional shared secret for webhook signature verification.","type":["string","null"]}},"required":["port"]},"WhatsAppConfig":{"description":"WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.","type":"object","properties":{"access_token":{"description":"Access token from Meta Business Suite (Cloud API mode)","type":["string","null"],"default":null},"allowed_numbers":{"description":"Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"app_secret":{"description":"App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"pair_code":{"description":"Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one","type":["string","null"],"default":null},"pair_phone":{"description":"Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used","type":["string","null"],"default":null},"phone_number_id":{"description":"Phone number ID from Meta Business API (Cloud API mode)","type":["string","null"],"default":null},"read_pool_size":{"description":"Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"session_path":{"description":"Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs","type":["string","null"],"default":null},"verify_token":{"description":"Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode","type":["string","null"],"default":null},"ws_url":{"description":"WebSocket URL override (replaces WHATSAPP_WS_URL)","type":["string","null"],"default":null}}},"WorkspaceHooks":{"description":"Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).","oneOf":[{"description":"They do not run (the default); `prx doctor` and `hooks_status` say so.","type":"string","const":"off"},{"description":"They run, in a cleared environment and a dedicated directory beside\n`config.toml`.","type":"string","const":"on"}]},"WorkspaceMcpServers":{"description":"Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).","oneOf":[{"description":"None: a workspace file may only narrow the servers defined in\n`config.toml`.","type":"string","const":"off"},{"description":"HTTP servers (still refused when they target a private address).","type":"string","const":"http_only"},{"description":"HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.","type":"string","const":"stdio"}]},"XinConfig":{"description":"Configuration for the xin autonomous task engine (`[xin]`).","type":"object","properties":{"adopt_legacy_tasks":{"description":"Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).","type":"boolean","default":false},"interval_minutes":{"description":"Tick interval in minutes (minimum 1). Default: 5.","type":"integer","format":"uint32","default":5,"minimum":0},"stale_timeout_minutes":{"description":"Minutes after which a running task is marked stale. Default: 60.","type":"integer","format":"uint32","default":60,"minimum":0}}},"AgentMessaging":{"description":"Owner-controlled inbound session messaging (enabled unless explicitly off).","type":"object","properties":{"inbound":{"type":"boolean","default":true}}}}} +{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Config","description":"Top-level OpenPRX configuration, loaded from `config.toml`.\n\nResolution order: `OPENPRX_WORKSPACE` (legacy: `OPENPRX_WORKSPACE`) env\n→ `active_workspace.toml` marker\n→ `~/.openprx/config.toml` (fallback `~/.openprx/config.toml`).","type":"object","properties":{"a2a":{"description":"Agent-to-Agent compatibility configuration (`[a2a]`).","$ref":"#/$defs/A2aConfig","default":{"agent_id":"prx-default","allowed_peer_issuers":[],"bind":"127.0.0.1:16832","card_jwks_uri":null,"card_signing_key_path":null,"card_ttl_seconds":3600,"discovery_advertised":false,"handoff_nonce_ttl_seconds":3600,"messaging_enabled":false,"peers":{},"spiffe_id":"spiffe://prx-local/agent/prx-default","spiffe_strict_validation":false,"spiffe_trust_bundle_pem":null,"trusted_trust_domains":[],"trust_domain":"prx.local"}},"agent":{"description":"Agent orchestration settings (`[agent]`).","$ref":"#/$defs/AgentConfig","default":{"approval_wait_secs":600,"compact_context":false,"compaction":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096},"low_priority_tools":["sessions_spawn","delegate"],"priority_scheduling_enabled":false,"read_only_tool_concurrency_window":2,"messaging":{"inbound":true}}},"agents":{"description":"Delegate agent configurations for multi-agent workflows.","type":"object","additionalProperties":{"$ref":"#/$defs/DelegateAgentConfig"},"default":{}},"api_key":{"description":"API key for the selected provider. No environment variable sets or\noverrides it; when it is unset, the key stored for the provider with\n`prx auth paste-token --provider ` is used.","type":["string","null"],"default":null},"api_url":{"description":"Base URL override for provider API (e.g. \"http://10.0.0.1:11434\" for remote Ollama)","type":["string","null"],"default":null},"auth":{"description":"Auth profile and external credential import settings (`[auth]`).","$ref":"#/$defs/AuthConfig","default":{"codex_auth_json_auto_import":false,"codex_auth_json_path":"~/.codex/auth.json"}},"autonomy":{"description":"Autonomy and security policy configuration (`[autonomy]`).","$ref":"#/$defs/AutonomyConfig","default":{"forbidden_paths":[],"level":"full","max_cost_per_day_cents":null,"scopes":{"assign_owners":[],"default":"allow","rules":[]}}},"browser":{"description":"Browser automation configuration (`[browser]`).","$ref":"#/$defs/BrowserConfig","default":{"allowed_domains":[],"computer_use":{"api_key":null}}},"channels_config":{"description":"Channel configurations: Telegram, Discord, Slack, etc. (`[channels_config]`).","$ref":"#/$defs/ChannelsConfig","default":{"cli":true,"dingtalk":null,"discord":null,"email":null,"imessage":null,"irc":null,"lark":null,"linq":null,"mattermost":null,"nextcloud_talk":null,"qq":null,"ramflux":null,"signal":null,"slack":null,"telegram":null,"wacli":null,"webhook":null,"whatsapp":null}},"chat":{"description":"Interactive chat UI configuration (`[chat]`).","$ref":"#/$defs/ChatConfig","default":{"daemon":{"token":"","url":""},"max_concurrent_visible_turns":2}},"compliance":{"description":"Operator-owned compliance controls (`[compliance]`).","$ref":"#/$defs/ComplianceConfig","default":{"eu_ai_act":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null},"interaction_notice":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}},"composio":{"description":"Composio managed OAuth tools integration (`[composio]`).","$ref":"#/$defs/ComposioConfig","default":{"api_key":null,"entity_id":"default"}},"cost":{"description":"Cost tracking and budget enforcement configuration (`[cost]`).","$ref":"#/$defs/CostConfig","default":{"allow_override":false,"daily_limit_usd":null,"monthly_limit_usd":null,"prices":{},"warn_at_percent":80}},"cron":{"description":"Cron job configuration (`[cron]`).","$ref":"#/$defs/CronConfig","default":{"max_run_history":50}},"decision_engine":{"description":"Optional advisory decision engine, disabled by default.","$ref":"#/$defs/DecisionEngineConfig","default":{"candidates":5,"enabled":false,"mode":"pre","observe_queue":64,"prompt_budget_tokens":300,"telemetry_cap":1000,"timeout_ms":1500,"latency_budget_ms":500,"max_candidates":12,"token_ratio_limit":0.3499999940395355}},"default_model":{"description":"Default model routed through the selected provider (e.g. `\"anthropic/claude-sonnet-4-6\"`).\n\n`None` when the file omits it; see `default_provider`.","type":["string","null"]},"default_provider":{"description":"Default provider ID or alias (e.g. `\"openrouter\"`, `\"ollama\"`, `\"anthropic\"`).\n\n`None` when the file omits it: the release catalog stays the sole owner\nof the release default, so a save never pins today's catalog value into\nthe operator's file.","type":["string","null"]},"default_temperature":{"description":"Default model temperature (0.0–2.0). Default: `0.7`.","type":"number","format":"double","default":0.7},"embedding_routes":{"description":"Embedding routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/EmbeddingRouteConfig"}},"gateway":{"description":"Gateway server configuration: host, port, pairing, rate limits (`[gateway]`).","$ref":"#/$defs/GatewayConfig","default":{"allow_public_bind":false,"api_rate_limit_per_minute":60,"channel_webhook_dedup_ttl_secs":86400,"host":"127.0.0.1","idempotency_max_keys":10000,"idempotency_ttl_secs":300,"pair_rate_limit_per_minute":10,"paired_tokens":[],"port":16830,"rate_limit_max_keys":10000,"require_pairing":true,"targeted_agents":true,"trust_forwarded_headers":false,"webhook_rate_limit_per_minute":60}},"heartbeat":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]`).","$ref":"#/$defs/HeartbeatConfig","default":{"active_hours":[8,23],"interval_minutes":30,"prompt":"Check HEARTBEAT.md and follow instructions."}},"http_request":{"description":"HTTP request tool configuration (`[http_request]`).","$ref":"#/$defs/HttpRequestConfig","default":{"max_response_size":1000000,"timeout_secs":30}},"identity":{"description":"Identity format configuration: OpenClaw or AIEOS (`[identity]`).","$ref":"#/$defs/IdentityConfig","default":{"aieos_inline":null,"aieos_path":null,"format":"openclaw"}},"identity_bindings":{"description":"Static identity bindings loaded at startup (`[[identity_bindings]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/IdentityBindingConfig"}},"mcp":{"description":"Secrets encryption configuration (`[secrets]`).","$ref":"#/$defs/McpConfig","default":{"servers":{}}},"mcp_server":{"description":"MCP server compatibility configuration (`[mcp_server]`).","$ref":"#/$defs/McpServerRuntimeConfig","default":{"allowed_origins":["claude.ai","openai.com","localhost"],"bind":"127.0.0.1:16831","exposed_tools":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"jwt_algorithms":["RS256"],"jwt_audience":null,"jwt_issuer":null,"jwt_jwks":null,"jwt_jwks_cache_ttl_secs":300,"jwt_jwks_uri":null,"jwt_public_key_pem":null,"rate_limit_rps":10,"require_auth":true}},"media":{"description":"Media understanding configuration (`[media]` section).\nControls audio STT and video frame extraction for incoming attachments.","$ref":"#/$defs/MediaConfig","default":{"audio_model":"whisper","audio_ollama_url":"http://localhost:11434","audio_provider":"none","max_audio_size_mb":20,"max_video_size_mb":50,"video_max_frames":4,"video_provider":"none"}},"memory":{"description":"Memory backend configuration: sqlite, markdown, embeddings (`[memory]`).","$ref":"#/$defs/MemoryConfig","default":{"acl_enabled":false,"archive_after_days":7,"auto_hydrate":true,"auto_save":true,"backend":"sqlite","conversation_retention_days":3,"daily_retention_days":7,"embedding_cache_size":10000,"embedding_dimensions":384,"embedding_model":"prx-local-hash-v1","embedding_provider":"local","events":{"record_assistant_messages":true,"record_tool_events":true,"record_user_messages":true},"keyword_weight":0.3,"legacy_conversation_turns_visible":true,"lucid_budget":null,"lucid_cmd":null,"lucid_failure_cooldown_ms":60000,"lucid_local_hit_threshold":3,"lucid_recall_timeout_ms":5000,"lucid_store_timeout_ms":3000,"min_relevance_score":0.4,"purge_after_days":30,"semantic":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30},"sqlite_open_timeout_secs":null,"sqlite_read_pool_size":null,"vector_candidate_cap":2000,"vector_weight":0.7}},"model_routes":{"description":"Model routing rules — route `hint:` to specific provider+model combos.","type":"array","default":[],"items":{"$ref":"#/$defs/ModelRouteConfig"}},"model_settings":{"description":"Catalog model levels and explicit parameters, keyed by canonical release ID.","type":"object","additionalProperties":{"$ref":"#/$defs/ModelSettings"},"default":{}},"multimodal":{"description":"Multimodal (image) handling configuration (`[multimodal]`).","$ref":"#/$defs/MultimodalConfig","default":{"allow_remote_fetch":true,"max_image_size_mb":5,"max_images":4}},"nodes":{"description":"Remote node proxy configuration (`[nodes]`).","$ref":"#/$defs/NodesConfig","default":{"nodes":[],"request_timeout_ms":15000,"retry_max":2,"server":{"allowed_commands":[],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}},"observability":{"description":"Observability backend configuration (`[observability]`).","$ref":"#/$defs/ObservabilityConfig","default":{"backend":"none","otel_endpoint":null,"otel_service_name":null}},"plugins":{"description":"WASM plugin runtime switch (`[plugins]`), off by default.","$ref":"#/$defs/PluginsConfig","default":{"enabled":false}},"providers":{"description":"Provider-specific runtime options (`[providers.]`).","$ref":"#/$defs/ProvidersConfig","default":{"ollama":{"num_ctx":null}}},"proxy":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]`).","$ref":"#/$defs/ProxyConfig","default":{"all_proxy":null,"http_proxy":null,"https_proxy":null,"no_proxy":[],"scope":"prx","services":[]}},"query_classification":{"description":"Automatic query classification — maps user messages to model hints.","$ref":"#/$defs/QueryClassificationConfig","default":{"rules":[]}},"reliability":{"description":"Reliability settings: retries, fallback providers, backoff (`[reliability]`).","$ref":"#/$defs/ReliabilityConfig","default":{"acknowledge_single_provider_risk":false,"api_keys":[],"channel_initial_backoff_secs":2,"channel_max_backoff_secs":60,"circuit_breaker":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30},"fallback_providers":[],"model_fallbacks":{},"provider_backoff_ms":500,"provider_retries":2,"scheduler_poll_secs":15,"scheduler_retries":2}},"router":{"description":"Heuristic LLM router configuration (`[router]`).","$ref":"#/$defs/RouterConfig","default":{"alpha":0.0,"beta":0.5,"delta":0.10000000149011612,"epsilon":0.10000000149011612,"gamma":0.30000001192092896,"knn_k":7,"knn_min_records":10,"models":[]}},"runtime":{"description":"Runtime adapter configuration (`[runtime]`). Controls native vs Docker execution.","$ref":"#/$defs/RuntimeConfig","default":{"codex_reasoning_effort":null,"codex_stream_idle_timeout_secs":null,"docker":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true},"idle_hang_secs":null,"kind":"native","long_task_warn_secs":null,"managed_cgroup_root":null,"max_blocking_threads":null,"reasoning_enabled":null,"shell_env_allowlist":[],"workdir":null}},"scheduler":{"description":"Scheduler configuration for periodic task execution (`[scheduler]`).","$ref":"#/$defs/SchedulerConfig","default":{"claim_lease_secs":90,"max_tasks":64}},"secrets":{"$ref":"#/$defs/SecretsConfig","default":{"encrypt":true}},"security":{"description":"Security configuration: sandboxing, resource limits, audit, tool policy (`[security]`).","$ref":"#/$defs/SecurityConfig","default":{"audit":{"log_path":"audit.log","max_size_mb":100}}},"self_system":{"description":"Self-system experimental automation controls (`[self_system]`).","$ref":"#/$defs/SelfSystemConfig","default":{"evolution_config_path":null,"evolution_debug_raw":false,"evolution_interval_hours":24,"evolution_judge_timeout_secs":180,"evolution_model_max_micro_usd":0,"evolution_model_max_tokens":16384,"fitness":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"},"fitness_interval_hours":24}},"sessions_spawn":{"description":"Session spawning configuration (`[sessions_spawn]`).","$ref":"#/$defs/SessionsSpawnConfig","default":{"cleanup_on_complete":true,"default_mode":"task","process_memory_strategy":"shared_fabric","worker_workspace_root":null}},"skill_rag":{"description":"Dynamic skill retrieval settings (`[skill_rag]`).","$ref":"#/$defs/SkillRagConfig","default":{"top_k":32}},"skills":{"description":"Skills loading and community repository behavior (`[skills]`).","$ref":"#/$defs/SkillsConfig","default":{"open_skills_dir":null,"openclaw_skills_dir":null}},"skills_lifecycle":{"description":"Skill lifecycle (`[skills_lifecycle]`), off by default.","$ref":"#/$defs/SkillsLifecycleConfig","default":{"allow_executable_proposals":false,"enabled":false,"max_concurrent_evaluations":1,"max_edit_fraction":0.2,"max_edit_tokens":300,"max_proposals_per_cycle":1,"min_cases_floor":3,"mode":"draft_only","owner_scope":null,"require_holdout":true,"storage_dir":"self/skill-lifecycle","suites":[]}},"smart_group":{"description":"Smart group-reply pre-gate configuration (`[smart_group]`).","$ref":"#/$defs/SmartGroupConfig","default":{"classifier_max_context_messages":3,"classifier_model":"","classifier_provider":"","classifier_temperature":0.0,"classifier_timeout_secs":5}},"storage":{"description":"Persistent storage provider configuration (`[storage]`).","$ref":"#/$defs/StorageConfig","default":{"provider":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"task_routing":{"description":"Task routing configuration — classifies work by intent before the main agent loop.","$ref":"#/$defs/TaskRoutingConfig","default":{"default_intent":"simple","rules":[]}},"tool_tiering":{"description":"Tool tiering configuration — controls which tools are exposed based on intent (`[tool_tiering]`).","$ref":"#/$defs/ToolTieringConfig","default":{"always_exclude":[],"always_include":[],"channel_exclude":[],"defer_unlisted":false}},"tunnel":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]`).","$ref":"#/$defs/TunnelConfig","default":{"cloudflare":null,"custom":null,"ngrok":null,"provider":"none","tailscale":null}},"user_policies":{"description":"Static user policy records loaded at startup (`[[user_policies]]`).","type":"array","default":[],"items":{"$ref":"#/$defs/UserPolicyConfig"}},"web_search":{"description":"Web search tool configuration (`[web_search]`).","$ref":"#/$defs/WebSearchConfig","default":{"brave_api_key":null,"fetch_max_chars":50000,"max_results":15,"provider":"duckduckgo","timeout_secs":15}},"webhook":{"description":"Standalone webhook receiver for external event -> topic synchronization (`[webhook]`).","$ref":"#/$defs/MemoryWebhookConfig","default":{"bind":"0.0.0.0:16899","signing_secret":null,"token":null}},"xin":{"description":"Xin autonomous task engine configuration (`[xin]`).","$ref":"#/$defs/XinConfig","default":{"adopt_legacy_tasks":false,"interval_minutes":5,"stale_timeout_minutes":60}}},"$defs":{"A2aConfig":{"type":"object","properties":{"agent_id":{"description":"Stable PRX agent identifier advertised to peers.","type":"string","default":"prx-default"},"allowed_peer_issuers":{"description":"Accepted external peer issuers.","type":"array","default":[],"items":{"type":"string"}},"bind":{"description":"Advertised bind address.","type":"string","default":"127.0.0.1:16832"},"card_jwks_uri":{"description":"Public JWKS URI advertised in the card signature block so peers know where\nto fetch the verification key. Defaults to the local JWKS endpoint.","type":["string","null"],"default":null},"card_signing_key_path":{"description":"On-disk Ed25519 signing key for the published Agent Card (JWS). When set,\nthe `/.well-known/agent.json` card is signed and verifiable via the JWKS\nendpoint. When unset, an ephemeral per-process key is used (card is still\nsigned, but the public key only lives for the lifetime of the process).","type":["string","null"],"default":null},"card_ttl_seconds":{"description":"Validity window of a published Agent Card, in seconds. Reflected in the\ncard's `expires_at` and the response `Cache-Control: max-age`.","type":"integer","format":"uint64","default":3600,"minimum":0},"discovery_advertised":{"description":"Whether to advertise into an external A2A registry.","type":"boolean","default":false},"handoff_nonce_ttl_seconds":{"description":"Replay window for future handoff delegation tokens.","type":"integer","format":"uint64","default":3600,"minimum":0},"messaging_enabled":{"description":"Enable the dedicated pinned mTLS messaging listener.","type":"boolean","default":false},"peers":{"type":"object","additionalProperties":{"$ref":"#/$defs/A2aPeer"},"default":{}},"spiffe_id":{"description":"Local SPIFFE-style identifier placeholder.","type":"string","default":"spiffe://prx-local/agent/prx-default"},"spiffe_strict_validation":{"description":"When true, a peer that presents an X.509 SVID header but fails chain /\nvalidity / trust-domain verification is rejected. When false (default),\nverification failures are logged but fall back to header-asserted trust\n(suitable for a trusted front proxy terminating mTLS).\n\nFor MCP tool calls, SPIFFE headers (and the fall-back) are considered\nonly when `gateway.trust_forwarded_headers` is true; otherwise they are\nignored and the caller must authenticate with a bearer JWT.","type":"boolean","default":false},"spiffe_trust_bundle_pem":{"description":"Trust bundle CA certificate(s) in PEM, used to verify the signature chain\nof a peer-presented X.509 SVID. When unset, SVID chain verification is not\nperformed (only header-asserted issuer allow-listing applies).","type":["string","null"],"default":null},"trusted_trust_domains":{"description":"Trust domains accepted when verifying a peer SPIFFE SVID. Empty means the\n`allowed_peer_issuers` allow-list is the sole gate (backward compatible).","type":"array","default":[],"items":{"type":"string"}},"trust_domain":{"description":"SPIFFE trust domain for new instance identities.","type":"string","default":"prx.local"}}},"A2aPeer":{"description":"Explicit pinned identity and local recipient grant.","type":"object","properties":{"spiffe_id":{"type":"string"},"fingerprints":{"type":"array","items":{"type":"string"}},"address":{"type":"string"},"owner":{"type":"string"},"sessions":{"type":"array","default":["*"],"items":{"type":"string"}},"agents":{"type":"array","default":["*"],"items":{"type":"string"}}},"required":["spiffe_id","fingerprints","address","owner"],"additionalProperties":false},"AgentCompactionConfig":{"description":"Agent context compaction configuration (`[agent.compaction]`).","type":"object","properties":{"keep_recent_messages":{"description":"Number of recent non-system messages to keep after compaction.","type":"integer","format":"uint","default":12,"minimum":0},"max_context_tokens":{"description":"Total model context window in tokens. This uses the same unit as\n`RouterModelConfig.max_context`; runtime trigger thresholds subtract\n`reserve_tokens` from this total window.","type":"integer","format":"uint","default":128000,"minimum":0},"memory_flush":{"description":"Run memory flush extraction before legacy summary/truncation modes.\nExact `switch` handoffs never invoke a summarizer.","type":"boolean","default":true},"mode":{"description":"Context rollover strategy (`off`, `switch`, `safeguard`, `aggressive`).","$ref":"#/$defs/AgentCompactionMode","default":"switch"},"os_paging":{"description":"Letta/MemGPT-style OS-paging controls (`[agent.compaction.os_paging]`).\n\nEnabled by default (Phase 1). When enabled, oldest messages are evicted\nto the durable document store (non-destructively, preserving full\ncontent) and semantically recalled on later turns, instead of being\ncollapsed into a lossy summary.","$ref":"#/$defs/OsPagingConfig","default":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"}},"reserve_tokens":{"description":"Tokens reserved for the next model response.","type":"integer","format":"uint","default":4096,"minimum":0}}},"AgentCompactionMode":{"description":"Compaction mode for long conversation contexts.","oneOf":[{"description":"Disable proactive compaction.","type":"string","const":"off"},{"description":"Replace cold context with an exact transcript reference and keep the\ndurable transcript unchanged.","type":"string","const":"switch"},{"description":"Conservative compaction that prefers summary replacement.","type":"string","const":"safeguard"},{"description":"Aggressive truncation mode for tighter contexts.","type":"string","const":"aggressive"}]},"AgentConfig":{"description":"Agent orchestration configuration (`[agent]` section).","type":"object","properties":{"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"compact_context":{"description":"When true: bootstrap_max_chars=6000. Use for 13B or smaller models.","type":"boolean","default":false},"compaction":{"description":"Context compaction controls (`[agent.compaction]`).","$ref":"#/$defs/AgentCompactionConfig","default":{"keep_recent_messages":12,"max_context_tokens":128000,"memory_flush":true,"mode":"switch","os_paging":{"eviction_threshold":0.7,"keep_recent_messages":12,"max_recalled_pages":10,"proactive_retrieval":true,"retrieval_injection_role":"system"},"reserve_tokens":4096}},"low_priority_tools":{"description":"Tool names treated as low-priority when `priority_scheduling_enabled = true`.","type":"array","default":["sessions_spawn","delegate"],"items":{"type":"string"}},"priority_scheduling_enabled":{"description":"Enables priority scheduling so foreground tool calls run before background batches.\nDefaults to false to preserve existing scheduler behavior.","type":"boolean","default":false},"read_only_tool_concurrency_window":{"description":"Max concurrent read-only tool calls in an iteration batch.\nDefaults to 2 to preserve existing scheduler behavior.","type":"integer","format":"uint","default":2,"minimum":0},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}}},"AgentLimits":{"description":"Optional admission limits for rf-started turns of a named agent.","type":"object","properties":{"max_concurrent_turns":{"type":["integer","null"],"format":"uint32","minimum":0},"max_cost_per_day_cents":{"type":["integer","null"],"format":"uint64","minimum":0}},"additionalProperties":false},"AuditConfig":{"description":"Audit logging configuration","type":"object","properties":{"log_path":{"description":"Path to the audit log file, relative to the workspace directory and\nkept inside it: a path that could leave it, or a symlink at the file\nor its `.lock`, skips audit records with an error (D-055).","type":"string","default":"audit.log"},"max_size_mb":{"description":"Maximum log size in MB before rotation (at least 1: a size of 0 would\nrotate on every record and keep only the last few, so it is refused\nat load).","type":"integer","format":"uint32","default":100,"minimum":0}}},"AuthConfig":{"description":"Authentication and external credential import configuration (`[auth]` section).","type":"object","properties":{"codex_auth_json_auto_import":{"description":"Automatically import `openai-codex` OAuth credentials from Codex CLI auth.json.\nOff unless the operator opts in. Imported Codex CLI tokens are not refreshed\nwith Codex's client id; run `prx auth login --provider openai-codex`.","type":"boolean","default":false},"codex_auth_json_path":{"description":"Source path for Codex CLI auth.json import.","type":"string","default":"~/.codex/auth.json"}}},"AutonomyConfig":{"type":"object","properties":{"acknowledge_unrestricted_profile":{"description":"Operator acknowledgement for an intentionally unrestricted profile.\nRetained for existing configs; it no longer changes any output or policy behavior.","type":"boolean","default":false},"forbidden_paths":{"description":"Explicit path denylist. Default: empty.\n\nApplies below level `full` only; list paths when running `supervised` or `readonly`.","type":"array","default":[],"items":{"type":"string"}},"level":{"description":"Autonomy level: `readonly` (alias `read_only`), `supervised`, or `full` (default).","$ref":"#/$defs/AutonomyLevel","default":"full"},"max_cost_per_day_cents":{"description":"Maximum cost per day in cents per policy. Default: unset (no ceiling).","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"scopes":{"description":"Scope-based tool access control: per-user/channel/chat-type allow/deny rules.","$ref":"#/$defs/ScopeConfig","default":{"assign_owners":[],"default":"allow","rules":[]}},"workspace_only":{"description":"Restrict file writes and command paths to the workspace directory. Default: `false`.\n\nApplies below level `full` only; set it when running `supervised` or `readonly`.","type":"boolean","default":false}}},"AutonomyLevel":{"description":"How much autonomy the agent has","oneOf":[{"description":"Read-only: can observe but not act","type":"string","const":"readonly"},{"description":"Supervised: acts but requires approval for risky operations","type":"string","const":"supervised"},{"description":"Full: autonomous execution within policy bounds","type":"string","const":"full"}]},"BackendSelection":{"description":"Which decision backend runs: `auto` (the factory's order) or one kind.","type":"string"},"BrowserComputerUseConfig":{"description":"Computer-use sidecar configuration (`[browser.computer_use]` section).\n\nThe computer-use / agent-browser automation tools were removed (agents use\n`shell` instead). Only `api_key` is retained, because the config secret\nencryption/migration path still references it.","type":"object","properties":{"api_key":{"description":"Optional bearer token (retained only for config secret handling).","type":["string","null"],"default":null}}},"BrowserConfig":{"description":"Browser configuration (`[browser]` section).\n\nThe `browser` / `browser_open` automation tools were removed. This section\nnow only carries `allowed_domains`, consumed by the `web_fetch` tool for\ndomain validation; `computer_use.api_key` is kept for config secret handling.","type":"object","properties":{"allowed_domains":{"description":"Allowed domains for `web_fetch` (exact or subdomain match).","type":"array","default":[],"items":{"type":"string"}},"computer_use":{"description":"Computer-use sidecar config (retained only for `api_key` secret handling).","$ref":"#/$defs/BrowserComputerUseConfig","default":{"api_key":null}}}},"ChannelsConfig":{"description":"Top-level channel configurations (`[channels_config]` section).\n\nEach channel sub-section (e.g. `telegram`, `discord`) is optional;\nsetting it to `Some(...)` enables that channel.","type":"object","properties":{"cli":{"description":"Enable the CLI interactive channel. Default: `true`.","type":"boolean","default":true},"dingtalk":{"description":"DingTalk channel configuration.","anyOf":[{"$ref":"#/$defs/DingTalkConfig"},{"type":"null"}]},"discord":{"description":"Discord bot channel configuration.","anyOf":[{"$ref":"#/$defs/DiscordConfig"},{"type":"null"}]},"email":{"description":"Email channel configuration.","anyOf":[{"$ref":"#/$defs/EmailConfig"},{"type":"null"}]},"imessage":{"description":"iMessage channel configuration (macOS only).","anyOf":[{"$ref":"#/$defs/IMessageConfig"},{"type":"null"}]},"irc":{"description":"IRC channel configuration.","anyOf":[{"$ref":"#/$defs/IrcConfig"},{"type":"null"}]},"lark":{"description":"Lark/Feishu channel configuration.","anyOf":[{"$ref":"#/$defs/LarkConfig"},{"type":"null"}]},"linq":{"description":"Linq Partner API channel configuration.","anyOf":[{"$ref":"#/$defs/LinqConfig"},{"type":"null"}]},"mattermost":{"description":"Mattermost bot channel configuration.","anyOf":[{"$ref":"#/$defs/MattermostConfig"},{"type":"null"}]},"nextcloud_talk":{"description":"Nextcloud Talk bot channel configuration.","anyOf":[{"$ref":"#/$defs/NextcloudTalkConfig"},{"type":"null"}]},"qq":{"description":"QQ Official Bot channel configuration.","anyOf":[{"$ref":"#/$defs/QQConfig"},{"type":"null"}]},"ramflux":{"description":"Local ramflux agent-host bridge.","anyOf":[{"$ref":"#/$defs/RamfluxConfig"},{"type":"null"}],"default":null},"signal":{"description":"Signal channel configuration.","anyOf":[{"$ref":"#/$defs/SignalConfig"},{"type":"null"}]},"slack":{"description":"Slack bot channel configuration.","anyOf":[{"$ref":"#/$defs/SlackConfig"},{"type":"null"}]},"telegram":{"description":"Telegram bot channel configuration.","anyOf":[{"$ref":"#/$defs/TelegramConfig"},{"type":"null"}]},"wacli":{"description":"wacli JSON-RPC daemon channel configuration.","anyOf":[{"$ref":"#/$defs/WacliConfig"},{"type":"null"}],"default":null},"webhook":{"description":"Webhook channel configuration.","anyOf":[{"$ref":"#/$defs/WebhookConfig"},{"type":"null"}]},"whatsapp":{"description":"WhatsApp channel configuration (Cloud API or Web mode).","anyOf":[{"$ref":"#/$defs/WhatsAppConfig"},{"type":"null"}]}}},"ChatConfig":{"description":"Interactive chat configuration (`[chat]`).","type":"object","properties":{"daemon":{"description":"How this chat process reaches the daemon it borrows channels from.","$ref":"#/$defs/ChatDaemonConfig","default":{"token":"","url":""}},"max_concurrent_visible_turns":{"description":"Maximum concurrent visible provider turns in the TUI Redux driver.","type":"integer","format":"uint","default":2,"minimum":0}}},"ChatDaemonConfig":{"description":"Where `prx chat` sends its outbound messages (`[chat.daemon]`).\n\nA chat session opens no IM connection of its own — that would race the\ndaemon for inbound messages on the same account — so `message_send` in chat\nasks the daemon to deliver. That is an ordinary authenticated call to the\ndaemon's control plane, so it needs the same address and token `prx tasks`\nuses.","type":"object","properties":{"token":{"description":"Bearer token for the daemon control plane. Empty sends no credential,\nwhich only works when the daemon runs with `gateway.require_pairing =\nfalse`; otherwise the daemon answers 401 and the send is refused.","type":"string","default":""},"url":{"description":"Base URL of the daemon gateway. Empty (the default) derives it from\n`[gateway] host`/`port`, which is right whenever both run on this host.","type":"string","default":""}}},"CircuitBreakerConfig":{"description":"The per-backend circuit breaker.","type":"object","properties":{"cooldown_secs":{"description":"Seconds the breaker stays open (1 to 3600).","type":"integer","format":"uint32","default":60,"minimum":0},"failure_threshold":{"description":"Consecutive failures before the breaker opens (1 to 100).","type":"integer","format":"uint32","default":5,"minimum":0}}},"ClassificationRule":{"description":"A single classification rule mapping message patterns to a model hint.","type":"object","properties":{"hint":{"description":"Must match a `[[model_routes]]` hint value.","type":"string"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"max_length":{"description":"Only match if message length <= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"min_length":{"description":"Only match if message length >= N chars.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"patterns":{"description":"Case-sensitive literal matches (for \"```\", \"fn \", etc.).","type":"array","default":[],"items":{"type":"string"}},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0}},"required":["hint"]},"CloudflareTunnelConfig":{"type":"object","properties":{"token":{"description":"Cloudflare Tunnel token (from Zero Trust dashboard)","type":"string"}},"required":["token"]},"ComplianceConfig":{"type":"object","properties":{"eu_ai_act":{"$ref":"#/$defs/EuAiActComplianceConfig","default":{"classification":{"assessed_at":null,"owner":null,"status":"unclassified"},"declaration":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null},"incident_store_path":null}},"interaction_notice":{"$ref":"#/$defs/InteractionNoticeConfig","default":{"applicability":"required","exception_owner":null,"exception_reviewed_at":null,"text":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers.","version":"1"}}}},"ComposioConfig":{"description":"Composio managed OAuth tools integration (`[composio]` section).\n\nProvides access to 1000+ OAuth-connected tools via the Composio platform.","type":"object","properties":{"api_key":{"description":"Composio API key (stored encrypted when secrets.encrypt = true)","type":["string","null"],"default":null},"entity_id":{"description":"Default entity ID for multi-user setups","type":"string","default":"default"}}},"CostConfig":{"description":"Cost tracking and budget enforcement configuration (`[cost]` section).","type":"object","properties":{"allow_override":{"description":"Allow requests to exceed budget with --override flag (default: false)","type":"boolean","default":false},"daily_limit_usd":{"description":"Daily spending limit in USD (default: unset, no limit; 0 refuses every priced turn)","type":["number","null"],"format":"double","default":null},"monthly_limit_usd":{"description":"Monthly spending limit in USD (default: unset, no limit)","type":["number","null"],"format":"double","default":null},"prices":{"description":"Per-model pricing (USD per 1M tokens)","type":"object","additionalProperties":{"$ref":"#/$defs/ModelPricing"},"default":{}},"warn_at_percent":{"description":"Warn when spending reaches this percentage of a configured limit (default: 80)","type":"integer","format":"uint8","default":80,"maximum":255,"minimum":0}}},"CredentialRefSetting":{"description":"Which credential a decision backend uses. A reference, never a secret.","type":"string"},"CronConfig":{"description":"Cron job configuration (`[cron]` section).","type":"object","properties":{"max_run_history":{"description":"Maximum number of historical cron run records to retain. Default: `50`.","type":"integer","format":"uint32","default":50,"minimum":0}}},"CustomTunnelConfig":{"type":"object","properties":{"health_url":{"description":"Optional URL to check tunnel health","type":["string","null"]},"start_command":{"description":"Command template to start the tunnel. Use {port} and {host} placeholders.\nExample: \"bore local {port} --to bore.pub\"","type":"string"},"url_pattern":{"description":"Optional regex to extract public URL from command stdout","type":["string","null"]}},"required":["start_command"]},"DecisionBackendConfig":{"description":"The decision backend (`[decision_engine.backend]`).","type":"object","properties":{"circuit_breaker":{"description":"The circuit breaker.","$ref":"#/$defs/CircuitBreakerConfig","default":{"cooldown_secs":60,"failure_threshold":5}},"credential_ref":{"description":"The credential reference: `\"\"`, `\"none\"` or `cred-`.","$ref":"#/$defs/CredentialRefSetting","default":""},"endpoint":{"description":"The System One endpoint (`compatible_http`, required), or the base\nURL that replaces a hosted service's (optional, COORD-6: a hosted\nbackend stays remote whatever the URL). https, or http on a literal\nloopback address; never user information.","type":"string","default":""},"kind":{"description":"`auto`, `builtin`, `compatible_http`, or a hosted service:\n`typesafe` or `openrouter` (CDP-13).","$ref":"#/$defs/BackendSelection","default":"auto"},"max_request_bytes":{"description":"Largest request body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":65536,"minimum":0},"max_response_bytes":{"description":"Largest response body (4 KiB to 1 MiB).","type":"integer","format":"uint32","default":262144,"minimum":0},"model":{"description":"The model the endpoint serves; one exact version for a hosted\nservice.","type":"string","default":""},"pinned_snapshot":{"description":"The exact model snapshot a hosted service must answer with (D-043\nC-8). OpenRouter requires the exact dated snapshot returned for the\nconfigured model; for TypeSafe it defaults to `model`. Refused for the\nother kinds.","type":"string"},"remote_enabled":{"description":"Whether decision state may leave this machine. Default `false`.","type":"boolean","default":false},"timeout_ms":{"description":"Transport timeout (10 ms up to the extra latency budget).","type":"integer","format":"uint32","default":250,"minimum":0}}},"DecisionEngineConfig":{"type":"object","properties":{"backend":{"anyOf":[{"$ref":"#/$defs/DecisionBackendConfig"},{"type":"null"}]},"candidates":{"type":"integer","format":"uint32","default":5,"minimum":0},"enabled":{"type":"boolean","default":false},"mode":{"$ref":"#/$defs/DecisionMode","default":"pre"},"observe_queue":{"type":"integer","format":"uint32","default":64,"minimum":0},"prompt_budget_tokens":{"type":"integer","format":"uint32","default":300,"minimum":0},"telemetry_cap":{"type":"integer","format":"uint32","default":1000,"minimum":0},"timeout_ms":{"type":"integer","format":"uint32","default":1500,"minimum":0},"latency_budget_ms":{"description":"The extra latency one turn may spend deciding (50 to 5000 ms); also the\nbackend transport timeout ceiling while the engine is disabled.","type":"integer","format":"uint64","default":500,"minimum":0},"token_ratio_limit":{"description":"Maximum ratio of extra tokens to the turn's baseline tokens (a finite\nnumber greater than 0).","type":"number","format":"float","default":0.3499999940395355},"max_candidates":{"description":"The most candidates a turn considers (1 to 32).","type":"integer","format":"uint8","default":12,"maximum":255,"minimum":0}}},"DecisionMode":{"type":"string","enum":["pre","post","both"]},"DeclarationOfConformityConfig":{"type":"object","properties":{"applicable_union_law":{"type":"array","default":[],"items":{"type":"string"}},"artifact_path":{"type":["string","null"],"default":null},"artifact_version":{"type":["string","null"],"default":null},"conformity_assessment_procedure":{"type":["string","null"],"default":null},"conformity_statement":{"type":["string","null"],"default":null},"harmonised_standards":{"type":"array","default":[],"items":{"type":"string"}},"issue_date":{"type":["string","null"],"default":null},"issue_place":{"type":["string","null"],"default":null},"notified_body_certificate":{"type":["string","null"],"default":null},"notified_body_identification_number":{"type":["string","null"],"default":null},"notified_body_name":{"type":["string","null"],"default":null},"personal_data_compliance_statement":{"type":["string","null"],"default":null},"processes_personal_data":{"type":"boolean","default":false},"provider_address":{"type":["string","null"],"default":null},"provider_name":{"type":["string","null"],"default":null},"signer_function":{"type":["string","null"],"default":null},"signer_name":{"type":["string","null"],"default":null},"signer_on_behalf_of":{"type":["string","null"],"default":null},"sole_responsibility_statement":{"type":["string","null"],"default":null},"standards_not_applicable_reason":{"type":["string","null"],"default":null},"system_name":{"type":["string","null"],"default":null},"system_reference":{"type":["string","null"],"default":null},"system_type":{"type":["string","null"],"default":null}}},"DelegateAgentConfig":{"description":"Configuration for a delegate sub-agent used by the `delegate` tool.","type":"object","properties":{"agentic":{"description":"Agentic sub-agent mode (multi-turn tool-call loop). Default true; an\nexplicit `false` makes the agent answer-only with no tools.","type":"boolean","default":true},"allowed_tools":{"description":"Allowlist of tool names available to the sub-agent in agentic mode.\nEmpty or omitted means all tools, the same as `[\"*\"]`.","type":"array","default":[],"items":{"type":"string"}},"api_key":{"description":"Optional API key override","type":["string","null"],"default":null},"approval_wait_secs":{"description":"rf approve-and-continue wait; Console approvals retain their own expiry.","type":"integer","format":"uint64","default":600,"maximum":86400,"minimum":1},"autonomy":{"description":"The agent's own autonomy level for targeted turns. Unset inherits the\nmain agent's level.","anyOf":[{"$ref":"#/$defs/AutonomyLevel"},{"type":"null"}]},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this agent's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"enabled":{"description":"Whether this agent can be targeted by `POST /api/sessions/{id}/message`\n(default: true). A disabled agent answers 409 `agent_disabled`.","type":"boolean","default":true},"identity_dir":{"description":"Optional identity files directory relative to workspace root.","type":["string","null"],"default":null},"limits":{"$ref":"#/$defs/AgentLimits","default":{"max_concurrent_turns":null,"max_cost_per_day_cents":null}},"max_depth":{"description":"Max recursion depth for nested delegation","type":"integer","format":"uint32","default":8,"minimum":0},"memory_scope":{"description":"Optional memory scope for spawned sessions: \"shared\" (default) or \"isolated\".","type":["string","null"],"default":null},"model":{"description":"Model name","type":"string"},"provider":{"description":"Provider name (e.g. \"ollama\", \"openrouter\", \"anthropic\")","type":"string"},"spawn_enabled":{"description":"Whether this agent is allowed to be targeted by sessions_spawn (default: true).","type":["boolean","null"],"default":null},"system_prompt":{"description":"Optional system prompt for the sub-agent","type":["string","null"],"default":null},"temperature":{"description":"Temperature override","type":["number","null"],"format":"double","default":null},"messaging":{"$ref":"#/$defs/AgentMessaging","default":{"inbound":true}}},"required":["provider","model"]},"DingTalkConfig":{"description":"DingTalk configuration for Stream Mode messaging","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs (staff IDs). Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"client_id":{"description":"Client ID (AppKey) from DingTalk developer console","type":"string"},"client_secret":{"description":"Client Secret (AppSecret) from DingTalk developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["client_id","client_secret"]},"DiscordConfig":{"description":"Discord bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Discord user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Discord bot token (from Discord Developer Portal).","type":"string"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in guild channels.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"guild_id":{"description":"Optional guild (server) ID to restrict the bot to a single guild.","type":["string","null"]},"listen_to_bots":{"description":"When true, process messages from other bots (not just humans).\nThe bot still ignores its own messages to prevent feedback loops.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the guild are silently ignored.","type":"boolean","default":false}},"required":["bot_token"]},"DmPolicy":{"description":"Policy for direct-message handling.","oneOf":[{"description":"Future pairing handshake flow (placeholder; runtime currently falls back to allowlist).","type":"string","const":"pairing"},{"description":"Accept only senders listed in `allowed_from`.","type":"string","const":"allowlist"},{"description":"Accept any direct sender.","type":"string","const":"open"},{"description":"Ignore direct messages.","type":"string","const":"disabled"}]},"DockerRuntimeConfig":{"description":"Docker runtime configuration (`[runtime.docker]` section).","type":"object","properties":{"allowed_workspace_roots":{"description":"Optional workspace root allowlist for Docker mount validation.","type":"array","default":[],"items":{"type":"string"}},"cpu_limit":{"description":"Optional CPU limit (`None` = no explicit limit).","type":["number","null"],"format":"double","default":1.0},"image":{"description":"Runtime image used to execute shell commands.","type":"string","default":"alpine:3.20"},"memory_limit_mb":{"description":"Optional memory limit in MB (`None` = no explicit limit).","type":["integer","null"],"format":"uint64","default":512,"minimum":0},"mount_workspace":{"description":"Mount configured workspace into `/workspace`.","type":"boolean","default":true},"network":{"description":"Docker network mode (`none`, `bridge`, etc.).","type":"string","default":"none"},"read_only_rootfs":{"description":"Mount root filesystem as read-only.","type":"boolean","default":true}}},"EmailConfig":{"description":"Email channel configuration","type":"object","properties":{"allowed_senders":{"description":"Allowed sender addresses/domains (empty = deny all, [\"*\"] = allow all)","type":"array","default":[],"items":{"type":"string"}},"from_address":{"description":"From address for outgoing emails","type":"string"},"idle_timeout_secs":{"description":"IDLE timeout in seconds before re-establishing connection (default: 1740 = 29 minutes)\nRFC 2177 recommends clients restart IDLE every 29 minutes","type":"integer","format":"uint64","default":1740,"minimum":0},"imap_folder":{"description":"IMAP folder to poll (default: INBOX)","type":"string","default":"INBOX"},"imap_host":{"description":"IMAP server hostname","type":"string"},"imap_port":{"description":"IMAP server port (default: 993 for TLS)","type":"integer","format":"uint16","default":993,"maximum":65535,"minimum":0},"password":{"description":"Email password for authentication","type":"string"},"smtp_host":{"description":"SMTP server hostname","type":"string"},"smtp_port":{"description":"SMTP server port (default: 465 for TLS)","type":"integer","format":"uint16","default":465,"maximum":65535,"minimum":0},"smtp_tls":{"description":"Use TLS for SMTP (default: true)","type":"boolean","default":true},"username":{"description":"Email username for authentication","type":"string"}},"required":["imap_host","smtp_host","username","password","from_address"]},"EmbeddingRouteConfig":{"description":"Route an embedding hint to a specific provider + model.\n\n```toml\n[[embedding_routes]]\nhint = \"semantic\"\nprovider = \"openai\"\nmodel = \"text-embedding-3-small\"\ndimensions = 1536\n\n[memory]\nembedding_model = \"hint:semantic\"\n```","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this embedding route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"dimensions":{"description":"Optional embedding dimension override for this route","type":["integer","null"],"format":"uint","default":null,"minimum":0},"hint":{"description":"Route hint name (e.g. \"semantic\", \"archive\", \"faq\")","type":"string"},"model":{"description":"Embedding model to use with that provider","type":"string"},"provider":{"description":"Embedding provider (`none`, `openai`, or `custom:`)","type":"string"}},"required":["hint","provider","model"]},"EuAiActClassificationConfig":{"type":"object","properties":{"assessed_at":{"type":["string","null"],"default":null},"owner":{"type":["string","null"],"default":null},"status":{"$ref":"#/$defs/EuAiActRiskClassification","default":"unclassified"}}},"EuAiActComplianceConfig":{"type":"object","properties":{"classification":{"$ref":"#/$defs/EuAiActClassificationConfig","default":{"assessed_at":null,"owner":null,"status":"unclassified"}},"declaration":{"$ref":"#/$defs/DeclarationOfConformityConfig","default":{"applicable_union_law":[],"artifact_path":null,"artifact_version":null,"conformity_assessment_procedure":null,"conformity_statement":null,"harmonised_standards":[],"issue_date":null,"issue_place":null,"notified_body_certificate":null,"notified_body_identification_number":null,"notified_body_name":null,"personal_data_compliance_statement":null,"processes_personal_data":false,"provider_address":null,"provider_name":null,"signer_function":null,"signer_name":null,"signer_on_behalf_of":null,"sole_responsibility_statement":null,"standards_not_applicable_reason":null,"system_name":null,"system_reference":null,"system_type":null}},"incident_store_path":{"type":["string","null"],"default":null}}},"EuAiActRiskClassification":{"type":"string","enum":["unclassified","high_risk","not_high_risk"]},"FitnessConfig":{"description":"Calendar schedule, evidence thresholds, and retention for fitness v2.","type":"object","properties":{"auto_run":{"description":"Run the daily fitness worker in daemon mode.","type":"boolean","default":true},"max_backfill_days":{"description":"Maximum number of closed days recovered after downtime.","type":"integer","format":"uint32","default":7,"minimum":0},"min_coverage":{"description":"Minimum available metric weight required to publish a final score.","type":"number","format":"double","default":0.6},"min_samples":{"description":"Minimum samples required before an evidence-derived subscore is usable.","type":"integer","format":"uint","default":5,"minimum":0},"retention_days":{"description":"Number of daily JSON reports retained on disk.","type":"integer","format":"uint32","default":180,"minimum":0},"run_at":{"description":"Local wall-clock time (`HH:MM`) at which the previous day is scored.","type":"string","default":"00:10"},"timezone":{"description":"IANA timezone used to define closed calendar days.","type":"string","default":"UTC"}}},"GatewayConfig":{"description":"Gateway server configuration (`[gateway]` section).\n\nControls the HTTP gateway for webhook and pairing endpoints.","type":"object","properties":{"allow_public_bind":{"description":"Allow binding to non-localhost without a tunnel (default: false)","type":"boolean","default":false},"api_rate_limit_per_minute":{"description":"Max `/api/*` requests per minute per authenticated token.","type":"integer","format":"uint32","default":60,"minimum":0},"channel_webhook_dedup_ttl_secs":{"description":"How long an already-accepted platform webhook delivery (`/whatsapp`,\n`/linq`, `/nextcloud-talk`) is remembered so a platform redelivery of the\nsame payload is answered instead of re-run.\n\nSized against the sender, not the agent: Meta retries a WhatsApp delivery\nfor up to 7 days and Linq for ~25 minutes, so a window shorter than the\nplatform's retry schedule lets a late retry start the turn a second time.","type":"integer","format":"uint64","default":86400,"minimum":0},"host":{"description":"Gateway host (default: 127.0.0.1)","type":"string","default":"127.0.0.1"},"idempotency_max_keys":{"description":"Maximum distinct idempotency keys retained in memory.","type":"integer","format":"uint","default":10000,"minimum":0},"idempotency_ttl_secs":{"description":"TTL for webhook idempotency keys.","type":"integer","format":"uint64","default":300,"minimum":0},"pair_rate_limit_per_minute":{"description":"Max `/pair` requests per minute per client key.","type":"integer","format":"uint32","default":10,"minimum":0},"paired_tokens":{"description":"Paired bearer tokens (managed automatically, not user-edited)","type":"array","default":[],"items":{"type":"string"}},"port":{"description":"Gateway port (default: 16830)","type":"integer","format":"uint16","default":16830,"maximum":65535,"minimum":0},"rate_limit_max_keys":{"description":"Maximum distinct client keys tracked by gateway rate limiter maps.","type":"integer","format":"uint","default":10000,"minimum":0},"require_pairing":{"description":"Require pairing before accepting requests (default: true)","type":"boolean","default":true},"targeted_agents":{"description":"Switch for targeted agent turns (`agent` on\n`POST /api/sessions/{id}/message`). Default true. While false, any\notherwise-valid named target answers 409 `agent_disabled` and never\nruns as Main.","type":"boolean","default":true},"trust_forwarded_headers":{"description":"Trust headers that a reverse proxy in front of the gateway asserts: the\nclient IP (`X-Forwarded-For`, `X-Real-IP`) for rate limiting, and the\ncaller identity of MCP tool calls (`X-Client-Cert-Subject`,\n`X-Forwarded-Client-Cert`, `X-Spiffe-Id`, `X-Spiffe-Svid`,\n`X-Client-Cert-Pem`). Disabled by default. Enable only when every request\nreaches the gateway through a proxy that removes or overwrites all of\nthese headers; otherwise any client can claim any identity.","type":"boolean","default":false},"webhook_rate_limit_per_minute":{"description":"Max `/webhook` requests per minute per client key.","type":"integer","format":"uint32","default":60,"minimum":0}}},"GroupPolicy":{"description":"Policy for group-message handling.","oneOf":[{"description":"Accept only groups listed in `group_allow_from`.","type":"string","const":"allowlist"},{"description":"Accept any group.","type":"string","const":"open"},{"description":"Ignore group messages.","type":"string","const":"disabled"}]},"GroupReplyMode":{"description":"How the bot decides whether to reply in a group/guild conversation.\n\nThis is orthogonal to [`GroupPolicy`] (which decides *which* groups are\nvisible at all): `GroupReplyMode` decides, within a visible group, *whether\nto speak*. It refines the legacy per-channel `mention_only` boolean.\n\nBackward compatibility: per-channel config carries\n`group_reply_mode: Option`. When `None`, the mode is derived\nfrom the existing `mention_only` flag (`true => MentionOnly`,\n`false => Off`), so existing configs behave exactly as before.","oneOf":[{"description":"Never reply to group messages unless explicitly @-mentioned at the\nchannel layer (equivalent to the legacy `mention_only = false` behavior:\nnon-@ group messages are dropped at the channel layer as today).","type":"string","const":"off"},{"description":"Reply only when the bot is @-mentioned (legacy `mention_only = true`).","type":"string","const":"mention-only"},{"description":"Read every group message and let the model decide whether to reply or\nstay silent (via the `stay_silent` tool). Only honored for channels that\nsupport smart group-reply (currently Telegram, Discord, and WhatsApp).","type":"string","const":"smart"}]},"HeartbeatConfig":{"description":"Heartbeat configuration for periodic health pings (`[heartbeat]` section).","type":"object","properties":{"active_hours":{"description":"Inclusive active hour window `[start_hour, end_hour]` in local time.\nHeartbeat ticks outside this range are skipped.","type":"array","default":[8,23],"items":{"type":"integer","format":"uint8","maximum":255,"minimum":0}},"interval_minutes":{"description":"Interval in minutes between heartbeat pings. Default: `30`.","type":"integer","format":"uint32","default":30,"minimum":0},"prompt":{"description":"Prompt used by heartbeat worker when dispatching tasks.","type":"string","default":"Check HEARTBEAT.md and follow instructions."}}},"HttpRequestConfig":{"description":"HTTP request tool configuration (`[http_request]` section).","type":"object","properties":{"max_response_size":{"description":"Maximum response size in bytes (default: 1MB)","type":"integer","format":"uint","default":1000000,"minimum":0},"timeout_secs":{"description":"Request timeout in seconds (default: 30)","type":"integer","format":"uint64","default":30,"minimum":0}}},"IMessageConfig":{"description":"iMessage channel configuration (macOS only).","type":"object","properties":{"allowed_contacts":{"description":"Allowed iMessage contacts (phone numbers or email addresses). Empty = deny all.","type":"array","items":{"type":"string"}},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["allowed_contacts"]},"IdentityBindingConfig":{"description":"Startup identity binding entry (`[[identity_bindings]]`).","type":"object","properties":{"channel":{"type":"string"},"channel_account":{"type":"string"},"display_name":{"type":["string","null"],"default":null},"user_id":{"type":"string"}},"required":["user_id","channel","channel_account"]},"IdentityConfig":{"description":"Identity format configuration (`[identity]` section).\n\nSupports `\"openclaw\"` (default) or `\"aieos\"` identity documents.","type":"object","properties":{"aieos_inline":{"description":"Inline AIEOS JSON (alternative to file path)","type":["string","null"],"default":null},"aieos_path":{"description":"Path to AIEOS JSON file (relative to workspace)","type":["string","null"],"default":null},"format":{"description":"Identity format: \"openclaw\" (default) or \"aieos\"","type":"string","default":"openclaw"}}},"InteractionNoticeApplicability":{"type":"string","enum":["required","not_applicable"]},"InteractionNoticeConfig":{"type":"object","properties":{"applicability":{"$ref":"#/$defs/InteractionNoticeApplicability","default":"required"},"exception_owner":{"type":["string","null"],"default":null},"exception_reviewed_at":{"type":["string","null"],"default":null},"text":{"type":"string","default":"You are interacting with PRX, an AI system. Its responses may be generated by third-party model providers."},"version":{"type":"string","default":"1"}}},"IrcConfig":{"description":"IRC channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed nicknames (case-insensitive) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"channels":{"description":"Channels to join on connect","type":"array","default":[],"items":{"type":"string"}},"mention_only":{"description":"When true, only process channel/group messages that mention the bot.","type":"boolean","default":false},"nickname":{"description":"Bot nickname","type":"string"},"nickserv_password":{"description":"NickServ IDENTIFY password","type":["string","null"]},"port":{"description":"IRC server port (default: 6697 for TLS)","type":"integer","format":"uint16","default":6697,"maximum":65535,"minimum":0},"sasl_password":{"description":"SASL PLAIN password (IRCv3)","type":["string","null"]},"server":{"description":"IRC server hostname","type":"string"},"server_password":{"description":"Server password (for bouncers like ZNC)","type":["string","null"]},"username":{"description":"Username (defaults to nickname if not set)","type":["string","null"]},"verify_tls":{"description":"Verify TLS certificate (default: true)","type":["boolean","null"]}},"required":["server","nickname"]},"LarkConfig":{"description":"Lark/Feishu configuration for messaging integration.\nLark is the international version; Feishu is the Chinese version.","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs or union IDs (empty = deny all, \"*\" = allow all)","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from Lark/Feishu developer console","type":"string"},"app_secret":{"description":"App Secret from Lark/Feishu developer console","type":"string"},"encrypt_key":{"description":"Encrypt key for webhook message decryption (optional)","type":["string","null"],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"port":{"description":"HTTP port for webhook mode only. Must be set when receive_mode = \"webhook\".\nNot required (and ignored) for websocket mode.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"receive_mode":{"description":"Event receive mode: \"websocket\" (default) or \"webhook\"","$ref":"#/$defs/LarkReceiveMode","default":"websocket"},"use_feishu":{"description":"Whether to use the Feishu (Chinese) endpoint instead of Lark (International)","type":"boolean","default":false},"verification_token":{"description":"Verification token for webhook validation (optional)","type":["string","null"],"default":null}},"required":["app_id","app_secret"]},"LarkReceiveMode":{"description":"How OpenPRX receives events from Feishu / Lark.\n\n- `websocket` (default) — persistent WSS long-connection; no public URL required.\n- `webhook` — HTTP callback server; requires a public HTTPS endpoint.","type":"string","enum":["websocket","webhook"]},"LinqConfig":{"type":"object","properties":{"allowed_senders":{"description":"Allowed sender handles (phone numbers) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"api_token":{"description":"Linq Partner API token (Bearer auth)","type":"string"},"from_phone":{"description":"Phone number to send from (E.164 format)","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"signing_secret":{"description":"Webhook signing secret for signature verification","type":["string","null"],"default":null}},"required":["api_token","from_phone"]},"MattermostConfig":{"description":"Mattermost bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Mattermost user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"bot_token":{"description":"Mattermost bot access token.","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only respond to messages that @-mention the bot.\nOther messages in the channel are silently ignored.","type":["boolean","null"],"default":null},"thread_replies":{"description":"When true (default), replies thread on the original post.\nWhen false, replies go to the channel root.","type":["boolean","null"],"default":null},"url":{"description":"Mattermost server URL (e.g. `\"https://mattermost.example.com\"`).","type":"string"}},"required":["url","bot_token"]},"McpConfig":{"type":"object","properties":{"servers":{"description":"Named MCP server definitions","type":"object","additionalProperties":{"$ref":"#/$defs/McpServerConfig"},"default":{}},"workspace_servers":{"description":"Which new servers a workspace `mcp.json` may add (D-085 F-1). A\nworkspace file may always narrow a server defined here (leave it out,\nor expose fewer of its tools); anything else it says about such a\nserver is ignored. `off` (the default) adds nothing, `http_only` adds\nHTTP servers, `stdio` adds HTTP and stdio servers (a stdio server is a\nprogram run as PRX's user). Widening this is a high-risk change.","$ref":"#/$defs/WorkspaceMcpServers"}}},"McpServerConfig":{"type":"object","properties":{"allow_tools":{"description":"Optional allow-list of exposed tools (empty = all)","type":"array","default":[],"items":{"type":"string"}},"args":{"description":"Command args for stdio mode","type":"array","default":[],"items":{"type":"string"}},"command":{"description":"Command for stdio mode","type":["string","null"],"default":null},"deny_tools":{"description":"Optional deny-list of exposed tools","type":"array","default":[],"items":{"type":"string"}},"env":{"description":"Environment variables for stdio mode","type":"object","additionalProperties":{"type":"string"},"default":{}},"request_timeout_ms":{"description":"Request timeout in milliseconds","type":"integer","format":"uint64","default":30000,"minimum":0},"startup_timeout_ms":{"description":"Startup timeout in milliseconds","type":"integer","format":"uint64","default":10000,"minimum":0},"tool_name_prefix":{"description":"Prefix used in tool naming and routing","type":"string","default":"mcp"},"transport":{"description":"Transport type: stdio or http","$ref":"#/$defs/McpTransport","default":"stdio"},"url":{"description":"URL for HTTP mode (streamable HTTP endpoint)","type":["string","null"],"default":null},"working_dir":{"description":"Working directory of a stdio server (absolute). Unset: a dedicated\nempty directory `mcp/` beside `config.toml`, never the\ndirectory PRX was started from (D-088 C-3). Changing it is a launch\nchange (high risk).","type":["string","null"]}}},"McpServerRuntimeConfig":{"type":"object","properties":{"allowed_origins":{"description":"Allowed browser origins for future streamable HTTP clients.","type":"array","default":["claude.ai","openai.com","localhost"],"items":{"type":"string"}},"bind":{"description":"Advertised bind address. The gateway may still be started with a CLI port override.","type":"string","default":"127.0.0.1:16831"},"exposed_tools":{"description":"Tools exposed to external MCP callers.\n\nThe defaults are all read-only. Every external MCP caller runs\nowner-isolated, so only names on the owner-isolation-aware list\n(`crate::tools::capability::policy::OWNER_ISOLATION_AWARE_TOOLS`) can run; any\nother name is not advertised, is refused with HTTP 403, and is warned\nabout at config load. An admissible tool with side effects\n(`memory_forget`, `memory_store`, `document_ingest`) is advertised with its real effect by\n`GET /mcp/v1/tools/list`, and a retry-safe call of it needs an\n`Idempotency-Key`.","type":"array","default":["memory_search","memory_recall","memory_get","document_search","document_get_chunk","sessions_list","sessions_history"],"items":{"type":"string"}},"jwt_algorithms":{"description":"Allowed JWT signing algorithms. Symmetric (`HS*`) and `none` are never\naccepted; only asymmetric algorithms in this list pass verification.","type":"array","default":["RS256"],"items":{"type":"string"}},"jwt_audience":{"description":"Expected `aud` claim for inbound bearer JWTs. When set, the token must\ncarry a matching audience.","type":["string","null"],"default":null},"jwt_issuer":{"description":"Expected `iss` claim for inbound bearer JWTs. When unset, bearer JWT\nverification is disabled and bearer tokens are rejected.","type":["string","null"],"default":null},"jwt_jwks":{"description":"Inline JWKS document (RFC 7517 JSON) used to resolve signing keys by\n`kid`. Takes precedence over `jwt_jwks_uri` and `jwt_public_key_pem`.","type":["string","null"],"default":null},"jwt_jwks_cache_ttl_secs":{"description":"Cache lifetime (seconds) for a fetched remote JWKS document. After this\nthe document is refreshed on the next verification. Defaults to 300s.","type":"integer","format":"uint64","default":300,"minimum":0},"jwt_jwks_uri":{"description":"Remote JWKS endpoint (HTTPS URL) whose document is fetched and cached to\nresolve signing keys by `kid`. Used when no inline `jwt_jwks` is set.\nFetching is fail-closed: a network failure with no still-valid cached\ncopy rejects the token rather than accepting it.","type":["string","null"],"default":null},"jwt_public_key_pem":{"description":"PEM-encoded public key (RSA/EC/Ed) used when no JWKS is configured.","type":["string","null"],"default":null},"rate_limit_rps":{"description":"Per-caller request budget, in requests per second, enforced on\n`POST /mcp/v1/tools/call` and keyed by the authenticated owner id.\n`0` disables the budget.","type":"integer","format":"uint32","default":10,"minimum":0},"require_auth":{"description":"Require an authenticated external identity for mutating calls.","type":"boolean","default":true}}},"McpTransport":{"type":"string","enum":["stdio","http"]},"MediaConfig":{"description":"Media understanding configuration (`[media]` section).\n\nControls STT transcription for audio and video frame extraction.\nAligns with OpenClaw's media-understanding architecture.","type":"object","properties":{"audio_model":{"description":"Audio model name (Ollama model or OpenAI model). Default: \"whisper\".","type":"string","default":"whisper"},"audio_ollama_url":{"description":"Ollama base URL for audio transcription. Default: \"http://localhost:11434\".","type":"string","default":"http://localhost:11434"},"audio_provider":{"description":"Audio STT provider: \"ollama\" | \"cli\" | \"none\". Default: \"none\".","type":"string","default":"none"},"max_audio_size_mb":{"description":"Maximum audio attachment size in MiB. Default: 20.","type":"integer","format":"uint","default":20,"minimum":0},"max_video_size_mb":{"description":"Maximum video attachment size in MiB. Default: 50.","type":"integer","format":"uint","default":50,"minimum":0},"video_max_frames":{"description":"Maximum video frames to extract per video. Default: 4.","type":"integer","format":"uint","default":4,"minimum":0},"video_provider":{"description":"Video provider: \"frames\" (ffmpeg frame extraction) | \"none\". Default: \"none\".","type":"string","default":"none"}}},"MemoryConfig":{"description":"Memory backend configuration (`[memory]` section).\n\nControls conversation memory storage, embeddings, hybrid search, response caching,\nand memory snapshot/hydration.","type":"object","properties":{"acl_enabled":{"description":"Feature gate for memory ACL enforcement. Phase 0 keeps this disabled.","type":"boolean","default":false},"archive_after_days":{"description":"Archive daily/session files older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"auto_hydrate":{"description":"Auto-hydrate from MEMORY_SNAPSHOT.md when brain.db is missing","type":"boolean","default":true},"auto_save":{"description":"Backward-compatible semantic auto-promotion gate.\n\nMessage events are controlled by `[memory.events]`; this controls whether\neligible user messages are promoted into long-term semantic memories.","type":"boolean","default":true},"backend":{"description":"\"sqlite\" | \"lucid\" | \"postgres\" | \"markdown\" | \"none\" (`none` = explicit no-op memory)\n\n`postgres` requires `[storage.provider.config]` with `db_url` (`dbURL` alias supported).","type":"string","default":"sqlite"},"conversation_retention_days":{"description":"For sqlite backend: prune conversation rows older than this many days","type":"integer","format":"uint32","default":3,"minimum":0},"daily_retention_days":{"description":"For sqlite backend: prune daily rows older than this many days","type":"integer","format":"uint32","default":7,"minimum":0},"embedding_cache_size":{"description":"Max embedding cache entries before LRU eviction","type":"integer","format":"uint","default":10000,"minimum":0},"embedding_dimensions":{"description":"Embedding vector dimensions","type":"integer","format":"uint","default":384,"minimum":0},"embedding_model":{"description":"Embedding model name (e.g. \"text-embedding-3-small\")","type":"string","default":"prx-local-hash-v1"},"embedding_provider":{"description":"Embedding provider: \"local\" | \"none\" | \"openai\" | \"custom:URL\"","type":"string","default":"local"},"events":{"description":"Raw/quasi-raw message event recording controls (`[memory.events]`).","$ref":"#/$defs/MemoryEventsConfig","default":{"record_assistant_messages":true,"record_tool_events":true,"record_user_messages":true}},"keyword_weight":{"description":"Weight for keyword BM25 in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.3},"legacy_conversation_turns_visible":{"description":"Phase 1/2 compatibility gate for legacy conversation turns while owner_id\nbackfill rolls out. Phase 3 can disable and remove this after NULL=0.","type":"boolean","default":true},"lucid_budget":{"description":"Token budget for lucid (replaces OPENPRX_LUCID_BUDGET)","type":["integer","null"],"format":"uint32","default":null,"minimum":0},"lucid_cmd":{"description":"Path to lucid binary (replaces OPENPRX_LUCID_CMD)","type":["string","null"],"default":null},"lucid_failure_cooldown_ms":{"description":"Failure cooldown in ms (replaces OPENPRX_LUCID_FAILURE_COOLDOWN_MS)","type":"integer","format":"uint64","default":60000,"minimum":0},"lucid_local_hit_threshold":{"description":"Local hit threshold: minimum number of local results before skipping\nremote Lucid recall. (replaces OPENPRX_LUCID_LOCAL_HIT_THRESHOLD)","type":"integer","format":"uint","default":3,"minimum":0},"lucid_recall_timeout_ms":{"description":"Recall timeout in ms (replaces OPENPRX_LUCID_RECALL_TIMEOUT_MS)","type":"integer","format":"uint64","default":5000,"minimum":0},"lucid_store_timeout_ms":{"description":"Store timeout in ms (replaces OPENPRX_LUCID_STORE_TIMEOUT_MS)","type":"integer","format":"uint64","default":3000,"minimum":0},"min_relevance_score":{"description":"Minimum hybrid score (0.0–1.0) for a memory to be included in context.\nMemories scoring below this threshold are dropped to prevent irrelevant\ncontext from bleeding into conversations. Default: 0.4","type":"number","format":"double","default":0.4},"purge_after_days":{"description":"Purge archived files older than this many days","type":"integer","format":"uint32","default":30,"minimum":0},"semantic":{"description":"Semantic memory promotion controls (`[memory.semantic]`).","$ref":"#/$defs/MemorySemanticConfig","default":{"auto_promote_assistant_messages":false,"auto_promote_user_messages":true,"min_chars":30}},"sqlite_open_timeout_secs":{"description":"For sqlite backend: max seconds to wait when opening the DB (e.g. file locked).\nNone = wait indefinitely (default). Recommended max: 300.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"sqlite_read_pool_size":{"description":"For sqlite backend: how many reader connections may be opened.\n\nSQLite allows one writer but genuinely concurrent readers under WAL, so\nonly reads are pooled. The pool is a connection *reuse* mechanism, not a\nconcurrency limiter: a caller that finds every reader busy queues for one\ninstead of failing. Unset derives the size from the available CPUs (see\n[`crate::runtime::sqlite_pool::default_read_pool_size`]); if set it must\nbe greater than 0. Deliberately a separate key from\n`channels_config.whatsapp.read_pool_size`, so the two SQLite databases\ncan be sized independently.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"vector_candidate_cap":{"description":"How many embedded memories one vector recall may score.\n\nCosine similarity cannot use an index, so the candidate set is bounded\nby insertion order (newest first) before scoring; without a bound this\nis a full scan of every embedded memory, once per turn. The trade-off is\nreal and not free: in a store with more embedded memories than this cap,\nan old-but-highly-relevant memory is never scored and therefore never\nrecalled. Raise it to buy recall with latency, lower it to buy latency\nwith recall. Vector recall logs a warning the first time a recall\nactually hits the cap, so a store that has outgrown it says so.","type":"integer","format":"uint","default":2000,"minimum":0},"vector_weight":{"description":"Weight for vector similarity in hybrid search (0.0–1.0)","type":"number","format":"double","default":0.7}}},"MemoryEventsConfig":{"description":"Raw message event recording configuration (`[memory.events]`).","type":"object","properties":{"record_assistant_messages":{"description":"Record assistant replies.","type":"boolean","default":true},"record_tool_events":{"description":"Record tool calls and tool results in the durable message log.","type":"boolean","default":true},"record_user_messages":{"description":"Record inbound/user messages.","type":"boolean","default":true}}},"MemorySemanticConfig":{"description":"Semantic memory promotion configuration (`[memory.semantic]`).","type":"object","properties":{"auto_promote_assistant_messages":{"description":"Auto-promote eligible assistant messages. Disabled by default to reduce noise.","type":"boolean","default":false},"auto_promote_user_messages":{"description":"Auto-promote eligible user messages into long-term semantic memories.","type":"boolean","default":true},"min_chars":{"description":"Minimum content length for semantic auto-promotion.","type":"integer","format":"uint","default":30,"minimum":0}}},"MemoryWebhookConfig":{"type":"object","properties":{"bind":{"description":"Socket address for the receiver (e.g. \"0.0.0.0:16899\").","type":"string","default":"0.0.0.0:16899"},"signing_secret":{"description":"Optional HMAC-SHA256 signing secret for `X-Webhook-Signature` verification.","type":["string","null"],"default":null},"token":{"description":"Required bearer token for incoming webhook events.","type":["string","null"],"default":null}}},"ModelOperationSetting":{"description":"The operations a `[[providers.models]]` entry may list.","type":"string","enum":["chat","embedding","decision_endpoint","rerank","image_generation","audio_generation","video_generation"]},"ModelPricing":{"description":"Per-model pricing entry (USD per 1M tokens).","type":"object","properties":{"cache_read":{"description":"Cache read input price per 1M tokens.","type":"number","format":"double","default":0.0},"cache_write":{"description":"Cache write/creation input price per 1M tokens.","type":"number","format":"double","default":0.0},"input":{"description":"Input price per 1M tokens","type":"number","format":"double","default":0.0},"output":{"description":"Output price per 1M tokens","type":"number","format":"double","default":0.0}}},"ModelRouteConfig":{"description":"Route a task hint to a specific provider + model.\n\n```toml\n[[model_routes]]\nhint = \"reasoning\"\nprovider = \"openrouter\"\nmodel = \"anthropic/claude-opus-4-20250514\"\n\n[[model_routes]]\nhint = \"fast\"\nprovider = \"groq\"\nmodel = \"llama-3.3-70b-versatile\"\n```\n\nUsage: pass `hint:reasoning` as the model parameter to route the request.","type":"object","properties":{"api_key":{"description":"Optional API key override for this route's provider","type":["string","null"],"default":null},"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"credential_ref":{"description":"A credential reference (`cred-`, `prx providers credential\nset`) issued for this route's provider, used instead of an inline\n`api_key`. The reference is resolved from the encrypted auth-profile\nstore only when its owner is this provider; setting both is refused.","type":["string","null"]},"hint":{"description":"Task hint name (e.g. \"reasoning\", \"fast\", \"code\", \"summarize\")","type":"string"},"level":{"type":["string","null"]},"model":{"description":"Model to use with that provider","type":"string"},"provider":{"description":"Provider to route to (must match a known provider name)","type":"string"},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true,"required":["hint","provider","model"]},"ModelSettings":{"description":"A model level plus explicit parameter overrides in `[model_settings.\"\"]`.","type":"object","properties":{"context_window":{"description":"Context window in tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1},"level":{"type":["string","null"]},"reserved_output_tokens":{"description":"Reserved output tokens for this model; only honoured under `[model_settings]`.","type":["integer","null"],"format":"uint64","minimum":1}},"additionalProperties":true},"MultimodalConfig":{"description":"Multimodal (image) handling configuration (`[multimodal]` section).","type":"object","properties":{"allow_remote_fetch":{"description":"Allow fetching remote image URLs (http/https). Enabled by default.","type":"boolean","default":true},"max_image_size_mb":{"description":"Maximum image payload size in MiB before base64 encoding.","type":"integer","format":"uint","default":5,"minimum":0},"max_images":{"description":"Maximum number of image attachments accepted per request.","type":"integer","format":"uint","default":4,"minimum":0}}},"NextcloudTalkConfig":{"description":"Nextcloud Talk bot configuration (webhook receive + OCS send API).","type":"object","properties":{"allowed_users":{"description":"Allowed Nextcloud actor IDs (`[]` = deny all, `\"*\"` = allow all).","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Bot app token used for OCS API bearer auth.","type":"string"},"base_url":{"description":"Nextcloud base URL (e.g. \"https://cloud.example.com\").","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"webhook_secret":{"description":"Shared secret for webhook signature verification.\n\nCan also be set via `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET` (legacy: `OPENPRX_NEXTCLOUD_TALK_WEBHOOK_SECRET`).","type":["string","null"],"default":null}},"required":["base_url","app_token"]},"NgrokTunnelConfig":{"type":"object","properties":{"auth_token":{"description":"ngrok auth token","type":"string"},"domain":{"description":"Optional custom domain","type":["string","null"]}},"required":["auth_token"]},"NodeServerConfig":{"description":"Node daemon runtime config used by `prx-node`.","type":"object","properties":{"allowed_commands":{"description":"Command allowlist matched on first token. Default: empty, which allows any\ncommand from an authenticated caller; `[\"*\"]` means the same.","type":"array","default":[],"items":{"type":"string"}},"bearer_token":{"description":"Required bearer token for /rpc.","type":"string","default":""},"blocked_commands":{"description":"Command denylist matched on first token. Always enforced.","type":"array","default":[],"items":{"type":"string"}},"exec_timeout_ms":{"description":"Default command timeout in milliseconds.","type":"integer","format":"uint64","default":15000,"minimum":0},"hmac_secret":{"description":"Optional HMAC signing secret.","type":["string","null"],"default":null},"listen_addr":{"description":"Listen address for node daemon.","type":"string","default":"127.0.0.1:8787"},"max_concurrent_tasks":{"description":"Maximum number of concurrent async command tasks.","type":"integer","format":"uint","default":8,"minimum":0},"max_output_bytes":{"description":"Maximum combined stdout/stderr bytes captured per command and maximum\nfile read/write payload accepted by the node RPC server.","type":"integer","format":"uint","default":1048576,"minimum":0},"sandbox_root":{"description":"Sandbox root directory for read/write/cwd constraints.","type":"string","default":"."},"task_result_ttl_ms":{"description":"TTL for completed task results in milliseconds.","type":"integer","format":"uint64","default":3600000,"minimum":0},"tls_cert":{"description":"TLS certificate path (PEM).","type":["string","null"],"default":null},"tls_key":{"description":"TLS private key path (PEM).","type":["string","null"],"default":null},"tls_required":{"description":"Require TLS for non-loopback binds.\n\nWhen true, node server must either bind to loopback or provide cert/key.","type":"boolean","default":true}}},"NodesConfig":{"description":"Remote node proxy configuration for core-side RPC calls and node daemon defaults.","type":"object","properties":{"nodes":{"description":"Configured remote nodes.","type":"array","default":[],"items":{"$ref":"#/$defs/RemoteNodeConfig"}},"request_timeout_ms":{"description":"Default request timeout for node RPC calls.","type":"integer","format":"uint64","default":15000,"minimum":0},"retry_max":{"description":"Default max retries for node RPC calls.","type":"integer","format":"uint8","default":2,"maximum":255,"minimum":0},"server":{"description":"Embedded node server defaults used by `prx-node`.","$ref":"#/$defs/NodeServerConfig","default":{"allowed_commands":[],"bearer_token":"","blocked_commands":[],"exec_timeout_ms":15000,"hmac_secret":null,"listen_addr":"127.0.0.1:8787","max_concurrent_tasks":8,"max_output_bytes":1048576,"sandbox_root":".","task_result_ttl_ms":3600000,"tls_cert":null,"tls_key":null,"tls_required":true}}}},"ObservabilityConfig":{"description":"Observability backend configuration (`[observability]` section).","type":"object","properties":{"backend":{"description":"\"none\" | \"log\" | \"prometheus\" | \"otel\"","type":"string","default":"none"},"otel_endpoint":{"description":"OTLP endpoint (e.g. \"http://localhost:4318\"). Only used when backend = \"otel\".","type":["string","null"],"default":null},"otel_service_name":{"description":"Service name reported to the OTel collector. Defaults to \"prx\".","type":["string","null"],"default":null}}},"OllamaProviderConfig":{"description":"Ollama-specific request options (`[providers.ollama]`).","type":"object","properties":{"num_ctx":{"description":"Explicit context window sent as Ollama `options.num_ctx`.","type":["integer","null"],"format":"uint","default":null,"minimum":0}}},"OsPagingConfig":{"description":"Letta/MemGPT-style OS-paging configuration (`[agent.compaction.os_paging]`).\n\nOS-paging is an additive layer for the legacy compaction modes. The exact\n`switch` mode bypasses it so paging cannot evict history before a durable\nhandoff is created. Configuration controls paging thresholds and recall.","type":"object","properties":{"eviction_threshold":{"description":"Token capacity ratio (0.0-1.0, relative to the input window after\nsubtracting reserved response tokens) above\nwhich eviction is triggered. Letta recommends ~0.70; the legacy\ncompaction path uses 0.85.","type":"number","format":"double","default":0.7},"keep_recent_messages":{"description":"Number of recent non-system messages always retained in the hot window\nduring eviction (older messages are paged out).","type":"integer","format":"uint","default":12,"minimum":0},"max_recalled_pages":{"description":"Maximum number of evicted pages (document chunks) recalled per turn.","type":"integer","format":"uint","default":10,"minimum":0},"proactive_retrieval":{"description":"Whether to proactively recall relevant evicted pages on every turn.\nWhen `false`, recall happens only after a context-overflow error.","type":"boolean","default":true},"retrieval_injection_role":{"description":"Role under which recalled pages are injected.","$ref":"#/$defs/RetrievalInjectionRole","default":"system"}}},"PluginsConfig":{"description":"WASM plugin runtime configuration.","type":"object","properties":{"enabled":{"description":"Load WASM plugins from `/plugins`. Default: `false`.","type":"boolean","default":false}},"additionalProperties":false},"ProviderModelConfig":{"description":"One `[[providers.models]]` entry: an operator declaration of what one\nmodel of a provider — or every model of it — can do.\n\nIt is the curated source of the per-(provider, model) descriptor the\nresolver consults. Every field but `provider` is optional and declares\nnothing when omitted. A declaration settles what discovery left unknown;\nit never lifts what the provider's adapter cannot execute, and negative\ncatalog evidence still wins over it.\n\n`tool_schema_dialect` and `tool_call_dialect` are the same declarations as\n`[[providers.tool_dialects]]` `tool_schema` / `tool_call`, which stays\naccepted; one `(provider, model)` may declare a dialect in only one of the\ntwo tables.","type":"object","properties":{"context_window":{"description":"The model's context window in tokens.","type":["integer","null"],"format":"uint32","minimum":0},"model":{"description":"The model (compared ignoring ASCII case), or every model of the\nprovider when omitted.","type":["string","null"]},"native_tools":{"description":"Whether the model accepts native tool calls.","type":["boolean","null"]},"operations":{"description":"The complete list of operations the model executes; every operation not\nlisted is unsupported.","type":["array","null"],"items":{"$ref":"#/$defs/ModelOperationSetting"}},"provider":{"description":"The provider, spelled as in `default_provider` (any alias, or a\n`custom:` endpoint). Every spelling of one provider identity is the\nsame provider.","type":"string"},"streaming":{"description":"Whether the model streams responses.","type":["boolean","null"]},"structured_output":{"description":"Whether the model honours a JSON-schema response format.","type":["boolean","null"]},"tool_call_dialect":{"description":"The textual tool-call grammar the endpoint emits. Entries without\n`model` only: the response parser cannot tell models apart.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema_dialect":{"description":"The tool-schema dialect the endpoint accepts for this model. Only for a\nprovider that reads dialect declarations.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]},"vision_input":{"description":"Whether the model accepts image input.","type":["boolean","null"]}},"required":["provider"]},"ProviderToolDialectConfig":{"description":"One `[[providers.tool_dialects]]` entry: what one OpenAI-compatible\nendpoint, or one model behind it, accepts.\n\nThe entry is the `(provider, optional model)` key plus two capability\nfields of the per-(provider, model) descriptor that will replace it (P1-B).\nThe descriptor now reads this table as operator declarations alongside\n`[[providers.models]]` (`tool_schema` / `tool_call` there are\n`tool_schema_dialect` / `tool_call_dialect`); the table stays accepted,\nand moving its rows into `[[providers.models]]` is a later migration step.","type":"object","properties":{"model":{"description":"The model this entry applies to (compared ignoring ASCII case), or every\nmodel of the provider when omitted.","type":["string","null"]},"provider":{"description":"The provider, spelled as in `default_provider`, `fallback_providers` or\n`--provider`: a `custom:` endpoint, or one of the catalog entries\nthat address a server the operator runs (`vllm`, `llamacpp`,\n`lmstudio`, `litellm`). Every spelling of the same provider identity is\nthe same entry: `custom:http://h:8080/v1/` and `CUSTOM:http://h:8080/v1`\nare one endpoint, a different port or path is another.","type":"string"},"tool_call":{"description":"The textual tool-call grammar the endpoint emits. Provider-wide entries\nonly: the response parser has no model, so a model-scoped grammar would\nsilently apply to every model of the endpoint.","anyOf":[{"$ref":"#/$defs/ToolCallDialectSetting"},{"type":"null"}]},"tool_schema":{"description":"The tool-schema dialect the endpoint accepts.","anyOf":[{"$ref":"#/$defs/ToolSchemaDialectSetting"},{"type":"null"}]}},"required":["provider"]},"ProvidersConfig":{"description":"Provider-specific runtime configuration (`[providers]`).","type":"object","properties":{"models":{"description":"Operator declarations of what a provider's models can do\n(`[[providers.models]]`): the curated source of the per-(provider,\nmodel) descriptor the model resolver consults.","type":"array","items":{"$ref":"#/$defs/ProviderModelConfig"}},"ollama":{"description":"Ollama-specific request options (`[providers.ollama]`).","$ref":"#/$defs/OllamaProviderConfig","default":{"num_ctx":null}},"tool_dialects":{"description":"Operator declarations of which tool-schema dialect and which textual\ntool-call grammar an OpenAI-compatible endpoint accepts\n(`[[providers.tool_dialects]]`).\n\nNothing is inferred from a URL: an endpoint with no entry is offered the\npublished tool schemas unchanged (`raw`) and only its native\n`tool_calls` array is read (`native`).","type":"array","items":{"$ref":"#/$defs/ProviderToolDialectConfig"}}}},"ProxyConfig":{"description":"Proxy configuration for outbound HTTP/HTTPS/SOCKS5 traffic (`[proxy]` section).","type":"object","properties":{"all_proxy":{"description":"Fallback proxy URL for all schemes.","type":["string","null"],"default":null},"http_proxy":{"description":"Proxy URL for HTTP requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"https_proxy":{"description":"Proxy URL for HTTPS requests (supports http, https, socks5, socks5h).","type":["string","null"],"default":null},"no_proxy":{"description":"No-proxy bypass list. Same format as NO_PROXY.","type":"array","default":[],"items":{"type":"string"}},"scope":{"description":"Proxy application scope.","$ref":"#/$defs/ProxyScope","default":"prx"},"services":{"description":"Service selectors used when scope = \"services\".","type":"array","default":[],"items":{"type":"string"}}}},"ProxyScope":{"description":"Proxy application scope — determines which outbound traffic uses the proxy.","oneOf":[{"description":"Use system environment proxy variables only.","type":"string","const":"environment"},{"description":"Apply proxy to all OpenPRX-managed HTTP traffic (default).","type":"string","const":"prx"},{"description":"Apply proxy only to explicitly listed service selectors.","type":"string","const":"services"}]},"QQConfig":{"description":"QQ Official Bot configuration (Tencent QQ Bot SDK)","type":"object","properties":{"allowed_users":{"description":"Allowed user IDs. Empty = deny all, \"*\" = allow all","type":"array","default":[],"items":{"type":"string"}},"app_id":{"description":"App ID from QQ Bot developer console","type":"string"},"app_secret":{"description":"App Secret from QQ Bot developer console","type":"string"},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["app_id","app_secret"]},"QueryClassificationConfig":{"description":"Automatic query classification — classifies user messages by keyword/pattern\nand routes to the appropriate model hint. Disabled by default.","type":"object","properties":{"rules":{"description":"Classification rules evaluated in priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/ClassificationRule"}}}},"RamfluxAccountConfig":{"description":"Persona for one ramflux AI account. Missing fields fall back to the global agent.","type":"object","properties":{"cross_conversation_retrieval":{"description":"Cross-conversation memory retrieval. Off unless the owner sets it.","type":"boolean","default":false},"model":{"type":["string","null"],"default":null},"provider":{"type":["string","null"],"default":null},"scope_profile":{"type":["string","null"],"default":null},"system_prompt_file":{"description":"Path to a system-prompt file. Relative paths are resolved from the workspace.","type":["string","null"],"default":null}},"additionalProperties":false},"RamfluxAttachmentFetch":{"description":"Per-turn caps for `attachment.fetch`.","type":"object","properties":{"max_bytes":{"type":"integer","format":"uint64","default":5242880,"minimum":0},"max_per_turn":{"type":"integer","format":"uint8","default":4,"maximum":255,"minimum":0}},"additionalProperties":false},"RamfluxAuthorizationMode":{"description":"How prx combines its own setting with `bridge.hello.authorization`.","oneOf":[{"description":"Use the agent-host value. Until hello arrives, the effective mode is supervised.","type":"string","const":"follow_rf"},{"description":"Always supervised, even when the agent-host declares full.","type":"string","const":"supervised"},{"description":"Full only when the agent-host also declares full. Config alone never yields full.","type":"string","const":"full"}]},"RamfluxConfig":{"description":"Local ramflux agent-host bridge (`[channels_config.ramflux]`).","type":"object","properties":{"accounts":{"type":"object","additionalProperties":{"$ref":"#/$defs/RamfluxAccountConfig"},"default":{}},"allowed_block_types":{"type":"array","default":["Text","Markdown","Heading","KeyValue","Metric","List","TableFallback","Form","Input","Select","Progress","LogStream","Warning","Error","Success","Approval","ActionGroup","FilePreview","Fallback"],"items":{"type":"string"}},"attachment_fetch":{"$ref":"#/$defs/RamfluxAttachmentFetch","default":{"max_bytes":5242880,"max_per_turn":4}},"authorization_mode":{"$ref":"#/$defs/RamfluxAuthorizationMode","default":"follow_rf"},"encrypt_at_rest":{"type":"boolean","default":true},"max_in_flight_per_conversation":{"type":"integer","format":"uint8","default":1,"maximum":255,"minimum":0},"on_new_message":{"$ref":"#/$defs/RamfluxOnNewMessage","default":"queue"},"socket_path":{"description":"Unix socket path. `None` uses `/ramflux/run/ramflux.sock`.\nThe channel creates `ramflux` and `run` at mode `0700`.","type":["string","null"],"default":null},"surface_limits":{"$ref":"#/$defs/RamfluxSurfaceLimits","default":{"max_actions":16,"max_blocks":32,"max_bytes":65536}},"turn_wall_clock_secs":{"description":"Advertised turn wall clock, in seconds. The agent-host enforces it with `turn.cancel`.","type":"integer","format":"uint64","default":120,"minimum":0}},"additionalProperties":false},"RamfluxOnNewMessage":{"description":"What to do with a new inbound message while a turn for that conversation is running.","type":"string","enum":["queue","interrupt"]},"RamfluxSurfaceLimits":{"description":"Limits for `reply.surface` blocks and actions.","type":"object","properties":{"max_actions":{"type":"integer","format":"uint32","default":16,"minimum":0},"max_blocks":{"type":"integer","format":"uint32","default":32,"minimum":0},"max_bytes":{"type":"integer","format":"uint32","default":65536,"minimum":0}},"additionalProperties":false},"ReliabilityCircuitBreakerConfig":{"description":"Process-local provider circuit policy (`[reliability.circuit_breaker]`).","type":"object","properties":{"enabled":{"description":"Enable protection for factory-built provider chains.","type":"boolean","default":true},"failure_threshold":{"description":"Consecutive transient failures that open a circuit (at least 1).","type":"integer","format":"uint32","default":5,"minimum":0},"max_open_secs":{"description":"Maximum doubled window, between open_secs and 3600 seconds.","type":"integer","format":"uint64","default":300,"minimum":0},"open_secs":{"description":"Initial open window in seconds (at least 1).","type":"integer","format":"uint64","default":30,"minimum":0}}},"ReliabilityConfig":{"description":"Reliability and supervision configuration (`[reliability]` section).\n\nControls provider retries, fallback chains, API key rotation, and channel restart backoff.","type":"object","properties":{"acknowledge_single_provider_risk":{"description":"Operator acknowledgement that no provider failover is configured.\nThis suppresses doctor noise only; it does not add a fallback.","type":"boolean","default":false},"api_keys":{"description":"Additional API keys for round-robin rotation on rate-limit (429) errors.\nThe primary `api_key` is always tried first; these are extras.","type":"array","default":[],"items":{"type":"string"}},"channel_initial_backoff_secs":{"description":"Initial backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":2,"minimum":0},"channel_max_backoff_secs":{"description":"Max backoff for channel/daemon restarts.","type":"integer","format":"uint64","default":60,"minimum":0},"circuit_breaker":{"description":"Per-provider consecutive failure protection.","$ref":"#/$defs/ReliabilityCircuitBreakerConfig","default":{"enabled":true,"failure_threshold":5,"max_open_secs":300,"open_secs":30}},"fallback_providers":{"description":"Fallback provider chain (e.g. `[\"anthropic\", \"openai\"]`).","type":"array","default":[],"items":{"type":"string"}},"model_fallbacks":{"description":"Per-model fallback chains. When a model fails, try these alternatives in order.\nExample: `{ \"claude-opus-4-20250514\" = [\"claude-sonnet-4-20250514\", \"gpt-4o\"] }`","type":"object","additionalProperties":{"type":"array","items":{"type":"string"}},"default":{}},"provider_backoff_ms":{"description":"Base backoff (ms) for provider retry delay.","type":"integer","format":"uint64","default":500,"minimum":0},"provider_retries":{"description":"Retries per provider before failing over.","type":"integer","format":"uint32","default":2,"minimum":0},"scheduler_poll_secs":{"description":"Scheduler polling cadence in seconds.","type":"integer","format":"uint64","default":15,"minimum":0},"scheduler_retries":{"description":"Max retries for cron shell attempts and Agent startup before decision admission.\nAdmitted Agent turns are not replanned automatically; provider request retries\nremain controlled by `provider_retries`.","type":"integer","format":"uint32","default":2,"minimum":0}}},"RemoteNodeConfig":{"description":"A remote node target for core-side node proxy calls.","type":"object","properties":{"bearer_token":{"description":"Bearer token for node RPC authentication.","type":"string"},"endpoint":{"description":"Base endpoint (e.g. \"http://127.0.0.1:8787\").","type":"string"},"hmac_secret":{"description":"Optional request signing key (HMAC-SHA256).","type":["string","null"],"default":null},"id":{"description":"Stable node ID used by the nodes tool.","type":"string"},"retry_max":{"description":"Optional per-node retry override.","type":["integer","null"],"format":"uint8","default":null,"maximum":255,"minimum":0},"timeout_ms":{"description":"Optional per-node timeout override.","type":["integer","null"],"format":"uint64","default":null,"minimum":0}},"required":["id","endpoint","bearer_token"]},"RetrievalInjectionRole":{"description":"Where recalled context pages are injected back into the request.","oneOf":[{"description":"Inject recalled pages as a leading `system` message (not user-visible).","type":"string","const":"system"},{"description":"Inject recalled pages as a leading `user` message.","type":"string","const":"user"}]},"RouterConfig":{"description":"Heuristic LLM router configuration (`[router]` section).","type":"object","properties":{"alpha":{"description":"Similarity score weight. Phase 1 keeps this at `0.0`.","type":"number","format":"float","default":0.0},"beta":{"description":"Capability score weight.","type":"number","format":"float","default":0.5},"delta":{"description":"Cost penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"epsilon":{"description":"Latency penalty coefficient.","type":"number","format":"float","default":0.10000000149011612},"gamma":{"description":"Elo score weight.","type":"number","format":"float","default":0.30000001192092896},"knn_k":{"description":"Number of nearest neighbors considered for voting. Default: `7`.","type":"integer","format":"uint","default":7,"minimum":0},"knn_min_records":{"description":"Minimum history records before KNN affects routing. Default: `10`.","type":"integer","format":"uint","default":10,"minimum":0},"models":{"description":"Candidate model registry.","type":"array","default":[],"items":{"$ref":"#/$defs/RouterModelConfig"}}}},"RouterModelConfig":{"description":"Static router metadata for one model candidate.","type":"object","properties":{"categories":{"description":"Capability categories such as `conversation`, `code`, or `analysis`.","type":"array","default":[],"items":{"type":"string"}},"cost_per_million_tokens":{"description":"USD cost per million tokens.","type":"number","format":"float","default":0.0},"elo_rating":{"description":"Initial Elo rating.","type":"number","format":"float","default":1000.0},"latency_ms":{"description":"Average latency in milliseconds.","type":"integer","format":"uint32","default":2000,"minimum":0},"max_context":{"description":"Maximum context window in tokens.","type":"integer","format":"uint","default":1000000,"minimum":0},"model_id":{"description":"Model identifier without provider prefix.","type":"string"},"provider":{"description":"Provider identifier.","type":"string"},"reserved_output_tokens":{"description":"Output tokens reserved for this model when planning input context.","type":["integer","null"],"format":"uint","minimum":0}},"required":["model_id","provider"]},"RuntimeConfig":{"description":"Runtime adapter configuration (`[runtime]` section).","type":"object","properties":{"codex_reasoning_effort":{"description":"Codex reasoning effort","type":["string","null"],"default":null},"codex_stream_idle_timeout_secs":{"description":"Codex stream idle timeout in seconds","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"docker":{"description":"Docker runtime settings (used when `kind = \"docker\"`).","$ref":"#/$defs/DockerRuntimeConfig","default":{"allowed_workspace_roots":[],"cpu_limit":1.0,"image":"alpine:3.20","memory_limit_mb":512,"mount_workspace":true,"network":"none","read_only_rootfs":true}},"idle_hang_secs":{"description":"Seconds an agent turn may produce **no observable progress at all**\nbefore it is judged hung and terminated.\n\n**This is not a turn timeout.** The window is reset by every sign of\nlife — a provider stream chunk, a tool call starting or finishing,\nhistory compaction, output written to a channel — so a turn that keeps\nworking runs for as long as it needs to, however long that is. Only\ntotal silence for the whole window counts, which is a stall rather than\na slow task.\n\nContrast [`RuntimeConfig::long_task_warn_secs`], which measures elapsed\nrun time, is *not* refreshed by progress, and never terminates anything.\nThe two must not be conflated or merged: one reports that work is long,\nthis one recovers from work that is wedged.\n\nLeave unset for the 1800s default; set `0` to disable hang detection\nentirely. Enabled values must be at least 30 seconds.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"kind":{"description":"Runtime kind (`native` | `docker`).","type":"string","default":"native"},"long_task_warn_secs":{"description":"Seconds after which a still-running work item is reported in the log.\n\n**Notification only — nothing is ever terminated because of it.** PRX\ntreats long tasks as normal business: a research run or a build can\nlegitimately take hours, and ending one on a timer is a worse outcome\nthan letting it finish. This threshold exists so that a task which is\ngenuinely wedged becomes *visible*, leaving the decision to an operator\n(`prx tasks list` / `prx tasks kill`).\n\nLeave unset for the 900s default; set `0` to silence the warning\nentirely. Enabled values must be at least 10 seconds, below which the\nsweeper would warn about ordinary tool calls.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"managed_cgroup_root":{"description":"Optional delegated Linux cgroup v2 root for managed native skill scripts.\nA configured but unavailable root refuses execution; macOS is unsupported.","type":["string","null"],"default":null},"max_blocking_threads":{"description":"Hard cap on the tokio blocking-thread pool.\n\nPRX places no ceiling on concurrent turns, sub-agents or sessions, which\nmakes this pool the last implicit concurrency gate in the process — and\nit fails by deadlock, not by rejection: once every slot is held, further\nblocking work queues forever with no timeout. Tokio's built-in default\nis a hardware-agnostic 512; leaving this unset instead derives the cap\nfrom `available_parallelism()` (cgroup-aware) with a 2048 floor. Raise\nit when `[runtime] blocking pool is saturated` warnings appear.\n\nRead during process bootstrap, before the runtime exists, so it takes\neffect only on restart — config hot-reload cannot resize a live pool.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"reasoning_enabled":{"description":"Global reasoning override for providers that expose explicit controls.\n- `None`: provider default behavior\n- `Some(true)`: request reasoning/thinking when supported\n- `Some(false)`: disable reasoning/thinking when supported","type":["boolean","null"],"default":null},"shell_env_allowlist":{"description":"Extra parent environment names inherited by the generic `shell` tool.\nEmpty by default. Exact uppercase ASCII names only; no wildcards.\nThis grants the shell access to their values and takes effect on restart.","type":"array","default":[],"items":{"type":"string"}},"workdir":{"description":"Optional absolute existing working directory for shell, native files and git.\nRestart-only; does not change the security workspace or memory ACL root.","type":["string","null"],"default":null}}},"SchedulerConfig":{"description":"Scheduler configuration for periodic task execution (`[scheduler]` section).","type":"object","properties":{"claim_lease_secs":{"description":"Execution claim lease. Active jobs renew this lease every one third of\nthe interval; expired claims may be recovered by another scheduler.","type":"integer","format":"uint64","default":90,"minimum":0},"max_tasks":{"description":"Maximum number of persisted scheduled tasks.","type":"integer","format":"uint","default":64,"minimum":0}}},"ScopeConfig":{"description":"Scope-based tool access control configuration (`[autonomy.scopes]`).\n\nControls which tools are available per-user, per-channel, and per-chat-type.\n\nExample config:\n```toml\n[autonomy.scopes]\ndefault = \"allow\"\n\n[[autonomy.scopes.rules]]\nchannel = \"signal\"\nchat_type = \"group\"\ntools_deny = [\"shell\", \"file_write\"]\n\n[[autonomy.scopes.rules]]\nuser = \"uuid:untrusted-user-uuid\"\ntools_allow = [\"memory_recall\"] # whitelist-only\n\n[[autonomy.scopes.rules]]\nchannel = \"wacli\"\nsend_deny = [\"*:+15550001111\"] # never message this recipient\n```","type":"object","properties":{"assign_owners":{"description":"Correspondents who own this daemon and may hand work to any `prx chat`\nsession it knows about.\n\nEntries are `{channel}:{sender}` — the same two-segment shape\n`send_allow` uses for a destination, read here as an *origin*. Either\nsegment may be `\"*\"`; a bare `\"*\"` makes every correspondent an owner\nand is almost never what an operator wants.\n\nThe identity compared here is the runtime-injected `_zc_scope`, not\nanything a model or an HTTP body claimed, so an entry names a real\nplatform account. An owner still loses to a matching `assign_deny`.\n\nEmpty (the default) means no correspondent owns this daemon, so the only\nway to assign work is an authenticated operator-plane request.","type":"array","default":[],"items":{"type":"string"}},"default":{"description":"Default action when no rule matches: \"allow\" (default) or \"deny\".","$ref":"#/$defs/ScopeDefault","default":"allow"},"rules":{"description":"Ordered list of scope rules evaluated top-to-bottom.","type":"array","default":[],"items":{"$ref":"#/$defs/ScopeRule"}}}},"ScopeDefault":{"description":"What `autonomy.scopes` does with a tool call no rule matches.\n\nParsed once, at load: `allow` or `deny` after trimming and ignoring case,\nand nothing else (D-050). The runtime (`SecurityPolicy::from_config`) and\nthe configuration plan (`config::manage::plan`) read this one value, so a\nspelling such as `\"deny \"` can never mean deny to the plan and allow at\nruntime. An unknown value is refused when the configuration loads.","oneOf":[{"description":"Unmatched tool calls are allowed (the default).","type":"string","const":"allow"},{"description":"Unmatched tool calls are refused.","type":"string","const":"deny"}]},"ScopeRule":{"description":"A single scope rule for tool access control.\n\nA rule matches when ALL specified criteria match (logical AND).\nDeny always takes priority over allow within a rule.\n\nThe two halves of a rule are evaluated differently, on purpose:\n* `tools_allow` / `tools_deny` are **first-match-wins** — the first matching\n rule decides tool access and later rules are not consulted.\n* `send_allow` / `send_deny` are evaluated over **every** matching rule that\n carries at least one outbound entry, so a rule written for some unrelated\n reason (a `tools_deny`-only rule, say) can never silently swallow a later\n rule's `send_deny`. See `SecurityPolicy::is_outbound_allowed`.","type":"object","properties":{"assign_allow":{"description":"Assignment whitelist: which `prx chat` sessions this scope may hand work\nto through `POST /api/chat-sessions/{id}/assign`.\n\nEntries are `{label}:{session_id}` — the same two-segment shape as\n`send_allow`, with the live chat session in the place of the recipient.\nEither segment may be `\"*\"`, and a bare `\"*\"` matches every session. The\nlabel is the human name the chat process registered under, so\n`\"workstation:*\"` follows that chat across restarts while\n`\"*:{session_id}\"` names exactly one run of it.\n\n**The label is self-declared by whoever registered the session.** It is a\nconvenience for writing rules, not an identity assertion: anything that\ncan reach the register endpoint can claim any label. Where that matters,\nname the session id, which the daemon generates.\n\nAssignment is **default-deny**: with no `assign_owners` and no\n`assign_allow` anywhere, no channel correspondent can assign anything.\nThat is the opposite of `send_allow`, whose empty default still permits\nthe turn's own channel, and it is deliberate — an assignment starts work\non another entry point, so silence must mean \"no\".","type":"array","default":[],"items":{"type":"string"}},"assign_deny":{"description":"Assignment blacklist, in the same `{label}:{session_id}` form.\n\nEvaluated across *every* matching rule, so a later `assign_deny` can\nnever be shadowed by an earlier rule, and it outranks both\n`assign_allow` and `autonomy.scopes.assign_owners` — an owner named here\nis refused, exactly as `tools_deny` outranks `tools_allow`.\n\nUnlike `send_deny` there is no alias folding: both segments are compared\nliterally. A chat session id is generated by this daemon and has exactly\none spelling, so there is no alias to fold and no guess to make.","type":"array","default":[],"items":{"type":"string"}},"channel":{"description":"Match by channel name: \"signal\", \"telegram\", \"discord\", etc.","type":["string","null"]},"chat_type":{"description":"Match by chat type: \"direct\", \"group\", or \"*\" for any type.","type":["string","null"]},"send_allow":{"description":"Outbound recipient whitelist for `message_send`.\n\nEntries are `{channel}:{recipient}` (for example `\"telegram:*\"` or\n`\"wacli:1234@s.whatsapp.net\"`); a bare `\"*\"` matches every destination.\nEmpty (the default) means this rule imposes no whitelist, so the\nsame-channel / cross-channel default decides.\n\nThe whitelist is matched on the recipient **exactly as written**: unlike\n`send_deny`, no alias folding widens it, because widening a whitelist\nwould grant reach on a guess. The first matching rule with a non-empty\n`send_allow` is the one that applies; `validate` rejects a rule whose\n`send_allow` an earlier rule would shadow, so this never fails silently.","type":"array","default":[],"items":{"type":"string"}},"send_deny":{"description":"Outbound recipient blacklist, in the same `{channel}:{recipient}` form.\n\nEvaluated before `send_allow`, mirroring how `tools_deny` outranks\n`tools_allow`, and evaluated across *every* matching rule so it can\nnever be shadowed by an earlier one.\n\nThe recipient is matched after folding the alias forms that are\nderivable from the string itself: a JID's `:device` suffix and server\ncase (`1234@s.whatsapp.net`, `1234:2@s.whatsapp.net` and\n`1234@S.WhatsApp.net` are one person), a leading `+` (`+15550001111`\nand `15550001111`), and a UUID's letter case and hyphenation.\n\n**Aliases that are NOT derivable are not covered.** A WhatsApp LID\n(`@lid`) carries a different number from the same contact's phone\nJID (`@s.whatsapp.net`), and a Signal UUID is unrelated to that\naccount's E.164 number; correlating either pair needs a mapping table\nthis layer does not hold. Write one entry per identifier form the\ncontact can appear under, or deny the whole channel with\n`\"{channel}:*\"`, which is the only form that is alias-proof.","type":"array","default":[],"items":{"type":"string"}},"tools_allow":{"description":"Tool whitelist: only these tools are allowed (empty = all tools permitted).","type":"array","default":[],"items":{"type":"string"}},"tools_deny":{"description":"Tool blacklist: these tools are denied regardless of allow list.","type":"array","default":[],"items":{"type":"string"}},"user":{"description":"Match by sender identity: UUID (e.g. \"uuid:xxx\"), phone number, or \"*\" for any sender.","type":["string","null"]}}},"SecretsConfig":{"description":"Secrets encryption configuration (`[secrets]` section).","type":"object","properties":{"encrypt":{"description":"Enable encryption for API keys and tokens in config.toml","type":"boolean","default":true}}},"SecurityConfig":{"description":"Security configuration for audit logging.\n\nThe host-shell sandbox configuration, the former `[security.tool_policy]`\npipeline and the `[security.resources]` command limits were removed: the\nfirst two had no pipeline behind them, and the limits named a per-command\nmemory/CPU/subprocess ceiling this runtime never enforced and, being an\nunbounded runtime, will not. Non-shell tool authorization remains driven by\n`[autonomy]`.","type":"object","properties":{"audit":{"description":"Audit logging configuration","$ref":"#/$defs/AuditConfig","default":{"log_path":"audit.log","max_size_mb":100}},"workspace_hooks":{"description":"Whether the command hooks of the workspace `hooks.json` run\n(HOOKS-ENV, D-085 O-1). `hooks.json` lives in the agent's workspace,\nwhere the workspace file tools can write it, and each hook runs a\nprogram as PRX's user; so they run only when the operator turns them\n`on` here. Turning it on is a high-risk change. WASM plugin hooks are\nnot affected.","$ref":"#/$defs/WorkspaceHooks"}}},"SelfSystemConfig":{"description":"Self-system experimental automation config (`[self_system]`).","type":"object","properties":{"evolution_config_path":{"description":"Path to evolution config file (replaces OPENPRX_EVOLUTION_CONFIG)","type":["string","null"],"default":null},"evolution_debug_raw":{"description":"Enable debug raw output for evolution (replaces OPENPRX_EVOLUTION_DEBUG_RAW)","type":"boolean","default":false},"evolution_interval_hours":{"description":"Evolution scheduler interval in hours (daemon mode).","type":"integer","format":"uint32","default":24,"minimum":0},"evolution_judge_timeout_secs":{"description":"Seconds one evolution model call may take (1 to 3600, default 180).\nShared by the proposer and judge. A missing verdict cannot apply a change.","type":"integer","format":"uint64","default":180,"minimum":0},"evolution_model_max_micro_usd":{"description":"Monetary allowance per evolution model call, in micro USD. The default\nzero allows explicitly priced free/local models only. Global cost limits\nstill apply; this is a reservation estimate, not a vendor billing cap.","type":"integer","format":"uint64","default":0,"minimum":0},"evolution_model_max_tokens":{"description":"Total input/output token allowance for one evolution model call,\nincluding physical retries. Zero disables evolution model calls.","type":"integer","format":"uint64","default":16384,"minimum":0},"fitness":{"description":"Daily fitness snapshot policy.","$ref":"#/$defs/FitnessConfig","default":{"auto_run":true,"max_backfill_days":7,"min_coverage":0.6,"min_samples":5,"retention_days":180,"run_at":"00:10","timezone":"UTC"}},"fitness_interval_hours":{"description":"Legacy fitness report interval in hours.\n\nKept for configuration compatibility. Calendar scheduling is controlled\nby `[self_system.fitness]` and this value is no longer used by the\ndaemon worker.","type":"integer","format":"uint64","default":24,"minimum":0}}},"SessionsSpawnConfig":{"description":"Sessions spawn configuration (`[sessions_spawn]` section).","type":"object","properties":{"cleanup_on_complete":{"description":"Remove worker workspace directory after process-mode completion.","type":"boolean","default":true},"default_mode":{"description":"Default execution mode for sessions_spawn (`task` or `process`).","type":"string","default":"task"},"process_memory_strategy":{"description":"Memory strategy for process-mode workers.\n\nSupported values:\n- `shared_fabric`: worker uses the parent workspace memory DB.\n- `isolated_private`: worker uses its private DB.","type":"string","default":"shared_fabric"},"worker_workspace_root":{"description":"Optional root directory for process-mode worker workspaces.\n\nWhen unset, falls back to `/workers`.","type":["string","null"],"default":null}}},"SignalConfig":{"type":"object","properties":{"account":{"description":"E.164 phone number of the signal-cli account (e.g. \"+1234567890\").","type":"string"},"allowed_from":{"description":"Allowed sender phone numbers (E.164) or \"*\" for all.","type":"array","default":[],"items":{"type":"string"}},"cli_path":{"description":"Path to signal-cli binary. Only used in native mode. Default: \"signal-cli\" (PATH lookup).","type":["string","null"],"default":null},"daemon_http_port":{"description":"Local HTTP port for the spawned signal-cli daemon. Only used in native mode. Default: 16866.","type":["integer","null"],"format":"uint16","default":null,"maximum":65535,"minimum":0},"daemon_mode":{"description":"Deprecated: ignored. Accepted for backward compatibility with older config files.","type":["boolean","null"],"default":null},"data_dir":{"description":"signal-cli data directory. Only used in native mode.\nDefault: $HOME/.local/share/signal-cli (signal-cli's standard XDG location).","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_id":{"description":"Optional group ID to filter messages.\n- `None` or omitted: accept all messages (DMs and groups)\n- `\"dm\"`: only accept direct messages\n- Specific group ID: only accept messages from that group","type":["string","null"],"default":null},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"http_url":{"description":"Base URL for the signal-cli HTTP daemon (e.g. \"http://127.0.0.1:16866\").\nIn \"native\" mode this is ignored; the daemon is spawned on `daemon_http_port`.","type":"string","default":"http://localhost:8080"},"ignore_attachments":{"description":"Skip messages that are attachment-only (no text body).","type":"boolean","default":false},"ignore_stories":{"description":"Skip incoming story messages.","type":"boolean","default":false},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"mode":{"description":"Channel mode: \"native\" (spawn signal-cli daemon locally) or \"rest\" (external daemon/Docker).\nDefault: \"rest\" for backward compatibility.","type":["string","null"],"default":null},"startup_timeout_ms":{"description":"Startup readiness timeout in milliseconds for native `signal-cli` daemon mode.","type":"integer","format":"uint64","default":30000,"minimum":0},"storm_protection":{"description":"Signal ingress storm protection controls.","$ref":"#/$defs/SignalStormProtectionConfig","default":{"abnormal_threshold":10,"abnormal_window_secs":60,"breaker_duration_secs":300,"dedupe_ttl_secs":60,"min_reply_interval_secs":2}}},"required":["account"]},"SignalStormProtectionConfig":{"type":"object","properties":{"abnormal_threshold":{"description":"Non-user event threshold within `abnormal_window_secs` before tripping the breaker.","type":"integer","format":"uint","default":10,"minimum":0},"abnormal_window_secs":{"description":"Sliding window in seconds for non-user event counting.","type":"integer","format":"uint64","default":60,"minimum":0},"breaker_duration_secs":{"description":"Circuit breaker duration in seconds after threshold is reached.","type":"integer","format":"uint64","default":300,"minimum":0},"dedupe_ttl_secs":{"description":"Deduplication TTL in seconds for `(channel + sender + event_type + normalized_content)`.","type":"integer","format":"uint64","default":60,"minimum":0},"min_reply_interval_secs":{"description":"Minimum interval in seconds between replies for the same `(channel + reply_target)`.","type":"integer","format":"uint64","default":2,"minimum":0}}},"SkillRagConfig":{"description":"Dynamic skill retrieval configuration (`[skill_rag]` section).","type":"object","properties":{"top_k":{"description":"How many skills the system prompt may advertise.\n\nThe section lists metadata only (instruction bodies stay behind\n`skill_read`), so a catalog at or below this size is published whole and\nthe section becomes a pure function of the installed skills — which is\nwhat keeps the provider's cacheable prefix identical across turns.\nLarger catalogs fall back to relevance retrieval, which does move with\nthe wording; entry points that hold a session narrow that churn with a\nsession-scoped union (`SessionSkillExposure`).","type":"integer","format":"uint","default":32,"minimum":0}}},"SkillSuiteRegistration":{"description":"The frozen suite that governs one skill's proposals.","type":"object","properties":{"skill_id":{"description":"The skill the suite governs.","type":"string"},"suite_digest":{"description":"SHA-256 digest (64 lowercase hex digits) of the frozen suite.","type":"string"}},"additionalProperties":false,"required":["skill_id","suite_digest"]},"SkillsConfig":{"description":"Skills loading configuration (`[skills]` section).","type":"object","properties":{"open_skills_dir":{"description":"Optional path to a local open-skills repository.\nIf unset, defaults to `$HOME/open-skills` when enabled.","type":["string","null"],"default":null},"openclaw_skills_dir":{"description":"Optional path to a local openclaw-skills clone directory.\nIf unset, defaults to `$HOME/.openprx/openclaw-skills/` when enabled.","type":["string","null"],"default":null}}},"SkillsLifecycleConfig":{"description":"`[skills_lifecycle]`. The defaults leave the lifecycle off, in `draft_only`\nmode, with the strongest publication policy.","type":"object","properties":{"allow_executable_proposals":{"description":"Allow explicit script drafts from operator-supplied templates. Drafts\nnever publish or execute. Import still requires review of the exact\ncomplete bundle hash and execution requires an independent tool grant.","type":"boolean","default":false},"enabled":{"description":"Turns the lifecycle on. Off by default: nothing is offered and no store\nis opened.","type":"boolean","default":false},"max_concurrent_evaluations":{"description":"Most evaluations running at once.","type":"integer","format":"uint32","default":1,"minimum":0},"max_edit_fraction":{"description":"Edit budget of a proposal as a fraction of the skill body, in (0, 1].","type":"number","format":"double","default":0.2},"max_edit_tokens":{"description":"Edit budget of a proposal, in tokens.","type":"integer","format":"uint64","default":300,"minimum":0},"max_proposals_per_cycle":{"description":"Most proposals one cycle may start.","type":"integer","format":"uint32","default":1,"minimum":0},"min_cases_floor":{"description":"Smallest `min_cases` a governing suite may declare. Below 3 is refused.","type":"integer","format":"uint32","default":3,"minimum":0},"mode":{"description":"`draft_only`, `shadow` or `auto`.","$ref":"#/$defs/SkillsLifecycleModeConfig","default":"draft_only"},"owner_scope":{"description":"The owner scope whose lifecycle store this installation manages.\nRequired when `enabled`.","type":["string","null"],"default":null},"require_holdout":{"description":"A governing suite must have a holdout split. `false` is refused.","type":"boolean","default":true},"storage_dir":{"description":"Store location under the workspace. Only the default is supported.","type":"string","default":"self/skill-lifecycle"},"suites":{"description":"The frozen suite per skill. Operator-owned: it is the only source of\nthe suite that governs a proposal.","type":"array","default":[],"items":{"$ref":"#/$defs/SkillSuiteRegistration"}}},"additionalProperties":false},"SkillsLifecycleModeConfig":{"description":"What the lifecycle may do. Mirrors `LifecycleMode`.","oneOf":[{"description":"Drafts and reviews only.","type":"string","const":"draft_only"},{"description":"Drafts plus evaluation and gating; never publishes.","type":"string","const":"shadow"},{"description":"Publishes an eligible proposal after every gate.","type":"string","const":"auto"}]},"SlackConfig":{"description":"Slack bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Slack user IDs. Empty = deny all.","type":"array","default":[],"items":{"type":"string"}},"app_token":{"description":"Slack app-level token for Socket Mode (xapp-...).","type":["string","null"]},"bot_token":{"description":"Slack bot OAuth token (xoxb-...).","type":"string"},"channel_id":{"description":"Optional channel ID to restrict the bot to a single channel.","type":["string","null"]},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false}},"required":["bot_token"]},"SmartGroupConfig":{"description":"Token-saving pre-gate for smart group-reply (`[smart_group]`).\n\nThe pre-gate runs after source decision admission and before the full agent\nloop for smart-mode group messages that do NOT explicitly @-mention the bot.\nA 0-token heuristic sends clearly relevant messages straight to the loop;\nobvious noise and uncertain messages require a yes/no confirmation from a\nresolver-built, physically accounted classifier before silence is allowed.\n\n@-mentions, DMs, and non-smart modes NEVER reach the pre-gate. The pre-gate\nis fail-open: any classifier error/timeout enters the loop (it must never\nsilently drop a message that should have been answered).","type":"object","properties":{"classifier_max_context_messages":{"description":"How many recent conversation turns to feed the classifier as context.\nDefault: `3`. Bounded to keep the classifier prompt (and cost) tiny.","type":"integer","format":"uint","default":3,"minimum":0},"classifier_model":{"description":"Model id for the Tier-2 classifier. When empty, the admitted channel\nroute's model is resolved. Set a lower-cost model id to minimize cost.","type":"string","default":""},"classifier_provider":{"description":"Provider id/alias for the Tier-2 classifier. When empty, the admitted\nchannel route's provider is resolved for this auxiliary call.","type":"string","default":""},"classifier_temperature":{"description":"Sampling temperature for the classifier call. Default: `0.0` (the\ndecision should be deterministic).","type":"number","format":"double","default":0.0},"classifier_timeout_secs":{"description":"Per-call timeout (seconds) for the Tier-2 classifier. On timeout the\npre-gate fails open (enters the loop). Default: `5`.","type":"integer","format":"uint64","default":5,"minimum":0}}},"StorageConfig":{"description":"Persistent storage configuration (`[storage]` section).","type":"object","properties":{"provider":{"description":"Storage provider settings (e.g. sqlite, postgres).","$ref":"#/$defs/StorageProviderSection","default":{"config":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}}},"StorageProviderConfig":{"description":"Storage provider backend configuration (e.g. postgres connection details).","type":"object","properties":{"connect_timeout_secs":{"description":"Optional timeout in seconds for *establishing* a connection to a remote\nprovider. Defaults to 15s when unset.\n\nThis bounds the TCP/startup handshake only. Statement execution is never\nbounded (no `statement_timeout` is applied) because long-running queries\nare normal for agent workloads.","type":["integer","null"],"format":"uint64","default":null,"minimum":0},"db_url":{"description":"Connection URL for remote providers.\nAccepts legacy aliases: dbURL, database_url, databaseUrl.","type":["string","null"],"default":null},"pool_max_size":{"description":"Maximum number of pooled connections for remote providers.\n\nThe pool exists for connection *reuse*, not to throttle work: a caller\nthat finds the pool saturated queues for a connection rather than\nfailing. Size it against the database's own `max_connections` budget,\nnot against expected task concurrency.","type":"integer","format":"uint","default":32,"minimum":0},"provider":{"description":"Storage engine key (e.g. \"postgres\", \"sqlite\").","type":"string","default":""},"schema":{"description":"Database schema for SQL backends.","type":"string","default":"public"},"table":{"description":"Table name for memory entries.","type":"string","default":"memories"}}},"StorageProviderSection":{"description":"Wrapper for the storage provider configuration section.","type":"object","properties":{"config":{"description":"Storage provider backend settings.","$ref":"#/$defs/StorageProviderConfig","default":{"connect_timeout_secs":null,"db_url":null,"pool_max_size":32,"provider":"","schema":"public","table":"memories"}}}},"StreamMode":{"description":"Streaming mode for channels that support progressive message updates.","oneOf":[{"description":"No streaming -- send the complete response as a single message (default).","type":"string","const":"off"},{"description":"Update a draft message with every flush interval.","type":"string","const":"partial"}]},"TailscaleTunnelConfig":{"type":"object","properties":{"funnel":{"description":"Use Tailscale Funnel (public internet) vs Serve (tailnet only)","type":"boolean","default":false},"hostname":{"description":"Optional hostname override","type":["string","null"]}}},"TaskRoutingConfig":{"description":"Lightweight pre-LLM task routing.","type":"object","properties":{"default_intent":{"description":"Fallback intent when no rule matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"rules":{"description":"Rules evaluated in descending priority order.","type":"array","default":[],"items":{"$ref":"#/$defs/TaskRoutingRule"}}}},"TaskRoutingIntentConfig":{"description":"Task-routing default and rule intent.","type":"string","enum":["simple","delegate","stream"]},"TaskRoutingRule":{"description":"A single task-routing rule.","type":"object","properties":{"intent":{"description":"Route intent to apply when a keyword matches.","$ref":"#/$defs/TaskRoutingIntentConfig","default":"simple"},"keywords":{"description":"Case-insensitive substring matches.","type":"array","default":[],"items":{"type":"string"}},"model_hint":{"description":"Optional model hint/raw model for non-delegated requests.","type":["string","null"],"default":null},"priority":{"description":"Higher priority rules are checked first.","type":"integer","format":"int32","default":0},"sub_agent_model":{"description":"Optional raw sub-agent model override for delegated tasks.","type":["string","null"],"default":null}}},"TelegramConfig":{"description":"Telegram bot channel configuration.","type":"object","properties":{"allowed_users":{"description":"Allowed Telegram user IDs or usernames. Empty = deny all.","type":"array","items":{"type":"string"}},"bot_token":{"description":"Telegram Bot API token (from @BotFather).","type":"string"},"draft_update_interval_ms":{"description":"Minimum interval (ms) between draft message edits to avoid rate limits.","type":"integer","format":"uint64","default":1000,"minimum":0},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in groups.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"interrupt_on_new_message":{"description":"When true, a newer Telegram message from the same sender in the same chat\ncancels the in-flight request and starts a fresh response with preserved history.","type":"boolean","default":false},"mention_only":{"description":"When true, only respond to messages that @-mention the bot in groups.\nDirect messages are always processed.","type":"boolean","default":false},"stream_mode":{"description":"Streaming mode for progressive response delivery via message edits.","$ref":"#/$defs/StreamMode","default":"off"}},"required":["bot_token","allowed_users"]},"ToolCallDialectSetting":{"description":"The tool-call grammars an operator may declare for an endpoint.","oneOf":[{"description":"Only the native `tool_calls` array is a tool call (the default).","type":"string","const":"native"},{"description":"Additionally read `{json}` from the content,\nfor a tool name the request registered.","type":"string","const":"xml_function_tags"}]},"ToolSchemaDialectSetting":{"description":"The tool-schema dialects an operator may declare for an endpoint.\n\n`gemini` and `anthropic` are deliberately absent: they name the fixed\nrewrite of a provider family, which the constructed provider already\nreports, and declaring one for a single model of an endpoint would make\nargument validation looser than the document that model was shown.\nAdding a stripping dialect here would make the model-less\n`OpenAiCompatibleProvider::tool_schema_dialect` (still read by callers\nthat do not know the model) answer `Raw` for endpoints that mix it with\nundeclared models; callers that know the model are exact.","oneOf":[{"description":"The published document, byte for byte (the default).","type":"string","const":"raw"},{"description":"The endpoint rejects `allOf`/`anyOf`/`oneOf` at the root of a tool\nschema: a root `allOf` of plain object fragments is merged losslessly,\nand a request carrying any other root combinator fails before transport.","type":"string","const":"no_root_combinators"}]},"ToolTieringConfig":{"description":"Tool surface policy consumed by capability publication and decision admission.\n\nExplicit exclusions take precedence over direct-publication preferences.\nThe selected decision constrains the tools supplied to each model call.","type":"object","properties":{"always_exclude":{"description":"Tool names excluded from capability publication.","type":"array","default":[],"items":{"type":"string"}},"always_include":{"description":"Tool names preferred for direct publication, subject to admission gates.","type":"array","default":[],"items":{"type":"string"}},"channel_exclude":{"description":"Tool names hidden from IM channel sessions only, on top of `always_exclude`.\nDefault: empty (nothing is hidden); list tool names to hide them on channels.","type":"array","default":[],"items":{"type":"string"}},"defer_unlisted":{"description":"Operator option for the tools outside the core set.\n- `None` (default): publish every available tool, unless their definitions would take more than a quarter of the model's context window; then the turn defers them, as `Some(true)` does.\n- `Some(true)`: publish only the core tools plus `always_include` and leave every other tool behind `capability_search` and its exact name.\n- `Some(false)`: always publish every available tool, whatever the window.","type":["boolean","null"],"default":null}}},"TunnelConfig":{"description":"Tunnel configuration for exposing the gateway publicly (`[tunnel]` section).\n\nSupported providers: `\"none\"` (default), `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, `\"custom\"`.","type":"object","properties":{"cloudflare":{"description":"Cloudflare Tunnel configuration (used when `provider = \"cloudflare\"`).","anyOf":[{"$ref":"#/$defs/CloudflareTunnelConfig"},{"type":"null"}],"default":null},"custom":{"description":"Custom tunnel command configuration (used when `provider = \"custom\"`).","anyOf":[{"$ref":"#/$defs/CustomTunnelConfig"},{"type":"null"}],"default":null},"ngrok":{"description":"ngrok tunnel configuration (used when `provider = \"ngrok\"`).","anyOf":[{"$ref":"#/$defs/NgrokTunnelConfig"},{"type":"null"}],"default":null},"provider":{"description":"Tunnel provider: `\"none\"`, `\"cloudflare\"`, `\"tailscale\"`, `\"ngrok\"`, or `\"custom\"`. Default: `\"none\"`.\n\nFails closed: a `[tunnel]` section that omits this key leaves the\ngateway unexposed.","type":"string","default":"none"},"tailscale":{"description":"Tailscale Funnel/Serve configuration (used when `provider = \"tailscale\"`).","anyOf":[{"$ref":"#/$defs/TailscaleTunnelConfig"},{"type":"null"}],"default":null}}},"UserPolicyConfig":{"description":"Startup user policy entry (`[[user_policies]]`).","type":"object","properties":{"blocked_patterns":{"type":"array","default":[],"items":{"type":"string"}},"projects":{"type":"array","default":[],"items":{"type":"string"}},"role":{"type":"string","default":"guest"},"user_id":{"type":"string"},"visibility_ceiling":{"type":"string","default":"private"}},"required":["user_id"]},"WacliConfig":{"description":"wacli (official) channel configuration.\n\nConnect OpenPRX to WhatsApp via the **official** `steipete/wacli` real-time\ninterface: inbound via `sync --webhook` (signed HTTP POST) and outbound via\nthe `wacli send` CLI. The legacy self-maintained JSON-RPC daemon (`host` /\n`port`) is no longer supported.\n\nDeployment (run alongside PRX, e.g. a systemd user service):\n```text\nwacli sync --follow \\\n --webhook http://127.0.0.1:16868/wacli \\\n --webhook-secret \\\n --store ~/.wacli\n```\n\nExample TOML:\n```toml\n[channels_config.wacli]\nwebhook_listen = \"127.0.0.1:16868\"\nwebhook_path = \"/wacli\"\nwebhook_secret = \"\" # must match --webhook-secret\nstore_dir = \"/prx_workspace/.wacli\"\nbot_jid = \"1234567890@s.whatsapp.net\"\nbot_number = \"1234567890\"\nself_chat_mode = true\nallowed_from = [\"*\"]\ngroup_reply_mode = \"smart\"\n```","type":"object","properties":{"allow_unsigned_loopback":{"description":"Allow processing unsigned requests when bound to a loopback address.\nDefaults to false (signature verification required).","type":"boolean","default":false},"allowed_from":{"description":"Sender JID allowlist. Use `[\"*\"]` to accept all senders.\nJIDs look like `1234567890@s.whatsapp.net` for individuals or\n`1234567890-1234567890@g.us` for groups.","type":"array","default":["*"],"items":{"type":"string"}},"bot_jid":{"description":"Bot's own JID, used for reply-to-bot mention detection.","type":["string","null"],"default":null},"bot_lid":{"description":"The bot's own WhatsApp LID, used for @mention detection inside groups.\nAccepts either the bare digits `263767598346470` or the full\n`263767598346470@lid` form; a device suffix such as `:3` is stripped.","type":["string","null"],"default":null},"bot_number":{"description":"Bot's own phone number (digits), used for `@` mention detection.","type":["string","null"],"default":null},"cli_path":{"description":"Path to the `wacli` binary used for outbound sends. When `None`, `wacli`\nis resolved from `PATH`.","type":["string","null"],"default":null},"group_reply_mode":{"description":"Smart group-reply mode. When `None`, derived from `mention_only`.","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"host":{"description":"REMOVED: legacy JSON-RPC daemon host. Retained only to detect and reject\nstale configs with a clear migration error in [`WacliConfig::validate`].","type":["string","null"],"writeOnly":true},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"outbound_media_workspace_only":{"description":"Confine **outbound** media markers (`[IMAGE:…]` and friends) to the\nworkspace again.\n\nDefaults to `false`: a marker may name any path the daemon can read,\nbecause agents attach files from the operator's own working directories.\nSet it to `true` to restore the workspace-confined, `O_NOFOLLOW` loader,\nafter which a marker pointing outside the workspace degrades to literal\ntext. It changes nothing else: the SSRF policy for `http(s)` sources, the\nper-category size caps, byte-derived typing, the private temp copy handed\nto wacli, and the `INFO` audit log all apply in both modes.","type":"boolean","default":false},"port":{"description":"REMOVED: legacy JSON-RPC daemon port. See `host`.","type":["integer","null"],"format":"uint16","maximum":65535,"minimum":0,"writeOnly":true},"self_chat_mode":{"description":"Treat messages authored by the linked account in WhatsApp's Message\nYourself chat as owner input. Disabled by default. When enabled, PRX\ninvokes wacli's experimental self-send path and suppresses reply echoes\nby their outbound message IDs.","type":"boolean","default":false},"store_dir":{"description":"wacli store directory passed as `--store` on outbound sends and used as\na read-only chat-title fallback for older webhook payloads.","type":["string","null"],"default":null},"webhook_listen":{"description":"Address the inbound webhook server binds to (default: \"127.0.0.1:16868\").","type":"string","default":"127.0.0.1:16868"},"webhook_path":{"description":"HTTP path the webhook server serves (default: \"/wacli\").","type":"string","default":"/wacli"},"webhook_secret":{"description":"HMAC-SHA256 secret shared with `wacli sync --webhook-secret`. Required\nunless `allow_unsigned_loopback` is set.","type":["string","null"],"default":null}}},"WebSearchConfig":{"description":"Web search tool configuration (`[web_search]` section).","type":"object","properties":{"brave_api_key":{"description":"Brave Search API key (required if provider is \"brave\")","type":["string","null"],"default":null},"fetch_max_chars":{"description":"Maximum characters returned by `web_fetch` (default 10000)","type":"integer","format":"uint","default":50000,"minimum":0},"max_results":{"description":"Maximum results per search (1-20)","type":"integer","format":"uint","default":15,"minimum":0},"provider":{"description":"Search provider: \"duckduckgo\" (free, no API key) or \"brave\" (requires API key)","type":"string","default":"duckduckgo"},"timeout_secs":{"description":"Request timeout in seconds","type":"integer","format":"uint64","default":15,"minimum":0}}},"WebhookConfig":{"description":"Webhook channel configuration.","type":"object","properties":{"port":{"description":"Port to listen on for incoming webhooks.","type":"integer","format":"uint16","maximum":65535,"minimum":0},"secret":{"description":"Optional shared secret for webhook signature verification.","type":["string","null"]}},"required":["port"]},"WhatsAppConfig":{"description":"WhatsApp channel configuration (Cloud API or Web mode).\n\nSet `phone_number_id` for Cloud API mode, or `session_path` for Web mode.","type":"object","properties":{"access_token":{"description":"Access token from Meta Business Suite (Cloud API mode)","type":["string","null"],"default":null},"allowed_numbers":{"description":"Allowed phone numbers (E.164 format: +1234567890) or \"*\" for all","type":"array","default":[],"items":{"type":"string"}},"app_secret":{"description":"App secret from Meta Business Suite (for webhook signature verification)\nCan also be set via `OPENPRX_WHATSAPP_APP_SECRET` (legacy: `OPENPRX_WHATSAPP_APP_SECRET`) environment variable\nOnly used in Cloud API mode","type":["string","null"],"default":null},"dm_policy":{"description":"Direct-message policy.","$ref":"#/$defs/DmPolicy","default":"allowlist"},"group_allow_from":{"description":"Allowlisted group IDs used when `group_policy = \"allowlist\"`.","type":"array","default":[],"items":{"type":"string"}},"group_policy":{"description":"Group-message policy.","$ref":"#/$defs/GroupPolicy","default":"allowlist"},"group_reply_mode":{"description":"Group reply decision mode. When `None` (default), derived from\n`mention_only` for backward compatibility (`true => MentionOnly`,\n`false => Off`). Set to `smart` to let the model decide per-message\nwhether to reply or stay silent in WhatsApp group chats (`@g.us`).","anyOf":[{"$ref":"#/$defs/GroupReplyMode"},{"type":"null"}],"default":null},"mention_only":{"description":"When true, only process group messages that mention the bot.","type":"boolean","default":false},"pair_code":{"description":"Custom pair code for linking (Web mode, optional)\nLeave empty to let WhatsApp generate one","type":["string","null"],"default":null},"pair_phone":{"description":"Phone number for pair code linking (Web mode, optional)\nFormat: country code + number (e.g., \"15551234567\")\nIf not set, QR code pairing will be used","type":["string","null"],"default":null},"phone_number_id":{"description":"Phone number ID from Meta Business API (Cloud API mode)","type":["string","null"],"default":null},"read_pool_size":{"description":"Concurrent read connections against the Web-mode session database.\n\nThe session store is SQLite in WAL mode: readers run in parallel while\nwrites stay serialised, so this sizes the read side only. When unset the\nsize is derived from the available CPUs. Must be greater than 0 when\nset; a saturated pool makes callers wait, it never fails them.","type":["integer","null"],"format":"uint","default":null,"minimum":0},"session_path":{"description":"Session database path for WhatsApp Web client (Web mode)\nWhen set, enables native WhatsApp Web mode with wa-rs","type":["string","null"],"default":null},"verify_token":{"description":"Webhook verify token (you define this, Meta sends it back for verification)\nOnly used in Cloud API mode","type":["string","null"],"default":null},"ws_url":{"description":"WebSocket URL override (replaces WHATSAPP_WS_URL)","type":["string","null"],"default":null}}},"WorkspaceHooks":{"description":"Whether workspace `hooks.json` command hooks run\n(`security.workspace_hooks`).","oneOf":[{"description":"They do not run (the default); `prx doctor` and `hooks_status` say so.","type":"string","const":"off"},{"description":"They run, in a cleared environment and a dedicated directory beside\n`config.toml`.","type":"string","const":"on"}]},"WorkspaceMcpServers":{"description":"Which new MCP servers a workspace `mcp.json` may add\n(`mcp.workspace_servers`).","oneOf":[{"description":"None: a workspace file may only narrow the servers defined in\n`config.toml`.","type":"string","const":"off"},{"description":"HTTP servers (still refused when they target a private address).","type":"string","const":"http_only"},{"description":"HTTP servers and stdio servers started with a bare launcher from the\nfixed list, in the cleared launch environment.","type":"string","const":"stdio"}]},"XinConfig":{"description":"Configuration for the xin autonomous task engine (`[xin]`).","type":"object","properties":{"adopt_legacy_tasks":{"description":"Adopt orphaned, stale, non-recurring legacy tasks into lease-managed\ngoal/step records on startup (FIX-P2-16). Default: false (zero-breakage).","type":"boolean","default":false},"interval_minutes":{"description":"Tick interval in minutes (minimum 1). Default: 5.","type":"integer","format":"uint32","default":5,"minimum":0},"stale_timeout_minutes":{"description":"Minutes after which a running task is marked stale. Default: 60.","type":"integer","format":"uint32","default":60,"minimum":0}}},"AgentMessaging":{"description":"Owner-controlled inbound session messaging (enabled unless explicitly off).","type":"object","properties":{"inbound":{"type":"boolean","default":true}}}}} From 6eb9f6ddff56562294a37c06eb78bccc52626dc0 Mon Sep 17 00:00:00 2001 From: nn <1936834+g1e2x87@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:18:53 +0400 Subject: [PATCH 0161/1567] refactor(hooks): split src/hooks/mod.rs into one-responsibility files Pure move: the event types, hooks.json loading and validation, command launch, the delivery core, the queue and manager, and the control tools each get their own file. Bodies are unchanged; only visibility and use lines differ. The architecture scanners that pinned mod.rs now pin the new files. --- src/hooks/config.rs | 224 +++ src/hooks/event.rs | 101 + src/hooks/hook_core.rs | 301 +++ src/hooks/launch.rs | 182 ++ src/hooks/manager.rs | 261 +++ src/hooks/mod.rs | 2256 +--------------------- src/hooks/tests.rs | 957 +++++++++ src/hooks/tools.rs | 255 +++ tests/architecture_boundaries/labels.rs | 4 +- tests/architecture_boundaries/process.rs | 12 +- 10 files changed, 2310 insertions(+), 2243 deletions(-) create mode 100644 src/hooks/config.rs create mode 100644 src/hooks/event.rs create mode 100644 src/hooks/hook_core.rs create mode 100644 src/hooks/launch.rs create mode 100644 src/hooks/manager.rs create mode 100644 src/hooks/tests.rs create mode 100644 src/hooks/tools.rs diff --git a/src/hooks/config.rs b/src/hooks/config.rs new file mode 100644 index 000000000..eab020161 --- /dev/null +++ b/src/hooks/config.rs @@ -0,0 +1,224 @@ +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::collections::HashMap; +use std::io::Read; +use std::path::Path; + +use super::event::{HookEvent, normalize_event_name}; +use super::{DEFAULT_TIMEOUT_MS, HOOKS_JSON_FILE, MAX_ACTIONS, MAX_ARGS_PER_ACTION, MAX_ENV_PER_ACTION, MAX_HOOKS_FILE_BYTES, MAX_TIMEOUT_MS}; + +#[derive(Debug, Clone, Deserialize)] +pub(super) struct HookAction { + pub(super) command: String, + #[serde(default)] + pub(super) args: Vec, + #[serde(default)] + pub(super) env: HashMap, + #[serde(default)] + pub(super) cwd: Option, + #[serde(default)] + pub(super) timeout_ms: Option, + #[serde(default = "default_stdin_json")] + pub(super) stdin_json: bool, +} + +const fn default_stdin_json() -> bool { + true +} + +#[derive(Debug, Clone, Deserialize, Default)] +pub(super) struct HooksFile { + #[serde(default)] + timeout_ms: Option, + #[serde(default)] + hooks: HashMap>, +} + +#[derive(Debug, Clone)] +pub(super) struct HookConfig { + pub(super) timeout_ms: u64, + pub(super) hooks: HashMap>, +} + +impl Default for HookConfig { + fn default() -> Self { + Self { + timeout_ms: DEFAULT_TIMEOUT_MS, + hooks: HashMap::new(), + } + } +} + +#[derive(Debug, Clone, Default)] +pub(super) struct RuntimeState { + pub(super) config: HookConfig, + pub(super) hooks_json_digest: Option<[u8; 32]>, +} + +#[derive(Debug, Clone, Serialize)] +pub struct HookDiagnostics { + pub configured: bool, + pub valid: bool, + pub config_path: String, + pub timeout_ms: u64, + pub action_count: usize, + pub events: BTreeMap, + /// Private catalog identity for the effective hooks file. Not returned + /// through doctor/API diagnostics. + #[serde(skip)] + pub(crate) catalog_digest: Option<[u8; 32]>, + pub error: Option, + /// Whether the command hooks of this `hooks.json` run: only with + /// `security.workspace_hooks = "on"` in config.toml (HOOKS-ENV). + pub runs: bool, + /// When configured hooks do not run: why, with the one-line fix. + pub blocked: Option, +} + +/// The one line that allows workspace command hooks. +pub const WORKSPACE_HOOKS_OPT_IN: &str = "[security] workspace_hooks = \"on\""; + +/// How many command hooks the workspace `hooks.json` under +/// `workspace_dir` defines; `None` without one. Reads and validates the +/// file only (for `prx doctor`). +/// +/// # Errors +/// +/// An unreadable, oversized or invalid `hooks.json`. +pub fn workspace_hook_actions(workspace_dir: &Path) -> anyhow::Result> { + let Some(raw) = read_bounded_file(&workspace_dir.join(HOOKS_JSON_FILE), MAX_HOOKS_FILE_BYTES)? else { + return Ok(None); + }; + Ok(Some(parse_hook_config(&raw)?.hooks.values().map(Vec::len).sum())) +} + +/// Why the command hooks of a `hooks.json` holding `actions` actions do not +/// run, with the fix; `None` when there are none. +#[must_use] +pub fn blocked_hooks_note(actions: usize) -> Option { + (actions > 0).then(|| { + format!( + "{actions} workspace command hook(s) in hooks.json are not run: `security.workspace_hooks` is off. To \ + run them, add `{WORKSPACE_HOOKS_OPT_IN}` to config.toml (a high-risk change: the workspace can then \ + start programs that run as PRX's user)" + ) + }) +} + +/// What a change to the workspace hooks can do: the one risk +/// classification of `hooks.json` changes on every surface (`hooks_manage`, +/// the Gateway hooks API; D-096). The file tools classify any write of the +/// file as a launch-definition write, which is High as well. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum HookChange { + /// Installs, changes or runs a hook command: its program, arguments or + /// the event it runs on. + Command, + /// Only removes hooks or changes their limits: nothing new runs. + Restriction, +} + +impl HookChange { + /// The side-effect risk of this change. + #[must_use] + pub const fn risk(self) -> crate::security::policy::ResourceRiskLevel { + match self { + Self::Command => crate::security::policy::ResourceRiskLevel::High, + Self::Restriction => crate::security::policy::ResourceRiskLevel::Medium, + } + } + + /// The change a `hooks_manage` action makes; `None` for the actions + /// that only read. + #[must_use] + pub fn of_manage_action(action: &str) -> Option { + match action { + "test" | "replace" => Some(Self::Command), + "remove" => Some(Self::Restriction), + _ => None, + } + } +} + +pub(super) fn bounded_timeout(timeout_ms: u64) -> anyhow::Result { + if timeout_ms == 0 || timeout_ms > MAX_TIMEOUT_MS { + anyhow::bail!("hook timeout_ms must be between 1 and {MAX_TIMEOUT_MS}"); + } + Ok(timeout_ms) +} + +fn validate_hooks_file(file: &HooksFile) -> anyhow::Result<()> { + if let Some(timeout_ms) = file.timeout_ms { + bounded_timeout(timeout_ms)?; + } + let action_count = file.hooks.values().map(Vec::len).sum::(); + if action_count > MAX_ACTIONS { + anyhow::bail!("hooks.json has {action_count} actions; limit is {MAX_ACTIONS}"); + } + let mut normalized_events = std::collections::HashSet::new(); + for event in file.hooks.keys() { + let normalized = normalize_event_name(event); + if HookEvent::from_name(&normalized).is_none() { + anyhow::bail!("unknown hook event '{event}'"); + } + if !normalized_events.insert(normalized) { + anyhow::bail!("duplicate hook event after normalization: '{event}'"); + } + } + for actions in file.hooks.values() { + for action in actions { + if action.args.len() > MAX_ARGS_PER_ACTION { + anyhow::bail!("hook action has too many arguments"); + } + if action.env.len() > MAX_ENV_PER_ACTION { + anyhow::bail!("hook action has too many environment entries"); + } + if let Some(timeout_ms) = action.timeout_ms { + bounded_timeout(timeout_ms)?; + } + // A hook starts in its dedicated directory beside config.toml. + // `cwd` is workspace-controlled, so it is refused here rather + // than accepted and silently ignored. + if action.cwd.is_some() { + anyhow::bail!( + "hooks.json `cwd` is not supported: hooks always start in their dedicated `hooks/` directory \ + beside config.toml; remove `cwd` and use an absolute path or a workspace-relative `command`" + ); + } + } + } + Ok(()) +} + +pub(super) fn parse_hook_config(raw: &[u8]) -> anyhow::Result { + let parsed: HooksFile = serde_json::from_slice(raw)?; + validate_hooks_file(&parsed)?; + Ok(HookConfig { + timeout_ms: bounded_timeout(parsed.timeout_ms.unwrap_or(DEFAULT_TIMEOUT_MS))?, + hooks: parsed + .hooks + .into_iter() + .map(|(name, actions)| (normalize_event_name(&name), actions)) + .collect(), + }) +} + +pub(super) fn read_bounded_file(path: &Path, max_bytes: u64) -> anyhow::Result>> { + let mut file = match std::fs::File::open(path) { + Ok(file) => file, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(error.into()), + }; + let metadata = file.metadata()?; + if metadata.len() > max_bytes { + anyhow::bail!("{} exceeds {max_bytes} byte limit", path.display()); + } + let mut bytes = Vec::with_capacity(metadata.len() as usize); + std::io::Read::by_ref(&mut file) + .take(max_bytes + 1) + .read_to_end(&mut bytes)?; + if bytes.len() as u64 > max_bytes { + anyhow::bail!("{} exceeds {max_bytes} byte limit", path.display()); + } + Ok(Some(bytes)) +} diff --git a/src/hooks/event.rs b/src/hooks/event.rs new file mode 100644 index 000000000..3c7b295f1 --- /dev/null +++ b/src/hooks/event.rs @@ -0,0 +1,101 @@ +use serde_json::json; + +#[derive(Debug, Clone, Copy)] +pub enum HookEvent { + AgentStart, + AgentEnd, + LlmRequest, + LlmResponse, + ToolCallStart, + ToolCall, + TurnComplete, + Error, +} + +impl HookEvent { + pub const fn as_str(self) -> &'static str { + match self { + Self::AgentStart => "agent_start", + Self::AgentEnd => "agent_end", + Self::LlmRequest => "llm_request", + Self::LlmResponse => "llm_response", + Self::ToolCallStart => "tool_call_start", + Self::ToolCall => "tool_call", + Self::TurnComplete => "turn_complete", + Self::Error => "error", + } + } + + #[cfg(feature = "wasm-plugins")] + pub(super) const fn wasm_lifecycle_name(self) -> &'static str { + match self { + // The native hook name predates the public WASM lifecycle schema. + Self::AgentEnd => "agent_stop", + _ => self.as_str(), + } + } + + pub(super) const ALL: [Self; 8] = [ + Self::AgentStart, + Self::AgentEnd, + Self::LlmRequest, + Self::LlmResponse, + Self::ToolCallStart, + Self::ToolCall, + Self::TurnComplete, + Self::Error, + ]; + + pub(super) fn from_name(name: &str) -> Option { + let normalized = normalize_event_name(name); + Self::ALL.into_iter().find(|event| event.as_str() == normalized) + } +} + +pub(super) fn normalize_event_name(name: &str) -> String { + name.trim().to_ascii_lowercase().replace('-', "_") +} + +/// The payload keys that can quote a provider label: the label itself and the +/// error texts that name it. +const PROVIDER_LABEL_PAYLOAD_KEYS: [&str; 4] = ["provider", "message", "error", "error_message"]; + +/// `payload` as a hook script may see it: a provider label (a `custom:` URL +/// may carry `user:password@`) and the error texts that quote one are +/// redacted with the one helper every other surface uses. Borrowed when +/// nothing needed redacting. +pub(super) fn redacted_hook_payload(payload: &serde_json::Value) -> std::borrow::Cow<'_, serde_json::Value> { + let Some(object) = payload.as_object() else { + return std::borrow::Cow::Borrowed(payload); + }; + let needs_redaction = PROVIDER_LABEL_PAYLOAD_KEYS.iter().any(|key| { + object + .get(*key) + .and_then(serde_json::Value::as_str) + .is_some_and(|text| { + matches!( + crate::providers::redact_endpoint_userinfo(text), + std::borrow::Cow::Owned(_) + ) + }) + }); + if !needs_redaction { + return std::borrow::Cow::Borrowed(payload); + } + let mut redacted = object.clone(); + for key in PROVIDER_LABEL_PAYLOAD_KEYS { + if let Some(serde_json::Value::String(text)) = redacted.get_mut(key) + && let std::borrow::Cow::Owned(safe) = crate::providers::redact_endpoint_userinfo(text) + { + *text = safe; + } + } + std::borrow::Cow::Owned(serde_json::Value::Object(redacted)) +} + +pub fn payload_error(component: &str, message: &str) -> serde_json::Value { + json!({ + "component": component, + "message": message, + }) +} diff --git a/src/hooks/hook_core.rs b/src/hooks/hook_core.rs new file mode 100644 index 000000000..b1a01742b --- /dev/null +++ b/src/hooks/hook_core.rs @@ -0,0 +1,301 @@ +use parking_lot::RwLock; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use std::io::Write; +use std::path::PathBuf; +use std::time::Duration; + +use super::config::{HookDiagnostics, RuntimeState, blocked_hooks_note, parse_hook_config, read_bounded_file}; +use super::event::HookEvent; +#[cfg(feature = "wasm-plugins")] +use super::event::redacted_hook_payload; +use super::{MAX_HOOKS_FILE_BYTES, MAX_TIMEOUT_MS, WORKSPACE_HOOKS_OPT_IN}; + +/// Where a [`HookManager`] reads whether workspace command hooks run, and +/// the directory they start in. +pub(super) enum HookPolicy { + /// Fixed at construction. Without a configuration (a sub-agent's own + /// manager, an embedding caller) workspace hooks do not run. + Fixed { + allowed: bool, + launch_root: Option, + }, + /// The process configuration, read at every event, so turning the + /// opt-in off stops hooks at once. + Live(crate::config::SharedConfig), +} + +/// The hook state every delivery reads: configuration generation, launch +/// policy and the plugin runtime. Shared between the [`HookManager`] and its +/// background dispatcher. +pub struct HookCore { + pub(super) workspace_dir: PathBuf, + pub(super) hooks_json_path: PathBuf, + pub(super) policy: RwLock, + pub(super) media_artifacts: std::sync::Arc, + pub(super) state: RwLock, + /// Longest one event may occupy the dispatcher. + pub(super) delivery_bound: Duration, + /// Process-level WASM plugin runtime; it is the sole generation owner. + #[cfg(feature = "wasm-plugins")] + pub(super) plugin_runtime: tokio::sync::RwLock>>, +} + +/// Longest one event may occupy the dispatcher: the largest single hook +/// timeout. Every hook, WASM hook and event-bus subscriber of the event shares +/// it, so one that never completes costs the queue this much, not forever. +pub(super) const HOOK_EVENT_DELIVERY_BOUND: Duration = Duration::from_millis(MAX_TIMEOUT_MS); + +impl HookCore { + /// Whether workspace command hooks run now, and the root their + /// dedicated directory lies under. + pub(super) fn workspace_policy(&self) -> (bool, Option) { + match &*self.policy.read() { + HookPolicy::Fixed { allowed, launch_root } => (*allowed, launch_root.clone()), + HookPolicy::Live(shared) => { + let config = &shared.pin().effective; + ( + config.security.workspace_hooks == crate::config::WorkspaceHooks::On, + config + .config_path + .parent() + .filter(|dir| !dir.as_os_str().is_empty()) + .map(|dir| dir.join("hooks")), + ) + } + } + } + + pub fn media_artifacts(&self) -> std::sync::Arc { + self.media_artifacts.clone() + } + + /// Attach the sole process-level plugin runtime for lifecycle observation. + #[cfg(feature = "wasm-plugins")] + pub async fn set_plugin_runtime(&self, runtime: std::sync::Arc) { + *self.plugin_runtime.write().await = Some(runtime); + } + + /// Transform one shared agent-pipeline envelope through the current WASM + /// middleware generation. Invalid JSON output is isolated and the original + /// envelope is preserved so a plugin cannot corrupt the turn protocol. + /// + /// The guest is third-party code like a lifecycle hook, so it receives the + /// envelope through the same redaction: the `llm_request` and + /// `llm_response` stages name the serving provider, whose `custom:` label + /// may carry URL userinfo. The turn never reads the provider back from the + /// transformed envelope. + #[cfg(feature = "wasm-plugins")] + pub async fn process_wasm_middleware( + &self, + stage: crate::plugins::capabilities::middleware::MiddlewareStage, + envelope: serde_json::Value, + ) -> serde_json::Value { + let runtime = self.plugin_runtime.read().await.clone(); + let Some(runtime) = runtime else { + return envelope; + }; + let chain = runtime.middleware(); + if chain.is_empty() { + return envelope; + } + let original = redacted_hook_payload(&envelope).to_string(); + let transformed = chain.process(stage, &original).await; + match serde_json::from_str(&transformed) { + Ok(value) => value, + Err(error) => { + tracing::warn!( + stage = stage.as_str(), + error = %error, + "WASM middleware returned invalid JSON; preserving the original envelope" + ); + envelope + } + } + } + + pub fn diagnostics(&self) -> HookDiagnostics { + let error = self.refresh_if_changed().err().map(|error| error.to_string()); + let state = self.state.read(); + let events = state + .config + .hooks + .iter() + .map(|(event, actions)| (event.clone(), actions.len())) + .collect::>(); + let action_count = events.values().sum(); + let runs = self.workspace_policy().0; + HookDiagnostics { + configured: self.hooks_json_path.is_file(), + valid: error.is_none(), + config_path: self.hooks_json_path.display().to_string(), + timeout_ms: state.config.timeout_ms, + action_count, + events, + catalog_digest: state.hooks_json_digest, + error, + runs, + blocked: if runs { None } else { blocked_hooks_note(action_count) }, + } + } + + pub fn validate_config(&self, content: &str) -> anyhow::Result { + if content.len() as u64 > MAX_HOOKS_FILE_BYTES { + anyhow::bail!("hooks config exceeds {MAX_HOOKS_FILE_BYTES} byte limit"); + } + let config = parse_hook_config(content.as_bytes())?; + let events = config + .hooks + .iter() + .map(|(event, actions)| (event.clone(), actions.len())) + .collect::>(); + let action_count = events.values().sum(); + let runs = self.workspace_policy().0; + Ok(HookDiagnostics { + configured: false, + valid: true, + config_path: self.hooks_json_path.display().to_string(), + timeout_ms: config.timeout_ms, + action_count, + events, + catalog_digest: Some(Sha256::digest(content.as_bytes()).into()), + error: None, + runs, + blocked: if runs { None } else { blocked_hooks_note(action_count) }, + }) + } + + pub fn replace_config(&self, content: &str) -> anyhow::Result { + let _ = self.validate_config(content)?; + std::fs::create_dir_all(&self.workspace_dir)?; + let mut candidate = tempfile::Builder::new() + .prefix(".hooks-json-") + .suffix(".tmp") + .tempfile_in(&self.workspace_dir)?; + candidate.write_all(content.as_bytes())?; + candidate.flush()?; + candidate.persist(&self.hooks_json_path).map_err(|error| error.error)?; + self.refresh_if_changed()?; + Ok(self.diagnostics()) + } + + pub fn remove_config(&self) -> anyhow::Result> { + if !self.hooks_json_path.exists() { + *self.state.write() = RuntimeState::default(); + return Ok(None); + } + let trash_dir = self.workspace_dir.join(".hooks-trash"); + std::fs::create_dir_all(&trash_dir)?; + let backup = trash_dir.join(format!("hooks-{}.json", uuid::Uuid::new_v4())); + std::fs::rename(&self.hooks_json_path, &backup)?; + *self.state.write() = RuntimeState::default(); + Ok(Some(backup)) + } + + /// [`Self::deliver`] under the per-event bound; on expiry the event is + /// abandoned (logged) so the next one is delivered. + pub(super) async fn deliver_bounded(&self, event: HookEvent, payload: &serde_json::Value) { + let progress = std::sync::atomic::AtomicUsize::new(0); + let total = std::sync::atomic::AtomicUsize::new(0); + if tokio::time::timeout(self.delivery_bound, self.deliver(event, payload, &total, &progress)) + .await + .is_err() + { + let planned = total.load(std::sync::atomic::Ordering::Relaxed); + let finished = progress.load(std::sync::atomic::Ordering::Relaxed); + tracing::warn!( + event = event.as_str(), + actions_total = planned, + actions_unfinished = planned.saturating_sub(finished), + bound_ms = u64::try_from(self.delivery_bound.as_millis()).unwrap_or(u64::MAX), + "hook delivery exceeded its bound and was abandoned" + ); + } + } + + /// Deliver one already-redacted event: command hooks first, then WASM + /// lifecycle hooks and the plugin event bus. Runs on the dispatcher, never + /// on a turn. + async fn deliver( + &self, + event: HookEvent, + payload: &serde_json::Value, + total: &std::sync::atomic::AtomicUsize, + finished: &std::sync::atomic::AtomicUsize, + ) { + if let Err(err) = self.refresh_if_changed() { + tracing::warn!(error = %err, "hooks refresh failed"); + } else { + let (timeout_ms, actions) = { + let state = self.state.read(); + ( + state.config.timeout_ms, + state.config.hooks.get(event.as_str()).cloned().unwrap_or_default(), + ) + }; + + let (allowed, _) = self.workspace_policy(); + if !actions.is_empty() && !allowed { + tracing::warn!( + event = event.as_str(), + actions = actions.len(), + "workspace command hooks are not run: security.workspace_hooks is off; add `{}` to \ + config.toml to run them", + WORKSPACE_HOOKS_OPT_IN + ); + } else if !actions.is_empty() { + // Progress lets the event bound say how many actions it cut off. + total.store(actions.len(), std::sync::atomic::Ordering::Relaxed); + for action in actions { + if let Err(err) = self.run_action(event, payload, timeout_ms, &action).await { + tracing::warn!( + event = event.as_str(), + command = action.command, + error = %err, + "hook execution failed" + ); + } + finished.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } + } + + // Fire WASM hooks and bridge the lifecycle topic through the same process runtime. + #[cfg(feature = "wasm-plugins")] + { + let runtime = self.plugin_runtime.read().await.clone(); + if let Some(runtime) = runtime { + let payload_str = payload.to_string(); + let topic = format!("prx.lifecycle.{}", event.wasm_lifecycle_name()); + runtime.emit_hook(&topic, &payload_str).await; + if let Err(error) = runtime.event_bus().publish(&topic, &payload_str).await { + tracing::debug!(topic = %topic, error = %error, "event bus lifecycle bridge error"); + } + } + } + } + + pub(super) fn refresh_if_changed(&self) -> anyhow::Result<()> { + let Some(raw) = read_bounded_file(&self.hooks_json_path, MAX_HOOKS_FILE_BYTES)? else { + let mut state = self.state.write(); + if state.hooks_json_digest.is_some() { + *state = RuntimeState::default(); + } + return Ok(()); + }; + + let digest: [u8; 32] = Sha256::digest(&raw).into(); + if self.state.read().hooks_json_digest == Some(digest) { + return Ok(()); + } + + let config = parse_hook_config(&raw)?; + + // Candidate parsing and validation finish before this single generation swap. + *self.state.write() = RuntimeState { + config, + hooks_json_digest: Some(digest), + }; + Ok(()) + } +} diff --git a/src/hooks/launch.rs b/src/hooks/launch.rs new file mode 100644 index 000000000..6801a2e95 --- /dev/null +++ b/src/hooks/launch.rs @@ -0,0 +1,182 @@ +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::time::Duration; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::process::Command; + +use super::config::{HookAction, bounded_timeout}; +use super::hook_core::HookCore; +use super::event::{HookEvent, redacted_hook_payload}; +use super::{MAX_PAYLOAD_BYTES, MAX_STDERR_BYTES, MAX_STDERR_CHARS}; + +impl HookCore { + pub(super) async fn run_action( + &self, + event: HookEvent, + payload: &serde_json::Value, + default_timeout_ms: u64, + action: &HookAction, + ) -> anyhow::Result<()> { + let command = action.command.trim(); + if command.is_empty() { + anyhow::bail!("hook command is empty"); + } + let timeout_ms = bounded_timeout(action.timeout_ms.unwrap_or(default_timeout_ms))?; + + // `emit` redacted the payload; this redacts again for direct callers + // and is a borrow when there is nothing left to redact. + let payload_json = redacted_hook_payload(payload).to_string(); + if payload_json.len() > MAX_PAYLOAD_BYTES { + anyhow::bail!( + "hook payload is {} bytes; limit is {MAX_PAYLOAD_BYTES}", + payload_json.len() + ); + } + // The dedicated directory the hook starts in: beside config.toml, + // never the workspace (which the agent's file tools can write) and + // never PRX's own working directory (HOOKS-ENV). A `cwd` in + // hooks.json is workspace-controlled and is not used. + let (_, launch_root) = self.workspace_policy(); + let Some(launch_root) = launch_root else { + anyhow::bail!( + "workspace hooks have no launch directory: PRX starts them in `hooks/` beside config.toml, and this \ + process has no configuration directory" + ); + }; + let working_dir = crate::config::mcp_launch::launch_directory(&launch_root, "workspace-hooks", None) + .map_err(|error| anyhow::anyhow!(error))?; + crate::config::mcp_launch::prepare_launch_directory(&launch_root, &working_dir).await?; + // A command with a path separator is workspace content (a script in + // the workspace): resolve it against the workspace, since the hook + // no longer starts there. A bare name is looked up in `PATH`. + let program = if command.contains(['/', '\\']) && !Path::new(command).is_absolute() { + self.workspace_dir.join(command) + } else { + PathBuf::from(command) + }; + + // A cleared environment through the shared launch builder: the + // launch allowlist of PRX's environment plus the hook's own `env`, + // without the variables a workspace may not set (HOOKS-ENV, D-045). + let (environment, dropped) = crate::config::mcp_launch::workspace_launch_environment(&action.env); + if !dropped.is_empty() { + tracing::warn!( + event = event.as_str(), + dropped = ?dropped, + "hook environment variables a workspace may not set were dropped" + ); + } + let mut cmd = Command::new(&program); + cmd.args(&action.args); + cmd.env_clear(); + cmd.envs(environment); + cmd.current_dir(&working_dir); + cmd.env("ZERO_HOOK_EVENT", event.as_str()); + + // Avoid execve argv+env size overflow for large payloads. + const MAX_ENV_PAYLOAD_BYTES: usize = 8 * 1024; + if payload_json.len() <= MAX_ENV_PAYLOAD_BYTES { + cmd.env("ZERO_HOOK_PAYLOAD", &payload_json); + } else { + cmd.env("ZERO_HOOK_PAYLOAD", ""); + cmd.env("ZERO_HOOK_PAYLOAD_TRUNCATED", "1"); + } + + // NamedTempFile is created with restrictive permissions and removes itself on every exit. + let mut payload_file = tempfile::Builder::new() + .prefix("openprx-hook-payload-") + .suffix(".json") + .tempfile()?; + payload_file.write_all(payload_json.as_bytes())?; + payload_file.flush()?; + cmd.env("ZERO_HOOK_PAYLOAD_FILE", payload_file.path()); + + if action.stdin_json { + cmd.stdin(std::process::Stdio::piped()); + } + cmd.stdout(std::process::Stdio::null()); + cmd.stderr(std::process::Stdio::piped()); + + let mut child = crate::runtime::shell_process::spawn_managed_shell_child(cmd)?; + let deadline = tokio::time::Instant::now() + Duration::from_millis(timeout_ms); + + let stderr = child.take_stderr(); + let stderr_reader = tokio::spawn(async move { + let Some(stderr) = stderr else { + return std::io::Result::Ok(Vec::new()); + }; + let mut bytes = Vec::new(); + stderr.take(MAX_STDERR_BYTES + 1).read_to_end(&mut bytes).await?; + Ok(bytes) + }); + + if action.stdin_json { + if let Some(mut stdin) = child.take_stdin() { + let write_result = tokio::time::timeout_at(deadline, stdin.write_all(payload_json.as_bytes())).await; + match write_result { + Err(_) => { + let _ = child.terminate_and_reap().await; + let _ = stderr_reader.await; + anyhow::bail!("hook timed out while writing stdin"); + } + Ok(Err(error)) if error.kind() != std::io::ErrorKind::BrokenPipe => { + let _ = child.terminate_and_reap().await; + let _ = stderr_reader.await; + return Err(error.into()); + } + Ok(_) => {} + } + } + } + + let status = match tokio::time::timeout_at(deadline, child.wait()).await { + Ok(Ok(status)) => status, + Ok(Err(error)) => { + let _ = child.terminate_and_reap().await; + let _ = stderr_reader.await; + return Err(error.into()); + } + Err(_) => { + let _ = child.terminate_and_reap().await; + let _ = stderr_reader.await; + anyhow::bail!("hook timed out after {timeout_ms} ms"); + } + }; + let mut stderr = stderr_reader.await??; + child.mark_complete(); + let stderr_truncated = stderr.len() > MAX_STDERR_BYTES as usize; + stderr.truncate(MAX_STDERR_BYTES as usize); + + if status.success() { + return Ok(()); + } + + let stderr = String::from_utf8_lossy(&stderr); + let mut stderr = truncate_for_log(stderr.as_ref(), MAX_STDERR_CHARS); + if stderr_truncated { + stderr.push_str(" [truncated]"); + } + anyhow::bail!( + "hook exited with status {}{}", + status, + if stderr.is_empty() { + String::new() + } else { + format!(", stderr: {stderr}") + } + ) + } +} + +pub(super) fn truncate_for_log(input: &str, max_chars: usize) -> String { + let char_count = input.chars().count(); + if char_count <= max_chars { + return input.to_string(); + } + let mut out = String::new(); + for c in input.chars().take(max_chars) { + out.push(c); + } + out.push_str("..."); + out +} diff --git a/src/hooks/manager.rs b/src/hooks/manager.rs new file mode 100644 index 000000000..20f955f65 --- /dev/null +++ b/src/hooks/manager.rs @@ -0,0 +1,261 @@ +use std::time::Duration; +use parking_lot::RwLock; +use std::path::PathBuf; + +use super::config::RuntimeState; +use super::hook_core::{HOOK_EVENT_DELIVERY_BOUND, HookCore, HookPolicy}; +use super::event::{HookEvent, redacted_hook_payload}; +use super::HOOKS_JSON_FILE; + +/// Hook events the queue holds before further events are dropped and counted. +pub const HOOK_QUEUE_CAPACITY: usize = 1024; + +/// Upper bound on the wait for queued events at shutdown. +pub const HOOK_DRAIN_BOUND: Duration = Duration::from_secs(3); + +pub(super) enum DispatchMessage { + Event { + event: HookEvent, + payload: serde_json::Value, + }, + Flush(tokio::sync::oneshot::Sender<()>), +} + +#[derive(Default)] +pub(super) struct DispatchStats { + queued: std::sync::atomic::AtomicU64, + delivered: std::sync::atomic::AtomicU64, + dropped: std::sync::atomic::AtomicU64, + /// Woken after every finished delivery (test waits). + #[cfg(test)] + delivery_signal: tokio::sync::Notify, +} + +/// Counters of one manager's background dispatcher. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct HookDispatchStats { + /// Events accepted into the queue. + pub queued: u64, + /// Events whose command, WASM and event-bus delivery finished. + pub delivered: u64, + /// Events dropped because the queue was full or closed. + pub dropped: u64, +} + +/// Observe-only hook manager. `emit` queues the event and returns at once; a +/// single background worker per manager delivers events in emit order, so +/// order is kept for every session and turn, and a slow hook never delays a +/// turn. +pub struct HookManager { + pub(super) core: std::sync::Arc, + pub(super) queue: std::sync::OnceLock>, + pub(super) capacity: usize, + pub(super) stats: std::sync::Arc, +} + +impl std::ops::Deref for HookManager { + type Target = HookCore; + + fn deref(&self) -> &HookCore { + &self.core + } +} + +impl HookManager { + pub fn new(workspace_dir: PathBuf) -> Self { + Self::with_queue_capacity(workspace_dir, HOOK_QUEUE_CAPACITY) + } + + pub(super) fn with_queue_capacity(workspace_dir: PathBuf, capacity: usize) -> Self { + let media_artifacts = crate::media::MediaArtifactOwner::for_workspace(&workspace_dir); + Self { + core: std::sync::Arc::new(HookCore { + hooks_json_path: workspace_dir.join(HOOKS_JSON_FILE), + workspace_dir, + policy: RwLock::new(HookPolicy::Fixed { + allowed: false, + launch_root: None, + }), + media_artifacts, + state: RwLock::new(RuntimeState::default()), + delivery_bound: HOOK_EVENT_DELIVERY_BOUND, + #[cfg(feature = "wasm-plugins")] + plugin_runtime: tokio::sync::RwLock::new(None), + }), + queue: std::sync::OnceLock::new(), + capacity: capacity.max(1), + stats: std::sync::Arc::new(DispatchStats::default()), + } + } + + /// Read whether workspace command hooks run + /// (`security.workspace_hooks`) from the live process configuration at + /// every event, and start them in `hooks/` beside `config.toml` + /// (HOOKS-ENV). Without this, workspace command hooks do not run. + #[must_use] + pub fn with_config(self, shared: crate::config::SharedConfig) -> Self { + *self.core.policy.write() = HookPolicy::Live(shared); + self + } + + /// Shorten the per-event delivery bound (tests). + #[cfg(test)] + #[must_use] + pub(crate) fn with_delivery_bound(mut self, bound: Duration) -> Self { + if let Some(core) = std::sync::Arc::get_mut(&mut self.core) { + core.delivery_bound = bound; + } + self + } + + /// Workspace hooks run, starting under `launch_root` (tests). + #[cfg(test)] + #[must_use] + pub(crate) fn allowing_workspace_hooks(self, launch_root: PathBuf) -> Self { + *self.core.policy.write() = HookPolicy::Fixed { + allowed: true, + launch_root: Some(launch_root), + }; + self + } +} + +impl HookManager { + /// Queue a test event and wait (bounded) until it was delivered, so the + /// operator's explicit test reports a finished delivery. + pub async fn test_event(&self, event: HookEvent, payload: serde_json::Value) { + self.emit(event, payload).await; + self.drain(HOOK_DRAIN_BOUND).await; + } + + /// Queue `event` for background delivery and return at once; the turn + /// never waits on a hook. The payload is redacted here, once, for every + /// consumer (command hooks, WASM lifecycle hooks, the plugin event bus), + /// so no secret waits in the queue. When the queue is full the event is + /// dropped and counted (see [`Self::dispatch_stats`]). + pub fn emit(&self, event: HookEvent, payload: serde_json::Value) -> impl std::future::Future + use<> { + let owned = match redacted_hook_payload(&payload) { + std::borrow::Cow::Owned(redacted) => Some(redacted), + std::borrow::Cow::Borrowed(_) => None, + }; + let payload = owned.unwrap_or(payload); + let sent = self.sender().map_or(Err("no async runtime"), |sender| { + sender + .try_send(DispatchMessage::Event { event, payload }) + .map_err(|error| match error { + tokio::sync::mpsc::error::TrySendError::Full(_) => "queue full", + tokio::sync::mpsc::error::TrySendError::Closed(_) => "dispatcher stopped", + }) + }); + match sent { + Ok(()) => { + self.stats.queued.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + Err(reason) => { + let dropped = self.stats.dropped.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + // Logged on the first drop and then every 100th, so a stalled + // hook cannot also flood the log. + if dropped == 1 || dropped.is_multiple_of(100) { + tracing::warn!( + event = event.as_str(), + reason, + dropped_total = dropped, + capacity = self.capacity, + "hook event dropped" + ); + } + } + } + std::future::ready(()) + } + + /// Counters of the background dispatcher. + #[must_use] + pub fn dispatch_stats(&self) -> HookDispatchStats { + HookDispatchStats { + queued: self.stats.queued.load(std::sync::atomic::Ordering::Relaxed), + delivered: self.stats.delivered.load(std::sync::atomic::Ordering::Relaxed), + dropped: self.stats.dropped.load(std::sync::atomic::Ordering::Relaxed), + } + } + + /// Wait until every event queued before this call was delivered, but at + /// most `bound`. Returns whether the queue was fully drained in time; + /// events still queued at the bound keep being delivered while the + /// runtime lives. The shutdown path calls this with [`HOOK_DRAIN_BOUND`]. + pub async fn drain(&self, bound: Duration) -> bool { + if self.queue.get().is_none() { + return true; + } + let (done, delivered) = tokio::sync::oneshot::channel(); + let wait = async { + let Some(sender) = self.sender() else { + return false; + }; + if sender.send(DispatchMessage::Flush(done)).await.is_err() { + return false; + } + delivered.await.is_ok() + }; + tokio::time::timeout(bound, wait).await.unwrap_or(false) + } + + /// Drain at process or component shutdown: wait at most + /// [`HOOK_DRAIN_BOUND`] and log what is abandoned. Every owner of a live + /// manager calls this on its exit path. + pub async fn drain_for_shutdown(&self) { + if !self.drain(HOOK_DRAIN_BOUND).await { + tracing::warn!( + bound_secs = HOOK_DRAIN_BOUND.as_secs(), + "hook events were still queued at shutdown; the rest are abandoned" + ); + } + } + + /// Wait until `count` events were delivered in total (tests whose + /// producer enqueues from a spawned task, where `drain` could run first). + #[cfg(test)] + pub(crate) async fn wait_delivered(&self, count: u64) { + loop { + let signal = self.stats.delivery_signal.notified(); + tokio::pin!(signal); + signal.as_mut().enable(); + if self.stats.delivered.load(std::sync::atomic::Ordering::Relaxed) >= count { + return; + } + signal.await; + } + } + + /// The queue's sender; the single worker starts with the first event. + /// `None` outside a tokio runtime, where no worker can start (the event is + /// dropped and counted rather than panicking the caller). + fn sender(&self) -> Option<&tokio::sync::mpsc::Sender> { + if let Some(sender) = self.queue.get() { + return Some(sender); + } + let runtime = tokio::runtime::Handle::try_current().ok()?; + Some(self.queue.get_or_init(|| { + let (tx, mut rx) = tokio::sync::mpsc::channel::(self.capacity); + let core = std::sync::Arc::clone(&self.core); + let stats = std::sync::Arc::clone(&self.stats); + runtime.spawn(async move { + while let Some(message) = rx.recv().await { + match message { + DispatchMessage::Event { event, payload } => { + core.deliver_bounded(event, &payload).await; + stats.delivered.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + #[cfg(test)] + stats.delivery_signal.notify_waiters(); + } + DispatchMessage::Flush(done) => { + // The waiter may have given up at its bound. + let _ = done.send(()); + } + } + } + }); + tx + })) + } +} diff --git a/src/hooks/mod.rs b/src/hooks/mod.rs index cbfd78b13..8a7099de1 100644 --- a/src/hooks/mod.rs +++ b/src/hooks/mod.rs @@ -1,15 +1,23 @@ -use async_trait::async_trait; -use parking_lot::RwLock; -use serde::{Deserialize, Serialize}; -use serde_json::json; -use sha2::{Digest, Sha256}; -use std::collections::BTreeMap; -use std::collections::HashMap; -use std::io::{Read, Write}; -use std::path::{Path, PathBuf}; -use std::time::Duration; -use tokio::io::{AsyncReadExt, AsyncWriteExt}; -use tokio::process::Command; +//! Lifecycle hooks: the event types, the workspace `hooks.json`, command +//! launch, the queued delivery and the manager that owns them. + +mod config; +mod hook_core; +mod event; +mod launch; +mod manager; +mod tools; + +#[cfg(test)] +mod tests; + +pub use config::{ + HookChange, HookDiagnostics, WORKSPACE_HOOKS_OPT_IN, blocked_hooks_note, workspace_hook_actions, +}; +pub use event::{HookEvent, payload_error}; +pub use manager::HookManager; +#[cfg(test)] +use launch::truncate_for_log; const HOOKS_JSON_FILE: &str = "hooks.json"; const DEFAULT_TIMEOUT_MS: u64 = 5_000; @@ -21,2227 +29,3 @@ const MAX_STDERR_CHARS: usize = 400; const MAX_ACTIONS: usize = 256; const MAX_ARGS_PER_ACTION: usize = 128; const MAX_ENV_PER_ACTION: usize = 128; - -#[derive(Debug, Clone, Copy)] -pub enum HookEvent { - AgentStart, - AgentEnd, - LlmRequest, - LlmResponse, - ToolCallStart, - ToolCall, - TurnComplete, - Error, -} - -impl HookEvent { - pub const fn as_str(self) -> &'static str { - match self { - Self::AgentStart => "agent_start", - Self::AgentEnd => "agent_end", - Self::LlmRequest => "llm_request", - Self::LlmResponse => "llm_response", - Self::ToolCallStart => "tool_call_start", - Self::ToolCall => "tool_call", - Self::TurnComplete => "turn_complete", - Self::Error => "error", - } - } - - #[cfg(feature = "wasm-plugins")] - const fn wasm_lifecycle_name(self) -> &'static str { - match self { - // The native hook name predates the public WASM lifecycle schema. - Self::AgentEnd => "agent_stop", - _ => self.as_str(), - } - } - - const ALL: [Self; 8] = [ - Self::AgentStart, - Self::AgentEnd, - Self::LlmRequest, - Self::LlmResponse, - Self::ToolCallStart, - Self::ToolCall, - Self::TurnComplete, - Self::Error, - ]; - - fn from_name(name: &str) -> Option { - let normalized = normalize_event_name(name); - Self::ALL.into_iter().find(|event| event.as_str() == normalized) - } -} - -#[derive(Debug, Clone, Deserialize)] -struct HookAction { - command: String, - #[serde(default)] - args: Vec, - #[serde(default)] - env: HashMap, - #[serde(default)] - cwd: Option, - #[serde(default)] - timeout_ms: Option, - #[serde(default = "default_stdin_json")] - stdin_json: bool, -} - -const fn default_stdin_json() -> bool { - true -} - -#[derive(Debug, Clone, Deserialize, Default)] -struct HooksFile { - #[serde(default)] - timeout_ms: Option, - #[serde(default)] - hooks: HashMap>, -} - -#[derive(Debug, Clone)] -struct HookConfig { - timeout_ms: u64, - hooks: HashMap>, -} - -impl Default for HookConfig { - fn default() -> Self { - Self { - timeout_ms: DEFAULT_TIMEOUT_MS, - hooks: HashMap::new(), - } - } -} - -#[derive(Debug, Clone, Default)] -struct RuntimeState { - config: HookConfig, - hooks_json_digest: Option<[u8; 32]>, -} - -#[derive(Debug, Clone, Serialize)] -pub struct HookDiagnostics { - pub configured: bool, - pub valid: bool, - pub config_path: String, - pub timeout_ms: u64, - pub action_count: usize, - pub events: BTreeMap, - /// Private catalog identity for the effective hooks file. Not returned - /// through doctor/API diagnostics. - #[serde(skip)] - pub(crate) catalog_digest: Option<[u8; 32]>, - pub error: Option, - /// Whether the command hooks of this `hooks.json` run: only with - /// `security.workspace_hooks = "on"` in config.toml (HOOKS-ENV). - pub runs: bool, - /// When configured hooks do not run: why, with the one-line fix. - pub blocked: Option, -} - -/// Where a [`HookManager`] reads whether workspace command hooks run, and -/// the directory they start in. -enum HookPolicy { - /// Fixed at construction. Without a configuration (a sub-agent's own - /// manager, an embedding caller) workspace hooks do not run. - Fixed { - allowed: bool, - launch_root: Option, - }, - /// The process configuration, read at every event, so turning the - /// opt-in off stops hooks at once. - Live(crate::config::SharedConfig), -} - -/// The one line that allows workspace command hooks. -pub const WORKSPACE_HOOKS_OPT_IN: &str = "[security] workspace_hooks = \"on\""; - -/// How many command hooks the workspace `hooks.json` under -/// `workspace_dir` defines; `None` without one. Reads and validates the -/// file only (for `prx doctor`). -/// -/// # Errors -/// -/// An unreadable, oversized or invalid `hooks.json`. -pub fn workspace_hook_actions(workspace_dir: &Path) -> anyhow::Result> { - let Some(raw) = read_bounded_file(&workspace_dir.join(HOOKS_JSON_FILE), MAX_HOOKS_FILE_BYTES)? else { - return Ok(None); - }; - Ok(Some(parse_hook_config(&raw)?.hooks.values().map(Vec::len).sum())) -} - -/// Why the command hooks of a `hooks.json` holding `actions` actions do not -/// run, with the fix; `None` when there are none. -#[must_use] -pub fn blocked_hooks_note(actions: usize) -> Option { - (actions > 0).then(|| { - format!( - "{actions} workspace command hook(s) in hooks.json are not run: `security.workspace_hooks` is off. To \ - run them, add `{WORKSPACE_HOOKS_OPT_IN}` to config.toml (a high-risk change: the workspace can then \ - start programs that run as PRX's user)" - ) - }) -} - -/// What a change to the workspace hooks can do: the one risk -/// classification of `hooks.json` changes on every surface (`hooks_manage`, -/// the Gateway hooks API; D-096). The file tools classify any write of the -/// file as a launch-definition write, which is High as well. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum HookChange { - /// Installs, changes or runs a hook command: its program, arguments or - /// the event it runs on. - Command, - /// Only removes hooks or changes their limits: nothing new runs. - Restriction, -} - -impl HookChange { - /// The side-effect risk of this change. - #[must_use] - pub const fn risk(self) -> crate::security::policy::ResourceRiskLevel { - match self { - Self::Command => crate::security::policy::ResourceRiskLevel::High, - Self::Restriction => crate::security::policy::ResourceRiskLevel::Medium, - } - } - - /// The change a `hooks_manage` action makes; `None` for the actions - /// that only read. - #[must_use] - pub fn of_manage_action(action: &str) -> Option { - match action { - "test" | "replace" => Some(Self::Command), - "remove" => Some(Self::Restriction), - _ => None, - } - } -} - -/// The hook state every delivery reads: configuration generation, launch -/// policy and the plugin runtime. Shared between the [`HookManager`] and its -/// background dispatcher. -pub struct HookCore { - workspace_dir: PathBuf, - hooks_json_path: PathBuf, - policy: RwLock, - media_artifacts: std::sync::Arc, - state: RwLock, - /// Longest one event may occupy the dispatcher. - delivery_bound: Duration, - /// Process-level WASM plugin runtime; it is the sole generation owner. - #[cfg(feature = "wasm-plugins")] - plugin_runtime: tokio::sync::RwLock>>, -} - -/// Hook events the queue holds before further events are dropped and counted. -pub const HOOK_QUEUE_CAPACITY: usize = 1024; - -/// Upper bound on the wait for queued events at shutdown. -pub const HOOK_DRAIN_BOUND: Duration = Duration::from_secs(3); - -/// Longest one event may occupy the dispatcher: the largest single hook -/// timeout. Every hook, WASM hook and event-bus subscriber of the event shares -/// it, so one that never completes costs the queue this much, not forever. -const HOOK_EVENT_DELIVERY_BOUND: Duration = Duration::from_millis(MAX_TIMEOUT_MS); - -enum DispatchMessage { - Event { - event: HookEvent, - payload: serde_json::Value, - }, - Flush(tokio::sync::oneshot::Sender<()>), -} - -#[derive(Default)] -struct DispatchStats { - queued: std::sync::atomic::AtomicU64, - delivered: std::sync::atomic::AtomicU64, - dropped: std::sync::atomic::AtomicU64, - /// Woken after every finished delivery (test waits). - #[cfg(test)] - delivery_signal: tokio::sync::Notify, -} - -/// Counters of one manager's background dispatcher. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct HookDispatchStats { - /// Events accepted into the queue. - pub queued: u64, - /// Events whose command, WASM and event-bus delivery finished. - pub delivered: u64, - /// Events dropped because the queue was full or closed. - pub dropped: u64, -} - -/// Observe-only hook manager. `emit` queues the event and returns at once; a -/// single background worker per manager delivers events in emit order, so -/// order is kept for every session and turn, and a slow hook never delays a -/// turn. -pub struct HookManager { - core: std::sync::Arc, - queue: std::sync::OnceLock>, - capacity: usize, - stats: std::sync::Arc, -} - -impl std::ops::Deref for HookManager { - type Target = HookCore; - - fn deref(&self) -> &HookCore { - &self.core - } -} - -impl HookManager { - pub fn new(workspace_dir: PathBuf) -> Self { - Self::with_queue_capacity(workspace_dir, HOOK_QUEUE_CAPACITY) - } - - fn with_queue_capacity(workspace_dir: PathBuf, capacity: usize) -> Self { - let media_artifacts = crate::media::MediaArtifactOwner::for_workspace(&workspace_dir); - Self { - core: std::sync::Arc::new(HookCore { - hooks_json_path: workspace_dir.join(HOOKS_JSON_FILE), - workspace_dir, - policy: RwLock::new(HookPolicy::Fixed { - allowed: false, - launch_root: None, - }), - media_artifacts, - state: RwLock::new(RuntimeState::default()), - delivery_bound: HOOK_EVENT_DELIVERY_BOUND, - #[cfg(feature = "wasm-plugins")] - plugin_runtime: tokio::sync::RwLock::new(None), - }), - queue: std::sync::OnceLock::new(), - capacity: capacity.max(1), - stats: std::sync::Arc::new(DispatchStats::default()), - } - } - - /// Read whether workspace command hooks run - /// (`security.workspace_hooks`) from the live process configuration at - /// every event, and start them in `hooks/` beside `config.toml` - /// (HOOKS-ENV). Without this, workspace command hooks do not run. - #[must_use] - pub fn with_config(self, shared: crate::config::SharedConfig) -> Self { - *self.core.policy.write() = HookPolicy::Live(shared); - self - } - - /// Shorten the per-event delivery bound (tests). - #[cfg(test)] - #[must_use] - pub(crate) fn with_delivery_bound(mut self, bound: Duration) -> Self { - if let Some(core) = std::sync::Arc::get_mut(&mut self.core) { - core.delivery_bound = bound; - } - self - } - - /// Workspace hooks run, starting under `launch_root` (tests). - #[cfg(test)] - #[must_use] - pub(crate) fn allowing_workspace_hooks(self, launch_root: PathBuf) -> Self { - *self.core.policy.write() = HookPolicy::Fixed { - allowed: true, - launch_root: Some(launch_root), - }; - self - } -} - -impl HookCore { - /// Whether workspace command hooks run now, and the root their - /// dedicated directory lies under. - fn workspace_policy(&self) -> (bool, Option) { - match &*self.policy.read() { - HookPolicy::Fixed { allowed, launch_root } => (*allowed, launch_root.clone()), - HookPolicy::Live(shared) => { - let config = &shared.pin().effective; - ( - config.security.workspace_hooks == crate::config::WorkspaceHooks::On, - config - .config_path - .parent() - .filter(|dir| !dir.as_os_str().is_empty()) - .map(|dir| dir.join("hooks")), - ) - } - } - } - - pub fn media_artifacts(&self) -> std::sync::Arc { - self.media_artifacts.clone() - } - - /// Attach the sole process-level plugin runtime for lifecycle observation. - #[cfg(feature = "wasm-plugins")] - pub async fn set_plugin_runtime(&self, runtime: std::sync::Arc) { - *self.plugin_runtime.write().await = Some(runtime); - } - - /// Transform one shared agent-pipeline envelope through the current WASM - /// middleware generation. Invalid JSON output is isolated and the original - /// envelope is preserved so a plugin cannot corrupt the turn protocol. - /// - /// The guest is third-party code like a lifecycle hook, so it receives the - /// envelope through the same redaction: the `llm_request` and - /// `llm_response` stages name the serving provider, whose `custom:` label - /// may carry URL userinfo. The turn never reads the provider back from the - /// transformed envelope. - #[cfg(feature = "wasm-plugins")] - pub async fn process_wasm_middleware( - &self, - stage: crate::plugins::capabilities::middleware::MiddlewareStage, - envelope: serde_json::Value, - ) -> serde_json::Value { - let runtime = self.plugin_runtime.read().await.clone(); - let Some(runtime) = runtime else { - return envelope; - }; - let chain = runtime.middleware(); - if chain.is_empty() { - return envelope; - } - let original = redacted_hook_payload(&envelope).to_string(); - let transformed = chain.process(stage, &original).await; - match serde_json::from_str(&transformed) { - Ok(value) => value, - Err(error) => { - tracing::warn!( - stage = stage.as_str(), - error = %error, - "WASM middleware returned invalid JSON; preserving the original envelope" - ); - envelope - } - } - } - - pub fn diagnostics(&self) -> HookDiagnostics { - let error = self.refresh_if_changed().err().map(|error| error.to_string()); - let state = self.state.read(); - let events = state - .config - .hooks - .iter() - .map(|(event, actions)| (event.clone(), actions.len())) - .collect::>(); - let action_count = events.values().sum(); - let runs = self.workspace_policy().0; - HookDiagnostics { - configured: self.hooks_json_path.is_file(), - valid: error.is_none(), - config_path: self.hooks_json_path.display().to_string(), - timeout_ms: state.config.timeout_ms, - action_count, - events, - catalog_digest: state.hooks_json_digest, - error, - runs, - blocked: if runs { None } else { blocked_hooks_note(action_count) }, - } - } - - pub fn validate_config(&self, content: &str) -> anyhow::Result { - if content.len() as u64 > MAX_HOOKS_FILE_BYTES { - anyhow::bail!("hooks config exceeds {MAX_HOOKS_FILE_BYTES} byte limit"); - } - let config = parse_hook_config(content.as_bytes())?; - let events = config - .hooks - .iter() - .map(|(event, actions)| (event.clone(), actions.len())) - .collect::>(); - let action_count = events.values().sum(); - let runs = self.workspace_policy().0; - Ok(HookDiagnostics { - configured: false, - valid: true, - config_path: self.hooks_json_path.display().to_string(), - timeout_ms: config.timeout_ms, - action_count, - events, - catalog_digest: Some(Sha256::digest(content.as_bytes()).into()), - error: None, - runs, - blocked: if runs { None } else { blocked_hooks_note(action_count) }, - }) - } - - pub fn replace_config(&self, content: &str) -> anyhow::Result { - let _ = self.validate_config(content)?; - std::fs::create_dir_all(&self.workspace_dir)?; - let mut candidate = tempfile::Builder::new() - .prefix(".hooks-json-") - .suffix(".tmp") - .tempfile_in(&self.workspace_dir)?; - candidate.write_all(content.as_bytes())?; - candidate.flush()?; - candidate.persist(&self.hooks_json_path).map_err(|error| error.error)?; - self.refresh_if_changed()?; - Ok(self.diagnostics()) - } - - pub fn remove_config(&self) -> anyhow::Result> { - if !self.hooks_json_path.exists() { - *self.state.write() = RuntimeState::default(); - return Ok(None); - } - let trash_dir = self.workspace_dir.join(".hooks-trash"); - std::fs::create_dir_all(&trash_dir)?; - let backup = trash_dir.join(format!("hooks-{}.json", uuid::Uuid::new_v4())); - std::fs::rename(&self.hooks_json_path, &backup)?; - *self.state.write() = RuntimeState::default(); - Ok(Some(backup)) - } - - /// [`Self::deliver`] under the per-event bound; on expiry the event is - /// abandoned (logged) so the next one is delivered. - async fn deliver_bounded(&self, event: HookEvent, payload: &serde_json::Value) { - let progress = std::sync::atomic::AtomicUsize::new(0); - let total = std::sync::atomic::AtomicUsize::new(0); - if tokio::time::timeout(self.delivery_bound, self.deliver(event, payload, &total, &progress)) - .await - .is_err() - { - let planned = total.load(std::sync::atomic::Ordering::Relaxed); - let finished = progress.load(std::sync::atomic::Ordering::Relaxed); - tracing::warn!( - event = event.as_str(), - actions_total = planned, - actions_unfinished = planned.saturating_sub(finished), - bound_ms = u64::try_from(self.delivery_bound.as_millis()).unwrap_or(u64::MAX), - "hook delivery exceeded its bound and was abandoned" - ); - } - } - - /// Deliver one already-redacted event: command hooks first, then WASM - /// lifecycle hooks and the plugin event bus. Runs on the dispatcher, never - /// on a turn. - async fn deliver( - &self, - event: HookEvent, - payload: &serde_json::Value, - total: &std::sync::atomic::AtomicUsize, - finished: &std::sync::atomic::AtomicUsize, - ) { - if let Err(err) = self.refresh_if_changed() { - tracing::warn!(error = %err, "hooks refresh failed"); - } else { - let (timeout_ms, actions) = { - let state = self.state.read(); - ( - state.config.timeout_ms, - state.config.hooks.get(event.as_str()).cloned().unwrap_or_default(), - ) - }; - - let (allowed, _) = self.workspace_policy(); - if !actions.is_empty() && !allowed { - tracing::warn!( - event = event.as_str(), - actions = actions.len(), - "workspace command hooks are not run: security.workspace_hooks is off; add `{}` to \ - config.toml to run them", - WORKSPACE_HOOKS_OPT_IN - ); - } else if !actions.is_empty() { - // Progress lets the event bound say how many actions it cut off. - total.store(actions.len(), std::sync::atomic::Ordering::Relaxed); - for action in actions { - if let Err(err) = self.run_action(event, payload, timeout_ms, &action).await { - tracing::warn!( - event = event.as_str(), - command = action.command, - error = %err, - "hook execution failed" - ); - } - finished.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - } - } - } - - // Fire WASM hooks and bridge the lifecycle topic through the same process runtime. - #[cfg(feature = "wasm-plugins")] - { - let runtime = self.plugin_runtime.read().await.clone(); - if let Some(runtime) = runtime { - let payload_str = payload.to_string(); - let topic = format!("prx.lifecycle.{}", event.wasm_lifecycle_name()); - runtime.emit_hook(&topic, &payload_str).await; - if let Err(error) = runtime.event_bus().publish(&topic, &payload_str).await { - tracing::debug!(topic = %topic, error = %error, "event bus lifecycle bridge error"); - } - } - } - } - - fn refresh_if_changed(&self) -> anyhow::Result<()> { - let Some(raw) = read_bounded_file(&self.hooks_json_path, MAX_HOOKS_FILE_BYTES)? else { - let mut state = self.state.write(); - if state.hooks_json_digest.is_some() { - *state = RuntimeState::default(); - } - return Ok(()); - }; - - let digest: [u8; 32] = Sha256::digest(&raw).into(); - if self.state.read().hooks_json_digest == Some(digest) { - return Ok(()); - } - - let config = parse_hook_config(&raw)?; - - // Candidate parsing and validation finish before this single generation swap. - *self.state.write() = RuntimeState { - config, - hooks_json_digest: Some(digest), - }; - Ok(()) - } - - async fn run_action( - &self, - event: HookEvent, - payload: &serde_json::Value, - default_timeout_ms: u64, - action: &HookAction, - ) -> anyhow::Result<()> { - let command = action.command.trim(); - if command.is_empty() { - anyhow::bail!("hook command is empty"); - } - let timeout_ms = bounded_timeout(action.timeout_ms.unwrap_or(default_timeout_ms))?; - - // `emit` redacted the payload; this redacts again for direct callers - // and is a borrow when there is nothing left to redact. - let payload_json = redacted_hook_payload(payload).to_string(); - if payload_json.len() > MAX_PAYLOAD_BYTES { - anyhow::bail!( - "hook payload is {} bytes; limit is {MAX_PAYLOAD_BYTES}", - payload_json.len() - ); - } - // The dedicated directory the hook starts in: beside config.toml, - // never the workspace (which the agent's file tools can write) and - // never PRX's own working directory (HOOKS-ENV). A `cwd` in - // hooks.json is workspace-controlled and is not used. - let (_, launch_root) = self.workspace_policy(); - let Some(launch_root) = launch_root else { - anyhow::bail!( - "workspace hooks have no launch directory: PRX starts them in `hooks/` beside config.toml, and this \ - process has no configuration directory" - ); - }; - let working_dir = crate::config::mcp_launch::launch_directory(&launch_root, "workspace-hooks", None) - .map_err(|error| anyhow::anyhow!(error))?; - crate::config::mcp_launch::prepare_launch_directory(&launch_root, &working_dir).await?; - // A command with a path separator is workspace content (a script in - // the workspace): resolve it against the workspace, since the hook - // no longer starts there. A bare name is looked up in `PATH`. - let program = if command.contains(['/', '\\']) && !Path::new(command).is_absolute() { - self.workspace_dir.join(command) - } else { - PathBuf::from(command) - }; - - // A cleared environment through the shared launch builder: the - // launch allowlist of PRX's environment plus the hook's own `env`, - // without the variables a workspace may not set (HOOKS-ENV, D-045). - let (environment, dropped) = crate::config::mcp_launch::workspace_launch_environment(&action.env); - if !dropped.is_empty() { - tracing::warn!( - event = event.as_str(), - dropped = ?dropped, - "hook environment variables a workspace may not set were dropped" - ); - } - let mut cmd = Command::new(&program); - cmd.args(&action.args); - cmd.env_clear(); - cmd.envs(environment); - cmd.current_dir(&working_dir); - cmd.env("ZERO_HOOK_EVENT", event.as_str()); - - // Avoid execve argv+env size overflow for large payloads. - const MAX_ENV_PAYLOAD_BYTES: usize = 8 * 1024; - if payload_json.len() <= MAX_ENV_PAYLOAD_BYTES { - cmd.env("ZERO_HOOK_PAYLOAD", &payload_json); - } else { - cmd.env("ZERO_HOOK_PAYLOAD", ""); - cmd.env("ZERO_HOOK_PAYLOAD_TRUNCATED", "1"); - } - - // NamedTempFile is created with restrictive permissions and removes itself on every exit. - let mut payload_file = tempfile::Builder::new() - .prefix("openprx-hook-payload-") - .suffix(".json") - .tempfile()?; - payload_file.write_all(payload_json.as_bytes())?; - payload_file.flush()?; - cmd.env("ZERO_HOOK_PAYLOAD_FILE", payload_file.path()); - - if action.stdin_json { - cmd.stdin(std::process::Stdio::piped()); - } - cmd.stdout(std::process::Stdio::null()); - cmd.stderr(std::process::Stdio::piped()); - - let mut child = crate::runtime::shell_process::spawn_managed_shell_child(cmd)?; - let deadline = tokio::time::Instant::now() + Duration::from_millis(timeout_ms); - - let stderr = child.take_stderr(); - let stderr_reader = tokio::spawn(async move { - let Some(stderr) = stderr else { - return std::io::Result::Ok(Vec::new()); - }; - let mut bytes = Vec::new(); - stderr.take(MAX_STDERR_BYTES + 1).read_to_end(&mut bytes).await?; - Ok(bytes) - }); - - if action.stdin_json { - if let Some(mut stdin) = child.take_stdin() { - let write_result = tokio::time::timeout_at(deadline, stdin.write_all(payload_json.as_bytes())).await; - match write_result { - Err(_) => { - let _ = child.terminate_and_reap().await; - let _ = stderr_reader.await; - anyhow::bail!("hook timed out while writing stdin"); - } - Ok(Err(error)) if error.kind() != std::io::ErrorKind::BrokenPipe => { - let _ = child.terminate_and_reap().await; - let _ = stderr_reader.await; - return Err(error.into()); - } - Ok(_) => {} - } - } - } - - let status = match tokio::time::timeout_at(deadline, child.wait()).await { - Ok(Ok(status)) => status, - Ok(Err(error)) => { - let _ = child.terminate_and_reap().await; - let _ = stderr_reader.await; - return Err(error.into()); - } - Err(_) => { - let _ = child.terminate_and_reap().await; - let _ = stderr_reader.await; - anyhow::bail!("hook timed out after {timeout_ms} ms"); - } - }; - let mut stderr = stderr_reader.await??; - child.mark_complete(); - let stderr_truncated = stderr.len() > MAX_STDERR_BYTES as usize; - stderr.truncate(MAX_STDERR_BYTES as usize); - - if status.success() { - return Ok(()); - } - - let stderr = String::from_utf8_lossy(&stderr); - let mut stderr = truncate_for_log(stderr.as_ref(), MAX_STDERR_CHARS); - if stderr_truncated { - stderr.push_str(" [truncated]"); - } - anyhow::bail!( - "hook exited with status {}{}", - status, - if stderr.is_empty() { - String::new() - } else { - format!(", stderr: {stderr}") - } - ) - } -} - -impl HookManager { - /// Queue a test event and wait (bounded) until it was delivered, so the - /// operator's explicit test reports a finished delivery. - pub async fn test_event(&self, event: HookEvent, payload: serde_json::Value) { - self.emit(event, payload).await; - self.drain(HOOK_DRAIN_BOUND).await; - } - - pub fn manage_tool( - self: &std::sync::Arc, - security: std::sync::Arc, - ) -> Box { - Box::new(HooksManageTool { - manager: self.clone(), - security, - }) - } - - pub fn status_tool(self: &std::sync::Arc) -> Box { - Box::new(HooksStatusTool { manager: self.clone() }) - } - - /// Shared control objects for registries that must preserve identity across - /// top-level and delegated turns. - pub fn control_tool_arcs( - self: &std::sync::Arc, - security: std::sync::Arc, - ) -> Vec> { - vec![ - std::sync::Arc::new(HooksStatusTool { manager: self.clone() }), - std::sync::Arc::new(HooksManageTool { - manager: self.clone(), - security, - }), - ] - } - - /// Append the model-visible control surface for this exact live manager. - /// - /// Every model-running entrypoint uses this helper so status/management - /// cannot accidentally target a different hook generation, or be omitted - /// while hook execution itself remains enabled. - pub fn append_control_tools( - self: &std::sync::Arc, - tools: &mut Vec>, - security: std::sync::Arc, - ) { - tools.push(self.status_tool()); - tools.push(self.manage_tool(security)); - } - - /// Queue `event` for background delivery and return at once; the turn - /// never waits on a hook. The payload is redacted here, once, for every - /// consumer (command hooks, WASM lifecycle hooks, the plugin event bus), - /// so no secret waits in the queue. When the queue is full the event is - /// dropped and counted (see [`Self::dispatch_stats`]). - pub fn emit(&self, event: HookEvent, payload: serde_json::Value) -> impl std::future::Future + use<> { - let owned = match redacted_hook_payload(&payload) { - std::borrow::Cow::Owned(redacted) => Some(redacted), - std::borrow::Cow::Borrowed(_) => None, - }; - let payload = owned.unwrap_or(payload); - let sent = self.sender().map_or(Err("no async runtime"), |sender| { - sender - .try_send(DispatchMessage::Event { event, payload }) - .map_err(|error| match error { - tokio::sync::mpsc::error::TrySendError::Full(_) => "queue full", - tokio::sync::mpsc::error::TrySendError::Closed(_) => "dispatcher stopped", - }) - }); - match sent { - Ok(()) => { - self.stats.queued.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - } - Err(reason) => { - let dropped = self.stats.dropped.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; - // Logged on the first drop and then every 100th, so a stalled - // hook cannot also flood the log. - if dropped == 1 || dropped.is_multiple_of(100) { - tracing::warn!( - event = event.as_str(), - reason, - dropped_total = dropped, - capacity = self.capacity, - "hook event dropped" - ); - } - } - } - std::future::ready(()) - } - - /// Counters of the background dispatcher. - #[must_use] - pub fn dispatch_stats(&self) -> HookDispatchStats { - HookDispatchStats { - queued: self.stats.queued.load(std::sync::atomic::Ordering::Relaxed), - delivered: self.stats.delivered.load(std::sync::atomic::Ordering::Relaxed), - dropped: self.stats.dropped.load(std::sync::atomic::Ordering::Relaxed), - } - } - - /// Wait until every event queued before this call was delivered, but at - /// most `bound`. Returns whether the queue was fully drained in time; - /// events still queued at the bound keep being delivered while the - /// runtime lives. The shutdown path calls this with [`HOOK_DRAIN_BOUND`]. - pub async fn drain(&self, bound: Duration) -> bool { - if self.queue.get().is_none() { - return true; - } - let (done, delivered) = tokio::sync::oneshot::channel(); - let wait = async { - let Some(sender) = self.sender() else { - return false; - }; - if sender.send(DispatchMessage::Flush(done)).await.is_err() { - return false; - } - delivered.await.is_ok() - }; - tokio::time::timeout(bound, wait).await.unwrap_or(false) - } - - /// Drain at process or component shutdown: wait at most - /// [`HOOK_DRAIN_BOUND`] and log what is abandoned. Every owner of a live - /// manager calls this on its exit path. - pub async fn drain_for_shutdown(&self) { - if !self.drain(HOOK_DRAIN_BOUND).await { - tracing::warn!( - bound_secs = HOOK_DRAIN_BOUND.as_secs(), - "hook events were still queued at shutdown; the rest are abandoned" - ); - } - } - - /// Wait until `count` events were delivered in total (tests whose - /// producer enqueues from a spawned task, where `drain` could run first). - #[cfg(test)] - pub(crate) async fn wait_delivered(&self, count: u64) { - loop { - let signal = self.stats.delivery_signal.notified(); - tokio::pin!(signal); - signal.as_mut().enable(); - if self.stats.delivered.load(std::sync::atomic::Ordering::Relaxed) >= count { - return; - } - signal.await; - } - } - - /// The queue's sender; the single worker starts with the first event. - /// `None` outside a tokio runtime, where no worker can start (the event is - /// dropped and counted rather than panicking the caller). - fn sender(&self) -> Option<&tokio::sync::mpsc::Sender> { - if let Some(sender) = self.queue.get() { - return Some(sender); - } - let runtime = tokio::runtime::Handle::try_current().ok()?; - Some(self.queue.get_or_init(|| { - let (tx, mut rx) = tokio::sync::mpsc::channel::(self.capacity); - let core = std::sync::Arc::clone(&self.core); - let stats = std::sync::Arc::clone(&self.stats); - runtime.spawn(async move { - while let Some(message) = rx.recv().await { - match message { - DispatchMessage::Event { event, payload } => { - core.deliver_bounded(event, &payload).await; - stats.delivered.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - #[cfg(test)] - stats.delivery_signal.notify_waiters(); - } - DispatchMessage::Flush(done) => { - // The waiter may have given up at its bound. - let _ = done.send(()); - } - } - } - }); - tx - })) - } -} - -pub struct HooksManageTool { - manager: std::sync::Arc, - security: std::sync::Arc, -} - -pub struct HooksStatusTool { - manager: std::sync::Arc, -} - -#[async_trait] -impl crate::tools::Tool for HooksStatusTool { - fn live_hook_manager(&self) -> Option> { - Some(self.manager.clone()) - } - - fn name(&self) -> &str { - "hooks_status" - } - - fn description(&self) -> &str { - "Inspect the active workspace lifecycle-hooks configuration, event coverage, action count, and validation error." - } - - fn parameters_schema(&self) -> serde_json::Value { - json!({"type": "object", "properties": {}, "additionalProperties": false}) - } - - async fn execute(&self, _args: serde_json::Value) -> anyhow::Result { - Ok(crate::tools::ToolResult { - success: true, - output: serde_json::to_string_pretty(&self.manager.diagnostics())?, - error: None, - }) - } - - fn tier(&self) -> crate::tools::ToolTier { - crate::tools::ToolTier::Standard - } - - fn categories(&self) -> &'static [crate::tools::ToolCategory] { - &[ - crate::tools::ToolCategory::System, - crate::tools::ToolCategory::Automation, - ] - } -} - -impl HooksManageTool { - fn authorize(&self, action: &str, args: &serde_json::Value) -> Result<(), crate::tools::ToolResult> { - use crate::security::policy::{ApprovalGrant, SideEffectGate}; - // The one classification of hooks.json changes (D-096). - let Some(change) = HookChange::of_manage_action(action) else { - return Ok(()); - }; - let risk = change.risk(); - let grant = ApprovalGrant::from_runtime_args("hooks_manage", args); - SideEffectGate::new(self.security.as_ref()) - .authorize_resource_operation("hooks_manage", &format!("hooks_manage:{action}"), risk, grant.as_ref()) - .map(|_| ()) - .map_err(|error| crate::tools::ToolResult { - success: false, - output: String::new(), - error: Some(error), - }) - } - - fn required_string<'a>(args: &'a serde_json::Value, key: &str) -> anyhow::Result<&'a str> { - args.get(key) - .and_then(serde_json::Value::as_str) - .map(str::trim) - .filter(|value| !value.is_empty()) - .ok_or_else(|| anyhow::anyhow!("Missing non-empty '{key}' parameter")) - } -} - -impl HooksManageTool { - fn execution_schema(&self) -> &'static std::sync::Arc { - static SCHEMA: std::sync::LazyLock> = std::sync::LazyLock::new(|| { - std::sync::Arc::new({ - crate::tools::schema::with_action_requirements( - json!({ - "type": "object", - "properties": { - "action": { - "type": "string", - "enum": ["status", "refresh", "validate", "replace", "remove", "test"], - "description": "Action to perform: 'status' reports the active hooks configuration, 'refresh' reloads it from disk, 'validate' checks a candidate hooks.json, 'replace' installs one atomically, 'remove' deletes it, 'test' fires a synthetic event" - }, - "content": {"type": "string", "description": "Complete hooks.json; required for 'validate' and 'replace'"}, - "event": { - "type": "string", - "enum": HookEvent::ALL.map(HookEvent::as_str), - "description": "Lifecycle event to fire; required for 'test'" - }, - "payload": {"type": "object", "description": "Synthetic payload for 'test'"} - }, - "required": ["action"], - "additionalProperties": false - }), - "action", - &[ - crate::tools::schema::ActionRequirement { - action: "validate", - required: &["content"], - }, - crate::tools::schema::ActionRequirement { - action: "replace", - required: &["content"], - }, - crate::tools::schema::ActionRequirement { - action: "test", - required: &["event"], - }, - ], - ) - }) - }); - &SCHEMA - } -} - -#[async_trait] -impl crate::tools::Tool for HooksManageTool { - fn name(&self) -> &str { - "hooks_manage" - } - - fn description(&self) -> &str { - "Manage workspace lifecycle hooks: 'status' reports the active configuration, 'refresh' reloads it from disk, 'validate' checks a candidate hooks.json, 'replace' installs one atomically, 'remove' deletes it, and 'test' fires a synthetic event. Mutating and test actions are approval-gated." - } - - fn parameters_schema(&self) -> serde_json::Value { - crate::tools::schema::publish_flat_schema(self.execution_schema()) - } - - fn execution_parameters_schema(&self) -> Option> { - Some(std::sync::Arc::clone(self.execution_schema())) - } - - async fn execute(&self, mut args: serde_json::Value) -> anyhow::Result { - crate::tools::schema::validate_execution_contract(self.name(), self.execution_schema(), &mut args)?; - use crate::tools::ToolResult; - let action = Self::required_string(&args, "action")?; - if let Err(result) = self.authorize(action, &args) { - return Ok(result); - } - let result: anyhow::Result = match action { - "status" | "refresh" => serde_json::to_value(self.manager.diagnostics()).map_err(Into::into), - "validate" => { - let content = Self::required_string(&args, "content")?; - self.manager - .validate_config(content) - .and_then(|status| serde_json::to_value(status).map_err(Into::into)) - } - "replace" => { - let content = Self::required_string(&args, "content")?; - self.manager - .replace_config(content) - .and_then(|status| serde_json::to_value(status).map_err(Into::into)) - } - "remove" => self - .manager - .remove_config() - .map(|backup| json!({"removed": backup.is_some(), "recoverable_backup": backup})), - "test" => { - let event_name = Self::required_string(&args, "event")?; - let event = HookEvent::from_name(event_name) - .ok_or_else(|| anyhow::anyhow!("Unknown hook event '{event_name}'"))?; - let payload = args - .get("payload") - .cloned() - .unwrap_or_else(|| json!({"source": "hooks_manage", "test": true})); - self.manager.test_event(event, payload).await; - Ok(json!({"tested": true, "event": event.as_str()})) - } - _ => anyhow::bail!("Unsupported hooks_manage action: {action}"), - }; - - Ok(match result { - Ok(output) => ToolResult { - success: true, - output: serde_json::to_string_pretty(&output)?, - error: None, - }, - Err(error) => ToolResult { - success: false, - output: String::new(), - error: Some(error.to_string()), - }, - }) - } - - fn tier(&self) -> crate::tools::ToolTier { - crate::tools::ToolTier::Extended - } - - fn categories(&self) -> &'static [crate::tools::ToolCategory] { - &[ - crate::tools::ToolCategory::System, - crate::tools::ToolCategory::Automation, - ] - } -} - -fn bounded_timeout(timeout_ms: u64) -> anyhow::Result { - if timeout_ms == 0 || timeout_ms > MAX_TIMEOUT_MS { - anyhow::bail!("hook timeout_ms must be between 1 and {MAX_TIMEOUT_MS}"); - } - Ok(timeout_ms) -} - -fn validate_hooks_file(file: &HooksFile) -> anyhow::Result<()> { - if let Some(timeout_ms) = file.timeout_ms { - bounded_timeout(timeout_ms)?; - } - let action_count = file.hooks.values().map(Vec::len).sum::(); - if action_count > MAX_ACTIONS { - anyhow::bail!("hooks.json has {action_count} actions; limit is {MAX_ACTIONS}"); - } - let mut normalized_events = std::collections::HashSet::new(); - for event in file.hooks.keys() { - let normalized = normalize_event_name(event); - if HookEvent::from_name(&normalized).is_none() { - anyhow::bail!("unknown hook event '{event}'"); - } - if !normalized_events.insert(normalized) { - anyhow::bail!("duplicate hook event after normalization: '{event}'"); - } - } - for actions in file.hooks.values() { - for action in actions { - if action.args.len() > MAX_ARGS_PER_ACTION { - anyhow::bail!("hook action has too many arguments"); - } - if action.env.len() > MAX_ENV_PER_ACTION { - anyhow::bail!("hook action has too many environment entries"); - } - if let Some(timeout_ms) = action.timeout_ms { - bounded_timeout(timeout_ms)?; - } - // A hook starts in its dedicated directory beside config.toml. - // `cwd` is workspace-controlled, so it is refused here rather - // than accepted and silently ignored. - if action.cwd.is_some() { - anyhow::bail!( - "hooks.json `cwd` is not supported: hooks always start in their dedicated `hooks/` directory \ - beside config.toml; remove `cwd` and use an absolute path or a workspace-relative `command`" - ); - } - } - } - Ok(()) -} - -fn parse_hook_config(raw: &[u8]) -> anyhow::Result { - let parsed: HooksFile = serde_json::from_slice(raw)?; - validate_hooks_file(&parsed)?; - Ok(HookConfig { - timeout_ms: bounded_timeout(parsed.timeout_ms.unwrap_or(DEFAULT_TIMEOUT_MS))?, - hooks: parsed - .hooks - .into_iter() - .map(|(name, actions)| (normalize_event_name(&name), actions)) - .collect(), - }) -} - -fn normalize_event_name(name: &str) -> String { - name.trim().to_ascii_lowercase().replace('-', "_") -} - -fn read_bounded_file(path: &Path, max_bytes: u64) -> anyhow::Result>> { - let mut file = match std::fs::File::open(path) { - Ok(file) => file, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), - Err(error) => return Err(error.into()), - }; - let metadata = file.metadata()?; - if metadata.len() > max_bytes { - anyhow::bail!("{} exceeds {max_bytes} byte limit", path.display()); - } - let mut bytes = Vec::with_capacity(metadata.len() as usize); - std::io::Read::by_ref(&mut file) - .take(max_bytes + 1) - .read_to_end(&mut bytes)?; - if bytes.len() as u64 > max_bytes { - anyhow::bail!("{} exceeds {max_bytes} byte limit", path.display()); - } - Ok(Some(bytes)) -} - -fn truncate_for_log(input: &str, max_chars: usize) -> String { - let char_count = input.chars().count(); - if char_count <= max_chars { - return input.to_string(); - } - let mut out = String::new(); - for c in input.chars().take(max_chars) { - out.push(c); - } - out.push_str("..."); - out -} - -/// The payload keys that can quote a provider label: the label itself and the -/// error texts that name it. -const PROVIDER_LABEL_PAYLOAD_KEYS: [&str; 4] = ["provider", "message", "error", "error_message"]; - -/// `payload` as a hook script may see it: a provider label (a `custom:` URL -/// may carry `user:password@`) and the error texts that quote one are -/// redacted with the one helper every other surface uses. Borrowed when -/// nothing needed redacting. -fn redacted_hook_payload(payload: &serde_json::Value) -> std::borrow::Cow<'_, serde_json::Value> { - let Some(object) = payload.as_object() else { - return std::borrow::Cow::Borrowed(payload); - }; - let needs_redaction = PROVIDER_LABEL_PAYLOAD_KEYS.iter().any(|key| { - object - .get(*key) - .and_then(serde_json::Value::as_str) - .is_some_and(|text| { - matches!( - crate::providers::redact_endpoint_userinfo(text), - std::borrow::Cow::Owned(_) - ) - }) - }); - if !needs_redaction { - return std::borrow::Cow::Borrowed(payload); - } - let mut redacted = object.clone(); - for key in PROVIDER_LABEL_PAYLOAD_KEYS { - if let Some(serde_json::Value::String(text)) = redacted.get_mut(key) - && let std::borrow::Cow::Owned(safe) = crate::providers::redact_endpoint_userinfo(text) - { - *text = safe; - } - } - std::borrow::Cow::Owned(serde_json::Value::Object(redacted)) -} - -pub fn payload_error(component: &str, message: &str) -> serde_json::Value { - json!({ - "component": component, - "message": message, - }) -} - -#[allow(clippy::indexing_slicing)] -#[cfg(test)] -mod tests { - use super::*; - use crate::tools::Tool; - use tempfile::TempDir; - - /// A manager whose workspace hooks run (the operator opted in), with its - /// workspace and launch root inside `temp`. - /// Generous bound for a delivery the tests wait on; reached only on failure. - const TEST_DRAIN: Duration = Duration::from_secs(30); - - fn allowed_manager(temp: &TempDir) -> HookManager { - HookManager::new(temp.path().join("workspace")).allowing_workspace_hooks(temp.path().join("hooks")) - } - - /// The shared action contract every action-dispatched tool is held to: - /// the tool-list description and the `action` parameter's own description - /// must each name every enumerated action, and no parameter may ship - /// undescribed. - #[tokio::test] - async fn hooks_manage_action_tool_contract() { - let temp = TempDir::new().unwrap(); - let manager = std::sync::Arc::new(HookManager::new(temp.path().to_path_buf())); - let tool = HooksManageTool { - manager, - security: std::sync::Arc::new(crate::security::SecurityPolicy::default()), - }; - crate::tools::schema::assert_flat_execution_contract(&tool, tool.execution_schema()).await; - crate::tools::schema::action_contract::assert_action_tool_contract( - tool.name(), - tool.description(), - tool.execution_schema(), - ); - } - - #[test] - fn normalize_event_name_handles_case_and_dash() { - assert_eq!(normalize_event_name("Tool-Call-Start"), "tool_call_start"); - } - - #[test] - fn refresh_loads_hooks_json() { - let temp = TempDir::new().unwrap(); - let path = temp.path().join(HOOKS_JSON_FILE); - std::fs::write( - &path, - r#"{ - "timeout_ms": 1200, - "hooks": { - "tool-call-start": [ - { "command": "echo", "args": ["ok"] } - ] - } -}"#, - ) - .unwrap(); - - let manager = HookManager::new(temp.path().to_path_buf()); - manager.refresh_if_changed().unwrap(); - - let state = manager.state.read(); - assert_eq!(state.config.timeout_ms, 1200); - assert!(state.config.hooks.contains_key("tool_call_start")); - } - - // ── HookEvent::as_str ───────────────────────────────────── - - #[test] - fn hook_event_all_variants_have_names() { - let events = [ - HookEvent::AgentStart, - HookEvent::AgentEnd, - HookEvent::LlmRequest, - HookEvent::LlmResponse, - HookEvent::ToolCallStart, - HookEvent::ToolCall, - HookEvent::TurnComplete, - HookEvent::Error, - ]; - for e in &events { - assert!(!e.as_str().is_empty(), "expected a non-empty value"); - } - } - - #[test] - fn hook_event_as_str_values() { - assert_eq!(HookEvent::AgentStart.as_str(), "agent_start"); - assert_eq!(HookEvent::ToolCall.as_str(), "tool_call"); - assert_eq!(HookEvent::Error.as_str(), "error"); - } - - // ── normalize_event_name ──────────────────────────────────── - - #[test] - fn normalize_event_name_identity() { - assert_eq!(normalize_event_name("agent_start"), "agent_start"); - } - - #[test] - fn normalize_event_name_trims() { - assert_eq!(normalize_event_name(" tool_call "), "tool_call"); - } - - #[test] - fn normalize_event_name_uppercased() { - assert_eq!(normalize_event_name("AGENT_END"), "agent_end"); - } - - // ── truncate_for_log ──────────────────────────────────────── - - #[test] - fn truncate_short_string_unchanged() { - assert_eq!(truncate_for_log("hello", 10), "hello"); - } - - #[test] - fn truncate_long_string_adds_ellipsis() { - let long = "a".repeat(500); - let out = truncate_for_log(&long, 10); - assert_eq!(out.len(), 13); // 10 chars + "..." - assert!(out.ends_with("...")); - } - - #[test] - fn truncate_empty_string() { - assert_eq!(truncate_for_log("", 10), ""); - } - - #[test] - fn truncate_unicode_safe() { - let s = "\u{41f}\u{440}\u{438}\u{432}\u{435}\u{442}, \u{44d}\u{442}\u{43e} \u{434}\u{43b}\u{438}\u{43d}\u{43d}\u{430}\u{44f} \u{441}\u{442}\u{440}\u{43e}\u{43a}\u{430}"; - let out = truncate_for_log(s, 4); - // Should take exactly 4 chars + "..." - assert!(out.ends_with("...")); - assert_eq!(out.chars().count(), 7); // 4 + 3 dots - } - - // ── payload_error ─────────────────────────────────────────── - - #[test] - fn payload_error_format() { - let p = payload_error("gateway", "connection refused"); - assert_eq!(p["component"], "gateway"); - assert_eq!(p["message"], "connection refused"); - } - - // ── HookManager::new ──────────────────────────────────────── - - #[test] - fn hook_manager_new_sets_path() { - let temp = TempDir::new().unwrap(); - let manager = HookManager::new(temp.path().to_path_buf()); - assert_eq!(manager.hooks_json_path, temp.path().join(HOOKS_JSON_FILE)); - } - - #[test] - fn append_control_tools_publishes_complete_live_surface() { - let temp = TempDir::new().unwrap(); - let manager = std::sync::Arc::new(HookManager::new(temp.path().to_path_buf())); - let mut tools = Vec::new(); - manager.append_control_tools( - &mut tools, - std::sync::Arc::new(crate::security::SecurityPolicy::default()), - ); - - let names = tools.iter().map(|tool| tool.name()).collect::>(); - assert_eq!(names, vec!["hooks_status", "hooks_manage"]); - } - - // ── refresh_if_changed edge cases ─────────────────────────── - - #[test] - fn refresh_missing_file_resets_to_default() { - let temp = TempDir::new().unwrap(); - let manager = HookManager::new(temp.path().to_path_buf()); - // No hooks.json → should succeed with default config - manager.refresh_if_changed().unwrap(); - let state = manager.state.read(); - assert_eq!(state.config.timeout_ms, DEFAULT_TIMEOUT_MS); - assert!(state.config.hooks.is_empty()); - } - - #[test] - fn refresh_invalid_json_fails() { - let temp = TempDir::new().unwrap(); - std::fs::write(temp.path().join(HOOKS_JSON_FILE), "not json!!!").unwrap(); - let manager = HookManager::new(temp.path().to_path_buf()); - assert!(manager.refresh_if_changed().is_err()); - } - - #[test] - fn refresh_invalid_candidate_preserves_active_generation() { - let temp = TempDir::new().unwrap(); - let path = temp.path().join(HOOKS_JSON_FILE); - std::fs::write(&path, r#"{"timeout_ms": 1200, "hooks": {}}"#).unwrap(); - let manager = HookManager::new(temp.path().to_path_buf()); - manager.refresh_if_changed().unwrap(); - let active_digest = manager.state.read().hooks_json_digest; - - std::fs::write(&path, "not json").unwrap(); - assert!(manager.refresh_if_changed().is_err()); - let state = manager.state.read(); - assert_eq!(state.config.timeout_ms, 1200); - assert_eq!(state.hooks_json_digest, active_digest); - } - - #[test] - fn diagnostics_and_recoverable_lifecycle_reflect_active_config() { - let temp = TempDir::new().unwrap(); - let manager = HookManager::new(temp.path().to_path_buf()); - let candidate = r#"{ - "timeout_ms": 1500, - "hooks": { - "tool-call": [{"command": "true"}], - "turn_complete": [{"command": "true"}] - } -}"#; - - let validated = manager.validate_config(candidate).unwrap(); - assert!(!validated.configured); - assert!(validated.valid); - assert_eq!(validated.action_count, 2); - - let active = manager.replace_config(candidate).unwrap(); - assert!(active.configured); - assert!(active.valid); - assert_eq!(active.timeout_ms, 1500); - assert_eq!(active.events.get("tool_call"), Some(&1)); - - let backup = manager.remove_config().unwrap().unwrap(); - assert!(!temp.path().join(HOOKS_JSON_FILE).exists()); - assert!(backup.is_file()); - assert!(!manager.diagnostics().configured); - } - - #[test] - fn validation_rejects_unknown_and_duplicate_normalized_events() { - let temp = TempDir::new().unwrap(); - let manager = HookManager::new(temp.path().to_path_buf()); - assert!( - manager - .validate_config(r#"{"hooks":{"not-real":[]}}"#) - .unwrap_err() - .to_string() - .contains("unknown hook event") - ); - assert!( - manager - .validate_config(r#"{"hooks":{"tool-call":[],"tool_call":[]}}"#) - .unwrap_err() - .to_string() - .contains("duplicate hook event") - ); - } - - #[test] - fn refresh_uses_content_generation_not_mtime_only() { - let temp = TempDir::new().unwrap(); - let path = temp.path().join(HOOKS_JSON_FILE); - std::fs::write(&path, r#"{"timeout_ms": 1000, "hooks": {}}"#).unwrap(); - let manager = HookManager::new(temp.path().to_path_buf()); - manager.refresh_if_changed().unwrap(); - let first_digest = manager.state.read().hooks_json_digest; - - std::fs::write(&path, r#"{"timeout_ms": 1200, "hooks": {}}"#).unwrap(); - manager.refresh_if_changed().unwrap(); - let state = manager.state.read(); - assert_ne!(state.hooks_json_digest, first_digest); - } - - #[test] - fn refresh_rejects_oversized_file_without_replacing_generation() { - let temp = TempDir::new().unwrap(); - let path = temp.path().join(HOOKS_JSON_FILE); - std::fs::write(&path, r#"{"timeout_ms": 1200, "hooks": {}}"#).unwrap(); - let manager = HookManager::new(temp.path().to_path_buf()); - manager.refresh_if_changed().unwrap(); - - std::fs::write(&path, vec![b' '; MAX_HOOKS_FILE_BYTES as usize + 1]).unwrap(); - assert!(manager.refresh_if_changed().is_err()); - } - - // ── run_action edge cases ─────────────────────────────────── - - #[tokio::test] - async fn run_action_empty_command_fails() { - let temp = TempDir::new().unwrap(); - let manager = allowed_manager(&temp); - let action = HookAction { - command: "".into(), - args: vec![], - env: HashMap::new(), - cwd: None, - timeout_ms: Some(1000), - stdin_json: false, - }; - let result = manager.run_action(HookEvent::ToolCall, &json!({}), 1000, &action).await; - assert!(result.is_err()); - assert!(result.unwrap_err().to_string().contains("empty")); - } - - #[tokio::test] - async fn run_action_success() { - let temp = TempDir::new().unwrap(); - let manager = allowed_manager(&temp); - let action = HookAction { - command: "true".into(), - args: vec![], - env: HashMap::new(), - cwd: None, - timeout_ms: Some(2000), - stdin_json: false, - }; - let result = manager - .run_action(HookEvent::AgentStart, &json!({"msg": "hi"}), 2000, &action) - .await; - assert!(result.is_ok()); - } - - #[tokio::test] - async fn run_action_failure_exit_code() { - let temp = TempDir::new().unwrap(); - let manager = allowed_manager(&temp); - let action = HookAction { - command: "false".into(), - args: vec![], - env: HashMap::new(), - cwd: None, - timeout_ms: Some(2000), - stdin_json: false, - }; - let result = manager.run_action(HookEvent::Error, &json!({}), 2000, &action).await; - assert!(result.is_err()); - assert!(result.unwrap_err().to_string().contains("exited with status")); - } - - #[tokio::test] - async fn run_action_timeout() { - let temp = TempDir::new().unwrap(); - let manager = allowed_manager(&temp); - let action = HookAction { - command: "sleep".into(), - args: vec!["10".into()], - env: HashMap::new(), - cwd: None, - timeout_ms: Some(100), - stdin_json: false, - }; - let result = manager.run_action(HookEvent::ToolCall, &json!({}), 100, &action).await; - assert!(result.is_err()); - assert!(result.unwrap_err().to_string().contains("timed out")); - } - - #[cfg(target_os = "linux")] - #[tokio::test] - async fn run_action_timeout_kills_reaps_and_removes_payload_file() { - let temp = TempDir::new().unwrap(); - let manager = allowed_manager(&temp); - let out = temp.path().display().to_string(); - let action = HookAction { - command: "sh".into(), - args: vec![ - "-c".into(), - format!( - "echo $$ > '{out}/hook.pid'; sleep 10 & echo $! > '{out}/hook-descendant.pid'; \ - echo \"$ZERO_HOOK_PAYLOAD_FILE\" > '{out}/payload.path'; wait" - ), - ], - env: HashMap::new(), - cwd: None, - timeout_ms: Some(250), - stdin_json: false, - }; - - let result = manager.run_action(HookEvent::ToolCall, &json!({}), 250, &action).await; - assert!(result.unwrap_err().to_string().contains("timed out")); - - let pid = std::fs::read_to_string(temp.path().join("hook.pid")) - .unwrap() - .trim() - .to_string(); - for _ in 0..200 { - if !Path::new(&format!("/proc/{pid}")).exists() { - break; - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - assert!( - !Path::new(&format!("/proc/{pid}")).exists(), - "hook child was not reaped" - ); - let descendant_pid = std::fs::read_to_string(temp.path().join("hook-descendant.pid")) - .unwrap() - .trim() - .to_string(); - for _ in 0..200 { - if !Path::new(&format!("/proc/{descendant_pid}")).exists() { - break; - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - assert!( - !Path::new(&format!("/proc/{descendant_pid}")).exists(), - "hook descendant process was not terminated" - ); - let payload_path = std::fs::read_to_string(temp.path().join("payload.path")).unwrap(); - assert!(!Path::new(payload_path.trim()).exists(), "payload temp file leaked"); - } - - /// Write `hooks.json` into `workspace` with one `turn_complete` hook that - /// runs `sh -c